feat: add report_export widget and enhance report generation capabilities
Deploy Development / deploy (push) Successful in 1m4s
Build Test / pytest-backend (push) Successful in 5s
Build Test / lint-backend (push) Successful in 1s
Build Test / build-frontend (push) Successful in 19s

- Introduced the `report_export` widget to the dashboard, allowing users to generate structured PDF reports.
- Updated widget configuration to include `report_export` in the allowed widgets and added validation for its configuration.
- Enhanced the widget catalog with details for the new `report_export` entry.
- Implemented API endpoints for managing report profiles and generating PDFs.
- Added frontend components for configuring and displaying report settings.
- Updated tests to ensure proper validation and functionality of the new report generation features.
- Bumped application version to reflect the addition of the new widget and related functionalities.
This commit is contained in:
Lars committed 2026-04-29 11:28:04 +02:00
1 parent 141df021c1
commit 62729d0648
22 files changed
+1389 -7

No files matched your search

@@ -0,0 +1,107 @@
import { useState } from 'react'
import dayjs from 'dayjs'
import { FileDown } from 'lucide-react'
import { useAuth } from '../../context/AuthContext'
import { useProfile } from '../../context/ProfileContext'
import { exportDashboardToPdf } from '../../utils/dashboardPdfExport'
/**
* @param {{ reportExportConfig: { document_title: string, subtitle: string, capture_scale: number } }} props
*/
export default function ReportExportWidget({ reportExportConfig }) {
const { canExport } = useAuth()
const { activeProfile } = useProfile()
const [busy, setBusy] = useState(false)
const [err, setErr] = useState(null)
const profileName = activeProfile?.name?.trim() || 'Profil'
const title =
reportExportConfig.document_title || `${profileName} – Übersicht`
const subtitle =
reportExportConfig.subtitle ||
`Erstellt am ${dayjs().format('DD.MM.YYYY HH:mm')} · Mitai Jinkendo`
const runExport = async () => {
setErr(null)
setBusy(true)
try {
const slug = (reportExportConfig.document_title || profileName).replace(/\s+/g, '-').slice(0, 80)
await exportDashboardToPdf({
scale: reportExportConfig.capture_scale,
filenameBase: `bericht-${slug}-${dayjs().format('YYYY-MM-DD')}`,
})
} catch (e) {
setErr(e?.message || 'PDF-Export fehlgeschlagen.')
} finally {
setBusy(false)
}
}
return (
<div className="card" style={{ marginBottom: 16 }}>
<div
className="card-title"
style={{ display: 'flex', alignItems: 'center', gap: 8 }}
data-dashboard-pdf-exclude="true"
>
<FileDown size={18} color="var(--accent)" aria-hidden />
Übersicht als Bild-PDF
</div>
<div style={{ marginTop: 12 }}>
<h2
style={{
fontSize: 17,
fontWeight: 650,
margin: '0 0 6px',
color: 'var(--text1)',
lineHeight: 1.35,
}}
>
{title}
</h2>
<p style={{ margin: 0, fontSize: 13, color: 'var(--text2)', lineHeight: 1.5 }}>{subtitle}</p>
</div>
<div data-dashboard-pdf-exclude="true">
<p style={{ fontSize: 12, color: 'var(--text3)', marginTop: 14, lineHeight: 1.55 }}>
<strong>Layout-Schnappschuss:</strong> Die sichtbare Übersicht wird im Browser gerastert (html2canvas).
Für einen <strong>datenbasierten Bericht</strong> unabhängig vom Dashboard nutze{' '}
<strong>Einstellungen → PDF-Bericht (strukturiert)</strong>.
</p>
<div style={{ marginTop: 14 }}>
{!canExport ? (
<p style={{ fontSize: 13, color: '#D85A30', margin: 0 }}>
PDF-Export ist für dieses Profil nicht freigeschaltet.
</p>
) : (
<>
{err && (
<p style={{ fontSize: 13, color: '#D85A30', margin: '0 0 10px' }} role="alert">
{err}
</p>
)}
<button
type="button"
className="btn btn-primary"
disabled={busy}
onClick={runExport}
style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}
>
{busy ? (
<>
<span className="spinner" style={{ width: 18, height: 18 }} aria-hidden />
PDF wird erzeugt…
</>
) : (
<>
<FileDown size={18} />
PDF-Schnappschuss herunterladen
</>
)}
</button>
</>
)}
</div>
</div>
</div>
)
}
+3 -1
View File
@@ -123,7 +123,9 @@ export default function Dashboard() {
)}
{!layoutLoading && layoutForPreview && (
<WidgetRenderer layout={layoutForPreview} refreshTick={refreshTick} requestRefresh={requestRefresh} />
<div id="dashboard-pdf-capture-root">
<WidgetRenderer layout={layoutForPreview} refreshTick={refreshTick} requestRefresh={requestRefresh} />
</div>
)}
</div>
)
@@ -16,6 +16,7 @@ import NutritionHistoryVizConfigEditor from '../widgetSystem/NutritionHistoryViz
import FitnessHistoryVizConfigEditor from '../widgetSystem/FitnessHistoryVizConfigEditor'
import RecoveryHistoryVizConfigEditor from '../widgetSystem/RecoveryHistoryVizConfigEditor'
import HistoryOverviewVizConfigEditor from '../widgetSystem/HistoryOverviewVizConfigEditor'
import ReportExportConfigEditor from '../widgetSystem/ReportExportConfigEditor'
import {
moveWidget,
moveWidgetToIndex,
@@ -590,6 +591,19 @@ export default function DashboardConfigurePage({ adminMode = false } = {}) {
}
/>
)}
{w.id === 'report_export' && (
<ReportExportConfigEditor
config={w.config || {}}
onChange={(next) =>
setLayout((L) =>
normalizeLayoutForEditor({
...L,
widgets: L.widgets.map((x, j) => (j !== i ? x : { ...x, config: { ...next } })),
})
)
}
/>
)}
</li>
)
})}
+320 -1
View File
@@ -1,5 +1,5 @@
import { useState, useEffect } from 'react'
import { Save, Download, Upload, Check, LogOut, Key, BarChart3, Target, LayoutDashboard } from 'lucide-react'
import { Save, Download, Upload, Check, LogOut, Key, BarChart3, Target, LayoutDashboard, FileText, Trash2 } from 'lucide-react'
import { Link } from 'react-router-dom'
import { useProfile } from '../context/ProfileContext'
import { useAuth } from '../context/AuthContext'
@@ -23,6 +23,11 @@ export default function SettingsPage() {
const [newPin, setNewPin] = useState('')
const [pinMsg, setPinMsg] = useState(null)
const [exportUsage, setExportUsage] = useState(null) // Phase 3: Usage badge
const [reportCatalog, setReportCatalog] = useState(null)
const [reportDraft, setReportDraft] = useState(null)
const [reportStored, setReportStored] = useState(false)
const [reportBusy, setReportBusy] = useState(false)
const [reportNote, setReportNote] = useState(null)
// Load feature usage for export badges
useEffect(() => {
@@ -32,6 +37,84 @@ export default function SettingsPage() {
}).catch(err => console.error('Failed to load usage:', err))
}, [])
useEffect(() => {
if (!activeProfile?.id) return
let cancel = false
Promise.all([api.getReportsCatalog(), api.getReportProfile()])
.then(([cat, bundle]) => {
if (cancel) return
setReportCatalog(cat)
setReportDraft(JSON.parse(JSON.stringify(bundle.profile)))
setReportStored(!!bundle.stored)
setReportNote(null)
})
.catch((e) => console.error('report profile load', e))
return () => {
cancel = true
}
}, [activeProfile?.id])
const reportNewBlock = (kind) => {
const charts = reportCatalog?.charts || []
const first = charts[0]
if (kind === 'section') return { type: 'section', title: 'Neue Überschrift' }
if (kind === 'chart')
return {
type: 'chart',
chart_id: first?.id || 'weight_trend',
window_days: first?.default_window_days || 28,
}
return { type: 'ai_insight', title: '', insight_id: null }
}
const handleSaveReportProfile = async () => {
if (!reportDraft) return
if (!reportDraft.blocks?.length) {
setReportNote({ type: 'err', text: 'Mindestens ein Block erforderlich.' })
return
}
setReportBusy(true)
setReportNote(null)
try {
await api.putReportProfile(reportDraft)
setReportStored(true)
setReportNote({ type: 'ok', text: 'Berichtsprofil gespeichert.' })
} catch (e) {
setReportNote({ type: 'err', text: e.message })
} finally {
setReportBusy(false)
}
}
const handleResetReportProfile = async () => {
if (!confirm('Persönliches Berichtsprofil löschen und Standard wiederherstellen?')) return
setReportBusy(true)
setReportNote(null)
try {
const bundle = await api.resetReportProfile()
setReportDraft(bundle.profile)
setReportStored(false)
setReportNote({ type: 'ok', text: 'Standard wiederhergestellt.' })
} catch (e) {
setReportNote({ type: 'err', text: e.message })
} finally {
setReportBusy(false)
}
}
const handleGenerateStructuredPdf = async () => {
setReportBusy(true)
setReportNote(null)
try {
await api.generateStructuredReportPdf()
setReportNote({ type: 'ok', text: 'PDF wurde heruntergeladen.' })
} catch (e) {
setReportNote({ type: 'err', text: e.message })
} finally {
setReportBusy(false)
}
}
const handleLogout = async () => {
if (!confirm('Ausloggen?')) return
await logout()
@@ -496,6 +579,242 @@ export default function SettingsPage() {
<FeatureUsageOverview />
</div>
{/* Strukturierter PDF-Bericht (Profil v1) */}
<div className="card section-gap">
<div className="card-title" style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<FileText size={18} color="var(--accent)" />
PDF-Bericht (strukturiert)
</div>
<p style={{ fontSize: 13, color: 'var(--text2)', marginBottom: 12, lineHeight: 1.65 }}>
<strong>Eigenes Berichtsprofil:</strong> Reihenfolge, Überschriften und Diagramme — unabhängig von der
Startübersicht. Die PDF-Datei wird <strong>serverseitig</strong> aus denselben Datenquellen wie die
Chart-API erzeugt (kein Screenshot). Das unterscheidet sich vom optionalen Widget „Übersicht als
Bild-PDF“ auf der Startseite.
</p>
{!canExport && (
<div
style={{
padding: '10px 12px',
background: '#FCEBEB',
borderRadius: 8,
fontSize: 13,
color: '#D85A30',
marginBottom: 12,
}}
>
🔒 PDF-Bericht nutzt dasselbe Kontingent wie Datenexporte. Bitte Admin kontaktieren.
</div>
)}
{reportNote && (
<div
style={{
padding: '10px 12px',
borderRadius: 8,
fontSize: 13,
marginBottom: 12,
background: reportNote.type === 'ok' ? '#E1F5EE' : '#FCEBEB',
color: reportNote.type === 'ok' ? 'var(--accent)' : '#D85A30',
}}
>
{reportNote.text}
</div>
)}
{canExport && reportDraft && reportCatalog && (
<>
<label className="form-label" style={{ fontSize: 12, display: 'block', marginBottom: 4 }}>
Dokumenttitel (optional)
</label>
<input
type="text"
className="form-input"
maxLength={120}
placeholder="Leer = Profilname + Bericht"
value={reportDraft.document_title || ''}
onChange={(e) => setReportDraft((d) => ({ ...d, document_title: e.target.value }))}
style={{ marginBottom: 14 }}
/>
<div style={{ fontSize: 12, fontWeight: 600, color: 'var(--text2)', marginBottom: 8 }}>
Blöcke {reportStored ? '' : '(Standard — noch nicht separat gespeichert)'}
</div>
<ul style={{ listStyle: 'none', padding: 0, margin: '0 0 12px' }}>
{reportDraft.blocks?.map((b, idx) => (
<li
key={idx}
style={{
border: '1px solid var(--border)',
borderRadius: 10,
padding: 12,
marginBottom: 10,
background: 'var(--surface2)',
}}
>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 8 }}>
<span style={{ fontSize: 11, color: 'var(--text3)', textTransform: 'uppercase' }}>{b.type}</span>
<button
type="button"
className="btn btn-secondary"
style={{ padding: '4px 8px' }}
aria-label="Block entfernen"
onClick={() =>
setReportDraft((d) => ({
...d,
blocks: d.blocks.filter((_, j) => j !== idx),
}))
}
>
<Trash2 size={16} />
</button>
</div>
{b.type === 'section' && (
<input
type="text"
className="form-input"
style={{ marginTop: 8 }}
value={b.title || ''}
onChange={(e) =>
setReportDraft((d) => {
const blocks = d.blocks.map((x, j) =>
j === idx ? { ...x, title: e.target.value } : x
)
return { ...d, blocks }
})
}
/>
)}
{b.type === 'chart' && (
<div style={{ marginTop: 8, display: 'flex', flexDirection: 'column', gap: 8 }}>
<select
className="form-input"
value={b.chart_id}
onChange={(e) =>
setReportDraft((d) => {
const blocks = d.blocks.map((x, j) =>
j === idx ? { ...x, chart_id: e.target.value } : x
)
return { ...d, blocks }
})
}
>
{reportCatalog.charts?.map((c) => (
<option key={c.id} value={c.id}>
{c.title}
</option>
))}
</select>
<div>
<label style={{ fontSize: 11, color: 'var(--text3)' }}>Zeitraum (Tage)</label>
<input
type="number"
className="form-input"
min={7}
max={365}
value={b.window_days}
onChange={(e) =>
setReportDraft((d) => {
const n = Number(e.target.value)
const blocks = d.blocks.map((x, j) =>
j === idx ? { ...x, window_days: Number.isFinite(n) ? n : x.window_days } : x
)
return { ...d, blocks }
})
}
/>
</div>
</div>
)}
{b.type === 'ai_insight' && (
<div style={{ marginTop: 8, display: 'flex', flexDirection: 'column', gap: 8 }}>
<input
type="text"
className="form-input"
placeholder="Optional: Überschrift"
value={b.title || ''}
onChange={(e) =>
setReportDraft((d) => {
const blocks = d.blocks.map((x, j) =>
j === idx ? { ...x, title: e.target.value } : x
)
return { ...d, blocks }
})
}
/>
<input
type="text"
className="form-input"
placeholder="Optional: Insight-UUID (aus KI-Verlauf)"
value={b.insight_id || ''}
onChange={(e) =>
setReportDraft((d) => {
const v = e.target.value.trim() || null
const blocks = d.blocks.map((x, j) =>
j === idx ? { ...x, insight_id: v } : x
)
return { ...d, blocks }
})
}
/>
</div>
)}
</li>
))}
</ul>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 12 }}>
<select
className="form-input"
style={{ maxWidth: 220 }}
defaultValue=""
onChange={(e) => {
const v = e.target.value
if (!v) return
setReportDraft((d) => ({ ...d, blocks: [...(d.blocks || []), reportNewBlock(v)] }))
e.target.value = ''
}}
>
<option value="">+ Block hinzufügen…</option>
<option value="section">Überschrift</option>
<option value="chart">Diagramm</option>
<option value="ai_insight">KI-Auswertung</option>
</select>
</div>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
<button
type="button"
className="btn btn-primary"
disabled={reportBusy}
onClick={handleSaveReportProfile}
style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}
>
<Save size={16} />
Bericht speichern
</button>
<button
type="button"
className="btn btn-secondary"
disabled={reportBusy}
onClick={handleResetReportProfile}
>
Standard wiederherstellen
</button>
<button
type="button"
className="btn btn-secondary"
disabled={reportBusy}
onClick={handleGenerateStructuredPdf}
style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}
>
<Download size={16} />
PDF erzeugen
</button>
</div>
{exportUsage && (
<div style={{ marginTop: 10 }}>
<UsageBadge {...exportUsage} />
</div>
)}
</>
)}
</div>
{/* Export */}
<div className="card section-gap">
<div className="card-title">Daten exportieren</div>
+32
View File
@@ -266,6 +266,38 @@ export const api = {
window.URL.revokeObjectURL(url)
},
// Strukturierter PDF-Bericht (Profil v1, unabhängig vom Dashboard)
getReportsCatalog: () => req('/reports/catalog'),
getReportProfile: () => req('/reports/profile'),
putReportProfile: (profile) => req('/reports/profile', jput(profile)),
resetReportProfile: () => req('/reports/profile', { method: 'DELETE' }),
generateStructuredReportPdf: async () => {
const res = await fetch(`${BASE}/reports/generate-pdf`, { method: 'POST', headers: hdrs() })
if (!res.ok) {
let msg = `HTTP ${res.status}`
try {
const d = await res.json()
msg = formatFastApiDetail(d.detail, msg)
} catch {
const t = await res.text()
if (t) msg = t
}
throw new Error(msg)
}
const cd = res.headers.get('Content-Disposition') || ''
const m = /filename="([^"]+)"/.exec(cd)
const filename = m ? m[1] : `mitai-bericht-${new Date().toISOString().split('T')[0]}.pdf`
const blob = await res.blob()
const url = window.URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = filename
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
window.URL.revokeObjectURL(url)
},
// Admin
adminListProfiles: () => req('/admin/profiles'),
adminCreateProfile: (d) => req('/admin/profiles',json(d)),
+69
View File
@@ -0,0 +1,69 @@
export const DASHBOARD_PDF_CAPTURE_ROOT_ID = 'dashboard-pdf-capture-root'
/**
* @param {{ scale?: number, filenameBase?: string }} [opts]
*/
export async function exportDashboardToPdf(opts = {}) {
const scale = opts.scale ?? 2
const filenameBase = opts.filenameBase ?? 'mitai-uebersicht'
const [{ default: html2canvas }, { jsPDF }] = await Promise.all([
import('html2canvas'),
import('jspdf'),
])
const el = document.getElementById(DASHBOARD_PDF_CAPTURE_ROOT_ID)
if (!el) throw new Error('Dashboard-Inhalt nicht gefunden (interner Fehler).')
const prevScroll = window.scrollY
window.scrollTo(0, 0)
await new Promise((r) => requestAnimationFrame(r))
await new Promise((r) => requestAnimationFrame(r))
await new Promise((r) => setTimeout(r, 320))
try {
const canvas = await html2canvas(el, {
scale,
useCORS: true,
allowTaint: true,
logging: false,
backgroundColor: '#ffffff',
ignoreElements: (node) => node?.getAttribute?.('data-dashboard-pdf-exclude') === 'true',
scrollX: 0,
scrollY: 0,
width: el.scrollWidth,
height: el.scrollHeight,
windowWidth: el.scrollWidth,
windowHeight: el.scrollHeight,
})
const imgData = canvas.toDataURL('image/png', 1.0)
const pdf = new jsPDF({ orientation: 'p', unit: 'mm', format: 'a4', compress: true })
const pageW = pdf.internal.pageSize.getWidth()
const pageH = pdf.internal.pageSize.getHeight()
const margin = 8
const innerW = pageW - 2 * margin
const innerH = pageH - 2 * margin
const imgW = innerW
const imgH = (canvas.height * imgW) / canvas.width
let position = margin
pdf.addImage(imgData, 'PNG', margin, position, imgW, imgH, undefined, 'FAST')
let heightLeft = imgH - innerH
while (heightLeft > 0) {
position = margin - (imgH - heightLeft)
pdf.addPage()
pdf.addImage(imgData, 'PNG', margin, position, imgW, imgH, undefined, 'FAST')
heightLeft -= innerH
}
const safe = String(filenameBase)
.replace(/[\\/:*?"<>|]+/g, '')
.trim()
pdf.save(`${safe || 'bericht'}.pdf`)
} finally {
window.scrollTo(0, prevScroll)
}
}
@@ -0,0 +1,66 @@
import { normalizeReportExportConfig } from './reportExportConfig'
function buildStoredConfig(n) {
const out = {}
if (n.document_title) out.document_title = n.document_title
if (n.subtitle) out.subtitle = n.subtitle
if (n.capture_scale !== 2) out.capture_scale = n.capture_scale
return out
}
/**
* @param {{
* config: Record<string, unknown>,
* onChange: (next: Record<string, unknown>) => void
* }} props
*/
export default function ReportExportConfigEditor({ config, onChange }) {
const n = normalizeReportExportConfig(config)
const push = (partial) => {
const merged = normalizeReportExportConfig({ ...(config || {}), ...partial })
onChange(buildStoredConfig(merged))
}
return (
<div style={{ marginTop: 12, marginLeft: 28, maxWidth: 440 }}>
<label style={{ fontSize: 12, color: 'var(--text2)', display: 'block', marginBottom: 4 }}>
Dokumenttitel (optional, max. 120 Zeichen)
</label>
<input
type="text"
className="form-input"
maxLength={120}
placeholder="Leer = Profilname + „Übersicht“"
value={n.document_title}
onChange={(e) => push({ document_title: e.target.value })}
/>
<label
style={{ fontSize: 12, color: 'var(--text2)', display: 'block', marginTop: 10, marginBottom: 4 }}
>
Untertitel (optional, max. 240 Zeichen)
</label>
<input
type="text"
className="form-input"
maxLength={240}
placeholder="Leer = Datum/Uhrzeit"
value={n.subtitle}
onChange={(e) => push({ subtitle: e.target.value })}
/>
<label style={{ fontSize: 12, color: 'var(--text2)', display: 'block', marginTop: 10, marginBottom: 4 }}>
PDF-Auflösung (1 = schneller/kleiner, 3 = schärfere Grafiken)
</label>
<select
className="form-input"
style={{ maxWidth: 120 }}
value={String(n.capture_scale)}
onChange={(e) => push({ capture_scale: Number(e.target.value) })}
>
<option value="1">1×</option>
<option value="2">2× (Standard)</option>
<option value="3">3×</option>
</select>
</div>
)
}
@@ -29,7 +29,9 @@ import ProgressPhotosWidget from '../components/dashboard-widgets/ProgressPhotos
import RecoverySleepRestWidget from '../components/dashboard-widgets/RecoverySleepRestWidget'
import GoalsFocusTeaserWidget from '../components/dashboard-widgets/GoalsFocusTeaserWidget'
import AiPipelineInsightWidget from '../components/dashboard-widgets/AiPipelineInsightWidget'
import ReportExportWidget from '../components/dashboard-widgets/ReportExportWidget'
import { normalizeBodyChartDays } from './bodyChartDays'
import { normalizeReportExportConfig } from './reportExportConfig'
import { registerDashboardWidget } from './dashboardWidgetRegistry'
let _registered = false
@@ -190,6 +192,13 @@ export function ensureDashboardWidgetsRegistered() {
Component: AiPipelineInsightWidget,
mapProps: (ctx) => ({ refreshTick: ctx.refreshTick }),
})
registerDashboardWidget({
id: 'report_export',
Component: ReportExportWidget,
mapProps: (ctx) => ({
reportExportConfig: normalizeReportExportConfig(ctx.layoutEntry?.config),
}),
})
}
/** @internal Nur für Tests */
@@ -0,0 +1,15 @@
/**
* @param {Record<string, unknown> | null | undefined} raw
* @returns {{ document_title: string, subtitle: string, capture_scale: number }}
*/
export function normalizeReportExportConfig(raw) {
const c = raw && typeof raw === 'object' ? raw : {}
let capture_scale = 2
if (c.capture_scale != null && c.capture_scale !== '') {
const n = Number(c.capture_scale)
if (Number.isFinite(n)) capture_scale = Math.min(3, Math.max(1, Math.round(n)))
}
const dt = typeof c.document_title === 'string' ? c.document_title.trim().slice(0, 120) : ''
const st = typeof c.subtitle === 'string' ? c.subtitle.trim().slice(0, 240) : ''
return { document_title: dt, subtitle: st, capture_scale }
}