Compare commits

..

8 Commits

Author SHA1 Message Date
jason
c0198df6d9 pretty it up 2026-03-13 16:16:59 -05:00
jason
f1a3a31a94 fixes 2026-03-13 16:00:33 -05:00
e08a2375ae Merge pull request 'admin board' (#17) from claude/suspicious-wilson into master
Reviewed-on: #17
2026-03-13 11:44:04 -05:00
jason
707f632d34 admin board 2026-03-13 11:39:46 -05:00
6813602b6c Merge pull request 'debounce' (#16) from claude/suspicious-wilson into master
Reviewed-on: #16
2026-03-13 11:36:09 -05:00
jason
65a4f79131 debounce 2026-03-13 11:35:28 -05:00
9046370b64 Merge pull request 'timezone' (#15) from claude/suspicious-wilson into master
Reviewed-on: #15
2026-03-13 11:18:20 -05:00
jason
0e2dc27779 timezone 2026-03-13 11:18:11 -05:00
7 changed files with 342 additions and 53 deletions

Submodule .claude/worktrees/suspicious-wilson added at 707f632d34

View File

@@ -0,0 +1,62 @@
import { NextResponse } from "next/server";
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
// GET /api/admin/users - List all users
export async function GET() {
const session = await getServerSession(authOptions);
if (!session || session.user.role !== "ADMIN") {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const users = await prisma.user.findMany({
select: {
id: true,
name: true,
email: true,
image: true,
role: true,
reports: {
orderBy: { date: "desc" },
take: 1,
select: { date: true, status: true },
},
},
orderBy: { name: "asc" },
});
return NextResponse.json(users);
}
// PATCH /api/admin/users - Update a user's role
export async function PATCH(req: Request) {
const session = await getServerSession(authOptions);
if (!session || session.user.role !== "ADMIN") {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const { userId, role } = await req.json();
if (!userId || !["EMPLOYEE", "ADMIN"].includes(role)) {
return NextResponse.json({ error: "Invalid request" }, { status: 400 });
}
// Prevent admins from demoting themselves
if (userId === session.user.id && role === "EMPLOYEE") {
return NextResponse.json({ error: "You cannot remove your own admin privileges" }, { status: 403 });
}
const updated = await prisma.user.update({
where: { id: userId },
data: { role },
select: { id: true, name: true, email: true, role: true },
});
return NextResponse.json(updated);
}

View File

@@ -5,7 +5,7 @@ export const runtime = "nodejs";
import { getServerSession } from "next-auth/next"; import { getServerSession } from "next-auth/next";
import { authOptions } from "@/lib/auth"; import { authOptions } from "@/lib/auth";
import { prisma } from "@/lib/prisma"; import { prisma } from "@/lib/prisma";
import { uploadToDrive, updateDriveFile, generateReportMarkdown } from "@/lib/google-drive"; import { uploadToDrive, updateDriveFile, generateReportHTML, getGoogleAuth } from "@/lib/google-drive";
export async function POST( export async function POST(
req: Request, req: Request,
@@ -18,13 +18,11 @@ export async function POST(
return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
} }
// With database sessions (not JWT), the Google access token lives in the let auth;
// Account table — getToken() returns null in this strategy. try {
const account = await prisma.account.findFirst({ auth = await getGoogleAuth(session.user.id);
where: { userId: session.user.id, provider: "google" }, } catch (error) {
}); console.error("Failed to get Google Auth:", error);
if (!account?.access_token) {
return NextResponse.json({ error: "Unauthorized or missing Google token" }, { status: 401 }); return NextResponse.json({ error: "Unauthorized or missing Google token" }, { status: 401 });
} }
@@ -37,7 +35,7 @@ export async function POST(
return NextResponse.json({ error: "Report not found" }, { status: 404 }); return NextResponse.json({ error: "Report not found" }, { status: 404 });
} }
const markdown = generateReportMarkdown(report); const htmlContent = generateReportHTML(report);
const fileName = `WFH_Report_${new Date(report.date).toISOString().split('T')[0]}_${report.user.name}`; const fileName = `WFH_Report_${new Date(report.date).toISOString().split('T')[0]}_${report.user.name}`;
// Fetch designated folder ID from settings // Fetch designated folder ID from settings
@@ -50,10 +48,10 @@ export async function POST(
if (report.driveFileId) { if (report.driveFileId) {
// Update the existing Drive file in place // Update the existing Drive file in place
driveFile = await updateDriveFile(account.access_token, report.driveFileId, markdown); driveFile = await updateDriveFile(auth, report.driveFileId, htmlContent);
} else { } else {
// First export — create a new Drive file and store its ID // First export — create a new Drive file and store its ID
driveFile = await uploadToDrive(account.access_token, fileName, markdown, folderSetting?.value); driveFile = await uploadToDrive(auth, fileName, htmlContent, folderSetting?.value);
await prisma.report.update({ await prisma.report.update({
where: { id }, where: { id },
data: { driveFileId: driveFile.id }, data: { driveFileId: driveFile.id },

View File

@@ -37,9 +37,12 @@ export async function POST(req: Request) {
const body = await req.json(); const body = await req.json();
const { managerName, date } = body; const { managerName, date } = body;
// Check if a report already exists for this date and user // Check if a report already exists for this date and user.
const reportDate = date ? new Date(date) : new Date(); // Client always sends a YYYY-MM-DD date string in Central US time;
reportDate.setHours(0, 0, 0, 0); // we store it as UTC midnight so the date string is stable across timezones.
const reportDate = date
? new Date(`${date}T00:00:00.000Z`)
: new Date(new Date().toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }) + 'T00:00:00.000Z');
let report = await prisma.report.findFirst({ let report = await prisma.report.findFirst({
where: { where: {

View File

@@ -1,16 +1,19 @@
"use client"; "use client";
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import { Search, ChevronDown, ChevronUp, ExternalLink, FileText, User, Calendar, Settings, ListChecks, Save } from "lucide-react"; import { Search, ChevronDown, ChevronUp, ExternalLink, FileText, User, Users, Calendar, Settings, ListChecks, Save, ShieldCheck, ShieldOff } from "lucide-react";
export default function AdminDashboard() { export default function AdminDashboard() {
const [reports, setReports] = useState<any[]>([]); const [reports, setReports] = useState<any[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [search, setSearch] = useState(""); const [search, setSearch] = useState("");
const [expandedId, setExpandedId] = useState<string | null>(null); const [expandedId, setExpandedId] = useState<string | null>(null);
const [tab, setTab] = useState<"REPORTS" | "SETTINGS">("REPORTS"); const [tab, setTab] = useState<"REPORTS" | "USERS" | "SETTINGS">("REPORTS");
const [folderId, setFolderId] = useState(""); const [folderId, setFolderId] = useState("");
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
const [users, setUsers] = useState<any[]>([]);
const [usersLoading, setUsersLoading] = useState(false);
const [togglingId, setTogglingId] = useState<string | null>(null);
useEffect(() => { useEffect(() => {
fetchReports(); fetchReports();
@@ -45,6 +48,41 @@ export default function AdminDashboard() {
} }
}; };
const fetchUsers = async () => {
setUsersLoading(true);
try {
const res = await fetch("/api/admin/users");
const data = await res.json();
setUsers(data);
} catch (error) {
console.error("Failed to fetch users");
} finally {
setUsersLoading(false);
}
};
const toggleRole = async (userId: string, currentRole: string) => {
setTogglingId(userId);
const newRole = currentRole === "ADMIN" ? "EMPLOYEE" : "ADMIN";
try {
const res = await fetch("/api/admin/users", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ userId, role: newRole }),
});
const data = await res.json();
if (data.error) {
alert(data.error);
} else {
setUsers(users.map(u => u.id === userId ? { ...u, role: newRole } : u));
}
} catch (error) {
alert("Failed to update role");
} finally {
setTogglingId(null);
}
};
const fetchReports = async () => { const fetchReports = async () => {
try { try {
const res = await fetch("/api/reports"); const res = await fetch("/api/reports");
@@ -76,6 +114,14 @@ export default function AdminDashboard() {
> >
<ListChecks size={18} /> Reports <ListChecks size={18} /> Reports
</button> </button>
<button
onClick={() => { setTab("USERS"); if (!users.length) fetchUsers(); }}
className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-colors text-sm font-medium ${
tab === "USERS" ? "bg-accent-primary text-white" : "hover:bg-white/5 text-text-dim"
}`}
>
<Users size={18} /> Users
</button>
<button <button
onClick={() => setTab("SETTINGS")} onClick={() => setTab("SETTINGS")}
className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-colors text-sm font-medium ${ className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-colors text-sm font-medium ${
@@ -164,6 +210,81 @@ export default function AdminDashboard() {
))} ))}
{filteredReports.length === 0 && <p className="text-center py-10 text-text-dim">No reports found matching your criteria.</p>} {filteredReports.length === 0 && <p className="text-center py-10 text-text-dim">No reports found matching your criteria.</p>}
</div> </div>
) : tab === "USERS" ? (
<div className="space-y-4 animate-fade-in">
<div>
<h3 className="text-lg font-semibold flex items-center gap-2">
<Users size={20} className="text-accent-primary" /> Employee List
</h3>
<p className="text-sm text-text-dim">Manage admin privileges for your team.</p>
</div>
{usersLoading ? (
<div className="text-center py-10 animate-pulse text-text-dim">Loading users...</div>
) : (
<div className="grid gap-3">
{users.map((user) => {
const lastReport = user.reports?.[0];
return (
<div key={user.id} className="glass-card p-4 flex items-center justify-between gap-4">
<div className="flex items-center gap-4 min-w-0">
{user.image ? (
<img src={user.image} alt={user.name} className="h-10 w-10 rounded-full flex-shrink-0" />
) : (
<div className="h-10 w-10 rounded-full bg-accent-primary/20 flex items-center justify-center text-accent-primary flex-shrink-0">
<User size={20} />
</div>
)}
<div className="min-w-0">
<div className="flex items-center gap-2 flex-wrap">
<p className="font-semibold truncate">{user.name || "Unnamed"}</p>
<span className={`text-[10px] uppercase tracking-wider px-2 py-0.5 rounded-full font-bold flex-shrink-0 ${
user.role === "ADMIN"
? "bg-accent-primary/20 text-accent-primary"
: "bg-white/10 text-text-dim"
}`}>
{user.role}
</span>
</div>
<p className="text-xs text-text-dim truncate">{user.email}</p>
{lastReport && (
<p className="text-[10px] text-text-dim mt-0.5">
Last report: {new Date(lastReport.date).toLocaleDateString()} {" "}
<span className={lastReport.status === "SUBMITTED" ? "text-green-400" : "text-yellow-400"}>
{lastReport.status}
</span>
</p>
)}
</div>
</div>
<button
onClick={() => toggleRole(user.id, user.role)}
disabled={togglingId === user.id}
className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors flex-shrink-0 disabled:opacity-50 ${
user.role === "ADMIN"
? "bg-red-500/10 hover:bg-red-500/20 text-red-400 border border-red-500/20"
: "bg-accent-primary/10 hover:bg-accent-primary/20 text-accent-primary border border-accent-primary/20"
}`}
title={user.role === "ADMIN" ? "Remove admin privileges" : "Grant admin privileges"}
>
{togglingId === user.id ? (
"..."
) : user.role === "ADMIN" ? (
<><ShieldOff size={16} /> Remove Admin</>
) : (
<><ShieldCheck size={16} /> Make Admin</>
)}
</button>
</div>
);
})}
{users.length === 0 && (
<p className="text-center py-10 text-text-dim">No users found.</p>
)}
</div>
)}
</div>
) : ( ) : (
<div className="glass-card p-8 space-y-8 animate-fade-in"> <div className="glass-card p-8 space-y-8 animate-fade-in">
<div className="space-y-4"> <div className="space-y-4">

View File

@@ -1,7 +1,7 @@
"use client"; "use client";
import { useSession, signIn, signOut } from "next-auth/react"; import { useSession, signIn, signOut } from "next-auth/react";
import { useState, useEffect } from "react"; import { useState, useEffect, useRef } from "react";
import { Plus, Trash2, Send, Save, CheckCircle, Clock, Calendar, User as UserIcon, Link as LinkIcon, LogOut, ShieldCheck, ClipboardList } from "lucide-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"; import AdminDashboard from "./AdminDashboard";
@@ -14,6 +14,8 @@ export default function ReportForm() {
const [completedTasks, setCompletedTasks] = useState<any[]>([]); const [completedTasks, setCompletedTasks] = useState<any[]>([]);
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
const [view, setView] = useState<"REPORT" | "ADMIN">("REPORT"); const [view, setView] = useState<"REPORT" | "ADMIN">("REPORT");
const debounceTimers = useRef<Record<string, ReturnType<typeof setTimeout>>>({});
const pendingUpdates = useRef<Record<string, any>>({});
useEffect(() => { useEffect(() => {
if (status === "authenticated") { if (status === "authenticated") {
@@ -23,11 +25,15 @@ export default function ReportForm() {
} }
}, [status]); }, [status]);
// Returns today's date as YYYY-MM-DD in Central US time
const getCentralToday = () =>
new Date().toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
const fetchReport = async () => { const fetchReport = async () => {
try { try {
const res = await fetch("/api/reports"); const res = await fetch("/api/reports");
const data = await res.json(); const data = await res.json();
const today = new Date().toISOString().split('T')[0]; const today = getCentralToday();
const todayReport = data.find((r: any) => r.date.split('T')[0] === today); const todayReport = data.find((r: any) => r.date.split('T')[0] === today);
if (todayReport) { if (todayReport) {
@@ -49,7 +55,7 @@ export default function ReportForm() {
const res = await fetch("/api/reports", { const res = await fetch("/api/reports", {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ managerName }), body: JSON.stringify({ managerName, date: getCentralToday() }),
}); });
const data = await res.json(); const data = await res.json();
setReport(data); setReport(data);
@@ -85,21 +91,33 @@ export default function ReportForm() {
} }
}; };
const updateTask = async (id: string, updates: any) => { const updateTask = (id: string, updates: any) => {
// Update local state immediately so the UI stays responsive
if (updates.type === 'PLANNED') {
setPlannedTasks(prev => prev.map(t => t.id === id ? { ...t, ...updates } : t));
} else {
setCompletedTasks(prev => prev.map(t => t.id === id ? { ...t, ...updates } : t));
}
// Accumulate all field changes for this task so a single request carries everything
pendingUpdates.current[id] = { ...pendingUpdates.current[id], ...updates };
// Reset the debounce timer — the API call fires 600 ms after the last keystroke
clearTimeout(debounceTimers.current[id]);
debounceTimers.current[id] = setTimeout(async () => {
const payload = pendingUpdates.current[id];
delete pendingUpdates.current[id];
delete debounceTimers.current[id];
try { try {
await fetch("/api/tasks", { await fetch("/api/tasks", {
method: "PATCH", method: "PATCH",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ id, ...updates }), body: JSON.stringify({ id, ...payload }),
}); });
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) { } catch (error) {
console.error("Failed to update task"); console.error("Failed to update task");
} }
}, 600);
}; };
const deleteTask = async (id: string, type: string) => { const deleteTask = async (id: string, type: string) => {

View File

@@ -1,10 +1,56 @@
import { google } from 'googleapis'; import { google } from 'googleapis';
import { Readable } from 'stream'; import { Readable } from 'stream';
import { prisma } from './prisma';
export async function uploadToDrive(accessToken: string, fileName: string, content: string, folderId?: string) { export async function getGoogleAuth(userId: string) {
const auth = new google.auth.OAuth2(); const account = await prisma.account.findFirst({
auth.setCredentials({ access_token: accessToken }); where: { userId, provider: 'google' },
});
if (!account) {
throw new Error('Google account not found');
}
const auth = new google.auth.OAuth2(
process.env.GOOGLE_CLIENT_ID,
process.env.GOOGLE_CLIENT_SECRET
);
auth.setCredentials({
access_token: account.access_token,
refresh_token: account.refresh_token,
expiry_date: account.expires_at ? account.expires_at * 1000 : null,
});
// Check if the token is expired or will expire in the next 1 minute
// NextAuth stores expires_at in seconds
const isExpired = account.expires_at ? (account.expires_at * 1000) < (Date.now() + 60000) : true;
if (isExpired && account.refresh_token) {
try {
const { credentials } = await auth.refreshAccessToken();
auth.setCredentials(credentials);
// Update database with new tokens
await prisma.account.update({
where: { id: account.id },
data: {
access_token: credentials.access_token,
refresh_token: credentials.refresh_token || account.refresh_token,
expires_at: credentials.expiry_date ? Math.floor(credentials.expiry_date / 1000) : null,
},
});
console.log('Successfully refreshed Google access token for user:', userId);
} catch (error) {
console.error('Error refreshing access token:', error);
// If refresh fails, we still return the auth object, but requests will fail with 401
}
}
return auth;
}
export async function uploadToDrive(auth: any, fileName: string, content: string, folderId?: string) {
const drive = google.drive({ version: 'v3', auth }); const drive = google.drive({ version: 'v3', auth });
const fileMetadata: any = { const fileMetadata: any = {
@@ -17,7 +63,7 @@ export async function uploadToDrive(accessToken: string, fileName: string, conte
} }
const media = { const media = {
mimeType: 'text/markdown', mimeType: 'text/html',
body: Readable.from([content]), body: Readable.from([content]),
}; };
@@ -34,14 +80,11 @@ export async function uploadToDrive(accessToken: string, fileName: string, conte
} }
} }
export async function updateDriveFile(accessToken: string, fileId: string, content: string) { export async function updateDriveFile(auth: any, fileId: string, content: string) {
const auth = new google.auth.OAuth2();
auth.setCredentials({ access_token: accessToken });
const drive = google.drive({ version: 'v3', auth }); const drive = google.drive({ version: 'v3', auth });
const media = { const media = {
mimeType: 'text/markdown', mimeType: 'text/html',
body: Readable.from([content]), body: Readable.from([content]),
}; };
@@ -58,23 +101,66 @@ export async function updateDriveFile(accessToken: string, fileId: string, conte
} }
} }
export function generateReportMarkdown(report: any) { export function generateReportHTML(report: any) {
let md = `# WFH Daily Report - ${new Date(report.date).toLocaleDateString()}\n`; const dateObj = new Date(report.date);
md += `**Employee:** ${report.user.name}\n`; const dateStr = dateObj.toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });
md += `**Manager:** ${report.managerName}\n\n`; const plannedTasks = report.tasks.filter((t: any) => t.type === 'PLANNED');
const completedTasks = report.tasks.filter((t: any) => t.type === 'COMPLETED');
md += `## Planned Tasks\n`; const cellStyle = "padding: 10px; border-bottom: 1px solid #e2e8f0; font-family: Arial, sans-serif; font-size: 11pt;";
report.tasks.filter((t: any) => t.type === 'PLANNED').forEach((t: any) => { const headerStyle = "padding: 12px 10px; background-color: #f1f5f9; border-bottom: 2px solid #cbd5e1; font-family: Arial, sans-serif; font-size: 11pt; font-weight: bold; text-align: left; color: #334155;";
md += `- [ ] ${t.description} (Est: ${t.timeEstimate})\n`;
if (t.notes) md += ` - Notes: ${t.notes}\n`;
});
md += `\n## Completed Tasks\n`; return `
report.tasks.filter((t: any) => t.type === 'COMPLETED').forEach((t: any) => { <html>
md += `- [x] ${t.description}\n`; <body style="font-family: Arial, sans-serif; color: #334155; line-height: 1.6; max-width: 800px; margin: 0 auto; padding: 20px;">
md += ` - Status: ${t.status}\n`; <h1 style="color: #0f172a; border-bottom: 3px solid #3b82f6; padding-bottom: 10px; font-family: Arial, sans-serif; margin-bottom: 20px;">WFH Daily Report</h1>
if (t.link) md += ` - Work Link: ${t.link}\n`;
});
return md; <div style="background-color: #f8fafc; padding: 20px; border-left: 4px solid #3b82f6; border-radius: 4px; margin-bottom: 30px; font-family: Arial, sans-serif;">
<p style="margin: 0 0 8px 0; font-size: 11pt;"><strong>Date:</strong> ${dateStr}</p>
<p style="margin: 0 0 8px 0; font-size: 11pt;"><strong>Employee:</strong> ${report.user.name}</p>
<p style="margin: 0; font-size: 11pt;"><strong>Manager:</strong> ${report.managerName || 'N/A'}</p>
</div>
<h2 style="color: #1e293b; margin-top: 30px; margin-bottom: 15px; font-family: Arial, sans-serif;">Planned Tasks</h2>
${plannedTasks.length > 0 ? `
<table style="width: 100%; border-collapse: collapse; margin-bottom: 30px;">
<tr>
<th style="${headerStyle} width: 45%;">Description</th>
<th style="${headerStyle} width: 20%;">Estimate</th>
<th style="${headerStyle} width: 35%;">Notes</th>
</tr>
${plannedTasks.map((t: any) => `
<tr>
<td style="${cellStyle}">${t.description}</td>
<td style="${cellStyle} color: #64748b;">${t.timeEstimate || '-'}</td>
<td style="${cellStyle} color: #64748b;">${t.notes || '-'}</td>
</tr>
`).join('')}
</table>
` : `<p style="font-style: italic; color: #94a3b8; font-family: Arial, sans-serif; margin-bottom: 30px;">No planned tasks for today.</p>`}
<h2 style="color: #1e293b; margin-top: 30px; margin-bottom: 15px; font-family: Arial, sans-serif;">Completed Tasks</h2>
${completedTasks.length > 0 ? `
<table style="width: 100%; border-collapse: collapse; margin-bottom: 30px;">
<tr>
<th style="${headerStyle} width: 40%;">Description</th>
<th style="${headerStyle} width: 20%;">Status</th>
<th style="${headerStyle} width: 40%;">Work Link</th>
</tr>
${completedTasks.map((t: any) => `
<tr>
<td style="${cellStyle}">${t.description}</td>
<td style="${cellStyle} font-weight: bold; color: #059669;">${t.status || 'Done'}</td>
<td style="${cellStyle}">${t.link ? `<a href="${t.link}" style="color: #2563eb; text-decoration: none;">${t.link}</a>` : '-'}</td>
</tr>
`).join('')}
</table>
` : `<p style="font-style: italic; color: #94a3b8; font-family: Arial, sans-serif; margin-bottom: 30px;">No completed tasks reported today.</p>`}
<div style="margin-top: 50px; font-size: 9pt; color: #cbd5e1; text-align: center; border-top: 1px solid #e2e8f0; padding-top: 20px; font-family: Arial, sans-serif;">
Generated automatically by WFH App
</div>
</body>
</html>
`;
} }