Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/packages/chat/src/mentions.server.ts
T

495 lines
19 KiB
TypeScript

import { logActivity } from "@hivegrid/activity";
import type { Prisma } from "@hivegrid/db/prisma-browser";
import type { DbTransactionClient } from "@hivegrid/db/transactions.server";
import { CatalogError, foundationErrors, withTenantScope } from "@hivegrid/foundation";
import { extractChatMentions, type ChatMention, type ChatMentionType } from "@hivegrid/realtime";
import { chatErrors } from "./errors.js";
import { CHAT_PERMISSIONS } from "./permissions.js";
import { runChatRepositoryTransaction } from "./repository.server.js";
import type { ChatRepositoryContext } from "./types.js";
const ACTIVE_TENANT_USER_STATUS = 2;
const MAX_QUERY_LENGTH = 120;
const MAX_SUGGESTIONS = 10;
const MAX_LABEL_LENGTH = 300;
export type ChatMentionSuggestion = Readonly<{
type: ChatMentionType;
id: string;
label: string;
detail: string | null;
}>;
export type ListChatMentionSuggestionsInput = ChatRepositoryContext &
Readonly<{
chatId: string;
query?: string;
type?: ChatMentionType | null;
limit?: number;
}>;
export type ChatMentionChannel = Readonly<{
id: string;
kind: "project" | "group" | "dm";
isPrivate: boolean;
projektId: string | null;
name: string | null;
}>;
type VisibilityPrincipals = Readonly<{
roleIds: readonly string[];
groupIds: readonly string[];
}>;
/**
* Lists mention candidates through the same fresh-permission and FORCE-RLS
* transaction boundary as channel reads. Results are intentionally bounded on
* the server; the combobox never receives a tenant-wide directory dump.
*/
export async function listChatMentionSuggestions(input: ListChatMentionSuggestionsInput): Promise<readonly ChatMentionSuggestion[]> {
const normalized = normalizeSuggestionInput(input);
return runChatRepositoryTransaction(input, CHAT_PERMISSIONS.readOwnChannels, async (tx, currentPermissions) => {
const channel = await requireMentionChannel(tx, input, normalized.chatId, true);
const principals = await loadVisibilityPrincipals(tx, input);
const types = normalized.type ? [normalized.type] : (["user", "project", "contact", "company"] as const);
const suggestions: ChatMentionSuggestion[] = [];
for (const type of types) {
const remaining = normalized.limit - suggestions.length;
if (remaining <= 0) break;
const rows = await listSuggestionsOfType(tx, input, channel, currentPermissions, principals, type, normalized.query, remaining);
suggestions.push(...rows);
}
return suggestions;
});
}
/**
* Extracts canonical tokens from the body and re-resolves every id and label.
* Client-provided mention arrays and labels are never authoritative.
*/
export async function resolveChatMentionsInBodyWithTx(
tx: DbTransactionClient,
context: ChatRepositoryContext,
channel: ChatMentionChannel,
body: string,
currentPermissions: readonly string[]
): Promise<ChatMention[]> {
let extracted: ChatMention[];
try {
extracted = extractChatMentions(body);
} catch {
throw new CatalogError(chatErrors.invalidInput, { field: "body" });
}
if (extracted.length === 0) return [];
const principals = await loadVisibilityPrincipals(tx, context);
const resolvedByKey = new Map<string, ChatMention>();
for (const type of ["user", "project", "contact", "company"] as const) {
const ids = [...new Set(extracted.filter((mention) => mention.type === type).map((mention) => mention.id))];
if (ids.length === 0) continue;
const rows = await resolveMentionsOfType(tx, context, channel, currentPermissions, principals, type, ids);
for (const row of rows) resolvedByKey.set(mentionKey(row), row);
}
const resolved = extracted.map((mention) => resolvedByKey.get(mentionKey(mention)));
if (resolved.some((mention) => mention === undefined)) {
throw new CatalogError(chatErrors.invalidInput, { mention: "not-visible" });
}
return resolved as ChatMention[];
}
/** Writes the project timeline entry and each entity-mention timeline entry. */
export async function logChatMessageActivitiesWithTx(
tx: DbTransactionClient,
context: ChatRepositoryContext,
input: Readonly<{
channel: Pick<ChatMentionChannel, "id" | "projektId" | "name">;
messageId: string;
body: string;
mentions: readonly ChatMention[];
includeProjectChannelActivity: boolean;
skipMentionKeys?: ReadonlySet<string>;
action: "message_created" | "thread_reply_created" | "message_edited";
}>
): Promise<void> {
const loggedSubjects = new Set<string>();
if (input.includeProjectChannelActivity && input.channel.projektId) {
await logActivity(
{
tenantId: context.tenantId,
actorUserId: context.userId,
actorKind: "user",
activityType: "chat_message",
subjectType: "project",
subjectId: input.channel.projektId,
summaryText:
input.action === "thread_reply_created"
? "activity.runtime.chat.threadReplyCreated"
: input.action === "message_edited"
? "activity.runtime.chat.messageEdited"
: "activity.runtime.chat.messageCreated",
metadata: {
sourceModule: "chat",
chatAction: input.action,
chatId: input.channel.id,
messageId: input.messageId,
},
},
{ client: tx }
);
loggedSubjects.add(`project\u0000${input.channel.projektId}`);
}
for (const mention of input.mentions) {
if (mention.type === "user") continue;
const key = mentionKey(mention);
if (input.skipMentionKeys?.has(key) || loggedSubjects.has(`${mention.type}\u0000${mention.id}`)) continue;
await logActivity(
{
tenantId: context.tenantId,
actorUserId: context.userId,
actorKind: "user",
activityType: "chat_message",
subjectType: mention.type,
subjectId: mention.id,
summaryText: "activity.runtime.chat.entityMentioned",
metadata: {
sourceModule: "chat",
chatAction: "entity_mentioned",
chatId: input.channel.id,
messageId: input.messageId,
mentionType: mention.type,
},
},
{ client: tx }
);
loggedSubjects.add(`${mention.type}\u0000${mention.id}`);
}
}
export function chatMentionKey(mention: Pick<ChatMention, "type" | "id">): string {
return mentionKey(mention);
}
async function requireMentionChannel(
tx: DbTransactionClient,
context: ChatRepositoryContext,
chatId: string,
lockMembership: boolean
): Promise<ChatMentionChannel> {
if (lockMembership) {
const rows = await tx.$queryRaw<Array<{ id: string }>>`
SELECT mention_viewer."id"
FROM "TeamChatMember" AS mention_viewer
WHERE mention_viewer."tenantId" = ${context.tenantId}
AND mention_viewer."chatId" = ${chatId}
AND mention_viewer."userId" = ${context.userId}
AND mention_viewer."leftAt" IS NULL
FOR SHARE
`;
if (rows.length !== 1) throw new CatalogError(foundationErrors.notFound, { chat: "not-visible" });
}
const channel = await tx.teamChat.findFirst({
where: withTenantScope(context.tenantId, {
id: chatId,
members: { some: withTenantScope(context.tenantId, { userId: context.userId, leftAt: null }) },
}),
select: { id: true, kind: true, isPrivate: true, projektId: true, name: true },
});
if (!channel) throw new CatalogError(foundationErrors.notFound, { chat: "not-visible" });
return channel;
}
async function loadVisibilityPrincipals(tx: DbTransactionClient, context: Pick<ChatRepositoryContext, "tenantId" | "userId">): Promise<VisibilityPrincipals> {
const [roles, groups] = await Promise.all([
tx.userRole.findMany({
where: { tenantId: context.tenantId, userId: context.userId, role: { type: "app", OR: [{ tenantId: context.tenantId }, { tenantId: null }] } },
select: { roleId: true },
}),
tx.groupUser.findMany({
where: { userId: context.userId, group: { tenantId: context.tenantId } },
select: { groupId: true },
}),
]);
return {
roleIds: [...new Set(roles.map((row) => row.roleId))],
groupIds: [...new Set(groups.map((row) => row.groupId))],
};
}
async function listSuggestionsOfType(
tx: DbTransactionClient,
context: ChatRepositoryContext,
channel: ChatMentionChannel,
permissions: readonly string[],
principals: VisibilityPrincipals,
type: ChatMentionType,
query: string,
limit: number
): Promise<ChatMentionSuggestion[]> {
if (type === "user") return listUserSuggestions(tx, context, channel, query, limit);
if (type === "project") return listProjectSuggestions(tx, context, permissions, principals, query, limit);
return listContactSuggestions(tx, context, permissions, type, query, limit);
}
async function listUserSuggestions(
tx: DbTransactionClient,
context: ChatRepositoryContext,
channel: ChatMentionChannel,
query: string,
limit: number
): Promise<ChatMentionSuggestion[]> {
const memberIds = (
await tx.teamChatMember.findMany({
where: withTenantScope(context.tenantId, { chatId: channel.id, leftAt: null }),
select: { userId: true },
})
).map((row) => row.userId);
if (memberIds.length === 0) return [];
const rows = await tx.tenantUser.findMany({
where: withTenantScope(context.tenantId, {
status: ACTIVE_TENANT_USER_STATUS,
userId: { in: memberIds },
user: {
active: true,
pendingDeletion: false,
...(query
? {
OR: [
{ firstName: { contains: query, mode: "insensitive" as const } },
{ lastName: { contains: query, mode: "insensitive" as const } },
{ email: { contains: query, mode: "insensitive" as const } },
],
}
: {}),
},
}),
select: { userId: true, user: { select: { firstName: true, lastName: true, email: true } } },
take: Math.max(limit * 3, limit),
});
return rows
.map((row) => ({
type: "user" as const,
id: row.userId,
label: userDisplayName(row.user),
detail: row.user.email,
}))
.sort(compareSuggestions)
.slice(0, limit);
}
async function listProjectSuggestions(
tx: DbTransactionClient,
context: ChatRepositoryContext,
permissions: readonly string[],
principals: VisibilityPrincipals,
query: string,
limit: number
): Promise<ChatMentionSuggestion[]> {
const scope = projectVisibilityWhere(context, permissions, principals);
if (scope === null) return [];
const rows = await tx.projekt.findMany({
where: withTenantScope(context.tenantId, {
archivedAt: null,
AND: [
scope,
...(query
? [
{
OR: [
{ projektname: { contains: query, mode: "insensitive" as const } },
{ projektNummer: { contains: query, mode: "insensitive" as const } },
],
},
]
: []),
],
}),
select: { id: true, projektNummer: true, projektname: true },
take: Math.max(limit * 3, limit),
});
return rows
.map((row) => ({ type: "project" as const, id: row.id, label: boundedLabel(`${row.projektNummer} · ${row.projektname}`), detail: row.projektNummer }))
.sort(compareSuggestions)
.slice(0, limit);
}
async function listContactSuggestions(
tx: DbTransactionClient,
context: ChatRepositoryContext,
permissions: readonly string[],
type: "contact" | "company",
query: string,
limit: number
): Promise<ChatMentionSuggestion[]> {
const scope = contactVisibilityWhere(context, permissions);
if (scope === null) return [];
const kontaktTyp = type === "company" ? ("organisation" as const) : ("privatperson" as const);
const rows = await tx.kontakt.findMany({
where: withTenantScope(context.tenantId, {
kontaktTyp,
archivedAt: null,
AND: [
scope,
...(query
? [
{
OR: [
{ vorname: { contains: query, mode: "insensitive" as const } },
{ nachname: { contains: query, mode: "insensitive" as const } },
{ orgName: { contains: query, mode: "insensitive" as const } },
{ primaerEmail: { contains: query, mode: "insensitive" as const } },
],
},
]
: []),
],
}),
select: { id: true, vorname: true, nachname: true, orgName: true, primaerEmail: true },
take: Math.max(limit * 3, limit),
});
return rows
.map((row) => ({ type, id: row.id, label: kontaktDisplayName(row, type), detail: row.primaerEmail }))
.sort(compareSuggestions)
.slice(0, limit);
}
async function resolveMentionsOfType(
tx: DbTransactionClient,
context: ChatRepositoryContext,
channel: ChatMentionChannel,
permissions: readonly string[],
principals: VisibilityPrincipals,
type: ChatMentionType,
ids: readonly string[]
): Promise<ChatMention[]> {
if (type === "user") {
const memberIds = (
await tx.teamChatMember.findMany({
where: withTenantScope(context.tenantId, { chatId: channel.id, leftAt: null, userId: { in: [...ids] } }),
select: { userId: true },
})
).map((row) => row.userId);
if (memberIds.length === 0) return [];
const rows = await tx.tenantUser.findMany({
where: withTenantScope(context.tenantId, {
userId: { in: memberIds },
status: ACTIVE_TENANT_USER_STATUS,
user: { active: true, pendingDeletion: false },
}),
select: { userId: true, user: { select: { firstName: true, lastName: true, email: true } } },
});
return rows.map((row) => ({ type: "user", id: row.userId, label: userDisplayName(row.user) }));
}
if (type === "project") {
const scope = projectVisibilityWhere(context, permissions, principals);
if (scope === null) return [];
const rows = await tx.projekt.findMany({
where: withTenantScope(context.tenantId, { id: { in: [...ids] }, archivedAt: null, AND: [scope] }),
select: { id: true, projektNummer: true, projektname: true },
});
return rows.map((row) => ({ type, id: row.id, label: boundedLabel(`${row.projektNummer} · ${row.projektname}`) }));
}
const scope = contactVisibilityWhere(context, permissions);
if (scope === null) return [];
const kontaktTyp = type === "company" ? ("organisation" as const) : ("privatperson" as const);
const rows = await tx.kontakt.findMany({
where: withTenantScope(context.tenantId, { id: { in: [...ids] }, kontaktTyp, archivedAt: null, AND: [scope] }),
select: { id: true, vorname: true, nachname: true, orgName: true, primaerEmail: true },
});
return rows.map((row) => ({ type, id: row.id, label: kontaktDisplayName(row, type) }));
}
function projectVisibilityWhere(
context: ChatRepositoryContext,
permissions: readonly string[],
principals: VisibilityPrincipals
): Prisma.ProjektWhereInput | null {
const ownerConditions: Prisma.ProjektWhereInput[] = [];
if (permissions.includes("projects.read_all")) {
// No owner restriction.
} else {
if (permissions.includes("projects.read_own")) ownerConditions.push({ zustaendigePersonId: context.userId });
if (permissions.includes("projects.read_own_pl")) ownerConditions.push({ projektleiterId: context.userId });
if (permissions.includes("projects.read_own_member")) {
ownerConditions.push({
mitglieder: {
some: withTenantScope(context.tenantId, {
archivedAt: null,
OR: [{ userId: context.userId }, ...(principals.groupIds.length > 0 ? [{ groupId: { in: [...principals.groupIds] } }] : [])],
}),
},
});
}
if (ownerConditions.length === 0) return null;
}
const effectivePrincipals: Prisma.PipelineAccessWhereInput[] = [
{ principalType: "user", principalId: context.userId },
...principals.roleIds.map((principalId) => ({ principalType: "role" as const, principalId })),
...principals.groupIds.map((principalId) => ({ principalType: "group" as const, principalId })),
];
return {
AND: [
...(ownerConditions.length > 0 ? [{ OR: ownerConditions }] : []),
{ pipeline: { accessRules: { none: withTenantScope(context.tenantId, { kannSehen: false, OR: effectivePrincipals }) } } },
],
};
}
function contactVisibilityWhere(context: ChatRepositoryContext, permissions: readonly string[]): Prisma.KontaktWhereInput | null {
if (permissions.includes("crm.read_all")) return {};
if (permissions.includes("crm.read_own")) return { zustaendigerUserId: context.userId };
return null;
}
function normalizeSuggestionInput(input: ListChatMentionSuggestionsInput): { chatId: string; query: string; type: ChatMentionType | null; limit: number } {
const chatId = normalizeIdentifier(input.chatId, "chatId");
if (input.type !== undefined && input.type !== null && !["user", "project", "contact", "company"].includes(input.type)) {
throw new CatalogError(chatErrors.invalidInput, { field: "type" });
}
const query = typeof input.query === "string" ? input.query.trim().slice(0, MAX_QUERY_LENGTH) : "";
const limit = input.limit === undefined ? MAX_SUGGESTIONS : input.limit;
if (!Number.isInteger(limit) || limit < 1 || limit > MAX_SUGGESTIONS) {
throw new CatalogError(chatErrors.invalidInput, { field: "limit" });
}
return { chatId, query, type: input.type ?? null, limit };
}
function normalizeIdentifier(value: unknown, field: string): string {
if (typeof value !== "string") throw new CatalogError(chatErrors.invalidInput, { field });
const normalized = value.trim();
if (!normalized || normalized.length > 500 || normalized.includes("\0")) throw new CatalogError(chatErrors.invalidInput, { field });
return normalized;
}
function userDisplayName(user: { firstName: string; lastName: string; email: string }): string {
return boundedLabel(`${user.firstName} ${user.lastName}`.trim() || user.email.trim());
}
function kontaktDisplayName(
row: { vorname: string | null; nachname: string | null; orgName: string | null; primaerEmail: string | null },
type: "contact" | "company"
): string {
const label = type === "company" ? row.orgName?.trim() : `${row.vorname ?? ""} ${row.nachname ?? ""}`.trim();
return boundedLabel(label || row.primaerEmail?.trim() || (type === "company" ? "Firma" : "Kontakt"));
}
function boundedLabel(value: string): string {
const normalized = value.trim().replace(/\s+/gu, " ");
if (!normalized) throw new CatalogError(chatErrors.integrityFailure);
return normalized.slice(0, MAX_LABEL_LENGTH);
}
function compareSuggestions(left: ChatMentionSuggestion, right: ChatMentionSuggestion): number {
return left.label.localeCompare(right.label, "de", { sensitivity: "base" }) || left.id.localeCompare(right.id);
}
function mentionKey(mention: Pick<ChatMention, "type" | "id">): string {
return `${mention.type}\u0000${mention.id}`;
}