Abteilungen als Ebene über der Personalakte

Punkt 3 der Wünsche.

Die Abteilung stand als Freitext in der Personalakte. Damit liess sich nichts
fragen: „SHD", „Shd" und „Sicherheitsdienst" waren drei Abteilungen. Sie ist
jetzt ein eigenes Modell, im Adminbereich verwaltbar, und die drei vorhandenen
Freitexte sind in der Migration zu Abteilungen geworden.

**Eine Fallakte trägt keine Abteilung.** Sie gehört zu einer, wenn eine
beteiligte Person ihr angehört - abgeleitet über CaseParticipant und die
Personalakte. Eine eingetragene Zuordnung wäre nach zwei Wochen falsch: Leute
wechseln, Beteiligte kommen dazu, und niemand pflegt das nach. Dasselbe gilt
für die Dokumente: ein Dokument unmittelbar an der Abteilung wäre halb
verdrahtet, weil die Vorlagen über TemplateUse nur Fall- und Personalakte
kennen.

Die Abteilungsseite zeigt Mitglieder, abgeleitete Fälle und Dokumente,
Vermerke, Chat und ein Kreisdiagramm der Fallarten; die Übersicht eines über
alle Abteilungen. Das Diagramm ist serverseitig gerendertes SVG - eine
Bibliothek wäre das Teuerste auf der Seite gewesen. Die Segmente sind
Abstufungen von --steel und nicht die Stufenfarben: ein Tortenstück in Oxidrot
würde als „streng geheim" gelesen.

Die Zusammenfassung ist die gefährliche Stelle. Eine Abteilungsseite fasst
zusammen, was einzeln längst geschützt ist, und eine Zusammenfassung, die nicht
filtert, verrät mehr als jede Einzelansicht. Deshalb läuft hier jede Liste und
jede Zahl durch dieselben Fragmente wie überall; ein Test prüft, dass die Summe
der Diagrammanteile mit der Länge der Liste übereinstimmt. Wo jemand
Personalakten gar nicht sehen darf, steht null und keine Null.

Vermerke erben Regel 2 unverändert: kein DELETE, Version bei jeder Änderung,
Grabstein bei jeder Zurücknahme, als Regel und Trigger in der Datenbank. Ohne
Korrekturkette, Anhänge und Karenzzeit - was Beweiswert hat, gehört in eine
Fallakte.

Nebenbei: das Zugriffsprotokoll hängt jetzt am dafür vorgesehenen Recht
audit.read statt an admin.
This commit is contained in:
Harlekin
2026-09-03 19:57:28 +02:00
parent 89bbed8679
commit aef3df0d44
39 changed files with 2765 additions and 36 deletions
+3
View File
@@ -2,6 +2,7 @@ import type { Prisma } from '@afis/db'
import type { EffectivePermissions } from '@/lib/auth/permissions'
import { visibleCaseWhere } from '@/lib/access/caseFilter'
import { visiblePersonnelWhere } from '@/lib/access/personnelFilter'
import { visibleDepartmentWhere } from '@/lib/access/departmentFilter'
/**
* Chat: der formlose Teil, der **an einer Akte hängt**.
@@ -22,5 +23,7 @@ export function visibleMessageWhere(p: EffectivePermissions): Prisma.ChatMessage
orte.push({ personnelFile: { is: visiblePersonnelWhere(p) } })
}
orte.push({ department: { is: visibleDepartmentWhere(p) } })
return { OR: orte }
}
+40
View File
@@ -0,0 +1,40 @@
import type { Prisma } from '@afis/db'
import type { EffectivePermissions } from '@/lib/auth/permissions'
/**
* Abteilungen, die ein Nutzer sehen darf.
*
* Anders als bei Akten gilt hier **nicht** „Existenz ist auch eine
* Information": dass es den Sicherheitsdienst gibt, weiss jeder im Haus, und
* eine Abteilung, die niemand findet, kann auch niemand einer Person zuordnen.
* Sie steht deshalb standardmässig auf Stufe 0.
*
* Die Stufe gibt es trotzdem, für den Fall, dass eine Abteilung selbst nicht
* allgemein bekannt sein soll. Und sie gilt dann für alles, was **an** der
* Abteilung hängt: ihre Vermerke und ihren Chat.
*
* Was in ihr aktenkundig ist, filtert dagegen weiterhin jede Liste für sich —
* die Mitglieder über `visiblePersonnelWhere`, die Fälle über
* `visibleCaseWhere`. Eine sichtbare Abteilung ist kein Zugang zu ihrem Inhalt.
*/
export function visibleDepartmentWhere(p: EffectivePermissions): Prisma.DepartmentWhereInput {
if (p.isAdmin) return {}
return { minClearance: { lte: p.clearanceLevel } }
}
/**
* Vermerke einer Abteilung: die Abteilung muss sichtbar sein **und** die
* Feldstufe des Vermerks darf die Stufe des Lesers nicht übersteigen. Derselbe
* Aufbau wie bei den Verlaufseinträgen einer Akte.
*/
export function visibleDepartmentEntryWhere(
p: EffectivePermissions,
): Prisma.DepartmentEntryWhereInput {
if (p.isAdmin) return { department: { is: visibleDepartmentWhere(p) } }
return {
AND: [
{ department: { is: visibleDepartmentWhere(p) } },
{ minClearance: { lte: p.clearanceLevel } },
],
}
}
+6
View File
@@ -44,6 +44,12 @@ export type AuditAction =
| 'attachment.read'
| 'attachment.release'
| 'chat.adopt'
| 'department.create'
| 'department.update'
| 'department.assign'
| 'department.entry.create'
| 'department.entry.edit'
| 'department.entry.retract'
| 'roles.update'
| 'export.pdf'
| 'export.approve'
+6 -2
View File
@@ -13,7 +13,7 @@ import type { EffectivePermissions } from '@/lib/auth/permissions'
*/
export async function loadChatView(p: EffectivePermissions, scope: ChatScope) {
const { ort, nachrichten } = await listMessages(p, scope)
const scopeId = ort.caseId ?? ort.personnelFileId!
const scopeId = ort.caseId ?? ort.personnelFileId ?? ort.departmentId!
const [autoren, vorschauen, reaktionen, lastReadAt, mitglieder] = await Promise.all([
db.user.findMany({
@@ -22,7 +22,11 @@ export async function loadChatView(p: EffectivePermissions, scope: ChatScope) {
}),
resolveCasePreviews(p, nachrichten.flatMap((n) => extractCaseNumbers(n.body))),
listReactions(p, nachrichten.map((n) => n.id)),
loadReadMarker(p, ort.caseId ? 'case' : 'personnel', scopeId),
loadReadMarker(
p,
ort.caseId ? 'case' : ort.personnelFileId ? 'personnel' : 'department',
scopeId,
),
// Für die Anzeige der Erwähnungen: Benutzername auf Anzeigename.
db.user.findMany({
where: { isActive: true },
+49 -8
View File
@@ -4,10 +4,17 @@ import { AccessError, must } from '@/lib/errors'
import { visibleCaseWhere } from '@/lib/access/caseFilter'
import { visibleMessageWhere } from '@/lib/access/chatFilter'
import { visiblePersonnelWhere } from '@/lib/access/personnelFilter'
import { visibleDepartmentWhere } from '@/lib/access/departmentFilter'
import { canEditCase } from '@/lib/access/caseWrite'
import { extractMentionNames } from '@/lib/chat/mentions'
import type { ReactionKey } from '@/lib/chat/terms'
import { caseTopic, personnelTopic, publish, type Topic } from '@/lib/realtime/publish'
import {
caseTopic,
departmentTopic,
personnelTopic,
publish,
type Topic,
} from '@/lib/realtime/publish'
import { enqueueCaseNotification, enqueuePersonnelNotification } from '@/lib/notify/enqueue'
import type { EffectivePermissions } from '@/lib/auth/permissions'
import type { Prisma } from '@afis/db'
@@ -28,6 +35,7 @@ import type { Prisma } from '@afis/db'
export type ChatScope =
| { kind: 'case'; caseNumber: string }
| { kind: 'personnel'; fileId: string }
| { kind: 'department'; departmentId: string }
const NACHRICHT = {
id: true,
@@ -41,6 +49,7 @@ const NACHRICHT = {
createdAt: true,
caseId: true,
personnelFileId: true,
departmentId: true,
} satisfies Prisma.ChatMessageSelect
/**
@@ -51,7 +60,13 @@ const NACHRICHT = {
export async function resolveScope(
p: EffectivePermissions,
scope: ChatScope,
): Promise<{ caseId?: string; personnelFileId?: string; topic: Topic; label: string } | null> {
): Promise<{
caseId?: string
personnelFileId?: string
departmentId?: string
topic: Topic
label: string
} | null> {
if (scope.kind === 'case') {
const akte = await db.case.findFirst({
where: { AND: [visibleCaseWhere(p), { caseNumber: scope.caseNumber }] },
@@ -60,6 +75,20 @@ export async function resolveScope(
return akte ? { caseId: akte.id, topic: caseTopic(akte.id), label: akte.caseNumber } : null
}
if (scope.kind === 'department') {
const abteilung = await db.department.findFirst({
where: { AND: [visibleDepartmentWhere(p), { id: scope.departmentId }] },
select: { id: true, key: true },
})
return abteilung
? {
departmentId: abteilung.id,
topic: departmentTopic(abteilung.id),
label: abteilung.key,
}
: null
}
// Personalakten setzen neben der Stufe ein eigenes Recht voraus.
if (!p.isAdmin && !p.permissions.has('personnel.read')) return null
@@ -89,7 +118,9 @@ export async function listMessages(
const wo: Prisma.ChatMessageWhereInput = ort.caseId
? { caseId: ort.caseId }
: { personnelFileId: ort.personnelFileId }
: ort.personnelFileId
? { personnelFileId: ort.personnelFileId }
: { departmentId: ort.departmentId }
const nachrichten = await db.chatMessage.findMany({
where: { AND: [wo, ...(options.since ? [{ id: { gt: options.since } }] : [])] },
@@ -156,7 +187,11 @@ export async function sendMessage(
const ziel = await db.chatMessage.findFirst({
where: {
id: input.replyToId,
...(ort.caseId ? { caseId: ort.caseId } : { personnelFileId: ort.personnelFileId }),
...(ort.caseId
? { caseId: ort.caseId }
: ort.personnelFileId
? { personnelFileId: ort.personnelFileId }
: { departmentId: ort.departmentId }),
},
select: { id: true },
})
@@ -169,6 +204,7 @@ export async function sendMessage(
id: input.id,
caseId: ort.caseId ?? null,
personnelFileId: ort.personnelFileId ?? null,
departmentId: ort.departmentId ?? null,
authorId: p.userId,
body: text,
replyToId,
@@ -382,9 +418,14 @@ export async function adoptAsEntry(
return { entryId }
}
function themaVon(nachricht: { caseId: string | null; personnelFileId: string | null }): Topic {
function themaVon(nachricht: {
caseId: string | null
personnelFileId: string | null
departmentId: string | null
}): Topic {
if (nachricht.caseId) return caseTopic(nachricht.caseId)
return personnelTopic(nachricht.personnelFileId!)
if (nachricht.personnelFileId) return personnelTopic(nachricht.personnelFileId)
return departmentTopic(nachricht.departmentId!)
}
// ---------------------------------------------------------------------------
@@ -400,7 +441,7 @@ function themaVon(nachricht: { caseId: string | null; personnelFileId: string |
*/
export async function loadReadMarker(
p: EffectivePermissions,
scopeType: 'case' | 'personnel',
scopeType: 'case' | 'personnel' | 'department',
scopeId: string,
): Promise<Date | null> {
const marker = await db.readMarker.findUnique({
@@ -412,7 +453,7 @@ export async function loadReadMarker(
export async function markRead(
p: EffectivePermissions,
scopeType: 'case' | 'personnel',
scopeType: 'case' | 'personnel' | 'department',
scopeId: string,
at: Date = new Date(),
): Promise<void> {
+186
View File
@@ -0,0 +1,186 @@
import { db } from '@/lib/db'
import { writeAudit } from '@/lib/audit/write'
import { AccessError } from '@/lib/errors'
import {
visibleDepartmentEntryWhere,
visibleDepartmentWhere,
} from '@/lib/access/departmentFilter'
import type { EffectivePermissions } from '@/lib/auth/permissions'
/**
* Vermerke an einer Abteilung.
*
* Harte Regel 2 aus CLAUDE.md gilt hier genauso wie im Verlauf einer Akte:
* **es gibt kein Löschen.** Jede Änderung legt den vorherigen Stand als
* Version ab, jede Zurücknahme lässt einen Grabstein stehen, und beides sieht
* jeder, der den Vermerk sehen darf. Die Regeln stehen in der Datenbank
* (`dept_entry_no_delete`, `dept_entry_immutable_guard`) und nicht nur hier.
*
* Schmaler als der Aktenverlauf ist er trotzdem: keine Korrekturkette, keine
* Anhänge, keine Karenzzeit. Ein Abteilungsvermerk ist ein laufendes
* Protokoll, kein Beweismittel — die Ermittlung gehört in eine Fallakte.
*/
const AUSWAHL = {
id: true,
body: true,
minClearance: true,
authorId: true,
createdAt: true,
version: true,
editedAt: true,
editedById: true,
retractedAt: true,
retractedById: true,
retractionReason: true,
} as const
export async function listEntries(p: EffectivePermissions, departmentId: string, take = 50) {
return db.departmentEntry.findMany({
where: { AND: [visibleDepartmentEntryWhere(p), { departmentId }] },
orderBy: { createdAt: 'desc' },
take,
select: AUSWAHL,
})
}
/** Wer Vermerke schreiben darf. Dasselbe Recht wie für den Aktenverlauf. */
function darfSchreiben(p: EffectivePermissions): boolean {
return p.isAdmin || p.permissions.has('entry.create')
}
export async function createEntry(
p: EffectivePermissions,
input: { id: string; departmentKey: string; body: string; minClearance: number },
): Promise<{ id: string }> {
if (!darfSchreiben(p)) throw new AccessError('no-permission')
const abteilung = await db.department.findFirst({
where: { AND: [visibleDepartmentWhere(p), { key: input.departmentKey }] },
select: { id: true, key: true },
})
if (!abteilung) throw new AccessError('not-found')
const text = input.body.trim()
if (text.length === 0) throw new AccessError('entry-empty')
// Niemand schreibt über seiner eigenen Stufe: sonst legte man einen Vermerk
// an, den man selbst nicht mehr lesen kann. Dieselbe Regel wie bei Akten.
if (!p.isAdmin && input.minClearance > p.clearanceLevel) {
throw new AccessError('clearance-too-low')
}
// Dieselbe Kennung zweimal erzeugt keinen zweiten Vermerk.
const vorhanden = await db.departmentEntry.findUnique({
where: { id: input.id },
select: { id: true },
})
if (vorhanden) return vorhanden
await db.$transaction(async (tx) => {
await tx.departmentEntry.create({
data: {
id: input.id,
departmentId: abteilung.id,
body: text,
minClearance: input.minClearance,
authorId: p.userId,
},
})
await writeAudit(tx, {
actorId: p.userId,
action: 'department.entry.create',
targetType: 'DepartmentEntry',
targetId: input.id,
clearanceAtTime: p.clearanceLevel,
meta: { department: abteilung.key, minClearance: input.minClearance },
})
})
return { id: input.id }
}
/**
* Ändern. Der vorherige Stand wird zur Version — in derselben Transaktion,
* sonst gäbe es einen Moment, in dem der alte Text nirgends mehr steht.
*/
export async function editEntry(
p: EffectivePermissions,
input: { id: string; body: string },
): Promise<void> {
const vermerk = await db.departmentEntry.findFirst({
where: { AND: [visibleDepartmentEntryWhere(p), { id: input.id }] },
select: { id: true, body: true, minClearance: true, authorId: true, version: true },
})
if (!vermerk) throw new AccessError('not-found')
const eigener = vermerk.authorId === p.userId
const darf =
p.isAdmin ||
(eigener && p.permissions.has('entry.edit_own')) ||
p.permissions.has('entry.edit_any')
if (!darf) throw new AccessError('no-permission')
const text = input.body.trim()
if (text.length === 0) throw new AccessError('entry-empty')
if (text === vermerk.body) return
await db.$transaction(async (tx) => {
await tx.departmentEntryVersion.create({
data: {
entryId: vermerk.id,
version: vermerk.version,
body: vermerk.body,
minClearance: vermerk.minClearance,
editedById: p.userId,
},
})
await tx.departmentEntry.update({
where: { id: vermerk.id },
data: { body: text, version: vermerk.version + 1, editedAt: new Date(), editedById: p.userId },
})
await writeAudit(tx, {
actorId: p.userId,
action: 'department.entry.edit',
targetType: 'DepartmentEntry',
targetId: vermerk.id,
clearanceAtTime: p.clearanceLevel,
meta: { version: vermerk.version + 1 },
})
})
}
/**
* Zurückziehen. Kein Löschen: der Vermerk bleibt als Grabstein stehen, mit
* Grund und Namen. Wer etwas anderes sagen will, schreibt einen neuen.
*/
export async function retractEntry(
p: EffectivePermissions,
input: { id: string; reason: string },
): Promise<void> {
const vermerk = await db.departmentEntry.findFirst({
where: { AND: [visibleDepartmentEntryWhere(p), { id: input.id }] },
select: { id: true, retractedAt: true },
})
if (!vermerk) throw new AccessError('not-found')
if (!p.isAdmin && !p.permissions.has('entry.retract')) throw new AccessError('no-permission')
if (vermerk.retractedAt) return
const grund = input.reason.trim()
if (grund.length === 0) throw new AccessError('reason-required')
await db.$transaction(async (tx) => {
await tx.departmentEntry.update({
where: { id: vermerk.id },
data: { retractedAt: new Date(), retractedById: p.userId, retractionReason: grund },
})
await writeAudit(tx, {
actorId: p.userId,
action: 'department.entry.retract',
targetType: 'DepartmentEntry',
targetId: vermerk.id,
clearanceAtTime: p.clearanceLevel,
meta: { reason: grund },
})
})
}
+377
View File
@@ -0,0 +1,377 @@
import { db } from '@/lib/db'
import { writeAudit } from '@/lib/audit/write'
import { AccessError } from '@/lib/errors'
import { visibleDepartmentWhere } from '@/lib/access/departmentFilter'
import { visibleCaseWhere } from '@/lib/access/caseFilter'
import { visibleDocumentWhere, visiblePersonnelWhere } from '@/lib/access/personnelFilter'
import { canWritePersonnel } from '@/lib/access/documentWrite'
import type { EffectivePermissions } from '@/lib/auth/permissions'
import type { Prisma } from '@afis/db'
/**
* Abteilungen — die Ebene über der Personalakte.
*
* Der Aufbau ist derselbe wie bei der Personalakte, nur eine Stufe höher: was
* zu einer Abteilung aktenkundig ist, **wird abgeleitet und nicht
* eingetragen**. Eine Fallakte trägt keine Abteilung; sie gehört zu einer,
* wenn eine beteiligte Person dieser Abteilung angehört.
*
* Das ist die wichtigste Festlegung hier. Eine eingetragene Abteilung an der
* Akte wäre schnell veraltet — Leute wechseln, Beteiligte kommen dazu — und
* niemand würde sie nachpflegen. Abgeleitet stimmt sie immer.
*
* Jede Abfrage läuft durch dieselben Sichtbarkeitsfragmente wie überall sonst.
* Eine sichtbare Abteilung ist kein Zugang zu ihrem Inhalt.
*/
export type DepartmentSummary = {
id: string
key: string
name: string
description: string | null
minClearance: number
isArchived: boolean
/** `null`, wenn der Fragende Personalakten gar nicht sehen darf. Nicht `0` —
eine Null wäre die Auskunft „hier ist niemand", und die steht ihm nicht zu. */
memberCount: number | null
}
/** Alle Abteilungen, die dieser Nutzer sehen darf. */
export async function listDepartments(
p: EffectivePermissions,
options: { includeArchived?: boolean } = {},
): Promise<DepartmentSummary[]> {
const abteilungen = await db.department.findMany({
where: {
AND: [
visibleDepartmentWhere(p),
...(options.includeArchived ? [] : [{ isArchived: false }]),
],
},
orderBy: { name: 'asc' },
select: {
id: true,
key: true,
name: true,
description: true,
minClearance: true,
isArchived: true,
},
})
if (abteilungen.length === 0) return []
// Die Mitgliederzahl zählt nur, was der Nutzer auch sehen dürfte — sonst
// verriete die Zahl, wie viele Personalakten über seiner Stufe liegen.
if (!darfPersonal(p)) {
return abteilungen.map((abteilung) => ({ ...abteilung, memberCount: null }))
}
const zaehler = await Promise.all(
abteilungen.map((abteilung) =>
db.personnelFile.count({
where: { AND: [visiblePersonnelWhere(p), { departmentId: abteilung.id }] },
}),
),
)
return abteilungen.map((abteilung, i) => ({ ...abteilung, memberCount: zaehler[i]! }))
}
export async function loadVisibleDepartment(p: EffectivePermissions, key: string) {
return db.department.findFirst({
where: { AND: [visibleDepartmentWhere(p), { key }] },
select: {
id: true,
key: true,
name: true,
description: true,
minClearance: true,
isArchived: true,
},
})
}
function darfPersonal(p: EffectivePermissions): boolean {
return p.isAdmin || p.permissions.has('personnel.read')
}
/** Die Mitglieder einer Abteilung, gefiltert wie jede Personalaktenliste. */
export async function listMembers(p: EffectivePermissions, departmentId: string) {
if (!darfPersonal(p)) return []
return db.personnelFile.findMany({
where: { AND: [visiblePersonnelWhere(p), { departmentId }] },
orderBy: { displayName: 'asc' },
select: {
id: true,
displayName: true,
rank: true,
statusTags: true,
classification: true,
},
})
}
/**
* Das Where-Fragment für „Fälle dieser Abteilung".
*
* Über die Beteiligten und deren Personalakten. Beide Richtungen zählen: ob
* jemand Ermittler oder Betroffener ist, ändert nichts daran, dass der Fall
* die Abteilung betrifft — für die Zugehörigkeit ist die Rolle unerheblich,
* für den Zugriff nicht (siehe lib/cases/terms.ts).
*/
function caseOfDepartment(departmentId: string): Prisma.CaseWhereInput {
return {
participants: { some: { personnelFile: { is: { departmentId } } } },
}
}
export async function listDepartmentCases(
p: EffectivePermissions,
departmentId: string,
take = 25,
) {
return db.case.findMany({
where: { AND: [visibleCaseWhere(p), caseOfDepartment(departmentId)] },
orderBy: { updatedAt: 'desc' },
take,
select: {
id: true,
caseNumber: true,
title: true,
status: true,
templateKey: true,
classification: true,
updatedAt: true,
},
})
}
/**
* Dokumente der Abteilung — abgeleitet wie alles hier.
*
* Zwei Wege dorthin: das Dokument hängt an der Personalakte eines Mitglieds,
* oder an einer Fallakte, die diese Abteilung betrifft. Ein Dokument
* unmittelbar an der Abteilung gibt es nicht: die Vorlagen kennen über
* `TemplateUse` nur Fall- und Personalakte, und ein Besitzer, für den es keine
* Vorlage gibt, wäre ein Feld, das nichts füllen kann.
*/
export async function listDepartmentDocuments(
p: EffectivePermissions,
departmentId: string,
take = 25,
) {
const gehoertDazu: Prisma.DocumentWhereInput = {
OR: [
{ case: { is: caseOfDepartment(departmentId) } },
...(darfPersonal(p)
? [{ personnelFile: { is: { departmentId } } } as Prisma.DocumentWhereInput]
: []),
],
}
return db.document.findMany({
where: { AND: [visibleDocumentWhere(p), gehoertDazu] },
orderBy: { updatedAt: 'desc' },
take,
select: {
id: true,
documentNumber: true,
title: true,
status: true,
classification: true,
updatedAt: true,
},
})
}
export type Slice = { label: string; value: number }
/**
* Womit diese Abteilung aktenkundig ist, nach Fallart.
*
* Gezählt wird über **dieselbe** Bedingung wie die Liste. Ein Diagramm, das
* mehr Fälle zeigt als die Liste hergibt, wäre selbst eine Auskunft — genau
* wie ein Facettenzähler. Siehe harte Regel 6.
*/
export async function caseTypesOfDepartment(
p: EffectivePermissions,
departmentId: string,
): Promise<Slice[]> {
const gruppen = await db.case.groupBy({
by: ['templateKey'],
where: { AND: [visibleCaseWhere(p), caseOfDepartment(departmentId)] },
_count: { _all: true },
})
return gruppen
.map((gruppe) => ({ label: gruppe.templateKey, value: gruppe._count._all }))
.sort((a, b) => b.value - a.value)
}
/**
* Die Gegenrichtung: welche Abteilung wie viele Fälle hat.
*
* Das ist die Frage, mit der die Übersicht der Abteilungen anfängt — wo häuft
* sich etwas. Auch hier zählt nur, was der Fragende sehen darf.
*/
export async function casesPerDepartment(p: EffectivePermissions): Promise<Slice[]> {
const abteilungen = await db.department.findMany({
where: { AND: [visibleDepartmentWhere(p), { isArchived: false }] },
select: { id: true, name: true },
})
const zahlen = await Promise.all(
abteilungen.map((abteilung) =>
db.case.count({
where: { AND: [visibleCaseWhere(p), caseOfDepartment(abteilung.id)] },
}),
),
)
return abteilungen
.map((abteilung, i) => ({ label: abteilung.name, value: zahlen[i]! }))
.filter((eintrag) => eintrag.value > 0)
.sort((a, b) => b.value - a.value)
}
// ---------------------------------------------------------------------------
// Verwaltung
// ---------------------------------------------------------------------------
function darfVerwalten(p: EffectivePermissions): boolean {
return p.isAdmin || p.permissions.has('roles.manage')
}
export async function createDepartment(
p: EffectivePermissions,
input: { key: string; name: string; description?: string | null; minClearance: number },
): Promise<{ key: string }> {
if (!darfVerwalten(p)) throw new AccessError('no-permission')
// Eine Abteilung anzulegen, die man selbst nicht sieht, ergibt keinen Sinn —
// dieselbe Regel wie bei Akten und Dokumenten.
if (!p.isAdmin && input.minClearance > p.clearanceLevel) {
throw new AccessError('clearance-too-low')
}
const key = input.key.trim().toUpperCase()
if (!/^[A-Z0-9][A-Z0-9-]{0,20}$/.test(key)) throw new AccessError('department-key-invalid')
const name = input.name.trim()
if (name.length === 0) throw new AccessError('department-name-missing')
const vorhanden = await db.department.findUnique({ where: { key }, select: { id: true } })
if (vorhanden) throw new AccessError('department-key-taken')
const abteilung = await db.$transaction(async (tx) => {
const angelegt = await tx.department.create({
data: {
key,
name,
description: input.description?.trim() || null,
minClearance: input.minClearance,
createdById: p.userId,
},
select: { id: true, key: true },
})
await writeAudit(tx, {
actorId: p.userId,
action: 'department.create',
targetType: 'Department',
targetId: angelegt.id,
clearanceAtTime: p.clearanceLevel,
meta: { key, name },
})
return angelegt
})
return { key: abteilung.key }
}
export async function updateDepartment(
p: EffectivePermissions,
input: {
id: string
name: string
description?: string | null
minClearance: number
isArchived: boolean
},
): Promise<void> {
if (!darfVerwalten(p)) throw new AccessError('no-permission')
if (!p.isAdmin && input.minClearance > p.clearanceLevel) {
throw new AccessError('clearance-too-low')
}
const abteilung = await db.department.findFirst({
where: { AND: [visibleDepartmentWhere(p), { id: input.id }] },
select: { id: true },
})
if (!abteilung) throw new AccessError('not-found')
const name = input.name.trim()
if (name.length === 0) throw new AccessError('department-name-missing')
await db.$transaction(async (tx) => {
await tx.department.update({
where: { id: input.id },
data: {
name,
description: input.description?.trim() || null,
minClearance: input.minClearance,
isArchived: input.isArchived,
},
})
await writeAudit(tx, {
actorId: p.userId,
action: 'department.update',
targetType: 'Department',
targetId: input.id,
clearanceAtTime: p.clearanceLevel,
meta: { name, minClearance: input.minClearance, isArchived: input.isArchived },
})
})
}
/**
* Eine Person einer Abteilung zuordnen — oder die Zuordnung aufheben.
*
* Setzt dasselbe Recht voraus wie das Ändern der Personalakte selbst: die
* Zugehörigkeit steht in der Akte, und wer sie nicht schreiben darf, darf auch
* das nicht.
*/
export async function assignToDepartment(
p: EffectivePermissions,
input: { personnelFileId: string; departmentId: string | null },
): Promise<void> {
const akte = await db.personnelFile.findFirst({
where: { AND: [visiblePersonnelWhere(p), { id: input.personnelFileId }] },
select: { id: true, classification: true, departmentId: true },
})
if (!akte || !darfPersonal(p)) throw new AccessError('not-found')
const erlaubt = canWritePersonnel(p, akte.classification)
if (!erlaubt.ok) throw new AccessError(erlaubt.reason)
if (input.departmentId) {
const ziel = await db.department.findFirst({
where: { AND: [visibleDepartmentWhere(p), { id: input.departmentId, isArchived: false }] },
select: { id: true },
})
if (!ziel) throw new AccessError('not-found')
}
await db.$transaction(async (tx) => {
await tx.personnelFile.update({
where: { id: akte.id },
data: { departmentId: input.departmentId },
})
await writeAudit(tx, {
actorId: p.userId,
action: 'department.assign',
targetType: 'PersonnelFile',
targetId: akte.id,
clearanceAtTime: p.clearanceLevel,
meta: { from: akte.departmentId, to: input.departmentId },
})
})
}
+10
View File
@@ -50,6 +50,12 @@ export const auditText = {
'attachment.read': 'Datei abgerufen',
'attachment.release': 'Datei freigegeben',
'chat.adopt': 'Nachricht als Vermerk übernommen',
'department.create': 'Abteilung angelegt',
'department.update': 'Abteilung geändert',
'department.assign': 'Abteilung zugeordnet',
'department.entry.create': 'Abteilungsvermerk angelegt',
'department.entry.edit': 'Abteilungsvermerk geändert',
'department.entry.retract': 'Abteilungsvermerk zurückgezogen',
'roles.update': 'Rollenzuordnung geändert',
'export.pdf': 'PDF erzeugt',
'export.approve': 'Export freigegeben',
@@ -70,6 +76,8 @@ export const auditText = {
RoleMapping: 'Rollenzuordnung',
ChangePolicy: 'Änderungsrichtlinie',
Database: 'Datenbank',
Department: 'Abteilung',
DepartmentEntry: 'Abteilungsvermerk',
} as Record<string, string>,
} as const
@@ -78,6 +86,7 @@ export const adminText = {
intro: 'Rollen, Vorlagen, Regeln und das Protokoll der Abteilung.',
sections: {
roles: 'Rollen',
departments: 'Abteilungen',
templates: 'Vorlagen',
policy: 'Änderungsrichtlinie',
log: 'Protokoll',
@@ -85,6 +94,7 @@ export const adminText = {
} as Record<string, string>,
descriptions: {
roles: 'Welche Discord-Rolle welche Freigabestufe und welche Rechte trägt.',
departments: 'Die Abteilungen der Foundation. Zugeordnet wird in der Personalakte.',
templates: 'Aufbau der Fallakten und Dokumente, Bausteine und Fassungen.',
policy: 'Ob und wie lange Verlaufseinträge nachträglich geändert werden dürfen.',
log: 'Wer was wo getan hat. Vollständig und nicht änderbar.',
+5
View File
@@ -27,6 +27,10 @@ export const commonText = {
*/
export const actionErrorsText = {
'not-found': 'Die Akte gibt es nicht, oder du darfst sie nicht sehen.',
'department-key-invalid':
'Kürzel: Grossbuchstaben, Ziffern und Bindestrich, höchstens 21 Zeichen.',
'department-key-taken': 'Dieses Kürzel gibt es schon.',
'department-name-missing': 'Die Abteilung braucht einen Namen.',
'clearance-too-low': 'Deine Freigabestufe reicht dafür nicht.',
'no-permission': 'Dir fehlt das nötige Recht.',
'read-only': 'Der Datensatz ist schreibgeschützt.',
@@ -40,6 +44,7 @@ export const actionErrorsText = {
'participant-target': 'Entweder ein Discord-Konto oder eine Personalakte, nicht beides.',
'link-self': 'Eine Akte lässt sich nicht mit sich selbst verknüpfen.',
'message-empty': 'Die Nachricht ist leer.',
'entry-empty': 'Der Vermerk ist leer.',
'message-too-long': 'Die Nachricht ist länger als 4000 Zeichen.',
'message-withdrawn': 'Die Nachricht wurde zurückgezogen.',
'adopt-needs-case': 'Nur eine Nachricht aus einem Aktenchat wird zum Vermerk.',
+8
View File
@@ -41,6 +41,11 @@ import { chatText } from '@/lib/i18n/chat'
import { personnelText, assignmentText } from '@/lib/i18n/people'
import { documentText, attachmentText } from '@/lib/i18n/documents'
import { exportText } from '@/lib/i18n/export'
import {
departmentText,
departmentAdminText,
departmentEntryText,
} from '@/lib/i18n/departments'
import {
adminText,
auditText,
@@ -70,6 +75,9 @@ export const de = {
document: documentText,
attachment: attachmentText,
export: exportText,
department: departmentText,
departmentAdmin: departmentAdminText,
departmentEntry: departmentEntryText,
common: commonText,
actionErrors: actionErrorsText,
errors: errorsText,
+69
View File
@@ -0,0 +1,69 @@
/**
* Abteilungen. Die Bezeichnungen der Abteilungen selbst stehen **nicht** hier:
* das sind Daten, im Adminbereich änderbar, so wie die Namen der
* Freigabestufen. Siehe CLAUDE.md, Sprachkonvention.
*/
export const departmentText = {
heading: 'Abteilungen',
one: 'Abteilung',
intro: 'Was zu einer Abteilung aktenkundig ist, ergibt sich aus ihren Mitgliedern.',
empty: 'Noch keine Abteilung. Die Abteilungsleitung legt sie im Adminbereich an.',
members: 'Mitglieder',
membersEmpty: 'Dieser Abteilung ist niemand zugeordnet.',
memberCount: (n: number) => (n === 1 ? '1 Mitglied' : `${n} Mitglieder`),
cases: 'Fallakten',
casesEmpty: 'Zu dieser Abteilung ist keine Fallakte offen einsehbar.',
documents: 'Dokumente',
documentsEmpty: 'Kein Dokument zu dieser Abteilung.',
entries: 'Vermerke',
entriesEmpty: 'Noch kein Vermerk. Ersten Vermerk schreiben.',
chart: 'Fallarten',
chartAll: 'Fälle je Abteilung',
chartEmpty: 'Noch keine Fallakte, aus der sich etwas ablesen liesse.',
chartTotal: (n: number) => (n === 1 ? '1 Fallakte' : `${n} Fallakten`),
minClearance: 'Mindeststufe',
archived: 'Archiviert',
derivedHint:
'Eine Fallakte gehört zu dieser Abteilung, wenn eine beteiligte Person ihr angehört. Die Zuordnung wird nicht eingetragen, sondern ergibt sich — damit stimmt sie auch, wenn sich die Beteiligten ändern.',
} as const
export const departmentAdminText = {
heading: 'Abteilungen',
intro:
'Die Abteilungen der Foundation. Personen werden in ihrer Personalakte zugeordnet.',
create: 'Abteilung anlegen',
createTitle: 'Neue Abteilung',
key: 'Kürzel',
keyHint: 'Grossbuchstaben, Ziffern und Bindestrich. Steht später in der Adresse.',
name: 'Name',
description: 'Beschreibung',
minClearance: 'Mindeststufe',
minClearanceHint: 'Wer diese Stufe nicht hat, sieht die Abteilung nicht.',
archived: 'Archiviert',
archivedHint: 'Archivierte Abteilungen stehen nicht mehr zur Auswahl.',
save: 'Abteilung speichern',
edit: 'Ändern',
cancel: 'Abbrechen',
saved: 'Abteilung gespeichert',
created: 'Abteilung angelegt',
empty: 'Noch keine Abteilung angelegt.',
members: 'Mitglieder',
} as const
export const departmentEntryText = {
heading: 'Vermerke',
add: 'Vermerk schreiben',
body: 'Vermerk',
save: 'Vermerk speichern',
saving: 'Wird gespeichert',
edit: 'Ändern',
editSave: 'Änderung speichern',
cancel: 'Abbrechen',
retract: 'Zurückziehen',
retractReason: 'Grund der Zurücknahme',
retracted: 'Zurückgezogen',
retractedBy: (wer: string, grund: string) => `Zurückgezogen von ${wer}: ${grund}`,
edited: (v: number) => `geändert, Fassung ${v}`,
minClearance: 'Sichtbar ab Stufe',
hint: 'Vermerke lassen sich ändern und zurückziehen, aber nie unsichtbar machen: jede Fassung bleibt, jede Zurücknahme hinterlässt einen Grabstein.',
} as const
+1
View File
@@ -17,6 +17,7 @@ export const personnelText = {
name: 'Name',
rank: 'Dienstgrad',
department: 'Abteilung',
noDepartment: 'Keine Abteilung',
status: 'Status',
statusHint: 'Mehrere möglich. „Gekündigt" und „Verhaftet" schließen einander nicht aus.',
statusNone: 'Kein Status gesetzt',
+2
View File
@@ -20,6 +20,7 @@ export const navText = {
dashboard: 'Übersicht',
cases: 'Fallakten',
personnel: 'Personalakten',
departments: 'Abteilungen',
search: 'Suche',
admin: 'Admin',
skipToContent: 'Zum Inhalt springen',
@@ -180,6 +181,7 @@ export const paletteText = {
{ href: '/faelle', label: 'Fallakten' },
{ href: '/faelle/neu', label: 'Neue Fallakte' },
{ href: '/personalakten', label: 'Personalakten' },
{ href: '/abteilungen', label: 'Abteilungen' },
{ href: '/suche', label: 'Suche' },
{ href: '/admin', label: 'Admin' },
{ href: '/admin/protokoll', label: 'Protokoll' },
+9 -7
View File
@@ -21,7 +21,8 @@ const KOPFDATEN = {
userId: true,
displayName: true,
rank: true,
department: true,
departmentId: true,
department: { select: { id: true, key: true, name: true } },
statusTags: true,
note: true,
classification: true,
@@ -57,7 +58,8 @@ export async function listPersonnelFiles(
OR: [
{ displayName: { contains: begriff, mode: 'insensitive' as const } },
{ rank: { contains: begriff, mode: 'insensitive' as const } },
{ department: { contains: begriff, mode: 'insensitive' as const } },
{ department: { is: { name: { contains: begriff, mode: 'insensitive' as const } } } },
{ department: { is: { key: { contains: begriff, mode: 'insensitive' as const } } } },
],
},
]
@@ -84,7 +86,7 @@ export async function createPersonnelFile(
displayName: string
userId?: string | null
rank?: string | null
department?: string | null
departmentId?: string | null
statusTags?: string[]
note?: string | null
classification: number
@@ -101,7 +103,7 @@ export async function createPersonnelFile(
displayName: name,
userId: input.userId || null,
rank: input.rank?.trim() || null,
department: input.department?.trim() || null,
departmentId: input.departmentId || null,
statusTags: await gueltigeStatusEtiketten(input.statusTags),
note: input.note?.trim() || null,
classification: input.classification,
@@ -130,7 +132,7 @@ export async function updatePersonnelFile(
input: {
displayName?: string
rank?: string | null
department?: string | null
departmentId?: string | null
statusTags?: string[]
note?: string | null
},
@@ -148,8 +150,8 @@ export async function updatePersonnelFile(
data: {
...(name !== undefined ? { displayName: name } : {}),
...(input.rank !== undefined ? { rank: input.rank?.trim() || null } : {}),
...(input.department !== undefined
? { department: input.department?.trim() || null }
...(input.departmentId !== undefined
? { departmentId: input.departmentId || null }
: {}),
...(input.statusTags !== undefined
? { statusTags: await gueltigeStatusEtiketten(input.statusTags) }
+8 -1
View File
@@ -29,7 +29,11 @@ export type EventKind =
| 'export.ready'
/** Wer das Ereignis angeht. */
export type Topic = `case:${string}` | `personnel:${string}` | `user:${string}`
export type Topic =
| `case:${string}`
| `personnel:${string}`
| `department:${string}`
| `user:${string}`
export function caseTopic(caseId: string): Topic {
return `case:${caseId}`
@@ -37,6 +41,9 @@ export function caseTopic(caseId: string): Topic {
export function personnelTopic(fileId: string): Topic {
return `personnel:${fileId}`
}
export function departmentTopic(departmentId: string): Topic {
return `department:${departmentId}`
}
export function userTopic(userId: string): Topic {
return `user:${userId}`
}