initial commit

This commit is contained in:
jason
2026-03-12 17:09:22 -05:00
commit 4982e5392e
35 changed files with 9803 additions and 0 deletions

View File

@@ -0,0 +1,37 @@
import { NextResponse } from "next/server";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
import { prisma } from "@/lib/prisma";
// GET /api/admin/settings - Fetch global settings
export async function GET() {
const session = await getServerSession(authOptions);
if (!session || session.user.role !== "ADMIN") {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const settings = await prisma.setting.findMany();
const settingsMap = settings.reduce((acc: any, curr: any) => ({ ...acc, [curr.key]: curr.value }), {});
return NextResponse.json(settingsMap);
}
// POST /api/admin/settings - Update or create setting
export async function POST(req: Request) {
const session = await getServerSession(authOptions);
if (!session || session.user.role !== "ADMIN") {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const { key, value } = await req.json();
const setting = await prisma.setting.upsert({
where: { key },
update: { value },
create: { key, value },
});
return NextResponse.json(setting);
}

View File

@@ -0,0 +1,49 @@
import NextAuth, { NextAuthOptions } from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import { prisma } from "@/lib/prisma";
export const authOptions: NextAuthOptions = {
adapter: PrismaAdapter(prisma),
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
}),
],
callbacks: {
async jwt({ token, account }) {
if (account) {
token.accessToken = account.access_token;
}
return token;
},
async session({ session, user, token }) {
if (session.user) {
session.user.id = user?.id || (token?.sub as string);
// Fetch fresh role from DB if needed, or use token
const dbUser = await prisma.user.findUnique({ where: { id: session.user.id } });
session.user.role = dbUser?.role || 'EMPLOYEE';
}
return session;
},
},
events: {
async createUser({ user }) {
const userCount = await prisma.user.count();
if (userCount === 1) {
await prisma.user.update({
where: { id: user.id },
data: { role: 'ADMIN' },
});
}
},
},
pages: {
signIn: "/auth/signin",
},
};
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };

View File

@@ -0,0 +1,56 @@
import { NextResponse } from "next/server";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
import { prisma } from "@/lib/prisma";
import { uploadToDrive, generateReportMarkdown } from "@/lib/google-drive";
import { getToken } from "next-auth/jwt";
export async function POST(
req: Request,
{ params }: { params: { id: string } }
) {
const session = await getServerSession(authOptions);
// We need the raw access token from JWT for Google API
const token = await getToken({ req: req as any });
if (!session || !token?.accessToken) {
return NextResponse.json({ error: "Unauthorized or missing Google token" }, { status: 401 });
}
const report = await prisma.report.findUnique({
where: { id: params.id, userId: session.user.id },
include: { tasks: true, user: true },
});
if (!report) {
return NextResponse.json({ error: "Report not found" }, { status: 404 });
}
const markdown = generateReportMarkdown(report);
const fileName = `WFH_Report_${new Date(report.date).toISOString().split('T')[0]}_${report.user.name}`;
// Fetch designated folder ID from settings
const folderSetting = await prisma.setting.findUnique({
where: { key: 'GOOGLE_DRIVE_FOLDER_ID' }
});
try {
const driveFile = await uploadToDrive(
token.accessToken as string,
fileName,
markdown,
folderSetting?.value
);
// Update report status to SUBMITTED
await prisma.report.update({
where: { id: params.id },
data: { status: 'SUBMITTED' }
});
return NextResponse.json({ success: true, link: driveFile.webViewLink });
} catch (error) {
return NextResponse.json({ error: "Failed to upload to Drive" }, { status: 500 });
}
}

View File

@@ -0,0 +1,48 @@
import { NextResponse } from "next/server";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
import { prisma } from "@/lib/prisma";
// PATCH /api/reports/[id] - Update report status or manager
export async function PATCH(
req: Request,
{ params }: { params: { id: string } }
) {
const session = await getServerSession(authOptions);
if (!session) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const { status, managerName } = await req.json();
const report = await prisma.report.update({
where: { id: params.id, userId: session.user.id },
data: { status, managerName },
});
return NextResponse.json(report);
}
// GET /api/reports/[id] - Fetch a specific report
export async function GET(
req: Request,
{ params }: { params: { id: string } }
) {
const session = await getServerSession(authOptions);
if (!session) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const report = await prisma.report.findUnique({
where: { id: params.id },
include: { tasks: true },
});
if (!report || (report.userId !== session.user.id && session.user.role !== "ADMIN")) {
return NextResponse.json({ error: "Not Found" }, { status: 404 });
}
return NextResponse.json(report);
}

View File

@@ -0,0 +1,59 @@
import { NextResponse } from "next/server";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
import { prisma } from "@/lib/prisma";
// GET /api/reports - Fetch reports for the logged-in user (or all for admin)
export async function GET() {
const session = await getServerSession(authOptions);
if (!session) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const where = session.user.role === "ADMIN" ? {} : { userId: session.user.id };
const reports = await prisma.report.findMany({
where,
include: { tasks: true },
orderBy: { date: "desc" },
});
return NextResponse.json(reports);
}
// POST /api/reports - Create or resume a report
export async function POST(req: Request) {
const session = await getServerSession(authOptions);
if (!session) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const body = await req.json();
const { managerName, date } = body;
// Check if a report already exists for this date and user
const reportDate = date ? new Date(date) : new Date();
reportDate.setHours(0, 0, 0, 0);
let report = await prisma.report.findFirst({
where: {
userId: session.user.id,
date: reportDate,
},
});
if (!report) {
report = await prisma.report.create({
data: {
userId: session.user.id,
managerName,
date: reportDate,
},
include: { tasks: true },
});
}
return NextResponse.json(report);
}

View File

@@ -0,0 +1,76 @@
import { NextResponse } from "next/server";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
import { prisma } from "@/lib/prisma";
// POST /api/tasks - Add a task to a report
export async function POST(req: Request) {
const session = await getServerSession(authOptions);
if (!session) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const { reportId, type, description, timeEstimate, notes, link, status } = await req.json();
// Verify ownership
const report = await prisma.report.findUnique({
where: { id: reportId, userId: session.user.id },
});
if (!report) {
return NextResponse.json({ error: "Report not found" }, { status: 404 });
}
const task = await prisma.task.create({
data: {
reportId,
type,
description,
timeEstimate,
notes,
link,
status: status || "PENDING",
},
});
return NextResponse.json(task);
}
// PATCH /api/tasks/[id] - Update a task
export async function PATCH(req: Request) {
const session = await getServerSession(authOptions);
if (!session) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const { id, type, description, timeEstimate, notes, link, status } = await req.json();
const task = await prisma.task.update({
where: { id },
data: { type, description, timeEstimate, notes, link, status },
});
return NextResponse.json(task);
}
// DELETE /api/tasks/[id] - Delete a task
export async function DELETE(req: Request) {
const session = await getServerSession(authOptions);
if (!session) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const { searchParams } = new URL(req.url);
const id = searchParams.get("id");
if (!id) return NextResponse.json({ error: "ID required" }, { status: 400 });
await prisma.task.delete({
where: { id },
});
return NextResponse.json({ success: true });
}

BIN
src/app/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

76
src/app/globals.css Normal file
View File

@@ -0,0 +1,76 @@
@import "tailwindcss";
:root {
--bg-dark: #0f172a;
--bg-card: rgba(30, 41, 59, 0.7);
--accent-primary: #38bdf8;
--accent-secondary: #818cf8;
--text-main: #f1f5f9;
--text-dim: #94a3b8;
--glass-border: rgba(255, 255, 255, 0.1);
--glass-highlight: rgba(255, 255, 255, 0.05);
}
body {
background: radial-gradient(circle at top left, #1e293b, #0f172a);
color: var(--text-main);
min-height: 100vh;
}
.glass-card {
background: var(--bg-card);
backdrop-filter: blur(12px);
border: 1px solid var(--glass-border);
box-shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.37);
border-radius: 1rem;
}
.glass-input {
background: rgba(15, 23, 42, 0.5);
border: 1px solid var(--glass-border);
color: white;
transition: all 0.2s ease;
}
.glass-input:focus {
border-color: var(--accent-primary);
box-shadow: 0 0 0 2px rgba(56, 189, 248, 0.2);
outline: none;
}
.btn-primary {
background: linear-gradient(135deg, var(--accent-primary), var(--accent-secondary));
color: white;
font-weight: 600;
padding: 0.75rem 1.5rem;
border-radius: 0.75rem;
transition: transform 0.2s ease, opacity 0.2s ease;
}
.btn-primary:hover {
transform: translateY(-2px);
opacity: 0.9;
}
.btn-secondary {
background: var(--glass-highlight);
border: 1px solid var(--glass-border);
color: white;
padding: 0.75rem 1.5rem;
border-radius: 0.75rem;
transition: all 0.2s ease;
}
.btn-secondary:hover {
background: rgba(255, 255, 255, 0.1);
}
/* Animations */
@keyframes fadeIn {
from { opacity: 0; transform: translateY(10px); }
to { opacity: 1; transform: translateY(0); }
}
.animate-fade-in {
animation: fadeIn 0.5s ease forwards;
}

25
src/app/layout.tsx Normal file
View File

@@ -0,0 +1,25 @@
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
import { AuthProvider } from "@/components/providers/AuthProvider";
const inter = Inter({ subsets: ["latin"] });
export const metadata: Metadata = {
title: "WFH Daily Report",
description: "Sleek and modern work from home reporting tool",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body className={inter.className}>
<AuthProvider>{children}</AuthProvider>
</body>
</html>
);
}

9
src/app/page.tsx Normal file
View File

@@ -0,0 +1,9 @@
import ReportForm from "@/components/ReportForm";
export default function Home() {
return (
<main className="min-h-screen">
<ReportForm />
</main>
);
}

View File

@@ -0,0 +1,203 @@
"use client";
import { useState, useEffect } from "react";
import { Search, ChevronDown, ChevronUp, ExternalLink, FileText, User, Calendar, Settings, ListChecks, Save } from "lucide-react";
export default function AdminDashboard() {
const [reports, setReports] = useState<any[]>([]);
const [loading, setLoading] = useState(true);
const [search, setSearch] = useState("");
const [expandedId, setExpandedId] = useState<string | null>(null);
const [tab, setTab] = useState<"REPORTS" | "SETTINGS">("REPORTS");
const [folderId, setFolderId] = useState("");
const [saving, setSaving] = useState(false);
useEffect(() => {
fetchReports();
fetchSettings();
}, []);
const fetchSettings = async () => {
try {
const res = await fetch("/api/admin/settings");
const data = await res.json();
if (data.GOOGLE_DRIVE_FOLDER_ID) {
setFolderId(data.GOOGLE_DRIVE_FOLDER_ID);
}
} catch (error) {
console.error("Failed to fetch settings");
}
};
const saveSetting = async (key: string, value: string) => {
setSaving(true);
try {
await fetch("/api/admin/settings", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key, value }),
});
alert("Setting saved successfully!");
} catch (error) {
alert("Failed to save setting");
} finally {
setSaving(false);
}
};
const fetchReports = async () => {
try {
const res = await fetch("/api/reports");
const data = await res.json();
setReports(data);
} catch (error) {
console.error("Failed to fetch reports");
} finally {
setLoading(false);
}
};
const filteredReports = reports.filter(r =>
r.user?.name?.toLowerCase().includes(search.toLowerCase()) ||
r.managerName?.toLowerCase().includes(search.toLowerCase())
);
if (loading) return <div className="text-center py-20 animate-pulse">Loading reports...</div>;
return (
<div className="space-y-6">
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
<div className="flex items-center gap-4">
<button
onClick={() => setTab("REPORTS")}
className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-colors text-sm font-medium ${
tab === "REPORTS" ? "bg-accent-primary text-white" : "hover:bg-white/5 text-text-dim"
}`}
>
<ListChecks size={18} /> Reports
</button>
<button
onClick={() => setTab("SETTINGS")}
className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-colors text-sm font-medium ${
tab === "SETTINGS" ? "bg-accent-primary text-white" : "hover:bg-white/5 text-text-dim"
}`}
>
<Settings size={18} /> Settings
</button>
</div>
{tab === "REPORTS" && (
<div className="relative max-w-sm w-full">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 text-text-dim" size={18} />
<input
type="text"
placeholder="Search by employee or manager..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="glass-input w-full pl-10 pr-4 py-2 rounded-lg text-sm"
/>
</div>
)}
</div>
{tab === "REPORTS" ? (
<div className="grid gap-4">
{filteredReports.map((report) => (
<div key={report.id} className="glass-card overflow-hidden transition-all duration-300">
<div
className="p-4 flex items-center justify-between cursor-pointer hover:bg-white/5"
onClick={() => setExpandedId(expandedId === report.id ? null : report.id)}
>
<div className="flex items-center gap-4">
<div className="h-10 w-10 rounded-full bg-accent-primary/20 flex items-center justify-center text-accent-primary">
<User size={20} />
</div>
<div>
<h3 className="font-semibold">{report.user?.name || "Unknown User"}</h3>
<p className="text-xs text-text-dim flex items-center gap-1">
<Calendar size={12} /> {new Date(report.date).toLocaleDateString()} Manager: {report.managerName}
</p>
</div>
</div>
<div className="flex items-center gap-4">
<span className={`text-[10px] uppercase tracking-wider px-2 py-1 rounded-full font-bold ${
report.status === 'SUBMITTED' ? 'bg-green-500/20 text-green-400' : 'bg-yellow-500/20 text-yellow-400'
}`}>
{report.status}
</span>
{expandedId === report.id ? <ChevronUp size={20} /> : <ChevronDown size={20} />}
</div>
</div>
{expandedId === report.id && (
<div className="p-6 border-t border-white/10 bg-black/20 space-y-6 animate-fade-in">
<div className="grid md:grid-cols-2 gap-8">
<div className="space-y-3">
<h4 className="text-xs font-bold uppercase text-accent-primary tracking-widest">Planned Tasks</h4>
{report.tasks.filter((t: any) => t.type === 'PLANNED').map((task: any) => (
<div key={task.id} className="text-sm border-l-2 border-accent-primary/30 pl-3 py-1">
<p className="font-medium">{task.description}</p>
<p className="text-xs text-text-dim">Est: {task.timeEstimate} {task.notes}</p>
</div>
))}
</div>
<div className="space-y-3">
<h4 className="text-xs font-bold uppercase text-accent-secondary tracking-widest">Completed Tasks</h4>
{report.tasks.filter((t: any) => t.type === 'COMPLETED').map((task: any) => (
<div key={task.id} className="text-sm border-l-2 border-accent-secondary/30 pl-3 py-1">
<p className="font-medium">{task.description}</p>
<div className="flex items-center justify-between">
<span className="text-[10px] text-text-dim italic">{task.status}</span>
{task.link && (
<a href={task.link} target="_blank" className="text-accent-secondary hover:underline flex items-center gap-1 text-[10px]">
<ExternalLink size={10} /> View Work
</a>
)}
</div>
</div>
))}
</div>
</div>
</div>
)}
</div>
))}
{filteredReports.length === 0 && <p className="text-center py-10 text-text-dim">No reports found matching your criteria.</p>}
</div>
) : (
<div className="glass-card p-8 space-y-8 animate-fade-in">
<div className="space-y-4">
<div>
<h3 className="text-lg font-semibold flex items-center gap-2">
<FileText size={20} className="text-accent-primary" /> Google Drive Configuration
</h3>
<p className="text-sm text-text-dim">Designate a specific folder where all exported reports will be saved.</p>
</div>
<div className="space-y-2">
<label className="text-xs font-bold uppercase text-text-dim tracking-wider">Google Drive Folder ID</label>
<input
type="text"
value={folderId}
onChange={(e) => setFolderId(e.target.value)}
placeholder="Enter Folder ID (from URL)"
className="glass-input w-full px-4 py-3 rounded-xl text-sm"
/>
<p className="text-[10px] text-text-dim italic">
Example ID: `1abc12345xyz_...` (Found in the URL of your Google Drive folder)
</p>
</div>
<button
onClick={() => saveSetting('GOOGLE_DRIVE_FOLDER_ID', folderId)}
disabled={saving}
className="btn-primary flex items-center gap-2 px-8"
>
<Save size={18} /> {saving ? "Saving..." : "Save Settings"}
</button>
</div>
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,328 @@
"use client";
import { useSession, signIn, signOut } from "next-auth/react";
import { useState, useEffect } from "react";
import { Plus, Trash2, Send, Save, CheckCircle, Clock, Calendar, User as UserIcon, Link as LinkIcon, LogOut, ShieldCheck, ClipboardList } from "lucide-react";
import AdminDashboard from "./AdminDashboard";
export default function ReportForm() {
const { data: session, status } = useSession();
const [report, setReport] = useState<any>(null);
const [loading, setLoading] = useState(true);
const [managerName, setManagerName] = useState("");
const [plannedTasks, setPlannedTasks] = useState<any[]>([]);
const [completedTasks, setCompletedTasks] = useState<any[]>([]);
const [saving, setSaving] = useState(false);
const [view, setView] = useState<"REPORT" | "ADMIN">("REPORT");
useEffect(() => {
if (status === "authenticated") {
fetchReport();
}
}, [status]);
const fetchReport = async () => {
try {
const res = await fetch("/api/reports");
const data = await res.json();
const today = new Date().toISOString().split('T')[0];
const todayReport = data.find((r: any) => r.date.split('T')[0] === today);
if (todayReport) {
setReport(todayReport);
setManagerName(todayReport.managerName);
setPlannedTasks(todayReport.tasks.filter((t: any) => t.type === "PLANNED"));
setCompletedTasks(todayReport.tasks.filter((t: any) => t.type === "COMPLETED"));
}
} catch (error) {
console.error("Failed to fetch report", error);
} finally {
setLoading(false);
}
};
const startReport = async () => {
setSaving(true);
try {
const res = await fetch("/api/reports", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ managerName }),
});
const data = await res.json();
setReport(data);
} catch (error) {
alert("Failed to start report");
} finally {
setSaving(false);
}
};
const addTask = async (type: "PLANNED" | "COMPLETED") => {
if (!report) return;
const newTask = {
reportId: report.id,
type,
description: "",
timeEstimate: type === "PLANNED" ? "" : null,
notes: "",
status: type === "COMPLETED" ? "DONE" : "PENDING",
};
try {
const res = await fetch("/api/tasks", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(newTask),
});
const data = await res.json();
if (type === "PLANNED") setPlannedTasks([...plannedTasks, data]);
else setCompletedTasks([...completedTasks, data]);
} catch (error) {
alert("Failed to add task");
}
};
const updateTask = async (id: string, updates: any) => {
try {
await fetch("/api/tasks", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ id, ...updates }),
});
if (updates.type === 'PLANNED') {
setPlannedTasks(plannedTasks.map(t => t.id === id ? { ...t, ...updates } : t));
} else {
setCompletedTasks(completedTasks.map(t => t.id === id ? { ...t, ...updates } : t));
}
} catch (error) {
console.error("Failed to update task");
}
};
const deleteTask = async (id: string, type: string) => {
try {
await fetch(`/api/tasks?id=${id}`, { method: "DELETE" });
if (type === "PLANNED") setPlannedTasks(plannedTasks.filter(t => t.id !== id));
else setCompletedTasks(completedTasks.filter(t => t.id !== id));
} catch (error) {
alert("Failed to delete task");
}
};
const exportToDrive = async () => {
if (!report) return;
setSaving(true);
try {
const res = await fetch(`/api/reports/${report.id}/export`, { method: "POST" });
const data = await res.json();
if (data.link) {
alert("Report exported to Google Drive!");
window.open(data.link, '_blank');
fetchReport();
} else {
alert("Export failed: " + data.error);
}
} catch (error) {
alert("Export error");
} finally {
setSaving(false);
}
};
if (status === "loading" || loading) {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-accent-primary"></div>
</div>
);
}
if (!session) {
return (
<div className="flex flex-col items-center justify-center min-h-screen p-4">
<div className="glass-card p-8 max-w-md w-full text-center space-y-6 animate-fade-in">
<h1 className="text-4xl font-bold bg-gradient-to-r from-accent-primary to-accent-secondary bg-clip-text text-transparent">
WFH Tracker
</h1>
<p className="text-text-dim">Please sign in with your company Google account to access your daily reports.</p>
<button onClick={() => signIn("google")} className="btn-primary w-full flex items-center justify-center gap-2">
Continue with Google
</button>
</div>
</div>
);
}
return (
<div className="max-w-4xl mx-auto p-4 md:p-8 space-y-8 animate-fade-in">
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold">{view === "REPORT" ? "Daily Report" : "Administration"}</h1>
<p className="text-text-dim flex items-center gap-2">
<Calendar size={16} /> {new Date().toLocaleDateString(undefined, { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })}
</p>
</div>
<div className="flex items-center gap-4">
{session.user.role === "ADMIN" && (
<button
onClick={() => setView(view === "REPORT" ? "ADMIN" : "REPORT")}
className="flex items-center gap-2 px-4 py-2 rounded-lg bg-white/5 hover:bg-white/10 transition-colors border border-white/10 text-sm font-medium"
>
{view === "REPORT" ? (
<><ShieldCheck size={18} className="text-accent-primary" /> Admin Panel</>
) : (
<><ClipboardList size={18} className="text-accent-primary" /> My Report</>
)}
</button>
)}
<span className="text-sm hidden md:inline">{session.user.name}</span>
<button onClick={() => signOut()} className="p-2 hover:bg-white/10 rounded-full transition-colors text-red-400" title="Logout">
<LogOut size={20} />
</button>
</div>
</div>
{view === "ADMIN" ? (
<AdminDashboard />
) : !report ? (
<div className="glass-card p-8 space-y-6">
<div className="space-y-4">
<label className="block text-sm font-medium text-text-dim">Assigning Manager</label>
<div className="relative">
<UserIcon className="absolute left-3 top-1/2 -translate-y-1/2 text-text-dim" size={18} />
<input
type="text"
value={managerName}
onChange={(e) => setManagerName(e.target.value)}
placeholder="Manager's Name"
className="glass-input w-full pl-10 pr-4 py-3 rounded-xl"
/>
</div>
</div>
<button
disabled={!managerName || saving}
onClick={startReport}
className="btn-primary w-full disabled:opacity-50"
>
{saving ? "Starting..." : "Start Today's Report"}
</button>
</div>
) : (
<div className="space-y-8">
{/* Morning Section */}
<section className="space-y-4">
<div className="flex items-center justify-between">
<h2 className="text-xl font-semibold flex items-center gap-2"><Clock className="text-accent-primary" /> Morning Setup (Planned Tasks)</h2>
<button onClick={() => addTask("PLANNED")} className="btn-secondary flex items-center gap-2 py-2 px-4 text-sm">
<Plus size={16} /> Add Task
</button>
</div>
<div className="space-y-3">
{plannedTasks.map((task) => (
<div key={task.id} className="glass-card p-4 flex gap-4 group">
<div className="flex-1 space-y-3">
<input
type="text"
value={task.description}
onChange={(e) => updateTask(task.id, { description: e.target.value, type: 'PLANNED' })}
placeholder="Task description..."
className="bg-transparent border-b border-white/10 w-full py-1 focus:border-accent-primary outline-none transition-colors"
/>
<div className="flex gap-4">
<div className="flex-1">
<input
type="text"
value={task.timeEstimate || ""}
onChange={(e) => updateTask(task.id, { timeEstimate: e.target.value, type: 'PLANNED' })}
placeholder="Time estimate (e.g. 2h)"
className="bg-transparent text-sm text-text-dim border-none p-0 focus:ring-0 outline-none w-full"
/>
</div>
<div className="flex-1">
<input
type="text"
value={task.notes || ""}
onChange={(e) => updateTask(task.id, { notes: e.target.value, type: 'PLANNED' })}
placeholder="Short notes..."
className="bg-transparent text-sm text-text-dim border-none p-0 focus:ring-0 outline-none w-full"
/>
</div>
</div>
</div>
<button onClick={() => deleteTask(task.id, "PLANNED")} className="opacity-0 group-hover:opacity-100 p-2 text-red-400 transition-opacity">
<Trash2 size={18} />
</button>
</div>
))}
{plannedTasks.length === 0 && <p className="text-center py-4 text-text-dim border border-dashed border-white/10 rounded-xl">No tasks added yet.</p>}
</div>
</section>
{/* Evening Section */}
<section className="space-y-4">
<div className="flex items-center justify-between">
<h2 className="text-xl font-semibold flex items-center gap-2"><CheckCircle className="text-accent-secondary" /> Evening Review (Completed Tasks)</h2>
<button onClick={() => addTask("COMPLETED")} className="btn-secondary flex items-center gap-2 py-2 px-4 text-sm">
<Plus size={16} /> Add Completed
</button>
</div>
<div className="space-y-3">
{completedTasks.map((task) => (
<div key={task.id} className="glass-card p-4 flex gap-4 group">
<div className="flex-1 space-y-3">
<input
type="text"
value={task.description}
onChange={(e) => updateTask(task.id, { description: e.target.value, type: 'COMPLETED' })}
placeholder="What did you complete?"
className="bg-transparent border-b border-white/10 w-full py-1 focus:border-accent-secondary outline-none transition-colors"
/>
<div className="flex gap-4">
<select
value={task.status || "DONE"}
onChange={(e) => updateTask(task.id, { status: e.target.value, type: 'COMPLETED' })}
className="bg-transparent text-sm text-text-dim border-none p-0 focus:ring-0 outline-none appearance-none cursor-pointer"
>
<option value="DONE" className="bg-slate-800">Completed</option>
<option value="IN_PROGRESS" className="bg-slate-800">In Progress</option>
<option value="CANCELLED" className="bg-slate-800">Delayed</option>
</select>
<div className="flex-1 relative">
<LinkIcon size={14} className="absolute left-0 top-1/2 -translate-y-1/2 text-text-dim" />
<input
type="text"
value={task.link || ""}
onChange={(e) => updateTask(task.id, { link: e.target.value, type: 'COMPLETED' })}
placeholder="Google Drive link (optional)"
className="bg-transparent text-sm text-text-dim border-none pl-5 p-0 focus:ring-0 outline-none w-full"
/>
</div>
</div>
</div>
<button onClick={() => deleteTask(task.id, "COMPLETED")} className="opacity-0 group-hover:opacity-100 p-2 text-red-400 transition-opacity">
<Trash2 size={18} />
</button>
</div>
))}
{completedTasks.length === 0 && <p className="text-center py-4 text-text-dim border border-dashed border-white/10 rounded-xl">Add your achievements for today.</p>}
</div>
</section>
<footer className="pt-8 border-t border-white/10 flex justify-end gap-4">
<button
onClick={exportToDrive}
disabled={saving || report.status === 'SUBMITTED'}
className="btn-primary flex items-center gap-2 px-8"
>
{saving ? "Processing..." : (report.status === 'SUBMITTED' ? "Already Submitted" : "Finalize & Export to Drive")}
<Send size={18} />
</button>
</footer>
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,7 @@
"use client";
import { SessionProvider } from "next-auth/react";
export const AuthProvider = ({ children }: { children: React.ReactNode }) => {
return <SessionProvider>{children}</SessionProvider>;
};

56
src/lib/google-drive.ts Normal file
View File

@@ -0,0 +1,56 @@
import { google } from 'googleapis';
import { Readable } from 'stream';
export async function uploadToDrive(accessToken: string, fileName: string, content: string, folderId?: string) {
const auth = new google.auth.OAuth2();
auth.setCredentials({ access_token: accessToken });
const drive = google.drive({ version: 'v3', auth });
const fileMetadata: any = {
name: fileName,
mimeType: 'application/vnd.google-apps.document', // Automatically convert to Google Doc
};
if (folderId) {
fileMetadata.parents = [folderId];
}
const media = {
mimeType: 'text/markdown',
body: Readable.from([content]),
};
try {
const response = await drive.files.create({
requestBody: fileMetadata,
media: media,
fields: 'id, webViewLink'
});
return response.data;
} catch (error) {
console.error('Error uploading to Google Drive:', error);
throw error;
}
}
export function generateReportMarkdown(report: any) {
let md = `# WFH Daily Report - ${new Date(report.date).toLocaleDateString()}\n`;
md += `**Employee:** ${report.user.name}\n`;
md += `**Manager:** ${report.managerName}\n\n`;
md += `## Planned Tasks\n`;
report.tasks.filter((t: any) => t.type === 'PLANNED').forEach((t: any) => {
md += `- [ ] ${t.description} (Est: ${t.timeEstimate})\n`;
if (t.notes) md += ` - Notes: ${t.notes}\n`;
});
md += `\n## Completed Tasks\n`;
report.tasks.filter((t: any) => t.type === 'COMPLETED').forEach((t: any) => {
md += `- [x] ${t.description}\n`;
md += ` - Status: ${t.status}\n`;
if (t.link) md += ` - Work Link: ${t.link}\n`;
});
return md;
}

13
src/lib/prisma.ts Normal file
View File

@@ -0,0 +1,13 @@
import { PrismaClient } from '@prisma/client'
const globalForPrisma = globalThis as unknown as {
prisma: PrismaClient | undefined
}
export const prisma =
globalForPrisma.prisma ??
new PrismaClient({
log: process.env.NODE_ENV === 'development' ? ['query', 'error', 'warn'] : ['error'],
})
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma

25
src/middleware.ts Normal file
View File

@@ -0,0 +1,25 @@
import { NextRequest, NextResponse } from "next/server";
export function middleware(request: NextRequest) {
// Simple check for auth routes or static files
if (
request.nextUrl.pathname.startsWith('/api/auth') ||
request.nextUrl.pathname.startsWith('/_next') ||
request.nextUrl.pathname === '/favicon.ico'
) {
return NextResponse.next();
}
const token = request.cookies.get('next-auth.session-token') ||
request.cookies.get('__Secure-next-auth.session-token');
if (!token && request.nextUrl.pathname !== '/') {
return NextResponse.redirect(new URL('/', request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ['/((?!api/auth|_next/static|_next/image|favicon.ico).*)'],
};

14
src/types/next-auth.d.ts vendored Normal file
View File

@@ -0,0 +1,14 @@
import { DefaultSession } from "next-auth";
declare module "next-auth" {
interface Session {
user: {
id: string;
role: string;
} & DefaultSession["user"];
}
interface User {
role: string;
}
}