mirror of
https://github.com/ichsankurnia/hats-app.git
synced 2026-12-05 11:06:29 +00:00
cf9e36f10a
Add calendar authentication and event/task actions, plus rich-description styling and setup documentation.
544 lines
14 KiB
TypeScript
544 lines
14 KiB
TypeScript
'use server';
|
|
|
|
import { revalidatePath } from 'next/cache';
|
|
import { calendar_v3 } from 'googleapis';
|
|
import dayjs from 'dayjs';
|
|
import { getGoogleCalendarClient, formatGoogleApiError } from './auth';
|
|
import {
|
|
CalendarActionResponse,
|
|
CalendarEventItem,
|
|
CreateEventInput,
|
|
UpdateEventInput,
|
|
} from './types';
|
|
|
|
const TIME_ZONE = 'Asia/Jakarta';
|
|
const FOOTER_DELIMITER = '\n\n--- [Additional Info H.A.T.s] ---';
|
|
|
|
function stripDescriptionFooter(desc?: string | null): string {
|
|
if (!desc) return '';
|
|
const idx = desc.indexOf(FOOTER_DELIMITER);
|
|
return idx !== -1 ? desc.slice(0, idx).trim() : desc.trim();
|
|
}
|
|
|
|
function buildDescriptionWithFooter(rawDesc: string, guests: string[], meetLink?: string): string {
|
|
const clean = stripDescriptionFooter(rawDesc);
|
|
const extraLines: string[] = [];
|
|
|
|
if (meetLink) {
|
|
extraLines.push(`Google Meet: ${meetLink}`);
|
|
}
|
|
if (guests.length > 0) {
|
|
extraLines.push(`Tamu (Guests): ${guests.join(', ')}`);
|
|
}
|
|
|
|
if (extraLines.length === 0) {
|
|
return clean;
|
|
}
|
|
|
|
return `${clean}${FOOTER_DELIMITER}\n${extraLines.join('\n')}`.trim();
|
|
}
|
|
|
|
function mapGoogleEventToItem(item: calendar_v3.Schema$Event): CalendarEventItem {
|
|
const isAllDay = !item.start?.dateTime && !!item.start?.date;
|
|
const startStr = item.start?.dateTime || item.start?.date || '';
|
|
let endStr = item.end?.dateTime || item.end?.date || '';
|
|
|
|
// Convert Google Calendar exclusive end.date back to inclusive date for UI
|
|
if (isAllDay && item.start?.date && item.end?.date) {
|
|
const startDay = dayjs(item.start.date);
|
|
const endDay = dayjs(item.end.date);
|
|
if (endDay.isAfter(startDay, 'day')) {
|
|
endStr = endDay.subtract(1, 'day').format('YYYY-MM-DD');
|
|
} else {
|
|
endStr = item.start.date;
|
|
}
|
|
}
|
|
|
|
const privateProps = item.extendedProperties?.private || {};
|
|
|
|
// Parse attendees from native field + fallback privateProps.guests
|
|
const nativeAttendees = item.attendees?.map((a) => a.email).filter((email): email is string => Boolean(email)) || [];
|
|
|
|
let storedGuests: string[] = [];
|
|
if (privateProps.guests) {
|
|
try {
|
|
const parsed = JSON.parse(privateProps.guests);
|
|
if (Array.isArray(parsed)) {
|
|
storedGuests = parsed.filter((e): e is string => typeof e === 'string');
|
|
}
|
|
} catch {
|
|
// ignore invalid json
|
|
}
|
|
}
|
|
|
|
const attendees = Array.from(new Set([...nativeAttendees, ...storedGuests]));
|
|
|
|
// Resolve Google Meet / Conference link
|
|
const videoEntry = item.conferenceData?.entryPoints?.find((ep) => ep.entryPointType === 'video')?.uri;
|
|
const hangoutLink = item.hangoutLink || videoEntry || privateProps.meetLink || undefined;
|
|
|
|
const rawDescription =
|
|
privateProps.rawDescription !== undefined
|
|
? privateProps.rawDescription
|
|
: stripDescriptionFooter(item.description);
|
|
|
|
return {
|
|
id: item.id || '',
|
|
summary: item.summary || '(Tanpa Judul)',
|
|
description: rawDescription,
|
|
location: item.location || '',
|
|
start: startStr,
|
|
end: endStr,
|
|
isAllDay,
|
|
colorId: item.colorId || undefined,
|
|
attendees,
|
|
hangoutLink,
|
|
htmlLink: item.htmlLink || '',
|
|
creatorEmail: item.creator?.email || '',
|
|
createdAt: item.created || '',
|
|
updatedAt: item.updated || '',
|
|
};
|
|
}
|
|
|
|
function buildEventStartAndEnd(
|
|
startDateTime: string,
|
|
endDateTime: string,
|
|
isAllDay?: boolean,
|
|
isPatch?: boolean
|
|
): {
|
|
start: calendar_v3.Schema$EventDateTime;
|
|
end: calendar_v3.Schema$EventDateTime;
|
|
} {
|
|
if (isAllDay) {
|
|
const startPart = startDateTime.split('T')[0];
|
|
const endPart = endDateTime.split('T')[0];
|
|
|
|
const startDay = dayjs(startPart);
|
|
const endDay = dayjs(endPart);
|
|
|
|
if (!startDay.isValid() || !endDay.isValid()) {
|
|
throw new Error('Format tanggal mulai atau selesai tidak valid.');
|
|
}
|
|
|
|
if (endDay.isBefore(startDay, 'day')) {
|
|
throw new Error('Tanggal selesai tidak boleh sebelum tanggal mulai.');
|
|
}
|
|
|
|
const startDateFormatted = startDay.format('YYYY-MM-DD');
|
|
// Google Calendar API requires exclusive end.date (+1 day from inclusive end date)
|
|
const exclusiveEndDate = endDay.add(1, 'day').format('YYYY-MM-DD');
|
|
|
|
if (isPatch) {
|
|
return {
|
|
start: { date: startDateFormatted, dateTime: null as unknown as string },
|
|
end: { date: exclusiveEndDate, dateTime: null as unknown as string },
|
|
};
|
|
}
|
|
|
|
return {
|
|
start: { date: startDateFormatted },
|
|
end: { date: exclusiveEndDate },
|
|
};
|
|
}
|
|
|
|
const startObj = new Date(startDateTime);
|
|
const endObj = new Date(endDateTime);
|
|
|
|
if (isNaN(startObj.getTime()) || isNaN(endObj.getTime())) {
|
|
throw new Error('Format waktu mulai atau selesai tidak valid.');
|
|
}
|
|
|
|
if (endObj.getTime() <= startObj.getTime()) {
|
|
throw new Error('Waktu selesai harus lebih akhir dari waktu mulai.');
|
|
}
|
|
|
|
if (isPatch) {
|
|
return {
|
|
start: {
|
|
date: null as unknown as string,
|
|
dateTime: startObj.toISOString(),
|
|
timeZone: TIME_ZONE,
|
|
},
|
|
end: {
|
|
date: null as unknown as string,
|
|
dateTime: endObj.toISOString(),
|
|
timeZone: TIME_ZONE,
|
|
},
|
|
};
|
|
}
|
|
|
|
return {
|
|
start: {
|
|
dateTime: startObj.toISOString(),
|
|
timeZone: TIME_ZONE,
|
|
},
|
|
end: {
|
|
dateTime: endObj.toISOString(),
|
|
timeZone: TIME_ZONE,
|
|
},
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Fetch list of Google Calendar events (excluding Task events).
|
|
*/
|
|
export async function getCalendarEvents(params?: {
|
|
timeMin?: string;
|
|
timeMax?: string;
|
|
maxResults?: number;
|
|
}): Promise<CalendarActionResponse<CalendarEventItem[]>> {
|
|
try {
|
|
const { calendar, calendarId } = getGoogleCalendarClient();
|
|
|
|
const response = await calendar.events.list({
|
|
calendarId,
|
|
timeMin: params?.timeMin || new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString(),
|
|
timeMax: params?.timeMax,
|
|
maxResults: params?.maxResults || 100,
|
|
singleEvents: true,
|
|
orderBy: 'startTime',
|
|
});
|
|
|
|
const items = response.data.items || [];
|
|
|
|
const regularEvents: CalendarEventItem[] = items
|
|
.filter((item) => {
|
|
const isTaskType = item.extendedProperties?.private?.type === 'task';
|
|
const hasTaskPrefix = (item.summary || '').startsWith('[TASK');
|
|
return !isTaskType && !hasTaskPrefix;
|
|
})
|
|
.map(mapGoogleEventToItem);
|
|
|
|
return {
|
|
success: true,
|
|
data: regularEvents,
|
|
};
|
|
} catch (error: unknown) {
|
|
console.error('[GOOGLE_CALENDAR] getCalendarEvents error:', error);
|
|
return {
|
|
success: false,
|
|
error: formatGoogleApiError(error),
|
|
};
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Execute insert or patch with intelligent handling for Service Account limitations
|
|
* regarding conferenceData (Google Meet) and attendees (Domain-Wide Delegation).
|
|
*/
|
|
async function executeEventMutation(
|
|
mode: 'insert' | 'patch',
|
|
calendar: calendar_v3.Calendar,
|
|
calendarId: string,
|
|
eventId: string | undefined,
|
|
requestBody: calendar_v3.Schema$Event,
|
|
options: {
|
|
wantsAutoMeet: boolean;
|
|
manualMeetLink: string;
|
|
hasAttendees: boolean;
|
|
}
|
|
): Promise<{ data: calendar_v3.Schema$Event; warnings: string[] }> {
|
|
const warnings: string[] = [];
|
|
let useConferenceVersion = options.wantsAutoMeet ? 1 : undefined;
|
|
|
|
const performCall = async () => {
|
|
const sendUpdates =
|
|
requestBody.attendees && requestBody.attendees.length > 0 ? 'all' : 'none';
|
|
|
|
if (mode === 'insert') {
|
|
return await calendar.events.insert({
|
|
calendarId,
|
|
conferenceDataVersion: useConferenceVersion,
|
|
sendUpdates,
|
|
requestBody,
|
|
});
|
|
} else {
|
|
return await calendar.events.patch({
|
|
calendarId,
|
|
eventId: eventId!,
|
|
conferenceDataVersion: useConferenceVersion,
|
|
sendUpdates,
|
|
requestBody,
|
|
});
|
|
}
|
|
};
|
|
|
|
// Up to 3 attempts in case both conferenceData and attendees hit Service Account limits
|
|
for (let attempt = 0; attempt < 3; attempt++) {
|
|
try {
|
|
const res = await performCall();
|
|
return { data: res.data, warnings };
|
|
} catch (err: unknown) {
|
|
const msg = err instanceof Error ? err.message : String(err);
|
|
|
|
// 1. Handle conferenceData / Google Meet auto-generation failure
|
|
if (msg.includes('Invalid conference type value') && requestBody.conferenceData) {
|
|
delete requestBody.conferenceData;
|
|
useConferenceVersion = undefined;
|
|
|
|
if (options.manualMeetLink) {
|
|
warnings.push(
|
|
'Kalender/Service Account ini tidak mendukung auto-generate Google Meet ("Invalid conference type value"). Link Google Meet manual telah digunakan.'
|
|
);
|
|
continue;
|
|
} else {
|
|
throw new Error(
|
|
'Pembuatan link Google Meet otomatis gagal ("Invalid conference type value"). Kalender akun Gmail personal dengan Service Account (tanpa Google Workspace Domain-Wide Delegation) tidak mendukung pembuatan ruang Google Meet otomatis. Silakan matikan toggle otomatis atau isi kolom Link Google Meet Manual.'
|
|
);
|
|
}
|
|
}
|
|
|
|
// 2. Handle attendees Domain-Wide Delegation limitation on Service Accounts
|
|
if (msg.includes('Domain-Wide Delegation') && requestBody.attendees) {
|
|
delete requestBody.attendees;
|
|
warnings.push(
|
|
'Service Account tanpa Domain-Wide Delegation tidak dapat mengirim email undangan (RSVP) langsung. Daftar tamu tetap disimpan pada event.'
|
|
);
|
|
continue;
|
|
}
|
|
|
|
throw err;
|
|
}
|
|
}
|
|
|
|
const finalRes = await performCall();
|
|
return { data: finalRes.data, warnings };
|
|
}
|
|
|
|
/**
|
|
* Create a new Google Calendar event.
|
|
*/
|
|
export async function createCalendarEvent(
|
|
payload: CreateEventInput
|
|
): Promise<CalendarActionResponse<CalendarEventItem>> {
|
|
try {
|
|
if (!payload.summary || !payload.summary.trim()) {
|
|
return { success: false, error: 'Judul event (summary) wajib diisi.' };
|
|
}
|
|
if (!payload.startDateTime || !payload.endDateTime) {
|
|
return { success: false, error: 'Waktu mulai dan selesai wajib diisi.' };
|
|
}
|
|
|
|
const { start, end } = buildEventStartAndEnd(
|
|
payload.startDateTime,
|
|
payload.endDateTime,
|
|
payload.isAllDay,
|
|
false
|
|
);
|
|
|
|
const { calendar, calendarId } = getGoogleCalendarClient();
|
|
|
|
const cleanGuests = Array.from(
|
|
new Set((payload.attendees || []).map((e) => e.trim().toLowerCase()).filter(Boolean))
|
|
);
|
|
const rawDescription = payload.description?.trim() || '';
|
|
const manualMeetLink = payload.manualMeetLink?.trim() || '';
|
|
|
|
const requestBody: calendar_v3.Schema$Event = {
|
|
summary: payload.summary.trim(),
|
|
description: buildDescriptionWithFooter(
|
|
rawDescription,
|
|
cleanGuests,
|
|
manualMeetLink
|
|
),
|
|
location: payload.location?.trim() || '',
|
|
start,
|
|
end,
|
|
colorId: payload.colorId || undefined,
|
|
extendedProperties: {
|
|
private: {
|
|
type: 'event',
|
|
source: 'hats-app',
|
|
rawDescription,
|
|
guests: JSON.stringify(cleanGuests),
|
|
meetLink: manualMeetLink,
|
|
},
|
|
},
|
|
};
|
|
|
|
if (cleanGuests.length > 0) {
|
|
requestBody.attendees = cleanGuests.map((email) => ({ email }));
|
|
}
|
|
|
|
if (payload.generateMeet) {
|
|
requestBody.conferenceData = {
|
|
createRequest: {
|
|
requestId: `hats-meet-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`,
|
|
conferenceSolutionKey: {
|
|
type: 'hangoutsMeet',
|
|
},
|
|
},
|
|
};
|
|
}
|
|
|
|
const { data: item, warnings } = await executeEventMutation(
|
|
'insert',
|
|
calendar,
|
|
calendarId,
|
|
undefined,
|
|
requestBody,
|
|
{
|
|
wantsAutoMeet: Boolean(payload.generateMeet),
|
|
manualMeetLink,
|
|
hasAttendees: cleanGuests.length > 0,
|
|
}
|
|
);
|
|
|
|
revalidatePath('/integrated-calendar');
|
|
|
|
return {
|
|
success: true,
|
|
data: mapGoogleEventToItem(item),
|
|
warning: warnings.length > 0 ? warnings.join(' ') : undefined,
|
|
};
|
|
} catch (error: unknown) {
|
|
console.error('[GOOGLE_CALENDAR] createCalendarEvent error:', error);
|
|
return {
|
|
success: false,
|
|
error: formatGoogleApiError(error),
|
|
};
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Update an existing Google Calendar event.
|
|
*/
|
|
export async function updateCalendarEvent(
|
|
id: string,
|
|
payload: UpdateEventInput
|
|
): Promise<CalendarActionResponse<CalendarEventItem>> {
|
|
try {
|
|
if (!id) {
|
|
return { success: false, error: 'ID event diperlukan.' };
|
|
}
|
|
|
|
const { calendar, calendarId } = getGoogleCalendarClient();
|
|
|
|
const cleanGuests = Array.from(
|
|
new Set(
|
|
(payload.attendees || [])
|
|
.map((e) => e.trim().toLowerCase())
|
|
.filter(Boolean)
|
|
)
|
|
);
|
|
const rawDescription = payload.description?.trim() ?? '';
|
|
const manualMeetLink = payload.manualMeetLink?.trim() ?? '';
|
|
|
|
const requestBody: calendar_v3.Schema$Event = {
|
|
extendedProperties: {
|
|
private: {
|
|
type: 'event',
|
|
source: 'hats-app',
|
|
rawDescription,
|
|
guests: JSON.stringify(cleanGuests),
|
|
meetLink: manualMeetLink,
|
|
},
|
|
},
|
|
};
|
|
|
|
if (payload.summary !== undefined) {
|
|
requestBody.summary = payload.summary.trim();
|
|
}
|
|
if (payload.description !== undefined || payload.attendees !== undefined || payload.manualMeetLink !== undefined) {
|
|
requestBody.description = buildDescriptionWithFooter(
|
|
rawDescription,
|
|
cleanGuests,
|
|
manualMeetLink
|
|
);
|
|
}
|
|
if (payload.location !== undefined) {
|
|
requestBody.location = payload.location.trim();
|
|
}
|
|
if (payload.colorId !== undefined) {
|
|
requestBody.colorId = payload.colorId || (null as unknown as string);
|
|
}
|
|
|
|
if (payload.startDateTime && payload.endDateTime) {
|
|
const { start, end } = buildEventStartAndEnd(
|
|
payload.startDateTime,
|
|
payload.endDateTime,
|
|
payload.isAllDay,
|
|
true
|
|
);
|
|
requestBody.start = start;
|
|
requestBody.end = end;
|
|
}
|
|
|
|
if (payload.attendees !== undefined) {
|
|
requestBody.attendees = cleanGuests.map((email) => ({ email }));
|
|
}
|
|
|
|
if (payload.generateMeet) {
|
|
requestBody.conferenceData = {
|
|
createRequest: {
|
|
requestId: `hats-meet-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`,
|
|
conferenceSolutionKey: {
|
|
type: 'hangoutsMeet',
|
|
},
|
|
},
|
|
};
|
|
}
|
|
|
|
const { data: item, warnings } = await executeEventMutation(
|
|
'patch',
|
|
calendar,
|
|
calendarId,
|
|
id,
|
|
requestBody,
|
|
{
|
|
wantsAutoMeet: Boolean(payload.generateMeet),
|
|
manualMeetLink,
|
|
hasAttendees: cleanGuests.length > 0,
|
|
}
|
|
);
|
|
|
|
revalidatePath('/integrated-calendar');
|
|
|
|
return {
|
|
success: true,
|
|
data: mapGoogleEventToItem(item),
|
|
warning: warnings.length > 0 ? warnings.join(' ') : undefined,
|
|
};
|
|
} catch (error: unknown) {
|
|
console.error('[GOOGLE_CALENDAR] updateCalendarEvent error:', error);
|
|
return {
|
|
success: false,
|
|
error: formatGoogleApiError(error),
|
|
};
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Delete a Google Calendar event.
|
|
*/
|
|
export async function deleteCalendarEvent(
|
|
id: string
|
|
): Promise<CalendarActionResponse<{ id: string }>> {
|
|
try {
|
|
if (!id) {
|
|
return { success: false, error: 'ID event diperlukan.' };
|
|
}
|
|
|
|
const { calendar, calendarId } = getGoogleCalendarClient();
|
|
|
|
await calendar.events.delete({
|
|
calendarId,
|
|
eventId: id,
|
|
sendUpdates: 'all',
|
|
});
|
|
|
|
revalidatePath('/integrated-calendar');
|
|
|
|
return {
|
|
success: true,
|
|
data: { id },
|
|
};
|
|
} catch (error: unknown) {
|
|
console.error('[GOOGLE_CALENDAR] deleteCalendarEvent error:', error);
|
|
return {
|
|
success: false,
|
|
error: formatGoogleApiError(error),
|
|
};
|
|
}
|
|
}
|