20260703_tagging von Zeilen und Verbindung

This commit is contained in:
Lars committed 2026-07-03 11:56:22 +02:00
1 parent f57db9d161
commit f47353dbe1
25 files changed
+869 -143

No files matched your search

+6
View File
@@ -44,3 +44,9 @@ export const RATING_NUM_MAP: Record<FeedbackRating, number> = {
nearly_client_ready: 3,
client_ready: 4,
}
/** Default-Zeitgewichtung für den Bewertungs-Vorschlag, überschreibbar über Config > Gewichtung. */
export const DEFAULT_RATING_TREND_WEIGHT_STEP = 0.5
/** Mindest-Punktedelta zwischen erstem und letztem bewerteten Meeting einer Kategorie, ab dem ein Trend gilt. */
export const RATING_TREND_DELTA_THRESHOLD = 0.5
+27
View File
@@ -9,6 +9,7 @@ import type {
FeedbackDimension, FeedbackCategory, FeedbackCriterionItem,
AssignmentFeedback, FeedbackCategoryRating, FeedbackDimensionText,
CriterionCategoryMapping, CriterionLevelDescription,
AppSettings,
} from './types'
class AssignmentMonitorDB extends Dexie {
@@ -32,6 +33,7 @@ class AssignmentMonitorDB extends Dexie {
feedbackDimensionTexts!: Table<FeedbackDimensionText>
criterionCategoryMappings!: Table<CriterionCategoryMapping>
criterionLevelDescriptions!: Table<CriterionLevelDescription>
appSettings!: Table<AppSettings>
constructor() {
super('AssignmentMonitorDB')
@@ -129,6 +131,31 @@ class AssignmentMonitorDB extends Dexie {
meetings: null,
consultantNotes: null,
})
this.version(6).stores({
categories: '++id, order',
criteria: '++id, categoryId, order',
assignmentTypes: '++id',
phaseTemplates: '++id, assignmentTypeId, order',
groups: '++id',
consultants: '++id, groupId',
assignments: '++id, status, createdAt',
meetingInstances: '++id, assignmentId, phaseTemplateId',
conversationEntries: '++id, meetingInstanceId, instituteeId, sequenceIndex',
conversationSkillScores: '++id, conversationEntryId, criteriaId',
assessments: '++id, meetingInstanceId, instituteeId, criteriaId',
feedbackDrafts: '++id, assignmentId, instituteeId',
feedbackDimensions: '++id, order',
feedbackCategories: '++id, dimensionId, order',
feedbackCriterionItems: '++id, categoryId, order',
assignmentFeedbacks: '++id, assignmentId, instituteeId',
feedbackCategoryRatings: '++id, assignmentFeedbackId, feedbackCategoryId',
feedbackDimensionTexts: '++id, assignmentFeedbackId, feedbackDimensionId',
criterionCategoryMappings: '++id, criterionId, feedbackCategoryId',
criterionLevelDescriptions: '++id, criterionItemId, rating',
appSettings: '++id',
meetings: null,
consultantNotes: null,
})
}
}
+13
View File
@@ -98,6 +98,11 @@ export interface MeetingInstance {
// ─── Gesprächs-Zeitleiste ─────────────────────────────────────────────────────
export interface ConversationLineTag {
text: string
criterionItemId: number // → FeedbackCriterionItem.id
}
export interface ConversationEntry {
id?: number
meetingInstanceId: number
@@ -106,6 +111,7 @@ export interface ConversationEntry {
note: string
fillerCount: number
updatedAt: string
lineTags?: ConversationLineTag[] // Kriterium-Zuordnung pro Zeile, gematcht per exaktem Zeilentext
}
// criteriaId → FeedbackCategory.id (Schnellbewertung während Gesprächsbeitrag)
@@ -200,3 +206,10 @@ export interface CriterionLevelDescription {
rating: FeedbackRating
text: string
}
// ─── App-Einstellungen (Singleton, id immer 1) ───────────────────────────────
export interface AppSettings {
id?: number
ratingTrendWeightStep: number // 0 = keine Zeitgewichtung, höher = stärkere Gewichtung späterer Meetings
}
+7 -2
View File
@@ -12,6 +12,7 @@ export default function AssignmentCreate() {
title: '',
client: '',
leadName: '',
assignmentNumber: '',
assignmentTypeId: 0,
selectedGroupId: 0,
instituteeIds: [] as number[],
@@ -66,11 +67,12 @@ export default function AssignmentCreate() {
}
const create = async () => {
if (!form.title.trim() || !form.client.trim() || !form.assignmentTypeId || form.instituteeIds.length === 0) return
if (!form.title.trim() || !form.client.trim() || !form.assignmentNumber.trim() || !form.assignmentTypeId || form.instituteeIds.length === 0) return
const id = await db.assignments.add({
title: form.title,
client: form.client,
leadName: form.leadName,
assignmentNumber: form.assignmentNumber.trim(),
assignmentTypeId: form.assignmentTypeId,
instituteeIds: form.instituteeIds,
status: 'active',
@@ -79,7 +81,7 @@ export default function AssignmentCreate() {
navigate(`/assignment/${id}`)
}
const canCreate = form.title.trim() && form.client.trim() && form.assignmentTypeId && form.instituteeIds.length > 0
const canCreate = form.title.trim() && form.client.trim() && form.assignmentNumber.trim() && form.assignmentTypeId && form.instituteeIds.length > 0
const selectedInstitutees = consultants.filter(c => form.instituteeIds.includes(c.id!))
return (
@@ -88,6 +90,9 @@ export default function AssignmentCreate() {
{/* Basisdaten */}
<div className="bg-white rounded-xl shadow-sm border border-gray-100 p-4 space-y-3">
<input className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-brand"
placeholder="Assignment-Nummer (Pflichtfeld)" value={form.assignmentNumber}
onChange={e => setForm(p => ({ ...p, assignmentNumber: e.target.value }))} />
<input className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-brand"
placeholder="Titel des Assignments" value={form.title}
onChange={e => setForm(p => ({ ...p, title: e.target.value }))} />
+110 -14
View File
@@ -12,7 +12,9 @@ import {
type FeedbackDimensionText,
type FeedbackRating,
} from '../db'
import { RATING_OPTIONS, RATING_NUM_MAP, AI_CONFIG } from '../config/constants'
import { RATING_OPTIONS, RATING_NUM_MAP, AI_CONFIG, DEFAULT_RATING_TREND_WEIGHT_STEP } from '../config/constants'
import { buildGroupMeetingScores, computeTrend, numberToRating, type TrendResult } from '../utils/ratingTrend'
import { splitNoteLines } from '../utils/notationParser'
const ratingToNum = (r: FeedbackRating | null | undefined): number =>
r ? (RATING_NUM_MAP[r] ?? 0) : 0
@@ -20,6 +22,12 @@ const ratingToNum = (r: FeedbackRating | null | undefined): number =>
const ratingColor = (r: FeedbackRating | undefined) =>
RATING_OPTIONS.find(x => x.value === r)?.color ?? 'bg-gray-50 text-gray-400 border-gray-200'
const trendArrow = (trend: TrendResult['trend']) => {
if (trend === 'up') return <span title="Verbesserung über die Laufzeit">↑</span>
if (trend === 'down') return <span title="Verschlechterung über die Laufzeit">↓</span>
return null
}
function getAiSettings() {
return {
apiKey: localStorage.getItem(AI_CONFIG.localStorageKeyApiKey) ?? '',
@@ -39,9 +47,9 @@ async function buildAiPrompt(
assignment: Assignment,
dimensions: FeedbackDimension[],
categories: FeedbackCategory[],
_items: FeedbackCriterionItem[],
items: FeedbackCriterionItem[],
ratings: FeedbackCategoryRating[],
_feedbackId: number,
catTrends: Map<number, TrendResult>,
): Promise<string> {
const meetings = await db.meetingInstances.where('assignmentId').equals(assignment.id!).toArray()
const meetingIds = meetings.map(m => m.id!)
@@ -54,24 +62,33 @@ async function buildAiPrompt(
const instAssessments = allAssessments.filter(a => a.instituteeId === institutee.id)
const instEntries = allEntries.filter(e => e.instituteeId === institutee.id)
const critIds = [...new Set(instAssessments.map(a => a.criteriaId))]
const crits = critIds.length > 0
? await db.criteria.where('id').anyOf(critIds).toArray()
: []
const allLineTags = instEntries.flatMap(e => e.lineTags ?? [])
const critIds = [...new Set([
...instAssessments.map(a => a.criteriaId),
...allLineTags.map(t => t.criterionItemId),
])]
const crits = items.filter(i => critIds.includes(i.id!))
const scoreLines = crits.map(c => {
const scores = instAssessments.filter(a => a.criteriaId === c.id && a.score !== null)
const avg = scores.length > 0
? (scores.reduce((s, a) => s + ratingToNum(a.score), 0) / scores.length).toFixed(1)
: '—'
const notes = instAssessments.filter(a => a.criteriaId === c.id && a.note).map(a => a.note)
const notes = [
...instAssessments.filter(a => a.criteriaId === c.id && a.note).map(a => a.note),
...allLineTags.filter(t => t.criterionItemId === c.id).map(t => t.text),
]
return ` ${c.name}: ${avg}/5${notes.length > 0 ? ` | Notizen: ${notes.join('; ')}` : ''}`
}).join('\n')
const fillerTotal = instEntries.reduce((s, e) => s + (e.fillerCount ?? 0), 0)
const protocolLines = instEntries
.filter(e => e.note)
.map(e => ` - ${e.note}${(e.fillerCount ?? 0) > 0 ? ` [äh×${e.fillerCount}]` : ''}`)
.flatMap(e => splitNoteLines(e.note).map(line => ({
line, tagged: (e.lineTags ?? []).some(t => t.text === line),
})))
.filter(x => !x.tagged)
.map(x => ` - ${x.line}`)
.join('\n')
// Kategorie-Ratings
@@ -85,6 +102,22 @@ async function buildAiPrompt(
return ` Dimension "${dim.name}":\n${lines}`
}).join('\n')
// Entwicklung über die Laufzeit (zeitgewichteter Trend pro Kategorie)
const trendLines = dimensions.map(dim => {
const dimCats = categories.filter(c => c.dimensionId === dim.id)
const lines = dimCats.map(cat => {
const t = catTrends.get(cat.id!)
if (!t || t.history.length === 0) return ` ${cat.name}: keine Verlaufsdaten`
const seq = t.history.map(h => h.score.toFixed(1)).join(' → ')
const trendLabel = t.trend === 'up' ? 'Verbesserung über die Laufzeit'
: t.trend === 'down' ? 'Verschlechterung über die Laufzeit'
: t.trend === 'stable' ? 'stabil'
: 'nur ein Meeting, kein Trend ableitbar'
return ` ${cat.name}: Verlauf ${seq} (${trendLabel})`
}).join('\n')
return ` Dimension "${dim.name}":\n${lines}`
}).join('\n')
// Feedback-Struktur für Output
const dimStructure = dimensions.map((dim, i) =>
`${i + 1}. ${dim.name}`
@@ -100,13 +133,16 @@ FÜLLWÖRTER GESAMT: ${fillerTotal}
BEOBACHTETE KRITERIEN UND SCORES (1-5):
${scoreLines || '(keine Scores erfasst)'}
PROTOKOLL-NOTIZEN (Kurznotizen aus dem Gespräch, Notation: + gut, ! negativ, > Kundeninput):
${protocolLines || '(keine Protokolleinträge)'}
PROTOKOLL-NOTIZEN, KEINEM KRITERIUM ZUGEORDNET (Notation: + gut, ! negativ, > Kundeninput):
${protocolLines || '(keine nicht zugeordneten Protokolleinträge)'}
KATEGORIE-BEWERTUNGEN:
${ratingLines}
Generiere für jede der folgenden ${dimensions.length} Dimensionen je einen kurzen Absatz "Achievements" (2-4 Sätze, konkret, anerkennend) und "Development Needs" (2-4 Sätze, konstruktiv, handlungsorientiert). Falls eine Dimension aus den Daten nicht beurteilbar ist, schreibe "n/a".
ENTWICKLUNG ÜBER DIE LAUFZEIT (chronologische Kategorie-Scores aus den Meetings, Skala 0-4):
${trendLines}
Generiere für jede der folgenden ${dimensions.length} Dimensionen je einen kurzen Absatz "Achievements" (2-4 Sätze, konkret, anerkennend) und "Development Needs" (2-4 Sätze, konstruktiv, handlungsorientiert). Falls eine Dimension aus den Daten nicht beurteilbar ist, schreibe "n/a". Erwähne eine erkennbare Verbesserung im Achievements-Absatz und eine erkennbare Verschlechterung im Development-Needs-Absatz der jeweiligen Dimension.
Ausgabe als JSON:
{
@@ -142,6 +178,7 @@ export default function AssignmentFeedbackPage() {
const [ratings, setRatings] = useState<FeedbackCategoryRating[]>([])
const [dimTexts, setDimTexts] = useState<FeedbackDimensionText[]>([])
const [expanded, setExpanded] = useState<Set<number>>(new Set())
const [catTrends, setCatTrends] = useState<Map<number, TrendResult>>(new Map())
const [showAiSettings, setShowAiSettings] = useState(false)
const [aiKey, setAiKey] = useState(getAiSettings().apiKey)
const [aiModel, setAiModel] = useState(getAiSettings().model)
@@ -163,6 +200,27 @@ export default function AssignmentFeedbackPage() {
setCategories(cats)
setItems(itms)
const meetings = (await db.meetingInstances.where('assignmentId').equals(assignmentId).toArray())
.filter(m => !m.deletedAt && m.status === 'done')
.sort((x, y) => new Date(x.date).getTime() - new Date(y.date).getTime())
const meetingIds = meetings.map(m => m.id!)
const [meetingAssessments, settings] = await Promise.all([
meetingIds.length > 0 ? db.assessments.where('meetingInstanceId').anyOf(meetingIds).toArray() : Promise.resolve([]),
db.appSettings.get(1),
])
const weightStep = settings?.ratingTrendWeightStep ?? DEFAULT_RATING_TREND_WEIGHT_STEP
const instAssessments = meetingAssessments.filter(as => as.instituteeId === instId)
const getScore = (meetingId: number, itemId: number): FeedbackRating | null =>
instAssessments.find(as => as.meetingInstanceId === meetingId && as.criteriaId === itemId)?.score ?? null
const trends = new Map<number, TrendResult>()
for (const cat of cats) {
const catItems = itms.filter(i => i.categoryId === cat.id)
const history = buildGroupMeetingScores(catItems, meetings, getScore)
trends.set(cat.id!, computeTrend(history, weightStep))
}
setCatTrends(trends)
let fb = await db.assignmentFeedbacks
.where('assignmentId').equals(assignmentId)
.filter(f => f.instituteeId === instId)
@@ -243,6 +301,17 @@ export default function AssignmentFeedbackPage() {
const getDimText = (dimId: number) =>
dimTexts.find(t => t.feedbackDimensionId === dimId)
const appendTrendSentence = (dimId: number, cat: FeedbackCategory, trend: TrendResult) => {
if (trend.trend !== 'up' && trend.trend !== 'down') return
const field = trend.trend === 'up' ? 'achievements' : 'developmentNeeds'
const firstLabel = RATING_OPTIONS.find(o => o.value === numberToRating(trend.history[0].score))?.short
const lastLabel = RATING_OPTIONS.find(o => o.value === numberToRating(trend.history[trend.history.length - 1].score))?.short
const verb = trend.trend === 'up' ? 'Verbesserung' : 'Verschlechterung'
const sentence = `Zeigt im Verlauf des Assignments in ${cat.name} eine ${verb} von ${firstLabel} zu ${lastLabel}.`
const existing = getDimText(dimId)?.[field] ?? ''
saveDimText(dimId, field, existing ? `${existing}\n${sentence}` : sentence)
}
// ── KI-Generierung ────────────────────────────────────────────────────────
const generateWithAi = async () => {
@@ -253,7 +322,7 @@ export default function AssignmentFeedbackPage() {
setGenerating(true)
setAiError('')
try {
const prompt = await buildAiPrompt(institutee, assignment, dimensions, categories, items, ratings, feedback.id)
const prompt = await buildAiPrompt(institutee, assignment, dimensions, categories, items, ratings, catTrends)
const res = await fetch('https://openrouter.ai/api/v1/chat/completions', {
method: 'POST',
@@ -462,6 +531,33 @@ export default function AssignmentFeedbackPage() {
))}
</div>
{/* Bewertungs-Vorschlag aus Meeting-Assessments */}
{(() => {
const trend = catTrends.get(cat.id!)
if (!trend || trend.suggestion === null) return null
const suggestedRating = numberToRating(trend.suggestion)
const shortLabel = RATING_OPTIONS.find(o => o.value === suggestedRating)?.short
return (
<div className="flex items-center gap-2 flex-wrap">
<span className="text-xs bg-blue-50 text-blue-700 border border-blue-200 px-2 py-1 rounded-lg font-medium">
Vorschlag: {shortLabel} ({trend.suggestion.toFixed(1)}) {trendArrow(trend.trend)}
</span>
<button
onClick={() => setRating(cat.id!, suggestedRating)}
className="text-xs bg-blue-100 text-blue-700 px-2 py-1 rounded-lg font-medium hover:bg-blue-200">
Übernehmen
</button>
{(trend.trend === 'up' || trend.trend === 'down') && (
<button
onClick={() => appendTrendSentence(dim.id!, cat, trend)}
className="text-xs bg-gray-100 text-gray-600 px-2 py-1 rounded-lg font-medium hover:bg-gray-200">
Trend in Text übernehmen
</button>
)}
</div>
)
})()}
{/* Kriterium-Items als Referenz */}
{catItems.length > 0 && (
<div className="flex flex-wrap gap-1">
+9 -3
View File
@@ -1,10 +1,11 @@
import { useRef, useState } from 'react'
import FeedbackStructureConfig from './FeedbackStructureConfig'
import AssignmentTypeConfig from './AssignmentTypeConfig'
import RatingWeightConfig from './RatingWeightConfig'
import { exportFullBackup, importFullBackup } from '../utils/dbBackup'
export default function Configuration() {
const [tab, setTab] = useState<'feedback' | 'types' | 'backup'>('feedback')
const [tab, setTab] = useState<'feedback' | 'types' | 'weighting' | 'backup'>('feedback')
const [backupStatus, setBackupStatus] = useState<{ type: 'success' | 'error'; msg: string } | null>(null)
const [restoreConfirm, setRestoreConfirm] = useState(false)
const [importing, setImporting] = useState(false)
@@ -48,6 +49,10 @@ export default function Configuration() {
className={`flex-1 py-2 rounded-lg text-sm font-medium transition ${tab === 'types' ? 'bg-white text-brand shadow-sm' : 'text-gray-500'}`}>
Ass.-Typen
</button>
<button onClick={() => setTab('weighting')}
className={`flex-1 py-2 rounded-lg text-sm font-medium transition ${tab === 'weighting' ? 'bg-white text-brand shadow-sm' : 'text-gray-500'}`}>
Gewichtung
</button>
<button onClick={() => setTab('backup')}
className={`flex-1 py-2 rounded-lg text-sm font-medium transition ${tab === 'backup' ? 'bg-white text-brand shadow-sm' : 'text-gray-500'}`}>
Backup
@@ -63,8 +68,9 @@ export default function Configuration() {
</div>
)}
{tab === 'feedback' && <FeedbackStructureConfig />}
{tab === 'types' && <AssignmentTypeConfig />}
{tab === 'feedback' && <FeedbackStructureConfig />}
{tab === 'types' && <AssignmentTypeConfig />}
{tab === 'weighting' && <RatingWeightConfig />}
{tab === 'backup' && (
<div className="space-y-4">
+39 -43
View File
@@ -3,33 +3,24 @@ import { useNavigate } from 'react-router-dom'
import {
db,
type Assignment, type Consultant,
type FeedbackDimension, type FeedbackCategory, type FeedbackCriterionItem,
type FeedbackDimension, type FeedbackCategory,
type FeedbackRating,
} from '../db'
import { RATING_OPTIONS, RATING_NUM_MAP } from '../config/constants'
import { RATING_OPTIONS, DEFAULT_RATING_TREND_WEIGHT_STEP } from '../config/constants'
import { buildGroupMeetingScores, computeTrend, type TrendResult } from '../utils/ratingTrend'
interface CatScore {
category: FeedbackCategory
avg: number | null
category: FeedbackCategory
avg: number | null
trend: TrendResult['trend']
}
interface InstScore {
institutee: Consultant
assignment: Assignment
catScores: CatScore[]
overall: number | null
}
function weightedAvg(
items: FeedbackCriterionItem[],
getScore: (itemId: number) => FeedbackRating | null,
): number | null {
const rated = items
.map(i => ({ score: getScore(i.id!), w: i.weight ?? 1 }))
.filter((x): x is { score: FeedbackRating; w: number } => x.score !== null && x.score !== 'na')
if (rated.length === 0) return null
const wSum = rated.reduce((s, x) => s + x.w, 0)
return rated.reduce((s, x) => s + RATING_NUM_MAP[x.score] * x.w, 0) / wSum
institutee: Consultant
assignment: Assignment
catScores: CatScore[]
overall: number | null
overallTrend: TrendResult['trend']
}
function ratingColor(avg: number | null): string {
@@ -51,6 +42,12 @@ function ratingLabel(avg: number | null): string {
return r ? `${r.short} (${avg.toFixed(1)})` : avg.toFixed(1)
}
function trendArrow(trend: TrendResult['trend']) {
if (trend === 'up') return <span className="text-green-600" title="Verbesserung über die Laufzeit">↑</span>
if (trend === 'down') return <span className="text-red-600" title="Verschlechterung über die Laufzeit">↓</span>
return null
}
export default function Evaluation() {
const [data, setData] = useState<InstScore[]>([])
const [dimensions, setDimensions] = useState<FeedbackDimension[]>([])
@@ -60,22 +57,26 @@ export default function Evaluation() {
useEffect(() => {
const load = async () => {
const [assignments, consultants, dims, cats, items, assessments] = await Promise.all([
const [assignments, consultants, dims, cats, items, assessments, settings] = await Promise.all([
db.assignments.toArray(),
db.consultants.toArray(),
db.feedbackDimensions.orderBy('order').toArray(),
db.feedbackCategories.orderBy('order').toArray(),
db.feedbackCriterionItems.orderBy('order').toArray(),
db.assessments.toArray(),
db.appSettings.get(1),
])
setDimensions(dims)
setCategories(cats)
const weightStep = settings?.ratingTrendWeightStep ?? DEFAULT_RATING_TREND_WEIGHT_STEP
const rows: InstScore[] = []
for (const a of assignments) {
const meetingIds = (await db.meetingInstances
const meetings = (await db.meetingInstances
.where('assignmentId').equals(a.id!).toArray()
).filter(m => !m.deletedAt && m.status === 'done').map(m => m.id!)
).filter(m => !m.deletedAt && m.status === 'done')
.sort((x, y) => new Date(x.date).getTime() - new Date(y.date).getTime())
const meetingIds = meetings.map(m => m.id!)
for (const instId of a.instituteeIds) {
const inst = consultants.find(c => c.id === instId)
@@ -86,25 +87,20 @@ export default function Evaluation() {
)
if (instAssessments.length === 0) continue
const getScore = (itemId: number): FeedbackRating | null => {
const relevant = instAssessments.filter(a => a.criteriaId === itemId && a.score !== null && a.score !== 'na')
if (relevant.length === 0) return null
const avg = relevant.reduce((s, a) => s + RATING_NUM_MAP[a.score!], 0) / relevant.length
if (avg < 1.5) return 'not_client_ready'
if (avg < 2.5) return 'partially_client_ready'
if (avg < 3.5) return 'nearly_client_ready'
return 'client_ready'
}
const getScore = (meetingId: number, itemId: number): FeedbackRating | null =>
instAssessments.find(as => as.meetingInstanceId === meetingId && as.criteriaId === itemId)?.score ?? null
const catScores: CatScore[] = cats.map(cat => ({
category: cat,
avg: weightedAvg(items.filter(i => i.categoryId === cat.id), getScore),
}))
const catScores: CatScore[] = cats.map(cat => {
const history = buildGroupMeetingScores(items.filter(i => i.categoryId === cat.id), meetings, getScore)
const { suggestion, trend } = computeTrend(history, weightStep)
return { category: cat, avg: suggestion, trend }
})
const overall = weightedAvg(items, getScore)
const overallHistory = buildGroupMeetingScores(items, meetings, getScore)
const { suggestion: overall, trend: overallTrend } = computeTrend(overallHistory, weightStep)
if (overall === null && catScores.every(c => c.avg === null)) continue
rows.push({ institutee: inst, assignment: a, catScores, overall })
rows.push({ institutee: inst, assignment: a, catScores, overall, overallTrend })
}
}
setData(rows)
@@ -150,8 +146,8 @@ export default function Evaluation() {
{row.institutee.firstName} {row.institutee.lastName}
</div>
<div className="flex items-center gap-2">
<div className={`px-3 py-1 rounded-full text-sm font-bold ${ratingColor(row.overall)}`}>
{ratingLabel(row.overall)}
<div className={`px-3 py-1 rounded-full text-sm font-bold flex items-center gap-1 ${ratingColor(row.overall)}`}>
{ratingLabel(row.overall)} {trendArrow(row.overallTrend)}
</div>
<button
onClick={e => { e.stopPropagation(); navigate(`/assignment/${row.assignment.id}/feedback/${row.institutee.id}`) }}
@@ -174,12 +170,12 @@ export default function Evaluation() {
<div className="text-xs font-semibold uppercase text-gray-400 tracking-wide mb-2">
{dim.name}
</div>
{dimScores.map(({ category, avg }) => (
{dimScores.map(({ category, avg, trend }) => (
<div key={category.id}
className="flex items-center justify-between py-1.5 border-b border-gray-50 last:border-0">
<span className="text-sm text-gray-700">{category.name}</span>
<span className={`text-xs font-semibold px-2 py-0.5 rounded ${ratingColor(avg)}`}>
{ratingLabel(avg)}
<span className={`text-xs font-semibold px-2 py-0.5 rounded flex items-center gap-1 ${ratingColor(avg)}`}>
{ratingLabel(avg)} {trendArrow(trend)}
</span>
</div>
))}
+4 -4
View File
@@ -271,13 +271,13 @@ export default function FeedbackStructureConfig() {
value={item.name}
onChange={e => updateItem(item.id!, e.target.value)}
/>
<select
<input
type="number" min={0} max={2} step={0.1}
value={item.weight ?? 1}
onChange={e => updateItemWeight(item.id!, Number(e.target.value))}
title="Gewichtung"
className="text-xs border border-gray-200 rounded px-1 py-0.5 text-gray-500 bg-white focus:outline-none focus:border-brand">
{[1,2,3,4,5].map(w => <option key={w} value={w}>×{w}</option>)}
</select>
className="w-14 text-xs border border-gray-200 rounded px-1 py-0.5 text-gray-500 bg-white focus:outline-none focus:border-brand"
/>
<button onClick={() => deleteItem(item.id!)}
className="text-xs text-red-200 hover:text-red-400">×</button>
</div>
+79
View File
@@ -0,0 +1,79 @@
import { useEffect, useState } from 'react'
import { db } from '../db'
import { DEFAULT_RATING_TREND_WEIGHT_STEP } from '../config/constants'
import { previewWeights } from '../utils/ratingTrend'
export default function RatingWeightConfig() {
const [weightStep, setWeightStep] = useState(DEFAULT_RATING_TREND_WEIGHT_STEP)
const [saved, setSaved] = useState(false)
useEffect(() => {
const load = async () => {
let settings = await db.appSettings.get(1)
if (!settings) {
await db.appSettings.add({ id: 1, ratingTrendWeightStep: DEFAULT_RATING_TREND_WEIGHT_STEP })
settings = await db.appSettings.get(1)
}
setWeightStep(settings?.ratingTrendWeightStep ?? DEFAULT_RATING_TREND_WEIGHT_STEP)
}
load()
}, [])
const save = async () => {
await db.appSettings.put({ id: 1, ratingTrendWeightStep: weightStep })
setSaved(true)
setTimeout(() => setSaved(false), 2500)
}
return (
<div className="bg-white rounded-xl border border-gray-100 shadow-sm p-5 space-y-4">
<div>
<h2 className="font-semibold text-gray-800">Zeitgewichtung des Bewertungs-Vorschlags</h2>
<p className="text-sm text-gray-500 mt-1">
Steuert, wie stark spätere Meetings in den Bewertungs-Vorschlag auf der Auswertungs- und
Feedback-Seite einfließen. 0 = alle Meetings gleich gewichtet, höher = stärkere Gewichtung
späterer Bewertungen.
</p>
</div>
<div className="space-y-2">
<div className="flex items-center justify-between">
<label className="text-sm font-medium text-gray-700">Gewichtungsfaktor</label>
<span className="text-sm font-semibold text-brand">{weightStep.toFixed(1)}</span>
</div>
<input
type="range"
min={0}
max={2}
step={0.1}
value={weightStep}
onChange={e => setWeightStep(Number(e.target.value))}
className="w-full"
/>
</div>
<div className="bg-gray-50 rounded-lg border border-gray-100 p-3">
<div className="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1.5">
Beispiel bei 3 bewerteten Meetings
</div>
<div className="flex gap-2 text-sm text-gray-600">
{previewWeights(3, weightStep).map((w, i) => (
<span key={i} className="bg-white border border-gray-200 rounded px-2 py-1">
Meeting {i + 1}: ×{w.toFixed(1)}
</span>
))}
</div>
</div>
<button onClick={save}
className="w-full py-2.5 bg-brand text-white rounded-xl text-sm font-semibold">
Speichern
</button>
{saved && (
<div className="text-xs text-green-700 bg-green-50 border border-green-200 rounded-lg px-3 py-2 text-center">
Gespeichert.
</div>
)}
</div>
)
}
+44 -3
View File
@@ -1,15 +1,18 @@
import { useState } from 'react'
import type {
Consultant, FeedbackCategory, FeedbackCriterionItem,
Assessment, FeedbackRating,
Assessment, ConversationEntry, FeedbackRating,
} from '../../db'
import { INST_COLORS, RATING_OPTIONS, RATING_NUM_MAP } from '../../config/constants'
import { detectNotationRating } from '../../utils/notationParser'
import { numberToRating } from '../../utils/ratingTrend'
interface Props {
institutees: Consultant[]
fbCategories: FeedbackCategory[]
fbItems: FeedbackCriterionItem[]
assessments: Assessment[]
entries: ConversationEntry[]
hasConv: boolean
tagLabel: (inst: Consultant) => string
fillerTotal: (instId: number) => number
@@ -30,6 +33,7 @@ function catMode(
.filter((x): x is { score: FeedbackRating; w: number } => x.score !== null && x.score !== 'na')
if (scored.length === 0) return null
const wSum = scored.reduce((s, x) => s + x.w, 0)
if (wSum === 0) return null // alle beteiligten Kriterien auf Gewicht 0 → keine Aussage möglich, sonst NaN < x ist überall false und fällt auf "Fully" durch
const avg = scored.reduce((s, x) => s + RATING_NUM_MAP[x.score] * x.w, 0) / wSum
if (avg < 1.5) return 'not_client_ready'
if (avg < 2.5) return 'partially_client_ready'
@@ -37,8 +41,20 @@ function catMode(
return 'client_ready'
}
function suggestedRating(entries: ConversationEntry[], instituteeId: number, itemId: number): FeedbackRating | null {
const ratings = entries
.filter(e => e.instituteeId === instituteeId)
.flatMap(e => e.lineTags ?? [])
.filter(t => t.criterionItemId === itemId)
.map(t => detectNotationRating(t.text))
.filter((r): r is FeedbackRating => r !== null)
if (ratings.length === 0) return null
const avg = ratings.reduce((s, r) => s + RATING_NUM_MAP[r], 0) / ratings.length
return numberToRating(avg)
}
export function AssessmentTab({
institutees, fbCategories, fbItems, assessments, hasConv,
institutees, fbCategories, fbItems, assessments, entries, hasConv,
tagLabel, fillerTotal,
getAssessmentScore, onSetAssessmentScore, onSaveAssessmentNote, onAutoCalc,
}: Props) {
@@ -82,6 +98,11 @@ export function AssessmentTab({
const isOpen = expandedCat[inst.id!] === cat.id
const mode = catMode(cat, fbItems, itemId => getAssessmentScore(inst.id!, itemId))
const headerRo = mode ? RATING_OPTIONS.find(r => r.value === mode) : null
const suggestionCount = catItems.filter(item => {
const current = getAssessmentScore(inst.id!, item.id!)
const suggestion = suggestedRating(entries, inst.id!, item.id!)
return suggestion && suggestion !== current
}).length
return (
<div key={cat.id} className="rounded-xl overflow-hidden border border-gray-100">
@@ -95,6 +116,14 @@ export function AssessmentTab({
}`}>
<span className={`text-sm font-medium ${headerRo ? 'text-white' : 'text-gray-700'}`}>{cat.name}</span>
<div className="flex items-center gap-2">
{suggestionCount > 0 && (
<span title="Vorschläge aus dem Protokoll verfügbar"
className={`text-xs px-1.5 py-0.5 rounded-full font-semibold ${
headerRo ? 'bg-white/20 text-white' : 'bg-blue-100 text-blue-700'
}`}>
💡 {suggestionCount}
</span>
)}
{!headerRo && ratedCount > 0 && (
<span className="text-xs text-brand font-medium">{ratedCount}/{catItems.length}</span>
)}
@@ -105,7 +134,8 @@ export function AssessmentTab({
{isOpen && (
<div className="border-t border-gray-100 divide-y divide-gray-50">
{catItems.map(item => {
const current = getAssessmentScore(inst.id!, item.id!)
const current = getAssessmentScore(inst.id!, item.id!)
const suggestion = suggestedRating(entries, inst.id!, item.id!)
return (
<div key={item.id} className="px-3 py-2.5 space-y-1.5">
<div className="text-xs text-gray-600 font-medium">{item.name}</div>
@@ -120,6 +150,17 @@ export function AssessmentTab({
</button>
))}
</div>
{suggestion && suggestion !== current && (
<div className="flex items-center gap-2">
<span className="text-xs bg-blue-50 text-blue-700 border border-blue-200 px-2 py-0.5 rounded-lg font-medium">
Vorschlag aus Protokoll: {RATING_OPTIONS.find(r => r.value === suggestion)?.short}
</span>
<button onClick={() => onSetAssessmentScore(inst.id!, item.id!, suggestion)}
className="text-xs bg-blue-100 text-blue-700 px-2 py-0.5 rounded-lg font-medium hover:bg-blue-200">
Übernehmen
</button>
</div>
)}
</div>
)
})}
+29 -3
View File
@@ -5,6 +5,7 @@ import type {
} from '../../db'
import { NotationText } from '../../utils/notationParser'
import { INST_COLORS, RATING_OPTIONS } from '../../config/constants'
import { CriterionTagPicker } from './CriterionTagPicker'
const NOTATIONS = [
{ sym: '+', tip: 'Gut' },
@@ -37,6 +38,8 @@ interface Props {
onSaveEntryNote: () => void
onIncrementFiller: () => void
onSetEntryScore: (entryId: number, categoryId: number, score: FeedbackRating) => void
onSetLineCriterion: (entryId: number, lineText: string, criterionItemId: number | null) => void
onChangeSpeaker: (entryId: number, instituteeId: number) => void
onStartEdit: (entry: ConversationEntry) => void
onSaveEdit: (entryId: number) => void
onCancelEdit: () => void
@@ -50,7 +53,7 @@ export function ConversationTab({
activeInstId, activeEntryId, entryNote, editingId, editNote, noteRef,
displayName, tagLabel, fillerTotal, getEntryScore,
onActivateInstitutee, onCloseActiveEntry, onInsertNotation,
onEntryNoteChange, onSaveEntryNote, onIncrementFiller, onSetEntryScore,
onEntryNoteChange, onSaveEntryNote, onIncrementFiller, onSetEntryScore, onSetLineCriterion, onChangeSpeaker,
onStartEdit, onSaveEdit, onCancelEdit, onEditNoteChange, onDeleteEntry, onAdjustFiller,
}: Props) {
const activeInstIdx = institutees.findIndex(c => c.id === activeInstId)
@@ -206,6 +209,17 @@ export function ConversationTab({
onChange={e => onEditNoteChange(e.target.value)}
autoFocus
/>
<div className="flex items-center gap-2">
<span className="text-xs text-gray-500">Sprecher:</span>
<select
value={entry.instituteeId}
onChange={e => onChangeSpeaker(entry.id!, Number(e.target.value))}
className="text-xs border border-gray-200 rounded px-2 py-1 bg-white focus:outline-none focus:border-brand">
{institutees.map(c => (
<option key={c.id} value={c.id}>{displayName(c)}</option>
))}
</select>
</div>
<div className="flex items-center gap-3">
<span className="text-xs text-gray-500">Füllwörter:</span>
<button onClick={() => onAdjustFiller(entry, -1)}
@@ -223,8 +237,20 @@ export function ConversationTab({
</div>
) : (
<>
{entry.note && <NotationText text={entry.note} />}
<div className="flex gap-1 flex-wrap mt-1">
{entry.note && (
<NotationText
text={entry.note}
renderLineAddon={line => (
<CriterionTagPicker
items={fbItems}
categories={fbCategories}
value={(entry.lineTags ?? []).find(t => t.text === line)?.criterionItemId ?? null}
onChange={itemId => onSetLineCriterion(entry.id!, line, itemId)}
/>
)}
/>
)}
<div className="flex items-center gap-1 flex-wrap mt-1">
{(entry.fillerCount ?? 0) > 0 && (
<span className="text-xs bg-red-50 text-red-500 border border-red-200 px-1.5 py-0.5 rounded font-medium">
äh×{entry.fillerCount}
+74
View File
@@ -0,0 +1,74 @@
import { useState } from 'react'
import type { FeedbackCategory, FeedbackCriterionItem } from '../../db'
interface Props {
items: FeedbackCriterionItem[]
categories: FeedbackCategory[]
value: number | null | undefined
onChange: (itemId: number | null) => void
}
export function CriterionTagPicker({ items, categories, value, onChange }: Props) {
const [open, setOpen] = useState(false)
const [filter, setFilter] = useState('')
const current = items.find(i => i.id === value)
const categoryName = (categoryId: number) => categories.find(c => c.id === categoryId)?.name ?? ''
const filtered = items.filter(i => {
const q = filter.trim().toLowerCase()
if (!q) return true
return i.name.toLowerCase().includes(q) || categoryName(i.categoryId).toLowerCase().includes(q)
})
const select = (itemId: number) => {
onChange(itemId)
setOpen(false)
setFilter('')
}
return (
<div className="relative inline-block">
{current ? (
<div className="inline-flex items-center gap-0.5 bg-indigo-50 text-indigo-700 border border-indigo-200 rounded-full pl-2 pr-1 py-0.5">
<button onClick={() => setOpen(p => !p)} className="text-xs font-medium max-w-[120px] truncate">
🏷 {current.name}
</button>
<button onClick={() => onChange(null)} className="text-indigo-400 hover:text-indigo-700 text-xs leading-none px-1">✕</button>
</div>
) : (
<button onClick={() => setOpen(p => !p)}
title="Kriterium zuordnen"
className="w-6 h-6 rounded-full border border-dashed border-gray-300 text-gray-400 text-xs flex items-center justify-center hover:bg-gray-50 hover:text-gray-600">
+
</button>
)}
{open && (
<div className="absolute z-20 mt-1 w-64 bg-white border border-gray-200 rounded-xl shadow-lg p-2">
<input
type="text"
autoFocus
placeholder="Kriterium suchen…"
value={filter}
onChange={e => setFilter(e.target.value)}
className="w-full text-xs border border-gray-200 rounded-lg px-2 py-1.5 mb-2 focus:outline-none focus:border-brand"
/>
<div className="max-h-48 overflow-y-auto space-y-0.5">
{filtered.length === 0 && (
<div className="text-xs text-gray-400 px-2 py-1.5">Kein Treffer.</div>
)}
{filtered.map(item => (
<button key={item.id}
onClick={() => select(item.id!)}
className="w-full text-left px-2 py-1.5 rounded-lg hover:bg-gray-50">
<div className="text-xs font-medium text-gray-700">{item.name}</div>
<div className="text-[10px] text-gray-400">{categoryName(item.categoryId)}</div>
</button>
))}
</div>
</div>
)}
</div>
)
}
+34 -5
View File
@@ -7,7 +7,7 @@ import {
type Consultant, type ConversationEntry, type ConversationSkillScore, type Assessment,
} from '../../db'
import { exportMeetingAsMarkdown, exportMeetingAsJson, downloadFile } from '../../utils/meetingExport'
import { NotationText } from '../../utils/notationParser'
import { NotationText, splitNoteLines } from '../../utils/notationParser'
import { RATING_NUM_MAP } from '../../config/constants'
import { ConversationTab } from './ConversationTab'
import { AssessmentTab } from './AssessmentTab'
@@ -96,7 +96,11 @@ export default function MeetingView() {
const activateInstitutee = async (instId: number) => {
if (activeEntryId !== null) {
await db.conversationEntries.update(activeEntryId, { note: entryNote, updatedAt: new Date().toISOString() })
if (entryNote.trim() === '') {
await db.conversationEntries.delete(activeEntryId)
} else {
await db.conversationEntries.update(activeEntryId, { note: entryNote, updatedAt: new Date().toISOString() })
}
}
const maxSeq = entries.reduce((m, e) => Math.max(m, e.sequenceIndex), 0)
const eid = await db.conversationEntries.add({
@@ -135,7 +139,11 @@ export default function MeetingView() {
}
const closeActiveEntry = async () => {
await saveEntryNote()
if (activeEntryId !== null && entryNote.trim() === '') {
await db.conversationEntries.delete(activeEntryId)
} else {
await saveEntryNote()
}
setActiveInstId(null)
setActiveEntryId(null)
setEntryNote('')
@@ -145,11 +153,24 @@ export default function MeetingView() {
const startEdit = (entry: ConversationEntry) => { setEditingId(entry.id!); setEditNote(entry.note) }
const saveEdit = async (entryId: number) => {
await db.conversationEntries.update(entryId, { note: editNote, updatedAt: new Date().toISOString() })
setEntries(prev => prev.map(e => e.id === entryId ? { ...e, note: editNote } : e))
const entry = entries.find(e => e.id === entryId)
const currentLines = splitNoteLines(editNote)
const prunedTags = (entry?.lineTags ?? []).filter(t => currentLines.includes(t.text))
await db.conversationEntries.update(entryId, { note: editNote, lineTags: prunedTags, updatedAt: new Date().toISOString() })
setEntries(prev => prev.map(e => e.id === entryId ? { ...e, note: editNote, lineTags: prunedTags } : e))
setEditingId(null)
}
const setLineCriterion = async (entryId: number, lineText: string, criterionItemId: number | null) => {
const entry = entries.find(e => e.id === entryId)
if (!entry) return
const currentLines = splitNoteLines(entry.note)
const kept = (entry.lineTags ?? []).filter(t => t.text !== lineText && currentLines.includes(t.text))
const nextTags = criterionItemId === null ? kept : [...kept, { text: lineText, criterionItemId }]
await db.conversationEntries.update(entryId, { lineTags: nextTags })
setEntries(prev => prev.map(e => e.id === entryId ? { ...e, lineTags: nextTags } : e))
}
const deleteEntry = async (entryId: number) => {
await db.conversationSkillScores.where('conversationEntryId').equals(entryId).delete()
await db.conversationEntries.delete(entryId)
@@ -162,6 +183,11 @@ export default function MeetingView() {
setEntries(prev => prev.map(e => e.id === entry.id ? { ...e, fillerCount: newCount } : e))
}
const changeEntrySpeaker = async (entryId: number, instituteeId: number) => {
await db.conversationEntries.update(entryId, { instituteeId })
setEntries(prev => prev.map(e => e.id === entryId ? { ...e, instituteeId } : e))
}
const getEntryScore = (entryId: number, categoryId: number): FeedbackRating | null =>
scores.find(s => s.conversationEntryId === entryId && s.criteriaId === categoryId)?.score ?? null
@@ -393,6 +419,8 @@ export default function MeetingView() {
onSaveEntryNote={saveEntryNote}
onIncrementFiller={incrementFiller}
onSetEntryScore={setEntryScore}
onSetLineCriterion={setLineCriterion}
onChangeSpeaker={changeEntrySpeaker}
onStartEdit={startEdit}
onSaveEdit={saveEdit}
onCancelEdit={() => setEditingId(null)}
@@ -408,6 +436,7 @@ export default function MeetingView() {
fbCategories={fbCategories}
fbItems={fbItems}
assessments={assessments}
entries={entries}
hasConv={hasConv}
tagLabel={tagLabel}
fillerTotal={fillerTotal}
+3
View File
@@ -1,6 +1,8 @@
import { db } from '../db'
import { downloadFile } from './meetingExport'
// Muss mit den Tabellen in db/schema.ts synchron gehalten werden — eine neue Tabelle dort
// landet nicht automatisch im Backup, sondern muss hier manuell ergänzt werden.
const TABLE_NAMES = [
'categories',
'criteria',
@@ -22,6 +24,7 @@ const TABLE_NAMES = [
'feedbackDimensionTexts',
'criterionCategoryMappings',
'criterionLevelDescriptions',
'appSettings',
] as const
export interface DbBackup {
+5 -2
View File
@@ -23,10 +23,11 @@ export async function exportMeetingAsMarkdown(meetingId: number): Promise<string
...new Set([
...(template?.criteriaIds ?? []),
...assessments.map(a => a.criteriaId),
...entries.flatMap(e => (e.lineTags ?? []).map(t => t.criterionItemId)),
]),
]
const criteria = critIds.length > 0
? await db.criteria.where('id').anyOf(critIds).toArray()
? await db.feedbackCriterionItems.where('id').anyOf(critIds).toArray()
: []
const institutees = instituteeIds
@@ -63,7 +64,9 @@ export async function exportMeetingAsMarkdown(meetingId: number): Promise<string
if (entry.note?.trim()) {
for (const noteLine of entry.note.trim().split('\n')) {
lines.push(`> ${noteLine}`)
const lineTag = entry.lineTags?.find(t => t.text === noteLine.trim())
const critName = lineTag ? criteria.find(c => c.id === lineTag.criterionItemId)?.name : null
lines.push(`> ${noteLine}${critName ? ` _(→ ${critName})_` : ''}`)
}
}
+33 -2
View File
@@ -1,4 +1,22 @@
import React from 'react'
import type { FeedbackRating } from '../db'
// Notation → Bewertungsstufe (Reihenfolge wichtig: Klammer-Varianten vor den nackten Zeichen prüfen,
// sonst matcht "+" bereits innerhalb von "(+)")
const NOTATION_RATING_ORDER: [string, FeedbackRating][] = [
['(+)', 'nearly_client_ready'],
['(!)', 'partially_client_ready'],
['+', 'client_ready'],
['!', 'not_client_ready'],
]
export function detectNotationRating(line: string): FeedbackRating | null {
const trimmed = line.trim()
for (const [prefix, rating] of NOTATION_RATING_ORDER) {
if (trimmed.startsWith(prefix)) return rating
}
return null
}
// Notations-Regeln (Reihenfolge wichtig: längere Symbole zuerst)
const NOTATION_RULES = [
@@ -57,14 +75,27 @@ function parseLine(line: string, key: number): React.ReactElement {
interface Props {
text: string
className?: string
renderLineAddon?: (line: string, index: number) => React.ReactNode
}
export function NotationText({ text, className }: Props) {
export function NotationText({ text, className, renderLineAddon }: Props) {
if (!text?.trim()) return null
const lines = text.split('\n')
return (
<div className={className}>
{lines.map((line, i) => parseLine(line, i))}
{lines.map((line, i) => renderLineAddon
? (
<div key={i} className="flex items-start justify-between gap-2">
<div className="flex-1 min-w-0">{parseLine(line, i)}</div>
{line.trim() && renderLineAddon(line.trim(), i)}
</div>
)
: parseLine(line, i)
)}
</div>
)
}
export function splitNoteLines(note: string): string[] {
return note.split('\n').map(l => l.trim()).filter(l => l !== '')
}
+73
View File
@@ -0,0 +1,73 @@
import type { FeedbackCriterionItem, FeedbackRating } from '../db'
import { RATING_NUM_MAP, RATING_TREND_DELTA_THRESHOLD } from '../config/constants'
export interface MeetingScorePoint {
meetingId: number
date: string
score: number
}
export interface TrendResult {
suggestion: number | null
history: MeetingScorePoint[]
trend: 'up' | 'down' | 'stable' | null
delta: number | null
}
/**
* Ein Wert pro Meeting für eine Gruppe von Kriterien (eine Kategorie oder alle Items für "overall").
* Meetings ohne bewertetes Item aus der Gruppe werden übersprungen — ein Delivery-Call, der eine
* Kategorie nicht abfragt, darf deren Zeitreihe nicht verfälschen.
*/
export function buildGroupMeetingScores(
items: FeedbackCriterionItem[],
meetingsChronological: { id: number; date: string }[],
getScore: (meetingId: number, itemId: number) => FeedbackRating | null,
): MeetingScorePoint[] {
const points: MeetingScorePoint[] = []
for (const meeting of meetingsChronological) {
const rated = items
.map(i => ({ score: getScore(meeting.id, i.id!), w: i.weight ?? 1 }))
.filter((x): x is { score: FeedbackRating; w: number } => x.score !== null && x.score !== 'na')
if (rated.length === 0) continue
const wSum = rated.reduce((s, x) => s + x.w, 0)
if (wSum === 0) continue // alle beteiligten Kriterien auf Gewicht 0 → keine Aussage möglich, sonst NaN < x ist überall false und fällt auf "Fully" durch
const score = rated.reduce((s, x) => s + RATING_NUM_MAP[x.score] * x.w, 0) / wSum
points.push({ meetingId: meeting.id, date: meeting.date, score })
}
return points
}
/**
* Lineare Zeitgewichtung: rank r (1-basiert, 1 = ältester Datenpunkt) → weight = 1 + (r-1) * weightStep.
* Trend wird aus dem Delta zwischen erstem und letztem Rohwert abgeleitet (nicht dem gewichteten Wert),
* da das ohnehin nur ab 2 Datenpunkten sinnvoll ist und der gewichtete Wert selbst schon Teil des
* Vorschlags ist.
*/
export function computeTrend(history: MeetingScorePoint[], weightStep: number): TrendResult {
if (history.length === 0) return { suggestion: null, history, trend: null, delta: null }
const weights = previewWeights(history.length, weightStep)
const wSum = weights.reduce((s, w) => s + w, 0)
const suggestion = history.reduce((s, p, i) => s + p.score * weights[i], 0) / wSum
if (history.length < 2) return { suggestion, history, trend: null, delta: null }
const delta = history[history.length - 1].score - history[0].score
const trend = delta >= RATING_TREND_DELTA_THRESHOLD ? 'up'
: delta <= -RATING_TREND_DELTA_THRESHOLD ? 'down'
: 'stable'
return { suggestion, history, trend, delta }
}
export function numberToRating(avg: number): FeedbackRating {
if (avg < 1.5) return 'not_client_ready'
if (avg < 2.5) return 'partially_client_ready'
if (avg < 3.5) return 'nearly_client_ready'
return 'client_ready'
}
/** Resultierende Gewichte für k chronologische Datenpunkte, z.B. previewWeights(3, 0.5) => [1, 1.5, 2]. */
export function previewWeights(k: number, weightStep: number): number[] {
return Array.from({ length: k }, (_, i) => 1 + i * weightStep)
}