adbcc4b9af
feat: implement conversations API with message retrieval and posting feat: add avatar URL handling for users and update user role definitions feat: create chat system tables in the database with initial seed data fix: update user roles from "sales_user" to "sales" for consistency chore: add middleware for system API route access fixed fuckups on john's side, added a benchmark Made Graphs actualy load from database and realtime data, graphs will update and percentages will be mathematically made, and made realtime added chatcart edits, made graphs glow. added in some little small home feeling fuctions added in a slide show, in login with qoutes from creators because i want to leave a print on it saying we made this shit, we built it brick for brick login page added qoutes some random, and made them shuffle from left to right one dissapears other come in adding shape to the textbox for the qoutes Fixed my chat fuckups when it comes to chats
116 lines
3.6 KiB
TypeScript
116 lines
3.6 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server"
|
|
import { getSessionUser } from "@/lib/auth"
|
|
import { query } from "@/lib/db"
|
|
|
|
export async function GET(
|
|
_request: NextRequest,
|
|
{ params }: { params: Promise<{ id: string }> },
|
|
) {
|
|
try {
|
|
const user = await getSessionUser()
|
|
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
|
|
|
const { id } = await params
|
|
|
|
const [msgResult, otherReadResult] = await Promise.all([
|
|
query(
|
|
`SELECT m.id, m.sender_id, m.content, m.created_at, m.updated_at, m.deleted_at,
|
|
u.first_name || ' ' || u.last_name AS sender_name,
|
|
u.email AS sender_email,
|
|
u.avatar_url AS sender_avatar_url
|
|
FROM messages m
|
|
JOIN users u ON u.id = m.sender_id
|
|
WHERE m.conversation_id = $1 AND m.deleted_at IS NULL
|
|
ORDER BY m.created_at ASC`,
|
|
[id],
|
|
),
|
|
query(
|
|
`SELECT last_read_at FROM conversation_participants
|
|
WHERE conversation_id = $1 AND user_id != $2`,
|
|
[id, user.id],
|
|
),
|
|
])
|
|
|
|
const otherLastReadAt = otherReadResult.rows[0]?.last_read_at
|
|
? new Date(otherReadResult.rows[0].last_read_at).getTime()
|
|
: 0
|
|
|
|
const messages = msgResult.rows.map((row: any) => ({
|
|
id: row.id,
|
|
conversationId: id,
|
|
senderId: row.sender_id,
|
|
senderName: row.sender_name,
|
|
senderAvatar: row.sender_avatar_url || `https://ui-avatars.com/api/?name=${encodeURIComponent(row.sender_name)}&background=1d4ed8&color=fff&size=128`,
|
|
content: row.content,
|
|
timestamp: formatTime(new Date(row.created_at)),
|
|
createdAt: row.created_at,
|
|
read: row.sender_id === user.id
|
|
? new Date(row.created_at).getTime() <= otherLastReadAt
|
|
: true,
|
|
}))
|
|
|
|
return NextResponse.json({ messages })
|
|
} catch (error) {
|
|
console.error("Messages error:", error)
|
|
return NextResponse.json({ error: "Failed to load messages" }, { status: 500 })
|
|
}
|
|
}
|
|
|
|
export async function POST(
|
|
request: NextRequest,
|
|
{ params }: { params: Promise<{ id: string }> },
|
|
) {
|
|
try {
|
|
const user = await getSessionUser()
|
|
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
|
|
|
const { id } = await params
|
|
const { content } = await request.json()
|
|
|
|
if (!content?.trim()) {
|
|
return NextResponse.json({ error: "Message content is required" }, { status: 400 })
|
|
}
|
|
|
|
const result = await query(
|
|
`INSERT INTO messages (conversation_id, sender_id, content)
|
|
VALUES ($1, $2, $3)
|
|
RETURNING id, created_at`,
|
|
[id, user.id, content.trim()],
|
|
)
|
|
|
|
await query(
|
|
`UPDATE conversations SET updated_at = NOW() WHERE id = $1`,
|
|
[id],
|
|
)
|
|
|
|
const msg = result.rows[0]
|
|
|
|
return NextResponse.json({
|
|
message: {
|
|
id: msg.id,
|
|
conversationId: id,
|
|
senderId: user.id,
|
|
senderName: `${user.firstName} ${user.lastName}`,
|
|
senderAvatar: user.avatar,
|
|
content: content.trim(),
|
|
timestamp: formatTime(new Date(msg.created_at)),
|
|
createdAt: msg.created_at,
|
|
read: false,
|
|
},
|
|
})
|
|
} catch (error) {
|
|
console.error("Send message error:", error)
|
|
return NextResponse.json({ error: "Failed to send message" }, { status: 500 })
|
|
}
|
|
}
|
|
|
|
function formatTime(date: Date): string {
|
|
const now = new Date()
|
|
const isToday = date.toDateString() === now.toDateString()
|
|
if (isToday) {
|
|
return date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })
|
|
}
|
|
return date.toLocaleDateString([], { month: "short", day: "numeric" }) + " " +
|
|
date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })
|
|
}
|