220 lines
9.0 KiB
JavaScript
220 lines
9.0 KiB
JavaScript
"use strict";
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.findConversationById = findConversationById;
|
|
exports.findActiveConversationForUser = findActiveConversationForUser;
|
|
exports.findActiveConversationForVisitor = findActiveConversationForVisitor;
|
|
exports.listConversationsForUser = listConversationsForUser;
|
|
exports.listConversationsAdmin = listConversationsAdmin;
|
|
exports.createConversation = createConversation;
|
|
exports.attachVisitorConversationToUser = attachVisitorConversationToUser;
|
|
exports.updateConversation = updateConversation;
|
|
exports.touchConversationLastMessage = touchConversationLastMessage;
|
|
exports.resetUnreadCounters = resetUnreadCounters;
|
|
exports.listMessages = listMessages;
|
|
exports.createMessage = createMessage;
|
|
exports.markMessagesRead = markMessagesRead;
|
|
exports.countUnreadStaffInbox = countUnreadStaffInbox;
|
|
exports.getUserContextForSupport = getUserContextForSupport;
|
|
exports.getStaffDisplayName = getStaffDisplayName;
|
|
exports.mergeAllVisitorConversationsToUser = mergeAllVisitorConversationsToUser;
|
|
const connection_1 = require("../db/connection");
|
|
async function findConversationById(id) {
|
|
const rows = await (0, connection_1.query)('SELECT * FROM support_conversations WHERE id = $1', [id]);
|
|
return rows[0] ?? null;
|
|
}
|
|
async function findActiveConversationForUser(userId) {
|
|
const rows = await (0, connection_1.query)(`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;
|
|
}
|
|
async function findActiveConversationForVisitor(visitorToken) {
|
|
const rows = await (0, connection_1.query)(`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;
|
|
}
|
|
async function listConversationsForUser(userId, limit = 20) {
|
|
return (0, connection_1.query)(`SELECT * FROM support_conversations
|
|
WHERE user_id = $1
|
|
ORDER BY last_message_at DESC NULLS LAST, created_at DESC
|
|
LIMIT $2`, [userId, limit]);
|
|
}
|
|
async function listConversationsAdmin(filters) {
|
|
const conditions = ['1=1'];
|
|
const params = [];
|
|
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++;
|
|
}
|
|
const where = conditions.join(' AND ');
|
|
const limit = Math.min(filters.limit ?? 50, 100);
|
|
const offset = filters.offset ?? 0;
|
|
const countRows = await (0, connection_1.query)(`SELECT COUNT(*)::text AS count FROM support_conversations c WHERE ${where}`, params);
|
|
const rows = await (0, connection_1.query)(`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) };
|
|
}
|
|
async function createConversation(input) {
|
|
const rows = await (0, connection_1.query)(`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];
|
|
}
|
|
async function attachVisitorConversationToUser(conversationId, userId) {
|
|
const rows = await (0, connection_1.query)(`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;
|
|
}
|
|
async function updateConversation(id, patch) {
|
|
const current = await findConversationById(id);
|
|
if (!current)
|
|
return null;
|
|
const rows = await (0, connection_1.query)(`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;
|
|
}
|
|
async function touchConversationLastMessage(id, preview, incrementUnreadUser, incrementUnreadStaff) {
|
|
await (0, connection_1.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]);
|
|
}
|
|
async function resetUnreadCounters(id, side) {
|
|
const col = side === 'user' ? 'unread_user' : 'unread_staff';
|
|
await (0, connection_1.query)(`UPDATE support_conversations SET ${col} = 0, updated_at = NOW() WHERE id = $1`, [
|
|
id,
|
|
]);
|
|
}
|
|
async function listMessages(conversationId, after, limit = 100) {
|
|
if (after) {
|
|
return (0, connection_1.query)(`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 (0, connection_1.query)(`SELECT * FROM support_messages
|
|
WHERE conversation_id = $1
|
|
ORDER BY created_at ASC
|
|
LIMIT $2`, [conversationId, limit]);
|
|
}
|
|
async function createMessage(input) {
|
|
const rows = await (0, connection_1.query)(`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];
|
|
}
|
|
async function markMessagesRead(conversationId, readerSide) {
|
|
const senderTypes = readerSide === 'user' ? ['staff'] : ['user', 'visitor'];
|
|
const rows = await (0, connection_1.query)(`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;
|
|
}
|
|
async function countUnreadStaffInbox() {
|
|
const rows = await (0, connection_1.query)(`SELECT COUNT(*)::text AS count FROM support_conversations
|
|
WHERE unread_staff > 0 AND status IN ('open', 'pending')`);
|
|
return Number(rows[0]?.count ?? 0);
|
|
}
|
|
async function getUserContextForSupport(userId) {
|
|
const rows = await (0, connection_1.query)(`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;
|
|
}
|
|
async function getStaffDisplayName(userId) {
|
|
const rows = await (0, connection_1.query)('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. */
|
|
async function mergeAllVisitorConversationsToUser(visitorToken, userId) {
|
|
const rows = await (0, connection_1.query)(`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 (0, connection_1.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;
|
|
}
|
|
//# sourceMappingURL=supportRepository.js.map
|