Phase 6 abgeschlossen: Aktenchat, Kanäle, Echtzeit, Benachrichtigungen

Ein Ereignisstrom mit Themen (/api/stream), in dem der Dateistrom aus Phase 5
aufgegangen ist. Zwei Prüfungen: beim Verbinden, welche Themen der Nutzer
abonnieren darf, und je Ereignis wird der Inhalt mit seinen Rechten geladen.
Das zweite ist nicht nur Vorsicht — eine Umklassifizierung wirkt dadurch in
einer offenen Verbindung sofort. In der pg_notify-Nutzlast steht nie ein
Inhalt, nur Thema, Art und Kennung.

Der Aktenchat sendet optimistisch mit clientseitiger UUIDv7, die zugleich
Idempotenzschlüssel ist. Antworten, vier feste Reaktionen, Bearbeiten mit
sichtbarem editedAt, Zurückziehen mit Platzhalter — Löschen gibt es nicht, und
eine Regel in der Datenbank hält das fest. Eine zurückgezogene Nachricht kommt
ohne Text an, nicht ausgeblendet.

Aktenzeichen im Text werden zu Vorschaukarten, serverseitig aufgelöst. Eine
Akte, die der Leser nicht sehen darf, sieht darin genauso aus wie eine, die es
gar nicht gibt.

"Als Vermerk übernehmen" steht sichtbar an jeder Nachricht. Der Vermerk gehört
dem Verfasser, nicht dem Übernehmenden; ein Systemeintrag nennt den Ursprung,
damit der Wortlaut später nicht für die Akte geschrieben wirkt.

Bei den Discord-Benachrichtigungen entscheidet die Web-App, wer was erfährt,
und der Worker liefert nur aus. Die Alternative hätte geheissen, die
Sichtbarkeitsprüfung im Worker ein zweites Mal zu bauen. In meta steht ein
Titel nur, wenn er hinaus darf — ab Stufe 3 keiner. Postausgang als Tabelle,
angestossen über LISTEN, mit Takt als Sicherheitsnetz.

Nebenbei riss das Budget der Fallakte erneut (122 kB). Drei Schritte zurück
auf 119,6: Chattexte in eine eigene i18n-Datei, ein gemeinsames AddPanel statt
viermal derselbe Aufklapp-Code, und eine eigene UUIDv7 statt des Pakets — die
Sortierbarkeit, auf der die Nachlieferung beruht, steht damit im eigenen Code
und hat Tests.

Unterwegs habe ich NotifyMode und User.notifyMode ein zweites Mal angelegt,
obwohl es beides seit dem Grundgerüst gibt. Die Migration schlug fehl und die
Datenbank musste von Hand aufgeräumt werden; die Lehre steht in docs/13.

155 Tests im Web-Paket, 15 in der Datenbank, 7 im Worker, 32 e2e.
This commit is contained in:
Harlekin
2026-09-02 21:06:03 +02:00
parent 10eeea4897
commit cf4348b8b1
59 changed files with 3776 additions and 510 deletions
+128
View File
@@ -0,0 +1,128 @@
'use server'
import { revalidatePath } from 'next/cache'
import { z } from 'zod'
import { requireUser } from '@/lib/auth/current'
import { AccessError } from '@/lib/errors'
import {
adoptAsEntry,
editMessage,
markRead,
sendMessage,
toggleReaction,
withdrawMessage,
} from '@/lib/chat/service'
import { REACTIONS } from '@/lib/chat/terms'
import { de } from '@/lib/i18n/de'
export type ActionResult = { ok: true } | { ok: false; error: string }
function toMessage(error: unknown): string {
if (error instanceof AccessError) {
return de.actionErrors[error.code] ?? de.actionErrors.default!
}
console.error('[chat] unerwartet', error)
return de.actionErrors.default!
}
const scope = z.union([
z.object({ kind: z.literal('case'), caseNumber: z.string().min(1) }),
z.object({ kind: z.literal('channel'), key: z.string().min(1) }),
])
const sendSchema = z.object({
id: z.string().min(1).max(64),
scope,
body: z.string().min(1).max(4000),
replyToId: z.string().max(64).nullish(),
})
export async function sendMessageAction(input: unknown): Promise<ActionResult> {
const user = await requireUser()
const parsed = sendSchema.safeParse(input)
if (!parsed.success) return { ok: false, error: de.actionErrors['message-empty']! }
try {
await sendMessage(user.permissions, parsed.data)
return { ok: true }
} catch (error) {
return { ok: false, error: toMessage(error) }
}
}
const editSchema = z.object({ id: z.string().min(1), body: z.string().min(1).max(4000) })
export async function editMessageAction(input: unknown): Promise<ActionResult> {
const user = await requireUser()
const parsed = editSchema.safeParse(input)
if (!parsed.success) return { ok: false, error: de.actionErrors['message-empty']! }
try {
await editMessage(user.permissions, parsed.data)
return { ok: true }
} catch (error) {
return { ok: false, error: toMessage(error) }
}
}
const idSchema = z.object({ id: z.string().min(1) })
export async function withdrawMessageAction(input: unknown): Promise<ActionResult> {
const user = await requireUser()
const parsed = idSchema.safeParse(input)
if (!parsed.success) return { ok: false, error: de.actionErrors.default! }
try {
await withdrawMessage(user.permissions, parsed.data.id)
return { ok: true }
} catch (error) {
return { ok: false, error: toMessage(error) }
}
}
const reactionSchema = z.object({ id: z.string().min(1), key: z.enum(REACTIONS) })
export async function toggleReactionAction(input: unknown): Promise<ActionResult> {
const user = await requireUser()
const parsed = reactionSchema.safeParse(input)
if (!parsed.success) return { ok: false, error: de.actionErrors.default! }
try {
await toggleReaction(user.permissions, parsed.data)
return { ok: true }
} catch (error) {
return { ok: false, error: toMessage(error) }
}
}
/**
* „Als Vermerk übernehmen". Danach wird die Akte neu geladen: der Vermerk
* gehört in den Verlauf, und der steht auf derselben Seite.
*/
export async function adoptAsEntryAction(input: unknown): Promise<ActionResult> {
const user = await requireUser()
const parsed = idSchema.safeParse(input)
if (!parsed.success) return { ok: false, error: de.actionErrors.default! }
try {
await adoptAsEntry(user.permissions, parsed.data.id)
revalidatePath('/faelle', 'layout')
return { ok: true }
} catch (error) {
return { ok: false, error: toMessage(error) }
}
}
const readSchema = z.object({
scopeType: z.enum(['case', 'channel']),
scopeId: z.string().min(1),
})
export async function markReadAction(input: unknown): Promise<ActionResult> {
const user = await requireUser()
const parsed = readSchema.safeParse(input)
if (!parsed.success) return { ok: false, error: de.actionErrors.default! }
await markRead(user.permissions, parsed.data.scopeType, parsed.data.scopeId)
return { ok: true }
}
@@ -47,6 +47,7 @@ async function Body({
title: string
layout: string
createdAt: Date
caseId: string | null
}
permissions: EffectivePermissions
canEdit: boolean
@@ -69,6 +70,7 @@ async function Body({
sections={sections}
canEdit={canEdit}
documentNumber={document.documentNumber}
topic={document.caseId ? `case:${document.caseId}` : `user:${permissions.userId}`}
photoUrls={photoUrls}
/>
)
@@ -108,11 +110,13 @@ async function Body({
async function AttachmentBlock({
documentId,
documentNumber,
topic,
permissions,
canUpload,
}: {
documentId: string
documentNumber: string
topic: string
permissions: EffectivePermissions
canUpload: boolean
}) {
@@ -120,6 +124,7 @@ async function AttachmentBlock({
return (
<Attachments
target={{ documentNumber }}
topic={topic}
initial={toAttachmentViews(anhaenge)}
canUpload={canUpload}
canRelease={permissions.isAdmin}
@@ -274,6 +279,7 @@ export default async function DocumentPage({
<AttachmentBlock
documentId={doc.id}
documentNumber={doc.documentNumber}
topic={doc.caseId ? `case:${doc.caseId}` : `user:${user.id}`}
permissions={user.permissions}
canUpload={canEdit}
/>
@@ -0,0 +1,46 @@
'use client'
import { useActionState } from 'react'
import { notifyText } from '@/lib/i18n/shell'
import { saveNotifyModeAction, type ActionResult } from './actions'
const MODES = ['ALL', 'OWN_CASES', 'MENTIONS', 'OFF'] as const
export function NotifyForm({ current }: { current: string }) {
const [state, action, pending] = useActionState<ActionResult | null, FormData>(
saveNotifyModeAction,
null,
)
return (
<form action={action} className="mt-6">
<fieldset>
<legend className="font-condensed text-xs text-text-dim">{notifyText.mode}</legend>
<div className="mt-3 space-y-2">
{MODES.map((mode) => (
<label key={mode} className="flex items-center gap-3 text-sm">
<input type="radio" name="notifyMode" value={mode} defaultChecked={current === mode} />
{notifyText.modes[mode]}
</label>
))}
</div>
</fieldset>
<div className="mt-5 flex items-center gap-3">
<button
type="submit"
disabled={pending}
className="border border-line bg-raised px-4 py-2 font-condensed text-xs text-accent disabled:text-text-dim"
>
{notifyText.save}
</button>
{state?.ok ? (
<span className="font-condensed text-2xs text-text-dim">{notifyText.saved}</span>
) : null}
{state && !state.ok ? (
<span className="font-condensed text-2xs text-stamp-4">{state.error}</span>
) : null}
</div>
</form>
)
}
+28
View File
@@ -0,0 +1,28 @@
'use server'
import { revalidatePath } from 'next/cache'
import { z } from 'zod'
import { db } from '@/lib/db'
import { requireUser } from '@/lib/auth/current'
import { de } from '@/lib/i18n/de'
export type ActionResult = { ok: true } | { ok: false; error: string }
const schema = z.object({ notifyMode: z.enum(['ALL', 'OWN_CASES', 'MENTIONS', 'OFF']) })
/** Jeder stellt nur für sich selbst ein — die Kennung kommt aus der Sitzung. */
export async function saveNotifyModeAction(
_prev: ActionResult | null,
formData: FormData,
): Promise<ActionResult> {
const user = await requireUser()
const parsed = schema.safeParse(Object.fromEntries(formData))
if (!parsed.success) return { ok: false, error: de.actionErrors.default! }
await db.user.update({
where: { id: user.id },
data: { notifyMode: parsed.data.notifyMode },
})
revalidatePath('/einstellungen')
return { ok: true }
}
+24
View File
@@ -0,0 +1,24 @@
import type { Metadata } from 'next'
import { db } from '@/lib/db'
import { requireUser } from '@/lib/auth/current'
import { de } from '@/lib/i18n/de'
import { NotifyForm } from './NotifyForm'
export const metadata: Metadata = { title: de.notify.heading }
export const dynamic = 'force-dynamic'
export default async function SettingsPage() {
const user = await requireUser()
const eigen = await db.user.findUniqueOrThrow({
where: { id: user.id },
select: { notifyMode: true },
})
return (
<main className="mx-auto max-w-(--container-measure) px-6 py-10">
<h1 className="font-condensed">{de.notify.heading}</h1>
<p className="mt-2 text-sm text-text-dim">{de.notify.intro}</p>
<NotifyForm current={eigen.notifyMode} />
</main>
)
}
+34 -68
View File
@@ -3,10 +3,10 @@
import { useState, useTransition } from 'react'
import Link from 'next/link'
import { linkText } from '@/lib/i18n/cases'
import { commonText } from '@/lib/i18n/common'
import { LINK_KINDS } from '@/lib/cases/terms'
import { linkCasesAction, unlinkCasesAction } from '../actions'
import { AddPanel, PanelSelect } from '@/components/AddPanel'
import { classificationEdgeStyle } from '@/components/StampMark'
import { linkCasesAction, unlinkCasesAction } from '../actions'
type Verknuepfung = {
kind: string
@@ -29,10 +29,9 @@ export function CaseLinks({
links: Verknuepfung[]
canEdit: boolean
}) {
const [open, setOpen] = useState(false)
const [target, setTarget] = useState('')
const [kind, setKind] = useState<string>('RELATED')
const [error, setError] = useState<string | null>(null)
const [fehler, setFehler] = useState<string | null>(null)
const [pending, startTransition] = useTransition()
return (
@@ -65,12 +64,12 @@ export function CaseLinks({
disabled={pending}
onClick={() =>
startTransition(async () => {
const result = await unlinkCasesAction({
const ergebnis = await unlinkCasesAction({
fromCaseNumber: caseNumber,
toCaseNumber: link.other.caseNumber,
kind: link.kind,
})
if (!result.ok) setError(result.error)
if (!ergebnis.ok) setFehler(ergebnis.error)
})
}
className="font-condensed text-2xs text-text-dim"
@@ -83,70 +82,37 @@ export function CaseLinks({
</ul>
)}
{error ? <p className="mt-2 font-condensed text-2xs text-stamp-4">{error}</p> : null}
{fehler ? <p className="mt-2 font-condensed text-2xs text-stamp-4">{fehler}</p> : null}
{canEdit ? (
open ? (
<div className="mt-4 flex flex-wrap items-center gap-2">
<select
value={kind}
onChange={(event) => setKind(event.target.value)}
aria-label={linkText.kind}
className="border border-line bg-raised px-2 py-1 text-2xs"
>
{LINK_KINDS.map((value) => (
<option key={value} value={value}>
{linkText.kinds[value] ?? value}
</option>
))}
</select>
<input
value={target}
onChange={(event) => setTarget(event.target.value)}
placeholder={linkText.target}
aria-label={linkText.target}
className="border border-line bg-raised px-2 py-1 font-mono text-2xs"
/>
<button
type="button"
disabled={pending || target.trim() === ''}
onClick={() =>
startTransition(async () => {
setError(null)
const result = await linkCasesAction({
fromCaseNumber: caseNumber,
toCaseNumber: target.trim(),
kind,
})
if (result.ok) {
setTarget('')
setOpen(false)
} else {
setError(result.error)
}
})
}
className="border border-line bg-raised px-3 py-1 font-condensed text-2xs text-accent disabled:text-text-dim"
>
{linkText.add}
</button>
<button
type="button"
onClick={() => setOpen(false)}
className="font-condensed text-2xs text-text-dim"
>
{commonText.cancel}
</button>
</div>
) : (
<button
type="button"
onClick={() => setOpen(true)}
className="mt-4 border border-line bg-raised px-3 py-1 font-condensed text-2xs text-accent"
>
{linkText.add}
</button>
)
<AddPanel
label={linkText.add}
disabled={target.trim() === ''}
onSubmit={async () => {
const ergebnis = await linkCasesAction({
fromCaseNumber: caseNumber,
toCaseNumber: target.trim(),
kind,
})
if (ergebnis.ok) setTarget('')
return ergebnis
}}
>
<PanelSelect value={kind} onChange={setKind} label={linkText.kind}>
{LINK_KINDS.map((value) => (
<option key={value} value={value}>
{linkText.kinds[value] ?? value}
</option>
))}
</PanelSelect>
<input
value={target}
onChange={(event) => setTarget(event.target.value)}
placeholder={linkText.target}
aria-label={linkText.target}
className="border border-line bg-raised px-2 py-1 font-mono text-2xs"
/>
</AddPanel>
) : null}
</div>
)
@@ -1,7 +1,7 @@
'use client'
import { useOptimistic, useRef, useState, useTransition } from 'react'
import { uuidv7 } from 'uuidv7'
import { uuidv7 } from '@/lib/uuidv7'
import { caseText, entryText } from '@/lib/i18n/cases'
import { addEntryAction } from '../actions'
@@ -2,9 +2,10 @@
import { useState, useTransition } from 'react'
import Link from 'next/link'
import { participantText } from '@/lib/i18n/cases'
import { commonText } from '@/lib/i18n/common'
import { participantText } from '@/lib/i18n/cases'
import { PARTICIPANT_ROLES } from '@/lib/cases/terms'
import { AddPanel, PanelSelect } from '@/components/AddPanel'
import { addParticipantAction, removeParticipantAction } from '../actions'
type Beteiligter = {
@@ -35,31 +36,11 @@ export function Participants({
members: { id: string; displayName: string }[]
files: { id: string; displayName: string }[]
}) {
const [open, setOpen] = useState(false)
const [role, setRole] = useState<string>('INVESTIGATOR')
const [target, setTarget] = useState('')
const [error, setError] = useState<string | null>(null)
const [fehler, setFehler] = useState<string | null>(null)
const [pending, startTransition] = useTransition()
function add() {
if (!target) return
setError(null)
const [art, id] = target.split(':')
startTransition(async () => {
const result = await addParticipantAction({
caseNumber,
role,
...(art === 'user' ? { userId: id } : { personnelFileId: id }),
})
if (result.ok) {
setTarget('')
setOpen(false)
} else {
setError(result.error)
}
})
}
return (
<div>
{participants.length === 0 ? (
@@ -89,11 +70,11 @@ export function Participants({
disabled={pending}
onClick={() =>
startTransition(async () => {
const result = await removeParticipantAction({
const ergebnis = await removeParticipantAction({
caseNumber,
participantId: person.id,
})
if (!result.ok) setError(result.error)
if (!ergebnis.ok) setFehler(ergebnis.error)
})
}
className="font-condensed text-2xs text-text-dim"
@@ -106,75 +87,49 @@ export function Participants({
</ul>
)}
{error ? <p className="mt-2 font-condensed text-2xs text-stamp-4">{error}</p> : null}
{fehler ? <p className="mt-2 font-condensed text-2xs text-stamp-4">{fehler}</p> : null}
{canEdit ? (
open ? (
<div className="mt-4 border border-line p-3">
<p className="max-w-(--container-measure) text-2xs text-text-dim">
{participantText.hint}
</p>
<div className="mt-3 flex flex-wrap items-center gap-2">
<select
value={role}
onChange={(event) => setRole(event.target.value)}
aria-label={participantText.role}
className="border border-line bg-raised px-2 py-1 text-2xs"
>
{PARTICIPANT_ROLES.map((value) => (
<option key={value} value={value}>
{participantText.roles[value] ?? value}
</option>
))}
</select>
<select
value={target}
onChange={(event) => setTarget(event.target.value)}
aria-label={participantText.person}
className="border border-line bg-raised px-2 py-1 text-2xs"
>
<option value="">—</option>
<optgroup label={participantText.pickUser}>
{members.map((member) => (
<option key={member.id} value={`user:${member.id}`}>
{member.displayName}
</option>
))}
</optgroup>
<optgroup label={participantText.pickPersonnel}>
{files.map((file) => (
<option key={file.id} value={`file:${file.id}`}>
{file.displayName}
</option>
))}
</optgroup>
</select>
<button
type="button"
disabled={pending || !target}
onClick={add}
className="border border-line bg-raised px-3 py-1 font-condensed text-2xs text-accent disabled:text-text-dim"
>
{participantText.add}
</button>
<button
type="button"
onClick={() => setOpen(false)}
className="font-condensed text-2xs text-text-dim"
>
{commonText.cancel}
</button>
</div>
</div>
) : (
<button
type="button"
onClick={() => setOpen(true)}
className="mt-4 border border-line bg-raised px-3 py-1 font-condensed text-2xs text-accent"
>
{participantText.add}
</button>
)
<AddPanel
label={participantText.add}
hint={participantText.hint}
disabled={!target}
onSubmit={async () => {
const [art, id] = target.split(':')
const ergebnis = await addParticipantAction({
caseNumber,
role,
...(art === 'user' ? { userId: id } : { personnelFileId: id }),
})
if (ergebnis.ok) setTarget('')
return ergebnis
}}
>
<PanelSelect value={role} onChange={setRole} label={participantText.role}>
{PARTICIPANT_ROLES.map((value) => (
<option key={value} value={value}>
{participantText.roles[value] ?? value}
</option>
))}
</PanelSelect>
<PanelSelect value={target} onChange={setTarget} label={participantText.person}>
<option value="">—</option>
<optgroup label={participantText.pickUser}>
{members.map((member) => (
<option key={member.id} value={`user:${member.id}`}>
{member.displayName}
</option>
))}
</optgroup>
<optgroup label={participantText.pickPersonnel}>
{files.map((file) => (
<option key={file.id} value={`file:${file.id}`}>
{file.displayName}
</option>
))}
</optgroup>
</PanelSelect>
</AddPanel>
) : null}
</div>
)
@@ -25,6 +25,8 @@ import { visiblePersonnelWhere } from '@/lib/access/personnelFilter'
import { DocumentList } from '@/components/documents/DocumentList'
import { NewDocument } from '@/components/documents/NewDocument'
import { Attachments } from '@/components/files/Attachments'
import { ChatLazy } from '@/components/chat/ChatLazy'
import { loadChatView } from '@/lib/chat/load'
import { listAttachments } from '@/lib/files/service'
import { toAttachmentViews } from '@/lib/files/view'
import { allowedTargets, type CaseStatusName } from '@/lib/cases/lifecycle'
@@ -214,6 +216,7 @@ async function Relations({
<div className="mt-4">
<Attachments
target={{ caseNumber: akte.caseNumber }}
topic={`case:${akte.id}`}
initial={toAttachmentViews(anhaenge)}
canUpload={canEdit}
canRelease={permissions.isAdmin}
@@ -239,6 +242,36 @@ async function Relations({
)
}
/**
* Der Aktenchat. Eigene Suspense-Grenze, weil er die meisten Abfragen macht
* und der Rest der Seite nicht auf ihn warten soll.
*/
async function ChatBlock({
akte,
user,
}: {
akte: { id: string; caseNumber: string; status: string; classification: number }
user: { id: string; permissions: EffectivePermissions }
}) {
const ansicht = await loadChatView(user.permissions, {
kind: 'case',
caseNumber: akte.caseNumber,
})
return (
<ChatLazy
scope={{ kind: 'case', caseNumber: akte.caseNumber, caseId: akte.id }}
topic={`case:${akte.id}`}
initial={ansicht.messages}
initialReactions={ansicht.reactions}
currentUserId={user.id}
lastReadAt={ansicht.lastReadAt}
canAdopt={canEditCase(user.permissions, akte, 'entry.create').ok}
mentionNames={ansicht.mentionNames}
/>
)
}
async function SectionBlock({
caseId,
caseNumber,
@@ -373,6 +406,20 @@ export default async function CasePage({
</Suspense>
</div>
<section className="mt-12">
<Suspense
fallback={
<div className="space-y-3 border border-line p-4">
<SkeletonLine width="8rem" />
<SkeletonLine width="70%" />
<SkeletonLine width="55%" />
</div>
}
>
<ChatBlock akte={akte} user={user} />
</Suspense>
</section>
<nav className="mt-12 flex gap-4 border-b border-line pb-2 font-condensed text-xs">
<span className="text-text-dim">{de.case.timeline}</span>
<Link href={`/faelle/${akte.caseNumber}/aenderungen`}>{de.case.changes}</Link>
+116
View File
@@ -0,0 +1,116 @@
'use client'
import { useActionState, useState } from 'react'
import { channelText } from '@/lib/i18n/chat'
import { clearanceText, commonText } from '@/lib/i18n/common'
import { createChannelAction, type ActionResult } from './actions'
export function NewChannelForm({ levels }: { levels: { level: number; name: string }[] }) {
const [offen, setOffen] = useState(false)
const [state, action, pending] = useActionState<ActionResult | null, FormData>(
createChannelAction,
null,
)
if (!offen) {
return (
<button
type="button"
onClick={() => setOffen(true)}
className="border border-line bg-raised px-3 py-1 font-condensed text-2xs text-accent"
>
{channelText.create}
</button>
)
}
return (
<form action={action} className="max-w-(--container-measure) border border-line p-4">
<p className="font-condensed text-xs text-text-dim">{channelText.createTitle}</p>
<div className="mt-3 grid gap-4 sm:grid-cols-2">
<div>
<label htmlFor="name" className="font-condensed text-2xs text-text-dim">
{channelText.name}
</label>
<input
id="name"
name="name"
required
minLength={2}
maxLength={120}
className="mt-1 block w-full border border-line bg-raised px-3 py-2 text-sm"
/>
</div>
<div>
<label htmlFor="key" className="font-condensed text-2xs text-text-dim">
{channelText.key}
</label>
<input
id="key"
name="key"
required
pattern="[a-z0-9][a-z0-9-]{1,40}"
className="mt-1 block w-full border border-line bg-raised px-3 py-2 font-mono text-sm"
/>
<p className="mt-1 text-2xs text-text-dim">{channelText.keyHint}</p>
</div>
<div className="sm:col-span-2">
<label htmlFor="description" className="font-condensed text-2xs text-text-dim">
{channelText.description}
</label>
<input
id="description"
name="description"
maxLength={500}
className="mt-1 block w-full border border-line bg-raised px-3 py-2 text-sm"
/>
</div>
<div>
<label htmlFor="minClearance" className="font-condensed text-2xs text-text-dim">
{channelText.minClearance}
</label>
<select
id="minClearance"
name="minClearance"
defaultValue={0}
className="mt-1 block w-full border border-line bg-raised px-3 py-2 text-sm"
>
{levels.map((level) => (
<option key={level.level} value={level.level}>
{level.level} · {level.name}
</option>
))}
</select>
<p className="mt-1 text-2xs text-text-dim">
{channelText.minClearanceHint} {clearanceText.label}
</p>
</div>
</div>
{state && !state.ok ? (
<p className="mt-3 font-condensed text-2xs text-stamp-4">{state.error}</p>
) : null}
<div className="mt-4 flex gap-3">
<button
type="submit"
disabled={pending}
className="border border-line bg-raised px-3 py-1 font-condensed text-2xs text-accent disabled:text-text-dim"
>
{pending ? commonText.loading : channelText.create}
</button>
<button
type="button"
onClick={() => setOffen(false)}
className="font-condensed text-2xs text-text-dim"
>
{commonText.cancel}
</button>
</div>
</form>
)
}
+70
View File
@@ -0,0 +1,70 @@
import type { Metadata } from 'next'
import { notFound } from 'next/navigation'
import { requireUser } from '@/lib/auth/current'
import { AccessError } from '@/lib/errors'
import { loadChatView } from '@/lib/chat/load'
import { db } from '@/lib/db'
import { visibleChannelWhere } from '@/lib/access/chatFilter'
import { de } from '@/lib/i18n/de'
import { Chat } from '@/components/chat/Chat'
export const dynamic = 'force-dynamic'
export async function generateMetadata({
params,
}: {
params: Promise<{ key: string }>
}): Promise<Metadata> {
const { key } = await params
return { title: `#${key}` }
}
export default async function ChannelPage({ params }: { params: Promise<{ key: string }> }) {
const user = await requireUser()
const { key } = await params
const kanal = await db.channel.findFirst({
where: { AND: [visibleChannelWhere(user.permissions), { key, isArchived: false }] },
select: { id: true, key: true, name: true, description: true },
})
// Kein Zugriff heisst 404.
if (!kanal) notFound()
let ansicht
try {
ansicht = await loadChatView(user.permissions, { kind: 'channel', key: kanal.key })
} catch (error) {
if (error instanceof AccessError) notFound()
throw error
}
return (
<main className="mx-auto max-w-5xl px-6 py-10">
<header>
<span className="font-mono text-xs text-text-dim">#{kanal.key}</span>
<h1 className="mt-1 font-condensed">{kanal.name}</h1>
{kanal.description ? (
<p className="mt-2 max-w-(--container-measure) text-sm text-text-dim">
{kanal.description}
</p>
) : null}
</header>
<div className="mt-8">
<Chat
scope={{ kind: 'channel', key: kanal.key, channelId: kanal.id }}
topic={`channel:${kanal.id}`}
initial={ansicht.messages}
initialReactions={ansicht.reactions}
currentUserId={user.id}
lastReadAt={ansicht.lastReadAt}
// Ein Vermerk gehört in eine Akte. Ein Kanal hat keine.
canAdopt={false}
mentionNames={ansicht.mentionNames}
/>
</div>
<p className="mt-4 text-2xs text-text-dim">{de.chat.hint}</p>
</main>
)
}
+40
View File
@@ -0,0 +1,40 @@
'use server'
import { redirect } from 'next/navigation'
import { z } from 'zod'
import { requireUser } from '@/lib/auth/current'
import { AccessError } from '@/lib/errors'
import { createChannel } from '@/lib/chat/service'
import { de } from '@/lib/i18n/de'
export type ActionResult = { ok: true } | { ok: false; error: string }
const schema = z.object({
key: z.string().min(2).max(40),
name: z.string().min(2).max(120),
description: z.string().max(500).optional(),
minClearance: z.coerce.number().int().min(0).max(5),
})
export async function createChannelAction(
_prev: ActionResult | null,
formData: FormData,
): Promise<ActionResult> {
const user = await requireUser()
const parsed = schema.safeParse(Object.fromEntries(formData))
if (!parsed.success) return { ok: false, error: de.actionErrors.default! }
let key: string
try {
const kanal = await createChannel(user.permissions, parsed.data)
key = kanal.key
} catch (error) {
if (error instanceof AccessError) {
return { ok: false, error: de.actionErrors[error.code] ?? de.actionErrors.default! }
}
console.error('[kanaele] unerwartet', error)
return { ok: false, error: de.actionErrors.default! }
}
redirect(`/kanaele/${key}`)
}
+71
View File
@@ -0,0 +1,71 @@
import type { Metadata } from 'next'
import Link from 'next/link'
import { db } from '@/lib/db'
import { requireUser } from '@/lib/auth/current'
import { listChannels } from '@/lib/chat/service'
import { de } from '@/lib/i18n/de'
import { StampMark } from '@/components/StampMark'
import { NewChannelForm } from './NewChannelForm'
export const metadata: Metadata = { title: de.channel.heading }
export const dynamic = 'force-dynamic'
/**
* Freie Kanäle: Räume für Absprachen, die zu keiner Akte gehören.
*
* Ein Kanal über der Stufe des Lesers taucht nicht auf. Anders als bei Akten
* ist die Existenz eines Kanals aber kein Geheimnis für die, die seine Stufe
* haben — ein Raum, den man erraten müsste, wäre keiner.
*/
export default async function ChannelListPage() {
const user = await requireUser()
const [kanaele, levels] = await Promise.all([
listChannels(user.permissions),
db.clearanceLevelConfig.findMany({ orderBy: { level: 'asc' } }),
])
const levelName = new Map(levels.map((l) => [l.level, l.name]))
const darfAnlegen = user.permissions.isAdmin || user.permissions.permissions.has('case.create')
return (
<main className="mx-auto max-w-5xl px-6 py-10">
<h1 className="font-condensed">{de.channel.heading}</h1>
<p className="mt-2 max-w-(--container-measure) text-sm text-text-dim">
{de.channel.intro}
</p>
{kanaele.length === 0 ? (
<p className="mt-10 text-text-dim">{de.channel.empty}</p>
) : (
<ul className="mt-6 border-t border-line">
{kanaele.map((kanal) => (
<li key={kanal.id} className="border-b border-line">
<Link
href={`/kanaele/${kanal.key}`}
prefetch
className="flex flex-wrap items-baseline gap-x-4 gap-y-1 py-3 text-text no-underline"
>
<span className="font-mono text-xs text-text-dim">#{kanal.key}</span>
<span className="grow">{kanal.name}</span>
{kanal.minClearance > 0 ? (
<StampMark
level={kanal.minClearance}
name={levelName.get(kanal.minClearance) ?? de.common.unknown}
/>
) : null}
</Link>
</li>
))}
</ul>
)}
{darfAnlegen ? (
<div className="mt-8">
<NewChannelForm
levels={levels.filter((l) => l.level <= user.permissions.clearanceLevel)}
/>
</div>
) : null}
</main>
)
}
+2
View File
@@ -25,6 +25,8 @@ export default async function AppLayout({ children }: { children: React.ReactNod
{user.permissions.isAdmin || user.permissions.permissions.has('personnel.read') ? (
<Link href="/personalakten">{de.nav.personnel}</Link>
) : null}
<Link href="/kanaele">{de.channel.heading}</Link>
<Link href="/einstellungen">{de.notify.heading}</Link>
{user.permissions.isAdmin || user.permissions.permissions.has('roles.manage') ? (
<>
<Link href="/admin/rollen">{de.nav.admin}</Link>
@@ -1,10 +1,10 @@
'use client'
import { useState, useTransition } from 'react'
import { participantText } from '@/lib/i18n/cases'
import { commonText } from '@/lib/i18n/common'
import { assignmentText } from '@/lib/i18n/people'
import { participantText } from '@/lib/i18n/cases'
import { ASSIGNMENT_ROLES } from '@/lib/personnel/terms'
import { AddPanel, PanelSelect } from '@/components/AddPanel'
import { addAssignmentAction, removeAssignmentAction } from '../actions'
type Zuordnung = {
@@ -30,10 +30,9 @@ export function Assignments({
members: { id: string; displayName: string }[]
canEdit: boolean
}) {
const [open, setOpen] = useState(false)
const [role, setRole] = useState<string>('HANDLER')
const [userId, setUserId] = useState('')
const [error, setError] = useState<string | null>(null)
const [fehler, setFehler] = useState<string | null>(null)
const [pending, startTransition] = useTransition()
return (
@@ -57,11 +56,11 @@ export function Assignments({
disabled={pending}
onClick={() =>
startTransition(async () => {
const result = await removeAssignmentAction({
const ergebnis = await removeAssignmentAction({
personnelFileId,
assignmentId: zuordnung.id,
})
if (!result.ok) setError(result.error)
if (!ergebnis.ok) setFehler(ergebnis.error)
})
}
className="font-condensed text-2xs text-text-dim"
@@ -74,77 +73,35 @@ export function Assignments({
</ul>
)}
{error ? <p className="mt-2 font-condensed text-2xs text-stamp-4">{error}</p> : null}
{fehler ? <p className="mt-2 font-condensed text-2xs text-stamp-4">{fehler}</p> : null}
{canEdit ? (
open ? (
<div className="mt-4 border border-line p-3">
<p className="max-w-(--container-measure) text-2xs text-text-dim">
{assignmentText.hint}
</p>
<div className="mt-3 flex flex-wrap items-center gap-2">
<select
value={role}
onChange={(event) => setRole(event.target.value)}
aria-label={participantText.role}
className="border border-line bg-raised px-2 py-1 text-2xs"
>
{ASSIGNMENT_ROLES.map((value) => (
<option key={value} value={value}>
{assignmentText.roles[value] ?? value}
</option>
))}
</select>
<select
value={userId}
onChange={(event) => setUserId(event.target.value)}
aria-label={participantText.pickUser}
className="border border-line bg-raised px-2 py-1 text-2xs"
>
<option value="">—</option>
{members.map((member) => (
<option key={member.id} value={member.id}>
{member.displayName}
</option>
))}
</select>
<button
type="button"
disabled={pending || !userId}
onClick={() =>
startTransition(async () => {
setError(null)
const result = await addAssignmentAction({ personnelFileId, userId, role })
if (result.ok) {
setUserId('')
setOpen(false)
} else {
setError(result.error)
}
})
}
className="border border-line bg-raised px-3 py-1 font-condensed text-2xs text-accent disabled:text-text-dim"
>
{assignmentText.add}
</button>
<button
type="button"
onClick={() => setOpen(false)}
className="font-condensed text-2xs text-text-dim"
>
{commonText.cancel}
</button>
</div>
</div>
) : (
<button
type="button"
onClick={() => setOpen(true)}
className="mt-4 border border-line bg-raised px-3 py-1 font-condensed text-2xs text-accent"
>
{assignmentText.add}
</button>
)
<AddPanel
label={assignmentText.add}
hint={assignmentText.hint}
disabled={!userId}
onSubmit={async () => {
const ergebnis = await addAssignmentAction({ personnelFileId, userId, role })
if (ergebnis.ok) setUserId('')
return ergebnis
}}
>
<PanelSelect value={role} onChange={setRole} label={participantText.role}>
{ASSIGNMENT_ROLES.map((value) => (
<option key={value} value={value}>
{assignmentText.roles[value] ?? value}
</option>
))}
</PanelSelect>
<PanelSelect value={userId} onChange={setUserId} label={participantText.pickUser}>
<option value="">—</option>
{members.map((member) => (
<option key={member.id} value={member.id}>
{member.displayName}
</option>
))}
</PanelSelect>
</AddPanel>
) : null}
</div>
)
+27 -74
View File
@@ -1,10 +1,10 @@
'use client'
import { useState, useTransition } from 'react'
import { useState } from 'react'
import { linkText, participantText } from '@/lib/i18n/cases'
import { commonText } from '@/lib/i18n/common'
import { personnelText } from '@/lib/i18n/people'
import { PARTICIPANT_ROLES } from '@/lib/cases/terms'
import { AddPanel, PanelSelect } from '@/components/AddPanel'
import { linkCaseToPersonAction } from '../actions'
/**
@@ -16,81 +16,34 @@ import { linkCaseToPersonAction } from '../actions'
* sichtbaren Fälle wäre auf einer Personalakte am falschen Ort.
*/
export function LinkCase({ personnelFileId }: { personnelFileId: string }) {
const [open, setOpen] = useState(false)
const [caseNumber, setCaseNumber] = useState('')
const [role, setRole] = useState<string>('SUBJECT')
const [error, setError] = useState<string | null>(null)
const [pending, startTransition] = useTransition()
if (!open) {
return (
<button
type="button"
onClick={() => setOpen(true)}
className="mt-4 border border-line bg-raised px-3 py-1 font-condensed text-2xs text-accent"
>
{personnelText.linkCase}
</button>
)
}
return (
<div className="mt-4 border border-line p-3">
<p className="max-w-(--container-measure) text-2xs text-text-dim">
{personnelText.linkCaseHint}
</p>
<div className="mt-3 flex flex-wrap items-center gap-2">
<select
value={role}
onChange={(event) => setRole(event.target.value)}
aria-label={participantText.role}
className="border border-line bg-raised px-2 py-1 text-2xs"
>
{PARTICIPANT_ROLES.map((value) => (
<option key={value} value={value}>
{participantText.roles[value] ?? value}
</option>
))}
</select>
<input
value={caseNumber}
onChange={(event) => setCaseNumber(event.target.value)}
placeholder={linkText.target}
aria-label={linkText.target}
className="border border-line bg-raised px-2 py-1 font-mono text-2xs"
/>
<button
type="button"
disabled={pending || caseNumber.trim() === ''}
onClick={() =>
startTransition(async () => {
setError(null)
const result = await linkCaseToPersonAction({
personnelFileId,
caseNumber,
role,
})
if (result.ok) {
setCaseNumber('')
setOpen(false)
} else {
setError(result.error)
}
})
}
className="border border-line bg-raised px-3 py-1 font-condensed text-2xs text-accent disabled:text-text-dim"
>
{personnelText.linkCase}
</button>
<button
type="button"
onClick={() => setOpen(false)}
className="font-condensed text-2xs text-text-dim"
>
{commonText.cancel}
</button>
</div>
{error ? <p className="mt-2 font-condensed text-2xs text-stamp-4">{error}</p> : null}
</div>
<AddPanel
label={personnelText.linkCase}
hint={personnelText.linkCaseHint}
disabled={caseNumber.trim() === ''}
onSubmit={async () => {
const ergebnis = await linkCaseToPersonAction({ personnelFileId, caseNumber, role })
if (ergebnis.ok) setCaseNumber('')
return ergebnis
}}
>
<PanelSelect value={role} onChange={setRole} label={participantText.role}>
{PARTICIPANT_ROLES.map((value) => (
<option key={value} value={value}>
{participantText.roles[value] ?? value}
</option>
))}
</PanelSelect>
<input
value={caseNumber}
onChange={(event) => setCaseNumber(event.target.value)}
placeholder={linkText.target}
aria-label={linkText.target}
className="border border-line bg-raised px-2 py-1 font-mono text-2xs"
/>
</AddPanel>
)
}
-111
View File
@@ -1,111 +0,0 @@
import { getCurrentUser } from '@/lib/auth/current'
import { db } from '@/lib/db'
import { visibleAttachmentWhere } from '@/lib/access/attachmentFilter'
import { ensureListening, subscribe } from '@/lib/realtime/listener'
import { ATTACHMENT_CHANNEL } from '@/lib/realtime/publish'
export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'
/** Damit Zwischenspeicher und Tunnel die Verbindung nicht für tot halten. */
const HEARTBEAT_MS = 25_000
/**
* Ereignisstrom für offene Ansichten.
*
* Nur `attachment.scanned` bislang; der Aktenchat kommt in Phase 6 dazu und
* benutzt denselben Weg. Server-Sent Events und kein WebSocket: die Richtung
* ist einseitig, es geht durch jeden Tunnel, und der Browser baut die
* Verbindung von selbst wieder auf.
*
* **Die Sichtbarkeitsprüfung läuft je Ereignis.** Ein Ereignis über einen
* Anhang, dessen Akte der Empfänger nicht sehen darf, wird nicht zugestellt —
* sonst verriete schon die Kennung die Existenz.
*/
export async function GET(request: Request): Promise<Response> {
const user = await getCurrentUser()
if (!user) return new Response(null, { status: 404 })
await ensureListening()
const encoder = new TextEncoder()
let heartbeat: ReturnType<typeof setInterval> | null = null
let unsubscribe: (() => void) | null = null
const stream = new ReadableStream({
start(controller) {
const send = (event: string, data: unknown) => {
try {
controller.enqueue(
encoder.encode(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`),
)
} catch {
// Verbindung schon zu; das Aufräumen übernimmt cancel().
}
}
send('ready', { at: new Date().toISOString() })
heartbeat = setInterval(() => {
try {
controller.enqueue(encoder.encode(': ping\n\n'))
} catch {
// s. o.
}
}, HEARTBEAT_MS)
unsubscribe = subscribe((event) => {
if (event.channel !== ATTACHMENT_CHANNEL) return
void zustellen(event.payload, user.permissions, send)
})
request.signal.addEventListener('abort', () => {
controller.close()
})
},
cancel() {
if (heartbeat) clearInterval(heartbeat)
unsubscribe?.()
},
})
return new Response(stream, {
headers: {
'Content-Type': 'text/event-stream; charset=utf-8',
'Cache-Control': 'no-cache, no-transform',
Connection: 'keep-alive',
// Der Tunnel darf nicht puffern, sonst kommt alles am Stück.
'X-Accel-Buffering': 'no',
},
})
}
async function zustellen(
attachmentId: string,
permissions: Awaited<ReturnType<typeof getCurrentUser>> extends infer U
? U extends { permissions: infer P }
? P
: never
: never,
send: (event: string, data: unknown) => void,
): Promise<void> {
try {
const anhang = await db.attachment.findFirst({
where: { AND: [visibleAttachmentWhere(permissions), { id: attachmentId }] },
select: {
id: true,
scanStatus: true,
scanMessage: true,
mimeType: true,
sizeBytes: true,
thumbKey: true,
blurhash: true,
width: true,
height: true,
},
})
if (!anhang) return
send('attachment.scanned', { ...anhang, hasThumb: anhang.thumbKey !== null, thumbKey: undefined })
} catch (error) {
console.error('[events] Ereignis nicht zugestellt', error)
}
}
+311
View File
@@ -0,0 +1,311 @@
import { getCurrentUser, type CurrentUser } from '@/lib/auth/current'
import { db } from '@/lib/db'
import { visibleCaseWhere } from '@/lib/access/caseFilter'
import { visibleChannelWhere, visibleMessageWhere } from '@/lib/access/chatFilter'
import { visibleAttachmentWhere } from '@/lib/access/attachmentFilter'
import { resolveCasePreviews, type CasePreview } from '@/lib/chat/preview'
import { extractCaseNumbers, type ChatMessageView } from '@/lib/chat/view'
import { ensureListening, subscribe } from '@/lib/realtime/listener'
import type { StreamEvent, Topic } from '@/lib/realtime/publish'
export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'
/** Gegen Zwischenspeicher und Tunnel, die eine stille Verbindung für tot halten. */
const HEARTBEAT_MS = 25_000
/**
* Ereignisstrom für offene Ansichten.
*
* GET /api/stream?topics=case:<id>,channel:<id>
*
* Server-Sent Events und kein WebSocket: die Richtung ist einseitig, es geht
* durch jeden Tunnel, und der Browser baut die Verbindung von selbst wieder
* auf. Siehe docs/06-chat-und-realtime.md.
*
* Zwei Prüfungen, beide nötig:
* 1. **Beim Verbinden**: welche der angefragten Themen darf dieser Nutzer
* überhaupt abonnieren. Wer ein fremdes Thema nennt, bekommt es nicht —
* und erfährt auch nicht, ob es existiert.
* 2. **Je Ereignis**: der Inhalt wird mit den Rechten des Empfängers geladen.
* Eine Umklassifizierung mitten in einer offenen Verbindung wirkt dadurch
* sofort, ohne dass jemand neu laden muss.
*/
export async function GET(request: Request): Promise<Response> {
const user = await getCurrentUser()
if (!user) return new Response(null, { status: 404 })
const url = new URL(request.url)
const gewuenscht = (url.searchParams.get('topics') ?? '')
.split(',')
.map((t) => t.trim())
.filter(Boolean)
.slice(0, 20)
const erlaubt = await erlaubteThemen(user, gewuenscht)
await ensureListening()
const encoder = new TextEncoder()
let heartbeat: ReturnType<typeof setInterval> | null = null
let unsubscribe: (() => void) | null = null
let offen = true
const stream = new ReadableStream({
async start(controller) {
const send = (event: string, data: unknown, id?: string) => {
if (!offen) return
try {
const zeilen = [
...(id ? [`id: ${id}`] : []),
`event: ${event}`,
`data: ${JSON.stringify(data)}`,
'',
'',
]
controller.enqueue(encoder.encode(zeilen.join('\n')))
} catch {
offen = false
}
}
// Verpasstes nachliefern. Der Browser schickt beim Wiederverbinden von
// selbst die zuletzt gesehene Kennung mit; die Kennungen sind UUIDv7 und
// damit zeitlich sortiert, ein Vergleich darauf reicht.
const seit = request.headers.get('last-event-id') ?? url.searchParams.get('since')
if (seit) await nachliefern(user, erlaubt, seit, send)
send('ready', { topics: erlaubt })
heartbeat = setInterval(() => {
if (!offen) return
try {
controller.enqueue(encoder.encode(': ping\n\n'))
} catch {
offen = false
}
}, HEARTBEAT_MS)
unsubscribe = subscribe((event) => {
if (!erlaubt.includes(event.t)) return
void zustellen(user, event, send)
})
request.signal.addEventListener('abort', () => {
offen = false
try {
controller.close()
} catch {
// schon zu
}
})
},
cancel() {
offen = false
if (heartbeat) clearInterval(heartbeat)
unsubscribe?.()
},
})
return new Response(stream, {
headers: {
'Content-Type': 'text/event-stream; charset=utf-8',
'Cache-Control': 'no-cache, no-transform',
Connection: 'keep-alive',
// Der Tunnel darf nicht puffern, sonst kommt alles am Stück.
'X-Accel-Buffering': 'no',
},
})
}
/**
* Filtert die angefragten Themen auf die, die der Nutzer sehen darf.
*
* Das eigene Nutzerthema ist immer dabei, alles andere muss belegt werden.
*/
async function erlaubteThemen(user: CurrentUser, gewuenscht: string[]): Promise<Topic[]> {
const themen: Topic[] = [`user:${user.id}`]
const fallIds = gewuenscht
.filter((t) => t.startsWith('case:'))
.map((t) => t.slice(5))
.filter(Boolean)
const kanalIds = gewuenscht
.filter((t) => t.startsWith('channel:'))
.map((t) => t.slice(8))
.filter(Boolean)
if (fallIds.length > 0) {
const sichtbar = await db.case.findMany({
where: { AND: [visibleCaseWhere(user.permissions), { id: { in: fallIds } }] },
select: { id: true },
})
themen.push(...sichtbar.map((akte) => `case:${akte.id}` as Topic))
}
if (kanalIds.length > 0) {
const sichtbar = await db.channel.findMany({
where: { AND: [visibleChannelWhere(user.permissions), { id: { in: kanalIds } }] },
select: { id: true },
})
themen.push(...sichtbar.map((kanal) => `channel:${kanal.id}` as Topic))
}
return themen
}
type Send = (event: string, data: unknown, id?: string) => void
/** Was seit `seit` in den abonnierten Themen passiert ist. */
async function nachliefern(
user: CurrentUser,
themen: Topic[],
seit: string,
send: Send,
): Promise<void> {
const fallIds = themen.filter((t) => t.startsWith('case:')).map((t) => t.slice(5))
const kanalIds = themen.filter((t) => t.startsWith('channel:')).map((t) => t.slice(8))
if (fallIds.length === 0 && kanalIds.length === 0) return
try {
const verpasst = await db.chatMessage.findMany({
where: {
AND: [
visibleMessageWhere(user.permissions),
{ id: { gt: seit } },
{ OR: [{ caseId: { in: fallIds } }, { channelId: { in: kanalIds } }] },
],
},
orderBy: { id: 'asc' },
take: 200,
select: NACHRICHT,
})
for (const angereichert of await anreichern(user, verpasst)) {
send('chat.new', angereichert, angereichert.id)
}
} catch (error) {
console.error('[stream] Nachlieferung fehlgeschlagen', error)
}
}
const NACHRICHT = {
id: true,
body: true,
authorId: true,
replyToId: true,
editedAt: true,
withdrawnAt: true,
adoptedEntryId: true,
mentions: true,
createdAt: true,
caseId: true,
channelId: true,
} as const
/**
* Ergänzt, was die Anzeige braucht und was **je Empfänger verschieden** ist:
* den Namen des Autors und die Vorschaukarten zu erwähnten Aktenzeichen. Die
* Karten werden mit den Rechten des Empfängers aufgelöst, deshalb hier und
* nicht beim Absender.
*/
function vorschauenFuer(
body: string,
alle: Map<string, CasePreview>,
): Record<string, CasePreview> {
const treffer: Record<string, CasePreview> = {}
for (const nummer of extractCaseNumbers(body)) {
const vorschau = alle.get(nummer)
if (vorschau) treffer[nummer] = vorschau
}
return treffer
}
async function anreichern(
user: CurrentUser,
nachrichten: {
id: string
body: string
authorId: string
replyToId: string | null
editedAt: Date | null
withdrawnAt: Date | null
adoptedEntryId: string | null
mentions: string[]
createdAt: Date
}[],
): Promise<ChatMessageView[]> {
if (nachrichten.length === 0) return []
const [autoren, vorschauen] = await Promise.all([
db.user.findMany({
where: { id: { in: [...new Set(nachrichten.map((n) => n.authorId))] } },
select: { id: true, displayName: true, username: true },
}),
resolveCasePreviews(
user.permissions,
nachrichten.flatMap((n) => extractCaseNumbers(n.body)),
),
])
const nameVon = new Map(autoren.map((a) => [a.id, a.displayName]))
return nachrichten.map((nachricht) => ({
id: nachricht.id,
body: nachricht.withdrawnAt ? '' : nachricht.body,
authorId: nachricht.authorId,
authorName: nameVon.get(nachricht.authorId) ?? nachricht.authorId,
replyToId: nachricht.replyToId,
editedAt: nachricht.editedAt?.toISOString() ?? null,
withdrawnAt: nachricht.withdrawnAt?.toISOString() ?? null,
adoptedEntryId: nachricht.adoptedEntryId,
createdAt: nachricht.createdAt.toISOString(),
previews: vorschauenFuer(nachricht.body, vorschauen),
}))
}
/**
* Lädt den Inhalt zu einem Ereignis **mit den Rechten des Empfängers**.
*
* Findet die Abfrage nichts, wird nichts geschickt: weder Inhalt noch die
* Kennung. Sonst verriete schon die Kennung, dass es etwas gibt.
*/
async function zustellen(user: CurrentUser, event: StreamEvent, send: Send): Promise<void> {
try {
if (event.k.startsWith('chat.')) {
const nachricht = await db.chatMessage.findFirst({
where: { AND: [visibleMessageWhere(user.permissions), { id: event.i }] },
select: NACHRICHT,
})
if (!nachricht) return
const [angereichert] = await anreichern(user, [nachricht])
if (angereichert) send(event.k, angereichert, angereichert.id)
return
}
if (event.k === 'attachment.scanned') {
const anhang = await db.attachment.findFirst({
where: { AND: [visibleAttachmentWhere(user.permissions), { id: event.i }] },
select: {
id: true,
scanStatus: true,
scanMessage: true,
mimeType: true,
sizeBytes: true,
thumbKey: true,
blurhash: true,
width: true,
height: true,
},
})
if (anhang) {
send('attachment.scanned', { ...anhang, hasThumb: anhang.thumbKey !== null, thumbKey: undefined })
}
return
}
// Verlaufseinträge und Kopfdaten: nur die Kennung. Die Ansicht lädt
// daraufhin nach, statt dass hier ein zweiter Renderpfad entsteht.
send(event.k, { id: event.i })
} catch (error) {
console.error('[stream] Ereignis nicht zugestellt', error)
}
}