mirror of
https://github.com/ichsankurnia/hats-app.git
synced 2026-12-05 11:06:29 +00:00
c9dc6a5e51
Replace the event and task lists with a monthly calendar grid, calendar filters, and event detail view. Add multi-calendar event fetching and route create, edit, and delete actions to the selected calendar.
722 lines
20 KiB
TypeScript
722 lines
20 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,
|
|
GoogleCalendarListEntry,
|
|
MultiCalendarEventsResult,
|
|
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, calMeta?: GoogleCalendarListEntry): 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 || '',
|
|
calendarId: calMeta?.id,
|
|
calendarSummary: calMeta?.summary,
|
|
calendarColor: calMeta?.backgroundColor,
|
|
isReadOnly: calMeta ? !calMeta.isWritable : false,
|
|
};
|
|
}
|
|
|
|
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 all calendars registered under the authenticated Google account.
|
|
*/
|
|
export async function getGoogleCalendarList(): Promise<CalendarActionResponse<GoogleCalendarListEntry[]>> {
|
|
try {
|
|
const { calendar, calendarId: defaultCalendarId } = getGoogleCalendarClient();
|
|
|
|
const res = await calendar.calendarList.list({
|
|
showHidden: false,
|
|
showDeleted: false,
|
|
});
|
|
|
|
const entries = res.data.items || [];
|
|
|
|
const mapped: GoogleCalendarListEntry[] = entries
|
|
.filter((entry) => Boolean(entry.id))
|
|
.map((entry) => {
|
|
const id = entry.id || '';
|
|
const accessRole = entry.accessRole || 'reader';
|
|
const isWritable = accessRole === 'owner' || accessRole === 'writer';
|
|
const isDefaultEnv =
|
|
id === defaultCalendarId ||
|
|
(defaultCalendarId === 'primary' && Boolean(entry.primary));
|
|
|
|
return {
|
|
id,
|
|
summary: entry.summaryOverride || entry.summary || id,
|
|
description: entry.description || '',
|
|
backgroundColor: entry.backgroundColor || '#039be5',
|
|
foregroundColor: entry.foregroundColor || '#ffffff',
|
|
primary: Boolean(entry.primary),
|
|
accessRole,
|
|
isWritable,
|
|
isDefaultEnv,
|
|
};
|
|
});
|
|
|
|
// Ensure the defaultCalendarId from .env is always in the list even if not subscribed in calendarList
|
|
const hasDefaultInList = mapped.some(
|
|
(c) => c.id === defaultCalendarId || c.isDefaultEnv
|
|
);
|
|
if (!hasDefaultInList && defaultCalendarId) {
|
|
try {
|
|
const singleCal = await calendar.calendars.get({
|
|
calendarId: defaultCalendarId,
|
|
});
|
|
mapped.unshift({
|
|
id: singleCal.data.id || defaultCalendarId,
|
|
summary: singleCal.data.summary || 'Default Calendar (.env)',
|
|
description: singleCal.data.description || '',
|
|
backgroundColor: '#039be5',
|
|
foregroundColor: '#ffffff',
|
|
primary: false,
|
|
accessRole: 'owner',
|
|
isWritable: true,
|
|
isDefaultEnv: true,
|
|
});
|
|
} catch {
|
|
// Ignore if not accessible
|
|
}
|
|
}
|
|
|
|
// Sort: Default (.env) first, then Primary, then Writable, then Read-only
|
|
mapped.sort((a, b) => {
|
|
if (a.isDefaultEnv && !b.isDefaultEnv) return -1;
|
|
if (!a.isDefaultEnv && b.isDefaultEnv) return 1;
|
|
if (a.primary && !b.primary) return -1;
|
|
if (!a.primary && b.primary) return 1;
|
|
if (a.isWritable && !b.isWritable) return -1;
|
|
if (!a.isWritable && b.isWritable) return 1;
|
|
return a.summary.localeCompare(b.summary);
|
|
});
|
|
|
|
return {
|
|
success: true,
|
|
data: mapped,
|
|
};
|
|
} catch (error: unknown) {
|
|
console.error('[GOOGLE_CALENDAR] getGoogleCalendarList error:', error);
|
|
return {
|
|
success: false,
|
|
error: formatGoogleApiError(error),
|
|
};
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Fetch events across ALL calendars in the authenticated Google account in parallel.
|
|
*/
|
|
export async function getAllCalendarsEvents(params?: { timeMin?: string; timeMax?: string; maxResultsPerCalendar?: number; }): Promise<CalendarActionResponse<MultiCalendarEventsResult>> {
|
|
try {
|
|
const {
|
|
calendar,
|
|
calendarId: defaultCalendarId,
|
|
serviceAccountEmail,
|
|
} = getGoogleCalendarClient();
|
|
|
|
const calListRes = await getGoogleCalendarList();
|
|
if (!calListRes.success || !calListRes.data) {
|
|
return {
|
|
success: false,
|
|
error: calListRes.error || 'Gagal memuat daftar kalender.',
|
|
};
|
|
}
|
|
|
|
const calendars = calListRes.data;
|
|
|
|
// Default time range: start of current month - 7 days to end of current month + 14 days
|
|
const defaultTimeMin = dayjs()
|
|
.startOf('month')
|
|
.subtract(7, 'day')
|
|
.toISOString();
|
|
const defaultTimeMax = dayjs()
|
|
.endOf('month')
|
|
.add(14, 'day')
|
|
.toISOString();
|
|
|
|
const timeMin = params?.timeMin || defaultTimeMin;
|
|
const timeMax = params?.timeMax || defaultTimeMax;
|
|
const maxResults = params?.maxResultsPerCalendar || 250;
|
|
|
|
const results = await Promise.allSettled(
|
|
calendars.map(async (calMeta) => {
|
|
const res = await calendar.events.list({
|
|
calendarId: calMeta.id,
|
|
timeMin,
|
|
timeMax,
|
|
maxResults,
|
|
singleEvents: true,
|
|
orderBy: 'startTime',
|
|
});
|
|
|
|
const items = res.data.items || [];
|
|
return items
|
|
.filter((item) => {
|
|
const isTaskType = item.extendedProperties?.private?.type === 'task';
|
|
const hasTaskPrefix = (item.summary || '').startsWith('[TASK');
|
|
return !isTaskType && !hasTaskPrefix;
|
|
})
|
|
.map((item) => mapGoogleEventToItem(item, calMeta));
|
|
})
|
|
);
|
|
|
|
const allEvents: CalendarEventItem[] = [];
|
|
for (const r of results) {
|
|
if (r.status === 'fulfilled' && Array.isArray(r.value)) {
|
|
allEvents.push(...r.value);
|
|
}
|
|
}
|
|
|
|
// Sort chronologically by start date/time
|
|
allEvents.sort((a, b) => {
|
|
const aTime = new Date(a.start).getTime();
|
|
const bTime = new Date(b.start).getTime();
|
|
return aTime - bTime;
|
|
});
|
|
|
|
return {
|
|
success: true,
|
|
data: {
|
|
calendars,
|
|
events: allEvents,
|
|
defaultCalendarId,
|
|
serviceAccountEmail,
|
|
},
|
|
};
|
|
} catch (error: unknown) {
|
|
console.error('[GOOGLE_CALENDAR] getAllCalendarsEvents error:', error);
|
|
return {
|
|
success: false,
|
|
error: formatGoogleApiError(error),
|
|
};
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Fetch list of Google Calendar events (single default calendar fallback).
|
|
*/
|
|
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((item) => mapGoogleEventToItem(item));
|
|
|
|
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,
|
|
});
|
|
}
|
|
};
|
|
|
|
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);
|
|
|
|
if (msg.includes('Invalid conference type value') && requestBody.conferenceData) {
|
|
delete requestBody.conferenceData;
|
|
useConferenceVersion = undefined;
|
|
|
|
if (options.manualMeetLink) {
|
|
warnings.push(
|
|
'Kalender 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"). Silakan matikan toggle otomatis atau isi kolom Link Google Meet Manual.'
|
|
);
|
|
}
|
|
}
|
|
|
|
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: defaultCalendarId } = getGoogleCalendarClient();
|
|
const targetCalendarId = payload.calendarId?.trim() || defaultCalendarId;
|
|
|
|
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,
|
|
targetCalendarId,
|
|
undefined,
|
|
requestBody,
|
|
{
|
|
wantsAutoMeet: Boolean(payload.generateMeet),
|
|
manualMeetLink,
|
|
hasAttendees: cleanGuests.length > 0,
|
|
}
|
|
);
|
|
|
|
revalidatePath('/integrated-calendar');
|
|
|
|
return {
|
|
success: true,
|
|
data: {
|
|
...mapGoogleEventToItem(item),
|
|
calendarId: targetCalendarId,
|
|
},
|
|
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: defaultCalendarId } = getGoogleCalendarClient();
|
|
const targetCalendarId = payload.calendarId?.trim() || defaultCalendarId;
|
|
|
|
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,
|
|
targetCalendarId,
|
|
id,
|
|
requestBody,
|
|
{
|
|
wantsAutoMeet: Boolean(payload.generateMeet),
|
|
manualMeetLink,
|
|
hasAttendees: cleanGuests.length > 0,
|
|
}
|
|
);
|
|
|
|
revalidatePath('/integrated-calendar');
|
|
|
|
return {
|
|
success: true,
|
|
data: {
|
|
...mapGoogleEventToItem(item),
|
|
calendarId: targetCalendarId,
|
|
},
|
|
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, targetCalendarId?: string): Promise<CalendarActionResponse<{ id: string }>> {
|
|
try {
|
|
if (!id) {
|
|
return { success: false, error: 'ID event diperlukan.' };
|
|
}
|
|
|
|
const { calendar, calendarId: defaultCalendarId } = getGoogleCalendarClient();
|
|
const resolvedCalendarId = targetCalendarId?.trim() || defaultCalendarId;
|
|
|
|
await calendar.events.delete({
|
|
calendarId: resolvedCalendarId,
|
|
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),
|
|
};
|
|
}
|
|
}
|