import path from 'path'; import fs from 'fs'; import crypto from 'crypto'; import { Request } from 'express'; import * as repo from '../repositories/faqRepository'; import { FaqCategoryRow } from '../models/faq.model'; import { ensureFaqUploadDir } from '../middleware/faqUpload'; import { sanitizeFaqHtml } from '../utils/sanitizeHtml'; function slugify(text: string): string { return text .trim() .toLowerCase() .normalize('NFD') .replace(/[\u0300-\u036f]/g, '') .replace(/[^a-z0-9]+/g, '-') .replace(/^-+|-+$/g, '') .slice(0, 64); } function mapCategory(row: FaqCategoryRow) { return { id: row.id, slug: row.slug, name: row.name, sortOrder: row.sort_order, isActive: row.is_active, createdAt: row.created_at.toISOString(), updatedAt: row.updated_at.toISOString(), }; } function mapEntryPublic(row: repo.FaqEntryWithCategory) { return { id: row.id, categoryId: row.category_id, categorySlug: row.category_slug, categoryName: row.category_name, question: row.question, answerHtml: row.answer_html, sortOrder: row.sort_order, viewCount: row.view_count, helpfulYes: row.helpful_yes, helpfulNo: row.helpful_no, }; } function mapEntryAdmin(row: repo.FaqEntryAdminRow) { return { ...mapEntryPublic(row), isActive: row.is_active, createdBy: row.created_by, updatedBy: row.updated_by, createdByName: row.created_by_name, updatedByName: row.updated_by_name, createdAt: row.created_at.toISOString(), updatedAt: row.updated_at.toISOString(), }; } export function buildVoterKey(req: Request, userId?: string): string { if (userId) return `user:${userId}`; const ip = req.ip ?? req.socket.remoteAddress ?? 'unknown'; const ua = req.get('user-agent') ?? ''; const hash = crypto.createHash('sha256').update(`${ip}|${ua}`).digest('hex').slice(0, 32); return `anon:${hash}`; } export function publicFaqFileUrl(filename: string): string { return `/api/v1/faq/files/${encodeURIComponent(filename)}`; } export function resolveFaqFilePath(filename: string): string { return path.join(ensureFaqUploadDir(), path.basename(filename)); } export async function listPublicCategories() { const rows = await repo.listCategories(true); return rows.map(mapCategory); } export async function listPublicFaqs(filters: { category?: string; search?: string }) { const rows = await repo.listPublicEntries({ categorySlug: filters.category, search: filters.search, }); return rows.map(mapEntryPublic); } export async function listPopularFaqs(limit?: number) { const rows = await repo.listPopularEntries(limit ?? 5); return rows.map(mapEntryPublic); } export async function getPublicFaq(id: string) { const row = await repo.getEntryById(id); if (!row || !row.is_active) throw new Error('FAQ not found'); return mapEntryPublic(row); } export async function recordFaqView(id: string) { const row = await repo.getEntryById(id); if (!row || !row.is_active) throw new Error('FAQ not found'); await repo.incrementViewCount(id); return { ok: true }; } export async function recordFaqHelpful(id: string, helpful: boolean, voterKey: string) { const row = await repo.getEntryById(id); if (!row || !row.is_active) throw new Error('FAQ not found'); return repo.recordHelpfulVote(id, voterKey, helpful); } export async function listAdminCategories() { const rows = await repo.listCategories(false); return rows.map(mapCategory); } export async function createAdminCategory(body: Record) { const name = typeof body.name === 'string' ? body.name.trim() : ''; if (!name) throw new Error('Category name is required'); const slug = typeof body.slug === 'string' && body.slug.trim() ? slugify(body.slug) : slugify(name); if (!slug) throw new Error('Invalid category slug'); return mapCategory( await repo.createCategory({ slug, name, sortOrder: typeof body.sortOrder === 'number' ? body.sortOrder : 0, isActive: body.isActive !== false, }) ); } export async function updateAdminCategory(id: number, body: Record) { const updated = await repo.updateCategory(id, { slug: typeof body.slug === 'string' ? slugify(body.slug) : undefined, name: typeof body.name === 'string' ? body.name.trim() : undefined, sortOrder: typeof body.sortOrder === 'number' ? body.sortOrder : undefined, isActive: typeof body.isActive === 'boolean' ? body.isActive : undefined, }); if (!updated) throw new Error('Category not found'); return mapCategory(updated); } export async function deleteAdminCategory(id: number) { const count = await repo.countEntriesInCategory(id); if (count > 0) { throw new Error('Cannot delete category that still contains FAQ entries'); } const ok = await repo.deleteCategory(id); if (!ok) throw new Error('Category not found'); return { ok: true }; } export async function listAdminFaqs(filters: { categoryId?: number; search?: string; isActive?: boolean; }) { const rows = await repo.listAdminEntries(filters); return rows.map(mapEntryAdmin); } export async function createAdminFaq(userId: string, body: Record) { const question = typeof body.question === 'string' ? body.question.trim() : ''; const answerHtml = typeof body.answerHtml === 'string' ? body.answerHtml : ''; const categoryId = Number(body.categoryId); if (!question) throw new Error('Question is required'); if (!answerHtml.trim()) throw new Error('Answer is required'); if (!Number.isFinite(categoryId)) throw new Error('categoryId is required'); const cat = await repo.getCategoryById(categoryId); if (!cat) throw new Error('Category not found'); const row = await repo.createEntry({ categoryId, question, answerHtml: sanitizeFaqHtml(answerHtml), isActive: body.isActive !== false, sortOrder: typeof body.sortOrder === 'number' ? body.sortOrder : 0, userId, }); const adminRows = await repo.listAdminEntries({}); const full = adminRows.find((r) => r.id === row.id); if (!full) throw new Error('FAQ created but not found'); return mapEntryAdmin(full); } export async function updateAdminFaq(id: string, userId: string, body: Record) { const updated = await repo.updateEntry(id, { categoryId: typeof body.categoryId === 'number' ? body.categoryId : undefined, question: typeof body.question === 'string' ? body.question.trim() : undefined, answerHtml: typeof body.answerHtml === 'string' ? sanitizeFaqHtml(body.answerHtml) : undefined, isActive: typeof body.isActive === 'boolean' ? body.isActive : undefined, sortOrder: typeof body.sortOrder === 'number' ? body.sortOrder : undefined, userId, }); if (!updated) throw new Error('FAQ not found'); const adminRows = await repo.listAdminEntries({}); const full = adminRows.find((r) => r.id === id); if (!full) throw new Error('FAQ not found'); return mapEntryAdmin(full); } export async function deleteAdminFaq(id: string) { const ok = await repo.deleteEntry(id); if (!ok) throw new Error('FAQ not found'); return { ok: true }; } export function readFaqFile(filename: string): string | null { const filePath = resolveFaqFilePath(filename); if (!fs.existsSync(filePath)) return null; return filePath; }