mirror of
https://github.com/ichsankurnia/hats-app.git
synced 2026-12-05 10:56:28 +00:00
Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| faa22e93e0 | |||
| 69a325a376 | |||
| cf9e36f10a | |||
| 123b5853a0 | |||
| bb8ab17909 |
+12
-1
@@ -19,4 +19,15 @@ NEXT_PUBLIC_HATS_SUPPORT_PHONE = "6285214074002"
|
||||
NEXT_PUBLIC_APP_VERSION = "v1.2.0"
|
||||
NEXT_PUBLIC_MANAGER_USER_ID = '2'
|
||||
|
||||
NEXT_PUBLIC_S3_IMAGE_URL = https://cdn.hisnutech.my.id/public
|
||||
NEXT_PUBLIC_S3_IMAGE_URL = https://cdn.hisnutech.my.id/public
|
||||
|
||||
# Google Calendar Service Account Config
|
||||
GOOGLE_SERVICE_ACCOUNT_EMAIL = "hats-calendar@hats-project-515003.iam.gserviceaccount.com"
|
||||
GOOGLE_PRIVATE_KEY = "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC2rZliu4vxv+mw\ng6D1O306tIwq30wzQ3QS8pA4pIsFQbtr/1Ur4EQyOHJGThzf1ndXS07zKN1eVt5O\nKsdbS70JKuwNPi2WgUtrsNURa20xNQMe88nILVFG54l1Wn2eXj5ZEeKfrdVO/zvW\nyhLIf4qGPRrNI8lMNcEo8NuNTvYNqTAfL/5fohOH9TLH0yB+zg3ee4C4tnhYj9OC\ntpN91cIXCtdWoAkr4QKyYejAsAgYz9DWZ/szGEyWClp+6NGOx2Lhkmx/Thcbww9H\nB8du7+02VryPhsl7eEHMcoRNgHsIj/ok2xLf9sBhL0pCxgpRa0lMjMrjw/m+nOzr\n22Zh1MXvAgMBAAECggEACe1mNATgJouY3gRRN3J7rDiKk3veDr0gLjVrXACpI2h+\nkHBoRwGhgx8pKqPtEsb7Zk2L5U/3s7xByXquqcn0ZG6mNFQIMzEkkZ4i/hbZ8L4i\nRMjX0t6Pl6xWfn+j6vrRJZMAv0+5k1jwfgwuOCIiO4hPkA1dT5xuOlTYgZXkbjqH\ne2Yr+WKSXG5fZ3y8X0lqBKirIIG0cT9EvTwBLYoelaYzxphcN23Z7upLqDMq5qPp\nklD50IQmsP9vh+ZWrWxApcCb71hFKk3lfIt+04wciPYJyN2WGSMvYCcKJHmP+QY9\nX+zmu3lFk+ToVmcd85z9PM8zO8GhfiU2o/FCvDjLfQKBgQDmU3UjYUosAU1R5reT\ntJdCOkdQg3zbsnxFrbqxwCGfM9aGDVROQWJ9uiY4iawMF57RNZ1i9NfpV3BhmcdS\nzg6OabTIefYbHkxQwQGP2benVteJLfoO3lKM7v/mfIbxQdFfFzUjjIPJP1S/IpX2\nuEHcB6lpxxeobxt5uQUchsbn0wKBgQDLCnhNyBIgmS8YodfinN+MIV6BRpia0bps\njSiPuRT8RMvq30Nn1orttyEo1F+EH3daiiVVZT+wnMp0AEZdKoi8v14l+6ALCycL\nZzme1c7tWQpXpr5K7rXlgN9iqH3fajhOM7BPZwAGnEQeRwGUrYtEGK/EPMb3la52\nUGw3kELT9QKBgCHTlfuJOVR3KHzjzohB2IkgeALKHNdDQl8VYbrjRczU1ye+42fO\n0IE4io55Iaxw96EwJ5o17VPWxKmA5TYzDw45VhSvXMakz354qhsPVZqc9XCvMO9o\nFWWfYDPgjAz4pqA5j1NWOrCevXqIwM+IRhvjgC0J0V6qWrWox6hl3uaDAoGBALfV\nJfF+qPL83shVmIpj8H8Go3M2wOrD4x9vev8N2zNA8sQYGwaEGEt8mDhIeKa+eqju\nFTlJL64vd5opuYuW/DCwr4SCW3hEQ7iuYFwwR2dcS+HqZbaghO5jjV3dIgJLQOmF\nISfzIPHbQE2Nip/btREVrOZnBNqbmlcjH6f7JJaVAoGATLoFdwPbGE38KOtqrxVS\nO2rpGSi1FstgtjIRKe60QKz3AkF7iG5mFV1LPgvMisBRADAvZs5FDlnWe4D8DFEp\nR2I6jg2NqQnZRSD6TTLjLSkGttd/x0NO0KkhDwcfWkTDejkpgAGCirDB8ayH84F/\nzdO/JzKM/noIOXjIzN1Z2zA=\n-----END PRIVATE KEY-----\n"
|
||||
GOOGLE_CALENDAR_ID = "a79f0cf9f55e1109d8c88ba61d2524a57e11e7da0167d5f7b0f7da3f628fe4a2@group.calendar.google.com"
|
||||
GOOGLE_CALENDAR_SA_FILE = "hats-project-sa-rifail.json"
|
||||
|
||||
# Google Calendar oAuth 2.0 Config
|
||||
GOOGLE_CLIENT_ID = "141775000325-3rammrevss2mq37u3vthdfra2l1dkm83.apps.googleusercontent.com"
|
||||
GOOGLE_CLIENT_SECRET = "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"
|
||||
GOOGLE_REFRESH_TOKEN = "1//04yMJqoGPYlTeCgYIARAAGAQSSQF-L9IrX-Zy510TWP7UlWM_JpZJQ-VaPPFLnCVbrpoO7zMWhndAbgKrpysh9Fd6ItuMpaPVM-wBzsHoQtOnAnMgIUb0dmPGYms"
|
||||
+4
-2
@@ -42,6 +42,8 @@ yarn-error.log*
|
||||
next-env.d.ts
|
||||
|
||||
*.log
|
||||
package-lock.json
|
||||
|
||||
anti-slop
|
||||
anti-slop
|
||||
|
||||
google_client_secret.json
|
||||
google_service_account.json
|
||||
@@ -9,7 +9,7 @@ import LazyLoading from '@/components/loader/LazyLoading';
|
||||
|
||||
import { type IProfile } from './components/type';
|
||||
import { type IUser } from '@/app/admin/administration/user/component/type';
|
||||
import { getAccessPagePermission, getCacheServerSession, getNonAdminAccessPagePermission } from '@/lib/get-access-data';
|
||||
import { getAccessPagePermission, getCacheServerSession } from '@/lib/get-access-data';
|
||||
|
||||
const ForgotPassword = lazy(() => import('./components/ForgotPassword'));
|
||||
const ChangeTheme = lazy(() => import("./components/ChangeTheme"))
|
||||
|
||||
@@ -9,7 +9,7 @@ import { getQueryStringFilteredAssignments } from '@/lib/fetchData';
|
||||
import { getFilteredAssignments } from '../../../data';
|
||||
import { getClientById, getAssignmentsByClient } from '../../../utils/queries';
|
||||
import Reveal from '@/components/ui/reveal';
|
||||
import { getNonAdminAccessPagePermission } from '@/lib/get-access-data';
|
||||
import { getAccessPagePermission } from '@/lib/get-access-data';
|
||||
|
||||
type Props = {
|
||||
params: Promise<{ client_id: string }>
|
||||
@@ -55,7 +55,7 @@ export async function generateMetadata({ params }: Props): Promise<Metadata> {
|
||||
}
|
||||
|
||||
export default async function ClientDetailPage({ params, searchParams }: Props) {
|
||||
const actions = await getNonAdminAccessPagePermission('/task', 'VIEW_CLIENT')
|
||||
const actions = await getAccessPagePermission('/task', 'VIEW_CLIENT', false)
|
||||
|
||||
const { client_id } = await params;
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import { Button } from '@/components/ui/button';
|
||||
import Link from 'next/link';
|
||||
import AssignmentDetailComponent from './AssignmentDetailComponent';
|
||||
import { getClientById, getAssignmentById } from '../../../utils/queries';
|
||||
import { getNonAdminAccessPagePermission } from '@/lib/get-access-data';
|
||||
import { getAccessPagePermission } from '@/lib/get-access-data';
|
||||
|
||||
type Props = {
|
||||
params: Promise<{ client_id: string; assignment_id: string }>
|
||||
@@ -46,7 +46,7 @@ export async function generateMetadata({ params }: Props): Promise<Metadata> {
|
||||
}
|
||||
|
||||
export default async function AssignmentDetailPage({ params }: Props) {
|
||||
const actions = await getNonAdminAccessPagePermission('/task', 'VIEW_ASSIGNMENT')
|
||||
const actions = await getAccessPagePermission('/task', 'VIEW_ASSIGNMENT', false)
|
||||
|
||||
const { client_id, assignment_id } = await params;
|
||||
|
||||
|
||||
+10
-2
@@ -76,8 +76,8 @@ export const assignmentSchema = yup.object({
|
||||
then: (schema) => schema.shape({
|
||||
name: yup.string().required('Work order name is required'),
|
||||
code: yup.string().required('Work order code is required'),
|
||||
startDate: yup.date().required('Start date is required'),
|
||||
endDate: yup.date().required('End date is required').min(yup.ref('startDate'), 'End date cannot be before start date'),
|
||||
startDate: yup.date().typeError('Work Order Start date is required').required('Start date is required'),
|
||||
endDate: yup.date().typeError('Work Order End date is required').required('End date is required').min(yup.ref('startDate'), 'End date cannot be before start date'),
|
||||
description: yup.string().optional().nullable().max(500, 'Description cannot exceed 500 characters').default(''),
|
||||
}),
|
||||
otherwise: (schema) => schema.nullable().notRequired()
|
||||
@@ -1044,6 +1044,14 @@ export default function ProjectAssignmentForm(
|
||||
setIsSameAsProject(isChecked);
|
||||
if (isChecked) {
|
||||
form.setValue('workOrder.name' as any, formValues.name || '', { shouldValidate: true });
|
||||
form.setValue('workOrder.startDate' as any, formValues.startDate || '', { shouldValidate: true });
|
||||
form.setValue('workOrder.endDate' as any, formValues.endDate || '', { shouldValidate: true });
|
||||
form.setValue('workOrder.description' as any, formValues.description || '', { shouldValidate: true });
|
||||
} else {
|
||||
form.setValue('workOrder.name' as any, '', { shouldValidate: true });
|
||||
form.setValue('workOrder.startDate' as any, '', { shouldValidate: true });
|
||||
form.setValue('workOrder.endDate' as any, '', { shouldValidate: true });
|
||||
form.setValue('workOrder.description' as any, '', { shouldValidate: true });
|
||||
}
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { Metadata } from 'next';
|
||||
import ProjectAssignmentForm from "./ProjectAssignmentForm";
|
||||
import { getClientById, getAssignmentById } from "../../../utils/queries";
|
||||
import { getNonAdminAccessPagePermission } from '@/lib/get-access-data';
|
||||
import { getAccessPagePermission } from '@/lib/get-access-data';
|
||||
|
||||
type Props = {
|
||||
params: Promise<{ client_id?: string }>
|
||||
@@ -15,7 +15,7 @@ export async function generateMetadata({ params, searchParams }: Props): Promise
|
||||
const assignmentId = typeof resolvedSearchParams?.assignment_id === 'string' ? resolvedSearchParams.assignment_id : undefined;
|
||||
const isPromote = resolvedSearchParams?.promote === 'true' || resolvedSearchParams?.is_promote === 'true';
|
||||
|
||||
await getNonAdminAccessPagePermission('/task', isPromote ? 'PROMOTE_ASSIGNMENT' : isEdit ? 'UPDATE_ASSIGNMENT' : 'CREATE_ASSIGNMENT');
|
||||
await getAccessPagePermission('/task', isPromote ? 'PROMOTE_ASSIGNMENT' : isEdit ? 'UPDATE_ASSIGNMENT' : 'CREATE_ASSIGNMENT', false);
|
||||
|
||||
try {
|
||||
const clientPromise = client_id ? getClientById(client_id) : Promise.resolve(undefined);
|
||||
|
||||
@@ -10,7 +10,7 @@ import FilterComponent from '@/app/(dashboard)/task/component/FilterComponent';
|
||||
import { COMPLETE_STATUS_LIST, getFilteredAssignments, ONPROGRESS_STATUS_LIST } from '@/app/(dashboard)/task/data';
|
||||
import { getClientById, getProjectAssignment } from '../../../../utils/queries';
|
||||
import Reveal from '@/components/ui/reveal';
|
||||
import { getNonAdminAccessPagePermission } from '@/lib/get-access-data';
|
||||
import { getAccessPagePermission } from '@/lib/get-access-data';
|
||||
|
||||
type Props = {
|
||||
params: Promise<{ client_id: string; project_id: string }>
|
||||
@@ -18,7 +18,7 @@ type Props = {
|
||||
};
|
||||
|
||||
export async function generateMetadata({ params, searchParams }: Props): Promise<Metadata> {
|
||||
const actions = await getNonAdminAccessPagePermission('/task', 'VIEW_PROJECT')
|
||||
await getAccessPagePermission('/task', 'VIEW_PROJECT', false)
|
||||
|
||||
const { client_id, project_id } = await params;
|
||||
const searchParams_ = await searchParams;
|
||||
|
||||
@@ -15,9 +15,10 @@ import { calculateOverviewStats } from '../utils/client-overview-helpers';
|
||||
|
||||
interface HomeTaskProps {
|
||||
clients?: IClient[];
|
||||
actions?: string[]
|
||||
}
|
||||
|
||||
export default function HomeTask({ clients = [] }: HomeTaskProps) {
|
||||
export default function HomeTask({ clients = [], actions }: HomeTaskProps) {
|
||||
const router = useRouter();
|
||||
const [showForm, setShowForm] = useState(false);
|
||||
|
||||
@@ -60,14 +61,16 @@ export default function HomeTask({ clients = [] }: HomeTaskProps) {
|
||||
Complete overview of all clients, projects, personnel and work orders in one place.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-3 shrink-0">
|
||||
<Button
|
||||
className="gap-2 w-full sm:w-auto shrink-0 font-medium"
|
||||
onClick={() => setShowForm(true)}
|
||||
>
|
||||
<Plus className="w-4 h-4" /> Add Client
|
||||
</Button>
|
||||
</div>
|
||||
{actions?.includes("CREATE_CLIENT") &&
|
||||
<div className="flex items-center gap-3 shrink-0">
|
||||
<Button
|
||||
className="gap-2 w-full sm:w-auto shrink-0 font-medium"
|
||||
onClick={() => setShowForm(true)}
|
||||
>
|
||||
<Plus className="w-4 h-4" /> Add Client
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
{/* Top Stat Cards (4 Cards Grid) */}
|
||||
|
||||
@@ -75,7 +75,7 @@ export default function Client({ clients, actions, initialLayout = 'grid' }: Cli
|
||||
<p className="text-muted-foreground max-w-sm mx-auto mt-2">
|
||||
Try to change the filter or create one to get started.
|
||||
</p>
|
||||
{actions?.includes('CREATE') &&
|
||||
{actions?.includes('CREATE_CLIENT') &&
|
||||
<Button
|
||||
variant="outline"
|
||||
className="mt-4"
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { Metadata } from 'next';
|
||||
import { getFilteredClients } from './data';
|
||||
import { getClients } from './utils/queries';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import { getNonAdminAccessPagePermission } from '@/lib/get-access-data';
|
||||
import { getAccessPagePermission } from '@/lib/get-access-data';
|
||||
|
||||
const HomeTask = lazy(() => import('./component/HomeTask'));
|
||||
const Client = lazy(() => import('./component/client/Client'));
|
||||
@@ -41,7 +41,7 @@ export async function generateMetadata(): Promise<Metadata> {
|
||||
}
|
||||
|
||||
export default async function ClientsPage({ searchParams }: Props) {
|
||||
const actions = await getNonAdminAccessPagePermission('/task', 'VIEW')
|
||||
const actions = await getAccessPagePermission('/task', 'VIEW', false)
|
||||
const searchParams_ = await searchParams;
|
||||
|
||||
// const view = searchParams_.view === 'assignments' ? 'assignments' : 'clients';
|
||||
@@ -64,7 +64,7 @@ export default async function ClientsPage({ searchParams }: Props) {
|
||||
<div className="flex-1 space-y-8 p-4 sm:p-8 pt-4 sm:pt-6">
|
||||
|
||||
<Suspense fallback={<div className='flex justify-center items-center h-48 gap-2'><Loader2 className="animate-spin" />Loading...</div>}>
|
||||
<HomeTask clients={allClients} />
|
||||
<HomeTask clients={allClients} actions={actions} />
|
||||
</Suspense>
|
||||
|
||||
<Suspense fallback={<div className="animate-pulse h-96 bg-accent rounded-xl" />}>
|
||||
|
||||
@@ -41,7 +41,7 @@ export function calculateOverviewStats(clients: IClient[]): OverviewStats {
|
||||
const realWorkOrders = clients.reduce((sum, c) => sum + (c.total_work_order || 0), 0);
|
||||
|
||||
return {
|
||||
totalClients: totalClients || 8,
|
||||
totalClients: totalClients || 0,
|
||||
activeProjects: realProjects > 0 ? realProjects : 0,
|
||||
activeInternalMemos: realInternalMemos > 0 ? realInternalMemos : 0,
|
||||
activeWorkOrders: realWorkOrders > 0 ? realWorkOrders : 0,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
@import "tailwindcss";
|
||||
@import "tw-animate-css";
|
||||
@import 'tailwind-scrollbar-hide/v4';
|
||||
@plugin "@tailwindcss/typography";
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
@@ -343,4 +344,36 @@
|
||||
|
||||
.tada {
|
||||
animation-name: tada;
|
||||
}
|
||||
|
||||
|
||||
/* Google Calendar Rich Description Styles */
|
||||
.gcal-rich-content ul {
|
||||
list-style-type: disc !important;
|
||||
padding-left: 1.75rem !important;
|
||||
margin: 0.35rem 0 !important;
|
||||
}
|
||||
|
||||
.gcal-rich-content ol {
|
||||
list-style-type: decimal !important;
|
||||
padding-left: 1.75rem !important;
|
||||
margin: 0.35rem 0 !important;
|
||||
}
|
||||
|
||||
.gcal-rich-content li {
|
||||
display: list-item !important;
|
||||
margin: 0.15rem 0 !important;
|
||||
}
|
||||
|
||||
.gcal-rich-content a,
|
||||
.gcal-rich-content a * {
|
||||
color: #1a73e8 !important;
|
||||
text-decoration: underline !important;
|
||||
text-underline-offset: 2px !important;
|
||||
cursor: pointer !important;
|
||||
}
|
||||
|
||||
.dark .gcal-rich-content a,
|
||||
.dark .gcal-rich-content a * {
|
||||
color: #8ab4f8 !important;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
Langkah 1: Google Cloud Console
|
||||
- Buka Google Cloud Console
|
||||
- Buat project baru (misal: hats-project) atau pilih project yang sudah ada.
|
||||
- Masuk ke APIs & Services > Library, cari Google Calendar API, lalu klik Enable.
|
||||
- Buat OAuth 2.0 Client ID (Web Application) di Google Cloud Console.
|
||||
- Tambah pada bagian Authorized redirect URIs: `https://developers.google.com/oauthplayground`
|
||||
|
||||
Langkah 2: Google Playground
|
||||
Buka Google OAuth 2.0 Playground
|
||||
- Klik ikon Gear (⚙️ OAuth 2.0 configuration) di pojok kanan atas:
|
||||
- Centang kotak "Use your own OAuth credentials".
|
||||
- Masukkan nilai GOOGLE_CLIENT_ID dan GOOGLE_CLIENT_SECRET Anda.
|
||||
- Klik Close.
|
||||
- Pada panel kiri (Step 1), masukkan scope: `https://www.googleapis.com/auth/calendar`
|
||||
- Lalu klik Authorize APIs dan login menggunakan akun Google sistem Anda (his.nutech@gmail.com).
|
||||
- Pada Step 2, klik tombol Exchange authorization code for tokens.
|
||||
- Salin Refresh token yang baru dihasilkan, lalu ganti nilai GOOGLE_REFRESH_TOKEN di .env.development dan restart server Next.js (npm run dev).
|
||||
|
||||
Langkah 3: Buka Google Calendar dengan akun Google pengelola.
|
||||
- Buat kalender khusus (misal: "HATS Tasks & Schedule") atau gunakan kalender yang sudah ada.
|
||||
- Klik ikon titik tiga di samping kalender > Settings and sharing.
|
||||
- Gulir ke bagian Share with specific people or groups, klik Add people and groups.
|
||||
- Tempelkan email Service Account Anda (format: hats-calendar-bot@<project-id>.iam.gserviceaccount.com).
|
||||
- Atur izin menjadi: "Make changes to events" (agar bot bisa membuat, mengedit, dan menghapus event).
|
||||
- Gulir ke bagian Integrate calendar, lalu salin Calendar ID (format: xxx@group.calendar.google.com atau alamat email pemilik).
|
||||
@@ -0,0 +1,131 @@
|
||||
import { google, calendar_v3 } from 'googleapis';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
|
||||
const SCOPES = [
|
||||
'https://www.googleapis.com/auth/calendar',
|
||||
'https://www.googleapis.com/auth/calendar.events',
|
||||
];
|
||||
|
||||
export interface GoogleClientContext {
|
||||
calendar: calendar_v3.Calendar;
|
||||
calendarId: string;
|
||||
serviceAccountEmail: string;
|
||||
authMode: 'oauth2' | 'service_account';
|
||||
}
|
||||
|
||||
export function getGoogleCalendarClient(): GoogleClientContext {
|
||||
const calendarId = process.env.GOOGLE_CALENDAR_ID || 'primary';
|
||||
|
||||
const clientId = process.env.GOOGLE_CLIENT_ID?.trim();
|
||||
const clientSecret = process.env.GOOGLE_CLIENT_SECRET?.trim();
|
||||
const refreshToken = process.env.GOOGLE_REFRESH_TOKEN?.trim();
|
||||
const serviceAccountFile = process.env.GOOGLE_CALENDAR_SA_FILE?.trim();
|
||||
|
||||
// 1. Primary Mode: Single System OAuth2 Refresh Token
|
||||
if (clientId && clientSecret && refreshToken) {
|
||||
const oauth2Client = new google.auth.OAuth2(
|
||||
clientId,
|
||||
clientSecret,
|
||||
'https://developers.google.com/oauthplayground'
|
||||
);
|
||||
|
||||
oauth2Client.setCredentials({
|
||||
refresh_token: refreshToken,
|
||||
});
|
||||
|
||||
const calendar = google.calendar({
|
||||
version: 'v3',
|
||||
auth: oauth2Client,
|
||||
});
|
||||
|
||||
return {
|
||||
calendar,
|
||||
calendarId,
|
||||
serviceAccountEmail: 'OAuth2 System Account',
|
||||
authMode: 'oauth2',
|
||||
};
|
||||
}
|
||||
|
||||
// 2. Fallback Mode: Google Service Account
|
||||
let clientEmail = process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL;
|
||||
let privateKey = process.env.GOOGLE_PRIVATE_KEY;
|
||||
|
||||
const keyFilePath = path.join(process.cwd(), serviceAccountFile!);
|
||||
if (fs.existsSync(keyFilePath)) {
|
||||
try {
|
||||
const fileData = JSON.parse(fs.readFileSync(keyFilePath, 'utf8'));
|
||||
if (fileData.client_email) clientEmail = fileData.client_email;
|
||||
if (fileData.private_key) privateKey = fileData.private_key;
|
||||
} catch (e) {
|
||||
console.warn('[GOOGLE_CALENDAR] Could not parse hats-project-sa-rifail.json:', e);
|
||||
}
|
||||
}
|
||||
|
||||
if (!clientEmail || !privateKey) {
|
||||
throw new Error(
|
||||
'Kredensial Google Calendar tidak ditemukan! Pastikan GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, dan GOOGLE_REFRESH_TOKEN telah dikonfigurasi di file .env.'
|
||||
);
|
||||
}
|
||||
|
||||
const formattedPrivateKey = privateKey.replace(/\\n/g, '\n');
|
||||
|
||||
const auth = new google.auth.JWT({
|
||||
email: clientEmail,
|
||||
key: formattedPrivateKey,
|
||||
scopes: SCOPES,
|
||||
});
|
||||
|
||||
const calendar = google.calendar({
|
||||
version: 'v3',
|
||||
auth,
|
||||
});
|
||||
|
||||
return {
|
||||
calendar,
|
||||
calendarId,
|
||||
serviceAccountEmail: clientEmail,
|
||||
authMode: 'service_account',
|
||||
};
|
||||
}
|
||||
|
||||
export function formatGoogleApiError(error: unknown): string {
|
||||
if (!error) return 'Terjadi kesalahan internal yang tidak diketahui.';
|
||||
|
||||
const err = error as { message?: string; code?: number | string };
|
||||
const message = err.message || String(error);
|
||||
|
||||
if (message.includes('unauthorized_client')) {
|
||||
return 'OAuth2 Error (unauthorized_client): GOOGLE_REFRESH_TOKEN tidak cocok dengan GOOGLE_CLIENT_ID & GOOGLE_CLIENT_SECRET Anda. Jika membuat token di Google OAuth Playground, pastikan Anda klik ikon Gear (⚙️) di kanan atas dan centang "Use your own OAuth credentials" lalu masukkan Client ID & Client Secret sebelum mengklik Authorize APIs.';
|
||||
}
|
||||
|
||||
if (message.includes('invalid_grant')) {
|
||||
return 'OAuth2 Error (invalid_grant): Refresh Token sudah kedaluwarsa, dicabut (revoked), atau aplikasi OAuth masih berstatus "Testing" di Google Cloud Console (token kedaluwarsa setelah 7 hari). Silakan generate ulang GOOGLE_REFRESH_TOKEN.';
|
||||
}
|
||||
|
||||
if (message.includes('Google Calendar API has not been used') || message.includes('disabled')) {
|
||||
return 'Google Calendar API belum diaktifkan di Google Cloud Console. Silakan aktifkan Calendar API di Console.';
|
||||
}
|
||||
|
||||
if (message.includes('Domain-Wide Delegation')) {
|
||||
return 'Service Account tanpa Domain-Wide Delegation tidak dapat mengirim undangan email (attendees) secara langsung.';
|
||||
}
|
||||
|
||||
if (message.includes('Invalid conference type value')) {
|
||||
return 'Pembuatan link Google Meet otomatis gagal ("Invalid conference type value"). Pastikan menggunakan autentikasi OAuth2 System Account atau masukkan link Google Meet secara manual.';
|
||||
}
|
||||
|
||||
if (message.includes('Invalid start time') || message.includes('time range is empty')) {
|
||||
return 'Format waktu mulai/selesai tidak valid. Pastikan waktu selesai lebih akhir dari waktu mulai.';
|
||||
}
|
||||
|
||||
if (message.includes('Not Found') || err.code === 404) {
|
||||
return 'Kalender tidak ditemukan (404). Pastikan akun Google OAuth2 yang digunakan memiliki akses ke GOOGLE_CALENDAR_ID tersebut (atau ubah GOOGLE_CALENDAR_ID="primary" untuk menggunakan kalender utama akun tersebut).';
|
||||
}
|
||||
|
||||
if (message.includes('forbidden') || err.code === 403) {
|
||||
return 'Akses ditolak (403). Pastikan akun yang digunakan memiliki izin "Make changes to events" pada kalender ini.';
|
||||
}
|
||||
|
||||
return message;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
export interface GoogleEventColor {
|
||||
id: string;
|
||||
name: string;
|
||||
hex: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Official Google Calendar API v3 Event colorId palette ("1" - "11")
|
||||
*/
|
||||
export const GOOGLE_EVENT_COLORS: GoogleEventColor[] = [
|
||||
{ id: '1', name: 'Lavender', hex: '#7986cb' },
|
||||
{ id: '2', name: 'Sage', hex: '#33b679' },
|
||||
{ id: '3', name: 'Grape', hex: '#8e24aa' },
|
||||
{ id: '4', name: 'Flamingo', hex: '#e67c73' },
|
||||
{ id: '5', name: 'Banana', hex: '#f6bf26' },
|
||||
{ id: '6', name: 'Tangerine', hex: '#f4511e' },
|
||||
{ id: '7', name: 'Peacock', hex: '#039be5' },
|
||||
{ id: '8', name: 'Graphite', hex: '#616161' },
|
||||
{ id: '9', name: 'Blueberry', hex: '#3f51b5' },
|
||||
{ id: '10', name: 'Basil', hex: '#0b8043' },
|
||||
{ id: '11', name: 'Tomato', hex: '#d50000' },
|
||||
];
|
||||
|
||||
export function getEventColorInfo(colorId?: string): GoogleEventColor | null {
|
||||
if (!colorId) return null;
|
||||
return GOOGLE_EVENT_COLORS.find((c) => c.id === colorId) || null;
|
||||
}
|
||||
@@ -0,0 +1,543 @@
|
||||
'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),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
export * from './types';
|
||||
export * from './constants';
|
||||
export * from './auth';
|
||||
export * from './events.actions';
|
||||
export * from './tasks.actions';
|
||||
@@ -0,0 +1,362 @@
|
||||
'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),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
export interface CalendarActionResponse<T = unknown> {
|
||||
success: boolean;
|
||||
data?: T;
|
||||
error?: string;
|
||||
warning?: string;
|
||||
}
|
||||
|
||||
export interface CalendarEventItem {
|
||||
id: string;
|
||||
summary: string;
|
||||
description?: string;
|
||||
location?: string;
|
||||
start: string; // ISO String or YYYY-MM-DD (inclusive for UI)
|
||||
end: string; // ISO String or YYYY-MM-DD (inclusive for UI)
|
||||
isAllDay: boolean;
|
||||
colorId?: string;
|
||||
attendees?: string[];
|
||||
hangoutLink?: string;
|
||||
htmlLink?: string;
|
||||
creatorEmail?: string;
|
||||
createdAt?: string;
|
||||
updatedAt?: string;
|
||||
}
|
||||
|
||||
export interface CreateEventInput {
|
||||
summary: string;
|
||||
description?: string;
|
||||
location?: string;
|
||||
startDateTime: string; // ISO string or YYYY-MM-DD
|
||||
endDateTime: string; // ISO string or YYYY-MM-DD (inclusive from form)
|
||||
isAllDay?: boolean;
|
||||
colorId?: string;
|
||||
attendees?: string[];
|
||||
generateMeet?: boolean;
|
||||
manualMeetLink?: string;
|
||||
}
|
||||
|
||||
export interface UpdateEventInput {
|
||||
summary?: string;
|
||||
description?: string;
|
||||
location?: string;
|
||||
startDateTime?: string;
|
||||
endDateTime?: string;
|
||||
isAllDay?: boolean;
|
||||
colorId?: string;
|
||||
attendees?: string[];
|
||||
generateMeet?: boolean;
|
||||
manualMeetLink?: string;
|
||||
}
|
||||
|
||||
export type TaskStatus = 'needsAction' | 'completed';
|
||||
|
||||
export interface CalendarTaskItem {
|
||||
id: string;
|
||||
title: string;
|
||||
description?: string;
|
||||
due: string; // ISO date/time string
|
||||
status: TaskStatus;
|
||||
completedAt?: string;
|
||||
htmlLink?: string;
|
||||
createdAt?: string;
|
||||
updatedAt?: string;
|
||||
}
|
||||
|
||||
export interface CreateTaskInput {
|
||||
title: string;
|
||||
description?: string;
|
||||
due: string; // ISO string
|
||||
status?: TaskStatus;
|
||||
}
|
||||
|
||||
export interface UpdateTaskInput {
|
||||
title?: string;
|
||||
description?: string;
|
||||
due?: string;
|
||||
status?: TaskStatus;
|
||||
}
|
||||
|
||||
export interface CalendarSummaryStats {
|
||||
totalEvents: number;
|
||||
totalTasks: number;
|
||||
completedTasks: number;
|
||||
pendingTasks: number;
|
||||
calendarId: string;
|
||||
serviceAccountEmail: string;
|
||||
}
|
||||
Generated
+12880
File diff suppressed because it is too large
Load Diff
@@ -51,6 +51,7 @@
|
||||
"firebase": "^12.6.0",
|
||||
"framer-motion": "^12.23.25",
|
||||
"get-orientation": "^1.1.2",
|
||||
"googleapis": "^190.0.0",
|
||||
"heic2any": "^0.0.4",
|
||||
"lucide-react": "^1.68.0",
|
||||
"motion": "^12.38.0",
|
||||
@@ -80,6 +81,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4",
|
||||
"@tailwindcss/typography": "^0.5.20",
|
||||
"@types/node": "^20",
|
||||
"@types/react": "^19",
|
||||
"@types/react-dom": "^19",
|
||||
|
||||
Reference in New Issue
Block a user