78 lines
2.3 KiB
TypeScript
78 lines
2.3 KiB
TypeScript
'use server'
|
|
import { clerkClient, auth } from '@clerk/nextjs/server'
|
|
import { google } from 'googleapis'
|
|
import { env } from '~/env'
|
|
|
|
export async function scheduleMeeting({
|
|
title,
|
|
description,
|
|
dateTime,
|
|
durationMinutes,
|
|
attendeeEmail,
|
|
attendeeName,
|
|
}: {
|
|
title: string
|
|
description: string
|
|
dateTime: string
|
|
durationMinutes: number
|
|
attendeeEmail?: string
|
|
attendeeName?: string
|
|
}) {
|
|
try {
|
|
const clerk = await clerkClient()
|
|
const userAuth = await auth()
|
|
const user = await clerk.users.getUser(userAuth.userId?userAuth.userId:"")
|
|
// Get admin's Google OAuth token to create the event on Gregor's calendar
|
|
const adminTokenResponse = await clerk.users.getUserOauthAccessToken(
|
|
env.ADMIN_USER_CLERK_ID,
|
|
'oauth_google',
|
|
)
|
|
const adminToken = adminTokenResponse.data[0]
|
|
|
|
if (!adminToken?.token) {
|
|
return { success: false, error: 'Admin Google Calendar not connected. Ensure the admin account is linked with Google and has calendar scope enabled.' }
|
|
}
|
|
|
|
// Try to resolve visitor's Google email for the invite
|
|
let visitorEmail: string | undefined = attendeeEmail
|
|
if (!visitorEmail) {
|
|
visitorEmail = user?.emailAddresses.at(0)?.emailAddress ?? undefined
|
|
}
|
|
|
|
const oAuth2Client = new google.auth.OAuth2()
|
|
oAuth2Client.setCredentials({ access_token: adminToken.token })
|
|
const calendar = google.calendar({ version: 'v3', auth: oAuth2Client })
|
|
|
|
const startTime = new Date(dateTime)
|
|
const endTime = new Date(startTime.getTime() + durationMinutes * 60 * 1000)
|
|
|
|
const attendees: { email: string; displayName?: string }[] = []
|
|
if (visitorEmail) {
|
|
attendees.push({ email: visitorEmail, displayName: attendeeName })
|
|
}
|
|
|
|
const event = await calendar.events.insert({
|
|
calendarId: 'primary',
|
|
sendUpdates: 'all',
|
|
requestBody: {
|
|
summary: title,
|
|
description,
|
|
start: { dateTime: startTime.toISOString(), timeZone: 'UTC' },
|
|
end: { dateTime: endTime.toISOString(), timeZone: 'UTC' },
|
|
attendees,
|
|
},
|
|
sendNotifications: true
|
|
})
|
|
|
|
return {
|
|
success: true,
|
|
eventId: event.data.id,
|
|
htmlLink: event.data.htmlLink,
|
|
message: `Meeting "${title}" scheduled for ${startTime.toLocaleString()}${visitorEmail ? `. Invite sent to ${visitorEmail}.` : '.'}`,
|
|
}
|
|
} catch (error) {
|
|
console.error('Failed to schedule meeting:', error)
|
|
return { success: false, error: 'Failed to schedule meeting. Please try again.' }
|
|
}
|
|
}
|