Update
This commit is contained in:
1 parent
911dcace72
commit
9c68c414d8
53 files changed
+2919
-469
No files matched your search
@@ -0,0 +1,125 @@
|
||||
/**
|
||||
* Generische SQL-CRUD-Bausteine über die Tabellen-Registry (tableRegistry.ts) — von allen
|
||||
* server/db/queries/*.ts-Modulen genutzt, damit Spalten-Codecs (JSON/Bool) nur an einer
|
||||
* Stelle behandelt werden.
|
||||
*/
|
||||
import { db } from '../database'
|
||||
import { TABLE_DEFINITIONS, type TableDef, type ColumnCodec } from './tableRegistry'
|
||||
|
||||
const tablesByName = new Map(TABLE_DEFINITIONS.map(t => [t.name, t]))
|
||||
|
||||
function requireTable(name: string): TableDef {
|
||||
const t = tablesByName.get(name)
|
||||
if (!t) throw new Error(`Unbekannte Tabelle: ${name}`)
|
||||
return t
|
||||
}
|
||||
|
||||
type SqlPrimitive = number | string | bigint | null
|
||||
|
||||
function toBindValue(raw: unknown, codec: ColumnCodec): SqlPrimitive {
|
||||
if (raw === undefined || raw === null) return null
|
||||
if (codec === 'json') return JSON.stringify(raw)
|
||||
if (codec === 'bool') return raw ? 1 : 0
|
||||
return raw as SqlPrimitive
|
||||
}
|
||||
|
||||
function fromSqlValue(raw: unknown, codec: ColumnCodec): unknown {
|
||||
if (raw === null || raw === undefined) return null
|
||||
if (codec === 'json') return JSON.parse(raw as string)
|
||||
if (codec === 'bool') return raw === 1
|
||||
return raw
|
||||
}
|
||||
|
||||
export function decodeRow<T>(table: TableDef, row: Record<string, unknown>): T {
|
||||
const result: Record<string, unknown> = { id: row.id }
|
||||
for (const c of table.columns) result[c.name] = fromSqlValue(row[c.name], c.codec)
|
||||
return result as T
|
||||
}
|
||||
|
||||
export function insertRow(tableName: string, obj: Record<string, unknown>): number {
|
||||
const table = requireTable(tableName)
|
||||
const cols = table.columns.map(c => `"${c.name}"`).join(', ')
|
||||
const placeholders = table.columns.map(() => '?').join(', ')
|
||||
const values = table.columns.map(c => toBindValue(obj[c.name], c.codec))
|
||||
const info = db.prepare(`INSERT INTO "${tableName}" (${cols}) VALUES (${placeholders})`).run(...values)
|
||||
return Number(info.lastInsertRowid)
|
||||
}
|
||||
|
||||
/** Für Backup-Restore: fügt eine Zeile mit expliziter id ein, damit Fremdschlüssel-Referenzen im importierten Datensatz stabil bleiben. */
|
||||
export function insertRowWithId(tableName: string, id: number, obj: Record<string, unknown>): void {
|
||||
const table = requireTable(tableName)
|
||||
const cols = ['"id"', ...table.columns.map(c => `"${c.name}"`)].join(', ')
|
||||
const placeholders = ['?', ...table.columns.map(() => '?')].join(', ')
|
||||
const values: SqlPrimitive[] = [id, ...table.columns.map(c => toBindValue(obj[c.name], c.codec))]
|
||||
db.prepare(`INSERT INTO "${tableName}" (${cols}) VALUES (${placeholders})`).run(...values)
|
||||
}
|
||||
|
||||
export function updateRow(tableName: string, id: number, patch: Record<string, unknown>): number {
|
||||
const table = requireTable(tableName)
|
||||
const entries = Object.entries(patch).filter(([k]) => k !== 'id')
|
||||
if (entries.length === 0) return 0
|
||||
const setSql = entries.map(([k]) => `"${k}" = ?`).join(', ')
|
||||
const values = entries.map(([k, v]) => {
|
||||
const colDef = table.columns.find(c => c.name === k)
|
||||
return toBindValue(v, colDef?.codec ?? 'plain')
|
||||
})
|
||||
const info = db.prepare(`UPDATE "${tableName}" SET ${setSql} WHERE id = ?`).run(...values, id)
|
||||
return Number(info.changes)
|
||||
}
|
||||
|
||||
export function getRowById<T>(tableName: string, id: number): T | undefined {
|
||||
const table = requireTable(tableName)
|
||||
const row = db.prepare(`SELECT * FROM "${tableName}" WHERE id = ?`).get(id) as Record<string, unknown> | undefined
|
||||
return row ? decodeRow<T>(table, row) : undefined
|
||||
}
|
||||
|
||||
export function getAllRows<T>(tableName: string): T[] {
|
||||
const table = requireTable(tableName)
|
||||
const rows = db.prepare(`SELECT * FROM "${tableName}"`).all() as Record<string, unknown>[]
|
||||
return rows.map(r => decodeRow<T>(table, r))
|
||||
}
|
||||
|
||||
export function getAllRowsOrderedBy<T>(tableName: string, column: string): T[] {
|
||||
const table = requireTable(tableName)
|
||||
const rows = db.prepare(`SELECT * FROM "${tableName}" ORDER BY "${column}" ASC`).all() as Record<string, unknown>[]
|
||||
return rows.map(r => decodeRow<T>(table, r))
|
||||
}
|
||||
|
||||
export function getRowsWhereEquals<T>(tableName: string, column: string, value: SqlPrimitive): T[] {
|
||||
const table = requireTable(tableName)
|
||||
const rows = db.prepare(`SELECT * FROM "${tableName}" WHERE "${column}" = ?`).all(value) as Record<string, unknown>[]
|
||||
return rows.map(r => decodeRow<T>(table, r))
|
||||
}
|
||||
|
||||
export function getRowsWhereIn<T>(tableName: string, column: string, values: number[]): T[] {
|
||||
if (values.length === 0) return []
|
||||
const table = requireTable(tableName)
|
||||
const placeholders = values.map(() => '?').join(', ')
|
||||
const rows = db.prepare(`SELECT * FROM "${tableName}" WHERE "${column}" IN (${placeholders})`).all(...values) as Record<string, unknown>[]
|
||||
return rows.map(r => decodeRow<T>(table, r))
|
||||
}
|
||||
|
||||
export function deleteRowById(tableName: string, id: number): void {
|
||||
requireTable(tableName)
|
||||
db.prepare(`DELETE FROM "${tableName}" WHERE id = ?`).run(id)
|
||||
}
|
||||
|
||||
export function deleteRowsWhereEquals(tableName: string, column: string, value: SqlPrimitive): number {
|
||||
requireTable(tableName)
|
||||
const info = db.prepare(`DELETE FROM "${tableName}" WHERE "${column}" = ?`).run(value)
|
||||
return Number(info.changes)
|
||||
}
|
||||
|
||||
export function deleteRowsWhereIn(tableName: string, column: string, values: number[]): number {
|
||||
if (values.length === 0) return 0
|
||||
requireTable(tableName)
|
||||
const placeholders = values.map(() => '?').join(', ')
|
||||
const info = db.prepare(`DELETE FROM "${tableName}" WHERE "${column}" IN (${placeholders})`).run(...values)
|
||||
return Number(info.changes)
|
||||
}
|
||||
|
||||
export function countWhereEquals(tableName: string, column: string, value: SqlPrimitive): number {
|
||||
requireTable(tableName)
|
||||
const row = db.prepare(`SELECT COUNT(*) as c FROM "${tableName}" WHERE "${column}" = ?`).get(value) as { c: number }
|
||||
return row.c
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { getRowById, insertRowWithId, updateRow } from '../crud'
|
||||
import type { AppSettings } from '../../../src/db/types'
|
||||
|
||||
/** Muss mit DEFAULT_RATING_TREND_WEIGHT_STEP in src/config/constants.ts synchron gehalten werden. */
|
||||
const DEFAULT_RATING_TREND_WEIGHT_STEP = 0.5
|
||||
|
||||
export function getRatingTrendWeightStep(): number {
|
||||
const settings = getRowById<AppSettings>('appSettings', 1)
|
||||
return settings?.ratingTrendWeightStep ?? DEFAULT_RATING_TREND_WEIGHT_STEP
|
||||
}
|
||||
|
||||
export function getOrSeedRatingTrendWeightStep(): number {
|
||||
let settings = getRowById<AppSettings>('appSettings', 1)
|
||||
if (!settings) {
|
||||
insertRowWithId('appSettings', 1, { ratingTrendWeightStep: DEFAULT_RATING_TREND_WEIGHT_STEP })
|
||||
settings = getRowById<AppSettings>('appSettings', 1)
|
||||
}
|
||||
return settings?.ratingTrendWeightStep ?? DEFAULT_RATING_TREND_WEIGHT_STEP
|
||||
}
|
||||
|
||||
export function saveRatingTrendWeightStep(weightStep: number): number {
|
||||
const existing = getRowById('appSettings', 1)
|
||||
if (existing) updateRow('appSettings', 1, { ratingTrendWeightStep: weightStep })
|
||||
else insertRowWithId('appSettings', 1, { ratingTrendWeightStep: weightStep })
|
||||
return 1
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { getAllRows, getRowsWhereEquals, getRowsWhereIn, insertRow, updateRow, deleteRowsWhereEquals } from '../crud'
|
||||
import type { Assessment } from '../../../src/db/types'
|
||||
|
||||
export const listAssessmentsAll = (): Assessment[] => getAllRows<Assessment>('assessments')
|
||||
export const listAssessmentsForMeeting = (meetingInstanceId: number): Assessment[] =>
|
||||
getRowsWhereEquals<Assessment>('assessments', 'meetingInstanceId', meetingInstanceId)
|
||||
export const listAssessmentsForMeetings = (meetingInstanceIds: number[]): Assessment[] =>
|
||||
getRowsWhereIn<Assessment>('assessments', 'meetingInstanceId', meetingInstanceIds)
|
||||
export const addAssessment = (a: Omit<Assessment, 'id'>): number => insertRow('assessments', a)
|
||||
export const updateAssessment = (id: number, patch: Partial<Assessment>): number => updateRow('assessments', id, patch)
|
||||
export const deleteAssessmentsForMeeting = (meetingInstanceId: number): number =>
|
||||
deleteRowsWhereEquals('assessments', 'meetingInstanceId', meetingInstanceId)
|
||||
@@ -0,0 +1,44 @@
|
||||
import { getRowById, getRowsWhereEquals, insertRow, updateRow } from '../crud'
|
||||
import type { FeedbackDraft, AssignmentFeedback, FeedbackCategoryRating, FeedbackDimensionText } from '../../../src/db/types'
|
||||
|
||||
export const getFeedbackDraft = (assignmentId: number, instituteeId: number): FeedbackDraft | undefined =>
|
||||
getRowsWhereEquals<FeedbackDraft>('feedbackDrafts', 'assignmentId', assignmentId).find(d => d.instituteeId === instituteeId)
|
||||
export const addFeedbackDraft = (d: Omit<FeedbackDraft, 'id'>): number => insertRow('feedbackDrafts', d)
|
||||
export const updateFeedbackDraft = (id: number, patch: Partial<FeedbackDraft>): number => updateRow('feedbackDrafts', id, patch)
|
||||
|
||||
export const getAssignmentFeedback = (assignmentId: number, instituteeId: number): AssignmentFeedback | undefined =>
|
||||
getRowsWhereEquals<AssignmentFeedback>('assignmentFeedbacks', 'assignmentId', assignmentId).find(f => f.instituteeId === instituteeId)
|
||||
export const getAssignmentFeedbackById = (id: number): AssignmentFeedback | undefined =>
|
||||
getRowById<AssignmentFeedback>('assignmentFeedbacks', id)
|
||||
export const addAssignmentFeedback = (f: Omit<AssignmentFeedback, 'id'>): number => insertRow('assignmentFeedbacks', f)
|
||||
export const updateAssignmentFeedback = (id: number, patch: Partial<AssignmentFeedback>): number =>
|
||||
updateRow('assignmentFeedbacks', id, patch)
|
||||
|
||||
export function getOrCreateAssignmentFeedback(assignmentId: number, instituteeId: number): AssignmentFeedback | undefined {
|
||||
let fb = getAssignmentFeedback(assignmentId, instituteeId)
|
||||
if (!fb) {
|
||||
const fbId = addAssignmentFeedback({
|
||||
assignmentId, instituteeId, status: 'draft', aiModel: '', updatedAt: new Date().toISOString(),
|
||||
})
|
||||
fb = getAssignmentFeedbackById(fbId)
|
||||
}
|
||||
return fb
|
||||
}
|
||||
|
||||
export const listFeedbackCategoryRatings = (assignmentFeedbackId: number): FeedbackCategoryRating[] =>
|
||||
getRowsWhereEquals<FeedbackCategoryRating>('feedbackCategoryRatings', 'assignmentFeedbackId', assignmentFeedbackId)
|
||||
export const addFeedbackCategoryRating = (r: Omit<FeedbackCategoryRating, 'id'>): number => insertRow('feedbackCategoryRatings', r)
|
||||
export const updateFeedbackCategoryRating = (id: number, patch: Partial<FeedbackCategoryRating>): number =>
|
||||
updateRow('feedbackCategoryRatings', id, patch)
|
||||
|
||||
export const listFeedbackDimensionTexts = (assignmentFeedbackId: number): FeedbackDimensionText[] =>
|
||||
getRowsWhereEquals<FeedbackDimensionText>('feedbackDimensionTexts', 'assignmentFeedbackId', assignmentFeedbackId)
|
||||
export const getFeedbackDimensionText = (
|
||||
assignmentFeedbackId: number,
|
||||
feedbackDimensionId: number,
|
||||
): FeedbackDimensionText | undefined =>
|
||||
getRowsWhereEquals<FeedbackDimensionText>('feedbackDimensionTexts', 'assignmentFeedbackId', assignmentFeedbackId)
|
||||
.find(t => t.feedbackDimensionId === feedbackDimensionId)
|
||||
export const addFeedbackDimensionText = (t: Omit<FeedbackDimensionText, 'id'>): number => insertRow('feedbackDimensionTexts', t)
|
||||
export const updateFeedbackDimensionText = (id: number, patch: Partial<FeedbackDimensionText>): number =>
|
||||
updateRow('feedbackDimensionTexts', id, patch)
|
||||
@@ -0,0 +1,31 @@
|
||||
import {
|
||||
getAllRows, getRowById, insertRow, updateRow,
|
||||
getRowsWhereEquals, deleteRowsWhereEquals, deleteRowById, countWhereEquals,
|
||||
} from '../crud'
|
||||
import type { AssignmentType, PhaseTemplate } from '../../../src/db/types'
|
||||
|
||||
export const listAssignmentTypes = (): AssignmentType[] => getAllRows<AssignmentType>('assignmentTypes')
|
||||
export const getAssignmentType = (id: number): AssignmentType | undefined => getRowById<AssignmentType>('assignmentTypes', id)
|
||||
export const addAssignmentType = (type: Omit<AssignmentType, 'id'>): number => insertRow('assignmentTypes', type)
|
||||
export const updateAssignmentType = (id: number, patch: Partial<AssignmentType>): number =>
|
||||
updateRow('assignmentTypes', id, patch)
|
||||
|
||||
/** Löscht nur, wenn keine Assignments mehr diesen Typ referenzieren (Cascade auf phaseTemplates sonst). */
|
||||
export function deleteAssignmentType(id: number): { ok: true } | { ok: false; assignmentCount: number } {
|
||||
const assignmentCount = countWhereEquals('assignments', 'assignmentTypeId', id)
|
||||
if (assignmentCount > 0) return { ok: false, assignmentCount }
|
||||
deleteRowsWhereEquals('phaseTemplates', 'assignmentTypeId', id)
|
||||
deleteRowById('assignmentTypes', id)
|
||||
return { ok: true }
|
||||
}
|
||||
|
||||
export const listPhaseTemplates = (): PhaseTemplate[] => getAllRows<PhaseTemplate>('phaseTemplates')
|
||||
export const getPhaseTemplate = (id: number): PhaseTemplate | undefined => getRowById<PhaseTemplate>('phaseTemplates', id)
|
||||
export const listPhaseTemplatesForType = (assignmentTypeId: number): PhaseTemplate[] => {
|
||||
const rows = getRowsWhereEquals<PhaseTemplate>('phaseTemplates', 'assignmentTypeId', assignmentTypeId)
|
||||
return rows.sort((a, b) => a.order - b.order)
|
||||
}
|
||||
export const addPhaseTemplate = (tmpl: Omit<PhaseTemplate, 'id'>): number => insertRow('phaseTemplates', tmpl)
|
||||
export const updatePhaseTemplate = (id: number, patch: Partial<PhaseTemplate>): number =>
|
||||
updateRow('phaseTemplates', id, patch)
|
||||
export const deletePhaseTemplate = (id: number): void => deleteRowById('phaseTemplates', id)
|
||||
@@ -0,0 +1,31 @@
|
||||
import { getAllRows, getRowById, insertRow, updateRow } from '../crud'
|
||||
import type { Assignment, AssignmentType, Consultant } from '../../../src/db/types'
|
||||
|
||||
export const listAssignments = (): Assignment[] => getAllRows<Assignment>('assignments')
|
||||
export const listAssignmentsNewestFirst = (): Assignment[] =>
|
||||
getAllRows<Assignment>('assignments').sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
|
||||
export const getAssignment = (id: number): Assignment | undefined => getRowById<Assignment>('assignments', id)
|
||||
export const addAssignment = (a: Omit<Assignment, 'id'>): number => insertRow('assignments', a)
|
||||
export const updateAssignment = (id: number, patch: Partial<Assignment>): number => updateRow('assignments', id, patch)
|
||||
|
||||
export interface AssignmentWithDetails extends Assignment {
|
||||
typeName: string
|
||||
instituteeNames: string[]
|
||||
}
|
||||
|
||||
/** Für die Dashboard-Liste: Assignments mit aufgelöstem Typ- und Institutee-Namen, neueste zuerst. */
|
||||
export function listAssignmentsWithDetails(): AssignmentWithDetails[] {
|
||||
const raw = listAssignmentsNewestFirst()
|
||||
const types = getAllRows<AssignmentType>('assignmentTypes')
|
||||
const consultants = getAllRows<Consultant>('consultants')
|
||||
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}` : '?'
|
||||
}),
|
||||
}))
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* Generischer Dump/Restore aller Tabellen — Server-Pendant zum bisherigen client-seitigen
|
||||
* dbBackup.ts (das direkt gegen Dexie/IndexedDB lief). Iteriert exakt TABLE_DEFINITIONS aus
|
||||
* tableRegistry.ts, derselben Liste, die auch das SQL-Schema erzeugt (siehe Vollständigkeits-
|
||||
* Garantie im Plan) — eine neue Tabelle kann dadurch nicht unbemerkt aus dem Backup fallen.
|
||||
*/
|
||||
import { db } from '../../database'
|
||||
import { TABLE_DEFINITIONS } from '../tableRegistry'
|
||||
import { getAllRows, insertRowWithId } from '../crud'
|
||||
|
||||
export interface BackupPayload {
|
||||
version: number
|
||||
exportedAt: string
|
||||
tables: Record<string, Array<Record<string, unknown>>>
|
||||
}
|
||||
|
||||
/** Liefert jede Tabelle mit dekodierten Spalten (echte Arrays/Booleans statt JSON-/Bit-Rohwerten). */
|
||||
export function exportAll(): BackupPayload {
|
||||
const tables: Record<string, Array<Record<string, unknown>>> = {}
|
||||
for (const table of TABLE_DEFINITIONS) {
|
||||
tables[table.name] = getAllRows<Record<string, unknown>>(table.name)
|
||||
}
|
||||
return { version: 1, exportedAt: new Date().toISOString(), tables }
|
||||
}
|
||||
|
||||
/** Löscht alle Tabellen und fügt die übergebenen Zeilen mit ihrer ursprünglichen id wieder ein (erhält Fremdschlüssel-Referenzen). */
|
||||
export function importAll(tables: Record<string, Array<Record<string, unknown>>>): void {
|
||||
db.exec('BEGIN')
|
||||
try {
|
||||
for (const table of TABLE_DEFINITIONS) {
|
||||
db.prepare(`DELETE FROM "${table.name}"`).run()
|
||||
}
|
||||
for (const table of TABLE_DEFINITIONS) {
|
||||
for (const row of tables[table.name] ?? []) {
|
||||
const { id, ...rest } = row
|
||||
if (typeof id !== 'number') continue
|
||||
insertRowWithId(table.name, id, rest)
|
||||
}
|
||||
}
|
||||
db.exec('COMMIT')
|
||||
} catch (err) {
|
||||
db.exec('ROLLBACK')
|
||||
throw err
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { getAllRows, getRowById, getRowsWhereIn, insertRow, updateRow, deleteRowById } from '../crud'
|
||||
import type { Group, Consultant } from '../../../src/db/types'
|
||||
|
||||
export const listGroups = (): Group[] => getAllRows<Group>('groups')
|
||||
export const addGroup = (group: Omit<Group, 'id'>): number => insertRow('groups', group)
|
||||
|
||||
export const listConsultants = (): Consultant[] => getAllRows<Consultant>('consultants')
|
||||
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)
|
||||
@@ -0,0 +1,19 @@
|
||||
import { getAllRows, getRowsWhereEquals, getRowsWhereIn, insertRow, updateRow, deleteRowById, deleteRowsWhereEquals } from '../crud'
|
||||
import type { ConversationEntry, ConversationSkillScore } from '../../../src/db/types'
|
||||
|
||||
export const listConversationEntriesForMeeting = (meetingInstanceId: number): ConversationEntry[] =>
|
||||
getRowsWhereEquals<ConversationEntry>('conversationEntries', 'meetingInstanceId', meetingInstanceId)
|
||||
.sort((a, b) => a.sequenceIndex - b.sequenceIndex)
|
||||
export const listConversationEntriesForMeetings = (meetingInstanceIds: number[]): ConversationEntry[] =>
|
||||
getRowsWhereIn<ConversationEntry>('conversationEntries', 'meetingInstanceId', meetingInstanceIds)
|
||||
export const addConversationEntry = (e: Omit<ConversationEntry, 'id'>): number => insertRow('conversationEntries', e)
|
||||
export const updateConversationEntry = (id: number, patch: Partial<ConversationEntry>): number =>
|
||||
updateRow('conversationEntries', id, patch)
|
||||
export const deleteConversationEntry = (id: number): void => deleteRowById('conversationEntries', id)
|
||||
|
||||
export const listConversationSkillScoresAll = (): ConversationSkillScore[] => getAllRows<ConversationSkillScore>('conversationSkillScores')
|
||||
export const addConversationSkillScore = (s: Omit<ConversationSkillScore, 'id'>): number => insertRow('conversationSkillScores', s)
|
||||
export const updateConversationSkillScore = (id: number, patch: Partial<ConversationSkillScore>): number =>
|
||||
updateRow('conversationSkillScores', id, patch)
|
||||
export const deleteConversationSkillScoresForEntry = (conversationEntryId: number): number =>
|
||||
deleteRowsWhereEquals('conversationSkillScores', 'conversationEntryId', conversationEntryId)
|
||||
@@ -0,0 +1,57 @@
|
||||
import {
|
||||
getAllRows, getRowsWhereIn, insertRow, updateRow,
|
||||
getRowsWhereEquals, deleteRowsWhereEquals, deleteRowById,
|
||||
} from '../crud'
|
||||
import type { FeedbackDimension, FeedbackCategory, FeedbackCriterionItem } from '../../../src/db/types'
|
||||
|
||||
export interface FeedbackStructure {
|
||||
dimensions: FeedbackDimension[]
|
||||
categories: FeedbackCategory[]
|
||||
items: FeedbackCriterionItem[]
|
||||
}
|
||||
|
||||
const byOrder = <T extends { order: number }>(rows: T[]) => [...rows].sort((a, b) => a.order - b.order)
|
||||
|
||||
/** Vollständige, nach `order` sortierte Feedback-Taxonomie. */
|
||||
export function loadFeedbackStructure(): FeedbackStructure {
|
||||
return {
|
||||
dimensions: byOrder(getAllRows<FeedbackDimension>('feedbackDimensions')),
|
||||
categories: byOrder(getAllRows<FeedbackCategory>('feedbackCategories')),
|
||||
items: byOrder(getAllRows<FeedbackCriterionItem>('feedbackCriterionItems')),
|
||||
}
|
||||
}
|
||||
|
||||
export const listFeedbackCategoriesOrdered = (): FeedbackCategory[] => byOrder(getAllRows<FeedbackCategory>('feedbackCategories'))
|
||||
export const listFeedbackCategoriesAll = (): FeedbackCategory[] => getAllRows<FeedbackCategory>('feedbackCategories')
|
||||
export const listFeedbackCriterionItemsAll = (): FeedbackCriterionItem[] => getAllRows<FeedbackCriterionItem>('feedbackCriterionItems')
|
||||
export const getFeedbackCriterionItemsByIds = (ids: number[]): FeedbackCriterionItem[] =>
|
||||
getRowsWhereIn<FeedbackCriterionItem>('feedbackCriterionItems', 'id', ids)
|
||||
|
||||
export const addFeedbackDimension = (d: Omit<FeedbackDimension, 'id'>): number => insertRow('feedbackDimensions', d)
|
||||
export const updateFeedbackDimension = (id: number, patch: Partial<FeedbackDimension>): number =>
|
||||
updateRow('feedbackDimensions', id, patch)
|
||||
|
||||
/** Cascade: Items der Kategorien → Kategorien → Dimension. */
|
||||
export function deleteFeedbackDimension(id: number): void {
|
||||
const cats = getRowsWhereEquals<FeedbackCategory>('feedbackCategories', 'dimensionId', id)
|
||||
for (const cat of cats) {
|
||||
deleteRowsWhereEquals('feedbackCriterionItems', 'categoryId', cat.id!)
|
||||
}
|
||||
deleteRowsWhereEquals('feedbackCategories', 'dimensionId', id)
|
||||
deleteRowById('feedbackDimensions', id)
|
||||
}
|
||||
|
||||
export const addFeedbackCategory = (c: Omit<FeedbackCategory, 'id'>): number => insertRow('feedbackCategories', c)
|
||||
export const updateFeedbackCategory = (id: number, patch: Partial<FeedbackCategory>): number =>
|
||||
updateRow('feedbackCategories', id, patch)
|
||||
|
||||
/** Cascade: Items der Kategorie → Kategorie. */
|
||||
export function deleteFeedbackCategory(id: number): void {
|
||||
deleteRowsWhereEquals('feedbackCriterionItems', 'categoryId', id)
|
||||
deleteRowById('feedbackCategories', id)
|
||||
}
|
||||
|
||||
export const addFeedbackCriterionItem = (i: Omit<FeedbackCriterionItem, 'id'>): number => insertRow('feedbackCriterionItems', i)
|
||||
export const updateFeedbackCriterionItem = (id: number, patch: Partial<FeedbackCriterionItem>): number =>
|
||||
updateRow('feedbackCriterionItems', id, patch)
|
||||
export const deleteFeedbackCriterionItem = (id: number): void => deleteRowById('feedbackCriterionItems', id)
|
||||
@@ -0,0 +1,69 @@
|
||||
import {
|
||||
getAllRows, getRowById, getRowsWhereEquals, insertRow, updateRow,
|
||||
deleteRowsWhereEquals, deleteRowsWhereIn, deleteRowById,
|
||||
} from '../crud'
|
||||
import type {
|
||||
MeetingInstance, PhaseTemplate, Assignment, Consultant,
|
||||
ConversationEntry, ConversationSkillScore, Assessment,
|
||||
} from '../../../src/db/types'
|
||||
import { getConsultantsByIds } from './consultants'
|
||||
|
||||
export const getMeetingInstance = (id: number): MeetingInstance | undefined => getRowById<MeetingInstance>('meetingInstances', id)
|
||||
export const listMeetingInstancesForAssignment = (assignmentId: number): MeetingInstance[] =>
|
||||
getRowsWhereEquals<MeetingInstance>('meetingInstances', 'assignmentId', assignmentId)
|
||||
|
||||
/**
|
||||
* Kanonischer Filter für Aggregationen über mehrere Meetings: Papierkorb-/unfertige Meetings ausschließen,
|
||||
* chronologisch sortiert. Siehe CLAUDE.md — immer diese Funktion nutzen, nicht erneut inline filtern.
|
||||
*/
|
||||
export function listDoneMeetingsChronological(assignmentId: number): MeetingInstance[] {
|
||||
const instances = listMeetingInstancesForAssignment(assignmentId)
|
||||
return instances
|
||||
.filter(m => !m.deletedAt && m.status === 'done')
|
||||
.sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime())
|
||||
}
|
||||
|
||||
export const addMeetingInstance = (m: Omit<MeetingInstance, 'id'>): number => insertRow('meetingInstances', m)
|
||||
export const updateMeetingInstance = (id: number, patch: Partial<MeetingInstance>): number =>
|
||||
updateRow('meetingInstances', id, patch)
|
||||
export const softDeleteMeetingInstance = (id: number): number =>
|
||||
updateRow('meetingInstances', id, { deletedAt: new Date().toISOString() })
|
||||
export const restoreMeetingInstance = (id: number): number =>
|
||||
updateRow('meetingInstances', id, { deletedAt: null })
|
||||
|
||||
/** Cascade: conversationSkillScores der Entries → conversationEntries → assessments → meetingInstance. */
|
||||
export function hardDeleteMeetingInstance(id: number): void {
|
||||
const entryIds = getRowsWhereEquals<ConversationEntry>('conversationEntries', 'meetingInstanceId', id).map(e => e.id!)
|
||||
deleteRowsWhereIn('conversationSkillScores', 'conversationEntryId', entryIds)
|
||||
deleteRowsWhereEquals('conversationEntries', 'meetingInstanceId', id)
|
||||
deleteRowsWhereEquals('assessments', 'meetingInstanceId', id)
|
||||
deleteRowById('meetingInstances', id)
|
||||
}
|
||||
|
||||
export interface MeetingExportData {
|
||||
meeting: MeetingInstance
|
||||
template: PhaseTemplate | undefined
|
||||
assignment: Assignment | undefined
|
||||
consultants: Consultant[]
|
||||
entries: ConversationEntry[]
|
||||
allScores: ConversationSkillScore[]
|
||||
assessments: Assessment[]
|
||||
}
|
||||
|
||||
/** Gebündelte Rohdaten für Markdown-/JSON-Export eines Meetings — vorher in meetingExport.ts dupliziert. */
|
||||
export function getMeetingExportData(meetingId: number): MeetingExportData {
|
||||
const meeting = getRowById<MeetingInstance>('meetingInstances', meetingId)
|
||||
if (!meeting) throw new Error('Meeting nicht gefunden')
|
||||
|
||||
const template = getRowById<PhaseTemplate>('phaseTemplates', meeting.phaseTemplateId)
|
||||
const assignment = getRowById<Assignment>('assignments', meeting.assignmentId)
|
||||
|
||||
const instituteeIds = assignment?.instituteeIds ?? []
|
||||
const consultants = getConsultantsByIds(instituteeIds)
|
||||
const entries = getRowsWhereEquals<ConversationEntry>('conversationEntries', 'meetingInstanceId', meetingId)
|
||||
.sort((a, b) => a.sequenceIndex - b.sequenceIndex)
|
||||
const allScores = getAllRows<ConversationSkillScore>('conversationSkillScores')
|
||||
const assessments = getRowsWhereEquals<Assessment>('assessments', 'meetingInstanceId', meetingId)
|
||||
|
||||
return { meeting, template, assignment, consultants, entries, allScores, assessments }
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
/**
|
||||
* Einzige Quelle der Wahrheit für alle SQL-Tabellen — treibt sowohl die Schema-Erstellung
|
||||
* (database.ts) als auch Export/Import (queries/backup.ts) an. Eine neue Tabelle, die hier
|
||||
* fehlt, fehlt dadurch gleichzeitig im Schema UND im Backup — sichtbarer Fehler statt eines
|
||||
* Datenverlusts, der erst beim nächsten Restore aus dem Backup auffällt (siehe CLAUDE.md:
|
||||
* appSettings fehlte einmal in TABLE_NAMES).
|
||||
*
|
||||
* 1:1 abgeleitet aus TABLE_NAMES (src/utils/dbBackup.ts) und den Interfaces in src/db/types.ts.
|
||||
*/
|
||||
|
||||
export type ColumnCodec = 'json' | 'bool' | 'plain'
|
||||
|
||||
export interface ColumnDef {
|
||||
name: string
|
||||
sqlType: 'INTEGER' | 'TEXT' | 'REAL'
|
||||
codec: ColumnCodec
|
||||
}
|
||||
|
||||
export interface TableDef {
|
||||
name: string
|
||||
columns: ColumnDef[]
|
||||
}
|
||||
|
||||
const col = (name: string, sqlType: ColumnDef['sqlType'], codec: ColumnCodec = 'plain'): ColumnDef =>
|
||||
({ name, sqlType, codec })
|
||||
|
||||
export const TABLE_DEFINITIONS: TableDef[] = [
|
||||
{ name: 'categories', columns: [
|
||||
col('name', 'TEXT'),
|
||||
col('order', 'INTEGER'),
|
||||
]},
|
||||
{ name: 'criteria', columns: [
|
||||
col('categoryId', 'INTEGER'),
|
||||
col('name', 'TEXT'),
|
||||
col('description', 'TEXT'),
|
||||
col('weight', 'REAL'),
|
||||
col('order', 'INTEGER'),
|
||||
]},
|
||||
{ name: 'assignmentTypes', columns: [
|
||||
col('name', 'TEXT'),
|
||||
col('defaultPhaseKeys', 'TEXT', 'json'),
|
||||
col('criteriaIds', 'TEXT', 'json'),
|
||||
]},
|
||||
{ name: 'phaseTemplates', columns: [
|
||||
col('assignmentTypeId', 'INTEGER'),
|
||||
col('phaseKey', 'TEXT'),
|
||||
col('label', 'TEXT'),
|
||||
col('withWhom', 'TEXT'),
|
||||
col('isRepeatable', 'INTEGER', 'bool'),
|
||||
col('hasConversation', 'INTEGER', 'bool'),
|
||||
col('hasAssessment', 'INTEGER', 'bool'),
|
||||
col('criteriaIds', 'TEXT', 'json'),
|
||||
col('order', 'INTEGER'),
|
||||
]},
|
||||
{ name: 'groups', columns: [
|
||||
col('name', 'TEXT'),
|
||||
col('cohortYear', 'INTEGER'),
|
||||
]},
|
||||
{ name: 'consultants', columns: [
|
||||
col('groupId', 'INTEGER'),
|
||||
col('firstName', 'TEXT'),
|
||||
col('lastName', 'TEXT'),
|
||||
]},
|
||||
{ name: 'assignments', columns: [
|
||||
col('title', 'TEXT'),
|
||||
col('client', 'TEXT'),
|
||||
col('assignmentTypeId', 'INTEGER'),
|
||||
col('instituteeIds', 'TEXT', 'json'),
|
||||
col('leadName', 'TEXT'),
|
||||
col('status', 'TEXT'),
|
||||
col('createdAt', 'TEXT'),
|
||||
col('assignmentNumber', 'TEXT'),
|
||||
col('description', 'TEXT'),
|
||||
col('instituteeEnrollments', 'TEXT', 'json'),
|
||||
]},
|
||||
{ name: 'meetingInstances', columns: [
|
||||
col('assignmentId', 'INTEGER'),
|
||||
col('phaseTemplateId', 'INTEGER'),
|
||||
col('phaseIndex', 'INTEGER'),
|
||||
col('date', 'TEXT'),
|
||||
col('status', 'TEXT'),
|
||||
col('generalNotes', 'TEXT'),
|
||||
col('deletedAt', 'TEXT'),
|
||||
]},
|
||||
{ name: 'conversationEntries', columns: [
|
||||
col('meetingInstanceId', 'INTEGER'),
|
||||
col('instituteeId', 'INTEGER'),
|
||||
col('sequenceIndex', 'INTEGER'),
|
||||
col('note', 'TEXT'),
|
||||
col('fillerCount', 'INTEGER'),
|
||||
col('updatedAt', 'TEXT'),
|
||||
col('lineTags', 'TEXT', 'json'),
|
||||
]},
|
||||
{ name: 'conversationSkillScores', columns: [
|
||||
col('conversationEntryId', 'INTEGER'),
|
||||
col('criteriaId', 'INTEGER'),
|
||||
col('score', 'TEXT'),
|
||||
]},
|
||||
{ name: 'assessments', columns: [
|
||||
col('meetingInstanceId', 'INTEGER'),
|
||||
col('instituteeId', 'INTEGER'),
|
||||
col('criteriaId', 'INTEGER'),
|
||||
col('score', 'TEXT'),
|
||||
col('note', 'TEXT'),
|
||||
col('updatedAt', 'TEXT'),
|
||||
]},
|
||||
{ name: 'feedbackDrafts', columns: [
|
||||
col('assignmentId', 'INTEGER'),
|
||||
col('instituteeId', 'INTEGER'),
|
||||
col('content', 'TEXT'),
|
||||
col('updatedAt', 'TEXT'),
|
||||
]},
|
||||
{ name: 'feedbackDimensions', columns: [
|
||||
col('name', 'TEXT'),
|
||||
col('order', 'INTEGER'),
|
||||
]},
|
||||
{ name: 'feedbackCategories', columns: [
|
||||
col('dimensionId', 'INTEGER'),
|
||||
col('name', 'TEXT'),
|
||||
col('order', 'INTEGER'),
|
||||
]},
|
||||
{ name: 'feedbackCriterionItems', columns: [
|
||||
col('categoryId', 'INTEGER'),
|
||||
col('name', 'TEXT'),
|
||||
col('weight', 'REAL'),
|
||||
col('order', 'INTEGER'),
|
||||
]},
|
||||
{ name: 'assignmentFeedbacks', columns: [
|
||||
col('assignmentId', 'INTEGER'),
|
||||
col('instituteeId', 'INTEGER'),
|
||||
col('status', 'TEXT'),
|
||||
col('aiModel', 'TEXT'),
|
||||
col('updatedAt', 'TEXT'),
|
||||
]},
|
||||
{ name: 'feedbackCategoryRatings', columns: [
|
||||
col('assignmentFeedbackId', 'INTEGER'),
|
||||
col('feedbackCategoryId', 'INTEGER'),
|
||||
col('rating', 'TEXT'),
|
||||
]},
|
||||
{ name: 'feedbackDimensionTexts', columns: [
|
||||
col('assignmentFeedbackId', 'INTEGER'),
|
||||
col('feedbackDimensionId', 'INTEGER'),
|
||||
col('achievements', 'TEXT'),
|
||||
col('developmentNeeds', 'TEXT'),
|
||||
]},
|
||||
{ name: 'criterionCategoryMappings', columns: [
|
||||
col('criterionId', 'INTEGER'),
|
||||
col('feedbackCategoryId', 'INTEGER'),
|
||||
]},
|
||||
{ name: 'criterionLevelDescriptions', columns: [
|
||||
col('criterionItemId', 'INTEGER'),
|
||||
col('rating', 'TEXT'),
|
||||
col('text', 'TEXT'),
|
||||
]},
|
||||
{ name: 'appSettings', columns: [
|
||||
col('ratingTrendWeightStep', 'REAL'),
|
||||
]},
|
||||
]
|
||||
|
||||
export const TABLE_NAMES = TABLE_DEFINITIONS.map(t => t.name)
|
||||
Reference in new issue
Block a user