444 lines
13 KiB
TypeScript
444 lines
13 KiB
TypeScript
import { query } from '../db/connection';
|
|
import { FaqCategoryRow, FaqEntryRow } from '../models/faq.model';
|
|
|
|
export type FaqEntryWithCategory = FaqEntryRow & {
|
|
category_slug: string;
|
|
category_name: string;
|
|
};
|
|
|
|
export type FaqEntryAdminRow = FaqEntryWithCategory & {
|
|
created_by_name: string | null;
|
|
updated_by_name: string | null;
|
|
};
|
|
|
|
export async function listCategories(activeOnly = false): Promise<FaqCategoryRow[]> {
|
|
if (activeOnly) {
|
|
return query<FaqCategoryRow[]>(
|
|
`SELECT * FROM faq_categories WHERE is_active = TRUE ORDER BY sort_order ASC, name ASC`
|
|
);
|
|
}
|
|
return query<FaqCategoryRow[]>(
|
|
`SELECT * FROM faq_categories ORDER BY sort_order ASC, name ASC`
|
|
);
|
|
}
|
|
|
|
export async function getCategoryById(id: number): Promise<FaqCategoryRow | null> {
|
|
const rows = await query<FaqCategoryRow[]>(`SELECT * FROM faq_categories WHERE id = $1`, [id]);
|
|
return rows[0] ?? null;
|
|
}
|
|
|
|
export async function getCategoryBySlug(slug: string): Promise<FaqCategoryRow | null> {
|
|
const rows = await query<FaqCategoryRow[]>(
|
|
`SELECT * FROM faq_categories WHERE slug = $1`,
|
|
[slug]
|
|
);
|
|
return rows[0] ?? null;
|
|
}
|
|
|
|
export async function createCategory(input: {
|
|
slug: string;
|
|
name: string;
|
|
description?: string | null;
|
|
sortOrder?: number;
|
|
isActive?: boolean;
|
|
}): Promise<FaqCategoryRow> {
|
|
const rows = await query<FaqCategoryRow[]>(
|
|
`INSERT INTO faq_categories (slug, name, description, sort_order, is_active)
|
|
VALUES ($1, $2, $3, $4, $5) RETURNING *`,
|
|
[
|
|
input.slug,
|
|
input.name,
|
|
input.description ?? null,
|
|
input.sortOrder ?? 0,
|
|
input.isActive ?? true,
|
|
]
|
|
);
|
|
return rows[0];
|
|
}
|
|
|
|
export async function updateCategory(
|
|
id: number,
|
|
patch: Partial<{
|
|
slug: string;
|
|
name: string;
|
|
description: string | null;
|
|
sortOrder: number;
|
|
isActive: boolean;
|
|
}>
|
|
): Promise<FaqCategoryRow | null> {
|
|
const c = await getCategoryById(id);
|
|
if (!c) return null;
|
|
const rows = await query<FaqCategoryRow[]>(
|
|
`UPDATE faq_categories SET
|
|
slug = $2,
|
|
name = $3,
|
|
description = $4,
|
|
sort_order = $5,
|
|
is_active = $6,
|
|
updated_at = NOW()
|
|
WHERE id = $1 RETURNING *`,
|
|
[
|
|
id,
|
|
patch.slug ?? c.slug,
|
|
patch.name ?? c.name,
|
|
patch.description !== undefined ? patch.description : c.description,
|
|
patch.sortOrder ?? c.sort_order,
|
|
patch.isActive ?? c.is_active,
|
|
]
|
|
);
|
|
return rows[0] ?? null;
|
|
}
|
|
|
|
/** Atomically set one language PDF pointer (safe replace). */
|
|
export async function setCategoryDocument(
|
|
id: number,
|
|
lang: 'fr' | 'en',
|
|
filename: string,
|
|
originalName: string
|
|
): Promise<FaqCategoryRow | null> {
|
|
const filenameCol = lang === 'fr' ? 'pdf_fr_filename' : 'pdf_en_filename';
|
|
const originalCol = lang === 'fr' ? 'pdf_fr_original_name' : 'pdf_en_original_name';
|
|
const rows = await query<FaqCategoryRow[]>(
|
|
`UPDATE faq_categories SET
|
|
${filenameCol} = $2,
|
|
${originalCol} = $3,
|
|
updated_at = NOW()
|
|
WHERE id = $1 RETURNING *`,
|
|
[id, filename, originalName]
|
|
);
|
|
return rows[0] ?? null;
|
|
}
|
|
|
|
/** Clear one language PDF pointer; returns previous filenames for disk cleanup. */
|
|
export async function clearCategoryDocument(
|
|
id: number,
|
|
lang: 'fr' | 'en'
|
|
): Promise<{ row: FaqCategoryRow; removedFilename: string | null } | null> {
|
|
const c = await getCategoryById(id);
|
|
if (!c) return null;
|
|
const removedFilename = lang === 'fr' ? c.pdf_fr_filename : c.pdf_en_filename;
|
|
const filenameCol = lang === 'fr' ? 'pdf_fr_filename' : 'pdf_en_filename';
|
|
const originalCol = lang === 'fr' ? 'pdf_fr_original_name' : 'pdf_en_original_name';
|
|
const rows = await query<FaqCategoryRow[]>(
|
|
`UPDATE faq_categories SET
|
|
${filenameCol} = NULL,
|
|
${originalCol} = NULL,
|
|
updated_at = NOW()
|
|
WHERE id = $1 RETURNING *`,
|
|
[id]
|
|
);
|
|
if (!rows[0]) return null;
|
|
return { row: rows[0], removedFilename };
|
|
}
|
|
|
|
export async function deleteCategory(id: number): Promise<boolean> {
|
|
const rows = await query<{ id: number }[]>(
|
|
`DELETE FROM faq_categories WHERE id = $1 RETURNING id`,
|
|
[id]
|
|
);
|
|
return rows.length > 0;
|
|
}
|
|
|
|
export async function listPublicEntries(filters: {
|
|
categorySlug?: string;
|
|
search?: string;
|
|
}): Promise<FaqEntryWithCategory[]> {
|
|
const conditions = ['e.is_active = TRUE', 'c.is_active = TRUE'];
|
|
const params: unknown[] = [];
|
|
let i = 1;
|
|
|
|
if (filters.categorySlug) {
|
|
conditions.push(`c.slug = $${i++}`);
|
|
params.push(filters.categorySlug);
|
|
}
|
|
if (filters.search?.trim()) {
|
|
conditions.push(`(e.question ILIKE $${i} OR e.answer_html ILIKE $${i})`);
|
|
params.push(`%${filters.search.trim()}%`);
|
|
i++;
|
|
}
|
|
|
|
return query<FaqEntryWithCategory[]>(
|
|
`SELECT e.*, c.slug AS category_slug, c.name AS category_name
|
|
FROM faq_entries e
|
|
INNER JOIN faq_categories c ON c.id = e.category_id
|
|
WHERE ${conditions.join(' AND ')}
|
|
ORDER BY c.sort_order ASC, e.sort_order ASC, e.question ASC`,
|
|
params
|
|
);
|
|
}
|
|
|
|
export async function listPopularEntries(limit = 5): Promise<FaqEntryWithCategory[]> {
|
|
return query<FaqEntryWithCategory[]>(
|
|
`SELECT e.*, c.slug AS category_slug, c.name AS category_name
|
|
FROM faq_entries e
|
|
INNER JOIN faq_categories c ON c.id = e.category_id
|
|
WHERE e.is_active = TRUE AND c.is_active = TRUE
|
|
ORDER BY (e.helpful_yes - e.helpful_no) DESC, e.view_count DESC
|
|
LIMIT $1`,
|
|
[Math.min(limit, 20)]
|
|
);
|
|
}
|
|
|
|
export async function getEntryById(id: string): Promise<FaqEntryWithCategory | null> {
|
|
const rows = await query<FaqEntryWithCategory[]>(
|
|
`SELECT e.*, c.slug AS category_slug, c.name AS category_name
|
|
FROM faq_entries e
|
|
INNER JOIN faq_categories c ON c.id = e.category_id
|
|
WHERE e.id = $1`,
|
|
[id]
|
|
);
|
|
return rows[0] ?? null;
|
|
}
|
|
|
|
export async function incrementViewCount(id: string): Promise<void> {
|
|
await query(`UPDATE faq_entries SET view_count = view_count + 1 WHERE id = $1`, [id]);
|
|
}
|
|
|
|
export async function recordHelpfulVote(
|
|
faqId: string,
|
|
voterKey: string,
|
|
helpful: boolean
|
|
): Promise<{ helpfulYes: number; helpfulNo: number; changed: boolean }> {
|
|
const existing = await query<{ helpful: boolean }[]>(
|
|
`SELECT helpful FROM faq_helpful_votes WHERE faq_id = $1 AND voter_key = $2`,
|
|
[faqId, voterKey]
|
|
);
|
|
|
|
if (existing[0]) {
|
|
if (existing[0].helpful === helpful) {
|
|
const counts = await getHelpfulCounts(faqId);
|
|
return { ...counts, changed: false };
|
|
}
|
|
await query(
|
|
`UPDATE faq_helpful_votes SET helpful = $3, created_at = NOW()
|
|
WHERE faq_id = $1 AND voter_key = $2`,
|
|
[faqId, voterKey, helpful]
|
|
);
|
|
if (existing[0].helpful) {
|
|
await query(
|
|
`UPDATE faq_entries SET helpful_yes = GREATEST(helpful_yes - 1, 0), helpful_no = helpful_no + 1 WHERE id = $1`,
|
|
[faqId]
|
|
);
|
|
} else {
|
|
await query(
|
|
`UPDATE faq_entries SET helpful_no = GREATEST(helpful_no - 1, 0), helpful_yes = helpful_yes + 1 WHERE id = $1`,
|
|
[faqId]
|
|
);
|
|
}
|
|
} else {
|
|
await query(
|
|
`INSERT INTO faq_helpful_votes (faq_id, voter_key, helpful) VALUES ($1, $2, $3)`,
|
|
[faqId, voterKey, helpful]
|
|
);
|
|
if (helpful) {
|
|
await query(`UPDATE faq_entries SET helpful_yes = helpful_yes + 1 WHERE id = $1`, [faqId]);
|
|
} else {
|
|
await query(`UPDATE faq_entries SET helpful_no = helpful_no + 1 WHERE id = $1`, [faqId]);
|
|
}
|
|
}
|
|
|
|
const counts = await getHelpfulCounts(faqId);
|
|
return { ...counts, changed: true };
|
|
}
|
|
|
|
async function getHelpfulCounts(faqId: string) {
|
|
const rows = await query<{ helpful_yes: number; helpful_no: number }[]>(
|
|
`SELECT helpful_yes, helpful_no FROM faq_entries WHERE id = $1`,
|
|
[faqId]
|
|
);
|
|
return {
|
|
helpfulYes: rows[0]?.helpful_yes ?? 0,
|
|
helpfulNo: rows[0]?.helpful_no ?? 0,
|
|
};
|
|
}
|
|
|
|
export async function listAdminEntries(filters: {
|
|
categoryId?: number;
|
|
search?: string;
|
|
isActive?: boolean;
|
|
}): Promise<FaqEntryAdminRow[]> {
|
|
const conditions: string[] = ['1=1'];
|
|
const params: unknown[] = [];
|
|
let i = 1;
|
|
|
|
if (filters.categoryId != null) {
|
|
conditions.push(`e.category_id = $${i++}`);
|
|
params.push(filters.categoryId);
|
|
}
|
|
if (filters.isActive != null) {
|
|
conditions.push(`e.is_active = $${i++}`);
|
|
params.push(filters.isActive);
|
|
}
|
|
if (filters.search?.trim()) {
|
|
conditions.push(`(e.question ILIKE $${i} OR e.answer_html ILIKE $${i})`);
|
|
params.push(`%${filters.search.trim()}%`);
|
|
i++;
|
|
}
|
|
|
|
return query<FaqEntryAdminRow[]>(
|
|
`SELECT e.*, c.slug AS category_slug, c.name AS category_name,
|
|
TRIM(CONCAT(cb.first_name, ' ', cb.last_name)) AS created_by_name,
|
|
TRIM(CONCAT(ub.first_name, ' ', ub.last_name)) AS updated_by_name
|
|
FROM faq_entries e
|
|
INNER JOIN faq_categories c ON c.id = e.category_id
|
|
LEFT JOIN users cb ON cb.id = e.created_by
|
|
LEFT JOIN users ub ON ub.id = e.updated_by
|
|
WHERE ${conditions.join(' AND ')}
|
|
ORDER BY c.sort_order ASC, e.sort_order ASC, e.created_at DESC`,
|
|
params
|
|
);
|
|
}
|
|
|
|
export async function createEntry(input: {
|
|
categoryId: number;
|
|
question: string;
|
|
answerHtml: string;
|
|
isActive?: boolean;
|
|
sortOrder?: number;
|
|
userId: string;
|
|
}): Promise<FaqEntryRow> {
|
|
const rows = await query<FaqEntryRow[]>(
|
|
`INSERT INTO faq_entries (
|
|
category_id, question, answer_html, is_active, sort_order, created_by, updated_by
|
|
) VALUES ($1, $2, $3, $4, $5, $6, $6) RETURNING *`,
|
|
[
|
|
input.categoryId,
|
|
input.question,
|
|
input.answerHtml,
|
|
input.isActive ?? true,
|
|
input.sortOrder ?? 0,
|
|
input.userId,
|
|
]
|
|
);
|
|
return rows[0];
|
|
}
|
|
|
|
export async function updateEntry(
|
|
id: string,
|
|
patch: Partial<{
|
|
categoryId: number;
|
|
question: string;
|
|
answerHtml: string;
|
|
isActive: boolean;
|
|
sortOrder: number;
|
|
userId: string;
|
|
}>
|
|
): Promise<FaqEntryRow | null> {
|
|
const current = await query<FaqEntryRow[]>(`SELECT * FROM faq_entries WHERE id = $1`, [id]);
|
|
if (!current[0]) return null;
|
|
const e = current[0];
|
|
const rows = await query<FaqEntryRow[]>(
|
|
`UPDATE faq_entries SET
|
|
category_id = $2,
|
|
question = $3,
|
|
answer_html = $4,
|
|
is_active = $5,
|
|
sort_order = $6,
|
|
updated_by = $7,
|
|
updated_at = NOW()
|
|
WHERE id = $1 RETURNING *`,
|
|
[
|
|
id,
|
|
patch.categoryId ?? e.category_id,
|
|
patch.question ?? e.question,
|
|
patch.answerHtml ?? e.answer_html,
|
|
patch.isActive ?? e.is_active,
|
|
patch.sortOrder ?? e.sort_order,
|
|
patch.userId ?? e.updated_by,
|
|
]
|
|
);
|
|
return rows[0] ?? null;
|
|
}
|
|
|
|
export async function deleteEntry(id: string): Promise<boolean> {
|
|
const rows = await query<{ id: string }[]>(
|
|
`DELETE FROM faq_entries WHERE id = $1 RETURNING id`,
|
|
[id]
|
|
);
|
|
return rows.length > 0;
|
|
}
|
|
|
|
export async function countEntriesInCategory(categoryId: number): Promise<number> {
|
|
const rows = await query<{ count: string }[]>(
|
|
`SELECT COUNT(*)::text AS count FROM faq_entries WHERE category_id = $1`,
|
|
[categoryId]
|
|
);
|
|
return Number(rows[0]?.count ?? 0);
|
|
}
|
|
|
|
export type FaqUploadedFileRow = {
|
|
filename: string;
|
|
mime: string;
|
|
original_name: string | null;
|
|
kind: 'media' | 'category_pdf';
|
|
category_id: number | null;
|
|
uploaded_by_user_id: string | null;
|
|
created_at: Date;
|
|
};
|
|
|
|
export async function insertUploadedFile(input: {
|
|
filename: string;
|
|
mime: string;
|
|
originalName?: string | null;
|
|
kind: 'media' | 'category_pdf';
|
|
categoryId?: number | null;
|
|
uploadedByUserId?: string | null;
|
|
}): Promise<FaqUploadedFileRow> {
|
|
const rows = await query<FaqUploadedFileRow[]>(
|
|
`INSERT INTO faq_uploaded_files (
|
|
filename, mime, original_name, kind, category_id, uploaded_by_user_id
|
|
) VALUES ($1, $2, $3, $4, $5, $6)
|
|
ON CONFLICT (filename) DO UPDATE SET
|
|
mime = EXCLUDED.mime,
|
|
original_name = EXCLUDED.original_name,
|
|
kind = EXCLUDED.kind,
|
|
category_id = EXCLUDED.category_id,
|
|
uploaded_by_user_id = COALESCE(EXCLUDED.uploaded_by_user_id, faq_uploaded_files.uploaded_by_user_id)
|
|
RETURNING *`,
|
|
[
|
|
input.filename,
|
|
input.mime,
|
|
input.originalName ?? null,
|
|
input.kind,
|
|
input.categoryId ?? null,
|
|
input.uploadedByUserId ?? null,
|
|
]
|
|
);
|
|
return rows[0]!;
|
|
}
|
|
|
|
export async function findUploadedFile(filename: string): Promise<FaqUploadedFileRow | null> {
|
|
const rows = await query<FaqUploadedFileRow[]>(
|
|
`SELECT * FROM faq_uploaded_files WHERE filename = $1`,
|
|
[filename]
|
|
);
|
|
return rows[0] ?? null;
|
|
}
|
|
|
|
export async function deleteUploadedFile(filename: string): Promise<void> {
|
|
await query(`DELETE FROM faq_uploaded_files WHERE filename = $1`, [filename]);
|
|
}
|
|
|
|
/** True if filename is still referenced as a category PDF pointer. */
|
|
export async function isCategoryPdfFilename(filename: string): Promise<boolean> {
|
|
const rows = await query<{ ok: number }[]>(
|
|
`SELECT 1 AS ok FROM faq_categories
|
|
WHERE pdf_fr_filename = $1 OR pdf_en_filename = $1
|
|
LIMIT 1`,
|
|
[filename]
|
|
);
|
|
return rows.length > 0;
|
|
}
|
|
|
|
/** Legacy media: referenced from an FAQ answer HTML body. */
|
|
export async function isReferencedInFaqAnswerHtml(filename: string): Promise<boolean> {
|
|
const needle = `%/faq/files/${filename}%`;
|
|
const rows = await query<{ ok: number }[]>(
|
|
`SELECT 1 AS ok FROM faq_entries
|
|
WHERE answer_html ILIKE $1
|
|
LIMIT 1`,
|
|
[needle]
|
|
);
|
|
return rows.length > 0;
|
|
}
|