"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.isStaffRole = isStaffRole; exports.assertConversationAccess = assertConversationAccess; exports.getOrCreateConversation = getOrCreateConversation; exports.listUserConversations = listUserConversations; exports.getConversationMessages = getConversationMessages; exports.sendMessage = sendMessage; exports.setTyping = setTyping; exports.listAdminConversations = listAdminConversations; exports.getAdminConversationDetail = getAdminConversationDetail; exports.updateAdminConversation = updateAdminConversation; exports.getStaffUnreadCount = getStaffUnreadCount; exports.resolveUploadPath = resolveUploadPath; exports.ensureUploadDir = ensureUploadDir; exports.publicAttachmentUrl = publicAttachmentUrl; exports.mergeVisitorSupportForUser = mergeVisitorSupportForUser; const path_1 = __importDefault(require("path")); const fs_1 = __importDefault(require("fs")); const crypto_1 = require("../utils/crypto"); const repo = __importStar(require("../repositories/supportRepository")); const supportRealtimeService_1 = require("./supportRealtimeService"); const STAFF_ROLES = new Set(['admin', 'moderator']); function isStaffRole(role) { return !!role && STAFF_ROLES.has(role); } function previewForMessage(body, attachmentName) { if (body?.trim()) return body.trim().slice(0, 200); if (attachmentName) return `📎 ${attachmentName}`; return 'Message'; } function mapMessage(row, staffNames) { const staffName = row.sender_type === 'staff' && row.sender_user_id ? staffNames?.get(row.sender_user_id) ?? null : null; return { id: row.id, conversationId: row.conversation_id, senderType: row.sender_type, senderUserId: row.sender_user_id, senderDisplayName: staffName, body: row.body, attachmentUrl: row.attachment_url, attachmentName: row.attachment_name, attachmentMime: row.attachment_mime, readAt: row.read_at?.toISOString() ?? null, createdAt: row.created_at.toISOString(), }; } function mapConversation(row) { 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) { if (!encrypted) return null; try { return (0, crypto_1.decrypt)(encrypted); } catch { return null; } } async function assertConversationAccess(conversationId, ctx) { 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'); } async function getOrCreateConversation(ctx) { 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); } } if (!conv) { conv = await repo.createConversation({ userId: ctx.userId }); } return mapConversation(conv); } if (!ctx.visitorToken) { throw new Error('Visitor token is required for anonymous support'); } let conv = await repo.findActiveConversationForVisitor(ctx.visitorToken); if (!conv) { conv = await repo.createConversation({ visitorToken: ctx.visitorToken }); } return mapConversation(conv); } async function listUserConversations(ctx) { 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); } async function getConversationMessages(conversationId, ctx, after) { 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(); 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 (0, supportRealtimeService_1.publishSupportEvent)(conversationId, { type: 'message.read', conversationId, }); const typing = await (0, supportRealtimeService_1.getTypingIndicators)(conversationId); return { messages: rows.map((r) => mapMessage(r, staffNames)), typing, }; } async function sendMessage(conversationId, ctx, input) { 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; let senderUserId = 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' }); } await (0, supportRealtimeService_1.publishSupportEvent)(conversationId, { type: 'message.new', conversationId, messageId: msg.id, message: mapMessage(msg), }); return mapMessage(msg); } async function setTyping(conversationId, ctx, active) { await assertConversationAccess(conversationId, ctx); const party = isStaffRole(ctx.role) ? 'staff' : 'user'; await (0, supportRealtimeService_1.setTypingIndicator)(conversationId, party, active); return { ok: true }; } async function listAdminConversations(filters) { 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, 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, }; } async function getAdminConversationDetail(conversationId) { 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, }; } async function updateAdminConversation(conversationId, staffUserId, patch) { const conv = await repo.findConversationById(conversationId); if (!conv) throw new Error('Conversation not found'); const updated = await repo.updateConversation(conversationId, { status: patch.status, assignedTo: patch.assignedTo !== undefined ? patch.assignedTo : conv.assigned_to ?? (patch.status === 'open' ? staffUserId : conv.assigned_to), subject: patch.subject, }); await (0, supportRealtimeService_1.publishSupportEvent)(conversationId, { type: 'conversation.updated', conversationId, }); return mapConversation(updated); } async function getStaffUnreadCount() { return repo.countUnreadStaffInbox(); } function resolveUploadPath(storedName) { const base = path_1.default.resolve(process.cwd(), 'data', 'support-uploads'); const safe = path_1.default.basename(storedName); return path_1.default.join(base, safe); } function ensureUploadDir() { const dir = path_1.default.resolve(process.cwd(), 'data', 'support-uploads'); fs_1.default.mkdirSync(dir, { recursive: true }); return dir; } function publicAttachmentUrl(storedName) { return `/api/v1/support/files/${encodeURIComponent(storedName)}`; } /** Links all anonymous visitor conversations to a newly registered or logged-in user. */ async function mergeVisitorSupportForUser(userId, visitorToken) { 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 (0, supportRealtimeService_1.publishSupportEvent)(row.id, { type: 'conversation.updated', conversationId: row.id, }); } } return count; } //# sourceMappingURL=supportService.js.map