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
69 lines
2.0 KiB
TypeScript
69 lines
2.0 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server';
|
|
import { db } from '@/lib/db';
|
|
import { requireAuth } from '@/lib/auth';
|
|
import { getErrorMessage } from '@/lib/errors';
|
|
|
|
// Send a message to a conversation
|
|
export async function POST(
|
|
request: NextRequest,
|
|
{ params }: { params: Promise<{ id: string }> }
|
|
) {
|
|
try {
|
|
const user = await requireAuth();
|
|
if (!user) {
|
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
|
}
|
|
|
|
const { id } = await params;
|
|
const { content } = await request.json();
|
|
|
|
if (!content || content.trim().length === 0) {
|
|
return NextResponse.json({ error: 'Message content is required' }, { status: 400 });
|
|
}
|
|
|
|
// Verify user is participant
|
|
const { rows: participants } = await db.query(
|
|
'SELECT * FROM conversation_participants WHERE conversation_id = $1 AND user_id = $2',
|
|
[id, user.id]
|
|
);
|
|
|
|
if (participants.length === 0) {
|
|
return NextResponse.json({ error: 'Not authorized for this conversation' }, { status: 403 });
|
|
}
|
|
|
|
// Create message
|
|
const { rows: msgRows } = await db.query(
|
|
'INSERT INTO direct_messages (conversation_id, sender_id, content) VALUES ($1, $2, $3) RETURNING *',
|
|
[id, user.id, content]
|
|
);
|
|
|
|
// Update conversation updated_at
|
|
await db.query(
|
|
'UPDATE conversations SET updated_at = NOW() WHERE id = $1',
|
|
[id]
|
|
);
|
|
|
|
// Get sender info
|
|
const { rows: userRows } = await db.query(
|
|
'SELECT id, username, first_name, last_name, role FROM users WHERE id = $1',
|
|
[user.id]
|
|
);
|
|
|
|
return NextResponse.json({
|
|
message: {
|
|
...msgRows[0],
|
|
sender_id: user.id,
|
|
username: userRows[0].username,
|
|
first_name: userRows[0].first_name,
|
|
last_name: userRows[0].last_name,
|
|
role: userRows[0].role
|
|
}
|
|
});
|
|
} catch (error) {
|
|
console.error('Send message error:', error);
|
|
return NextResponse.json(
|
|
{ error: getErrorMessage(error, 'Failed to send message') },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
} |