Add unified shift reporting
This commit is contained in:
1 parent
1b060377aa
commit
41a5ae7a63
30 files changed
+3751
-9
No files matched your search
@@ -0,0 +1,173 @@
|
||||
"""Machine-independent shift downtime from raw source intervals."""
|
||||
|
||||
from collections import defaultdict
|
||||
from collections.abc import Iterable
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, datetime
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ShiftDowntimeEvent:
|
||||
external_id: str
|
||||
machine_id: str
|
||||
source_start: datetime
|
||||
source_end: datetime | None
|
||||
reason_id: str | None
|
||||
reason_name: str | None
|
||||
reason_description: str | None
|
||||
reason_group: str | None
|
||||
category: str | None
|
||||
comment: str | None
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
for name in ("external_id", "machine_id"):
|
||||
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")
|
||||
_aware(self.source_start, "source_start")
|
||||
if self.source_end is not None:
|
||||
_aware(self.source_end, "source_end")
|
||||
if self.source_end.astimezone(UTC) < self.source_start.astimezone(UTC):
|
||||
raise ValueError("source_end must not precede source_start")
|
||||
for name in (
|
||||
"reason_id",
|
||||
"reason_name",
|
||||
"reason_description",
|
||||
"reason_group",
|
||||
"category",
|
||||
"comment",
|
||||
):
|
||||
value = getattr(self, name)
|
||||
if value is not None and not isinstance(value, str):
|
||||
raise ValueError(f"{name} must be a string or null")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ClippedShiftDowntimeEvent:
|
||||
source: ShiftDowntimeEvent
|
||||
start: datetime
|
||||
end: datetime
|
||||
duration_seconds: float
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ShiftDowntimeReason:
|
||||
reason_id: str | None
|
||||
reason_name: str | None
|
||||
reason_description: str | None
|
||||
reason_group: str | None
|
||||
category: str | None
|
||||
duration_seconds: float
|
||||
event_count: int
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ShiftDowntimeSummary:
|
||||
machine_id: str
|
||||
start: datetime
|
||||
end: datetime
|
||||
shift_duration_seconds: float
|
||||
total_downtime_seconds: float
|
||||
non_downtime_seconds: float
|
||||
events: tuple[ClippedShiftDowntimeEvent, ...]
|
||||
reasons: tuple[ShiftDowntimeReason, ...]
|
||||
|
||||
|
||||
def validate_downtime_window(*, machine_id: str, start: datetime, end: datetime) -> None:
|
||||
if not isinstance(machine_id, str) or not machine_id.strip() or "\x00" in machine_id:
|
||||
raise ValueError("machine_id must be a non-empty string without NUL bytes")
|
||||
_aware(start, "start")
|
||||
_aware(end, "end")
|
||||
if end.astimezone(UTC) <= start.astimezone(UTC):
|
||||
raise ValueError("end must follow start")
|
||||
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
"""
|
||||
validate_downtime_window(machine_id=machine_id, start=start, end=end)
|
||||
lower, upper = start.astimezone(UTC), end.astimezone(UTC)
|
||||
clipped = []
|
||||
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)
|
||||
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
|
||||
duration = (clipped_end.astimezone(UTC) - clipped_start.astimezone(UTC)).total_seconds()
|
||||
if duration > 0:
|
||||
clipped.append(ClippedShiftDowntimeEvent(event, clipped_start, clipped_end, duration))
|
||||
clipped.sort(key=lambda value: (value.start.astimezone(UTC), value.source.external_id))
|
||||
groups = defaultdict(list)
|
||||
for value in clipped:
|
||||
source = value.source
|
||||
groups[
|
||||
(
|
||||
source.reason_id,
|
||||
source.reason_name,
|
||||
source.reason_description,
|
||||
source.reason_group,
|
||||
source.category,
|
||||
)
|
||||
].append(value)
|
||||
reasons = [
|
||||
ShiftDowntimeReason(*key, _union_seconds(values), len(values))
|
||||
for key, values in groups.items()
|
||||
]
|
||||
reasons.sort(
|
||||
key=lambda value: (
|
||||
-value.duration_seconds,
|
||||
tuple(
|
||||
(field is not None, field or "")
|
||||
for field in (
|
||||
value.reason_id,
|
||||
value.reason_name,
|
||||
value.reason_description,
|
||||
value.reason_group,
|
||||
value.category,
|
||||
)
|
||||
),
|
||||
)
|
||||
)
|
||||
shift_seconds = (upper - lower).total_seconds()
|
||||
downtime_seconds = _union_seconds(clipped)
|
||||
return ShiftDowntimeSummary(
|
||||
machine_id=machine_id,
|
||||
start=start,
|
||||
end=end,
|
||||
shift_duration_seconds=shift_seconds,
|
||||
total_downtime_seconds=downtime_seconds,
|
||||
non_downtime_seconds=max(0.0, shift_seconds - downtime_seconds),
|
||||
events=tuple(clipped),
|
||||
reasons=tuple(reasons),
|
||||
)
|
||||
|
||||
|
||||
def _union_seconds(events: Iterable[ClippedShiftDowntimeEvent]) -> float:
|
||||
intervals = sorted((event.start.astimezone(UTC), event.end.astimezone(UTC)) for event in events)
|
||||
if not intervals:
|
||||
return 0.0
|
||||
start, end = intervals[0]
|
||||
total = 0.0
|
||||
for next_start, next_end in intervals[1:]:
|
||||
if next_start <= end:
|
||||
end = max(end, next_end)
|
||||
else:
|
||||
total += (end - start).total_seconds()
|
||||
start, end = next_start, next_end
|
||||
return total + (end - start).total_seconds()
|
||||
|
||||
|
||||
def _aware(value: datetime, name: str) -> None:
|
||||
if not isinstance(value, datetime) or value.tzinfo is None or value.utcoffset() is None:
|
||||
raise ValueError(f"{name} must be a timezone-aware datetime")
|
||||
@@ -0,0 +1,304 @@
|
||||
"""Shift deltas from cumulative counters; no material identity is inferred."""
|
||||
|
||||
from collections import defaultdict
|
||||
from collections.abc import Iterable
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, datetime
|
||||
from math import fsum, isfinite
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ShiftMaterialSnapshot:
|
||||
timestamp: datetime
|
||||
calculation_id: str
|
||||
machine_id: str
|
||||
production_order: str
|
||||
run_id: str
|
||||
consumption_kg: float | None
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ShiftChannelMaterialSnapshot:
|
||||
timestamp: datetime
|
||||
calculation_id: str
|
||||
machine_id: str
|
||||
extruder: str
|
||||
doser_channel: str
|
||||
production_order: str
|
||||
run_id: str
|
||||
cumulative_consumption_kg: float | None
|
||||
material_number: str | None
|
||||
material_name: str | None
|
||||
material_mapping_status: str
|
||||
percentage_sum_valid: bool
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ShiftMaterialItem:
|
||||
source: str
|
||||
calculation_id: str
|
||||
machine_id: str
|
||||
production_order: str
|
||||
run_id: str
|
||||
consumption_kg: float
|
||||
baseline_timestamp: datetime
|
||||
end_timestamp: datetime
|
||||
baseline_missing: bool
|
||||
extruder: str | None = None
|
||||
doser_channel: str | None = None
|
||||
material_number: str | None = None
|
||||
material_name: str | None = None
|
||||
material_mapping_status: str | None = None
|
||||
percentage_sum_valid: bool | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ShiftMaterialSummary:
|
||||
machine_id: str
|
||||
start: datetime
|
||||
end: datetime
|
||||
total_consumption_kg: float
|
||||
items: tuple[ShiftMaterialItem, ...]
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class _ChannelSegment:
|
||||
identity: tuple[str | None, str | None, str]
|
||||
first: ShiftChannelMaterialSnapshot
|
||||
last: ShiftChannelMaterialSnapshot
|
||||
deltas: list[float]
|
||||
quality: bool
|
||||
|
||||
|
||||
def validate_material_window(
|
||||
*, machine_id: str, calculation_ids: tuple[str, ...], start: datetime, end: datetime
|
||||
) -> None:
|
||||
_identifier(machine_id, "machine_id")
|
||||
if not isinstance(calculation_ids, tuple) or not calculation_ids:
|
||||
raise ValueError("calculation_ids must be a non-empty tuple")
|
||||
for calculation_id in calculation_ids:
|
||||
_identifier(calculation_id, "calculation_id")
|
||||
if len(set(calculation_ids)) != len(calculation_ids):
|
||||
raise ValueError("calculation_ids must be unique")
|
||||
if _instant(end) <= _instant(start):
|
||||
raise ValueError("end must follow start")
|
||||
|
||||
|
||||
def aggregate_shift_material(
|
||||
snapshots: Iterable[ShiftMaterialSnapshot],
|
||||
*,
|
||||
machine_id: str,
|
||||
calculation_ids: tuple[str, ...],
|
||||
start: datetime,
|
||||
end: datetime,
|
||||
include_zero: bool = True,
|
||||
) -> ShiftMaterialSummary:
|
||||
"""Difference each observed run independently, never counters from different runs.
|
||||
|
||||
Use the last valid sample at/before start and samples strictly before end.
|
||||
If a run has no baseline at/before start, its first observed sample establishes
|
||||
a baseline (baseline_missing=True); its existing counter is never counted.
|
||||
Null/non-finite counters are not valid samples and are skipped. Negative
|
||||
counters are rejected. A lone baseline produces a diagnostic zero item; it
|
||||
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.
|
||||
"""
|
||||
validate_material_window(
|
||||
machine_id=machine_id, calculation_ids=calculation_ids, start=start, end=end
|
||||
)
|
||||
streams = defaultdict(list)
|
||||
for row in snapshots:
|
||||
if row.machine_id == machine_id and row.calculation_id in calculation_ids:
|
||||
if _instant(row.timestamp) < _instant(end):
|
||||
streams[(row.calculation_id,)].append(row)
|
||||
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),
|
||||
)
|
||||
)
|
||||
return _summary(items, machine_id, start, end, include_zero)
|
||||
|
||||
|
||||
def aggregate_shift_channel_material(
|
||||
snapshots: Iterable[ShiftChannelMaterialSnapshot],
|
||||
*,
|
||||
machine_id: str,
|
||||
calculation_ids: tuple[str, ...],
|
||||
start: datetime,
|
||||
end: datetime,
|
||||
include_zero: bool = True,
|
||||
) -> 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.
|
||||
"""
|
||||
validate_material_window(
|
||||
machine_id=machine_id, calculation_ids=calculation_ids, start=start, end=end
|
||||
)
|
||||
streams = defaultdict(list)
|
||||
for row in snapshots:
|
||||
if row.machine_id == machine_id and row.calculation_id in calculation_ids:
|
||||
if _instant(row.timestamp) < _instant(end):
|
||||
streams[(row.calculation_id, row.extruder, row.doser_channel)].append(row)
|
||||
items = []
|
||||
for rows in streams.values():
|
||||
for run in _runs(rows, start, channel=True):
|
||||
_check_deltas(run, channel=True)
|
||||
missing = _instant(run[0].timestamp) > _instant(start)
|
||||
intervals = list(zip(run, run[1:])) or [(run[0], run[0])]
|
||||
segments = []
|
||||
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
|
||||
)
|
||||
)
|
||||
for segment in segments:
|
||||
number, name, status = segment.identity
|
||||
first, last = segment.first, segment.last
|
||||
items.append(
|
||||
ShiftMaterialItem(
|
||||
source="channel_material_consumption_snapshots",
|
||||
calculation_id=first.calculation_id,
|
||||
machine_id=machine_id,
|
||||
production_order=first.production_order,
|
||||
run_id=first.run_id,
|
||||
consumption_kg=fsum(segment.deltas),
|
||||
baseline_timestamp=first.timestamp,
|
||||
end_timestamp=last.timestamp,
|
||||
baseline_missing=missing,
|
||||
extruder=first.extruder,
|
||||
doser_channel=first.doser_channel,
|
||||
material_number=number,
|
||||
material_name=name,
|
||||
material_mapping_status=status,
|
||||
percentage_sum_valid=segment.quality,
|
||||
)
|
||||
)
|
||||
return _summary(items, machine_id, start, end, include_zero)
|
||||
|
||||
|
||||
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:])):
|
||||
raise ValueError("Ambiguous snapshots at the same stream timestamp")
|
||||
# Invalid counters still establish run boundaries. Retain the active run's
|
||||
# history until its valid baseline has been selected below.
|
||||
before = [i for i, row in enumerate(ordered) if _instant(row.timestamp) <= _instant(start)]
|
||||
active = before[-1] if before else 0
|
||||
while active > 0 and ordered[active - 1].run_id == ordered[active].run_id:
|
||||
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
|
||||
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)]
|
||||
selected = baseline[-1:] + [
|
||||
row for row in valid if _instant(row.timestamp) > _instant(start)
|
||||
]
|
||||
if selected:
|
||||
yield selected
|
||||
|
||||
|
||||
def _check_deltas(run, *, channel):
|
||||
for previous, current in zip(run, run[1:]):
|
||||
a = previous.cumulative_consumption_kg if channel else previous.consumption_kg
|
||||
b = current.cumulative_consumption_kg if channel else current.consumption_kg
|
||||
if b < a:
|
||||
raise ValueError("Cumulative counter decreased/reset within a run")
|
||||
|
||||
|
||||
def _identity(row: ShiftChannelMaterialSnapshot) -> tuple[str | None, str | None, str]:
|
||||
number = _label(row.material_number)
|
||||
name = _label(row.material_name)
|
||||
status = (
|
||||
row.material_mapping_status if number is not None or name is not None else "UNAVAILABLE"
|
||||
)
|
||||
return number, name, status
|
||||
|
||||
|
||||
def _label(value: str | None) -> str | None:
|
||||
if value is not None and not isinstance(value, str):
|
||||
raise ValueError("Material labels must be strings or null")
|
||||
return value.strip() or None if value is not None else None
|
||||
|
||||
|
||||
def _valid_counter(value: float | None) -> bool:
|
||||
if value is None:
|
||||
return False
|
||||
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
||||
raise ValueError("Cumulative counter must be numeric or null")
|
||||
if not isfinite(value):
|
||||
return False
|
||||
if value < 0:
|
||||
raise ValueError("Cumulative counter must be non-negative")
|
||||
return True
|
||||
|
||||
|
||||
def _summary(items, machine_id, start, end, include_zero):
|
||||
items = [item for item in items if include_zero or item.consumption_kg != 0]
|
||||
items.sort(
|
||||
key=lambda item: (
|
||||
item.calculation_id,
|
||||
item.extruder or "",
|
||||
item.doser_channel or "",
|
||||
_instant(item.baseline_timestamp),
|
||||
item.run_id,
|
||||
item.production_order,
|
||||
item.material_number or "",
|
||||
item.material_name or "",
|
||||
)
|
||||
)
|
||||
return ShiftMaterialSummary(
|
||||
machine_id, start, end, fsum(item.consumption_kg for item in items), tuple(items)
|
||||
)
|
||||
|
||||
|
||||
def _instant(value: datetime) -> datetime:
|
||||
if not isinstance(value, datetime) or value.tzinfo is None or value.utcoffset() is None:
|
||||
raise ValueError("Snapshot and window timestamps must be timezone-aware")
|
||||
return value.astimezone(UTC)
|
||||
|
||||
|
||||
def _identifier(value: str, name: str) -> None:
|
||||
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")
|
||||
@@ -0,0 +1,124 @@
|
||||
"""Pure finished-production aggregation for an explicit workplace and shift window."""
|
||||
|
||||
from collections import defaultdict
|
||||
from collections.abc import Iterable
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from math import fsum, isfinite
|
||||
|
||||
from production_analytics.erp import ProductionConfirmation
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ShiftProductionItem:
|
||||
production_order: str
|
||||
article_number: str | None
|
||||
article_description: str | None
|
||||
produced_m2: float
|
||||
roll_count: int
|
||||
first_confirmation_at: datetime
|
||||
last_confirmation_at: datetime
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ShiftProductionSummary:
|
||||
start: datetime
|
||||
end: datetime
|
||||
workplace: str
|
||||
total_produced_m2: float
|
||||
total_roll_count: int
|
||||
items: tuple[ShiftProductionItem, ...]
|
||||
|
||||
|
||||
def validate_shift_window(*, workplace: str, start: datetime, end: datetime) -> str:
|
||||
"""Validate inputs and return the exact workplace with surrounding padding removed."""
|
||||
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")
|
||||
_aware(start, "start")
|
||||
_aware(end, "end")
|
||||
# Compare instants, including distinct folds of the same local DST hour.
|
||||
if end.timestamp() <= start.timestamp():
|
||||
raise ValueError("end must follow start")
|
||||
return workplace.strip()
|
||||
|
||||
|
||||
def aggregate_shift_production(
|
||||
confirmations: Iterable[ProductionConfirmation],
|
||||
*,
|
||||
workplace: str,
|
||||
start: datetime,
|
||||
end: datetime,
|
||||
) -> ShiftProductionSummary:
|
||||
"""Sum positive ERP feedback in [start, end), preserving supplied timezones.
|
||||
|
||||
Only rows for the exact workplace and window contribute. Every finished-goods
|
||||
row contributes its feedback m²; only roll counts are deduplicated, within each
|
||||
order/article/description group. Missing or blank roll numbers count as no roll.
|
||||
"""
|
||||
workplace = validate_shift_window(workplace=workplace, start=start, end=end)
|
||||
groups: dict[tuple[str, str | None, str | None], list[ProductionConfirmation]] = defaultdict(
|
||||
list
|
||||
)
|
||||
for confirmation in confirmations:
|
||||
_aware(confirmation.timestamp, "confirmation timestamp")
|
||||
if confirmation.workplace != workplace or not (
|
||||
start.timestamp() <= confirmation.timestamp.timestamp() < end.timestamp()
|
||||
):
|
||||
continue
|
||||
quantity = confirmation.feedback_quantity_m2
|
||||
if quantity is not None and (isinstance(quantity, bool) or not isfinite(quantity)):
|
||||
raise ValueError("feedback quantity must be finite")
|
||||
if not confirmation.is_finished_goods:
|
||||
continue
|
||||
groups[
|
||||
(
|
||||
confirmation.production_order,
|
||||
confirmation.article_number,
|
||||
confirmation.article_description,
|
||||
)
|
||||
].append(confirmation)
|
||||
items = []
|
||||
for (order, article, description), rows in groups.items():
|
||||
produced = fsum(row.feedback_quantity_m2 for row in rows)
|
||||
if not isfinite(produced):
|
||||
raise ValueError("produced quantity must be finite")
|
||||
items.append(
|
||||
ShiftProductionItem(
|
||||
production_order=order,
|
||||
article_number=article,
|
||||
article_description=description,
|
||||
produced_m2=produced,
|
||||
roll_count=len(
|
||||
{
|
||||
row.roll_number.strip()
|
||||
for row in rows
|
||||
if row.roll_number is not None and row.roll_number.strip()
|
||||
}
|
||||
),
|
||||
first_confirmation_at=min(
|
||||
rows, key=lambda row: row.timestamp.timestamp()
|
||||
).timestamp,
|
||||
last_confirmation_at=max(rows, key=lambda row: row.timestamp.timestamp()).timestamp,
|
||||
)
|
||||
)
|
||||
items.sort(
|
||||
key=lambda item: (
|
||||
item.first_confirmation_at.timestamp(),
|
||||
item.production_order,
|
||||
(item.article_number is not None, item.article_number or ""),
|
||||
(item.article_description is not None, item.article_description or ""),
|
||||
)
|
||||
)
|
||||
return ShiftProductionSummary(
|
||||
start=start,
|
||||
end=end,
|
||||
workplace=workplace,
|
||||
total_produced_m2=fsum(item.produced_m2 for item in items),
|
||||
total_roll_count=sum(item.roll_count for item in items),
|
||||
items=tuple(items),
|
||||
)
|
||||
|
||||
|
||||
def _aware(value: datetime, name: str) -> None:
|
||||
if not isinstance(value, datetime) or value.tzinfo is None or value.utcoffset() is None:
|
||||
raise ValueError(f"{name} must be a timezone-aware datetime")
|
||||
@@ -0,0 +1,76 @@
|
||||
"""Immutable shift-report composition models, independent of output format."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime, time, timedelta
|
||||
from typing import Literal
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from production_analytics.calculations.shift_downtime import (
|
||||
ShiftDowntimeReason,
|
||||
ShiftDowntimeSummary,
|
||||
)
|
||||
from production_analytics.calculations.shift_material import ShiftMaterialSummary
|
||||
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:
|
||||
reason: ShiftDowntimeReason
|
||||
display_name: str
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ShiftReport:
|
||||
machine_name: str
|
||||
machine_id: str
|
||||
start: datetime
|
||||
end: datetime
|
||||
production: ShiftProductionSummary
|
||||
downtime: ShiftDowntimeSummary
|
||||
materials: ShiftMaterialSummary
|
||||
speed: ShiftSpeedSummary
|
||||
|
||||
@property
|
||||
def downtime_event_count(self) -> int:
|
||||
return len(self.downtime.events)
|
||||
|
||||
@property
|
||||
def downtime_reasons(self) -> tuple[ShiftReportDowntimeReason, ...]:
|
||||
return tuple(
|
||||
ShiftReportDowntimeReason(
|
||||
reason=reason,
|
||||
display_name=reason.reason_name
|
||||
if reason.reason_name and reason.reason_name.strip()
|
||||
else "Ohne Stillstandsgrund",
|
||||
)
|
||||
for reason in self.downtime.reasons
|
||||
)
|
||||
|
||||
@property
|
||||
def top_downtime_reasons(self) -> tuple[ShiftReportDowntimeReason, ...]:
|
||||
# Preserve the source summary's validated duration ranking and tie order.
|
||||
return self.downtime_reasons[:3]
|
||||
|
||||
|
||||
def shift_report_window(
|
||||
day: date, shift: Literal["early", "late", "night"],
|
||||
) -> tuple[datetime, datetime]:
|
||||
"""Berlin 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")
|
||||
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),
|
||||
)
|
||||
@@ -0,0 +1,116 @@
|
||||
"""Arithmetic sample mean of line speed while running, without time weighting."""
|
||||
|
||||
from collections.abc import Iterable
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, datetime
|
||||
from math import isfinite
|
||||
from statistics import mean
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ShiftSpeedConfig:
|
||||
machine_id: str
|
||||
speed_signal_ref: str
|
||||
production_gate_m_min: float
|
||||
unit: str = "m/min"
|
||||
signal: str = ""
|
||||
|
||||
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")
|
||||
gate = finite_speed(self.production_gate_m_min)
|
||||
if gate is None or gate < 0:
|
||||
raise ValueError("production_gate_m_min must be finite and non-negative")
|
||||
if self.unit != "m/min":
|
||||
raise ValueError("Shift speed requires unit m/min")
|
||||
if not isinstance(self.signal, str):
|
||||
raise ValueError("signal must be a string")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ShiftSpeedSample:
|
||||
timestamp: datetime | None
|
||||
value: object
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ShiftSpeedSummary:
|
||||
machine_id: str
|
||||
start: datetime
|
||||
end: datetime
|
||||
speed_signal_ref: str
|
||||
unit: str
|
||||
production_gate_m_min: float
|
||||
sample_count: int
|
||||
active_sample_count: int
|
||||
inactive_sample_count: int
|
||||
average_line_speed_m_min: float | None
|
||||
minimum_active_speed_m_min: float | None
|
||||
maximum_active_speed_m_min: float | None
|
||||
invalid_sample_count: int
|
||||
|
||||
|
||||
def validate_speed_window(start: datetime, end: datetime) -> None:
|
||||
if _instant(end) <= _instant(start):
|
||||
raise ValueError("end must follow start")
|
||||
|
||||
|
||||
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.
|
||||
|
||||
sample_count = active_sample_count + inactive_sample_count. Invalid values
|
||||
are counted separately, never converted to zero. Out-of-window samples are
|
||||
ignored. Missing/invalid timestamps are unavailable and counted as invalid.
|
||||
Each active sample has equal weight; this is not a full-shift/time mean.
|
||||
"""
|
||||
validate_speed_window(start, end)
|
||||
first, last = _instant(start), _instant(end)
|
||||
active = []
|
||||
count = invalid = 0
|
||||
for sample in samples:
|
||||
try:
|
||||
timestamp = _instant(sample.timestamp)
|
||||
except ValueError:
|
||||
invalid += 1
|
||||
continue
|
||||
if not first <= timestamp < last:
|
||||
continue
|
||||
value = finite_speed(sample.value)
|
||||
if value is None:
|
||||
invalid += 1
|
||||
continue
|
||||
count += 1
|
||||
if value > config.production_gate_m_min:
|
||||
active.append(value)
|
||||
return ShiftSpeedSummary(
|
||||
machine_id=config.machine_id, start=start, end=end,
|
||||
speed_signal_ref=config.speed_signal_ref, unit=config.unit,
|
||||
production_gate_m_min=config.production_gate_m_min,
|
||||
sample_count=count, active_sample_count=len(active),
|
||||
inactive_sample_count=count - len(active),
|
||||
average_line_speed_m_min=mean(active) if active else None,
|
||||
minimum_active_speed_m_min=min(active) if active else None,
|
||||
maximum_active_speed_m_min=max(active) if active else None,
|
||||
invalid_sample_count=invalid,
|
||||
)
|
||||
|
||||
|
||||
def finite_speed(value: object) -> float | None:
|
||||
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
||||
return None
|
||||
try:
|
||||
number = float(value)
|
||||
except (ValueError, OverflowError):
|
||||
return None
|
||||
return number if isfinite(number) else None
|
||||
|
||||
|
||||
def _instant(value: datetime | None) -> datetime:
|
||||
if not isinstance(value, datetime) or value.tzinfo is None or value.utcoffset() is None:
|
||||
raise ValueError("Shift speed timestamps must be timezone-aware")
|
||||
return value.astimezone(UTC)
|
||||
@@ -12,6 +12,7 @@ from production_analytics.calculations.material_consumption import (
|
||||
area_application_rate_kg_per_hour,
|
||||
rotational_discharge_rate_kg_per_hour,
|
||||
)
|
||||
from production_analytics.calculations.shift_speed import ShiftSpeedSample, validate_speed_window
|
||||
from production_analytics.enlyze.exploration import ExplorationClient
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -153,6 +154,63 @@ class EnlyzeApiGateway:
|
||||
except (KeyError, TypeError, ValueError) as exc:
|
||||
raise ValueError(f"Invalid downtime response on page {page}: {exc}") from exc
|
||||
|
||||
def get_speed_samples(
|
||||
self, *, machine_id: str, speed_signal_ref: str, start: datetime, end: datetime,
|
||||
) -> list[ShiftSpeedSample]:
|
||||
"""Retrieve one bounded signal using the existing timeseries cursor contract.
|
||||
|
||||
Invalid/missing sample values remain unavailable for domain aggregation.
|
||||
Malformed timestamps/rows become invalid samples, while structural response
|
||||
and pagination errors still fail the read instead of returning partial KPIs.
|
||||
"""
|
||||
validate_speed_window(start, end)
|
||||
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")
|
||||
body = {
|
||||
"machine": machine_id,
|
||||
"start": start.astimezone(UTC).isoformat(),
|
||||
"end": end.astimezone(UTC).isoformat(),
|
||||
"variables": [{"uuid": speed_signal_ref}],
|
||||
}
|
||||
samples = []
|
||||
cursors: set[str] = set()
|
||||
page = 1
|
||||
while True:
|
||||
response = self._client.post_json("/v2/timeseries", body)
|
||||
try:
|
||||
data = response.body["data"]
|
||||
columns = data["columns"]
|
||||
if not isinstance(columns, list) or any(
|
||||
columns.count(column) != 1 for column in ("time", speed_signal_ref)
|
||||
):
|
||||
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)
|
||||
for record in records:
|
||||
if not isinstance(record, list) or len(record) != len(columns):
|
||||
samples.append(ShiftSpeedSample(None, None))
|
||||
continue
|
||||
try:
|
||||
timestamp = _parse_timestamp(record[time_index])
|
||||
except (TypeError, ValueError):
|
||||
timestamp = None
|
||||
samples.append(ShiftSpeedSample(timestamp, record[speed_index]))
|
||||
cursor = _next_cursor(response.body)
|
||||
if cursor is None:
|
||||
return samples
|
||||
if cursor in cursors:
|
||||
raise ValueError("next_cursor has already been followed")
|
||||
cursors.add(cursor)
|
||||
body = {**body, "cursor": cursor}
|
||||
page += 1
|
||||
except (KeyError, TypeError, ValueError) as exc:
|
||||
raise ValueError(
|
||||
f"Invalid speed timeseries response on page {page}: {exc}"
|
||||
) from exc
|
||||
|
||||
def get_material_samples(
|
||||
self,
|
||||
*,
|
||||
|
||||
@@ -1,10 +1,19 @@
|
||||
"""Read-only ERP current workplace context."""
|
||||
"""Read-only ERP workplace context and historical production confirmations."""
|
||||
|
||||
from production_analytics.erp.gateway import (
|
||||
CurrentWorkplaceStatus,
|
||||
ErpProductionConfirmationGateway,
|
||||
ErpReadError,
|
||||
ErpSettings,
|
||||
ErpWorkplaceStatusGateway,
|
||||
ProductionConfirmation,
|
||||
)
|
||||
|
||||
__all__ = ["CurrentWorkplaceStatus", "ErpReadError", "ErpSettings", "ErpWorkplaceStatusGateway"]
|
||||
__all__ = [
|
||||
"CurrentWorkplaceStatus",
|
||||
"ErpProductionConfirmationGateway",
|
||||
"ErpReadError",
|
||||
"ErpSettings",
|
||||
"ErpWorkplaceStatusGateway",
|
||||
"ProductionConfirmation",
|
||||
]
|
||||
@@ -1,11 +1,12 @@
|
||||
"""Focused MSSQL boundary for dbo.GRAFANA_WORKPLACE_STATUS."""
|
||||
"""Focused read-only MSSQL boundaries for ERP status and confirmations."""
|
||||
|
||||
import os
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from datetime import UTC, datetime
|
||||
from decimal import Decimal
|
||||
from math import isfinite
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
import pymssql
|
||||
|
||||
@@ -62,7 +63,7 @@ class ErpSettings:
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class CurrentWorkplaceStatus:
|
||||
"""Latest ERP feedback; timestamp and timezone are preserved, with no freshness claim."""
|
||||
"""Latest ERP feedback with an aware timestamp; no freshness claim."""
|
||||
|
||||
workplace: str
|
||||
production_order: str
|
||||
@@ -120,7 +121,10 @@ class ErpWorkplaceStatusGateway:
|
||||
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],
|
||||
feedback_timestamp=(
|
||||
row[4].replace(tzinfo=_PLANT_TIMEZONE)
|
||||
if row[4].utcoffset() is None else row[4]
|
||||
),
|
||||
order_quantity_m2=_number(row[5]), good_quantity_m2=_number(row[6]),
|
||||
remaining_quantity_m2=_number(row[7]), remaining_time_hours=_number(row[8]),
|
||||
remaining_rolls=_number(row[9]),
|
||||
@@ -146,3 +150,106 @@ def _number(value: object) -> float | None:
|
||||
if not isfinite(result):
|
||||
raise ValueError
|
||||
return result
|
||||
|
||||
|
||||
_PLANT_TIMEZONE = ZoneInfo("Europe/Berlin")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ProductionConfirmation:
|
||||
"""Historical ERP view row; quantities follow the view's production semantics."""
|
||||
|
||||
workplace: str
|
||||
production_order: str
|
||||
timestamp: datetime
|
||||
article_number: str | None
|
||||
article_description: str | None
|
||||
roll_number: str | None
|
||||
production_quantity_m2: float | None
|
||||
feedback_quantity_m2: float | None
|
||||
raw_material_number: str | None
|
||||
raw_material_description: str | None
|
||||
batch_number: str | None
|
||||
raw_material_quantity: float | None
|
||||
tenant: str | None
|
||||
|
||||
@property
|
||||
def is_finished_goods(self) -> bool:
|
||||
"""Positive feedback identifies finished production, independently of workplace."""
|
||||
return self.feedback_quantity_m2 is not None and self.feedback_quantity_m2 > 0
|
||||
|
||||
|
||||
_PRODUCTION_CONFIRMATION_SQL = """SELECT
|
||||
[Mandant], [Fertigungsauftragsnummer], [Zeitstempel], [Arbeitsplatz],
|
||||
[Artikelnummer], [Artikelbezeichnung], [Rollennummer], [Fertigungsmenge],
|
||||
[Rohstoffnummer], [Rohstoffbezeichnung], [Chargennummer], [Rückmeldemenge], [Fasermenge]
|
||||
FROM [dbo].[GRAFANA_PRODUCTION_CONFIRMATION]
|
||||
WHERE [Arbeitsplatz] = %s AND [Zeitstempel] >= %s AND [Zeitstempel] < %s
|
||||
ORDER BY [Zeitstempel], [Mandant], [Fertigungsauftragsnummer], [Rollennummer],
|
||||
[Artikelnummer], [Rohstoffnummer], [Chargennummer], [Fertigungsmenge],
|
||||
[Rückmeldemenge], [Fasermenge], [Artikelbezeichnung], [Rohstoffbezeichnung]"""
|
||||
|
||||
|
||||
class ErpProductionConfirmationGateway:
|
||||
"""Read complete view rows for an exact workplace and a plant-local [start, end).
|
||||
|
||||
SQL datetime stores no offset or fold. Ambiguous autumn timestamps are attached
|
||||
with fold=0 (the first occurrence); the source cannot identify their actual fold.
|
||||
Windows whose local end does not follow their local start cannot be expressed
|
||||
by this SQL predicate and are rejected. Repeated hours cannot be queried separately.
|
||||
"""
|
||||
|
||||
def __init__(self, settings: ErpSettings) -> None:
|
||||
self._settings = settings
|
||||
|
||||
def get_confirmations(
|
||||
self, *, workplace: str, start: datetime, end: datetime
|
||||
) -> list[ProductionConfirmation]:
|
||||
if not isinstance(workplace, str) or not workplace.strip() or "\x00" in workplace:
|
||||
raise ValueError("workplace must be a non-empty string without NUL bytes")
|
||||
for name, value in (("start", start), ("end", end)):
|
||||
if not isinstance(value, datetime) or value.tzinfo is None or value.utcoffset() is None:
|
||||
raise ValueError(f"{name} must be a timezone-aware datetime")
|
||||
if end.astimezone(UTC) <= start.astimezone(UTC):
|
||||
raise ValueError("end must follow start")
|
||||
local_start = start.astimezone(_PLANT_TIMEZONE).replace(tzinfo=None)
|
||||
local_end = end.astimezone(_PLANT_TIMEZONE).replace(tzinfo=None)
|
||||
if local_end <= local_start:
|
||||
raise ValueError("end must follow start in plant-local SQL time")
|
||||
try:
|
||||
with pymssql.connect(
|
||||
server=self._settings.host, port=self._settings.port,
|
||||
database=self._settings.database, user=self._settings.user,
|
||||
password=self._settings.password, login_timeout=10, timeout=10,
|
||||
) as connection:
|
||||
with connection.cursor() as cursor:
|
||||
cursor.execute(
|
||||
_PRODUCTION_CONFIRMATION_SQL, (workplace.strip(), local_start, local_end)
|
||||
)
|
||||
rows = cursor.fetchall()
|
||||
except Exception:
|
||||
raise ErpReadError("ERP production confirmation read failed") from None
|
||||
try:
|
||||
return [_production_confirmation(row) for row in rows]
|
||||
except Exception:
|
||||
raise ErpReadError("ERP production confirmation returned an invalid row") from None
|
||||
|
||||
|
||||
def _production_confirmation(row: tuple[object, ...]) -> 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),
|
||||
article_number=_text(row[4], nullable=True),
|
||||
article_description=_text(row[5], nullable=True),
|
||||
roll_number=_text(row[6], nullable=True),
|
||||
production_quantity_m2=_number(row[7]),
|
||||
feedback_quantity_m2=_number(row[11]),
|
||||
raw_material_number=_text(row[8], nullable=True),
|
||||
raw_material_description=_text(row[9], nullable=True),
|
||||
batch_number=_text(row[10], nullable=True),
|
||||
raw_material_quantity=_number(row[12]),
|
||||
tenant=_text(row[0], nullable=True),
|
||||
)
|
||||
@@ -1,9 +1,19 @@
|
||||
"""PostgreSQL persistence for reconciled ENLYZE downtime events."""
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from production_analytics.calculations.shift_downtime import (
|
||||
ShiftDowntimeEvent,
|
||||
validate_downtime_window,
|
||||
)
|
||||
from production_analytics.service.downtime import ProductionDowntimeEvent, ProductionOrderBoundary
|
||||
from production_analytics.service.postgres_material import PostgresSettings
|
||||
|
||||
|
||||
class DowntimeReadError(RuntimeError):
|
||||
"""Safe operator-facing error for persisted downtime reads."""
|
||||
|
||||
|
||||
class PostgresDowntimeRepository:
|
||||
def __init__(self, settings: PostgresSettings) -> None:
|
||||
self.settings = settings
|
||||
@@ -21,6 +31,30 @@ class PostgresDowntimeRepository:
|
||||
options="-c statement_timeout=10000",
|
||||
)
|
||||
|
||||
def get_events(
|
||||
self, *, machine_id: str, start: datetime, end: datetime
|
||||
) -> list[ShiftDowntimeEvent]:
|
||||
"""Read raw machine intervals intersecting [start, end), independent of orders."""
|
||||
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
|
||||
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""",
|
||||
(machine_id, end, start),
|
||||
).fetchall()
|
||||
except Exception:
|
||||
raise DowntimeReadError("PostgreSQL shift downtime read failed") from None
|
||||
try:
|
||||
return [ShiftDowntimeEvent(*row) for row in rows]
|
||||
except Exception:
|
||||
raise DowntimeReadError("PostgreSQL shift downtime returned an invalid row") from None
|
||||
|
||||
def current_boundary(self, machine_id: str) -> ProductionOrderBoundary | None:
|
||||
with self._connect() as connection:
|
||||
row = connection.execute(
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
"""Read-only baseline plus bounded-window queries for shift material deltas.
|
||||
|
||||
One valid baseline per calculation/channel, followed by every raw in-window
|
||||
row. Missing baselines leave window rows intact for aggregation's fallback.
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from production_analytics.calculations.shift_material import (
|
||||
ShiftChannelMaterialSnapshot,
|
||||
ShiftMaterialSnapshot,
|
||||
validate_material_window,
|
||||
)
|
||||
from production_analytics.service.postgres_material import PostgresSettings
|
||||
|
||||
|
||||
class ShiftMaterialReadError(RuntimeError):
|
||||
"""Safe operator-facing cumulative snapshot read/result error."""
|
||||
|
||||
|
||||
# A backward index scan per requested calculation stops at its first valid
|
||||
# baseline. The other branch reads only the bounded shift, without filtering
|
||||
# counters (invalid samples can mark run transitions).
|
||||
_MATERIAL_SQL = """WITH request AS (
|
||||
SELECT %s::text AS machine_id, %s::text[] AS calculation_ids,
|
||||
%s::timestamptz AS start_time, %s::timestamptz AS end_time
|
||||
), baseline AS (
|
||||
SELECT sample.*
|
||||
FROM request r
|
||||
CROSS JOIN LATERAL unnest(r.calculation_ids) AS ids(calculation_id)
|
||||
CROSS JOIN LATERAL (
|
||||
SELECT timestamp, calculation_id, machine_id, production_order, run_id, consumption_kg
|
||||
FROM material_consumption_snapshots
|
||||
WHERE calculation_id = ids.calculation_id AND machine_id = r.machine_id
|
||||
AND timestamp <= r.start_time
|
||||
AND consumption_kg >= 0 AND consumption_kg < 'Infinity'::double precision
|
||||
ORDER BY timestamp DESC, run_id, production_order
|
||||
LIMIT 1
|
||||
) sample
|
||||
)
|
||||
SELECT * FROM baseline
|
||||
UNION ALL
|
||||
SELECT timestamp, s.calculation_id, s.machine_id, production_order, run_id, consumption_kg
|
||||
FROM material_consumption_snapshots s CROSS JOIN request r
|
||||
WHERE s.machine_id = r.machine_id AND s.calculation_id = ANY(r.calculation_ids)
|
||||
AND timestamp > r.start_time AND timestamp < r.end_time
|
||||
ORDER BY calculation_id, timestamp, run_id, production_order"""
|
||||
|
||||
# The channel index has production_order between channel and timestamp, so it
|
||||
# cannot directly support a backward timestamp seek per channel. DISTINCT ON
|
||||
# selects all channel baselines in one filtered pass rather than rescanning
|
||||
# pre-shift history separately for every channel. See the performance notes.
|
||||
_CHANNEL_SQL = """WITH request AS (
|
||||
SELECT %s::text AS machine_id, %s::text[] AS calculation_ids,
|
||||
%s::timestamptz AS start_time, %s::timestamptz AS end_time
|
||||
), baseline AS (
|
||||
SELECT DISTINCT ON (s.calculation_id, extruder, doser_channel)
|
||||
timestamp, s.calculation_id, s.machine_id, extruder, doser_channel,
|
||||
production_order, run_id, cumulative_consumption_kg, material_number,
|
||||
material_name, material_mapping_status, percentage_sum_valid
|
||||
FROM channel_material_consumption_snapshots s CROSS JOIN request r
|
||||
WHERE s.machine_id = r.machine_id AND s.calculation_id = ANY(r.calculation_ids)
|
||||
AND timestamp <= r.start_time
|
||||
AND cumulative_consumption_kg >= 0
|
||||
AND cumulative_consumption_kg < 'Infinity'::double precision
|
||||
ORDER BY s.calculation_id, extruder, doser_channel, timestamp DESC, run_id, production_order
|
||||
)
|
||||
SELECT * FROM baseline
|
||||
UNION ALL
|
||||
SELECT timestamp, s.calculation_id, s.machine_id, extruder, doser_channel,
|
||||
production_order, run_id, cumulative_consumption_kg, material_number,
|
||||
material_name, material_mapping_status, percentage_sum_valid
|
||||
FROM channel_material_consumption_snapshots s CROSS JOIN request r
|
||||
WHERE s.machine_id = r.machine_id AND s.calculation_id = ANY(r.calculation_ids)
|
||||
AND timestamp > r.start_time AND timestamp < r.end_time
|
||||
ORDER BY calculation_id, extruder, doser_channel, timestamp, run_id, production_order"""
|
||||
|
||||
|
||||
class PostgresShiftMaterialRepository:
|
||||
def __init__(self, settings: PostgresSettings) -> None:
|
||||
self.settings = settings
|
||||
|
||||
def get_snapshots(
|
||||
self, *, machine_id: str, calculation_ids: tuple[str, ...], start: datetime, end: datetime
|
||||
) -> list[ShiftMaterialSnapshot]:
|
||||
validate_material_window(
|
||||
machine_id=machine_id, calculation_ids=calculation_ids, start=start, end=end
|
||||
)
|
||||
rows = _read(
|
||||
self.settings, _MATERIAL_SQL, (machine_id, list(calculation_ids), start, end)
|
||||
)
|
||||
try:
|
||||
return [ShiftMaterialSnapshot(*row) for row in rows]
|
||||
except Exception:
|
||||
raise ShiftMaterialReadError(
|
||||
"PostgreSQL shift material returned an invalid row"
|
||||
) from None
|
||||
|
||||
|
||||
class PostgresShiftChannelMaterialRepository:
|
||||
def __init__(self, settings: PostgresSettings) -> None:
|
||||
self.settings = settings
|
||||
|
||||
def get_snapshots(
|
||||
self, *, machine_id: str, calculation_ids: tuple[str, ...], start: datetime, end: datetime
|
||||
) -> list[ShiftChannelMaterialSnapshot]:
|
||||
validate_material_window(
|
||||
machine_id=machine_id, calculation_ids=calculation_ids, start=start, end=end
|
||||
)
|
||||
rows = _read(
|
||||
self.settings, _CHANNEL_SQL, (machine_id, list(calculation_ids), start, end)
|
||||
)
|
||||
try:
|
||||
return [ShiftChannelMaterialSnapshot(*row) for row in rows]
|
||||
except Exception:
|
||||
raise ShiftMaterialReadError(
|
||||
"PostgreSQL shift material returned an invalid row"
|
||||
) from None
|
||||
|
||||
|
||||
def _read(settings: PostgresSettings, sql: str, parameters: tuple) -> list[tuple]:
|
||||
import psycopg
|
||||
|
||||
try:
|
||||
with psycopg.connect(
|
||||
host=settings.host,
|
||||
port=settings.port,
|
||||
dbname=settings.dbname,
|
||||
user=settings.user,
|
||||
password=settings.password,
|
||||
connect_timeout=10,
|
||||
options="-c statement_timeout=10000",
|
||||
) as connection:
|
||||
return connection.execute(sql, parameters).fetchall()
|
||||
except Exception:
|
||||
raise ShiftMaterialReadError("PostgreSQL shift material read failed") from None
|
||||
@@ -0,0 +1,27 @@
|
||||
"""Compose persisted source downtime reads with pure shift aggregation."""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Protocol
|
||||
|
||||
from production_analytics.calculations.shift_downtime import (
|
||||
ShiftDowntimeEvent,
|
||||
ShiftDowntimeSummary,
|
||||
aggregate_shift_downtime,
|
||||
validate_downtime_window,
|
||||
)
|
||||
|
||||
|
||||
class ShiftDowntimeReader(Protocol):
|
||||
def get_events(
|
||||
self, *, machine_id: str, start: datetime, end: datetime
|
||||
) -> list[ShiftDowntimeEvent]: ...
|
||||
|
||||
|
||||
class ShiftDowntimeService:
|
||||
def __init__(self, repository: ShiftDowntimeReader) -> None:
|
||||
self.repository = repository
|
||||
|
||||
def summarize(self, *, machine_id: str, start: datetime, end: datetime) -> ShiftDowntimeSummary:
|
||||
validate_downtime_window(machine_id=machine_id, start=start, end=end)
|
||||
events = self.repository.get_events(machine_id=machine_id, start=start, end=end)
|
||||
return aggregate_shift_downtime(events, machine_id=machine_id, start=start, end=end)
|
||||
@@ -0,0 +1,83 @@
|
||||
"""Thin services composing explicit snapshot sources with pure shift aggregation."""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Protocol
|
||||
|
||||
from production_analytics.calculations.shift_material import (
|
||||
ShiftChannelMaterialSnapshot,
|
||||
ShiftMaterialSnapshot,
|
||||
ShiftMaterialSummary,
|
||||
aggregate_shift_channel_material,
|
||||
aggregate_shift_material,
|
||||
validate_material_window,
|
||||
)
|
||||
|
||||
|
||||
class ShiftMaterialReader(Protocol):
|
||||
def get_snapshots(
|
||||
self, *, machine_id: str, calculation_ids: tuple[str, ...], start: datetime, end: datetime
|
||||
) -> list[ShiftMaterialSnapshot]: ...
|
||||
|
||||
|
||||
class ShiftChannelMaterialReader(Protocol):
|
||||
def get_snapshots(
|
||||
self, *, machine_id: str, calculation_ids: tuple[str, ...], start: datetime, end: datetime
|
||||
) -> list[ShiftChannelMaterialSnapshot]: ...
|
||||
|
||||
|
||||
class ShiftMaterialService:
|
||||
def __init__(self, repository: ShiftMaterialReader) -> None:
|
||||
self.repository = repository
|
||||
|
||||
def summarize(
|
||||
self,
|
||||
*,
|
||||
machine_id: str,
|
||||
calculation_ids: tuple[str, ...],
|
||||
start: datetime,
|
||||
end: datetime,
|
||||
include_zero: bool = True,
|
||||
) -> ShiftMaterialSummary:
|
||||
validate_material_window(
|
||||
machine_id=machine_id, calculation_ids=calculation_ids, start=start, end=end
|
||||
)
|
||||
snapshots = self.repository.get_snapshots(
|
||||
machine_id=machine_id, calculation_ids=calculation_ids, start=start, end=end
|
||||
)
|
||||
return aggregate_shift_material(
|
||||
snapshots,
|
||||
machine_id=machine_id,
|
||||
calculation_ids=calculation_ids,
|
||||
start=start,
|
||||
end=end,
|
||||
include_zero=include_zero,
|
||||
)
|
||||
|
||||
|
||||
class ShiftChannelMaterialService:
|
||||
def __init__(self, repository: ShiftChannelMaterialReader) -> None:
|
||||
self.repository = repository
|
||||
|
||||
def summarize(
|
||||
self,
|
||||
*,
|
||||
machine_id: str,
|
||||
calculation_ids: tuple[str, ...],
|
||||
start: datetime,
|
||||
end: datetime,
|
||||
include_zero: bool = True,
|
||||
) -> ShiftMaterialSummary:
|
||||
validate_material_window(
|
||||
machine_id=machine_id, calculation_ids=calculation_ids, start=start, end=end
|
||||
)
|
||||
snapshots = self.repository.get_snapshots(
|
||||
machine_id=machine_id, calculation_ids=calculation_ids, start=start, end=end
|
||||
)
|
||||
return aggregate_shift_channel_material(
|
||||
snapshots,
|
||||
machine_id=machine_id,
|
||||
calculation_ids=calculation_ids,
|
||||
start=start,
|
||||
end=end,
|
||||
include_zero=include_zero,
|
||||
)
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Compose historical ERP reads with pure shift-production aggregation."""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Protocol
|
||||
|
||||
from production_analytics.calculations.shift_production import (
|
||||
ShiftProductionSummary,
|
||||
aggregate_shift_production,
|
||||
validate_shift_window,
|
||||
)
|
||||
from production_analytics.erp import ProductionConfirmation
|
||||
|
||||
|
||||
class ProductionConfirmationReader(Protocol):
|
||||
def get_confirmations(
|
||||
self, *, workplace: str, start: datetime, end: datetime
|
||||
) -> list[ProductionConfirmation]: ...
|
||||
|
||||
|
||||
class ShiftProductionService:
|
||||
def __init__(self, gateway: ProductionConfirmationReader) -> None:
|
||||
self.gateway = gateway
|
||||
|
||||
def summarize(
|
||||
self, *, workplace: str, start: datetime, end: datetime
|
||||
) -> ShiftProductionSummary:
|
||||
workplace = validate_shift_window(workplace=workplace, start=start, end=end)
|
||||
confirmations = self.gateway.get_confirmations(workplace=workplace, start=start, end=end)
|
||||
return aggregate_shift_production(confirmations, workplace=workplace, start=start, end=end)
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Sequential composition of validated services; mandatory failures propagate."""
|
||||
|
||||
from collections.abc import Mapping
|
||||
from datetime import datetime
|
||||
from types import MappingProxyType
|
||||
|
||||
from production_analytics.calculations.shift_report import SHIFT_TIMEZONE, 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 (
|
||||
ShiftChannelMaterialService,
|
||||
ShiftMaterialService,
|
||||
)
|
||||
from production_analytics.service.shift_production import ShiftProductionService
|
||||
from production_analytics.service.shift_report_config import ShiftReportMachineConfig
|
||||
from production_analytics.service.shift_speed import ShiftSpeedService
|
||||
|
||||
|
||||
class ShiftReportService:
|
||||
def __init__(
|
||||
self, *, machines: Mapping[str, ShiftReportMachineConfig],
|
||||
production: ShiftProductionService, downtime: ShiftDowntimeService,
|
||||
materials: ShiftMaterialService, channel_materials: ShiftChannelMaterialService,
|
||||
speed: ShiftSpeedService,
|
||||
) -> None:
|
||||
self.machines = MappingProxyType(dict(machines))
|
||||
self.production = production
|
||||
self.downtime = downtime
|
||||
self.materials = materials
|
||||
self.channel_materials = channel_materials
|
||||
self.speed = speed
|
||||
|
||||
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)
|
||||
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)
|
||||
return ShiftReport(
|
||||
machine_name=machine_name, machine_id=config.machine_id, start=start, end=end,
|
||||
production=production, downtime=downtime, materials=materials, speed=speed,
|
||||
)
|
||||
@@ -0,0 +1,105 @@
|
||||
"""Strict, self-contained configuration for shift-report composition."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
import yaml
|
||||
|
||||
from production_analytics.calculations.shift_speed import ShiftSpeedConfig
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ShiftReportMaterialConfig:
|
||||
mode: Literal["cumulative", "channel"]
|
||||
calculation_ids: tuple[str, ...]
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if self.mode not in ("cumulative", "channel"):
|
||||
raise ValueError("material.mode must be cumulative or channel")
|
||||
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:
|
||||
_text(calculation_id, "material.calculation_ids")
|
||||
if len(set(self.calculation_ids)) != len(self.calculation_ids):
|
||||
raise ValueError("material.calculation_ids must be unique")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ShiftReportMachineConfig:
|
||||
machine_id: str
|
||||
erp_workplace: str
|
||||
material: ShiftReportMaterialConfig
|
||||
speed: ShiftSpeedConfig
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
_text(self.machine_id, "machine_id")
|
||||
_text(self.erp_workplace, "erp_workplace")
|
||||
if 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")
|
||||
|
||||
|
||||
class _StrictLoader(yaml.SafeLoader):
|
||||
"""Reject duplicate YAML keys instead of silently replacing configuration."""
|
||||
|
||||
|
||||
def _mapping(loader, node):
|
||||
result = {}
|
||||
for key_node, value_node in node.value:
|
||||
key = loader.construct_object(key_node)
|
||||
if not isinstance(key, str) or key in result:
|
||||
raise ValueError("Configuration mapping keys must be unique strings")
|
||||
result[key] = loader.construct_object(value_node)
|
||||
return result
|
||||
|
||||
|
||||
_StrictLoader.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, _mapping)
|
||||
|
||||
|
||||
def _text(value: object, name: str) -> None:
|
||||
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")
|
||||
|
||||
|
||||
def _fields(value: object, expected: set[str], name: str) -> dict:
|
||||
if not isinstance(value, dict) or set(value) != expected:
|
||||
raise ValueError(f"{name} has missing or unknown fields")
|
||||
return value
|
||||
|
||||
|
||||
def load_shift_report_machines(path: str | Path) -> dict[str, ShiftReportMachineConfig]:
|
||||
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")
|
||||
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",
|
||||
)
|
||||
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"],
|
||||
),
|
||||
)
|
||||
if len({config.machine_id for config in result.values()}) != len(result):
|
||||
raise ValueError("Shift-report machine IDs must be unique")
|
||||
return result
|
||||
@@ -0,0 +1,33 @@
|
||||
"""Compose bounded ENLYZE speed reads with the pure running-speed KPI."""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Protocol
|
||||
|
||||
from production_analytics.calculations.shift_speed import (
|
||||
ShiftSpeedConfig,
|
||||
ShiftSpeedSample,
|
||||
ShiftSpeedSummary,
|
||||
aggregate_shift_speed,
|
||||
validate_speed_window,
|
||||
)
|
||||
|
||||
|
||||
class ShiftSpeedReader(Protocol):
|
||||
def get_speed_samples(
|
||||
self, *, machine_id: str, speed_signal_ref: str, start: datetime, end: datetime,
|
||||
) -> list[ShiftSpeedSample]: ...
|
||||
|
||||
|
||||
class ShiftSpeedService:
|
||||
def __init__(self, gateway: ShiftSpeedReader) -> None:
|
||||
self.gateway = gateway
|
||||
|
||||
def summarize(
|
||||
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,
|
||||
)
|
||||
return aggregate_shift_speed(samples, config=config, start=start, end=end)
|
||||
Reference in new issue
Block a user