V2-Dev-Stand: Skala 1-10, Benefits/Concerns, DEV-Isolation und Gitea-Doku.
Bündelt die Neuentwicklung in AssigmentMonitorV2 (eigene Ports/DB), die Umstellung auf numerische Bewertungen, Meeting-Checklisten, KI-Tagging und die geplante Feedback-Kaskade — als Basis für Versionsverwaltung in Gitea. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
782678a1cf
commit
234f87d408
71 files changed
+7567
-705
No files matched your search
@@ -0,0 +1,85 @@
|
||||
import {
|
||||
DEFAULT_RATING_COLOR_BANDS,
|
||||
RATING_SCORES,
|
||||
normalizeRatingScore,
|
||||
resolveScoreStyle,
|
||||
} from '../config/constants'
|
||||
import type { RatingColorBand, RatingScore } from '../db/types'
|
||||
|
||||
interface ScorePickerProps {
|
||||
value: RatingScore | null
|
||||
onChange: (score: RatingScore | null) => void
|
||||
bands?: RatingColorBand[]
|
||||
/** 'buttons' = 1–10-Leiste, 'select' = kompaktes Dropdown */
|
||||
variant?: 'buttons' | 'select'
|
||||
className?: string
|
||||
/** Zeigt n/a / Leeren — setzt Score auf null. */
|
||||
allowClear?: boolean
|
||||
}
|
||||
|
||||
export function ScorePicker({
|
||||
value,
|
||||
onChange,
|
||||
bands = DEFAULT_RATING_COLOR_BANDS,
|
||||
variant = 'buttons',
|
||||
className = '',
|
||||
allowClear = true,
|
||||
}: ScorePickerProps) {
|
||||
const normalized = normalizeRatingScore(value)
|
||||
|
||||
if (variant === 'select') {
|
||||
const style = resolveScoreStyle(normalized, bands)
|
||||
return (
|
||||
<select
|
||||
value={normalized ?? ''}
|
||||
onChange={e => {
|
||||
const v = e.target.value
|
||||
onChange(v === '' ? null : Number(v) as RatingScore)
|
||||
}}
|
||||
className={`text-xs rounded-lg border px-1 py-1 focus:outline-none flex-shrink-0 tabular-nums ${
|
||||
normalized !== null ? style.active : style.color
|
||||
} ${className}`}
|
||||
>
|
||||
<option value="">{allowClear ? 'n/a' : '–'}</option>
|
||||
{RATING_SCORES.map(n => (
|
||||
<option key={n} value={n}>{n}</option>
|
||||
))}
|
||||
</select>
|
||||
)
|
||||
}
|
||||
|
||||
const clearStyle = resolveScoreStyle(null, bands)
|
||||
|
||||
return (
|
||||
<div className={`flex gap-0.5 ${className}`}>
|
||||
{allowClear && (
|
||||
<button
|
||||
type="button"
|
||||
title="Nicht bewertet / zurücksetzen"
|
||||
onClick={() => onChange(null)}
|
||||
className={`flex-shrink-0 px-1.5 py-1.5 rounded text-xs font-bold border transition ${
|
||||
normalized === null ? clearStyle.active : clearStyle.color
|
||||
}`}
|
||||
>
|
||||
n/a
|
||||
</button>
|
||||
)}
|
||||
{RATING_SCORES.map(n => {
|
||||
const style = resolveScoreStyle(n, bands)
|
||||
const selected = normalized === n
|
||||
return (
|
||||
<button
|
||||
key={n}
|
||||
type="button"
|
||||
onClick={() => onChange(n)}
|
||||
className={`flex-1 min-w-0 py-1.5 rounded text-xs font-bold border transition tabular-nums ${
|
||||
selected ? style.active : style.color
|
||||
}`}
|
||||
>
|
||||
{n}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
+181
-62
@@ -1,28 +1,101 @@
|
||||
import type { FeedbackRating } from '../db/types'
|
||||
import type { RatingBandKey, RatingColorBand, RatingScore } from '../db/types'
|
||||
|
||||
export const BRAND_COLOR = '#0070AD'
|
||||
|
||||
export const RATING_MIN = 1
|
||||
export const RATING_MAX = 10
|
||||
|
||||
/** Kanonische Scores 1–10 — einzige Quelle für Picker/Selects. */
|
||||
export const RATING_SCORES: readonly RatingScore[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
||||
|
||||
/**
|
||||
* Kanonische Reihenfolge der Rating-Skala (nicht ändern — DB-Werte sind stabil).
|
||||
* `color` = Badge/Display-State (inaktiv)
|
||||
* `active` = ausgewählter Button-State
|
||||
* Abwärtskompatible Options-Liste (short/label/full = Zahl als Text).
|
||||
* Farben kommen dynamisch über `resolveScoreStyle` / Farbbänder — `color`/`active` hier nur Fallback.
|
||||
*/
|
||||
export const RATING_OPTIONS: ReadonlyArray<{
|
||||
value: FeedbackRating
|
||||
value: RatingScore
|
||||
short: string
|
||||
label: string
|
||||
/** Ausgeschriebene Bezeichnung fürs KI-Prompting — "Not" allein ist für ein Modell nicht aussagekräftig, "Not Client Ready" transportiert das eigentliche Bewertungsziel des Trainee-Programms. */
|
||||
full: string
|
||||
color: string
|
||||
active: string
|
||||
}> = [
|
||||
{ value: 'na', short: 'N/A', label: 'N/A (0)', full: 'Not Applicable', color: 'bg-gray-100 text-gray-500 border-gray-300', active: 'bg-gray-400 text-white border-gray-400' },
|
||||
{ value: 'not_client_ready', short: 'Not', label: 'Not (1)', full: 'Not Client Ready', color: 'bg-red-100 text-red-700 border-red-300', active: 'bg-red-500 text-white border-red-500' },
|
||||
{ value: 'partially_client_ready', short: 'Partially', label: 'Partially (2)', full: 'Partially Client Ready', color: 'bg-orange-100 text-orange-700 border-orange-300', active: 'bg-orange-500 text-white border-orange-500' },
|
||||
{ value: 'nearly_client_ready', short: 'Nearly', label: 'Nearly (3)', full: 'Nearly Client Ready', color: 'bg-green-100 text-green-600 border-green-300', active: 'bg-green-400 text-white border-green-400' },
|
||||
{ value: 'client_ready', short: 'Fully', label: 'Fully (4)', full: 'Fully Client Ready', color: 'bg-green-100 text-green-800 border-green-400', active: 'bg-green-700 text-white border-green-700' },
|
||||
}> = RATING_SCORES.map(n => ({
|
||||
value: n,
|
||||
short: String(n),
|
||||
label: String(n),
|
||||
full: String(n),
|
||||
color: 'bg-gray-100 text-gray-600 border-gray-300',
|
||||
active: 'bg-brand text-white border-brand',
|
||||
}))
|
||||
|
||||
export const BAND_STYLES: Record<RatingBandKey, { color: string; active: string; hex: string }> = {
|
||||
red: { color: 'bg-red-100 text-red-700 border-red-300', active: 'bg-red-500 text-white border-red-500', hex: '#ef4444' },
|
||||
orange: { color: 'bg-orange-100 text-orange-700 border-orange-300', active: 'bg-orange-500 text-white border-orange-500', hex: '#f97316' },
|
||||
// Unselected: light lime vs saturated green — both used bg-green-100 before and looked identical.
|
||||
lightGreen: { color: 'bg-lime-50 text-lime-700 border-lime-300', active: 'bg-lime-400 text-white border-lime-400', hex: '#a3e635' },
|
||||
darkGreen: { color: 'bg-green-200 text-green-900 border-green-700', active: 'bg-green-700 text-white border-green-700', hex: '#15803d' },
|
||||
}
|
||||
|
||||
/** Default: 1–2 rot, 3–5 orange, 6–8 hellgrün, 9–10 dunkelgrün (siehe docs/SCALE_1_TO_10.md). */
|
||||
export const DEFAULT_RATING_COLOR_BANDS: RatingColorBand[] = [
|
||||
{ max: 2, key: 'red' },
|
||||
{ max: 5, key: 'orange' },
|
||||
{ max: 8, key: 'lightGreen' },
|
||||
{ max: 10, key: 'darkGreen' },
|
||||
]
|
||||
|
||||
export function isValidRatingScore(value: unknown): value is RatingScore {
|
||||
const n = typeof value === 'number' ? value : typeof value === 'string' && value.trim() !== '' ? Number(value) : NaN
|
||||
return Number.isInteger(n) && n >= RATING_MIN && n <= RATING_MAX
|
||||
}
|
||||
|
||||
/** Normalisiert DB-/UI-Werte auf 1–10 oder null (SQLite kann INTEGER-Spalten als String liefern). */
|
||||
export function normalizeRatingScore(value: unknown): RatingScore | null {
|
||||
if (value === null || value === undefined || value === '') return null
|
||||
const n = typeof value === 'number' ? value : Number(value)
|
||||
if (!Number.isInteger(n) || n < RATING_MIN || n > RATING_MAX) return null
|
||||
return n
|
||||
}
|
||||
|
||||
/** Rundet Mittelwerte auf 1–10; außerhalb / NaN → null. */
|
||||
export function clampRatingScore(avg: number): RatingScore | null {
|
||||
if (!Number.isFinite(avg)) return null
|
||||
const rounded = Math.round(avg)
|
||||
if (rounded < RATING_MIN || rounded > RATING_MAX) return null
|
||||
return rounded
|
||||
}
|
||||
|
||||
export function normalizeRatingColorBands(bands: RatingColorBand[] | null | undefined): RatingColorBand[] {
|
||||
if (!bands?.length) return DEFAULT_RATING_COLOR_BANDS.map(b => ({ ...b }))
|
||||
const sorted = [...bands].sort((a, b) => a.max - b.max)
|
||||
if (sorted[sorted.length - 1]?.max !== RATING_MAX) return DEFAULT_RATING_COLOR_BANDS.map(b => ({ ...b }))
|
||||
return sorted
|
||||
}
|
||||
|
||||
export function bandForScore(score: RatingScore, bands: RatingColorBand[] = DEFAULT_RATING_COLOR_BANDS): RatingColorBand {
|
||||
const normalized = normalizeRatingColorBands(bands)
|
||||
return normalized.find(b => score <= b.max) ?? normalized[normalized.length - 1]
|
||||
}
|
||||
|
||||
export function resolveScoreStyle(
|
||||
score: RatingScore | null | undefined,
|
||||
bands: RatingColorBand[] = DEFAULT_RATING_COLOR_BANDS,
|
||||
): { value: RatingScore | null; short: string; color: string; active: string; hex: string } {
|
||||
const normalized = normalizeRatingScore(score)
|
||||
if (normalized === null) {
|
||||
return {
|
||||
value: null,
|
||||
short: '–',
|
||||
color: 'bg-gray-100 text-gray-500 border-gray-300',
|
||||
active: 'bg-gray-400 text-white border-gray-400',
|
||||
hex: '#9ca3af',
|
||||
}
|
||||
}
|
||||
const band = bandForScore(normalized, bands)
|
||||
const style = BAND_STYLES[band.key]
|
||||
return { value: normalized, short: String(normalized), color: style.color, active: style.active, hex: style.hex }
|
||||
}
|
||||
|
||||
/** Farb-Schemata für Teilnehmer-Badges (Index = Reihenfolge im Assignment). */
|
||||
export const INST_COLORS = [
|
||||
{ bg: 'bg-blue-50', border: 'border-blue-300', tag: 'bg-blue-500', text: 'text-blue-700' },
|
||||
@@ -36,74 +109,120 @@ export const AI_CONFIG = {
|
||||
localStorageKeyModel: 'ai_model',
|
||||
defaultModel: 'openai/gpt-4o-mini',
|
||||
openRouterBaseUrl: 'https://openrouter.ai/api/v1',
|
||||
defaultDimensionPromptTemplate: `Du bist Führungskraft und Mentor bei Capgemini. Erstelle einen professionellen, konstruktiven Beitrag zum Performance-Feedback für einen Berater/Trainee, beschränkt auf die Dimension "{{DIMENSION_NAME}}", auf Basis der folgenden Beobachtungsdaten aus echten Kundenterminen.
|
||||
/**
|
||||
* Seit 2026-07-14 nur noch einmaliger Erstbefüllungs-Wert für `appSettings.defaultDimensionPromptTemplate`
|
||||
* (siehe `getOrSeedDefaultDimensionPromptTemplate()` in server/db/queries/appSettings.ts) — der tatsächlich
|
||||
* aktive Standard-Prompt lebt danach in der DB und ist im Admin-Tab „KI-Prompts" editierbar, nicht mehr hier.
|
||||
*/
|
||||
defaultCategoryPromptTemplate: `Du bist Führungskraft bei Capgemini. Erstelle Feedback-Inhalte für EINE Kategorie auf Basis der Beobachtungsdaten aus Kundenterminen.
|
||||
|
||||
BERATER: {{BERATER_NAME}}
|
||||
ASSIGNMENT: {{ASSIGNMENT_TITEL}} | Kunde: {{ASSIGNMENT_KUNDE}}
|
||||
FÜLLWÖRTER GESAMT: {{FUELLWOERTER_GESAMT}}
|
||||
DIMENSION: {{DIMENSION_NAME}}
|
||||
KATEGORIE: {{KATEGORIE_NAME}}
|
||||
{{KATEGORIE_ERLAEUTERUNG}}
|
||||
|
||||
KATEGORIEN DIESER DIMENSION:
|
||||
{{KATEGORIEN_STRUKTUR}}
|
||||
|
||||
BEOBACHTETE KRITERIEN (nur mit tatsächlicher Bewertung oder Notiz):
|
||||
KRITERIEN & BEOBACHTUNGEN (nur diese Kategorie):
|
||||
{{KRITERIEN_SCORES}}
|
||||
|
||||
MANUELLE KATEGORIE-BEWERTUNGEN:
|
||||
{{KATEGORIE_BEWERTUNGEN}}
|
||||
MANUELLE KATEGORIE-BEWERTUNG: {{KATEGORIE_BEWERTUNG}}
|
||||
ENTWICKLUNG ÜBER MEETINGS: {{ENTWICKLUNG_VERLAUF}}
|
||||
{{TREND_VORSCHLAG}}
|
||||
|
||||
ENTWICKLUNG ÜBER DIE LAUFZEIT (chronologisch je Kategorie):
|
||||
{{ENTWICKLUNG_VERLAUF}}
|
||||
GETAGGTE PROTOKOLLZEILEN (dieser Kategorie zugeordnet):
|
||||
{{PROTOKOLL_GETAGGT}}
|
||||
|
||||
ALLGEMEINE MEETING-NOTIZEN (Berater-unabhängig, chronologisch):
|
||||
{{NOTIZEN_ALLGEMEIN_MEETING}}
|
||||
Schreibe:
|
||||
- SCORE: 1–10 (Trend-Vorschlag beachten — bestätigen oder maximal ±1 abweichen)
|
||||
- BENEFITS: 1–3 kurze positive Beobachtungen (Stichpunkte mit "- ")
|
||||
- CONCERNS: 1–3 kurze kritische Beobachtungen (Stichpunkte mit "- "). Concerns sind Feststellungen, KEINE Handlungsempfehlungen.
|
||||
|
||||
NICHT EINEM KRITERIUM ZUGEORDNETE PROTOKOLL-NOTIZEN DIESES BERATERS (chronologisch, Bewertungs-Notation bereits als "Not/Partially/Nearly/Fully Client Ready — Text" bzw. "Kundenzitat — Text" aufgelöst):
|
||||
{{PROTOKOLL_UNZUGEORDNET}}
|
||||
Nutze ausschließlich die oben genannten Daten. Reicht die Datenlage nicht: SCORE weglassen, BENEFITS/CONCERNS mit "- n/a".
|
||||
|
||||
Schreibe für JEDE der oben gelisteten Kategorien 1-3 kurze Stichpunkte (konkret, auf Beobachtungen gestützt, jede Zeile beginnt mit "- "). Schreibe abschließend für die gesamte Dimension einen Achievements-Abschnitt (2-4 Stichpunkte, anerkennend, jede Zeile beginnt mit "- ") und einen Development-Needs-Abschnitt (2-4 Stichpunkte, jeder als konkrete Handlungsempfehlung formuliert, z.B. "Sollte darauf achten, dass ..." oder "Empfehlenswert wäre, ...", jede Zeile beginnt mit "- "). Falls eine Kategorie aus den Daten nicht beurteilbar ist, schreibe "- n/a". Beziehe erkennbare Verbesserungen/Verschlechterungen aus der Entwicklung über die Laufzeit ein. Schreibe direkt und persönlich (du-Form), vermeide generische Phrasen und ganze Fließtext-Absätze.
|
||||
Antwortformat (Marker in eigener Zeile oder mit Text in derselben Zeile), ohne Markdown-Codefences:
|
||||
|
||||
SCORE: <1-10>
|
||||
BENEFITS:
|
||||
- <Stichpunkt>
|
||||
CONCERNS:
|
||||
- <Stichpunkt>`,
|
||||
defaultDimensionPromptTemplate: `Du bist Führungskraft bei Capgemini. Verdichte die folgenden Kategorie-Feedbacks zu übergreifenden Dimension-Hauptpunkten — ohne Rohprotokoll, nur auf Basis der Kategorie-Ergebnisse.
|
||||
|
||||
BERATER: {{BERATER_NAME}}
|
||||
ASSIGNMENT: {{ASSIGNMENT_TITEL}} | Kunde: {{ASSIGNMENT_KUNDE}}
|
||||
DIMENSION: {{DIMENSION_NAME}}
|
||||
|
||||
KATEGORIE-ERGEBNISSE:
|
||||
{{KATEGORIE_ERGEBNISSE}}
|
||||
|
||||
Schreibe für die gesamte Dimension:
|
||||
- ACHIEVEMENTS: genau 3 bis 5 übergreifende Benefits (keine bloße Wiederholung einzelner Kategorien)
|
||||
- DEVELOPMENT_NEEDS: genau 3 bis 5 übergreifende Concerns als Beobachtungen (keine Empfehlungsformeln wie "Sollte …")
|
||||
|
||||
Nutze ausschließlich die Kategorie-Ergebnisse oben. Antwortformat:
|
||||
|
||||
ACHIEVEMENTS:
|
||||
- <Hauptpunkt>
|
||||
DEVELOPMENT_NEEDS:
|
||||
- <Beobachtung>`,
|
||||
categoryPromptPlaceholders: [
|
||||
{ token: '{{BERATER_NAME}}', description: 'Vor- und Nachname des Institutee' },
|
||||
{ token: '{{ASSIGNMENT_TITEL}}', description: 'Titel des Assignments' },
|
||||
{ token: '{{ASSIGNMENT_KUNDE}}', description: 'Kundenname des Assignments' },
|
||||
{ token: '{{DIMENSION_NAME}}', description: 'Name der übergeordneten Dimension' },
|
||||
{ token: '{{KATEGORIE_NAME}}', description: 'Name der aktuellen Kategorie' },
|
||||
{ token: '{{KATEGORIE_ERLAEUTERUNG}}', description: 'Optional: Erläuterung der Kategorie' },
|
||||
{ token: '{{KRITERIEN_SCORES}}', description: 'Kriterien dieser Kategorie mit Ø-Score und Notizen' },
|
||||
{ token: '{{KATEGORIE_BEWERTUNG}}', description: 'Manuelle Kategorie-Bewertung (1–10)' },
|
||||
{ token: '{{ENTWICKLUNG_VERLAUF}}', description: 'Meeting-Verlauf dieser Kategorie' },
|
||||
{ token: '{{TREND_VORSCHLAG}}', description: 'Vorgeschlagener Score aus Meeting-Trend (±1 Regel)' },
|
||||
{ token: '{{PROTOKOLL_GETAGGT}}', description: 'Protokollzeilen, die Kriterien dieser Kategorie zugeordnet sind' },
|
||||
],
|
||||
dimensionPromptPlaceholders: [
|
||||
{ token: '{{BERATER_NAME}}', description: 'Vor- und Nachname des Institutee' },
|
||||
{ token: '{{ASSIGNMENT_TITEL}}', description: 'Titel des Assignments' },
|
||||
{ token: '{{ASSIGNMENT_KUNDE}}', description: 'Kundenname des Assignments' },
|
||||
{ token: '{{DIMENSION_NAME}}', description: 'Name der aktuellen Dimension' },
|
||||
{ token: '{{KATEGORIE_ERGEBNISSE}}', description: 'Scores + Benefits/Concerns aller Kategorien (Stufe A)' },
|
||||
],
|
||||
defaultCriterionTaggingPromptTemplate: `Du bist Assistent bei der Auswertung von Kundentermin-Protokollen für Capgemini-Trainees (Institutees). Analysiere die folgenden noch nicht einem Bewertungskriterium zugeordneten Protokollzeilen und schlage pro Zeile passende Kriterien vor.
|
||||
|
||||
ASSIGNMENT-TYP: {{ASSIGNMENT_TYP}}
|
||||
|
||||
VERFÜGBARE KRITERIEN (Dimension → Kategorie → Kriterium, referenziert über die Zahl in eckigen Klammern):
|
||||
{{KRITERIEN_STRUKTUR}}
|
||||
|
||||
BEREITS BEKANNTE, TYPISCHE FORMULIERUNGSMUSTER PRO KRITERIUM (aus früheren Analyse-Läufen, sofern vorhanden):
|
||||
{{GELERNTE_MUSTER}}
|
||||
|
||||
ÄHNLICHE, BEREITS ZUGEORDNETE ALT-ZEILEN (Kontext-Hinweis, keine feste Vorgabe):
|
||||
{{AEHNLICHE_ALT_ZUORDNUNGEN}}
|
||||
|
||||
NOCH NICHT ZUGEORDNETE PROTOKOLLZEILEN (nummeriert):
|
||||
{{PROTOKOLL_ZEILEN}}
|
||||
|
||||
Ordne jede Zeile 0 bis 3 Kriterien zu, priorisiert nach Passung (wahrscheinlichstes zuerst). Nutze ausschließlich die oben gelisteten Kriterium-IDs. Wenn keine sinnvolle Zuordnung erkennbar ist, gib "-" an. Erfinde keine Kriterien und keine Beobachtungen, die nicht im Zeilentext stehen.
|
||||
|
||||
Antworte AUSSCHLIESSLICH in exakt diesem Format, ohne zusätzliche Erklärungen, ohne Markdown-Formatierung:
|
||||
|
||||
KATEGORIE: <Name der ersten Kategorie>
|
||||
- <Stichpunkt>
|
||||
- <Stichpunkt>
|
||||
ZEILE <Nummer>: <Kriterium-ID>, <Kriterium-ID>, ...
|
||||
ZEILE <Nummer>: -
|
||||
|
||||
KATEGORIE: <Name der zweiten Kategorie>
|
||||
- <Stichpunkt>
|
||||
Ergänze danach, nur für Kriterien mit mindestens einer Zuordnung in dieser Analyse, kurze generalisierte Formulierungsmuster (1-2 Sätze, keine Zitate einzelner Zeilen):
|
||||
|
||||
ACHIEVEMENTS:
|
||||
- <Stichpunkt>
|
||||
- <Stichpunkt>
|
||||
|
||||
DEVELOPMENT_NEEDS:
|
||||
- <Handlungsempfehlung, z.B. "Sollte darauf achten, dass ...">
|
||||
- <Handlungsempfehlung>`,
|
||||
dimensionPromptPlaceholders: [
|
||||
{ token: '{{BERATER_NAME}}', description: 'Vor- und Nachname des Institutee' },
|
||||
{ token: '{{ASSIGNMENT_TITEL}}', description: 'Titel des Assignments' },
|
||||
{ token: '{{ASSIGNMENT_KUNDE}}', description: 'Kundenname des Assignments' },
|
||||
{ token: '{{DIMENSION_NAME}}', description: 'Name der aktuellen Dimension' },
|
||||
{ token: '{{KATEGORIEN_STRUKTUR}}', description: 'Liste der Kategorienamen dieser Dimension' },
|
||||
{ token: '{{KRITERIEN_SCORES}}', description: 'Kriterien mit Ø-Score und zusammengeführten Notizen, gruppiert nach Kategorie' },
|
||||
{ token: '{{KATEGORIE_BEWERTUNGEN}}', description: 'Manuell gesetzte Kategorie-Bewertungen (Not/Partially/Nearly/Fully)' },
|
||||
{ token: '{{ENTWICKLUNG_VERLAUF}}', description: 'Chronologischer Bewertungs-Trend je Kategorie über die Meetings' },
|
||||
{ token: '{{NOTIZEN_ALLGEMEIN_MEETING}}', description: 'Allgemeine, Berater-unabhängige Notizen je Meeting, chronologisch' },
|
||||
{ token: '{{PROTOKOLL_UNZUGEORDNET}}', description: 'Nicht getaggte Protokollzeilen dieses Beraters, chronologisch je Meeting' },
|
||||
{ token: '{{FUELLWOERTER_GESAMT}}', description: 'Füllwörter-Summe dieses Beraters über alle Meetings' },
|
||||
MUSTER:
|
||||
<Kriterium-ID>: <kurze Beschreibung typischer Formulierungen für dieses Kriterium>`,
|
||||
criterionTaggingPromptPlaceholders: [
|
||||
{ token: '{{ASSIGNMENT_TYP}}', description: 'Name des Assignment-Typs des aktuellen Meetings' },
|
||||
{ token: '{{KRITERIEN_STRUKTUR}}', description: 'ID-referenzierte Struktur Dimension → Kategorie → Kriterium, gefiltert auf die im Assignment-Typ sichtbaren Kriterien, inkl. aller Beschreibungen' },
|
||||
{ token: '{{GELERNTE_MUSTER}}', description: 'KI-destillierte Formulierungsmuster pro Kriterium aus früheren Analyse-Läufen (Nebenprodukt, siehe FeedbackCriterionItem.learnedPatternHints)' },
|
||||
{ token: '{{AEHNLICHE_ALT_ZUORDNUNGEN}}', description: 'Lokal (ohne KI) ermittelte, ähnlichste bereits getaggte Alt-Zeilen je noch offener Zeile' },
|
||||
{ token: '{{PROTOKOLL_ZEILEN}}', description: 'Nummerierte, noch nicht zugeordnete Zeilen des gesamten offenen Protokolls (Gesprächsbeiträge + allgemeine Notizen)' },
|
||||
],
|
||||
} as const
|
||||
|
||||
/** Numerische Gewichte für Rating-Aggregation. N/A wird aus Berechnungen ausgeschlossen. */
|
||||
export const RATING_NUM_MAP: Record<FeedbackRating, number> = {
|
||||
na: 0,
|
||||
not_client_ready: 1,
|
||||
partially_client_ready: 2,
|
||||
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
|
||||
/** Mindest-Punktedelta auf der 1–10-Skala zwischen erstem und letztem Meeting, ab dem ein Trend gilt. */
|
||||
export const RATING_TREND_DELTA_THRESHOLD = 1
|
||||
@@ -1,6 +1,29 @@
|
||||
import { rpc } from '../rpcClient'
|
||||
import type { RatingColorBand } from '../types'
|
||||
|
||||
export const getRatingTrendWeightStep = (): Promise<number> => rpc('appSettings', 'getRatingTrendWeightStep')
|
||||
export const getOrSeedRatingTrendWeightStep = (): Promise<number> => rpc('appSettings', 'getOrSeedRatingTrendWeightStep')
|
||||
export const saveRatingTrendWeightStep = (weightStep: number): Promise<number> =>
|
||||
rpc('appSettings', 'saveRatingTrendWeightStep', weightStep)
|
||||
|
||||
export const getOrSeedRatingColorBands = (): Promise<RatingColorBand[]> =>
|
||||
rpc('appSettings', 'getOrSeedRatingColorBands')
|
||||
export const saveRatingColorBands = (bands: RatingColorBand[]): Promise<number> =>
|
||||
rpc('appSettings', 'saveRatingColorBands', bands)
|
||||
|
||||
export const getDefaultDimensionPromptTemplate = (): Promise<string> =>
|
||||
rpc('appSettings', 'getDefaultDimensionPromptTemplate')
|
||||
export const getOrSeedDefaultDimensionPromptTemplate = (): Promise<string> =>
|
||||
rpc('appSettings', 'getOrSeedDefaultDimensionPromptTemplate')
|
||||
export const saveDefaultDimensionPromptTemplate = (template: string): Promise<number> =>
|
||||
rpc('appSettings', 'saveDefaultDimensionPromptTemplate', template)
|
||||
|
||||
export const getOrSeedCriterionTaggingPromptTemplate = (): Promise<string> =>
|
||||
rpc('appSettings', 'getOrSeedCriterionTaggingPromptTemplate')
|
||||
export const saveCriterionTaggingPromptTemplate = (template: string): Promise<number> =>
|
||||
rpc('appSettings', 'saveCriterionTaggingPromptTemplate', template)
|
||||
|
||||
export const getOrSeedDefaultCategoryPromptTemplate = (): Promise<string> =>
|
||||
rpc('appSettings', 'getOrSeedDefaultCategoryPromptTemplate')
|
||||
export const saveDefaultCategoryPromptTemplate = (template: string): Promise<number> =>
|
||||
rpc('appSettings', 'saveDefaultCategoryPromptTemplate', template)
|
||||
@@ -31,6 +31,8 @@ export const addFeedbackCategoryRating = (r: Omit<FeedbackCategoryRating, 'id'>)
|
||||
rpc('assignmentFeedback', 'addFeedbackCategoryRating', r)
|
||||
export const updateFeedbackCategoryRating = (id: number, patch: Partial<FeedbackCategoryRating>): Promise<number> =>
|
||||
rpc('assignmentFeedback', 'updateFeedbackCategoryRating', id, patch)
|
||||
export const deleteFeedbackCategoryRating = (id: number): Promise<void> =>
|
||||
rpc('assignmentFeedback', 'deleteFeedbackCategoryRating', id)
|
||||
|
||||
export const listFeedbackDimensionTexts = (assignmentFeedbackId: number): Promise<FeedbackDimensionText[]> =>
|
||||
rpc('assignmentFeedback', 'listFeedbackDimensionTexts', assignmentFeedbackId)
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { rpc } from '../rpcClient'
|
||||
import type { ChecklistItemDef, ChecklistResponse } from '../types'
|
||||
|
||||
export const listChecklistItemDefsForPhaseTemplate = (phaseTemplateId: number): Promise<ChecklistItemDef[]> =>
|
||||
rpc('checklists', 'listChecklistItemDefsForPhaseTemplate', phaseTemplateId)
|
||||
export const listChecklistItemDefsForPhaseTemplates = (phaseTemplateIds: number[]): Promise<ChecklistItemDef[]> =>
|
||||
rpc('checklists', 'listChecklistItemDefsForPhaseTemplates', phaseTemplateIds)
|
||||
export const addChecklistItemDef = (def: Omit<ChecklistItemDef, 'id'>): Promise<number> =>
|
||||
rpc('checklists', 'addChecklistItemDef', def)
|
||||
export const updateChecklistItemDef = (id: number, patch: Partial<ChecklistItemDef>): Promise<number> =>
|
||||
rpc('checklists', 'updateChecklistItemDef', id, patch)
|
||||
export const deleteChecklistItemDef = (id: number): Promise<void> =>
|
||||
rpc('checklists', 'deleteChecklistItemDef', id)
|
||||
|
||||
export const listChecklistResponsesForMeeting = (meetingInstanceId: number): Promise<ChecklistResponse[]> =>
|
||||
rpc('checklists', 'listChecklistResponsesForMeeting', meetingInstanceId)
|
||||
export const listChecklistResponsesForMeetings = (meetingInstanceIds: number[]): Promise<ChecklistResponse[]> =>
|
||||
rpc('checklists', 'listChecklistResponsesForMeetings', meetingInstanceIds)
|
||||
|
||||
export const upsertChecklistResponse = (input: {
|
||||
meetingInstanceId: number
|
||||
instituteeId?: number
|
||||
checklistItemId: number
|
||||
rating: ChecklistResponse['rating']
|
||||
note: string
|
||||
criterionItemId?: number
|
||||
}): Promise<number> => rpc('checklists', 'upsertChecklistResponse', input)
|
||||
@@ -0,0 +1,6 @@
|
||||
import { rpc } from '../rpcClient'
|
||||
import type { ConversationLineTag } from '../types'
|
||||
|
||||
/** Globaler (Zeilentext → Kriterium)-Korpus über alle Assignments — siehe server/db/queries/criterionSuggestions.ts. */
|
||||
export const getGlobalLineTagCorpus = (): Promise<ConversationLineTag[]> =>
|
||||
rpc('criterionSuggestions', 'getGlobalLineTagCorpus')
|
||||
@@ -33,6 +33,36 @@ export function filterVisibleFeedbackStructure<
|
||||
return { categories, items }
|
||||
}
|
||||
|
||||
/**
|
||||
* Kanonische Sichtbarkeit für Assignment-Typ: Dimension → Kategorie → Kriterien.
|
||||
* Kategorien ohne sichtbare Items und Dimensionen ohne sichtbare Kategorien entfallen.
|
||||
* Leere/undefined criteriaIds = alles sichtbar. Baut auf `filterVisibleFeedbackStructure`.
|
||||
*/
|
||||
export function resolveVisibleStructure<
|
||||
D extends { id?: number },
|
||||
C extends { id?: number; dimensionId: number },
|
||||
I extends { id?: number; categoryId: number },
|
||||
>(
|
||||
allDimensions: D[],
|
||||
allCategories: C[],
|
||||
allItems: I[],
|
||||
criteriaIds: number[] | undefined,
|
||||
): { dimensions: D[]; categories: C[]; items: I[] } {
|
||||
const { categories, items } = filterVisibleFeedbackStructure(allCategories, allItems, criteriaIds)
|
||||
const visibleDimIds = new Set(categories.map(c => c.dimensionId))
|
||||
const dimensions = allDimensions.filter(d => visibleDimIds.has(d.id!))
|
||||
return { dimensions, categories, items }
|
||||
}
|
||||
|
||||
/** Alle Kriterium-IDs der gegebenen Kategorien — für Config „Kategorie/Dimension wählen → criteriaIds“. */
|
||||
export function criterionIdsForCategories(
|
||||
categoryIds: number[],
|
||||
allItems: { id?: number; categoryId: number }[],
|
||||
): number[] {
|
||||
const catSet = new Set(categoryIds)
|
||||
return allItems.filter(i => catSet.has(i.categoryId) && i.id != null).map(i => i.id!)
|
||||
}
|
||||
|
||||
export const addFeedbackDimension = (d: Omit<FeedbackDimension, 'id'>): Promise<number> =>
|
||||
rpc('feedbackStructure', 'addFeedbackDimension', d)
|
||||
export const updateFeedbackDimension = (id: number, patch: Partial<FeedbackDimension>): Promise<number> =>
|
||||
@@ -53,8 +83,45 @@ export const addFeedbackCriterionItem = (i: Omit<FeedbackCriterionItem, 'id'>):
|
||||
rpc('feedbackStructure', 'addFeedbackCriterionItem', i)
|
||||
export const updateFeedbackCriterionItem = (id: number, patch: Partial<FeedbackCriterionItem>): Promise<number> =>
|
||||
rpc('feedbackStructure', 'updateFeedbackCriterionItem', id, patch)
|
||||
/** Räumt vorher selbst alle Verwendungen auf (Assessments/Tags/Sichtbarkeitslisten) — siehe CLAUDE.md. */
|
||||
export const deleteFeedbackCriterionItem = (id: number): Promise<void> => rpc('feedbackStructure', 'deleteFeedbackCriterionItem', id)
|
||||
|
||||
export interface CriterionUsage {
|
||||
assessmentCount: number
|
||||
lineTagCount: number
|
||||
generalNoteTagCount: number
|
||||
assignmentTypeNames: string[]
|
||||
phaseTemplateLabels: string[]
|
||||
meetings: { meetingId: number; assignmentId: number; assignmentTitle: string; date: string }[]
|
||||
}
|
||||
|
||||
/** Verwendungs-Übersicht für alle Kriterien in einem Rutsch — siehe CLAUDE.md „Kriterien-Umbau". */
|
||||
export const getCriterionUsageMap = (): Promise<Record<number, CriterionUsage>> =>
|
||||
rpc('feedbackStructure', 'getCriterionUsageMap')
|
||||
|
||||
/** Überträgt alle Referenzen von `fromId` auf `toId` (für sicheres Löschen mit Zusammenführung statt Datenverlust). */
|
||||
export const reassignCriterionReferences = (fromId: number, toId: number): Promise<{ mergedConflicts: number }> =>
|
||||
rpc('feedbackStructure', 'reassignCriterionReferences', fromId, toId)
|
||||
|
||||
export type CriterionUsageInstance =
|
||||
| { kind: 'assessment'; assessmentId: number; meetingId: number; assignmentTitle: string; date: string; personLabel: string; text: string }
|
||||
| { kind: 'lineTag'; conversationEntryId: number; tagText: string; meetingId: number; assignmentTitle: string; date: string; personLabel: string; text: string }
|
||||
| { kind: 'generalNoteTag'; meetingInstanceId: number; tagText: string; meetingId: number; assignmentTitle: string; date: string; personLabel: string; text: string }
|
||||
| { kind: 'assignmentTypeVisibility'; assignmentTypeId: number; criterionId: number; text: string }
|
||||
| { kind: 'phaseTemplateVisibility'; phaseTemplateId: number; criterionId: number; text: string }
|
||||
|
||||
/** Einzelinstanzen-Liste für EIN Kriterium — Grundlage, um eine Zuordnung direkt umzuhängen/zu entfernen. */
|
||||
export const getCriterionUsageDetails = (criterionId: number): Promise<CriterionUsageInstance[]> =>
|
||||
rpc('feedbackStructure', 'getCriterionUsageDetails', criterionId)
|
||||
|
||||
/** Hängt EINE einzelne Verwendungsinstanz auf ein anderes Kriterium um. */
|
||||
export const reassignUsageInstance = (instance: CriterionUsageInstance, toId: number): Promise<{ merged: boolean }> =>
|
||||
rpc('feedbackStructure', 'reassignUsageInstance', instance, toId)
|
||||
|
||||
/** Entfernt EINE einzelne Verwendungsinstanz (Assessment wird gelöscht, Tags nur von der Zuordnung befreit). */
|
||||
export const removeUsageInstance = (instance: CriterionUsageInstance): Promise<void> =>
|
||||
rpc('feedbackStructure', 'removeUsageInstance', instance)
|
||||
|
||||
export const listFeedbackDimensionPrompts = (): Promise<FeedbackDimensionPrompt[]> =>
|
||||
rpc('feedbackStructure', 'listFeedbackDimensionPrompts')
|
||||
/** Selbstheilend — legt serverseitig bei Bedarf eine fehlende Prompt-Zeile mit Default-Template an. */
|
||||
@@ -62,3 +129,26 @@ export const getFeedbackDimensionPrompt = (dimensionId: number): Promise<Feedbac
|
||||
rpc('feedbackStructure', 'getFeedbackDimensionPrompt', dimensionId)
|
||||
export const updateFeedbackDimensionPrompt = (id: number, patch: Partial<FeedbackDimensionPrompt>): Promise<number> =>
|
||||
rpc('feedbackStructure', 'updateFeedbackDimensionPrompt', id, patch)
|
||||
|
||||
export const resetAllDimensionPromptsToDefault = (): Promise<{ updated: number }> =>
|
||||
rpc('feedbackStructure', 'resetAllDimensionPromptsToDefault')
|
||||
|
||||
export type { FeedbackStructureSeed } from '../../utils/feedbackStructureImport'
|
||||
export type ReplaceFeedbackStructureResult = {
|
||||
dimensions: number
|
||||
categories: number
|
||||
items: number
|
||||
clearedDimensions: number
|
||||
}
|
||||
|
||||
/** Ersetzt die gesamte Feedback-Struktur durch ein Seed-Objekt. */
|
||||
export const replaceFeedbackStructure = (seed: import('../../utils/feedbackStructureImport').FeedbackStructureSeed): Promise<ReplaceFeedbackStructureResult> =>
|
||||
rpc('feedbackStructure', 'replaceFeedbackStructure', seed)
|
||||
|
||||
/** Parst Markdown (Export-Format) und ersetzt die Struktur. */
|
||||
export const importFeedbackStructureFromMarkdown = (md: string): Promise<ReplaceFeedbackStructureResult> =>
|
||||
rpc('feedbackStructure', 'importFeedbackStructureFromMarkdown', md)
|
||||
|
||||
/** Lädt docs/preload/Feedback-Struktur-final.md in die Dev-DB. */
|
||||
export const preloadFinalFeedbackStructure = (): Promise<ReplaceFeedbackStructureResult> =>
|
||||
rpc('feedbackStructure', 'preloadFinalFeedbackStructure')
|
||||
@@ -3,7 +3,10 @@ export * from './consultants'
|
||||
export * from './assignmentTypes'
|
||||
export * from './assignments'
|
||||
export * from './feedbackStructure'
|
||||
export * from './criterionSuggestions'
|
||||
export * from './checklists'
|
||||
export * from './meetings'
|
||||
export * from './conversationEntries'
|
||||
export * from './assessments'
|
||||
export * from './assignmentFeedback'
|
||||
export * from './meetingCategoryRatings'
|
||||
@@ -0,0 +1,16 @@
|
||||
import { rpc } from '../rpcClient'
|
||||
import type { MeetingCategoryRating, RatingScore } from '../types'
|
||||
|
||||
export const listMeetingCategoryRatingsForMeeting = (meetingInstanceId: number): Promise<MeetingCategoryRating[]> =>
|
||||
rpc('meetingCategoryRatings', 'listMeetingCategoryRatingsForMeeting', meetingInstanceId)
|
||||
|
||||
export const listMeetingCategoryRatingsForMeetings = (meetingInstanceIds: number[]): Promise<MeetingCategoryRating[]> =>
|
||||
rpc('meetingCategoryRatings', 'listMeetingCategoryRatingsForMeetings', meetingInstanceIds)
|
||||
|
||||
export const upsertMeetingCategoryRating = (input: {
|
||||
meetingInstanceId: number
|
||||
instituteeId: number
|
||||
categoryId: number
|
||||
score: RatingScore | null
|
||||
note?: string
|
||||
}): Promise<number> => rpc('meetingCategoryRatings', 'upsertMeetingCategoryRating', input)
|
||||
@@ -2,6 +2,7 @@ import { rpc } from '../rpcClient'
|
||||
import type {
|
||||
MeetingInstance, PhaseTemplate, Assignment, Consultant,
|
||||
ConversationEntry, ConversationSkillScore, Assessment,
|
||||
ChecklistItemDef, ChecklistResponse, MeetingCategoryRating,
|
||||
} from '../types'
|
||||
|
||||
export const getMeetingInstance = (id: number): Promise<MeetingInstance | undefined> => rpc('meetings', 'getMeetingInstance', id)
|
||||
@@ -32,6 +33,9 @@ export interface MeetingExportData {
|
||||
entries: ConversationEntry[]
|
||||
allScores: ConversationSkillScore[]
|
||||
assessments: Assessment[]
|
||||
categoryRatings: MeetingCategoryRating[]
|
||||
checklistItems: ChecklistItemDef[]
|
||||
checklistResponses: ChecklistResponse[]
|
||||
}
|
||||
|
||||
/** Gebündelte Rohdaten für Markdown-/JSON-Export eines Meetings — vorher in meetingExport.ts dupliziert. */
|
||||
|
||||
+19
-6
@@ -5,12 +5,25 @@
|
||||
* unverändert über den Vite-Dev-Proxy UND später hinter einem Reverse Proxy/Docker funktioniert.
|
||||
*/
|
||||
export async function rpc<T>(module: string, fn: string, ...args: unknown[]): Promise<T> {
|
||||
const res = await fetch('/api/rpc', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ module, fn, args }),
|
||||
})
|
||||
if (!res.ok) throw new Error(`RPC-Fehler: ${res.status} ${res.statusText}`)
|
||||
let res: Response
|
||||
try {
|
||||
res = await fetch('/api/rpc', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ module, fn, args }),
|
||||
})
|
||||
} catch (err) {
|
||||
throw new Error(
|
||||
`API nicht erreichbar (${err instanceof Error ? err.message : String(err)}). `
|
||||
+ `Läuft der Dev-Server? In AssigmentMonitorV2: npm run dev:all (API-Port 4001).`,
|
||||
)
|
||||
}
|
||||
if (!res.ok) {
|
||||
const hint = res.status === 502 || res.status === 504 || res.status === 500
|
||||
? ` — vermutlich läuft die API auf Port 4001 nicht (npm run server / npm run dev:all).`
|
||||
: ''
|
||||
throw new Error(`RPC-Fehler: ${res.status} ${res.statusText}${hint}`)
|
||||
}
|
||||
const body = await res.json() as { ok: boolean; result?: T; error?: string }
|
||||
if (!body.ok) throw new Error(body.error ?? 'RPC-Fehler')
|
||||
return body.result as T
|
||||
|
||||
@@ -41,6 +41,7 @@ export async function seedIfEmpty() {
|
||||
isRepeatable: opts.repeatable ?? false,
|
||||
hasConversation: opts.conv ?? false,
|
||||
hasAssessment: opts.assess ?? false,
|
||||
hasChecklist: false,
|
||||
criteriaIds: opts.criteriaIds ?? [],
|
||||
order: opts.order,
|
||||
})
|
||||
|
||||
@@ -0,0 +1,660 @@
|
||||
{
|
||||
"dimensions": [
|
||||
{
|
||||
"name": "Client-Readiness",
|
||||
"categories": [
|
||||
{
|
||||
"name": "Problem Structuring",
|
||||
"items": [
|
||||
{
|
||||
"name": "Problem- und Zielklarheit",
|
||||
"weight": 1,
|
||||
"description": "Klärt Ausgangslage, eigentliches Problem, angestrebtes Ergebnis und relevante Entscheidung, bevor mit der Bearbeitung begonnen wird."
|
||||
},
|
||||
{
|
||||
"name": "Scope-Klarheit",
|
||||
"weight": 1,
|
||||
"description": "Grenzt Untersuchungsgegenstand, Betrachtungszeitraum, Stakeholder, Annahmen und Nicht-Ziele nachvollziehbar ab."
|
||||
},
|
||||
{
|
||||
"name": "Logische Zerlegung",
|
||||
"weight": 1,
|
||||
"description": "Zerlegt komplexe Fragestellungen in verständliche, trennscharfe und gemeinsam hinreichend vollständige Teilfragen."
|
||||
},
|
||||
{
|
||||
"name": "Hypothesenorientierung",
|
||||
"weight": 1,
|
||||
"description": "Formuliert frühzeitig plausible, überprüfbare Hypothesen und nutzt sie zur Steuerung der weiteren Analyse."
|
||||
},
|
||||
{
|
||||
"name": "Priorisierung nach Relevanz",
|
||||
"weight": 1,
|
||||
"description": "Fokussiert die Struktur auf die entscheidungs- und wirkungsrelevanten Fragestellungen und vermeidet unnötige Analysebreite."
|
||||
},
|
||||
{
|
||||
"name": "Treiber- und Abhängigkeitsverständnis",
|
||||
"weight": 1,
|
||||
"description": "Erkennt wesentliche Ursachen, Wirkzusammenhänge, Abhängigkeiten und Wechselwirkungen innerhalb der Fragestellung."
|
||||
},
|
||||
{
|
||||
"name": "Ableitung eines Analyseplans",
|
||||
"weight": 1,
|
||||
"description": "Übersetzt die Problemstruktur in konkrete Arbeitsschritte, benötigte Informationen, Verantwortlichkeiten und sinnvolle Prüfsequenzen."
|
||||
}
|
||||
],
|
||||
"description": "Übersetzt eine zunächst offene oder komplexe Kundenfragestellung in eine präzise, logisch gegliederte und bearbeitbare Problemstruktur, die eine fokussierte Analyse und zielgerichtete Entscheidungsfindung ermöglicht."
|
||||
},
|
||||
{
|
||||
"name": "Problem Solving",
|
||||
"items": [
|
||||
{
|
||||
"name": "Fakten- und Evidenzorientierung",
|
||||
"weight": 1,
|
||||
"description": "Stützt Aussagen auf belastbare Daten, Quellen, Interviews, Analysen oder transparent hergeleitete Annahmen."
|
||||
},
|
||||
{
|
||||
"name": "Methodengerechte Analyse",
|
||||
"weight": 1,
|
||||
"description": "Wählt geeignete qualitative und quantitative Methoden aus und wendet sie fachlich korrekt und zweckmäßig an."
|
||||
},
|
||||
{
|
||||
"name": "Kritische Prüfung von Informationen",
|
||||
"weight": 1,
|
||||
"description": "Hinterfragt Datenqualität, Quellen, Annahmen, Widersprüche und mögliche Verzerrungen, statt Ergebnisse ungeprüft zu übernehmen."
|
||||
},
|
||||
{
|
||||
"name": "Hypothesenprüfung und Iteration",
|
||||
"weight": 1,
|
||||
"description": "Prüft Hypothesen systematisch, verwirft oder schärft sie anhand neuer Erkenntnisse und passt das Vorgehen entsprechend an."
|
||||
},
|
||||
{
|
||||
"name": "Entwicklung von Lösungsoptionen",
|
||||
"weight": 1,
|
||||
"description": "Entwickelt mehrere relevante Handlungsoptionen und macht deren Unterschiede, Vor- und Nachteile sowie Konsequenzen sichtbar."
|
||||
},
|
||||
{
|
||||
"name": "Impact- und Value-Orientierung",
|
||||
"weight": 1,
|
||||
"description": "Richtet Analyse, Vorgehen und Lösung auf den höchsten realistischen Kundennutzen aus. Hinterfragt bei Bedarf den ursprünglich gewünschten Deliverable-Typ und entwickelt wirkungsvollere Alternativen, ohne Ziel, Scope, Risiken oder Umsetzbarkeit eigenmächtig zu verändern."
|
||||
},
|
||||
{
|
||||
"name": "Machbarkeit und Realitätsnähe",
|
||||
"weight": 1,
|
||||
"description": "Berücksichtigt organisatorische, technische, wirtschaftliche und zeitliche Rahmenbedingungen bei der Lösungsentwicklung."
|
||||
},
|
||||
{
|
||||
"name": "Entscheidungsorientierte Empfehlung",
|
||||
"weight": 1,
|
||||
"description": "Verdichtet Analyseergebnisse zu einer klaren Empfehlung mit Begründung, Auswirkungen, Risiken und nächsten Schritten."
|
||||
}
|
||||
],
|
||||
"description": "Bearbeitet strukturierte Fragestellungen analytisch belastbar, pragmatisch und ergebnisorientiert. Entwickelt aus Fakten und Erkenntnissen umsetzbare Optionen, Entscheidungen und Empfehlungen."
|
||||
},
|
||||
{
|
||||
"name": "Storylining",
|
||||
"items": [
|
||||
{
|
||||
"name": "Answer First / Kernaussage",
|
||||
"weight": 1,
|
||||
"description": "Stellt die zentrale Aussage, Empfehlung oder Antwort frühzeitig und eindeutig heraus."
|
||||
},
|
||||
{
|
||||
"name": "Logische Argumentationsstruktur",
|
||||
"weight": 1,
|
||||
"description": "Ordnet Aussagen so, dass Schlussfolgerungen nachvollziehbar aus Fakten, Analysen und Teilargumenten hervorgehen."
|
||||
},
|
||||
{
|
||||
"name": "Relevanz und Fokus",
|
||||
"weight": 1,
|
||||
"description": "Beschränkt die Storyline auf Inhalte, die für Fragestellung, Zielgruppe und Entscheidung tatsächlich erforderlich sind."
|
||||
},
|
||||
{
|
||||
"name": "Belegführung",
|
||||
"weight": 1,
|
||||
"description": "Verknüpft Kernaussagen sichtbar mit belastbaren Fakten, Analysen und nachvollziehbaren Begründungen."
|
||||
},
|
||||
{
|
||||
"name": "Managementgerechte Dramaturgie",
|
||||
"weight": 1,
|
||||
"description": "Führt verständlich von Ausgangslage und Handlungsdruck über Erkenntnisse zu Empfehlung, Wirkung und nächstem Schritt."
|
||||
},
|
||||
{
|
||||
"name": "Konsistenz über Medien und Beiträge",
|
||||
"weight": 1,
|
||||
"description": "Hält Botschaften, Begriffe, Zahlen und Argumentationslogik über Folien, Dokumente und mündliche Beiträge hinweg widerspruchsfrei."
|
||||
}
|
||||
],
|
||||
"description": "Verdichtet komplexe Inhalte zu einer logisch schlüssigen, adressatengerechten und entscheidungsorientierten Argumentationslinie, die Kernbotschaften klar transportiert."
|
||||
},
|
||||
{
|
||||
"name": "Precise Communication",
|
||||
"items": [
|
||||
{
|
||||
"name": "Active Listening",
|
||||
"weight": 1,
|
||||
"description": "Hört aufmerksam zu, erfasst Inhalt und Kontext und greift relevante Aussagen, Bedenken und Signale gezielt auf."
|
||||
},
|
||||
{
|
||||
"name": "Präzise Fragetechnik",
|
||||
"weight": 1,
|
||||
"description": "Stellt klare, relevante und aufeinander aufbauende Fragen, die Verständnis, Erkenntnisgewinn oder Entscheidung fördern."
|
||||
},
|
||||
{
|
||||
"name": "To the Point",
|
||||
"weight": 1,
|
||||
"description": "Formuliert die wesentliche Aussage ohne unnötige Vorrede, Wiederholungen oder Nebenpfade."
|
||||
},
|
||||
{
|
||||
"name": "Adressatengerechte Kommunikation",
|
||||
"weight": 1,
|
||||
"description": "Passt Tonalität, Detailtiefe, Begriffswahl und Kommunikationsstil an Zielgruppe, Hierarchie und Situation an."
|
||||
},
|
||||
{
|
||||
"name": "Sprachliche Klarheit und Verbindlichkeit",
|
||||
"weight": 1,
|
||||
"description": "Verwendet eindeutige Formulierungen und vermeidet unnötige Füllwörter, Weichmacher, Mehrdeutigkeit und Scheingenauigkeit."
|
||||
},
|
||||
{
|
||||
"name": "Recap und Verständnissicherung",
|
||||
"weight": 1,
|
||||
"description": "Fasst Kernaussagen, Entscheidungen, offene Punkte und nächste Schritte prägnant zusammen und prüft gemeinsames Verständnis."
|
||||
},
|
||||
{
|
||||
"name": "Souveräne Präsenz",
|
||||
"weight": 1,
|
||||
"description": "Tritt ruhig, vorbereitet, klar und entscheidungsorientiert auf. Behält auch bei kritischen Rückfragen, Widerspruch oder unvollständigen Informationen die Handlungsfähigkeit, unterscheidet sicher zwischen Fakten, Annahmen und offenen Punkten und vermittelt Orientierung, ohne Sicherheit vorzutäuschen."
|
||||
}
|
||||
],
|
||||
"description": "Nimmt Informationen aktiv auf und kommuniziert mündlich wie schriftlich klar, prägnant, adressatengerecht und handlungsorientiert."
|
||||
},
|
||||
{
|
||||
"name": "Client Intimacy Building",
|
||||
"items": [
|
||||
{
|
||||
"name": "Verständnis des Kundenkontexts",
|
||||
"weight": 1,
|
||||
"description": "Erfasst Ziele, Geschäftsmodell, Prioritäten, Restriktionen, Entscheidungslogiken und relevante Rahmenbedingungen des Kunden."
|
||||
},
|
||||
{
|
||||
"name": "Stakeholderverständnis",
|
||||
"weight": 1,
|
||||
"description": "Erkennt Interessen, Einfluss, Erwartungen und mögliche Widerstände relevanter Stakeholder und berücksichtigt sie im Vorgehen."
|
||||
},
|
||||
{
|
||||
"name": "Vertrauensaufbau und Beziehungsqualität",
|
||||
"weight": 1,
|
||||
"description": "Schafft durch Verlässlichkeit, Integrität, professionelles Verhalten und respektvolle Zusammenarbeit eine belastbare Arbeitsbeziehung."
|
||||
},
|
||||
{
|
||||
"name": "Fachliche Glaubwürdigkeit und Kompetenzwahrnehmung",
|
||||
"weight": 1,
|
||||
"description": "Wird durch fachliche Substanz, Kundenverständnis, klare Einordnung und belastbare Empfehlungen als relevanter und kompetenter Ansprechpartner wahrgenommen. Gibt Orientierung und macht zugleich Grenzen des eigenen Wissens transparent."
|
||||
},
|
||||
{
|
||||
"name": "Aktives Erwartungsmanagement",
|
||||
"weight": 1,
|
||||
"description": "Klärt Ziele, Rollen, Umfang, Annahmen, Risiken und Liefererwartungen und steuert Abweichungen frühzeitig nach."
|
||||
},
|
||||
{
|
||||
"name": "Active Advisory und Customer Steering",
|
||||
"weight": 1,
|
||||
"description": "Führt den Kunden aktiv durch Fragestellungen, Optionen, Konsequenzen und notwendige Entscheidungen. Spricht klare Empfehlungen aus und verhindert eine rein ausführende Rolle, ohne die Entscheidungsverantwortung des Kunden zu übergehen."
|
||||
},
|
||||
{
|
||||
"name": "Konstruktives Challengen",
|
||||
"weight": 1,
|
||||
"description": "Hinterfragt Annahmen oder Kundenwünsche respektvoll, faktenbasiert und lösungsorientiert, wenn dies dem Ergebnis dient."
|
||||
},
|
||||
{
|
||||
"name": "Beziehungsentwicklung über den Einzeltermin hinaus",
|
||||
"weight": 1,
|
||||
"description": "Pflegt relevante Kontakte, erkennt Anschlussbedarfe und schafft Kontinuität in der Zusammenarbeit, ohne aufdringlich oder rein vertriebsorientiert zu handeln."
|
||||
}
|
||||
],
|
||||
"description": "Baut professionelle, vertrauensvolle Kundenbeziehungen auf, versteht fachliche und persönliche Stakeholderbedürfnisse und entwickelt sich vom Ausführenden zum wirksamen Berater."
|
||||
},
|
||||
{
|
||||
"name": "Quality of Deliverables",
|
||||
"items": [
|
||||
{
|
||||
"name": "Fachliche Richtigkeit",
|
||||
"weight": 1,
|
||||
"description": "Inhalte, Berechnungen, Aussagen und Schlussfolgerungen sind fachlich korrekt und belastbar."
|
||||
},
|
||||
{
|
||||
"name": "Inhaltliche Vollständigkeit",
|
||||
"weight": 1,
|
||||
"description": "Deckt die für Fragestellung und Entscheidung relevanten Aspekte, Perspektiven und Auswirkungen angemessen ab."
|
||||
},
|
||||
{
|
||||
"name": "Logische Konsistenz",
|
||||
"weight": 1,
|
||||
"description": "Stellt sicher, dass Aussagen, Zahlen, Argumente und Empfehlungen in sich sowie untereinander widerspruchsfrei sind."
|
||||
},
|
||||
{
|
||||
"name": "Kundenspezifische Konkretisierung",
|
||||
"weight": 1,
|
||||
"description": "Überträgt generische Erkenntnisse sichtbar auf Situation, Sprache, Daten und Handlungsrealität des Kunden."
|
||||
},
|
||||
{
|
||||
"name": "Informationsdichte und Nutzbarkeit",
|
||||
"weight": 1,
|
||||
"description": "Wählt eine angemessene Detailtiefe und ermöglicht dem Adressaten, Kernaussagen und Handlungsbedarf schnell zu erfassen."
|
||||
},
|
||||
{
|
||||
"name": "Visualisierungs- und Darstellungsqualität",
|
||||
"weight": 1,
|
||||
"description": "Nutzt Struktur, Layout, Tabellen, Grafiken und Visualisierungen so, dass sie Verständnis und Botschaft wirksam unterstützen."
|
||||
},
|
||||
{
|
||||
"name": "Formale Qualität und Standardkonformität",
|
||||
"weight": 1,
|
||||
"description": "Hält relevante Templates, Designvorgaben, Sprache, Quellenangaben, Versionierung und Dokumentationsstandards konsequent ein."
|
||||
}
|
||||
],
|
||||
"description": "Erstellt fachlich belastbare, konsistente und professionell aufbereitete Arbeitsergebnisse, die für den Kunden verständlich, relevant und unmittelbar nutzbar sind."
|
||||
},
|
||||
{
|
||||
"name": "Proposal Writing & Value Proposition Design",
|
||||
"items": [
|
||||
{
|
||||
"name": "Verständnis von Bedarf und Buying Context",
|
||||
"weight": 1,
|
||||
"description": "Erfasst Problem, Auslöser, Zielbild, Entscheidungskriterien, Stakeholder und Beschaffungskontext hinter der Anfrage."
|
||||
},
|
||||
{
|
||||
"name": "Klare Value Proposition",
|
||||
"weight": 1,
|
||||
"description": "Formuliert prägnant, welchen konkreten Nutzen und welche angestrebten Ergebnisse das Angebot für den Kunden erzeugt."
|
||||
},
|
||||
{
|
||||
"name": "Kundenspezifische Differenzierung",
|
||||
"weight": 1,
|
||||
"description": "Verbindet Kundenbedarf mit relevanten Fähigkeiten, Erfahrungen, Assets und unterscheidbaren Stärken des eigenen Angebots."
|
||||
},
|
||||
{
|
||||
"name": "Schlüssiger Scope und Deliverables",
|
||||
"weight": 1,
|
||||
"description": "Beschreibt Leistungsumfang, Ergebnisse, Grenzen und Verantwortlichkeiten klar und vermeidet Interpretationsspielräume."
|
||||
},
|
||||
{
|
||||
"name": "Plausibles Vorgehensmodell",
|
||||
"weight": 1,
|
||||
"description": "Entwickelt einen nachvollziehbaren Ansatz mit Arbeitspaketen, Meilensteinen, Beteiligten und Entscheidungszeitpunkten."
|
||||
},
|
||||
{
|
||||
"name": "Belastbare Annahmen und Machbarkeit",
|
||||
"weight": 1,
|
||||
"description": "Macht Voraussetzungen, Abhängigkeiten, Risiken und Mitwirkungspflichten transparent und verspricht nur realistisch Lieferbares."
|
||||
},
|
||||
{
|
||||
"name": "Kommerzielles Verständnis",
|
||||
"weight": 1,
|
||||
"description": "Berücksichtigt Aufwand, Preislogik, Wirtschaftlichkeit, Risiken und den für beide Seiten tragfähigen Zuschnitt des Angebots."
|
||||
},
|
||||
{
|
||||
"name": "Überzeugende Angebotsstory",
|
||||
"weight": 1,
|
||||
"description": "Verbindet Kundensituation, Handlungsdruck, Lösung, Nutzen, Vorgehen und Glaubwürdigkeit zu einer konsistenten Entscheidungsgrundlage."
|
||||
}
|
||||
],
|
||||
"description": "Übersetzt einen Kundenbedarf in ein überzeugendes, differenziertes und realistisch lieferbares Leistungsversprechen mit klarer Wirkung, Vorgehensweise und Nutzenargumentation."
|
||||
},
|
||||
{
|
||||
"name": "Workshop Design & Facilitation",
|
||||
"items": [
|
||||
{
|
||||
"name": "Ziel- und Ergebnisdefinition",
|
||||
"weight": 1,
|
||||
"description": "Klärt vorab, welches konkrete Ergebnis, welche Entscheidung oder welcher Arbeitsfortschritt im Workshop erreicht werden soll."
|
||||
},
|
||||
{
|
||||
"name": "Teilnehmer- und Stakeholderdesign",
|
||||
"weight": 1,
|
||||
"description": "Bindet die für Inhalt, Entscheidung und Umsetzung relevanten Personen mit passenden Rollen ein."
|
||||
},
|
||||
{
|
||||
"name": "Dramaturgie und Methodenauswahl",
|
||||
"weight": 1,
|
||||
"description": "Entwickelt eine logische Agenda und wählt Methoden, die Ziel, Teilnehmergruppe, Zeit und Arbeitsmodus unterstützen."
|
||||
},
|
||||
{
|
||||
"name": "Vorbereitung und Arbeitsfähigkeit",
|
||||
"weight": 1,
|
||||
"description": "Stellt Inhalte, Leitfragen, Daten, Materialien, Technik, Rollen und organisatorische Voraussetzungen rechtzeitig bereit."
|
||||
},
|
||||
{
|
||||
"name": "Zielgerichtete Moderation",
|
||||
"weight": 1,
|
||||
"description": "Führt verständlich durch den Prozess, hält Fokus und Zeit und macht Übergänge sowie Arbeitsaufträge klar."
|
||||
},
|
||||
{
|
||||
"name": "Aktivierung und Gruppendynamik",
|
||||
"weight": 1,
|
||||
"description": "Fördert ausgewogene Beteiligung, geht konstruktiv mit Dominanz, Zurückhaltung, Konflikten und Abschweifungen um."
|
||||
},
|
||||
{
|
||||
"name": "Ergebnissicherung und Follow-up",
|
||||
"weight": 1,
|
||||
"description": "Verdichtet Diskussionen, dokumentiert Entscheidungen, Verantwortlichkeiten und nächste Schritte und stellt eine klare Nachbereitung sicher."
|
||||
}
|
||||
],
|
||||
"description": "Konzipiert und moderiert Workshops so, dass relevante Beteiligte fokussiert zusammenarbeiten, belastbare Ergebnisse erzielen und klare Entscheidungen oder nächste Schritte vereinbaren."
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "AI-Readiness",
|
||||
"categories": [
|
||||
{
|
||||
"name": "AI Fundamentals",
|
||||
"items": [
|
||||
{
|
||||
"name": "Grundverständnis generativer KI",
|
||||
"weight": 1,
|
||||
"description": "Erklärt in angemessener Tiefe, wie Modelle, Trainingsdaten, Kontext, Prompts und probabilistische Ausgabe die Ergebnisse beeinflussen."
|
||||
},
|
||||
{
|
||||
"name": "Use-Case-Eignung beurteilen",
|
||||
"weight": 1,
|
||||
"description": "Erkennt, für welche Aufgaben KI sinnvoll ist und wo menschliche Expertise, klassische Analyse oder andere Werkzeuge geeigneter sind."
|
||||
},
|
||||
{
|
||||
"name": "Grenzen und Fehlerbilder erkennen",
|
||||
"weight": 1,
|
||||
"description": "Berücksichtigt insbesondere Halluzinationen, Bias, fehlende Aktualität, Scheingenauigkeit, Kontextverlust und unvollständige Quellenlage."
|
||||
},
|
||||
{
|
||||
"name": "Datenschutz und Vertraulichkeit",
|
||||
"weight": 1,
|
||||
"description": "Behandelt Kunden-, Personen- und Unternehmensdaten entsprechend den geltenden Sicherheits-, Datenschutz- und Vertraulichkeitsvorgaben."
|
||||
},
|
||||
{
|
||||
"name": "Responsible-AI-Verständnis",
|
||||
"weight": 1,
|
||||
"description": "Berücksichtigt ethische, rechtliche, sicherheitsbezogene und gesellschaftliche Auswirkungen beim Einsatz von KI."
|
||||
},
|
||||
{
|
||||
"name": "Qualitätssicherung von KI-Ergebnissen",
|
||||
"weight": 1,
|
||||
"description": "Prüft Ergebnisse fachlich, logisch, methodisch und quellenbezogen und übernimmt keine KI-Ausgabe ungeprüft."
|
||||
}
|
||||
],
|
||||
"description": "Versteht Funktionsweise, Einsatzvoraussetzungen, Chancen, Grenzen und Risiken von KI auf einem für die Beratung angemessenen Niveau und handelt verantwortungsvoll."
|
||||
},
|
||||
{
|
||||
"name": "AI-Augmented Consulting",
|
||||
"items": [
|
||||
{
|
||||
"name": "Zielgerichtete Tool- und Use-Case-Auswahl",
|
||||
"weight": 1,
|
||||
"description": "Wählt KI-Werkzeug und Einsatzform passend zu Aufgabe, Datenlage, Risiko und erwartetem Mehrwert aus."
|
||||
},
|
||||
{
|
||||
"name": "Kontext- und Promptgestaltung",
|
||||
"weight": 1,
|
||||
"description": "Formuliert klare Arbeitsaufträge, stellt relevanten Kontext bereit und verbessert Ergebnisse iterativ durch geeignete Steuerung."
|
||||
},
|
||||
{
|
||||
"name": "KI-gestützte Recherche und Verdichtung",
|
||||
"weight": 1,
|
||||
"description": "Nutzt KI zur Informationsstrukturierung und Synthese, überprüft jedoch Quellen, Aktualität und Vollständigkeit."
|
||||
},
|
||||
{
|
||||
"name": "KI-gestützte Analyse und Hypothesenbildung",
|
||||
"weight": 1,
|
||||
"description": "Nutzt KI zur Entwicklung von Analysefragen, Hypothesen, Strukturierungsansätzen oder Auswertungsoptionen und validiert diese eigenständig."
|
||||
},
|
||||
{
|
||||
"name": "KI-gestützte Storyline- und Deliverable-Erstellung",
|
||||
"weight": 1,
|
||||
"description": "Erstellt mit KI erste Entwürfe für Storylines, Texte, Folien oder Arbeitsmaterialien und veredelt sie fachlich sowie kundenspezifisch."
|
||||
},
|
||||
{
|
||||
"name": "KI-gestützte Meeting- und Workshopvorbereitung",
|
||||
"weight": 1,
|
||||
"description": "Nutzt KI für Interviewleitfäden, Fragen, Szenarien, Zusammenfassungen oder Moderationsvorbereitung und prüft die Praxistauglichkeit."
|
||||
},
|
||||
{
|
||||
"name": "Systematische Workflow-Integration",
|
||||
"weight": 1,
|
||||
"description": "Identifiziert wiederkehrende Arbeitsschritte, integriert KI reproduzierbar und dokumentiert Vorgehen, Qualitätskontrollen und menschliche Entscheidungen angemessen."
|
||||
}
|
||||
],
|
||||
"description": "Integriert KI gezielt und verantwortungsvoll in typische Beratungsaufgaben, um Qualität, Geschwindigkeit und Erkenntnisgewinn zu verbessern, ohne die Verantwortung für Ergebnisse abzugeben."
|
||||
},
|
||||
{
|
||||
"name": "AI Certification",
|
||||
"items": [
|
||||
{
|
||||
"name": "Vorgegebene Basiszertifizierung",
|
||||
"weight": 1,
|
||||
"description": "Hat die für die Rolle oder Entwicklungsstufe vorgeschriebene grundlegende KI-Zertifizierung erfolgreich abgeschlossen."
|
||||
},
|
||||
{
|
||||
"name": "Rollen- oder technologiespezifische Zertifizierung",
|
||||
"weight": 1,
|
||||
"description": "Verfügt über die für Einsatzgebiet, Technologie oder Projektkontext relevanten weiterführenden Nachweise, soweit diese gefordert sind."
|
||||
},
|
||||
{
|
||||
"name": "Aktualität des Nachweises",
|
||||
"weight": 1,
|
||||
"description": "Hält verpflichtende Zertifizierungen, Rezertifizierungen und vorgeschriebene Lernstände aktuell."
|
||||
},
|
||||
{
|
||||
"name": "Nachgewiesener Praxistransfer",
|
||||
"weight": 1,
|
||||
"description": "Kann zentrale Inhalte der Zertifizierung in Übungen oder Assignments korrekt anwenden und deren Grenzen erläutern."
|
||||
}
|
||||
],
|
||||
"description": "Dokumentiert formale, rollenbezogene KI-Qualifikationsnachweise. Da Zertifizierungen primär einen Nachweisstatus und kein beobachtbares Verhalten darstellen, sollten diese Kriterien möglichst als erfüllt, nicht erfüllt oder nicht erforderlich geführt werden."
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Culture-Readiness",
|
||||
"categories": [
|
||||
{
|
||||
"name": "Quality Excellence",
|
||||
"items": [
|
||||
{
|
||||
"name": "Qualitätsanspruch",
|
||||
"weight": 1,
|
||||
"description": "Richtet die eigene Arbeit sichtbar auf fachlich belastbare, verständliche und kundentaugliche Ergebnisse aus."
|
||||
},
|
||||
{
|
||||
"name": "Systematische Qualitätschecks",
|
||||
"weight": 1,
|
||||
"description": "Prüft Inhalte, Zahlen, Logik, Sprache, Quellen, Format und Konsistenz vor Weitergabe anhand geeigneter Kontrollschritte."
|
||||
},
|
||||
{
|
||||
"name": "Prozess- und Standardtreue",
|
||||
"weight": 1,
|
||||
"description": "Kennt relevante Prozesse, Methoden, Templates und Vorgaben und wendet sie zweckmäßig sowie nachvollziehbar an."
|
||||
},
|
||||
{
|
||||
"name": "Reviewfähigkeit",
|
||||
"weight": 1,
|
||||
"description": "Bereitet Arbeitsergebnisse so vor, dass andere sie effizient prüfen können, und arbeitet Reviewhinweise sauber und vollständig ein."
|
||||
},
|
||||
{
|
||||
"name": "Frühzeitige Qualitätssicherung",
|
||||
"weight": 1,
|
||||
"description": "Plant Reviews, Abstimmungen und Prüfschritte rechtzeitig ein, statt Qualität ausschließlich am Ende herzustellen."
|
||||
},
|
||||
{
|
||||
"name": "Integrität und Compliance",
|
||||
"weight": 1,
|
||||
"description": "Handelt ehrlich und regelkonform, macht Unsicherheiten oder Fehler transparent und wahrt Vertraulichkeit sowie relevante fachliche und organisatorische Vorgaben."
|
||||
},
|
||||
{
|
||||
"name": "Kontinuierliche Verbesserung",
|
||||
"weight": 1,
|
||||
"description": "Erkennt wiederkehrende Fehler oder Ineffizienzen und verbessert Vorgehen, Standards oder Hilfsmittel nachhaltig."
|
||||
}
|
||||
],
|
||||
"description": "Verankert Qualität als kontinuierliche Arbeitsweise und sorgt durch Standards, Reviews und kritische Prüfung dafür, dass belastbare Ergebnisse reproduzierbar entstehen."
|
||||
},
|
||||
{
|
||||
"name": "Drive (Extra Mile)",
|
||||
"items": [
|
||||
{
|
||||
"name": "Proaktive Initiative",
|
||||
"weight": 1,
|
||||
"description": "Erkennt Handlungsbedarf oder Chancen und wird selbstständig aktiv, ohne auf detaillierte Einzelaufträge zu warten."
|
||||
},
|
||||
{
|
||||
"name": "Ambitionierter Wirkungsanspruch",
|
||||
"weight": 1,
|
||||
"description": "Strebt nicht nur formale Erledigung, sondern ein erkennbar nützliches und überzeugendes Ergebnis an."
|
||||
},
|
||||
{
|
||||
"name": "Beharrlichkeit bei Hindernissen",
|
||||
"weight": 1,
|
||||
"description": "Verfolgt wichtige Themen trotz Rückschlägen konstruktiv weiter und sucht aktiv nach alternativen Lösungswegen."
|
||||
},
|
||||
{
|
||||
"name": "Mehrwert über den Auftrag hinaus",
|
||||
"weight": 1,
|
||||
"description": "Identifiziert sinnvolle zusätzliche Beiträge, Impulse oder wiederverwendbare Lösungen, ohne Scope, Prioritäten oder Wirtschaftlichkeit aus dem Blick zu verlieren."
|
||||
},
|
||||
{
|
||||
"name": "Anpassungsfähigkeit",
|
||||
"weight": 1,
|
||||
"description": "Bleibt bei veränderten Prioritäten, unvollständigen Informationen oder neuen Anforderungen handlungsfähig und richtet das Vorgehen neu aus."
|
||||
},
|
||||
{
|
||||
"name": "Konstruktive Energie unter Druck",
|
||||
"weight": 1,
|
||||
"description": "Bewahrt auch bei hoher Belastung Fokus, Lösungsorientierung und professionelles Verhalten."
|
||||
}
|
||||
],
|
||||
"description": "Zeigt wirkungsorientierte Initiative, Ausdauer und Gestaltungswillen und leistet bei relevantem Mehrwert bewusst mehr als das formal Geforderte. Bewertet wird nicht die Anzahl der Arbeitsstunden, sondern der zusätzliche Beitrag zum Ergebnis."
|
||||
},
|
||||
{
|
||||
"name": "Ownership",
|
||||
"items": [
|
||||
{
|
||||
"name": "Auftrags- und Ergebnisverständnis",
|
||||
"weight": 1,
|
||||
"description": "Klärt Ziel, Qualitätsmaßstab, Umfang, Rollen, Abhängigkeiten und erwartete Lieferung, bevor die Umsetzung fortschreitet."
|
||||
},
|
||||
{
|
||||
"name": "Eigenständige Arbeitssteuerung",
|
||||
"weight": 1,
|
||||
"description": "Plant, priorisiert und organisiert die eigene Arbeit nachvollziehbar und benötigt nur ein der Entwicklungsstufe angemessenes Maß an Steuerung."
|
||||
},
|
||||
{
|
||||
"name": "Verbindlichkeit und Zuverlässigkeit",
|
||||
"weight": 1,
|
||||
"description": "Hält Zusagen ein und behandelt vereinbarte Termine, Qualitätsziele und Verantwortlichkeiten verbindlich."
|
||||
},
|
||||
{
|
||||
"name": "Fortschritts- und Risikotransparenz",
|
||||
"weight": 1,
|
||||
"description": "Kommuniziert Arbeitsstand, offene Punkte, Abhängigkeiten und mögliche Abweichungen frühzeitig und konkret und vermittelt eine realistische Einschätzung der Zielerreichung."
|
||||
},
|
||||
{
|
||||
"name": "Stufenweises Alignment und Acceptance Management",
|
||||
"weight": 1,
|
||||
"description": "Validiert Annahmen, Konzepte und Zwischenergebnisse rechtzeitig mit den relevanten Kundenvertretern. Sichert ein explizites gemeinsames Verständnis beziehungsweise eine Teilfreigabe als Grundlage für die weitere Bearbeitung und dokumentiert Entscheidungen, Vorbehalte und Änderungen nachvollziehbar."
|
||||
},
|
||||
{
|
||||
"name": "Vorausschauendes Handeln",
|
||||
"weight": 1,
|
||||
"description": "Erkennt Risiken, Engpässe und Entscheidungsbedarfe früh und leitet geeignete Maßnahmen ein."
|
||||
},
|
||||
{
|
||||
"name": "Angemessene Entscheidung und Eskalation",
|
||||
"weight": 1,
|
||||
"description": "Entscheidet im eigenen Verantwortungsbereich selbstständig und eskaliert rechtzeitig mit klarer Sachlage und Lösungsvorschlägen."
|
||||
},
|
||||
{
|
||||
"name": "Konsequenter Abschluss",
|
||||
"weight": 1,
|
||||
"description": "Verfolgt offene Punkte bis zu einem belastbaren Ergebnis, sichert Übergaben und schließt Kommunikations- und Dokumentationsschleifen."
|
||||
}
|
||||
],
|
||||
"description": "Übernimmt End-to-End-Verantwortung für übertragene Aufgaben und angestrebte Ergebnisse, steuert die eigene Arbeit aktiv und schafft jederzeit Transparenz über Fortschritt, Risiken und Handlungsbedarf."
|
||||
},
|
||||
{
|
||||
"name": "Coachability",
|
||||
"items": [
|
||||
{
|
||||
"name": "Aktives Einholen von Feedback",
|
||||
"weight": 1,
|
||||
"description": "Fragt gezielt und rechtzeitig nach Rückmeldung zu Wirkung, Vorgehen und Ergebnis, statt nur auf formale Feedbacktermine zu warten."
|
||||
},
|
||||
{
|
||||
"name": "Offene Feedbackannahme",
|
||||
"weight": 1,
|
||||
"description": "Hört Feedback aufmerksam an, bleibt sachlich und vermeidet vorschnelle Rechtfertigung oder Abwehr."
|
||||
},
|
||||
{
|
||||
"name": "Verständnisklärung",
|
||||
"weight": 1,
|
||||
"description": "Fragt bei unklarer Rückmeldung nach konkreten Situationen, Erwartungen und beobachtbaren Alternativen."
|
||||
},
|
||||
{
|
||||
"name": "Übersetzung in Entwicklungsmaßnahmen",
|
||||
"weight": 1,
|
||||
"description": "Leitet aus Feedback konkrete, realistische und überprüfbare Verhaltens- oder Lernschritte ab."
|
||||
},
|
||||
{
|
||||
"name": "Sichtbarer Praxistransfer",
|
||||
"weight": 1,
|
||||
"description": "Wendet vereinbarte Verbesserungen in folgenden Aufgaben erkennbar an und zeigt nachhaltigen Fortschritt."
|
||||
},
|
||||
{
|
||||
"name": "Selbstreflexion und Lernagilität",
|
||||
"weight": 1,
|
||||
"description": "Analysiert eigene Wirkung, Stärken, Fehler und Muster realistisch und passt Verhalten an neue Situationen an."
|
||||
}
|
||||
],
|
||||
"description": "Nutzt Feedback, Reflexion und neue Erfahrungen aktiv zur Weiterentwicklung und zeigt nachvollziehbare Verhaltensänderungen über mehrere Assignments hinweg."
|
||||
},
|
||||
{
|
||||
"name": "Collaboration",
|
||||
"items": [
|
||||
{
|
||||
"name": "Proaktive Abstimmung",
|
||||
"weight": 1,
|
||||
"description": "Stimmt sich rechtzeitig mit relevanten Beteiligten ab, macht Schnittstellen transparent und vermeidet Informationslücken."
|
||||
},
|
||||
{
|
||||
"name": "Wissens- und Ergebnisteilung",
|
||||
"weight": 1,
|
||||
"description": "Teilt Informationen, Zwischenergebnisse, Erfahrungen und wiederverwendbare Inhalte so, dass das Team wirksam weiterarbeiten kann."
|
||||
},
|
||||
{
|
||||
"name": "Unterstützungsbereitschaft",
|
||||
"weight": 1,
|
||||
"description": "Unterstützt andere konstruktiv und bedarfsgerecht, ohne eigene Verantwortlichkeiten oder gemeinsame Prioritäten zu vernachlässigen."
|
||||
},
|
||||
{
|
||||
"name": "Verlässliches Teamverhalten",
|
||||
"weight": 1,
|
||||
"description": "Hält Teamzusagen ein, respektiert Rollen und schafft durch professionelles Verhalten eine belastbare Arbeitsbasis."
|
||||
},
|
||||
{
|
||||
"name": "Konstruktiver Umgang mit Differenzen",
|
||||
"weight": 1,
|
||||
"description": "Spricht abweichende Sichtweisen sachlich an, hört Gegenargumente an und arbeitet auf eine tragfähige Lösung hin."
|
||||
},
|
||||
{
|
||||
"name": "Einbindung unterschiedlicher Perspektiven",
|
||||
"weight": 1,
|
||||
"description": "Bezieht relevante Erfahrungen und Meinungen aktiv ein und schafft Raum für Beteiligung unabhängig von Rolle oder Hierarchie."
|
||||
},
|
||||
{
|
||||
"name": "Team- und organisationsübergreifende Zusammenarbeit",
|
||||
"weight": 1,
|
||||
"description": "Vernetzt sich bei Bedarf über das unmittelbare Team hinaus und nutzt passende Experten, Communities oder Kontakte für den gemeinsamen Erfolg."
|
||||
}
|
||||
],
|
||||
"description": "Arbeitet verlässlich, respektvoll und lösungsorientiert mit anderen zusammen, stärkt den gemeinsamen Teamerfolg und nutzt unterschiedliche Perspektiven und Fähigkeiten konstruktiv."
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
+85
-14
@@ -1,11 +1,16 @@
|
||||
// ─── Bewertungs-Skala ────────────────────────────────────────────────────────
|
||||
// ─── Bewertungs-Skala (1–10) ─────────────────────────────────────────────────
|
||||
|
||||
export type FeedbackRating =
|
||||
| 'na'
|
||||
| 'not_client_ready'
|
||||
| 'partially_client_ready'
|
||||
| 'nearly_client_ready'
|
||||
| 'client_ready'
|
||||
/** Ganzzahlige Bewertung 1–10. Speicherung: INTEGER; „nicht gesetzt" = null (kein N/A-String). */
|
||||
export type RatingScore = number
|
||||
|
||||
/** Farbband für die 1–10-Skala — Grenzen/Keys editierbar in Config → Skala. */
|
||||
export type RatingBandKey = 'red' | 'orange' | 'lightGreen' | 'darkGreen'
|
||||
|
||||
export interface RatingColorBand {
|
||||
/** Inklusive Obergrenze dieses Bandes (aufsteigend, letzte max muss 10 sein). */
|
||||
max: number
|
||||
key: RatingBandKey
|
||||
}
|
||||
|
||||
// ─── Legacy-Konfiguration (nur noch für Evaluation.tsx) ───────────────────────
|
||||
|
||||
@@ -44,10 +49,45 @@ export interface PhaseTemplate {
|
||||
isRepeatable: boolean
|
||||
hasConversation: boolean
|
||||
hasAssessment: boolean
|
||||
/** Opt-in wie hasConversation/hasAssessment — schaltet den Checkliste-Tab in MeetingView frei. */
|
||||
hasChecklist: boolean
|
||||
criteriaIds: number[]
|
||||
order: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Definition eines Checklisten-Punkts für einen Phasentyp (Config → Assignment-Typen).
|
||||
* Kriterium-Verknüpfung ist bewusst nur bei scope==='perInstitutee' sinnvoll/erlaubt — Kriterien
|
||||
* sind in diesem Modell immer Personen-Kompetenzen, nie Meeting-Kollektiv-Eigenschaften (siehe
|
||||
* CLAUDE.md „Präzisiert bei der Umsetzungsplanung"). Verknüpfte Punkte schreiben direkt in
|
||||
* `Assessment` (keine eigene Antwort-Speicherung), unverknüpfte in `ChecklistResponse`.
|
||||
*/
|
||||
export interface ChecklistItemDef {
|
||||
id?: number
|
||||
phaseTemplateId: number
|
||||
label: string
|
||||
linkedCriterionItemId?: number
|
||||
scope: 'perInstitutee' | 'meetingWide'
|
||||
order: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Antwort auf einen Checklisten-Punkt für dieses Meeting. `criterionItemId` überschreibt pro
|
||||
* Antwort individuell die Konfigurations-Vorgabe aus `ChecklistItemDef.linkedCriterionItemId`
|
||||
* (leer = es gilt die konfigurierte Vorgabe, falls vorhanden) — nur bei effektiv vorhandenem
|
||||
* Kriterium wird nach `Assessment` gespiegelt (siehe CLAUDE.md).
|
||||
*/
|
||||
export interface ChecklistResponse {
|
||||
id?: number
|
||||
meetingInstanceId: number
|
||||
/** Gesetzt bei scope 'perInstitutee', leer bei 'meetingWide'. */
|
||||
instituteeId?: number
|
||||
checklistItemId: number
|
||||
rating: RatingScore | null
|
||||
note: string
|
||||
criterionItemId?: number
|
||||
}
|
||||
|
||||
// ─── Stammdaten ───────────────────────────────────────────────────────────────
|
||||
|
||||
export interface Group {
|
||||
@@ -98,6 +138,8 @@ export interface MeetingInstance {
|
||||
status: 'planned' | 'active' | 'done'
|
||||
generalNotes: string
|
||||
deletedAt?: string
|
||||
/** Kriterium-Zuordnung pro Zeile der allgemeinen Notizen — anders als ConversationEntry.lineTags NICHT an ein Institutee gebunden, gilt für alle Institutees des Assignments. */
|
||||
generalNoteTags?: ConversationLineTag[]
|
||||
}
|
||||
|
||||
// ─── Gesprächs-Zeitleiste ─────────────────────────────────────────────────────
|
||||
@@ -123,22 +165,35 @@ export interface ConversationSkillScore {
|
||||
id?: number
|
||||
conversationEntryId: number
|
||||
criteriaId: number
|
||||
score: FeedbackRating | null
|
||||
score: RatingScore | null
|
||||
}
|
||||
|
||||
// ─── Gesamtbewertung ─────────────────────────────────────────────────────────
|
||||
|
||||
// criteriaId → FeedbackCriterionItem.id (Gesamtbewertung am Meeting-Ende)
|
||||
// criteriaId → FeedbackCriterionItem.id (optionale Detail-Bewertung / Beobachtungsnotiz am Meeting)
|
||||
export interface Assessment {
|
||||
id?: number
|
||||
meetingInstanceId: number
|
||||
instituteeId: number
|
||||
criteriaId: number
|
||||
score: FeedbackRating | null
|
||||
score: RatingScore | null
|
||||
note: string
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Pflicht-Meeting-Bewertung auf Kategorie-Ebene (1–10), unabhängig davon ob alle
|
||||
* Kriterien beobachtet wurden — siehe docs/SCALE_1_TO_10.md.
|
||||
*/
|
||||
export interface MeetingCategoryRating {
|
||||
id?: number
|
||||
meetingInstanceId: number
|
||||
instituteeId: number
|
||||
categoryId: number
|
||||
score: RatingScore | null
|
||||
note?: string
|
||||
}
|
||||
|
||||
// ─── Feedback-Entwurf (Legacy) ────────────────────────────────────────────────
|
||||
|
||||
export interface FeedbackDraft {
|
||||
@@ -162,6 +217,8 @@ export interface FeedbackCategory {
|
||||
dimensionId: number
|
||||
name: string
|
||||
order: number
|
||||
/** Erläuterung, welche Themen/Beobachtungen in diese Kategorie einzahlen — fließt in {{KATEGORIEN_STRUKTUR}} der KI-Prompts ein. */
|
||||
description?: string
|
||||
}
|
||||
|
||||
export interface FeedbackCriterionItem {
|
||||
@@ -172,6 +229,8 @@ export interface FeedbackCriterionItem {
|
||||
order: number
|
||||
/** Konkretisierung, worauf bei diesem Kriterium zu achten ist — fließt in {{KRITERIEN_SCORES}} der KI-Prompts ein. */
|
||||
description?: string
|
||||
/** KI-destillierte, generalisierte Formulierungsmuster (Nebenprodukt des „🏷 Vorschläge analysieren"-Laufs) — fließt in {{GELERNTE_MUSTER}} des Tagging-Prompts ein, wird bei jedem weiteren Lauf überschrieben. */
|
||||
learnedPatternHints?: string
|
||||
}
|
||||
|
||||
export interface AssignmentFeedback {
|
||||
@@ -187,14 +246,16 @@ export interface FeedbackCategoryRating {
|
||||
id?: number
|
||||
assignmentFeedbackId: number
|
||||
feedbackCategoryId: number
|
||||
rating: FeedbackRating
|
||||
rating: RatingScore
|
||||
}
|
||||
|
||||
export interface FeedbackDimensionText {
|
||||
id?: number
|
||||
assignmentFeedbackId: number
|
||||
feedbackDimensionId: number
|
||||
/** DB-Feldname historisch; UI/PDF: Benefits */
|
||||
achievements: string
|
||||
/** DB-Feldname historisch; UI/PDF: Concerns */
|
||||
developmentNeeds: string
|
||||
suggestedAchievements?: string
|
||||
suggestedDevelopmentNeeds?: string
|
||||
@@ -212,8 +273,10 @@ export interface FeedbackCategoryText {
|
||||
id?: number
|
||||
assignmentFeedbackId: number
|
||||
feedbackCategoryId: number
|
||||
text: string
|
||||
suggestedText?: string
|
||||
benefits: string
|
||||
concerns: string
|
||||
suggestedBenefits?: string
|
||||
suggestedConcerns?: string
|
||||
}
|
||||
|
||||
// ─── Legacy-Mappings ──────────────────────────────────────────────────────────
|
||||
@@ -227,7 +290,7 @@ export interface CriterionCategoryMapping {
|
||||
export interface CriterionLevelDescription {
|
||||
id?: number
|
||||
criterionItemId: number
|
||||
rating: FeedbackRating
|
||||
rating: RatingScore
|
||||
text: string
|
||||
}
|
||||
|
||||
@@ -236,4 +299,12 @@ export interface CriterionLevelDescription {
|
||||
export interface AppSettings {
|
||||
id?: number
|
||||
ratingTrendWeightStep: number // 0 = keine Zeitgewichtung, höher = stärkere Gewichtung späterer Meetings
|
||||
/** Verdichtungs-Prompt Stufe B (Dimension aus Kategorie-Ergebnissen), editierbar in Config → KI-Prompts. */
|
||||
defaultDimensionPromptTemplate?: string
|
||||
/** Kategorie-Prompt Stufe A (1 Call pro Kategorie), editierbar in Config → KI-Prompts. */
|
||||
defaultCategoryPromptTemplate?: string
|
||||
/** Prompt-Template für „🏷 Vorschläge analysieren" (selbstlernendes Kriterien-Tagging), editierbar in Config → KI-Prompts. */
|
||||
criterionTaggingPromptTemplate?: string
|
||||
/** Farbbänder der 1–10-Skala (Defaults in constants.ts), editierbar in Config → Skala. */
|
||||
ratingColorBands?: RatingColorBand[]
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { DEFAULT_RATING_COLOR_BANDS, normalizeRatingColorBands } from '../config/constants'
|
||||
import { getOrSeedRatingColorBands } from '../db'
|
||||
import type { RatingColorBand } from '../db/types'
|
||||
|
||||
/** Lädt die konfigurierten Farbbänder einmalig (Config → Skala). */
|
||||
export function useRatingColorBands(): RatingColorBand[] {
|
||||
const [bands, setBands] = useState<RatingColorBand[]>(DEFAULT_RATING_COLOR_BANDS)
|
||||
|
||||
useEffect(() => {
|
||||
getOrSeedRatingColorBands()
|
||||
.then(b => setBands(normalizeRatingColorBands(b)))
|
||||
.catch(() => setBands(DEFAULT_RATING_COLOR_BANDS))
|
||||
}, [])
|
||||
|
||||
return bands
|
||||
}
|
||||
@@ -2,23 +2,47 @@ import { useEffect, useRef, useState } from 'react'
|
||||
import {
|
||||
type FeedbackDimension, type FeedbackDimensionPrompt,
|
||||
loadFeedbackStructure, listFeedbackDimensionPrompts, updateFeedbackDimensionPrompt,
|
||||
resetAllDimensionPromptsToDefault,
|
||||
getOrSeedDefaultDimensionPromptTemplate, saveDefaultDimensionPromptTemplate,
|
||||
getOrSeedDefaultCategoryPromptTemplate, saveDefaultCategoryPromptTemplate,
|
||||
getOrSeedCriterionTaggingPromptTemplate, saveCriterionTaggingPromptTemplate,
|
||||
} from '../db'
|
||||
import { AI_CONFIG } from '../config/constants'
|
||||
import { getAiSettings, saveAiSettings } from '../utils/aiClient'
|
||||
|
||||
export default function AiPromptConfig() {
|
||||
const [dimensions, setDimensions] = useState<FeedbackDimension[]>([])
|
||||
const [prompts, setPrompts] = useState<FeedbackDimensionPrompt[]>([])
|
||||
const [defaultTemplate, setDefaultTemplate] = useState('')
|
||||
const [defaultExpanded, setDefaultExpanded] = useState(false)
|
||||
const [defaultSaved, setDefaultSaved] = useState(false)
|
||||
const [categoryTemplate, setCategoryTemplate] = useState('')
|
||||
const [categoryExpanded, setCategoryExpanded] = useState(false)
|
||||
const [categorySaved, setCategorySaved] = useState(false)
|
||||
const [taggingTemplate, setTaggingTemplate] = useState('')
|
||||
const [taggingExpanded, setTaggingExpanded] = useState(false)
|
||||
const [taggingSaved, setTaggingSaved] = useState(false)
|
||||
const [expanded, setExpanded] = useState<Set<number>>(new Set())
|
||||
const [savedDimId, setSavedDimId] = useState<number | null>(null)
|
||||
const saveTimer = useRef<Map<number, ReturnType<typeof setTimeout>>>(new Map())
|
||||
const [bulkResetMsg, setBulkResetMsg] = useState('')
|
||||
const saveTimer = useRef<Map<number | 'default' | 'category' | 'tagging', ReturnType<typeof setTimeout>>>(new Map())
|
||||
const [aiKey, setAiKey] = useState(getAiSettings().apiKey)
|
||||
const [aiModel, setAiModel] = useState(getAiSettings().model)
|
||||
const [aiSaved, setAiSaved] = useState(false)
|
||||
|
||||
const load = async () => {
|
||||
const [structure, promptRows] = await Promise.all([
|
||||
const [structure, promptRows, defTemplate, catTemplate, taggingTpl] = await Promise.all([
|
||||
loadFeedbackStructure(),
|
||||
listFeedbackDimensionPrompts(),
|
||||
getOrSeedDefaultDimensionPromptTemplate(),
|
||||
getOrSeedDefaultCategoryPromptTemplate(),
|
||||
getOrSeedCriterionTaggingPromptTemplate(),
|
||||
])
|
||||
setDimensions([...structure.dimensions].sort((a, b) => a.order - b.order))
|
||||
setPrompts(promptRows)
|
||||
setDefaultTemplate(defTemplate)
|
||||
setCategoryTemplate(catTemplate)
|
||||
setTaggingTemplate(taggingTpl)
|
||||
}
|
||||
|
||||
useEffect(() => { load() }, [])
|
||||
@@ -41,20 +65,167 @@ export default function AiPromptConfig() {
|
||||
const resetToDefault = async (dimId: number) => {
|
||||
const existing = getPrompt(dimId)
|
||||
if (!existing?.id) return
|
||||
await updateFeedbackDimensionPrompt(existing.id, { promptTemplate: AI_CONFIG.defaultDimensionPromptTemplate })
|
||||
setPrompts(prev => prev.map(p => p.dimensionId === dimId ? { ...p, promptTemplate: AI_CONFIG.defaultDimensionPromptTemplate } : p))
|
||||
await updateFeedbackDimensionPrompt(existing.id, { promptTemplate: defaultTemplate })
|
||||
setPrompts(prev => prev.map(p => p.dimensionId === dimId ? { ...p, promptTemplate: defaultTemplate } : p))
|
||||
}
|
||||
|
||||
const resetAllToDefault = async () => {
|
||||
if (!confirm('Alle Dimension-Prompts wirklich auf den Standard (1–10) setzen? Individuelle Anpassungen gehen verloren.')) return
|
||||
const { updated } = await resetAllDimensionPromptsToDefault()
|
||||
const promptRows = await listFeedbackDimensionPrompts()
|
||||
setPrompts(promptRows)
|
||||
setBulkResetMsg(`${updated} Dimension-Prompt(s) auf Standard gesetzt.`)
|
||||
setTimeout(() => setBulkResetMsg(''), 4000)
|
||||
}
|
||||
|
||||
const saveDefaultTemplate = (value: string) => {
|
||||
setDefaultTemplate(value)
|
||||
const prevTimer = saveTimer.current.get('default')
|
||||
if (prevTimer) clearTimeout(prevTimer)
|
||||
saveTimer.current.set('default', setTimeout(async () => {
|
||||
await saveDefaultDimensionPromptTemplate(value)
|
||||
setDefaultSaved(true)
|
||||
setTimeout(() => setDefaultSaved(false), 2000)
|
||||
}, 600))
|
||||
}
|
||||
|
||||
const saveCategoryTemplate = (value: string) => {
|
||||
setCategoryTemplate(value)
|
||||
const prevTimer = saveTimer.current.get('category')
|
||||
if (prevTimer) clearTimeout(prevTimer)
|
||||
saveTimer.current.set('category', setTimeout(async () => {
|
||||
await saveDefaultCategoryPromptTemplate(value)
|
||||
setCategorySaved(true)
|
||||
setTimeout(() => setCategorySaved(false), 2000)
|
||||
}, 600))
|
||||
}
|
||||
|
||||
const saveTaggingTemplate = (value: string) => {
|
||||
setTaggingTemplate(value)
|
||||
const prevTimer = saveTimer.current.get('tagging')
|
||||
if (prevTimer) clearTimeout(prevTimer)
|
||||
saveTimer.current.set('tagging', setTimeout(async () => {
|
||||
await saveCriterionTaggingPromptTemplate(value)
|
||||
setTaggingSaved(true)
|
||||
setTimeout(() => setTaggingSaved(false), 2000)
|
||||
}, 600))
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<h2 className="text-lg font-bold text-gray-800">KI-Prompts je Dimension</h2>
|
||||
<h2 className="text-lg font-bold text-gray-800">KI-Feedback (Kaskade)</h2>
|
||||
<p className="text-sm text-gray-500 mt-1">
|
||||
Jede Dimension bekommt bei der KI-Feedback-Generierung einen eigenen, separaten Call. Der Prompt-Text
|
||||
ist frei editierbar und wird bei neuen Dimensionen automatisch mit einem Standard-Prompt vorbelegt.
|
||||
Stufe A: ein Call pro Kategorie (globaler Kategorie-Prompt). Stufe B: ein Call pro Dimension
|
||||
(Verdichtung aus Kategorie-Ergebnissen — pro Dimension editierbar unten).
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-xl border border-blue-100 shadow-sm p-4 space-y-3">
|
||||
<div className="text-sm font-semibold text-blue-800">OpenRouter API-Key</div>
|
||||
<p className="text-xs text-gray-500">
|
||||
Wird lokal im Browser gespeichert (<span className="font-mono">localStorage</span>) — nötig für
|
||||
KI-Feedback und „Vorschläge analysieren". Key von{' '}
|
||||
<span className="font-mono">openrouter.ai</span>.
|
||||
</p>
|
||||
<input
|
||||
type="password"
|
||||
className="w-full border border-blue-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-brand"
|
||||
placeholder="sk-or-..."
|
||||
value={aiKey}
|
||||
onChange={e => setAiKey(e.target.value)}
|
||||
/>
|
||||
<select
|
||||
className="w-full border border-blue-200 rounded-lg px-3 py-2 text-sm bg-white"
|
||||
value={aiModel}
|
||||
onChange={e => setAiModel(e.target.value)}>
|
||||
<option value="openai/gpt-4o-mini">GPT-4o mini (günstig)</option>
|
||||
<option value="openai/gpt-4o">GPT-4o</option>
|
||||
<option value="anthropic/claude-sonnet-4-5">Claude Sonnet 4.5</option>
|
||||
<option value="anthropic/claude-haiku-4-5">Claude Haiku 4.5 (schnell)</option>
|
||||
<option value="google/gemini-flash-1.5">Gemini Flash 1.5</option>
|
||||
</select>
|
||||
<button
|
||||
onClick={() => {
|
||||
saveAiSettings(aiKey, aiModel)
|
||||
setAiSaved(true)
|
||||
setTimeout(() => setAiSaved(false), 2000)
|
||||
}}
|
||||
className="w-full py-2.5 bg-brand text-white rounded-xl text-sm font-semibold">
|
||||
API-Key speichern
|
||||
</button>
|
||||
{aiSaved && (
|
||||
<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>
|
||||
|
||||
{/* Kategorie-Prompt Stufe A */}
|
||||
<div className="bg-white rounded-xl border border-green-100 shadow-sm overflow-hidden">
|
||||
<button
|
||||
onClick={() => setCategoryExpanded(p => !p)}
|
||||
className="w-full flex items-center justify-between p-3 bg-green-50 border-b border-green-100 text-left">
|
||||
<span className="font-semibold text-sm text-green-800">Stufe A — Kategorie-Prompt (1 Call pro Kategorie)</span>
|
||||
<span className="text-xs text-green-400">{categoryExpanded ? '▲' : '▼'}</span>
|
||||
</button>
|
||||
{categoryExpanded && (
|
||||
<div className="p-3 space-y-2">
|
||||
<p className="text-xs text-gray-500">
|
||||
Wird für jede Kategorie einzeln aufgerufen. Der Trend-Vorschlag aus Meetings wird im Prompt
|
||||
vorgegeben; die KI bestätigt oder passt maximal ±1 an.
|
||||
</p>
|
||||
<textarea
|
||||
className="w-full border border-gray-200 rounded-lg px-3 py-2 text-xs font-mono focus:outline-none focus:border-brand min-h-[280px]"
|
||||
value={categoryTemplate}
|
||||
onChange={e => saveCategoryTemplate(e.target.value)}
|
||||
/>
|
||||
{categorySaved && <span className="text-xs text-green-600 font-medium">Gespeichert.</span>}
|
||||
<div className="grid gap-1.5 pt-2">
|
||||
{AI_CONFIG.categoryPromptPlaceholders.map(p => (
|
||||
<div key={p.token} className="text-xs text-gray-600 flex gap-2">
|
||||
<code className="bg-white border border-gray-200 rounded px-1.5 py-0.5 text-brand font-mono flex-shrink-0">{p.token}</code>
|
||||
<span>{p.description}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Standard-Prompt Stufe B */}
|
||||
<div className="bg-white rounded-xl border border-blue-100 shadow-sm overflow-hidden">
|
||||
<button
|
||||
onClick={() => setDefaultExpanded(p => !p)}
|
||||
className="w-full flex items-center justify-between p-3 bg-blue-50 border-b border-blue-100 text-left">
|
||||
<span className="font-semibold text-sm text-blue-800">Stufe B — Dimensions-Verdichtung (Basis für neue Dimensionen & „Zurücksetzen")</span>
|
||||
<span className="text-xs text-blue-400">{defaultExpanded ? '▲' : '▼'}</span>
|
||||
</button>
|
||||
{defaultExpanded && (
|
||||
<div className="p-3 space-y-2">
|
||||
<p className="text-xs text-gray-500">
|
||||
Input sind nur die Kategorie-Ergebnisse aus Stufe A — kein Rohprotokoll. Wird beim Anlegen
|
||||
neuer Dimensionen automatisch übernommen und ist die Basis für „Auf Standard zurücksetzen".
|
||||
</p>
|
||||
<textarea
|
||||
className="w-full border border-gray-200 rounded-lg px-3 py-2 text-xs font-mono focus:outline-none focus:border-brand min-h-[320px]"
|
||||
value={defaultTemplate}
|
||||
onChange={e => saveDefaultTemplate(e.target.value)}
|
||||
/>
|
||||
{defaultSaved && <span className="text-xs text-green-600 font-medium">Gespeichert.</span>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 flex-wrap">
|
||||
<button
|
||||
onClick={resetAllToDefault}
|
||||
className="text-xs bg-amber-50 hover:bg-amber-100 text-amber-800 border border-amber-200 px-3 py-1.5 rounded-lg font-medium">
|
||||
Alle Dimension-Prompts auf Standard (Stufe B) setzen
|
||||
</button>
|
||||
{bulkResetMsg && <span className="text-xs text-green-600 font-medium">{bulkResetMsg}</span>}
|
||||
</div>
|
||||
|
||||
{/* Platzhalter-Legende */}
|
||||
<div className="bg-gray-50 rounded-xl border border-gray-100 p-4 space-y-2">
|
||||
<div className="text-xs font-semibold text-gray-500 uppercase tracking-wide">Verfügbare Platzhalter</div>
|
||||
@@ -68,6 +239,45 @@ export default function AiPromptConfig() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h2 className="text-lg font-bold text-gray-800">KI-Prompt: Kriterien-Zuordnungsvorschläge</h2>
|
||||
<p className="text-sm text-gray-500 mt-1">
|
||||
Wird durch den „🏷 Vorschläge analysieren"-Button im Protokoll ausgelöst — ein gebündelter Call pro
|
||||
Protokoll-Ansicht, nicht pro Zeile. Lernt aus bereits vergebenen Kriterium-Zuordnungen.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="bg-white rounded-xl border border-indigo-100 shadow-sm overflow-hidden">
|
||||
<button
|
||||
onClick={() => setTaggingExpanded(p => !p)}
|
||||
className="w-full flex items-center justify-between p-3 bg-indigo-50 border-b border-indigo-100 text-left">
|
||||
<span className="font-semibold text-sm text-indigo-800">🏷 Tagging-Prompt</span>
|
||||
<span className="text-xs text-indigo-400">{taggingExpanded ? '▲' : '▼'}</span>
|
||||
</button>
|
||||
{taggingExpanded && (
|
||||
<div className="p-3 space-y-2">
|
||||
<textarea
|
||||
className="w-full border border-gray-200 rounded-lg px-3 py-2 text-xs font-mono focus:outline-none focus:border-brand min-h-[320px]"
|
||||
value={taggingTemplate}
|
||||
onChange={e => saveTaggingTemplate(e.target.value)}
|
||||
/>
|
||||
{taggingSaved && <span className="text-xs text-green-600 font-medium">Gespeichert.</span>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="bg-gray-50 rounded-xl border border-gray-100 p-4 space-y-2">
|
||||
<div className="text-xs font-semibold text-gray-500 uppercase tracking-wide">Platzhalter im Tagging-Prompt</div>
|
||||
<div className="grid gap-1.5">
|
||||
{AI_CONFIG.criterionTaggingPromptPlaceholders.map(p => (
|
||||
<div key={p.token} className="text-xs text-gray-600 flex gap-2">
|
||||
<code className="bg-white border border-gray-200 rounded px-1.5 py-0.5 text-brand font-mono flex-shrink-0">{p.token}</code>
|
||||
<span>{p.description}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Dimensionen */}
|
||||
{dimensions.map(dim => {
|
||||
const isOpen = expanded.has(dim.id!)
|
||||
|
||||
@@ -1,25 +1,22 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useNavigate, useParams } from 'react-router-dom'
|
||||
import {
|
||||
type Assignment, type AssignmentType, type PhaseTemplate, type MeetingInstance, type Consultant, type Assessment, type FeedbackRating, type FeedbackCategory, type FeedbackCriterionItem,
|
||||
type Assignment, type AssignmentType, type PhaseTemplate, type MeetingInstance, type Consultant, type Assessment, type RatingScore, type FeedbackCategory, type FeedbackCriterionItem,
|
||||
getAssignment, getAssignmentType,
|
||||
listPhaseTemplatesForType,
|
||||
listMeetingInstancesForAssignment, addMeetingInstance, softDeleteMeetingInstance, restoreMeetingInstance, hardDeleteMeetingInstance,
|
||||
getConsultantsByIds,
|
||||
listAssessmentsForMeetings,
|
||||
listFeedbackCategoriesAll, listFeedbackCriterionItemsAll, filterVisibleFeedbackStructure,
|
||||
listMeetingCategoryRatingsForMeetings,
|
||||
loadFeedbackStructure, resolveVisibleStructure,
|
||||
isAssignmentFeedbackComplete, softDeleteAssignment, archiveAssignment,
|
||||
} from '../db'
|
||||
import { exportMeetingAsMarkdown, exportMeetingAsJson, downloadFile } from '../utils/meetingExport'
|
||||
import { weightedAverageRating } from '../utils/ratingTrend'
|
||||
|
||||
const RATING_BG: Record<FeedbackRating, string> = {
|
||||
na: 'bg-gray-400 text-white',
|
||||
not_client_ready: 'bg-red-500 text-white',
|
||||
partially_client_ready: 'bg-orange-500 text-white',
|
||||
nearly_client_ready: 'bg-green-400 text-white',
|
||||
client_ready: 'bg-green-700 text-white',
|
||||
}
|
||||
import { exportAssignmentReportPdf, exportInstituteeFeedbackPdf } from '../utils/pdfExport'
|
||||
import { resolveScoreStyle } from '../config/constants'
|
||||
import { resolveCategoryChipScore } from '../utils/meetingCategoryScore'
|
||||
import { useRatingColorBands } from '../hooks/useRatingColorBands'
|
||||
import type { MeetingCategoryRating } from '../db'
|
||||
|
||||
interface PhaseRow {
|
||||
template: PhaseTemplate
|
||||
@@ -43,11 +40,14 @@ export default function AssignmentDetail() {
|
||||
const [confirmSoftDelete, setConfirmSoftDelete] = useState<number | null>(null)
|
||||
const [confirmHardDelete, setConfirmHardDelete] = useState<number | null>(null)
|
||||
const [allAssessments, setAllAssessments] = useState<Assessment[]>([])
|
||||
const [categoryRatings, setCategoryRatings] = useState<MeetingCategoryRating[]>([])
|
||||
const [fbCategories, setFbCategories] = useState<FeedbackCategory[]>([])
|
||||
const [fbItems, setFbItems] = useState<FeedbackCriterionItem[]>([])
|
||||
const colorBands = useRatingColorBands()
|
||||
const [feedbackComplete, setFeedbackComplete] = useState(false)
|
||||
const [confirmAssignmentTrash, setConfirmAssignmentTrash] = useState(false)
|
||||
const [confirmAssignmentArchive, setConfirmAssignmentArchive] = useState(false)
|
||||
const [pdfExportingKey, setPdfExportingKey] = useState<string | null>(null)
|
||||
|
||||
const load = async () => {
|
||||
const a = await getAssignment(assignmentId)
|
||||
@@ -73,16 +73,17 @@ export default function AssignmentDetail() {
|
||||
instances: active.filter(i => i.phaseTemplateId === t.id).sort((a, b) => a.phaseIndex - b.phaseIndex),
|
||||
})))
|
||||
const instIds = active.map(i => i.id!)
|
||||
const [asmts, allCats, allItems, aType2] = await Promise.all([
|
||||
const [asmts, catRatings, structure, aType2] = await Promise.all([
|
||||
listAssessmentsForMeetings(instIds),
|
||||
listFeedbackCategoriesAll(),
|
||||
listFeedbackCriterionItemsAll(),
|
||||
listMeetingCategoryRatingsForMeetings(instIds),
|
||||
loadFeedbackStructure(),
|
||||
getAssignmentType(a.assignmentTypeId),
|
||||
])
|
||||
setAllAssessments(asmts)
|
||||
const { categories: visibleCats, items: visibleItems } = filterVisibleFeedbackStructure(allCats, allItems, aType2?.criteriaIds)
|
||||
setFbItems(visibleItems)
|
||||
setFbCategories(visibleCats)
|
||||
setCategoryRatings(catRatings)
|
||||
const visible = resolveVisibleStructure(structure.dimensions, structure.categories, structure.items, aType2?.criteriaIds)
|
||||
setFbItems(visible.items)
|
||||
setFbCategories(visible.categories)
|
||||
}
|
||||
|
||||
useEffect(() => { load() }, [assignmentId])
|
||||
@@ -147,6 +148,25 @@ export default function AssignmentDetail() {
|
||||
navigate('/')
|
||||
}
|
||||
|
||||
const handleExportReportPdf = async () => {
|
||||
setPdfExportingKey('report')
|
||||
try {
|
||||
await exportAssignmentReportPdf(assignmentId)
|
||||
} finally {
|
||||
setPdfExportingKey(null)
|
||||
}
|
||||
}
|
||||
|
||||
const handleExportInstituteeFeedbackPdf = async (instituteeId: number) => {
|
||||
const key = `inst-${instituteeId}`
|
||||
setPdfExportingKey(key)
|
||||
try {
|
||||
await exportInstituteeFeedbackPdf(assignmentId, instituteeId)
|
||||
} finally {
|
||||
setPdfExportingKey(null)
|
||||
}
|
||||
}
|
||||
|
||||
const statusBadge = (status: MeetingInstance['status']) => {
|
||||
const map = {
|
||||
planned: 'bg-yellow-100 text-yellow-700',
|
||||
@@ -176,6 +196,13 @@ export default function AssignmentDetail() {
|
||||
className="text-xs px-3 py-1.5 border border-gray-200 rounded-lg text-gray-500 hover:border-brand hover:text-brand transition">
|
||||
📜 Gesamtprotokoll
|
||||
</button>
|
||||
<button
|
||||
onClick={handleExportReportPdf}
|
||||
disabled={pdfExportingKey === 'report'}
|
||||
title="Gesamtprotokoll + Feedback als PDF"
|
||||
className="text-xs px-3 py-1.5 border border-gray-200 rounded-lg text-gray-500 hover:border-brand hover:text-brand transition disabled:opacity-50">
|
||||
{pdfExportingKey === 'report' ? '⏳' : '⬇ PDF'}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => navigate(`/assignment/${assignmentId}/edit`)}
|
||||
className="text-xs px-3 py-1.5 border border-gray-200 rounded-lg text-gray-500 hover:border-brand hover:text-brand transition">
|
||||
@@ -269,11 +296,20 @@ export default function AssignmentDetail() {
|
||||
<span className="text-sm text-amber-800 font-medium">Feedback-Entwürfe</span>
|
||||
<div className="flex gap-2 flex-wrap">
|
||||
{institutees.map(c => (
|
||||
<button key={c.id}
|
||||
onClick={() => navigate(`/assignment/${assignmentId}/feedback/${c.id}`)}
|
||||
className="text-xs bg-amber-600 text-white px-3 py-1 rounded-lg">
|
||||
{c.firstName}
|
||||
</button>
|
||||
<div key={c.id} className="flex items-center gap-1">
|
||||
<button
|
||||
onClick={() => navigate(`/assignment/${assignmentId}/feedback/${c.id}`)}
|
||||
className="text-xs bg-amber-600 text-white px-3 py-1 rounded-lg">
|
||||
{c.firstName}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleExportInstituteeFeedbackPdf(c.id!)}
|
||||
disabled={pdfExportingKey === `inst-${c.id}`}
|
||||
title={`Feedback für ${c.firstName} als PDF`}
|
||||
className="text-xs bg-amber-100 text-amber-700 px-2 py-1 rounded-lg disabled:opacity-50">
|
||||
{pdfExportingKey === `inst-${c.id}` ? '⏳' : '⬇'}
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
@@ -323,24 +359,24 @@ export default function AssignmentDetail() {
|
||||
{institutees.map(c => {
|
||||
const chips = fbCategories.map(cat => {
|
||||
const catItems = fbItems.filter(i => i.categoryId === cat.id)
|
||||
const mode = weightedAverageRating(catItems, itemId => {
|
||||
const asmt = allAssessments.find(a =>
|
||||
a.meetingInstanceId === inst.id &&
|
||||
a.instituteeId === c.id &&
|
||||
a.criteriaId === itemId
|
||||
)
|
||||
return asmt?.score ?? null
|
||||
const mode = resolveCategoryChipScore({
|
||||
meetingId: inst.id!,
|
||||
instituteeId: c.id!,
|
||||
categoryId: cat.id!,
|
||||
categoryRatings,
|
||||
assessments: allAssessments,
|
||||
catItems,
|
||||
})
|
||||
return mode ? { cat, mode } : null
|
||||
}).filter(Boolean) as { cat: FeedbackCategory; mode: FeedbackRating }[]
|
||||
}).filter(Boolean) as { cat: FeedbackCategory; mode: RatingScore }[]
|
||||
|
||||
if (chips.length === 0) return null
|
||||
return (
|
||||
<div key={c.id} className="mt-1">
|
||||
<span className="text-xs text-gray-400 mr-1">{c.firstName}:</span>
|
||||
{chips.map(({ cat, mode }) => (
|
||||
<span key={cat.id} className={`inline-block text-xs px-2 py-0.5 rounded font-medium mr-1 ${RATING_BG[mode]}`}>
|
||||
{cat.name}
|
||||
<span key={cat.id} className={`inline-block text-xs px-2 py-0.5 rounded font-medium mr-1 tabular-nums ${resolveScoreStyle(mode, colorBands).active}`}>
|
||||
{cat.name} {mode}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -10,27 +10,38 @@ import {
|
||||
type FeedbackCategoryRating,
|
||||
type FeedbackDimensionText,
|
||||
type FeedbackCategoryText,
|
||||
type FeedbackRating,
|
||||
type RatingScore,
|
||||
type MeetingInstance,
|
||||
type Assessment,
|
||||
type ConversationEntry,
|
||||
getAssignment, getConsultant,
|
||||
loadFeedbackStructure,
|
||||
getAssignment, getConsultant, getAssignmentType,
|
||||
loadFeedbackStructure, resolveVisibleStructure,
|
||||
listDoneMeetingsChronological,
|
||||
listAssessmentsForMeetings, listConversationEntriesForMeetings,
|
||||
listMeetingCategoryRatingsForMeetings,
|
||||
getRatingTrendWeightStep,
|
||||
getOrCreateAssignmentFeedback, updateAssignmentFeedback,
|
||||
listFeedbackCategoryRatings, addFeedbackCategoryRating, updateFeedbackCategoryRating,
|
||||
listFeedbackCategoryRatings, addFeedbackCategoryRating, updateFeedbackCategoryRating, deleteFeedbackCategoryRating,
|
||||
listFeedbackDimensionTexts, getFeedbackDimensionText, addFeedbackDimensionText, updateFeedbackDimensionText,
|
||||
listFeedbackCategoryTexts, getFeedbackCategoryText, addFeedbackCategoryText, updateFeedbackCategoryText,
|
||||
getFeedbackDimensionPrompt,
|
||||
getOrSeedDefaultCategoryPromptTemplate,
|
||||
getOrSeedDefaultDimensionPromptTemplate,
|
||||
} from '../db'
|
||||
import { RATING_OPTIONS, AI_CONFIG } from '../config/constants'
|
||||
import { buildGroupMeetingScores, computeTrend, numberToRating, type TrendResult } from '../utils/ratingTrend'
|
||||
import { buildDimensionPromptContext, renderDimensionPrompt, parseDimensionAiResponse } from '../utils/aiPrompt'
|
||||
|
||||
const ratingColor = (r: FeedbackRating | undefined) =>
|
||||
RATING_OPTIONS.find(x => x.value === r)?.color ?? 'bg-gray-50 text-gray-400 border-gray-200'
|
||||
import {
|
||||
AI_CONFIG, isValidRatingScore, resolveScoreStyle,
|
||||
} from '../config/constants'
|
||||
import { ScorePicker } from '../components/ScorePicker'
|
||||
import { useRatingColorBands } from '../hooks/useRatingColorBands'
|
||||
import { resolveCategoryChipScore } from '../utils/meetingCategoryScore'
|
||||
import { computeTrend, numberToRating, type MeetingScorePoint, type TrendResult } from '../utils/ratingTrend'
|
||||
import {
|
||||
buildDimensionCondenseContext, buildCategoryPromptContext,
|
||||
renderPrompt, parseCategoryAiResponse, parseDimensionCondenseResponse,
|
||||
type CategoryCondenseEntry,
|
||||
} from '../utils/aiPrompt'
|
||||
import { getAiSettings, saveAiSettings, callOpenRouter } from '../utils/aiClient'
|
||||
import { exportInstituteeFeedbackPdf } from '../utils/pdfExport'
|
||||
|
||||
const trendArrow = (trend: TrendResult['trend']) => {
|
||||
if (trend === 'up') return <span title="Verbesserung über die Laufzeit">↑</span>
|
||||
@@ -38,18 +49,6 @@ const trendArrow = (trend: TrendResult['trend']) => {
|
||||
return null
|
||||
}
|
||||
|
||||
function getAiSettings() {
|
||||
return {
|
||||
apiKey: localStorage.getItem(AI_CONFIG.localStorageKeyApiKey) ?? '',
|
||||
model: localStorage.getItem(AI_CONFIG.localStorageKeyModel) ?? AI_CONFIG.defaultModel,
|
||||
}
|
||||
}
|
||||
|
||||
function saveAiSettings(apiKey: string, model: string) {
|
||||
localStorage.setItem(AI_CONFIG.localStorageKeyApiKey, apiKey)
|
||||
localStorage.setItem(AI_CONFIG.localStorageKeyModel, model)
|
||||
}
|
||||
|
||||
/** Klein gehaltene KI-Vorschlag-Box mit Übernehmen/Verwerfen — gleiche Bedienlogik überall im Feedback. */
|
||||
function AiSuggestionBox({ text, onAccept, onDiscard }: { text: string; onAccept: () => void; onDiscard: () => void }) {
|
||||
return (
|
||||
@@ -77,6 +76,7 @@ export default function AssignmentFeedbackPage() {
|
||||
const navigate = useNavigate()
|
||||
const assignmentId = Number(id)
|
||||
const instId = Number(instituteeId)
|
||||
const colorBands = useRatingColorBands()
|
||||
|
||||
const [assignment, setAssignment] = useState<Assignment | null>(null)
|
||||
const [institutee, setInstitutee] = useState<Consultant | null>(null)
|
||||
@@ -96,6 +96,8 @@ export default function AssignmentFeedbackPage() {
|
||||
const [generationProgress, setGenerationProgress] = useState('')
|
||||
const [aiError, setAiError] = useState('')
|
||||
const [dimensionErrors, setDimensionErrors] = useState<Record<number, string>>({})
|
||||
const [categoryErrors, setCategoryErrors] = useState<Record<string, string>>({})
|
||||
const [exportingPdf, setExportingPdf] = useState(false)
|
||||
const [previewOpen, setPreviewOpen] = useState<Set<number>>(new Set())
|
||||
const [previewText, setPreviewText] = useState<Record<number, string>>({})
|
||||
const [previewLoading, setPreviewLoading] = useState<Set<number>>(new Set())
|
||||
@@ -109,25 +111,44 @@ export default function AssignmentFeedbackPage() {
|
||||
])
|
||||
setAssignment(a ?? null)
|
||||
setInstitutee(cons ?? null)
|
||||
setDimensions(structure.dimensions)
|
||||
setCategories(structure.categories)
|
||||
setItems(structure.items)
|
||||
const { categories: cats, items: itms } = structure
|
||||
|
||||
const aType = a ? await getAssignmentType(a.assignmentTypeId) : undefined
|
||||
const visible = resolveVisibleStructure(
|
||||
structure.dimensions,
|
||||
structure.categories,
|
||||
structure.items,
|
||||
aType?.criteriaIds,
|
||||
)
|
||||
setDimensions(visible.dimensions)
|
||||
setCategories(visible.categories)
|
||||
setItems(visible.items)
|
||||
const { categories: cats, items: itms } = visible
|
||||
|
||||
const meetings = await listDoneMeetingsChronological(assignmentId)
|
||||
const meetingIds = meetings.map(m => m.id!)
|
||||
const [meetingAssessments, weightStep] = await Promise.all([
|
||||
const [meetingAssessments, categoryRatings, weightStep] = await Promise.all([
|
||||
listAssessmentsForMeetings(meetingIds),
|
||||
listMeetingCategoryRatingsForMeetings(meetingIds),
|
||||
getRatingTrendWeightStep(),
|
||||
])
|
||||
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)
|
||||
const history: MeetingScorePoint[] = []
|
||||
for (const meeting of meetings) {
|
||||
const score = resolveCategoryChipScore({
|
||||
meetingId: meeting.id!,
|
||||
instituteeId: instId,
|
||||
categoryId: cat.id!,
|
||||
categoryRatings,
|
||||
assessments: instAssessments,
|
||||
catItems,
|
||||
})
|
||||
if (score === null) continue
|
||||
history.push({ meetingId: meeting.id!, date: meeting.date, score })
|
||||
}
|
||||
trends.set(cat.id!, computeTrend(history, weightStep))
|
||||
}
|
||||
setCatTrends(trends)
|
||||
@@ -146,17 +167,23 @@ export default function AssignmentFeedbackPage() {
|
||||
setCategoryTexts(catTxts)
|
||||
}
|
||||
|
||||
// Alle Dimensionen initial expandiert
|
||||
setExpanded(new Set(structure.dimensions.map(d => d.id!)))
|
||||
setExpanded(new Set(visible.dimensions.map(d => d.id!)))
|
||||
}, [assignmentId, instId])
|
||||
|
||||
useEffect(() => { load() }, [load])
|
||||
|
||||
// ── Rating setzen ─────────────────────────────────────────────────────────
|
||||
|
||||
const setRating = async (categoryId: number, rating: FeedbackRating) => {
|
||||
const setRating = async (categoryId: number, rating: RatingScore | null) => {
|
||||
if (!feedback?.id) return
|
||||
const existing = ratings.find(r => r.feedbackCategoryId === categoryId)
|
||||
if (rating === null) {
|
||||
if (existing?.id) {
|
||||
await deleteFeedbackCategoryRating(existing.id)
|
||||
setRatings(prev => prev.filter(r => r.feedbackCategoryId !== categoryId))
|
||||
}
|
||||
return
|
||||
}
|
||||
if (existing?.id) {
|
||||
await updateFeedbackCategoryRating(existing.id, { rating })
|
||||
setRatings(prev => prev.map(r => r.feedbackCategoryId === categoryId ? { ...r, rating } : r))
|
||||
@@ -168,8 +195,8 @@ export default function AssignmentFeedbackPage() {
|
||||
}
|
||||
}
|
||||
|
||||
const getRating = (categoryId: number): FeedbackRating | undefined =>
|
||||
ratings.find(r => r.feedbackCategoryId === categoryId)?.rating
|
||||
const getRating = (categoryId: number): RatingScore | null =>
|
||||
ratings.find(r => r.feedbackCategoryId === categoryId)?.rating ?? null
|
||||
|
||||
// ── Dimension-Text speichern (debounced) ──────────────────────────────────
|
||||
|
||||
@@ -201,15 +228,15 @@ export default function AssignmentFeedbackPage() {
|
||||
const getDimText = (dimId: number) =>
|
||||
dimTexts.find(t => t.feedbackDimensionId === dimId)
|
||||
|
||||
const appendTrendSentence = (dimId: number, cat: FeedbackCategory, trend: TrendResult) => {
|
||||
const appendTrendSentence = (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 field = trend.trend === 'up' ? 'benefits' : 'concerns'
|
||||
const firstLabel = String(numberToRating(trend.history[0].score) ?? trend.history[0].score.toFixed(1))
|
||||
const lastLabel = String(numberToRating(trend.history[trend.history.length - 1].score) ?? trend.history[trend.history.length - 1].score.toFixed(1))
|
||||
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)
|
||||
const existing = getCategoryText(cat.id!)?.[field] ?? ''
|
||||
saveCategoryField(cat.id!, field, existing ? `${existing}\n${sentence}` : sentence)
|
||||
}
|
||||
|
||||
const acceptDimSuggestion = (dimId: number, field: 'achievements' | 'developmentNeeds') => {
|
||||
@@ -229,42 +256,55 @@ export default function AssignmentFeedbackPage() {
|
||||
if (existing?.id) await updateFeedbackDimensionText(existing.id, { [sugField]: '' })
|
||||
}
|
||||
|
||||
// ── Kategorie-Text speichern (debounced) ──────────────────────────────────
|
||||
// ── Kategorie Benefits/Concerns speichern (debounced) ─────────────────────
|
||||
|
||||
const getCategoryText = (catId: number) => categoryTexts.find(t => t.feedbackCategoryId === catId)
|
||||
|
||||
const saveCategoryText = (catId: number, value: string) => {
|
||||
const saveCategoryField = (catId: number, field: 'benefits' | 'concerns', value: string) => {
|
||||
setCategoryTexts(prev => {
|
||||
const existing = prev.find(t => t.feedbackCategoryId === catId)
|
||||
if (existing) return prev.map(t => t.feedbackCategoryId === catId ? { ...t, text: value } : t)
|
||||
return [...prev, { assignmentFeedbackId: feedback?.id ?? 0, feedbackCategoryId: catId, text: value }]
|
||||
if (existing) return prev.map(t => t.feedbackCategoryId === catId ? { ...t, [field]: value } : t)
|
||||
return [...prev, {
|
||||
assignmentFeedbackId: feedback?.id ?? 0,
|
||||
feedbackCategoryId: catId,
|
||||
benefits: '',
|
||||
concerns: '',
|
||||
[field]: value,
|
||||
}]
|
||||
})
|
||||
const key = `cat-${catId}`
|
||||
const key = `cat-${catId}-${field}`
|
||||
const prev = saveTimer.current.get(key)
|
||||
if (prev) clearTimeout(prev)
|
||||
saveTimer.current.set(key, setTimeout(async () => {
|
||||
if (!feedback?.id) return
|
||||
const existing = await getFeedbackCategoryText(feedback.id, catId)
|
||||
if (existing?.id) {
|
||||
await updateFeedbackCategoryText(existing.id, { text: value })
|
||||
await updateFeedbackCategoryText(existing.id, { [field]: value })
|
||||
} else {
|
||||
await addFeedbackCategoryText({ assignmentFeedbackId: feedback.id, feedbackCategoryId: catId, text: value })
|
||||
await addFeedbackCategoryText({
|
||||
assignmentFeedbackId: feedback.id,
|
||||
feedbackCategoryId: catId,
|
||||
benefits: field === 'benefits' ? value : '',
|
||||
concerns: field === 'concerns' ? value : '',
|
||||
})
|
||||
}
|
||||
}, 600))
|
||||
}
|
||||
|
||||
const acceptCategorySuggestion = (catId: number) => {
|
||||
const value = getCategoryText(catId)?.suggestedText
|
||||
const acceptCategorySuggestion = (catId: number, field: 'benefits' | 'concerns') => {
|
||||
const row = getCategoryText(catId)
|
||||
const value = field === 'benefits' ? row?.suggestedBenefits : row?.suggestedConcerns
|
||||
if (!value) return
|
||||
saveCategoryText(catId, value)
|
||||
discardCategorySuggestion(catId)
|
||||
saveCategoryField(catId, field, value)
|
||||
discardCategorySuggestion(catId, field)
|
||||
}
|
||||
|
||||
const discardCategorySuggestion = async (catId: number) => {
|
||||
setCategoryTexts(prev => prev.map(t => t.feedbackCategoryId === catId ? { ...t, suggestedText: '' } : t))
|
||||
const discardCategorySuggestion = async (catId: number, field: 'benefits' | 'concerns') => {
|
||||
const sugField = field === 'benefits' ? 'suggestedBenefits' : 'suggestedConcerns'
|
||||
setCategoryTexts(prev => prev.map(t => t.feedbackCategoryId === catId ? { ...t, [sugField]: '' } : t))
|
||||
if (!feedback?.id) return
|
||||
const existing = await getFeedbackCategoryText(feedback.id, catId)
|
||||
if (existing?.id) await updateFeedbackCategoryText(existing.id, { suggestedText: '' })
|
||||
if (existing?.id) await updateFeedbackCategoryText(existing.id, { [sugField]: '' })
|
||||
}
|
||||
|
||||
// ── Prompt-Vorschau (ohne API-Call) ───────────────────────────────────────
|
||||
@@ -279,7 +319,11 @@ export default function AssignmentFeedbackPage() {
|
||||
|
||||
setPreviewLoading(prev => new Set(prev).add(dim.id!))
|
||||
try {
|
||||
const meetings = await listDoneMeetingsChronological(assignmentId)
|
||||
const [meetings, categoryTemplate, dimensionTemplate] = await Promise.all([
|
||||
listDoneMeetingsChronological(assignmentId),
|
||||
getOrSeedDefaultCategoryPromptTemplate(),
|
||||
getOrSeedDefaultDimensionPromptTemplate(),
|
||||
])
|
||||
const meetingIds = meetings.map(m => m.id!)
|
||||
const [allAssessments, allEntries] = await Promise.all([
|
||||
listAssessmentsForMeetings(meetingIds),
|
||||
@@ -288,60 +332,101 @@ export default function AssignmentFeedbackPage() {
|
||||
const instAssessments = allAssessments.filter(a => a.instituteeId === institutee.id)
|
||||
const instEntries = allEntries.filter(e => e.instituteeId === institutee.id)
|
||||
const dimCategories = categories.filter(c => c.dimensionId === dim.id)
|
||||
const dimItems = items.filter(i => dimCategories.some(c => c.id === i.categoryId))
|
||||
|
||||
const promptCfg = await getFeedbackDimensionPrompt(dim.id!)
|
||||
const context = buildDimensionPromptContext({
|
||||
institutee, assignment, dimension: dim, dimCategories, dimItems,
|
||||
ratings, catTrends, instAssessments, instEntries, meetings,
|
||||
})
|
||||
const rendered = renderDimensionPrompt(promptCfg.promptTemplate, context)
|
||||
const firstCat = dimCategories[0]
|
||||
const catPreview = firstCat
|
||||
? renderPrompt(categoryTemplate, buildCategoryPromptContext({
|
||||
institutee, assignment, dimension: dim, category: firstCat,
|
||||
catItems: items.filter(i => i.categoryId === firstCat.id),
|
||||
ratings, catTrend: catTrends.get(firstCat.id!), instAssessments, instEntries, meetings,
|
||||
}))
|
||||
: '(keine Kategorien)'
|
||||
|
||||
const sampleResults: CategoryCondenseEntry[] = dimCategories.map(c => ({
|
||||
name: c.name,
|
||||
score: catTrends.get(c.id!)?.suggestion ?? null,
|
||||
benefits: '(Beispiel — wird aus Stufe A befüllt)',
|
||||
concerns: '(Beispiel — wird aus Stufe A befüllt)',
|
||||
}))
|
||||
const dimPreview = renderPrompt(dimensionTemplate, buildDimensionCondenseContext({
|
||||
institutee, assignment, dimension: dim, categoryResults: sampleResults,
|
||||
}))
|
||||
|
||||
const rendered = `=== Stufe A: Kategorie-Prompt (Beispiel: ${firstCat?.name ?? '—'}) ===\n\n${catPreview}\n\n=== Stufe B: Dimensions-Verdichtung ===\n\n${dimPreview}`
|
||||
setPreviewText(prev => ({ ...prev, [dim.id!]: rendered }))
|
||||
} finally {
|
||||
setPreviewLoading(prev => { const next = new Set(prev); next.delete(dim.id!); return next })
|
||||
}
|
||||
}
|
||||
|
||||
// ── KI-Generierung: ein Call pro Dimension ────────────────────────────────
|
||||
const saveCategorySuggestions = async (
|
||||
catId: number,
|
||||
parsed: { benefits: string; concerns: string },
|
||||
) => {
|
||||
if (!feedback?.id) return
|
||||
const existing = await getFeedbackCategoryText(feedback.id, catId)
|
||||
if (existing?.id) {
|
||||
await updateFeedbackCategoryText(existing.id, {
|
||||
suggestedBenefits: parsed.benefits,
|
||||
suggestedConcerns: parsed.concerns,
|
||||
})
|
||||
} else {
|
||||
await addFeedbackCategoryText({
|
||||
assignmentFeedbackId: feedback.id,
|
||||
feedbackCategoryId: catId,
|
||||
benefits: '', concerns: '',
|
||||
suggestedBenefits: parsed.benefits,
|
||||
suggestedConcerns: parsed.concerns,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const generateOneDimension = async (
|
||||
// ── KI-Kaskade: Stufe A (Kategorie) → Stufe B (Dimension) ─────────────────
|
||||
|
||||
const generateOneCategory = async (
|
||||
dim: FeedbackDimension,
|
||||
cat: FeedbackCategory,
|
||||
meetings: MeetingInstance[],
|
||||
instAssessments: Assessment[],
|
||||
instEntries: ConversationEntry[],
|
||||
categoryTemplate: string,
|
||||
settings: { apiKey: string; model: string },
|
||||
): Promise<CategoryCondenseEntry> => {
|
||||
if (!institutee || !assignment || !feedback?.id) {
|
||||
return { name: cat.name, score: null, benefits: '', concerns: '' }
|
||||
}
|
||||
const catItems = items.filter(i => i.categoryId === cat.id)
|
||||
const context = buildCategoryPromptContext({
|
||||
institutee, assignment, dimension: dim, category: cat, catItems,
|
||||
ratings, catTrend: catTrends.get(cat.id!), instAssessments, instEntries, meetings,
|
||||
})
|
||||
const prompt = renderPrompt(categoryTemplate, context)
|
||||
const text = await callOpenRouter(prompt, settings)
|
||||
const parsed = parseCategoryAiResponse(text)
|
||||
await saveCategorySuggestions(cat.id!, parsed)
|
||||
return {
|
||||
name: cat.name,
|
||||
score: parsed.score,
|
||||
benefits: parsed.benefits,
|
||||
concerns: parsed.concerns,
|
||||
}
|
||||
}
|
||||
|
||||
const generateDimensionCondense = async (
|
||||
dim: FeedbackDimension,
|
||||
categoryResults: CategoryCondenseEntry[],
|
||||
settings: { apiKey: string; model: string },
|
||||
) => {
|
||||
if (!institutee || !assignment || !feedback?.id) return
|
||||
const dimCategories = categories.filter(c => c.dimensionId === dim.id)
|
||||
const dimItems = items.filter(i => dimCategories.some(c => c.id === i.categoryId))
|
||||
|
||||
const promptCfg = await getFeedbackDimensionPrompt(dim.id!)
|
||||
const template = promptCfg?.promptTemplate ?? AI_CONFIG.defaultDimensionPromptTemplate
|
||||
|
||||
const context = buildDimensionPromptContext({
|
||||
institutee, assignment, dimension: dim, dimCategories, dimItems,
|
||||
ratings, catTrends, instAssessments, instEntries, meetings,
|
||||
const context = buildDimensionCondenseContext({
|
||||
institutee, assignment, dimension: dim, categoryResults,
|
||||
})
|
||||
const prompt = renderDimensionPrompt(template, context)
|
||||
|
||||
const res = await fetch('https://openrouter.ai/api/v1/chat/completions', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${settings.apiKey}`,
|
||||
'Content-Type': 'application/json',
|
||||
'HTTP-Referer': window.location.origin,
|
||||
'X-Title': 'Assignment Monitor',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: settings.model,
|
||||
messages: [{ role: 'user', content: prompt }],
|
||||
}),
|
||||
})
|
||||
if (!res.ok) throw new Error(`API-Fehler: ${res.status} ${res.statusText}`)
|
||||
|
||||
const data = await res.json()
|
||||
const text = data.choices?.[0]?.message?.content ?? ''
|
||||
const parsed = parseDimensionAiResponse(text)
|
||||
const prompt = renderPrompt(template, context)
|
||||
const text = await callOpenRouter(prompt, settings)
|
||||
const parsed = parseDimensionCondenseResponse(text)
|
||||
|
||||
const existingDimText = await getFeedbackDimensionText(feedback.id, dim.id!)
|
||||
if (existingDimText?.id) {
|
||||
@@ -358,17 +443,43 @@ export default function AssignmentFeedbackPage() {
|
||||
suggestedDevelopmentNeeds: parsed.developmentNeeds,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
for (const ct of parsed.categoryTexts) {
|
||||
const cat = dimCategories.find(c => c.name === ct.name || ct.name.includes(c.name) || c.name.includes(ct.name))
|
||||
if (!cat?.id) continue
|
||||
const existing = await getFeedbackCategoryText(feedback.id, cat.id)
|
||||
if (existing?.id) {
|
||||
await updateFeedbackCategoryText(existing.id, { suggestedText: ct.text })
|
||||
} else {
|
||||
await addFeedbackCategoryText({ assignmentFeedbackId: feedback.id, feedbackCategoryId: cat.id, text: '', suggestedText: ct.text })
|
||||
const generateOneDimension = async (
|
||||
dim: FeedbackDimension,
|
||||
dimIndex: number,
|
||||
dimTotal: number,
|
||||
meetings: MeetingInstance[],
|
||||
instAssessments: Assessment[],
|
||||
instEntries: ConversationEntry[],
|
||||
categoryTemplate: string,
|
||||
settings: { apiKey: string; model: string },
|
||||
) => {
|
||||
if (!institutee || !assignment || !feedback?.id) return
|
||||
const dimCategories = categories.filter(c => c.dimensionId === dim.id)
|
||||
const categoryResults: CategoryCondenseEntry[] = []
|
||||
|
||||
for (let ci = 0; ci < dimCategories.length; ci++) {
|
||||
const cat = dimCategories[ci]
|
||||
const errKey = `${dim.id}:${cat.id}`
|
||||
setGenerationProgress(
|
||||
`Dimension ${dimIndex + 1}/${dimTotal} · Kategorie ${ci + 1}/${dimCategories.length}: ${cat.name}…`,
|
||||
)
|
||||
try {
|
||||
const result = await generateOneCategory(
|
||||
dim, cat, meetings, instAssessments, instEntries, categoryTemplate, settings,
|
||||
)
|
||||
categoryResults.push(result)
|
||||
setCategoryErrors(prev => { const next = { ...prev }; delete next[errKey]; return next })
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : 'Unbekannter Fehler'
|
||||
setCategoryErrors(prev => ({ ...prev, [errKey]: msg }))
|
||||
throw new Error(`Kategorie „${cat.name}": ${msg}`)
|
||||
}
|
||||
}
|
||||
|
||||
setGenerationProgress(`Dimension ${dimIndex + 1}/${dimTotal}: ${dim.name} verdichten…`)
|
||||
await generateDimensionCondense(dim, categoryResults, settings)
|
||||
}
|
||||
|
||||
/** Sequenziell mit Fortschrittsanzeige — Fehler einzelner Dimensionen stoppen den Lauf nicht. */
|
||||
@@ -384,9 +495,13 @@ export default function AssignmentFeedbackPage() {
|
||||
for (const d of dimsToRun) delete next[d.id!]
|
||||
return next
|
||||
})
|
||||
setCategoryErrors({})
|
||||
|
||||
try {
|
||||
const meetings = await listDoneMeetingsChronological(assignmentId)
|
||||
const [meetings, categoryTemplate] = await Promise.all([
|
||||
listDoneMeetingsChronological(assignmentId),
|
||||
getOrSeedDefaultCategoryPromptTemplate(),
|
||||
])
|
||||
const meetingIds = meetings.map(m => m.id!)
|
||||
const [allAssessments, allEntries] = await Promise.all([
|
||||
listAssessmentsForMeetings(meetingIds),
|
||||
@@ -397,11 +512,15 @@ export default function AssignmentFeedbackPage() {
|
||||
|
||||
for (let i = 0; i < dimsToRun.length; i++) {
|
||||
const dim = dimsToRun[i]
|
||||
setGenerationProgress(`Generiere Dimension ${i + 1}/${dimsToRun.length}: ${dim.name}…`)
|
||||
try {
|
||||
await generateOneDimension(dim, meetings, instAssessments, instEntries, settings)
|
||||
await generateOneDimension(
|
||||
dim, i, dimsToRun.length, meetings, instAssessments, instEntries, categoryTemplate, settings,
|
||||
)
|
||||
} catch (e) {
|
||||
setDimensionErrors(prev => ({ ...prev, [dim.id!]: e instanceof Error ? e.message : 'Unbekannter Fehler' }))
|
||||
setDimensionErrors(prev => ({
|
||||
...prev,
|
||||
[dim.id!]: e instanceof Error ? e.message : 'Unbekannter Fehler',
|
||||
}))
|
||||
}
|
||||
}
|
||||
await updateAssignmentFeedback(feedback.id, { aiModel: settings.model, updatedAt: new Date().toISOString() })
|
||||
@@ -427,6 +546,15 @@ export default function AssignmentFeedbackPage() {
|
||||
setFeedback(prev => prev ? { ...prev, status: next } : null)
|
||||
}
|
||||
|
||||
const handleExportPdf = async () => {
|
||||
setExportingPdf(true)
|
||||
try {
|
||||
await exportInstituteeFeedbackPdf(assignmentId, instId)
|
||||
} finally {
|
||||
setExportingPdf(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (!assignment || !institutee) return <div className="text-center py-10 text-gray-400">Lädt…</div>
|
||||
|
||||
return (
|
||||
@@ -454,6 +582,10 @@ export default function AssignmentFeedbackPage() {
|
||||
className="text-xs text-gray-400 hover:text-gray-600">
|
||||
⚙ KI-Einstellungen
|
||||
</button>
|
||||
<button onClick={handleExportPdf} disabled={exportingPdf}
|
||||
className="text-xs text-gray-400 hover:text-gray-600 disabled:opacity-50">
|
||||
{exportingPdf ? 'Erstelle PDF…' : '⬇ Als PDF exportieren'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -512,16 +644,28 @@ export default function AssignmentFeedbackPage() {
|
||||
{aiError}
|
||||
</div>
|
||||
)}
|
||||
{!generating && Object.keys(dimensionErrors).length > 0 && (
|
||||
{!generating && (Object.keys(dimensionErrors).length > 0 || Object.keys(categoryErrors).length > 0) && (
|
||||
<div className="text-xs text-red-600 bg-red-50 border border-red-200 rounded-lg px-3 py-2 space-y-1.5">
|
||||
<div className="font-medium">Fehler bei {Object.keys(dimensionErrors).length} Dimension(en):</div>
|
||||
{Object.entries(dimensionErrors).map(([dimId, msg]) => (
|
||||
<div key={dimId}>• {dimensions.find(d => d.id === Number(dimId))?.name}: {msg}</div>
|
||||
))}
|
||||
<button onClick={retryFailedDimensions}
|
||||
className="text-xs bg-red-100 text-red-700 px-2 py-1 rounded-lg font-medium hover:bg-red-200">
|
||||
Fehlgeschlagene Dimensionen erneut versuchen
|
||||
</button>
|
||||
{Object.keys(dimensionErrors).length > 0 && (
|
||||
<>
|
||||
<div className="font-medium">Fehler bei {Object.keys(dimensionErrors).length} Dimension(en):</div>
|
||||
{Object.entries(dimensionErrors).map(([dimId, msg]) => (
|
||||
<div key={dimId}>• {dimensions.find(d => d.id === Number(dimId))?.name}: {msg}</div>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
{Object.entries(categoryErrors).map(([key, msg]) => {
|
||||
const [dimId, catId] = key.split(':').map(Number)
|
||||
const dimName = dimensions.find(d => d.id === dimId)?.name ?? 'Dimension'
|
||||
const catName = categories.find(c => c.id === catId)?.name ?? 'Kategorie'
|
||||
return <div key={key}>• {dimName} → {catName}: {msg}</div>
|
||||
})}
|
||||
{Object.keys(dimensionErrors).length > 0 && (
|
||||
<button onClick={retryFailedDimensions}
|
||||
className="text-xs bg-red-100 text-red-700 px-2 py-1 rounded-lg font-medium hover:bg-red-200">
|
||||
Fehlgeschlagene Dimensionen erneut versuchen
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -531,14 +675,9 @@ export default function AssignmentFeedbackPage() {
|
||||
const isOpen = expanded.has(dim.id!)
|
||||
const text = getDimText(dim.id!)
|
||||
|
||||
// Zusammenfassung der Bewertungen
|
||||
const catRatings = dimCats.map(c => getRating(c.id!)).filter(Boolean) as FeedbackRating[]
|
||||
const worstRating = catRatings.includes('not_client_ready') ? 'not_client_ready'
|
||||
: catRatings.includes('partially_client_ready') ? 'partially_client_ready'
|
||||
: catRatings.includes('nearly_client_ready') ? 'nearly_client_ready'
|
||||
: catRatings.includes('client_ready') ? 'client_ready'
|
||||
: catRatings.length > 0 ? 'na' : undefined
|
||||
const summaryColor = ratingColor(worstRating)
|
||||
const catRatings = dimCats.map(c => getRating(c.id!)).filter(isValidRatingScore)
|
||||
const worstRating = catRatings.length > 0 ? Math.min(...catRatings) : null
|
||||
const summaryStyle = resolveScoreStyle(worstRating, colorBands)
|
||||
|
||||
return (
|
||||
<div key={dim.id} className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
|
||||
@@ -553,9 +692,9 @@ export default function AssignmentFeedbackPage() {
|
||||
className="w-full flex items-center justify-between p-4 text-left hover:bg-gray-50 transition">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-semibold text-gray-800 text-sm">{dim.name}</span>
|
||||
{worstRating && (
|
||||
<span className={`text-xs px-2 py-0.5 rounded-full border font-medium ${summaryColor}`}>
|
||||
{RATING_OPTIONS.find(r => r.value === worstRating)?.short}
|
||||
{worstRating !== null && (
|
||||
<span className={`text-xs px-2 py-0.5 rounded-full border font-medium tabular-nums ${summaryStyle.color}`}>
|
||||
{summaryStyle.short}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
@@ -599,31 +738,21 @@ export default function AssignmentFeedbackPage() {
|
||||
<div key={cat.id} className="space-y-2">
|
||||
<div className="font-medium text-sm text-gray-700">{cat.name}</div>
|
||||
|
||||
{/* Rating-Buttons */}
|
||||
<div className="flex gap-1 flex-wrap">
|
||||
{RATING_OPTIONS.map(r => (
|
||||
<button key={r.value}
|
||||
onClick={() => setRating(cat.id!, r.value)}
|
||||
className={`px-2.5 py-1.5 rounded-lg text-xs font-semibold border transition ${
|
||||
currentRating === r.value
|
||||
? r.color + ' ring-2 ring-offset-1 ring-current'
|
||||
: 'bg-gray-50 text-gray-400 border-gray-200 hover:bg-gray-100'
|
||||
}`}>
|
||||
{r.short}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<ScorePicker
|
||||
value={currentRating ?? null}
|
||||
onChange={score => setRating(cat.id!, score)}
|
||||
bands={colorBands}
|
||||
/>
|
||||
|
||||
{/* 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
|
||||
if (suggestedRating === null) return null
|
||||
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 className="text-xs bg-blue-50 text-blue-700 border border-blue-200 px-2 py-1 rounded-lg font-medium tabular-nums">
|
||||
Vorschlag: {suggestedRating} ({trend.suggestion.toFixed(1)}) {trendArrow(trend.trend)}
|
||||
</span>
|
||||
<button
|
||||
onClick={() => setRating(cat.id!, suggestedRating)}
|
||||
@@ -632,7 +761,7 @@ export default function AssignmentFeedbackPage() {
|
||||
</button>
|
||||
{(trend.trend === 'up' || trend.trend === 'down') && (
|
||||
<button
|
||||
onClick={() => appendTrendSentence(dim.id!, cat, trend)}
|
||||
onClick={() => appendTrendSentence(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>
|
||||
@@ -653,21 +782,40 @@ export default function AssignmentFeedbackPage() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Kategorie-Notiz */}
|
||||
<div className="space-y-1.5">
|
||||
<textarea
|
||||
className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-brand min-h-[50px]"
|
||||
placeholder="Kurze Einschätzung zu dieser Kategorie…"
|
||||
value={catText?.text ?? ''}
|
||||
onChange={e => saveCategoryText(cat.id!, e.target.value)}
|
||||
/>
|
||||
{catText?.suggestedText && (
|
||||
<AiSuggestionBox
|
||||
text={catText.suggestedText}
|
||||
onAccept={() => acceptCategorySuggestion(cat.id!)}
|
||||
onDiscard={() => discardCategorySuggestion(cat.id!)}
|
||||
{/* Kategorie Benefits / Concerns */}
|
||||
<div className="space-y-2">
|
||||
<div className="space-y-1">
|
||||
<label className="text-xs font-medium text-green-700">Benefits</label>
|
||||
<textarea
|
||||
className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-brand min-h-[44px]"
|
||||
placeholder="Positive Beobachtungen zu dieser Kategorie…"
|
||||
value={catText?.benefits ?? ''}
|
||||
onChange={e => saveCategoryField(cat.id!, 'benefits', e.target.value)}
|
||||
/>
|
||||
)}
|
||||
{catText?.suggestedBenefits && (
|
||||
<AiSuggestionBox
|
||||
text={catText.suggestedBenefits}
|
||||
onAccept={() => acceptCategorySuggestion(cat.id!, 'benefits')}
|
||||
onDiscard={() => discardCategorySuggestion(cat.id!, 'benefits')}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<label className="text-xs font-medium text-amber-700">Concerns</label>
|
||||
<textarea
|
||||
className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-brand min-h-[44px]"
|
||||
placeholder="Entwicklungsfelder / Risiken zu dieser Kategorie…"
|
||||
value={catText?.concerns ?? ''}
|
||||
onChange={e => saveCategoryField(cat.id!, 'concerns', e.target.value)}
|
||||
/>
|
||||
{catText?.suggestedConcerns && (
|
||||
<AiSuggestionBox
|
||||
text={catText.suggestedConcerns}
|
||||
onAccept={() => acceptCategorySuggestion(cat.id!, 'concerns')}
|
||||
onDiscard={() => discardCategorySuggestion(cat.id!, 'concerns')}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
@@ -677,11 +825,11 @@ export default function AssignmentFeedbackPage() {
|
||||
<div className="space-y-3 pt-2 border-t border-gray-50">
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-xs font-semibold text-green-700 uppercase tracking-wide block mb-1.5">
|
||||
Achievements
|
||||
Benefits (Dimension)
|
||||
</label>
|
||||
<textarea
|
||||
className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-green-400 min-h-[80px]"
|
||||
placeholder="Konkrete Stärken und positive Beobachtungen…"
|
||||
placeholder="3–5 Hauptstärken dieser Dimension…"
|
||||
value={text?.achievements ?? ''}
|
||||
onChange={e => saveDimText(dim.id!, 'achievements', e.target.value)}
|
||||
/>
|
||||
@@ -695,11 +843,11 @@ export default function AssignmentFeedbackPage() {
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-xs font-semibold text-amber-700 uppercase tracking-wide block mb-1.5">
|
||||
Development Needs
|
||||
Concerns (Dimension)
|
||||
</label>
|
||||
<textarea
|
||||
className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-amber-400 min-h-[80px]"
|
||||
placeholder="Entwicklungsfelder und konkrete Handlungsempfehlungen…"
|
||||
placeholder="3–5 zentrale Entwicklungsfelder dieser Dimension…"
|
||||
value={text?.developmentNeeds ?? ''}
|
||||
onChange={e => saveDimText(dim.id!, 'developmentNeeds', e.target.value)}
|
||||
/>
|
||||
|
||||
@@ -1,12 +1,18 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import {
|
||||
type AssignmentType, type PhaseTemplate, type FeedbackDimension, type FeedbackCategory, type FeedbackCriterionItem,
|
||||
type ChecklistItemDef,
|
||||
listAssignmentTypes, listPhaseTemplates, loadFeedbackStructure,
|
||||
addAssignmentType, updateAssignmentType, deleteAssignmentType,
|
||||
addPhaseTemplate, updatePhaseTemplate, deletePhaseTemplate,
|
||||
listChecklistItemDefsForPhaseTemplate, addChecklistItemDef, updateChecklistItemDef, deleteChecklistItemDef,
|
||||
} from '../db'
|
||||
import { exportAssignmentTypesReportAsMarkdown } from '../utils/structureExport'
|
||||
import { exportAssignmentTypesReportPdf } from '../utils/pdfExport'
|
||||
import { criterionOptionGroups } from '../utils/criterionOptions'
|
||||
|
||||
export default function AssignmentTypeConfig() {
|
||||
const [exportingPdf, setExportingPdf] = useState(false)
|
||||
const [types, setTypes] = useState<AssignmentType[]>([])
|
||||
const [templates, setTemplates] = useState<PhaseTemplate[]>([])
|
||||
const [dimensions, setDimensions] = useState<FeedbackDimension[]>([])
|
||||
@@ -19,7 +25,12 @@ export default function AssignmentTypeConfig() {
|
||||
const [typeError, setTypeError] = useState<Record<number, string>>({})
|
||||
const [newPhase, setNewPhase] = useState<Record<number, {
|
||||
label: string; withWhom: 'lead' | 'client'
|
||||
isRepeatable: boolean; hasConversation: boolean; hasAssessment: boolean
|
||||
isRepeatable: boolean; hasConversation: boolean; hasAssessment: boolean; hasChecklist: boolean
|
||||
}>>({})
|
||||
const [checklistItems, setChecklistItems] = useState<ChecklistItemDef[]>([])
|
||||
const [expandedChecklist, setExpandedChecklist] = useState<Set<number>>(new Set())
|
||||
const [newChecklistItem, setNewChecklistItem] = useState<Record<number, {
|
||||
label: string; scope: 'perInstitutee' | 'meetingWide'; linkedCriterionItemId: string
|
||||
}>>({})
|
||||
|
||||
const load = async () => {
|
||||
@@ -33,6 +44,8 @@ export default function AssignmentTypeConfig() {
|
||||
setDimensions(structure.dimensions)
|
||||
setCategories(structure.categories)
|
||||
setItems(structure.items)
|
||||
const checklistLists = await Promise.all(tmpl.map(p => listChecklistItemDefsForPhaseTemplate(p.id!)))
|
||||
setChecklistItems(checklistLists.flat())
|
||||
}
|
||||
|
||||
useEffect(() => { load() }, [])
|
||||
@@ -74,7 +87,7 @@ export default function AssignmentTypeConfig() {
|
||||
const toggleAllInCategory = async (type: AssignmentType, catId: number) => {
|
||||
const catItemIds = items.filter(i => i.categoryId === catId).map(i => i.id!)
|
||||
const current = type.criteriaIds ?? []
|
||||
const allSelected = catItemIds.every(id => current.includes(id))
|
||||
const allSelected = catItemIds.length > 0 && catItemIds.every(id => current.includes(id))
|
||||
const next = allSelected
|
||||
? current.filter(id => !catItemIds.includes(id))
|
||||
: [...new Set([...current, ...catItemIds])]
|
||||
@@ -82,6 +95,23 @@ export default function AssignmentTypeConfig() {
|
||||
setTypes(prev => prev.map(t => t.id === type.id ? { ...t, criteriaIds: next } : t))
|
||||
}
|
||||
|
||||
const toggleAllInDimension = async (type: AssignmentType, dimId: number) => {
|
||||
const dimCatIds = categories.filter(c => c.dimensionId === dimId).map(c => c.id!)
|
||||
const dimItemIds = items.filter(i => dimCatIds.includes(i.categoryId)).map(i => i.id!)
|
||||
const current = type.criteriaIds ?? []
|
||||
const allSelected = dimItemIds.length > 0 && dimItemIds.every(id => current.includes(id))
|
||||
const next = allSelected
|
||||
? current.filter(id => !dimItemIds.includes(id))
|
||||
: [...new Set([...current, ...dimItemIds])]
|
||||
await updateAssignmentType(type.id!, { criteriaIds: next })
|
||||
setTypes(prev => prev.map(t => t.id === type.id ? { ...t, criteriaIds: next } : t))
|
||||
}
|
||||
|
||||
const clearStructureFilter = async (type: AssignmentType) => {
|
||||
await updateAssignmentType(type.id!, { criteriaIds: [] })
|
||||
setTypes(prev => prev.map(t => t.id === type.id ? { ...t, criteriaIds: [] } : t))
|
||||
}
|
||||
|
||||
// ── Phasen-Templates ───────────────────────────────────────────────────────
|
||||
|
||||
const addPhase = async (typeId: number) => {
|
||||
@@ -96,10 +126,11 @@ export default function AssignmentTypeConfig() {
|
||||
isRepeatable: np.isRepeatable,
|
||||
hasConversation: np.hasConversation,
|
||||
hasAssessment: np.hasAssessment,
|
||||
hasChecklist: np.hasChecklist,
|
||||
criteriaIds: [],
|
||||
order: existing.length + 1,
|
||||
})
|
||||
setNewPhase(prev => ({ ...prev, [typeId]: { label: '', withWhom: 'lead', isRepeatable: false, hasConversation: false, hasAssessment: false } }))
|
||||
setNewPhase(prev => ({ ...prev, [typeId]: { label: '', withWhom: 'lead', isRepeatable: false, hasConversation: false, hasAssessment: false, hasChecklist: false } }))
|
||||
await load()
|
||||
}
|
||||
|
||||
@@ -113,8 +144,51 @@ export default function AssignmentTypeConfig() {
|
||||
await load()
|
||||
}
|
||||
|
||||
// ── Checkliste pro Phase ───────────────────────────────────────────────────
|
||||
|
||||
const addChecklistItem = async (phaseId: number) => {
|
||||
const nci = newChecklistItem[phaseId]
|
||||
if (!nci?.label.trim()) return
|
||||
const existing = checklistItems.filter(c => c.phaseTemplateId === phaseId)
|
||||
await addChecklistItemDef({
|
||||
phaseTemplateId: phaseId,
|
||||
label: nci.label.trim(),
|
||||
scope: nci.scope,
|
||||
linkedCriterionItemId: nci.linkedCriterionItemId ? Number(nci.linkedCriterionItemId) : undefined,
|
||||
order: existing.length + 1,
|
||||
})
|
||||
setNewChecklistItem(prev => ({ ...prev, [phaseId]: { label: '', scope: 'perInstitutee', linkedCriterionItemId: '' } }))
|
||||
await load()
|
||||
}
|
||||
|
||||
const updateChecklistItem = async (id: number, patch: Partial<ChecklistItemDef>) => {
|
||||
await updateChecklistItemDef(id, patch)
|
||||
setChecklistItems(prev => prev.map(c => c.id === id ? { ...c, ...patch } : c))
|
||||
}
|
||||
|
||||
const deleteChecklistItem = async (id: number) => {
|
||||
await deleteChecklistItemDef(id)
|
||||
setChecklistItems(prev => prev.filter(c => c.id !== id))
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<h2 className="text-lg font-bold text-gray-800">Assignment-Typen</h2>
|
||||
<div className="flex gap-1.5 flex-shrink-0">
|
||||
<button onClick={() => exportAssignmentTypesReportAsMarkdown()}
|
||||
className="text-xs px-2.5 py-1.5 border border-gray-200 rounded-lg text-gray-500 hover:border-brand hover:text-brand transition">
|
||||
⬇ MD
|
||||
</button>
|
||||
<button
|
||||
onClick={async () => { setExportingPdf(true); try { await exportAssignmentTypesReportPdf() } finally { setExportingPdf(false) } }}
|
||||
disabled={exportingPdf}
|
||||
className="text-xs px-2.5 py-1.5 border border-gray-200 rounded-lg text-gray-500 hover:border-brand hover:text-brand transition disabled:opacity-50">
|
||||
{exportingPdf ? '⏳' : '⬇ PDF'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Neuer Typ */}
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
@@ -138,7 +212,7 @@ export default function AssignmentTypeConfig() {
|
||||
const isOpen = expanded === type.id
|
||||
const typPhases = templates.filter(t => t.assignmentTypeId === type.id).sort((a, b) => a.order - b.order)
|
||||
const tab = activeTab[type.id!] ?? 'phases'
|
||||
const np = newPhase[type.id!] ?? { label: '', withWhom: 'lead' as const, isRepeatable: false, hasConversation: false, hasAssessment: false }
|
||||
const np = newPhase[type.id!] ?? { label: '', withWhom: 'lead' as const, isRepeatable: false, hasConversation: false, hasAssessment: false, hasChecklist: false }
|
||||
const selected = type.criteriaIds ?? []
|
||||
|
||||
return (
|
||||
@@ -150,7 +224,7 @@ export default function AssignmentTypeConfig() {
|
||||
value={type.name}
|
||||
onChange={e => updateTypeName(type.id!, e.target.value)}
|
||||
/>
|
||||
<span className="text-xs text-gray-400">{typPhases.length} Phasen · {selected.length ? `${selected.length} Kriterien` : 'alle Kriterien'}</span>
|
||||
<span className="text-xs text-gray-400">{typPhases.length} Phasen · {selected.length ? `${selected.length} Kriterien` : 'gesamte Struktur'}</span>
|
||||
<button onClick={() => setExpanded(isOpen ? null : type.id!)}
|
||||
className="text-xs text-gray-400 px-1">{isOpen ? '▲' : '▼'}</button>
|
||||
<button onClick={() => deleteType(type.id!)}
|
||||
@@ -173,7 +247,7 @@ export default function AssignmentTypeConfig() {
|
||||
className={`flex-1 py-2 text-xs font-medium transition ${
|
||||
tab === t ? 'text-brand border-b-2 border-brand' : 'text-gray-400'
|
||||
}`}>
|
||||
{t === 'phases' ? `Phasen (${typPhases.length})` : `Kriterien (${selected.length || 'alle'})`}
|
||||
{t === 'phases' ? `Phasen (${typPhases.length})` : `Struktur (${selected.length || 'alle'})`}
|
||||
|
||||
</button>
|
||||
))}
|
||||
@@ -216,7 +290,90 @@ export default function AssignmentTypeConfig() {
|
||||
onChange={e => updatePhase(phase.id!, { hasAssessment: e.target.checked })} />
|
||||
Bewertung
|
||||
</label>
|
||||
<label className="flex items-center gap-1 cursor-pointer">
|
||||
<input type="checkbox" checked={phase.hasChecklist}
|
||||
onChange={e => updatePhase(phase.id!, { hasChecklist: e.target.checked })} />
|
||||
Checkliste
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{phase.hasChecklist && (() => {
|
||||
const phaseChecklist = checklistItems
|
||||
.filter(c => c.phaseTemplateId === phase.id)
|
||||
.sort((a, b) => a.order - b.order)
|
||||
const isChecklistOpen = expandedChecklist.has(phase.id!)
|
||||
const nci = newChecklistItem[phase.id!] ?? { label: '', scope: 'perInstitutee' as const, linkedCriterionItemId: '' }
|
||||
return (
|
||||
<div className="border-t border-gray-100 pt-1.5">
|
||||
<button
|
||||
onClick={() => setExpandedChecklist(prev => {
|
||||
const next = new Set(prev)
|
||||
if (next.has(phase.id!)) next.delete(phase.id!); else next.add(phase.id!)
|
||||
return next
|
||||
})}
|
||||
className="text-xs text-gray-500 font-medium">
|
||||
🗹 Checkliste ({phaseChecklist.length}) {isChecklistOpen ? '▲' : '▼'}
|
||||
</button>
|
||||
{isChecklistOpen && (
|
||||
<div className="mt-1.5 space-y-1.5">
|
||||
{phaseChecklist.map(ci => (
|
||||
<div key={ci.id} className="flex items-center gap-1.5 bg-gray-50 rounded-lg px-2 py-1.5">
|
||||
<input
|
||||
className="flex-1 text-xs bg-transparent border-b border-transparent focus:border-brand focus:outline-none"
|
||||
value={ci.label}
|
||||
onChange={e => updateChecklistItem(ci.id!, { label: e.target.value })}
|
||||
/>
|
||||
<select
|
||||
value={ci.scope}
|
||||
onChange={e => updateChecklistItem(ci.id!, { scope: e.target.value as 'perInstitutee' | 'meetingWide' })}
|
||||
className="text-xs border border-gray-200 rounded px-1 py-0.5 bg-white focus:outline-none">
|
||||
<option value="perInstitutee">pro Institutee</option>
|
||||
<option value="meetingWide">meeting-weit</option>
|
||||
</select>
|
||||
<select
|
||||
value={ci.linkedCriterionItemId ?? ''}
|
||||
onChange={e => updateChecklistItem(ci.id!, { linkedCriterionItemId: e.target.value ? Number(e.target.value) : undefined })}
|
||||
className="text-xs border border-gray-200 rounded px-1 py-0.5 bg-white focus:outline-none max-w-[140px]">
|
||||
<option value="">— frei —</option>
|
||||
{criterionOptionGroups(dimensions, categories, items)}
|
||||
</select>
|
||||
<button onClick={() => deleteChecklistItem(ci.id!)}
|
||||
className="text-red-300 hover:text-red-500 text-xs">×</button>
|
||||
</div>
|
||||
))}
|
||||
<div className="flex items-center gap-1.5">
|
||||
<input
|
||||
className="flex-1 border border-gray-200 rounded px-2 py-1 text-xs focus:outline-none focus:border-brand bg-white"
|
||||
placeholder="Neuer Checklisten-Punkt…"
|
||||
value={nci.label}
|
||||
onChange={e => setNewChecklistItem(prev => ({ ...prev, [phase.id!]: { ...nci, label: e.target.value } }))}
|
||||
onKeyDown={e => e.key === 'Enter' && addChecklistItem(phase.id!)}
|
||||
/>
|
||||
<select
|
||||
value={nci.scope}
|
||||
onChange={e => setNewChecklistItem(prev => ({ ...prev, [phase.id!]: { ...nci, scope: e.target.value as 'perInstitutee' | 'meetingWide' } }))}
|
||||
className="text-xs border border-gray-200 rounded px-1 py-1 bg-white focus:outline-none">
|
||||
<option value="perInstitutee">pro Institutee</option>
|
||||
<option value="meetingWide">meeting-weit</option>
|
||||
</select>
|
||||
<select
|
||||
value={nci.linkedCriterionItemId}
|
||||
onChange={e => setNewChecklistItem(prev => ({ ...prev, [phase.id!]: { ...nci, linkedCriterionItemId: e.target.value } }))}
|
||||
className="text-xs border border-gray-200 rounded px-1 py-1 bg-white focus:outline-none max-w-[140px]">
|
||||
<option value="">— frei —</option>
|
||||
{criterionOptionGroups(dimensions, categories, items)}
|
||||
</select>
|
||||
<button onClick={() => addChecklistItem(phase.id!)}
|
||||
className="text-xs bg-brand text-white px-2 py-1 rounded-lg font-medium">+ Punkt</button>
|
||||
</div>
|
||||
<p className="text-[10px] text-gray-400">
|
||||
Verknüpfte Punkte fließen automatisch in Gesamtbewertung und KI-Auswertung ein — bei „meeting-weit" für alle Institutees gleichzeitig.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})()}
|
||||
</div>
|
||||
))}
|
||||
|
||||
@@ -255,6 +412,11 @@ export default function AssignmentTypeConfig() {
|
||||
onChange={e => setNewPhase(prev => ({ ...prev, [type.id!]: { ...np, hasAssessment: e.target.checked } }))} />
|
||||
Bewertung
|
||||
</label>
|
||||
<label className="flex items-center gap-1 cursor-pointer">
|
||||
<input type="checkbox" checked={np.hasChecklist}
|
||||
onChange={e => setNewPhase(prev => ({ ...prev, [type.id!]: { ...np, hasChecklist: e.target.checked } }))} />
|
||||
Checkliste
|
||||
</label>
|
||||
</div>
|
||||
<button onClick={() => addPhase(type.id!)}
|
||||
className="px-4 py-1.5 bg-brand text-white text-xs rounded-lg font-medium">
|
||||
@@ -267,9 +429,18 @@ export default function AssignmentTypeConfig() {
|
||||
{/* Kriterien-Tab */}
|
||||
{tab === 'criteria' && (
|
||||
<div className="p-3 space-y-1">
|
||||
<p className="text-xs text-gray-400 pb-2">
|
||||
Kein Haken = alle Kriterien werden angezeigt.
|
||||
</p>
|
||||
<div className="flex items-start justify-between gap-2 pb-2">
|
||||
<p className="text-xs text-gray-400">
|
||||
Steuert, welche Dimensionen/Kategorien in Meeting und Feedback sichtbar sind.
|
||||
Kein Haken = gesamte Struktur. Haken setzen schränkt auf die Auswahl ein (gespeichert als Kriterien-IDs).
|
||||
</p>
|
||||
{selected.length > 0 && (
|
||||
<button type="button" onClick={() => clearStructureFilter(type)}
|
||||
className="text-xs text-brand whitespace-nowrap flex-shrink-0">
|
||||
Alles freigeben
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{items.length === 0 && (
|
||||
<div className="text-xs text-gray-400">Keine Kriterien konfiguriert. Erst unter "Feedback" anlegen.</div>
|
||||
)}
|
||||
@@ -279,20 +450,33 @@ export default function AssignmentTypeConfig() {
|
||||
if (dimItems.length === 0) return null
|
||||
const isDimOpen = expandedDim.has(dim.id!)
|
||||
const dimSelectedCount = dimItems.filter(i => selected.includes(i.id!)).length
|
||||
const allDimSelected = dimItems.every(i => selected.includes(i.id!))
|
||||
const someDimSelected = dimItems.some(i => selected.includes(i.id!))
|
||||
return (
|
||||
<div key={dim.id} className="border border-gray-100 rounded-lg overflow-hidden">
|
||||
<button
|
||||
onClick={() => setExpandedDim(prev => {
|
||||
const next = new Set(prev)
|
||||
if (next.has(dim.id!)) next.delete(dim.id!); else next.add(dim.id!)
|
||||
return next
|
||||
})}
|
||||
className="w-full flex items-center justify-between px-3 py-2 bg-gray-50 hover:bg-gray-100 text-left">
|
||||
<span className="text-xs font-semibold text-gray-700">{dim.name}</span>
|
||||
<span className="text-xs text-gray-400">
|
||||
{dimSelectedCount > 0 ? `${dimSelectedCount}/${dimItems.length}` : 'alle'} · {isDimOpen ? '▲' : '▼'}
|
||||
</span>
|
||||
</button>
|
||||
<div className="flex items-center gap-2 px-3 py-2 bg-gray-50">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={allDimSelected}
|
||||
ref={el => { if (el) el.indeterminate = someDimSelected && !allDimSelected }}
|
||||
onChange={() => toggleAllInDimension(type, dim.id!)}
|
||||
className="rounded border-gray-300"
|
||||
title="Gesamte Dimension"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setExpandedDim(prev => {
|
||||
const next = new Set(prev)
|
||||
if (next.has(dim.id!)) next.delete(dim.id!); else next.add(dim.id!)
|
||||
return next
|
||||
})}
|
||||
className="flex-1 flex items-center justify-between text-left hover:opacity-80">
|
||||
<span className="text-xs font-semibold text-gray-700">{dim.name}</span>
|
||||
<span className="text-xs text-gray-400">
|
||||
{selected.length === 0 ? 'alle' : `${dimSelectedCount}/${dimItems.length}`} · {isDimOpen ? '▲' : '▼'}
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
{isDimOpen && (
|
||||
<div className="divide-y divide-gray-50">
|
||||
{dimCats.map(cat => {
|
||||
@@ -311,6 +495,7 @@ export default function AssignmentTypeConfig() {
|
||||
className="rounded border-gray-300"
|
||||
/>
|
||||
<span className="text-xs font-semibold text-gray-600">{cat.name}</span>
|
||||
<span className="text-xs text-gray-300">{catItems.length} Krit.</span>
|
||||
</label>
|
||||
<div className="pl-5 space-y-1">
|
||||
{catItems.map(item => (
|
||||
@@ -322,7 +507,7 @@ export default function AssignmentTypeConfig() {
|
||||
className="rounded border-gray-300"
|
||||
/>
|
||||
<span className="text-xs text-gray-600">{item.name}</span>
|
||||
{(item.weight ?? 1) > 1 && (
|
||||
{(item.weight ?? 1) !== 1 && (
|
||||
<span className="text-xs text-gray-300">×{item.weight}</span>
|
||||
)}
|
||||
</label>
|
||||
|
||||
@@ -2,11 +2,12 @@ import { useRef, useState } from 'react'
|
||||
import FeedbackStructureConfig from './FeedbackStructureConfig'
|
||||
import AssignmentTypeConfig from './AssignmentTypeConfig'
|
||||
import RatingWeightConfig from './RatingWeightConfig'
|
||||
import RatingScaleConfig from './RatingScaleConfig'
|
||||
import AiPromptConfig from './AiPromptConfig'
|
||||
import { exportFullBackup, importFullBackup } from '../utils/dbBackup'
|
||||
|
||||
export default function Configuration() {
|
||||
const [tab, setTab] = useState<'feedback' | 'types' | 'weighting' | 'aiPrompts' | 'backup'>('feedback')
|
||||
const [tab, setTab] = useState<'feedback' | 'types' | 'weighting' | 'scale' | 'aiPrompts' | 'backup'>('feedback')
|
||||
const [backupStatus, setBackupStatus] = useState<{ type: 'success' | 'error'; msg: string } | null>(null)
|
||||
const [restoreConfirm, setRestoreConfirm] = useState(false)
|
||||
const [importing, setImporting] = useState(false)
|
||||
@@ -40,26 +41,29 @@ export default function Configuration() {
|
||||
<div className="space-y-4">
|
||||
<h1 className="text-xl font-bold text-gray-800">Konfiguration</h1>
|
||||
|
||||
{/* Tab-Switcher */}
|
||||
<div className="flex bg-gray-100 rounded-xl p-1 gap-0.5">
|
||||
<div className="flex bg-gray-100 rounded-xl p-1 gap-0.5 flex-wrap">
|
||||
<button onClick={() => setTab('feedback')}
|
||||
className={`flex-1 py-2 rounded-lg text-sm font-medium transition ${tab === 'feedback' ? 'bg-white text-brand shadow-sm' : 'text-gray-500'}`}>
|
||||
className={`flex-1 min-w-[4.5rem] py-2 rounded-lg text-sm font-medium transition ${tab === 'feedback' ? 'bg-white text-brand shadow-sm' : 'text-gray-500'}`}>
|
||||
Feedback
|
||||
</button>
|
||||
<button onClick={() => setTab('types')}
|
||||
className={`flex-1 py-2 rounded-lg text-sm font-medium transition ${tab === 'types' ? 'bg-white text-brand shadow-sm' : 'text-gray-500'}`}>
|
||||
className={`flex-1 min-w-[4.5rem] 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'}`}>
|
||||
className={`flex-1 min-w-[4.5rem] 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('scale')}
|
||||
className={`flex-1 min-w-[4.5rem] py-2 rounded-lg text-sm font-medium transition ${tab === 'scale' ? 'bg-white text-brand shadow-sm' : 'text-gray-500'}`}>
|
||||
Skala
|
||||
</button>
|
||||
<button onClick={() => setTab('aiPrompts')}
|
||||
className={`flex-1 py-2 rounded-lg text-sm font-medium transition ${tab === 'aiPrompts' ? 'bg-white text-brand shadow-sm' : 'text-gray-500'}`}>
|
||||
className={`flex-1 min-w-[4.5rem] py-2 rounded-lg text-sm font-medium transition ${tab === 'aiPrompts' ? 'bg-white text-brand shadow-sm' : 'text-gray-500'}`}>
|
||||
KI-Prompts
|
||||
</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'}`}>
|
||||
className={`flex-1 min-w-[4.5rem] py-2 rounded-lg text-sm font-medium transition ${tab === 'backup' ? 'bg-white text-brand shadow-sm' : 'text-gray-500'}`}>
|
||||
Backup
|
||||
</button>
|
||||
</div>
|
||||
@@ -76,6 +80,7 @@ export default function Configuration() {
|
||||
{tab === 'feedback' && <FeedbackStructureConfig />}
|
||||
{tab === 'types' && <AssignmentTypeConfig />}
|
||||
{tab === 'weighting' && <RatingWeightConfig />}
|
||||
{tab === 'scale' && <RatingScaleConfig />}
|
||||
{tab === 'aiPrompts' && <AiPromptConfig />}
|
||||
|
||||
{tab === 'backup' && (
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useNavigate } from 'react-router-dom'
|
||||
import {
|
||||
type Assignment, type Consultant,
|
||||
type FeedbackDimension, type FeedbackCategory,
|
||||
type FeedbackRating,
|
||||
type RatingScore,
|
||||
listAssignments, listConsultants,
|
||||
loadFeedbackStructure,
|
||||
listAssessmentsAll,
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
listDoneMeetingsChronological,
|
||||
listAssignmentFeedbacksAll,
|
||||
} from '../db'
|
||||
import { RATING_OPTIONS } from '../config/constants'
|
||||
import { DEFAULT_RATING_COLOR_BANDS, resolveScoreStyle } from '../config/constants'
|
||||
import { buildGroupMeetingScores, computeTrend, type TrendResult } from '../utils/ratingTrend'
|
||||
|
||||
interface CatScore {
|
||||
@@ -36,22 +36,13 @@ function feedbackStatusBadge(status: InstScore['feedbackStatus']) {
|
||||
}
|
||||
|
||||
function ratingColor(avg: number | null): string {
|
||||
if (avg === null) return 'bg-gray-100 text-gray-400'
|
||||
if (avg >= 3.5) return 'bg-green-100 text-green-700'
|
||||
if (avg >= 2.5) return 'bg-lime-100 text-lime-700'
|
||||
if (avg >= 1.5) return 'bg-orange-100 text-orange-700'
|
||||
return 'bg-red-100 text-red-700'
|
||||
const rounded = avg === null ? null : Math.round(avg)
|
||||
return resolveScoreStyle(rounded as RatingScore | null, DEFAULT_RATING_COLOR_BANDS).color
|
||||
}
|
||||
|
||||
function ratingLabel(avg: number | null): string {
|
||||
if (avg === null) return '—'
|
||||
const r = RATING_OPTIONS.find(o =>
|
||||
avg >= 3.5 ? o.value === 'client_ready' :
|
||||
avg >= 2.5 ? o.value === 'nearly_client_ready' :
|
||||
avg >= 1.5 ? o.value === 'partially_client_ready' :
|
||||
o.value === 'not_client_ready'
|
||||
)
|
||||
return r ? `${r.short} (${avg.toFixed(1)})` : avg.toFixed(1)
|
||||
return avg.toFixed(1)
|
||||
}
|
||||
|
||||
function trendArrow(trend: TrendResult['trend']) {
|
||||
@@ -98,7 +89,7 @@ export default function Evaluation() {
|
||||
)
|
||||
if (instAssessments.length === 0) continue
|
||||
|
||||
const getScore = (meetingId: number, itemId: number): FeedbackRating | null =>
|
||||
const getScore = (meetingId: number, itemId: number): RatingScore | null =>
|
||||
instAssessments.find(as => as.meetingInstanceId === meetingId && as.criteriaId === itemId)?.score ?? null
|
||||
|
||||
const catScores: CatScore[] = cats.map(cat => {
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
type FeedbackCategory,
|
||||
type FeedbackCriterionItem,
|
||||
type FeedbackDraft,
|
||||
type FeedbackRating,
|
||||
getAssignment, getConsultant,
|
||||
listFeedbackCategoriesOrdered, getFeedbackCriterionItemsByIds,
|
||||
listMeetingInstancesForAssignment,
|
||||
@@ -14,21 +13,19 @@ import {
|
||||
listConversationEntriesForMeetings,
|
||||
getFeedbackDraft, addFeedbackDraft, updateFeedbackDraft,
|
||||
} from '../db'
|
||||
import { RATING_OPTIONS, RATING_NUM_MAP } from '../config/constants'
|
||||
import { numberToRating } from '../utils/ratingTrend'
|
||||
|
||||
const ratingToNum = (r: FeedbackRating | null | undefined): number =>
|
||||
r ? (RATING_NUM_MAP[r] ?? 0) : 0
|
||||
import {
|
||||
DEFAULT_RATING_COLOR_BANDS, isValidRatingScore, resolveScoreStyle,
|
||||
} from '../config/constants'
|
||||
import type { RatingScore } from '../db/types'
|
||||
|
||||
const ratingLabel = (avg: number | null): string => {
|
||||
if (avg === null) return '—'
|
||||
const r = RATING_OPTIONS.find(x => x.value === numberToRating(avg))
|
||||
return r ? `${r.short} (${avg.toFixed(1)})` : avg.toFixed(1)
|
||||
return `${avg.toFixed(1)}/10`
|
||||
}
|
||||
|
||||
const scoreColor = (avg: number | null): string => {
|
||||
if (avg === null) return 'bg-gray-100 text-gray-400'
|
||||
return RATING_OPTIONS.find(r => r.value === numberToRating(avg))?.color ?? 'bg-gray-100 text-gray-400'
|
||||
const rounded = avg === null ? null : Math.round(avg)
|
||||
return resolveScoreStyle(rounded as RatingScore | null, DEFAULT_RATING_COLOR_BANDS).color
|
||||
}
|
||||
|
||||
interface CriterionSummary {
|
||||
@@ -73,21 +70,25 @@ export default function FeedbackDraftPage() {
|
||||
const instAssessments = allAssessments.filter(a => a.instituteeId === instId)
|
||||
const instEntries = allEntries.filter(e => e.instituteeId === instId)
|
||||
const allLineTags = instEntries.flatMap(e => e.lineTags ?? [])
|
||||
// Allgemeine Notizen sind an kein Institutee gebunden — zählen daher ungefiltert für jedes Institutee.
|
||||
const generalNoteTags = meetings.flatMap(m => m.generalNoteTags ?? [])
|
||||
|
||||
const criteriaIds = [...new Set([
|
||||
...instAssessments.map(a => a.criteriaId),
|
||||
...allLineTags.map(t => t.criterionItemId),
|
||||
...generalNoteTags.map(t => t.criterionItemId),
|
||||
])]
|
||||
const crits = await getFeedbackCriterionItemsByIds(criteriaIds)
|
||||
|
||||
const sum: CriterionSummary[] = crits.map(crit => {
|
||||
const relevant = instAssessments.filter(a => a.criteriaId === crit.id && a.score !== null && a.score !== 'na')
|
||||
const relevant = instAssessments.filter(a => a.criteriaId === crit.id && isValidRatingScore(a.score))
|
||||
const avg = relevant.length > 0
|
||||
? relevant.reduce((s, a) => s + ratingToNum(a.score), 0) / relevant.length
|
||||
? relevant.reduce((s, a) => s + (a.score as number), 0) / relevant.length
|
||||
: null
|
||||
const notes = [
|
||||
...instAssessments.filter(a => a.criteriaId === crit.id && a.note).map(a => a.note),
|
||||
...allLineTags.filter(t => t.criterionItemId === crit.id).map(t => t.text),
|
||||
...generalNoteTags.filter(t => t.criterionItemId === crit.id).map(t => t.text),
|
||||
]
|
||||
return { criterion: crit, avg, notes }
|
||||
})
|
||||
|
||||
@@ -1,29 +1,87 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import {
|
||||
type FeedbackDimension, type FeedbackCategory, type FeedbackCriterionItem,
|
||||
type FeedbackDimension, type FeedbackCategory, type FeedbackCriterionItem, type CriterionUsage, type CriterionUsageInstance,
|
||||
loadFeedbackStructure,
|
||||
addFeedbackDimension, updateFeedbackDimension, deleteFeedbackDimension,
|
||||
addFeedbackCategory, updateFeedbackCategory, deleteFeedbackCategory,
|
||||
addFeedbackCriterionItem, updateFeedbackCriterionItem, deleteFeedbackCriterionItem,
|
||||
getCriterionUsageMap, reassignCriterionReferences,
|
||||
getCriterionUsageDetails, reassignUsageInstance, removeUsageInstance,
|
||||
preloadFinalFeedbackStructure, importFeedbackStructureFromMarkdown,
|
||||
} from '../db'
|
||||
import { exportFeedbackStructureAsMarkdown } from '../utils/structureExport'
|
||||
import { exportFeedbackStructurePdf } from '../utils/pdfExport'
|
||||
import { criterionOptionGroups } from '../utils/criterionOptions'
|
||||
import { summarizeFeedbackStructureSeed, parseFeedbackStructureMarkdown } from '../utils/feedbackStructureImport'
|
||||
|
||||
const totalUsage = (u: CriterionUsage | undefined): number =>
|
||||
!u ? 0 : u.assessmentCount + u.lineTagCount + u.generalNoteTagCount + u.assignmentTypeNames.length + u.phaseTemplateLabels.length
|
||||
|
||||
const instanceKindLabel: Record<CriterionUsageInstance['kind'], string> = {
|
||||
assessment: 'Bewertung',
|
||||
lineTag: 'Protokollzeile',
|
||||
generalNoteTag: 'Allgemeine Notiz',
|
||||
assignmentTypeVisibility: 'Sichtbarkeit (Assignment-Typ)',
|
||||
phaseTemplateVisibility: 'Sichtbarkeit (Phase)',
|
||||
}
|
||||
|
||||
/** Die drei "Daten"-Kinds haben Meeting/Person-Kontext, die zwei "Sichtbarkeits"-Kinds nicht. */
|
||||
const isDataInstance = (
|
||||
instance: CriterionUsageInstance,
|
||||
): instance is Extract<CriterionUsageInstance, { kind: 'assessment' | 'lineTag' | 'generalNoteTag' }> =>
|
||||
instance.kind === 'assessment' || instance.kind === 'lineTag' || instance.kind === 'generalNoteTag'
|
||||
|
||||
/**
|
||||
* Stabiler, inhaltsbasierter Schlüssel statt Array-Index — der Index verschiebt sich nach jedem
|
||||
* Übertragen/Entfernen, weil die Instanzen-Liste neu vom Server geladen wird. Mit dem Index als
|
||||
* Schlüssel hingen ausgewählte Ziel-Kriterien danach plötzlich an der falschen (neu an dieser
|
||||
* Position stehenden) Instanz.
|
||||
*/
|
||||
const instanceKey = (instance: CriterionUsageInstance): string => {
|
||||
switch (instance.kind) {
|
||||
case 'assessment': return `assessment:${instance.assessmentId}`
|
||||
case 'lineTag': return `lineTag:${instance.conversationEntryId}:${instance.tagText}`
|
||||
case 'generalNoteTag': return `generalNoteTag:${instance.meetingInstanceId}:${instance.tagText}`
|
||||
case 'assignmentTypeVisibility': return `atVis:${instance.assignmentTypeId}`
|
||||
case 'phaseTemplateVisibility': return `ptVis:${instance.phaseTemplateId}`
|
||||
}
|
||||
}
|
||||
|
||||
export default function FeedbackStructureConfig() {
|
||||
const [dimensions, setDimensions] = useState<FeedbackDimension[]>([])
|
||||
const [categories, setCategories] = useState<FeedbackCategory[]>([])
|
||||
const [items, setItems] = useState<FeedbackCriterionItem[]>([])
|
||||
const [usageMap, setUsageMap] = useState<Record<number, CriterionUsage>>({})
|
||||
const [usageDetails, setUsageDetails] = useState<Record<number, CriterionUsageInstance[]>>({})
|
||||
const [loadingUsage, setLoadingUsage] = useState<Set<number>>(new Set())
|
||||
const [instanceTarget, setInstanceTarget] = useState<Record<string, number>>({})
|
||||
const [instanceNotice, setInstanceNotice] = useState<Record<number, string>>({})
|
||||
const [expanded, setExpanded] = useState<Set<number>>(new Set())
|
||||
const [expandedCat, setExpandedCat] = useState<Set<number>>(new Set())
|
||||
const [expandedUsage, setExpandedUsage] = useState<Set<number>>(new Set())
|
||||
|
||||
// Neue Einträge
|
||||
const [newDimName, setNewDimName] = useState('')
|
||||
const [newCatName, setNewCatName] = useState<Record<number, string>>({})
|
||||
const [newItemName, setNewItemName] = useState<Record<number, string>>({})
|
||||
const [exportingPdf, setExportingPdf] = useState(false)
|
||||
const [importingStructure, setImportingStructure] = useState(false)
|
||||
const [importNotice, setImportNotice] = useState<string | null>(null)
|
||||
const [confirmPreload, setConfirmPreload] = useState(false)
|
||||
|
||||
// Lösch-Bestätigungen & Übertragen-auf-anderes-Kriterium
|
||||
const [confirmDeleteDimId, setConfirmDeleteDimId] = useState<number | null>(null)
|
||||
const [confirmDeleteCatId, setConfirmDeleteCatId] = useState<number | null>(null)
|
||||
const [confirmDeleteItemId, setConfirmDeleteItemId] = useState<number | null>(null)
|
||||
const [reassignTarget, setReassignTarget] = useState<Record<number, number>>({})
|
||||
const [mergeNotice, setMergeNotice] = useState('')
|
||||
|
||||
const load = async () => {
|
||||
const structure = await loadFeedbackStructure()
|
||||
const [structure, usage] = await Promise.all([loadFeedbackStructure(), getCriterionUsageMap()])
|
||||
setDimensions(structure.dimensions)
|
||||
setCategories(structure.categories)
|
||||
setItems(structure.items)
|
||||
setUsageMap(usage)
|
||||
}
|
||||
|
||||
useEffect(() => { load() }, [])
|
||||
@@ -39,13 +97,23 @@ export default function FeedbackStructureConfig() {
|
||||
setExpanded(prev => new Set([...prev, id]))
|
||||
}
|
||||
|
||||
const updateDimension = async (id: number, name: string) => {
|
||||
await updateFeedbackDimension(id, { name })
|
||||
const updateDimension = (id: number, name: string) => {
|
||||
setDimensions(prev => prev.map(d => d.id === id ? { ...d, name } : d))
|
||||
updateFeedbackDimension(id, { name })
|
||||
}
|
||||
|
||||
const dimensionUsageTotal = (dimId: number): number =>
|
||||
categories.filter(c => c.dimensionId === dimId)
|
||||
.reduce((sum, cat) => sum + categoryUsageTotal(cat.id!), 0)
|
||||
|
||||
const requestDeleteDimension = (id: number) => {
|
||||
if (dimensionUsageTotal(id) === 0) { deleteDimension(id); return }
|
||||
setConfirmDeleteDimId(id)
|
||||
}
|
||||
|
||||
const deleteDimension = async (id: number) => {
|
||||
await deleteFeedbackDimension(id)
|
||||
setConfirmDeleteDimId(null)
|
||||
await load()
|
||||
}
|
||||
|
||||
@@ -72,13 +140,27 @@ export default function FeedbackStructureConfig() {
|
||||
setExpandedCat(prev => new Set([...prev, id]))
|
||||
}
|
||||
|
||||
const updateCategory = async (id: number, name: string) => {
|
||||
await updateFeedbackCategory(id, { name })
|
||||
const updateCategory = (id: number, name: string) => {
|
||||
setCategories(prev => prev.map(c => c.id === id ? { ...c, name } : c))
|
||||
updateFeedbackCategory(id, { name })
|
||||
}
|
||||
|
||||
const updateCategoryDescription = (id: number, description: string) => {
|
||||
setCategories(prev => prev.map(c => c.id === id ? { ...c, description } : c))
|
||||
updateFeedbackCategory(id, { description })
|
||||
}
|
||||
|
||||
const categoryUsageTotal = (catId: number): number =>
|
||||
items.filter(i => i.categoryId === catId).reduce((sum, i) => sum + totalUsage(usageMap[i.id!]), 0)
|
||||
|
||||
const requestDeleteCategory = (id: number) => {
|
||||
if (categoryUsageTotal(id) === 0) { deleteCategory(id); return }
|
||||
setConfirmDeleteCatId(id)
|
||||
}
|
||||
|
||||
const deleteCategory = async (id: number) => {
|
||||
await deleteFeedbackCategory(id)
|
||||
setConfirmDeleteCatId(null)
|
||||
await load()
|
||||
}
|
||||
|
||||
@@ -94,31 +176,220 @@ export default function FeedbackStructureConfig() {
|
||||
await load()
|
||||
}
|
||||
|
||||
const updateItem = async (id: number, name: string) => {
|
||||
await updateFeedbackCriterionItem(id, { name })
|
||||
const updateItem = (id: number, name: string) => {
|
||||
setItems(prev => prev.map(i => i.id === id ? { ...i, name } : i))
|
||||
updateFeedbackCriterionItem(id, { name })
|
||||
}
|
||||
|
||||
const requestDeleteItem = (id: number) => {
|
||||
if (totalUsage(usageMap[id]) === 0) { deleteItem(id); return }
|
||||
setMergeNotice('')
|
||||
setConfirmDeleteItemId(id)
|
||||
}
|
||||
|
||||
const deleteItem = async (id: number) => {
|
||||
await deleteFeedbackCriterionItem(id)
|
||||
setItems(prev => prev.filter(i => i.id !== id))
|
||||
setConfirmDeleteItemId(null)
|
||||
await load()
|
||||
}
|
||||
|
||||
const updateItemWeight = async (id: number, weight: number) => {
|
||||
await updateFeedbackCriterionItem(id, { weight })
|
||||
const reassignAndDeleteItem = async (fromId: number) => {
|
||||
const toId = reassignTarget[fromId]
|
||||
if (!toId) return
|
||||
const { mergedConflicts } = await reassignCriterionReferences(fromId, toId)
|
||||
await deleteFeedbackCriterionItem(fromId)
|
||||
setConfirmDeleteItemId(null)
|
||||
setMergeNotice(mergedConflicts > 0 ? `${mergedConflicts} Bewertung(en) wurden dabei mit bereits vorhandenen Bewertungen des Ziel-Kriteriums zusammengeführt.` : '')
|
||||
await load()
|
||||
}
|
||||
|
||||
const updateItemWeight = (id: number, weight: number) => {
|
||||
setItems(prev => prev.map(i => i.id === id ? { ...i, weight } : i))
|
||||
updateFeedbackCriterionItem(id, { weight })
|
||||
}
|
||||
|
||||
const updateItemDescription = async (id: number, description: string) => {
|
||||
await updateFeedbackCriterionItem(id, { description })
|
||||
const updateItemDescription = (id: number, description: string) => {
|
||||
setItems(prev => prev.map(i => i.id === id ? { ...i, description } : i))
|
||||
updateFeedbackCriterionItem(id, { description })
|
||||
}
|
||||
|
||||
const moveItemToCategory = (itemId: number, newCategoryId: number) => {
|
||||
setItems(prev => prev.map(i => i.id === itemId ? { ...i, categoryId: newCategoryId } : i))
|
||||
updateFeedbackCriterionItem(itemId, { categoryId: newCategoryId })
|
||||
}
|
||||
|
||||
const toggleUsageExpanded = async (itemId: number) => {
|
||||
const willOpen = !expandedUsage.has(itemId)
|
||||
setExpandedUsage(prev => {
|
||||
const next = new Set(prev)
|
||||
if (next.has(itemId)) next.delete(itemId); else next.add(itemId)
|
||||
return next
|
||||
})
|
||||
if (willOpen && !usageDetails[itemId]) {
|
||||
setLoadingUsage(prev => new Set(prev).add(itemId))
|
||||
const details = await getCriterionUsageDetails(itemId)
|
||||
setUsageDetails(prev => ({ ...prev, [itemId]: details }))
|
||||
setLoadingUsage(prev => { const next = new Set(prev); next.delete(itemId); return next })
|
||||
}
|
||||
}
|
||||
|
||||
const refreshUsageAfterInstanceChange = async (itemId: number) => {
|
||||
const [details, usage] = await Promise.all([getCriterionUsageDetails(itemId), getCriterionUsageMap()])
|
||||
setUsageDetails(prev => ({ ...prev, [itemId]: details }))
|
||||
setUsageMap(usage)
|
||||
}
|
||||
|
||||
const reassignOneInstance = async (itemId: number, instance: CriterionUsageInstance) => {
|
||||
const key = `${itemId}:${instanceKey(instance)}`
|
||||
const toId = instanceTarget[key]
|
||||
if (!toId) return
|
||||
const { merged } = await reassignUsageInstance(instance, toId)
|
||||
setInstanceTarget(prev => { const next = { ...prev }; delete next[key]; return next })
|
||||
setInstanceNotice(prev => ({ ...prev, [itemId]: merged ? 'Mit vorhandener Bewertung des Ziel-Kriteriums zusammengeführt.' : 'Übertragen.' }))
|
||||
await refreshUsageAfterInstanceChange(itemId)
|
||||
}
|
||||
|
||||
const removeOneInstance = async (itemId: number, instance: CriterionUsageInstance) => {
|
||||
await removeUsageInstance(instance)
|
||||
setInstanceNotice(prev => ({ ...prev, [itemId]: 'Zuordnung entfernt.' }))
|
||||
await refreshUsageAfterInstanceChange(itemId)
|
||||
}
|
||||
|
||||
const runPreloadFinal = async () => {
|
||||
setImportingStructure(true)
|
||||
setImportNotice(null)
|
||||
setConfirmPreload(false)
|
||||
try {
|
||||
const result = await preloadFinalFeedbackStructure()
|
||||
setImportNotice(
|
||||
`Finale Struktur geladen: ${result.dimensions} Dimensionen, ${result.categories} Kategorien, ${result.items} Kriterien`
|
||||
+ (result.clearedDimensions ? ` (vorher ${result.clearedDimensions} Dimensionen ersetzt)` : ''),
|
||||
)
|
||||
await load()
|
||||
} catch (e) {
|
||||
setImportNotice(`Import fehlgeschlagen: ${e instanceof Error ? e.message : String(e)}`)
|
||||
} finally {
|
||||
setImportingStructure(false)
|
||||
}
|
||||
}
|
||||
|
||||
const importMarkdownFile = async (file: File) => {
|
||||
setImportingStructure(true)
|
||||
setImportNotice(null)
|
||||
try {
|
||||
const md = await file.text()
|
||||
const seed = parseFeedbackStructureMarkdown(md)
|
||||
const sum = summarizeFeedbackStructureSeed(seed)
|
||||
const result = await importFeedbackStructureFromMarkdown(md)
|
||||
setImportNotice(
|
||||
`MD importiert: ${result.dimensions} Dimensionen, ${result.categories} Kategorien, ${result.items} Kriterien`
|
||||
+ ` (Datei: ${sum.items} Kriterien erkannt)`,
|
||||
)
|
||||
await load()
|
||||
} catch (e) {
|
||||
setImportNotice(`MD-Import fehlgeschlagen: ${e instanceof Error ? e.message : String(e)}`)
|
||||
} finally {
|
||||
setImportingStructure(false)
|
||||
}
|
||||
}
|
||||
|
||||
const sorted = [...dimensions].sort((a, b) => a.order - b.order)
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<h2 className="text-lg font-bold text-gray-800">Feedback-Dimensionen & Kategorien</h2>
|
||||
<div className="flex items-center justify-between gap-2 flex-wrap">
|
||||
<h2 className="text-lg font-bold text-gray-800">Feedback-Dimensionen & Kategorien</h2>
|
||||
<div className="flex gap-1.5 flex-shrink-0 flex-wrap">
|
||||
{!confirmPreload ? (
|
||||
<button
|
||||
onClick={() => setConfirmPreload(true)}
|
||||
disabled={importingStructure}
|
||||
className="text-xs px-2.5 py-1.5 border border-brand/30 rounded-lg text-brand hover:bg-brand/5 transition disabled:opacity-50">
|
||||
Preload final
|
||||
</button>
|
||||
) : (
|
||||
<div className="flex gap-1">
|
||||
<button
|
||||
onClick={runPreloadFinal}
|
||||
disabled={importingStructure}
|
||||
className="text-xs px-2.5 py-1.5 bg-brand text-white rounded-lg disabled:opacity-50">
|
||||
{importingStructure ? '…' : 'Ersetzen bestätigen'}
|
||||
</button>
|
||||
<button onClick={() => setConfirmPreload(false)}
|
||||
className="text-xs px-2.5 py-1.5 border border-gray-200 rounded-lg text-gray-500">
|
||||
Abbrechen
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<label className={`text-xs px-2.5 py-1.5 border border-gray-200 rounded-lg text-gray-500 hover:border-brand hover:text-brand transition cursor-pointer ${importingStructure ? 'opacity-50 pointer-events-none' : ''}`}>
|
||||
↑ MD
|
||||
<input
|
||||
type="file"
|
||||
accept=".md,text/markdown,text/plain"
|
||||
className="hidden"
|
||||
onChange={e => {
|
||||
const file = e.target.files?.[0]
|
||||
if (file) importMarkdownFile(file)
|
||||
e.target.value = ''
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
<button onClick={() => exportFeedbackStructureAsMarkdown()}
|
||||
className="text-xs px-2.5 py-1.5 border border-gray-200 rounded-lg text-gray-500 hover:border-brand hover:text-brand transition">
|
||||
⬇ MD
|
||||
</button>
|
||||
<button
|
||||
onClick={async () => { setExportingPdf(true); try { await exportFeedbackStructurePdf() } finally { setExportingPdf(false) } }}
|
||||
disabled={exportingPdf}
|
||||
className="text-xs px-2.5 py-1.5 border border-gray-200 rounded-lg text-gray-500 hover:border-brand hover:text-brand transition disabled:opacity-50">
|
||||
{exportingPdf ? '⏳' : '⬇ PDF'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{importNotice && (
|
||||
<div className="rounded-xl px-4 py-3 text-sm bg-blue-50 text-blue-800 border border-blue-200">
|
||||
{importNotice}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{confirmPreload && (
|
||||
<div className="rounded-xl px-4 py-3 text-sm bg-amber-50 text-amber-800 border border-amber-200">
|
||||
Ersetzt die gesamte Feedback-Struktur durch die finale Preload-Datei
|
||||
(<code className="mx-1 text-xs bg-amber-100 px-1 rounded">docs/preload/Feedback-Struktur-final.md</code>
|
||||
(3 Dimensionen, 16 Kategorien, 109 Kriterien). Bestehende Dimensionen/Kategorien/Kriterien werden gelöscht.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Fokus-Übersicht: was wird über alle Bewerter hinweg am häufigsten kommentiert (siehe CLAUDE.md „Beobachter-Fokus") */}
|
||||
{items.length > 0 && (
|
||||
<details className="bg-white rounded-xl border border-gray-100 shadow-sm p-3">
|
||||
<summary className="text-sm font-semibold text-gray-700 cursor-pointer select-none">📊 Fokus-Übersicht — am häufigsten kommentierte Kriterien</summary>
|
||||
<div className="mt-2 space-y-1.5">
|
||||
{[...items]
|
||||
.sort((a, b) => totalUsage(usageMap[b.id!]) - totalUsage(usageMap[a.id!]))
|
||||
.slice(0, 5)
|
||||
.filter(i => totalUsage(usageMap[i.id!]) > 0)
|
||||
.map(i => (
|
||||
<div key={i.id} className="flex items-start justify-between gap-2 text-xs">
|
||||
<div className="min-w-0">
|
||||
<span className="font-medium text-gray-700">{i.name}</span>
|
||||
{i.learnedPatternHints && (
|
||||
<div className="text-gray-400 truncate">{i.learnedPatternHints}</div>
|
||||
)}
|
||||
</div>
|
||||
<span className="flex-shrink-0 bg-blue-50 text-blue-700 border border-blue-200 px-1.5 py-0.5 rounded-full font-semibold">
|
||||
{totalUsage(usageMap[i.id!])}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
{items.every(i => totalUsage(usageMap[i.id!]) === 0) && (
|
||||
<div className="text-xs text-gray-400">Noch keine Verwendungen erfasst.</div>
|
||||
)}
|
||||
</div>
|
||||
</details>
|
||||
)}
|
||||
|
||||
{/* Neue Dimension */}
|
||||
<div className="flex gap-2">
|
||||
@@ -160,10 +431,22 @@ export default function FeedbackStructureConfig() {
|
||||
if (next.has(dim.id!)) next.delete(dim.id!); else next.add(dim.id!)
|
||||
return next
|
||||
})} className="text-xs text-gray-400 px-1">{isOpen ? '▲' : '▼'}</button>
|
||||
<button onClick={() => deleteDimension(dim.id!)}
|
||||
<button onClick={() => requestDeleteDimension(dim.id!)}
|
||||
className="text-xs text-red-300 hover:text-red-500 px-1">🗑</button>
|
||||
</div>
|
||||
|
||||
{confirmDeleteDimId === dim.id && (
|
||||
<div className="px-3 py-2 bg-red-50 border-b border-red-100 flex items-center justify-between gap-2">
|
||||
<span className="text-xs text-red-700">
|
||||
Diese Dimension enthält Kriterien mit insgesamt {dimensionUsageTotal(dim.id!)} Verwendung(en) — werden beim Löschen mit entfernt.
|
||||
</span>
|
||||
<div className="flex gap-1.5 flex-shrink-0">
|
||||
<button onClick={() => deleteDimension(dim.id!)} className="text-xs bg-red-600 text-white px-2.5 py-1 rounded-lg font-medium">Trotzdem löschen</button>
|
||||
<button onClick={() => setConfirmDeleteDimId(null)} className="text-xs border border-gray-200 text-gray-500 px-2.5 py-1 rounded-lg">Abbrechen</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isOpen && (
|
||||
<div className="p-3 space-y-3">
|
||||
{dimCats.map(cat => {
|
||||
@@ -182,13 +465,35 @@ export default function FeedbackStructureConfig() {
|
||||
if (next.has(cat.id!)) next.delete(cat.id!); else next.add(cat.id!)
|
||||
return next
|
||||
})} className="text-xs text-gray-400">{isCatOpen ? '▲' : '▼'}</button>
|
||||
<button onClick={() => deleteCategory(cat.id!)}
|
||||
<button onClick={() => requestDeleteCategory(cat.id!)}
|
||||
className="text-xs text-red-300 hover:text-red-500">🗑</button>
|
||||
</div>
|
||||
<input
|
||||
className="w-full px-3 py-1.5 text-xs text-gray-400 border-b border-gray-100 focus:outline-none focus:border-brand bg-white"
|
||||
placeholder="Erläuterung, welche Themen/Beobachtungen in diese Kategorie einzahlen (optional, fließt in KI-Prompts ein)…"
|
||||
value={cat.description ?? ''}
|
||||
onChange={e => updateCategoryDescription(cat.id!, e.target.value)}
|
||||
/>
|
||||
|
||||
{confirmDeleteCatId === cat.id && (
|
||||
<div className="px-3 py-2 bg-red-50 border-b border-red-100 flex items-center justify-between gap-2">
|
||||
<span className="text-xs text-red-700">
|
||||
Diese Kategorie enthält Kriterien mit insgesamt {categoryUsageTotal(cat.id!)} Verwendung(en) — werden beim Löschen mit entfernt.
|
||||
</span>
|
||||
<div className="flex gap-1.5 flex-shrink-0">
|
||||
<button onClick={() => deleteCategory(cat.id!)} className="text-xs bg-red-600 text-white px-2.5 py-1 rounded-lg font-medium">Trotzdem löschen</button>
|
||||
<button onClick={() => setConfirmDeleteCatId(null)} className="text-xs border border-gray-200 text-gray-500 px-2.5 py-1 rounded-lg">Abbrechen</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isCatOpen && (
|
||||
<div className="p-2 space-y-1.5">
|
||||
{catItems.map(item => (
|
||||
{catItems.map(item => {
|
||||
const usage = usageMap[item.id!]
|
||||
const usageCount = totalUsage(usage)
|
||||
const isUsageOpen = expandedUsage.has(item.id!)
|
||||
return (
|
||||
<div key={item.id} className="space-y-0.5">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-gray-300 text-xs">·</span>
|
||||
@@ -204,7 +509,23 @@ export default function FeedbackStructureConfig() {
|
||||
title="Gewichtung"
|
||||
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!)}
|
||||
<select
|
||||
value=""
|
||||
onChange={e => e.target.value && moveItemToCategory(item.id!, Number(e.target.value))}
|
||||
title="In andere Kategorie verschieben"
|
||||
className="text-xs border border-gray-200 rounded px-1 py-0.5 text-gray-500 bg-white focus:outline-none focus:border-brand max-w-[7rem]">
|
||||
<option value="">Verschieben…</option>
|
||||
{sorted.map(d => {
|
||||
const dimCats = categories.filter(c => c.dimensionId === d.id && c.id !== item.categoryId).sort((a, b) => a.order - b.order)
|
||||
if (dimCats.length === 0) return null
|
||||
return (
|
||||
<optgroup key={d.id} label={d.name}>
|
||||
{dimCats.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
|
||||
</optgroup>
|
||||
)
|
||||
})}
|
||||
</select>
|
||||
<button onClick={() => requestDeleteItem(item.id!)}
|
||||
className="text-xs text-red-200 hover:text-red-400">×</button>
|
||||
</div>
|
||||
<input
|
||||
@@ -213,8 +534,101 @@ export default function FeedbackStructureConfig() {
|
||||
value={item.description ?? ''}
|
||||
onChange={e => updateItemDescription(item.id!, e.target.value)}
|
||||
/>
|
||||
|
||||
{usageCount > 0 && (
|
||||
<div className="ml-3.5">
|
||||
<button onClick={() => toggleUsageExpanded(item.id!)}
|
||||
className="text-xs bg-indigo-50 text-indigo-600 border border-indigo-100 px-1.5 py-0.5 rounded-full">
|
||||
{usageCount} Verwendung(en) {isUsageOpen ? '▲' : '▼'}
|
||||
</button>
|
||||
{isUsageOpen && (
|
||||
<div className="mt-1 space-y-1.5">
|
||||
{instanceNotice[item.id!] && (
|
||||
<div className="text-xs text-indigo-600 bg-indigo-50 border border-indigo-100 rounded-lg px-2 py-1">
|
||||
{instanceNotice[item.id!]}
|
||||
</div>
|
||||
)}
|
||||
{loadingUsage.has(item.id!) && <div className="text-xs text-gray-400">Lädt…</div>}
|
||||
{(usageDetails[item.id!] ?? []).map(instance => {
|
||||
const key = `${item.id}:${instanceKey(instance)}`
|
||||
return (
|
||||
<div key={key} className="bg-gray-50 border border-gray-100 rounded-lg p-1.5 space-y-1">
|
||||
<div className="text-xs text-gray-600">
|
||||
<span className="font-medium">{instanceKindLabel[instance.kind]}</span>
|
||||
{isDataInstance(instance) && (
|
||||
<>
|
||||
{' · '}{instance.assignmentTitle} ({instance.date ? new Date(instance.date).toLocaleDateString('de-DE') : '—'})
|
||||
{' · '}{instance.personLabel}
|
||||
</>
|
||||
)}
|
||||
<div className="text-gray-400 truncate">{instance.text}</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-1 flex-wrap">
|
||||
<select
|
||||
value={instanceTarget[key] ?? ''}
|
||||
onChange={e => setInstanceTarget(prev => ({ ...prev, [key]: Number(e.target.value) }))}
|
||||
className="text-xs border border-gray-200 rounded px-1 py-0.5 bg-white focus:outline-none">
|
||||
<option value="">→ anderes Kriterium…</option>
|
||||
{criterionOptionGroups(dimensions, categories, items, item.id)}
|
||||
</select>
|
||||
<button
|
||||
onClick={() => reassignOneInstance(item.id!, instance)}
|
||||
disabled={!instanceTarget[key]}
|
||||
className="text-xs bg-indigo-600 text-white px-1.5 py-0.5 rounded font-medium disabled:opacity-40">
|
||||
Übertragen
|
||||
</button>
|
||||
<button
|
||||
onClick={() => removeOneInstance(item.id!, instance)}
|
||||
className="text-xs bg-red-100 text-red-600 px-1.5 py-0.5 rounded font-medium">
|
||||
Entfernen
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{confirmDeleteItemId === item.id && (
|
||||
<div className="ml-3.5 bg-red-50 border border-red-200 rounded-lg p-2 space-y-1.5">
|
||||
<div className="text-xs text-red-700">
|
||||
Wird an {usageCount} Stelle(n) verwendet. „Übertragen" verschiebt alle Bewertungen/Zuordnungen auf ein anderes Kriterium (kein Datenverlust). „Trotzdem löschen" entfernt Bewertungen vollständig, Protokollzeilen bleiben als Text erhalten, nur die Zuordnung geht verloren.
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5 flex-wrap">
|
||||
<select
|
||||
value={reassignTarget[item.id!] ?? ''}
|
||||
onChange={e => setReassignTarget(prev => ({ ...prev, [item.id!]: Number(e.target.value) }))}
|
||||
className="text-xs border border-red-200 rounded px-1.5 py-1 bg-white focus:outline-none">
|
||||
<option value="">Übertragen auf…</option>
|
||||
{criterionOptionGroups(dimensions, categories, items, item.id)}
|
||||
</select>
|
||||
<button
|
||||
onClick={() => reassignAndDeleteItem(item.id!)}
|
||||
disabled={!reassignTarget[item.id!]}
|
||||
className="text-xs bg-indigo-600 text-white px-2 py-1 rounded-lg font-medium disabled:opacity-40">
|
||||
Übertragen & löschen
|
||||
</button>
|
||||
<button onClick={() => deleteItem(item.id!)}
|
||||
className="text-xs bg-red-600 text-white px-2 py-1 rounded-lg font-medium">
|
||||
Trotzdem löschen
|
||||
</button>
|
||||
<button onClick={() => setConfirmDeleteItemId(null)}
|
||||
className="text-xs border border-gray-200 text-gray-500 px-2 py-1 rounded-lg">
|
||||
Abbrechen
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
)
|
||||
})}
|
||||
{mergeNotice && (
|
||||
<div className="text-xs text-indigo-600 bg-indigo-50 border border-indigo-100 rounded-lg px-2 py-1.5">
|
||||
{mergeNotice}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex gap-1.5 mt-1">
|
||||
<input
|
||||
className="flex-1 border border-gray-200 rounded px-2 py-1 text-xs focus:outline-none focus:border-brand"
|
||||
|
||||
@@ -2,26 +2,25 @@ import { useEffect, useRef, useState } from 'react'
|
||||
import { useNavigate, useParams } from 'react-router-dom'
|
||||
import {
|
||||
type Assignment, type PhaseTemplate, type MeetingInstance, type Consultant,
|
||||
type FeedbackCategory, type FeedbackCriterionItem, type ConversationEntry, type Assessment, type FeedbackRating,
|
||||
type FeedbackCategory, type FeedbackCriterionItem, type ConversationEntry, type Assessment, type RatingScore,
|
||||
type ChecklistItemDef, type ChecklistResponse,
|
||||
getAssignment, getAssignmentType,
|
||||
listPhaseTemplatesForType,
|
||||
listDoneMeetingsChronological,
|
||||
getConsultantsByIds,
|
||||
listFeedbackCategoriesAll, listFeedbackCriterionItemsAll, filterVisibleFeedbackStructure,
|
||||
loadFeedbackStructure, resolveVisibleStructure,
|
||||
listConversationEntriesForMeetings,
|
||||
listAssessmentsForMeetings,
|
||||
listMeetingCategoryRatingsForMeetings,
|
||||
listChecklistItemDefsForPhaseTemplates,
|
||||
listChecklistResponsesForMeetings,
|
||||
} from '../db'
|
||||
import { NotationText } from '../utils/notationParser'
|
||||
import { INST_COLORS } from '../config/constants'
|
||||
import { weightedAverageRating } from '../utils/ratingTrend'
|
||||
|
||||
const RATING_BG: Record<FeedbackRating, string> = {
|
||||
na: 'bg-gray-400 text-white',
|
||||
not_client_ready: 'bg-red-500 text-white',
|
||||
partially_client_ready: 'bg-orange-500 text-white',
|
||||
nearly_client_ready: 'bg-green-400 text-white',
|
||||
client_ready: 'bg-green-700 text-white',
|
||||
}
|
||||
import { INST_COLORS, resolveScoreStyle } from '../config/constants'
|
||||
import { resolveCategoryChipScore } from '../utils/meetingCategoryScore'
|
||||
import { useRatingColorBands } from '../hooks/useRatingColorBands'
|
||||
import { exportAssignmentReportPdf } from '../utils/pdfExport'
|
||||
import type { MeetingCategoryRating } from '../db'
|
||||
|
||||
export default function MeetingHistory() {
|
||||
const { id } = useParams()
|
||||
@@ -36,8 +35,13 @@ export default function MeetingHistory() {
|
||||
const [fbItems, setFbItems] = useState<FeedbackCriterionItem[]>([])
|
||||
const [entries, setEntries] = useState<ConversationEntry[]>([])
|
||||
const [assessments, setAssessments] = useState<Assessment[]>([])
|
||||
const [categoryRatings, setCategoryRatings] = useState<MeetingCategoryRating[]>([])
|
||||
const [checklistItems, setChecklistItems] = useState<ChecklistItemDef[]>([])
|
||||
const [checklistResponses, setChecklistResponses] = useState<ChecklistResponse[]>([])
|
||||
const [loaded, setLoaded] = useState(false)
|
||||
const [exportingPdf, setExportingPdf] = useState(false)
|
||||
const latestRef = useRef<HTMLDivElement>(null)
|
||||
const colorBands = useRatingColorBands()
|
||||
|
||||
useEffect(() => {
|
||||
const load = async () => {
|
||||
@@ -55,21 +59,25 @@ export default function MeetingHistory() {
|
||||
setMeetings(doneMeetings)
|
||||
setInstitutees(a.instituteeIds.map(cid => cons.find(c => c.id === cid)!).filter(Boolean))
|
||||
|
||||
const [allCats, allItems] = await Promise.all([
|
||||
listFeedbackCategoriesAll(),
|
||||
listFeedbackCriterionItemsAll(),
|
||||
])
|
||||
const { categories: visibleCats, items: visibleItems } = filterVisibleFeedbackStructure(allCats, allItems, aType?.criteriaIds)
|
||||
setFbCategories(visibleCats)
|
||||
setFbItems(visibleItems)
|
||||
const structure = await loadFeedbackStructure()
|
||||
const visible = resolveVisibleStructure(structure.dimensions, structure.categories, structure.items, aType?.criteriaIds)
|
||||
setFbCategories(visible.categories)
|
||||
setFbItems(visible.items)
|
||||
|
||||
const meetingIds = doneMeetings.map(m => m.id!)
|
||||
const [convEntries, asmts] = await Promise.all([
|
||||
const templateIds = tmpls.map(t => t.id!)
|
||||
const [convEntries, asmts, catRatings, checklistDefs, checklistResp] = await Promise.all([
|
||||
listConversationEntriesForMeetings(meetingIds),
|
||||
listAssessmentsForMeetings(meetingIds),
|
||||
listMeetingCategoryRatingsForMeetings(meetingIds),
|
||||
listChecklistItemDefsForPhaseTemplates(templateIds),
|
||||
listChecklistResponsesForMeetings(meetingIds),
|
||||
])
|
||||
setEntries(convEntries)
|
||||
setAssessments(asmts)
|
||||
setCategoryRatings(catRatings)
|
||||
setChecklistItems(checklistDefs)
|
||||
setChecklistResponses(checklistResp)
|
||||
setLoaded(true)
|
||||
}
|
||||
load()
|
||||
@@ -79,6 +87,15 @@ export default function MeetingHistory() {
|
||||
if (loaded) latestRef.current?.scrollIntoView({ block: 'start' })
|
||||
}, [loaded])
|
||||
|
||||
const handleExportPdf = async () => {
|
||||
setExportingPdf(true)
|
||||
try {
|
||||
await exportAssignmentReportPdf(assignmentId)
|
||||
} finally {
|
||||
setExportingPdf(false)
|
||||
}
|
||||
}
|
||||
|
||||
const displayName = (inst: Consultant) => {
|
||||
const dup = institutees.filter(c => c.firstName === inst.firstName && c.id !== inst.id).length > 0
|
||||
return dup ? `${inst.firstName} ${inst.lastName.charAt(0)}.` : inst.firstName
|
||||
@@ -88,10 +105,16 @@ export default function MeetingHistory() {
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<button onClick={() => navigate(`/assignment/${assignmentId}`)} className="text-sm text-brand mb-2 block">← Assignment</button>
|
||||
<h1 className="text-xl font-bold text-gray-800">📜 Gesamtprotokoll</h1>
|
||||
<div className="text-sm text-gray-500">{assignment.title} · {assignment.client}</div>
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div>
|
||||
<button onClick={() => navigate(`/assignment/${assignmentId}`)} className="text-sm text-brand mb-2 block">← Assignment</button>
|
||||
<h1 className="text-xl font-bold text-gray-800">📜 Gesamtprotokoll</h1>
|
||||
<div className="text-sm text-gray-500">{assignment.title} · {assignment.client}</div>
|
||||
</div>
|
||||
<button onClick={handleExportPdf} disabled={exportingPdf}
|
||||
className="flex-shrink-0 text-xs px-3 py-1.5 border border-gray-200 rounded-lg text-gray-500 hover:border-brand hover:text-brand transition disabled:opacity-50">
|
||||
{exportingPdf ? 'Erstelle PDF…' : '⬇ Als PDF exportieren'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{meetings.length === 0 && (
|
||||
@@ -103,7 +126,7 @@ export default function MeetingHistory() {
|
||||
const meetingEntries = entries
|
||||
.filter(e => e.meetingInstanceId === meeting.id)
|
||||
.sort((a, b) => a.sequenceIndex - b.sequenceIndex)
|
||||
const meetingAssessments = assessments.filter(a => a.meetingInstanceId === meeting.id)
|
||||
const meetingChecklistItems = checklistItems.filter(ci => ci.phaseTemplateId === template?.id).sort((a, b) => a.order - b.order)
|
||||
const isLatest = idx === meetings.length - 1
|
||||
|
||||
return (
|
||||
@@ -126,7 +149,16 @@ export default function MeetingHistory() {
|
||||
|
||||
{meeting.generalNotes?.trim() && (
|
||||
<div className="bg-gray-50 rounded-lg px-3 py-2">
|
||||
<NotationText text={meeting.generalNotes} />
|
||||
<NotationText
|
||||
text={meeting.generalNotes}
|
||||
renderLineAddon={line => {
|
||||
const critId = meeting.generalNoteTags?.find(t => t.text === line)?.criterionItemId
|
||||
const critName = critId ? fbItems.find(i => i.id === critId)?.name : null
|
||||
return critName
|
||||
? <span className="flex-shrink-0 text-xs bg-indigo-50 text-indigo-700 border border-indigo-200 rounded-full px-2 py-0.5 mt-0.5">{critName}</span>
|
||||
: null
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -169,23 +201,56 @@ export default function MeetingHistory() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{institutees.length > 0 && fbCategories.length > 0 && meetingAssessments.length > 0 && (
|
||||
{meetingChecklistItems.length > 0 && (
|
||||
<div className="space-y-1 pt-1 border-t border-gray-50">
|
||||
<div className="text-xs font-semibold text-gray-400 uppercase tracking-wide">🗹 Checkliste</div>
|
||||
{meetingChecklistItems.map(ci => {
|
||||
const responsesForItem = checklistResponses.filter(r => r.checklistItemId === ci.id)
|
||||
const targets = ci.scope === 'meetingWide' ? [undefined] : institutees.map(i => i.id)
|
||||
return targets.map(instituteeId => {
|
||||
const response = responsesForItem.find(r => (r.instituteeId ?? undefined) === instituteeId)
|
||||
if (!response) return null
|
||||
const effectiveCritId = response.criterionItemId ?? ci.linkedCriterionItemId
|
||||
const critName = effectiveCritId ? fbItems.find(i => i.id === effectiveCritId)?.name : null
|
||||
const inst = instituteeId ? institutees.find(c => c.id === instituteeId) : undefined
|
||||
return (
|
||||
<div key={`${ci.id}-${instituteeId ?? 'm'}`} className="text-xs text-gray-600 flex items-center gap-1.5 flex-wrap">
|
||||
<span className="font-medium">{ci.label}</span>
|
||||
{inst && <span className="text-gray-400">— {displayName(inst)}</span>}
|
||||
<span className={`px-1.5 py-0.5 rounded font-medium tabular-nums ${resolveScoreStyle(response.rating, colorBands).active}`}>
|
||||
{response.rating ?? '—'}
|
||||
</span>
|
||||
{critName && <span className="text-indigo-600">→ {critName}</span>}
|
||||
{response.note?.trim() && <span className="text-gray-500">— {response.note.trim()}</span>}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{institutees.length > 0 && fbCategories.length > 0 && (
|
||||
<div className="space-y-1 pt-1 border-t border-gray-50">
|
||||
{institutees.map(inst => {
|
||||
const chips = fbCategories.map(cat => {
|
||||
const catItems = fbItems.filter(i => i.categoryId === cat.id)
|
||||
const mode = weightedAverageRating(catItems, itemId =>
|
||||
meetingAssessments.find(a => a.instituteeId === inst.id && a.criteriaId === itemId)?.score ?? null,
|
||||
)
|
||||
const mode = resolveCategoryChipScore({
|
||||
meetingId: meeting.id!,
|
||||
instituteeId: inst.id!,
|
||||
categoryId: cat.id!,
|
||||
categoryRatings,
|
||||
assessments,
|
||||
catItems,
|
||||
})
|
||||
return mode ? { cat, mode } : null
|
||||
}).filter(Boolean) as { cat: FeedbackCategory; mode: FeedbackRating }[]
|
||||
}).filter(Boolean) as { cat: FeedbackCategory; mode: RatingScore }[]
|
||||
if (chips.length === 0) return null
|
||||
return (
|
||||
<div key={inst.id} className="flex items-center gap-1 flex-wrap">
|
||||
<span className="text-xs text-gray-400">{displayName(inst)}:</span>
|
||||
{chips.map(({ cat, mode }) => (
|
||||
<span key={cat.id} className={`text-xs px-2 py-0.5 rounded font-medium ${RATING_BG[mode]}`}>
|
||||
{cat.name}
|
||||
<span key={cat.id} className={`text-xs px-2 py-0.5 rounded font-medium tabular-nums ${resolveScoreStyle(mode, colorBands).active}`}>
|
||||
{cat.name} {mode}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import {
|
||||
BAND_STYLES,
|
||||
DEFAULT_RATING_COLOR_BANDS,
|
||||
RATING_MAX,
|
||||
normalizeRatingColorBands,
|
||||
resolveScoreStyle,
|
||||
} from '../config/constants'
|
||||
import { getOrSeedRatingColorBands, saveRatingColorBands } from '../db'
|
||||
import type { RatingBandKey, RatingColorBand } from '../db/types'
|
||||
|
||||
const BAND_KEYS: RatingBandKey[] = ['red', 'orange', 'lightGreen', 'darkGreen']
|
||||
const BAND_LABELS: Record<RatingBandKey, string> = {
|
||||
red: 'Rot',
|
||||
orange: 'Orange',
|
||||
lightGreen: 'Hellgrün',
|
||||
darkGreen: 'Dunkelgrün',
|
||||
}
|
||||
|
||||
export default function RatingScaleConfig() {
|
||||
const [bands, setBands] = useState<RatingColorBand[]>(DEFAULT_RATING_COLOR_BANDS.map(b => ({ ...b })))
|
||||
const [saved, setSaved] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
getOrSeedRatingColorBands().then(b => setBands(normalizeRatingColorBands(b)))
|
||||
}, [])
|
||||
|
||||
const updateMax = (idx: number, max: number) => {
|
||||
setBands(prev => prev.map((b, i) => i === idx ? { ...b, max } : b))
|
||||
}
|
||||
|
||||
const updateKey = (idx: number, key: RatingBandKey) => {
|
||||
setBands(prev => prev.map((b, i) => i === idx ? { ...b, key } : b))
|
||||
}
|
||||
|
||||
const save = async () => {
|
||||
const sorted = [...bands].sort((a, b) => a.max - b.max)
|
||||
if (sorted[sorted.length - 1]?.max !== RATING_MAX) {
|
||||
setError(`Das letzte Band muss bei ${RATING_MAX} enden.`)
|
||||
return
|
||||
}
|
||||
for (let i = 1; i < sorted.length; i++) {
|
||||
if (sorted[i].max <= sorted[i - 1].max) {
|
||||
setError('Obergrenzen müssen streng aufsteigend sein.')
|
||||
return
|
||||
}
|
||||
}
|
||||
setError(null)
|
||||
try {
|
||||
await saveRatingColorBands(sorted)
|
||||
setBands(sorted)
|
||||
setSaved(true)
|
||||
setTimeout(() => setSaved(false), 2500)
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Speichern fehlgeschlagen.')
|
||||
}
|
||||
}
|
||||
|
||||
const reset = () => setBands(DEFAULT_RATING_COLOR_BANDS.map(b => ({ ...b })))
|
||||
|
||||
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">Bewertungsskala 1–10 · Farbbänder</h2>
|
||||
<p className="text-sm text-gray-500 mt-1">
|
||||
Steuert die farbliche Darstellung von Scores in Notation, Meeting und Feedback.
|
||||
Jedes Band gilt von der vorherigen Obergrenze + 1 bis zur eigenen Obergrenze (inklusive).
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<p className="text-xs text-gray-400">Vorschau (nicht ausgewählt / ausgewählt)</p>
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{Array.from({ length: 10 }, (_, i) => i + 1).map(n => {
|
||||
const style = resolveScoreStyle(n, bands)
|
||||
return (
|
||||
<span key={`idle-${n}`} className={`w-8 text-center text-xs font-bold py-1.5 rounded border tabular-nums ${style.color}`}>
|
||||
{n}
|
||||
</span>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{Array.from({ length: 10 }, (_, i) => i + 1).map(n => {
|
||||
const style = resolveScoreStyle(n, bands)
|
||||
return (
|
||||
<span key={`active-${n}`} className={`w-8 text-center text-xs font-bold py-1.5 rounded border tabular-nums ${style.active}`}>
|
||||
{n}
|
||||
</span>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
{bands.map((band, idx) => {
|
||||
const prevMax = idx === 0 ? 0 : bands[idx - 1].max
|
||||
return (
|
||||
<div key={idx} className="flex items-center gap-2 flex-wrap">
|
||||
<span className="text-xs text-gray-500 w-16">{prevMax + 1}–{band.max}</span>
|
||||
<label className="text-xs text-gray-600">bis</label>
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
max={10}
|
||||
value={band.max}
|
||||
onChange={e => updateMax(idx, Number(e.target.value))}
|
||||
className="w-14 border border-gray-200 rounded-lg px-2 py-1 text-sm tabular-nums"
|
||||
/>
|
||||
<select
|
||||
value={band.key}
|
||||
onChange={e => updateKey(idx, e.target.value as RatingBandKey)}
|
||||
className={`text-xs border rounded-lg px-2 py-1 ${BAND_STYLES[band.key].color}`}
|
||||
>
|
||||
{BAND_KEYS.map(k => (
|
||||
<option key={k} value={k}>{BAND_LABELS[k]}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="text-xs text-red-700 bg-red-50 border border-red-200 rounded-lg px-3 py-2">{error}</div>
|
||||
)}
|
||||
|
||||
<div className="flex gap-2">
|
||||
<button onClick={save} className="flex-1 py-2.5 bg-brand text-white rounded-xl text-sm font-semibold">
|
||||
Speichern
|
||||
</button>
|
||||
<button onClick={reset} className="px-4 py-2.5 border border-gray-200 text-gray-600 rounded-xl text-sm">
|
||||
Standard
|
||||
</button>
|
||||
</div>
|
||||
{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>
|
||||
)
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
import { useState } from 'react'
|
||||
import type {
|
||||
Consultant, FeedbackCategory, FeedbackCriterionItem,
|
||||
Assessment, ConversationEntry, FeedbackRating,
|
||||
Assessment, ConversationEntry, ConversationLineTag, RatingScore, RatingColorBand,
|
||||
} from '../../db'
|
||||
import { INST_COLORS, RATING_OPTIONS, RATING_NUM_MAP } from '../../config/constants'
|
||||
import {
|
||||
INST_COLORS, DEFAULT_RATING_COLOR_BANDS, isValidRatingScore, resolveScoreStyle,
|
||||
} from '../../config/constants'
|
||||
import { ScorePicker } from '../../components/ScorePicker'
|
||||
import { detectNotationRating } from '../../utils/notationParser'
|
||||
import { numberToRating, weightedAverageRating } from '../../utils/ratingTrend'
|
||||
|
||||
@@ -13,39 +16,53 @@ interface Props {
|
||||
fbItems: FeedbackCriterionItem[]
|
||||
assessments: Assessment[]
|
||||
entries: ConversationEntry[]
|
||||
/** Kriterium-Zuordnungen aus den allgemeinen Notizen — gelten für ALLE Institutees, nicht gefiltert. */
|
||||
generalNoteTags: ConversationLineTag[]
|
||||
hasConv: boolean
|
||||
tagLabel: (inst: Consultant) => string
|
||||
fillerTotal: (instId: number) => number
|
||||
getAssessmentScore: (instituteeId: number, itemId: number) => FeedbackRating | null
|
||||
onSetAssessmentScore: (instituteeId: number, itemId: number, score: FeedbackRating) => void
|
||||
getAssessmentScore: (instituteeId: number, itemId: number) => RatingScore | null
|
||||
onSetAssessmentScore: (instituteeId: number, itemId: number, score: RatingScore | null) => void
|
||||
onSaveAssessmentNote: (instituteeId: number, itemId: number, note: string) => void
|
||||
onAutoCalc: (instituteeId: number) => void
|
||||
colorBands?: RatingColorBand[]
|
||||
}
|
||||
|
||||
function catMode(
|
||||
cat: FeedbackCategory,
|
||||
fbItems: FeedbackCriterionItem[],
|
||||
getScore: (itemId: number) => FeedbackRating | null,
|
||||
): FeedbackRating | null {
|
||||
getScore: (itemId: number) => RatingScore | null,
|
||||
): RatingScore | null {
|
||||
return weightedAverageRating(fbItems.filter(i => i.categoryId === cat.id), getScore)
|
||||
}
|
||||
|
||||
function suggestedRating(entries: ConversationEntry[], instituteeId: number, itemId: number): FeedbackRating | null {
|
||||
const ratings = entries
|
||||
function suggestedRating(
|
||||
entries: ConversationEntry[],
|
||||
generalNoteTags: ConversationLineTag[],
|
||||
instituteeId: number,
|
||||
itemId: number,
|
||||
): RatingScore | null {
|
||||
const entryTexts = 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)
|
||||
.map(t => t.text)
|
||||
const generalTexts = generalNoteTags
|
||||
.filter(t => t.criterionItemId === itemId)
|
||||
.map(t => t.text)
|
||||
const ratings = [...entryTexts, ...generalTexts]
|
||||
.map(detectNotationRating)
|
||||
.filter(isValidRatingScore)
|
||||
if (ratings.length === 0) return null
|
||||
const avg = ratings.reduce((s, r) => s + RATING_NUM_MAP[r], 0) / ratings.length
|
||||
const avg = ratings.reduce((s, r) => s + r, 0) / ratings.length
|
||||
return numberToRating(avg)
|
||||
}
|
||||
|
||||
export function AssessmentTab({
|
||||
institutees, fbCategories, fbItems, assessments, entries, hasConv,
|
||||
institutees, fbCategories, fbItems, assessments, entries, generalNoteTags, hasConv,
|
||||
tagLabel, fillerTotal,
|
||||
getAssessmentScore, onSetAssessmentScore, onSaveAssessmentNote, onAutoCalc,
|
||||
colorBands = DEFAULT_RATING_COLOR_BANDS,
|
||||
}: Props) {
|
||||
const [expandedCat, setExpandedCat] = useState<Record<number, number | null>>({})
|
||||
|
||||
@@ -78,19 +95,16 @@ export function AssessmentTab({
|
||||
</div>
|
||||
|
||||
{fbCategories.map(cat => {
|
||||
const catItems = fbItems.filter(i => i.categoryId === cat.id)
|
||||
if (catItems.length === 0) return null
|
||||
const ratedCount = catItems.filter(i => {
|
||||
const s = getAssessmentScore(inst.id!, i.id!)
|
||||
return s !== null && s !== 'na'
|
||||
}).length
|
||||
const catItems = fbItems.filter(i => i.categoryId === cat.id)
|
||||
const ratedCount = catItems.filter(i => isValidRatingScore(getAssessmentScore(inst.id!, i.id!))).length
|
||||
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 headerRo = resolveScoreStyle(mode, colorBands)
|
||||
const hasScore = isValidRatingScore(mode)
|
||||
const suggestionCount = catItems.filter(item => {
|
||||
const current = getAssessmentScore(inst.id!, item.id!)
|
||||
const suggestion = suggestedRating(entries, inst.id!, item.id!)
|
||||
return suggestion && suggestion !== current
|
||||
const suggestion = suggestedRating(entries, generalNoteTags, inst.id!, item.id!)
|
||||
return suggestion !== null && suggestion !== current
|
||||
}).length
|
||||
|
||||
return (
|
||||
@@ -101,48 +115,57 @@ export function AssessmentTab({
|
||||
[inst.id!]: prev[inst.id!] === cat.id ? null : cat.id!,
|
||||
}))}
|
||||
className={`w-full flex items-center justify-between px-3 py-2.5 text-left transition ${
|
||||
headerRo ? headerRo.active : 'bg-white hover:bg-gray-50'
|
||||
hasScore ? headerRo.active : 'bg-white hover:bg-gray-50'
|
||||
}`}>
|
||||
<span className={`text-sm font-medium ${headerRo ? 'text-white' : 'text-gray-700'}`}>{cat.name}</span>
|
||||
<span className={`text-sm font-medium ${hasScore ? 'text-white' : 'text-gray-700'}`}>
|
||||
{cat.name}
|
||||
{hasScore && <span className="ml-2 tabular-nums opacity-90">{headerRo.short}</span>}
|
||||
</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'
|
||||
hasScore ? '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>
|
||||
)}
|
||||
<span className={`text-xs ${headerRo ? 'text-white/70' : 'text-gray-300'}`}>{isOpen ? '▲' : '▼'}</span>
|
||||
<span className={`text-xs ${hasScore ? 'text-white/70' : 'text-gray-400'}`}>
|
||||
{ratedCount}/{catItems.length}
|
||||
</span>
|
||||
<span className={`text-xs ${hasScore ? 'text-white/70' : 'text-gray-300'}`}>{isOpen ? '▲' : '▼'}</span>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
{isOpen && (
|
||||
<div className="border-t border-gray-100 divide-y divide-gray-50">
|
||||
{catItems.map(item => {
|
||||
{catItems.length === 0 ? (
|
||||
<div className="px-3 py-2.5 text-xs text-gray-400">Keine Kriterien in dieser Kategorie.</div>
|
||||
) : catItems.map(item => {
|
||||
const current = getAssessmentScore(inst.id!, item.id!)
|
||||
const suggestion = suggestedRating(entries, inst.id!, item.id!)
|
||||
const suggestion = suggestedRating(entries, generalNoteTags, inst.id!, item.id!)
|
||||
const note = assessments.find(a => a.instituteeId === inst.id && a.criteriaId === item.id)?.note ?? ''
|
||||
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>
|
||||
<div className="flex gap-1">
|
||||
{RATING_OPTIONS.map(r => (
|
||||
<button key={r.value}
|
||||
onClick={() => onSetAssessmentScore(inst.id!, item.id!, r.value)}
|
||||
className={`flex-1 py-1.5 rounded-lg text-xs font-semibold border transition ${
|
||||
current === r.value ? r.active : r.color
|
||||
}`}>
|
||||
{r.short}
|
||||
</button>
|
||||
))}
|
||||
<div className="flex items-baseline justify-between gap-2">
|
||||
<div className="text-xs text-gray-700 font-medium">{item.name}</div>
|
||||
{(item.weight ?? 1) !== 1 && (
|
||||
<span className="text-xs text-gray-400 flex-shrink-0">×{item.weight}</span>
|
||||
)}
|
||||
</div>
|
||||
{suggestion && suggestion !== current && (
|
||||
{item.description && (
|
||||
<div className="text-xs text-gray-400 leading-snug">{item.description}</div>
|
||||
)}
|
||||
<ScorePicker
|
||||
value={current}
|
||||
onChange={score => onSetAssessmentScore(inst.id!, item.id!, score)}
|
||||
bands={colorBands}
|
||||
allowClear
|
||||
/>
|
||||
{suggestion !== null && 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 className="text-xs bg-blue-50 text-blue-700 border border-blue-200 px-2 py-0.5 rounded-lg font-medium tabular-nums">
|
||||
Vorschlag aus Protokoll: {suggestion}
|
||||
</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">
|
||||
@@ -150,18 +173,17 @@ export function AssessmentTab({
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<textarea
|
||||
className="w-full border border-gray-200 rounded-lg px-3 py-1.5 text-xs focus:outline-none focus:border-brand bg-white"
|
||||
rows={1}
|
||||
placeholder="Notiz zum Kriterium"
|
||||
defaultValue={note}
|
||||
key={`note-${item.id}-${inst.id}-${note}`}
|
||||
onBlur={e => onSaveAssessmentNote(inst.id!, item.id!, e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
<div className="px-3 py-2 bg-gray-50">
|
||||
<textarea
|
||||
className="w-full border border-gray-200 rounded-lg px-3 py-1.5 text-xs focus:outline-none focus:border-brand bg-white"
|
||||
rows={1}
|
||||
placeholder="Kommentar zur Kategorie"
|
||||
defaultValue={assessments.find(a => a.instituteeId === inst.id && a.criteriaId === cat.id)?.note ?? ''}
|
||||
onBlur={e => onSaveAssessmentNote(inst.id!, cat.id!, e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
import { useState } from 'react'
|
||||
import type {
|
||||
Consultant, FeedbackCategory, FeedbackCriterionItem, RatingScore, RatingColorBand,
|
||||
ChecklistItemDef, ChecklistResponse,
|
||||
} from '../../db'
|
||||
import { DEFAULT_RATING_COLOR_BANDS } from '../../config/constants'
|
||||
import { ScorePicker } from '../../components/ScorePicker'
|
||||
import { CriterionTagPicker, type CriterionSuggestion } from './CriterionTagPicker'
|
||||
|
||||
interface Props {
|
||||
institutees: Consultant[]
|
||||
checklist: ChecklistItemDef[]
|
||||
fbItems: FeedbackCriterionItem[]
|
||||
fbCategories: FeedbackCategory[]
|
||||
tagLabel: (inst: Consultant) => string
|
||||
getChecklistResponse: (checklistItemId: number, instituteeId: number | undefined) => ChecklistResponse | undefined
|
||||
onSetChecklistRating: (item: ChecklistItemDef, instituteeId: number | undefined, rating: RatingScore | null) => void
|
||||
onSaveChecklistNote: (item: ChecklistItemDef, instituteeId: number | undefined, note: string) => void
|
||||
getEffectiveCriterion: (item: ChecklistItemDef, instituteeId: number | undefined) => number | null
|
||||
onSetChecklistCriterion: (item: ChecklistItemDef, instituteeId: number | undefined, criterionItemId: number | null) => void
|
||||
getChecklistSuggestions: (checklistItemId: number, instituteeId: number | undefined) => CriterionSuggestion[] | undefined
|
||||
colorBands?: RatingColorBand[]
|
||||
}
|
||||
|
||||
function ChecklistLine({
|
||||
label, items, categories, criterionValue, onSetCriterion, suggestions,
|
||||
rating, note, open, onToggleComment, onSelectRating, onSaveNote, colorBands,
|
||||
}: {
|
||||
label: string
|
||||
items: FeedbackCriterionItem[]
|
||||
categories: FeedbackCategory[]
|
||||
criterionValue: number | null
|
||||
onSetCriterion: (id: number | null) => void
|
||||
suggestions: CriterionSuggestion[] | undefined
|
||||
rating: RatingScore | null
|
||||
note: string
|
||||
open: boolean
|
||||
onToggleComment: () => void
|
||||
onSelectRating: (r: RatingScore | null) => void
|
||||
onSaveNote: (note: string) => void
|
||||
colorBands: RatingColorBand[]
|
||||
}) {
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center gap-1.5 py-1">
|
||||
<span className="flex-1 truncate text-xs text-gray-700">{label}</span>
|
||||
<CriterionTagPicker
|
||||
items={items}
|
||||
categories={categories}
|
||||
value={criterionValue}
|
||||
onChange={onSetCriterion}
|
||||
suggestions={suggestions}
|
||||
/>
|
||||
<ScorePicker
|
||||
value={rating}
|
||||
onChange={onSelectRating}
|
||||
bands={colorBands}
|
||||
variant="select"
|
||||
/>
|
||||
<button onClick={onToggleComment} title="Kommentar"
|
||||
className={`text-xs flex-shrink-0 rounded-lg px-1.5 py-1 ${note.trim() ? 'bg-blue-100 text-blue-700' : 'text-gray-300 hover:text-gray-500'}`}>
|
||||
💬
|
||||
</button>
|
||||
</div>
|
||||
{open && (
|
||||
<input
|
||||
autoFocus
|
||||
className="w-full border border-gray-200 rounded-lg px-2 py-1 text-xs focus:outline-none focus:border-brand mb-1"
|
||||
placeholder="Kommentar"
|
||||
defaultValue={note}
|
||||
onBlur={e => onSaveNote(e.target.value)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* „Ganz normal im Gesprächsprotokoll angezeigt" (siehe CLAUDE.md) — direkt oberhalb der
|
||||
* Gesprächs-Zeitleiste gerendert, kein eigener Meeting-Tab. Zeilenbasiert statt kartenbasiert
|
||||
* (Feedback nach Nutzungstests: nahm zu viel Platz ein). Die Kriterium-Zuordnung ist pro Antwort
|
||||
* individuell überschreibbar (`CriterionTagPicker`, gleiche Komponente wie im Protokoll) — die
|
||||
* Konfigurations-Vorgabe (`ChecklistItemDef.linkedCriterionItemId`) ist nur der Startwert.
|
||||
* `ChecklistResponse` ist immer die Quelle für die UI selbst; bei effektiv vorhandenem Kriterium
|
||||
* spiegelt MeetingView.tsx die Eingabe zusätzlich einseitig nach `Assessment`.
|
||||
*/
|
||||
export function ChecklistTab({
|
||||
institutees, checklist, fbItems, fbCategories, tagLabel,
|
||||
getChecklistResponse, onSetChecklistRating, onSaveChecklistNote,
|
||||
getEffectiveCriterion, onSetChecklistCriterion, getChecklistSuggestions,
|
||||
colorBands = DEFAULT_RATING_COLOR_BANDS,
|
||||
}: Props) {
|
||||
const [openComments, setOpenComments] = useState<Set<string>>(new Set())
|
||||
const toggleComment = (key: string) => setOpenComments(prev => {
|
||||
const next = new Set(prev)
|
||||
if (next.has(key)) next.delete(key); else next.add(key)
|
||||
return next
|
||||
})
|
||||
|
||||
if (checklist.length === 0) return null
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="text-xs font-semibold text-gray-400 uppercase tracking-wide px-1 mb-1">🗹 Checkliste</div>
|
||||
<div className="bg-white rounded-xl border border-gray-100 divide-y divide-gray-50 px-3">
|
||||
{checklist.map(ci => {
|
||||
if (ci.scope === 'meetingWide') {
|
||||
const key = `${ci.id}`
|
||||
return (
|
||||
<ChecklistLine key={ci.id}
|
||||
label={ci.label}
|
||||
items={fbItems}
|
||||
categories={fbCategories}
|
||||
criterionValue={getEffectiveCriterion(ci, undefined)}
|
||||
onSetCriterion={id => onSetChecklistCriterion(ci, undefined, id)}
|
||||
suggestions={getChecklistSuggestions(ci.id!, undefined)}
|
||||
rating={getChecklistResponse(ci.id!, undefined)?.rating ?? null}
|
||||
note={getChecklistResponse(ci.id!, undefined)?.note ?? ''}
|
||||
open={openComments.has(key)}
|
||||
onToggleComment={() => toggleComment(key)}
|
||||
onSelectRating={r => onSetChecklistRating(ci, undefined, r)}
|
||||
onSaveNote={note => onSaveChecklistNote(ci, undefined, note)}
|
||||
colorBands={colorBands}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div key={ci.id} className="py-1">
|
||||
<div className="text-xs font-medium text-gray-500 truncate">{ci.label}</div>
|
||||
{institutees.map(inst => {
|
||||
const key = `${ci.id}:${inst.id}`
|
||||
return (
|
||||
<ChecklistLine key={inst.id}
|
||||
label={tagLabel(inst)}
|
||||
items={fbItems}
|
||||
categories={fbCategories}
|
||||
criterionValue={getEffectiveCriterion(ci, inst.id!)}
|
||||
onSetCriterion={id => onSetChecklistCriterion(ci, inst.id!, id)}
|
||||
suggestions={getChecklistSuggestions(ci.id!, inst.id!)}
|
||||
rating={getChecklistResponse(ci.id!, inst.id!)?.rating ?? null}
|
||||
note={getChecklistResponse(ci.id!, inst.id!)?.note ?? ''}
|
||||
open={openComments.has(key)}
|
||||
onToggleComment={() => toggleComment(key)}
|
||||
onSelectRating={r => onSetChecklistRating(ci, inst.id!, r)}
|
||||
onSaveNote={note => onSaveChecklistNote(ci, inst.id!, note)}
|
||||
colorBands={colorBands}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,18 +1,23 @@
|
||||
import type React from 'react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import type {
|
||||
Consultant, FeedbackCategory, FeedbackCriterionItem,
|
||||
ConversationEntry, FeedbackRating,
|
||||
ConversationEntry, RatingScore, ConversationLineTag, RatingColorBand,
|
||||
} from '../../db'
|
||||
import { NotationText } from '../../utils/notationParser'
|
||||
import { INST_COLORS, RATING_OPTIONS } from '../../config/constants'
|
||||
import { CriterionTagPicker } from './CriterionTagPicker'
|
||||
import { INST_COLORS, resolveScoreStyle, DEFAULT_RATING_COLOR_BANDS } from '../../config/constants'
|
||||
import { ScorePicker } from '../../components/ScorePicker'
|
||||
import { findSimilarTaggedLines, type SimilarTaggedLine } from '../../utils/criterionSuggestion'
|
||||
import { CriterionTagPicker, type CriterionSuggestion } from './CriterionTagPicker'
|
||||
|
||||
const NOTATIONS = [
|
||||
{ sym: '+', tip: 'Gut' },
|
||||
{ sym: '(+)', tip: 'Gut mit Abstrichen' },
|
||||
{ sym: '!', tip: 'Negativ' },
|
||||
{ sym: '(!)', tip: 'Negativ mit Abstrichen' },
|
||||
{ sym: '>', tip: 'Einwand / Kundeninput' },
|
||||
{ sym: '1 ', tip: 'Score 1' },
|
||||
{ sym: '3 ', tip: 'Score 3' },
|
||||
{ sym: '5 ', tip: 'Score 5' },
|
||||
{ sym: '7 ', tip: 'Score 7' },
|
||||
{ sym: '9 ', tip: 'Score 9' },
|
||||
{ sym: '10 ', tip: 'Score 10' },
|
||||
{ sym: '>', tip: 'Einwand / Kundeninput' },
|
||||
{ sym: '[…]', tip: 'Slide-Referenz' },
|
||||
]
|
||||
|
||||
@@ -21,6 +26,10 @@ interface Props {
|
||||
fbCategories: FeedbackCategory[]
|
||||
fbItems: FeedbackCriterionItem[]
|
||||
entries: ConversationEntry[]
|
||||
/** Vorschläge aus „🏷 Vorschläge analysieren", Schlüssel = exakter Zeilentext. */
|
||||
lineSuggestions: Map<string, CriterionSuggestion[]>
|
||||
/** Einmal pro Meeting-Load geholter globaler Lern-Korpus, für die rein lokale Live-Formulierungshilfe. */
|
||||
corpus: ConversationLineTag[]
|
||||
activeInstId: number | null
|
||||
activeEntryId: number | null
|
||||
entryNote: string
|
||||
@@ -30,14 +39,14 @@ interface Props {
|
||||
displayName: (inst: Consultant) => string
|
||||
tagLabel: (inst: Consultant) => string
|
||||
fillerTotal: (instId: number) => number
|
||||
getEntryScore: (entryId: number, categoryId: number) => FeedbackRating | null
|
||||
getEntryScore: (entryId: number, categoryId: number) => RatingScore | null
|
||||
onActivateInstitutee: (id: number) => void
|
||||
onCloseActiveEntry: () => void
|
||||
onInsertNotation: (sym: string) => void
|
||||
onEntryNoteChange: (note: string) => void
|
||||
onSaveEntryNote: () => void
|
||||
onIncrementFiller: () => void
|
||||
onSetEntryScore: (entryId: number, categoryId: number, score: FeedbackRating) => void
|
||||
onSetEntryScore: (entryId: number, categoryId: number, score: RatingScore | null) => void
|
||||
onSetLineCriterion: (entryId: number, lineText: string, criterionItemId: number | null) => void
|
||||
onChangeSpeaker: (entryId: number, instituteeId: number) => void
|
||||
onStartEdit: (entry: ConversationEntry) => void
|
||||
@@ -46,24 +55,46 @@ interface Props {
|
||||
onEditNoteChange: (note: string) => void
|
||||
onDeleteEntry: (entryId: number) => void
|
||||
onAdjustFiller: (entry: ConversationEntry, delta: number) => void
|
||||
colorBands?: RatingColorBand[]
|
||||
}
|
||||
|
||||
export function ConversationTab({
|
||||
institutees, fbCategories, fbItems, entries,
|
||||
institutees, fbCategories, fbItems, entries, lineSuggestions, corpus,
|
||||
activeInstId, activeEntryId, entryNote, editingId, editNote, noteRef,
|
||||
displayName, tagLabel, fillerTotal, getEntryScore,
|
||||
onActivateInstitutee, onCloseActiveEntry, onInsertNotation,
|
||||
onEntryNoteChange, onSaveEntryNote, onIncrementFiller, onSetEntryScore, onSetLineCriterion, onChangeSpeaker,
|
||||
onStartEdit, onSaveEdit, onCancelEdit, onEditNoteChange, onDeleteEntry, onAdjustFiller,
|
||||
colorBands = DEFAULT_RATING_COLOR_BANDS,
|
||||
}: Props) {
|
||||
const activeInstIdx = institutees.findIndex(c => c.id === activeInstId)
|
||||
const activeColor = INST_COLORS[activeInstIdx % INST_COLORS.length]
|
||||
const activeEntry = entries.find(e => e.id === activeEntryId)
|
||||
const pastEntries = [...entries].filter(e => e.id !== activeEntryId).reverse()
|
||||
|
||||
const [formulationHints, setFormulationHints] = useState<SimilarTaggedLine[]>([])
|
||||
const hintsTimer = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
useEffect(() => {
|
||||
if (hintsTimer.current) clearTimeout(hintsTimer.current)
|
||||
hintsTimer.current = setTimeout(() => {
|
||||
const lastLine = entryNote.split('\n').pop()?.trim() ?? ''
|
||||
setFormulationHints(lastLine ? findSimilarTaggedLines(lastLine, corpus) : [])
|
||||
}, 800)
|
||||
return () => { if (hintsTimer.current) clearTimeout(hintsTimer.current) }
|
||||
}, [entryNote, corpus])
|
||||
|
||||
const criterionName = (id: number) => fbItems.find(i => i.id === id)?.name
|
||||
|
||||
const applyHint = (hintText: string) => {
|
||||
const lines = entryNote.split('\n')
|
||||
lines[lines.length - 1] = hintText
|
||||
onEntryNoteChange(lines.join('\n'))
|
||||
setFormulationHints([])
|
||||
setTimeout(() => noteRef.current?.focus(), 0)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{/* Aktiver Sprecher-Bereich */}
|
||||
<div className={`bg-white rounded-xl shadow-sm border-2 p-4 space-y-3 ${
|
||||
activeInstId !== null ? (activeColor?.border ?? 'border-brand') : 'border-gray-200'
|
||||
}`}>
|
||||
@@ -102,7 +133,6 @@ export function ConversationTab({
|
||||
|
||||
{activeInstId !== null && (
|
||||
<>
|
||||
{/* Notation + Äh-Counter */}
|
||||
<div className="flex items-start gap-2">
|
||||
<div className="flex gap-1.5 flex-wrap flex-1">
|
||||
{NOTATIONS.map(({ sym, tip }) => (
|
||||
@@ -126,18 +156,37 @@ export function ConversationTab({
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Notiz */}
|
||||
<textarea
|
||||
ref={noteRef}
|
||||
className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-brand"
|
||||
rows={4}
|
||||
placeholder="Notizen… (+ gut, (!) negativ mit Abstrichen, > Kundeninput, [Slide 3])"
|
||||
placeholder="Notizen… (1–10 Score am Zeilenanfang, > Kundeninput, [Slide 3])"
|
||||
value={entryNote}
|
||||
onChange={e => onEntryNoteChange(e.target.value)}
|
||||
onBlur={onSaveEntryNote}
|
||||
/>
|
||||
|
||||
{/* Kategorie-Bewertung (optional) */}
|
||||
{formulationHints.length > 0 && (
|
||||
<details className="bg-blue-50 border border-blue-100 rounded-lg px-3 py-1.5" open>
|
||||
<summary className="text-xs font-medium text-blue-700 cursor-pointer select-none">💭 Ähnliche frühere Notizen — klicken zum Übernehmen</summary>
|
||||
<ul className="mt-1 space-y-0.5">
|
||||
{formulationHints.map((h, i) => (
|
||||
<li key={i}>
|
||||
<button type="button"
|
||||
onMouseDown={e => e.preventDefault()}
|
||||
onClick={() => applyHint(h.text)}
|
||||
className="text-xs text-blue-800 hover:text-blue-950 hover:underline truncate text-left w-full">
|
||||
„{h.text}"
|
||||
{criterionName(h.criterionItemId) && (
|
||||
<span className="text-blue-400"> → 🏷 {criterionName(h.criterionItemId)}</span>
|
||||
)}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</details>
|
||||
)}
|
||||
|
||||
{fbCategories.length > 0 && activeEntryId !== null && (
|
||||
<details>
|
||||
<summary className="text-xs text-gray-400 cursor-pointer select-none hover:text-gray-600">
|
||||
@@ -157,17 +206,11 @@ export function ConversationTab({
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex gap-1">
|
||||
{RATING_OPTIONS.map(r => (
|
||||
<button key={r.value}
|
||||
onClick={() => onSetEntryScore(activeEntryId, cat.id!, r.value)}
|
||||
className={`flex-1 py-1.5 rounded text-xs font-bold border transition ${
|
||||
current === r.value ? r.active : r.color
|
||||
}`}>
|
||||
{r.short}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<ScorePicker
|
||||
value={current}
|
||||
onChange={score => onSetEntryScore(activeEntryId, cat.id!, score)}
|
||||
bands={colorBands}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
@@ -178,7 +221,6 @@ export function ConversationTab({
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Protokoll-Zeitleiste */}
|
||||
{pastEntries.length > 0 && (
|
||||
<div className="space-y-1.5">
|
||||
<div className="text-xs font-semibold text-gray-400 uppercase tracking-wide px-1">Protokoll</div>
|
||||
@@ -240,12 +282,14 @@ export function ConversationTab({
|
||||
{entry.note && (
|
||||
<NotationText
|
||||
text={entry.note}
|
||||
colorBands={colorBands}
|
||||
renderLineAddon={line => (
|
||||
<CriterionTagPicker
|
||||
items={fbItems}
|
||||
categories={fbCategories}
|
||||
value={(entry.lineTags ?? []).find(t => t.text === line)?.criterionItemId ?? null}
|
||||
onChange={itemId => onSetLineCriterion(entry.id!, line, itemId)}
|
||||
suggestions={lineSuggestions.get(line)}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
@@ -257,10 +301,10 @@ export function ConversationTab({
|
||||
</span>
|
||||
)}
|
||||
{scoreChips.map(({ name, s }) => {
|
||||
const ro = RATING_OPTIONS.find(r => r.value === s)
|
||||
const style = resolveScoreStyle(s, colorBands)
|
||||
return (
|
||||
<span key={name} className={`text-xs px-1.5 py-0.5 rounded border font-medium ${ro?.active ?? 'bg-gray-100 text-gray-500 border-gray-200'}`}>
|
||||
{name.slice(0, 8)}: {ro?.short ?? s}
|
||||
<span key={name} className={`text-xs px-1.5 py-0.5 rounded border font-medium tabular-nums ${style.active}`}>
|
||||
{name.slice(0, 8)}: {style.short}
|
||||
</span>
|
||||
)
|
||||
})}
|
||||
|
||||
@@ -1,14 +1,22 @@
|
||||
import { useState } from 'react'
|
||||
import type { FeedbackCategory, FeedbackCriterionItem } from '../../db'
|
||||
|
||||
/** Priorisierter Vorschlag aus „🏷 Vorschläge analysieren" — rank 1 = wahrscheinlichstes Kriterium. */
|
||||
export interface CriterionSuggestion {
|
||||
criterionItemId: number
|
||||
rank: number
|
||||
}
|
||||
|
||||
interface Props {
|
||||
items: FeedbackCriterionItem[]
|
||||
categories: FeedbackCategory[]
|
||||
value: number | null | undefined
|
||||
onChange: (itemId: number | null) => void
|
||||
/** Nur relevant solange `value` leer ist — überschreibt den leeren „+"-Button durch einen Vorschlags-Chip. */
|
||||
suggestions?: CriterionSuggestion[]
|
||||
}
|
||||
|
||||
export function CriterionTagPicker({ items, categories, value, onChange }: Props) {
|
||||
export function CriterionTagPicker({ items, categories, value, onChange, suggestions }: Props) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const [filter, setFilter] = useState('')
|
||||
|
||||
@@ -27,6 +35,9 @@ export function CriterionTagPicker({ items, categories, value, onChange }: Props
|
||||
setFilter('')
|
||||
}
|
||||
|
||||
const sortedSuggestions = suggestions ? [...suggestions].sort((a, b) => a.rank - b.rank) : []
|
||||
const topItem = sortedSuggestions[0] ? items.find(i => i.id === sortedSuggestions[0].criterionItemId) : undefined
|
||||
|
||||
return (
|
||||
<div className="relative inline-block">
|
||||
{current ? (
|
||||
@@ -36,6 +47,15 @@ export function CriterionTagPicker({ items, categories, value, onChange }: Props
|
||||
</button>
|
||||
<button onClick={() => onChange(null)} className="text-indigo-400 hover:text-indigo-700 text-xs leading-none px-1">✕</button>
|
||||
</div>
|
||||
) : topItem ? (
|
||||
<div className="inline-flex items-center gap-0.5 bg-blue-50 text-blue-700 border border-blue-200 rounded-full pl-2 pr-1 py-0.5">
|
||||
<button onClick={() => select(topItem.id!)} title="Vorschlag übernehmen"
|
||||
className="text-xs font-medium max-w-[120px] truncate">
|
||||
💡 {topItem.name}
|
||||
</button>
|
||||
<button onClick={() => setOpen(p => !p)} title="Weitere Vorschläge / Suche"
|
||||
className="text-blue-400 hover:text-blue-700 text-xs leading-none px-1">▾</button>
|
||||
</div>
|
||||
) : (
|
||||
<button onClick={() => setOpen(p => !p)}
|
||||
title="Kriterium zuordnen"
|
||||
@@ -46,6 +66,23 @@ export function CriterionTagPicker({ items, categories, value, onChange }: Props
|
||||
|
||||
{open && (
|
||||
<div className="absolute z-20 mt-1 w-64 bg-white border border-gray-200 rounded-xl shadow-lg p-2">
|
||||
{sortedSuggestions.length > 0 && (
|
||||
<div className="mb-2 space-y-0.5">
|
||||
<div className="text-[10px] font-semibold text-blue-400 uppercase tracking-wide px-2">Vorschläge</div>
|
||||
{sortedSuggestions.map(s => {
|
||||
const item = items.find(i => i.id === s.criterionItemId)
|
||||
if (!item) return null
|
||||
return (
|
||||
<button key={s.criterionItemId} onClick={() => select(item.id!)}
|
||||
className="w-full text-left px-2 py-1.5 rounded-lg hover:bg-blue-50">
|
||||
<div className="text-xs font-medium text-blue-700">💡 {item.name}</div>
|
||||
<div className="text-[10px] text-gray-400">{categoryName(item.categoryId)}</div>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
<div className="border-t border-gray-100 my-1" />
|
||||
</div>
|
||||
)}
|
||||
<input
|
||||
type="text"
|
||||
autoFocus
|
||||
|
||||
@@ -1,24 +1,37 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useNavigate, useParams } from 'react-router-dom'
|
||||
import {
|
||||
type Assignment, type MeetingInstance, type PhaseTemplate,
|
||||
type FeedbackCategory, type FeedbackCriterionItem, type FeedbackRating,
|
||||
type Consultant, type ConversationEntry, type ConversationSkillScore, type Assessment,
|
||||
type FeedbackCategory, type FeedbackCriterionItem, type RatingScore,
|
||||
type Consultant, type ConversationEntry, type ConversationSkillScore, type Assessment, type ConversationLineTag,
|
||||
type ChecklistItemDef, type ChecklistResponse,
|
||||
getMeetingInstance, updateMeetingInstance, softDeleteMeetingInstance,
|
||||
getAssignmentType,
|
||||
getAssignment,
|
||||
getPhaseTemplate,
|
||||
getConsultantsByIds,
|
||||
listFeedbackCategoriesAll, listFeedbackCriterionItemsAll, filterVisibleFeedbackStructure,
|
||||
loadFeedbackStructure, resolveVisibleStructure, updateFeedbackCriterionItem,
|
||||
getGlobalLineTagCorpus,
|
||||
getOrSeedCriterionTaggingPromptTemplate,
|
||||
listConversationEntriesForMeeting, addConversationEntry, updateConversationEntry, deleteConversationEntry,
|
||||
listConversationSkillScoresAll, addConversationSkillScore, updateConversationSkillScore, deleteConversationSkillScoresForEntry,
|
||||
listAssessmentsForMeeting, addAssessment, updateAssessment,
|
||||
listChecklistItemDefsForPhaseTemplate, listChecklistResponsesForMeeting, upsertChecklistResponse,
|
||||
upsertMeetingCategoryRating,
|
||||
} from '../../db'
|
||||
import { exportMeetingAsMarkdown, exportMeetingAsJson, downloadFile } from '../../utils/meetingExport'
|
||||
import { NotationText, splitNoteLines } from '../../utils/notationParser'
|
||||
import { RATING_NUM_MAP } from '../../config/constants'
|
||||
import { NotationText, splitNoteLines, parseNotationPrefix } from '../../utils/notationParser'
|
||||
import { clampRatingScore, isValidRatingScore, normalizeRatingScore } from '../../config/constants'
|
||||
import { getAiSettings, callOpenRouter } from '../../utils/aiClient'
|
||||
import { weightedAverageRating } from '../../utils/ratingTrend'
|
||||
import { renderDimensionPrompt } from '../../utils/aiPrompt'
|
||||
import { buildCriterionSuggestionPromptContext, parseCriterionSuggestionResponse } from '../../utils/criterionSuggestionPrompt'
|
||||
import { findSimilarTaggedLines, type SimilarTaggedLine } from '../../utils/criterionSuggestion'
|
||||
import { useRatingColorBands } from '../../hooks/useRatingColorBands'
|
||||
import { ConversationTab } from './ConversationTab'
|
||||
import { AssessmentTab } from './AssessmentTab'
|
||||
import { ChecklistTab } from './ChecklistTab'
|
||||
import { CriterionTagPicker, type CriterionSuggestion } from './CriterionTagPicker'
|
||||
|
||||
type Tab = 'conversation' | 'assessment'
|
||||
|
||||
@@ -26,6 +39,7 @@ export default function MeetingView() {
|
||||
const { id, meetingId: meetingIdParam } = useParams()
|
||||
const navigate = useNavigate()
|
||||
const meetingId = Number(meetingIdParam ?? id)
|
||||
const colorBands = useRatingColorBands()
|
||||
|
||||
const [meeting, setMeeting] = useState<MeetingInstance | null>(null)
|
||||
const [assignment, setAssignment] = useState<Assignment | null>(null)
|
||||
@@ -36,18 +50,34 @@ export default function MeetingView() {
|
||||
const [entries, setEntries] = useState<ConversationEntry[]>([])
|
||||
const [scores, setScores] = useState<ConversationSkillScore[]>([])
|
||||
const [assessments, setAssessments] = useState<Assessment[]>([])
|
||||
const [checklist, setChecklist] = useState<ChecklistItemDef[]>([])
|
||||
const [checklistResponses, setChecklistResponses] = useState<ChecklistResponse[]>([])
|
||||
const [tab, setTab] = useState<Tab>('conversation')
|
||||
const [activeInstId, setActiveInstId] = useState<number | null>(null)
|
||||
const [activeEntryId, setActiveEntryId] = useState<number | null>(null)
|
||||
const [entryNote, setEntryNote] = useState('')
|
||||
const [generalNotes, setGeneralNotes] = useState('')
|
||||
const [generalNoteTags, setGeneralNoteTags] = useState<ConversationLineTag[]>([])
|
||||
const [editingGeneralNotes, setEditingGeneralNotes] = useState(false)
|
||||
const [editingId, setEditingId] = useState<number | null>(null)
|
||||
const [editNote, setEditNote] = useState('')
|
||||
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)
|
||||
const [showExportMenu, setShowExportMenu] = useState(false)
|
||||
const noteRef = useRef<HTMLTextAreaElement>(null)
|
||||
const [lineSuggestions, setLineSuggestions] = useState<Map<string, CriterionSuggestion[]>>(new Map())
|
||||
/** KI-Vorschläge für Checklisten-Antworten, Schlüssel `${checklistItemId}:${instituteeId ?? ''}`. */
|
||||
const [checklistSuggestions, setChecklistSuggestions] = useState<Map<string, CriterionSuggestion[]>>(new Map())
|
||||
const [analyzingSuggestions, setAnalyzingSuggestions] = useState(false)
|
||||
const [suggestionError, setSuggestionError] = useState('')
|
||||
/** Status/Diagnose nach „Vorschläge analysieren" — macht sichtbar, ob überhaupt etwas zu analysieren war und was die KI zurückgegeben hat. */
|
||||
const [suggestionInfo, setSuggestionInfo] = useState('')
|
||||
const [lastAnalysisRaw, setLastAnalysisRaw] = useState<string | null>(null)
|
||||
/** Einmal pro Meeting-Load geholt, dient der rein lokalen Live-Formulierungshilfe (kein KI-Call). */
|
||||
const [corpus, setCorpus] = useState<ConversationLineTag[]>([])
|
||||
const [generalNotesHints, setGeneralNotesHints] = useState<SimilarTaggedLine[]>([])
|
||||
const noteRef = useRef<HTMLTextAreaElement>(null)
|
||||
const generalNotesRef = useRef<HTMLTextAreaElement>(null)
|
||||
const notesTimer = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
const hintsTimer = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
|
||||
const displayName = (inst: Consultant) => {
|
||||
const dup = institutees.filter(c => c.firstName === inst.firstName && c.id !== inst.id).length > 0
|
||||
@@ -59,11 +89,52 @@ export default function MeetingView() {
|
||||
const fillerTotal = (instId: number) =>
|
||||
entries.filter(e => e.instituteeId === instId).reduce((s, e) => s + (e.fillerCount ?? 0), 0)
|
||||
|
||||
/**
|
||||
* Rein lokale (KI-freie) Kriterium-Vorschläge für noch nicht zugeordnete Zeilen — direkt verfügbar,
|
||||
* ohne „🏷 Vorschläge analysieren" auszulösen (siehe CLAUDE.md „Direkte Kriterien-Vorschläge ohne KI").
|
||||
* Mindest-Ähnlichkeit 0,25 ("mittel", gleiche Schwelle wie in criterionSuggestionPrompt.ts), damit
|
||||
* nur halbwegs verlässliche Treffer als klickbarer Vorschlags-Chip erscheinen — schwächere Treffer
|
||||
* bleiben im „💭 Ähnliche frühere Notizen"-Panel weiterhin als reine Textreferenz sichtbar.
|
||||
*/
|
||||
const localLineSuggestions = useMemo(() => {
|
||||
const map = new Map<string, CriterionSuggestion[]>()
|
||||
if (corpus.length === 0) return map
|
||||
|
||||
const untaggedLines: string[] = []
|
||||
for (const entry of entries) {
|
||||
const taggedTexts = new Set((entry.lineTags ?? []).map(t => t.text))
|
||||
for (const line of splitNoteLines(entry.note)) {
|
||||
if (taggedTexts.has(line) || parseNotationPrefix(line).isQuote) continue
|
||||
untaggedLines.push(line)
|
||||
}
|
||||
}
|
||||
const taggedGeneralTexts = new Set(generalNoteTags.map(t => t.text))
|
||||
for (const line of splitNoteLines(generalNotes)) {
|
||||
if (taggedGeneralTexts.has(line) || parseNotationPrefix(line).isQuote) continue
|
||||
untaggedLines.push(line)
|
||||
}
|
||||
|
||||
for (const line of untaggedLines) {
|
||||
const hints = findSimilarTaggedLines(line, corpus, 3).filter(h => h.score >= 0.25)
|
||||
if (hints.length === 0) continue
|
||||
map.set(line, hints.map((h, idx) => ({ criterionItemId: h.criterionItemId, rank: idx + 1 })))
|
||||
}
|
||||
return map
|
||||
}, [entries, generalNotes, generalNoteTags, corpus])
|
||||
|
||||
/** KI-Vorschläge (aus „🏷 Vorschläge analysieren") haben Vorrang vor den lokalen, wenn beide für dieselbe Zeile vorliegen. */
|
||||
const mergedLineSuggestions = useMemo(() => {
|
||||
const merged = new Map(localLineSuggestions)
|
||||
for (const [text, sugg] of lineSuggestions) merged.set(text, sugg)
|
||||
return merged
|
||||
}, [localLineSuggestions, lineSuggestions])
|
||||
|
||||
const loadData = useCallback(async () => {
|
||||
const m = await getMeetingInstance(meetingId)
|
||||
if (!m) return
|
||||
setMeeting(m)
|
||||
setGeneralNotes(m.generalNotes ?? '')
|
||||
setGeneralNoteTags(m.generalNoteTags ?? [])
|
||||
|
||||
const [tmpl, a] = await Promise.all([
|
||||
getPhaseTemplate(m.phaseTemplateId),
|
||||
@@ -77,14 +148,13 @@ export default function MeetingView() {
|
||||
setInstitutees(a.instituteeIds.map(cid => cons.find(c => c.id === cid)!).filter(Boolean))
|
||||
}
|
||||
|
||||
const [allCats, allItems, aType] = await Promise.all([
|
||||
listFeedbackCategoriesAll(),
|
||||
listFeedbackCriterionItemsAll(),
|
||||
const [structure, aType] = await Promise.all([
|
||||
loadFeedbackStructure(),
|
||||
a ? getAssignmentType(a.assignmentTypeId) : Promise.resolve(undefined),
|
||||
])
|
||||
const { categories: visibleCats, items: visibleItems } = filterVisibleFeedbackStructure(allCats, allItems, aType?.criteriaIds)
|
||||
setFbItems(visibleItems)
|
||||
setFbCategories(visibleCats)
|
||||
const visible = resolveVisibleStructure(structure.dimensions, structure.categories, structure.items, aType?.criteriaIds)
|
||||
setFbItems(visible.items)
|
||||
setFbCategories(visible.categories)
|
||||
|
||||
const [convEntries, convScores, asmts] = await Promise.all([
|
||||
listConversationEntriesForMeeting(meetingId),
|
||||
@@ -94,6 +164,20 @@ export default function MeetingView() {
|
||||
setEntries(convEntries)
|
||||
setScores(convScores)
|
||||
setAssessments(asmts)
|
||||
|
||||
getGlobalLineTagCorpus().then(setCorpus)
|
||||
|
||||
if (tmpl?.hasChecklist) {
|
||||
const [checklistDefs, responses] = await Promise.all([
|
||||
listChecklistItemDefsForPhaseTemplate(tmpl.id!),
|
||||
listChecklistResponsesForMeeting(meetingId),
|
||||
])
|
||||
setChecklist(checklistDefs)
|
||||
setChecklistResponses(responses)
|
||||
} else {
|
||||
setChecklist([])
|
||||
setChecklistResponses([])
|
||||
}
|
||||
}, [meetingId])
|
||||
|
||||
useEffect(() => { loadData() }, [loadData])
|
||||
@@ -194,12 +278,16 @@ export default function MeetingView() {
|
||||
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
|
||||
const getEntryScore = (entryId: number, categoryId: number): RatingScore | null =>
|
||||
normalizeRatingScore(scores.find(s => s.conversationEntryId === entryId && s.criteriaId === categoryId)?.score)
|
||||
|
||||
const setEntryScore = async (entryId: number, categoryId: number, score: FeedbackRating) => {
|
||||
const setEntryScore = async (entryId: number, categoryId: number, score: RatingScore | null) => {
|
||||
const existing = scores.find(s => s.conversationEntryId === entryId && s.criteriaId === categoryId)
|
||||
if (existing?.id) {
|
||||
if (score === null) {
|
||||
if (existing?.id) {
|
||||
await updateConversationSkillScore(existing.id, { score: null })
|
||||
}
|
||||
} else if (existing?.id) {
|
||||
await updateConversationSkillScore(existing.id, { score })
|
||||
} else {
|
||||
await addConversationSkillScore({ conversationEntryId: entryId, criteriaId: categoryId, score })
|
||||
@@ -209,10 +297,24 @@ export default function MeetingView() {
|
||||
|
||||
// ── Assessment handlers ───────────────────────────────────────────────────
|
||||
|
||||
const getAssessmentScore = (instituteeId: number, itemId: number): FeedbackRating | null =>
|
||||
assessments.find(a => a.instituteeId === instituteeId && a.criteriaId === itemId)?.score ?? null
|
||||
const getAssessmentScore = (instituteeId: number, itemId: number): RatingScore | null =>
|
||||
normalizeRatingScore(assessments.find(a => a.instituteeId === instituteeId && a.criteriaId === itemId)?.score)
|
||||
|
||||
const setAssessmentScore = async (instituteeId: number, itemId: number, score: FeedbackRating) => {
|
||||
/** Kategorie-Score = gewichteter Ø der Kriterien (wie Altsystem); null wenn nichts bewertet. */
|
||||
const syncCategoryFromCriteria = async (
|
||||
instituteeId: number,
|
||||
categoryId: number,
|
||||
nextAssessments: Assessment[],
|
||||
) => {
|
||||
const catItems = fbItems.filter(i => i.categoryId === categoryId)
|
||||
const avg = weightedAverageRating(
|
||||
catItems,
|
||||
itemId => nextAssessments.find(a => a.instituteeId === instituteeId && a.criteriaId === itemId)?.score ?? null,
|
||||
)
|
||||
await upsertMeetingCategoryRating({ meetingInstanceId: meetingId, instituteeId, categoryId, score: avg })
|
||||
}
|
||||
|
||||
const setAssessmentScore = async (instituteeId: number, itemId: number, score: RatingScore | null) => {
|
||||
const existing = assessments.find(a => a.instituteeId === instituteeId && a.criteriaId === itemId)
|
||||
const now = new Date().toISOString()
|
||||
if (existing?.id) {
|
||||
@@ -220,7 +322,12 @@ export default function MeetingView() {
|
||||
} else {
|
||||
await addAssessment({ meetingInstanceId: meetingId, instituteeId, criteriaId: itemId, score, note: '', updatedAt: now })
|
||||
}
|
||||
setAssessments(await listAssessmentsForMeeting(meetingId))
|
||||
const next = await listAssessmentsForMeeting(meetingId)
|
||||
setAssessments(next)
|
||||
const item = fbItems.find(i => i.id === itemId)
|
||||
if (item) {
|
||||
await syncCategoryFromCriteria(instituteeId, item.categoryId, next)
|
||||
}
|
||||
}
|
||||
|
||||
const saveAssessmentNote = async (instituteeId: number, itemId: number, note: string) => {
|
||||
@@ -239,22 +346,264 @@ export default function MeetingView() {
|
||||
for (const cat of fbCategories) {
|
||||
const vals = instEntries
|
||||
.map(e => getEntryScore(e.id!, cat.id!))
|
||||
.filter((s): s is FeedbackRating => s !== null && s !== 'na')
|
||||
.filter(isValidRatingScore)
|
||||
if (vals.length === 0) continue
|
||||
const avg = vals.reduce((s, v) => s + RATING_NUM_MAP[v], 0) / vals.length
|
||||
const rating: FeedbackRating = avg < 1.5 ? 'not_client_ready' : avg < 2.5 ? 'partially_client_ready' : avg < 3.5 ? 'nearly_client_ready' : 'client_ready'
|
||||
const avg = vals.reduce((s, v) => s + v, 0) / vals.length
|
||||
const rating = clampRatingScore(avg)
|
||||
if (rating === null) continue
|
||||
for (const item of fbItems.filter(i => i.categoryId === cat.id)) {
|
||||
await setAssessmentScore(instituteeId, item.id!, rating)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Checkliste-Handler ─────────────────────────────────────────────────────
|
||||
|
||||
const getChecklistResponse = (checklistItemId: number, instituteeId: number | undefined): ChecklistResponse | undefined =>
|
||||
checklistResponses.find(r => r.checklistItemId === checklistItemId && (r.instituteeId ?? undefined) === instituteeId)
|
||||
|
||||
/**
|
||||
* Checklisten-Text für die KI/Assessment-Notiz — Checkpunkt-Label und Bewertung werden explizit
|
||||
* mitgegeben (nicht nur der freie Kommentar), siehe CLAUDE.md „Checkliste an Assessment gespiegelt".
|
||||
*/
|
||||
const composeChecklistNote = (label: string, note: string, rating: RatingScore): string => {
|
||||
const ratingLabel = String(rating)
|
||||
return note.trim() ? `Checkliste „${label}" (${ratingLabel}): ${note.trim()}` : `Checkliste „${label}" (${ratingLabel})`
|
||||
}
|
||||
|
||||
/** Effektives Kriterium einer Antwort — individuelle Zuordnung überschreibt die Konfigurations-Vorgabe. */
|
||||
const getEffectiveChecklistCriterion = (ci: ChecklistItemDef, instituteeId: number | undefined): number | null =>
|
||||
getChecklistResponse(ci.id!, instituteeId)?.criterionItemId ?? ci.linkedCriterionItemId ?? null
|
||||
|
||||
/**
|
||||
* `ChecklistResponse` ist immer die Quelle für die Checkliste-UI selbst. Bei effektiv vorhandenem
|
||||
* Kriterium (individuelle Zuordnung ODER Konfigurations-Vorgabe) wird zusätzlich einseitig nach
|
||||
* `Assessment` gespiegelt (score+note), damit Gesamtbewertung/Evaluation und die KI-Prompt-Auswertung
|
||||
* (aiPrompt.ts::kriterienScores liest Assessment.note bereits) die Checklisten-Eintragung ganz normal
|
||||
* als Protokolleintrag mitverwenden — bei `scope: meetingWide` für JEDEN aktuellen Institutee
|
||||
* identisch (Kriterien sind Personen-Kompetenzen, ein meeting-weiter Checkpunkt gilt für alle
|
||||
* gleichermaßen). Wechselt die individuelle Zuordnung auf ein anderes Kriterium, bleibt ein bereits
|
||||
* gespiegelter Eintrag beim alten Kriterium unangetastet (keine rückwirkende Korrektur) — bewusst
|
||||
* einfach gehalten, gleiches Prinzip wie beim Löschen eines Checklisten-Punkts.
|
||||
*/
|
||||
const saveChecklistResponse = async (
|
||||
ci: ChecklistItemDef,
|
||||
instituteeId: number | undefined,
|
||||
patch: { rating?: RatingScore | null; note?: string; criterionItemId?: number },
|
||||
) => {
|
||||
const existing = getChecklistResponse(ci.id!, instituteeId)
|
||||
const rating = 'rating' in patch ? (patch.rating ?? null) : (existing?.rating ?? null)
|
||||
const note = patch.note ?? existing?.note ?? ''
|
||||
const criterionItemId = 'criterionItemId' in patch ? patch.criterionItemId : existing?.criterionItemId
|
||||
await upsertChecklistResponse({ meetingInstanceId: meetingId, instituteeId, checklistItemId: ci.id!, rating, note, criterionItemId })
|
||||
setChecklistResponses(await listChecklistResponsesForMeeting(meetingId))
|
||||
|
||||
const effectiveCriterion = criterionItemId ?? ci.linkedCriterionItemId
|
||||
if (effectiveCriterion && isValidRatingScore(rating)) {
|
||||
const composed = composeChecklistNote(ci.label, note, rating)
|
||||
const targets = ci.scope === 'meetingWide' ? institutees.map(i => i.id!) : [instituteeId!]
|
||||
for (const targetId of targets) {
|
||||
await setAssessmentScore(targetId, effectiveCriterion, rating)
|
||||
await saveAssessmentNote(targetId, effectiveCriterion, composed)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const setChecklistRating = (ci: ChecklistItemDef, instituteeId: number | undefined, rating: RatingScore | null) =>
|
||||
saveChecklistResponse(ci, instituteeId, { rating })
|
||||
|
||||
const saveChecklistNote = (ci: ChecklistItemDef, instituteeId: number | undefined, note: string) =>
|
||||
saveChecklistResponse(ci, instituteeId, { note })
|
||||
|
||||
const setChecklistCriterion = (ci: ChecklistItemDef, instituteeId: number | undefined, criterionItemId: number | null) =>
|
||||
saveChecklistResponse(ci, instituteeId, { criterionItemId: criterionItemId ?? undefined })
|
||||
|
||||
/** Lokale (KI-freie) Kriterium-Vorschläge für Checklisten-Antworten ohne effektives Kriterium — analog `localLineSuggestions`. */
|
||||
const localChecklistSuggestions = useMemo(() => {
|
||||
const map = new Map<string, CriterionSuggestion[]>()
|
||||
if (corpus.length === 0) return map
|
||||
for (const ci of checklist) {
|
||||
const targets = ci.scope === 'meetingWide' ? [undefined] : institutees.map(i => i.id)
|
||||
for (const instituteeId of targets) {
|
||||
if (getEffectiveChecklistCriterion(ci, instituteeId) !== null) continue
|
||||
const comment = getChecklistResponse(ci.id!, instituteeId)?.note?.trim()
|
||||
if (!comment) continue
|
||||
const hints = findSimilarTaggedLines(comment, corpus, 3).filter(h => h.score >= 0.25)
|
||||
if (hints.length === 0) continue
|
||||
map.set(`${ci.id}:${instituteeId ?? ''}`, hints.map((h, idx) => ({ criterionItemId: h.criterionItemId, rank: idx + 1 })))
|
||||
}
|
||||
}
|
||||
return map
|
||||
}, [checklist, checklistResponses, institutees, corpus])
|
||||
|
||||
const mergedChecklistSuggestions = useMemo(() => {
|
||||
const merged = new Map(localChecklistSuggestions)
|
||||
for (const [key, sugg] of checklistSuggestions) merged.set(key, sugg)
|
||||
return merged
|
||||
}, [localChecklistSuggestions, checklistSuggestions])
|
||||
|
||||
const getChecklistSuggestions = (checklistItemId: number, instituteeId: number | undefined): CriterionSuggestion[] | undefined =>
|
||||
mergedChecklistSuggestions.get(`${checklistItemId}:${instituteeId ?? ''}`)
|
||||
|
||||
// ── Meeting-level handlers ────────────────────────────────────────────────
|
||||
|
||||
const saveGeneralNotes = (val: string) => {
|
||||
setGeneralNotes(val)
|
||||
if (notesTimer.current) clearTimeout(notesTimer.current)
|
||||
notesTimer.current = setTimeout(() => updateMeetingInstance(meetingId, { generalNotes: val }), 600)
|
||||
|
||||
if (hintsTimer.current) clearTimeout(hintsTimer.current)
|
||||
hintsTimer.current = setTimeout(() => {
|
||||
const lastLine = val.split('\n').pop()?.trim() ?? ''
|
||||
setGeneralNotesHints(lastLine ? findSimilarTaggedLines(lastLine, corpus) : [])
|
||||
}, 800)
|
||||
}
|
||||
|
||||
/** Verwaiste Zuordnungen entfernen, falls eine getaggte Zeile beim Editieren verändert/gelöscht wurde. */
|
||||
const finishEditingGeneralNotes = () => {
|
||||
const currentLines = splitNoteLines(generalNotes)
|
||||
const prunedTags = generalNoteTags.filter(t => currentLines.includes(t.text))
|
||||
if (prunedTags.length !== generalNoteTags.length) {
|
||||
setGeneralNoteTags(prunedTags)
|
||||
updateMeetingInstance(meetingId, { generalNoteTags: prunedTags })
|
||||
}
|
||||
setEditingGeneralNotes(false)
|
||||
setGeneralNotesHints([])
|
||||
}
|
||||
|
||||
/** Übernimmt einen Formulierungsvorschlag als Ersatz für die gerade getippte (letzte) Zeile. */
|
||||
const applyGeneralHint = (hintText: string) => {
|
||||
const lines = generalNotes.split('\n')
|
||||
lines[lines.length - 1] = hintText
|
||||
saveGeneralNotes(lines.join('\n'))
|
||||
setGeneralNotesHints([])
|
||||
setTimeout(() => generalNotesRef.current?.focus(), 0)
|
||||
}
|
||||
|
||||
/** Wie setLineCriterion, aber meeting-weit statt an ein Institutee gebunden — gilt für alle Institutees. */
|
||||
const setGeneralNoteCriterion = async (lineText: string, criterionItemId: number | null) => {
|
||||
const currentLines = splitNoteLines(generalNotes)
|
||||
const kept = generalNoteTags.filter(t => t.text !== lineText && currentLines.includes(t.text))
|
||||
const nextTags = criterionItemId === null ? kept : [...kept, { text: lineText, criterionItemId }]
|
||||
await updateMeetingInstance(meetingId, { generalNoteTags: nextTags })
|
||||
setGeneralNoteTags(nextTags)
|
||||
}
|
||||
|
||||
/**
|
||||
* „🏷 Vorschläge analysieren" — EIN gebündelter KI-Call für das gesamte offene Protokoll
|
||||
* (nicht pro Zeile), siehe CLAUDE.md „Selbstlernendes Kriterien-Tagging". Sammelt alle noch
|
||||
* nicht zugeordneten Zeilen (Gesprächsbeiträge + allgemeine Notizen, Kundenzitate ausgenommen —
|
||||
* gleiches Ausschlussprinzip wie in aiPrompt.ts), lässt die KI pro Zeile priorisierte
|
||||
* Kriterium-IDs vorschlagen und persistiert die als Nebenprodukt gelieferten Formulierungsmuster
|
||||
* direkt auf `FeedbackCriterionItem.learnedPatternHints`.
|
||||
*/
|
||||
const analyzeSuggestions = async () => {
|
||||
if (!assignment) return
|
||||
const settings = getAiSettings()
|
||||
if (!settings.apiKey) {
|
||||
setSuggestionError('Kein KI-API-Key hinterlegt (Config → KI-Prompts bzw. Feedback-Seite → KI-Einstellungen).')
|
||||
return
|
||||
}
|
||||
|
||||
setAnalyzingSuggestions(true)
|
||||
setSuggestionError('')
|
||||
setSuggestionInfo('')
|
||||
setLastAnalysisRaw(null)
|
||||
try {
|
||||
const [aType, structure, corpus, template] = await Promise.all([
|
||||
getAssignmentType(assignment.assignmentTypeId),
|
||||
loadFeedbackStructure(),
|
||||
getGlobalLineTagCorpus(),
|
||||
getOrSeedCriterionTaggingPromptTemplate(),
|
||||
])
|
||||
const visible = resolveVisibleStructure(
|
||||
structure.dimensions,
|
||||
structure.categories,
|
||||
structure.items,
|
||||
aType?.criteriaIds,
|
||||
)
|
||||
|
||||
interface LineRef { lineNumber: number; text: string; speakerLabel?: string; checklistKey?: string }
|
||||
const lineRefs: LineRef[] = []
|
||||
let n = 1
|
||||
for (const entry of entries) {
|
||||
const inst = institutees.find(i => i.id === entry.instituteeId)
|
||||
const taggedTexts = new Set((entry.lineTags ?? []).map(t => t.text))
|
||||
for (const line of splitNoteLines(entry.note)) {
|
||||
if (taggedTexts.has(line) || parseNotationPrefix(line).isQuote) continue
|
||||
lineRefs.push({ lineNumber: n++, text: line, speakerLabel: inst ? tagLabel(inst) : undefined })
|
||||
}
|
||||
}
|
||||
const taggedGeneralTexts = new Set(generalNoteTags.map(t => t.text))
|
||||
for (const line of splitNoteLines(generalNotes)) {
|
||||
if (taggedGeneralTexts.has(line) || parseNotationPrefix(line).isQuote) continue
|
||||
lineRefs.push({ lineNumber: n++, text: line })
|
||||
}
|
||||
// Checklisten-Antworten ohne effektives Kriterium (weder individuell noch konfiguriert) — auch
|
||||
// ohne Kommentar einbeziehen (Label allein ist bereits ein brauchbares Signal für die KI),
|
||||
// sonst bleiben reine Bewertungen ohne Freitext fälschlich unanalysiert.
|
||||
for (const ci of checklist) {
|
||||
const targets = ci.scope === 'meetingWide' ? [undefined] : institutees.map(i => i.id)
|
||||
for (const instituteeId of targets) {
|
||||
if (getEffectiveChecklistCriterion(ci, instituteeId) !== null) continue
|
||||
const comment = getChecklistResponse(ci.id!, instituteeId)?.note?.trim()
|
||||
const inst = instituteeId ? institutees.find(i => i.id === instituteeId) : undefined
|
||||
lineRefs.push({
|
||||
lineNumber: n++,
|
||||
text: comment ? `${ci.label}: ${comment}` : ci.label,
|
||||
speakerLabel: inst ? tagLabel(inst) : undefined,
|
||||
checklistKey: `${ci.id}:${instituteeId ?? ''}`,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (lineRefs.length === 0) {
|
||||
setSuggestionInfo('Keine offenen Protokollzeilen oder Checklisten-Punkte gefunden — alles bereits zugeordnet oder leer.')
|
||||
return
|
||||
}
|
||||
|
||||
const context = buildCriterionSuggestionPromptContext({
|
||||
assignmentTypeName: aType?.name ?? '—',
|
||||
dimensions: visible.dimensions,
|
||||
categories: visible.categories,
|
||||
items: visible.items,
|
||||
visibleCriteriaIds: aType?.criteriaIds,
|
||||
lines: lineRefs,
|
||||
corpus,
|
||||
})
|
||||
const prompt = renderDimensionPrompt(template, context)
|
||||
const raw = await callOpenRouter(prompt, settings)
|
||||
setLastAnalysisRaw(raw)
|
||||
const { lineSuggestions: parsedLines, patternHints } = parseCriterionSuggestionResponse(raw)
|
||||
|
||||
const nextSuggestions = new Map<string, CriterionSuggestion[]>()
|
||||
const nextChecklistSuggestions = new Map<string, CriterionSuggestion[]>()
|
||||
for (const ref of lineRefs) {
|
||||
const ids = parsedLines.get(ref.lineNumber)
|
||||
if (!ids || ids.length === 0) continue
|
||||
const suggestions = ids.map((criterionItemId, idx) => ({ criterionItemId, rank: idx + 1 }))
|
||||
if (ref.checklistKey) nextChecklistSuggestions.set(ref.checklistKey, suggestions)
|
||||
else nextSuggestions.set(ref.text, suggestions)
|
||||
}
|
||||
setLineSuggestions(nextSuggestions)
|
||||
setChecklistSuggestions(nextChecklistSuggestions)
|
||||
|
||||
const totalSuggestions = nextSuggestions.size + nextChecklistSuggestions.size
|
||||
setSuggestionInfo(totalSuggestions === 0
|
||||
? `${lineRefs.length} Zeile(n)/Punkt(e) analysiert, aber die KI hat für keine(n) davon einen Vorschlag geliefert — Rohantwort unten einsehbar.`
|
||||
: `${lineRefs.length} Zeile(n)/Punkt(e) analysiert, ${totalSuggestions} Vorschlag/Vorschläge erhalten.`)
|
||||
|
||||
if (patternHints.size > 0) {
|
||||
await Promise.all([...patternHints.entries()].map(([criterionItemId, hint]) =>
|
||||
updateFeedbackCriterionItem(criterionItemId, { learnedPatternHints: hint }),
|
||||
))
|
||||
setFbItems(prev => prev.map(i => patternHints.has(i.id!) ? { ...i, learnedPatternHints: patternHints.get(i.id!) } : i))
|
||||
}
|
||||
} catch (e) {
|
||||
setSuggestionError(e instanceof Error ? e.message : 'Unbekannter Fehler bei der Analyse.')
|
||||
} finally {
|
||||
setAnalyzingSuggestions(false)
|
||||
}
|
||||
}
|
||||
|
||||
const buildFilename = (ext: string) => {
|
||||
@@ -291,8 +640,9 @@ export default function MeetingView() {
|
||||
|
||||
if (!meeting || !template) return <div className="text-center py-10 text-gray-400">Lädt…</div>
|
||||
|
||||
const hasConv = template.hasConversation
|
||||
const hasAssess = template.hasAssessment
|
||||
const hasConv = template.hasConversation
|
||||
const hasAssess = template.hasAssessment
|
||||
const hasChecklist = template.hasChecklist
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
@@ -316,6 +666,12 @@ export default function MeetingView() {
|
||||
className="text-sm bg-white border border-gray-200 text-gray-600 px-2.5 py-1.5 rounded-lg font-medium">
|
||||
📜 Verlauf
|
||||
</button>
|
||||
<button onClick={analyzeSuggestions}
|
||||
disabled={analyzingSuggestions}
|
||||
title="KI-Vorschläge für noch nicht zugeordnete Protokollzeilen"
|
||||
className="text-sm bg-white border border-blue-200 text-blue-600 px-2.5 py-1.5 rounded-lg font-medium disabled:opacity-50">
|
||||
{analyzingSuggestions ? '⏳ Analysiere…' : '🏷 Vorschläge analysieren'}
|
||||
</button>
|
||||
<div className="relative">
|
||||
<button onClick={() => setShowExportMenu(p => !p)}
|
||||
className="text-sm bg-white border border-gray-200 text-gray-600 px-2.5 py-1.5 rounded-lg font-medium">
|
||||
@@ -346,6 +702,24 @@ export default function MeetingView() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{suggestionError && (
|
||||
<div className="bg-red-50 border border-red-200 rounded-xl px-3 py-2 text-xs text-red-600">
|
||||
{suggestionError}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{suggestionInfo && (
|
||||
<div className="bg-blue-50 border border-blue-200 rounded-xl px-3 py-2 text-xs text-blue-700 space-y-1">
|
||||
<div>{suggestionInfo}</div>
|
||||
{lastAnalysisRaw && (
|
||||
<details>
|
||||
<summary className="cursor-pointer select-none font-medium">🔍 Rohantwort ansehen</summary>
|
||||
<pre className="mt-1 whitespace-pre-wrap text-[10px] text-blue-900 bg-white border border-blue-100 rounded-lg p-2 max-h-64 overflow-y-auto">{lastAnalysisRaw}</pre>
|
||||
</details>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Löschen-Bestätigung */}
|
||||
{showDeleteConfirm && (
|
||||
<div className="bg-red-50 border border-red-200 rounded-xl p-4 space-y-3">
|
||||
@@ -367,28 +741,66 @@ export default function MeetingView() {
|
||||
{/* Allgemeine Notizen */}
|
||||
{editingGeneralNotes ? (
|
||||
<textarea
|
||||
ref={generalNotesRef}
|
||||
autoFocus
|
||||
className="w-full border border-brand rounded-xl px-3 py-2 text-sm bg-white focus:outline-none resize-none"
|
||||
style={{ minHeight: '4rem', fieldSizing: 'content' } as React.CSSProperties}
|
||||
placeholder="Allgemeine Notizen zum Meeting… (+ gut, ! negativ, > Kundeninput)"
|
||||
value={generalNotes}
|
||||
onChange={e => saveGeneralNotes(e.target.value)}
|
||||
onBlur={() => setEditingGeneralNotes(false)}
|
||||
onBlur={finishEditingGeneralNotes}
|
||||
/>
|
||||
) : (
|
||||
) : null}
|
||||
{editingGeneralNotes && generalNotesHints.length > 0 && (
|
||||
<details className="bg-blue-50 border border-blue-100 rounded-lg px-3 py-1.5" open>
|
||||
<summary className="text-xs font-medium text-blue-700 cursor-pointer select-none">💭 Ähnliche frühere Notizen — klicken zum Übernehmen</summary>
|
||||
<ul className="mt-1 space-y-0.5">
|
||||
{generalNotesHints.map((h, i) => (
|
||||
<li key={i}>
|
||||
<button type="button"
|
||||
onMouseDown={e => e.preventDefault()}
|
||||
onClick={() => applyGeneralHint(h.text)}
|
||||
className="text-xs text-blue-800 hover:text-blue-950 hover:underline truncate text-left w-full">
|
||||
„{h.text}"
|
||||
{fbItems.find(i => i.id === h.criterionItemId)?.name && (
|
||||
<span className="text-blue-400"> → 🏷 {fbItems.find(i => i.id === h.criterionItemId)?.name}</span>
|
||||
)}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</details>
|
||||
)}
|
||||
{!editingGeneralNotes && (
|
||||
<div onClick={() => setEditingGeneralNotes(true)}
|
||||
className="w-full border border-gray-200 rounded-xl px-3 py-2 text-sm bg-white cursor-text min-h-[2.5rem]">
|
||||
{generalNotes.trim()
|
||||
? <NotationText text={generalNotes} />
|
||||
? (
|
||||
<NotationText
|
||||
text={generalNotes}
|
||||
colorBands={colorBands}
|
||||
renderLineAddon={line => (
|
||||
<span onClick={e => e.stopPropagation()}>
|
||||
<CriterionTagPicker
|
||||
items={fbItems}
|
||||
categories={fbCategories}
|
||||
value={generalNoteTags.find(t => t.text === line)?.criterionItemId ?? null}
|
||||
onChange={itemId => setGeneralNoteCriterion(line, itemId)}
|
||||
suggestions={mergedLineSuggestions.get(line)}
|
||||
/>
|
||||
</span>
|
||||
)}
|
||||
/>
|
||||
)
|
||||
: <span className="text-gray-300">Allgemeine Notizen zum Meeting…</span>
|
||||
}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Tabs */}
|
||||
{(hasConv || hasAssess) && (
|
||||
{(hasConv || hasAssess || hasChecklist) && (
|
||||
<div className="flex bg-gray-100 rounded-xl p-1">
|
||||
{hasConv && (
|
||||
{(hasConv || hasChecklist) && (
|
||||
<button onClick={() => setTab('conversation')}
|
||||
className={`flex-1 py-2 rounded-lg text-sm font-medium transition ${
|
||||
tab === 'conversation' ? 'bg-white text-brand shadow-sm' : 'text-gray-500'
|
||||
@@ -401,18 +813,38 @@ export default function MeetingView() {
|
||||
className={`flex-1 py-2 rounded-lg text-sm font-medium transition ${
|
||||
tab === 'assessment' ? 'bg-white text-brand shadow-sm' : 'text-gray-500'
|
||||
}`}>
|
||||
Gesamtbewertung
|
||||
Einschätzung
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Checkliste — ganz normal im Gesprächsprotokoll angezeigt, kein eigener Tab (siehe CLAUDE.md) */}
|
||||
{tab === 'conversation' && hasChecklist && (
|
||||
<ChecklistTab
|
||||
institutees={institutees}
|
||||
checklist={checklist}
|
||||
fbItems={fbItems}
|
||||
fbCategories={fbCategories}
|
||||
tagLabel={tagLabel}
|
||||
getChecklistResponse={getChecklistResponse}
|
||||
onSetChecklistRating={setChecklistRating}
|
||||
onSaveChecklistNote={saveChecklistNote}
|
||||
getEffectiveCriterion={getEffectiveChecklistCriterion}
|
||||
onSetChecklistCriterion={setChecklistCriterion}
|
||||
getChecklistSuggestions={getChecklistSuggestions}
|
||||
colorBands={colorBands}
|
||||
/>
|
||||
)}
|
||||
|
||||
{tab === 'conversation' && hasConv && (
|
||||
<ConversationTab
|
||||
institutees={institutees}
|
||||
fbCategories={fbCategories}
|
||||
fbItems={fbItems}
|
||||
entries={entries}
|
||||
lineSuggestions={mergedLineSuggestions}
|
||||
corpus={corpus}
|
||||
activeInstId={activeInstId}
|
||||
activeEntryId={activeEntryId}
|
||||
entryNote={entryNote}
|
||||
@@ -438,6 +870,7 @@ export default function MeetingView() {
|
||||
onEditNoteChange={setEditNote}
|
||||
onDeleteEntry={deleteEntry}
|
||||
onAdjustFiller={adjustFiller}
|
||||
colorBands={colorBands}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -448,6 +881,7 @@ export default function MeetingView() {
|
||||
fbItems={fbItems}
|
||||
assessments={assessments}
|
||||
entries={entries}
|
||||
generalNoteTags={generalNoteTags}
|
||||
hasConv={hasConv}
|
||||
tagLabel={tagLabel}
|
||||
fillerTotal={fillerTotal}
|
||||
@@ -455,8 +889,10 @@ export default function MeetingView() {
|
||||
onSetAssessmentScore={setAssessmentScore}
|
||||
onSaveAssessmentNote={saveAssessmentNote}
|
||||
onAutoCalc={autoCalcAssessment}
|
||||
colorBands={colorBands}
|
||||
/>
|
||||
)}
|
||||
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { AI_CONFIG } from '../config/constants'
|
||||
|
||||
export interface AiSettings {
|
||||
apiKey: string
|
||||
model: string
|
||||
}
|
||||
|
||||
export function getAiSettings(): AiSettings {
|
||||
return {
|
||||
apiKey: localStorage.getItem(AI_CONFIG.localStorageKeyApiKey) ?? '',
|
||||
model: localStorage.getItem(AI_CONFIG.localStorageKeyModel) ?? AI_CONFIG.defaultModel,
|
||||
}
|
||||
}
|
||||
|
||||
export function saveAiSettings(apiKey: string, model: string): void {
|
||||
localStorage.setItem(AI_CONFIG.localStorageKeyApiKey, apiKey)
|
||||
localStorage.setItem(AI_CONFIG.localStorageKeyModel, model)
|
||||
}
|
||||
|
||||
/**
|
||||
* Einziger Netzwerk-Kontaktpunkt zu OpenRouter — läuft bewusst client-seitig direkt gegen die
|
||||
* API (nicht über den RPC-Server), API-Key kommt aus `localStorage`. Extrahiert aus
|
||||
* `AssignmentFeedbackPage.tsx` (KI-Feedback-Generierung), damit das selbstlernende
|
||||
* Kriterien-Tagging keine zweite, leicht abweichende Fetch-Implementierung braucht.
|
||||
*/
|
||||
export async function callOpenRouter(prompt: string, settings: AiSettings): Promise<string> {
|
||||
const res = await fetch(`${AI_CONFIG.openRouterBaseUrl}/chat/completions`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${settings.apiKey}`,
|
||||
'Content-Type': 'application/json',
|
||||
'HTTP-Referer': window.location.origin,
|
||||
'X-Title': 'Assignment Monitor',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: settings.model,
|
||||
messages: [{ role: 'user', content: prompt }],
|
||||
}),
|
||||
})
|
||||
if (!res.ok) throw new Error(`API-Fehler: ${res.status} ${res.statusText}`)
|
||||
|
||||
const data = await res.json()
|
||||
return data.choices?.[0]?.message?.content ?? ''
|
||||
}
|
||||
+454
-50
@@ -1,28 +1,38 @@
|
||||
import type {
|
||||
Consultant, Assignment, FeedbackDimension, FeedbackCategory, FeedbackCriterionItem,
|
||||
FeedbackCategoryRating, Assessment, ConversationEntry, MeetingInstance, FeedbackRating,
|
||||
FeedbackCategoryRating, Assessment, ConversationEntry, MeetingInstance, RatingScore,
|
||||
} from '../db/types'
|
||||
import { RATING_OPTIONS, RATING_NUM_MAP } from '../config/constants'
|
||||
import { clampRatingScore, isValidRatingScore } from '../config/constants'
|
||||
import { splitNoteLines, parseNotationPrefix } from './notationParser'
|
||||
import { numberToRating, type TrendResult } from './ratingTrend'
|
||||
|
||||
const ratingToNum = (r: FeedbackRating | null | undefined): number =>
|
||||
r ? (RATING_NUM_MAP[r] ?? 0) : 0
|
||||
|
||||
const fullRatingLabel = (r: FeedbackRating): string => RATING_OPTIONS.find(o => o.value === r)?.full ?? r
|
||||
import type { TrendResult } from './ratingTrend'
|
||||
|
||||
/**
|
||||
* Löst ein Notation-Präfix (`+`/`(+)`/`(!)`/`!`/`>`) am Zeilenanfang zu einem ausgeschriebenen,
|
||||
* mit " — " abgetrennten Label auf. Bewusst KEINE eckigen Klammern als Wrapper — die Notizen
|
||||
* nutzen `[Titel]` bereits für Slide-/Themen-Referenzen (siehe SLIDE_RE in notationParser.tsx),
|
||||
* eckige Klammern um das Label würden damit für die KI ununterscheidbar kollidieren.
|
||||
* Löst ein Notations-Präfix (führende Score-Zahl 1–10 bzw. `>`) am Zeilenanfang auf.
|
||||
* Format bewusst „Score N/10 — Text" bzw. „Kundenzitat — Text" — keine eckigen Klammern
|
||||
* als Wrapper, da `[Titel]` bereits für Slide-/Themen-Referenzen reserviert ist.
|
||||
*/
|
||||
const formatNotationLine = (line: string): string => {
|
||||
const { rating, isQuote, text } = parseNotationPrefix(line)
|
||||
const tag = isQuote ? 'Kundenzitat' : rating ? fullRatingLabel(rating) : null
|
||||
const tag = isQuote ? 'Kundenzitat' : rating !== null ? `Score ${rating}/10` : null
|
||||
return tag ? `${tag} — ${text}` : text
|
||||
}
|
||||
|
||||
/** Ganze Zeile besteht nur aus "[Titel]" — Abschnittsmarker des Bewerters (Slide-/Themen-Referenz). */
|
||||
const MARKER_ONLY_RE = /^\[[^\]]*\]$/
|
||||
|
||||
/**
|
||||
* Abschnittsmarker wie "[Background]" sind reine Navigationshilfe für den Bewerter (an welcher
|
||||
* Stelle der Präsentation/des Dialogs eine Beobachtung entstand) — für die KI ohne nachfolgenden
|
||||
* Inhalt bedeutungslos und keine Bewertungsgrundlage. Bleibt erhalten, wenn die direkt folgende
|
||||
* Zeile noch Inhalt liefert (dann als Kontext-Header sinnvoll), sonst wird die Marker-Zeile entfernt.
|
||||
*/
|
||||
const dropDanglingMarkers = (lines: string[]): string[] =>
|
||||
lines.filter((line, i) => {
|
||||
if (!MARKER_ONLY_RE.test(line.trim())) return true
|
||||
const next = lines[i + 1]
|
||||
return next !== undefined && !MARKER_ONLY_RE.test(next.trim())
|
||||
})
|
||||
|
||||
export interface DimensionPromptInput {
|
||||
institutee: Consultant
|
||||
assignment: Assignment
|
||||
@@ -53,36 +63,41 @@ export function buildDimensionPromptContext(input: DimensionPromptInput): Record
|
||||
const fillerTotal = instEntries.reduce((s, e) => s + (e.fillerCount ?? 0), 0)
|
||||
|
||||
const kategorienStruktur = dimCategories
|
||||
.map((c, i) => `${i + 1}. ${c.name}`)
|
||||
.map((c, i) => `${i + 1}. ${c.name}${c.description ? ` — ${c.description}` : ''}`)
|
||||
.join('\n') || '(keine Kategorien)'
|
||||
|
||||
const kriterienScores = dimCategories.map(cat => {
|
||||
const catItems = dimItems.filter(i => i.categoryId === cat.id)
|
||||
const lines = catItems.map(c => {
|
||||
const scores = instAssessments.filter(a => a.criteriaId === c.id && a.score !== null && a.score !== 'na')
|
||||
const scores = instAssessments.filter(a => a.criteriaId === c.id && isValidRatingScore(a.score))
|
||||
const generalNotesForCrit = meetings.flatMap(m =>
|
||||
(m.generalNoteTags ?? []).filter(t => t.criterionItemId === c.id).map(t => t.text),
|
||||
)
|
||||
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),
|
||||
...generalNotesForCrit,
|
||||
].map(formatNotationLine)
|
||||
// Kriterien ohne jede Beobachtung (weder Score noch Notiz) auslassen — reines Rauschen für die KI.
|
||||
if (scores.length === 0 && notes.length === 0) return null
|
||||
const avgNum = scores.length > 0
|
||||
? scores.reduce((s, a) => s + ratingToNum(a.score), 0) / scores.length
|
||||
? scores.reduce((s, a) => s + (a.score as number), 0) / scores.length
|
||||
: null
|
||||
const avgLabel = avgNum !== null ? `${fullRatingLabel(numberToRating(avgNum))} (${avgNum.toFixed(1)})` : 'nur Notiz, keine Bewertung'
|
||||
const clamped = avgNum !== null ? clampRatingScore(avgNum) : null
|
||||
const avgLabel = avgNum !== null
|
||||
? `${clamped ?? avgNum.toFixed(1)}/10 (Ø ${avgNum.toFixed(1)})`
|
||||
: 'nur Notiz, keine Bewertung'
|
||||
const label = c.description ? `${c.name} (${c.description})` : c.name
|
||||
return ` ${label}: ${avgLabel}${notes.length > 0 ? ` | Notizen: ${notes.join('; ')}` : ''}`
|
||||
}).filter((l): l is string => l !== null)
|
||||
// Kategorien ohne jede Beobachtung ganz auslassen — tauchen bereits über KATEGORIEN_STRUKTUR/
|
||||
// KATEGORIE_BEWERTUNGEN/ENTWICKLUNG_VERLAUF auf, hier nur zusätzliches Rauschen.
|
||||
if (lines.length === 0) return null
|
||||
return ` ${cat.name}:\n${lines.join('\n')}`
|
||||
}).filter((l): l is string => l !== null).join('\n') || '(keine Scores erfasst)'
|
||||
|
||||
const kategorieBewertungen = dimCategories.map(cat => {
|
||||
const r = ratings.find(r => r.feedbackCategoryId === cat.id)
|
||||
const rating = RATING_OPTIONS.find(x => x.value === r?.rating)?.label ?? 'nicht bewertet'
|
||||
return ` ${cat.name}: ${rating}`
|
||||
const r = ratings.find(x => x.feedbackCategoryId === cat.id)
|
||||
const rating: RatingScore | undefined = r?.rating
|
||||
const label = isValidRatingScore(rating) ? `${rating}/10` : 'nicht bewertet'
|
||||
return ` ${cat.name}: ${label}`
|
||||
}).join('\n') || '(keine Kategorien)'
|
||||
|
||||
const entwicklungVerlauf = dimCategories.map(cat => {
|
||||
@@ -99,7 +114,11 @@ export function buildDimensionPromptContext(input: DimensionPromptInput): Record
|
||||
const notizenAllgemeinMeeting = meetings
|
||||
.map(m => {
|
||||
if (!m.generalNotes || m.generalNotes.trim() === '') return null
|
||||
const lines = splitNoteLines(m.generalNotes).map(line => ` - ${formatNotationLine(line)}`)
|
||||
const rawLines = splitNoteLines(m.generalNotes)
|
||||
.filter(line => !(m.generalNoteTags ?? []).some(t => t.text === line))
|
||||
.filter(line => !parseNotationPrefix(line).isQuote)
|
||||
const lines = dropDanglingMarkers(rawLines).map(line => ` - ${formatNotationLine(line)}`)
|
||||
if (lines.length === 0) return null
|
||||
return ` [${m.date}]\n${lines.join('\n')}`
|
||||
})
|
||||
.filter((x): x is string => x !== null)
|
||||
@@ -108,12 +127,14 @@ export function buildDimensionPromptContext(input: DimensionPromptInput): Record
|
||||
const protokollUnzugeordnet = meetings
|
||||
.map(m => {
|
||||
const meetingEntries = instEntries.filter(e => e.meetingInstanceId === m.id)
|
||||
const lines = meetingEntries
|
||||
const rawLines = meetingEntries
|
||||
.flatMap(e => splitNoteLines(e.note).map(line => ({
|
||||
line, tagged: (e.lineTags ?? []).some(t => t.text === line),
|
||||
})))
|
||||
.filter(x => !x.tagged)
|
||||
.map(x => ` - ${formatNotationLine(x.line)}`)
|
||||
.filter(x => !parseNotationPrefix(x.line).isQuote)
|
||||
.map(x => x.line)
|
||||
const lines = dropDanglingMarkers(rawLines).map(line => ` - ${formatNotationLine(line)}`)
|
||||
if (lines.length === 0) return null
|
||||
return ` [${m.date}]\n${lines.join('\n')}`
|
||||
})
|
||||
@@ -143,56 +164,439 @@ export function renderDimensionPrompt(template: string, context: Record<string,
|
||||
return result
|
||||
}
|
||||
|
||||
export interface ParsedDimensionResponse {
|
||||
categoryTexts: { name: string; text: string }[]
|
||||
export const renderPrompt = renderDimensionPrompt
|
||||
|
||||
export interface CategoryPromptInput {
|
||||
institutee: Consultant
|
||||
assignment: Assignment
|
||||
dimension: FeedbackDimension
|
||||
category: FeedbackCategory
|
||||
catItems: FeedbackCriterionItem[]
|
||||
ratings: FeedbackCategoryRating[]
|
||||
catTrend: TrendResult | undefined
|
||||
instAssessments: Assessment[]
|
||||
instEntries: ConversationEntry[]
|
||||
meetings: MeetingInstance[]
|
||||
}
|
||||
|
||||
export interface CategoryAiResult {
|
||||
score: number | null
|
||||
benefits: string
|
||||
concerns: string
|
||||
}
|
||||
|
||||
export interface CategoryCondenseEntry {
|
||||
name: string
|
||||
score: number | null
|
||||
benefits: string
|
||||
concerns: string
|
||||
}
|
||||
|
||||
export interface DimensionCondenseInput {
|
||||
institutee: Consultant
|
||||
assignment: Assignment
|
||||
dimension: FeedbackDimension
|
||||
categoryResults: CategoryCondenseEntry[]
|
||||
}
|
||||
|
||||
export interface ParsedDimensionCondenseResponse {
|
||||
achievements: string
|
||||
developmentNeeds: string
|
||||
}
|
||||
|
||||
/** Stufe A: schmaler Kontext für genau eine Kategorie. */
|
||||
export function buildCategoryPromptContext(input: CategoryPromptInput): Record<string, string> {
|
||||
const {
|
||||
institutee, assignment, dimension, category, catItems,
|
||||
ratings, catTrend, instAssessments, instEntries, meetings,
|
||||
} = input
|
||||
|
||||
const catItemIds = new Set(catItems.map(i => i.id))
|
||||
const allLineTags = instEntries.flatMap(e => e.lineTags ?? [])
|
||||
|
||||
const kriterienScores = catItems.map(c => {
|
||||
const scores = instAssessments.filter(a => a.criteriaId === c.id && isValidRatingScore(a.score))
|
||||
const generalNotesForCrit = meetings.flatMap(m =>
|
||||
(m.generalNoteTags ?? []).filter(t => t.criterionItemId === c.id).map(t => t.text),
|
||||
)
|
||||
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),
|
||||
...generalNotesForCrit,
|
||||
].map(formatNotationLine)
|
||||
if (scores.length === 0 && notes.length === 0) return null
|
||||
const avgNum = scores.length > 0
|
||||
? scores.reduce((s, a) => s + (a.score as number), 0) / scores.length
|
||||
: null
|
||||
const clamped = avgNum !== null ? clampRatingScore(avgNum) : null
|
||||
const avgLabel = avgNum !== null
|
||||
? `${clamped ?? avgNum.toFixed(1)}/10 (Ø ${avgNum.toFixed(1)})`
|
||||
: 'nur Notiz, keine Bewertung'
|
||||
const label = c.description ? `${c.name} (${c.description})` : c.name
|
||||
return ` ${label}: ${avgLabel}${notes.length > 0 ? ` | Notizen: ${notes.join('; ')}` : ''}`
|
||||
}).filter((l): l is string => l !== null).join('\n') || '(keine Scores/Notizen)'
|
||||
|
||||
const r = ratings.find(x => x.feedbackCategoryId === category.id)
|
||||
const manualRating = isValidRatingScore(r?.rating) ? `${r!.rating}/10` : 'nicht bewertet'
|
||||
|
||||
let entwicklungVerlauf = 'keine Verlaufsdaten'
|
||||
if (catTrend && catTrend.history.length > 0) {
|
||||
const seq = catTrend.history.map(h => h.score.toFixed(1)).join(' → ')
|
||||
const trendLabel = catTrend.trend === 'up' ? 'Verbesserung über die Laufzeit'
|
||||
: catTrend.trend === 'down' ? 'Verschlechterung über die Laufzeit'
|
||||
: catTrend.trend === 'stable' ? 'stabil'
|
||||
: 'nur ein Meeting, kein Trend ableitbar'
|
||||
entwicklungVerlauf = `Verlauf ${seq} (${trendLabel})`
|
||||
}
|
||||
|
||||
let trendVorschlag = 'Kein Meeting-Trend berechenbar — SCORE nur setzen wenn manuelle Bewertung oder Kriterien-Daten vorliegen.'
|
||||
if (catTrend?.suggestion !== null && catTrend?.suggestion !== undefined) {
|
||||
const s = catTrend.suggestion.toFixed(1)
|
||||
trendVorschlag = `Vorgeschlagener Score aus Meeting-Verlauf: ${s}/10. Bestätige diesen Wert im SCORE-Feld oder passe maximal um ±1 an (nicht frei erfinden).`
|
||||
}
|
||||
|
||||
const protokollGetaggt = meetings
|
||||
.map(m => {
|
||||
const meetingEntries = instEntries.filter(e => e.meetingInstanceId === m.id)
|
||||
const rawLines = meetingEntries
|
||||
.flatMap(e => splitNoteLines(e.note).map(line => ({
|
||||
line,
|
||||
tags: (e.lineTags ?? []).filter(t => t.text === line && catItemIds.has(t.criterionItemId)),
|
||||
})))
|
||||
.filter(x => x.tags.length > 0)
|
||||
.filter(x => !parseNotationPrefix(x.line).isQuote)
|
||||
.map(x => x.line)
|
||||
const generalTagged = (m.generalNoteTags ?? [])
|
||||
.filter(t => catItemIds.has(t.criterionItemId))
|
||||
.map(t => t.text)
|
||||
const allLines = [...rawLines, ...generalTagged]
|
||||
const lines = dropDanglingMarkers(allLines).map(line => ` - ${formatNotationLine(line)}`)
|
||||
if (lines.length === 0) return null
|
||||
return ` [${m.date}]\n${lines.join('\n')}`
|
||||
})
|
||||
.filter((x): x is string => x !== null)
|
||||
.join('\n') || '(keine getaggten Zeilen)'
|
||||
|
||||
const erlaeuterung = category.description
|
||||
? `Erläuterung: ${category.description}`
|
||||
: ''
|
||||
|
||||
return {
|
||||
'{{BERATER_NAME}}': `${institutee.firstName} ${institutee.lastName}`,
|
||||
'{{ASSIGNMENT_TITEL}}': assignment.title,
|
||||
'{{ASSIGNMENT_KUNDE}}': assignment.client,
|
||||
'{{DIMENSION_NAME}}': dimension.name,
|
||||
'{{KATEGORIE_NAME}}': category.name,
|
||||
'{{KATEGORIE_ERLAEUTERUNG}}': erlaeuterung,
|
||||
'{{KRITERIEN_SCORES}}': kriterienScores,
|
||||
'{{KATEGORIE_BEWERTUNG}}': manualRating,
|
||||
'{{ENTWICKLUNG_VERLAUF}}': entwicklungVerlauf,
|
||||
'{{TREND_VORSCHLAG}}': trendVorschlag,
|
||||
'{{PROTOKOLL_GETAGGT}}': protokollGetaggt,
|
||||
}
|
||||
}
|
||||
|
||||
/** Stufe B: Verdichtung aus Kategorie-Ergebnissen (ohne Rohprotokoll). */
|
||||
export function buildDimensionCondenseContext(input: DimensionCondenseInput): Record<string, string> {
|
||||
const { institutee, assignment, dimension, categoryResults } = input
|
||||
|
||||
const kategorieErgebnisse = categoryResults.map(cr => {
|
||||
const scoreLine = cr.score !== null ? `Score: ${cr.score}/10` : 'Score: nicht gesetzt'
|
||||
const ben = cr.benefits.trim() || '- n/a'
|
||||
const con = cr.concerns.trim() || '- n/a'
|
||||
return `${cr.name}\n${scoreLine}\nBenefits:\n${ben}\nConcerns:\n${con}`
|
||||
}).join('\n\n') || '(keine Kategorie-Ergebnisse)'
|
||||
|
||||
return {
|
||||
'{{BERATER_NAME}}': `${institutee.firstName} ${institutee.lastName}`,
|
||||
'{{ASSIGNMENT_TITEL}}': assignment.title,
|
||||
'{{ASSIGNMENT_KUNDE}}': assignment.client,
|
||||
'{{DIMENSION_NAME}}': dimension.name,
|
||||
'{{KATEGORIE_ERGEBNISSE}}': kategorieErgebnisse,
|
||||
}
|
||||
}
|
||||
|
||||
export function parseCategoryAiResponse(raw: string): CategoryAiResult {
|
||||
const cleaned = raw.trim().replace(/^```[a-z]*\n?/i, '').replace(/```$/, '').trim()
|
||||
const lines = cleaned.split('\n')
|
||||
|
||||
let score: number | null = null
|
||||
let benefits = ''
|
||||
let concerns = ''
|
||||
type Mode = 'none' | 'benefits' | 'concerns'
|
||||
let mode: Mode = 'none'
|
||||
let buffer: string[] = []
|
||||
|
||||
const takeBuffer = () => {
|
||||
const t = buffer.join('\n').trim()
|
||||
buffer = []
|
||||
return t
|
||||
}
|
||||
|
||||
const append = (prev: string, next: string) => [prev, next].filter(Boolean).join('\n').trim()
|
||||
|
||||
for (const line of lines) {
|
||||
const scoreMatch = line.match(SCORE_HDR)
|
||||
const benMatch = line.match(BENEFITS_HDR)
|
||||
const conMatch = line.match(CONCERNS_HDR)
|
||||
|
||||
if (scoreMatch) {
|
||||
score = Number(scoreMatch[1])
|
||||
continue
|
||||
}
|
||||
|
||||
if (benMatch) {
|
||||
const leftover = takeBuffer()
|
||||
if (leftover && mode === 'concerns') concerns = append(concerns, leftover)
|
||||
else if (leftover && mode === 'none') {
|
||||
const split = splitLooseCategoryBody(leftover)
|
||||
benefits = append(benefits, split.benefits)
|
||||
concerns = append(concerns, split.concerns)
|
||||
}
|
||||
mode = 'benefits'
|
||||
if (benMatch[2].trim()) benefits = append(benefits, benMatch[2].trim())
|
||||
continue
|
||||
}
|
||||
|
||||
if (conMatch) {
|
||||
const leftover = takeBuffer()
|
||||
if (leftover && mode === 'benefits') benefits = append(benefits, leftover)
|
||||
mode = 'concerns'
|
||||
if (conMatch[2].trim()) concerns = append(concerns, conMatch[2].trim())
|
||||
continue
|
||||
}
|
||||
|
||||
buffer.push(line)
|
||||
}
|
||||
|
||||
const leftover = takeBuffer()
|
||||
if (leftover) {
|
||||
if (mode === 'benefits') benefits = append(benefits, leftover)
|
||||
else if (mode === 'concerns') concerns = append(concerns, leftover)
|
||||
else {
|
||||
const split = splitLooseCategoryBody(leftover)
|
||||
benefits = append(benefits, split.benefits)
|
||||
concerns = append(concerns, split.concerns)
|
||||
}
|
||||
}
|
||||
|
||||
return { score, benefits, concerns }
|
||||
}
|
||||
|
||||
export function parseDimensionCondenseResponse(raw: string): ParsedDimensionCondenseResponse {
|
||||
const parsed = parseDimensionAiResponse(raw)
|
||||
return {
|
||||
achievements: parsed.achievements,
|
||||
developmentNeeds: parsed.developmentNeeds,
|
||||
}
|
||||
}
|
||||
|
||||
export interface ParsedDimensionResponse {
|
||||
categoryTexts: { name: string; benefits: string; concerns: string; score?: number | null }[]
|
||||
achievements: string
|
||||
developmentNeeds: string
|
||||
}
|
||||
|
||||
const BENEFITS_HDR = /^(BENEFITS|STÄRKEN|STAERKEN)\s*:\s*(.*)$/i
|
||||
const CONCERNS_HDR = /^(CONCERNS|RISIKEN|SCHWÄCHEN|SCHWAECHEN)\s*:\s*(.*)$/i
|
||||
const ACHIEVEMENTS_HDR = /^ACHIEVEMENTS\s*:\s*(.*)$/i
|
||||
const DEV_NEEDS_HDR = /^DEVELOPMENT_NEEDS\s*:\s*(.*)$/i
|
||||
const SCORE_HDR = /^SCORE\s*:\s*(\d{1,2})\s*$/i
|
||||
|
||||
/** Lose Stichpunkte ohne BENEFITS/CONCERNS-Marker: nach Score-/Präfix-Hinweisen aufteilen. */
|
||||
function splitLooseCategoryBody(raw: string): { benefits: string; concerns: string } {
|
||||
const lines = raw.split('\n').map(l => l.trim()).filter(Boolean)
|
||||
if (lines.length === 0) return { benefits: '', concerns: '' }
|
||||
|
||||
const benefits: string[] = []
|
||||
const concerns: string[] = []
|
||||
let bucket: 'b' | 'c' | null = null
|
||||
|
||||
for (const line of lines) {
|
||||
const benInline = line.match(BENEFITS_HDR)
|
||||
if (benInline) {
|
||||
bucket = 'b'
|
||||
if (benInline[2].trim()) benefits.push(benInline[2].trim())
|
||||
continue
|
||||
}
|
||||
const conInline = line.match(CONCERNS_HDR)
|
||||
if (conInline) {
|
||||
bucket = 'c'
|
||||
if (conInline[2].trim()) concerns.push(conInline[2].trim())
|
||||
continue
|
||||
}
|
||||
|
||||
const bullet = line.replace(/^[-*•]\s*/, '')
|
||||
if (/^(benefit|stärke|staerke|positiv)\b/i.test(bullet)) {
|
||||
benefits.push(line)
|
||||
continue
|
||||
}
|
||||
if (/^(concern|risiko|schwäche|schwaeche|negativ|sollte|empfehl)/i.test(bullet)) {
|
||||
concerns.push(line)
|
||||
continue
|
||||
}
|
||||
|
||||
const scoreInLine = bullet.match(/\b(?:score|bewertung)?\s*([1-9]|10)\s*(?:\/\s*10)?\b/i)
|
||||
?? bullet.match(/^([1-9]|10)\s*[:–—-]/)
|
||||
if (scoreInLine) {
|
||||
const n = Number(scoreInLine[1])
|
||||
if (n >= 6) benefits.push(line)
|
||||
else concerns.push(line)
|
||||
continue
|
||||
}
|
||||
|
||||
if (bucket === 'b') benefits.push(line)
|
||||
else if (bucket === 'c') concerns.push(line)
|
||||
else concerns.push(line)
|
||||
}
|
||||
|
||||
return {
|
||||
benefits: benefits.join('\n').trim(),
|
||||
concerns: concerns.join('\n').trim(),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Entfernt vorsorglich Markdown-Codefences (manche Provider ignorieren die Format-Anweisung im
|
||||
* Prompt trotzdem) und parst dann per Zeilen-Scan auf die festen KATEGORIE:/ACHIEVEMENTS:/
|
||||
* DEVELOPMENT_NEEDS:-Marker. Siehe CLAUDE.md — löst den früheren response_format-Bug strukturell.
|
||||
* Marker-basiert (kein JSON). Tolerant gegenüber Text in derselben Zeile wie der Marker
|
||||
* (`BENEFITS: - …`) und deutschen Synonymen. Ohne Untermarker: Heuristik über Score/Präfixe.
|
||||
*/
|
||||
export function parseDimensionAiResponse(raw: string): ParsedDimensionResponse {
|
||||
const cleaned = raw.trim().replace(/^```[a-z]*\n?/i, '').replace(/```$/, '').trim()
|
||||
const lines = cleaned.split('\n')
|
||||
|
||||
const categoryTexts: { name: string; text: string }[] = []
|
||||
const categoryTexts: { name: string; benefits: string; concerns: string; score?: number | null }[] = []
|
||||
let achievements = ''
|
||||
let developmentNeeds = ''
|
||||
|
||||
let mode: 'none' | 'category' | 'achievements' | 'development' = 'none'
|
||||
type Mode = 'none' | 'category' | 'catBenefits' | 'catConcerns' | 'achievements' | 'development'
|
||||
let mode: Mode = 'none'
|
||||
let currentName = ''
|
||||
let catBenefits = ''
|
||||
let catConcerns = ''
|
||||
let catScore: number | null = null
|
||||
let buffer: string[] = []
|
||||
|
||||
const flush = () => {
|
||||
const text = buffer.join('\n').trim()
|
||||
if (mode === 'category' && currentName) categoryTexts.push({ name: currentName, text })
|
||||
else if (mode === 'achievements') achievements = text
|
||||
else if (mode === 'development') developmentNeeds = text
|
||||
const takeBuffer = () => {
|
||||
const t = buffer.join('\n').trim()
|
||||
buffer = []
|
||||
return t
|
||||
}
|
||||
|
||||
const append = (prev: string, next: string) => [prev, next].filter(Boolean).join('\n').trim()
|
||||
|
||||
const flushCategory = () => {
|
||||
if (!currentName) { buffer = []; return }
|
||||
const leftover = takeBuffer()
|
||||
let benefits = catBenefits
|
||||
let concerns = catConcerns
|
||||
if (mode === 'catBenefits' && leftover) benefits = append(benefits, leftover)
|
||||
else if (mode === 'catConcerns' && leftover) concerns = append(concerns, leftover)
|
||||
else if (mode === 'category' && leftover) {
|
||||
if (!benefits && !concerns) {
|
||||
const split = splitLooseCategoryBody(leftover)
|
||||
benefits = split.benefits
|
||||
concerns = split.concerns
|
||||
} else {
|
||||
concerns = append(concerns, leftover)
|
||||
}
|
||||
}
|
||||
categoryTexts.push({ name: currentName, benefits, concerns, score: catScore })
|
||||
currentName = ''
|
||||
catBenefits = ''
|
||||
catConcerns = ''
|
||||
catScore = null
|
||||
}
|
||||
|
||||
const flush = () => {
|
||||
if (mode === 'category' || mode === 'catBenefits' || mode === 'catConcerns') flushCategory()
|
||||
else if (mode === 'achievements') achievements = takeBuffer()
|
||||
else if (mode === 'development') developmentNeeds = takeBuffer()
|
||||
else buffer = []
|
||||
}
|
||||
|
||||
const startDimBenefits = (sameLine: string) => {
|
||||
flush()
|
||||
mode = 'achievements'
|
||||
currentName = ''
|
||||
if (sameLine.trim()) buffer = [sameLine.trim()]
|
||||
}
|
||||
|
||||
const startDimConcerns = (sameLine: string) => {
|
||||
flush()
|
||||
mode = 'development'
|
||||
currentName = ''
|
||||
if (sameLine.trim()) buffer = [sameLine.trim()]
|
||||
}
|
||||
|
||||
for (const line of lines) {
|
||||
const catMatch = line.match(/^KATEGORIE:\s*(.+)$/i)
|
||||
const achMatch = line.match(/^ACHIEVEMENTS:\s*$/i)
|
||||
const devMatch = line.match(/^DEVELOPMENT_NEEDS:\s*$/i)
|
||||
const scoreMatch = line.match(SCORE_HDR)
|
||||
const benMatch = line.match(BENEFITS_HDR)
|
||||
const conMatch = line.match(CONCERNS_HDR)
|
||||
const achMatch = line.match(ACHIEVEMENTS_HDR)
|
||||
const devMatch = line.match(DEV_NEEDS_HDR)
|
||||
const inCat = mode === 'category' || mode === 'catBenefits' || mode === 'catConcerns'
|
||||
|
||||
if (catMatch) {
|
||||
flush()
|
||||
mode = 'category'
|
||||
currentName = catMatch[1].trim()
|
||||
} else if (achMatch) {
|
||||
flush()
|
||||
mode = 'achievements'
|
||||
currentName = ''
|
||||
} else if (devMatch) {
|
||||
flush()
|
||||
mode = 'development'
|
||||
currentName = ''
|
||||
} else {
|
||||
buffer.push(line)
|
||||
catBenefits = ''
|
||||
catConcerns = ''
|
||||
catScore = null
|
||||
continue
|
||||
}
|
||||
|
||||
if (inCat && scoreMatch) {
|
||||
catScore = Number(scoreMatch[1])
|
||||
continue
|
||||
}
|
||||
|
||||
if (inCat && benMatch) {
|
||||
const leftover = takeBuffer()
|
||||
if (leftover && mode === 'category') {
|
||||
const split = splitLooseCategoryBody(leftover)
|
||||
catBenefits = append(catBenefits, split.benefits)
|
||||
catConcerns = append(catConcerns, split.concerns)
|
||||
} else if (leftover && mode === 'catConcerns') catConcerns = append(catConcerns, leftover)
|
||||
else if (leftover && mode === 'catBenefits') catBenefits = append(catBenefits, leftover)
|
||||
mode = 'catBenefits'
|
||||
if (benMatch[2].trim()) catBenefits = append(catBenefits, benMatch[2].trim())
|
||||
continue
|
||||
}
|
||||
|
||||
if (inCat && conMatch) {
|
||||
const leftover = takeBuffer()
|
||||
if (leftover && mode === 'catBenefits') catBenefits = append(catBenefits, leftover)
|
||||
else if (leftover && mode === 'catConcerns') catConcerns = append(catConcerns, leftover)
|
||||
else if (leftover && mode === 'category') {
|
||||
const split = splitLooseCategoryBody(leftover)
|
||||
catBenefits = append(catBenefits, split.benefits)
|
||||
catConcerns = append(catConcerns, split.concerns)
|
||||
}
|
||||
mode = 'catConcerns'
|
||||
if (conMatch[2].trim()) catConcerns = append(catConcerns, conMatch[2].trim())
|
||||
continue
|
||||
}
|
||||
|
||||
if (achMatch) {
|
||||
startDimBenefits(achMatch[1] ?? '')
|
||||
continue
|
||||
}
|
||||
if (devMatch) {
|
||||
startDimConcerns(devMatch[1] ?? '')
|
||||
continue
|
||||
}
|
||||
if (!inCat && benMatch) {
|
||||
startDimBenefits(benMatch[2] ?? '')
|
||||
continue
|
||||
}
|
||||
if (!inCat && conMatch) {
|
||||
startDimConcerns(conMatch[2] ?? '')
|
||||
continue
|
||||
}
|
||||
|
||||
buffer.push(line)
|
||||
}
|
||||
flush()
|
||||
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { FeedbackDimension, FeedbackCategory, FeedbackCriterionItem } from '../db/types'
|
||||
|
||||
/**
|
||||
* Optgroups Dimension → Kategorie (HTML kennt kein verschachteltes optgroup) für "Ziel-Kriterium"-
|
||||
* Dropdowns — extrahiert aus FeedbackStructureConfig.tsx, damit AssignmentTypeConfig.tsx (Checklisten-
|
||||
* Kriterium-Verknüpfung) dieselbe Logik nutzt statt sie zu duplizieren.
|
||||
*/
|
||||
export function criterionOptionGroups(
|
||||
dimensions: FeedbackDimension[],
|
||||
categories: FeedbackCategory[],
|
||||
items: FeedbackCriterionItem[],
|
||||
excludeItemId?: number,
|
||||
) {
|
||||
const sorted = [...dimensions].sort((a, b) => a.order - b.order)
|
||||
return sorted.flatMap(d => {
|
||||
const dimCats = categories.filter(c => c.dimensionId === d.id).sort((a, b) => a.order - b.order)
|
||||
return dimCats.map(c => {
|
||||
const catItems = items.filter(i => i.categoryId === c.id && i.id !== excludeItemId).sort((a, b) => a.order - b.order)
|
||||
if (catItems.length === 0) return null
|
||||
return (
|
||||
<optgroup key={c.id} label={`${d.name} → ${c.name}`}>
|
||||
{catItems.map(i => <option key={i.id} value={i.id}>{i.name}</option>)}
|
||||
</optgroup>
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import type { ConversationLineTag } from '../db/types'
|
||||
import { parseNotationPrefix } from './notationParser'
|
||||
|
||||
/** Wörter unter dieser Länge sind zu unspezifisch (Artikel/Präpositionen) und werden verworfen. */
|
||||
const MIN_TOKEN_LENGTH = 3
|
||||
|
||||
/**
|
||||
* Zerlegt eine Protokollzeile in ein normalisiertes Token-Set für die lokale Ähnlichkeitssuche —
|
||||
* Notation-Präfix (führende Score-Zahl 1–10 bzw. `>`) wird über `parseNotationPrefix()` entfernt (gleiche
|
||||
* Normalisierung wie überall sonst), Rest kleingeschrieben und auf Wortzeichen aufgesplittet.
|
||||
*/
|
||||
export function normalizeLine(text: string): string[] {
|
||||
const { text: withoutPrefix } = parseNotationPrefix(text)
|
||||
return withoutPrefix
|
||||
.toLowerCase()
|
||||
.split(/[^\p{L}\p{N}]+/u)
|
||||
.filter(token => token.length >= MIN_TOKEN_LENGTH)
|
||||
}
|
||||
|
||||
export interface SimilarTaggedLine {
|
||||
text: string
|
||||
criterionItemId: number
|
||||
score: number
|
||||
}
|
||||
|
||||
const jaccard = (a: Set<string>, b: Set<string>): number => {
|
||||
if (a.size === 0 || b.size === 0) return 0
|
||||
let intersection = 0
|
||||
for (const token of a) if (b.has(token)) intersection++
|
||||
const union = a.size + b.size - intersection
|
||||
return union === 0 ? 0 : intersection / union
|
||||
}
|
||||
|
||||
/**
|
||||
* Rein lokale, KI-freie Vorauswahl ähnlicher bereits getaggter Alt-Zeilen (Wortüberschneidung/
|
||||
* Jaccard) — liefert der KI Kontext-Hinweise, ersetzt aber nicht deren Entscheidung. Pro
|
||||
* Kriterium wird nur der jeweils beste Treffer behalten, damit die Hinweisliste nicht von einem
|
||||
* einzelnen, oft wiederholten Kriterium dominiert wird.
|
||||
*/
|
||||
export function findSimilarTaggedLines(
|
||||
line: string,
|
||||
corpus: ConversationLineTag[],
|
||||
topK = 8,
|
||||
): SimilarTaggedLine[] {
|
||||
const lineTokens = new Set(normalizeLine(line))
|
||||
if (lineTokens.size === 0) return []
|
||||
|
||||
const bestPerCriterion = new Map<number, SimilarTaggedLine>()
|
||||
for (const entry of corpus) {
|
||||
const score = jaccard(lineTokens, new Set(normalizeLine(entry.text)))
|
||||
if (score <= 0) continue
|
||||
const existing = bestPerCriterion.get(entry.criterionItemId)
|
||||
if (!existing || score > existing.score) {
|
||||
bestPerCriterion.set(entry.criterionItemId, { text: entry.text, criterionItemId: entry.criterionItemId, score })
|
||||
}
|
||||
}
|
||||
|
||||
return [...bestPerCriterion.values()]
|
||||
.sort((a, b) => b.score - a.score)
|
||||
.slice(0, topK)
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
import type { FeedbackDimension, FeedbackCategory, FeedbackCriterionItem, ConversationLineTag } from '../db/types'
|
||||
import { resolveVisibleStructure } from '../db/queries/feedbackStructure'
|
||||
import { findSimilarTaggedLines } from './criterionSuggestion'
|
||||
|
||||
const byOrder = <T extends { order: number }>(rows: T[]) => [...rows].sort((a, b) => a.order - b.order)
|
||||
|
||||
/**
|
||||
* `{{KRITERIEN_STRUKTUR}}` — ID-referenzierte, verschachtelte Liste Dimension → Kategorie
|
||||
* (Name+Beschreibung) → Kriterium (Name+Beschreibung), gefiltert auf die im Assignment-Typ
|
||||
* sichtbaren Kriterien über `resolveVisibleStructure()` (dieselbe Logik wie Meeting/Feedback).
|
||||
*/
|
||||
export function buildCriterionStructureText(
|
||||
dimensions: FeedbackDimension[],
|
||||
allCategories: FeedbackCategory[],
|
||||
allItems: FeedbackCriterionItem[],
|
||||
visibleCriteriaIds: number[] | undefined,
|
||||
): string {
|
||||
const {
|
||||
dimensions: visibleDimensions,
|
||||
categories: visibleCategories,
|
||||
items: visibleItems,
|
||||
} = resolveVisibleStructure(dimensions, allCategories, allItems, visibleCriteriaIds)
|
||||
|
||||
const text = byOrder(visibleDimensions).map(dim => {
|
||||
const dimCategories = byOrder(visibleCategories.filter(c => c.dimensionId === dim.id))
|
||||
const catLines = dimCategories.map(cat => {
|
||||
const catItems = byOrder(visibleItems.filter(i => i.categoryId === cat.id))
|
||||
const itemLines = catItems.map(item => {
|
||||
const label = item.description ? `${item.name} — ${item.description}` : item.name
|
||||
return ` [${item.id}] ${label}`
|
||||
}).join('\n')
|
||||
const catLabel = cat.description ? `${cat.name} — ${cat.description}` : cat.name
|
||||
return ` ${catLabel}\n${itemLines}`
|
||||
}).join('\n')
|
||||
return `${dim.name}\n${catLines}`
|
||||
}).join('\n')
|
||||
|
||||
return text || '(keine sichtbaren Kriterien)'
|
||||
}
|
||||
|
||||
export interface CriterionSuggestionLine {
|
||||
/** Stabiler, nur innerhalb dieser Analyse gültiger Anker — nicht persistiert. */
|
||||
lineNumber: number
|
||||
text: string
|
||||
/** Institutee-Name bei Gesprächsbeiträgen, undefined bei allgemeinen Notizen. */
|
||||
speakerLabel?: string
|
||||
}
|
||||
|
||||
export interface CriterionSuggestionPromptInput {
|
||||
assignmentTypeName: string
|
||||
dimensions: FeedbackDimension[]
|
||||
categories: FeedbackCategory[]
|
||||
items: FeedbackCriterionItem[]
|
||||
visibleCriteriaIds: number[] | undefined
|
||||
lines: CriterionSuggestionLine[]
|
||||
/** Globaler Lern-Korpus, siehe `getGlobalLineTagCorpus()`. */
|
||||
corpus: ConversationLineTag[]
|
||||
}
|
||||
|
||||
const similarityLabel = (score: number): string => score >= 0.5 ? 'hoch' : score >= 0.25 ? 'mittel' : 'niedrig'
|
||||
|
||||
export function buildCriterionSuggestionPromptContext(input: CriterionSuggestionPromptInput): Record<string, string> {
|
||||
const { assignmentTypeName, dimensions, categories, items, visibleCriteriaIds, lines, corpus } = input
|
||||
|
||||
const { items: visibleItems } = resolveVisibleStructure(dimensions, categories, items, visibleCriteriaIds)
|
||||
const itemName = (id: number) => items.find(i => i.id === id)?.name ?? `#${id}`
|
||||
|
||||
const kriterienStruktur = buildCriterionStructureText(dimensions, categories, items, visibleCriteriaIds)
|
||||
|
||||
const protokollZeilen = lines
|
||||
.map(l => `${l.lineNumber}. ${l.speakerLabel ? `[${l.speakerLabel}] ` : ''}${l.text}`)
|
||||
.join('\n') || '(keine offenen Zeilen)'
|
||||
|
||||
const aehnlicheAltZuordnungen = lines.map(l => {
|
||||
const hints = findSimilarTaggedLines(l.text, corpus)
|
||||
if (hints.length === 0) return `Zeile ${l.lineNumber}: (keine ähnlichen Alt-Zeilen gefunden)`
|
||||
const hintLines = hints.map(h => ` - "${h.text}" → [${h.criterionItemId}] ${itemName(h.criterionItemId)} (Ähnlichkeit ${similarityLabel(h.score)})`)
|
||||
return `Zeile ${l.lineNumber}:\n${hintLines.join('\n')}`
|
||||
}).join('\n') || '(keine offenen Zeilen)'
|
||||
|
||||
const gelernteMuster = visibleItems
|
||||
.filter(i => i.learnedPatternHints?.trim())
|
||||
.map(i => ` [${i.id}] ${i.name}: ${i.learnedPatternHints}`)
|
||||
.join('\n') || '(noch keine gelernten Muster vorhanden)'
|
||||
|
||||
return {
|
||||
'{{ASSIGNMENT_TYP}}': assignmentTypeName,
|
||||
'{{KRITERIEN_STRUKTUR}}': kriterienStruktur,
|
||||
'{{GELERNTE_MUSTER}}': gelernteMuster,
|
||||
'{{AEHNLICHE_ALT_ZUORDNUNGEN}}': aehnlicheAltZuordnungen,
|
||||
'{{PROTOKOLL_ZEILEN}}': protokollZeilen,
|
||||
}
|
||||
}
|
||||
|
||||
export interface ParsedCriterionSuggestionResponse {
|
||||
/** Zeilennummer → priorisierte Kriterium-ID-Liste (leer = kein Vorschlag). */
|
||||
lineSuggestions: Map<number, number[]>
|
||||
/** Kriterium-ID → destilliertes Formulierungsmuster (Nebenprodukt dieses Laufs). */
|
||||
patternHints: Map<number, string>
|
||||
}
|
||||
|
||||
/**
|
||||
* Parst das Klartext-Antwortformat (`ZEILE 3: 12, 47, 5` / `ZEILE 9: -`, gefolgt von einem
|
||||
* `MUSTER:`-Block) — bewusst kein JSON, gleiches Robustheitsprinzip wie `parseDimensionAiResponse`
|
||||
* (Codefence-Stripping vorab, tolerant gegenüber fehlenden/kaputten Zeilen, kein Absturz).
|
||||
*/
|
||||
export function parseCriterionSuggestionResponse(raw: string): ParsedCriterionSuggestionResponse {
|
||||
const cleaned = raw.trim().replace(/^```[a-z]*\n?/i, '').replace(/```$/, '').trim()
|
||||
const lines = cleaned.split('\n')
|
||||
|
||||
const lineSuggestions = new Map<number, number[]>()
|
||||
const patternHints = new Map<number, string>()
|
||||
|
||||
let mode: 'lines' | 'patterns' = 'lines'
|
||||
let currentPatternId: number | null = null
|
||||
let patternBuffer: string[] = []
|
||||
|
||||
const flushPattern = () => {
|
||||
if (currentPatternId !== null) {
|
||||
const text = patternBuffer.join(' ').trim()
|
||||
if (text) patternHints.set(currentPatternId, text)
|
||||
}
|
||||
currentPatternId = null
|
||||
patternBuffer = []
|
||||
}
|
||||
|
||||
for (const rawLine of lines) {
|
||||
const line = rawLine.trim()
|
||||
if (/^MUSTER:\s*$/i.test(line)) {
|
||||
flushPattern()
|
||||
mode = 'patterns'
|
||||
continue
|
||||
}
|
||||
|
||||
if (mode === 'lines') {
|
||||
const m = line.match(/^ZEILE\s+(\d+)\s*:\s*(.*)$/i)
|
||||
if (!m) continue
|
||||
const lineNumber = Number(m[1])
|
||||
const rest = m[2].trim()
|
||||
if (rest === '' || rest === '-') {
|
||||
lineSuggestions.set(lineNumber, [])
|
||||
} else {
|
||||
const ids = rest.split(',').map(s => Number(s.trim())).filter(n => Number.isFinite(n))
|
||||
lineSuggestions.set(lineNumber, ids)
|
||||
}
|
||||
} else {
|
||||
const m = line.match(/^(\d+)\s*:\s*(.*)$/)
|
||||
if (m) {
|
||||
flushPattern()
|
||||
currentPatternId = Number(m[1])
|
||||
patternBuffer = [m[2].trim()]
|
||||
} else if (currentPatternId !== null && line !== '') {
|
||||
patternBuffer.push(line)
|
||||
}
|
||||
}
|
||||
}
|
||||
flushPattern()
|
||||
|
||||
return { lineSuggestions, patternHints }
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
/**
|
||||
* Parst den Markdown-Export der Feedback-Struktur (gleiches Format wie
|
||||
* `exportFeedbackStructureAsMarkdown`) in ein importierbares Seed-Objekt.
|
||||
*/
|
||||
export interface FeedbackStructureSeedItem {
|
||||
name: string
|
||||
weight: number
|
||||
description?: string
|
||||
}
|
||||
|
||||
export interface FeedbackStructureSeedCategory {
|
||||
name: string
|
||||
description?: string
|
||||
items: FeedbackStructureSeedItem[]
|
||||
}
|
||||
|
||||
export interface FeedbackStructureSeedDimension {
|
||||
name: string
|
||||
categories: FeedbackStructureSeedCategory[]
|
||||
}
|
||||
|
||||
export interface FeedbackStructureSeed {
|
||||
dimensions: FeedbackStructureSeedDimension[]
|
||||
}
|
||||
|
||||
const ITEM_RE = /^- \*\*(.+?)\*\* \(Gewicht ([0-9]+(?:\.[0-9]+)?)\)(?: — (.+))?$/
|
||||
|
||||
export function parseFeedbackStructureMarkdown(md: string): FeedbackStructureSeed {
|
||||
const lines = md.replace(/\r\n/g, '\n').split('\n')
|
||||
const dimensions: FeedbackStructureSeedDimension[] = []
|
||||
let dim: FeedbackStructureSeedDimension | null = null
|
||||
let cat: FeedbackStructureSeedCategory | null = null
|
||||
let pendingCatDesc: string[] = []
|
||||
|
||||
const flushCatDesc = () => {
|
||||
if (!cat || pendingCatDesc.length === 0) return
|
||||
const text = pendingCatDesc.join('\n').trim()
|
||||
if (text) cat.description = text
|
||||
pendingCatDesc = []
|
||||
}
|
||||
|
||||
for (const raw of lines) {
|
||||
const line = raw.trimEnd()
|
||||
if (line.startsWith('# ') || line === '---' || line.startsWith('_Export:')) continue
|
||||
if (!line.trim()) {
|
||||
continue
|
||||
}
|
||||
|
||||
if (line.startsWith('## ')) {
|
||||
flushCatDesc()
|
||||
dim = { name: line.slice(3).trim(), categories: [] }
|
||||
dimensions.push(dim)
|
||||
cat = null
|
||||
continue
|
||||
}
|
||||
|
||||
if (line.startsWith('### ')) {
|
||||
flushCatDesc()
|
||||
if (!dim) throw new Error(`Kategorie ohne Dimension: "${line}"`)
|
||||
cat = { name: line.slice(4).trim(), items: [] }
|
||||
dim.categories.push(cat)
|
||||
pendingCatDesc = []
|
||||
continue
|
||||
}
|
||||
|
||||
const itemMatch = line.trim().match(ITEM_RE)
|
||||
if (itemMatch) {
|
||||
flushCatDesc()
|
||||
if (!cat) throw new Error(`Kriterium ohne Kategorie: "${line}"`)
|
||||
cat.items.push({
|
||||
name: itemMatch[1].trim(),
|
||||
weight: Number(itemMatch[2]),
|
||||
description: itemMatch[3]?.trim() || undefined,
|
||||
})
|
||||
continue
|
||||
}
|
||||
|
||||
if (cat && !line.trim().startsWith('- ')) {
|
||||
pendingCatDesc.push(line.trim())
|
||||
}
|
||||
}
|
||||
flushCatDesc()
|
||||
|
||||
if (dimensions.length === 0) throw new Error('Keine Dimensionen im Markdown gefunden.')
|
||||
return { dimensions }
|
||||
}
|
||||
|
||||
export function summarizeFeedbackStructureSeed(seed: FeedbackStructureSeed): {
|
||||
dimensions: number
|
||||
categories: number
|
||||
items: number
|
||||
} {
|
||||
const categories = seed.dimensions.reduce((s, d) => s + d.categories.length, 0)
|
||||
const items = seed.dimensions.reduce(
|
||||
(s, d) => s + d.categories.reduce((cs, c) => cs + c.items.length, 0),
|
||||
0,
|
||||
)
|
||||
return { dimensions: seed.dimensions.length, categories, items }
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { Assessment, FeedbackCriterionItem, MeetingCategoryRating, RatingScore } from '../db/types'
|
||||
import { normalizeRatingScore } from '../config/constants'
|
||||
import { weightedAverageRating } from './ratingTrend'
|
||||
|
||||
/**
|
||||
* Kategorie-Score für Chips/Historie: zuerst gespeicherter Meeting-Kategorie-Score
|
||||
* (aus Einschätzung synchronisiert), sonst gewichteter Ø der Kriterium-Assessments.
|
||||
*/
|
||||
export function resolveCategoryChipScore(input: {
|
||||
meetingId: number
|
||||
instituteeId: number
|
||||
categoryId: number
|
||||
categoryRatings: MeetingCategoryRating[]
|
||||
assessments: Assessment[]
|
||||
catItems: FeedbackCriterionItem[]
|
||||
}): RatingScore | null {
|
||||
const stored = normalizeRatingScore(
|
||||
input.categoryRatings.find(r =>
|
||||
r.meetingInstanceId === input.meetingId &&
|
||||
r.instituteeId === input.instituteeId &&
|
||||
r.categoryId === input.categoryId,
|
||||
)?.score,
|
||||
)
|
||||
if (stored !== null) return stored
|
||||
|
||||
return weightedAverageRating(
|
||||
input.catItems,
|
||||
itemId => normalizeRatingScore(
|
||||
input.assessments.find(a =>
|
||||
a.meetingInstanceId === input.meetingId &&
|
||||
a.instituteeId === input.instituteeId &&
|
||||
a.criteriaId === itemId,
|
||||
)?.score,
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -1,7 +1,11 @@
|
||||
import { getMeetingExportData, getFeedbackCriterionItemsByIds } from '../db'
|
||||
import { getMeetingExportData, getFeedbackCriterionItemsByIds, listFeedbackCategoriesAll } from '../db'
|
||||
import { normalizeRatingScore } from '../config/constants'
|
||||
|
||||
export async function exportMeetingAsMarkdown(meetingId: number): Promise<string> {
|
||||
const { meeting, template, assignment, consultants, entries, allScores, assessments } = await getMeetingExportData(meetingId)
|
||||
const {
|
||||
meeting, template, assignment, consultants, entries, allScores,
|
||||
assessments, categoryRatings, checklistItems, checklistResponses,
|
||||
} = await getMeetingExportData(meetingId)
|
||||
|
||||
const instituteeIds = assignment?.instituteeIds ?? []
|
||||
const critIds = [
|
||||
@@ -9,9 +13,13 @@ export async function exportMeetingAsMarkdown(meetingId: number): Promise<string
|
||||
...(template?.criteriaIds ?? []),
|
||||
...assessments.map(a => a.criteriaId),
|
||||
...entries.flatMap(e => (e.lineTags ?? []).map(t => t.criterionItemId)),
|
||||
...(meeting.generalNoteTags ?? []).map(t => t.criterionItemId),
|
||||
...checklistItems.map(ci => ci.linkedCriterionItemId).filter((id): id is number => id !== undefined),
|
||||
...checklistResponses.map(r => r.criterionItemId).filter((id): id is number => id !== undefined),
|
||||
]),
|
||||
]
|
||||
const criteria = await getFeedbackCriterionItemsByIds(critIds)
|
||||
const categories = await listFeedbackCategoriesAll()
|
||||
|
||||
const institutees = instituteeIds
|
||||
.map(id => consultants.find(c => c.id === id))
|
||||
@@ -32,7 +40,11 @@ export async function exportMeetingAsMarkdown(meetingId: number): Promise<string
|
||||
|
||||
if (meeting.generalNotes?.trim()) {
|
||||
lines.push('## Allgemeine Notizen')
|
||||
lines.push(meeting.generalNotes.trim())
|
||||
for (const noteLine of meeting.generalNotes.trim().split('\n')) {
|
||||
const lineTag = meeting.generalNoteTags?.find(t => t.text === noteLine.trim())
|
||||
const critName = lineTag ? criteria.find(c => c.id === lineTag.criterionItemId)?.name : null
|
||||
lines.push(`${noteLine}${critName ? ` _(→ ${critName})_` : ''}`)
|
||||
}
|
||||
lines.push('')
|
||||
}
|
||||
|
||||
@@ -73,8 +85,52 @@ export async function exportMeetingAsMarkdown(meetingId: number): Promise<string
|
||||
}
|
||||
}
|
||||
|
||||
if (checklistItems.length > 0) {
|
||||
lines.push('## Checkliste')
|
||||
lines.push('')
|
||||
|
||||
for (const ci of checklistItems) {
|
||||
const responsesForItem = checklistResponses.filter(r => r.checklistItemId === ci.id)
|
||||
const targets = ci.scope === 'meetingWide' ? [undefined] : institutees.map(i => i.id)
|
||||
|
||||
for (const instituteeId of targets) {
|
||||
const response = responsesForItem.find(r => (r.instituteeId ?? undefined) === instituteeId)
|
||||
if (!response) continue
|
||||
const effectiveCritId = response.criterionItemId ?? ci.linkedCriterionItemId
|
||||
const critName = effectiveCritId ? criteria.find(c => c.id === effectiveCritId)?.name : null
|
||||
const inst = instituteeId ? institutees.find(c => c.id === instituteeId) : undefined
|
||||
const who = ci.scope === 'meetingWide' ? '' : ` — ${inst ? `${inst.firstName} ${inst.lastName}` : 'Unbekannt'}`
|
||||
const scoreStr = response.rating ?? '—'
|
||||
const noteStr = response.note?.trim() ? ` — ${response.note.trim()}` : ''
|
||||
lines.push(`- **${ci.label}**${who}: ${scoreStr}${critName ? ` _(→ ${critName})_` : ''}${noteStr}`)
|
||||
}
|
||||
}
|
||||
lines.push('')
|
||||
}
|
||||
|
||||
if (categoryRatings.some(r => normalizeRatingScore(r.score) !== null)) {
|
||||
lines.push('## Einschätzung (Kategorien)')
|
||||
lines.push('')
|
||||
|
||||
for (const inst of institutees) {
|
||||
const instRatings = categoryRatings.filter(
|
||||
r => r.instituteeId === inst.id && normalizeRatingScore(r.score) !== null,
|
||||
)
|
||||
if (instRatings.length === 0) continue
|
||||
|
||||
lines.push(`### ${inst.firstName} ${inst.lastName}`)
|
||||
for (const r of instRatings) {
|
||||
const cat = categories.find(c => c.id === r.categoryId)
|
||||
if (!cat) continue
|
||||
const noteStr = r.note?.trim() ? ` — ${r.note.trim()}` : ''
|
||||
lines.push(`- **${cat.name}:** ${normalizeRatingScore(r.score)}/10${noteStr}`)
|
||||
}
|
||||
lines.push('')
|
||||
}
|
||||
}
|
||||
|
||||
if (assessments.length > 0) {
|
||||
lines.push('## Gesamtbewertung')
|
||||
lines.push('## Kriterien-Beobachtungen')
|
||||
lines.push('')
|
||||
|
||||
for (const inst of institutees) {
|
||||
@@ -86,7 +142,7 @@ export async function exportMeetingAsMarkdown(meetingId: number): Promise<string
|
||||
for (const a of instAssessments) {
|
||||
const crit = criteria.find(c => c.id === a.criteriaId)
|
||||
if (!crit) continue
|
||||
const scoreStr = a.score !== null ? `${a.score}/5` : '—'
|
||||
const scoreStr = a.score !== null ? `${a.score}/10` : '—'
|
||||
const noteStr = a.note?.trim() ? ` — ${a.note.trim()}` : ''
|
||||
lines.push(`- **${crit.name}:** ${scoreStr}${noteStr}`)
|
||||
}
|
||||
@@ -107,7 +163,10 @@ export async function exportMeetingAsMarkdown(meetingId: number): Promise<string
|
||||
}
|
||||
|
||||
export async function exportMeetingAsJson(meetingId: number): Promise<string> {
|
||||
const { meeting, template, assignment, consultants, entries, allScores, assessments } = await getMeetingExportData(meetingId)
|
||||
const {
|
||||
meeting, template, assignment, consultants, entries, allScores,
|
||||
assessments, categoryRatings, checklistItems, checklistResponses,
|
||||
} = await getMeetingExportData(meetingId)
|
||||
|
||||
const entryIds = entries.map(e => e.id!)
|
||||
const entryScores = allScores.filter(s => entryIds.includes(s.conversationEntryId))
|
||||
@@ -123,6 +182,9 @@ export async function exportMeetingAsJson(meetingId: number): Promise<string> {
|
||||
scores: entryScores.filter(s => s.conversationEntryId === e.id),
|
||||
})),
|
||||
assessments,
|
||||
categoryRatings,
|
||||
checklistItems,
|
||||
checklistResponses,
|
||||
}
|
||||
|
||||
return JSON.stringify(payload, null, 2)
|
||||
|
||||
@@ -1,54 +1,52 @@
|
||||
import React from 'react'
|
||||
import type { FeedbackRating } from '../db'
|
||||
import type { RatingColorBand, RatingScore } from '../db/types'
|
||||
import {
|
||||
DEFAULT_RATING_COLOR_BANDS,
|
||||
isValidRatingScore,
|
||||
resolveScoreStyle,
|
||||
} from '../config/constants'
|
||||
|
||||
// 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 {
|
||||
export function detectNotationRating(line: string): RatingScore | null {
|
||||
return parseNotationPrefix(line).rating
|
||||
}
|
||||
|
||||
export interface NotationPrefixMatch {
|
||||
rating: FeedbackRating | null
|
||||
rating: RatingScore | null
|
||||
/** `>`-Präfix — Zitat/Kundeninput, keine Bewertung. */
|
||||
isQuote: boolean
|
||||
/** Zeile ohne das erkannte Präfix. */
|
||||
text: string
|
||||
}
|
||||
|
||||
/** Wie `detectNotationRating`, liefert zusätzlich die Zitat-Kennzeichnung und den Text ohne Präfix. */
|
||||
/**
|
||||
* Führende Score-Zahl 1–10 (zuerst `10`, dann `1`–`9`), optional gefolgt von Leerzeichen/Satzzeichen.
|
||||
* `>` bleibt Zitat; `[…]` wird in NotationText separat behandelt.
|
||||
*/
|
||||
export function parseNotationPrefix(line: string): NotationPrefixMatch {
|
||||
const trimmed = line.trim()
|
||||
if (trimmed.startsWith('>')) return { rating: null, isQuote: true, text: trimmed.slice(1).trim() }
|
||||
for (const [prefix, rating] of NOTATION_RATING_ORDER) {
|
||||
if (trimmed.startsWith(prefix)) return { rating, isQuote: false, text: trimmed.slice(prefix.length).trim() }
|
||||
|
||||
const m = trimmed.match(/^(10|[1-9])(?:\s+|[.:)\-]|$)/)
|
||||
if (m) {
|
||||
const score = Number(m[1])
|
||||
if (isValidRatingScore(score)) {
|
||||
const rest = trimmed.slice(m[1].length).replace(/^[\s.:)\-]+/, '').trim()
|
||||
return { rating: score, isQuote: false, text: rest }
|
||||
}
|
||||
}
|
||||
return { rating: null, isQuote: false, text: trimmed }
|
||||
}
|
||||
|
||||
// Notations-Regeln (Reihenfolge wichtig: längere Symbole zuerst)
|
||||
const NOTATION_RULES = [
|
||||
{ prefix: '(+)', className: 'text-green-600', icon: '✓~', bg: 'bg-green-50', indent: false },
|
||||
{ prefix: '(!)', className: 'text-red-500', icon: '✗~', bg: 'bg-red-50', indent: false },
|
||||
{ prefix: '+', className: 'text-green-700 font-semibold', icon: '✓', bg: 'bg-green-50', indent: false },
|
||||
{ prefix: '!', className: 'text-red-600 font-semibold', icon: '✗', bg: 'bg-red-50', indent: false },
|
||||
{ prefix: '>', className: 'text-blue-600 italic', icon: '›', bg: 'bg-blue-50', indent: true },
|
||||
] as const
|
||||
|
||||
// Erkennt [Slide 3] oder […] am Anfang einer Zeile
|
||||
const SLIDE_RE = /^\[([^\]]*)\]/
|
||||
|
||||
function parseLine(line: string, key: number): React.ReactElement {
|
||||
function parseLine(
|
||||
line: string,
|
||||
key: number,
|
||||
bands: RatingColorBand[],
|
||||
): React.ReactElement {
|
||||
const trimmed = line.trim()
|
||||
if (!trimmed) return <div key={key} className="h-1" />
|
||||
|
||||
// Slide-Referenz [Titel…]
|
||||
const slideMatch = trimmed.match(SLIDE_RE)
|
||||
if (slideMatch) {
|
||||
const rest = trimmed.slice(slideMatch[0].length).trim()
|
||||
@@ -62,23 +60,29 @@ function parseLine(line: string, key: number): React.ReactElement {
|
||||
)
|
||||
}
|
||||
|
||||
// Notations-Präfixe
|
||||
for (const rule of NOTATION_RULES) {
|
||||
if (trimmed.startsWith(rule.prefix)) {
|
||||
const rest = trimmed.slice(rule.prefix.length).trim()
|
||||
return (
|
||||
<div key={key}
|
||||
className={`flex items-start gap-2 py-0.5 px-2 rounded ${rule.bg} ${rule.indent ? 'ml-2' : ''}`}>
|
||||
<span className={`flex-shrink-0 text-xs font-bold mt-0.5 ${rule.className}`}>
|
||||
{rule.icon}
|
||||
</span>
|
||||
<span className={`text-sm ${rule.className}`}>{rest}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
if (trimmed.startsWith('>')) {
|
||||
const rest = trimmed.slice(1).trim()
|
||||
return (
|
||||
<div key={key} className="flex items-start gap-2 py-0.5 px-2 rounded bg-blue-50 ml-2">
|
||||
<span className="flex-shrink-0 text-xs font-bold mt-0.5 text-blue-600 italic">›</span>
|
||||
<span className="text-sm text-blue-600 italic">{rest}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const { rating, text } = parseNotationPrefix(trimmed)
|
||||
if (rating !== null) {
|
||||
const style = resolveScoreStyle(rating, bands)
|
||||
return (
|
||||
<div key={key} className={`flex items-start gap-2 py-0.5 px-2 rounded ${style.color}`}>
|
||||
<span className={`flex-shrink-0 text-xs font-bold mt-0.5 tabular-nums ${style.active.includes('text-white') ? '' : ''}`.trim()}>
|
||||
<span className={`inline-block px-1.5 py-0.5 rounded border ${style.active}`}>{rating}</span>
|
||||
</span>
|
||||
<span className="text-sm text-gray-800">{text}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Normaler Text
|
||||
return (
|
||||
<div key={key} className="py-0.5 text-sm text-gray-800">
|
||||
{trimmed}
|
||||
@@ -90,26 +94,28 @@ interface Props {
|
||||
text: string
|
||||
className?: string
|
||||
renderLineAddon?: (line: string, index: number) => React.ReactNode
|
||||
/** Optional — Default aus constants, Config-Bänder können später durchgereicht werden. */
|
||||
colorBands?: RatingColorBand[]
|
||||
}
|
||||
|
||||
export function NotationText({ text, className, renderLineAddon }: Props) {
|
||||
export function NotationText({ text, className, renderLineAddon, colorBands }: Props) {
|
||||
if (!text?.trim()) return null
|
||||
const bands = colorBands ?? DEFAULT_RATING_COLOR_BANDS
|
||||
const lines = text.split('\n')
|
||||
return (
|
||||
<div className={className}>
|
||||
{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 key={i} className="flex items-start gap-1">
|
||||
<div className="flex-1 min-w-0">{parseLine(line, i, bands)}</div>
|
||||
{renderLineAddon(line, i)}
|
||||
</div>
|
||||
)
|
||||
: parseLine(line, i)
|
||||
)}
|
||||
: parseLine(line, i, bands))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function splitNoteLines(note: string): string[] {
|
||||
return note.split('\n').map(l => l.trim()).filter(l => l !== '')
|
||||
return note.split('\n').map(l => l.trim()).filter(Boolean)
|
||||
}
|
||||
@@ -0,0 +1,613 @@
|
||||
import { Document, Page, Text, View, StyleSheet, pdf } from '@react-pdf/renderer'
|
||||
import {
|
||||
type Assignment, type AssignmentType, type PhaseTemplate, type MeetingInstance, type Consultant,
|
||||
type FeedbackDimension, type FeedbackCategory, type FeedbackCriterionItem,
|
||||
type ConversationEntry, type Assessment, type AssignmentFeedback,
|
||||
type FeedbackCategoryRating, type FeedbackDimensionText, type FeedbackCategoryText,
|
||||
type ChecklistItemDef, type ChecklistResponse, type MeetingCategoryRating, type RatingColorBand,
|
||||
getAssignment, getAssignmentType, listPhaseTemplatesForType,
|
||||
listDoneMeetingsChronological, getConsultantsByIds, getConsultant,
|
||||
loadFeedbackStructure, resolveVisibleStructure,
|
||||
listConversationEntriesForMeetings, listAssessmentsForMeetings, listMeetingCategoryRatingsForMeetings,
|
||||
listChecklistItemDefsForPhaseTemplates, listChecklistResponsesForMeetings,
|
||||
getAssignmentFeedback, listFeedbackCategoryRatings, listFeedbackDimensionTexts, listFeedbackCategoryTexts,
|
||||
listAssignmentTypes, listPhaseTemplates, getOrSeedRatingColorBands,
|
||||
} from '../db'
|
||||
import { DEFAULT_RATING_COLOR_BANDS, normalizeRatingColorBands, resolveScoreStyle } from '../config/constants'
|
||||
import { splitNoteLines, parseNotationPrefix } from './notationParser'
|
||||
import { resolveCategoryChipScore } from '../utils/meetingCategoryScore'
|
||||
|
||||
// ─── Styles ────────────────────────────────────────────────────────────────
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
page: { padding: 32, fontSize: 9, fontFamily: 'Helvetica', color: '#1f2937' },
|
||||
h1: { fontSize: 16, fontWeight: 700, marginBottom: 2 },
|
||||
assignmentNumber: {
|
||||
fontSize: 12, fontWeight: 700, color: '#0070AD', marginBottom: 4, letterSpacing: 0.5,
|
||||
},
|
||||
h2: { fontSize: 13, fontWeight: 700, marginTop: 16, marginBottom: 6, borderBottomWidth: 1, borderBottomColor: '#d1d5db', paddingBottom: 3 },
|
||||
h3: { fontSize: 11, fontWeight: 700, marginTop: 10, marginBottom: 3 },
|
||||
h4: { fontSize: 9.5, fontWeight: 700, marginTop: 6, marginBottom: 2 },
|
||||
meta: { fontSize: 9, color: '#6b7280', marginBottom: 1.5 },
|
||||
meetingCard: { marginBottom: 10, padding: 8, backgroundColor: '#f9fafb', borderRadius: 4 },
|
||||
meetingHeader: { fontSize: 10, fontWeight: 700, marginBottom: 1 },
|
||||
meetingDate: { fontSize: 8, color: '#9ca3af', marginBottom: 4 },
|
||||
speakerLabel: {
|
||||
fontSize: 7.5, fontWeight: 700, color: '#ffffff', backgroundColor: '#4b5563',
|
||||
paddingHorizontal: 4, paddingVertical: 1.5, borderRadius: 2, marginTop: 4, marginBottom: 1.5, alignSelf: 'flex-start',
|
||||
},
|
||||
line: { fontSize: 9, marginBottom: 1.5, lineHeight: 1.3 },
|
||||
chipRow: { flexDirection: 'row', flexWrap: 'wrap', marginTop: 3 },
|
||||
chip: {
|
||||
fontSize: 7, color: '#ffffff', backgroundColor: '#0070AD',
|
||||
paddingHorizontal: 4, paddingVertical: 1.5, borderRadius: 3, marginRight: 3, marginBottom: 3,
|
||||
},
|
||||
bullet: { fontSize: 9, marginBottom: 2, lineHeight: 1.3 },
|
||||
statusBadge: {
|
||||
fontSize: 8, fontWeight: 700, color: '#ffffff', paddingHorizontal: 5, paddingVertical: 2,
|
||||
borderRadius: 3, alignSelf: 'flex-start', marginBottom: 6,
|
||||
},
|
||||
categoryBlock: {
|
||||
marginBottom: 8, paddingBottom: 6, paddingTop: 4, paddingHorizontal: 6,
|
||||
backgroundColor: '#f3f4f6', borderRadius: 3,
|
||||
borderLeftWidth: 3, borderLeftColor: '#0070AD',
|
||||
},
|
||||
categoryName: { fontSize: 9, fontWeight: 700, color: '#0070AD', flexGrow: 1 },
|
||||
categoryRow: { flexDirection: 'row', alignItems: 'center', marginBottom: 3, gap: 4 },
|
||||
ratingBadge: { fontSize: 7.5, fontWeight: 700, color: '#ffffff', paddingHorizontal: 4, paddingVertical: 1.5, borderRadius: 3 },
|
||||
footer: { position: 'absolute', bottom: 16, left: 32, right: 32, fontSize: 7, color: '#9ca3af', textAlign: 'center' },
|
||||
})
|
||||
|
||||
// ─── Notation-Auflösung fürs PDF (führende Score-Zahl + Farbband) ─────────────
|
||||
|
||||
function classifyLine(
|
||||
line: string,
|
||||
colorBands: RatingColorBand[] = DEFAULT_RATING_COLOR_BANDS,
|
||||
): { icon: string; color: string; bold: boolean; italic: boolean; text: string } {
|
||||
const { rating, isQuote, text } = parseNotationPrefix(line)
|
||||
if (isQuote) return { icon: '›', color: '#2563eb', bold: false, italic: true, text }
|
||||
if (rating !== null) {
|
||||
const style = resolveScoreStyle(rating, colorBands)
|
||||
return { icon: String(rating), color: style.hex, bold: true, italic: false, text }
|
||||
}
|
||||
return { icon: '', color: '#1f2937', bold: false, italic: false, text }
|
||||
}
|
||||
|
||||
function ProtocolLine({ line, criterionName, colorBands }: {
|
||||
line: string; criterionName?: string; colorBands?: RatingColorBand[]
|
||||
}) {
|
||||
const cls = classifyLine(line, colorBands)
|
||||
return (
|
||||
<Text style={[styles.line, { color: cls.color, fontWeight: cls.bold ? 700 : 400, fontStyle: cls.italic ? 'italic' : 'normal' }]}>
|
||||
{cls.icon ? `${cls.icon} ` : ''}{cls.text}
|
||||
{criterionName && <Text style={{ color: '#4f46e5', fontSize: 7.5 }}> → {criterionName}</Text>}
|
||||
</Text>
|
||||
)
|
||||
}
|
||||
|
||||
const formatDate = (iso: string) =>
|
||||
new Date(iso).toLocaleDateString('de-DE', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })
|
||||
|
||||
const sanitizeFilename = (s: string) => s.replace(/[^a-z0-9äöüß]+/gi, '-').replace(/^-+|-+$/g, '')
|
||||
|
||||
/** Primäres Zuordnungskriterium — am Dateinamen-Anfang; Fallback wenn Nummer fehlt. */
|
||||
function assignmentFilenamePrefix(assignment: Assignment): string {
|
||||
const num = assignment.assignmentNumber?.trim()
|
||||
return sanitizeFilename(num || 'ohne-Nr') || 'ohne-Nr'
|
||||
}
|
||||
|
||||
function AssignmentNumberHeader({ assignment }: { assignment: Assignment }) {
|
||||
const num = assignment.assignmentNumber?.trim()
|
||||
return (
|
||||
<Text style={styles.assignmentNumber}>
|
||||
Assignment-Nr.: {num || '—'}
|
||||
</Text>
|
||||
)
|
||||
}
|
||||
|
||||
// ─── Feedback-Abschnitt (gemeinsam für Einzel- und Sammel-PDF) ──────────────
|
||||
|
||||
interface FeedbackSectionData {
|
||||
institutee: Consultant
|
||||
feedback: AssignmentFeedback | undefined
|
||||
dimensions: FeedbackDimension[]
|
||||
categories: FeedbackCategory[]
|
||||
ratings: FeedbackCategoryRating[]
|
||||
dimTexts: FeedbackDimensionText[]
|
||||
categoryTexts: FeedbackCategoryText[]
|
||||
colorBands?: RatingColorBand[]
|
||||
}
|
||||
|
||||
function FeedbackSection({
|
||||
institutee, feedback, dimensions, categories, ratings, dimTexts, categoryTexts,
|
||||
colorBands = DEFAULT_RATING_COLOR_BANDS,
|
||||
}: FeedbackSectionData) {
|
||||
const isFinal = feedback?.status === 'final'
|
||||
return (
|
||||
<View>
|
||||
<View wrap={false} minPresenceAhead={50}>
|
||||
<Text style={styles.h3}>{institutee.firstName} {institutee.lastName}</Text>
|
||||
<Text style={[styles.statusBadge, { backgroundColor: isFinal ? '#15803d' : '#9ca3af' }]}>
|
||||
{isFinal ? '✓ Final' : 'Entwurf'}
|
||||
</Text>
|
||||
</View>
|
||||
{!feedback && <Text style={styles.meta}>Noch kein Feedback erfasst.</Text>}
|
||||
{dimensions.map(dim => {
|
||||
const dimCats = categories.filter(c => c.dimensionId === dim.id)
|
||||
const text = dimTexts.find(t => t.feedbackDimensionId === dim.id)
|
||||
const hasContent = dimCats.some(c => {
|
||||
const ct = categoryTexts.find(t => t.feedbackCategoryId === c.id)
|
||||
return ratings.find(r => r.feedbackCategoryId === c.id)
|
||||
|| ct?.benefits || ct?.concerns
|
||||
})
|
||||
|| text?.achievements || text?.developmentNeeds
|
||||
if (!hasContent) return null
|
||||
return (
|
||||
<View key={dim.id} style={{ marginBottom: 8 }}>
|
||||
<View wrap={false} minPresenceAhead={40}>
|
||||
<Text style={styles.h4}>{dim.name}</Text>
|
||||
</View>
|
||||
{dimCats.map(cat => {
|
||||
const rating = ratings.find(r => r.feedbackCategoryId === cat.id)?.rating
|
||||
const ct = categoryTexts.find(t => t.feedbackCategoryId === cat.id)
|
||||
if (!rating && !ct?.benefits && !ct?.concerns) return null
|
||||
return (
|
||||
<View key={cat.id} style={styles.categoryBlock} wrap={false}>
|
||||
<View style={styles.categoryRow}>
|
||||
<Text style={styles.categoryName}>{cat.name}</Text>
|
||||
{rating != null && (
|
||||
<Text style={[styles.ratingBadge, { backgroundColor: resolveScoreStyle(rating, colorBands).hex }]}>
|
||||
{rating}/10
|
||||
</Text>
|
||||
)}
|
||||
</View>
|
||||
{ct?.benefits ? (
|
||||
<View style={{ marginTop: 2 }}>
|
||||
<Text style={{ fontSize: 7.5, fontWeight: 700, color: '#15803d' }}>Benefits</Text>
|
||||
{splitNoteLines(ct.benefits).map((l, i) => <Text key={`b-${i}`} style={styles.bullet}>{l}</Text>)}
|
||||
</View>
|
||||
) : null}
|
||||
{ct?.concerns ? (
|
||||
<View style={{ marginTop: 2 }}>
|
||||
<Text style={{ fontSize: 7.5, fontWeight: 700, color: '#b45309' }}>Concerns</Text>
|
||||
{splitNoteLines(ct.concerns).map((l, i) => <Text key={`c-${i}`} style={styles.bullet}>{l}</Text>)}
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
)
|
||||
})}
|
||||
{(text?.achievements || text?.developmentNeeds) ? (
|
||||
<View style={{ marginTop: 6, paddingTop: 4, borderTopWidth: 1, borderTopColor: '#d1d5db' }}>
|
||||
{text?.achievements ? (
|
||||
<View style={{ marginBottom: 4 }}>
|
||||
<View wrap={false} minPresenceAhead={30}>
|
||||
<Text style={{ fontSize: 8.5, fontWeight: 700, color: '#15803d' }}>Top Benefits (Dimension)</Text>
|
||||
</View>
|
||||
{splitNoteLines(text.achievements).map((l, i) => <Text key={i} style={styles.bullet}>{l}</Text>)}
|
||||
</View>
|
||||
) : null}
|
||||
{text?.developmentNeeds ? (
|
||||
<View>
|
||||
<View wrap={false} minPresenceAhead={30}>
|
||||
<Text style={{ fontSize: 8.5, fontWeight: 700, color: '#b45309' }}>Top Concerns (Dimension)</Text>
|
||||
</View>
|
||||
{splitNoteLines(text.developmentNeeds).map((l, i) => <Text key={i} style={styles.bullet}>{l}</Text>)}
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
)
|
||||
})}
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
// ─── Kombiniertes Assignment-Report-Dokument ────────────────────────────────
|
||||
|
||||
interface AssignmentReportData {
|
||||
assignment: Assignment
|
||||
templates: PhaseTemplate[]
|
||||
meetings: MeetingInstance[]
|
||||
institutees: Consultant[]
|
||||
visibleCategories: FeedbackCategory[]
|
||||
visibleItems: FeedbackCriterionItem[]
|
||||
entries: ConversationEntry[]
|
||||
assessments: Assessment[]
|
||||
categoryRatings: MeetingCategoryRating[]
|
||||
colorBands: RatingColorBand[]
|
||||
checklistItems: ChecklistItemDef[]
|
||||
checklistResponses: ChecklistResponse[]
|
||||
dimensions: FeedbackDimension[]
|
||||
allCategories: FeedbackCategory[]
|
||||
feedbackByInstitutee: FeedbackSectionData[]
|
||||
}
|
||||
|
||||
function AssignmentReportDocument({ data }: { data: AssignmentReportData }) {
|
||||
const {
|
||||
assignment, templates, meetings, institutees, visibleCategories, visibleItems, entries, assessments,
|
||||
categoryRatings, colorBands, checklistItems, checklistResponses, dimensions, allCategories, feedbackByInstitutee,
|
||||
} = data
|
||||
return (
|
||||
<Document>
|
||||
<Page size="A4" style={styles.page} wrap>
|
||||
<AssignmentNumberHeader assignment={assignment} />
|
||||
<Text style={styles.h1}>{assignment.title}</Text>
|
||||
<Text style={styles.meta}>Kunde: {assignment.client}</Text>
|
||||
<Text style={styles.meta}>Institutees: {institutees.map(c => `${c.firstName} ${c.lastName}`).join(', ')}</Text>
|
||||
|
||||
<Text style={styles.h2}>Gesamtprotokoll</Text>
|
||||
{meetings.length === 0 && <Text style={styles.meta}>Keine abgeschlossenen Meetings.</Text>}
|
||||
{meetings.map(meeting => {
|
||||
const template = templates.find(t => t.id === meeting.phaseTemplateId)
|
||||
const meetingEntries = entries
|
||||
.filter(e => e.meetingInstanceId === meeting.id)
|
||||
.sort((a, b) => a.sequenceIndex - b.sequenceIndex)
|
||||
const meetingAssessments = assessments.filter(a => a.meetingInstanceId === meeting.id)
|
||||
const meetingChecklistItems = checklistItems.filter(ci => ci.phaseTemplateId === template?.id).sort((a, b) => a.order - b.order)
|
||||
|
||||
return (
|
||||
<View key={meeting.id} style={styles.meetingCard}>
|
||||
<View wrap={false} minPresenceAhead={60}>
|
||||
<Text style={styles.meetingHeader}>
|
||||
{template?.label ?? 'Meeting'}{template?.isRepeatable ? ` #${meeting.phaseIndex}` : ''}
|
||||
</Text>
|
||||
<Text style={styles.meetingDate}>{formatDate(meeting.date)}</Text>
|
||||
</View>
|
||||
|
||||
{meeting.generalNotes?.trim() && splitNoteLines(meeting.generalNotes).map((l, i) => {
|
||||
const critId = meeting.generalNoteTags?.find(t => t.text === l)?.criterionItemId
|
||||
const critName = critId ? visibleItems.find(item => item.id === critId)?.name : undefined
|
||||
return <ProtocolLine key={`g${i}`} line={l} criterionName={critName} colorBands={colorBands} />
|
||||
})}
|
||||
|
||||
{meetingEntries.map(entry => {
|
||||
const inst = institutees.find(c => c.id === entry.instituteeId)
|
||||
return (
|
||||
<View key={entry.id} wrap={false}>
|
||||
<Text style={styles.speakerLabel}>{inst ? `${inst.firstName} ${inst.lastName}` : 'Unbekannt'}</Text>
|
||||
{entry.note && splitNoteLines(entry.note).map((l, i) => {
|
||||
const critId = entry.lineTags?.find(t => t.text === l)?.criterionItemId
|
||||
const critName = critId ? visibleItems.find(item => item.id === critId)?.name : undefined
|
||||
return <ProtocolLine key={i} line={l} criterionName={critName} colorBands={colorBands} />
|
||||
})}
|
||||
{(entry.fillerCount ?? 0) > 0 && (
|
||||
<Text style={[styles.line, { color: '#dc2626' }]}>Füllwörter: {entry.fillerCount}</Text>
|
||||
)}
|
||||
</View>
|
||||
)
|
||||
})}
|
||||
|
||||
{meetingChecklistItems.length > 0 && (
|
||||
<View style={{ marginTop: 4 }}>
|
||||
<Text style={{ fontSize: 8, fontWeight: 700, color: '#4b5563', marginBottom: 1.5 }}>Checkliste</Text>
|
||||
{meetingChecklistItems.map(ci => {
|
||||
const responsesForItem = checklistResponses.filter(r => r.checklistItemId === ci.id)
|
||||
const targets = ci.scope === 'meetingWide' ? [undefined] : institutees.map(i => i.id)
|
||||
return targets.map(instituteeId => {
|
||||
const response = responsesForItem.find(r => (r.instituteeId ?? undefined) === instituteeId)
|
||||
if (!response) return null
|
||||
const effectiveCritId = response.criterionItemId ?? ci.linkedCriterionItemId
|
||||
const critName = effectiveCritId ? visibleItems.find(i => i.id === effectiveCritId)?.name : undefined
|
||||
const inst = instituteeId ? institutees.find(c => c.id === instituteeId) : undefined
|
||||
const who = ci.scope === 'meetingWide' ? '' : ` — ${inst ? `${inst.firstName} ${inst.lastName}` : 'Unbekannt'}`
|
||||
const ratingLabel = response.rating != null ? `${response.rating}/10` : '—'
|
||||
return (
|
||||
<Text key={`${ci.id}-${instituteeId ?? 'm'}`} style={styles.bullet}>
|
||||
<Text style={{ fontWeight: 700 }}>{ci.label}</Text>{who}: {ratingLabel}
|
||||
{critName && <Text style={{ color: '#4f46e5' }}> ({critName})</Text>}
|
||||
{response.note?.trim() ? ` — ${response.note.trim()}` : ''}
|
||||
</Text>
|
||||
)
|
||||
})
|
||||
})}
|
||||
</View>
|
||||
)}
|
||||
|
||||
{institutees.length > 0 && visibleCategories.length > 0 && (
|
||||
<View style={styles.chipRow}>
|
||||
{institutees.map(inst => visibleCategories.map(cat => {
|
||||
const catItems = visibleItems.filter(i => i.categoryId === cat.id)
|
||||
const mode = resolveCategoryChipScore({
|
||||
meetingId: meeting.id!,
|
||||
instituteeId: inst.id!,
|
||||
categoryId: cat.id!,
|
||||
categoryRatings,
|
||||
assessments: meetingAssessments,
|
||||
catItems,
|
||||
})
|
||||
if (!mode) return null
|
||||
return (
|
||||
<Text key={`${inst.id}-${cat.id}`} style={[styles.chip, { backgroundColor: resolveScoreStyle(mode, colorBands).hex }]}>
|
||||
{inst.firstName} · {cat.name} {mode}
|
||||
</Text>
|
||||
)
|
||||
}))}
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
)
|
||||
})}
|
||||
|
||||
<Text style={styles.h2} break>Feedback</Text>
|
||||
{feedbackByInstitutee.map((fb, i) => (
|
||||
<View key={fb.institutee.id} break={i > 0}>
|
||||
<FeedbackSection {...fb} dimensions={dimensions} categories={allCategories} colorBands={colorBands} />
|
||||
</View>
|
||||
))}
|
||||
|
||||
<Text style={styles.footer} render={({ pageNumber, totalPages }) => `Seite ${pageNumber} / ${totalPages} — Export: ${new Date().toLocaleString('de-DE')}`} fixed />
|
||||
</Page>
|
||||
</Document>
|
||||
)
|
||||
}
|
||||
|
||||
// ─── Einzel-Feedback-Dokument ────────────────────────────────────────────────
|
||||
|
||||
function InstituteeFeedbackDocument({ assignment, data }: { assignment: Assignment; data: FeedbackSectionData }) {
|
||||
return (
|
||||
<Document>
|
||||
<Page size="A4" style={styles.page} wrap>
|
||||
<AssignmentNumberHeader assignment={assignment} />
|
||||
<Text style={styles.h1}>Feedback: {data.institutee.firstName} {data.institutee.lastName}</Text>
|
||||
<Text style={styles.meta}>{assignment.title} · {assignment.client}</Text>
|
||||
<View style={{ marginTop: 10 }}>
|
||||
<FeedbackSection {...data} />
|
||||
</View>
|
||||
<Text style={styles.footer} render={({ pageNumber, totalPages }) => `Seite ${pageNumber} / ${totalPages} — Export: ${new Date().toLocaleString('de-DE')}`} fixed />
|
||||
</Page>
|
||||
</Document>
|
||||
)
|
||||
}
|
||||
|
||||
// ─── Download-Helfer ─────────────────────────────────────────────────────────
|
||||
|
||||
function downloadPdfBlob(blob: Blob, filename: string) {
|
||||
const url = URL.createObjectURL(blob)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = filename
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
document.body.removeChild(a)
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
|
||||
// ─── Daten sammeln + Export auslösen ─────────────────────────────────────────
|
||||
|
||||
async function loadFeedbackSectionData(assignmentId: number, institutee: Consultant): Promise<FeedbackSectionData> {
|
||||
const feedback = await getAssignmentFeedback(assignmentId, institutee.id!)
|
||||
if (!feedback?.id) {
|
||||
return { institutee, feedback: undefined, dimensions: [], categories: [], ratings: [], dimTexts: [], categoryTexts: [] }
|
||||
}
|
||||
const [ratings, dimTexts, categoryTexts] = await Promise.all([
|
||||
listFeedbackCategoryRatings(feedback.id),
|
||||
listFeedbackDimensionTexts(feedback.id),
|
||||
listFeedbackCategoryTexts(feedback.id),
|
||||
])
|
||||
return { institutee, feedback, dimensions: [], categories: [], ratings, dimTexts, categoryTexts }
|
||||
}
|
||||
|
||||
/** Reine Erzeugung ohne Download-Nebeneffekt — auch außerhalb des Browsers (z.B. Node/tsx) testbar. */
|
||||
export async function buildAssignmentReportPdfBlob(assignmentId: number): Promise<{ blob: Blob; filename: string }> {
|
||||
const assignment = await getAssignment(assignmentId)
|
||||
if (!assignment) throw new Error('Assignment nicht gefunden')
|
||||
|
||||
const [aType, templates, meetings, institutees, structure] = await Promise.all([
|
||||
getAssignmentType(assignment.assignmentTypeId),
|
||||
listPhaseTemplatesForType(assignment.assignmentTypeId),
|
||||
listDoneMeetingsChronological(assignmentId),
|
||||
getConsultantsByIds(assignment.instituteeIds),
|
||||
loadFeedbackStructure(),
|
||||
])
|
||||
const {
|
||||
dimensions: visibleDimensions,
|
||||
categories: visibleCategories,
|
||||
items: visibleItems,
|
||||
} = resolveVisibleStructure(structure.dimensions, structure.categories, structure.items, aType?.criteriaIds)
|
||||
|
||||
const meetingIds = meetings.map(m => m.id!)
|
||||
const templateIds = templates.map(t => t.id!)
|
||||
const [entries, assessments, categoryRatings, checklistItems, checklistResponses, rawBands] = await Promise.all([
|
||||
listConversationEntriesForMeetings(meetingIds),
|
||||
listAssessmentsForMeetings(meetingIds),
|
||||
listMeetingCategoryRatingsForMeetings(meetingIds),
|
||||
listChecklistItemDefsForPhaseTemplates(templateIds),
|
||||
listChecklistResponsesForMeetings(meetingIds),
|
||||
getOrSeedRatingColorBands(),
|
||||
])
|
||||
const colorBands = normalizeRatingColorBands(rawBands)
|
||||
|
||||
const orderedInstitutees = assignment.instituteeIds
|
||||
.map(id => institutees.find(c => c.id === id))
|
||||
.filter((c): c is Consultant => !!c)
|
||||
|
||||
const feedbackByInstitutee = await Promise.all(
|
||||
orderedInstitutees.map(inst => loadFeedbackSectionData(assignmentId, inst)),
|
||||
)
|
||||
|
||||
const data: AssignmentReportData = {
|
||||
assignment, templates, meetings, institutees: orderedInstitutees,
|
||||
visibleCategories, visibleItems, entries, assessments, categoryRatings, colorBands,
|
||||
checklistItems, checklistResponses,
|
||||
dimensions: visibleDimensions, allCategories: visibleCategories,
|
||||
feedbackByInstitutee,
|
||||
}
|
||||
|
||||
const blob = await pdf(<AssignmentReportDocument data={data} />).toBlob()
|
||||
const filename = `${assignmentFilenamePrefix(assignment)}_Assignment-Report-${sanitizeFilename(assignment.title)}-${new Date().toISOString().slice(0, 10)}.pdf`
|
||||
return { blob, filename }
|
||||
}
|
||||
|
||||
export async function exportAssignmentReportPdf(assignmentId: number): Promise<void> {
|
||||
const { blob, filename } = await buildAssignmentReportPdfBlob(assignmentId)
|
||||
downloadPdfBlob(blob, filename)
|
||||
}
|
||||
|
||||
/** Reine Erzeugung ohne Download-Nebeneffekt — auch außerhalb des Browsers (z.B. Node/tsx) testbar. */
|
||||
export async function buildInstituteeFeedbackPdfBlob(assignmentId: number, instituteeId: number): Promise<{ blob: Blob; filename: string }> {
|
||||
const [assignment, institutee, structure, rawBands] = await Promise.all([
|
||||
getAssignment(assignmentId),
|
||||
getConsultant(instituteeId),
|
||||
loadFeedbackStructure(),
|
||||
getOrSeedRatingColorBands(),
|
||||
])
|
||||
if (!assignment || !institutee) throw new Error('Assignment oder Institutee nicht gefunden')
|
||||
|
||||
const aType = await getAssignmentType(assignment.assignmentTypeId)
|
||||
const visible = resolveVisibleStructure(
|
||||
structure.dimensions,
|
||||
structure.categories,
|
||||
structure.items,
|
||||
aType?.criteriaIds,
|
||||
)
|
||||
|
||||
const base = await loadFeedbackSectionData(assignmentId, institutee)
|
||||
const data: FeedbackSectionData = {
|
||||
...base,
|
||||
dimensions: visible.dimensions,
|
||||
categories: visible.categories,
|
||||
colorBands: normalizeRatingColorBands(rawBands),
|
||||
}
|
||||
|
||||
const blob = await pdf(<InstituteeFeedbackDocument assignment={assignment} data={data} />).toBlob()
|
||||
const filename = `${assignmentFilenamePrefix(assignment)}_Feedback-${sanitizeFilename(institutee.firstName + '-' + institutee.lastName)}-${sanitizeFilename(assignment.title)}.pdf`
|
||||
return { blob, filename }
|
||||
}
|
||||
|
||||
export async function exportInstituteeFeedbackPdf(assignmentId: number, instituteeId: number): Promise<void> {
|
||||
const { blob, filename } = await buildInstituteeFeedbackPdfBlob(assignmentId, instituteeId)
|
||||
downloadPdfBlob(blob, filename)
|
||||
}
|
||||
|
||||
// ─── Feedback-Struktur-Dokument (Dimensionen/Kategorien/Kriterien + Beschreibungen) ──
|
||||
|
||||
function FeedbackStructureDocument({ dimensions, categories, items }: {
|
||||
dimensions: FeedbackDimension[]; categories: FeedbackCategory[]; items: FeedbackCriterionItem[]
|
||||
}) {
|
||||
return (
|
||||
<Document>
|
||||
<Page size="A4" style={styles.page} wrap>
|
||||
<Text style={styles.h1}>Feedback-Struktur</Text>
|
||||
{dimensions.map((dim, di) => {
|
||||
const dimCats = categories.filter(c => c.dimensionId === dim.id)
|
||||
return (
|
||||
<View key={dim.id} break={di > 0}>
|
||||
<Text style={styles.h2}>{dim.name}</Text>
|
||||
{dimCats.map(cat => {
|
||||
const catItems = items.filter(i => i.categoryId === cat.id)
|
||||
return (
|
||||
<View key={cat.id} style={{ marginBottom: 8 }}>
|
||||
<View wrap={false} minPresenceAhead={40}>
|
||||
<Text style={styles.h4}>{cat.name}</Text>
|
||||
{cat.description && <Text style={[styles.meta, { marginBottom: 2 }]}>{cat.description}</Text>}
|
||||
</View>
|
||||
{catItems.length === 0 && <Text style={styles.meta}>(keine Kriterien)</Text>}
|
||||
{catItems.map(item => (
|
||||
<Text key={item.id} style={styles.bullet}>
|
||||
<Text style={{ fontWeight: 700 }}>{item.name}</Text>
|
||||
{` (Gewicht ${(item.weight ?? 1).toFixed(1)})`}
|
||||
{item.description ? ` — ${item.description}` : ''}
|
||||
</Text>
|
||||
))}
|
||||
</View>
|
||||
)
|
||||
})}
|
||||
</View>
|
||||
)
|
||||
})}
|
||||
<Text style={styles.footer} render={({ pageNumber, totalPages }) => `Seite ${pageNumber} / ${totalPages} — Export: ${new Date().toLocaleString('de-DE')}`} fixed />
|
||||
</Page>
|
||||
</Document>
|
||||
)
|
||||
}
|
||||
|
||||
export async function exportFeedbackStructurePdf(): Promise<void> {
|
||||
const { dimensions, categories, items } = await loadFeedbackStructure()
|
||||
const blob = await pdf(<FeedbackStructureDocument dimensions={dimensions} categories={categories} items={items} />).toBlob()
|
||||
downloadPdfBlob(blob, `Feedback-Struktur-${new Date().toISOString().slice(0, 10)}.pdf`)
|
||||
}
|
||||
|
||||
// ─── Assignment-Typen-Bericht (inkl. Kriterien-Mapping) ─────────────────────
|
||||
|
||||
function AssignmentTypesDocument({ types, templates, checklistItems, dimensions, categories, items }: {
|
||||
types: AssignmentType[]; templates: PhaseTemplate[]; checklistItems: ChecklistItemDef[]
|
||||
dimensions: FeedbackDimension[]; categories: FeedbackCategory[]; items: FeedbackCriterionItem[]
|
||||
}) {
|
||||
return (
|
||||
<Document>
|
||||
<Page size="A4" style={styles.page} wrap>
|
||||
<Text style={styles.h1}>Assignment-Typen</Text>
|
||||
{types.map((type, ti) => {
|
||||
const typPhases = templates.filter(t => t.assignmentTypeId === type.id).sort((a, b) => a.order - b.order)
|
||||
const criteriaIds = type.criteriaIds ?? []
|
||||
return (
|
||||
<View key={type.id} break={ti > 0}>
|
||||
<Text style={styles.h2}>{type.name}</Text>
|
||||
|
||||
{typPhases.length > 0 && (
|
||||
<View style={{ marginBottom: 6 }}>
|
||||
<Text style={styles.h4}>Phasen</Text>
|
||||
{typPhases.map(p => {
|
||||
const phaseChecklist = checklistItems.filter(ci => ci.phaseTemplateId === p.id).sort((a, b) => a.order - b.order)
|
||||
return (
|
||||
<View key={p.id} style={{ marginBottom: 2 }}>
|
||||
<Text style={styles.bullet}>
|
||||
{p.label} ({p.withWhom === 'client' ? 'Kunde' : 'Lead'}{p.isRepeatable ? ', wiederholbar' : ''}{p.hasChecklist ? ', mit Checkliste' : ''})
|
||||
</Text>
|
||||
{phaseChecklist.map(ci => {
|
||||
const critName = ci.linkedCriterionItemId ? items.find(i => i.id === ci.linkedCriterionItemId)?.name : undefined
|
||||
return (
|
||||
<Text key={ci.id} style={[styles.bullet, { marginLeft: 10, fontSize: 8 }]}>
|
||||
• {ci.label} ({ci.scope === 'meetingWide' ? 'meeting-weit' : 'pro Institutee'})
|
||||
{critName && <Text style={{ color: '#4f46e5' }}> → {critName}</Text>}
|
||||
</Text>
|
||||
)
|
||||
})}
|
||||
</View>
|
||||
)
|
||||
})}
|
||||
</View>
|
||||
)}
|
||||
|
||||
<View wrap={false} minPresenceAhead={30}>
|
||||
<Text style={styles.h4}>Kriterien-Mapping</Text>
|
||||
</View>
|
||||
{criteriaIds.length === 0 ? (
|
||||
<Text style={styles.bullet}>Alle Kriterien (keine Einschränkung)</Text>
|
||||
) : dimensions.map(dim => {
|
||||
const dimCats = categories.filter(c => c.dimensionId === dim.id)
|
||||
const relevantCats = dimCats.filter(c => items.some(i => i.categoryId === c.id && criteriaIds.includes(i.id!)))
|
||||
if (relevantCats.length === 0) return null
|
||||
return (
|
||||
<View key={dim.id} style={{ marginBottom: 3 }} wrap={false}>
|
||||
<Text style={{ fontSize: 8.5, fontWeight: 700 }}>{dim.name}</Text>
|
||||
{relevantCats.map(cat => {
|
||||
const names = items.filter(i => i.categoryId === cat.id && criteriaIds.includes(i.id!)).map(i => i.name).join(', ')
|
||||
return <Text key={cat.id} style={styles.bullet}>{cat.name}: {names}</Text>
|
||||
})}
|
||||
</View>
|
||||
)
|
||||
})}
|
||||
</View>
|
||||
)
|
||||
})}
|
||||
<Text style={styles.footer} render={({ pageNumber, totalPages }) => `Seite ${pageNumber} / ${totalPages} — Export: ${new Date().toLocaleString('de-DE')}`} fixed />
|
||||
</Page>
|
||||
</Document>
|
||||
)
|
||||
}
|
||||
|
||||
export async function exportAssignmentTypesReportPdf(): Promise<void> {
|
||||
const [types, templates, structure] = await Promise.all([
|
||||
listAssignmentTypes(),
|
||||
listPhaseTemplates(),
|
||||
loadFeedbackStructure(),
|
||||
])
|
||||
const checklistItems = await listChecklistItemDefsForPhaseTemplates(templates.map(t => t.id!))
|
||||
const blob = await pdf(
|
||||
<AssignmentTypesDocument types={types} templates={templates} checklistItems={checklistItems}
|
||||
dimensions={structure.dimensions} categories={structure.categories} items={structure.items} />,
|
||||
).toBlob()
|
||||
downloadPdfBlob(blob, `Assignment-Typen-Bericht-${new Date().toISOString().slice(0, 10)}.pdf`)
|
||||
}
|
||||
+18
-24
@@ -1,5 +1,5 @@
|
||||
import type { FeedbackCriterionItem, FeedbackRating } from '../db'
|
||||
import { RATING_NUM_MAP, RATING_TREND_DELTA_THRESHOLD } from '../config/constants'
|
||||
import type { FeedbackCriterionItem, RatingScore } from '../db'
|
||||
import { clampRatingScore, normalizeRatingScore, RATING_TREND_DELTA_THRESHOLD } from '../config/constants'
|
||||
|
||||
export interface MeetingScorePoint {
|
||||
meetingId: number
|
||||
@@ -15,41 +15,39 @@ export interface TrendResult {
|
||||
}
|
||||
|
||||
/**
|
||||
* Gewichteter Rohwert (0–4) über eine Menge von Kriterien, N/A ausgeschlossen.
|
||||
* `null` wenn nichts bewertet ist oder Σweight===0 (sonst NaN < x überall false → fällt auf "Fully" durch).
|
||||
* Einzige Implementierung dieser Regel — nicht pro Callsite neu schreiben, siehe CLAUDE.md.
|
||||
* Gewichteter Rohwert (1–10) über eine Menge von Kriterien; ungesetzte Scores ausgeschlossen.
|
||||
* `null` wenn nichts bewertet ist oder Σweight===0.
|
||||
*/
|
||||
export function weightedAverageScore(
|
||||
items: { id?: number; weight?: number }[],
|
||||
getScore: (itemId: number) => FeedbackRating | null,
|
||||
getScore: (itemId: number) => RatingScore | 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')
|
||||
.map(i => ({ score: normalizeRatingScore(getScore(i.id!)), w: i.weight ?? 1 }))
|
||||
.filter((x): x is { score: RatingScore; w: number } => x.score !== null)
|
||||
if (rated.length === 0) return null
|
||||
const wSum = rated.reduce((s, x) => s + x.w, 0)
|
||||
if (wSum === 0) return null
|
||||
return rated.reduce((s, x) => s + RATING_NUM_MAP[x.score] * x.w, 0) / wSum
|
||||
return rated.reduce((s, x) => s + x.score * x.w, 0) / wSum
|
||||
}
|
||||
|
||||
/** Wie weightedAverageScore, aber als FeedbackRating-Bucket statt Rohwert. */
|
||||
/** Wie weightedAverageScore, aber auf ganze Score-Stufe 1–10 gerundet. */
|
||||
export function weightedAverageRating(
|
||||
items: { id?: number; weight?: number }[],
|
||||
getScore: (itemId: number) => FeedbackRating | null,
|
||||
): FeedbackRating | null {
|
||||
getScore: (itemId: number) => RatingScore | null,
|
||||
): RatingScore | null {
|
||||
const avg = weightedAverageScore(items, getScore)
|
||||
return avg === null ? null : numberToRating(avg)
|
||||
return avg === null ? null : clampRatingScore(avg)
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Meetings ohne bewertetes Item aus der Gruppe werden übersprungen.
|
||||
*/
|
||||
export function buildGroupMeetingScores(
|
||||
items: FeedbackCriterionItem[],
|
||||
meetingsChronological: { id?: number; date: string }[],
|
||||
getScore: (meetingId: number, itemId: number) => FeedbackRating | null,
|
||||
getScore: (meetingId: number, itemId: number) => RatingScore | null,
|
||||
): MeetingScorePoint[] {
|
||||
const points: MeetingScorePoint[] = []
|
||||
for (const meeting of meetingsChronological) {
|
||||
@@ -62,9 +60,7 @@ export function buildGroupMeetingScores(
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Trend aus Delta zwischen erstem und letztem Rohwert (Schwelle auf 1–10-Skala).
|
||||
*/
|
||||
export function computeTrend(history: MeetingScorePoint[], weightStep: number): TrendResult {
|
||||
if (history.length === 0) return { suggestion: null, history, trend: null, delta: null }
|
||||
@@ -82,11 +78,9 @@ export function computeTrend(history: MeetingScorePoint[], weightStep: number):
|
||||
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'
|
||||
/** @deprecated Alias — Rundung auf 1–10; früher Bucket auf Client-Ready-Stufen. */
|
||||
export function numberToRating(avg: number): RatingScore | null {
|
||||
return clampRatingScore(avg)
|
||||
}
|
||||
|
||||
/** Resultierende Gewichte für k chronologische Datenpunkte, z.B. previewWeights(3, 0.5) => [1, 1.5, 2]. */
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import { loadFeedbackStructure, listAssignmentTypes, listPhaseTemplates, listChecklistItemDefsForPhaseTemplates } from '../db'
|
||||
import { downloadFile } from './meetingExport'
|
||||
|
||||
export async function exportFeedbackStructureAsMarkdown(): Promise<void> {
|
||||
const { dimensions, categories, items } = await loadFeedbackStructure()
|
||||
const lines: string[] = ['# Feedback-Struktur', '']
|
||||
|
||||
for (const dim of dimensions) {
|
||||
lines.push(`## ${dim.name}`, '')
|
||||
const dimCats = categories.filter(c => c.dimensionId === dim.id)
|
||||
for (const cat of dimCats) {
|
||||
lines.push(`### ${cat.name}`)
|
||||
if (cat.description) lines.push('', cat.description)
|
||||
lines.push('')
|
||||
const catItems = items.filter(i => i.categoryId === cat.id)
|
||||
for (const item of catItems) {
|
||||
const weight = (item.weight ?? 1).toFixed(1)
|
||||
const desc = item.description ? ` — ${item.description}` : ''
|
||||
lines.push(`- **${item.name}** (Gewicht ${weight})${desc}`)
|
||||
}
|
||||
lines.push('')
|
||||
}
|
||||
}
|
||||
|
||||
lines.push('---', `_Export: ${new Date().toLocaleString('de-DE')}_`)
|
||||
downloadFile(lines.join('\n'), `Feedback-Struktur-${new Date().toISOString().slice(0, 10)}.md`, 'text/markdown')
|
||||
}
|
||||
|
||||
export async function exportAssignmentTypesReportAsMarkdown(): Promise<void> {
|
||||
const [types, templates, structure] = await Promise.all([
|
||||
listAssignmentTypes(),
|
||||
listPhaseTemplates(),
|
||||
loadFeedbackStructure(),
|
||||
])
|
||||
const checklistItems = await listChecklistItemDefsForPhaseTemplates(templates.map(t => t.id!))
|
||||
const lines: string[] = ['# Assignment-Typen', '']
|
||||
|
||||
for (const type of types) {
|
||||
lines.push(`## ${type.name}`, '')
|
||||
const typPhases = templates.filter(t => t.assignmentTypeId === type.id).sort((a, b) => a.order - b.order)
|
||||
|
||||
if (typPhases.length > 0) {
|
||||
lines.push('**Phasen:**')
|
||||
for (const p of typPhases) {
|
||||
const tags = [p.withWhom === 'client' ? 'Kunde' : 'Lead', p.isRepeatable ? 'wiederholbar' : null, p.hasChecklist ? 'mit Checkliste' : null].filter(Boolean).join(', ')
|
||||
lines.push(`- ${p.label} (${tags})`)
|
||||
const phaseChecklist = checklistItems.filter(ci => ci.phaseTemplateId === p.id).sort((a, b) => a.order - b.order)
|
||||
for (const ci of phaseChecklist) {
|
||||
const critName = ci.linkedCriterionItemId ? structure.items.find(i => i.id === ci.linkedCriterionItemId)?.name : undefined
|
||||
const scopeLabel = ci.scope === 'meetingWide' ? 'meeting-weit' : 'pro Institutee'
|
||||
lines.push(` - 🗹 ${ci.label} (${scopeLabel})${critName ? ` → ${critName}` : ''}`)
|
||||
}
|
||||
}
|
||||
lines.push('')
|
||||
}
|
||||
|
||||
lines.push('**Kriterien-Mapping:**')
|
||||
const criteriaIds = type.criteriaIds ?? []
|
||||
if (criteriaIds.length === 0) {
|
||||
lines.push('Alle Kriterien (keine Einschränkung)', '')
|
||||
} else {
|
||||
for (const dim of structure.dimensions) {
|
||||
const dimCats = structure.categories.filter(c => c.dimensionId === dim.id)
|
||||
const relevantCats = dimCats.filter(c => structure.items.some(i => i.categoryId === c.id && criteriaIds.includes(i.id!)))
|
||||
if (relevantCats.length === 0) continue
|
||||
lines.push(`- ${dim.name}`)
|
||||
for (const cat of relevantCats) {
|
||||
const catItemNames = structure.items
|
||||
.filter(i => i.categoryId === cat.id && criteriaIds.includes(i.id!))
|
||||
.map(i => i.name)
|
||||
lines.push(` - ${cat.name}: ${catItemNames.join(', ')}`)
|
||||
}
|
||||
}
|
||||
lines.push('')
|
||||
}
|
||||
}
|
||||
|
||||
lines.push('---', `_Export: ${new Date().toLocaleString('de-DE')}_`)
|
||||
downloadFile(lines.join('\n'), `Assignment-Typen-Bericht-${new Date().toISOString().slice(0, 10)}.md`, 'text/markdown')
|
||||
}
|
||||
Reference in new issue
Block a user