498 lines
14 KiB
TypeScript
498 lines
14 KiB
TypeScript
import { query } from '../db/connection';
|
|
import {
|
|
SupportConversationRow,
|
|
SupportConversationStatus,
|
|
SupportMessageRow,
|
|
SupportSenderType,
|
|
} from '../models/support.model';
|
|
|
|
export type ConversationListFilters = {
|
|
status?: SupportConversationStatus;
|
|
assignedTo?: string | null;
|
|
search?: string;
|
|
limit?: number;
|
|
offset?: number;
|
|
};
|
|
|
|
export async function findConversationById(id: string): Promise<SupportConversationRow | null> {
|
|
const rows = await query<SupportConversationRow[]>(
|
|
'SELECT * FROM support_conversations WHERE id = $1',
|
|
[id]
|
|
);
|
|
return rows[0] ?? null;
|
|
}
|
|
|
|
export async function findActiveConversationForUser(
|
|
userId: string
|
|
): Promise<SupportConversationRow | null> {
|
|
const rows = await query<SupportConversationRow[]>(
|
|
`SELECT * FROM support_conversations
|
|
WHERE user_id = $1 AND status IN ('open', 'pending')
|
|
ORDER BY last_message_at DESC NULLS LAST, created_at DESC
|
|
LIMIT 1`,
|
|
[userId]
|
|
);
|
|
return rows[0] ?? null;
|
|
}
|
|
|
|
export async function findActiveConversationForVisitor(
|
|
visitorToken: string
|
|
): Promise<SupportConversationRow | null> {
|
|
const rows = await query<SupportConversationRow[]>(
|
|
`SELECT * FROM support_conversations
|
|
WHERE visitor_token = $1 AND status IN ('open', 'pending')
|
|
ORDER BY last_message_at DESC NULLS LAST, created_at DESC
|
|
LIMIT 1`,
|
|
[visitorToken]
|
|
);
|
|
return rows[0] ?? null;
|
|
}
|
|
|
|
export async function listConversationsForUser(
|
|
userId: string,
|
|
limit = 20
|
|
): Promise<SupportConversationRow[]> {
|
|
return query<SupportConversationRow[]>(
|
|
`SELECT * FROM support_conversations
|
|
WHERE user_id = $1
|
|
ORDER BY last_message_at DESC NULLS LAST, created_at DESC
|
|
LIMIT $2`,
|
|
[userId, limit]
|
|
);
|
|
}
|
|
|
|
export async function listConversationsAdmin(
|
|
filters: ConversationListFilters
|
|
): Promise<{ rows: SupportConversationRow[]; total: number }> {
|
|
const conditions: string[] = ['1=1'];
|
|
const params: unknown[] = [];
|
|
let i = 1;
|
|
|
|
if (filters.status) {
|
|
conditions.push(`c.status = $${i++}`);
|
|
params.push(filters.status);
|
|
}
|
|
if (filters.assignedTo !== undefined) {
|
|
if (filters.assignedTo === null) {
|
|
conditions.push('c.assigned_to IS NULL');
|
|
} else {
|
|
conditions.push(`c.assigned_to = $${i++}`);
|
|
params.push(filters.assignedTo);
|
|
}
|
|
}
|
|
if (filters.search?.trim()) {
|
|
const term = `%${filters.search.trim()}%`;
|
|
conditions.push(`(
|
|
c.subject ILIKE $${i}
|
|
OR c.last_message_preview ILIKE $${i}
|
|
OR c.visitor_token ILIKE $${i}
|
|
OR EXISTS (
|
|
SELECT 1 FROM users u
|
|
WHERE u.id = c.user_id
|
|
AND (
|
|
u.id::text ILIKE $${i}
|
|
OR u.first_name ILIKE $${i}
|
|
OR u.last_name ILIKE $${i}
|
|
OR u.email_encrypted ILIKE $${i}
|
|
)
|
|
)
|
|
OR EXISTS (
|
|
SELECT 1 FROM support_messages m
|
|
WHERE m.conversation_id = c.id AND m.body ILIKE $${i}
|
|
)
|
|
)`);
|
|
params.push(term);
|
|
i++;
|
|
}
|
|
|
|
conditions.push('c.last_message_at IS NOT NULL');
|
|
const where = conditions.join(' AND ');
|
|
const limit = Math.min(filters.limit ?? 50, 100);
|
|
const offset = filters.offset ?? 0;
|
|
|
|
const countRows = await query<{ count: string }[]>(
|
|
`SELECT COUNT(*)::text AS count FROM support_conversations c WHERE ${where}`,
|
|
params
|
|
);
|
|
|
|
const rows = await query<SupportConversationRow[]>(
|
|
`SELECT c.* FROM support_conversations c
|
|
WHERE ${where}
|
|
ORDER BY c.last_message_at DESC NULLS LAST, c.created_at DESC
|
|
LIMIT $${i++} OFFSET $${i}`,
|
|
[...params, limit, offset]
|
|
);
|
|
|
|
return { rows, total: Number(countRows[0]?.count ?? 0) };
|
|
}
|
|
|
|
export async function createConversation(input: {
|
|
userId?: string | null;
|
|
visitorToken?: string | null;
|
|
subject?: string | null;
|
|
}): Promise<SupportConversationRow> {
|
|
const rows = await query<SupportConversationRow[]>(
|
|
`INSERT INTO support_conversations (user_id, visitor_token, subject)
|
|
VALUES ($1, $2, $3)
|
|
RETURNING *`,
|
|
[input.userId ?? null, input.visitorToken ?? null, input.subject ?? null]
|
|
);
|
|
return rows[0];
|
|
}
|
|
|
|
export async function attachVisitorConversationToUser(
|
|
conversationId: string,
|
|
userId: string
|
|
): Promise<SupportConversationRow | null> {
|
|
const rows = await query<SupportConversationRow[]>(
|
|
`UPDATE support_conversations
|
|
SET user_id = $2, visitor_token = NULL, updated_at = NOW()
|
|
WHERE id = $1 AND user_id IS NULL
|
|
RETURNING *`,
|
|
[conversationId, userId]
|
|
);
|
|
return rows[0] ?? null;
|
|
}
|
|
|
|
export async function updateConversation(
|
|
id: string,
|
|
patch: Partial<{
|
|
status: SupportConversationStatus;
|
|
assignedTo: string | null;
|
|
subject: string | null;
|
|
unreadUser: number;
|
|
unreadStaff: number;
|
|
}>
|
|
): Promise<SupportConversationRow | null> {
|
|
const current = await findConversationById(id);
|
|
if (!current) return null;
|
|
|
|
const rows = await query<SupportConversationRow[]>(
|
|
`UPDATE support_conversations SET
|
|
status = $2,
|
|
assigned_to = $3,
|
|
subject = $4,
|
|
unread_user = $5,
|
|
unread_staff = $6,
|
|
updated_at = NOW()
|
|
WHERE id = $1
|
|
RETURNING *`,
|
|
[
|
|
id,
|
|
patch.status ?? current.status,
|
|
patch.assignedTo !== undefined ? patch.assignedTo : current.assigned_to,
|
|
patch.subject !== undefined ? patch.subject : current.subject,
|
|
patch.unreadUser ?? current.unread_user,
|
|
patch.unreadStaff ?? current.unread_staff,
|
|
]
|
|
);
|
|
return rows[0] ?? null;
|
|
}
|
|
|
|
export async function touchConversationLastMessage(
|
|
id: string,
|
|
preview: string,
|
|
incrementUnreadUser: boolean,
|
|
incrementUnreadStaff: boolean
|
|
): Promise<void> {
|
|
await query(
|
|
`UPDATE support_conversations SET
|
|
last_message_at = NOW(),
|
|
last_message_preview = $2,
|
|
unread_user = unread_user + $3,
|
|
unread_staff = unread_staff + $4,
|
|
updated_at = NOW()
|
|
WHERE id = $1`,
|
|
[id, preview.slice(0, 500), incrementUnreadUser ? 1 : 0, incrementUnreadStaff ? 1 : 0]
|
|
);
|
|
}
|
|
|
|
export async function resetUnreadCounters(
|
|
id: string,
|
|
side: 'user' | 'staff'
|
|
): Promise<void> {
|
|
const col = side === 'user' ? 'unread_user' : 'unread_staff';
|
|
await query(`UPDATE support_conversations SET ${col} = 0, updated_at = NOW() WHERE id = $1`, [
|
|
id,
|
|
]);
|
|
}
|
|
|
|
export async function listMessages(
|
|
conversationId: string,
|
|
after?: string,
|
|
limit = 100
|
|
): Promise<SupportMessageRow[]> {
|
|
if (after) {
|
|
return query<SupportMessageRow[]>(
|
|
`SELECT * FROM support_messages
|
|
WHERE conversation_id = $1 AND created_at > (
|
|
SELECT created_at FROM support_messages WHERE id = $2
|
|
)
|
|
ORDER BY created_at ASC
|
|
LIMIT $3`,
|
|
[conversationId, after, limit]
|
|
);
|
|
}
|
|
return query<SupportMessageRow[]>(
|
|
`SELECT * FROM support_messages
|
|
WHERE conversation_id = $1
|
|
ORDER BY created_at ASC
|
|
LIMIT $2`,
|
|
[conversationId, limit]
|
|
);
|
|
}
|
|
|
|
export async function findMessageById(id: string): Promise<SupportMessageRow | null> {
|
|
const rows = await query<SupportMessageRow[]>(
|
|
'SELECT * FROM support_messages WHERE id = $1',
|
|
[id]
|
|
);
|
|
return rows[0] ?? null;
|
|
}
|
|
|
|
export async function findLatestVisibleMessage(
|
|
conversationId: string
|
|
): Promise<SupportMessageRow | null> {
|
|
const rows = await query<SupportMessageRow[]>(
|
|
`SELECT * FROM support_messages
|
|
WHERE conversation_id = $1 AND deleted_at IS NULL
|
|
ORDER BY created_at DESC
|
|
LIMIT 1`,
|
|
[conversationId]
|
|
);
|
|
return rows[0] ?? null;
|
|
}
|
|
|
|
export async function updateMessageBody(
|
|
id: string,
|
|
body: string
|
|
): Promise<SupportMessageRow | null> {
|
|
const rows = await query<SupportMessageRow[]>(
|
|
`UPDATE support_messages
|
|
SET body = $2, edited_at = NOW()
|
|
WHERE id = $1 AND deleted_at IS NULL
|
|
RETURNING *`,
|
|
[id, body]
|
|
);
|
|
return rows[0] ?? null;
|
|
}
|
|
|
|
export async function softDeleteMessage(id: string): Promise<SupportMessageRow | null> {
|
|
const rows = await query<SupportMessageRow[]>(
|
|
`UPDATE support_messages
|
|
SET deleted_at = NOW()
|
|
WHERE id = $1 AND deleted_at IS NULL
|
|
RETURNING *`,
|
|
[id]
|
|
);
|
|
return rows[0] ?? null;
|
|
}
|
|
|
|
export async function updateConversationPreview(
|
|
id: string,
|
|
preview: string,
|
|
lastMessageAt: Date | null
|
|
): Promise<void> {
|
|
await query(
|
|
`UPDATE support_conversations SET
|
|
last_message_preview = $2,
|
|
last_message_at = $3,
|
|
updated_at = NOW()
|
|
WHERE id = $1`,
|
|
[id, preview.slice(0, 500), lastMessageAt]
|
|
);
|
|
}
|
|
|
|
export async function createMessage(input: {
|
|
conversationId: string;
|
|
senderType: SupportSenderType;
|
|
senderUserId?: string | null;
|
|
body?: string | null;
|
|
attachmentUrl?: string | null;
|
|
attachmentName?: string | null;
|
|
attachmentMime?: string | null;
|
|
}): Promise<SupportMessageRow> {
|
|
const rows = await query<SupportMessageRow[]>(
|
|
`INSERT INTO support_messages (
|
|
conversation_id, sender_type, sender_user_id, body,
|
|
attachment_url, attachment_name, attachment_mime
|
|
) VALUES ($1, $2, $3, $4, $5, $6, $7)
|
|
RETURNING *`,
|
|
[
|
|
input.conversationId,
|
|
input.senderType,
|
|
input.senderUserId ?? null,
|
|
input.body ?? null,
|
|
input.attachmentUrl ?? null,
|
|
input.attachmentName ?? null,
|
|
input.attachmentMime ?? null,
|
|
]
|
|
);
|
|
return rows[0];
|
|
}
|
|
|
|
export async function markMessagesRead(
|
|
conversationId: string,
|
|
readerSide: 'user' | 'staff'
|
|
): Promise<number> {
|
|
const senderTypes =
|
|
readerSide === 'user' ? ['staff'] : (['user', 'visitor'] as SupportSenderType[]);
|
|
const rows = await query<{ id: string }[]>(
|
|
`UPDATE support_messages SET read_at = NOW()
|
|
WHERE conversation_id = $1
|
|
AND sender_type = ANY($2::varchar[])
|
|
AND read_at IS NULL
|
|
RETURNING id`,
|
|
[conversationId, senderTypes]
|
|
);
|
|
return rows.length;
|
|
}
|
|
|
|
export async function countUnreadStaffInbox(): Promise<number> {
|
|
const rows = await query<{ count: string }[]>(
|
|
`SELECT COUNT(*)::text AS count FROM support_conversations
|
|
WHERE unread_staff > 0 AND status IN ('open', 'pending')`
|
|
);
|
|
return Number(rows[0]?.count ?? 0);
|
|
}
|
|
|
|
export async function getUserContextForSupport(userId: string): Promise<{
|
|
id: string;
|
|
email_encrypted: string | null;
|
|
first_name: string | null;
|
|
last_name: string | null;
|
|
role_name: string;
|
|
email_verified: boolean;
|
|
is_enabled: boolean;
|
|
created_at: Date;
|
|
} | null> {
|
|
const rows = await query<
|
|
{
|
|
id: string;
|
|
email_encrypted: string | null;
|
|
first_name: string | null;
|
|
last_name: string | null;
|
|
role_name: string;
|
|
email_verified: boolean;
|
|
is_enabled: boolean;
|
|
created_at: Date;
|
|
}[]
|
|
>(
|
|
`SELECT u.id, u.email_encrypted, u.first_name, u.last_name,
|
|
r.name AS role_name, u.email_verified, u.is_enabled, u.created_at
|
|
FROM users u
|
|
JOIN roles r ON r.id = u.role_id
|
|
WHERE u.id = $1`,
|
|
[userId]
|
|
);
|
|
return rows[0] ?? null;
|
|
}
|
|
|
|
export async function getStaffDisplayName(userId: string): Promise<string | null> {
|
|
const rows = await query<{ first_name: string | null; last_name: string | null }[]>(
|
|
'SELECT first_name, last_name FROM users WHERE id = $1',
|
|
[userId]
|
|
);
|
|
const u = rows[0];
|
|
if (!u) return null;
|
|
const name = [u.first_name, u.last_name].filter(Boolean).join(' ').trim();
|
|
return name || null;
|
|
}
|
|
|
|
/** Attach every open visitor conversation to the user and rewrite visitor senders. */
|
|
export async function mergeAllVisitorConversationsToUser(
|
|
visitorToken: string,
|
|
userId: string
|
|
): Promise<number> {
|
|
const rows = await query<{ id: string }[]>(
|
|
`UPDATE support_conversations
|
|
SET user_id = $2, visitor_token = NULL, updated_at = NOW()
|
|
WHERE visitor_token = $1 AND user_id IS NULL
|
|
RETURNING id`,
|
|
[visitorToken, userId]
|
|
);
|
|
if (!rows.length) return 0;
|
|
|
|
const ids = rows.map((r) => r.id);
|
|
await query(
|
|
`UPDATE support_messages
|
|
SET sender_type = 'user', sender_user_id = $2
|
|
WHERE conversation_id = ANY($1::uuid[]) AND sender_type = 'visitor'`,
|
|
[ids, userId]
|
|
);
|
|
return rows.length;
|
|
}
|
|
|
|
export type SupportUploadedFileRow = {
|
|
filename: string;
|
|
mime: string;
|
|
original_name: string | null;
|
|
conversation_id: string | null;
|
|
uploaded_by_user_id: string | null;
|
|
visitor_token: string | null;
|
|
created_at: Date;
|
|
};
|
|
|
|
export async function insertUploadedFile(input: {
|
|
filename: string;
|
|
mime: string;
|
|
originalName?: string | null;
|
|
conversationId?: string | null;
|
|
uploadedByUserId?: string | null;
|
|
visitorToken?: string | null;
|
|
}): Promise<SupportUploadedFileRow> {
|
|
const rows = await query<SupportUploadedFileRow[]>(
|
|
`INSERT INTO support_uploaded_files (
|
|
filename, mime, original_name, conversation_id, uploaded_by_user_id, visitor_token
|
|
) VALUES ($1, $2, $3, $4, $5, $6)
|
|
RETURNING *`,
|
|
[
|
|
input.filename,
|
|
input.mime,
|
|
input.originalName ?? null,
|
|
input.conversationId ?? null,
|
|
input.uploadedByUserId ?? null,
|
|
input.visitorToken ?? null,
|
|
]
|
|
);
|
|
return rows[0]!;
|
|
}
|
|
|
|
export async function findUploadedFile(filename: string): Promise<SupportUploadedFileRow | null> {
|
|
const rows = await query<SupportUploadedFileRow[]>(
|
|
`SELECT * FROM support_uploaded_files WHERE filename = $1`,
|
|
[filename]
|
|
);
|
|
return rows[0] ?? null;
|
|
}
|
|
|
|
export async function bindUploadedFileConversation(
|
|
filename: string,
|
|
conversationId: string
|
|
): Promise<void> {
|
|
await query(
|
|
`UPDATE support_uploaded_files
|
|
SET conversation_id = COALESCE(conversation_id, $2)
|
|
WHERE filename = $1`,
|
|
[filename, conversationId]
|
|
);
|
|
}
|
|
|
|
export async function findMessageByAttachmentFilename(
|
|
filename: string
|
|
): Promise<{ conversation_id: string } | null> {
|
|
const suffix = `%/support/files/${filename}`;
|
|
const rows = await query<{ conversation_id: string }[]>(
|
|
`SELECT conversation_id FROM support_messages
|
|
WHERE attachment_url IS NOT NULL
|
|
AND (
|
|
attachment_url = $1
|
|
OR attachment_url LIKE $2
|
|
)
|
|
ORDER BY created_at DESC
|
|
LIMIT 1`,
|
|
[`/api/v1/support/files/${filename}`, suffix]
|
|
);
|
|
return rows[0] ?? null;
|
|
}
|