diff --git a/app/(dashboard)/integrated-calendar/components/CalendarHeader.tsx b/app/(dashboard)/integrated-calendar/components/CalendarHeader.tsx index 046f6ce..14d3b1e 100644 --- a/app/(dashboard)/integrated-calendar/components/CalendarHeader.tsx +++ b/app/(dashboard)/integrated-calendar/components/CalendarHeader.tsx @@ -9,7 +9,7 @@ interface CalendarHeaderProps { serviceAccountEmail?: string; onRefresh: () => void; onAddEvent: () => void; - onAddTask: () => void; + onAddTask?: () => void; isRefreshing?: boolean; } @@ -85,15 +85,17 @@ export default function CalendarHeader({ - + {onAddTask && ( + + )} +
+ {/* Google Calendar Style Toolbar */} +
+ - + - + -
+
- + - + -
+
- + - -
+ +
- {/* Editable Content Area */} -
- {isEmpty && ( -
- {placeholder} -
- )} + {/* Editable Content Area */} +
+ {isEmpty && ( +
+ {placeholder} +
+ )} -
-
-
+
+
+
- {/* Google Calendar Floating Link Action Pill (when cursor is inside a link) */} - {hasActiveAnchor && !linkDialogOpen && ( -
- - {activeAnchorHref} - - -
- - -
- )} + {/* Google Calendar Floating Link Action Pill (when cursor is inside a link) */} + {hasActiveAnchor && !linkDialogOpen && ( +
+ + {activeAnchorHref} + + +
+ + +
+ )} - {/* Google Calendar "Edit link" Modal Overlay */} - {linkDialogOpen && ( -
-

- Edit link -

+ {/* Google Calendar "Edit link" Modal Overlay */} + {linkDialogOpen && ( +
+

+ Edit link +

-
- {/* Text to display */} -
- - setLinkText(e.target.value)} - onKeyDown={(e) => { - if (e.key === 'Enter') { - e.preventDefault(); - handleApplyLink(); - } else if (e.key === 'Escape') { - setLinkDialogOpen(false); - } - }} - placeholder="Text to display" - className="flex-1 h-9 px-3 rounded-md text-xs sm:text-sm bg-zinc-100 dark:bg-zinc-800 border-b-2 border-transparent focus:border-sky-500 text-zinc-900 dark:text-zinc-100 outline-none transition-colors" - /> -
+
+ {/* Text to display */} +
+ + setLinkText(e.target.value)} + onKeyDown={(e) => { + if (e.key === 'Enter') { + e.preventDefault(); + handleApplyLink(); + } else if (e.key === 'Escape') { + setLinkDialogOpen(false); + } + }} + placeholder="Text to display" + className="flex-1 h-9 px-3 rounded-md text-xs sm:text-sm bg-zinc-100 dark:bg-zinc-800 border-b-2 border-transparent focus:border-sky-500 text-zinc-900 dark:text-zinc-100 outline-none transition-colors" + /> +
- {/* Link to url address */} -
- - setLinkUrl(e.target.value)} - onKeyDown={(e) => { - if (e.key === 'Enter') { - e.preventDefault(); - handleApplyLink(); - } else if (e.key === 'Escape') { - setLinkDialogOpen(false); - } - }} - placeholder="Link to url address" - autoFocus - className="flex-1 h-9 px-3 rounded-md text-xs sm:text-sm bg-zinc-100 dark:bg-zinc-800 border-b-2 border-sky-500 text-zinc-900 dark:text-zinc-100 outline-none transition-colors" - /> -
-
+ {/* Link to url address */} +
+ + setLinkUrl(e.target.value)} + onKeyDown={(e) => { + if (e.key === 'Enter') { + e.preventDefault(); + handleApplyLink(); + } else if (e.key === 'Escape') { + setLinkDialogOpen(false); + } + }} + placeholder="Link to url address" + autoFocus + className="flex-1 h-9 px-3 rounded-md text-xs sm:text-sm bg-zinc-100 dark:bg-zinc-800 border-b-2 border-sky-500 text-zinc-900 dark:text-zinc-100 outline-none transition-colors" + /> +
+
-
- - -
-
- )} -
- ); +
+ + +
+
+ )} +
+ ); } diff --git a/app/(dashboard)/integrated-calendar/components/EventDetailModal.tsx b/app/(dashboard)/integrated-calendar/components/EventDetailModal.tsx new file mode 100644 index 0000000..2c2565b --- /dev/null +++ b/app/(dashboard)/integrated-calendar/components/EventDetailModal.tsx @@ -0,0 +1,298 @@ +'use client'; + +import React from 'react'; +import { + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogDescription, + DialogFooter, +} from '@/components/ui/dialog'; +import { Button } from '@/components/ui/button'; +import { Badge } from '@/components/ui/badge'; +import { CalendarEventItem } from '@/lib/google-calendar/types'; +import { getEventColorInfo } from '@/lib/google-calendar/constants'; +import { + Calendar, + Clock, + MapPin, + Users, + Video, + Edit2, + Trash2, + ExternalLink, + AlignLeft, + Lock, +} from 'lucide-react'; +import dayjs from 'dayjs'; + +interface EventDetailModalProps { + open: boolean; + onOpenChange: (open: boolean) => void; + event: CalendarEventItem | null; + onEdit: (event: CalendarEventItem) => void; + onDelete: (event: CalendarEventItem) => void; +} + +export default function EventDetailModal({ + open, + onOpenChange, + event, + onEdit, + onDelete, +}: EventDetailModalProps) { + if (!event) return null; + + const colorInfo = getEventColorInfo(event.colorId); + const displayHex = colorInfo?.hex || event.calendarColor || '#039be5'; + const guestList = event.attendees || []; + + const formatDateRange = (startStr: string, endStr: string, isAllDay: boolean) => { + if (!startStr) return '-'; + if (isAllDay) { + const s = dayjs(startStr).format('dddd, DD MMMM YYYY'); + const e = + endStr && endStr !== startStr + ? ` – ${dayjs(endStr).format('dddd, DD MMMM YYYY')}` + : ''; + return `${s}${e}`; + } + const s = dayjs(startStr).format('dddd, DD MMMM YYYY • HH:mm'); + const sameDay = dayjs(startStr).isSame(dayjs(endStr), 'day'); + const e = endStr + ? sameDay + ? dayjs(endStr).format('HH:mm') + : dayjs(endStr).format('dddd, DD MMMM YYYY • HH:mm') + : ''; + return `${s} – ${e} WIB`; + }; + + return ( + + + {/* Top Colored Strip */} +
+ + +
+ +
+ + {event.summary} + + + + {formatDateRange(event.start, event.end, event.isAllDay)} + + +
+ {event.isAllDay && ( + + Sepanjang Hari (All-Day) + + )} + {colorInfo && ( + +
+ {colorInfo.name} + + )} + {event.isReadOnly && ( + + + Read-only + + )} +
+
+
+ + + {/* Event Details Body */} +
+ {/* Google Meet Button */} + {event.hangoutLink && ( +
+
+
+
+
+

+ Rapat Video Google Meet +

+

+ {event.hangoutLink} +

+
+
+ +
+ )} + + {/* Source Calendar */} + {event.calendarSummary && ( +
+ +
+

+ Kalender +

+
+ + + {event.calendarSummary} + +
+
+
+ )} + + {/* Location */} + {event.location && ( +
+ +
+

+ Lokasi +

+

+ {event.location} +

+
+
+ )} + + {/* Guests / Attendees */} + {guestList.length > 0 && ( +
+ +
+

+ {guestList.length} Tamu (Guests) +

+
+ {guestList.map((email) => ( + + {email} + + ))} +
+
+
+ )} + + {/* Rich HTML Description */} + {event.description && ( +
+ +
+

+ Deskripsi +

+
+
+
+ )} +
+ + {/* Footer Actions */} + +
+ {event.htmlLink && ( + + )} +
+ +
+ {!event.isReadOnly && ( + <> + + + + + )} + + {event.isReadOnly && ( + + )} +
+
+ +
+ ); +} diff --git a/app/(dashboard)/integrated-calendar/components/EventFormModal.tsx b/app/(dashboard)/integrated-calendar/components/EventFormModal.tsx index c947c23..e66711e 100644 --- a/app/(dashboard)/integrated-calendar/components/EventFormModal.tsx +++ b/app/(dashboard)/integrated-calendar/components/EventFormModal.tsx @@ -15,51 +15,77 @@ import { Label } from '@/components/ui/label'; import { Switch } from '@/components/ui/switch'; import { Badge } from '@/components/ui/badge'; import DescriptionRichEditor from './DescriptionRichEditor'; -import { CalendarEventItem } from '@/lib/google-calendar/types'; +import { CalendarEventItem, GoogleCalendarListEntry } from '@/lib/google-calendar/types'; import { GOOGLE_EVENT_COLORS, getEventColorInfo } from '@/lib/google-calendar/constants'; import { createCalendarEvent, updateCalendarEvent } from '@/lib/google-calendar/events.actions'; import { toast } from 'sonner'; -import { Loader2, Plus, X, Video, Users, Palette, Check } from 'lucide-react'; +import { Loader2, Plus, X, Video, Users, Palette, Check, Calendar as CalendarIcon } from 'lucide-react'; import dayjs from 'dayjs'; interface EventFormModalProps { open: boolean; onOpenChange: (open: boolean) => void; event?: CalendarEventItem | null; + initialDate?: string | null; // YYYY-MM-DD when clicking empty grid cell + defaultCalendarId?: string; + calendars?: GoogleCalendarListEntry[]; onSuccess: () => void; } interface FormInnerProps { event?: CalendarEventItem | null; + initialDate?: string | null; + defaultCalendarId?: string; + calendars?: GoogleCalendarListEntry[]; onClose: () => void; onSuccess: () => void; } const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; -function EventFormInner({ event, onClose, onSuccess }: FormInnerProps) { +function EventFormInner({ + event, + initialDate, + defaultCalendarId, + calendars = [], + onClose, + onSuccess, +}: FormInnerProps) { const isEdit = Boolean(event); + // Default All-Day Event when creating a new event + const initialIsAllDay = event ? event.isAllDay : true; + const baseDateStr = initialDate || dayjs().format('YYYY-MM-DD'); + const defaultStart = event ? event.isAllDay ? dayjs(event.start).format('YYYY-MM-DD') : dayjs(event.start).format('YYYY-MM-DDTHH:mm') - : dayjs().add(1, 'hour').minute(0).second(0).format('YYYY-MM-DDTHH:mm'); + : baseDateStr; const defaultEnd = event ? event.isAllDay ? dayjs(event.end || event.start).format('YYYY-MM-DD') : dayjs(event.end).format('YYYY-MM-DDTHH:mm') - : dayjs().add(2, 'hour').minute(0).second(0).format('YYYY-MM-DDTHH:mm'); + : baseDateStr; + const writableCalendars = calendars.filter((c) => c.isWritable); + const resolvedDefaultCalId = + event?.calendarId || + defaultCalendarId || + writableCalendars.find((c) => c.isDefaultEnv)?.id || + writableCalendars[0]?.id || + ''; + + const [targetCalendarId, setTargetCalendarId] = useState(resolvedDefaultCalId); const [summary, setSummary] = useState(event?.summary || ''); const [description, setDescription] = useState(event?.description || ''); const [location, setLocation] = useState(event?.location || ''); - const [isAllDay, setIsAllDay] = useState(event?.isAllDay || false); + const [isAllDay, setIsAllDay] = useState(initialIsAllDay); const [startDateTime, setStartDateTime] = useState(defaultStart); const [endDateTime, setEndDateTime] = useState(defaultEnd); - // New fields: colorId, attendees, Google Meet + // Fields: colorId, attendees, Google Meet const [colorId, setColorId] = useState(event?.colorId || ''); const [attendees, setAttendees] = useState(event?.attendees || []); const [guestInput, setGuestInput] = useState(''); @@ -127,7 +153,6 @@ function EventFormInner({ event, onClose, onSuccess }: FormInnerProps) { return; } - // If user typed a valid email in guestInput without clicking "Tambah", include it const finalAttendees = [...attendees]; const pendingGuest = guestInput.trim().toLowerCase(); if (pendingGuest) { @@ -144,6 +169,7 @@ function EventFormInner({ event, onClose, onSuccess }: FormInnerProps) { setLoading(true); const payload = { + calendarId: targetCalendarId || defaultCalendarId || undefined, summary, description, location, @@ -156,10 +182,17 @@ function EventFormInner({ event, onClose, onSuccess }: FormInnerProps) { manualMeetLink: manualMeetLink.trim() || undefined, }; - const res = isEdit && event ? await updateCalendarEvent(event.id, payload) : await createCalendarEvent(payload); + const res = + isEdit && event + ? await updateCalendarEvent(event.id, payload) + : await createCalendarEvent(payload); if (res.success) { - toast.success(isEdit ? 'Event berhasil diperbarui di Google Calendar!' : 'Event berhasil ditambahkan ke Google Calendar!'); + toast.success( + isEdit + ? 'Event berhasil diperbarui di Google Calendar!' + : 'Event berhasil ditambahkan ke Google Calendar!' + ); if (res.warning) { toast.warning(res.warning, { duration: 6000 }); } @@ -188,6 +221,29 @@ function EventFormInner({ event, onClose, onSuccess }: FormInnerProps) {
+ {/* Target Calendar Selector (when multiple writable calendars exist) */} + {writableCalendars.length > 0 && ( +
+ + +
+ )} + {/* Summary */}
@@ -285,14 +342,13 @@ function EventFormInner({ event, onClose, onSuccess }: FormInnerProps) {
- {/* Default / No colorId */} + +
+ + +
+ +

+ {currentMonth.format('MMMM YYYY')} +

+ + {isLoadingMonth && ( +
+ + Menyinkronkan... +
+ )} +
+ + {/* Right: Event Count Summary */} +
+ + + + {visibleEvents.length} + {' '} + agenda ditampilkan + +
+
+ + {/* Integrated Multi-Calendar Filter Pills */} + {calendars.length > 0 && ( +
+
+ {calendars.map((cal) => { + const isChecked = selectedCalendarIds.includes(cal.id); + return ( + + ); + })} +
+ +
+ + • + +
+
+ )} +
+ + {/* Dedicated 7-Column Weekday Header Bar */} +
+ {WEEKDAYS.map((day, idx) => ( +
+ {day.short} +
+ ))} +
+ + {/* Week Rows Grid (Explicit minHeight guarantees tall cells in all browsers) */} +
+ {weekLayouts.map((weekLayout, weekIdx) => { + return ( +
+ {/* 7 Background Day Cells with Clear Vertical Borders */} + {weekLayout.weekDays.map((day, colIdx) => { + const dateStr = day.format('YYYY-MM-DD'); + const isCurrentMonth = day.month() === currentMonth.month(); + const isToday = dateStr === todayStr; + const isSunday = colIdx === 0; + const hiddenCount = weekLayout.hiddenCountPerCol[colIdx]; + + const dateLabel = + day.date() === 1 ? day.format('D MMM') : String(day.date()); + + return ( +
onSelectEmptyDate(dateStr)} + style={{ minHeight: `${ROW_MIN_HEIGHT_PX}px` }} + className={`group relative flex flex-col justify-between p-2 border-r last:border-r-0 border-zinc-200 dark:border-zinc-800 transition-colors cursor-pointer select-none ${ + isCurrentMonth + ? 'bg-white dark:bg-zinc-900 hover:bg-zinc-50/80 dark:hover:bg-zinc-800/50' + : 'bg-zinc-50/70 dark:bg-zinc-950/70 hover:bg-zinc-100/60 dark:hover:bg-zinc-900/60' + }`} + > + {/* Top Row inside Cell: Date Badge & Hover Quick-Add Button */} +
+ + {dateLabel} + + + +
+ + {/* Bottom Row inside Cell: "+X lainnya" overflow pill */} +
+ {hiddenCount > 0 && ( + + )} +
+
+ ); + })} + + {/* Continuous Horizontal Event Lanes Layer */} +
+ {weekLayout.visibleSegments.map((seg) => { + const { + event: ev, + startCol, + span, + lane, + isBar, + continuesBefore, + continuesAfter, + } = seg; + const hex = resolveEventColor(ev); + const leftPercent = (startCol / 7) * 100; + const widthPercent = (span / 7) * 100; + const topPx = lane * LANE_HEIGHT_PX; + + if (isBar) { + const timePrefix = !ev.isAllDay + ? `${formatGCalShortTime(ev.start)} ` + : ''; + + const leftInset = continuesBefore ? 1 : 6; + const rightInset = continuesAfter ? 1 : 6; + + return ( +
+ +
+ ); + } + + // Single-day timed event pill + const shortTime = formatGCalShortTime(ev.start); + + return ( +
+ +
+ ); + })} +
+
+ ); + })} +
+
+ + {/* Dialog for "+X agenda lainnya" (All events on a specific date) */} + { + if (!open) setMoreEventsDate(null); + }} + > + + + + {moreEventsDate ? dayjs(moreEventsDate).format('dddd, DD MMMM YYYY') : ''} + + + Total {moreDateEvents.length} event pada tanggal ini + + + +
+ {moreDateEvents.map((ev) => { + const hex = resolveEventColor(ev); + const timeLabel = ev.isAllDay + ? 'Sepanjang Hari' + : `${dayjs(ev.start).format('HH:mm')} - ${dayjs(ev.end).format('HH:mm')}`; + + return ( + + ); + })} +
+ +
+ + {moreEventsDate && ( + + )} +
+
+
+
+ ); +} diff --git a/app/(dashboard)/integrated-calendar/page.tsx b/app/(dashboard)/integrated-calendar/page.tsx index 74969eb..7f17504 100644 --- a/app/(dashboard)/integrated-calendar/page.tsx +++ b/app/(dashboard)/integrated-calendar/page.tsx @@ -1,41 +1,30 @@ import type { Metadata } from 'next'; -import { getCalendarEvents } from '@/lib/google-calendar/events.actions'; -import { getCalendarTasks, getCalendarSummaryStats } from '@/lib/google-calendar/tasks.actions'; +import { getAllCalendarsEvents } from '@/lib/google-calendar/events.actions'; import IntegratedCalendarClient from './components/IntegratedCalendarClient'; export const metadata: Metadata = { - title: 'Integrated Google Calendar & Task - HIS Attendance Task System (H.A.T.s)', - description: 'Pengujian integrasi langsung Server-to-Server Google Calendar API dan Tasks dengan Service Account.', + title: 'Integrated Google Calendar - HIS Attendance Task System (H.A.T.s)', + description: 'Integrasi Monthly Grid View Google Calendar API (Multi-Calendar OAuth2).', }; export default async function IntegratedCalendarPage() { - // Fetch initial data in parallel on the server - const [eventsRes, tasksRes, statsRes] = await Promise.all([ - getCalendarEvents(), - getCalendarTasks(), - getCalendarSummaryStats(), - ]); + const res = await getAllCalendarsEvents(); - const initialEvents = eventsRes.data || []; - const initialTasks = tasksRes.data || []; + const initialCalendars = res.data?.calendars || []; + const initialEvents = res.data?.events || []; + const defaultCalendarId = + res.data?.defaultCalendarId || process.env.GOOGLE_CALENDAR_ID || 'primary'; + const serviceAccountEmail = + res.data?.serviceAccountEmail || 'OAuth2 System Account'; + const initialError = res.error || null; - const initialStats = statsRes.data || { - totalEvents: initialEvents.length, - totalTasks: initialTasks.length, - completedTasks: initialTasks.filter((t) => t.status === 'completed').length, - pendingTasks: initialTasks.filter((t) => t.status === 'needsAction').length, - calendarId: process.env.GOOGLE_CALENDAR_ID || '', - serviceAccountEmail: process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL || '', - }; - - const initialError = eventsRes.error || tasksRes.error || statsRes.error || null; - - return ( - - ); + return ( + + ); } diff --git a/lib/google-calendar/events.actions.ts b/lib/google-calendar/events.actions.ts index 4f467e3..6036fa9 100644 --- a/lib/google-calendar/events.actions.ts +++ b/lib/google-calendar/events.actions.ts @@ -8,6 +8,8 @@ import { CalendarActionResponse, CalendarEventItem, CreateEventInput, + GoogleCalendarListEntry, + MultiCalendarEventsResult, UpdateEventInput, } from './types'; @@ -38,7 +40,7 @@ function buildDescriptionWithFooter(rawDesc: string, guests: string[], meetLink? return `${clean}${FOOTER_DELIMITER}\n${extraLines.join('\n')}`.trim(); } -function mapGoogleEventToItem(item: calendar_v3.Schema$Event): CalendarEventItem { +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 || ''; @@ -97,18 +99,14 @@ function mapGoogleEventToItem(item: calendar_v3.Schema$Event): CalendarEventItem 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; -} { +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]; @@ -180,19 +178,192 @@ function buildEventStartAndEnd( } /** - * Fetch list of Google Calendar events (excluding Task events). + * Fetch all calendars registered under the authenticated Google account. */ -export async function getCalendarEvents(params?: { - timeMin?: string; - timeMax?: string; - maxResults?: number; -}): Promise> { +export async function getGoogleCalendarList(): Promise> { + 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> { + 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> { 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(), + timeMin: + params?.timeMin || + new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString(), timeMax: params?.timeMax, maxResults: params?.maxResults || 100, singleEvents: true, @@ -207,7 +378,7 @@ export async function getCalendarEvents(params?: { const hasTaskPrefix = (item.summary || '').startsWith('[TASK'); return !isTaskType && !hasTaskPrefix; }) - .map(mapGoogleEventToItem); + .map((item) => mapGoogleEventToItem(item)); return { success: true, @@ -263,7 +434,6 @@ async function executeEventMutation( } }; - // 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(); @@ -271,24 +441,22 @@ async function executeEventMutation( } 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.' + '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"). 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.' + 'Pembuatan link Google Meet otomatis gagal ("Invalid conference type value"). 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( @@ -308,9 +476,7 @@ async function executeEventMutation( /** * Create a new Google Calendar event. */ -export async function createCalendarEvent( - payload: CreateEventInput -): Promise> { +export async function createCalendarEvent(payload: CreateEventInput): Promise> { try { if (!payload.summary || !payload.summary.trim()) { return { success: false, error: 'Judul event (summary) wajib diisi.' }; @@ -326,10 +492,15 @@ export async function createCalendarEvent( false ); - const { calendar, calendarId } = getGoogleCalendarClient(); + 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)) + new Set( + (payload.attendees || []) + .map((e) => e.trim().toLowerCase()) + .filter(Boolean) + ) ); const rawDescription = payload.description?.trim() || ''; const manualMeetLink = payload.manualMeetLink?.trim() || ''; @@ -374,7 +545,7 @@ export async function createCalendarEvent( const { data: item, warnings } = await executeEventMutation( 'insert', calendar, - calendarId, + targetCalendarId, undefined, requestBody, { @@ -388,7 +559,10 @@ export async function createCalendarEvent( return { success: true, - data: mapGoogleEventToItem(item), + data: { + ...mapGoogleEventToItem(item), + calendarId: targetCalendarId, + }, warning: warnings.length > 0 ? warnings.join(' ') : undefined, }; } catch (error: unknown) { @@ -403,16 +577,14 @@ export async function createCalendarEvent( /** * Update an existing Google Calendar event. */ -export async function updateCalendarEvent( - id: string, - payload: UpdateEventInput -): Promise> { +export async function updateCalendarEvent(id: string, payload: UpdateEventInput): Promise> { try { if (!id) { return { success: false, error: 'ID event diperlukan.' }; } - const { calendar, calendarId } = getGoogleCalendarClient(); + const { calendar, calendarId: defaultCalendarId } = getGoogleCalendarClient(); + const targetCalendarId = payload.calendarId?.trim() || defaultCalendarId; const cleanGuests = Array.from( new Set( @@ -439,7 +611,11 @@ export async function updateCalendarEvent( if (payload.summary !== undefined) { requestBody.summary = payload.summary.trim(); } - if (payload.description !== undefined || payload.attendees !== undefined || payload.manualMeetLink !== undefined) { + if ( + payload.description !== undefined || + payload.attendees !== undefined || + payload.manualMeetLink !== undefined + ) { requestBody.description = buildDescriptionWithFooter( rawDescription, cleanGuests, @@ -482,7 +658,7 @@ export async function updateCalendarEvent( const { data: item, warnings } = await executeEventMutation( 'patch', calendar, - calendarId, + targetCalendarId, id, requestBody, { @@ -496,7 +672,10 @@ export async function updateCalendarEvent( return { success: true, - data: mapGoogleEventToItem(item), + data: { + ...mapGoogleEventToItem(item), + calendarId: targetCalendarId, + }, warning: warnings.length > 0 ? warnings.join(' ') : undefined, }; } catch (error: unknown) { @@ -511,18 +690,17 @@ export async function updateCalendarEvent( /** * Delete a Google Calendar event. */ -export async function deleteCalendarEvent( - id: string -): Promise> { +export async function deleteCalendarEvent(id: string, targetCalendarId?: string): Promise> { try { if (!id) { return { success: false, error: 'ID event diperlukan.' }; } - const { calendar, calendarId } = getGoogleCalendarClient(); + const { calendar, calendarId: defaultCalendarId } = getGoogleCalendarClient(); + const resolvedCalendarId = targetCalendarId?.trim() || defaultCalendarId; await calendar.events.delete({ - calendarId, + calendarId: resolvedCalendarId, eventId: id, sendUpdates: 'all', }); diff --git a/lib/google-calendar/types.ts b/lib/google-calendar/types.ts index dddff7b..e213f74 100644 --- a/lib/google-calendar/types.ts +++ b/lib/google-calendar/types.ts @@ -5,6 +5,18 @@ export interface CalendarActionResponse { warning?: string; } +export interface GoogleCalendarListEntry { + id: string; + summary: string; + description?: string; + backgroundColor: string; + foregroundColor: string; + primary?: boolean; + accessRole: string; + isWritable: boolean; + isDefaultEnv?: boolean; +} + export interface CalendarEventItem { id: string; summary: string; @@ -20,9 +32,22 @@ export interface CalendarEventItem { creatorEmail?: string; createdAt?: string; updatedAt?: string; + // Multi-calendar metadata + calendarId?: string; + calendarSummary?: string; + calendarColor?: string; + isReadOnly?: boolean; +} + +export interface MultiCalendarEventsResult { + calendars: GoogleCalendarListEntry[]; + events: CalendarEventItem[]; + defaultCalendarId: string; + serviceAccountEmail: string; } export interface CreateEventInput { + calendarId?: string; summary: string; description?: string; location?: string; @@ -36,6 +61,7 @@ export interface CreateEventInput { } export interface UpdateEventInput { + calendarId?: string; summary?: string; description?: string; location?: string;