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

43
.gitignore vendored Normal file
View File

@@ -0,0 +1,43 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
/src/generated/prisma

66
Dockerfile Normal file
View File

@@ -0,0 +1,66 @@
FROM node:20-alpine AS base
# Install dependencies only when needed
FROM base AS deps
RUN apk add --no-cache libc6-compat
WORKDIR /app
COPY package.json package-lock.json* ./
RUN npm ci
# Rebuild the source code only when needed
FROM base AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
# Generate Prisma Client (with SQLite)
ENV DATABASE_URL="file:/app/data/dev.db"
RUN npx prisma generate
# Disable telemetry during build
ENV NEXT_TELEMETRY_DISABLED 1
RUN npm run build
# Production image, copy all the files and run next
FROM base AS runner
WORKDIR /app
ENV NODE_ENV production
ENV NEXT_TELEMETRY_DISABLED 1
ENV DATABASE_URL="file:/app/data/dev.db"
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs
# Create data directory for SQLite and set permissions
RUN mkdir -p /app/data && chown nextjs:nodejs /app/data
COPY --from=builder /app/public ./public
# Set the correct permission for prerender cache
RUN mkdir .next
RUN chown nextjs:nodejs .next
# Automatically leverage output traces to reduce image size
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
COPY --from=builder --chown=nextjs:nodejs /app/prisma ./prisma
USER nextjs
EXPOSE 3000
ENV PORT 3000
# script to run migrations before starting
COPY --chown=nextjs:nodejs <<EOF /app/entrypoint.sh
#!/bin/sh
npx prisma db push --accept-data-loss
node server.js
EOF
RUN chmod +x /app/entrypoint.sh
CMD ["/app/entrypoint.sh"]

52
README.md Normal file
View File

@@ -0,0 +1,52 @@
# WFH Daily Report App
A sleek, modern, and dockerized web application for employees to track and submit their daily work-from-home reports. Features a stunning glassmorphic design and seamless integration with Google Workspace.
## ✨ Features
- **Premium UI**: Modern glassmorphism aesthetics with smooth animations and responsive design.
- **Google OAuth 2.0**: Secure authentication using your company's Google Workspace accounts.
- **Multi-Step Reporting**:
- **Morning**: Log planned tasks, time estimates, and initial notes.
- **Evening**: Review achievements, update statuses, and submit links to completed work.
- **Smart Admin Logic**:
- The first user to log in is automatically granted the **ADMIN** role.
- Exclusive **Admin Panel** to search and review all employee reports.
- **Google Drive Integration**:
- Automatically exports completed reports as Google Docs.
- Admins can designate a specific folder for all exports.
- **Single-Container Architecture**: Uses SQLite for persistent storage, making it ideal for "drop-in" deployments (e.g., Unraid, Synology).
## 🚀 Quick Start
### 1. Prerequisites
- [Google Cloud Console](https://console.cloud.google.com/) Project with:
- OAuth 2.0 Credentials (Web Application)
- Google Drive API enabled
- Docker installed on your host.
### 2. Environment Setup
Copy `.env.example` to `.env` and provide your credentials:
```bash
cp .env.example .env
```
### 3. Run with Docker
```bash
# Build and run the container
docker build -t wfh-report .
docker run -p 3000:3000 \
--env-file .env \
-v $(pwd)/data:/app/data \
wfh-report
```
## 🏡 Unraid Installation
For specific instructions on installing this on Unraid (including volume mapping and Unraid UI configuration), please refer to our [Unraid Installation Guide](C:\Users\stedw\.gemini\antigravity\brain\26965ef4-0e57-4fac-9aaf-0111085e228b\unraid_install.md).
## 🛠️ Tech Stack
- **Framework**: [Next.js](https://nextjs.org/) (App Router)
- **Database**: [SQLite](https://sqlite.org/) via [Prisma ORM](https://www.prisma.io/)
- **Auth**: [NextAuth.js](https://next-auth.js.org/)
- **Styles**: Vanilla CSS & TailwindCSS (for utility)
- **Icons**: [Lucide React](https://lucide.dev/)

18
eslint.config.mjs Normal file
View File

@@ -0,0 +1,18 @@
import { defineConfig, globalIgnores } from "eslint/config";
import nextVitals from "eslint-config-next/core-web-vitals";
import nextTs from "eslint-config-next/typescript";
const eslintConfig = defineConfig([
...nextVitals,
...nextTs,
// Override default ignores of eslint-config-next.
globalIgnores([
// Default ignores of eslint-config-next:
".next/**",
"out/**",
"build/**",
"next-env.d.ts",
]),
]);
export default eslintConfig;

6
next.config.mjs Normal file
View File

@@ -0,0 +1,6 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
output: 'standalone',
};
export default nextConfig;

7
next.config.ts Normal file
View File

@@ -0,0 +1,7 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
/* config options here */
};
export default nextConfig;

8260
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

32
package.json Normal file
View File

@@ -0,0 +1,32 @@
{
"name": "wfh",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "eslint"
},
"dependencies": {
"@next-auth/prisma-adapter": "^1.0.7",
"@prisma/client": "^7.5.0",
"googleapis": "^171.4.0",
"lucide-react": "^0.577.0",
"next": "16.1.6",
"next-auth": "^4.24.13",
"prisma": "^7.5.0",
"react": "19.2.3",
"react-dom": "19.2.3"
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"eslint": "^9",
"eslint-config-next": "16.1.6",
"tailwindcss": "^4",
"typescript": "^5"
}
}

7
postcss.config.mjs Normal file
View File

@@ -0,0 +1,7 @@
const config = {
plugins: {
"@tailwindcss/postcss": {},
},
};
export default config;

14
prisma.config.ts Normal file
View File

@@ -0,0 +1,14 @@
// This file was generated by Prisma, and assumes you have installed the following:
// npm install --save-dev prisma dotenv
import "dotenv/config";
import { defineConfig } from "prisma/config";
export default defineConfig({
schema: "prisma/schema.prisma",
migrations: {
path: "prisma/migrations",
},
datasource: {
url: process.env["DATABASE_URL"],
},
});

104
prisma/schema.prisma Normal file
View File

@@ -0,0 +1,104 @@
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "sqlite"
url = env("DATABASE_URL")
}
model Account {
id String @id @default(cuid())
userId String
type String
provider String
providerAccountId String
refresh_token String?
access_token String?
expires_at Int?
token_type String?
scope String?
id_token String?
session_state String?
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@unique([provider, providerAccountId])
}
model Session {
id String @id @default(cuid())
sessionToken String @unique
userId String
expires DateTime
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
}
model User {
id String @id @default(cuid())
name String?
email String? @unique
emailVerified DateTime?
image String?
role Role @default(EMPLOYEE)
accounts Account[]
sessions Session[]
reports Report[]
}
model VerificationToken {
identifier String
token String @unique
expires DateTime
@@unique([identifier, token])
}
enum Role {
EMPLOYEE
ADMIN
}
model Report {
id String @id @default(cuid())
date DateTime @default(now())
managerName String
status ReportStatus @default(IN_PROGRESS)
userId String
user User @relation(fields: [userId], references: [id])
tasks Task[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
enum ReportStatus {
IN_PROGRESS
COMPLETED
SUBMITTED
}
model Task {
id String @id @default(cuid())
type TaskType
description String
timeEstimate String?
notes String?
status String? @default("PENDING") // For completed tasks: DONE, IN_PROGRESS, etc.
link String? // Google Drive link
reportId String
report Report @relation(fields: [reportId], references: [id], onDelete: Cascade)
}
model Setting {
id String @id @default(cuid())
key String @unique
value String
}
enum TaskType {
PLANNED
COMPLETED
}

1
public/file.svg Normal file
View File

@@ -0,0 +1 @@
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>

After

Width:  |  Height:  |  Size: 391 B

1
public/globe.svg Normal file
View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

1
public/next.svg Normal file
View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

1
public/vercel.svg Normal file
View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>

After

Width:  |  Height:  |  Size: 128 B

1
public/window.svg Normal file
View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>

After

Width:  |  Height:  |  Size: 385 B

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;
}
}

34
tsconfig.json Normal file
View File

@@ -0,0 +1,34 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./src/*"]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts"
],
"exclude": ["node_modules"]
}

74
unraid_install.md Normal file
View File

@@ -0,0 +1,74 @@
# Unraid Installation Guide for WFH Daily Report
To install the WFH Daily Report app on your Unraid server, follow these steps.
## Docker Configuration
1. **Go to the 'Docker' tab** on your Unraid dashboard.
2. **Click 'Add Container'** (at the bottom).
3. **Configure the following settings**:
- **Name**: `WFH-Daily-Report`
- **Repository**: `[your-docker-registry]/wfh-daily-report:latest` (or your local build)
- **Network Type**: `Bridge`
- **WebUI**: `http://[IP]:[PORT:3000]`
### 1. Port Mapping
- **Container Port**: `3000`
- **Host Port**: `3000` (or any free port on your server)
### 2. Path Mapping (Volumes)
Adding a path mapping ensures your reports (SQLite database) persist when the container updates.
- **Container Path**: `/app/data`
- **Host Path**: `/mnt/user/appdata/wfh-daily-report/data`
- **Access Mode**: `Read/Write`
### 3. Environment Variables
Click **'Add another Path, Port, Variable, Label or Device'** to add each of these required variables:
| Variable | Recommended Value / Description |
| :--- | :--- |
| `NEXTAUTH_URL` | `http://[your-unraid-ip]:3000` |
| `NEXTAUTH_SECRET` | A random 32-char hex string (e.g. from `openssl rand -hex 32`) |
| `GOOGLE_CLIENT_ID` | Your Google Cloud Client ID |
| `GOOGLE_CLIENT_SECRET` | Your Google Cloud Client Secret |
| `DATABASE_URL` | `file:/app/data/dev.db` |
---
## Obtaining Google OAuth Credentials
To enable login and Google Drive exports, you must create a project in the [Google Cloud Console](https://console.cloud.google.com/).
### 1. Create a New Project
- Click the project dropdown in the top-left and select **'New Project'**.
- Give it a name like `WFH-Daily-Report` and click **Create**.
### 2. Configure OAuth Consent Screen
- Go to **APIs & Services > OAuth consent screen**.
- Select **'Internal'** (if you have Google Workspace) or 'External'.
- Fill in the required App Information (App name, support email, developer contact).
- In the **Scopes** section, click **'Add or Remove Scopes'** and add:
- `.../auth/userinfo.email`
- `.../auth/userinfo.profile`
- `.../auth/drive.file` (Required for report exports)
### 3. Create Credentials
- Go to **APIs & Services > Credentials**.
- Click **'Create Credentials'** and select **'OAuth client ID'**.
- Select **'Web application'** as the Application type.
- **Authorized Redirect URIs**: Add `http://[your-unraid-ip]:3000/api/auth/callback/google`.
- Click **Create**. Copy the **Client ID** and **Client Secret** now displayed.
### 4. Enable Google Drive API
- Go to **Enabled APIs & Services > Enable APIs and Services**.
- Search for **'Google Drive API'** and click **Enable**.
---
## Google Cloud Console Requirements
For the application to work, you must configure your Google Cloud Project:
1. **Authorized Redirect URIs**: `http://[your-unraid-ip]:3000/api/auth/callback/google`
2. **Scopes**: Enable `Google Drive API` and ensure `auth/drive.file` scope is requested.
## Support
The database is a single SQLite file located at `/mnt/user/appdata/wfh-daily-report/data/dev.db`. You can back this file up directly.