1e66e918ac
- Add conversations and direct_messages tables to schema - User messaging page at /messages (users can start conversations, see admin responses) - Admin messaging page at /admin/messages (view all conversations, reply to users) - Admin bulk messaging: send to all customers, specific users, or admins - Mail icon in navbar for logged-in users (links to appropriate messaging page) - Show first name of admin who responded in conversation view - Clean build cache after middleware changes
63 lines
2.2 KiB
TypeScript
63 lines
2.2 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server';
|
|
import { db } from '@/lib/db';
|
|
import { requireRole } from '@/lib/auth';
|
|
import { getErrorMessage } from '@/lib/errors';
|
|
|
|
// Admin: Get all conversations
|
|
export async function GET() {
|
|
try {
|
|
await requireRole('admin');
|
|
|
|
// Get all conversations with participant info and last message
|
|
const { rows } = await db.query(`
|
|
SELECT
|
|
c.id,
|
|
c.subject,
|
|
c.created_at,
|
|
c.updated_at,
|
|
(SELECT content FROM direct_messages WHERE conversation_id = c.id ORDER BY created_at DESC LIMIT 1) as last_message,
|
|
(SELECT created_at FROM direct_messages WHERE conversation_id = c.id ORDER BY created_at DESC LIMIT 1) as last_message_at,
|
|
(SELECT COUNT(*) FROM direct_messages WHERE conversation_id = c.id) as message_count
|
|
FROM conversations c
|
|
ORDER BY c.updated_at DESC
|
|
`);
|
|
|
|
// Get participants for each conversation
|
|
const conversations = await Promise.all(rows.map(async (conv: any) => {
|
|
const { rows: participants } = await db.query(`
|
|
SELECT u.id, u.username, u.first_name, u.last_name, u.role
|
|
FROM conversation_participants cp
|
|
JOIN users u ON cp.user_id = u.id
|
|
WHERE cp.conversation_id = $1
|
|
ORDER BY u.role DESC, u.first_name
|
|
`, [conv.id]);
|
|
|
|
// Count unread for admins (messages from customers)
|
|
const { rows: unreadRows } = await db.query(`
|
|
SELECT COUNT(*) as unread
|
|
FROM direct_messages dm
|
|
JOIN users u ON dm.sender_id = u.id
|
|
WHERE dm.conversation_id = $1
|
|
AND u.role != 'admin'
|
|
AND dm.created_at > COALESCE(
|
|
(SELECT joined_at FROM conversation_participants WHERE conversation_id = $1 AND user_id = (SELECT id FROM users WHERE role = 'admin' LIMIT 1)),
|
|
'1970-01-01'::timestamp
|
|
)
|
|
`, [conv.id]);
|
|
|
|
return {
|
|
...conv,
|
|
participants,
|
|
unread_count: parseInt(unreadRows[0]?.unread || '0')
|
|
};
|
|
}));
|
|
|
|
return NextResponse.json({ conversations });
|
|
} catch (error) {
|
|
console.error('Admin get conversations error:', error);
|
|
return NextResponse.json(
|
|
{ error: getErrorMessage(error, 'Failed to get conversations') },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
} |