mirror of
https://github.com/ichsankurnia/hats-app.git
synced 2026-12-05 10:56:28 +00:00
Compare commits
13 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9cda75f5b1 | |||
| 4931d3be5f | |||
| 525f85edaf | |||
| d10603acc8 | |||
| d4168b45f2 | |||
| c9dc6a5e51 | |||
| 99a6849e17 | |||
| faa22e93e0 | |||
| b657f79a2a | |||
| 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
|
||||
@@ -43,7 +43,7 @@ export function MainNav({ className, ...props }: HTMLAttributes<HTMLElement>) {
|
||||
className={`text-sm font-medium transition-colors hover:text-his hover:border-b-[3px] border-his pt-6 pb-5 ${getMenuActiveStyle('/task')}`}
|
||||
>
|
||||
<i className="ti ti-checklist text-base mr-0.5"></i>
|
||||
My Task
|
||||
Task
|
||||
</Link>
|
||||
{session?.user.detail.role.allow_admin_panel &&
|
||||
<Link
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
'use client';
|
||||
|
||||
import { AlertTriangle, ExternalLink } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
interface ApiNoticeBannerProps {
|
||||
error?: string | null;
|
||||
}
|
||||
|
||||
export default function ApiNoticeBanner({ error }: ApiNoticeBannerProps) {
|
||||
if (!error) return null;
|
||||
|
||||
const isApiDisabledError =
|
||||
error.includes('belum diaktifkan') ||
|
||||
error.includes('Google Calendar API has not been used') ||
|
||||
error.includes('disabled');
|
||||
|
||||
const isOAuthMismatchError =
|
||||
error.includes('unauthorized_client') || error.includes('invalid_grant');
|
||||
|
||||
const enableUrl =
|
||||
'https://console.developers.google.com/apis/api/calendar-json.googleapis.com/overview?project=141775000325';
|
||||
const playgroundUrl = 'https://developers.google.com/oauthplayground/';
|
||||
|
||||
return (
|
||||
<div
|
||||
role="alert"
|
||||
className="rounded-xl border border-amber-300 bg-amber-50/80 p-4 text-amber-950 dark:border-amber-800/60 dark:bg-amber-950/30 dark:text-amber-200 shadow-xs"
|
||||
>
|
||||
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3">
|
||||
<div className="flex items-start gap-3">
|
||||
<AlertTriangle className="size-5 text-amber-600 dark:text-amber-400 shrink-0 mt-0.5" />
|
||||
<div className="space-y-1">
|
||||
<h4 className="text-sm font-semibold tracking-tight">
|
||||
{isApiDisabledError
|
||||
? 'Google Calendar API Belum Diaktifkan di Project Cloud'
|
||||
: isOAuthMismatchError
|
||||
? 'Konfigurasi OAuth2 Refresh Token Perlu Diperbarui'
|
||||
: 'Pemberitahuan Sinkronisasi Google Calendar'}
|
||||
</h4>
|
||||
<p className="text-xs text-amber-900/90 dark:text-amber-300/90 leading-relaxed max-w-3xl">
|
||||
{error}
|
||||
</p>
|
||||
{isOAuthMismatchError && (
|
||||
<ol className="text-xs text-amber-800 dark:text-amber-300 list-decimal list-inside space-y-0.5 pt-1">
|
||||
<li>
|
||||
Pastikan <code className="font-mono">https://developers.google.com/oauthplayground</code> sudah ditambahkan ke <strong>Authorized redirect URIs</strong> pada OAuth 2.0 Client ID Anda di Google Cloud Console.
|
||||
</li>
|
||||
<li>
|
||||
Buka OAuth 2.0 Playground, klik ikon <strong>Gear (⚙️)</strong> di kanan atas, centang <strong>"Use your own OAuth credentials"</strong>, lalu isi <code className="font-mono">GOOGLE_CLIENT_ID</code> & <code className="font-mono">GOOGLE_CLIENT_SECRET</code> Anda.
|
||||
</li>
|
||||
<li>
|
||||
Pilih scope <code className="font-mono">https://www.googleapis.com/auth/calendar</code> > klik <strong>Authorize APIs</strong> > klik <strong>Exchange authorization code for tokens</strong> > salin <strong>Refresh token</strong> baru ke <code className="font-mono">.env.development</code>.
|
||||
</li>
|
||||
</ol>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isApiDisabledError && (
|
||||
<Button
|
||||
asChild
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="shrink-0 border-amber-400 bg-white hover:bg-amber-100 text-amber-900 dark:border-amber-700 dark:bg-amber-900/40 dark:text-amber-100 dark:hover:bg-amber-900/70"
|
||||
>
|
||||
<a href={enableUrl} target="_blank" rel="noopener noreferrer">
|
||||
<span>Aktifkan API Sekarang</span>
|
||||
<ExternalLink className="size-3.5 ml-1.5" />
|
||||
</a>
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{isOAuthMismatchError && (
|
||||
<Button
|
||||
asChild
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="shrink-0 border-amber-400 bg-white hover:bg-amber-100 text-amber-900 dark:border-amber-700 dark:bg-amber-900/40 dark:text-amber-100 dark:hover:bg-amber-900/70"
|
||||
>
|
||||
<a href={playgroundUrl} target="_blank" rel="noopener noreferrer">
|
||||
<span>Buka OAuth Playground</span>
|
||||
<ExternalLink className="size-3.5 ml-1.5" />
|
||||
</a>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
'use client';
|
||||
|
||||
import { Calendar as CalendarIcon, ExternalLink, RefreshCw, Plus, CheckSquare } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
|
||||
interface CalendarHeaderProps {
|
||||
calendarId?: string;
|
||||
serviceAccountEmail?: string;
|
||||
onRefresh: () => void;
|
||||
onAddEvent: () => void;
|
||||
onAddTask?: () => void;
|
||||
isRefreshing?: boolean;
|
||||
}
|
||||
|
||||
export default function CalendarHeader({
|
||||
calendarId,
|
||||
serviceAccountEmail,
|
||||
onRefresh,
|
||||
onAddEvent,
|
||||
onAddTask,
|
||||
isRefreshing = false,
|
||||
}: CalendarHeaderProps) {
|
||||
const googleCalendarWebUrl = calendarId
|
||||
? `https://calendar.google.com/calendar/u/0/r?cid=${encodeURIComponent(calendarId)}`
|
||||
: 'https://calendar.google.com';
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4 pb-4 border-b border-zinc-200 dark:border-zinc-800">
|
||||
<div className="flex flex-col lg:flex-row lg:items-center justify-between gap-4">
|
||||
{/* Title & Info */}
|
||||
<div className="space-y-1.5">
|
||||
<div className="flex items-center gap-2.5">
|
||||
<div className="p-2 rounded-lg bg-zinc-100 dark:bg-zinc-800 text-zinc-900 dark:text-zinc-100">
|
||||
<CalendarIcon className="size-5" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-xl md:text-2xl font-bold tracking-tight text-zinc-900 dark:text-zinc-100">
|
||||
Google Calendar & Task Testing
|
||||
</h1>
|
||||
<p className="text-xs md:text-sm text-zinc-500 dark:text-zinc-400">
|
||||
Integrasi Server-to-Server (Single System OAuth2 Refresh Token) • Tanpa OAuth Login Pengguna
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Badges Info */}
|
||||
<div className="flex flex-wrap items-center gap-2 pt-1 text-xs">
|
||||
<span className="text-zinc-500 font-medium">Koneksi Aktif:</span>
|
||||
{calendarId && (
|
||||
<Badge variant="outline" className="font-mono text-[11px] max-w-[280px] sm:max-w-none truncate">
|
||||
Cal: {calendarId}
|
||||
</Badge>
|
||||
)}
|
||||
{serviceAccountEmail && (
|
||||
<Badge variant="outline" className="font-mono text-[11px] max-w-[260px] sm:max-w-none truncate">
|
||||
Auth: {serviceAccountEmail}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Action Buttons */}
|
||||
<div className="flex flex-wrap items-center gap-2.5">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={onRefresh}
|
||||
disabled={isRefreshing}
|
||||
className="h-9 px-3"
|
||||
>
|
||||
<RefreshCw className={`size-3.5 mr-1.5 ${isRefreshing ? 'animate-spin' : ''}`} />
|
||||
<span>Muat Ulang</span>
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
asChild
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-9 px-3"
|
||||
>
|
||||
<a href={googleCalendarWebUrl} target="_blank" rel="noopener noreferrer">
|
||||
<span>Buka Google Calendar</span>
|
||||
<ExternalLink className="size-3.5 ml-1.5" />
|
||||
</a>
|
||||
</Button>
|
||||
|
||||
{onAddTask && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={onAddTask}
|
||||
className="h-9 px-3 border-emerald-600 text-emerald-700 dark:text-emerald-400 dark:border-emerald-700 hover:bg-emerald-50 dark:hover:bg-emerald-950/40"
|
||||
>
|
||||
<CheckSquare className="size-3.5 mr-1.5" />
|
||||
<span>Tambah Task</span>
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={onAddEvent}
|
||||
>
|
||||
<Plus className="size-3.5 mr-1.5" />
|
||||
<span>Tambah Event</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
'use client';
|
||||
|
||||
import React from 'react';
|
||||
import { Calendar, CheckCircle2, Clock, ListTodo } from 'lucide-react';
|
||||
import { Card900 } from '@/components/ui/card';
|
||||
|
||||
interface CalendarStatsOverviewProps {
|
||||
totalEvents: number;
|
||||
totalTasks: number;
|
||||
completedTasks: number;
|
||||
pendingTasks: number;
|
||||
}
|
||||
|
||||
export default function CalendarStatsOverview({
|
||||
totalEvents,
|
||||
totalTasks,
|
||||
completedTasks,
|
||||
pendingTasks,
|
||||
}: CalendarStatsOverviewProps) {
|
||||
const cards = [
|
||||
{
|
||||
title: 'Total Event Kalender',
|
||||
value: totalEvents,
|
||||
icon: Calendar,
|
||||
desc: 'Agenda terjadwal di Google Calendar',
|
||||
iconColor: 'text-sky-600 dark:text-sky-400',
|
||||
bgColor: 'bg-sky-50 dark:bg-sky-950/40',
|
||||
},
|
||||
{
|
||||
title: 'Total Task',
|
||||
value: totalTasks,
|
||||
icon: ListTodo,
|
||||
desc: 'Item task berlabel [TASK]',
|
||||
iconColor: 'text-indigo-600 dark:text-indigo-400',
|
||||
bgColor: 'bg-indigo-50 dark:bg-indigo-950/40',
|
||||
},
|
||||
{
|
||||
title: 'Task Selesai',
|
||||
value: completedTasks,
|
||||
icon: CheckCircle2,
|
||||
desc: 'Status: completed / selesai',
|
||||
iconColor: 'text-emerald-600 dark:text-emerald-400',
|
||||
bgColor: 'bg-emerald-50 dark:bg-emerald-950/40',
|
||||
},
|
||||
{
|
||||
title: 'Task Tertunda',
|
||||
value: pendingTasks,
|
||||
icon: Clock,
|
||||
desc: 'Status: needsAction / menunggu',
|
||||
iconColor: 'text-amber-600 dark:text-amber-400',
|
||||
bgColor: 'bg-amber-50 dark:bg-amber-950/80',
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4">
|
||||
{cards.map((card, idx) => {
|
||||
const Icon = card.icon;
|
||||
return (
|
||||
<Card900
|
||||
key={idx}
|
||||
className="p-4 rounded-xl border border-zinc-200 dark:border-zinc-800 bg-white dark:bg-zinc-900 gap-2 shadow-xs"
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-xs font-medium text-zinc-500 dark:text-zinc-400">
|
||||
{card.title}
|
||||
</span>
|
||||
<div className={`p-1.5 rounded-lg ${card.bgColor} ${card.iconColor}`}>
|
||||
<Icon className="size-4" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-baseline gap-2">
|
||||
<span className="text-2xl font-bold tracking-tight text-zinc-900 dark:text-zinc-100">
|
||||
{card.value}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-[11px] text-zinc-400 dark:text-zinc-500 truncate">
|
||||
{card.desc}
|
||||
</p>
|
||||
</Card900>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogContent,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogCancel,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { deleteCalendarEvent } from '@/lib/google-calendar/events.actions';
|
||||
import { deleteCalendarTask } from '@/lib/google-calendar/tasks.actions';
|
||||
import { toast } from 'sonner';
|
||||
import { Loader2, AlertCircle } from 'lucide-react';
|
||||
|
||||
interface DeleteConfirmDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
item: {
|
||||
id: string;
|
||||
title: string;
|
||||
type: 'event' | 'task';
|
||||
calendarId?: string;
|
||||
} | null;
|
||||
onSuccess: () => void;
|
||||
}
|
||||
|
||||
export default function DeleteConfirmDialog({ open, onOpenChange, item, onSuccess }: DeleteConfirmDialogProps) {
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
if (!item) return null;
|
||||
|
||||
const handleConfirmDelete = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
|
||||
const res =
|
||||
item.type === 'event'
|
||||
? await deleteCalendarEvent(item.id, item.calendarId)
|
||||
: await deleteCalendarTask(item.id);
|
||||
|
||||
if (res.success) {
|
||||
toast.success(`${item.type === 'event' ? 'Event' : 'Task'} berhasil dihapus dari Google Calendar.`);
|
||||
onOpenChange(false);
|
||||
onSuccess();
|
||||
} else {
|
||||
toast.error(res.error || 'Gagal menghapus data.');
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
const msg = err instanceof Error ? err.message : 'Terjadi kesalahan sistem.';
|
||||
toast.error(msg);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<AlertDialog open={open} onOpenChange={onOpenChange}>
|
||||
<AlertDialogContent className="bg-white dark:bg-zinc-950 border-zinc-200 dark:border-zinc-800">
|
||||
<AlertDialogHeader>
|
||||
<div className="flex items-center gap-2.5 text-rose-600 dark:text-rose-500 mb-1">
|
||||
<AlertCircle className="size-5" />
|
||||
<AlertDialogTitle className="text-base font-semibold">
|
||||
Hapus {item.type === 'event' ? 'Event' : 'Task'}?
|
||||
</AlertDialogTitle>
|
||||
</div>
|
||||
<AlertDialogDescription className="text-xs text-zinc-600 dark:text-zinc-400 leading-relaxed">
|
||||
Apakah Anda yakin ingin menghapus{' '}
|
||||
<strong className="text-zinc-900 dark:text-zinc-100 font-semibold">
|
||||
"{item.title}"
|
||||
</strong>
|
||||
? Agenda ini akan dihapus secara permanen dari akun Google Calendar resmi Anda.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
|
||||
<AlertDialogFooter className="mt-4 gap-2">
|
||||
<AlertDialogCancel disabled={loading} className="text-xs h-9 border-zinc-200 dark:border-zinc-800">
|
||||
Batal
|
||||
</AlertDialogCancel>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="destructive"
|
||||
onClick={handleConfirmDelete}
|
||||
disabled={loading}
|
||||
className="h-9 px-3 text-xs font-medium"
|
||||
>
|
||||
{loading && <Loader2 className="size-3.5 mr-1.5 animate-spin" />}
|
||||
Hapus Permanen
|
||||
</Button>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,556 @@
|
||||
'use client';
|
||||
|
||||
import React, { useRef, useState, useEffect, useCallback } from 'react';
|
||||
import {
|
||||
Bold,
|
||||
Italic,
|
||||
Underline,
|
||||
ListOrdered,
|
||||
List,
|
||||
Link2,
|
||||
RemoveFormatting,
|
||||
AlignLeft,
|
||||
Globe,
|
||||
Pencil,
|
||||
X,
|
||||
ExternalLink,
|
||||
} from 'lucide-react';
|
||||
|
||||
interface DescriptionRichEditorProps {
|
||||
value: string;
|
||||
onChange: (html: string) => void;
|
||||
placeholder?: string;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
interface ActiveFormats {
|
||||
bold: boolean;
|
||||
italic: boolean;
|
||||
underline: boolean;
|
||||
insertOrderedList: boolean;
|
||||
insertUnorderedList: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Basic HTML sanitizer allowing safe Google Calendar formatting tags:
|
||||
* b, strong, i, em, u, ul, ol, li, br, p, div, span, a (href, target, rel)
|
||||
*/
|
||||
export function sanitizeCalendarHtml(dirtyHtml?: string): string {
|
||||
if (!dirtyHtml) return '';
|
||||
|
||||
return dirtyHtml
|
||||
.replace(/<(script|style|iframe|object|embed|form)[^>]*>[\s\S]*?<\/\1>/gi, '')
|
||||
.replace(/\son\w+\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)/gi, '')
|
||||
.replace(/href\s*=\s*["']?\s*javascript:[^"'\s>]*/gi, 'href="#"');
|
||||
}
|
||||
|
||||
export default function DescriptionRichEditor({
|
||||
value,
|
||||
onChange,
|
||||
placeholder = 'Add description',
|
||||
disabled = false,
|
||||
}: DescriptionRichEditorProps) {
|
||||
const editorRef = useRef<HTMLDivElement>(null);
|
||||
const isInternalChange = useRef(false);
|
||||
const savedRangeRef = useRef<Range | null>(null);
|
||||
|
||||
const [formats, setFormats] = useState<ActiveFormats>({
|
||||
bold: false,
|
||||
italic: false,
|
||||
underline: false,
|
||||
insertOrderedList: false,
|
||||
insertUnorderedList: false,
|
||||
});
|
||||
|
||||
// Google Calendar "Edit link" modal state
|
||||
const [linkDialogOpen, setLinkDialogOpen] = useState(false);
|
||||
const [linkText, setLinkText] = useState('');
|
||||
const [linkUrl, setLinkUrl] = useState('');
|
||||
const editingAnchorRef = useRef<HTMLAnchorElement | null>(null);
|
||||
|
||||
// Active link under cursor (for Google Calendar's bottom floating link bar [✏️ | ✕])
|
||||
const activeAnchorRef = useRef<HTMLAnchorElement | null>(null);
|
||||
const [hasActiveAnchor, setHasActiveAnchor] = useState(false);
|
||||
const [activeAnchorHref, setActiveAnchorHref] = useState('');
|
||||
|
||||
// Sync external value into contentEditable only when not actively typing inside it
|
||||
useEffect(() => {
|
||||
const el = editorRef.current;
|
||||
if (!el) return;
|
||||
|
||||
if (!isInternalChange.current && el.innerHTML !== value) {
|
||||
el.innerHTML = sanitizeCalendarHtml(value);
|
||||
}
|
||||
isInternalChange.current = false;
|
||||
}, [value]);
|
||||
|
||||
const findParentAnchor = useCallback((node: Node | null): HTMLAnchorElement | null => {
|
||||
const el = editorRef.current;
|
||||
if (!el || !node) return null;
|
||||
let curr: Node | null = node;
|
||||
while (curr && curr !== el) {
|
||||
if (curr.nodeName === 'A') {
|
||||
return curr as HTMLAnchorElement;
|
||||
}
|
||||
curr = curr.parentNode;
|
||||
}
|
||||
return null;
|
||||
}, []);
|
||||
|
||||
const checkActiveFormats = useCallback(() => {
|
||||
const el = editorRef.current;
|
||||
if (!el) return;
|
||||
|
||||
try {
|
||||
const sel = window.getSelection();
|
||||
if (sel && sel.rangeCount > 0 && el.contains(sel.anchorNode)) {
|
||||
savedRangeRef.current = sel.getRangeAt(0).cloneRange();
|
||||
const anchor = findParentAnchor(sel.anchorNode);
|
||||
activeAnchorRef.current = anchor;
|
||||
setHasActiveAnchor(Boolean(anchor));
|
||||
setActiveAnchorHref(anchor?.getAttribute('href') || '');
|
||||
}
|
||||
|
||||
setFormats({
|
||||
bold: document.queryCommandState('bold'),
|
||||
italic: document.queryCommandState('italic'),
|
||||
underline: document.queryCommandState('underline'),
|
||||
insertOrderedList: document.queryCommandState('insertOrderedList'),
|
||||
insertUnorderedList: document.queryCommandState('insertUnorderedList'),
|
||||
});
|
||||
} catch {
|
||||
// Ignore if selection state is unavailable
|
||||
}
|
||||
}, [findParentAnchor]);
|
||||
|
||||
const emitChange = useCallback(() => {
|
||||
const el = editorRef.current;
|
||||
if (!el) return;
|
||||
|
||||
isInternalChange.current = true;
|
||||
const rawHtml = el.innerHTML;
|
||||
const textOnly = el.textContent?.trim() || '';
|
||||
const hasList = /<(ul|ol|li)\b/i.test(rawHtml);
|
||||
|
||||
if (!textOnly && !hasList) {
|
||||
onChange('');
|
||||
} else {
|
||||
onChange(sanitizeCalendarHtml(rawHtml));
|
||||
}
|
||||
checkActiveFormats();
|
||||
}, [onChange, checkActiveFormats]);
|
||||
|
||||
const ensureSelectionInsideEditor = () => {
|
||||
const el = editorRef.current;
|
||||
if (!el) return;
|
||||
|
||||
el.focus();
|
||||
const sel = window.getSelection();
|
||||
if (!sel) return;
|
||||
|
||||
if (sel.rangeCount > 0 && el.contains(sel.anchorNode)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (savedRangeRef.current && el.contains(savedRangeRef.current.commonAncestorContainer)) {
|
||||
sel.removeAllRanges();
|
||||
sel.addRange(savedRangeRef.current);
|
||||
return;
|
||||
}
|
||||
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(el);
|
||||
range.collapse(false);
|
||||
sel.removeAllRanges();
|
||||
sel.addRange(range);
|
||||
};
|
||||
|
||||
const executeCommand = (command: string, arg?: string) => {
|
||||
if (disabled) return;
|
||||
ensureSelectionInsideEditor();
|
||||
document.execCommand(command, false, arg);
|
||||
emitChange();
|
||||
};
|
||||
|
||||
const handleClearFormatting = () => {
|
||||
if (disabled) return;
|
||||
ensureSelectionInsideEditor();
|
||||
document.execCommand('removeFormat', false);
|
||||
document.execCommand('unlink', false);
|
||||
emitChange();
|
||||
};
|
||||
|
||||
const handleOpenLinkDialog = (useActiveAnchor = false) => {
|
||||
if (disabled) return;
|
||||
const el = editorRef.current;
|
||||
if (!el) return;
|
||||
|
||||
const sel = window.getSelection();
|
||||
if (sel && sel.rangeCount > 0 && el.contains(sel.anchorNode)) {
|
||||
savedRangeRef.current = sel.getRangeAt(0).cloneRange();
|
||||
}
|
||||
|
||||
const targetAnchor = useActiveAnchor ? activeAnchorRef.current : activeAnchorRef.current;
|
||||
if (targetAnchor) {
|
||||
editingAnchorRef.current = targetAnchor;
|
||||
setLinkText(targetAnchor.textContent || '');
|
||||
setLinkUrl(targetAnchor.getAttribute('href') || '');
|
||||
} else {
|
||||
editingAnchorRef.current = null;
|
||||
const selectedStr =
|
||||
savedRangeRef.current && el.contains(savedRangeRef.current.commonAncestorContainer)
|
||||
? savedRangeRef.current.toString()
|
||||
: '';
|
||||
setLinkText(selectedStr);
|
||||
setLinkUrl('');
|
||||
}
|
||||
|
||||
setLinkDialogOpen(true);
|
||||
};
|
||||
|
||||
const handleApplyLink = () => {
|
||||
const el = editorRef.current;
|
||||
if (!el) return;
|
||||
|
||||
const rawUrl = linkUrl.trim();
|
||||
if (!rawUrl) {
|
||||
setLinkDialogOpen(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const finalUrl = /^https?:\/\/|^mailto:|^tel:/i.test(rawUrl)
|
||||
? rawUrl
|
||||
: `https://${rawUrl}`;
|
||||
const displayText = linkText.trim() || rawUrl;
|
||||
|
||||
const currentEditingAnchor = editingAnchorRef.current;
|
||||
if (currentEditingAnchor && el.contains(currentEditingAnchor)) {
|
||||
currentEditingAnchor.setAttribute('href', finalUrl);
|
||||
currentEditingAnchor.setAttribute('target', '_blank');
|
||||
currentEditingAnchor.setAttribute('rel', 'noopener noreferrer');
|
||||
currentEditingAnchor.textContent = displayText;
|
||||
} else {
|
||||
el.focus();
|
||||
const sel = window.getSelection();
|
||||
if (sel) {
|
||||
sel.removeAllRanges();
|
||||
if (
|
||||
savedRangeRef.current &&
|
||||
el.contains(savedRangeRef.current.commonAncestorContainer)
|
||||
) {
|
||||
sel.addRange(savedRangeRef.current);
|
||||
} else {
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(el);
|
||||
range.collapse(false);
|
||||
sel.addRange(range);
|
||||
}
|
||||
|
||||
const range = sel.getRangeAt(0);
|
||||
range.deleteContents();
|
||||
|
||||
const anchor = document.createElement('a');
|
||||
anchor.setAttribute('href', finalUrl);
|
||||
anchor.setAttribute('target', '_blank');
|
||||
anchor.setAttribute('rel', 'noopener noreferrer');
|
||||
anchor.textContent = displayText;
|
||||
|
||||
range.insertNode(anchor);
|
||||
|
||||
// Place cursor right after the inserted link
|
||||
range.setStartAfter(anchor);
|
||||
range.setEndAfter(anchor);
|
||||
sel.removeAllRanges();
|
||||
sel.addRange(range);
|
||||
savedRangeRef.current = range.cloneRange();
|
||||
}
|
||||
}
|
||||
|
||||
setLinkDialogOpen(false);
|
||||
editingAnchorRef.current = null;
|
||||
emitChange();
|
||||
};
|
||||
|
||||
const handleUnlinkActive = () => {
|
||||
const el = editorRef.current;
|
||||
const targetAnchor = activeAnchorRef.current;
|
||||
if (!el || !targetAnchor) return;
|
||||
|
||||
const textNode = document.createTextNode(targetAnchor.textContent || '');
|
||||
targetAnchor.parentNode?.replaceChild(textNode, targetAnchor);
|
||||
activeAnchorRef.current = null;
|
||||
setHasActiveAnchor(false);
|
||||
setActiveAnchorHref('');
|
||||
emitChange();
|
||||
};
|
||||
|
||||
const isEmpty = !value || value === '<br>' || value.trim() === '';
|
||||
|
||||
const toolbarBtnClass = (active: boolean) =>
|
||||
`size-8 rounded-full flex items-center justify-center transition-colors ${active
|
||||
? 'bg-zinc-200/90 text-zinc-900 dark:bg-zinc-700 dark:text-zinc-50'
|
||||
: 'text-zinc-600 dark:text-zinc-300 hover:bg-zinc-200/50 dark:hover:bg-zinc-800 hover:text-zinc-900 dark:hover:text-zinc-100'
|
||||
} disabled:opacity-40 disabled:pointer-events-none`;
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
{/* Scoped CSS ensuring bullets, numbers, and blue links ALWAYS render inside the editor and EventList */}
|
||||
<style>{`
|
||||
.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;
|
||||
}
|
||||
`}</style>
|
||||
|
||||
<div className="rounded-lg border border-zinc-200 dark:border-zinc-800 bg-zinc-50/50 dark:bg-zinc-950 overflow-hidden focus-within:border-zinc-400 dark:focus-within:border-zinc-600 transition-colors">
|
||||
{/* Google Calendar Style Toolbar */}
|
||||
<div className="flex flex-wrap items-center gap-0.5 px-2.5 py-1.5 border-b border-zinc-200/80 dark:border-zinc-800 bg-zinc-100/70 dark:bg-zinc-900">
|
||||
<button
|
||||
type="button"
|
||||
onMouseDown={(e) => {
|
||||
e.preventDefault();
|
||||
executeCommand('bold');
|
||||
}}
|
||||
disabled={disabled}
|
||||
title="Bold (Ctrl+B)"
|
||||
className={toolbarBtnClass(formats.bold)}
|
||||
>
|
||||
<Bold className="size-4 stroke-[2.5]" />
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onMouseDown={(e) => {
|
||||
e.preventDefault();
|
||||
executeCommand('italic');
|
||||
}}
|
||||
disabled={disabled}
|
||||
title="Italic (Ctrl+I)"
|
||||
className={toolbarBtnClass(formats.italic)}
|
||||
>
|
||||
<Italic className="size-4 stroke-[2.2]" />
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onMouseDown={(e) => {
|
||||
e.preventDefault();
|
||||
executeCommand('underline');
|
||||
}}
|
||||
disabled={disabled}
|
||||
title="Underline (Ctrl+U)"
|
||||
className={toolbarBtnClass(formats.underline)}
|
||||
>
|
||||
<Underline className="size-4 stroke-[2.2]" />
|
||||
</button>
|
||||
|
||||
<div className="h-5 w-px bg-zinc-300 dark:bg-zinc-700 mx-1.5" />
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onMouseDown={(e) => {
|
||||
e.preventDefault();
|
||||
executeCommand('insertOrderedList');
|
||||
}}
|
||||
disabled={disabled}
|
||||
title="Numbered list"
|
||||
className={toolbarBtnClass(formats.insertOrderedList)}
|
||||
>
|
||||
<ListOrdered className="size-4 stroke-[2.2]" />
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onMouseDown={(e) => {
|
||||
e.preventDefault();
|
||||
executeCommand('insertUnorderedList');
|
||||
}}
|
||||
disabled={disabled}
|
||||
title="Bulleted list"
|
||||
className={toolbarBtnClass(formats.insertUnorderedList)}
|
||||
>
|
||||
<List className="size-4 stroke-[2.2]" />
|
||||
</button>
|
||||
|
||||
<div className="h-5 w-px bg-zinc-300 dark:bg-zinc-700 mx-1.5" />
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onMouseDown={(e) => {
|
||||
e.preventDefault();
|
||||
handleOpenLinkDialog(false);
|
||||
}}
|
||||
disabled={disabled}
|
||||
title="Insert link"
|
||||
className={toolbarBtnClass(linkDialogOpen || hasActiveAnchor)}
|
||||
>
|
||||
<Link2 className="size-4 stroke-[2.2]" />
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onMouseDown={(e) => {
|
||||
e.preventDefault();
|
||||
handleClearFormatting();
|
||||
}}
|
||||
disabled={disabled}
|
||||
title="Clear formatting"
|
||||
className={toolbarBtnClass(false)}
|
||||
>
|
||||
<RemoveFormatting className="size-4 stroke-[2.2]" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Editable Content Area */}
|
||||
<div className="relative min-h-32 max-h-72 overflow-y-auto">
|
||||
{isEmpty && (
|
||||
<div className="pointer-events-none absolute top-4 left-3 text-xs sm:text-sm text-zinc-400 dark:text-zinc-500 select-none">
|
||||
{placeholder}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div
|
||||
ref={editorRef}
|
||||
contentEditable={!disabled}
|
||||
suppressContentEditableWarning
|
||||
onInput={emitChange}
|
||||
onKeyUp={checkActiveFormats}
|
||||
onMouseUp={checkActiveFormats}
|
||||
onBlur={emitChange}
|
||||
className="gcal-rich-content min-h-30 px-3.5 py-3 text-xs sm:text-sm text-zinc-900 dark:text-zinc-100 outline-none leading-relaxed wrap-break-word"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Google Calendar Floating Link Action Pill (when cursor is inside a link) */}
|
||||
{hasActiveAnchor && !linkDialogOpen && (
|
||||
<div className="mt-1.5 inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-zinc-900 text-zinc-100 dark:bg-zinc-800 dark:text-zinc-100 shadow-md border border-zinc-700 text-xs">
|
||||
<a
|
||||
href={activeAnchorHref}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-sky-400 hover:underline truncate max-w-50 flex items-center gap-1"
|
||||
title={activeAnchorHref}
|
||||
>
|
||||
<span className="truncate">{activeAnchorHref}</span>
|
||||
<ExternalLink className="size-3 shrink-0" />
|
||||
</a>
|
||||
<div className="h-3.5 w-px bg-zinc-700" />
|
||||
<button
|
||||
type="button"
|
||||
onMouseDown={(e) => {
|
||||
e.preventDefault();
|
||||
handleOpenLinkDialog(true);
|
||||
}}
|
||||
className="p-1 rounded hover:bg-zinc-700 text-zinc-300 hover:text-white transition-colors"
|
||||
title="Edit link"
|
||||
>
|
||||
<Pencil className="size-3.5" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onMouseDown={(e) => {
|
||||
e.preventDefault();
|
||||
handleUnlinkActive();
|
||||
}}
|
||||
className="p-1 rounded hover:bg-zinc-700 text-zinc-300 hover:text-white transition-colors"
|
||||
title="Remove link"
|
||||
>
|
||||
<X className="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Google Calendar "Edit link" Modal Overlay */}
|
||||
{linkDialogOpen && (
|
||||
<div className="mt-2 p-4 rounded-2xl border border-zinc-200 dark:border-zinc-700 bg-white dark:bg-zinc-900 shadow-lg space-y-3.5">
|
||||
<h4 className="text-sm font-medium text-zinc-900 dark:text-zinc-100">
|
||||
Edit link
|
||||
</h4>
|
||||
|
||||
<div className="space-y-2.5">
|
||||
{/* Text to display */}
|
||||
<div className="flex items-center gap-3">
|
||||
<AlignLeft className="size-4 text-zinc-400 shrink-0" />
|
||||
<input
|
||||
type="text"
|
||||
value={linkText}
|
||||
onChange={(e) => 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"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Link to url address */}
|
||||
<div className="flex items-center gap-3">
|
||||
<Globe className="size-4 text-zinc-400 shrink-0" />
|
||||
<input
|
||||
type="text"
|
||||
value={linkUrl}
|
||||
onChange={(e) => 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"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-end gap-2 pt-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setLinkDialogOpen(false)}
|
||||
className="h-8 px-4 rounded-full text-xs font-medium text-sky-600 dark:text-sky-400 hover:bg-sky-50 dark:hover:bg-sky-950/50 transition-colors"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={!linkUrl.trim()}
|
||||
onClick={handleApplyLink}
|
||||
className="h-8 px-5 rounded-full text-xs font-medium bg-sky-600 hover:bg-sky-500 text-white disabled:bg-zinc-200 disabled:text-zinc-400 dark:disabled:bg-zinc-800 dark:disabled:text-zinc-500 transition-colors"
|
||||
>
|
||||
OK
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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 (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="p-0 overflow-hidden bg-white dark:bg-zinc-950 border-zinc-200 dark:border-zinc-800">
|
||||
{/* Top Colored Strip */}
|
||||
<div className="h-2 w-full" style={{ backgroundColor: displayHex }} />
|
||||
|
||||
<DialogHeader className="p-6 py-4 border-b border-zinc-100 dark:border-zinc-800">
|
||||
<div className="flex items-start gap-3 pr-6">
|
||||
<span
|
||||
className="size-4 rounded-md shrink-0 mt-1 shadow-xs"
|
||||
style={{ backgroundColor: displayHex }}
|
||||
/>
|
||||
<div className="space-y-1.5 min-w-0 flex-1">
|
||||
<DialogTitle className="text-lg font-semibold text-zinc-900 dark:text-zinc-100 leading-snug break-words">
|
||||
{event.summary}
|
||||
</DialogTitle>
|
||||
<DialogDescription className="text-xs text-zinc-600 dark:text-zinc-400 flex items-center gap-1.5">
|
||||
<Clock className="size-3.5 text-zinc-400 shrink-0" />
|
||||
<span>{formatDateRange(event.start, event.end, event.isAllDay)}</span>
|
||||
</DialogDescription>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-1.5 pt-1">
|
||||
{event.isAllDay && (
|
||||
<Badge variant="outline" className="text-[10px] py-0 px-2">
|
||||
Sepanjang Hari (All-Day)
|
||||
</Badge>
|
||||
)}
|
||||
{colorInfo && (
|
||||
<Badge variant="outline" className="text-[10px] py-0 px-2 gap-1 font-normal relative text-white">
|
||||
<div
|
||||
className="size-1.5 rounded-full w-full h-full absolute inset-0"
|
||||
style={{ backgroundColor: displayHex }}
|
||||
/>
|
||||
<span className='relative'>{colorInfo.name}</span>
|
||||
</Badge>
|
||||
)}
|
||||
{event.isReadOnly && (
|
||||
<Badge variant="secondary" className="text-[10px] py-0 px-2 gap-1 font-normal">
|
||||
<Lock className="size-2.5" />
|
||||
Read-only
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</DialogHeader>
|
||||
|
||||
{/* Event Details Body */}
|
||||
<div className="p-6 pt-3 space-y-4 max-h-[65vh] overflow-y-auto text-xs sm:text-sm">
|
||||
{/* Google Meet Button */}
|
||||
{event.hangoutLink && (
|
||||
<div className="flex items-center justify-between p-3 rounded-xl border border-sky-200 dark:border-sky-900/60 bg-sky-50/60 dark:bg-sky-950/30">
|
||||
<div className="flex items-center gap-2.5 min-w-0">
|
||||
<div className="p-2 rounded-lg text-primary shrink-0">
|
||||
<Video className="size-4" />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<p className="text-xs font-semibold text-zinc-900 dark:text-zinc-100">
|
||||
Rapat Video Google Meet
|
||||
</p>
|
||||
<p className="text-[11px] text-zinc-500 dark:text-zinc-400 truncate">
|
||||
{event.hangoutLink}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
asChild
|
||||
size="sm"
|
||||
className="h-8 px-3 text-xs bg-sky-600 hover:bg-sky-700 text-white shrink-0 ml-2"
|
||||
>
|
||||
<a href={event.hangoutLink} target="_blank" rel="noopener noreferrer">
|
||||
Gabung Meet
|
||||
</a>
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Source Calendar */}
|
||||
{event.calendarSummary && (
|
||||
<div className="flex items-start gap-3">
|
||||
<Calendar className="size-4 text-zinc-400 shrink-0 mt-0.5" />
|
||||
<div className="space-y-0.5">
|
||||
<p className="font-medium text-zinc-400 dark:text-zinc-500">
|
||||
Kalender
|
||||
</p>
|
||||
<div className="flex items-center gap-2">
|
||||
<span
|
||||
className="size-2.5 rounded-full shrink-0"
|
||||
style={{ backgroundColor: event.calendarColor || '#039be5' }}
|
||||
/>
|
||||
<span className="text-xs sm:text-sm font-medium text-zinc-800 dark:text-zinc-200">
|
||||
{event.calendarSummary}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Location */}
|
||||
{event.location && (
|
||||
<div className="flex items-start gap-3">
|
||||
<MapPin className="size-4 text-zinc-400 shrink-0 mt-0.5" />
|
||||
<div className="space-y-0.5 min-w-0">
|
||||
<p className="font-medium text-zinc-400 dark:text-zinc-500">
|
||||
Lokasi
|
||||
</p>
|
||||
<p className="text-xs sm:text-sm text-zinc-800 dark:text-zinc-200 break-words">
|
||||
{event.location}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Guests / Attendees */}
|
||||
{guestList.length > 0 && (
|
||||
<div className="flex items-start gap-3">
|
||||
<Users className="size-4 text-zinc-400 shrink-0 mt-0.5" />
|
||||
<div className="space-y-1.5 min-w-0 flex-1">
|
||||
<p className="font-medium text-zinc-400 dark:text-zinc-500">
|
||||
{guestList.length} Tamu (Guests)
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{guestList.map((email) => (
|
||||
<Badge
|
||||
key={email}
|
||||
variant="secondary"
|
||||
className="text-[11px] font-normal bg-zinc-100 dark:bg-zinc-800 text-zinc-800 dark:text-zinc-200"
|
||||
>
|
||||
{email}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Rich HTML Description */}
|
||||
{event.description && (
|
||||
<div className="flex items-start gap-3 pt-1">
|
||||
<AlignLeft className="size-4 text-zinc-400 shrink-0 mt-0.5" />
|
||||
<div className="space-y-1 min-w-0 flex-1">
|
||||
<p className="font-medium text-zinc-400 dark:text-zinc-500">
|
||||
Deskripsi
|
||||
</p>
|
||||
<div
|
||||
className="prose prose-sm dark:prose-invert max-w-none
|
||||
prose-headings:text-foreground prose-headings:font-bold
|
||||
prose-h1:text-xl prose-h1:mb-3 prose-h1:mt-0
|
||||
prose-h2:text-lg prose-h2:mb-2 prose-h2:mt-5
|
||||
prose-p:text-muted-foreground prose-p:leading-relaxed
|
||||
prose-li:text-muted-foreground prose-li:marker:text-primary
|
||||
prose-a:text-blue-500 hover:prose-a:text-his
|
||||
prose-strong:text-foreground
|
||||
prose-ul:my-2 prose-li:my-0.5"
|
||||
dangerouslySetInnerHTML={{ __html: event.description, }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Footer Actions */}
|
||||
<DialogFooter className="p-4 bg-zinc-50 dark:bg-zinc-900/50 border-t border-zinc-100 dark:border-zinc-800 flex flex-row items-center justify-between sm:justify-between gap-2">
|
||||
<div>
|
||||
{event.htmlLink && (
|
||||
<Button
|
||||
asChild
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 px-2.5 text-xs text-zinc-600 dark:text-zinc-400 hover:text-zinc-900 dark:hover:text-zinc-100"
|
||||
>
|
||||
<a href={event.htmlLink} target="_blank" rel="noopener noreferrer">
|
||||
<span>Buka di Google Calendar</span>
|
||||
<ExternalLink className="size-3.5 ml-1.5" />
|
||||
</a>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
{!event.isReadOnly && (
|
||||
<>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
onOpenChange(false);
|
||||
onDelete(event);
|
||||
}}
|
||||
className="h-8 px-3 text-xs border-rose-200 text-rose-600 hover:bg-rose-50 dark:border-rose-900/60 dark:text-rose-400 dark:hover:bg-rose-950/40"
|
||||
>
|
||||
<Trash2 className="size-3.5" />
|
||||
<span>Hapus</span>
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
onOpenChange(false);
|
||||
onEdit(event);
|
||||
}}
|
||||
className="h-8 px-3 text-xs"
|
||||
>
|
||||
<Edit2 className="size-3.5" />
|
||||
<span>Edit Event</span>
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
|
||||
{event.isReadOnly && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => onOpenChange(false)}
|
||||
className="h-8 px-3 text-xs"
|
||||
>
|
||||
Tutup
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,537 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState } from 'react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import DescriptionRichEditor from './DescriptionRichEditor';
|
||||
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, 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,
|
||||
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') : baseDateStr;
|
||||
|
||||
const defaultEnd = event ? event.isAllDay ? dayjs(event.end || event.start).format('YYYY-MM-DD') : dayjs(event.end).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<string>(resolvedDefaultCalId);
|
||||
const [summary, setSummary] = useState(event?.summary || '');
|
||||
const [description, setDescription] = useState(event?.description || '');
|
||||
const [location, setLocation] = useState(event?.location || '');
|
||||
const [isAllDay, setIsAllDay] = useState(initialIsAllDay);
|
||||
const [startDateTime, setStartDateTime] = useState(defaultStart);
|
||||
const [endDateTime, setEndDateTime] = useState(defaultEnd);
|
||||
|
||||
// Fields: colorId, attendees, Google Meet
|
||||
const [colorId, setColorId] = useState<string>(event?.colorId || '');
|
||||
const [attendees, setAttendees] = useState<string[]>(event?.attendees || []);
|
||||
const [guestInput, setGuestInput] = useState('');
|
||||
const [generateMeet, setGenerateMeet] = useState(false);
|
||||
const [manualMeetLink, setManualMeetLink] = useState(event?.hangoutLink || '');
|
||||
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const selectedColorInfo = getEventColorInfo(colorId);
|
||||
|
||||
const handleAddGuest = () => {
|
||||
const raw = guestInput.trim().toLowerCase().replace(/,$/, '');
|
||||
if (!raw) return;
|
||||
|
||||
if (!EMAIL_REGEX.test(raw)) {
|
||||
toast.error(`Format email "${raw}" tidak valid.`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (attendees.includes(raw)) {
|
||||
toast.info(`Email "${raw}" sudah ada di daftar tamu.`);
|
||||
setGuestInput('');
|
||||
return;
|
||||
}
|
||||
|
||||
setAttendees((prev) => [...prev, raw]);
|
||||
setGuestInput('');
|
||||
};
|
||||
|
||||
const handleGuestKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
if (e.key === 'Enter' || e.key === ',') {
|
||||
e.preventDefault();
|
||||
handleAddGuest();
|
||||
}
|
||||
};
|
||||
|
||||
const handleRemoveGuest = (emailToRemove: string) => {
|
||||
setAttendees((prev) => prev.filter((email) => email !== emailToRemove));
|
||||
};
|
||||
|
||||
const handleStartChange = (val: string) => {
|
||||
setStartDateTime(val);
|
||||
if (!val) return;
|
||||
|
||||
if (isAllDay) {
|
||||
if (endDateTime && dayjs(endDateTime).isBefore(dayjs(val), 'day')) {
|
||||
setEndDateTime(dayjs(val).format('YYYY-MM-DD'));
|
||||
}
|
||||
} else {
|
||||
if (endDateTime && !dayjs(endDateTime).isAfter(dayjs(val))) {
|
||||
setEndDateTime(dayjs(val).add(1, 'hour').format('YYYY-MM-DDTHH:mm'));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (!summary.trim()) {
|
||||
toast.error('Judul event wajib diisi!');
|
||||
return;
|
||||
}
|
||||
if (!startDateTime || !endDateTime) {
|
||||
toast.error('Waktu mulai dan selesai wajib diisi!');
|
||||
return;
|
||||
}
|
||||
|
||||
const finalAttendees = [...attendees];
|
||||
const pendingGuest = guestInput.trim().toLowerCase();
|
||||
if (pendingGuest) {
|
||||
if (!EMAIL_REGEX.test(pendingGuest)) {
|
||||
toast.error(`Format email tamu "${pendingGuest}" tidak valid.`);
|
||||
return;
|
||||
}
|
||||
if (!finalAttendees.includes(pendingGuest)) {
|
||||
finalAttendees.push(pendingGuest);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
|
||||
const payload = {
|
||||
calendarId: targetCalendarId || defaultCalendarId || undefined,
|
||||
summary,
|
||||
description,
|
||||
location,
|
||||
startDateTime,
|
||||
endDateTime,
|
||||
isAllDay,
|
||||
colorId: colorId || undefined,
|
||||
attendees: finalAttendees,
|
||||
generateMeet,
|
||||
manualMeetLink: manualMeetLink.trim() || undefined,
|
||||
};
|
||||
|
||||
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!'
|
||||
);
|
||||
if (res.warning) {
|
||||
toast.warning(res.warning, { duration: 6000 });
|
||||
}
|
||||
onClose();
|
||||
onSuccess();
|
||||
} else {
|
||||
toast.error(res.error || 'Gagal menyimpan event.', { duration: 5000 });
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
const msg = err instanceof Error ? err.message : 'Terjadi kesalahan tidak terduga.';
|
||||
toast.error(msg);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="flex flex-col">
|
||||
<DialogHeader className="p-6 pb-4 border-b border-zinc-100 dark:border-zinc-800">
|
||||
<DialogTitle className="text-lg font-semibold text-zinc-900 dark:text-zinc-100">
|
||||
{isEdit ? 'Edit Event Google Calendar' : 'Tambah Event Baru'}
|
||||
</DialogTitle>
|
||||
<DialogDescription className="text-xs text-zinc-500 dark:text-zinc-400">
|
||||
Perubahan akan langsung disinkronkan ke kalender Google secara real-time.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="p-6 space-y-4 max-h-[70vh] overflow-y-auto">
|
||||
{/* Target Calendar Selector (when multiple writable calendars exist) */}
|
||||
{writableCalendars.length > 0 && (
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="target-calendar" className="text-xs font-semibold text-zinc-700 dark:text-zinc-300 flex items-center gap-1.5">
|
||||
<CalendarIcon className="size-3.5 text-zinc-500" />
|
||||
<span>Simpan ke Kalender</span>
|
||||
</Label>
|
||||
<select
|
||||
id="target-calendar"
|
||||
value={targetCalendarId}
|
||||
onChange={(e) => setTargetCalendarId(e.target.value)}
|
||||
disabled={loading || isEdit}
|
||||
className="h-9 w-full rounded-md border border-zinc-200 dark:border-zinc-800 bg-white dark:bg-zinc-950 px-3 text-xs sm:text-sm text-zinc-900 dark:text-zinc-100 outline-none focus:ring-2 focus:ring-zinc-400 disabled:opacity-60"
|
||||
>
|
||||
{writableCalendars.map((cal) => (
|
||||
<option key={cal.id} value={cal.id}>
|
||||
{cal.summary} {cal.isDefaultEnv ? '(Default .env)' : cal.primary ? '(Utama)' : ''}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Summary */}
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="event-summary" className="text-xs font-semibold text-zinc-700 dark:text-zinc-300">
|
||||
Judul Event <span className="text-rose-500">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="event-summary"
|
||||
placeholder="misal: Rapat Koordinasi Tim Project"
|
||||
value={summary}
|
||||
onChange={(e) => setSummary(e.target.value)}
|
||||
disabled={loading}
|
||||
required
|
||||
autoFocus
|
||||
className="h-9 text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* All Day Toggle */}
|
||||
<div className="flex items-center justify-between p-3 rounded-lg bg-zinc-50 dark:bg-zinc-900/60 border border-zinc-200/80 dark:border-zinc-800">
|
||||
<div className="space-y-0.5">
|
||||
<Label htmlFor="all-day-toggle" className="text-xs font-semibold text-zinc-800 dark:text-zinc-200 cursor-pointer">
|
||||
Acara Sepanjang Hari (All Day)
|
||||
</Label>
|
||||
<p className="text-[11px] text-zinc-500">
|
||||
Menggunakan format tanggal harian (YYYY-MM-DD) tanpa jam spesifik
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
id="all-day-toggle"
|
||||
checked={isAllDay}
|
||||
onCheckedChange={(checked) => {
|
||||
setIsAllDay(checked);
|
||||
if (checked) {
|
||||
const startDay = startDateTime.split('T')[0] || dayjs().format('YYYY-MM-DD');
|
||||
const endDay = endDateTime.split('T')[0] || startDay;
|
||||
setStartDateTime(startDay);
|
||||
setEndDateTime(dayjs(endDay).isBefore(dayjs(startDay), 'day') ? startDay : endDay);
|
||||
} else {
|
||||
const baseDay = startDateTime.split('T')[0] || dayjs().format('YYYY-MM-DD');
|
||||
const startFull = dayjs(`${baseDay}T09:00`).format('YYYY-MM-DDTHH:mm');
|
||||
const endFull = dayjs(`${baseDay}T10:00`).format('YYYY-MM-DDTHH:mm');
|
||||
setStartDateTime(startFull);
|
||||
setEndDateTime(endFull);
|
||||
}
|
||||
}}
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Dates: Start & End */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="event-start" className="text-xs font-semibold text-zinc-700 dark:text-zinc-300">
|
||||
{isAllDay ? 'Tanggal Mulai' : 'Waktu Mulai'} <span className="text-rose-500">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="event-start"
|
||||
type={isAllDay ? 'date' : 'datetime-local'}
|
||||
value={startDateTime}
|
||||
onChange={(e) => handleStartChange(e.target.value)}
|
||||
disabled={loading}
|
||||
required
|
||||
className="h-9 text-xs sm:text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="event-end" className="text-xs font-semibold text-zinc-700 dark:text-zinc-300">
|
||||
{isAllDay ? 'Tanggal Selesai (Inklusif)' : 'Waktu Selesai'} <span className="text-rose-500">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="event-end"
|
||||
type={isAllDay ? 'date' : 'datetime-local'}
|
||||
value={endDateTime}
|
||||
min={startDateTime}
|
||||
onChange={(e) => setEndDateTime(e.target.value)}
|
||||
disabled={loading}
|
||||
required
|
||||
className="h-9 text-xs sm:text-sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Event Color Picker (colorId 1 - 11) */}
|
||||
<div className="space-y-2 p-3 rounded-lg border border-zinc-200 dark:border-zinc-800 bg-white dark:bg-zinc-900/40">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label className="text-xs font-semibold text-zinc-700 dark:text-zinc-300 flex items-center gap-1.5">
|
||||
<Palette className="size-3.5 text-zinc-500" />
|
||||
<span>Warna Event (colorId)</span>
|
||||
</Label>
|
||||
<span className="text-[11px] font-medium text-zinc-500 dark:text-zinc-400">
|
||||
{selectedColorInfo
|
||||
? `${selectedColorInfo.id} - ${selectedColorInfo.name}`
|
||||
: 'Default Kalender'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2 pt-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setColorId('')}
|
||||
disabled={loading}
|
||||
title="Default Kalender"
|
||||
className={`h-6 px-2 rounded-full text-[11px] font-medium border transition-all flex items-center gap-1 ${colorId === ''
|
||||
? 'border-zinc-900 dark:border-zinc-100 bg-zinc-900 text-white dark:bg-zinc-100 dark:text-zinc-900'
|
||||
: 'border-zinc-300 dark:border-zinc-700 text-zinc-600 dark:text-zinc-400 hover:bg-zinc-100 dark:hover:bg-zinc-800'
|
||||
}`}
|
||||
>
|
||||
Default
|
||||
</button>
|
||||
|
||||
{GOOGLE_EVENT_COLORS.map((color) => {
|
||||
const isSelected = colorId === color.id;
|
||||
return (
|
||||
<button
|
||||
key={color.id}
|
||||
type="button"
|
||||
onClick={() => setColorId(color.id)}
|
||||
disabled={loading}
|
||||
title={`${color.id}: ${color.name}`}
|
||||
style={{ backgroundColor: color.hex }}
|
||||
className={`size-6 rounded-full flex items-center justify-center transition-transform ${isSelected
|
||||
? 'ring-2 ring-offset-2 ring-zinc-900 dark:ring-zinc-100 dark:ring-offset-zinc-950 scale-110'
|
||||
: 'opacity-85 hover:opacity-100 hover:scale-105'
|
||||
}`}
|
||||
>
|
||||
{isSelected && <Check className="size-3.5 text-white stroke-[3]" />}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Add Guest (attendees) */}
|
||||
<div className="space-y-2 p-3 rounded-lg border border-zinc-200 dark:border-zinc-800 bg-white dark:bg-zinc-900/40">
|
||||
<Label htmlFor="event-guest-input" className="text-xs font-semibold text-zinc-700 dark:text-zinc-300 flex items-center gap-1.5">
|
||||
<Users className="size-3.5 text-zinc-500" />
|
||||
<span>Tambah Tamu / Peserta (Attendees)</span>
|
||||
</Label>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
id="event-guest-input"
|
||||
type="email"
|
||||
placeholder="Ketik email tamu lalu tekan Enter / Tambah..."
|
||||
value={guestInput}
|
||||
onChange={(e) => setGuestInput(e.target.value)}
|
||||
onKeyDown={handleGuestKeyDown}
|
||||
disabled={loading}
|
||||
className="h-8 text-xs flex-1"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleAddGuest}
|
||||
disabled={loading || !guestInput.trim()}
|
||||
className="h-8 px-2.5 text-xs shrink-0"
|
||||
>
|
||||
<Plus className="size-3.5 mr-1" />
|
||||
Tambah
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{attendees.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1.5 pt-1">
|
||||
{attendees.map((email) => (
|
||||
<Badge
|
||||
key={email}
|
||||
variant="secondary"
|
||||
className="text-[11px] py-0.5 pl-2 pr-1 gap-1 font-normal bg-zinc-100 dark:bg-zinc-800 text-zinc-800 dark:text-zinc-200"
|
||||
>
|
||||
<span className="truncate max-w-[210px]">{email}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleRemoveGuest(email)}
|
||||
disabled={loading}
|
||||
className="p-0.5 rounded-full hover:bg-zinc-300 dark:hover:bg-zinc-700 text-zinc-500 hover:text-zinc-900 dark:hover:text-zinc-100"
|
||||
title={`Hapus ${email}`}
|
||||
>
|
||||
<X className="size-3" />
|
||||
</button>
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Google Meet (conferenceData / hangoutLink) */}
|
||||
<div className="space-y-3 p-3 rounded-lg border border-zinc-200 dark:border-zinc-800 bg-white dark:bg-zinc-900/40">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<div className="space-y-0.5">
|
||||
<Label htmlFor="meet-toggle" className="text-xs font-semibold text-zinc-800 dark:text-zinc-200 flex items-center gap-1.5 cursor-pointer">
|
||||
<Video className="size-3.5 text-sky-600 dark:text-sky-400" />
|
||||
<span>Generate Link Google Meet Otomatis</span>
|
||||
</Label>
|
||||
<p className="text-[11px] text-zinc-500">
|
||||
Mengirim <code className="text-[10px]">conferenceData.createRequest</code> (<code className="text-[10px]">conferenceDataVersion: 1</code>)
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
id="meet-toggle"
|
||||
checked={generateMeet}
|
||||
onCheckedChange={setGenerateMeet}
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5 pt-1 border-t border-zinc-100 dark:border-zinc-800/80">
|
||||
<Label htmlFor="manual-meet-link" className="text-[11px] font-medium text-zinc-600 dark:text-zinc-400">
|
||||
Link Google Meet Manual (Fallback / Custom Meet URL)
|
||||
</Label>
|
||||
<Input
|
||||
id="manual-meet-link"
|
||||
type="url"
|
||||
placeholder="https://meet.google.com/xxx-xxxx-xxx (opsional)"
|
||||
value={manualMeetLink}
|
||||
onChange={(e) => setManualMeetLink(e.target.value)}
|
||||
disabled={loading}
|
||||
className="h-8 text-xs"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Location */}
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="event-location" className="text-xs font-semibold text-zinc-700 dark:text-zinc-300">
|
||||
Lokasi / Ruangan (Opsional)
|
||||
</Label>
|
||||
<Input
|
||||
id="event-location"
|
||||
placeholder="misal: Ruang Meeting Lantai 2"
|
||||
value={location}
|
||||
onChange={(e) => setLocation(e.target.value)}
|
||||
disabled={loading}
|
||||
className="h-9 text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Description */}
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs font-semibold text-zinc-700 dark:text-zinc-300">
|
||||
Deskripsi / Catatan (Opsional)
|
||||
</Label>
|
||||
<DescriptionRichEditor
|
||||
value={description}
|
||||
onChange={setDescription}
|
||||
disabled={loading}
|
||||
placeholder="Add description"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter className="p-4 bg-zinc-50 dark:bg-zinc-900/50 border-t border-zinc-100 dark:border-zinc-800 flex items-center justify-end gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={onClose}
|
||||
disabled={loading}
|
||||
>
|
||||
Batal
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
size="sm"
|
||||
disabled={loading}
|
||||
className="bg-zinc-900 hover:bg-zinc-800 text-white dark:bg-zinc-100 dark:hover:bg-zinc-200 dark:text-zinc-900"
|
||||
>
|
||||
{loading && <Loader2 className="size-3.5 mr-1.5 animate-spin" />}
|
||||
{isEdit ? 'Simpan Perubahan' : 'Buat Event'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
export default function EventFormModal({
|
||||
open,
|
||||
onOpenChange,
|
||||
event,
|
||||
initialDate,
|
||||
defaultCalendarId,
|
||||
calendars,
|
||||
onSuccess,
|
||||
}: EventFormModalProps) {
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="p-0 overflow-hidden bg-white dark:bg-zinc-950 border-zinc-200 dark:border-zinc-800">
|
||||
{open && (
|
||||
<EventFormInner
|
||||
key={`${event?.id || 'new'}-${initialDate || ''}`}
|
||||
event={event}
|
||||
initialDate={initialDate}
|
||||
defaultCalendarId={defaultCalendarId}
|
||||
calendars={calendars}
|
||||
onClose={() => onOpenChange(false)}
|
||||
onSuccess={onSuccess}
|
||||
/>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState } from 'react';
|
||||
import { CalendarEventItem } from '@/lib/google-calendar/types';
|
||||
import { getEventColorInfo } from '@/lib/google-calendar/constants';
|
||||
import {
|
||||
Calendar,
|
||||
MapPin,
|
||||
Clock,
|
||||
Edit2,
|
||||
Trash2,
|
||||
ExternalLink,
|
||||
Search,
|
||||
Users,
|
||||
Video,
|
||||
} from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { sanitizeCalendarHtml } from './DescriptionRichEditor';
|
||||
import dayjs from 'dayjs';
|
||||
|
||||
interface EventListProps {
|
||||
events: CalendarEventItem[];
|
||||
onEdit: (event: CalendarEventItem) => void;
|
||||
onDelete: (event: CalendarEventItem) => void;
|
||||
onAddEvent: () => void;
|
||||
}
|
||||
|
||||
export default function EventList({
|
||||
events,
|
||||
onEdit,
|
||||
onDelete,
|
||||
onAddEvent,
|
||||
}: EventListProps) {
|
||||
const [search, setSearch] = useState('');
|
||||
|
||||
const filtered = events.filter((e) => {
|
||||
const q = search.toLowerCase();
|
||||
const guestMatch = e.attendees?.some((guest) => guest.toLowerCase().includes(q));
|
||||
return (
|
||||
e.summary.toLowerCase().includes(q) ||
|
||||
Boolean(e.description && e.description.toLowerCase().includes(q)) ||
|
||||
Boolean(e.location && e.location.toLowerCase().includes(q)) ||
|
||||
Boolean(guestMatch)
|
||||
);
|
||||
});
|
||||
|
||||
const formatDateRange = (startStr: string, endStr: string, isAllDay: boolean) => {
|
||||
if (!startStr) return '-';
|
||||
if (isAllDay) {
|
||||
const s = dayjs(startStr).format('DD MMM YYYY');
|
||||
const e =
|
||||
endStr && endStr !== startStr ? ` - ${dayjs(endStr).format('DD MMM YYYY')}` : '';
|
||||
return `${s}${e} (Sepanjang Hari)`;
|
||||
}
|
||||
const s = dayjs(startStr).format('DD MMM YYYY, HH:mm');
|
||||
const sameDay = dayjs(startStr).isSame(dayjs(endStr), 'day');
|
||||
const e = endStr
|
||||
? sameDay
|
||||
? dayjs(endStr).format('HH:mm')
|
||||
: dayjs(endStr).format('DD MMM YYYY, HH:mm')
|
||||
: '';
|
||||
return `${s} s/d ${e} WIB`;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Search Bar */}
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="relative flex-1 max-w-sm">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-zinc-400 pointer-events-none" />
|
||||
<Input
|
||||
placeholder="Cari event (judul, lokasi, tamu, deskripsi)..."
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
className="pl-9 h-9 text-xs sm:text-sm bg-white dark:bg-zinc-900 border-zinc-200 dark:border-zinc-800"
|
||||
/>
|
||||
</div>
|
||||
<span className="text-xs text-zinc-500 font-medium">
|
||||
{filtered.length} dari {events.length} event
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* List Container */}
|
||||
{filtered.length === 0 ? (
|
||||
<div className="rounded-xl border border-dashed border-zinc-300 dark:border-zinc-800 p-8 text-center bg-zinc-50/50 dark:bg-zinc-900/30">
|
||||
<Calendar className="size-10 text-zinc-400 mx-auto mb-3 stroke-[1.5]" />
|
||||
<h3 className="text-sm font-semibold text-zinc-800 dark:text-zinc-200">
|
||||
{events.length === 0
|
||||
? 'Belum Ada Event di Google Calendar'
|
||||
: 'Tidak Ada Event yang Sesuai Pencarian'}
|
||||
</h3>
|
||||
<p className="text-xs text-zinc-500 max-w-sm mx-auto mt-1 mb-4">
|
||||
{events.length === 0
|
||||
? 'Tambahkan event baru untuk melakukan uji coba sinkronisasi ke Google Calendar web.'
|
||||
: 'Coba ubah kata kunci pencarian Anda.'}
|
||||
</p>
|
||||
{events.length === 0 && (
|
||||
<Button size="sm" onClick={onAddEvent} className="h-9">
|
||||
Tambah Event Pertama
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2.5">
|
||||
{filtered.map((item) => {
|
||||
const colorInfo = getEventColorInfo(item.colorId);
|
||||
const guestList = item.attendees || [];
|
||||
|
||||
return (
|
||||
<div
|
||||
key={item.id}
|
||||
style={
|
||||
colorInfo
|
||||
? { borderLeftColor: colorInfo.hex, borderLeftWidth: '4px' }
|
||||
: undefined
|
||||
}
|
||||
className="group flex flex-col md:flex-row md:items-center justify-between p-4 rounded-xl border border-zinc-200 dark:border-zinc-800/80 bg-white dark:bg-zinc-900 hover:border-zinc-300 dark:hover:border-zinc-700 transition-colors shadow-xs gap-3"
|
||||
>
|
||||
{/* Event Info */}
|
||||
<div className="space-y-1.5 flex-1 min-w-0">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span
|
||||
className="size-2.5 rounded-full shrink-0"
|
||||
style={{ backgroundColor: colorInfo?.hex || '#039be5' }}
|
||||
title={
|
||||
colorInfo
|
||||
? `Warna: ${colorInfo.name} (ID ${colorInfo.id})`
|
||||
: 'Warna Default Kalender'
|
||||
}
|
||||
/>
|
||||
<h4 className="font-semibold text-sm sm:text-base text-zinc-900 dark:text-zinc-100 truncate">
|
||||
{item.summary}
|
||||
</h4>
|
||||
|
||||
{item.isAllDay && (
|
||||
<Badge variant="outline" className="text-[10px] py-0 px-1.5">
|
||||
All-Day
|
||||
</Badge>
|
||||
)}
|
||||
|
||||
{colorInfo && (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="text-[10px] py-0 px-1.5 gap-1 font-normal border-zinc-200 dark:border-zinc-700"
|
||||
>
|
||||
<span
|
||||
className="size-1.5 rounded-full"
|
||||
style={{ backgroundColor: colorInfo.hex }}
|
||||
/>
|
||||
{colorInfo.name}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Date, Location & Guest Count */}
|
||||
<div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-zinc-500 dark:text-zinc-400">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Clock className="size-3.5 text-zinc-400" />
|
||||
<span>{formatDateRange(item.start, item.end, item.isAllDay)}</span>
|
||||
</div>
|
||||
|
||||
{item.location && (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<MapPin className="size-3.5 text-zinc-400" />
|
||||
<span className="truncate max-w-[220px]">{item.location}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{guestList.length > 0 && (
|
||||
<div
|
||||
className="flex items-center gap-1.5 text-zinc-600 dark:text-zinc-300"
|
||||
title={`Tamu: ${guestList.join(', ')}`}
|
||||
>
|
||||
<Users className="size-3.5 text-zinc-400" />
|
||||
<span>{guestList.length} Tamu</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Guest Email Badges */}
|
||||
{guestList.length > 0 && (
|
||||
<div className="flex flex-wrap items-center gap-1 pt-0.5">
|
||||
{guestList.slice(0, 3).map((email) => (
|
||||
<Badge
|
||||
key={email}
|
||||
variant="secondary"
|
||||
className="text-[10px] py-0 px-1.5 font-normal bg-zinc-100 dark:bg-zinc-800 text-zinc-700 dark:text-zinc-300"
|
||||
>
|
||||
{email}
|
||||
</Badge>
|
||||
))}
|
||||
{guestList.length > 3 && (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="text-[10px] py-0 px-1.5 font-normal"
|
||||
title={guestList.slice(3).join(', ')}
|
||||
>
|
||||
+{guestList.length - 3} lainnya
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{item.description && (
|
||||
<div
|
||||
className="gcal-rich-content text-xs text-zinc-600 dark:text-zinc-300 pt-1 leading-relaxed break-words"
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: sanitizeCalendarHtml(item.description),
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Action Buttons */}
|
||||
<div className="flex flex-wrap items-center gap-1.5 self-end md:self-center shrink-0 pt-2 md:pt-0 border-t md:border-t-0 border-zinc-100 dark:border-zinc-800/60 w-full md:w-auto justify-end">
|
||||
{item.hangoutLink && (
|
||||
<Button
|
||||
asChild
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-8 px-2.5 text-xs border-sky-200 bg-sky-50/60 text-sky-700 hover:bg-sky-100 dark:border-sky-900/60 dark:bg-sky-950/40 dark:text-sky-300 dark:hover:bg-sky-900/60"
|
||||
>
|
||||
<a href={item.hangoutLink} target="_blank" rel="noopener noreferrer">
|
||||
<Video className="size-3.5 mr-1.5" />
|
||||
<span>Google Meet</span>
|
||||
</a>
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{item.htmlLink && (
|
||||
<Button
|
||||
asChild
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 w-8 p-0 text-zinc-500 hover:text-zinc-800 dark:hover:text-zinc-200"
|
||||
title="Buka di Google Calendar"
|
||||
>
|
||||
<a href={item.htmlLink} target="_blank" rel="noopener noreferrer">
|
||||
<ExternalLink className="size-3.5" />
|
||||
</a>
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => onEdit(item)}
|
||||
className="h-8 px-2.5 text-xs text-zinc-700 dark:text-zinc-300 hover:bg-zinc-100 dark:hover:bg-zinc-800"
|
||||
>
|
||||
<Edit2 className="size-3 mr-1" />
|
||||
<span>Edit</span>
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => onDelete(item)}
|
||||
className="h-8 px-2.5 text-xs border-rose-200 text-rose-600 hover:bg-rose-50 dark:border-rose-900/60 dark:text-rose-400 dark:hover:bg-rose-950/40"
|
||||
>
|
||||
<Trash2 className="size-3 mr-1" />
|
||||
<span>Hapus</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState, useTransition } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import {
|
||||
CalendarEventItem,
|
||||
GoogleCalendarListEntry,
|
||||
} from '@/lib/google-calendar/types';
|
||||
import { getAllCalendarsEvents } from '@/lib/google-calendar/events.actions';
|
||||
import CalendarHeader from './CalendarHeader';
|
||||
import ApiNoticeBanner from './ApiNoticeBanner';
|
||||
import MonthlyCalendarGrid from './MonthlyCalendarGrid';
|
||||
import EventDetailModal from './EventDetailModal';
|
||||
import EventFormModal from './EventFormModal';
|
||||
import DeleteConfirmDialog from './DeleteConfirmDialog';
|
||||
import dayjs, { Dayjs } from 'dayjs';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
interface IntegratedCalendarClientProps {
|
||||
initialCalendars: GoogleCalendarListEntry[];
|
||||
initialEvents: CalendarEventItem[];
|
||||
defaultCalendarId: string;
|
||||
serviceAccountEmail: string;
|
||||
initialError?: string | null;
|
||||
}
|
||||
|
||||
export default function IntegratedCalendarClient({
|
||||
initialCalendars,
|
||||
initialEvents,
|
||||
defaultCalendarId,
|
||||
serviceAccountEmail,
|
||||
initialError,
|
||||
}: IntegratedCalendarClientProps) {
|
||||
const router = useRouter();
|
||||
const [isPending, startTransition] = useTransition();
|
||||
|
||||
// Month & Multi-Calendar State
|
||||
const [currentMonth, setCurrentMonth] = useState<Dayjs>(() => dayjs());
|
||||
const [calendars, setCalendars] = useState<GoogleCalendarListEntry[]>(initialCalendars);
|
||||
const [selectedCalendarIds, setSelectedCalendarIds] = useState<string[]>(() => initialCalendars.map((c) => c.id));
|
||||
const [events, setEvents] = useState<CalendarEventItem[]>(initialEvents);
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(initialError || null);
|
||||
|
||||
// Modals State
|
||||
const [detailModalOpen, setDetailModalOpen] = useState(false);
|
||||
const [eventModalOpen, setEventModalOpen] = useState(false);
|
||||
const [selectedEvent, setSelectedEvent] = useState<CalendarEventItem | null>(null);
|
||||
const [initialFormDate, setInitialFormDate] = useState<string | null>(null);
|
||||
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [deleteItem, setDeleteItem] = useState<{
|
||||
id: string;
|
||||
title: string;
|
||||
type: 'event' | 'task';
|
||||
calendarId?: string;
|
||||
} | null>(null);
|
||||
|
||||
// Fetch events for a given month across all calendars
|
||||
const fetchMonthEvents = (targetMonth: Dayjs, showToast = false) => {
|
||||
startTransition(async () => {
|
||||
try {
|
||||
const timeMin = targetMonth
|
||||
.startOf('month')
|
||||
.subtract(7, 'day')
|
||||
.toISOString();
|
||||
const timeMax = targetMonth
|
||||
.endOf('month')
|
||||
.add(14, 'day')
|
||||
.toISOString();
|
||||
|
||||
const res = await getAllCalendarsEvents({ timeMin, timeMax });
|
||||
|
||||
if (res.success && res.data) {
|
||||
setCalendars(res.data.calendars);
|
||||
setEvents(res.data.events);
|
||||
setErrorMessage(null);
|
||||
|
||||
// Ensure any newly discovered calendar is also checked by default
|
||||
setSelectedCalendarIds((prev) => {
|
||||
if (prev.length === 0 && res.data!.calendars.length > 0) {
|
||||
return res.data!.calendars.map((c) => c.id);
|
||||
}
|
||||
return prev;
|
||||
});
|
||||
|
||||
if (showToast) {
|
||||
toast.info('Data kalender berhasil dimuat ulang.');
|
||||
}
|
||||
} else if (res.error) {
|
||||
setErrorMessage(res.error);
|
||||
}
|
||||
|
||||
router.refresh();
|
||||
} catch (err: unknown) {
|
||||
const msg = err instanceof Error ? err.message : 'Gagal memuat ulang data kalender.';
|
||||
toast.error(msg);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const handleMonthChange = (newMonth: Dayjs) => {
|
||||
setCurrentMonth(newMonth);
|
||||
fetchMonthEvents(newMonth, false);
|
||||
};
|
||||
|
||||
const handleRefresh = () => {
|
||||
fetchMonthEvents(currentMonth, true);
|
||||
};
|
||||
|
||||
// Calendar Filter Checkbox Handlers
|
||||
const handleToggleCalendar = (calId: string) => {
|
||||
setSelectedCalendarIds((prev) =>
|
||||
prev.includes(calId) ? prev.filter((id) => id !== calId) : [...prev, calId]
|
||||
);
|
||||
};
|
||||
|
||||
const handleSelectAllCalendars = (selectAll: boolean) => {
|
||||
setSelectedCalendarIds(selectAll ? calendars.map((c) => c.id) : []);
|
||||
};
|
||||
|
||||
// Event Grid Interaction Handlers
|
||||
const handleAddEventFromButton = () => {
|
||||
setSelectedEvent(null);
|
||||
setInitialFormDate(dayjs().format('YYYY-MM-DD'));
|
||||
setEventModalOpen(true);
|
||||
};
|
||||
|
||||
const handleSelectEmptyDate = (dateStr: string) => {
|
||||
setSelectedEvent(null);
|
||||
setInitialFormDate(dateStr);
|
||||
setEventModalOpen(true);
|
||||
};
|
||||
|
||||
const handleSelectEvent = (event: CalendarEventItem) => {
|
||||
setSelectedEvent(event);
|
||||
setDetailModalOpen(true);
|
||||
};
|
||||
|
||||
const handleEditEvent = (event: CalendarEventItem) => {
|
||||
setSelectedEvent(event);
|
||||
setInitialFormDate(null);
|
||||
setEventModalOpen(true);
|
||||
};
|
||||
|
||||
const handleDeleteEvent = (event: CalendarEventItem) => {
|
||||
setDeleteItem({
|
||||
id: event.id,
|
||||
title: event.summary,
|
||||
type: 'event',
|
||||
calendarId: event.calendarId,
|
||||
});
|
||||
setDeleteDialogOpen(true);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6 p-4 sm:p-6 lg:p-8 max-w-7xl mx-auto">
|
||||
{/* Header */}
|
||||
<CalendarHeader
|
||||
calendarId={defaultCalendarId}
|
||||
serviceAccountEmail={serviceAccountEmail}
|
||||
onRefresh={handleRefresh}
|
||||
onAddEvent={handleAddEventFromButton}
|
||||
isRefreshing={isPending}
|
||||
/>
|
||||
|
||||
{/* Error / API Disabled Notice */}
|
||||
<ApiNoticeBanner error={errorMessage} />
|
||||
|
||||
{/* Monthly Grid View with Multi-Calendar Filter */}
|
||||
<MonthlyCalendarGrid
|
||||
currentMonth={currentMonth}
|
||||
onMonthChange={handleMonthChange}
|
||||
calendars={calendars}
|
||||
selectedCalendarIds={selectedCalendarIds}
|
||||
onToggleCalendar={handleToggleCalendar}
|
||||
onSelectAllCalendars={handleSelectAllCalendars}
|
||||
events={events}
|
||||
onSelectEvent={handleSelectEvent}
|
||||
onSelectEmptyDate={handleSelectEmptyDate}
|
||||
isLoadingMonth={isPending}
|
||||
/>
|
||||
|
||||
{/* Event Detail Modal (on clicking an event in the grid) */}
|
||||
<EventDetailModal
|
||||
open={detailModalOpen}
|
||||
onOpenChange={setDetailModalOpen}
|
||||
event={selectedEvent}
|
||||
onEdit={handleEditEvent}
|
||||
onDelete={handleDeleteEvent}
|
||||
/>
|
||||
|
||||
{/* Event Create / Edit Modal */}
|
||||
<EventFormModal
|
||||
open={eventModalOpen}
|
||||
onOpenChange={setEventModalOpen}
|
||||
event={selectedEvent}
|
||||
initialDate={initialFormDate}
|
||||
defaultCalendarId={defaultCalendarId}
|
||||
calendars={calendars}
|
||||
onSuccess={() => fetchMonthEvents(currentMonth, false)}
|
||||
/>
|
||||
|
||||
{/* Delete Confirmation Dialog */}
|
||||
<DeleteConfirmDialog
|
||||
open={deleteDialogOpen}
|
||||
onOpenChange={setDeleteDialogOpen}
|
||||
item={deleteItem}
|
||||
onSuccess={() => fetchMonthEvents(currentMonth, false)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,692 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState, useMemo } from 'react';
|
||||
import {
|
||||
CalendarEventItem,
|
||||
GoogleCalendarListEntry,
|
||||
} from '@/lib/google-calendar/types';
|
||||
import { getEventColorInfo } from '@/lib/google-calendar/constants';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
Plus,
|
||||
Check,
|
||||
Lock,
|
||||
Loader2,
|
||||
Clock,
|
||||
Video,
|
||||
Calendar as CalendarIcon,
|
||||
} from 'lucide-react';
|
||||
import dayjs, { Dayjs } from 'dayjs';
|
||||
|
||||
interface MonthlyCalendarGridProps {
|
||||
currentMonth: Dayjs;
|
||||
onMonthChange: (newMonth: Dayjs) => void;
|
||||
calendars: GoogleCalendarListEntry[];
|
||||
selectedCalendarIds: string[];
|
||||
onToggleCalendar: (calendarId: string) => void;
|
||||
onSelectAllCalendars: (selectAll: boolean) => void;
|
||||
events: CalendarEventItem[];
|
||||
onSelectEvent: (event: CalendarEventItem) => void;
|
||||
onSelectEmptyDate: (dateStr: string) => void;
|
||||
isLoadingMonth?: boolean;
|
||||
}
|
||||
|
||||
interface WeekEventSegment {
|
||||
event: CalendarEventItem;
|
||||
startCol: number; // 0..6
|
||||
endCol: number; // 0..6
|
||||
span: number; // 1..7
|
||||
lane: number; // 0, 1, 2...
|
||||
isBar: boolean; // true if all-day or multi-day
|
||||
continuesBefore: boolean;
|
||||
continuesAfter: boolean;
|
||||
}
|
||||
|
||||
const WEEKDAYS = [
|
||||
{ short: 'MIN', full: 'Minggu' },
|
||||
{ short: 'SEN', full: 'Senin' },
|
||||
{ short: 'SEL', full: 'Selasa' },
|
||||
{ short: 'RAB', full: 'Rabu' },
|
||||
{ short: 'KAM', full: 'Kamis' },
|
||||
{ short: 'JUM', full: 'Jumat' },
|
||||
{ short: 'SAB', full: 'Sabtu' },
|
||||
];
|
||||
|
||||
const MAX_VISIBLE_LANES = 3;
|
||||
const LANE_HEIGHT_PX = 28;
|
||||
const DATE_HEADER_HEIGHT_PX = 38;
|
||||
const ROW_MIN_HEIGHT_PX = 152;
|
||||
|
||||
/**
|
||||
* Formats time in Google Calendar compact style: "10am", "1:30pm", "2pm"
|
||||
*/
|
||||
function formatGCalShortTime(isoStr: string): string {
|
||||
const d = dayjs(isoStr);
|
||||
if (!d.isValid()) return '';
|
||||
return d.minute() === 0 ? d.format('ha') : d.format('h:mma');
|
||||
}
|
||||
|
||||
export default function MonthlyCalendarGrid({
|
||||
currentMonth,
|
||||
onMonthChange,
|
||||
calendars,
|
||||
selectedCalendarIds,
|
||||
onToggleCalendar,
|
||||
onSelectAllCalendars,
|
||||
events,
|
||||
onSelectEvent,
|
||||
onSelectEmptyDate,
|
||||
isLoadingMonth = false,
|
||||
}: MonthlyCalendarGridProps) {
|
||||
const [moreEventsDate, setMoreEventsDate] = useState<string | null>(null);
|
||||
|
||||
const todayStr = dayjs().format('YYYY-MM-DD');
|
||||
|
||||
// Filter events by checked calendars
|
||||
const visibleEvents = useMemo(() => {
|
||||
const selectedSet = new Set(selectedCalendarIds);
|
||||
return events.filter((ev) => {
|
||||
if (!ev.calendarId) return true;
|
||||
return selectedSet.has(ev.calendarId);
|
||||
});
|
||||
}, [events, selectedCalendarIds]);
|
||||
|
||||
// Build weeks array (5 or 6 weeks dynamically matching Google Calendar)
|
||||
const weeks = useMemo(() => {
|
||||
const startOfMonth = currentMonth.startOf('month');
|
||||
const endOfMonth = currentMonth.endOf('month');
|
||||
|
||||
const firstGridDay = startOfMonth.subtract(startOfMonth.day(), 'day');
|
||||
const lastGridDay = endOfMonth.add(6 - endOfMonth.day(), 'day');
|
||||
const totalDays = lastGridDay.diff(firstGridDay, 'day') + 1;
|
||||
const numWeeks = Math.ceil(totalDays / 7);
|
||||
|
||||
const weekRows: Dayjs[][] = [];
|
||||
for (let w = 0; w < numWeeks; w++) {
|
||||
const row: Dayjs[] = [];
|
||||
for (let d = 0; d < 7; d++) {
|
||||
row.push(firstGridDay.add(w * 7 + d, 'day'));
|
||||
}
|
||||
weekRows.push(row);
|
||||
}
|
||||
return weekRows;
|
||||
}, [currentMonth]);
|
||||
|
||||
// Compute continuous horizontal lanes for each week row
|
||||
const weekLayouts = useMemo(() => {
|
||||
return weeks.map((weekDays) => {
|
||||
const weekStartStr = weekDays[0].format('YYYY-MM-DD');
|
||||
const weekEndStr = weekDays[6].format('YYYY-MM-DD');
|
||||
|
||||
const overlapping = visibleEvents.filter((ev) => {
|
||||
if (!ev.start) return false;
|
||||
const evStartStr = dayjs(ev.start).format('YYYY-MM-DD');
|
||||
const evEndStr = dayjs(ev.end || ev.start).format('YYYY-MM-DD');
|
||||
return evEndStr >= weekStartStr && evStartStr <= weekEndStr;
|
||||
});
|
||||
|
||||
const rawSegments = overlapping.map((ev) => {
|
||||
const evStartStr = dayjs(ev.start).format('YYYY-MM-DD');
|
||||
const evEndStr = dayjs(ev.end || ev.start).format('YYYY-MM-DD');
|
||||
const isMultiDay = evEndStr > evStartStr;
|
||||
const isBar = ev.isAllDay || isMultiDay;
|
||||
|
||||
const continuesBefore = evStartStr < weekStartStr;
|
||||
const continuesAfter = evEndStr > weekEndStr;
|
||||
|
||||
const clampedStart = continuesBefore ? weekStartStr : evStartStr;
|
||||
const clampedEnd = continuesAfter ? weekEndStr : evEndStr;
|
||||
|
||||
const startCol = Math.max(
|
||||
0,
|
||||
Math.min(6, dayjs(clampedStart).diff(weekDays[0], 'day'))
|
||||
);
|
||||
const endCol = Math.max(
|
||||
startCol,
|
||||
Math.min(6, dayjs(clampedEnd).diff(weekDays[0], 'day'))
|
||||
);
|
||||
const span = endCol - startCol + 1;
|
||||
|
||||
return {
|
||||
event: ev,
|
||||
evStartStr,
|
||||
evEndStr,
|
||||
startCol,
|
||||
endCol,
|
||||
span,
|
||||
isBar,
|
||||
continuesBefore,
|
||||
continuesAfter,
|
||||
};
|
||||
});
|
||||
|
||||
// Sort: Multi-day / All-day bars first, earlier startCol, wider span, then start time
|
||||
rawSegments.sort((a, b) => {
|
||||
if (a.isBar && !b.isBar) return -1;
|
||||
if (!a.isBar && b.isBar) return 1;
|
||||
if (a.startCol !== b.startCol) return a.startCol - b.startCol;
|
||||
if (b.span !== a.span) return b.span - a.span;
|
||||
return new Date(a.event.start).getTime() - new Date(b.event.start).getTime();
|
||||
});
|
||||
|
||||
const occupied: boolean[][] = [];
|
||||
const assignedSegments: WeekEventSegment[] = [];
|
||||
|
||||
for (const seg of rawSegments) {
|
||||
let lane = 0;
|
||||
while (true) {
|
||||
if (!occupied[lane]) {
|
||||
occupied[lane] = [false, false, false, false, false, false, false];
|
||||
}
|
||||
let canFit = true;
|
||||
for (let c = seg.startCol; c <= seg.endCol; c++) {
|
||||
if (occupied[lane][c]) {
|
||||
canFit = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (canFit) {
|
||||
for (let c = seg.startCol; c <= seg.endCol; c++) {
|
||||
occupied[lane][c] = true;
|
||||
}
|
||||
break;
|
||||
}
|
||||
lane++;
|
||||
}
|
||||
|
||||
assignedSegments.push({
|
||||
event: seg.event,
|
||||
startCol: seg.startCol,
|
||||
endCol: seg.endCol,
|
||||
span: seg.span,
|
||||
lane,
|
||||
isBar: seg.isBar,
|
||||
continuesBefore: seg.continuesBefore,
|
||||
continuesAfter: seg.continuesAfter,
|
||||
});
|
||||
}
|
||||
|
||||
const hiddenCountPerCol = [0, 0, 0, 0, 0, 0, 0];
|
||||
const allEventsPerCol: CalendarEventItem[][] = [[], [], [], [], [], [], []];
|
||||
|
||||
for (const seg of assignedSegments) {
|
||||
for (let c = seg.startCol; c <= seg.endCol; c++) {
|
||||
allEventsPerCol[c].push(seg.event);
|
||||
if (seg.lane >= MAX_VISIBLE_LANES) {
|
||||
hiddenCountPerCol[c]++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const visibleSegments = assignedSegments.filter(
|
||||
(seg) => seg.lane < MAX_VISIBLE_LANES
|
||||
);
|
||||
|
||||
return {
|
||||
weekDays,
|
||||
visibleSegments,
|
||||
hiddenCountPerCol,
|
||||
allEventsPerCol,
|
||||
};
|
||||
});
|
||||
}, [weeks, visibleEvents]);
|
||||
|
||||
const moreDateEvents = useMemo(() => {
|
||||
if (!moreEventsDate) return [];
|
||||
for (const wl of weekLayouts) {
|
||||
for (let c = 0; c < 7; c++) {
|
||||
if (wl.weekDays[c].format('YYYY-MM-DD') === moreEventsDate) {
|
||||
return wl.allEventsPerCol[c];
|
||||
}
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}, [moreEventsDate, weekLayouts]);
|
||||
|
||||
const resolveEventColor = (ev: CalendarEventItem) => {
|
||||
const colorInfo = getEventColorInfo(ev.colorId);
|
||||
return colorInfo?.hex || ev.calendarColor || '#2563eb';
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Main Unified Calendar Card */}
|
||||
<div className="rounded-xl border border-zinc-200 dark:border-zinc-800 bg-white dark:bg-zinc-900 shadow-sm overflow-hidden">
|
||||
{/* Top Toolbar: Month Navigation & Calendar Filter Chips */}
|
||||
<div className="flex flex-col gap-3 p-4 border-b border-zinc-200 dark:border-zinc-800 bg-white dark:bg-zinc-900">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
{/* Left: Today, Prev/Next, Month Title */}
|
||||
<div className="flex items-center gap-2.5">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => onMonthChange(dayjs())}
|
||||
className="h-9 px-4 rounded-full font-medium text-xs sm:text-sm border-zinc-300 dark:border-zinc-700 bg-white dark:bg-zinc-800 text-zinc-800 dark:text-zinc-100 hover:bg-zinc-100 dark:hover:bg-zinc-700"
|
||||
>
|
||||
Today
|
||||
</Button>
|
||||
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => onMonthChange(currentMonth.subtract(1, 'month'))}
|
||||
className="size-8 p-0 rounded-full text-zinc-600 dark:text-zinc-300 hover:bg-zinc-100 dark:hover:bg-zinc-800"
|
||||
title="Bulan Sebelumnya"
|
||||
>
|
||||
<ChevronLeft className="size-4" />
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => onMonthChange(currentMonth.add(1, 'month'))}
|
||||
className="size-8 p-0 rounded-full text-zinc-600 dark:text-zinc-300 hover:bg-zinc-100 dark:hover:bg-zinc-800"
|
||||
title="Bulan Berikutnya"
|
||||
>
|
||||
<ChevronRight className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<h2 className="text-lg sm:text-xl font-bold tracking-tight text-zinc-900 dark:text-zinc-100 pl-1">
|
||||
{currentMonth.format('MMMM YYYY')}
|
||||
</h2>
|
||||
|
||||
{isLoadingMonth && (
|
||||
<div className="flex items-center gap-1.5 text-xs text-zinc-500 dark:text-zinc-400 pl-2">
|
||||
<Loader2 className="size-4 animate-spin text-sky-500" />
|
||||
<span className="hidden sm:inline">Menyinkronkan...</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Right: Event Count Summary */}
|
||||
<div className="flex items-center gap-2 text-xs text-zinc-500 dark:text-zinc-400">
|
||||
<CalendarIcon className="size-3.5 text-zinc-400" />
|
||||
<span>
|
||||
<strong className="text-zinc-900 dark:text-zinc-100 font-semibold">
|
||||
{visibleEvents.length}
|
||||
</strong>{' '}
|
||||
agenda ditampilkan
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Integrated Multi-Calendar Filter Pills */}
|
||||
{calendars.length > 0 && (
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 pt-2.5 border-t border-zinc-100 dark:border-zinc-800/80">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{calendars.map((cal) => {
|
||||
const isChecked = selectedCalendarIds.includes(cal.id);
|
||||
return (
|
||||
<button
|
||||
key={cal.id}
|
||||
type="button"
|
||||
onClick={() => onToggleCalendar(cal.id)}
|
||||
className={`inline-flex items-center gap-2 px-2.5 py-1 rounded-full border text-xs transition-all ${isChecked
|
||||
? 'border-zinc-300 dark:border-zinc-700 bg-zinc-100/80 dark:bg-zinc-800 text-zinc-900 dark:text-zinc-100 font-medium'
|
||||
: 'border-zinc-200 dark:border-zinc-800 bg-transparent text-zinc-400 dark:text-zinc-500 opacity-60 hover:opacity-100'
|
||||
}`}
|
||||
>
|
||||
<span
|
||||
className="size-3.5 rounded-full flex items-center justify-center shrink-0"
|
||||
style={{
|
||||
backgroundColor: isChecked ? cal.backgroundColor : 'transparent',
|
||||
border: `2px solid ${cal.backgroundColor}`,
|
||||
}}
|
||||
>
|
||||
{isChecked && <Check className="size-2.5 text-white stroke-[3]" />}
|
||||
</span>
|
||||
|
||||
<span className="truncate max-w-[180px]">{cal.summary}</span>
|
||||
|
||||
{cal.isDefaultEnv && (
|
||||
<span className="text-[10px] px-1.5 py-0.2 rounded-full bg-zinc-200 dark:bg-zinc-700 text-zinc-700 dark:text-zinc-300 font-normal">
|
||||
Default
|
||||
</span>
|
||||
)}
|
||||
|
||||
{!cal.isWritable && (
|
||||
<span title="Kalender Read-only">
|
||||
<Lock className="size-3 text-zinc-400 shrink-0" />
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 text-[11px]">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onSelectAllCalendars(true)}
|
||||
className="font-medium text-sky-600 dark:text-sky-400 hover:underline"
|
||||
>
|
||||
Pilih Semua
|
||||
</button>
|
||||
<span className="text-zinc-300 dark:text-zinc-700">•</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onSelectAllCalendars(false)}
|
||||
className="font-medium text-zinc-500 dark:text-zinc-400 hover:text-zinc-900 dark:hover:text-zinc-100 hover:underline"
|
||||
>
|
||||
Reset
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Dedicated 7-Column Weekday Header Bar */}
|
||||
<div className="grid grid-cols-7 border-b border-zinc-200 dark:border-zinc-800 bg-zinc-50 dark:bg-zinc-800">
|
||||
{WEEKDAYS.map((day, idx) => (
|
||||
<div
|
||||
key={day.short}
|
||||
className={`py-2.5 text-center text-[11px] font-semibold tracking-wider uppercase border-r last:border-r-0 border-zinc-200 dark:border-zinc-800 ${idx === 0
|
||||
? 'text-rose-600 dark:text-rose-400'
|
||||
: 'text-zinc-500 dark:text-zinc-400'
|
||||
}`}
|
||||
>
|
||||
{day.short}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Week Rows Grid (Explicit minHeight guarantees tall cells in all browsers) */}
|
||||
<div className="flex flex-col">
|
||||
{weekLayouts.map((weekLayout, weekIdx) => {
|
||||
return (
|
||||
<div key={weekLayout.weekDays[0].format('YYYY-MM-DD')}
|
||||
style={{ minHeight: `${ROW_MIN_HEIGHT_PX}px` }}
|
||||
className="relative grid grid-cols-7 border-b last:border-b-0 border-zinc-200 dark:border-zinc-800"
|
||||
>
|
||||
{/* 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 (
|
||||
<div
|
||||
key={dateStr}
|
||||
onClick={() => 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-100 dark:hover:bg-zinc-800'
|
||||
: '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 */}
|
||||
<div className="flex items-center justify-between">
|
||||
<span
|
||||
style={isToday ? { backgroundColor: '#2563eb', color: '#ffffff' } : undefined}
|
||||
className={`inline-flex items-center justify-center text-xs font-semibold transition-colors ${isToday
|
||||
? 'min-w-[26px] h-[26px] px-1.5 rounded-full shadow-xs'
|
||||
: isCurrentMonth
|
||||
? isSunday
|
||||
? 'h-[26px] px-1 text-rose-600 dark:text-rose-400'
|
||||
: 'h-[26px] px-1 text-zinc-800 dark:text-zinc-200'
|
||||
: 'h-[26px] px-1 text-zinc-400 dark:text-zinc-600'
|
||||
}`}
|
||||
>
|
||||
{dateLabel}
|
||||
</span>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onSelectEmptyDate(dateStr);
|
||||
}}
|
||||
title={`Tambah event pada ${day.format('DD MMM YYYY')}`}
|
||||
className="opacity-0 group-hover:opacity-100 size-6 rounded-md flex items-center justify-center text-zinc-400 hover:text-zinc-900 dark:hover:text-zinc-100 hover:bg-zinc-200/70 dark:hover:bg-zinc-700 transition-opacity"
|
||||
>
|
||||
<Plus className="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Bottom Row inside Cell: "+X lainnya" overflow pill */}
|
||||
<div className="mt-auto pt-1">
|
||||
{hiddenCount > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setMoreEventsDate(dateStr);
|
||||
}}
|
||||
className="w-full text-left px-2 py-0.5 rounded-md text-[11px] font-semibold text-sky-600 dark:text-sky-400 bg-sky-50/80 dark:bg-sky-950/50 hover:bg-sky-100 dark:hover:bg-sky-900/60 transition-colors truncate"
|
||||
>
|
||||
+{hiddenCount} agenda lainnya
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* Continuous Horizontal Event Lanes Layer */}
|
||||
<div className="pointer-events-none absolute inset-x-0"
|
||||
style={{ top: `${DATE_HEADER_HEIGHT_PX}px`, height: `${MAX_VISIBLE_LANES * LANE_HEIGHT_PX}px`, }}
|
||||
>
|
||||
{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 (
|
||||
<div
|
||||
key={`${ev.id}-w${weekIdx}-c${startCol}`}
|
||||
style={{
|
||||
top: `${topPx}px`,
|
||||
left: `calc(${leftPercent}% + ${leftInset}px)`,
|
||||
width: `calc(${widthPercent}% - ${leftInset + rightInset}px)`,
|
||||
height: `${LANE_HEIGHT_PX - 4}px`,
|
||||
}}
|
||||
className="pointer-events-auto absolute z-10 flex items-center"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onSelectEvent(ev);
|
||||
}}
|
||||
style={{
|
||||
backgroundColor: hex,
|
||||
borderTopLeftRadius: continuesBefore ? '2px' : '6px',
|
||||
borderBottomLeftRadius: continuesBefore ? '2px' : '6px',
|
||||
borderTopRightRadius: continuesAfter ? '2px' : '6px',
|
||||
borderBottomRightRadius: continuesAfter ? '2px' : '6px',
|
||||
}}
|
||||
title={`${timePrefix}${ev.summary}${ev.calendarSummary ? ` • ${ev.calendarSummary}` : ''
|
||||
}`}
|
||||
className="w-full h-full px-2.5 text-left text-[11px] font-medium text-white flex items-center justify-between gap-1 truncate hover:brightness-110 transition-all shadow-xs border border-black/10 dark:border-white/15"
|
||||
>
|
||||
<span className="truncate leading-none flex items-center gap-1">
|
||||
{continuesBefore && (
|
||||
<span className="opacity-80 text-[10px] mr-0.5">←</span>
|
||||
)}
|
||||
{!continuesBefore && timePrefix && (
|
||||
<span className="opacity-90 font-normal">{timePrefix}</span>
|
||||
)}
|
||||
<span className="font-semibold tracking-tight truncate">
|
||||
{ev.summary}
|
||||
</span>
|
||||
</span>
|
||||
|
||||
{continuesAfter && (
|
||||
<span className="opacity-80 text-[10px] shrink-0">→</span>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Single-day timed event pill
|
||||
const shortTime = formatGCalShortTime(ev.start);
|
||||
|
||||
return (
|
||||
<div
|
||||
key={`${ev.id}-w${weekIdx}-c${startCol}`}
|
||||
style={{
|
||||
top: `${topPx}px`,
|
||||
left: `calc(${leftPercent}% + 6px)`,
|
||||
width: `calc(${widthPercent}% - 12px)`,
|
||||
height: `${LANE_HEIGHT_PX - 4}px`,
|
||||
}}
|
||||
className="pointer-events-auto absolute z-10 flex items-center"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onSelectEvent(ev);
|
||||
}}
|
||||
title={`${shortTime} ${ev.summary}${ev.calendarSummary ? ` • ${ev.calendarSummary}` : ''
|
||||
}`}
|
||||
className="w-full h-full px-2 rounded-md text-left text-[11px] bg-zinc-100/70 dark:bg-zinc-800/80 hover:bg-zinc-200/80 dark:hover:bg-zinc-700/90 border border-zinc-200/80 dark:border-zinc-700/70 transition-colors flex items-center gap-1.5 min-w-0"
|
||||
>
|
||||
<span
|
||||
className="size-2 rounded-full shrink-0"
|
||||
style={{ backgroundColor: hex }}
|
||||
/>
|
||||
<span className="truncate leading-none">
|
||||
<span className="font-medium text-zinc-500 dark:text-zinc-400 mr-1">
|
||||
{shortTime}
|
||||
</span>
|
||||
<span className="font-semibold text-zinc-900 dark:text-zinc-100">
|
||||
{ev.summary}
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Dialog for "+X agenda lainnya" (All events on a specific date) */}
|
||||
<Dialog
|
||||
open={Boolean(moreEventsDate)}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setMoreEventsDate(null);
|
||||
}}
|
||||
>
|
||||
<DialogContent className="p-0 overflow-hidden bg-white dark:bg-zinc-950 border-zinc-200 dark:border-zinc-800">
|
||||
<DialogHeader className="p-5 pb-3 border-b border-zinc-100 dark:border-zinc-800">
|
||||
<DialogTitle className="text-base font-bold text-zinc-900 dark:text-zinc-100">
|
||||
{moreEventsDate ? dayjs(moreEventsDate).format('dddd, DD MMMM YYYY') : ''}
|
||||
</DialogTitle>
|
||||
<DialogDescription className="text-xs text-zinc-500">
|
||||
Total {moreDateEvents.length} event pada tanggal ini
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="p-4 space-y-2 max-h-[60vh] overflow-y-auto">
|
||||
{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 (
|
||||
<button
|
||||
key={ev.id}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setMoreEventsDate(null);
|
||||
onSelectEvent(ev);
|
||||
}}
|
||||
style={{ borderLeftColor: hex, borderLeftWidth: '4px' }}
|
||||
className="w-full text-left p-3 rounded-lg border border-zinc-200 dark:border-zinc-800 bg-zinc-50/50 dark:bg-zinc-900/60 hover:bg-zinc-100 dark:hover:bg-zinc-800/80 transition-colors space-y-1"
|
||||
>
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="text-xs sm:text-sm font-semibold text-zinc-900 dark:text-zinc-100 truncate">
|
||||
{ev.summary}
|
||||
</span>
|
||||
{ev.hangoutLink && (
|
||||
<Video className="size-3.5 text-sky-600 dark:text-sky-400 shrink-0" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between gap-2 text-[11px] text-zinc-500 dark:text-zinc-400">
|
||||
<span className="flex items-center gap-1">
|
||||
<Clock className="size-3" />
|
||||
{timeLabel}
|
||||
</span>
|
||||
{ev.calendarSummary && (
|
||||
<span className="truncate max-w-[160px] text-[10px] px-1.5 py-0.5 rounded bg-zinc-200/70 dark:bg-zinc-800">
|
||||
{ev.calendarSummary}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="p-3 bg-zinc-50 dark:bg-zinc-900/50 border-t border-zinc-100 dark:border-zinc-800 flex items-center justify-end gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setMoreEventsDate(null)}
|
||||
className="h-8 text-xs"
|
||||
>
|
||||
Tutup
|
||||
</Button>
|
||||
{moreEventsDate && (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
const targetDate = moreEventsDate;
|
||||
setMoreEventsDate(null);
|
||||
onSelectEmptyDate(targetDate);
|
||||
}}
|
||||
className="h-8 text-xs bg-zinc-900 hover:bg-zinc-800 text-white dark:bg-zinc-100 dark:hover:bg-zinc-200 dark:text-zinc-900"
|
||||
>
|
||||
<Plus className="size-3.5 mr-1" />
|
||||
Tambah Event Baru
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState } from 'react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { CalendarTaskItem, TaskStatus } from '@/lib/google-calendar/types';
|
||||
import { createCalendarTask, updateCalendarTask } from '@/lib/google-calendar/tasks.actions';
|
||||
import { toast } from 'sonner';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import dayjs from 'dayjs';
|
||||
|
||||
interface TaskFormModalProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
task?: CalendarTaskItem | null;
|
||||
onSuccess: () => void;
|
||||
}
|
||||
|
||||
interface FormInnerProps {
|
||||
task?: CalendarTaskItem | null;
|
||||
onClose: () => void;
|
||||
onSuccess: () => void;
|
||||
}
|
||||
|
||||
function TaskFormInner({ task, onClose, onSuccess }: FormInnerProps) {
|
||||
const isEdit = !!task;
|
||||
|
||||
const defaultDue = task
|
||||
? task.due.includes('T')
|
||||
? dayjs(task.due).format('YYYY-MM-DDTHH:mm')
|
||||
: dayjs(task.due).format('YYYY-MM-DD')
|
||||
: dayjs().add(1, 'day').hour(17).minute(0).second(0).format('YYYY-MM-DDTHH:mm');
|
||||
|
||||
const [title, setTitle] = useState(task?.title || '');
|
||||
const [description, setDescription] = useState(task?.description || '');
|
||||
const [due, setDue] = useState(defaultDue);
|
||||
const [status, setStatus] = useState<TaskStatus>(task?.status || 'needsAction');
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (!title.trim()) {
|
||||
toast.error('Judul task wajib diisi!');
|
||||
return;
|
||||
}
|
||||
if (!due) {
|
||||
toast.error('Tenggat waktu task wajib diisi!');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
|
||||
if (isEdit && task) {
|
||||
const res = await updateCalendarTask(task.id, {
|
||||
title,
|
||||
description,
|
||||
due,
|
||||
status,
|
||||
});
|
||||
|
||||
if (res.success) {
|
||||
toast.success('Task berhasil diperbarui di Google Calendar!');
|
||||
onClose();
|
||||
onSuccess();
|
||||
} else {
|
||||
toast.error(res.error || 'Gagal memperbarui task.');
|
||||
}
|
||||
} else {
|
||||
const res = await createCalendarTask({
|
||||
title,
|
||||
description,
|
||||
due,
|
||||
status,
|
||||
});
|
||||
|
||||
if (res.success) {
|
||||
toast.success('Task berhasil ditambahkan ke Google Calendar!');
|
||||
onClose();
|
||||
onSuccess();
|
||||
} else {
|
||||
toast.error(res.error || 'Gagal membuat task.');
|
||||
}
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
const msg = err instanceof Error ? err.message : 'Terjadi kesalahan sistem.';
|
||||
toast.error(msg);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="flex flex-col">
|
||||
<DialogHeader className="p-6 pb-4 border-b border-zinc-100 dark:border-zinc-800">
|
||||
<DialogTitle className="text-lg font-semibold text-zinc-900 dark:text-zinc-100">
|
||||
{isEdit ? 'Edit Task Kalender' : 'Tambah Task Baru'}
|
||||
</DialogTitle>
|
||||
<DialogDescription className="text-xs text-zinc-500 dark:text-zinc-400">
|
||||
Task akan disimpan sebagai agenda berlabel [TASK] pada kalender Google resmi.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="p-6 space-y-4 max-h-[70vh] overflow-y-auto">
|
||||
{/* Title */}
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="task-title" className="text-xs font-semibold text-zinc-700 dark:text-zinc-300">
|
||||
Judul Task <span className="text-rose-500">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="task-title"
|
||||
placeholder="misal: Finalisasi Laporan Bulanan"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
disabled={loading}
|
||||
required
|
||||
className="h-9 text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Due Date & Time */}
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="task-due" className="text-xs font-semibold text-zinc-700 dark:text-zinc-300">
|
||||
Tenggat Waktu (Due Date) <span className="text-rose-500">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="task-due"
|
||||
type="datetime-local"
|
||||
value={due}
|
||||
onChange={(e) => setDue(e.target.value)}
|
||||
disabled={loading}
|
||||
required
|
||||
className="h-9 text-xs sm:text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Status Option */}
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs font-semibold text-zinc-700 dark:text-zinc-300">
|
||||
Status Pengerjaan
|
||||
</Label>
|
||||
<div className="grid grid-cols-2 gap-2.5">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setStatus('needsAction')}
|
||||
className={`flex items-center justify-center py-2 px-3 rounded-lg border text-xs font-medium transition-all ${status === 'needsAction'
|
||||
? 'border-amber-500 bg-amber-50/70 text-amber-900 dark:border-amber-600 dark:bg-amber-950/40 dark:text-amber-200'
|
||||
: 'border-zinc-200 dark:border-zinc-800 text-zinc-600 dark:text-zinc-400 hover:bg-zinc-50 dark:hover:bg-zinc-900'
|
||||
}`}
|
||||
>
|
||||
Menunggu (needsAction)
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setStatus('completed')}
|
||||
className={`flex items-center justify-center py-2 px-3 rounded-lg border text-xs font-medium transition-all ${status === 'completed'
|
||||
? 'border-emerald-500 bg-emerald-50/70 text-emerald-900 dark:border-emerald-600 dark:bg-emerald-950/40 dark:text-emerald-200'
|
||||
: 'border-zinc-200 dark:border-zinc-800 text-zinc-600 dark:text-zinc-400 hover:bg-zinc-50 dark:hover:bg-zinc-900'
|
||||
}`}
|
||||
>
|
||||
Selesai (completed)
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Description / Notes */}
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="task-description" className="text-xs font-semibold text-zinc-700 dark:text-zinc-300">
|
||||
Catatan / Detail Task (Opsional)
|
||||
</Label>
|
||||
<Textarea
|
||||
id="task-description"
|
||||
placeholder="Rincian checklist atau catatan tugas..."
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
disabled={loading}
|
||||
rows={3}
|
||||
className="text-xs sm:text-sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter className="p-4 bg-zinc-50 dark:bg-zinc-900/50 border-t border-zinc-100 dark:border-zinc-800 flex items-center justify-end gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={onClose}
|
||||
disabled={loading}
|
||||
>
|
||||
Batal
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
size="sm"
|
||||
disabled={loading}
|
||||
className="bg-emerald-600 hover:bg-emerald-700 text-white font-medium"
|
||||
>
|
||||
{loading && <Loader2 className="size-3.5 mr-1.5 animate-spin" />}
|
||||
{isEdit ? 'Simpan Perubahan' : 'Buat Task'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
export default function TaskFormModal({
|
||||
open,
|
||||
onOpenChange,
|
||||
task,
|
||||
onSuccess,
|
||||
}: TaskFormModalProps) {
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="p-0 overflow-hidden bg-white dark:bg-zinc-950 border-zinc-200 dark:border-zinc-800">
|
||||
{open && (
|
||||
<TaskFormInner
|
||||
key={task?.id || 'new'}
|
||||
task={task}
|
||||
onClose={() => onOpenChange(false)}
|
||||
onSuccess={onSuccess}
|
||||
/>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState } from 'react';
|
||||
import { CalendarTaskItem, TaskStatus } from '@/lib/google-calendar/types';
|
||||
import { ListTodo, CheckCircle2, Clock, Edit2, Trash2, Search, ExternalLink } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import dayjs from 'dayjs';
|
||||
|
||||
interface TaskListProps {
|
||||
tasks: CalendarTaskItem[];
|
||||
onToggleStatus: (task: CalendarTaskItem, newStatus: TaskStatus) => void;
|
||||
onEdit: (task: CalendarTaskItem) => void;
|
||||
onDelete: (task: CalendarTaskItem) => void;
|
||||
onAddTask: () => void;
|
||||
isTogglingId?: string | null;
|
||||
}
|
||||
|
||||
export default function TaskList({
|
||||
tasks,
|
||||
onToggleStatus,
|
||||
onEdit,
|
||||
onDelete,
|
||||
onAddTask,
|
||||
isTogglingId,
|
||||
}: TaskListProps) {
|
||||
const [search, setSearch] = useState('');
|
||||
const [statusFilter, setStatusFilter] = useState<'all' | 'needsAction' | 'completed'>('all');
|
||||
|
||||
const filtered = tasks.filter((t) => {
|
||||
const q = search.toLowerCase();
|
||||
const matchSearch =
|
||||
t.title.toLowerCase().includes(q) ||
|
||||
(t.description && t.description.toLowerCase().includes(q));
|
||||
|
||||
if (!matchSearch) return false;
|
||||
|
||||
if (statusFilter === 'all') return true;
|
||||
return t.status === statusFilter;
|
||||
});
|
||||
|
||||
const formatDue = (dueStr: string) => {
|
||||
if (!dueStr) return '-';
|
||||
if (!dueStr.includes('T')) {
|
||||
return dayjs(dueStr).format('DD MMM YYYY');
|
||||
}
|
||||
return dayjs(dueStr).format('DD MMM YYYY, HH:mm') + ' WIB';
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Controls: Search & Filter Tabs */}
|
||||
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
|
||||
<div className="relative flex-1 max-w-sm">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-zinc-400 pointer-events-none" />
|
||||
<Input
|
||||
placeholder="Cari task..."
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
className="pl-9 h-9 text-xs sm:text-sm bg-white dark:bg-zinc-900 border-zinc-200 dark:border-zinc-800"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1.5 bg-zinc-100 dark:bg-zinc-800/80 p-1 rounded-lg self-start sm:self-auto">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setStatusFilter('all')}
|
||||
className={`px-2.5 py-1 text-xs rounded-md font-medium transition-colors ${
|
||||
statusFilter === 'all'
|
||||
? 'bg-white dark:bg-zinc-900 text-zinc-900 dark:text-zinc-100 shadow-xs'
|
||||
: 'text-zinc-500 hover:text-zinc-800 dark:hover:text-zinc-200'
|
||||
}`}
|
||||
>
|
||||
Semua ({tasks.length})
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setStatusFilter('needsAction')}
|
||||
className={`px-2.5 py-1 text-xs rounded-md font-medium transition-colors ${
|
||||
statusFilter === 'needsAction'
|
||||
? 'bg-white dark:bg-zinc-900 text-zinc-900 dark:text-zinc-100 shadow-xs'
|
||||
: 'text-zinc-500 hover:text-zinc-800 dark:hover:text-zinc-200'
|
||||
}`}
|
||||
>
|
||||
Menunggu ({tasks.filter((t) => t.status === 'needsAction').length})
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setStatusFilter('completed')}
|
||||
className={`px-2.5 py-1 text-xs rounded-md font-medium transition-colors ${
|
||||
statusFilter === 'completed'
|
||||
? 'bg-white dark:bg-zinc-900 text-zinc-900 dark:text-zinc-100 shadow-xs'
|
||||
: 'text-zinc-500 hover:text-zinc-800 dark:hover:text-zinc-200'
|
||||
}`}
|
||||
>
|
||||
Selesai ({tasks.filter((t) => t.status === 'completed').length})
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* List Container */}
|
||||
{filtered.length === 0 ? (
|
||||
<div className="rounded-xl border border-dashed border-zinc-300 dark:border-zinc-800 p-8 text-center bg-zinc-50/50 dark:bg-zinc-900/30">
|
||||
<ListTodo className="size-10 text-zinc-400 mx-auto mb-3 stroke-[1.5]" />
|
||||
<h3 className="text-sm font-semibold text-zinc-800 dark:text-zinc-200">
|
||||
{tasks.length === 0 ? 'Belum Ada Task Kalender' : 'Tidak Ada Task yang Sesuai Filter'}
|
||||
</h3>
|
||||
<p className="text-xs text-zinc-500 max-w-sm mx-auto mt-1 mb-4">
|
||||
{tasks.length === 0
|
||||
? 'Tambahkan task pertama Anda. Task akan diberi penanda khusus [TASK] pada Google Calendar resmi.'
|
||||
: 'Silakan reset pencarian atau filter status untuk melihat data lain.'}
|
||||
</p>
|
||||
{tasks.length === 0 && (
|
||||
<Button size="sm" onClick={onAddTask} className="h-9">
|
||||
Tambah Task Pertama
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2.5">
|
||||
{filtered.map((item) => {
|
||||
const isCompleted = item.status === 'completed';
|
||||
const isProcessing = isTogglingId === item.id;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={item.id}
|
||||
className={`group flex flex-col md:flex-row md:items-center justify-between p-4 rounded-xl border transition-colors shadow-xs gap-3 ${
|
||||
isCompleted
|
||||
? 'border-zinc-200/60 dark:border-zinc-800/50 bg-zinc-50/60 dark:bg-zinc-900/40 opacity-85'
|
||||
: 'border-zinc-200 dark:border-zinc-800/80 bg-white dark:bg-zinc-900 hover:border-zinc-300 dark:hover:border-zinc-700'
|
||||
}`}
|
||||
>
|
||||
{/* Checkbox & Task Details */}
|
||||
<div className="flex items-start gap-3 flex-1 min-w-0">
|
||||
<div className="pt-0.5">
|
||||
<Checkbox
|
||||
checked={isCompleted}
|
||||
disabled={isProcessing}
|
||||
onCheckedChange={(checked) => {
|
||||
onToggleStatus(item, checked ? 'completed' : 'needsAction');
|
||||
}}
|
||||
className="size-5 rounded-md border-zinc-300 dark:border-zinc-700 data-[state=checked]:bg-emerald-600 data-[state=checked]:border-emerald-600"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1 flex-1 min-w-0">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<h4
|
||||
className={`font-semibold text-sm sm:text-base truncate ${
|
||||
isCompleted
|
||||
? 'line-through text-zinc-500 dark:text-zinc-400'
|
||||
: 'text-zinc-900 dark:text-zinc-100'
|
||||
}`}
|
||||
>
|
||||
{item.title}
|
||||
</h4>
|
||||
|
||||
{isCompleted ? (
|
||||
<Badge variant="statusSuccess" className="text-[10px] py-0 px-2 gap-1">
|
||||
<CheckCircle2 className="size-3" />
|
||||
<span>Selesai</span>
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="statusWarning" className="text-[10px] py-0 px-2 gap-1">
|
||||
<Clock className="size-3" />
|
||||
<span>Menunggu</span>
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-zinc-500 dark:text-zinc-400">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Clock className="size-3.5 text-zinc-400" />
|
||||
<span>Tenggat: {formatDue(item.due)}</span>
|
||||
</div>
|
||||
{item.completedAt && (
|
||||
<span className="text-[11px] text-zinc-400">
|
||||
(Diselesaikan {dayjs(item.completedAt).format('DD MMM YYYY, HH:mm')})
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{item.description && (
|
||||
<p className="text-xs text-zinc-600 dark:text-zinc-300 line-clamp-2 pt-0.5">
|
||||
{item.description}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex items-center gap-1.5 self-end md:self-center shrink-0 pt-2 md:pt-0 border-t md:border-t-0 border-zinc-100 dark:border-zinc-800/60 w-full md:w-auto justify-end">
|
||||
{item.htmlLink && (
|
||||
<Button
|
||||
asChild
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 w-8 p-0 text-zinc-500 hover:text-zinc-800 dark:hover:text-zinc-200"
|
||||
title="Lihat di Google Calendar"
|
||||
>
|
||||
<a href={item.htmlLink} target="_blank" rel="noopener noreferrer">
|
||||
<ExternalLink className="size-3.5" />
|
||||
</a>
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => onEdit(item)}
|
||||
className="h-8 px-2.5 text-xs text-zinc-700 dark:text-zinc-300 hover:bg-zinc-100 dark:hover:bg-zinc-800"
|
||||
>
|
||||
<Edit2 className="size-3 mr-1" />
|
||||
<span>Edit</span>
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => onDelete(item)}
|
||||
className="h-8 px-2.5 text-xs border-rose-200 text-rose-600 hover:bg-rose-50 dark:border-rose-900/60 dark:text-rose-400 dark:hover:bg-rose-950/40"
|
||||
>
|
||||
<Trash2 className="size-3 mr-1" />
|
||||
<span>Hapus</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { Metadata } from 'next';
|
||||
import { getAllCalendarsEvents } from '@/lib/google-calendar/events.actions';
|
||||
import IntegratedCalendarClient from './components/IntegratedCalendarClient';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
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() {
|
||||
const res = await getAllCalendarsEvents();
|
||||
|
||||
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;
|
||||
|
||||
return (
|
||||
<IntegratedCalendarClient
|
||||
initialCalendars={initialCalendars}
|
||||
initialEvents={initialEvents}
|
||||
defaultCalendarId={defaultCalendarId}
|
||||
serviceAccountEmail={serviceAccountEmail}
|
||||
initialError={initialError}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -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"))
|
||||
|
||||
@@ -10,6 +10,7 @@ import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import dynamic from 'next/dynamic';
|
||||
import FilterComponent from '../../../component/FilterComponent';
|
||||
import ProjectAssignmentDashboardStats from '../../../component/project-assignment/ProjectAssignmentDashboardStats';
|
||||
import { IClient } from '../../../types';
|
||||
|
||||
const AssignmentList = dynamic(
|
||||
() => import('../../../component/project-assignment/AssignmentList'),
|
||||
@@ -69,12 +70,13 @@ const ConfirmDeleteWithInput = dynamic(
|
||||
);
|
||||
|
||||
interface Props {
|
||||
client: IClient;
|
||||
clientId: string;
|
||||
assignmentLists: IProjectAssignment[];
|
||||
actions?: string[]
|
||||
}
|
||||
|
||||
export default function ClientDetailComponent({ clientId, assignmentLists, actions }: Props) {
|
||||
export default function ClientDetailComponent({ client, clientId, assignmentLists, actions }: Props) {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const urlLayout = searchParams?.get('layout') as 'grid' | 'list' | null;
|
||||
@@ -133,7 +135,7 @@ export default function ClientDetailComponent({ clientId, assignmentLists, actio
|
||||
This client doesn't have any projects or internal memos yet. Try to change the filter or create one to get started.
|
||||
</p>
|
||||
</div>
|
||||
{actions?.includes("CREATE_ASSIGNMENT") &&
|
||||
{client?.name && actions?.includes("CREATE_ASSIGNMENT") &&
|
||||
<Link href={`/task/client-detail/${clientId}/project-assignments`}>
|
||||
<Button variant="outline" className="mt-4">Create Assignment</Button>
|
||||
</Link>
|
||||
|
||||
@@ -61,7 +61,7 @@ export default function ClientProfileCard({ client, clientId, actions }: Props)
|
||||
|
||||
{/* Right: + New assignment Button */}
|
||||
<div className="shrink-0 self-start lg:self-center">
|
||||
{actions?.includes("CREATE_ASSIGNMENT") &&
|
||||
{client.name && actions?.includes("CREATE_ASSIGNMENT") &&
|
||||
<Link href={`/task/client-detail/${clientId}/project-assignments`}>
|
||||
<Button className="gap-2 bg-his hover:bg-his/90 text-white font-medium rounded-xl px-5 py-2.5 shadow-sm transition-transform active:scale-[0.98]">
|
||||
<Plus className="h-4 w-4" />
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -103,6 +103,7 @@ export default async function ClientDetailPage({ params, searchParams }: Props)
|
||||
</Reveal>
|
||||
|
||||
<ClientDetailComponent
|
||||
client={client}
|
||||
clientId={client_id}
|
||||
assignmentLists={filterAssignments}
|
||||
actions={actions}
|
||||
|
||||
+11
-9
@@ -527,15 +527,17 @@ export default function AssignmentDetail({ client, initialAssignment: assignment
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
<Button
|
||||
onClick={() => setAction('MANAGE_EMPLOYEE')}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="gap-1.5 transition-transform active:scale-[0.98]"
|
||||
>
|
||||
<UserPlus className="h-4 w-4" />
|
||||
Manage team
|
||||
</Button>
|
||||
{actions?.includes("MANAGE_TEAM") &&
|
||||
<Button
|
||||
onClick={() => setAction('MANAGE_EMPLOYEE')}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="gap-1.5 transition-transform active:scale-[0.98]"
|
||||
>
|
||||
<UserPlus className="h-4 w-4" />
|
||||
Manage team
|
||||
</Button>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
>
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -36,7 +36,8 @@ const FormEndUser: FC<Props> = ({ data, onSuccess, onCancel }) => {
|
||||
|
||||
const existFile = data?.photo || null
|
||||
const dropzoneRef = useRef<any>(null);
|
||||
const maxSizeMB = 5
|
||||
const maxSizeMB = 2
|
||||
const maxSizeBytes = maxSizeMB * 1024 * 1024;
|
||||
|
||||
const openDialog = () => {
|
||||
// Note that the ref is set async,
|
||||
@@ -48,6 +49,13 @@ const FormEndUser: FC<Props> = ({ data, onSuccess, onCancel }) => {
|
||||
|
||||
const onDrop = useCallback((acceptedFiles: any[]) => {
|
||||
acceptedFiles.forEach(async (file: any) => {
|
||||
if (file.size > maxSizeBytes) {
|
||||
toast.error('File size exceeds the limit', {
|
||||
description: `Maximum allowed file size is ${maxSizeMB}MB.`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const reader = new FileReader();
|
||||
|
||||
reader.onabort = () => console.log('file reading was aborted');
|
||||
@@ -184,7 +192,7 @@ const FormEndUser: FC<Props> = ({ data, onSuccess, onCancel }) => {
|
||||
<Label>Add End User Image</Label>
|
||||
{/* Drop area */}
|
||||
<Dropzone ref={dropzoneRef} onDrop={onDrop} multiple={false} noClick noKeyboard
|
||||
accept={{ 'image/*': ['.png', '.bmp', '.jpeg', '.jpg', '.webp'] }}
|
||||
accept={{ 'image/*': ['.svg', '.png', '.bmp', '.jpeg', '.jpg', '.webp'] }}
|
||||
>
|
||||
{/* @ts-ignore */}
|
||||
{({ getRootProps, getInputProps, acceptedFiles }) => {
|
||||
@@ -217,7 +225,7 @@ const FormEndUser: FC<Props> = ({ data, onSuccess, onCancel }) => {
|
||||
</div>
|
||||
<p className="mb-1.5 text-sm font-medium">Drop your files here</p>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
SVG, PNG, JPG or GIF (max. {maxSizeMB}MB)
|
||||
SVG, PNG, JPG, WEBP, BMP or GIF (max. {maxSizeMB}MB)
|
||||
</p>
|
||||
<Button type='button' variant="outline" className="mt-4" onClick={openDialog}>
|
||||
<UploadIcon className="-ms-1 opacity-60" aria-hidden="true" />
|
||||
|
||||
@@ -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) */}
|
||||
|
||||
@@ -76,7 +76,7 @@ export default function UpdateAdministrationStatus({
|
||||
}, [assignment, statusList]);
|
||||
|
||||
const [selectedStatusId, setSelectedStatusId] = useState<string>(initialStatusId);
|
||||
const [description, setDescription] = useState<string>(assignment?.project_assignment_status?.remark || assignment?.project_assignment_status?.description || assignment?.note || '');
|
||||
const [description, setDescription] = useState<string>(assignment?.project_assignment_status?.remark || assignment?.note || '');
|
||||
|
||||
useEffect(() => {
|
||||
if (initialStatusId) {
|
||||
@@ -85,7 +85,7 @@ export default function UpdateAdministrationStatus({
|
||||
}, [initialStatusId]);
|
||||
|
||||
useEffect(() => {
|
||||
const initialRemark = assignment?.project_assignment_status_notes || assignment?.project_assignment_status?.remark || assignment?.project_assignment_status?.description || assignment?.note || '';
|
||||
const initialRemark = assignment?.project_assignment_status_notes || assignment?.project_assignment_status?.remark || assignment?.note || '';
|
||||
setDescription(initialRemark);
|
||||
}, [assignment]);
|
||||
|
||||
|
||||
@@ -137,11 +137,11 @@ function EditTechnicalStatusModal({ assignmentId, data, onClose, onSuccess }: Ed
|
||||
return dayjs(endDate).isBefore(dayjs(startDate), 'day');
|
||||
}, [startDate, endDate]);
|
||||
|
||||
const isDateMissing = !startDate || !endDate;
|
||||
const isDateMissing = !startDate;
|
||||
|
||||
const handleSave = async () => {
|
||||
if (isDateMissing) {
|
||||
toast.error('Date range required', {
|
||||
toast.error('Start Date is required', {
|
||||
description: 'Please select both a start date and an end date.'
|
||||
});
|
||||
return;
|
||||
@@ -258,7 +258,7 @@ function EditTechnicalStatusModal({ assignmentId, data, onClose, onSuccess }: Ed
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<label className="text-xs font-medium text-foreground">
|
||||
End Date <span className="text-destructive">*</span>
|
||||
End Date
|
||||
</label>
|
||||
<DatePicker
|
||||
date={endDate}
|
||||
@@ -298,18 +298,10 @@ function EditTechnicalStatusModal({ assignmentId, data, onClose, onSuccess }: Ed
|
||||
</div>
|
||||
|
||||
<DialogFooter className="gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={onClose}
|
||||
disabled={isSaving}
|
||||
>
|
||||
<Button type="button" variant="outline" onClick={onClose} disabled={isSaving}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={handleSave}
|
||||
disabled={isSaving || isDateRangeInvalid || isDateMissing}
|
||||
<Button type="button" onClick={handleSave} disabled={isSaving || isDateRangeInvalid || isDateMissing}
|
||||
className="bg-his text-white hover:bg-his/90 gap-1.5 shadow-2xs font-medium"
|
||||
>
|
||||
{isSaving ? (
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -40,7 +40,8 @@ const FormClient: FC<Props> = ({ data, onSuccess, onCancel, isRedirectToDetail }
|
||||
|
||||
const existFile = data?.photo || null
|
||||
const dropzoneRef = useRef<any>(null);
|
||||
const maxSizeMB = 5
|
||||
const maxSizeMB = 2
|
||||
const maxSizeBytes = maxSizeMB * 1024 * 1024;
|
||||
|
||||
const openDialog = () => {
|
||||
if (dropzoneRef.current) {
|
||||
@@ -50,6 +51,13 @@ const FormClient: FC<Props> = ({ data, onSuccess, onCancel, isRedirectToDetail }
|
||||
|
||||
const onDrop = useCallback((acceptedFiles: any[]) => {
|
||||
acceptedFiles.forEach(async (file: any) => {
|
||||
if (file.size > maxSizeBytes) {
|
||||
toast.error('File size exceeds the limit', {
|
||||
description: `Maximum allowed file size is ${maxSizeMB}MB.`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const reader = new FileReader();
|
||||
|
||||
reader.onabort = () => console.log('file reading was aborted');
|
||||
@@ -208,7 +216,7 @@ const FormClient: FC<Props> = ({ data, onSuccess, onCancel, isRedirectToDetail }
|
||||
<Label>Add Client Image</Label>
|
||||
{/* Drop area */}
|
||||
<Dropzone ref={dropzoneRef} onDrop={onDrop} multiple={false} noClick noKeyboard
|
||||
accept={{ 'image/*': ['.png', '.bmp', '.jpeg', '.jpg', '.webp'] }}
|
||||
accept={{ 'image/*': ['.svg', '.png', '.bmp', '.jpeg', '.jpg', '.webp'] }}
|
||||
>
|
||||
{/* @ts-ignore */}
|
||||
{({ getRootProps, getInputProps, acceptedFiles }) => {
|
||||
@@ -241,7 +249,7 @@ const FormClient: FC<Props> = ({ data, onSuccess, onCancel, isRedirectToDetail }
|
||||
</div>
|
||||
<p className="mb-1.5 text-sm font-medium">Drop your files here</p>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
SVG, PNG, JPG or GIF (max. {maxSizeMB}MB)
|
||||
SVG, PNG, JPG, WEBP, BMP or GIF (max. {maxSizeMB}MB)
|
||||
</p>
|
||||
<Button type='button' variant="outline" className="mt-4" onClick={openDialog}>
|
||||
<UploadIcon className="-ms-1 opacity-60" aria-hidden="true" />
|
||||
|
||||
@@ -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).
|
||||
+3
-1
@@ -1,4 +1,4 @@
|
||||
import { redirect } from "next/navigation"
|
||||
import { notFound, redirect } from "next/navigation"
|
||||
import { ResponseData } from "@/types/types"
|
||||
import { logger } from "./logger"
|
||||
import { getCacheServerSession } from "./get-access-data"
|
||||
@@ -24,6 +24,7 @@ export default async function fetchData(url: string = '/', cache: "default" | "f
|
||||
|
||||
console.log("FETCH ERROR DATA :", res.status, data)
|
||||
if (res.status === 401 || res.status === 403) return redirect(`/auth?error=Session error or has expired !`)
|
||||
if (res.status === 404) notFound()
|
||||
// This will activate the closest `error.js` Error Boundary
|
||||
throw new Error(`(${data.code || res.status}) ${data.message || res.statusText}`)
|
||||
}
|
||||
@@ -62,6 +63,7 @@ export async function fetchDataWithPost(url: string = '/', payload: any = {}, ca
|
||||
|
||||
console.log("FETCH ERROR DATA :", res.status, data)
|
||||
if (res.status === 401 || res.status === 403) redirect(`/auth?error=Session error or has expired !`);
|
||||
if (res.status === 404) notFound()
|
||||
|
||||
throw new Error(`(${data?.code || res.status} ${res.statusText}) ${data?.message}`);
|
||||
}
|
||||
|
||||
@@ -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,721 @@
|
||||
'use server';
|
||||
|
||||
import { revalidatePath } from 'next/cache';
|
||||
import { calendar_v3 } from 'googleapis';
|
||||
import dayjs from 'dayjs';
|
||||
import { getGoogleCalendarClient, formatGoogleApiError } from './auth';
|
||||
import {
|
||||
CalendarActionResponse,
|
||||
CalendarEventItem,
|
||||
CreateEventInput,
|
||||
GoogleCalendarListEntry,
|
||||
MultiCalendarEventsResult,
|
||||
UpdateEventInput,
|
||||
} from './types';
|
||||
|
||||
const TIME_ZONE = 'Asia/Jakarta';
|
||||
const FOOTER_DELIMITER = '\n\n--- [Additional Info H.A.T.s] ---';
|
||||
|
||||
function stripDescriptionFooter(desc?: string | null): string {
|
||||
if (!desc) return '';
|
||||
const idx = desc.indexOf(FOOTER_DELIMITER);
|
||||
return idx !== -1 ? desc.slice(0, idx).trim() : desc.trim();
|
||||
}
|
||||
|
||||
function buildDescriptionWithFooter(rawDesc: string, guests: string[], meetLink?: string): string {
|
||||
const clean = stripDescriptionFooter(rawDesc);
|
||||
const extraLines: string[] = [];
|
||||
|
||||
if (meetLink) {
|
||||
extraLines.push(`Google Meet: ${meetLink}`);
|
||||
}
|
||||
if (guests.length > 0) {
|
||||
extraLines.push(`Tamu (Guests): ${guests.join(', ')}`);
|
||||
}
|
||||
|
||||
if (extraLines.length === 0) {
|
||||
return clean;
|
||||
}
|
||||
|
||||
return `${clean}${FOOTER_DELIMITER}\n${extraLines.join('\n')}`.trim();
|
||||
}
|
||||
|
||||
function mapGoogleEventToItem(item: calendar_v3.Schema$Event, calMeta?: GoogleCalendarListEntry): CalendarEventItem {
|
||||
const isAllDay = !item.start?.dateTime && !!item.start?.date;
|
||||
const startStr = item.start?.dateTime || item.start?.date || '';
|
||||
let endStr = item.end?.dateTime || item.end?.date || '';
|
||||
|
||||
// Convert Google Calendar exclusive end.date back to inclusive date for UI
|
||||
if (isAllDay && item.start?.date && item.end?.date) {
|
||||
const startDay = dayjs(item.start.date);
|
||||
const endDay = dayjs(item.end.date);
|
||||
if (endDay.isAfter(startDay, 'day')) {
|
||||
endStr = endDay.subtract(1, 'day').format('YYYY-MM-DD');
|
||||
} else {
|
||||
endStr = item.start.date;
|
||||
}
|
||||
}
|
||||
|
||||
const privateProps = item.extendedProperties?.private || {};
|
||||
|
||||
// Parse attendees from native field + fallback privateProps.guests
|
||||
const nativeAttendees = item.attendees?.map((a) => a.email).filter((email): email is string => Boolean(email)) || [];
|
||||
|
||||
let storedGuests: string[] = [];
|
||||
if (privateProps.guests) {
|
||||
try {
|
||||
const parsed = JSON.parse(privateProps.guests);
|
||||
if (Array.isArray(parsed)) {
|
||||
storedGuests = parsed.filter((e): e is string => typeof e === 'string');
|
||||
}
|
||||
} catch {
|
||||
// ignore invalid json
|
||||
}
|
||||
}
|
||||
|
||||
const attendees = Array.from(new Set([...nativeAttendees, ...storedGuests]));
|
||||
|
||||
// Resolve Google Meet / Conference link
|
||||
const videoEntry = item.conferenceData?.entryPoints?.find((ep) => ep.entryPointType === 'video')?.uri;
|
||||
const hangoutLink = item.hangoutLink || videoEntry || privateProps.meetLink || undefined;
|
||||
|
||||
const rawDescription =
|
||||
privateProps.rawDescription !== undefined
|
||||
? privateProps.rawDescription
|
||||
: stripDescriptionFooter(item.description);
|
||||
|
||||
return {
|
||||
id: item.id || '',
|
||||
summary: item.summary || '(Tanpa Judul)',
|
||||
description: rawDescription,
|
||||
location: item.location || '',
|
||||
start: startStr,
|
||||
end: endStr,
|
||||
isAllDay,
|
||||
colorId: item.colorId || undefined,
|
||||
attendees,
|
||||
hangoutLink,
|
||||
htmlLink: item.htmlLink || '',
|
||||
creatorEmail: item.creator?.email || '',
|
||||
createdAt: item.created || '',
|
||||
updatedAt: item.updated || '',
|
||||
calendarId: calMeta?.id,
|
||||
calendarSummary: calMeta?.summary,
|
||||
calendarColor: calMeta?.backgroundColor,
|
||||
isReadOnly: calMeta ? !calMeta.isWritable : false,
|
||||
};
|
||||
}
|
||||
|
||||
function buildEventStartAndEnd(startDateTime: string, endDateTime: string, isAllDay?: boolean, isPatch?: boolean): { start: calendar_v3.Schema$EventDateTime; end: calendar_v3.Schema$EventDateTime; } {
|
||||
if (isAllDay) {
|
||||
const startPart = startDateTime.split('T')[0];
|
||||
const endPart = endDateTime.split('T')[0];
|
||||
|
||||
const startDay = dayjs(startPart);
|
||||
const endDay = dayjs(endPart);
|
||||
|
||||
if (!startDay.isValid() || !endDay.isValid()) {
|
||||
throw new Error('Format tanggal mulai atau selesai tidak valid.');
|
||||
}
|
||||
|
||||
if (endDay.isBefore(startDay, 'day')) {
|
||||
throw new Error('Tanggal selesai tidak boleh sebelum tanggal mulai.');
|
||||
}
|
||||
|
||||
const startDateFormatted = startDay.format('YYYY-MM-DD');
|
||||
// Google Calendar API requires exclusive end.date (+1 day from inclusive end date)
|
||||
const exclusiveEndDate = endDay.add(1, 'day').format('YYYY-MM-DD');
|
||||
|
||||
if (isPatch) {
|
||||
return {
|
||||
start: { date: startDateFormatted, dateTime: null as unknown as string },
|
||||
end: { date: exclusiveEndDate, dateTime: null as unknown as string },
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
start: { date: startDateFormatted },
|
||||
end: { date: exclusiveEndDate },
|
||||
};
|
||||
}
|
||||
|
||||
const startObj = new Date(startDateTime);
|
||||
const endObj = new Date(endDateTime);
|
||||
|
||||
if (isNaN(startObj.getTime()) || isNaN(endObj.getTime())) {
|
||||
throw new Error('Format waktu mulai atau selesai tidak valid.');
|
||||
}
|
||||
|
||||
if (endObj.getTime() <= startObj.getTime()) {
|
||||
throw new Error('Waktu selesai harus lebih akhir dari waktu mulai.');
|
||||
}
|
||||
|
||||
if (isPatch) {
|
||||
return {
|
||||
start: {
|
||||
date: null as unknown as string,
|
||||
dateTime: startObj.toISOString(),
|
||||
timeZone: TIME_ZONE,
|
||||
},
|
||||
end: {
|
||||
date: null as unknown as string,
|
||||
dateTime: endObj.toISOString(),
|
||||
timeZone: TIME_ZONE,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
start: {
|
||||
dateTime: startObj.toISOString(),
|
||||
timeZone: TIME_ZONE,
|
||||
},
|
||||
end: {
|
||||
dateTime: endObj.toISOString(),
|
||||
timeZone: TIME_ZONE,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch all calendars registered under the authenticated Google account.
|
||||
*/
|
||||
export async function getGoogleCalendarList(): Promise<CalendarActionResponse<GoogleCalendarListEntry[]>> {
|
||||
try {
|
||||
const { calendar, calendarId: defaultCalendarId } = getGoogleCalendarClient();
|
||||
|
||||
const res = await calendar.calendarList.list({
|
||||
showHidden: false,
|
||||
showDeleted: false,
|
||||
});
|
||||
|
||||
const entries = res.data.items || [];
|
||||
|
||||
const mapped: GoogleCalendarListEntry[] = entries
|
||||
.filter((entry) => Boolean(entry.id))
|
||||
.map((entry) => {
|
||||
const id = entry.id || '';
|
||||
const accessRole = entry.accessRole || 'reader';
|
||||
const isWritable = accessRole === 'owner' || accessRole === 'writer';
|
||||
const isDefaultEnv =
|
||||
id === defaultCalendarId ||
|
||||
(defaultCalendarId === 'primary' && Boolean(entry.primary));
|
||||
|
||||
return {
|
||||
id,
|
||||
summary: entry.summaryOverride || entry.summary || id,
|
||||
description: entry.description || '',
|
||||
backgroundColor: entry.backgroundColor || '#039be5',
|
||||
foregroundColor: entry.foregroundColor || '#ffffff',
|
||||
primary: Boolean(entry.primary),
|
||||
accessRole,
|
||||
isWritable,
|
||||
isDefaultEnv,
|
||||
};
|
||||
});
|
||||
|
||||
// Ensure the defaultCalendarId from .env is always in the list even if not subscribed in calendarList
|
||||
const hasDefaultInList = mapped.some(
|
||||
(c) => c.id === defaultCalendarId || c.isDefaultEnv
|
||||
);
|
||||
if (!hasDefaultInList && defaultCalendarId) {
|
||||
try {
|
||||
const singleCal = await calendar.calendars.get({
|
||||
calendarId: defaultCalendarId,
|
||||
});
|
||||
mapped.unshift({
|
||||
id: singleCal.data.id || defaultCalendarId,
|
||||
summary: singleCal.data.summary || 'Default Calendar (.env)',
|
||||
description: singleCal.data.description || '',
|
||||
backgroundColor: '#039be5',
|
||||
foregroundColor: '#ffffff',
|
||||
primary: false,
|
||||
accessRole: 'owner',
|
||||
isWritable: true,
|
||||
isDefaultEnv: true,
|
||||
});
|
||||
} catch {
|
||||
// Ignore if not accessible
|
||||
}
|
||||
}
|
||||
|
||||
// Sort: Default (.env) first, then Primary, then Writable, then Read-only
|
||||
mapped.sort((a, b) => {
|
||||
if (a.isDefaultEnv && !b.isDefaultEnv) return -1;
|
||||
if (!a.isDefaultEnv && b.isDefaultEnv) return 1;
|
||||
if (a.primary && !b.primary) return -1;
|
||||
if (!a.primary && b.primary) return 1;
|
||||
if (a.isWritable && !b.isWritable) return -1;
|
||||
if (!a.isWritable && b.isWritable) return 1;
|
||||
return a.summary.localeCompare(b.summary);
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: mapped,
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
console.error('[GOOGLE_CALENDAR] getGoogleCalendarList error:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: formatGoogleApiError(error),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch events across ALL calendars in the authenticated Google account in parallel.
|
||||
*/
|
||||
export async function getAllCalendarsEvents(params?: { timeMin?: string; timeMax?: string; maxResultsPerCalendar?: number; }): Promise<CalendarActionResponse<MultiCalendarEventsResult>> {
|
||||
try {
|
||||
const {
|
||||
calendar,
|
||||
calendarId: defaultCalendarId,
|
||||
serviceAccountEmail,
|
||||
} = getGoogleCalendarClient();
|
||||
|
||||
const calListRes = await getGoogleCalendarList();
|
||||
if (!calListRes.success || !calListRes.data) {
|
||||
return {
|
||||
success: false,
|
||||
error: calListRes.error || 'Gagal memuat daftar kalender.',
|
||||
};
|
||||
}
|
||||
|
||||
const calendars = calListRes.data;
|
||||
|
||||
// Default time range: start of current month - 7 days to end of current month + 14 days
|
||||
const defaultTimeMin = dayjs()
|
||||
.startOf('month')
|
||||
.subtract(7, 'day')
|
||||
.toISOString();
|
||||
const defaultTimeMax = dayjs()
|
||||
.endOf('month')
|
||||
.add(14, 'day')
|
||||
.toISOString();
|
||||
|
||||
const timeMin = params?.timeMin || defaultTimeMin;
|
||||
const timeMax = params?.timeMax || defaultTimeMax;
|
||||
const maxResults = params?.maxResultsPerCalendar || 250;
|
||||
|
||||
const results = await Promise.allSettled(
|
||||
calendars.map(async (calMeta) => {
|
||||
const res = await calendar.events.list({
|
||||
calendarId: calMeta.id,
|
||||
timeMin,
|
||||
timeMax,
|
||||
maxResults,
|
||||
singleEvents: true,
|
||||
orderBy: 'startTime',
|
||||
});
|
||||
|
||||
const items = res.data.items || [];
|
||||
return items
|
||||
.filter((item) => {
|
||||
const isTaskType = item.extendedProperties?.private?.type === 'task';
|
||||
const hasTaskPrefix = (item.summary || '').startsWith('[TASK');
|
||||
return !isTaskType && !hasTaskPrefix;
|
||||
})
|
||||
.map((item) => mapGoogleEventToItem(item, calMeta));
|
||||
})
|
||||
);
|
||||
|
||||
const allEvents: CalendarEventItem[] = [];
|
||||
for (const r of results) {
|
||||
if (r.status === 'fulfilled' && Array.isArray(r.value)) {
|
||||
allEvents.push(...r.value);
|
||||
}
|
||||
}
|
||||
|
||||
// Sort chronologically by start date/time
|
||||
allEvents.sort((a, b) => {
|
||||
const aTime = new Date(a.start).getTime();
|
||||
const bTime = new Date(b.start).getTime();
|
||||
return aTime - bTime;
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
calendars,
|
||||
events: allEvents,
|
||||
defaultCalendarId,
|
||||
serviceAccountEmail,
|
||||
},
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
console.error('[GOOGLE_CALENDAR] getAllCalendarsEvents error:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: formatGoogleApiError(error),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch list of Google Calendar events (single default calendar fallback).
|
||||
*/
|
||||
export async function getCalendarEvents(params?: { timeMin?: string; timeMax?: string; maxResults?: number; }): Promise<CalendarActionResponse<CalendarEventItem[]>> {
|
||||
try {
|
||||
const { calendar, calendarId } = getGoogleCalendarClient();
|
||||
|
||||
const response = await calendar.events.list({
|
||||
calendarId,
|
||||
timeMin:
|
||||
params?.timeMin ||
|
||||
new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString(),
|
||||
timeMax: params?.timeMax,
|
||||
maxResults: params?.maxResults || 100,
|
||||
singleEvents: true,
|
||||
orderBy: 'startTime',
|
||||
});
|
||||
|
||||
const items = response.data.items || [];
|
||||
|
||||
const regularEvents: CalendarEventItem[] = items
|
||||
.filter((item) => {
|
||||
const isTaskType = item.extendedProperties?.private?.type === 'task';
|
||||
const hasTaskPrefix = (item.summary || '').startsWith('[TASK');
|
||||
return !isTaskType && !hasTaskPrefix;
|
||||
})
|
||||
.map((item) => mapGoogleEventToItem(item));
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: regularEvents,
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
console.error('[GOOGLE_CALENDAR] getCalendarEvents error:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: formatGoogleApiError(error),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute insert or patch with intelligent handling for Service Account limitations
|
||||
* regarding conferenceData (Google Meet) and attendees (Domain-Wide Delegation).
|
||||
*/
|
||||
async function executeEventMutation(
|
||||
mode: 'insert' | 'patch',
|
||||
calendar: calendar_v3.Calendar,
|
||||
calendarId: string,
|
||||
eventId: string | undefined,
|
||||
requestBody: calendar_v3.Schema$Event,
|
||||
options: {
|
||||
wantsAutoMeet: boolean;
|
||||
manualMeetLink: string;
|
||||
hasAttendees: boolean;
|
||||
}
|
||||
): Promise<{ data: calendar_v3.Schema$Event; warnings: string[] }> {
|
||||
const warnings: string[] = [];
|
||||
let useConferenceVersion = options.wantsAutoMeet ? 1 : undefined;
|
||||
|
||||
const performCall = async () => {
|
||||
const sendUpdates =
|
||||
requestBody.attendees && requestBody.attendees.length > 0 ? 'all' : 'none';
|
||||
|
||||
if (mode === 'insert') {
|
||||
return await calendar.events.insert({
|
||||
calendarId,
|
||||
conferenceDataVersion: useConferenceVersion,
|
||||
sendUpdates,
|
||||
requestBody,
|
||||
});
|
||||
} else {
|
||||
return await calendar.events.patch({
|
||||
calendarId,
|
||||
eventId: eventId!,
|
||||
conferenceDataVersion: useConferenceVersion,
|
||||
sendUpdates,
|
||||
requestBody,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
for (let attempt = 0; attempt < 3; attempt++) {
|
||||
try {
|
||||
const res = await performCall();
|
||||
return { data: res.data, warnings };
|
||||
} catch (err: unknown) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
|
||||
if (msg.includes('Invalid conference type value') && requestBody.conferenceData) {
|
||||
delete requestBody.conferenceData;
|
||||
useConferenceVersion = undefined;
|
||||
|
||||
if (options.manualMeetLink) {
|
||||
warnings.push(
|
||||
'Kalender ini tidak mendukung auto-generate Google Meet ("Invalid conference type value"). Link Google Meet manual telah digunakan.'
|
||||
);
|
||||
continue;
|
||||
} else {
|
||||
throw new Error(
|
||||
'Pembuatan link Google Meet otomatis gagal ("Invalid conference type value"). Silakan matikan toggle otomatis atau isi kolom Link Google Meet Manual.'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (msg.includes('Domain-Wide Delegation') && requestBody.attendees) {
|
||||
delete requestBody.attendees;
|
||||
warnings.push(
|
||||
'Service Account tanpa Domain-Wide Delegation tidak dapat mengirim email undangan (RSVP) langsung. Daftar tamu tetap disimpan pada event.'
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
const finalRes = await performCall();
|
||||
return { data: finalRes.data, warnings };
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new Google Calendar event.
|
||||
*/
|
||||
export async function createCalendarEvent(payload: CreateEventInput): Promise<CalendarActionResponse<CalendarEventItem>> {
|
||||
try {
|
||||
if (!payload.summary || !payload.summary.trim()) {
|
||||
return { success: false, error: 'Judul event (summary) wajib diisi.' };
|
||||
}
|
||||
if (!payload.startDateTime || !payload.endDateTime) {
|
||||
return { success: false, error: 'Waktu mulai dan selesai wajib diisi.' };
|
||||
}
|
||||
|
||||
const { start, end } = buildEventStartAndEnd(
|
||||
payload.startDateTime,
|
||||
payload.endDateTime,
|
||||
payload.isAllDay,
|
||||
false
|
||||
);
|
||||
|
||||
const { calendar, calendarId: defaultCalendarId } = getGoogleCalendarClient();
|
||||
const targetCalendarId = payload.calendarId?.trim() || defaultCalendarId;
|
||||
|
||||
const cleanGuests = Array.from(
|
||||
new Set(
|
||||
(payload.attendees || [])
|
||||
.map((e) => e.trim().toLowerCase())
|
||||
.filter(Boolean)
|
||||
)
|
||||
);
|
||||
const rawDescription = payload.description?.trim() || '';
|
||||
const manualMeetLink = payload.manualMeetLink?.trim() || '';
|
||||
|
||||
const requestBody: calendar_v3.Schema$Event = {
|
||||
summary: payload.summary.trim(),
|
||||
description: buildDescriptionWithFooter(
|
||||
rawDescription,
|
||||
cleanGuests,
|
||||
manualMeetLink
|
||||
),
|
||||
location: payload.location?.trim() || '',
|
||||
start,
|
||||
end,
|
||||
colorId: payload.colorId || undefined,
|
||||
extendedProperties: {
|
||||
private: {
|
||||
type: 'event',
|
||||
source: 'hats-app',
|
||||
rawDescription,
|
||||
guests: JSON.stringify(cleanGuests),
|
||||
meetLink: manualMeetLink,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
if (cleanGuests.length > 0) {
|
||||
requestBody.attendees = cleanGuests.map((email) => ({ email }));
|
||||
}
|
||||
|
||||
if (payload.generateMeet) {
|
||||
requestBody.conferenceData = {
|
||||
createRequest: {
|
||||
requestId: `hats-meet-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`,
|
||||
conferenceSolutionKey: {
|
||||
type: 'hangoutsMeet',
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const { data: item, warnings } = await executeEventMutation(
|
||||
'insert',
|
||||
calendar,
|
||||
targetCalendarId,
|
||||
undefined,
|
||||
requestBody,
|
||||
{
|
||||
wantsAutoMeet: Boolean(payload.generateMeet),
|
||||
manualMeetLink,
|
||||
hasAttendees: cleanGuests.length > 0,
|
||||
}
|
||||
);
|
||||
|
||||
revalidatePath('/integrated-calendar');
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
...mapGoogleEventToItem(item),
|
||||
calendarId: targetCalendarId,
|
||||
},
|
||||
warning: warnings.length > 0 ? warnings.join(' ') : undefined,
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
console.error('[GOOGLE_CALENDAR] createCalendarEvent error:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: formatGoogleApiError(error),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update an existing Google Calendar event.
|
||||
*/
|
||||
export async function updateCalendarEvent(id: string, payload: UpdateEventInput): Promise<CalendarActionResponse<CalendarEventItem>> {
|
||||
try {
|
||||
if (!id) {
|
||||
return { success: false, error: 'ID event diperlukan.' };
|
||||
}
|
||||
|
||||
const { calendar, calendarId: defaultCalendarId } = getGoogleCalendarClient();
|
||||
const targetCalendarId = payload.calendarId?.trim() || defaultCalendarId;
|
||||
|
||||
const cleanGuests = Array.from(
|
||||
new Set(
|
||||
(payload.attendees || [])
|
||||
.map((e) => e.trim().toLowerCase())
|
||||
.filter(Boolean)
|
||||
)
|
||||
);
|
||||
const rawDescription = payload.description?.trim() ?? '';
|
||||
const manualMeetLink = payload.manualMeetLink?.trim() ?? '';
|
||||
|
||||
const requestBody: calendar_v3.Schema$Event = {
|
||||
extendedProperties: {
|
||||
private: {
|
||||
type: 'event',
|
||||
source: 'hats-app',
|
||||
rawDescription,
|
||||
guests: JSON.stringify(cleanGuests),
|
||||
meetLink: manualMeetLink,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
if (payload.summary !== undefined) {
|
||||
requestBody.summary = payload.summary.trim();
|
||||
}
|
||||
if (
|
||||
payload.description !== undefined ||
|
||||
payload.attendees !== undefined ||
|
||||
payload.manualMeetLink !== undefined
|
||||
) {
|
||||
requestBody.description = buildDescriptionWithFooter(
|
||||
rawDescription,
|
||||
cleanGuests,
|
||||
manualMeetLink
|
||||
);
|
||||
}
|
||||
if (payload.location !== undefined) {
|
||||
requestBody.location = payload.location.trim();
|
||||
}
|
||||
if (payload.colorId !== undefined) {
|
||||
requestBody.colorId = payload.colorId || (null as unknown as string);
|
||||
}
|
||||
|
||||
if (payload.startDateTime && payload.endDateTime) {
|
||||
const { start, end } = buildEventStartAndEnd(
|
||||
payload.startDateTime,
|
||||
payload.endDateTime,
|
||||
payload.isAllDay,
|
||||
true
|
||||
);
|
||||
requestBody.start = start;
|
||||
requestBody.end = end;
|
||||
}
|
||||
|
||||
if (payload.attendees !== undefined) {
|
||||
requestBody.attendees = cleanGuests.map((email) => ({ email }));
|
||||
}
|
||||
|
||||
if (payload.generateMeet) {
|
||||
requestBody.conferenceData = {
|
||||
createRequest: {
|
||||
requestId: `hats-meet-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`,
|
||||
conferenceSolutionKey: {
|
||||
type: 'hangoutsMeet',
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const { data: item, warnings } = await executeEventMutation(
|
||||
'patch',
|
||||
calendar,
|
||||
targetCalendarId,
|
||||
id,
|
||||
requestBody,
|
||||
{
|
||||
wantsAutoMeet: Boolean(payload.generateMeet),
|
||||
manualMeetLink,
|
||||
hasAttendees: cleanGuests.length > 0,
|
||||
}
|
||||
);
|
||||
|
||||
revalidatePath('/integrated-calendar');
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
...mapGoogleEventToItem(item),
|
||||
calendarId: targetCalendarId,
|
||||
},
|
||||
warning: warnings.length > 0 ? warnings.join(' ') : undefined,
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
console.error('[GOOGLE_CALENDAR] updateCalendarEvent error:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: formatGoogleApiError(error),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a Google Calendar event.
|
||||
*/
|
||||
export async function deleteCalendarEvent(id: string, targetCalendarId?: string): Promise<CalendarActionResponse<{ id: string }>> {
|
||||
try {
|
||||
if (!id) {
|
||||
return { success: false, error: 'ID event diperlukan.' };
|
||||
}
|
||||
|
||||
const { calendar, calendarId: defaultCalendarId } = getGoogleCalendarClient();
|
||||
const resolvedCalendarId = targetCalendarId?.trim() || defaultCalendarId;
|
||||
|
||||
await calendar.events.delete({
|
||||
calendarId: resolvedCalendarId,
|
||||
eventId: id,
|
||||
sendUpdates: 'all',
|
||||
});
|
||||
|
||||
revalidatePath('/integrated-calendar');
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: { id },
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
console.error('[GOOGLE_CALENDAR] deleteCalendarEvent error:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: formatGoogleApiError(error),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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,112 @@
|
||||
export interface CalendarActionResponse<T = unknown> {
|
||||
success: boolean;
|
||||
data?: T;
|
||||
error?: string;
|
||||
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;
|
||||
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;
|
||||
// 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;
|
||||
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 {
|
||||
calendarId?: string;
|
||||
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;
|
||||
}
|
||||
@@ -27,6 +27,11 @@ const nextConfig: NextConfig = {
|
||||
reactStrictMode: false,
|
||||
experimental: {
|
||||
authInterrupts: true, // for forbidden page
|
||||
// MEMORY OPTIMIZING
|
||||
// 1. Prevent Next.js from loading all route modules into RAM at startup
|
||||
preloadEntriesOnStart: false,
|
||||
// 2. Optimize barrel imports (e.g., lucide-react, @mui/icons-material, lodash)
|
||||
optimizePackageImports: ['lucide-react', 'date-fns', 'lodash'],
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
Generated
+12880
File diff suppressed because it is too large
Load Diff
+4
-2
@@ -12,7 +12,7 @@
|
||||
"url": "https://github.com/ichsankurnia/hats-app/issues"
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "next dev -p 1209",
|
||||
"dev": "set NODE_OPTIONS=\"--max-old-space-size=2048\" && next dev -p 1209",
|
||||
"dev:save": "set NODE_TLS_REJECT_UNAUTHORIZED='0' && next dev -p 1209",
|
||||
"build": "next build",
|
||||
"start": "next start -p 7002",
|
||||
@@ -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",
|
||||
@@ -93,4 +95,4 @@
|
||||
"tw-animate-css": "^1.4.0",
|
||||
"typescript": "^5"
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -30,5 +30,5 @@
|
||||
".next/dev/types/**/*.ts",
|
||||
"**/*.mts"
|
||||
],
|
||||
"exclude": ["node_modules", "**/*.old.tsx", "**/*.old.ts"]
|
||||
"exclude": ["node_modules", ".next", "**/*.old.tsx", "**/*.old.ts"]
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user