mirror of
https://github.com/ichsankurnia/hats-app.git
synced 2026-12-05 10:46:29 +00:00
cf9e36f10a
Add calendar authentication and event/task actions, plus rich-description styling and setup documentation.
363 lines
9.7 KiB
TypeScript
363 lines
9.7 KiB
TypeScript
'use server';
|
|
|
|
import { revalidatePath } from 'next/cache';
|
|
import { calendar_v3 } from 'googleapis';
|
|
import dayjs from 'dayjs';
|
|
import { getGoogleCalendarClient, formatGoogleApiError } from './auth';
|
|
import { getCalendarEvents } from './events.actions';
|
|
import {
|
|
CalendarActionResponse,
|
|
CalendarTaskItem,
|
|
CreateTaskInput,
|
|
TaskStatus,
|
|
UpdateTaskInput,
|
|
CalendarSummaryStats,
|
|
} from './types';
|
|
|
|
const TIME_ZONE = 'Asia/Jakarta';
|
|
|
|
// Helpers to extract clean task title from event summary
|
|
function formatTaskSummary(title: string, status: TaskStatus): string {
|
|
const cleanTitle = title
|
|
.replace(/^\[TASK:DONE\]\s*/i, '')
|
|
.replace(/^\[TASK\]\s*/i, '')
|
|
.trim();
|
|
|
|
return status === 'completed'
|
|
? `[TASK:DONE] ${cleanTitle}`
|
|
: `[TASK] ${cleanTitle}`;
|
|
}
|
|
|
|
function extractTaskTitle(summary: string): string {
|
|
return summary
|
|
.replace(/^\[TASK:DONE\]\s*/i, '')
|
|
.replace(/^\[TASK\]\s*/i, '')
|
|
.trim() || summary;
|
|
}
|
|
|
|
/**
|
|
* Fetch all task events from Google Calendar.
|
|
*/
|
|
export async function getCalendarTasks(params?: { timeMin?: string; timeMax?: string; }): Promise<CalendarActionResponse<CalendarTaskItem[]>> {
|
|
try {
|
|
const { calendar, calendarId } = getGoogleCalendarClient();
|
|
|
|
const response = await calendar.events.list({
|
|
calendarId,
|
|
timeMin: params?.timeMin || new Date(Date.now() - 60 * 24 * 60 * 60 * 1000).toISOString(), // 60 days
|
|
timeMax: params?.timeMax,
|
|
maxResults: 250,
|
|
singleEvents: true,
|
|
orderBy: 'startTime',
|
|
});
|
|
|
|
const items = response.data.items || [];
|
|
|
|
// Filter items that are tasks (either by extendedProperties or prefix)
|
|
const taskItems: CalendarTaskItem[] = items
|
|
.filter((item) => {
|
|
const isTaskType = item.extendedProperties?.private?.type === 'task';
|
|
const hasTaskPrefix = (item.summary || '').startsWith('[TASK');
|
|
return isTaskType || hasTaskPrefix;
|
|
})
|
|
.map((item) => {
|
|
const privateProps = item.extendedProperties?.private || {};
|
|
let status: TaskStatus = 'needsAction';
|
|
|
|
if (privateProps.status === 'completed' || (item.summary || '').startsWith('[TASK:DONE]')) {
|
|
status = 'completed';
|
|
}
|
|
|
|
const dueStr = item.start?.dateTime || item.start?.date || '';
|
|
const title = privateProps.title || extractTaskTitle(item.summary || '');
|
|
|
|
return {
|
|
id: item.id || '',
|
|
title,
|
|
description: item.description || '',
|
|
due: dueStr,
|
|
status,
|
|
completedAt: privateProps.completedAt,
|
|
htmlLink: item.htmlLink || '',
|
|
createdAt: item.created || '',
|
|
updatedAt: item.updated || '',
|
|
};
|
|
});
|
|
|
|
return {
|
|
success: true,
|
|
data: taskItems,
|
|
};
|
|
} catch (error: unknown) {
|
|
console.error('[GOOGLE_CALENDAR] getCalendarTasks error:', error);
|
|
return {
|
|
success: false,
|
|
error: formatGoogleApiError(error),
|
|
};
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Create a new task event in Google Calendar.
|
|
*/
|
|
export async function createCalendarTask(
|
|
payload: CreateTaskInput
|
|
): Promise<CalendarActionResponse<CalendarTaskItem>> {
|
|
try {
|
|
if (!payload.title || !payload.title.trim()) {
|
|
return { success: false, error: 'Judul task wajib diisi.' };
|
|
}
|
|
if (!payload.due) {
|
|
return { success: false, error: 'Tenggat waktu (due date) wajib diisi.' };
|
|
}
|
|
|
|
const { calendar, calendarId } = getGoogleCalendarClient();
|
|
const status: TaskStatus = payload.status || 'needsAction';
|
|
const summary = formatTaskSummary(payload.title, status);
|
|
|
|
// Format start & end: 1 hour window or date
|
|
const isDateOnly = !payload.due.includes('T');
|
|
let start: calendar_v3.Schema$EventDateTime;
|
|
let end: calendar_v3.Schema$EventDateTime;
|
|
|
|
if (isDateOnly) {
|
|
const startDay = dayjs(payload.due).format('YYYY-MM-DD');
|
|
const endDay = dayjs(payload.due).add(1, 'day').format('YYYY-MM-DD');
|
|
start = { date: startDay };
|
|
end = { date: endDay };
|
|
} else {
|
|
const startDate = new Date(payload.due);
|
|
const endDate = new Date(startDate.getTime() + 60 * 60 * 1000); // +1 hour
|
|
start = { dateTime: startDate.toISOString(), timeZone: TIME_ZONE };
|
|
end = { dateTime: endDate.toISOString(), timeZone: TIME_ZONE };
|
|
}
|
|
|
|
const colorId = status === 'completed' ? '10' : '11'; // 10 = Basil (green), 11 = Tomato (red)
|
|
|
|
const res = await calendar.events.insert({
|
|
calendarId,
|
|
requestBody: {
|
|
summary,
|
|
description: payload.description?.trim() || '',
|
|
start,
|
|
end,
|
|
colorId,
|
|
extendedProperties: {
|
|
private: {
|
|
type: 'task',
|
|
status,
|
|
title: payload.title.trim(),
|
|
completedAt: status === 'completed' ? new Date().toISOString() : '',
|
|
source: 'hats-app',
|
|
},
|
|
},
|
|
},
|
|
});
|
|
|
|
const item = res.data;
|
|
revalidatePath('/integrated-calendar');
|
|
|
|
return {
|
|
success: true,
|
|
data: {
|
|
id: item.id || '',
|
|
title: payload.title.trim(),
|
|
description: item.description || '',
|
|
due: item.start?.dateTime || item.start?.date || '',
|
|
status,
|
|
completedAt: status === 'completed' ? new Date().toISOString() : undefined,
|
|
htmlLink: item.htmlLink || '',
|
|
createdAt: item.created || '',
|
|
updatedAt: item.updated || '',
|
|
},
|
|
};
|
|
} catch (error: unknown) {
|
|
console.error('[GOOGLE_CALENDAR] createCalendarTask error:', error);
|
|
return {
|
|
success: false,
|
|
error: formatGoogleApiError(error),
|
|
};
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Update an existing task event in Google Calendar.
|
|
*/
|
|
export async function updateCalendarTask(
|
|
id: string,
|
|
payload: UpdateTaskInput
|
|
): Promise<CalendarActionResponse<CalendarTaskItem>> {
|
|
try {
|
|
if (!id) {
|
|
return { success: false, error: 'ID task diperlukan.' };
|
|
}
|
|
|
|
const { calendar, calendarId } = getGoogleCalendarClient();
|
|
|
|
// Fetch existing event first to preserve title/status
|
|
const existing = await calendar.events.get({
|
|
calendarId,
|
|
eventId: id,
|
|
});
|
|
|
|
const prevProps = existing.data.extendedProperties?.private || {};
|
|
const newTitle = payload.title !== undefined ? payload.title.trim() : prevProps.title || extractTaskTitle(existing.data.summary || '');
|
|
const newStatus: TaskStatus = payload.status !== undefined ? payload.status : (prevProps.status as TaskStatus) || 'needsAction';
|
|
|
|
const summary = formatTaskSummary(newTitle, newStatus);
|
|
const colorId = newStatus === 'completed' ? '10' : '11';
|
|
|
|
const requestBody: calendar_v3.Schema$Event = {
|
|
summary,
|
|
colorId,
|
|
extendedProperties: {
|
|
private: {
|
|
...prevProps,
|
|
type: 'task',
|
|
status: newStatus,
|
|
title: newTitle,
|
|
completedAt: newStatus === 'completed' ? (prevProps.completedAt || new Date().toISOString()) : '',
|
|
},
|
|
},
|
|
};
|
|
|
|
if (payload.description !== undefined) {
|
|
requestBody.description = payload.description.trim();
|
|
}
|
|
|
|
if (payload.due) {
|
|
const isDateOnly = !payload.due.includes('T');
|
|
if (isDateOnly) {
|
|
const startDay = dayjs(payload.due).format('YYYY-MM-DD');
|
|
const endDay = dayjs(payload.due).add(1, 'day').format('YYYY-MM-DD');
|
|
requestBody.start = { date: startDay, dateTime: null as unknown as string };
|
|
requestBody.end = { date: endDay, dateTime: null as unknown as string };
|
|
} else {
|
|
const startDate = new Date(payload.due);
|
|
const endDate = new Date(startDate.getTime() + 60 * 60 * 1000);
|
|
requestBody.start = {
|
|
date: null as unknown as string,
|
|
dateTime: startDate.toISOString(),
|
|
timeZone: TIME_ZONE,
|
|
};
|
|
requestBody.end = {
|
|
date: null as unknown as string,
|
|
dateTime: endDate.toISOString(),
|
|
timeZone: TIME_ZONE,
|
|
};
|
|
}
|
|
}
|
|
|
|
const res = await calendar.events.patch({
|
|
calendarId,
|
|
eventId: id,
|
|
requestBody,
|
|
});
|
|
|
|
const item = res.data;
|
|
revalidatePath('/integrated-calendar');
|
|
|
|
return {
|
|
success: true,
|
|
data: {
|
|
id: item.id || '',
|
|
title: newTitle,
|
|
description: item.description || '',
|
|
due: item.start?.dateTime || item.start?.date || '',
|
|
status: newStatus,
|
|
completedAt: newStatus === 'completed' ? new Date().toISOString() : undefined,
|
|
htmlLink: item.htmlLink || '',
|
|
createdAt: item.created || '',
|
|
updatedAt: item.updated || '',
|
|
},
|
|
};
|
|
} catch (error: unknown) {
|
|
console.error('[GOOGLE_CALENDAR] updateCalendarTask error:', error);
|
|
return {
|
|
success: false,
|
|
error: formatGoogleApiError(error),
|
|
};
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Toggle task completion status (needsAction <-> completed).
|
|
*/
|
|
export async function toggleCalendarTaskStatus(
|
|
id: string,
|
|
newStatus: TaskStatus
|
|
): Promise<CalendarActionResponse<CalendarTaskItem>> {
|
|
return updateCalendarTask(id, { status: newStatus });
|
|
}
|
|
|
|
/**
|
|
* Delete a task event in Google Calendar.
|
|
*/
|
|
export async function deleteCalendarTask(
|
|
id: string
|
|
): Promise<CalendarActionResponse<{ id: string }>> {
|
|
try {
|
|
if (!id) {
|
|
return { success: false, error: 'ID task diperlukan.' };
|
|
}
|
|
|
|
const { calendar, calendarId } = getGoogleCalendarClient();
|
|
|
|
await calendar.events.delete({
|
|
calendarId,
|
|
eventId: id,
|
|
});
|
|
|
|
revalidatePath('/integrated-calendar');
|
|
|
|
return {
|
|
success: true,
|
|
data: { id },
|
|
};
|
|
} catch (error: unknown) {
|
|
console.error('[GOOGLE_CALENDAR] deleteCalendarTask error:', error);
|
|
return {
|
|
success: false,
|
|
error: formatGoogleApiError(error),
|
|
};
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get overall summary stats for Events and Tasks.
|
|
*/
|
|
export async function getCalendarSummaryStats(): Promise<
|
|
CalendarActionResponse<CalendarSummaryStats>
|
|
> {
|
|
try {
|
|
const { calendarId, serviceAccountEmail } = getGoogleCalendarClient();
|
|
const [eventsRes, tasksRes] = await Promise.all([
|
|
getCalendarEvents(),
|
|
getCalendarTasks(),
|
|
]);
|
|
|
|
const events = eventsRes.data || [];
|
|
const tasks = tasksRes.data || [];
|
|
|
|
const completedTasks = tasks.filter((t: CalendarTaskItem) => t.status === 'completed').length;
|
|
const pendingTasks = tasks.filter((t: CalendarTaskItem) => t.status === 'needsAction').length;
|
|
|
|
return {
|
|
success: true,
|
|
data: {
|
|
totalEvents: events.length,
|
|
totalTasks: tasks.length,
|
|
completedTasks,
|
|
pendingTasks,
|
|
calendarId,
|
|
serviceAccountEmail,
|
|
},
|
|
};
|
|
} catch (error: unknown) {
|
|
return {
|
|
success: false,
|
|
error: formatGoogleApiError(error),
|
|
};
|
|
}
|
|
}
|