import { Response } from 'express'; import fs from 'fs'; import path from 'path'; import { AuthRequest } from '../middleware/auth'; import { readVisitorToken } from '../middleware/optionalAuth'; import { SUPPORT_ALLOWED_MIMES } from '../middleware/supportUpload'; import { removeUploadedFile } from '../utils/fileMagic'; import { validateUploadedFile } from '../utils/uploadValidation'; import * as supportService from '../services/supportService'; import { recordUploadedFile, FILE_INTEGRITY_ROOTS } from '../services/fileIntegrityService'; function buildCtx(req: AuthRequest) { return { userId: req.user?.userId, role: req.user?.role, visitorToken: readVisitorToken(req), }; } function handleError(res: Response, e: unknown): void { const msg = e instanceof Error ? e.message : 'Request failed'; if (msg === 'Forbidden') { res.status(403).json({ error: msg }); return; } if (msg === 'Conversation not found' || msg === 'Not found') { res.status(404).json({ error: msg }); return; } res.status(400).json({ error: msg }); } export async function getOrCreateConversation(req: AuthRequest, res: Response): Promise { try { const conv = await supportService.getOrCreateConversation(buildCtx(req)); res.json(conv); } catch (e) { handleError(res, e); } } export async function listMyConversations(req: AuthRequest, res: Response): Promise { try { const items = await supportService.listUserConversations(buildCtx(req)); res.json({ items }); } catch (e) { handleError(res, e); } } export async function getMessages(req: AuthRequest, res: Response): Promise { try { const after = typeof req.query.after === 'string' ? req.query.after : undefined; const data = await supportService.getConversationMessages( req.params.id, buildCtx(req), after ); res.json(data); } catch (e) { handleError(res, e); } } export async function postMessage(req: AuthRequest, res: Response): Promise { try { const body = typeof req.body?.body === 'string' ? req.body.body : undefined; const msg = await supportService.sendMessage(req.params.id, buildCtx(req), { body }); res.status(201).json(msg); } catch (e) { handleError(res, e); } } export async function postTyping(req: AuthRequest, res: Response): Promise { try { const active = req.body?.active !== false; const result = await supportService.setTyping(req.params.id, buildCtx(req), active); res.json(result); } catch (e) { handleError(res, e); } } export async function uploadAttachment(req: AuthRequest, res: Response): Promise { try { if (!req.file) { res.status(400).json({ error: 'No file uploaded' }); return; } const filePath = supportService.resolveUploadPath(req.file.filename); try { await validateUploadedFile(filePath, SUPPORT_ALLOWED_MIMES); } catch (e) { removeUploadedFile(filePath); const msg = e instanceof Error ? e.message : 'File validation failed'; res.status(msg.includes('virus') ? 422 : 400).json({ error: msg }); return; } await supportService.assertConversationAccess(req.params.id, buildCtx(req)); const url = supportService.publicAttachmentUrl(req.file.filename); await recordUploadedFile(FILE_INTEGRITY_ROOTS.support, req.file.filename); res.status(201).json({ attachmentUrl: url, attachmentName: req.file.originalname, attachmentMime: req.file.mimetype, }); } catch (e) { handleError(res, e); } } export async function getAttachment(req: AuthRequest, res: Response): Promise { try { const filePath = supportService.resolveUploadPath(req.params.filename); if (!fs.existsSync(filePath)) { res.status(404).json({ error: 'File not found' }); return; } res.sendFile(filePath); } catch (e) { handleError(res, e); } } export async function adminListConversations(req: AuthRequest, res: Response): Promise { try { const assignedTo = req.query.assignedTo === 'unassigned' ? null : typeof req.query.assignedTo === 'string' ? req.query.assignedTo : undefined; const data = await supportService.listAdminConversations({ status: typeof req.query.status === 'string' ? req.query.status : undefined, assignedTo, search: typeof req.query.search === 'string' ? req.query.search : undefined, page: req.query.page ? Number(req.query.page) : 1, pageSize: req.query.pageSize ? Number(req.query.pageSize) : 30, }); res.json(data); } catch (e) { handleError(res, e); } } export async function adminGetConversation(req: AuthRequest, res: Response): Promise { try { const data = await supportService.getAdminConversationDetail(req.params.id); res.json(data); } catch (e) { handleError(res, e); } } export async function adminUpdateConversation(req: AuthRequest, res: Response): Promise { try { const body = req.body as Record; const updated = await supportService.updateAdminConversation( req.params.id, req.user!.userId, { status: typeof body.status === 'string' ? body.status : undefined, assignedTo: body.assignedTo === null ? null : typeof body.assignedTo === 'string' ? body.assignedTo : undefined, subject: typeof body.subject === 'string' ? body.subject : undefined, } ); res.json(updated); } catch (e) { handleError(res, e); } } export async function adminPostMessage(req: AuthRequest, res: Response): Promise { try { const body = typeof req.body?.body === 'string' ? req.body.body : undefined; const msg = await supportService.sendMessage( req.params.id, { userId: req.user!.userId, role: req.user!.role }, { body } ); res.status(201).json(msg); } catch (e) { handleError(res, e); } } export async function adminGetMessages(req: AuthRequest, res: Response): Promise { try { const after = typeof req.query.after === 'string' ? req.query.after : undefined; const data = await supportService.getConversationMessages( req.params.id, { userId: req.user!.userId, role: req.user!.role }, after ); res.json(data); } catch (e) { handleError(res, e); } } export async function adminUnreadCount(_req: AuthRequest, res: Response): Promise { try { const count = await supportService.getStaffUnreadCount(); res.json({ unreadCount: count }); } catch (e) { handleError(res, e); } } export async function adminUploadAttachment(req: AuthRequest, res: Response): Promise { try { if (!req.file) { res.status(400).json({ error: 'No file uploaded' }); return; } const filePath = supportService.resolveUploadPath(req.file.filename); try { await validateUploadedFile(filePath, SUPPORT_ALLOWED_MIMES); } catch (e) { removeUploadedFile(filePath); const msg = e instanceof Error ? e.message : 'File validation failed'; res.status(msg.includes('virus') ? 422 : 400).json({ error: msg }); return; } const url = supportService.publicAttachmentUrl(req.file.filename); await recordUploadedFile(FILE_INTEGRITY_ROOTS.support, req.file.filename); res.status(201).json({ attachmentUrl: url, attachmentName: req.file.originalname, attachmentMime: req.file.mimetype, }); } catch (e) { handleError(res, e); } } export async function adminSendWithAttachment(req: AuthRequest, res: Response): Promise { try { const body = typeof req.body?.body === 'string' ? req.body.body : undefined; const attachmentUrl = typeof req.body?.attachmentUrl === 'string' ? req.body.attachmentUrl : undefined; const attachmentName = typeof req.body?.attachmentName === 'string' ? req.body.attachmentName : undefined; const attachmentMime = typeof req.body?.attachmentMime === 'string' ? req.body.attachmentMime : undefined; const msg = await supportService.sendMessage( req.params.id, { userId: req.user!.userId, role: req.user!.role }, { body, attachmentUrl, attachmentName, attachmentMime } ); res.status(201).json(msg); } catch (e) { handleError(res, e); } } export async function userSendWithAttachment(req: AuthRequest, res: Response): Promise { try { const body = typeof req.body?.body === 'string' ? req.body.body : undefined; const attachmentUrl = typeof req.body?.attachmentUrl === 'string' ? req.body.attachmentUrl : undefined; const attachmentName = typeof req.body?.attachmentName === 'string' ? req.body.attachmentName : undefined; const attachmentMime = typeof req.body?.attachmentMime === 'string' ? req.body.attachmentMime : undefined; const msg = await supportService.sendMessage(req.params.id, buildCtx(req), { body, attachmentUrl, attachmentName, attachmentMime, }); res.status(201).json(msg); } catch (e) { handleError(res, e); } }