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'),
|
||||
]},
|
||||
]
|
||||
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
import express from 'express'
|
||||
import { existsSync } from 'node:fs'
|
||||
import './database'
|
||||
import { getAllRows } from './db/crud'
|
||||
import { rpcModules } from './rpcModules'
|
||||
import {
|
||||
STARTER_FILE,
|
||||
readStarterPackage,
|
||||
importStarterPackage,
|
||||
summarizeStarter,
|
||||
} from './db/starterPackage'
|
||||
|
||||
const app = express()
|
||||
app.use(express.json({ limit: '50mb' })) // Backup-Import kann alle Tabellen als ein JSON-Body enthalten
|
||||
@@ -32,6 +40,30 @@ if (!Number.isFinite(port) || port === 4000) {
|
||||
)
|
||||
}
|
||||
|
||||
/** Team-ZIP: leere DB automatisch mit Struktur befüllen (keine Meetings/Personen). */
|
||||
function seedStarterIfEmpty(): void {
|
||||
const dims = getAllRows('feedbackDimensions')
|
||||
if (dims.length > 0) return
|
||||
if (!existsSync(STARTER_FILE)) {
|
||||
console.warn('[server] DB ohne Feedback-Struktur und ohne Starter-Paket — Config bleibt leer.')
|
||||
return
|
||||
}
|
||||
try {
|
||||
const pkg = readStarterPackage()
|
||||
const { structureRows } = importStarterPackage(pkg)
|
||||
const counts = summarizeStarter(pkg)
|
||||
console.log(`[server] Starter-Struktur automatisch geladen (${structureRows} Zeilen).`)
|
||||
console.log(
|
||||
`[server] Dimensionen=${counts.feedbackDimensions} Kategorien=${counts.feedbackCategories} ` +
|
||||
`Kriterien=${counts.feedbackCriterionItems} Typen=${counts.assignmentTypes}`,
|
||||
)
|
||||
} catch (err) {
|
||||
console.warn('[server] Auto-Seed fehlgeschlagen:', err instanceof Error ? err.message : err)
|
||||
}
|
||||
}
|
||||
|
||||
seedStarterIfEmpty()
|
||||
|
||||
app.listen(port, () => {
|
||||
console.log(`[server] DEV-RPC-API (AssignmentMonitorV2) auf http://localhost:${port}/api/rpc`)
|
||||
console.log(`[server] Produktiv (AssigmentMonitor) nutzt Port 4000 — diese Instanz ist davon getrennt.`)
|
||||
|
||||
@@ -11,6 +11,7 @@ import * as assessments from './db/queries/assessments'
|
||||
import * as assignmentFeedback from './db/queries/assignmentFeedback'
|
||||
import * as meetingCategoryRatings from './db/queries/meetingCategoryRatings'
|
||||
import * as backup from './db/queries/backup'
|
||||
import * as assignmentTransfer from './db/queries/assignmentTransfer'
|
||||
|
||||
const modules = {
|
||||
appSettings,
|
||||
@@ -26,6 +27,7 @@ const modules = {
|
||||
assignmentFeedback,
|
||||
meetingCategoryRatings,
|
||||
backup,
|
||||
assignmentTransfer,
|
||||
}
|
||||
|
||||
export type RpcModuleName = keyof typeof modules
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* Spielt docs/starter/starter-structure.json in die V2-Dev-DB ein (voller Wipe).
|
||||
* Usage: npm run bootstrap -- --yes
|
||||
* Ohne --yes / CONFIRM=1: Abbruch (Schutz vor versehentlichem Löschen).
|
||||
* Produktiv-Ports/DB-Namen werden blockiert.
|
||||
*/
|
||||
const args = new Set(process.argv.slice(2))
|
||||
const confirmed = args.has('--yes') || args.has('-y') || process.env.CONFIRM === '1'
|
||||
|
||||
if (!confirmed) {
|
||||
console.error('[bootstrap] Abbruch: würde die V2-Dev-DB komplett ersetzen.')
|
||||
console.error('[bootstrap] Zum Bestätigen: npm run bootstrap -- --yes')
|
||||
console.error('[bootstrap] Quelle: docs/starter/starter-structure.json')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const {
|
||||
readStarterPackage,
|
||||
importStarterPackage,
|
||||
summarizeStarter,
|
||||
STARTER_FILE,
|
||||
} = await import('../db/starterPackage')
|
||||
|
||||
const pkg = readStarterPackage()
|
||||
const counts = summarizeStarter(pkg)
|
||||
const { structureRows } = importStarterPackage(pkg)
|
||||
|
||||
console.log(`[bootstrap] Starter eingespielt (${structureRows} Struktur-Zeilen).`)
|
||||
console.log(`[bootstrap] Quelle: ${STARTER_FILE} (${pkg.exportedAt})`)
|
||||
for (const [table, n] of Object.entries(counts)) {
|
||||
if (n > 0) console.log(` ${table}: ${n}`)
|
||||
}
|
||||
console.log('[bootstrap] Keine Personen-/Meeting-Daten. API-Key lokal unter Config → KI setzen.')
|
||||
console.log('[bootstrap] Start: npm run dev:all → http://localhost:5174')
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* Exportiert Struktur/Config aus der V2-Dev-DB nach docs/starter/starter-structure.json.
|
||||
* Usage: npm run starter:export
|
||||
* Produktiv wird per Guard blockiert.
|
||||
*/
|
||||
import {
|
||||
buildStarterPackageFromDb,
|
||||
writeStarterPackage,
|
||||
summarizeStarter,
|
||||
STARTER_FILE,
|
||||
} from '../db/starterPackage'
|
||||
|
||||
const pkg = buildStarterPackageFromDb()
|
||||
const path = writeStarterPackage(pkg)
|
||||
const counts = summarizeStarter(pkg)
|
||||
|
||||
console.log(`[starter:export] geschrieben: ${path}`)
|
||||
console.log(`[starter:export] Stand: ${pkg.exportedAt}`)
|
||||
for (const [table, n] of Object.entries(counts)) {
|
||||
if (n > 0) console.log(` ${table}: ${n}`)
|
||||
}
|
||||
console.log(`[starter:export] Ziel: ${STARTER_FILE}`)
|
||||
@@ -0,0 +1,158 @@
|
||||
/**
|
||||
* Laptop-Umzug: Code + komplette V2-Dev-SQLite (ohne node_modules, .env).
|
||||
* Enthält personenbezogene Daten — nur an sich selbst / den Ziel-Laptop schicken.
|
||||
*
|
||||
* Usage: npm run pack:laptop
|
||||
*/
|
||||
import { mkdirSync, existsSync, rmSync, readFileSync, copyFileSync, writeFileSync } from 'node:fs'
|
||||
import { dirname, join, resolve, relative } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { execFileSync } from 'node:child_process'
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url))
|
||||
const projectRoot = resolve(join(__dirname, '../..'))
|
||||
const outDir = join(projectRoot, 'dist-release')
|
||||
const stamp = new Date().toISOString().slice(0, 10)
|
||||
const zipName = `AssignmentMonitor-Umzug-${stamp}.zip`
|
||||
const zipPath = join(outDir, zipName)
|
||||
const stageName = 'AssigmentMonitorV2'
|
||||
const stageRoot = join(outDir, '_stage-laptop', stageName)
|
||||
|
||||
const rootNorm = projectRoot.toLowerCase()
|
||||
if (!rootNorm.includes('assigmentmonitorv2')) {
|
||||
throw new Error('[pack:laptop] SAFETY: Skript nur innerhalb AssigmentMonitorV2 ausführen.')
|
||||
}
|
||||
|
||||
const sqliteFilename = process.env.SQLITE_FILENAME?.trim() || 'assignment-monitor-v2-dev.sqlite3'
|
||||
if (sqliteFilename.includes('/') || sqliteFilename.includes('\\') || sqliteFilename.includes('..')) {
|
||||
throw new Error(`[pack:laptop] SAFETY: SQLITE_FILENAME ungültig: "${sqliteFilename}"`)
|
||||
}
|
||||
if (sqliteFilename === 'assignment-monitor.sqlite3') {
|
||||
throw new Error('[pack:laptop] SAFETY: Produktiv-DB-Dateiname blockiert.')
|
||||
}
|
||||
|
||||
const dbPath = join(projectRoot, 'server', 'data', sqliteFilename)
|
||||
|
||||
const EXCLUDE_DIR_NAMES = new Set([
|
||||
'node_modules',
|
||||
'dist',
|
||||
'dist-release',
|
||||
'dist-ssr',
|
||||
'.vite',
|
||||
'.claude',
|
||||
'.vscode',
|
||||
'_quarantine',
|
||||
'_stage',
|
||||
'_stage-laptop',
|
||||
])
|
||||
|
||||
const EXCLUDE_FILE_NAMES = new Set([
|
||||
'.env',
|
||||
'.env.local',
|
||||
'dist-release-log.txt',
|
||||
])
|
||||
|
||||
function shouldSkip(absPath: string): boolean {
|
||||
const rel = relative(projectRoot, absPath).split(/[/\\]/).join('/')
|
||||
if (!rel || rel.startsWith('..')) return true
|
||||
if (rel === 'server/data' || rel.startsWith('server/data/')) return true
|
||||
if (rel === 'dist-release' || rel.startsWith('dist-release/')) return true
|
||||
const parts = rel.split('/')
|
||||
if (parts.some(p => EXCLUDE_DIR_NAMES.has(p) || p.startsWith('_quarantine'))) return true
|
||||
const base = parts[parts.length - 1] ?? ''
|
||||
if (EXCLUDE_FILE_NAMES.has(base)) return true
|
||||
if (base.endsWith('.tsbuildinfo')) return true
|
||||
if (base.startsWith('.env.') && base.endsWith('.local')) return true
|
||||
if (base.endsWith('.bak')) return true
|
||||
return false
|
||||
}
|
||||
|
||||
async function copyTree(srcDir: string, destDir: string): Promise<number> {
|
||||
const { readdirSync, statSync, mkdirSync: mkdir, copyFileSync: cp } = await import('node:fs')
|
||||
let count = 0
|
||||
mkdir(destDir, { recursive: true })
|
||||
for (const name of readdirSync(srcDir)) {
|
||||
const src = join(srcDir, name)
|
||||
if (shouldSkip(src)) continue
|
||||
const dest = join(destDir, name)
|
||||
const st = statSync(src)
|
||||
if (st.isDirectory()) {
|
||||
count += await copyTree(src, dest)
|
||||
} else if (st.isFile()) {
|
||||
cp(src, dest)
|
||||
count++
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
function zipWithPowerShell(sourceFolder: string, targetZip: string): void {
|
||||
const parent = dirname(sourceFolder)
|
||||
const leaf = sourceFolder.split(/[/\\]/).pop()
|
||||
const ps = `
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if (Test-Path -LiteralPath '${targetZip.replace(/'/g, "''")}') { Remove-Item -LiteralPath '${targetZip.replace(/'/g, "''")}' -Force }
|
||||
Compress-Archive -Path (Join-Path '${parent.replace(/'/g, "''")}' '${leaf}') -DestinationPath '${targetZip.replace(/'/g, "''")}' -CompressionLevel Optimal
|
||||
`
|
||||
execFileSync('powershell.exe', ['-NoProfile', '-Command', ps], { stdio: 'inherit' })
|
||||
}
|
||||
|
||||
if (!existsSync(dbPath)) {
|
||||
throw new Error(
|
||||
`[pack:laptop] Datenbank fehlt: ${dbPath}\n` +
|
||||
'Ohne SQLite wäre das nur ein Team-Paket — zuerst die App einmal starten oder pack:zip nutzen.',
|
||||
)
|
||||
}
|
||||
|
||||
mkdirSync(outDir, { recursive: true })
|
||||
const stageParent = join(outDir, '_stage-laptop')
|
||||
if (existsSync(stageParent)) rmSync(stageParent, { recursive: true, force: true })
|
||||
mkdirSync(stageRoot, { recursive: true })
|
||||
|
||||
console.log('[pack:laptop] Kopiere Projektdateien (ohne node_modules, .env; inkl. .git) …')
|
||||
const files = await copyTree(projectRoot, stageRoot)
|
||||
console.log(`[pack:laptop] ${files} Dateien → Staging`)
|
||||
|
||||
const stageDataDir = join(stageRoot, 'server', 'data')
|
||||
mkdirSync(stageDataDir, { recursive: true })
|
||||
copyFileSync(dbPath, join(stageDataDir, sqliteFilename))
|
||||
let extraDbFiles = 0
|
||||
for (const suffix of ['-wal', '-shm']) {
|
||||
const extra = `${dbPath}${suffix}`
|
||||
if (existsSync(extra)) {
|
||||
copyFileSync(extra, join(stageDataDir, `${sqliteFilename}${suffix}`))
|
||||
extraDbFiles++
|
||||
}
|
||||
}
|
||||
writeFileSync(
|
||||
join(stageDataDir, 'README.txt'),
|
||||
[
|
||||
'Diese SQLite-Datei ist die vollständige lokale Datenbank (Personen, Assignments, Meetings).',
|
||||
`Datei: ${sqliteFilename}`,
|
||||
'Nach dem Entpacken NICHT npm run setup / bootstrap / db:reset ausführen.',
|
||||
'',
|
||||
].join('\n'),
|
||||
'utf8',
|
||||
)
|
||||
console.log(`[pack:laptop] DB kopiert: ${sqliteFilename}${extraDbFiles ? ` (+${extraDbFiles} WAL/SHM)` : ''}`)
|
||||
|
||||
if (!existsSync(join(stageRoot, 'UMZUG.md'))) {
|
||||
throw new Error('[pack:laptop] UMZUG.md fehlt im Staging — Abbruch.')
|
||||
}
|
||||
if (!existsSync(join(stageRoot, '.env.example'))) {
|
||||
throw new Error('[pack:laptop] .env.example fehlt')
|
||||
}
|
||||
if (!existsSync(join(stageRoot, 'server', 'data', sqliteFilename))) {
|
||||
throw new Error('[pack:laptop] DB landete nicht im Staging — Abbruch.')
|
||||
}
|
||||
|
||||
console.log(`[pack:laptop] Erzeuge ${zipName} …`)
|
||||
zipWithPowerShell(stageRoot, zipPath)
|
||||
rmSync(stageParent, { recursive: true, force: true })
|
||||
|
||||
const sizeMb = (readFileSync(zipPath).byteLength / (1024 * 1024)).toFixed(2)
|
||||
console.log(`[pack:laptop] Fertig: ${zipPath}`)
|
||||
console.log(`[pack:laptop] Größe: ${sizeMb} MB (E-Mail-tauglich, solange unter dem Postfach-Limit)`)
|
||||
console.log('[pack:laptop] Enthält personenbezogene Daten — nur an den Ziel-Laptop schicken.')
|
||||
console.log('[pack:laptop] Am Ziel: UMZUG.md folgen. Nicht npm run setup.')
|
||||
console.log('[pack:laptop] Produktiv (AssigmentMonitor) wurde nicht angefasst.')
|
||||
@@ -0,0 +1,120 @@
|
||||
/**
|
||||
* Erzeugt ein versandfertiges ZIP der V2-Team-Version (ohne node_modules, .env, Dev-DB, .git).
|
||||
* Schreibt nach dist-release/ — Ordner ist gitignored; Produktiv wird nicht angefasst.
|
||||
*
|
||||
* Usage: npm run pack:zip
|
||||
*/
|
||||
import { mkdirSync, existsSync, rmSync, readFileSync } from 'node:fs'
|
||||
import { dirname, join, resolve, relative } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { execFileSync } from 'node:child_process'
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url))
|
||||
const projectRoot = resolve(join(__dirname, '../..'))
|
||||
const outDir = join(projectRoot, 'dist-release')
|
||||
const stamp = new Date().toISOString().slice(0, 10)
|
||||
const zipName = `AssignmentMonitor-Team-${stamp}.zip`
|
||||
const zipPath = join(outDir, zipName)
|
||||
const stageName = 'AssigmentMonitorV2'
|
||||
const stageRoot = join(outDir, '_stage', stageName)
|
||||
|
||||
const rootNorm = projectRoot.toLowerCase()
|
||||
if (!rootNorm.includes('assigmentmonitorv2')) {
|
||||
throw new Error('[pack:zip] SAFETY: Skript nur innerhalb AssigmentMonitorV2 ausführen.')
|
||||
}
|
||||
|
||||
const EXCLUDE_DIR_NAMES = new Set([
|
||||
'node_modules',
|
||||
'.git',
|
||||
'dist',
|
||||
'dist-release',
|
||||
'dist-ssr',
|
||||
'.vite',
|
||||
'.claude',
|
||||
'.vscode',
|
||||
'server\\data',
|
||||
'server/data',
|
||||
'_quarantine',
|
||||
'_stage',
|
||||
])
|
||||
|
||||
const EXCLUDE_FILE_NAMES = new Set([
|
||||
'.env',
|
||||
'.env.local',
|
||||
'dist-release-log.txt',
|
||||
])
|
||||
|
||||
function shouldSkip(absPath: string): boolean {
|
||||
const rel = relative(projectRoot, absPath).split(/[/\\]/).join('/')
|
||||
if (!rel || rel.startsWith('..')) return true
|
||||
if (rel === 'server/data' || rel.startsWith('server/data/')) return true
|
||||
if (rel === 'dist-release' || rel.startsWith('dist-release/')) return true
|
||||
const parts = rel.split('/')
|
||||
if (parts.some(p => EXCLUDE_DIR_NAMES.has(p) || p.startsWith('_quarantine'))) return true
|
||||
const base = parts[parts.length - 1] ?? ''
|
||||
if (EXCLUDE_FILE_NAMES.has(base)) return true
|
||||
if (base.endsWith('.tsbuildinfo')) return true
|
||||
if (base.startsWith('.env.') && base.endsWith('.local')) return true
|
||||
return false
|
||||
}
|
||||
|
||||
async function copyTree(srcDir: string, destDir: string): Promise<number> {
|
||||
const { readdirSync, statSync, mkdirSync: mkdir, copyFileSync: cp } = await import('node:fs')
|
||||
let count = 0
|
||||
mkdir(destDir, { recursive: true })
|
||||
for (const name of readdirSync(srcDir)) {
|
||||
const src = join(srcDir, name)
|
||||
if (shouldSkip(src)) continue
|
||||
const dest = join(destDir, name)
|
||||
const st = statSync(src)
|
||||
if (st.isDirectory()) {
|
||||
count += await copyTree(src, dest)
|
||||
} else if (st.isFile()) {
|
||||
cp(src, dest)
|
||||
count++
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
function zipWithPowerShell(sourceFolder: string, targetZip: string): void {
|
||||
// Compress-Archive braucht den Inhalt so, dass der Root-Ordner im ZIP liegt
|
||||
const parent = dirname(sourceFolder)
|
||||
const leaf = sourceFolder.split(/[/\\]/).pop()
|
||||
const ps = `
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if (Test-Path -LiteralPath '${targetZip.replace(/'/g, "''")}') { Remove-Item -LiteralPath '${targetZip.replace(/'/g, "''")}' -Force }
|
||||
Compress-Archive -Path (Join-Path '${parent.replace(/'/g, "''")}' '${leaf}') -DestinationPath '${targetZip.replace(/'/g, "''")}' -CompressionLevel Optimal
|
||||
`
|
||||
execFileSync('powershell.exe', ['-NoProfile', '-Command', ps], { stdio: 'inherit' })
|
||||
}
|
||||
|
||||
mkdirSync(outDir, { recursive: true })
|
||||
const stageParent = join(outDir, '_stage')
|
||||
if (existsSync(stageParent)) rmSync(stageParent, { recursive: true, force: true })
|
||||
mkdirSync(stageRoot, { recursive: true })
|
||||
|
||||
console.log('[pack:zip] Kopiere Projektdateien (ohne DB, .env, node_modules, .git) …')
|
||||
const files = await copyTree(projectRoot, stageRoot)
|
||||
console.log(`[pack:zip] ${files} Dateien → Staging`)
|
||||
|
||||
// Sicherstellen, dass Einrichtungsdateien im Root der ZIP liegen
|
||||
if (!existsSync(join(stageRoot, 'EINRICHTUNG.md'))) {
|
||||
throw new Error('[pack:zip] EINRICHTUNG.md fehlt im Staging — Abbruch.')
|
||||
}
|
||||
if (!existsSync(join(stageRoot, 'docs', 'starter', 'starter-structure.json'))) {
|
||||
throw new Error('[pack:zip] starter-structure.json fehlt — zuerst npm run starter:export')
|
||||
}
|
||||
if (!existsSync(join(stageRoot, '.env.example'))) {
|
||||
throw new Error('[pack:zip] .env.example fehlt')
|
||||
}
|
||||
|
||||
console.log(`[pack:zip] Erzeuge ${zipName} …`)
|
||||
zipWithPowerShell(stageRoot, zipPath)
|
||||
rmSync(stageParent, { recursive: true, force: true })
|
||||
|
||||
const sizeMb = (readFileSync(zipPath).byteLength / (1024 * 1024)).toFixed(2)
|
||||
console.log(`[pack:zip] Fertig: ${zipPath}`)
|
||||
console.log(`[pack:zip] Größe: ${sizeMb} MB`)
|
||||
console.log('[pack:zip] An Kollegen: ZIP schicken + auf EINRICHTUNG.md verweisen.')
|
||||
console.log('[pack:zip] Produktiv (AssigmentMonitor) wurde nicht angefasst.')
|
||||
@@ -0,0 +1,124 @@
|
||||
/**
|
||||
* Automatisierter Smoke für C0 (Skala/Farbbänder) + C6/C7-Hilfslogik (Batches, Prompt-Größe).
|
||||
* Schreibt temporär Farbbänder in die V2-Dev-DB und stellt den vorherigen Stand wieder her.
|
||||
*
|
||||
* Aufruf: npm run smoke
|
||||
* Voraussetzung: .env mit V2-Ports/DB (wie npm run setup / server).
|
||||
*
|
||||
* Nur server-kompatible Imports (kein DOM/JSX) — siehe tsconfig.server.json.
|
||||
*/
|
||||
import '../database'
|
||||
import {
|
||||
DEFAULT_RATING_COLOR_BANDS,
|
||||
BAND_STYLES,
|
||||
bandForScore,
|
||||
normalizeRatingColorBands,
|
||||
normalizeRatingScore,
|
||||
resolveScoreStyle,
|
||||
AI_CONFIG,
|
||||
} from '../../src/config/constants'
|
||||
import { getOrSeedRatingColorBands, saveRatingColorBands } from '../db/queries/appSettings'
|
||||
import { buildCharAwareBatches, mergePatternHints } from '../../src/utils/charAwareBatches'
|
||||
import { checkPromptSize } from '../../src/utils/promptSize'
|
||||
|
||||
let failed = 0
|
||||
let passed = 0
|
||||
|
||||
function assert(cond: boolean, label: string, detail?: string) {
|
||||
if (cond) {
|
||||
console.log(`✅ ${label}`)
|
||||
passed++
|
||||
} else {
|
||||
console.log(`❌ ${label}${detail ? ` — ${detail}` : ''}`)
|
||||
failed++
|
||||
}
|
||||
}
|
||||
|
||||
console.log('=== Smoke: Skala 1–10 (C0) ===\n')
|
||||
|
||||
assert(normalizeRatingScore(7) === 7, 'normalizeRatingScore(7) → 7')
|
||||
assert(normalizeRatingScore(0) === null, 'normalizeRatingScore(0) → null')
|
||||
assert(normalizeRatingScore(11) === null, 'normalizeRatingScore(11) → null')
|
||||
assert(normalizeRatingScore('5') === 5, 'normalizeRatingScore("5") → 5')
|
||||
|
||||
const bands = normalizeRatingColorBands(DEFAULT_RATING_COLOR_BANDS)
|
||||
assert(bandForScore(1, bands).key === 'red', 'Score 1 → Band rot')
|
||||
assert(bandForScore(2, bands).key === 'red', 'Score 2 → Band rot')
|
||||
assert(bandForScore(3, bands).key === 'orange', 'Score 3 → Band orange')
|
||||
assert(bandForScore(5, bands).key === 'orange', 'Score 5 → Band orange')
|
||||
assert(bandForScore(6, bands).key === 'lightGreen', 'Score 6 → Band hellgrün')
|
||||
assert(bandForScore(8, bands).key === 'lightGreen', 'Score 8 → Band hellgrün')
|
||||
assert(bandForScore(9, bands).key === 'darkGreen', 'Score 9 → Band dunkelgrün')
|
||||
assert(bandForScore(10, bands).key === 'darkGreen', 'Score 10 → Band dunkelgrün')
|
||||
|
||||
assert(
|
||||
BAND_STYLES.lightGreen.color !== BAND_STYLES.darkGreen.color,
|
||||
'Hellgrün und Dunkelgrün haben unterscheidbare CSS-Klassen',
|
||||
)
|
||||
assert(
|
||||
BAND_STYLES.lightGreen.hex !== BAND_STYLES.darkGreen.hex,
|
||||
'Hellgrün und Dunkelgrün haben unterscheidbare Hex-Farben',
|
||||
)
|
||||
|
||||
const style6 = resolveScoreStyle(6, bands)
|
||||
const style9 = resolveScoreStyle(9, bands)
|
||||
assert(style6.color !== style9.color, 'resolveScoreStyle: 6 und 9 unterschiedliche Farben')
|
||||
|
||||
const previousBands = getOrSeedRatingColorBands()
|
||||
const probeBands = [
|
||||
{ max: 3, key: 'red' as const },
|
||||
{ max: 6, key: 'orange' as const },
|
||||
{ max: 8, key: 'lightGreen' as const },
|
||||
{ max: 10, key: 'darkGreen' as const },
|
||||
]
|
||||
saveRatingColorBands(probeBands)
|
||||
const reloaded = getOrSeedRatingColorBands()
|
||||
assert(
|
||||
JSON.stringify(reloaded) === JSON.stringify(normalizeRatingColorBands(probeBands)),
|
||||
'Farbbänder speichern/laden Roundtrip (DB)',
|
||||
`got ${JSON.stringify(reloaded)}`,
|
||||
)
|
||||
saveRatingColorBands(previousBands)
|
||||
const restored = getOrSeedRatingColorBands()
|
||||
assert(
|
||||
JSON.stringify(restored) === JSON.stringify(normalizeRatingColorBands(previousBands)),
|
||||
'Vorherige Farbbänder wiederhergestellt',
|
||||
)
|
||||
|
||||
console.log('\n=== Smoke: Tagging-Batches (C6) ===\n')
|
||||
|
||||
const manyShort = Array.from({ length: 25 }, (_, i) => `Zeile ${i + 1} kurz`)
|
||||
const byLines = buildCharAwareBatches(manyShort, s => s, 12, 50_000)
|
||||
assert(byLines.length === 3, `25 Zeilen / max 12 → 3 Batches (ist ${byLines.length})`)
|
||||
assert(byLines[0].length === 12 && byLines[1].length === 12 && byLines[2].length === 1, 'Batch-Größen 12+12+1')
|
||||
|
||||
const longA = 'a'.repeat(2000)
|
||||
const longB = 'b'.repeat(2000)
|
||||
const byChars = buildCharAwareBatches([longA, longB, 'kurz'], s => s, 12, 3500)
|
||||
assert(byChars.length === 2, `Zeichen-Budget → 2 Batches (ist ${byChars.length})`)
|
||||
assert(byChars[0].length === 1 && byChars[0][0] === longA, 'Erste lange Zeile allein im Batch')
|
||||
assert(byChars[1][0] === longB && byChars[1].includes('kurz'), 'Zweite lange Zeile + Kurzzeile im Folgebatch')
|
||||
|
||||
const oneHuge = ['x'.repeat(5000)]
|
||||
const alone = buildCharAwareBatches(oneHuge, s => s, 12, 3500)
|
||||
assert(alone.length === 1 && alone[0].length === 1, 'Überlanges Einzelstück → 1 Batch mit 1 Zeile')
|
||||
|
||||
const patterns = new Map<number, string>()
|
||||
mergePatternHints(patterns, new Map([[1, 'alt'], [2, 'zwei']]))
|
||||
mergePatternHints(patterns, new Map([[1, 'neu']]))
|
||||
assert(patterns.get(1) === 'neu' && patterns.get(2) === 'zwei', 'MUSTER-Merge: später überschreibt früher')
|
||||
|
||||
console.log('\n=== Smoke: Prompt-Größe (C7) ===\n')
|
||||
|
||||
const small = checkPromptSize('kurz')
|
||||
assert(!small.softWarn && !small.overHardLimit, 'Kleiner Prompt: kein Soft/Hard')
|
||||
|
||||
const soft = checkPromptSize('y'.repeat(AI_CONFIG.promptSoftWarnChars))
|
||||
assert(soft.softWarn && !soft.overHardLimit, 'Soft-Warn-Schwelle greift')
|
||||
|
||||
const hard = checkPromptSize('z'.repeat(AI_CONFIG.promptHardLimitChars))
|
||||
assert(hard.overHardLimit, 'Hard-Limit-Schwelle greift')
|
||||
|
||||
console.log(`\n=== Ergebnis: ${passed} pass, ${failed} fail ===`)
|
||||
if (failed > 0) process.exit(1)
|
||||
console.log('\nHinweis: UI-Teile → manuell in docs/SMOKE_TESTS.md')
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Einmal-Setup für Team-ZIP: Starter-Struktur in die V2-Dev-DB laden.
|
||||
* Usage: npm run setup
|
||||
*/
|
||||
import { existsSync, copyFileSync } from 'node:fs'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const rootPath = join(dirname(fileURLToPath(import.meta.url)), '../..')
|
||||
const envPath = join(rootPath, '.env')
|
||||
const examplePath = join(rootPath, '.env.example')
|
||||
if (!existsSync(envPath) && existsSync(examplePath)) {
|
||||
copyFileSync(examplePath, envPath)
|
||||
console.log('[setup] .env aus .env.example angelegt.')
|
||||
}
|
||||
|
||||
process.env.CONFIRM = '1'
|
||||
await import('./bootstrapFromStarter')
|
||||
Reference in new issue
Block a user