mirror of
https://git.coastit.co.za/caitlin/CRM_ENVR.git
synced 2026-07-10 11:15:43 +02:00
189 lines
7.0 KiB
TypeScript
189 lines
7.0 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server"
|
|
import { getSessionUser } from "@/lib/auth"
|
|
import { query } from "@/lib/db"
|
|
import { sendEventConfirmation } from "@/lib/email"
|
|
|
|
export async function GET(request: NextRequest) {
|
|
try {
|
|
const user = await getSessionUser()
|
|
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
|
|
|
const { searchParams } = new URL(request.url)
|
|
const start = searchParams.get("start")
|
|
const end = searchParams.get("end")
|
|
const status = searchParams.get("status")
|
|
|
|
let sql = `SELECT e.id, e.user_id, e.participant_id, e.lead_id, e.conversation_id,
|
|
e.title, e.description, e.participant_notes, e.event_type,
|
|
e.start_time, e.end_time, e.duration_minutes, e.status, e.created_at,
|
|
u.id AS u_id, u.first_name AS u_first, u.last_name AS u_last, u.email AS u_email, u.avatar_url AS u_avatar,
|
|
ur.role_id AS u_role_id, r.name AS u_role_name, r.display_name AS u_role_display,
|
|
p.id AS p_id, p.first_name AS p_first, p.last_name AS p_last, p.email AS p_email, p.avatar_url AS p_avatar,
|
|
pr.role_id AS p_role_id, pr2.name AS p_role_name, pr2.display_name AS p_role_display,
|
|
l.id AS l_id, l.company_name, l.contact_name
|
|
FROM scheduled_events e
|
|
JOIN users u ON u.id = e.user_id
|
|
LEFT JOIN users p ON p.id = e.participant_id
|
|
LEFT JOIN leads l ON l.id = e.lead_id
|
|
LEFT JOIN user_roles ur ON ur.user_id = e.user_id
|
|
LEFT JOIN roles r ON r.id = ur.role_id
|
|
LEFT JOIN user_roles pr ON pr.user_id = e.participant_id
|
|
LEFT JOIN roles pr2 ON pr2.id = pr.role_id`
|
|
const params: unknown[] = []
|
|
let idx = 1
|
|
|
|
if (user.role !== "super_admin") {
|
|
sql += ` WHERE e.user_id = $${idx} OR e.participant_id = $${idx}`
|
|
params.push(user.id)
|
|
idx++
|
|
} else {
|
|
sql += ` WHERE 1=1`
|
|
}
|
|
|
|
if (start) {
|
|
sql += ` AND e.start_time >= $${idx}`
|
|
params.push(start)
|
|
idx++
|
|
}
|
|
|
|
if (end) {
|
|
sql += ` AND e.start_time <= $${idx}`
|
|
params.push(end)
|
|
idx++
|
|
}
|
|
|
|
if (status) {
|
|
sql += ` AND e.status = $${idx}`
|
|
params.push(status)
|
|
idx++
|
|
}
|
|
|
|
sql += " ORDER BY e.start_time ASC"
|
|
|
|
const result = await query(sql, params, user.id)
|
|
|
|
const events = result.rows.map((r: any) => ({
|
|
id: r.id,
|
|
userId: r.user_id,
|
|
participantId: r.participant_id,
|
|
leadId: r.lead_id,
|
|
conversationId: r.conversation_id,
|
|
title: r.title,
|
|
description: r.description,
|
|
participantNotes: r.participant_notes,
|
|
eventType: r.event_type,
|
|
startTime: r.start_time,
|
|
endTime: r.end_time,
|
|
durationMinutes: r.duration_minutes,
|
|
status: r.status,
|
|
creator: { id: r.u_id, name: `${r.u_first} ${r.u_last}`, email: r.u_email, role: r.u_role_display || r.u_role_name, avatar: r.u_avatar },
|
|
participant: r.p_id ? { id: r.p_id, name: `${r.p_first} ${r.p_last}`, email: r.p_email, role: r.p_role_display || r.p_role_name, avatar: r.p_avatar } : null,
|
|
lead: r.l_id ? { id: r.l_id, companyName: r.company_name, contactName: r.contact_name } : null,
|
|
createdAt: r.created_at,
|
|
}))
|
|
|
|
return NextResponse.json({ events })
|
|
} catch (error) {
|
|
console.error("Events GET error:", error)
|
|
return NextResponse.json({ error: "Failed to load events" }, { status: 500 })
|
|
}
|
|
}
|
|
|
|
export async function POST(request: NextRequest) {
|
|
try {
|
|
const user = await getSessionUser()
|
|
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
|
|
|
const {
|
|
participantId, leadId, conversationId,
|
|
title, description, eventType,
|
|
startTime, endTime, durationMinutes,
|
|
} = await request.json()
|
|
|
|
if (!title || !startTime) {
|
|
return NextResponse.json({ error: "Title and start time are required" }, { status: 400 })
|
|
}
|
|
|
|
const result = await query(
|
|
`INSERT INTO scheduled_events (user_id, participant_id, lead_id, conversation_id, title, description, event_type, start_time, end_time, duration_minutes)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
|
RETURNING id, user_id, participant_id, lead_id, conversation_id, title, description, participant_notes, event_type, start_time, end_time, duration_minutes, status, created_at`,
|
|
[
|
|
user.id,
|
|
participantId || null,
|
|
leadId || null,
|
|
conversationId || null,
|
|
title,
|
|
description || null,
|
|
eventType || "meeting",
|
|
startTime,
|
|
endTime || null,
|
|
durationMinutes || null,
|
|
],
|
|
user.id,
|
|
)
|
|
|
|
const r = result.rows[0]
|
|
|
|
if (participantId && participantId !== user.id) {
|
|
await query(
|
|
`INSERT INTO notifications (user_id, type, title, description, link, context_id, context_type)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7)`,
|
|
[
|
|
participantId,
|
|
"event_scheduled",
|
|
`Meeting scheduled: ${title}`,
|
|
`${user.firstName} ${user.lastName} scheduled a ${eventType || "meeting"} with you`,
|
|
`/calendar`,
|
|
r.id,
|
|
"scheduled_event",
|
|
],
|
|
)
|
|
}
|
|
|
|
const participantResult = participantId ? await query(
|
|
`SELECT email, first_name, last_name FROM users WHERE id = $1`,
|
|
[participantId],
|
|
) : null
|
|
const participant = participantResult?.rows[0] || null
|
|
|
|
sendEventConfirmation({
|
|
creatorName: `${user.firstName} ${user.lastName}`,
|
|
creatorEmail: user.email,
|
|
participantName: participant ? `${participant.first_name} ${participant.last_name}` : null,
|
|
participantEmail: participant?.email || null,
|
|
title,
|
|
description: description || undefined,
|
|
eventType: eventType || "meeting",
|
|
startTime,
|
|
endTime: endTime || undefined,
|
|
durationMinutes: durationMinutes || undefined,
|
|
}).catch((err) => console.error("Email error:", err))
|
|
|
|
return NextResponse.json({
|
|
event: {
|
|
id: r.id,
|
|
userId: r.user_id,
|
|
participantId: r.participant_id,
|
|
leadId: r.lead_id,
|
|
conversationId: r.conversation_id,
|
|
title: r.title,
|
|
description: r.description,
|
|
participantNotes: r.participant_notes,
|
|
eventType: r.event_type,
|
|
startTime: r.start_time,
|
|
endTime: r.end_time,
|
|
durationMinutes: r.duration_minutes,
|
|
status: r.status,
|
|
creator: { id: user.id, name: `${user.firstName} ${user.lastName}`, email: user.email, role: user.role },
|
|
participant: participantId ? { id: participantId, name: participant ? `${participant.first_name} ${participant.last_name}` : participantId, email: participant?.email || null } : null,
|
|
lead: leadId ? { id: leadId, companyName: "", contactName: "" } : null,
|
|
createdAt: r.created_at,
|
|
},
|
|
}, { status: 201 })
|
|
} catch (error) {
|
|
console.error("Events POST error:", error)
|
|
return NextResponse.json({ error: "Failed to create event" }, { status: 500 })
|
|
}
|
|
}
|