Add multi-calendar monthly grid view

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.
This commit is contained in:
Ichsan Kurniawan
2026-11-18 18:17:26 +07:00
parent 99a6849e17
commit c9dc6a5e51
10 changed files with 1995 additions and 793 deletions
+221 -43
View File
@@ -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<CalendarActionResponse<CalendarEventItem[]>> {
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(),
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<CalendarActionResponse<CalendarEventItem>> {
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.' };
@@ -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<CalendarActionResponse<CalendarEventItem>> {
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 { 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<CalendarActionResponse<{ id: string }>> {
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 } = getGoogleCalendarClient();
const { calendar, calendarId: defaultCalendarId } = getGoogleCalendarClient();
const resolvedCalendarId = targetCalendarId?.trim() || defaultCalendarId;
await calendar.events.delete({
calendarId,
calendarId: resolvedCalendarId,
eventId: id,
sendUpdates: 'all',
});
+26
View File
@@ -5,6 +5,18 @@ export interface CalendarActionResponse<T = unknown> {
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;