Extend shift reporting and downtime analytics

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

No files matched your search

@@ -0,0 +1 @@
"""Output presenters independent of report composition and source access."""
@@ -0,0 +1,315 @@
"""German operational shift slips with deterministic A4 PDF output."""
from collections import defaultdict
from dataclasses import dataclass
from io import BytesIO
from math import fsum
from pathlib import Path
from xml.sax.saxutils import escape
from production_analytics.calculations.shift_report import ShiftReport
def _number(value: float) -> str:
return f"{value:,.2f}".translate(str.maketrans({",": ".", ".": ","}))
def _duration(seconds: float) -> str:
hours, remainder = divmod(round(seconds, 1), 3600)
minutes, seconds = divmod(remainder, 60)
return f"{int(hours)} h {int(minutes):02d} min {seconds:04.1f} s".replace(".", ",")
@dataclass(frozen=True, slots=True)
class TextBlock:
text: str
style: str = "Normal"
@dataclass(frozen=True, slots=True)
class TableBlock:
headers: tuple[str, ...]
rows: tuple[tuple[str, ...], ...]
widths_mm: tuple[float, ...]
@dataclass(frozen=True, slots=True)
class MaterialPieBlock:
labels: tuple[str, ...]
consumption_kg: tuple[float, ...]
def present_report(
report: ShiftReport,
*,
include_single_material_chart: bool = False,
) -> tuple[TextBlock | TableBlock | MaterialPieBlock, ...]:
"""Format supplied values and material totals without source access or a clock."""
story = []
def text(value: str, style: str = "Normal") -> None:
story.append(TextBlock(value, style))
def table(headers: tuple[str, ...], rows: list[tuple], widths: list[float]) -> None:
story.append(TableBlock(headers, tuple(rows), tuple(widths)))
text("Schichtbericht", "Title")
text(f"Maschine: {report.display_name or report.machine_name}", "Heading2")
for label, timestamp in (("Schichtbeginn", report.start), ("Schichtende", report.end)):
text(f"{label}: {timestamp.astimezone(report.timezone):%d.%m.%Y %H:%M:%S %Z (%z)}")
text(f"Zeitzone: {report.timezone.key}")
text("Produktion", "Heading2")
if report.production is None:
text("Für diese Maschine nicht verfügbar.")
elif report.production.items:
table(
("Produktionsauftrag", "Artikelnummer", "Artikelbeschreibung", "Menge", "Rollen"),
[
(
item.production_order,
item.article_number or "Nicht verfügbar",
item.article_description or "Nicht verfügbar",
f"{_number(item.produced_m2)} m²",
str(item.roll_count),
)
for item in report.production.items
],
[36, 30, 62, 30, 20],
)
elif report.production is not None:
text("Keine Produktionsdaten vorhanden.")
if report.production is not None:
text(
f"Gesamtmenge: {_number(report.production.total_produced_m2)} m² | "
f"Rollen gesamt: {report.production.total_roll_count}"
)
text("Stillstand", "Heading2")
if report.downtime is None:
text("Für diese Maschine nicht verfügbar.")
else:
text(f"Stillstand gesamt: {_duration(report.downtime.total_downtime_seconds)}")
text("Zeit ohne erfassten Stillstand: " + _duration(report.downtime.non_downtime_seconds))
text("Top 3 Stillstandsgründe", "Heading3")
if report.top_downtime_reasons:
table(
("Stillstandsgrund", "Dauer"),
[
(view.display_name, _duration(view.reason.duration_seconds))
for view in report.top_downtime_reasons
],
[125, 53],
)
else:
text("Keine Stillstandsgründe vorhanden.")
if not report.downtime.events:
text("Keine Stillstandsereignisse vorhanden.")
text("Materialverbrauch", "Heading2")
if report.materials is None:
text("Für diese Maschine nicht verfügbar.")
else:
material_totals = defaultdict(list)
for item in report.materials.items:
material_totals[(item.material_number, item.material_name)].append(item.consumption_kg)
materials = [
(number, name, fsum(quantities))
for (number, name), quantities in sorted(
material_totals.items(),
key=lambda entry: (entry[0][1] or "", entry[0][0] or ""),
)
if fsum(quantities) != 0
]
if any(item.erp_booking_share is not None for item in report.materials.items):
allocation_totals = defaultdict(list)
for item in report.materials.items:
allocation_totals[
(
item.production_order,
item.material_number,
item.material_name,
item.erp_booking_share,
)
].append(item.consumption_kg)
rows = []
for (order, number, name, share), quantities in sorted(
allocation_totals.items(),
key=lambda entry: (
entry[0][0],
entry[0][2] or "",
entry[0][1] or "",
-1 if entry[0][3] is None else entry[0][3],
),
):
quantity = fsum(quantities)
if quantity != 0:
rows.append(
(
order,
name or number or "Materialzuordnung fehlt",
number or "–",
f"{_number(quantity)} kg",
f"{share * 100:.0f}%" if share is not None else "–",
)
)
if rows:
table(
("Produktionsauftrag", "Materialname", "Materialnummer", "Verbrauch",
"ERP-Anteil"),
rows,
[32, 66, 28, 30, 22],
)
else:
text("Keine Materialverbrauchsdaten vorhanden.")
text(
"Verbrauchsaufteilung geschätzt nach ERP-Buchungsverhältnis; "
"Gesamtverbrauch aus ENLYZE."
)
elif materials:
table(
("Materialname", "Materialnummer", "Verbrauch"),
[
(
name or number or "Materialzuordnung fehlt",
number or "–",
f"{_number(quantity)} kg",
)
for number, name, quantity in materials
],
[110, 38, 30],
)
else:
text("Keine Materialverbrauchsdaten vorhanden.")
text(f"Materialverbrauch gesamt: {_number(report.materials.total_consumption_kg)} kg")
positive_materials = [
(number, name, quantity) for number, name, quantity in materials if quantity > 0
]
if len(positive_materials) >= (1 if include_single_material_chart else 2):
base_labels = [
name or number or "Materialzuordnung fehlt"
for number, name, _ in positive_materials
]
labels = tuple(
f"{label} ({number or 'ohne Materialnummer'})"
if base_labels.count(label) > 1
else label
for label, (number, _, _) in zip(base_labels, positive_materials)
)
story.append(
MaterialPieBlock(labels, tuple(quantity for _, _, quantity in positive_materials))
)
text("Liniengeschwindigkeit", "Heading2")
if report.speed is None:
text("Für diese Maschine nicht verfügbar.")
else:
speed = report.speed.average_line_speed_m_min
text(
"Durchschnittliche Liniengeschwindigkeit im Lauf: "
+ (f"{_number(speed)} m/min" if speed is not None
else "Nicht verfügbar (keine Laufdaten).")
)
return tuple(story)
def render_pdf(report: ShiftReport) -> bytes:
"""Repeatable bytes with the same ReportLab version and invariant metadata."""
from reportlab.graphics.charts.piecharts import Pie
from reportlab.graphics.shapes import Drawing, Rect
from reportlab.lib import colors
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import mm
from reportlab.pdfgen.canvas import Canvas
from reportlab.platypus import Paragraph, SimpleDocTemplate, Spacer, Table, TableStyle
styles = getSampleStyleSheet()
styles["Normal"].fontSize = 9
styles["Normal"].leading = 12
def paragraph(value: str, style: str = "Normal") -> Paragraph:
return Paragraph(escape(value).replace("\n", "<br/>"), styles[style])
story = []
for block in present_report(report):
if isinstance(block, TextBlock):
story.extend([paragraph(block.text, block.style), Spacer(1, 3 * mm)])
elif isinstance(block, MaterialPieBlock):
palette = tuple(
colors.HexColor(value)
for value in ("#496a81", "#8aa399", "#c4ad7a", "#9a869f", "#8399b0", "#b78e7c")
)
drawing = Drawing(65 * mm, 60 * mm)
pie = Pie()
pie.x, pie.y = 5 * mm, 2 * mm
pie.width = pie.height = 55 * mm
pie.data = list(block.consumption_kg)
pie.labels = []
pie.slices.strokeColor = colors.white
pie.slices.strokeWidth = 0.5
legend_rows = []
for index, label in enumerate(block.labels):
color = palette[index % len(palette)]
pie.slices[index].fillColor = color
swatch = Drawing(4 * mm, 4 * mm)
swatch.add(Rect(0, 0, 4 * mm, 4 * mm, fillColor=color, strokeColor=None))
legend_rows.append([swatch, paragraph(label)])
drawing.add(pie)
legend = Table(legend_rows, colWidths=[8 * mm, 101 * mm])
legend.setStyle(TableStyle([("VALIGN", (0, 0), (-1, -1), "TOP")]))
chart = Table([[drawing, legend]], colWidths=[65 * mm, 113 * mm], splitInRow=1)
chart.setStyle(
TableStyle(
[
("VALIGN", (0, 0), (-1, -1), "TOP"),
("LEFTPADDING", (0, 0), (-1, -1), 0),
("RIGHTPADDING", (0, 0), (-1, -1), 0),
]
)
)
story.extend([chart, Spacer(1, 4 * mm)])
else:
cells = [[paragraph(value) for value in row] for row in [block.headers, *block.rows]]
result = Table(cells, colWidths=[width * mm for width in block.widths_mm], repeatRows=1)
result.setStyle(
TableStyle(
[
("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#e8eef3")),
("VALIGN", (0, 0), (-1, -1), "TOP"),
("LINEBELOW", (0, 0), (-1, -1), 0.3, colors.HexColor("#c9d1d8")),
("TOPPADDING", (0, 0), (-1, -1), 6),
("BOTTOMPADDING", (0, 0), (-1, -1), 6),
]
)
)
story.extend([result, Spacer(1, 4 * mm)])
buffer = BytesIO()
document = SimpleDocTemplate(
buffer,
pagesize=A4,
leftMargin=16 * mm,
rightMargin=16 * mm,
topMargin=16 * mm,
bottomMargin=16 * mm,
title="Schichtbericht",
author="Production Analytics",
pageCompression=0,
)
def canvas(*args, **kwargs):
kwargs["invariant"] = 1
return Canvas(*args, **kwargs)
def footer(canvas, document):
canvas.saveState()
canvas.setFont("Helvetica", 8)
canvas.drawRightString(A4[0] - 16 * mm, 10 * mm, f"Seite {document.page}")
canvas.restoreState()
document.build(story, canvasmaker=canvas, onFirstPage=footer, onLaterPages=footer)
return buffer.getvalue()
def write_pdf(report: ShiftReport, output: Path) -> None:
payload = render_pdf(report)
output.parent.mkdir(parents=True, exist_ok=True)
output.write_bytes(payload)
@@ -0,0 +1,130 @@
"""HTML formatting of the shared report presentation; no data-source access."""
from html import escape
from math import fsum
from production_analytics.presentation.shift_report import (
MaterialPieBlock,
TableBlock,
TextBlock,
_number,
present_report,
)
def _material_chart(block: MaterialPieBlock) -> str:
"""Draw supplied material slices; percentages are presentation geometry only.
No scripts or external assets: source labels are escaped HTML/SVG text.
The adjacent shared material table remains the textual source of truth.
"""
palette = ("#496a81", "#8aa399", "#c4ad7a", "#9a869f", "#8399b0", "#b78e7c")
total = fsum(block.consumption_kg)
slices, legend = [], []
offset = 0.0
for index, (label, kg) in enumerate(zip(block.labels, block.consumption_kg)):
percent = kg / total * 100
color = palette[index % len(palette)]
description = f"{label}: {_number(kg)} kg ({_number(percent)} %)"
slices.append(
f'<circle cx="60" cy="60" r="44" pathLength="100" fill="none" '
f'stroke="{color}" stroke-width="22" '
f'stroke-dasharray="{percent:.8f} {100 - percent:.8f}" '
f'stroke-dashoffset="{-offset:.8f}" transform="rotate(-90 60 60)">'
f"<title>{escape(description)}</title></circle>"
)
legend.append(
f'<li><span class="material-swatch" style="background:{color}" '
f'aria-hidden="true"></span><span>{escape(description)}</span></li>'
)
offset += percent
return (
'<figure class="material-chart"><figcaption>Verbrauchsanteile nach Material</figcaption>'
'<svg viewBox="0 0 120 120" role="img" aria-label="Materialverbrauch in kg">'
"<title>Verbrauchsanteile nach Material; Werte in der Legende</title>"
+ "".join(slices)
+ '</svg><ul class="material-legend">'
+ "".join(legend)
+ '</ul><p class="metadata">Anteile der positiven Verbrauchsmengen.</p></figure>'
)
def render_page(*, machines, labels, day, shift, machine, report, generated_at, error,
sites=None):
machine_labels = ((key, getattr(config, "display_name", key))
for key, config in machines.items())
def options(values, selected):
return "".join(
f'<option value="{escape(key, quote=True)}"'
+ (" selected" if key == selected else "")
+ f">{escape(label)}</option>"
for key, label in values
)
body = ""
if error:
body = f'<p class="error" role="alert">{escape(error)}</p>'
if report is not None:
body += (
f'<p class="metadata">Datenstand: {generated_at:%d.%m.%Y %H:%M:%S %Z} '
f"({report.timezone.key}). Quellen können nachträglich korrigiert werden.</p>"
)
material_open = False
details_open = False
for block in present_report(report, include_single_material_chart=True):
if isinstance(block, TextBlock):
if material_open and block.style == "Heading2":
body += ("</div>" if details_open else "") + "</div></section>"
material_open = details_open = False
if block.text == "Materialverbrauch" and block.style == "Heading2":
body += (
'<section class="material-section"><h2>Materialverbrauch</h2>'
'<div class="material-layout"><div class="material-details">'
)
material_open = details_open = True
continue
tag = {"Title": "h1", "Heading2": "h2", "Heading3": "h3"}.get(block.style, "p")
body += f"<{tag}>{escape(block.text)}</{tag}>"
elif isinstance(block, TableBlock):
body += '<div class="table-scroll"><table><thead><tr>'
body += "".join(f'<th scope="col">{escape(cell)}</th>' for cell in block.headers)
body += "</tr></thead><tbody>"
for row in block.rows:
body += "<tr>" + "".join(f"<td>{escape(cell)}</td>" for cell in row) + "</tr>"
body += "</tbody></table></div>"
elif isinstance(block, MaterialPieBlock):
body += "</div>" + _material_chart(block)
details_open = False
if material_open:
body += ("</div>" if details_open else "") + "</div></section>"
return f'''<!doctype html>
<html lang="de"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Live-Schichtberichte</title><style>
body {{font: 16px system-ui,sans-serif; background:#f4f6f8; color:#182c3b; margin:0}}
main {{max-width:1100px; margin:2rem auto; padding:1.5rem; background:white}}
form {{display:flex; flex-wrap:wrap; gap:1rem; align-items:end; padding:1rem;
background:#e8eef3}} label {{display:grid; gap:.4rem}}
input,select,button {{font:inherit; padding:.55rem}} button {{cursor:pointer}}
table {{width:100%; border-collapse:collapse}} th,td {{text-align:left; padding:.7rem;
border-bottom:1px solid #c9d1d8}} th {{background:#e8eef3}}
.table-scroll {{overflow-x:auto}} .metadata {{color:#526473; font-size:.9rem}}
.material-layout {{display:grid; grid-template-columns:minmax(0, 1fr) 300px; gap:1.5rem}}
.material-chart {{margin:0; min-width:0}} .material-chart svg {{display:block;
width:220px; max-width:100%; margin:.75rem auto}}
.material-chart figcaption {{font-weight:600}} .material-legend {{list-style:none; padding:0}}
.material-legend li {{display:flex; gap:.5rem; margin:.6rem 0; overflow-wrap:anywhere}}
.material-swatch {{width:.9rem; height:.9rem; flex-shrink:0; margin-top:.2rem}}
@media(max-width:850px) {{.material-layout {{grid-template-columns:minmax(0, 1fr)}}}}
.error {{padding:1rem; background:#ffe8e5; border-left:4px solid #a32920}}
</style></head><body><main><h1>Live-Schichtberichte</h1>
<form method="get" action="/">
<label>Datum (Schichtbeginn)<input type="date" name="date" required
value="{day.isoformat()}"></label>
<label>Schicht<select name="shift">{options(labels.items(), shift)}</select></label>
<label>Maschine<select name="machine">{options(machine_labels, machine)}
</select></label>
<button type="submit">Bericht anzeigen</button>
<button type="submit" name="format" value="pdf">Als PDF exportieren</button>
</form><p class="metadata">Nachtschicht: 22:00 Uhr am gewählten Datum bis 06:00 Uhr
am Folgetag. Jeder Aufruf liest die aktuellen Quelldaten.</p>{body}</main></body></html>'''