Add per-order speed and material KPIs

This commit is contained in:
admin committed 2026-10-20 16:07:57 +02:00
1 parent 211fb45d52
commit f6ebd78a4a
15 files changed
+773 -30

No files matched your search

+48 -9
View File
@@ -1,11 +1,11 @@
# Unified shift-report composition # Unified shift-report composition
`ShiftReportService` composes the existing production, downtime, material, and `ShiftReportService` composes the existing production, downtime, material, and
speed services sequentially. It performs no database or HTTP reads itself and speed services sequentially. It performs no database or HTTP reads itself.
adds no quantity or interval aggregation. Its frozen `ShiftReport` reuses all For production rows it asks the shared production-order service for FA KPI
four immutable summary models directly, preserving source metadata and items attribution, preserving the original shift totals and source metadata. The
for PDF output and the live web UI. Presentation lives separately in frozen `ShiftReport` feeds both PDF and live web UI; presentation remains
`presentation.shift_report`; report composition remains output-independent. output-independent.
## Configuration and API ## Configuration and API
@@ -116,7 +116,7 @@ Speed is the arithmetic sample mean strictly above the configured production
gate: average speed while running, not average speed over the full shift. gate: average speed while running, not average speed over the full shift.
Counts, gate, and active min/max are preserved in `report.speed`. Counts, gate, and active min/max are preserved in `report.speed`.
Every enabled source is mandatory. Disabled sections are `None` in the report and Every enabled shift-wide source is mandatory. Disabled sections are `None` in the report and
render as unavailable; no source is queried for them. Exceptions propagate render as unavailable; no source is queried for them. Exceptions propagate
immediately and later services are not called. An empty successful summary remains immediately and later services are not called. An empty successful summary remains
an empty summary; a failed an empty summary; a failed
@@ -243,8 +243,47 @@ FA, machine and shift sum their positive feedback m². Unknown or ambiguous
workplaces remain visible but cannot be assigned a configured shift. workplaces remain visible but cannot be assigned a configured shift.
The ERP gateway owns parameterized read-only SQL, the production-order service The ERP gateway owns parameterized read-only SQL, the production-order service
owns mapping and shift grouping, and a dedicated presenter renders HTML. The owns mapping, shift grouping, and approximate KPI windows, and a dedicated
order/machine/shift model is the anchor for later order-specific KPI, roll/QS and presenter renders HTML. The order/machine/shift model can later anchor roll/QS
setup-sheet views; those data are not included yet. ERP timestamps are local and setup-sheet views; those data are not included yet. ERP timestamps are local
datetimes without offsets; autumn repeated-hour rows are interpreted as the datetimes without offsets; autumn repeated-hour rows are interpreted as the
first occurrence, as in the existing confirmation gateway. first occurrence, as in the existing confirmation gateway.
For each affected machine shift, positive ERP confirmations for **all** FAs are
sorted by instant (FA breaks ties). Consecutive confirmations of one FA form a
run. The boundary between adjacent runs is the midpoint between the preceding
run's last confirmation and the next run's first confirmation. The first run
starts at shift start and the last ends at shift end. Windows are half-open and
do not overlap. If an FA returns after another FA, it has multiple windows but
still one row for that shift. These windows are a practical estimate from ERP
confirmation times, **not** exact machine-running intervals; idle periods at
shift edges may be included. Exact same-time FA changes are sorted by FA; a
zero-length window yields unavailable KPIs rather than an invented interval.
Each window is passed to the existing speed service, retaining the machine's
numeric, Boolean, or dwell activity gate. The displayed FA speed combines active
sample means by active sample count, so it remains an arithmetic sample mean.
For material sources without an order-aware allocator, each window is passed to
the configured cumulative or channel material service, using its normal
baseline and counter-delta rules. Snapshot timing around midpoint boundaries
can leave small gaps or shifts in attribution, so those segment totals need only
approximately reconcile with the whole-shift total. Where an order-aware
allocator is configured, K7 being the current example, FA material instead sums
the allocated items from the **full-shift** material result by production order.
The compact FA value thus uses the same ENLYZE measurement and ERP fiber
allocation as the detailed material table. The shift report reuses its already
allocated summary; the order detail obtains and allocates a full-shift summary.
Speed always uses the approximate FA windows.
The shift report's production table uses these same FA windows and KPI results
for each listed order. Its speed describes the FA's estimated period; material
uses the configured segment or order-aware source rule. The shift-wide speed and
material sections remain useful reconciliation totals. In HTML, the FA number
links directly to `/order?production_order=...` for the order's full shift list.
The PDF prints the FA number as text.
Disabled speed or material capability produces `—` and makes no query to that
source. No active speed samples also produce `—`; an observed material total of
zero remains `0,00 kg`. Known ENLYZE/PostgreSQL/ERP source-read failures degrade
that optional KPI to unavailable. Unexpected configuration or calculation errors
still fail the order page rather than being hidden.
@@ -18,6 +18,8 @@ class ShiftProductionItem:
roll_count: int roll_count: int
first_confirmation_at: datetime first_confirmation_at: datetime
last_confirmation_at: datetime last_confirmation_at: datetime
average_speed_m_min: float | None = None
material_consumption_kg: float | None = None
@dataclass(frozen=True, slots=True) @dataclass(frozen=True, slots=True)
@@ -7,6 +7,7 @@ from production_analytics.presentation.mode_navigation import (
MODE_NAV_CSS, MODE_NAV_CSS,
render_mode_navigation, render_mode_navigation,
) )
from production_analytics.presentation.shift_report import _number
from production_analytics.service.production_order import ( from production_analytics.service.production_order import (
ProductionOrderDetail, ProductionOrderDetail,
ProductionOrderSearchResult, ProductionOrderSearchResult,
@@ -83,7 +84,8 @@ def render_detail(*, detail: ProductionOrderDetail | None,
return _page("Fertigungsauftrag", "<p>Fertigungsauftrag nicht gefunden.</p>") return _page("Fertigungsauftrag", "<p>Fertigungsauftrag nicht gefunden.</p>")
body = f"<h1>Fertigungsauftrag {escape(detail.production_order)}</h1>" body = f"<h1>Fertigungsauftrag {escape(detail.production_order)}</h1>"
body += '<p class="metadata">Zeiten sind ERP-Rückmeldezeitpunkte, keine durchgehenden ' body += '<p class="metadata">Zeiten sind ERP-Rückmeldezeitpunkte, keine durchgehenden '
body += 'Maschinenlaufzeiten. Mengen sind positive Rückmeldemengen in m².</p>' body += 'Maschinenlaufzeiten. Mengen sind positive Rückmeldemengen in m². '
body += 'Geschwindigkeit und Material beziehen sich auf angenäherte FA-Zeitfenster.</p>'
body += '<h2>Artikel und Arbeitsplätze</h2><div class="table-scroll"><table><thead><tr>' body += '<h2>Artikel und Arbeitsplätze</h2><div class="table-scroll"><table><thead><tr>'
body += '<th>Artikel</th><th>Artikelbezeichnung</th><th>Arbeitsplatz / Maschine</th>' body += '<th>Artikel</th><th>Artikelbezeichnung</th><th>Arbeitsplatz / Maschine</th>'
body += '<th>Erste Rückmeldung</th><th>Letzte Rückmeldung</th></tr></thead><tbody>' body += '<th>Erste Rückmeldung</th><th>Letzte Rückmeldung</th></tr></thead><tbody>'
@@ -101,6 +103,7 @@ def render_detail(*, detail: ProductionOrderDetail | None,
else: else:
body += '<div class="table-scroll"><table><thead><tr><th>Standort</th><th>Maschine</th>' body += '<div class="table-scroll"><table><thead><tr><th>Standort</th><th>Maschine</th>'
body += '<th>Datum</th><th>Schicht</th><th>Produzierte Menge</th>' body += '<th>Datum</th><th>Schicht</th><th>Produzierte Menge</th>'
body += '<th>Ø Geschwindigkeit</th><th>Materialverbrauch</th>'
body += '<th>Erste Rückmeldung</th><th>Letzte Rückmeldung</th><th>Bericht</th>' body += '<th>Erste Rückmeldung</th><th>Letzte Rückmeldung</th><th>Bericht</th>'
body += '</tr></thead><tbody>' body += '</tr></thead><tbody>'
for item in detail.shifts: for item in detail.shifts:
@@ -110,6 +113,10 @@ def render_detail(*, detail: ProductionOrderDetail | None,
escape(item.site.title()), escape(item.machine_name), escape(item.site.title()), escape(item.machine_name),
item.date.strftime("%d.%m.%Y"), item.date.strftime("%d.%m.%Y"),
SHIFT_LABELS[item.shift], f"{item.produced_m2:,.2f} m²", SHIFT_LABELS[item.shift], f"{item.produced_m2:,.2f} m²",
(f"{_number(item.average_speed_m_min)} m/min"
if item.average_speed_m_min is not None else "—"),
(f"{_number(item.material_consumption_kg)} kg"
if item.material_consumption_kg is not None else "—"),
escape(item.first_confirmation.strftime("%d.%m.%Y %H:%M %Z")), escape(item.first_confirmation.strftime("%d.%m.%Y %H:%M %Z")),
escape(item.last_confirmation.strftime("%d.%m.%Y %H:%M %Z")), escape(item.last_confirmation.strftime("%d.%m.%Y %H:%M %Z")),
f'<a href="{escape(href, quote=True)}">Schichtbericht</a>', f'<a href="{escape(href, quote=True)}">Schichtbericht</a>',
@@ -63,7 +63,8 @@ def present_report(
text("Für diese Maschine nicht verfügbar.") text("Für diese Maschine nicht verfügbar.")
elif report.production.items: elif report.production.items:
table( table(
("Produktionsauftrag", "Artikelnummer", "Artikelbeschreibung", "Menge", "Rollen"), ("Produktionsauftrag", "Artikelnummer", "Artikelbeschreibung", "Menge", "Rollen",
"Ø Geschwindigkeit", "Materialverbrauch"),
[ [
( (
item.production_order, item.production_order,
@@ -71,10 +72,14 @@ def present_report(
item.article_description or "Nicht verfügbar", item.article_description or "Nicht verfügbar",
f"{_number(item.produced_m2)} m²", f"{_number(item.produced_m2)} m²",
str(item.roll_count), str(item.roll_count),
(f"{_number(item.average_speed_m_min)} m/min"
if item.average_speed_m_min is not None else "—"),
(f"{_number(item.material_consumption_kg)} kg"
if item.material_consumption_kg is not None else "—"),
) )
for item in report.production.items for item in report.production.items
], ],
[36, 30, 62, 30, 20], [28, 22, 44, 23, 13, 23, 25],
) )
elif report.production is not None: elif report.production is not None:
text("Keine Produktionsdaten vorhanden.") text("Keine Produktionsdaten vorhanden.")
@@ -2,6 +2,7 @@
from html import escape from html import escape
from math import fsum from math import fsum
from urllib.parse import urlencode
from production_analytics.presentation.mode_navigation import ( from production_analytics.presentation.mode_navigation import (
MODE_NAV_CSS, MODE_NAV_CSS,
@@ -93,8 +94,19 @@ def render_page(*, machines, labels, day, shift, machine, report, generated_at,
body += '<div class="table-scroll"><table><thead><tr>' body += '<div class="table-scroll"><table><thead><tr>'
body += "".join(f'<th scope="col">{escape(cell)}</th>' for cell in block.headers) body += "".join(f'<th scope="col">{escape(cell)}</th>' for cell in block.headers)
body += "</tr></thead><tbody>" body += "</tr></thead><tbody>"
production_table = block.headers[:2] == ("Produktionsauftrag", "Artikelnummer")
for row in block.rows: for row in block.rows:
body += "<tr>" + "".join(f"<td>{escape(cell)}</td>" for cell in row) + "</tr>" cells = []
for index, cell in enumerate(row):
if production_table and index == 0:
href = "/order?" + urlencode({"production_order": cell})
cells.append(
f'<td><a class="fa-link" href="{escape(href, quote=True)}">'
f"{escape(cell)}</a></td>"
)
else:
cells.append(f"<td>{escape(cell)}</td>")
body += "<tr>" + "".join(cells) + "</tr>"
body += "</tbody></table></div>" body += "</tbody></table></div>"
elif isinstance(block, MaterialPieBlock): elif isinstance(block, MaterialPieBlock):
body += "</div>" + _material_chart(block) body += "</div>" + _material_chart(block)
@@ -113,6 +125,8 @@ input,select,button {{font:inherit; padding:.55rem}} button {{cursor:pointer}}
table {{width:100%; border-collapse:collapse}} th,td {{text-align:left; padding:.7rem; table {{width:100%; border-collapse:collapse}} th,td {{text-align:left; padding:.7rem;
border-bottom:1px solid #c9d1d8}} th {{background:#e8eef3}} border-bottom:1px solid #c9d1d8}} th {{background:#e8eef3}}
.table-scroll {{overflow-x:auto}} .metadata {{color:#526473; font-size:.9rem}} .table-scroll {{overflow-x:auto}} .metadata {{color:#526473; font-size:.9rem}}
.fa-link {{color:#17547a; font-weight:600; text-decoration:underline;
text-underline-offset:2px}} .fa-link:hover,.fa-link:focus-visible {{color:#0b3653}}
.material-layout {{display:grid; grid-template-columns:minmax(0, 1fr) 300px; gap:1.5rem}} .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; .material-chart {{margin:0; min-width:0}} .material-chart svg {{display:block;
width:220px; max-width:100%; margin:.75rem auto}} width:220px; max-width:100%; margin:.75rem auto}}
@@ -1,7 +1,9 @@
"""Explicit K7 order adapter; generic measured material calculation stays ERP-free.""" """Explicit K7 order adapter; generic measured material calculation stays ERP-free."""
import re import re
from collections import defaultdict
from dataclasses import replace from dataclasses import replace
from math import fsum
from typing import Protocol from typing import Protocol
from production_analytics.calculations.fiber_allocation import ( from production_analytics.calculations.fiber_allocation import (
@@ -33,3 +35,12 @@ class K7FiberAllocationService:
items.extend(allocate_fiber_materials(item, bookings[order], erp_order=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. # Keep the measured shift total, rather than replacing it with an ERP total.
return replace(measured, items=tuple(items)) return replace(measured, items=tuple(items))
def totals_by_order(self, allocated: ShiftMaterialSummary) -> dict[str, float]:
"""Sum the same allocated items shown in the shift material table by ERP FA."""
quantities = defaultdict(list)
for item in allocated.items:
match = re.fullmatch(r"(?:K 7-)?([0-9]+)", item.production_order.strip())
if match is not None:
quantities[match[1]].append(item.consumption_kg)
return {order: fsum(values) for order, values in quantities.items()}
@@ -2,20 +2,40 @@
from collections import defaultdict from collections import defaultdict
from collections.abc import Mapping from collections.abc import Mapping
from dataclasses import dataclass from dataclasses import dataclass, replace
from datetime import UTC, date, datetime from datetime import UTC, date, datetime
from math import fsum from math import fsum
from typing import Literal, Protocol from typing import Literal, Protocol
from zoneinfo import ZoneInfo from zoneinfo import ZoneInfo
from production_analytics.calculations.shift_material import ShiftMaterialSummary
from production_analytics.calculations.shift_report import shift_containing from production_analytics.calculations.shift_report import shift_containing
from production_analytics.erp.gateway import OrderConfirmationGroup, OrderConfirmationRow from production_analytics.enlyze.exploration import ExplorationError
from production_analytics.erp.gateway import (
ErpReadError,
OrderConfirmationGroup,
OrderConfirmationRow,
ProductionConfirmation,
)
from production_analytics.service.postgres_shift_material import ShiftMaterialReadError
from production_analytics.service.shift_material import (
ShiftChannelMaterialService,
ShiftMaterialService,
)
from production_analytics.service.shift_report_config import ShiftReportMachineConfig from production_analytics.service.shift_report_config import ShiftReportMachineConfig
from production_analytics.service.shift_speed import ShiftSpeedService
class ProductionOrderReader(Protocol): class ProductionOrderReader(Protocol):
def search_orders(self, query: str, *, limit: int = 25) -> list[OrderConfirmationGroup]: ... def search_orders(self, query: str, *, limit: int = 25) -> list[OrderConfirmationGroup]: ...
def get_order_confirmations(self, production_order: str) -> list[OrderConfirmationRow]: ... def get_order_confirmations(self, production_order: str) -> list[OrderConfirmationRow]: ...
def get_confirmations(self, *, workplace: str, start: datetime, end: datetime,
timezone: ZoneInfo) -> list[ProductionConfirmation]: ...
class MaterialAllocator(Protocol):
def allocate(self, measured: ShiftMaterialSummary) -> ShiftMaterialSummary: ...
def totals_by_order(self, allocated: ShiftMaterialSummary) -> dict[str, float]: ...
@dataclass(frozen=True, slots=True) @dataclass(frozen=True, slots=True)
@@ -37,6 +57,19 @@ class ProductionOrderSearchResult:
placements: tuple[ProductionOrderPlacement, ...] placements: tuple[ProductionOrderPlacement, ...]
@dataclass(frozen=True, slots=True)
class ProductionOrderSegment:
start: datetime
end: datetime
@dataclass(frozen=True, slots=True)
class ProductionOrderShiftKpi:
segments: tuple[ProductionOrderSegment, ...]
average_speed_m_min: float | None
material_consumption_kg: float | None
@dataclass(frozen=True, slots=True) @dataclass(frozen=True, slots=True)
class ProductionOrderShift: class ProductionOrderShift:
production_order: str production_order: str
@@ -51,6 +84,9 @@ class ProductionOrderShift:
first_confirmation: datetime first_confirmation: datetime
last_confirmation: datetime last_confirmation: datetime
produced_m2: float produced_m2: float
segments: tuple[ProductionOrderSegment, ...] = ()
average_speed_m_min: float | None = None
material_consumption_kg: float | None = None
@dataclass(frozen=True, slots=True) @dataclass(frozen=True, slots=True)
@@ -64,8 +100,17 @@ class ProductionOrderService:
"""Resolve workplace and site timezone before assigning confirmation timestamps.""" """Resolve workplace and site timezone before assigning confirmation timestamps."""
def __init__(self, gateway: ProductionOrderReader, def __init__(self, gateway: ProductionOrderReader,
machines: Mapping[str, ShiftReportMachineConfig]) -> None: machines: Mapping[str, ShiftReportMachineConfig], *,
speed: ShiftSpeedService | None = None,
materials: ShiftMaterialService | None = None,
channel_materials: ShiftChannelMaterialService | None = None,
material_allocators: Mapping[str, MaterialAllocator] | None = None) -> None:
self.gateway = gateway self.gateway = gateway
self.speed = speed
self.materials = materials
self.channel_materials = channel_materials
self.material_allocators = dict(material_allocators or {})
self.machines = dict(machines)
workplace_map = defaultdict(list) workplace_map = defaultdict(list)
for name, config in machines.items(): for name, config in machines.items():
workplace_map[config.erp_workplace].append((name, config)) workplace_map[config.erp_workplace].append((name, config))
@@ -145,7 +190,133 @@ class ProductionOrderService:
)) ))
shift_models.sort(key=lambda item: (item.shift_start.astimezone(UTC), shift_models.sort(key=lambda item: (item.shift_start.astimezone(UTC),
item.machine_name)) item.machine_name))
return ProductionOrderDetail(order, place_models, tuple(shift_models)) enriched = []
for item in shift_models:
kpi = self.for_shift(machine_name=item.machine_name, start=item.shift_start,
end=item.shift_end, orders=(item.production_order,))[
item.production_order]
enriched.append(replace(item, segments=kpi.segments,
average_speed_m_min=kpi.average_speed_m_min,
material_consumption_kg=kpi.material_consumption_kg))
return ProductionOrderDetail(order, place_models, tuple(enriched))
def for_shift(self, *, machine_name: str, start: datetime, end: datetime,
orders: tuple[str, ...],
allocated_shift_materials: ShiftMaterialSummary | None = None,
) -> dict[str, ProductionOrderShiftKpi]:
"""Attribute one machine shift to all requested FAs with shared segmentation."""
if machine_name not in self.machines:
raise ValueError("Unknown machine")
if not orders:
return {}
config = self.machines[machine_name]
confirmations = self.gateway.get_confirmations(
workplace=config.erp_workplace, start=start, end=end, timezone=config.timezone)
by_order = _segments_by_order(
confirmations, workplace=config.erp_workplace, timezone=config.timezone,
start=start, end=end)
allocator = self.material_allocators.get(machine_name)
allocated_totals = None
if allocator is not None and config.material is not None:
try:
if allocated_shift_materials is None:
service = (self.channel_materials if config.material.mode == "channel"
else self.materials)
if service is not None:
measured = service.summarize(
machine_id=config.machine_id,
calculation_ids=config.material.calculation_ids,
start=start, end=end,
)
allocated_shift_materials = allocator.allocate(measured)
if allocated_shift_materials is not None:
allocated_totals = allocator.totals_by_order(allocated_shift_materials)
except (ShiftMaterialReadError, ErpReadError):
allocated_totals = None
result = {}
for order in dict.fromkeys(orders):
segments = by_order.get(order, ())
if allocator is not None:
material = allocated_totals.get(order) if allocated_totals is not None else None
elif segments:
material = self._material_for_segments(config, segments)
else:
material = None
result[order] = ProductionOrderShiftKpi(
segments=segments,
average_speed_m_min=self._speed_for_segments(config, segments) if segments
else None,
material_consumption_kg=material,
)
return result
def _speed_for_segments(self, config: ShiftReportMachineConfig,
segments: tuple[ProductionOrderSegment, ...]) -> float | None:
if config.speed is None or self.speed is None:
return None
try:
summaries = [self.speed.summarize(config=config.speed, start=part.start,
end=part.end) for part in segments]
except ExplorationError:
return None
count = sum(summary.active_sample_count for summary in summaries)
if count == 0:
return None
return fsum(summary.average_line_speed_m_min * (summary.active_sample_count / count)
for summary in summaries if summary.active_sample_count)
def _material_for_segments(self, config: ShiftReportMachineConfig,
segments: tuple[ProductionOrderSegment, ...]) -> float | None:
if config.material is None:
return None
service = (self.channel_materials if config.material.mode == "channel"
else self.materials)
if service is None:
return None
try:
measured = [service.summarize(
machine_id=config.machine_id,
calculation_ids=config.material.calculation_ids,
start=part.start, end=part.end,
) for part in segments]
except (ShiftMaterialReadError, ErpReadError):
return None
return fsum(summary.total_consumption_kg for summary in measured)
def _segments_by_order(
confirmations: list[ProductionConfirmation], *, workplace: str, timezone: ZoneInfo,
start: datetime, end: datetime,
) -> dict[str, tuple[ProductionOrderSegment, ...]]:
"""Partition one shift at midpoints between adjacent FA confirmation runs."""
first = start.astimezone(UTC)
last = end.astimezone(UTC)
ordered = sorted(
((row.timestamp.astimezone(UTC), row.production_order) for row in confirmations
if row.workplace == workplace and row.is_finished_goods
and first <= row.timestamp.astimezone(UTC) < last),
key=lambda entry: (entry[0], entry[1]),
)
if not ordered:
return {}
runs = []
for stamp, order in ordered:
if not runs or runs[-1][0] != order:
runs.append([order, stamp, stamp])
else:
runs[-1][2] = stamp
boundaries = [first]
for before, after in zip(runs, runs[1:]):
midpoint = before[2] + (after[1] - before[2]) / 2
boundaries.append(max(first, min(midpoint, last)))
boundaries.append(last)
by_order = defaultdict(list)
for index, run in enumerate(runs):
if boundaries[index] < boundaries[index + 1]:
by_order[run[0]].append(ProductionOrderSegment(
boundaries[index].astimezone(timezone),
boundaries[index + 1].astimezone(timezone)))
return {order: tuple(segments) for order, segments in by_order.items()}
def _order_input(value: str) -> str: def _order_input(value: str) -> str:
@@ -1,6 +1,7 @@
"""Sequential composition of validated services; mandatory failures propagate.""" """Sequential composition of validated services; mandatory failures propagate."""
from collections.abc import Mapping from collections.abc import Mapping
from dataclasses import replace
from datetime import datetime from datetime import datetime
from types import MappingProxyType from types import MappingProxyType
from typing import Protocol from typing import Protocol
@@ -8,6 +9,7 @@ from typing import Protocol
from production_analytics.calculations.shift_material import ShiftMaterialSummary from production_analytics.calculations.shift_material import ShiftMaterialSummary
from production_analytics.calculations.shift_report import ShiftReport from production_analytics.calculations.shift_report import ShiftReport
from production_analytics.calculations.shift_speed import validate_speed_window from production_analytics.calculations.shift_speed import validate_speed_window
from production_analytics.service.production_order import ProductionOrderService
from production_analytics.service.shift_downtime import ShiftDowntimeService from production_analytics.service.shift_downtime import ShiftDowntimeService
from production_analytics.service.shift_material import ( from production_analytics.service.shift_material import (
ShiftChannelMaterialService, ShiftChannelMaterialService,
@@ -33,6 +35,7 @@ class ShiftReportService:
channel_materials: ShiftChannelMaterialService, channel_materials: ShiftChannelMaterialService,
speed: ShiftSpeedService, speed: ShiftSpeedService,
material_allocators: Mapping[str, ShiftMaterialAllocator] | None = None, material_allocators: Mapping[str, ShiftMaterialAllocator] | None = None,
order_kpis: ProductionOrderService | None = None,
) -> None: ) -> None:
self.machines = MappingProxyType(dict(machines)) self.machines = MappingProxyType(dict(machines))
self.production = production self.production = production
@@ -41,6 +44,7 @@ class ShiftReportService:
self.channel_materials = channel_materials self.channel_materials = channel_materials
self.speed = speed self.speed = speed
self.material_allocators = MappingProxyType(dict(material_allocators or {})) self.material_allocators = MappingProxyType(dict(material_allocators or {}))
self.order_kpis = order_kpis
def build(self, *, machine_name: str, start: datetime, end: datetime) -> ShiftReport: def build(self, *, machine_name: str, start: datetime, end: datetime) -> ShiftReport:
validate_speed_window(start, end) validate_speed_window(start, end)
@@ -71,6 +75,20 @@ class ShiftReportService:
materials = self.material_allocators[machine_name].allocate(materials) materials = self.material_allocators[machine_name].allocate(materials)
speed = (self.speed.summarize(config=config.speed, start=start, end=end) speed = (self.speed.summarize(config=config.speed, start=start, end=end)
if config.speed is not None else None) if config.speed is not None else None)
if (production is not None and production.items and self.order_kpis is not None
and (config.speed is not None or config.material is not None)):
kpis = self.order_kpis.for_shift(
machine_name=machine_name, start=start, end=end,
orders=tuple(item.production_order for item in production.items),
allocated_shift_materials=(materials if machine_name in self.material_allocators
else None),
)
production = replace(production, items=tuple(
replace(item,
average_speed_m_min=kpis[item.production_order].average_speed_m_min,
material_consumption_kg=kpis[item.production_order].material_consumption_kg)
for item in production.items
))
return ShiftReport( return ShiftReport(
machine_name=machine_name, machine_name=machine_name,
machine_id=config.machine_id, machine_id=config.machine_id,
@@ -16,6 +16,7 @@ from production_analytics.service.postgres_shift_material import (
PostgresShiftChannelMaterialRepository, PostgresShiftChannelMaterialRepository,
PostgresShiftMaterialRepository, PostgresShiftMaterialRepository,
) )
from production_analytics.service.production_order import ProductionOrderService
from production_analytics.service.shift_downtime import ShiftDowntimeService from production_analytics.service.shift_downtime import ShiftDowntimeService
from production_analytics.service.shift_material import ( from production_analytics.service.shift_material import (
ShiftChannelMaterialService, ShiftChannelMaterialService,
@@ -39,14 +40,21 @@ def build_shift_report_service(
for name, config in machines.items() for name, config in machines.items()
if config.material is not None and config.material.allocation == "erp_fiber_share" if config.material is not None and config.material.allocation == "erp_fiber_share"
} }
confirmation_gateway = ErpProductionConfirmationGateway(erp)
materials = ShiftMaterialService(PostgresShiftMaterialRepository(postgres))
channel_materials = ShiftChannelMaterialService(
PostgresShiftChannelMaterialRepository(postgres))
speed = ShiftSpeedService(EnlyzeApiGateway(ExplorationClient(enlyze)))
order_kpis = ProductionOrderService(
confirmation_gateway, machines, speed=speed, materials=materials,
channel_materials=channel_materials, material_allocators=allocators)
return ShiftReportService( return ShiftReportService(
machines=machines, machines=machines,
material_allocators=allocators, material_allocators=allocators,
production=ShiftProductionService(ErpProductionConfirmationGateway(erp)), order_kpis=order_kpis,
production=ShiftProductionService(confirmation_gateway),
downtime=ShiftDowntimeService(PostgresDowntimeRepository(postgres)), downtime=ShiftDowntimeService(PostgresDowntimeRepository(postgres)),
materials=ShiftMaterialService(PostgresShiftMaterialRepository(postgres)), materials=materials,
channel_materials=ShiftChannelMaterialService( channel_materials=channel_materials,
PostgresShiftChannelMaterialRepository(postgres) speed=speed,
),
speed=ShiftSpeedService(EnlyzeApiGateway(ExplorationClient(enlyze))),
) )
+5 -6
View File
@@ -176,12 +176,11 @@ def main(argv=None):
return build_shift_report_service(machines, environment) return build_shift_report_service(machines, environment)
def order_service(): def order_service():
from production_analytics.erp import ErpProductionConfirmationGateway, ErpSettings environment = dict(os.environ)
from production_analytics.service.production_order import ProductionOrderService for path in (args.secrets_file, args.erp_secrets_file, args.db_secrets_file):
environment.update(load_secret_file(path))
environment = {**os.environ, **load_secret_file(args.erp_secrets_file)} sources = build_shift_report_service(machines, environment)
gateway = ErpProductionConfirmationGateway(ErpSettings.from_environment(environment)) return sources.order_kpis
return ProductionOrderService(gateway, machines)
app = create_app(machines, service, sites=config.sites, app = create_app(machines, service, sites=config.sites,
order_service_factory=order_service) order_service_factory=order_service)
+17 -1
View File
@@ -14,6 +14,7 @@ from production_analytics.erp.gateway import (
ErpSettings, ErpSettings,
OrderConfirmationGroup, OrderConfirmationGroup,
OrderConfirmationRow, OrderConfirmationRow,
ProductionConfirmation,
) )
from production_analytics.presentation.production_order_html import render_detail, render_search from production_analytics.presentation.production_order_html import render_detail, render_search
from production_analytics.service.production_order import ProductionOrderService from production_analytics.service.production_order import ProductionOrderService
@@ -32,8 +33,9 @@ def row(hour, minute, *, workplace="GITTERIII", day=19, amount=10,
class FakeGateway: class FakeGateway:
def __init__(self, rows=(), groups=()): def __init__(self, rows=(), groups=(), shift_rows=None):
self.rows = list(rows) self.rows = list(rows)
self.shift_rows = list(rows if shift_rows is None else shift_rows)
self.groups = list(groups) self.groups = list(groups)
self.calls = [] self.calls = []
@@ -45,6 +47,20 @@ class FakeGateway:
self.calls.append(("detail", production_order)) self.calls.append(("detail", production_order))
return self.rows return self.rows
def get_confirmations(self, *, workplace, start, end, timezone):
self.calls.append(("shift", workplace, start, end, timezone))
return [ProductionConfirmation(
workplace=value.workplace, production_order=value.production_order,
timestamp=value.timestamp_local.replace(tzinfo=timezone),
article_number=value.article_number,
article_description=value.article_description,
roll_number=None, production_quantity_m2=None,
feedback_quantity_m2=value.feedback_quantity_m2,
raw_material_number=None, raw_material_description=None, batch_number=None,
raw_material_quantity=None, tenant=None,
) for value in self.shift_rows if value.workplace == workplace and
start <= value.timestamp_local.replace(tzinfo=timezone) < end]
def group(order=ORDER, workplace="GITTERIII", article="A"): def group(order=ORDER, workplace="GITTERIII", article="A"):
return OrderConfirmationGroup(order, workplace, article, "Article name", return OrderConfirmationGroup(order, workplace, article, "Article name",
+380
View File
@@ -0,0 +1,380 @@
"""Approximate FA windows feed existing speed and material services."""
from dataclasses import replace
from datetime import datetime
from math import fsum
from types import SimpleNamespace
import pytest
from test_production_order import BERLIN, MACHINES, FakeGateway, row
from test_shift_report import composition
from production_analytics.calculations.fiber_allocation import FiberBooking
from production_analytics.calculations.shift_material import (
ShiftMaterialItem,
ShiftMaterialSnapshot,
ShiftMaterialSummary,
)
from production_analytics.enlyze.exploration import ExplorationError
from production_analytics.presentation.production_order_html import render_detail
from production_analytics.presentation.shift_report import TableBlock, present_report
from production_analytics.service.fiber_allocation import K7FiberAllocationService
from production_analytics.service.postgres_shift_material import ShiftMaterialReadError
from production_analytics.service.production_order import ProductionOrderService
from production_analytics.service.shift_material import ShiftMaterialService
A, B, C = "FA-A", "FA-B", "FA-C"
class Speed:
def __init__(self, count=2, error=None):
self.calls = []
self.count = count
self.error = error
def summarize(self, *, config, start, end):
self.calls.append((config, start, end))
if self.error:
raise self.error
speed = float(start.hour + 1) if self.count else None
return SimpleNamespace(average_line_speed_m_min=speed,
active_sample_count=self.count)
class Material:
def __init__(self, value=0, error=None):
self.calls = []
self.value = value
self.error = error
def summarize(self, *, machine_id, calculation_ids, start, end):
self.calls.append((machine_id, calculation_ids, start, end))
if self.error:
raise self.error
value = self.value(start, end) if callable(self.value) else self.value
return SimpleNamespace(total_consumption_kg=value, items=())
def service(selected, all_rows, *, speed=None, materials=None, machines=MACHINES):
return ProductionOrderService(FakeGateway(rows=selected, shift_rows=all_rows), machines,
speed=speed, materials=materials)
def b1(hour, minute=0, *, order=A, day=19, amount=10):
return row(hour, minute, workplace="BENTO 1", order=order, day=day, amount=amount)
def windows(detail):
return [(part.start, part.end) for shift in detail.shifts for part in shift.segments]
def test_one_fa_occupies_full_shift_and_sources_receive_segment_window():
speed, material = Speed(), Material(12)
detail = service([b1(9)], [b1(9)], speed=speed, materials=material).detail(A)
shift = detail.shifts[0]
assert windows(detail) == [(datetime(2026, 10, 19, 6, tzinfo=BERLIN),
datetime(2026, 10, 19, 14, tzinfo=BERLIN))]
assert speed.calls[0][1:] == windows(detail)[0]
assert material.calls[0][2:] == windows(detail)[0]
assert (shift.average_speed_m_min, shift.material_consumption_kg) == (7, 12)
def test_two_fas_have_distinct_nonoverlapping_windows_and_kpis():
a, b = b1(7, order=A), b1(11, order=B)
speed, material = Speed(), Material(lambda start, end: 5 if start.hour == 6 else 12)
service_a = service([a], [a, b], speed=speed, materials=material)
service_b = service([b], [a, b], speed=speed, materials=material)
first, second = service_a.detail(A).shifts[0], service_b.detail(B).shifts[0]
assert first.segments[0].start.hour == 6
assert first.segments[0].end.hour == 9
assert second.segments[0].start == first.segments[0].end
assert second.segments[0].end.hour == 14
assert (first.average_speed_m_min, second.average_speed_m_min) == (7, 10)
assert (first.material_consumption_kg, second.material_consumption_kg) == (5, 12)
assert speed.calls[0][1:] == (first.segments[0].start, first.segments[0].end)
assert material.calls[1][2:] == (second.segments[0].start, second.segments[0].end)
def test_shift_report_and_order_detail_use_same_kpi_attribution():
a, b = b1(7, order=A), b1(11, order=B)
speed, material = Speed(), Material(lambda start, end: 5 if start.hour == 6 else 12)
order_service = service([a], [a, b], speed=speed, materials=material)
start = datetime(2026, 10, 19, 6, tzinfo=BERLIN)
end = datetime(2026, 10, 19, 14, tzinfo=BERLIN)
shift_kpis = order_service.for_shift(machine_name="B1", start=start, end=end,
orders=(A, B))
detail = order_service.detail(A).shifts[0]
assert shift_kpis[A].segments == detail.segments
assert shift_kpis[A].average_speed_m_min == detail.average_speed_m_min
assert shift_kpis[A].material_consumption_kg == detail.material_consumption_kg
assert shift_kpis[B].segments[0].start == shift_kpis[A].segments[0].end
assert shift_kpis[A].material_consumption_kg + shift_kpis[B].material_consumption_kg == 17
def test_three_sequential_fas_and_midpoints_are_clamped():
a, b, c = b1(6, order=A), b1(9, order=B), b1(13, order=C)
details = [service([selected], [a, b, c]).detail(selected.production_order)
for selected in (a, b, c)]
segments = [detail.shifts[0].segments[0] for detail in details]
assert [part.start.strftime("%H:%M") for part in segments] == ["06:00", "07:30", "11:00"]
assert [part.end.strftime("%H:%M") for part in segments] == ["07:30", "11:00", "14:00"]
assert all(left.end == right.start for left, right in zip(segments, segments[1:]))
def test_repeated_adjacent_fa_rows_keep_one_segment_and_sum_production():
a1, a2, b = b1(7, order=A, amount=3), b1(8, order=A, amount=4), b1(10, order=B)
detail = service([a1, a2], [a1, a2, b]).detail(A)
assert len(detail.shifts) == len(detail.shifts[0].segments) == 1
assert detail.shifts[0].produced_m2 == 7
assert detail.shifts[0].segments[0].end.hour == 9
def test_alternating_fa_confirmation_runs_remain_two_disjoint_segments():
a1, b, a2 = b1(7, order=A), b1(9, order=B), b1(11, order=A)
speed, material = Speed(), Material(4)
detail = service([a1, a2], [a1, b, a2], speed=speed, materials=material).detail(A)
parts = detail.shifts[0].segments
assert len(parts) == 2
assert parts[0].end.hour == 8 and parts[1].start.hour == 10
assert parts[0].end < parts[1].start
assert len(speed.calls) == len(material.calls) == 2
assert detail.shifts[0].material_consumption_kg == 8
assert detail.shifts[0].average_speed_m_min == 9
def test_simultaneous_three_fa_tie_gives_middle_order_unavailable_kpis():
a, b, c = (b1(9, order=order) for order in (A, B, C))
speed, material = Speed(), Material(4)
shift = service([b], [a, b, c], speed=speed, materials=material).detail(B).shifts[0]
assert shift.produced_m2 == 10
assert shift.segments == ()
assert shift.average_speed_m_min is shift.material_consumption_kg is None
assert speed.calls == material.calls == []
def test_cross_shift_and_night_keep_separate_kpis():
first = b1(21, order=A)
second = b1(1, order=A, day=20)
speed, material = Speed(), Material(3)
detail = service([first, second], [first, second], speed=speed, materials=material).detail(A)
assert [(item.date.day, item.shift) for item in detail.shifts] == [
(19, "late"), (19, "night")]
assert detail.shifts[0].segments[0].end.hour == 22
assert detail.shifts[1].segments[0].start.hour == 22
assert detail.shifts[1].segments[0].end == datetime(2026, 10, 20, 6, tzinfo=BERLIN)
assert [item.material_consumption_kg for item in detail.shifts] == [3, 3]
assert len(speed.calls) == len(material.calls) == 2
def test_disabled_capabilities_never_query_optional_sources():
k1 = row(7, 0, workplace="K1", order=A)
speed, material = Speed(), Material(10)
shift = service([k1], [k1], speed=speed, materials=material).detail(A).shifts[0]
assert shift.average_speed_m_min is shift.material_consumption_kg is None
assert speed.calls == material.calls == []
gitter = row(7, 0, workplace="GITTERIII", order=A)
service([gitter], [gitter], speed=speed, materials=material).detail(A)
assert len(speed.calls) == 1 and material.calls == []
@pytest.mark.parametrize("workplace,machine", [("GITTERIII", "Gitter 3"), ("K5", "K5")])
def test_machine_speed_gate_configuration_is_forwarded_unchanged(workplace, machine):
confirmation = row(7, 0, workplace=workplace, order=A)
speed = Speed()
shift = service([confirmation], [confirmation], speed=speed).detail(A).shifts[0]
assert speed.calls[0][0] is MACHINES[machine].speed
assert shift.average_speed_m_min == 7
def test_channel_material_uses_existing_channel_path():
e1 = row(7, 0, workplace="1568705", order=A)
cumulative, channel = Material(99), Material(6)
order_service = ProductionOrderService(
FakeGateway(rows=[e1]), MACHINES, materials=cumulative,
channel_materials=channel)
shift = order_service.detail(A).shifts[0]
assert shift.material_consumption_kg == 6
assert cumulative.calls == [] and len(channel.calls) == 1
def test_order_aware_allocator_uses_full_shift_summary():
k7 = row(7, 0, workplace="K7", order=A)
material = Material(9)
class Allocator:
def __init__(self):
self.calls = []
def allocate(self, measured):
self.calls.append(measured)
return measured
def totals_by_order(self, allocated):
return {A: allocated.total_consumption_kg}
allocator = Allocator()
order_service = ProductionOrderService(
FakeGateway(rows=[k7]), MACHINES, materials=material,
material_allocators={"K7": allocator})
shift = order_service.detail(A).shifts[0]
assert shift.material_consumption_kg == 9
assert len(allocator.calls) == 1
assert material.calls[0][2:] == (shift.shift_start, shift.shift_end)
def test_k7_compact_material_matches_allocated_shift_items_not_time_segments():
first_order, second_order = "12026001032", "12026001037"
start = datetime(2026, 10, 13, 14, tzinfo=BERLIN)
end = datetime(2026, 10, 13, 22, tzinfo=BERLIN)
config = MACHINES["K7"]
template = ShiftMaterialItem(
source="material_consumption_snapshots",
calculation_id=config.material.calculation_ids[0], machine_id=config.machine_id,
production_order=f"K 7-{first_order}", run_id="run", consumption_kg=3317.58,
baseline_timestamp=start, end_timestamp=end, baseline_missing=False,
)
measured = ShiftMaterialSummary(
config.machine_id, start, end, 5180.94,
(template, replace(template, production_order=f"K 7-{second_order}",
consumption_kg=1863.36)),
)
class Bookings:
def get_fiber_bookings(self, order):
amounts = ((2288.71, 1028.87) if order == first_order else (1312.62, 550.74))
return [FiberBooking(order, str(index), f"Fiber {index}", amount)
for index, amount in enumerate(amounts)]
allocator = K7FiberAllocationService(Bookings())
service, stubs, _, _ = composition("K7")
stubs["materials"].result = measured
first = row(15, 0, day=13, workplace="K7", order=first_order)
second = row(20, 0, day=13, workplace="K7", order=second_order)
order_service = ProductionOrderService(
FakeGateway(rows=[first], shift_rows=[first, second]), MACHINES,
speed=Speed(), materials=stubs["materials"],
material_allocators={"K7": allocator},
)
service.order_kpis = order_service
service.material_allocators = {"K7": allocator}
production = stubs["production"].result
production_items = tuple(
replace(production.items[0], production_order=order,
first_confirmation_at=start, last_confirmation_at=start)
for order in (first_order, second_order)
)
stubs["production"].result = replace(production, items=production_items)
report = service.build(machine_name="K7", start=start, end=end)
assert [item.material_consumption_kg for item in report.production.items] == pytest.approx(
[3317.58, 1863.36])
assert report.materials.total_consumption_kg == pytest.approx(5180.94)
assert fsum(item.consumption_kg for item in report.materials.items) == pytest.approx(5180.94)
assert len(report.materials.items) == 4
assert [item.consumption_kg for item in report.materials.items] == pytest.approx(
[2288.71, 1028.87, 1312.62, 550.74])
material_calls = [kwargs for name, kwargs in stubs["materials"].calls if name == "materials"]
assert material_calls == [{"machine_id": config.machine_id,
"calculation_ids": config.material.calculation_ids,
"start": start, "end": end}]
table = next(block for block in present_report(report)
if isinstance(block, TableBlock) and "Ø Geschwindigkeit" in block.headers)
assert [entry[-1] for entry in table.rows] == ["3.317,58 kg", "1.863,36 kg"]
material_table = next(block for block in present_report(report)
if isinstance(block, TableBlock) and "ERP-Anteil" in block.headers)
assert [entry[3] for entry in material_table.rows] == [
"2.288,71 kg", "1.028,87 kg", "1.312,62 kg", "550,74 kg"]
assert len(order_service.speed.calls) == 2
assert order_service.speed.calls[0][2] == order_service.speed.calls[1][1]
assert order_service.detail(first_order).shifts[0].material_consumption_kg == pytest.approx(
3317.58)
def test_k7_allocated_zero_remains_zero_and_absent_order_is_unavailable():
start = datetime(2026, 10, 13, 14, tzinfo=BERLIN)
end = datetime(2026, 10, 13, 22, tzinfo=BERLIN)
config = MACHINES["K7"]
item = ShiftMaterialItem(
source="material_consumption_snapshots",
calculation_id=config.material.calculation_ids[0], machine_id=config.machine_id,
production_order="K 7-12026001032", run_id="run", consumption_kg=0,
baseline_timestamp=start, end_timestamp=end, baseline_missing=False,
)
allocated = ShiftMaterialSummary(config.machine_id, start, end, 0, (item,))
allocator = K7FiberAllocationService(SimpleNamespace(get_fiber_bookings=lambda order: []))
first = row(15, 0, day=13, workplace="K7", order="12026001032")
second = row(20, 0, day=13, workplace="K7", order="12026001037")
order_service = ProductionOrderService(
FakeGateway(shift_rows=[first, second]), MACHINES,
material_allocators={"K7": allocator},
)
kpis = order_service.for_shift(
machine_name="K7", start=start, end=end,
orders=(first.production_order, second.production_order),
allocated_shift_materials=allocated,
)
assert kpis[first.production_order].material_consumption_kg == 0
assert kpis[second.production_order].material_consumption_kg is None
def test_no_active_speed_is_unavailable_and_material_zero_is_not():
speed, material = Speed(count=0), Material(0)
shift = service([b1(7)], [b1(7)], speed=speed, materials=material).detail(A).shifts[0]
assert shift.average_speed_m_min is None
assert shift.material_consumption_kg == 0
html = render_detail(detail=service([b1(7)], [b1(7)], speed=speed,
materials=material).detail(A))
assert "Ø Geschwindigkeit" in html and "Materialverbrauch" in html
assert "<td>—</td>" in html and "<td>0,00 kg</td>" in html
def test_order_html_formats_per_shift_kpis_in_german():
detail = service([b1(7)], [b1(7)]).detail(A)
enriched = replace(detail, shifts=(replace(detail.shifts[0],
average_speed_m_min=4.77,
material_consumption_kg=1234),))
html = render_detail(detail=enriched)
assert "<td>4,77 m/min</td>" in html
assert "<td>1.234,00 kg</td>" in html
def test_optional_source_failure_degrades_only_that_kpi():
speed = Speed(error=ExplorationError("unavailable"))
material = Material(2)
shift = service([b1(7)], [b1(7)], speed=speed, materials=material).detail(A).shifts[0]
assert shift.average_speed_m_min is None and shift.material_consumption_kg == 2
speed = Speed()
material = Material(error=ShiftMaterialReadError("unavailable"))
shift = service([b1(7)], [b1(7)], speed=speed, materials=material).detail(A).shifts[0]
assert shift.average_speed_m_min == 7 and shift.material_consumption_kg is None
def test_unexpected_programming_error_still_propagates():
with pytest.raises(ValueError, match="invalid configuration"):
service([b1(7)], [b1(7)], speed=Speed(error=ValueError("invalid configuration"))).detail(A)
def test_cumulative_material_segments_use_snapshot_deltas_without_double_counting():
a, b = b1(7, order=A), b1(12, order=B)
config = MACHINES["B1"]
stamps = [(6, 0), (8, 20), (10, 40), (13, 70)]
snapshots = [ShiftMaterialSnapshot(datetime(2026, 10, 19, hour, tzinfo=BERLIN),
config.material.calculation_ids[0], config.machine_id,
A, "run", value) for hour, value in stamps]
class Repository:
def get_snapshots(self, *, machine_id, calculation_ids, start, end):
earlier = [sample for sample in snapshots if sample.timestamp <= start]
inside = [sample for sample in snapshots if start < sample.timestamp < end]
return earlier[-1:] + inside
material = ShiftMaterialService(Repository())
first = service([a], [a, b], materials=material).detail(A).shifts[0]
second = service([b], [a, b], materials=material).detail(B).shifts[0]
whole = material.summarize(machine_id=config.machine_id,
calculation_ids=config.material.calculation_ids,
start=first.shift_start, end=first.shift_end)
assert first.segments[0].end == second.segments[0].start
assert (first.material_consumption_kg, second.material_consumption_kg) == (20, 50)
assert first.material_consumption_kg + second.material_consumption_kg == (
whole.total_consumption_kg)
+37
View File
@@ -123,6 +123,43 @@ def test_machine_composition(name, workplace, mode, ids):
report.machine_name = "other" report.machine_name = "other"
def test_order_kpis_enrich_each_production_row_without_changing_shift_totals():
from dataclasses import replace
from production_analytics.service.production_order import ProductionOrderShiftKpi
service, stubs, _, _ = composition("K7")
first = stubs["production"].result.items[0]
second = replace(first, production_order="other", produced_m2=24)
stubs["production"].result = replace(
stubs["production"].result,
items=(first, second), total_produced_m2=147, total_roll_count=2,
)
class OrderKpis:
def __init__(self):
self.calls = []
def for_shift(self, **kwargs):
self.calls.append(kwargs)
return {
"order": ProductionOrderShiftKpi((), 10.24, 3317.58),
"other": ProductionOrderShiftKpi((), 8.5, 1863.36),
}
order_kpis = OrderKpis()
service.order_kpis = order_kpis
report = service.build(machine_name="K7", start=START, end=END)
assert order_kpis.calls == [{"machine_name": "K7", "start": START, "end": END,
"orders": ("order", "other"),
"allocated_shift_materials": None}]
assert [(item.average_speed_m_min, item.material_consumption_kg)
for item in report.production.items] == [(10.24, 3317.58), (8.5, 1863.36)]
assert report.production.total_produced_m2 == 147
assert report.materials is stubs["materials"].result
assert report.speed is stubs["speed"].result
@pytest.mark.parametrize("name", ["Gitter 1", "Gitter 2", "Gitter 3", "Gitter 4", "K5"]) @pytest.mark.parametrize("name", ["Gitter 1", "Gitter 2", "Gitter 3", "Gitter 4", "K5"])
def test_boolean_speed_machines_appear_in_report_without_material(name): def test_boolean_speed_machines_appear_in_report_without_material(name):
service, stubs, calls, config = composition(name) service, stubs, calls, config = composition(name)
+20
View File
@@ -34,6 +34,26 @@ def test_shift_report_mode_navigation():
assert ".mode-nav a:focus-visible" in html assert ".mode-nav a:focus-visible" in html
def test_production_rows_show_attributed_kpis_and_link_fa_to_detail():
value = material_report((10,))
item = replace(value.production.items[0], production_order="FA A/1",
average_speed_m_min=10.24, material_consumption_kg=3317.58)
html = page(replace(value, production=replace(value.production, items=(item,))))
assert '<a class="fa-link" href="/order?production_order=FA+A%2F1">FA A/1</a>' in html
assert '<th scope="col">Ø Geschwindigkeit</th>' in html
assert '<td>10,24 m/min</td>' in html
assert '<td>3.317,58 kg</td>' in html
assert '<th scope="col">Details</th>' not in html
def test_production_kpis_distinguish_unavailable_from_zero():
value = material_report((10,))
item = replace(value.production.items[0], average_speed_m_min=None,
material_consumption_kg=0)
html = page(replace(value, production=replace(value.production, items=(item,))))
assert '<td>—</td><td>0,00 kg</td>' in html
def test_multiple_materials_chart_and_table(): def test_multiple_materials_chart_and_table():
html = page(material_report((10, 30))) html = page(material_report((10, 30)))
assert '<figure class="material-chart">' in html assert '<figure class="material-chart">' in html
+16
View File
@@ -59,6 +59,22 @@ def test_stable_model_required_labels_and_supplied_quantities():
assert "12,35 m/min" in content(value) assert "12,35 m/min" in content(value)
def test_production_pdf_table_contains_attributed_kpis_as_plain_text():
value = report("K7")
first = replace(value.production.items[0], production_order="12026001032",
average_speed_m_min=10.24, material_consumption_kg=3317.58)
second = replace(first, production_order="12026001037",
average_speed_m_min=None, material_consumption_kg=0)
value = replace(value, production=replace(value.production, items=(first, second)))
table = next(block for block in present_report(value)
if isinstance(block, TableBlock) and "Ø Geschwindigkeit" in block.headers)
assert table.rows[0][-2:] == ("10,24 m/min", "3.317,58 kg")
assert table.rows[1][-2:] == ("—", "0,00 kg")
assert table.rows[0][0] == "12026001032"
assert "Materialverbrauch gesamt: 42,00 kg" in content(value)
assert render_pdf(value).startswith(b"%PDF-")
def test_top_three_preserve_order_and_durations(): def test_top_three_preserve_order_and_durations():
tables = [block for block in present_report(report()) if isinstance(block, TableBlock)] tables = [block for block in present_report(report()) if isinstance(block, TableBlock)]
reasons = next(block for block in tables if block.headers == ("Stillstandsgrund", "Dauer")) reasons = next(block for block in tables if block.headers == ("Stillstandsgrund", "Dauer"))