Compare commits
28 Commits
1b0982d523
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c0198df6d9 | ||
|
|
f1a3a31a94 | ||
| e08a2375ae | |||
|
|
707f632d34 | ||
| 6813602b6c | |||
|
|
65a4f79131 | ||
| 9046370b64 | |||
|
|
0e2dc27779 | ||
| 9e735b00f2 | |||
|
|
b2df27cfc5 | ||
|
|
5e3ca19c83 | ||
| b81a568592 | |||
| 04ebc91e9f | |||
| 8eaf239c5d | |||
| 2077ab3275 | |||
| 19b1f26254 | |||
| bc9a13bfe4 | |||
| cfeee5dc2a | |||
| a091420573 | |||
| b1fa70eba4 | |||
| ca414bb903 | |||
| 716b37c6f2 | |||
| 8c7142ca78 | |||
| 8b18566761 | |||
| 1c12b9a70d | |||
| ea5b4a955d | |||
| d2d1eb17b5 | |||
| 3e536a0a0e |
@@ -0,0 +1,9 @@
|
|||||||
|
import "dotenv/config";
|
||||||
|
import { defineConfig, env } from "prisma/config";
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
schema: "prisma/schema.prisma",
|
||||||
|
datasource: {
|
||||||
|
url: env("DATABASE_URL") ?? "file:./dev.db",
|
||||||
|
},
|
||||||
|
});
|
||||||
8
.claude/settings.local.json
Normal file
8
.claude/settings.local.json
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"permissions": {
|
||||||
|
"allow": [
|
||||||
|
"Bash(npx prisma migrate dev --name add-drive-file-id)",
|
||||||
|
"Bash(npx prisma db push)"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
1
.claude/worktrees/quirky-golick
Submodule
1
.claude/worktrees/quirky-golick
Submodule
Submodule .claude/worktrees/quirky-golick added at 04ebc91e9f
1
.claude/worktrees/reverent-proskuriakova
Submodule
1
.claude/worktrees/reverent-proskuriakova
Submodule
Submodule .claude/worktrees/reverent-proskuriakova added at 19b1f26254
1
.claude/worktrees/suspicious-wilson
Submodule
1
.claude/worktrees/suspicious-wilson
Submodule
Submodule .claude/worktrees/suspicious-wilson added at 707f632d34
32
.stignore
Normal file
32
.stignore
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
// Git internals - never sync
|
||||||
|
.git
|
||||||
|
|
||||||
|
// Dependencies
|
||||||
|
node_modules
|
||||||
|
|
||||||
|
// Next.js build output
|
||||||
|
.next
|
||||||
|
out
|
||||||
|
|
||||||
|
// Local env files with secrets
|
||||||
|
.env
|
||||||
|
.env.local
|
||||||
|
.env.*.local
|
||||||
|
|
||||||
|
// Database files (use migrations, not the file)
|
||||||
|
*.db
|
||||||
|
*.db-journal
|
||||||
|
*.db-shm
|
||||||
|
*.db-wal
|
||||||
|
|
||||||
|
// Build artifacts
|
||||||
|
build
|
||||||
|
tsconfig.tsbuildinfo
|
||||||
|
|
||||||
|
// Syncthing own temp files (safety net)
|
||||||
|
~syncthing~*
|
||||||
|
.syncthing.*
|
||||||
|
|
||||||
|
// OS junk
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
14
Dockerfile
14
Dockerfile
@@ -1,5 +1,4 @@
|
|||||||
FROM node:20-alpine AS base
|
FROM node:20-alpine AS base
|
||||||
RUN apk update && apk upgrade --no-cache
|
|
||||||
|
|
||||||
# Install dependencies only when needed
|
# Install dependencies only when needed
|
||||||
FROM base AS deps
|
FROM base AS deps
|
||||||
@@ -7,7 +6,7 @@ RUN apk add --no-cache libc6-compat openssl
|
|||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
COPY package.json package-lock.json* ./
|
COPY package.json package-lock.json* ./
|
||||||
RUN npm ci
|
RUN npm install
|
||||||
|
|
||||||
# Rebuild the source code only when needed
|
# Rebuild the source code only when needed
|
||||||
FROM base AS builder
|
FROM base AS builder
|
||||||
@@ -35,9 +34,6 @@ ENV DATABASE_URL="file:/app/data/dev.db"
|
|||||||
RUN addgroup --system --gid 1001 nodejs
|
RUN addgroup --system --gid 1001 nodejs
|
||||||
RUN adduser --system --uid 1001 nextjs
|
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
|
COPY --from=builder /app/public ./public
|
||||||
|
|
||||||
# Set the correct permission for prerender cache
|
# Set the correct permission for prerender cache
|
||||||
@@ -48,6 +44,11 @@ RUN chown nextjs:nodejs .next
|
|||||||
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
|
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/.next/static ./.next/static
|
||||||
COPY --from=builder --chown=nextjs:nodejs /app/prisma ./prisma
|
COPY --from=builder --chown=nextjs:nodejs /app/prisma ./prisma
|
||||||
|
COPY --from=builder --chown=nextjs:nodejs /app/prisma.config.ts ./prisma.config.ts
|
||||||
|
COPY --from=deps --chown=nextjs:nodejs /app/node_modules ./node_modules
|
||||||
|
|
||||||
|
# Create data directory AFTER all copies so permissions are never clobbered
|
||||||
|
RUN mkdir -p /app/data && chown nextjs:nodejs /app/data && chmod 700 /app/data
|
||||||
|
|
||||||
USER nextjs
|
USER nextjs
|
||||||
|
|
||||||
@@ -58,7 +59,10 @@ ENV PORT=3000
|
|||||||
# script to run migrations before starting
|
# script to run migrations before starting
|
||||||
COPY --chown=nextjs:nodejs <<EOF /app/entrypoint.sh
|
COPY --chown=nextjs:nodejs <<EOF /app/entrypoint.sh
|
||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
|
set -e
|
||||||
|
echo "Running prisma db push..."
|
||||||
npx prisma db push --accept-data-loss
|
npx prisma db push --accept-data-loss
|
||||||
|
echo "Starting server..."
|
||||||
node server.js
|
node server.js
|
||||||
EOF
|
EOF
|
||||||
|
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ docker run -p 3000:3000 \
|
|||||||
```
|
```
|
||||||
|
|
||||||
## 🏡 Unraid Installation
|
## 🏡 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).
|
For specific instructions on installing this on Unraid (including volume mapping and Unraid UI configuration), please refer to our [Unraid Installation Guide](https://git.alwisp.com/jason/wfh/src/branch/master/unraid_install.md).
|
||||||
|
|
||||||
## 🛠️ Tech Stack
|
## 🛠️ Tech Stack
|
||||||
- **Framework**: [Next.js](https://nextjs.org/) (App Router)
|
- **Framework**: [Next.js](https://nextjs.org/) (App Router)
|
||||||
|
|||||||
173
package-lock.json
generated
173
package-lock.json
generated
@@ -8,7 +8,6 @@
|
|||||||
"name": "wfh",
|
"name": "wfh",
|
||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@libsql/client": "^0.14.0",
|
|
||||||
"@next-auth/prisma-adapter": "^1.0.7",
|
"@next-auth/prisma-adapter": "^1.0.7",
|
||||||
"@prisma/adapter-libsql": "^7.5.0",
|
"@prisma/adapter-libsql": "^7.5.0",
|
||||||
"@prisma/client": "^7.5.0",
|
"@prisma/client": "^7.5.0",
|
||||||
@@ -1127,75 +1126,6 @@
|
|||||||
"@jridgewell/sourcemap-codec": "^1.4.14"
|
"@jridgewell/sourcemap-codec": "^1.4.14"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@libsql/client": {
|
|
||||||
"version": "0.14.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/@libsql/client/-/client-0.14.0.tgz",
|
|
||||||
"integrity": "sha512-/9HEKfn6fwXB5aTEEoMeFh4CtG0ZzbncBb1e++OCdVpgKZ/xyMsIVYXm0w7Pv4RUel803vE6LwniB3PqD72R0Q==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"@libsql/core": "^0.14.0",
|
|
||||||
"@libsql/hrana-client": "^0.7.0",
|
|
||||||
"js-base64": "^3.7.5",
|
|
||||||
"libsql": "^0.4.4",
|
|
||||||
"promise-limit": "^2.7.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@libsql/core": {
|
|
||||||
"version": "0.14.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/@libsql/core/-/core-0.14.0.tgz",
|
|
||||||
"integrity": "sha512-nhbuXf7GP3PSZgdCY2Ecj8vz187ptHlZQ0VRc751oB2C1W8jQUXKKklvt7t1LJiUTQBVJuadF628eUk+3cRi4Q==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"js-base64": "^3.7.5"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@libsql/darwin-arm64": {
|
|
||||||
"version": "0.4.7",
|
|
||||||
"resolved": "https://registry.npmjs.org/@libsql/darwin-arm64/-/darwin-arm64-0.4.7.tgz",
|
|
||||||
"integrity": "sha512-yOL742IfWUlUevnI5PdnIT4fryY3LYTdLm56bnY0wXBw7dhFcnjuA7jrH3oSVz2mjZTHujxoITgAE7V6Z+eAbg==",
|
|
||||||
"cpu": [
|
|
||||||
"arm64"
|
|
||||||
],
|
|
||||||
"license": "MIT",
|
|
||||||
"optional": true,
|
|
||||||
"os": [
|
|
||||||
"darwin"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"node_modules/@libsql/darwin-x64": {
|
|
||||||
"version": "0.4.7",
|
|
||||||
"resolved": "https://registry.npmjs.org/@libsql/darwin-x64/-/darwin-x64-0.4.7.tgz",
|
|
||||||
"integrity": "sha512-ezc7V75+eoyyH07BO9tIyJdqXXcRfZMbKcLCeF8+qWK5nP8wWuMcfOVywecsXGRbT99zc5eNra4NEx6z5PkSsA==",
|
|
||||||
"cpu": [
|
|
||||||
"x64"
|
|
||||||
],
|
|
||||||
"license": "MIT",
|
|
||||||
"optional": true,
|
|
||||||
"os": [
|
|
||||||
"darwin"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"node_modules/@libsql/hrana-client": {
|
|
||||||
"version": "0.7.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/@libsql/hrana-client/-/hrana-client-0.7.0.tgz",
|
|
||||||
"integrity": "sha512-OF8fFQSkbL7vJY9rfuegK1R7sPgQ6kFMkDamiEccNUvieQ+3urzfDFI616oPl8V7T9zRmnTkSjMOImYCAVRVuw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"@libsql/isomorphic-fetch": "^0.3.1",
|
|
||||||
"@libsql/isomorphic-ws": "^0.1.5",
|
|
||||||
"js-base64": "^3.7.5",
|
|
||||||
"node-fetch": "^3.3.2"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@libsql/isomorphic-fetch": {
|
|
||||||
"version": "0.3.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/@libsql/isomorphic-fetch/-/isomorphic-fetch-0.3.1.tgz",
|
|
||||||
"integrity": "sha512-6kK3SUK5Uu56zPq/Las620n5aS9xJq+jMBcNSOmjhNf/MUvdyji4vrMTqD7ptY7/4/CAVEAYDeotUz60LNQHtw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"engines": {
|
|
||||||
"node": ">=18.0.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@libsql/isomorphic-ws": {
|
"node_modules/@libsql/isomorphic-ws": {
|
||||||
"version": "0.1.5",
|
"version": "0.1.5",
|
||||||
"resolved": "https://registry.npmjs.org/@libsql/isomorphic-ws/-/isomorphic-ws-0.1.5.tgz",
|
"resolved": "https://registry.npmjs.org/@libsql/isomorphic-ws/-/isomorphic-ws-0.1.5.tgz",
|
||||||
@@ -1232,71 +1162,6 @@
|
|||||||
"linux"
|
"linux"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"node_modules/@libsql/linux-arm64-gnu": {
|
|
||||||
"version": "0.4.7",
|
|
||||||
"resolved": "https://registry.npmjs.org/@libsql/linux-arm64-gnu/-/linux-arm64-gnu-0.4.7.tgz",
|
|
||||||
"integrity": "sha512-WlX2VYB5diM4kFfNaYcyhw5y+UJAI3xcMkEUJZPtRDEIu85SsSFrQ+gvoKfcVh76B//ztSeEX2wl9yrjF7BBCA==",
|
|
||||||
"cpu": [
|
|
||||||
"arm64"
|
|
||||||
],
|
|
||||||
"license": "MIT",
|
|
||||||
"optional": true,
|
|
||||||
"os": [
|
|
||||||
"linux"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"node_modules/@libsql/linux-arm64-musl": {
|
|
||||||
"version": "0.4.7",
|
|
||||||
"resolved": "https://registry.npmjs.org/@libsql/linux-arm64-musl/-/linux-arm64-musl-0.4.7.tgz",
|
|
||||||
"integrity": "sha512-6kK9xAArVRlTCpWeqnNMCoXW1pe7WITI378n4NpvU5EJ0Ok3aNTIC2nRPRjhro90QcnmLL1jPcrVwO4WD1U0xw==",
|
|
||||||
"cpu": [
|
|
||||||
"arm64"
|
|
||||||
],
|
|
||||||
"license": "MIT",
|
|
||||||
"optional": true,
|
|
||||||
"os": [
|
|
||||||
"linux"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"node_modules/@libsql/linux-x64-gnu": {
|
|
||||||
"version": "0.4.7",
|
|
||||||
"resolved": "https://registry.npmjs.org/@libsql/linux-x64-gnu/-/linux-x64-gnu-0.4.7.tgz",
|
|
||||||
"integrity": "sha512-CMnNRCmlWQqqzlTw6NeaZXzLWI8bydaXDke63JTUCvu8R+fj/ENsLrVBtPDlxQ0wGsYdXGlrUCH8Qi9gJep0yQ==",
|
|
||||||
"cpu": [
|
|
||||||
"x64"
|
|
||||||
],
|
|
||||||
"license": "MIT",
|
|
||||||
"optional": true,
|
|
||||||
"os": [
|
|
||||||
"linux"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"node_modules/@libsql/linux-x64-musl": {
|
|
||||||
"version": "0.4.7",
|
|
||||||
"resolved": "https://registry.npmjs.org/@libsql/linux-x64-musl/-/linux-x64-musl-0.4.7.tgz",
|
|
||||||
"integrity": "sha512-nI6tpS1t6WzGAt1Kx1n1HsvtBbZ+jHn0m7ogNNT6pQHZQj7AFFTIMeDQw/i/Nt5H38np1GVRNsFe99eSIMs9XA==",
|
|
||||||
"cpu": [
|
|
||||||
"x64"
|
|
||||||
],
|
|
||||||
"license": "MIT",
|
|
||||||
"optional": true,
|
|
||||||
"os": [
|
|
||||||
"linux"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"node_modules/@libsql/win32-x64-msvc": {
|
|
||||||
"version": "0.4.7",
|
|
||||||
"resolved": "https://registry.npmjs.org/@libsql/win32-x64-msvc/-/win32-x64-msvc-0.4.7.tgz",
|
|
||||||
"integrity": "sha512-7pJzOWzPm6oJUxml+PCDRzYQ4A1hTMHAciTAHfFK4fkbDZX33nWPVG7Y3vqdKtslcwAzwmrNDc6sXy2nwWnbiw==",
|
|
||||||
"cpu": [
|
|
||||||
"x64"
|
|
||||||
],
|
|
||||||
"license": "MIT",
|
|
||||||
"optional": true,
|
|
||||||
"os": [
|
|
||||||
"win32"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"node_modules/@mrleebo/prisma-ast": {
|
"node_modules/@mrleebo/prisma-ast": {
|
||||||
"version": "0.13.1",
|
"version": "0.13.1",
|
||||||
"resolved": "https://registry.npmjs.org/@mrleebo/prisma-ast/-/prisma-ast-0.13.1.tgz",
|
"resolved": "https://registry.npmjs.org/@mrleebo/prisma-ast/-/prisma-ast-0.13.1.tgz",
|
||||||
@@ -5874,44 +5739,6 @@
|
|||||||
"node": ">= 0.8.0"
|
"node": ">= 0.8.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/libsql": {
|
|
||||||
"version": "0.4.7",
|
|
||||||
"resolved": "https://registry.npmjs.org/libsql/-/libsql-0.4.7.tgz",
|
|
||||||
"integrity": "sha512-T9eIRCs6b0J1SHKYIvD8+KCJMcWZ900iZyxdnSCdqxN12Z1ijzT+jY5nrk72Jw4B0HGzms2NgpryArlJqvc3Lw==",
|
|
||||||
"cpu": [
|
|
||||||
"x64",
|
|
||||||
"arm64",
|
|
||||||
"wasm32"
|
|
||||||
],
|
|
||||||
"license": "MIT",
|
|
||||||
"os": [
|
|
||||||
"darwin",
|
|
||||||
"linux",
|
|
||||||
"win32"
|
|
||||||
],
|
|
||||||
"dependencies": {
|
|
||||||
"@neon-rs/load": "^0.0.4",
|
|
||||||
"detect-libc": "2.0.2"
|
|
||||||
},
|
|
||||||
"optionalDependencies": {
|
|
||||||
"@libsql/darwin-arm64": "0.4.7",
|
|
||||||
"@libsql/darwin-x64": "0.4.7",
|
|
||||||
"@libsql/linux-arm64-gnu": "0.4.7",
|
|
||||||
"@libsql/linux-arm64-musl": "0.4.7",
|
|
||||||
"@libsql/linux-x64-gnu": "0.4.7",
|
|
||||||
"@libsql/linux-x64-musl": "0.4.7",
|
|
||||||
"@libsql/win32-x64-msvc": "0.4.7"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/libsql/node_modules/detect-libc": {
|
|
||||||
"version": "2.0.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.2.tgz",
|
|
||||||
"integrity": "sha512-UX6sGumvvqSaXgdKGUsgZWqcUyIXZ/vZTrlRT/iobiKhGL0zL4d3osHj3uqllWJK+i+sixDS/3COVEOFbupFyw==",
|
|
||||||
"license": "Apache-2.0",
|
|
||||||
"engines": {
|
|
||||||
"node": ">=8"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/lightningcss": {
|
"node_modules/lightningcss": {
|
||||||
"version": "1.31.1",
|
"version": "1.31.1",
|
||||||
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.31.1.tgz",
|
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.31.1.tgz",
|
||||||
|
|||||||
@@ -9,7 +9,6 @@
|
|||||||
"lint": "eslint"
|
"lint": "eslint"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@libsql/client": "^0.14.0",
|
|
||||||
"@next-auth/prisma-adapter": "^1.0.7",
|
"@next-auth/prisma-adapter": "^1.0.7",
|
||||||
"@prisma/adapter-libsql": "^7.5.0",
|
"@prisma/adapter-libsql": "^7.5.0",
|
||||||
"@prisma/client": "^7.5.0",
|
"@prisma/client": "^7.5.0",
|
||||||
|
|||||||
@@ -1,16 +1,9 @@
|
|||||||
import "dotenv/config";
|
import "dotenv/config";
|
||||||
import { defineConfig } from "prisma/config";
|
import { defineConfig, env } from "prisma/config";
|
||||||
import { createClient } from "@libsql/client";
|
|
||||||
import { PrismaLibSql } from "@prisma/adapter-libsql";
|
|
||||||
|
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
schema: "prisma/schema.prisma",
|
schema: "prisma/schema.prisma",
|
||||||
migrate: {
|
datasource: {
|
||||||
adapter: async () => {
|
url: env("DATABASE_URL") ?? "file:./dev.db",
|
||||||
const libsql = createClient({
|
|
||||||
url: process.env.DATABASE_URL ?? "file:./dev.db",
|
|
||||||
});
|
|
||||||
return new PrismaLibSql(libsql);
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -66,6 +66,7 @@ model Report {
|
|||||||
date DateTime @default(now())
|
date DateTime @default(now())
|
||||||
managerName String
|
managerName String
|
||||||
status ReportStatus @default(IN_PROGRESS)
|
status ReportStatus @default(IN_PROGRESS)
|
||||||
|
driveFileId String?
|
||||||
userId String
|
userId String
|
||||||
user User @relation(fields: [userId], references: [id])
|
user User @relation(fields: [userId], references: [id])
|
||||||
tasks Task[]
|
tasks Task[]
|
||||||
|
|||||||
62
src/app/api/admin/users/route.ts
Normal file
62
src/app/api/admin/users/route.ts
Normal 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);
|
||||||
|
}
|
||||||
@@ -2,12 +2,10 @@ import { NextResponse } from "next/server";
|
|||||||
export const dynamic = "force-dynamic";
|
export const dynamic = "force-dynamic";
|
||||||
export const runtime = "nodejs";
|
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, generateReportMarkdown } from "@/lib/google-drive";
|
import { uploadToDrive, updateDriveFile, generateReportHTML, getGoogleAuth } from "@/lib/google-drive";
|
||||||
import { getToken } from "next-auth/jwt";
|
|
||||||
|
|
||||||
export async function POST(
|
export async function POST(
|
||||||
req: Request,
|
req: Request,
|
||||||
@@ -15,11 +13,16 @@ export async function POST(
|
|||||||
) {
|
) {
|
||||||
const { id } = await params;
|
const { id } = await params;
|
||||||
const session = await getServerSession(authOptions);
|
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) {
|
if (!session?.user?.id) {
|
||||||
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
let auth;
|
||||||
|
try {
|
||||||
|
auth = await getGoogleAuth(session.user.id);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Failed to get Google Auth:", error);
|
||||||
return NextResponse.json({ error: "Unauthorized or missing Google token" }, { status: 401 });
|
return NextResponse.json({ error: "Unauthorized or missing Google token" }, { status: 401 });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -32,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
|
||||||
@@ -41,17 +44,23 @@ export async function POST(
|
|||||||
});
|
});
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const driveFile = await uploadToDrive(
|
let driveFile;
|
||||||
token.accessToken as string,
|
|
||||||
fileName,
|
if (report.driveFileId) {
|
||||||
markdown,
|
// Update the existing Drive file in place
|
||||||
folderSetting?.value
|
driveFile = await updateDriveFile(auth, report.driveFileId, htmlContent);
|
||||||
);
|
} else {
|
||||||
|
// First export — create a new Drive file and store its ID
|
||||||
// Update report status to SUBMITTED
|
driveFile = await uploadToDrive(auth, fileName, htmlContent, folderSetting?.value);
|
||||||
|
await prisma.report.update({
|
||||||
|
where: { id },
|
||||||
|
data: { driveFileId: driveFile.id },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
await prisma.report.update({
|
await prisma.report.update({
|
||||||
where: { id },
|
where: { id },
|
||||||
data: { status: 'SUBMITTED' }
|
data: { status: 'SUBMITTED' },
|
||||||
});
|
});
|
||||||
|
|
||||||
return NextResponse.json({ success: true, link: driveFile.webViewLink });
|
return NextResponse.json({ success: true, link: driveFile.webViewLink });
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ export async function GET() {
|
|||||||
|
|
||||||
const reports = await prisma.report.findMany({
|
const reports = await prisma.report.findMany({
|
||||||
where,
|
where,
|
||||||
include: { tasks: true },
|
include: { tasks: true, user: true },
|
||||||
orderBy: { date: "desc" },
|
orderBy: { date: "desc" },
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -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: {
|
||||||
|
|||||||
@@ -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,7 +114,15 @@ export default function AdminDashboard() {
|
|||||||
>
|
>
|
||||||
<ListChecks size={18} /> Reports
|
<ListChecks size={18} /> Reports
|
||||||
</button>
|
</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
|
||||||
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 ${
|
||||||
tab === "SETTINGS" ? "bg-accent-primary text-white" : "hover:bg-white/5 text-text-dim"
|
tab === "SETTINGS" ? "bg-accent-primary text-white" : "hover:bg-white/5 text-text-dim"
|
||||||
@@ -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">
|
||||||
|
|||||||
@@ -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) => {
|
||||||
try {
|
// 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 {
|
||||||
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) => {
|
||||||
@@ -314,12 +332,12 @@ export default function ReportForm() {
|
|||||||
</section>
|
</section>
|
||||||
|
|
||||||
<footer className="pt-8 border-t border-white/10 flex justify-end gap-4">
|
<footer className="pt-8 border-t border-white/10 flex justify-end gap-4">
|
||||||
<button
|
<button
|
||||||
onClick={exportToDrive}
|
onClick={exportToDrive}
|
||||||
disabled={saving || report.status === 'SUBMITTED'}
|
disabled={saving}
|
||||||
className="btn-primary flex items-center gap-2 px-8"
|
className="btn-primary flex items-center gap-2 px-8"
|
||||||
>
|
>
|
||||||
{saving ? "Processing..." : (report.status === 'SUBMITTED' ? "Already Submitted" : "Finalize & Export to Drive")}
|
{saving ? "Processing..." : (report.status === 'SUBMITTED' ? "Re-export to Drive" : "Finalize & Export to Drive")}
|
||||||
<Send size={18} />
|
<Send size={18} />
|
||||||
</button>
|
</button>
|
||||||
</footer>
|
</footer>
|
||||||
|
|||||||
@@ -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,23 +80,87 @@ export async function uploadToDrive(accessToken: string, fileName: string, conte
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function generateReportMarkdown(report: any) {
|
export async function updateDriveFile(auth: any, fileId: string, content: string) {
|
||||||
let md = `# WFH Daily Report - ${new Date(report.date).toLocaleDateString()}\n`;
|
const drive = google.drive({ version: 'v3', auth });
|
||||||
md += `**Employee:** ${report.user.name}\n`;
|
|
||||||
md += `**Manager:** ${report.managerName}\n\n`;
|
|
||||||
|
|
||||||
md += `## Planned Tasks\n`;
|
const media = {
|
||||||
report.tasks.filter((t: any) => t.type === 'PLANNED').forEach((t: any) => {
|
mimeType: 'text/html',
|
||||||
md += `- [ ] ${t.description} (Est: ${t.timeEstimate})\n`;
|
body: Readable.from([content]),
|
||||||
if (t.notes) md += ` - Notes: ${t.notes}\n`;
|
};
|
||||||
});
|
|
||||||
|
|
||||||
md += `\n## Completed Tasks\n`;
|
try {
|
||||||
report.tasks.filter((t: any) => t.type === 'COMPLETED').forEach((t: any) => {
|
const response = await drive.files.update({
|
||||||
md += `- [x] ${t.description}\n`;
|
fileId,
|
||||||
md += ` - Status: ${t.status}\n`;
|
media,
|
||||||
if (t.link) md += ` - Work Link: ${t.link}\n`;
|
fields: 'id, webViewLink',
|
||||||
});
|
});
|
||||||
|
return response.data;
|
||||||
return md;
|
} catch (error) {
|
||||||
|
console.error('Error updating Google Drive file:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function generateReportHTML(report: any) {
|
||||||
|
const dateObj = new Date(report.date);
|
||||||
|
const dateStr = dateObj.toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });
|
||||||
|
const plannedTasks = report.tasks.filter((t: any) => t.type === 'PLANNED');
|
||||||
|
const completedTasks = report.tasks.filter((t: any) => t.type === 'COMPLETED');
|
||||||
|
|
||||||
|
const cellStyle = "padding: 10px; border-bottom: 1px solid #e2e8f0; font-family: Arial, sans-serif; font-size: 11pt;";
|
||||||
|
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;";
|
||||||
|
|
||||||
|
return `
|
||||||
|
<html>
|
||||||
|
<body style="font-family: Arial, sans-serif; color: #334155; line-height: 1.6; max-width: 800px; margin: 0 auto; padding: 20px;">
|
||||||
|
<h1 style="color: #0f172a; border-bottom: 3px solid #3b82f6; padding-bottom: 10px; font-family: Arial, sans-serif; margin-bottom: 20px;">WFH Daily Report</h1>
|
||||||
|
|
||||||
|
<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>
|
||||||
|
`;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import { PrismaClient } from '@prisma/client'
|
import { PrismaClient } from '@prisma/client'
|
||||||
import { PrismaLibSql } from '@prisma/adapter-libsql'
|
import { PrismaLibSql } from '@prisma/adapter-libsql'
|
||||||
import { createClient } from '@libsql/client'
|
|
||||||
|
|
||||||
const globalForPrisma = globalThis as unknown as {
|
const globalForPrisma = globalThis as unknown as {
|
||||||
prisma: PrismaClient | undefined
|
prisma: PrismaClient | undefined
|
||||||
@@ -8,10 +7,9 @@ const globalForPrisma = globalThis as unknown as {
|
|||||||
|
|
||||||
function getPrismaClient(): PrismaClient {
|
function getPrismaClient(): PrismaClient {
|
||||||
if (!globalForPrisma.prisma) {
|
if (!globalForPrisma.prisma) {
|
||||||
const libsql = createClient({
|
const adapter = new PrismaLibSql({
|
||||||
url: process.env.DATABASE_URL ?? 'file:./dev.db',
|
url: process.env.DATABASE_URL ?? 'file:./dev.db',
|
||||||
})
|
})
|
||||||
const adapter = new PrismaLibSql(libsql)
|
|
||||||
globalForPrisma.prisma = new PrismaClient({
|
globalForPrisma.prisma = new PrismaClient({
|
||||||
adapter,
|
adapter,
|
||||||
log: process.env.NODE_ENV === 'development' ? ['query', 'error', 'warn'] : ['error'],
|
log: process.env.NODE_ENV === 'development' ? ['query', 'error', 'warn'] : ['error'],
|
||||||
|
|||||||
@@ -30,5 +30,5 @@
|
|||||||
".next/dev/types/**/*.ts",
|
".next/dev/types/**/*.ts",
|
||||||
"**/*.mts"
|
"**/*.mts"
|
||||||
],
|
],
|
||||||
"exclude": ["node_modules"]
|
"exclude": ["node_modules", "prisma.config.ts"]
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user