V2-Stand: UX-Dashboard, Personen v2, Starter-Paket und Dexie-Legacy entfernt.
Sichert den lokalen Entwicklungsstand nach Gitea: Nav/Dashboard, Personen-Excel/Archiv, Team-Setup, Assignment-Übergabe und C6/C7/T2. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
234f87d408
commit
d894c3c8e4
91 files changed
+7196
-2134
No files matched your search
@@ -88,24 +88,28 @@ export function saveDefaultDimensionPromptTemplate(template: string): number {
|
||||
}
|
||||
|
||||
/**
|
||||
* Prompt-Template für „🏷 Vorschläge analysieren" (selbstlernendes Kriterien-Tagging) — ein
|
||||
* einziges, protokollweites Template statt eines pro Assignment-Typ, siehe CLAUDE.md. Gleiches
|
||||
* Erstbefüllungs-/Persistenz-Muster wie `getOrSeedDefaultDimensionPromptTemplate`.
|
||||
* Prompt-Template für Protokoll-Tagging („🏷 Vorschläge analysieren", Freitext-Zeilen).
|
||||
* Checklisten haben seit der Trennung ein eigenes Template (`checklistTaggingPromptTemplate`).
|
||||
* Alte Zwischenstände mit `{{CHECKLISTEN_PUNKTE}}` im Protokoll-Prompt werden einmalig auf den
|
||||
* aktuellen Protokoll-Standard migriert — sonst bleibt der Platzhalter unersetzt und die KI
|
||||
* liefert keine brauchbaren ZEILE-Vorschläge mehr.
|
||||
*/
|
||||
export function getOrSeedCriterionTaggingPromptTemplate(): string {
|
||||
const fresh = AI_CONFIG.defaultCriterionTaggingPromptTemplate
|
||||
let settings = getRowById<AppSettings>('appSettings', 1)
|
||||
if (!settings) {
|
||||
insertRowWithId('appSettings', 1, {
|
||||
ratingTrendWeightStep: DEFAULT_RATING_TREND_WEIGHT_STEP,
|
||||
criterionTaggingPromptTemplate: AI_CONFIG.defaultCriterionTaggingPromptTemplate,
|
||||
criterionTaggingPromptTemplate: fresh,
|
||||
})
|
||||
return AI_CONFIG.defaultCriterionTaggingPromptTemplate
|
||||
return fresh
|
||||
}
|
||||
if (!settings.criterionTaggingPromptTemplate) {
|
||||
updateRow('appSettings', 1, { criterionTaggingPromptTemplate: AI_CONFIG.defaultCriterionTaggingPromptTemplate })
|
||||
return AI_CONFIG.defaultCriterionTaggingPromptTemplate
|
||||
const stored = settings.criterionTaggingPromptTemplate
|
||||
if (!stored || stored.includes('{{CHECKLISTEN_PUNKTE}}')) {
|
||||
updateRow('appSettings', 1, { criterionTaggingPromptTemplate: fresh })
|
||||
return fresh
|
||||
}
|
||||
return settings.criterionTaggingPromptTemplate
|
||||
return stored
|
||||
}
|
||||
|
||||
export function saveCriterionTaggingPromptTemplate(template: string): number {
|
||||
@@ -115,6 +119,32 @@ export function saveCriterionTaggingPromptTemplate(template: string): number {
|
||||
return 1
|
||||
}
|
||||
|
||||
export function getOrSeedChecklistTaggingPromptTemplate(): string {
|
||||
let settings = getRowById<AppSettings>('appSettings', 1)
|
||||
if (!settings) {
|
||||
insertRowWithId('appSettings', 1, {
|
||||
ratingTrendWeightStep: DEFAULT_RATING_TREND_WEIGHT_STEP,
|
||||
checklistTaggingPromptTemplate: AI_CONFIG.defaultChecklistTaggingPromptTemplate,
|
||||
})
|
||||
return AI_CONFIG.defaultChecklistTaggingPromptTemplate
|
||||
}
|
||||
if (!settings.checklistTaggingPromptTemplate) {
|
||||
updateRow('appSettings', 1, { checklistTaggingPromptTemplate: AI_CONFIG.defaultChecklistTaggingPromptTemplate })
|
||||
return AI_CONFIG.defaultChecklistTaggingPromptTemplate
|
||||
}
|
||||
return settings.checklistTaggingPromptTemplate
|
||||
}
|
||||
|
||||
export function saveChecklistTaggingPromptTemplate(template: string): number {
|
||||
const existing = getRowById('appSettings', 1)
|
||||
if (existing) updateRow('appSettings', 1, { checklistTaggingPromptTemplate: template })
|
||||
else insertRowWithId('appSettings', 1, {
|
||||
ratingTrendWeightStep: DEFAULT_RATING_TREND_WEIGHT_STEP,
|
||||
checklistTaggingPromptTemplate: template,
|
||||
})
|
||||
return 1
|
||||
}
|
||||
|
||||
export function getOrSeedDefaultCategoryPromptTemplate(): string {
|
||||
let settings = getRowById<AppSettings>('appSettings', 1)
|
||||
if (!settings) {
|
||||
@@ -140,3 +170,29 @@ export function saveDefaultCategoryPromptTemplate(template: string): number {
|
||||
})
|
||||
return 1
|
||||
}
|
||||
|
||||
export function getOrSeedRequirePlannedDates(): boolean {
|
||||
let settings = getRowById<AppSettings>('appSettings', 1)
|
||||
if (!settings) {
|
||||
insertRowWithId('appSettings', 1, {
|
||||
ratingTrendWeightStep: DEFAULT_RATING_TREND_WEIGHT_STEP,
|
||||
requirePlannedDates: false,
|
||||
})
|
||||
return false
|
||||
}
|
||||
if (settings.requirePlannedDates === undefined || settings.requirePlannedDates === null) {
|
||||
updateRow('appSettings', 1, { requirePlannedDates: false })
|
||||
return false
|
||||
}
|
||||
return !!settings.requirePlannedDates
|
||||
}
|
||||
|
||||
export function saveRequirePlannedDates(required: boolean): number {
|
||||
const existing = getRowById('appSettings', 1)
|
||||
if (existing) updateRow('appSettings', 1, { requirePlannedDates: required })
|
||||
else insertRowWithId('appSettings', 1, {
|
||||
ratingTrendWeightStep: DEFAULT_RATING_TREND_WEIGHT_STEP,
|
||||
requirePlannedDates: required,
|
||||
})
|
||||
return 1
|
||||
}
|
||||
@@ -0,0 +1,527 @@
|
||||
/**
|
||||
* Einzel-Assignment Export/Import für Lead-Übergabe (Urlaub/Krankheit).
|
||||
* Enthält Runtime-Daten inkl. Checklisten + referenzierte Berater/Gruppen.
|
||||
* Struktur wird per stabilem Schlüssel gemappt; Berater werden bei Namensgleichheit
|
||||
* wiederverwendet, sonst neu angelegt.
|
||||
*/
|
||||
import { db } from '../../database'
|
||||
import {
|
||||
getAllRows, getRowById, getRowsWhereEquals, getRowsWhereIn, insertRow,
|
||||
} from '../crud'
|
||||
import type {
|
||||
Assignment, AssignmentType, PhaseTemplate, ChecklistItemDef, ChecklistResponse,
|
||||
Group, Consultant, MeetingInstance, ConversationEntry, ConversationSkillScore,
|
||||
Assessment, FeedbackDraft, AssignmentFeedback,
|
||||
FeedbackCategoryRating, FeedbackDimensionText, FeedbackCategoryText,
|
||||
FeedbackDimension, FeedbackCategory, FeedbackCriterionItem, ConversationLineTag,
|
||||
AssignmentTransferPackage, AssignmentImportResult,
|
||||
} from '../../../src/db/types'
|
||||
import { ASSIGNMENT_TRANSFER_KIND } from '../../../src/db/types'
|
||||
import { listMeetingInstancesForAssignment } from './meetings'
|
||||
import { listChecklistItemDefsForPhaseTemplates, listChecklistResponsesForMeetings } from './checklists'
|
||||
import { listConversationEntriesForMeetings } from './conversationEntries'
|
||||
import { listAssessmentsForMeetings } from './assessments'
|
||||
import { listMeetingCategoryRatingsForMeetings } from './meetingCategoryRatings'
|
||||
|
||||
const norm = (s: string) => s.trim().toLowerCase().replace(/\s+/g, ' ')
|
||||
const personKey = (c: Pick<Consultant, 'firstName' | 'lastName'>) =>
|
||||
`${norm(c.firstName)}|${norm(c.lastName)}`
|
||||
const emailKey = (c: Pick<Consultant, 'email'>): string | null => {
|
||||
const e = (c.email ?? '').trim().toLowerCase()
|
||||
return e || null
|
||||
}
|
||||
const groupKey = (g: Pick<Group, 'name' | 'cohortYear'>) =>
|
||||
`${norm(g.name)}|${g.cohortYear}`
|
||||
|
||||
function collectCriterionIds(pkgParts: {
|
||||
assignmentType: AssignmentType
|
||||
phaseTemplates: PhaseTemplate[]
|
||||
checklistItemDefs: ChecklistItemDef[]
|
||||
assessments: Assessment[]
|
||||
checklistResponses: ChecklistResponse[]
|
||||
conversationEntries: ConversationEntry[]
|
||||
meetingInstances: MeetingInstance[]
|
||||
}): Set<number> {
|
||||
const ids = new Set<number>()
|
||||
for (const id of pkgParts.assignmentType.criteriaIds ?? []) ids.add(id)
|
||||
for (const p of pkgParts.phaseTemplates) for (const id of p.criteriaIds ?? []) ids.add(id)
|
||||
for (const c of pkgParts.checklistItemDefs) {
|
||||
if (c.linkedCriterionItemId != null) ids.add(c.linkedCriterionItemId)
|
||||
}
|
||||
for (const a of pkgParts.assessments) ids.add(a.criteriaId)
|
||||
for (const r of pkgParts.checklistResponses) {
|
||||
if (r.criterionItemId != null) ids.add(r.criterionItemId)
|
||||
}
|
||||
for (const e of pkgParts.conversationEntries) {
|
||||
for (const t of e.lineTags ?? []) ids.add(t.criterionItemId)
|
||||
}
|
||||
for (const m of pkgParts.meetingInstances) {
|
||||
for (const t of m.generalNoteTags ?? []) ids.add(t.criterionItemId)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
function remapTags(
|
||||
tags: ConversationLineTag[] | undefined,
|
||||
criterionMap: Map<number, number>,
|
||||
): ConversationLineTag[] | undefined {
|
||||
if (!tags) return tags
|
||||
return tags.map(t => ({
|
||||
text: t.text,
|
||||
criterionItemId: criterionMap.get(t.criterionItemId) ?? t.criterionItemId,
|
||||
}))
|
||||
}
|
||||
|
||||
function requireMap(map: Map<number, number>, oldId: number, label: string): number {
|
||||
const next = map.get(oldId)
|
||||
if (next == null) throw new Error(`${label}: Quell-ID ${oldId} konnte nicht gemappt werden`)
|
||||
return next
|
||||
}
|
||||
|
||||
/** Exportiert ein Assignment inkl. aller Meetings/Notizen/Checklisten/Feedbacks und referenzierter Berater. */
|
||||
export function exportAssignmentTransfer(assignmentId: number): AssignmentTransferPackage {
|
||||
const assignment = getRowById<Assignment>('assignments', assignmentId)
|
||||
if (!assignment) throw new Error('Assignment nicht gefunden')
|
||||
|
||||
const assignmentType = getRowById<AssignmentType>('assignmentTypes', assignment.assignmentTypeId)
|
||||
if (!assignmentType) throw new Error('Assignment-Typ nicht gefunden')
|
||||
|
||||
const phaseTemplates = getRowsWhereEquals<PhaseTemplate>('phaseTemplates', 'assignmentTypeId', assignment.assignmentTypeId)
|
||||
.sort((a, b) => a.order - b.order)
|
||||
const phaseIds = phaseTemplates.map(p => p.id!)
|
||||
const checklistItemDefs = listChecklistItemDefsForPhaseTemplates(phaseIds)
|
||||
|
||||
const meetingInstances = listMeetingInstancesForAssignment(assignmentId)
|
||||
const meetingIds = meetingInstances.map(m => m.id!)
|
||||
const conversationEntries = listConversationEntriesForMeetings(meetingIds)
|
||||
const entryIds = conversationEntries.map(e => e.id!)
|
||||
const conversationSkillScores = getAllRows<ConversationSkillScore>('conversationSkillScores')
|
||||
.filter(s => entryIds.includes(s.conversationEntryId))
|
||||
const assessments = listAssessmentsForMeetings(meetingIds)
|
||||
const meetingCategoryRatings = listMeetingCategoryRatingsForMeetings(meetingIds)
|
||||
const checklistResponses = listChecklistResponsesForMeetings(meetingIds)
|
||||
|
||||
const feedbackDrafts = getRowsWhereEquals<FeedbackDraft>('feedbackDrafts', 'assignmentId', assignmentId)
|
||||
const assignmentFeedbacks = getRowsWhereEquals<AssignmentFeedback>('assignmentFeedbacks', 'assignmentId', assignmentId)
|
||||
const feedbackIds = assignmentFeedbacks.map(f => f.id!)
|
||||
const feedbackCategoryRatings = getRowsWhereIn<FeedbackCategoryRating>('feedbackCategoryRatings', 'assignmentFeedbackId', feedbackIds)
|
||||
const feedbackDimensionTexts = getRowsWhereIn<FeedbackDimensionText>('feedbackDimensionTexts', 'assignmentFeedbackId', feedbackIds)
|
||||
const feedbackCategoryTexts = getRowsWhereIn<FeedbackCategoryText>('feedbackCategoryTexts', 'assignmentFeedbackId', feedbackIds)
|
||||
|
||||
const instituteeIds = new Set<number>(assignment.instituteeIds)
|
||||
for (const e of assignment.instituteeEnrollments ?? []) instituteeIds.add(e.instituteeId)
|
||||
for (const e of conversationEntries) instituteeIds.add(e.instituteeId)
|
||||
for (const a of assessments) instituteeIds.add(a.instituteeId)
|
||||
for (const r of meetingCategoryRatings) instituteeIds.add(r.instituteeId)
|
||||
for (const r of checklistResponses) if (r.instituteeId != null) instituteeIds.add(r.instituteeId)
|
||||
for (const f of feedbackDrafts) instituteeIds.add(f.instituteeId)
|
||||
for (const f of assignmentFeedbacks) instituteeIds.add(f.instituteeId)
|
||||
|
||||
const consultants = getRowsWhereIn<Consultant>('consultants', 'id', [...instituteeIds])
|
||||
const groupIds = [...new Set(consultants.map(c => c.groupId))]
|
||||
const groups = getRowsWhereIn<Group>('groups', 'id', groupIds)
|
||||
|
||||
const criterionIds = collectCriterionIds({
|
||||
assignmentType, phaseTemplates, checklistItemDefs, assessments,
|
||||
checklistResponses, conversationEntries, meetingInstances,
|
||||
})
|
||||
for (const r of meetingCategoryRatings) {
|
||||
for (const i of getRowsWhereEquals<FeedbackCriterionItem>('feedbackCriterionItems', 'categoryId', r.categoryId)) {
|
||||
criterionIds.add(i.id!)
|
||||
}
|
||||
}
|
||||
for (const r of feedbackCategoryRatings) {
|
||||
for (const i of getRowsWhereEquals<FeedbackCriterionItem>('feedbackCriterionItems', 'categoryId', r.feedbackCategoryId)) {
|
||||
criterionIds.add(i.id!)
|
||||
}
|
||||
}
|
||||
for (const s of conversationSkillScores) {
|
||||
for (const i of getRowsWhereEquals<FeedbackCriterionItem>('feedbackCriterionItems', 'categoryId', s.criteriaId)) {
|
||||
criterionIds.add(i.id!)
|
||||
}
|
||||
}
|
||||
|
||||
const feedbackCriterionItems = getRowsWhereIn<FeedbackCriterionItem>('feedbackCriterionItems', 'id', [...criterionIds])
|
||||
.map(i => ({ ...i, learnedPatternHints: undefined }))
|
||||
const categoryIds = new Set(feedbackCriterionItems.map(i => i.categoryId))
|
||||
for (const r of meetingCategoryRatings) categoryIds.add(r.categoryId)
|
||||
for (const r of feedbackCategoryRatings) categoryIds.add(r.feedbackCategoryId)
|
||||
for (const t of feedbackCategoryTexts) categoryIds.add(t.feedbackCategoryId)
|
||||
for (const s of conversationSkillScores) categoryIds.add(s.criteriaId)
|
||||
|
||||
const feedbackCategories = getRowsWhereIn<FeedbackCategory>('feedbackCategories', 'id', [...categoryIds])
|
||||
const dimensionIds = new Set(feedbackCategories.map(c => c.dimensionId))
|
||||
for (const t of feedbackDimensionTexts) dimensionIds.add(t.feedbackDimensionId)
|
||||
const feedbackDimensions = getRowsWhereIn<FeedbackDimension>('feedbackDimensions', 'id', [...dimensionIds])
|
||||
|
||||
return {
|
||||
kind: ASSIGNMENT_TRANSFER_KIND,
|
||||
version: 1,
|
||||
exportedAt: new Date().toISOString(),
|
||||
source: {
|
||||
assignmentId,
|
||||
assignmentNumber: assignment.assignmentNumber,
|
||||
title: assignment.title,
|
||||
client: assignment.client,
|
||||
},
|
||||
groups,
|
||||
consultants,
|
||||
assignmentType,
|
||||
phaseTemplates,
|
||||
checklistItemDefs,
|
||||
feedbackDimensions,
|
||||
feedbackCategories,
|
||||
feedbackCriterionItems,
|
||||
assignment,
|
||||
meetingInstances,
|
||||
conversationEntries,
|
||||
conversationSkillScores,
|
||||
assessments,
|
||||
meetingCategoryRatings,
|
||||
checklistResponses,
|
||||
feedbackDrafts,
|
||||
assignmentFeedbacks,
|
||||
feedbackCategoryRatings,
|
||||
feedbackDimensionTexts,
|
||||
feedbackCategoryTexts,
|
||||
}
|
||||
}
|
||||
|
||||
/** Importiert ein Transfer-Paket als neues Assignment (Merge, kein Wipe). */
|
||||
export function importAssignmentTransfer(pkg: AssignmentTransferPackage): AssignmentImportResult {
|
||||
if (!pkg || pkg.kind !== ASSIGNMENT_TRANSFER_KIND || pkg.version !== 1) {
|
||||
throw new Error('Ungültiges Assignment-Übergabe-Format')
|
||||
}
|
||||
if (!pkg.assignment || !pkg.assignmentType) {
|
||||
throw new Error('Paket unvollständig (Assignment/Typ fehlt)')
|
||||
}
|
||||
|
||||
const groupMap = new Map<number, number>()
|
||||
const consultantMap = new Map<number, number>()
|
||||
const dimensionMap = new Map<number, number>()
|
||||
const categoryMap = new Map<number, number>()
|
||||
const criterionMap = new Map<number, number>()
|
||||
const typeMap = new Map<number, number>()
|
||||
const phaseMap = new Map<number, number>()
|
||||
const checklistDefMap = new Map<number, number>()
|
||||
const meetingMap = new Map<number, number>()
|
||||
const entryMap = new Map<number, number>()
|
||||
const feedbackMap = new Map<number, number>()
|
||||
|
||||
const consultantsMatched: string[] = []
|
||||
const consultantsCreated: string[] = []
|
||||
|
||||
const localDims = getAllRows<FeedbackDimension>('feedbackDimensions')
|
||||
for (const d of pkg.feedbackDimensions) {
|
||||
const byId = d.id != null ? getRowById<FeedbackDimension>('feedbackDimensions', d.id) : undefined
|
||||
if (byId && norm(byId.name) === norm(d.name)) {
|
||||
dimensionMap.set(d.id!, d.id!)
|
||||
continue
|
||||
}
|
||||
const hit = localDims.find(x => norm(x.name) === norm(d.name))
|
||||
if (!hit?.id) {
|
||||
throw new Error(`Feedback-Dimension „${d.name}" fehlt lokal — bitte zuerst npm run setup / Starter laden.`)
|
||||
}
|
||||
dimensionMap.set(d.id!, hit.id)
|
||||
}
|
||||
|
||||
const localCats = getAllRows<FeedbackCategory>('feedbackCategories')
|
||||
for (const c of pkg.feedbackCategories) {
|
||||
const dimId = requireMap(dimensionMap, c.dimensionId, 'Dimension')
|
||||
const byId = c.id != null ? getRowById<FeedbackCategory>('feedbackCategories', c.id) : undefined
|
||||
if (byId && norm(byId.name) === norm(c.name) && byId.dimensionId === dimId) {
|
||||
categoryMap.set(c.id!, c.id!)
|
||||
continue
|
||||
}
|
||||
const hit = localCats.find(x => x.dimensionId === dimId && norm(x.name) === norm(c.name))
|
||||
if (!hit?.id) {
|
||||
throw new Error(`Feedback-Kategorie „${c.name}" fehlt lokal — bitte Starter-Struktur angleichen.`)
|
||||
}
|
||||
categoryMap.set(c.id!, hit.id)
|
||||
}
|
||||
|
||||
const localItems = getAllRows<FeedbackCriterionItem>('feedbackCriterionItems')
|
||||
for (const item of pkg.feedbackCriterionItems) {
|
||||
const catId = requireMap(categoryMap, item.categoryId, 'Kategorie')
|
||||
const byId = item.id != null ? getRowById<FeedbackCriterionItem>('feedbackCriterionItems', item.id) : undefined
|
||||
if (byId && norm(byId.name) === norm(item.name) && byId.categoryId === catId) {
|
||||
criterionMap.set(item.id!, item.id!)
|
||||
continue
|
||||
}
|
||||
const hit = localItems.find(x => x.categoryId === catId && norm(x.name) === norm(item.name))
|
||||
if (!hit?.id) {
|
||||
throw new Error(`Kriterium „${item.name}" fehlt lokal — bitte Starter-Struktur angleichen.`)
|
||||
}
|
||||
criterionMap.set(item.id!, hit.id)
|
||||
}
|
||||
|
||||
const localTypes = getAllRows<AssignmentType>('assignmentTypes')
|
||||
{
|
||||
const t = pkg.assignmentType
|
||||
const byId = t.id != null ? getRowById<AssignmentType>('assignmentTypes', t.id) : undefined
|
||||
let typeId: number
|
||||
if (byId && norm(byId.name) === norm(t.name)) {
|
||||
typeId = t.id!
|
||||
} else {
|
||||
const hit = localTypes.find(x => norm(x.name) === norm(t.name))
|
||||
if (hit?.id) {
|
||||
typeId = hit.id
|
||||
} else {
|
||||
typeId = insertRow('assignmentTypes', {
|
||||
name: t.name,
|
||||
defaultPhaseKeys: t.defaultPhaseKeys,
|
||||
criteriaIds: (t.criteriaIds ?? [])
|
||||
.map(id => criterionMap.get(id))
|
||||
.filter((id): id is number => id != null),
|
||||
})
|
||||
}
|
||||
}
|
||||
typeMap.set(t.id!, typeId)
|
||||
}
|
||||
|
||||
const targetTypeId = requireMap(typeMap, pkg.assignmentType.id!, 'Assignment-Typ')
|
||||
const localPhases = getRowsWhereEquals<PhaseTemplate>('phaseTemplates', 'assignmentTypeId', targetTypeId)
|
||||
for (const p of pkg.phaseTemplates) {
|
||||
const byKey = localPhases.find(x => x.phaseKey === p.phaseKey && norm(x.label) === norm(p.label))
|
||||
?? localPhases.find(x => x.phaseKey === p.phaseKey)
|
||||
let phaseId: number
|
||||
if (byKey?.id) {
|
||||
phaseId = byKey.id
|
||||
} else {
|
||||
phaseId = insertRow('phaseTemplates', {
|
||||
assignmentTypeId: targetTypeId,
|
||||
phaseKey: p.phaseKey,
|
||||
label: p.label,
|
||||
withWhom: p.withWhom,
|
||||
isRepeatable: p.isRepeatable,
|
||||
hasConversation: p.hasConversation,
|
||||
hasAssessment: p.hasAssessment,
|
||||
hasChecklist: p.hasChecklist,
|
||||
criteriaIds: (p.criteriaIds ?? [])
|
||||
.map(id => criterionMap.get(id))
|
||||
.filter((id): id is number => id != null),
|
||||
order: p.order,
|
||||
})
|
||||
}
|
||||
phaseMap.set(p.id!, phaseId)
|
||||
}
|
||||
|
||||
for (const def of pkg.checklistItemDefs) {
|
||||
const phaseId = requireMap(phaseMap, def.phaseTemplateId, 'Phase')
|
||||
const localDefs = getRowsWhereEquals<ChecklistItemDef>('checklistItemDefs', 'phaseTemplateId', phaseId)
|
||||
const hit = localDefs.find(x => norm(x.label) === norm(def.label) && x.order === def.order)
|
||||
?? localDefs.find(x => norm(x.label) === norm(def.label))
|
||||
let defId: number
|
||||
if (hit?.id) {
|
||||
defId = hit.id
|
||||
} else {
|
||||
defId = insertRow('checklistItemDefs', {
|
||||
phaseTemplateId: phaseId,
|
||||
label: def.label,
|
||||
linkedCriterionItemId: def.linkedCriterionItemId != null
|
||||
? (criterionMap.get(def.linkedCriterionItemId) ?? null)
|
||||
: null,
|
||||
scope: def.scope,
|
||||
order: def.order,
|
||||
scoreContribution: def.scoreContribution,
|
||||
})
|
||||
}
|
||||
checklistDefMap.set(def.id!, defId)
|
||||
}
|
||||
|
||||
const pkgGroupsById = new Map(pkg.groups.map(g => [g.id!, g]))
|
||||
for (const g of pkg.groups) {
|
||||
const locals = getAllRows<Group>('groups')
|
||||
const hit = locals.find(x => groupKey(x) === groupKey(g))
|
||||
groupMap.set(g.id!, hit?.id ?? insertRow('groups', { name: g.name, cohortYear: g.cohortYear }))
|
||||
}
|
||||
|
||||
for (const c of pkg.consultants) {
|
||||
const label = `${c.firstName} ${c.lastName}`.trim()
|
||||
const locals = getAllRows<Consultant>('consultants')
|
||||
const ek = emailKey(c)
|
||||
const hit = ek
|
||||
? locals.find(x => emailKey(x) === ek)
|
||||
: locals.find(x => personKey(x) === personKey(c))
|
||||
if (hit?.id) {
|
||||
consultantMap.set(c.id!, hit.id)
|
||||
consultantsMatched.push(label)
|
||||
continue
|
||||
}
|
||||
const srcGroup = pkgGroupsById.get(c.groupId)
|
||||
if (!srcGroup) throw new Error(`Gruppe für Berater „${label}" fehlt im Paket`)
|
||||
let groupId = groupMap.get(srcGroup.id!)
|
||||
if (groupId == null) {
|
||||
const gLocals = getAllRows<Group>('groups')
|
||||
const gHit = gLocals.find(x => groupKey(x) === groupKey(srcGroup))
|
||||
groupId = gHit?.id ?? insertRow('groups', { name: srcGroup.name, cohortYear: srcGroup.cohortYear })
|
||||
groupMap.set(srcGroup.id!, groupId)
|
||||
}
|
||||
const newId = insertRow('consultants', {
|
||||
groupId,
|
||||
firstName: c.firstName,
|
||||
lastName: c.lastName,
|
||||
email: ek ?? '',
|
||||
})
|
||||
consultantMap.set(c.id!, newId)
|
||||
consultantsCreated.push(label)
|
||||
}
|
||||
|
||||
let newAssignmentId = 0
|
||||
let checklistResponseCount = 0
|
||||
|
||||
db.exec('BEGIN')
|
||||
try {
|
||||
const a = pkg.assignment
|
||||
newAssignmentId = insertRow('assignments', {
|
||||
title: a.title,
|
||||
client: a.client,
|
||||
assignmentTypeId: targetTypeId,
|
||||
instituteeIds: a.instituteeIds.map(id => requireMap(consultantMap, id, 'Berater')),
|
||||
leadName: a.leadName,
|
||||
status: a.status,
|
||||
createdAt: a.createdAt || new Date().toISOString(),
|
||||
assignmentNumber: a.assignmentNumber,
|
||||
description: a.description,
|
||||
instituteeEnrollments: (a.instituteeEnrollments ?? []).map(e => ({
|
||||
...e,
|
||||
instituteeId: requireMap(consultantMap, e.instituteeId, 'Berater'),
|
||||
})),
|
||||
deletedAt: null,
|
||||
archivedAt: null,
|
||||
})
|
||||
|
||||
for (const m of pkg.meetingInstances) {
|
||||
const meetingId = insertRow('meetingInstances', {
|
||||
assignmentId: newAssignmentId,
|
||||
phaseTemplateId: requireMap(phaseMap, m.phaseTemplateId, 'Phase'),
|
||||
phaseIndex: m.phaseIndex,
|
||||
date: m.date,
|
||||
status: m.status,
|
||||
generalNotes: m.generalNotes ?? '',
|
||||
deletedAt: m.deletedAt ?? null,
|
||||
generalNoteTags: remapTags(m.generalNoteTags, criterionMap),
|
||||
})
|
||||
meetingMap.set(m.id!, meetingId)
|
||||
}
|
||||
|
||||
for (const e of pkg.conversationEntries) {
|
||||
const entryId = insertRow('conversationEntries', {
|
||||
meetingInstanceId: requireMap(meetingMap, e.meetingInstanceId, 'Meeting'),
|
||||
instituteeId: requireMap(consultantMap, e.instituteeId, 'Berater'),
|
||||
sequenceIndex: e.sequenceIndex,
|
||||
note: e.note,
|
||||
fillerCount: e.fillerCount ?? 0,
|
||||
updatedAt: e.updatedAt || new Date().toISOString(),
|
||||
lineTags: remapTags(e.lineTags, criterionMap),
|
||||
})
|
||||
entryMap.set(e.id!, entryId)
|
||||
}
|
||||
|
||||
for (const s of pkg.conversationSkillScores) {
|
||||
insertRow('conversationSkillScores', {
|
||||
conversationEntryId: requireMap(entryMap, s.conversationEntryId, 'Protokoll-Eintrag'),
|
||||
criteriaId: requireMap(categoryMap, s.criteriaId, 'Kategorie (Skill-Score)'),
|
||||
score: s.score,
|
||||
})
|
||||
}
|
||||
|
||||
for (const asmt of pkg.assessments) {
|
||||
insertRow('assessments', {
|
||||
meetingInstanceId: requireMap(meetingMap, asmt.meetingInstanceId, 'Meeting'),
|
||||
instituteeId: requireMap(consultantMap, asmt.instituteeId, 'Berater'),
|
||||
criteriaId: requireMap(criterionMap, asmt.criteriaId, 'Kriterium'),
|
||||
score: asmt.score,
|
||||
note: asmt.note ?? '',
|
||||
updatedAt: asmt.updatedAt || new Date().toISOString(),
|
||||
scoreNeedsReview: asmt.scoreNeedsReview ?? false,
|
||||
})
|
||||
}
|
||||
|
||||
for (const r of pkg.meetingCategoryRatings) {
|
||||
insertRow('meetingCategoryRatings', {
|
||||
meetingInstanceId: requireMap(meetingMap, r.meetingInstanceId, 'Meeting'),
|
||||
instituteeId: requireMap(consultantMap, r.instituteeId, 'Berater'),
|
||||
categoryId: requireMap(categoryMap, r.categoryId, 'Kategorie'),
|
||||
score: r.score,
|
||||
note: r.note,
|
||||
})
|
||||
}
|
||||
|
||||
for (const r of pkg.checklistResponses) {
|
||||
insertRow('checklistResponses', {
|
||||
meetingInstanceId: requireMap(meetingMap, r.meetingInstanceId, 'Meeting'),
|
||||
instituteeId: r.instituteeId != null ? requireMap(consultantMap, r.instituteeId, 'Berater') : null,
|
||||
checklistItemId: requireMap(checklistDefMap, r.checklistItemId, 'Checklistenpunkt'),
|
||||
rating: r.rating,
|
||||
note: r.note ?? '',
|
||||
criterionItemId: r.criterionItemId != null ? (criterionMap.get(r.criterionItemId) ?? null) : null,
|
||||
criterionOverride: r.criterionOverride ?? false,
|
||||
})
|
||||
checklistResponseCount++
|
||||
}
|
||||
|
||||
for (const d of pkg.feedbackDrafts) {
|
||||
insertRow('feedbackDrafts', {
|
||||
assignmentId: newAssignmentId,
|
||||
instituteeId: requireMap(consultantMap, d.instituteeId, 'Berater'),
|
||||
content: d.content,
|
||||
updatedAt: d.updatedAt || new Date().toISOString(),
|
||||
})
|
||||
}
|
||||
|
||||
for (const f of pkg.assignmentFeedbacks) {
|
||||
const fbId = insertRow('assignmentFeedbacks', {
|
||||
assignmentId: newAssignmentId,
|
||||
instituteeId: requireMap(consultantMap, f.instituteeId, 'Berater'),
|
||||
status: f.status,
|
||||
aiModel: f.aiModel ?? '',
|
||||
updatedAt: f.updatedAt || new Date().toISOString(),
|
||||
})
|
||||
feedbackMap.set(f.id!, fbId)
|
||||
}
|
||||
|
||||
for (const r of pkg.feedbackCategoryRatings) {
|
||||
insertRow('feedbackCategoryRatings', {
|
||||
assignmentFeedbackId: requireMap(feedbackMap, r.assignmentFeedbackId, 'Feedback'),
|
||||
feedbackCategoryId: requireMap(categoryMap, r.feedbackCategoryId, 'Kategorie'),
|
||||
rating: r.rating,
|
||||
})
|
||||
}
|
||||
|
||||
for (const t of pkg.feedbackDimensionTexts) {
|
||||
insertRow('feedbackDimensionTexts', {
|
||||
assignmentFeedbackId: requireMap(feedbackMap, t.assignmentFeedbackId, 'Feedback'),
|
||||
feedbackDimensionId: requireMap(dimensionMap, t.feedbackDimensionId, 'Dimension'),
|
||||
achievements: t.achievements ?? '',
|
||||
developmentNeeds: t.developmentNeeds ?? '',
|
||||
suggestedAchievements: t.suggestedAchievements,
|
||||
suggestedDevelopmentNeeds: t.suggestedDevelopmentNeeds,
|
||||
})
|
||||
}
|
||||
|
||||
for (const t of pkg.feedbackCategoryTexts) {
|
||||
insertRow('feedbackCategoryTexts', {
|
||||
assignmentFeedbackId: requireMap(feedbackMap, t.assignmentFeedbackId, 'Feedback'),
|
||||
feedbackCategoryId: requireMap(categoryMap, t.feedbackCategoryId, 'Kategorie'),
|
||||
benefits: t.benefits ?? '',
|
||||
concerns: t.concerns ?? '',
|
||||
suggestedBenefits: t.suggestedBenefits,
|
||||
suggestedConcerns: t.suggestedConcerns,
|
||||
})
|
||||
}
|
||||
|
||||
db.exec('COMMIT')
|
||||
} catch (err) {
|
||||
db.exec('ROLLBACK')
|
||||
throw err
|
||||
}
|
||||
|
||||
return {
|
||||
assignmentId: newAssignmentId,
|
||||
consultantsMatched,
|
||||
consultantsCreated,
|
||||
meetings: pkg.meetingInstances.length,
|
||||
checklistResponses: checklistResponseCount,
|
||||
}
|
||||
}
|
||||
@@ -68,6 +68,8 @@ export function purgeExpiredAssignmentTrash(): void {
|
||||
|
||||
export interface AssignmentWithDetails extends Assignment {
|
||||
typeName: string
|
||||
/** Hex-Farbe des Assignment-Typs (Fallback Brand). */
|
||||
typeColor: string
|
||||
instituteeNames: string[]
|
||||
/** Nur für status==='done' relevant: jedes Institutee hat ein finales Feedback — steuert den Löschen-Button in der Übersicht. */
|
||||
feedbackComplete: boolean
|
||||
@@ -82,15 +84,19 @@ export function listAssignmentsWithDetails(): AssignmentWithDetails[] {
|
||||
const allFeedbacks = getAllRows<AssignmentFeedback>('assignmentFeedbacks')
|
||||
const typeMap = new Map<number, AssignmentType>(types.map(t => [t.id!, t]))
|
||||
const consMap = new Map<number, Consultant>(consultants.map(c => [c.id!, c]))
|
||||
return raw.map(a => ({
|
||||
...a,
|
||||
typeName: typeMap.get(a.assignmentTypeId)?.name ?? '—',
|
||||
instituteeNames: a.instituteeIds.map(id => {
|
||||
const c = consMap.get(id)
|
||||
return c ? `${c.firstName} ${c.lastName}` : '?'
|
||||
}),
|
||||
feedbackComplete: a.instituteeIds.every(iid =>
|
||||
allFeedbacks.some(f => f.assignmentId === a.id && f.instituteeId === iid && f.status === 'final'),
|
||||
),
|
||||
}))
|
||||
return raw.map(a => {
|
||||
const t = typeMap.get(a.assignmentTypeId)
|
||||
return {
|
||||
...a,
|
||||
typeName: t?.name ?? '—',
|
||||
typeColor: t?.color?.trim() || '#0070AD',
|
||||
instituteeNames: a.instituteeIds.map(id => {
|
||||
const c = consMap.get(id)
|
||||
return c ? `${c.firstName} ${c.lastName}` : '?'
|
||||
}),
|
||||
feedbackComplete: a.instituteeIds.every(iid =>
|
||||
allFeedbacks.some(f => f.assignmentId === a.id && f.instituteeId === iid && f.status === 'final'),
|
||||
),
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -48,16 +48,23 @@ export function upsertChecklistResponse(input: {
|
||||
checklistItemId: number
|
||||
rating: ChecklistResponse['rating']
|
||||
note: string
|
||||
criterionItemId?: number
|
||||
criterionItemId?: number | null
|
||||
criterionOverride?: boolean
|
||||
}): number {
|
||||
const existing = getAllRows<ChecklistResponse>('checklistResponses').find(r =>
|
||||
r.meetingInstanceId === input.meetingInstanceId &&
|
||||
r.checklistItemId === input.checklistItemId &&
|
||||
(r.instituteeId ?? null) === (input.instituteeId ?? null),
|
||||
)
|
||||
const row = {
|
||||
rating: input.rating,
|
||||
note: input.note,
|
||||
criterionItemId: input.criterionItemId,
|
||||
criterionOverride: input.criterionOverride,
|
||||
}
|
||||
if (existing?.id) {
|
||||
updateRow('checklistResponses', existing.id, { rating: input.rating, note: input.note, criterionItemId: input.criterionItemId })
|
||||
updateRow('checklistResponses', existing.id, row)
|
||||
return existing.id
|
||||
}
|
||||
return insertRow('checklistResponses', input)
|
||||
return insertRow('checklistResponses', { ...input, ...row })
|
||||
}
|
||||
@@ -1,12 +1,266 @@
|
||||
import { getAllRows, getRowById, getRowsWhereIn, insertRow, updateRow, deleteRowById } from '../crud'
|
||||
import type { Group, Consultant } from '../../../src/db/types'
|
||||
import {
|
||||
getAllRows, getRowById, getRowsWhereIn,
|
||||
insertRow, updateRow, deleteRowById, deleteRowsWhereEquals, deleteRowsWhereIn,
|
||||
} from '../crud'
|
||||
import type {
|
||||
Group, Consultant, Assignment, AssignmentFeedback, FeedbackCategoryRating,
|
||||
FeedbackCategory, ConversationEntry, RatingScore,
|
||||
ConsultantImportRow, ConsultantImportResult, HardDeleteConsultantResult,
|
||||
ConsultantAssignmentSummary, ConsultantDetail,
|
||||
} from '../../../src/db/types'
|
||||
|
||||
export type {
|
||||
ConsultantImportRow, ConsultantImportResult, HardDeleteConsultantResult,
|
||||
ConsultantAssignmentSummary, ConsultantDetail,
|
||||
}
|
||||
|
||||
export function normalizeEmail(email: string): string {
|
||||
return email.trim().toLowerCase()
|
||||
}
|
||||
|
||||
export function listGroups(): Group[] {
|
||||
return getAllRows<Group>('groups').sort((a, b) =>
|
||||
a.cohortYear !== b.cohortYear ? b.cohortYear - a.cohortYear : a.name.localeCompare(b.name),
|
||||
)
|
||||
}
|
||||
|
||||
export const getGroup = (id: number): Group | undefined => getRowById<Group>('groups', id)
|
||||
|
||||
export const listGroups = (): Group[] => getAllRows<Group>('groups')
|
||||
export const addGroup = (group: Omit<Group, 'id'>): number => insertRow('groups', group)
|
||||
|
||||
export function updateGroup(id: number, patch: Partial<Group>): number {
|
||||
return updateRow('groups', id, patch)
|
||||
}
|
||||
|
||||
/** Nur leere Gruppen — sonst Fehlertext. */
|
||||
export function deleteGroup(id: number): { ok: true } | { ok: false; reason: string; memberCount: number } {
|
||||
const members = getAllRows<Consultant>('consultants').filter(c => c.groupId === id)
|
||||
if (members.length > 0) {
|
||||
return {
|
||||
ok: false,
|
||||
reason: 'Gruppe hat noch Personen — zuerst umziehen oder archivieren/löschen.',
|
||||
memberCount: members.length,
|
||||
}
|
||||
}
|
||||
deleteRowById('groups', id)
|
||||
return { ok: true }
|
||||
}
|
||||
|
||||
export const listConsultants = (): Consultant[] => getAllRows<Consultant>('consultants')
|
||||
|
||||
export function listActiveConsultants(): Consultant[] {
|
||||
return listConsultants().filter(c => !c.archivedAt)
|
||||
}
|
||||
|
||||
export function listArchivedConsultants(): Consultant[] {
|
||||
return listConsultants().filter(c => !!c.archivedAt)
|
||||
}
|
||||
|
||||
export const getConsultant = (id: number): Consultant | undefined => getRowById<Consultant>('consultants', id)
|
||||
export const getConsultantsByIds = (ids: number[]): Consultant[] => getRowsWhereIn<Consultant>('consultants', 'id', ids)
|
||||
export const addConsultant = (consultant: Omit<Consultant, 'id'>): number => insertRow('consultants', consultant)
|
||||
export const updateConsultant = (id: number, patch: Partial<Consultant>): number => updateRow('consultants', id, patch)
|
||||
export const deleteConsultant = (id: number): void => deleteRowById('consultants', id)
|
||||
|
||||
export const getConsultantsByIds = (ids: number[]): Consultant[] =>
|
||||
getRowsWhereIn<Consultant>('consultants', 'id', ids)
|
||||
|
||||
export function findConsultantByEmail(email: string): Consultant | undefined {
|
||||
const key = normalizeEmail(email)
|
||||
if (!key) return undefined
|
||||
return listConsultants().find(c => normalizeEmail(c.email ?? '') === key)
|
||||
}
|
||||
|
||||
function assertUniqueEmail(email: string, exceptId?: number): void {
|
||||
const key = normalizeEmail(email)
|
||||
if (!key) throw new Error('E-Mail ist Pflicht.')
|
||||
const hit = listConsultants().find(c => normalizeEmail(c.email ?? '') === key && c.id !== exceptId)
|
||||
if (hit) throw new Error(`E-Mail „${key}" ist bereits vergeben (${hit.firstName} ${hit.lastName}).`)
|
||||
}
|
||||
|
||||
export function addConsultant(consultant: Omit<Consultant, 'id'>): number {
|
||||
const email = normalizeEmail(consultant.email ?? '')
|
||||
assertUniqueEmail(email)
|
||||
return insertRow('consultants', {
|
||||
...consultant,
|
||||
email,
|
||||
firstName: consultant.firstName.trim(),
|
||||
lastName: consultant.lastName.trim(),
|
||||
})
|
||||
}
|
||||
|
||||
export function updateConsultant(id: number, patch: Partial<Consultant>): number {
|
||||
const next: Partial<Consultant> = { ...patch }
|
||||
if (patch.email !== undefined) {
|
||||
const email = normalizeEmail(patch.email)
|
||||
assertUniqueEmail(email, id)
|
||||
next.email = email
|
||||
}
|
||||
if (patch.firstName !== undefined) next.firstName = patch.firstName.trim()
|
||||
if (patch.lastName !== undefined) next.lastName = patch.lastName.trim()
|
||||
return updateRow('consultants', id, next)
|
||||
}
|
||||
|
||||
export function archiveConsultant(id: number): number {
|
||||
return updateRow('consultants', id, { archivedAt: new Date().toISOString() })
|
||||
}
|
||||
|
||||
export function unarchiveConsultant(id: number): number {
|
||||
return updateRow('consultants', id, { archivedAt: null as unknown as undefined })
|
||||
}
|
||||
|
||||
/**
|
||||
* Import in eine gewählte Zielgruppe. Abgleich nur über E-Mail.
|
||||
* moveIfDifferentGroup: bekannte Personen mit anderer Gruppe in die Zielgruppe verschieben.
|
||||
*/
|
||||
export function importConsultantsToGroup(
|
||||
groupId: number,
|
||||
rows: ConsultantImportRow[],
|
||||
moveIfDifferentGroup = true,
|
||||
): ConsultantImportResult {
|
||||
const group = getGroup(groupId)
|
||||
if (!group) throw new Error('Zielgruppe nicht gefunden.')
|
||||
|
||||
const result: ConsultantImportResult = { created: 0, updated: 0, moved: 0, skipped: 0, errors: [] }
|
||||
const seenInFile = new Set<string>()
|
||||
|
||||
for (let i = 0; i < rows.length; i++) {
|
||||
const row = rows[i]!
|
||||
const line = i + 1
|
||||
const email = normalizeEmail(row.email ?? '')
|
||||
const firstName = (row.firstName ?? '').trim()
|
||||
const lastName = (row.lastName ?? '').trim()
|
||||
|
||||
if (!email) {
|
||||
result.errors.push(`Zeile ${line}: E-Mail fehlt`)
|
||||
result.skipped++
|
||||
continue
|
||||
}
|
||||
if (!firstName || !lastName) {
|
||||
result.errors.push(`Zeile ${line}: Name unvollständig (${email})`)
|
||||
result.skipped++
|
||||
continue
|
||||
}
|
||||
if (seenInFile.has(email)) {
|
||||
result.errors.push(`Zeile ${line}: doppelte E-Mail in Datei (${email})`)
|
||||
result.skipped++
|
||||
continue
|
||||
}
|
||||
seenInFile.add(email)
|
||||
|
||||
const existing = findConsultantByEmail(email)
|
||||
if (!existing?.id) {
|
||||
insertRow('consultants', { groupId, firstName, lastName, email })
|
||||
result.created++
|
||||
continue
|
||||
}
|
||||
|
||||
const patch: Partial<Consultant> = { firstName, lastName }
|
||||
if (existing.groupId !== groupId) {
|
||||
if (moveIfDifferentGroup) {
|
||||
patch.groupId = groupId
|
||||
result.moved++
|
||||
}
|
||||
}
|
||||
updateRow('consultants', existing.id, patch)
|
||||
result.updated++
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
/** Feedback + personenbezogene Meeting-Daten weg; Assignment bleibt, Person wird entkoppelt. */
|
||||
export function hardDeleteConsultant(id: number): HardDeleteConsultantResult {
|
||||
const person = getConsultant(id)
|
||||
if (!person) throw new Error('Person nicht gefunden.')
|
||||
|
||||
const feedbacks = getAllRows<AssignmentFeedback>('assignmentFeedbacks').filter(f => f.instituteeId === id)
|
||||
const feedbackIds = feedbacks.map(f => f.id!).filter(Boolean)
|
||||
if (feedbackIds.length) {
|
||||
deleteRowsWhereIn('feedbackCategoryRatings', 'assignmentFeedbackId', feedbackIds)
|
||||
deleteRowsWhereIn('feedbackDimensionTexts', 'assignmentFeedbackId', feedbackIds)
|
||||
deleteRowsWhereIn('feedbackCategoryTexts', 'assignmentFeedbackId', feedbackIds)
|
||||
}
|
||||
deleteRowsWhereEquals('assignmentFeedbacks', 'instituteeId', id)
|
||||
deleteRowsWhereEquals('feedbackDrafts', 'instituteeId', id)
|
||||
|
||||
const entries = getAllRows<ConversationEntry>('conversationEntries').filter(e => e.instituteeId === id)
|
||||
const entryIds = entries.map(e => e.id!).filter(Boolean)
|
||||
if (entryIds.length) {
|
||||
deleteRowsWhereIn('conversationSkillScores', 'conversationEntryId', entryIds)
|
||||
}
|
||||
deleteRowsWhereEquals('conversationEntries', 'instituteeId', id)
|
||||
deleteRowsWhereEquals('assessments', 'instituteeId', id)
|
||||
deleteRowsWhereEquals('meetingCategoryRatings', 'instituteeId', id)
|
||||
deleteRowsWhereEquals('checklistResponses', 'instituteeId', id)
|
||||
|
||||
const emptiedAssignmentIds: number[] = []
|
||||
let assignmentsTouched = 0
|
||||
const assignments = getAllRows<Assignment>('assignments')
|
||||
for (const a of assignments) {
|
||||
if (!a.id || !a.instituteeIds.includes(id)) continue
|
||||
assignmentsTouched++
|
||||
const instituteeIds = a.instituteeIds.filter(x => x !== id)
|
||||
const instituteeEnrollments = (a.instituteeEnrollments ?? []).filter(e => e.instituteeId !== id)
|
||||
updateRow('assignments', a.id, { instituteeIds, instituteeEnrollments })
|
||||
if (instituteeIds.length === 0) emptiedAssignmentIds.push(a.id)
|
||||
}
|
||||
|
||||
deleteRowById('consultants', id)
|
||||
return {
|
||||
emptiedAssignmentIds,
|
||||
feedbacksDeleted: feedbacks.length,
|
||||
assignmentsTouched,
|
||||
}
|
||||
}
|
||||
|
||||
/** @deprecated — nutze hardDeleteConsultant; bleibt als Alias für alte Client-Aufrufe. */
|
||||
export function deleteConsultant(id: number): void {
|
||||
hardDeleteConsultant(id)
|
||||
}
|
||||
|
||||
export function getConsultantDetail(id: number): ConsultantDetail | undefined {
|
||||
const consultant = getConsultant(id)
|
||||
if (!consultant) return undefined
|
||||
|
||||
const group = getGroup(consultant.groupId)
|
||||
const types = getAllRows<{ id?: number; name: string }>('assignmentTypes')
|
||||
const typeMap = new Map(types.map(t => [t.id!, t.name]))
|
||||
const categories = getAllRows<FeedbackCategory>('feedbackCategories')
|
||||
const catMap = new Map(categories.map(c => [c.id!, c.name]))
|
||||
const allFeedbacks = getAllRows<AssignmentFeedback>('assignmentFeedbacks')
|
||||
const allRatings = getAllRows<FeedbackCategoryRating>('feedbackCategoryRatings')
|
||||
|
||||
const assignments = getAllRows<Assignment>('assignments')
|
||||
.filter(a => a.instituteeIds.includes(id))
|
||||
.map(a => {
|
||||
const fb = allFeedbacks.find(f => f.assignmentId === a.id && f.instituteeId === id)
|
||||
const ratings = fb?.id
|
||||
? allRatings
|
||||
.filter(r => r.assignmentFeedbackId === fb.id)
|
||||
.map(r => ({
|
||||
categoryId: r.feedbackCategoryId,
|
||||
categoryName: catMap.get(r.feedbackCategoryId) ?? `Kategorie ${r.feedbackCategoryId}`,
|
||||
rating: (r.rating ?? null) as RatingScore | null,
|
||||
}))
|
||||
: []
|
||||
return {
|
||||
assignmentId: a.id!,
|
||||
title: a.title,
|
||||
assignmentNumber: a.assignmentNumber,
|
||||
client: a.client,
|
||||
status: a.status,
|
||||
deletedAt: a.deletedAt,
|
||||
archivedAt: a.archivedAt,
|
||||
plannedStart: a.plannedStart,
|
||||
plannedEnd: a.plannedEnd,
|
||||
createdAt: a.createdAt,
|
||||
typeName: typeMap.get(a.assignmentTypeId) ?? '—',
|
||||
feedbackStatus: (!fb ? 'none' : fb.status === 'final' ? 'final' : 'draft') as 'none' | 'draft' | 'final',
|
||||
categoryRatings: ratings,
|
||||
}
|
||||
})
|
||||
.sort((a, b) => {
|
||||
const ae = a.plannedEnd ?? a.createdAt
|
||||
const be = b.plannedEnd ?? b.createdAt
|
||||
return be.localeCompare(ae)
|
||||
})
|
||||
|
||||
return { consultant, group, assignments }
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
/**
|
||||
* Starter-Paket: nur Konfigurations-/Strukturdaten für Team-Verteilung.
|
||||
* Keine Personen-, Assignment- oder Meeting-Daten (GDPR).
|
||||
* Produktiv (`AssigmentMonitor`) wird nie angefasst — Skripte nutzen dieselben Pfad-Guards.
|
||||
*/
|
||||
import { writeFileSync, readFileSync, mkdirSync, existsSync } from 'node:fs'
|
||||
import { dirname, join, resolve, sep } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { TABLE_DEFINITIONS, TABLE_NAMES } from './tableRegistry'
|
||||
import { getAllRows, insertRowWithId } from './crud'
|
||||
import { db } from '../database'
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url))
|
||||
export const PROJECT_ROOT = resolve(join(__dirname, '../..'))
|
||||
export const STARTER_DIR = join(PROJECT_ROOT, 'docs', 'starter')
|
||||
export const STARTER_FILE = join(STARTER_DIR, 'starter-structure.json')
|
||||
|
||||
/** Tabellen mit Stammdaten / Config — IDs bleiben stabil (FK zwischen Struktur-Tabellen). */
|
||||
export const STARTER_STRUCTURE_TABLES = [
|
||||
'feedbackDimensions',
|
||||
'feedbackCategories',
|
||||
'feedbackCriterionItems',
|
||||
'feedbackDimensionPrompts',
|
||||
'assignmentTypes',
|
||||
'phaseTemplates',
|
||||
'checklistItemDefs',
|
||||
'appSettings',
|
||||
'criterionLevelDescriptions',
|
||||
] as const
|
||||
|
||||
const STRUCTURE_SET = new Set<string>(STARTER_STRUCTURE_TABLES)
|
||||
|
||||
export interface StarterPackage {
|
||||
kind: 'assignment-monitor-starter'
|
||||
version: 1
|
||||
exportedAt: string
|
||||
note: string
|
||||
tables: Record<string, Array<Record<string, unknown>>>
|
||||
}
|
||||
|
||||
/** Verweigert jeden Pfad außerhalb V2 und jeden Produktiv-DB-Pfad. */
|
||||
export function assertV2DevOnly(resolvedPath: string, label: string): void {
|
||||
const pathNorm = resolvedPath.toLowerCase()
|
||||
const rootNorm = PROJECT_ROOT.toLowerCase()
|
||||
const rootPrefix = rootNorm.endsWith(sep) ? rootNorm : rootNorm + sep
|
||||
|
||||
if (!pathNorm.startsWith(rootPrefix) && pathNorm !== rootNorm) {
|
||||
throw new Error(`[${label}] SAFETY: Pfad außerhalb AssignmentMonitorV2:\n ${resolvedPath}`)
|
||||
}
|
||||
if (
|
||||
/[/\\]assigmentmonitor[/\\]/.test(pathNorm) &&
|
||||
!/[/\\]assigmentmonitorv2[/\\]/.test(pathNorm)
|
||||
) {
|
||||
throw new Error(`[${label}] SAFETY: Produktiv-Pfad blockiert:\n ${resolvedPath}`)
|
||||
}
|
||||
}
|
||||
|
||||
export function assertStarterEnv(): void {
|
||||
const apiPort = process.env.API_PORT?.trim() || '4001'
|
||||
const vitePort = process.env.PORT?.trim() || '5174'
|
||||
const sqliteFilename = process.env.SQLITE_FILENAME?.trim() || 'assignment-monitor-v2-dev.sqlite3'
|
||||
|
||||
if (apiPort === '4000') {
|
||||
throw new Error('[starter] SAFETY: API_PORT=4000 ist der Produktiv-Port — abgebrochen.')
|
||||
}
|
||||
if (vitePort === '5173') {
|
||||
throw new Error('[starter] SAFETY: PORT=5173 ist der Produktiv-Port — abgebrochen.')
|
||||
}
|
||||
if (sqliteFilename === 'assignment-monitor.sqlite3') {
|
||||
throw new Error('[starter] SAFETY: Produktiv-DB-Dateiname blockiert.')
|
||||
}
|
||||
if (sqliteFilename.includes('/') || sqliteFilename.includes('\\') || sqliteFilename.includes('..')) {
|
||||
throw new Error(`[starter] SAFETY: SQLITE_FILENAME ungültig: "${sqliteFilename}"`)
|
||||
}
|
||||
}
|
||||
|
||||
function sanitizeStructureRow(tableName: string, row: Record<string, unknown>): Record<string, unknown> {
|
||||
const copy = { ...row }
|
||||
// Destillierte Muster stammen aus echten Protokollen — nicht mitverteilen.
|
||||
if (tableName === 'feedbackCriterionItems' && 'learnedPatternHints' in copy) {
|
||||
copy.learnedPatternHints = null
|
||||
}
|
||||
return copy
|
||||
}
|
||||
|
||||
/** Liest Struktur aus der aktuellen V2-Dev-DB (leere Laufzeit-Tabellen im Payload). */
|
||||
export function buildStarterPackageFromDb(): StarterPackage {
|
||||
assertStarterEnv()
|
||||
assertV2DevOnly(PROJECT_ROOT, 'starter:export')
|
||||
|
||||
const tables: Record<string, Array<Record<string, unknown>>> = {}
|
||||
for (const name of TABLE_NAMES) {
|
||||
if (STRUCTURE_SET.has(name)) {
|
||||
tables[name] = getAllRows<Record<string, unknown>>(name).map(r => sanitizeStructureRow(name, r))
|
||||
} else {
|
||||
tables[name] = []
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
kind: 'assignment-monitor-starter',
|
||||
version: 1,
|
||||
exportedAt: new Date().toISOString(),
|
||||
note: 'Nur Struktur/Config — keine Personen, Assignments oder Meetings. Nur für AssignmentMonitorV2.',
|
||||
tables,
|
||||
}
|
||||
}
|
||||
|
||||
export function writeStarterPackage(pkg: StarterPackage, targetPath = STARTER_FILE): string {
|
||||
assertV2DevOnly(targetPath, 'starter:export')
|
||||
mkdirSync(dirname(targetPath), { recursive: true })
|
||||
writeFileSync(targetPath, JSON.stringify(pkg, null, 2), 'utf8')
|
||||
return targetPath
|
||||
}
|
||||
|
||||
export function readStarterPackage(sourcePath = STARTER_FILE): StarterPackage {
|
||||
assertV2DevOnly(sourcePath, 'starter:import')
|
||||
if (!existsSync(sourcePath)) {
|
||||
throw new Error(`[starter] Datei fehlt: ${sourcePath}`)
|
||||
}
|
||||
const raw = JSON.parse(readFileSync(sourcePath, 'utf8')) as StarterPackage
|
||||
if (raw.kind !== 'assignment-monitor-starter' || raw.version !== 1 || !raw.tables) {
|
||||
throw new Error('[starter] Ungültiges Starter-Paket (kind/version/tables).')
|
||||
}
|
||||
return raw
|
||||
}
|
||||
|
||||
/**
|
||||
* Ersetzt den kompletten DB-Inhalt durch das Starter-Paket (Struktur befüllt, Rest leer).
|
||||
* Absichtlich voller Wipe — für frische Team-Installationen.
|
||||
*/
|
||||
export function importStarterPackage(pkg: StarterPackage): { structureRows: number } {
|
||||
assertStarterEnv()
|
||||
assertV2DevOnly(PROJECT_ROOT, 'starter:import')
|
||||
|
||||
let structureRows = 0
|
||||
db.exec('BEGIN')
|
||||
try {
|
||||
for (const table of TABLE_DEFINITIONS) {
|
||||
db.prepare(`DELETE FROM "${table.name}"`).run()
|
||||
}
|
||||
for (const table of TABLE_DEFINITIONS) {
|
||||
const rows = pkg.tables[table.name] ?? []
|
||||
for (const row of rows) {
|
||||
const { id, ...rest } = row
|
||||
if (typeof id !== 'number') continue
|
||||
insertRowWithId(table.name, id, sanitizeStructureRow(table.name, rest))
|
||||
if (STRUCTURE_SET.has(table.name)) structureRows++
|
||||
}
|
||||
}
|
||||
db.exec('COMMIT')
|
||||
} catch (err) {
|
||||
db.exec('ROLLBACK')
|
||||
throw err
|
||||
}
|
||||
return { structureRows }
|
||||
}
|
||||
|
||||
export function summarizeStarter(pkg: StarterPackage): Record<string, number> {
|
||||
const counts: Record<string, number> = {}
|
||||
for (const name of STARTER_STRUCTURE_TABLES) {
|
||||
counts[name] = pkg.tables[name]?.length ?? 0
|
||||
}
|
||||
return counts
|
||||
}
|
||||
@@ -40,6 +40,7 @@ export const TABLE_DEFINITIONS: TableDef[] = [
|
||||
col('name', 'TEXT'),
|
||||
col('defaultPhaseKeys', 'TEXT', 'json'),
|
||||
col('criteriaIds', 'TEXT', 'json'),
|
||||
col('color', 'TEXT'),
|
||||
]},
|
||||
{ name: 'phaseTemplates', columns: [
|
||||
col('assignmentTypeId', 'INTEGER'),
|
||||
@@ -61,6 +62,8 @@ export const TABLE_DEFINITIONS: TableDef[] = [
|
||||
col('groupId', 'INTEGER'),
|
||||
col('firstName', 'TEXT'),
|
||||
col('lastName', 'TEXT'),
|
||||
col('email', 'TEXT'),
|
||||
col('archivedAt', 'TEXT'),
|
||||
]},
|
||||
{ name: 'assignments', columns: [
|
||||
col('title', 'TEXT'),
|
||||
@@ -75,6 +78,8 @@ export const TABLE_DEFINITIONS: TableDef[] = [
|
||||
col('instituteeEnrollments', 'TEXT', 'json'),
|
||||
col('deletedAt', 'TEXT'),
|
||||
col('archivedAt', 'TEXT'),
|
||||
col('plannedStart', 'TEXT'),
|
||||
col('plannedEnd', 'TEXT'),
|
||||
]},
|
||||
{ name: 'meetingInstances', columns: [
|
||||
col('assignmentId', 'INTEGER'),
|
||||
@@ -107,6 +112,7 @@ export const TABLE_DEFINITIONS: TableDef[] = [
|
||||
col('score', 'INTEGER'),
|
||||
col('note', 'TEXT'),
|
||||
col('updatedAt', 'TEXT'),
|
||||
col('scoreNeedsReview', 'INTEGER', 'bool'),
|
||||
]},
|
||||
{ name: 'meetingCategoryRatings', columns: [
|
||||
col('meetingInstanceId', 'INTEGER'),
|
||||
@@ -185,7 +191,9 @@ export const TABLE_DEFINITIONS: TableDef[] = [
|
||||
col('defaultDimensionPromptTemplate', 'TEXT'),
|
||||
col('defaultCategoryPromptTemplate', 'TEXT'),
|
||||
col('criterionTaggingPromptTemplate', 'TEXT'),
|
||||
col('checklistTaggingPromptTemplate', 'TEXT'),
|
||||
col('ratingColorBands', 'TEXT', 'json'),
|
||||
col('requirePlannedDates', 'INTEGER', 'bool'),
|
||||
]},
|
||||
{ name: 'checklistItemDefs', columns: [
|
||||
col('phaseTemplateId', 'INTEGER'),
|
||||
@@ -193,6 +201,7 @@ export const TABLE_DEFINITIONS: TableDef[] = [
|
||||
col('linkedCriterionItemId', 'INTEGER'),
|
||||
col('scope', 'TEXT'),
|
||||
col('order', 'INTEGER'),
|
||||
col('scoreContribution', 'TEXT'),
|
||||
]},
|
||||
{ name: 'checklistResponses', columns: [
|
||||
col('meetingInstanceId', 'INTEGER'),
|
||||
@@ -201,6 +210,7 @@ export const TABLE_DEFINITIONS: TableDef[] = [
|
||||
col('rating', 'INTEGER'),
|
||||
col('note', 'TEXT'),
|
||||
col('criterionItemId', 'INTEGER'),
|
||||
col('criterionOverride', 'INTEGER', 'bool'),
|
||||
]},
|
||||
]
|
||||
|
||||
|
||||
Reference in new issue
Block a user