games_app/backend/src/services/supportService.ts
2026-09-24 15:40:35 +02:00

534 lines
16 KiB
TypeScript

import path from 'path';
import fs from 'fs';
import { decrypt } from '../utils/crypto';
import * as repo from '../repositories/supportRepository';
import {
SupportConversationRow,
SupportMessageRow,
SupportSenderType,
} from '../models/support.model';
import {
getTypingIndicators,
publishSupportEvent,
setTypingIndicator,
} from './supportRealtimeService';
import * as settingsRepository from '../repositories/settingsRepository';
import {
assertSupportMessageAction,
isSupportMessageOwner,
resolveSupportMessageActions,
type SupportMessageActionFlags,
} from './supportMessagePolicy';
const STAFF_ROLES = new Set(['admin', 'moderator', 'super_admin']);
export function isStaffRole(role: string | undefined): boolean {
return !!role && STAFF_ROLES.has(role);
}
function previewForMessage(body: string | null, attachmentName: string | null): string {
if (body?.trim()) return body.trim().slice(0, 200);
if (attachmentName) return `📎 ${attachmentName}`;
return 'Message';
}
function mapMessage(
row: SupportMessageRow,
staffNames?: Map<string, string>,
actions?: SupportMessageActionFlags
) {
const staffName =
row.sender_type === 'staff' && row.sender_user_id
? staffNames?.get(row.sender_user_id) ?? null
: null;
const deleted = !!row.deleted_at;
return {
id: row.id,
conversationId: row.conversation_id,
senderType: row.sender_type,
senderUserId: row.sender_user_id,
senderDisplayName: staffName,
body: deleted ? null : row.body,
attachmentUrl: deleted ? null : row.attachment_url,
attachmentName: deleted ? null : row.attachment_name,
attachmentMime: deleted ? null : row.attachment_mime,
readAt: row.read_at?.toISOString() ?? null,
editedAt: row.edited_at?.toISOString() ?? null,
deletedAt: row.deleted_at?.toISOString() ?? null,
deleted,
createdAt: row.created_at.toISOString(),
canEdit: actions?.canEdit ?? false,
canDelete: actions?.canDelete ?? false,
editAvailableUntil: actions?.editAvailableUntil ?? null,
deleteAvailableUntil: actions?.deleteAvailableUntil ?? null,
};
}
async function loadActionWindows() {
const settings = await settingsRepository.getSettings();
return {
editWindowMinutes: settings.support_message_edit_window_minutes,
deleteWindowMinutes: settings.support_message_delete_window_minutes,
};
}
function ownerFlags(
row: SupportMessageRow,
conv: SupportConversationRow,
ctx: SupportAccessContext
): boolean {
return isSupportMessageOwner({
senderType: row.sender_type,
senderUserId: row.sender_user_id,
conversationVisitorToken: conv.visitor_token,
actorUserId: ctx.userId,
actorVisitorToken: ctx.visitorToken,
});
}
function messageActions(
row: SupportMessageRow,
conv: SupportConversationRow,
ctx: SupportAccessContext,
windows: { editWindowMinutes: number; deleteWindowMinutes: number }
): SupportMessageActionFlags {
return resolveSupportMessageActions({
createdAt: row.created_at,
deleted: !!row.deleted_at,
isOwner: ownerFlags(row, conv, ctx),
editWindowMinutes: windows.editWindowMinutes,
deleteWindowMinutes: windows.deleteWindowMinutes,
});
}
async function refreshConversationPreview(conversationId: string): Promise<void> {
const latest = await repo.findLatestVisibleMessage(conversationId);
if (!latest) {
await repo.updateConversationPreview(conversationId, '', null);
return;
}
await repo.updateConversationPreview(
conversationId,
previewForMessage(latest.body, latest.attachment_name),
latest.created_at
);
}
function mapConversation(row: SupportConversationRow) {
return {
id: row.id,
userId: row.user_id,
visitorToken: row.visitor_token,
isAnonymous: row.user_id == null,
subject: row.subject,
status: row.status,
assignedTo: row.assigned_to,
lastMessageAt: row.last_message_at?.toISOString() ?? null,
lastMessagePreview: row.last_message_preview,
unreadUser: row.unread_user,
unreadStaff: row.unread_staff,
createdAt: row.created_at.toISOString(),
updatedAt: row.updated_at.toISOString(),
};
}
function decryptEmail(encrypted: string | null): string | null {
if (!encrypted) return null;
try {
return decrypt(encrypted);
} catch {
return null;
}
}
export type SupportAccessContext = {
userId?: string;
role?: string;
visitorToken?: string | null;
};
export async function assertConversationAccess(
conversationId: string,
ctx: SupportAccessContext
): Promise<SupportConversationRow> {
const conv = await repo.findConversationById(conversationId);
if (!conv) throw new Error('Conversation not found');
if (isStaffRole(ctx.role)) return conv;
if (ctx.userId && conv.user_id === ctx.userId) return conv;
if (
ctx.visitorToken &&
conv.visitor_token === ctx.visitorToken &&
conv.user_id == null
) {
return conv;
}
throw new Error('Forbidden');
}
export async function findCurrentConversation(ctx: SupportAccessContext) {
const conv = await findActiveConversationRow(ctx);
return conv ? mapConversation(conv) : null;
}
async function findActiveConversationRow(
ctx: SupportAccessContext
): Promise<SupportConversationRow | null> {
if (ctx.userId) {
let conv = await repo.findActiveConversationForUser(ctx.userId);
if (!conv && ctx.visitorToken) {
const visitorConv = await repo.findActiveConversationForVisitor(ctx.visitorToken);
if (visitorConv && !visitorConv.user_id) {
conv = await repo.attachVisitorConversationToUser(visitorConv.id, ctx.userId);
}
}
return conv;
}
if (!ctx.visitorToken) return null;
return repo.findActiveConversationForVisitor(ctx.visitorToken);
}
async function ensureConversationRow(
ctx: SupportAccessContext
): Promise<SupportConversationRow> {
const existing = await findActiveConversationRow(ctx);
if (existing) return existing;
if (ctx.userId) {
return repo.createConversation({ userId: ctx.userId });
}
if (!ctx.visitorToken) {
throw new Error('Visitor token is required for anonymous support');
}
return repo.createConversation({ visitorToken: ctx.visitorToken });
}
export async function ensureCurrentConversation(ctx: SupportAccessContext) {
return mapConversation(await ensureConversationRow(ctx));
}
export async function sendToCurrentConversation(
ctx: SupportAccessContext,
input: { body?: string; attachmentUrl?: string; attachmentName?: string; attachmentMime?: string }
) {
const conv = await ensureConversationRow(ctx);
return sendMessage(conv.id, ctx, input);
}
export async function listUserConversations(ctx: SupportAccessContext) {
if (!ctx.userId) {
if (!ctx.visitorToken) throw new Error('Not authenticated');
const conv = await repo.findActiveConversationForVisitor(ctx.visitorToken);
return conv ? [mapConversation(conv)] : [];
}
const rows = await repo.listConversationsForUser(ctx.userId);
return rows.map(mapConversation);
}
export async function getConversationMessages(
conversationId: string,
ctx: SupportAccessContext,
after?: string
) {
const conv = await assertConversationAccess(conversationId, ctx);
const rows = await repo.listMessages(conversationId, after);
const staffIds = rows
.filter((m) => m.sender_type === 'staff' && m.sender_user_id)
.map((m) => m.sender_user_id!);
const staffNames = new Map<string, string>();
for (const id of [...new Set(staffIds)]) {
const name = await repo.getStaffDisplayName(id);
if (name) staffNames.set(id, name);
}
const readerSide = isStaffRole(ctx.role) ? 'staff' : 'user';
await repo.markMessagesRead(conversationId, readerSide);
await repo.resetUnreadCounters(conversationId, readerSide);
await publishSupportEvent(conversationId, {
type: 'message.read',
conversationId,
});
const typing = await getTypingIndicators(conversationId);
const windows = await loadActionWindows();
return {
messages: rows.map((r) => mapMessage(r, staffNames, messageActions(r, conv, ctx, windows))),
typing,
policy: windows,
};
}
export async function sendMessage(
conversationId: string,
ctx: SupportAccessContext,
input: { body?: string; attachmentUrl?: string; attachmentName?: string; attachmentMime?: string }
) {
const conv = await assertConversationAccess(conversationId, ctx);
const body = input.body?.trim() ?? null;
if (!body && !input.attachmentUrl) {
throw new Error('Message body or attachment is required');
}
let senderType: SupportSenderType;
let senderUserId: string | null = null;
if (isStaffRole(ctx.role)) {
senderType = 'staff';
senderUserId = ctx.userId ?? null;
} else if (ctx.userId && conv.user_id === ctx.userId) {
senderType = 'user';
senderUserId = ctx.userId;
} else {
senderType = 'visitor';
}
const msg = await repo.createMessage({
conversationId,
senderType,
senderUserId,
body,
attachmentUrl: input.attachmentUrl ?? null,
attachmentName: input.attachmentName ?? null,
attachmentMime: input.attachmentMime ?? null,
});
const preview = previewForMessage(body, input.attachmentName ?? null);
const staffSent = senderType === 'staff';
await repo.touchConversationLastMessage(
conversationId,
preview,
staffSent,
!staffSent
);
if (conv.status === 'resolved' || conv.status === 'closed') {
await repo.updateConversation(conversationId, { status: 'open' });
}
const windows = await loadActionWindows();
const mapped = mapMessage(msg, undefined, messageActions(msg, conv, ctx, windows));
await publishSupportEvent(conversationId, {
type: 'message.new',
conversationId,
messageId: msg.id,
message: mapped as unknown as Record<string, unknown>,
});
return mapped;
}
export async function editMessage(
conversationId: string,
messageId: string,
ctx: SupportAccessContext,
body: string
) {
const conv = await assertConversationAccess(conversationId, ctx);
const row = await repo.findMessageById(messageId);
if (!row || row.conversation_id !== conversationId) {
throw new Error('Message not found');
}
const windows = await loadActionWindows();
assertSupportMessageAction('edit', {
createdAt: row.created_at,
deleted: !!row.deleted_at,
isOwner: ownerFlags(row, conv, ctx),
editWindowMinutes: windows.editWindowMinutes,
deleteWindowMinutes: windows.deleteWindowMinutes,
});
const trimmed = body.trim();
if (!trimmed && !row.attachment_url) {
throw new Error('Message body or attachment is required');
}
const updated = await repo.updateMessageBody(messageId, trimmed);
if (!updated) {
throw new Error('Message already deleted');
}
await refreshConversationPreview(conversationId);
const mapped = mapMessage(updated, undefined, messageActions(updated, conv, ctx, windows));
await publishSupportEvent(conversationId, {
type: 'message.updated',
conversationId,
messageId: updated.id,
message: mapped as unknown as Record<string, unknown>,
});
return mapped;
}
export async function deleteMessage(
conversationId: string,
messageId: string,
ctx: SupportAccessContext
) {
const conv = await assertConversationAccess(conversationId, ctx);
const row = await repo.findMessageById(messageId);
if (!row || row.conversation_id !== conversationId) {
throw new Error('Message not found');
}
const windows = await loadActionWindows();
assertSupportMessageAction('delete', {
createdAt: row.created_at,
deleted: !!row.deleted_at,
isOwner: ownerFlags(row, conv, ctx),
editWindowMinutes: windows.editWindowMinutes,
deleteWindowMinutes: windows.deleteWindowMinutes,
});
const updated = await repo.softDeleteMessage(messageId);
if (!updated) {
throw new Error('Message already deleted');
}
await refreshConversationPreview(conversationId);
const mapped = mapMessage(updated, undefined, messageActions(updated, conv, ctx, windows));
await publishSupportEvent(conversationId, {
type: 'message.deleted',
conversationId,
messageId: updated.id,
message: mapped as unknown as Record<string, unknown>,
});
return mapped;
}
export async function setTyping(
conversationId: string,
ctx: SupportAccessContext,
active: boolean
) {
await assertConversationAccess(conversationId, ctx);
const party = isStaffRole(ctx.role) ? 'staff' : 'user';
await setTypingIndicator(conversationId, party, active);
return { ok: true };
}
export async function listAdminConversations(filters: {
status?: string;
assignedTo?: string | null;
search?: string;
page?: number;
pageSize?: number;
}) {
const pageSize = Math.min(filters.pageSize ?? 30, 100);
const page = Math.max(filters.page ?? 1, 1);
const { rows, total } = await repo.listConversationsAdmin({
status: filters.status as repo.ConversationListFilters['status'],
assignedTo: filters.assignedTo,
search: filters.search,
limit: pageSize,
offset: (page - 1) * pageSize,
});
return {
items: rows.map(mapConversation),
total,
page,
pageSize,
totalPages: Math.ceil(total / pageSize) || 1,
};
}
export async function getAdminConversationDetail(conversationId: string) {
const conv = await repo.findConversationById(conversationId);
if (!conv) throw new Error('Conversation not found');
let userContext = null;
if (conv.user_id) {
const u = await repo.getUserContextForSupport(conv.user_id);
if (u) {
userContext = {
id: u.id,
email: decryptEmail(u.email_encrypted),
firstName: u.first_name,
lastName: u.last_name,
displayName: [u.first_name, u.last_name].filter(Boolean).join(' ').trim() || null,
role: u.role_name,
emailVerified: u.email_verified,
isEnabled: u.is_enabled,
createdAt: u.created_at.toISOString(),
};
}
}
return {
conversation: mapConversation(conv),
user: userContext,
};
}
export async function updateAdminConversation(
conversationId: string,
staffUserId: string,
patch: {
status?: string;
assignedTo?: string | null;
subject?: string;
}
) {
const conv = await repo.findConversationById(conversationId);
if (!conv) throw new Error('Conversation not found');
const updated = await repo.updateConversation(conversationId, {
status: patch.status as SupportConversationRow['status'],
assignedTo:
patch.assignedTo !== undefined
? patch.assignedTo
: conv.assigned_to ?? (patch.status === 'open' ? staffUserId : conv.assigned_to),
subject: patch.subject,
});
await publishSupportEvent(conversationId, {
type: 'conversation.updated',
conversationId,
});
return mapConversation(updated!);
}
export async function getStaffUnreadCount(): Promise<number> {
return repo.countUnreadStaffInbox();
}
export function resolveUploadPath(storedName: string): string {
const base = path.resolve(process.cwd(), 'data', 'support-uploads');
const safe = path.basename(storedName);
return path.join(base, safe);
}
export function ensureUploadDir(): string {
const dir = path.resolve(process.cwd(), 'data', 'support-uploads');
fs.mkdirSync(dir, { recursive: true });
return dir;
}
export function publicAttachmentUrl(storedName: string): string {
return `/api/v1/support/files/${encodeURIComponent(storedName)}`;
}
/** Links all anonymous visitor conversations to a newly registered or logged-in user. */
export async function mergeVisitorSupportForUser(
userId: string,
visitorToken: string | null | undefined
): Promise<number> {
if (!visitorToken || visitorToken.length < 16) return 0;
const count = await repo.mergeAllVisitorConversationsToUser(visitorToken, userId);
if (count > 0) {
const rows = await repo.listConversationsForUser(userId, count);
for (const row of rows.slice(0, count)) {
await publishSupportEvent(row.id, {
type: 'conversation.updated',
conversationId: row.id,
});
}
}
return count;
}