init
This commit is contained in:
@@ -0,0 +1,34 @@
|
|||||||
|
{
|
||||||
|
"permissions": {
|
||||||
|
"allow": [
|
||||||
|
"mcp__figma-console__figma_get_status",
|
||||||
|
"mcp__figma-console__figma_take_screenshot",
|
||||||
|
"mcp__figma-console__figma_get_selection",
|
||||||
|
"mcp__figma-console__figma_execute",
|
||||||
|
"mcp__figma-console__figma_reconnect",
|
||||||
|
"mcp__figma-console__figma_capture_screenshot",
|
||||||
|
"mcp__figma-console__figma_get_file_data",
|
||||||
|
"Bash(cd \"C:\\\\Users\\\\tom_chien\\\\Desktop\\\\TrendMicro_Projetc\\\\it_cost_dashboad\" && ls -la && node --version && npm --version)",
|
||||||
|
"Bash(cd \"C:\\\\Users\\\\tom_chien\\\\Desktop\\\\TrendMicro_Projetc\\\\it_cost_dashboad\" && npm install 2>&1 | tail -n 20)",
|
||||||
|
"Bash(cd \"C:\\\\Users\\\\tom_chien\\\\Desktop\\\\TrendMicro_Projetc\\\\it_cost_dashboad\" && npx prisma generate 2>&1 | tail -n 25)",
|
||||||
|
"Bash(cd \"C:\\\\Users\\\\tom_chien\\\\Desktop\\\\TrendMicro_Projetc\\\\it_cost_dashboad\" && npx prisma migrate dev --name init 2>&1 | tail -n 30)",
|
||||||
|
"Bash(cd \"C:\\\\Users\\\\tom_chien\\\\Desktop\\\\TrendMicro_Projetc\\\\it_cost_dashboad\" && npm run build 2>&1 | tail -n 45)",
|
||||||
|
"Bash(cd \"C:\\\\Users\\\\tom_chien\\\\Desktop\\\\TrendMicro_Projetc\\\\it_cost_dashboad\" && npm run build 2>&1 | tail -n 40)",
|
||||||
|
"Bash(cd \"C:\\\\Users\\\\tom_chien\\\\Desktop\\\\TrendMicro_Projetc\\\\it_cost_dashboad\" && rm -rf src/app/budgets src/app/reports && echo \"removed\" && ls src/app)",
|
||||||
|
"Bash(cd \"C:\\\\Users\\\\tom_chien\\\\Desktop\\\\TrendMicro_Projetc\\\\it_cost_dashboad\" && npm run build 2>&1 | tail -n 30)",
|
||||||
|
"Bash(cd \"C:\\\\Users\\\\tom_chien\\\\Desktop\\\\TrendMicro_Projetc\\\\it_cost_dashboad\" && tasklist | grep -i node || echo \"no node\"; echo \"---\"; npx next build 2>&1 | tail -n 35)",
|
||||||
|
"Bash(cd \"C:\\\\Users\\\\tom_chien\\\\Desktop\\\\TrendMicro_Projetc\\\\it_cost_dashboad\" && npx next build 2>&1 | tail -n 12)",
|
||||||
|
"Bash(cd \"C:/Users/tom_chien/Desktop/TrendMicro_Projetc/it_cost_dashboad\" && npx prisma migrate dev --name add_year --skip-seed 2>&1 | tail -30)",
|
||||||
|
"Bash(cd \"C:/Users/tom_chien/Desktop/TrendMicro_Projetc/it_cost_dashboad\" && taskkill //F //IM node.exe 2>&1 | head -5; sleep 1; npx prisma generate 2>&1 | tail -10)",
|
||||||
|
"Bash(cd \"C:/Users/tom_chien/Desktop/TrendMicro_Projetc/it_cost_dashboad\" && npx next build 2>&1 | tail -40)",
|
||||||
|
"Bash(taskkill //F //IM node.exe 2>&1 | head -3)",
|
||||||
|
"Bash(cd:*)",
|
||||||
|
"Bash(ssh:*)",
|
||||||
|
"Bash(node:*)",
|
||||||
|
"Bash(git fetch:*)",
|
||||||
|
"Bash(command:*)",
|
||||||
|
"Bash(timeout:*)",
|
||||||
|
"Bash(git:*)"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
# SQLite for local dev only. Production (MySQL/RDS) config lives in .env.production
|
||||||
|
# (gitignored) and uses prisma/prod/schema.prisma — see DEPLOY.md.
|
||||||
|
DATABASE_URL="file:./dev.db"
|
||||||
|
DATABASE_PROVIDER="sqlite"
|
||||||
|
|
||||||
|
# SSO secrets are NOT stored here (this file is committed). Dev auth vars live in
|
||||||
|
# .env.local (gitignored); prod auth vars in .env.production — see .env.production.example.
|
||||||
|
|
||||||
|
# Local break-glass admin login (username/password, in addition to SSO). The
|
||||||
|
# password is intentionally EMPTY here so local login is DISABLED by default;
|
||||||
|
# set a real value in the gitignored .env.local (dev) / .env.production (prod).
|
||||||
|
# Role model: config/users.json maps SSO emails -> "admin" | "user"; unlisted
|
||||||
|
# SSO emails cannot sign in. The local admin always has the admin role.
|
||||||
|
LOCAL_ADMIN_USERNAME="admin"
|
||||||
|
LOCAL_ADMIN_PASSWORD=""
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
# Production environment template (AWS RDS MySQL).
|
||||||
|
# Copy to .env.production on the EC2 host and fill in the real credentials.
|
||||||
|
# The real .env.production is gitignored so secrets never land in git.
|
||||||
|
#
|
||||||
|
# For Prisma CLI commands (migrate/seed), export these first:
|
||||||
|
# set -a && source .env.production && set +a
|
||||||
|
#
|
||||||
|
# Note: if the DB password contains URL-reserved characters, percent-encode them
|
||||||
|
# (e.g. "@" -> %40, "/" -> %2F, ":" -> %3A).
|
||||||
|
DATABASE_URL="mysql://USER:PASSWORD@it-cost-prod-db.c8hgbsblyypx.us-west-2.rds.amazonaws.com:3306/it_cost_dashboard"
|
||||||
|
DATABASE_PROVIDER="mysql"
|
||||||
|
NODE_ENV="production"
|
||||||
|
|
||||||
|
# --- Microsoft Entra ID (Azure AD) SSO ---
|
||||||
|
# Next.js does NOT load .env.local in production, so prod auth vars MUST live here.
|
||||||
|
# Register the prod redirect URI in Azure:
|
||||||
|
# https://<your-prod-domain>/api/auth/callback/microsoft-entra-id
|
||||||
|
AUTH_MICROSOFT_ENTRA_ID_ID="<prod Application (client) ID>"
|
||||||
|
AUTH_MICROSOFT_ENTRA_ID_SECRET="<prod client secret VALUE>"
|
||||||
|
AUTH_MICROSOFT_ENTRA_ID_ISSUER="https://login.microsoftonline.com/<Directory (tenant) ID>/v2.0"
|
||||||
|
# 32-byte random string used to sign session cookies (generate: npx auth secret).
|
||||||
|
AUTH_SECRET="<prod AUTH_SECRET>"
|
||||||
|
# Canonical public URL of the app. If TLS is terminated by a proxy/ALB in front
|
||||||
|
# of the app, set AUTH_TRUST_HOST=true instead of (or in addition to) AUTH_URL.
|
||||||
|
AUTH_URL="https://<your-prod-domain>"
|
||||||
|
# AUTH_TRUST_HOST=true
|
||||||
|
|
||||||
|
# --- Local break-glass admin + role model ---
|
||||||
|
# In addition to SSO, /login offers a username/password form for a local admin.
|
||||||
|
# A NON-EMPTY password ENABLES it; leave empty to disable local login entirely.
|
||||||
|
# This account always has the admin role and bypasses config/users.json (so you
|
||||||
|
# can still get in to fix a broken/empty allowlist).
|
||||||
|
LOCAL_ADMIN_USERNAME="admin"
|
||||||
|
LOCAL_ADMIN_PASSWORD="<set a strong password to enable local login>"
|
||||||
|
|
||||||
|
# Role-based access is driven by the committed, hand-edited allowlist
|
||||||
|
# config/users.json (email -> "admin" | "user"). SSO emails NOT listed there
|
||||||
|
# cannot sign in (fail closed). Edit that file and re-login / restart to apply.
|
||||||
+34
@@ -0,0 +1,34 @@
|
|||||||
|
# dependencies
|
||||||
|
/node_modules
|
||||||
|
/.pnp
|
||||||
|
.pnp.js
|
||||||
|
|
||||||
|
# next.js
|
||||||
|
/.next/
|
||||||
|
/out/
|
||||||
|
|
||||||
|
# production
|
||||||
|
/build
|
||||||
|
|
||||||
|
# misc
|
||||||
|
.DS_Store
|
||||||
|
*.pem
|
||||||
|
|
||||||
|
# debug
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
|
||||||
|
# local env files
|
||||||
|
.env*.local
|
||||||
|
|
||||||
|
# production env (contains real RDS credentials) - use .env.production.example as template
|
||||||
|
.env.production
|
||||||
|
|
||||||
|
# typescript
|
||||||
|
*.tsbuildinfo
|
||||||
|
next-env.d.ts
|
||||||
|
|
||||||
|
# prisma / sqlite
|
||||||
|
/prisma/dev.db
|
||||||
|
/prisma/dev.db-journal
|
||||||
@@ -0,0 +1,183 @@
|
|||||||
|
# Production Deployment (EC2 + RDS)
|
||||||
|
|
||||||
|
Dev runs on **SQLite**; production runs on **MySQL (AWS RDS)**. Because Prisma
|
||||||
|
cannot switch the datasource `provider` via `env()`, dev and prod use separate
|
||||||
|
schema files and migration histories:
|
||||||
|
|
||||||
|
| Environment | Schema | Migrations | DB |
|
||||||
|
| ----------- | -------------------------- | ------------------------- | --------------------------- |
|
||||||
|
| dev | `prisma/schema.prisma` | `prisma/migrations` | SQLite (`prisma/dev.db`) |
|
||||||
|
| prod | `prisma/prod/schema.prisma`| `prisma/prod/migrations` | MySQL / RDS |
|
||||||
|
|
||||||
|
## Infrastructure
|
||||||
|
|
||||||
|
- **App EC2**: `10.106.103.40`
|
||||||
|
- **RDS (private subnet)**: `it-cost-prod-db.c8hgbsblyypx.us-west-2.rds.amazonaws.com:3306`
|
||||||
|
- Database: `it_cost_dashboard`
|
||||||
|
- The EC2 host is verified able to reach the RDS instance.
|
||||||
|
|
||||||
|
## One-time setup on the EC2 host
|
||||||
|
|
||||||
|
1. Install dependencies:
|
||||||
|
```bash
|
||||||
|
npm ci
|
||||||
|
```
|
||||||
|
2. Create the production env file from the template and fill in the real
|
||||||
|
RDS credentials (this file is gitignored and must never be committed):
|
||||||
|
```bash
|
||||||
|
cp .env.production.example .env.production
|
||||||
|
# edit .env.production -> set the real DATABASE_URL
|
||||||
|
```
|
||||||
|
|
||||||
|
## Deploy / release steps
|
||||||
|
|
||||||
|
Run from the project root on the EC2 host (`/var/www/it_cost_dashboard`):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd /var/www/it_cost_dashboard
|
||||||
|
|
||||||
|
# 1. Make the prod DATABASE_URL available to the Prisma CLI (it only reads .env
|
||||||
|
# by default, so we export .env.production explicitly).
|
||||||
|
set -a && source .env.production && set +a
|
||||||
|
|
||||||
|
# 2. Apply migrations to RDS (idempotent; safe to re-run).
|
||||||
|
npm run prod:migrate
|
||||||
|
|
||||||
|
# 3. (First release only) seed baseline data.
|
||||||
|
npm run seed
|
||||||
|
|
||||||
|
# 4. Generate the MySQL Prisma client. ALWAYS re-run this if you just ran
|
||||||
|
# `npm ci` / `npm install` — installing can reset the generated client in
|
||||||
|
# node_modules/.prisma/client back to the default (dev/SQLite) schema.
|
||||||
|
npm run prod:generate
|
||||||
|
|
||||||
|
# 5. Wipe stale build output BEFORE building. This is a hard rule: a leftover
|
||||||
|
# `.next/cache` from an earlier `npm run build` (dev/SQLite) can bake the
|
||||||
|
# wrong Prisma client into the compiled routes ("URL must start with `file:`").
|
||||||
|
rm -rf .next
|
||||||
|
|
||||||
|
# 6. Generate the MySQL client again + build Next.js.
|
||||||
|
npm run build:prod
|
||||||
|
|
||||||
|
# 7. (Re)start under pm2, picking up fresh env from .env.production.
|
||||||
|
pm2 restart it_cost_dashboard --update-env # first time: pm2 start npm --name it_cost_dashboard -- run start
|
||||||
|
```
|
||||||
|
|
||||||
|
### Verify the release
|
||||||
|
|
||||||
|
Always confirm the app came up on the MySQL client (not a stale SQLite build):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# No Prisma init errors in the logs.
|
||||||
|
pm2 logs it_cost_dashboard --lines 40 --nostream
|
||||||
|
|
||||||
|
# The failing endpoint returns 200 + JSON (adjust port if PORT differs).
|
||||||
|
curl -s -o /dev/null -w "%{http_code}\n" http://localhost:3000/api/years # expect 200
|
||||||
|
curl -s http://localhost:3000/api/years | head -c 300 # expect JSON, not a 500
|
||||||
|
```
|
||||||
|
|
||||||
|
Success = `/api/years` returns 200 + JSON and pm2 logs show no
|
||||||
|
`PrismaClientInitializationError` / `the URL must start with the protocol \`file:\``.
|
||||||
|
|
||||||
|
### Alternative: systemd unit
|
||||||
|
|
||||||
|
For a systemd-managed process instead of pm2:
|
||||||
|
|
||||||
|
```ini
|
||||||
|
# /etc/systemd/system/it-cost-dashboard.service
|
||||||
|
[Service]
|
||||||
|
WorkingDirectory=/var/www/it_cost_dashboard
|
||||||
|
EnvironmentFile=/var/www/it_cost_dashboard/.env.production
|
||||||
|
ExecStart=/usr/bin/npm run start
|
||||||
|
Restart=always
|
||||||
|
```
|
||||||
|
|
||||||
|
## Authentication & authorization
|
||||||
|
|
||||||
|
Sign-in uses Auth.js / NextAuth v5. There are **two** ways in, and access is
|
||||||
|
**role-based** (`admin` = full access; `user` = read-only dashboard/trend):
|
||||||
|
|
||||||
|
1. **Microsoft Entra ID SSO** — allowed only if the user's email is in the
|
||||||
|
allowlist (see below). Unlisted emails cannot enter the app (fail closed).
|
||||||
|
2. **Local username/password** (break-glass admin) — a form on `/login`,
|
||||||
|
controlled by `LOCAL_ADMIN_USERNAME` / `LOCAL_ADMIN_PASSWORD`. This account is
|
||||||
|
always `admin` and bypasses the allowlist, so you can always get in to fix a
|
||||||
|
broken/empty `config/users.json`.
|
||||||
|
|
||||||
|
Middleware redirects any unauthenticated request to `/login` and enforces roles
|
||||||
|
**server-side**: normal users are redirected away from admin pages
|
||||||
|
(`/cost-registration`, `/cost-item-creation`, `/year-creation`) and any write API
|
||||||
|
call (non-`GET` `/api/*`) returns **403**. Read APIs (`GET /api/*`) stay open to
|
||||||
|
any signed-in user. The sidebar "Admin" group is also hidden for normal users.
|
||||||
|
|
||||||
|
### Role allowlist — `config/users.json`
|
||||||
|
|
||||||
|
Committed (NOT secret), hand-edited map of **email → role**:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"Sunny_Ho@trendmicro.com": "admin",
|
||||||
|
"tom_chien@trendmicro.com": "user"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- Emails are matched **case-insensitively**.
|
||||||
|
- An email that is absent (or an unreadable/invalid file) ⇒ SSO sign-in denied.
|
||||||
|
- The role is baked into the session JWT at sign-in, so after editing this file
|
||||||
|
users must **re-login** (or restart the app) for changes to apply:
|
||||||
|
`pm2 restart it_cost_dashboard`.
|
||||||
|
|
||||||
|
### Required env vars (`.env.production`)
|
||||||
|
|
||||||
|
Next.js does **not** load `.env.local` in production, so these must live in
|
||||||
|
`.env.production` on the EC2 host:
|
||||||
|
|
||||||
|
```env
|
||||||
|
AUTH_MICROSOFT_ENTRA_ID_ID="<prod Application (client) ID>"
|
||||||
|
AUTH_MICROSOFT_ENTRA_ID_SECRET="<prod client secret VALUE>"
|
||||||
|
AUTH_MICROSOFT_ENTRA_ID_ISSUER="https://login.microsoftonline.com/<tenant ID>/v2.0"
|
||||||
|
AUTH_SECRET="<32-byte random string, e.g. `npx auth secret`>"
|
||||||
|
AUTH_URL="https://<your-prod-domain>" # or set AUTH_TRUST_HOST=true behind a TLS proxy/ALB
|
||||||
|
|
||||||
|
# Local break-glass admin. Non-empty password ENABLES the /login form; empty disables it.
|
||||||
|
LOCAL_ADMIN_USERNAME="admin"
|
||||||
|
LOCAL_ADMIN_PASSWORD="<set a strong password>"
|
||||||
|
```
|
||||||
|
|
||||||
|
After changing `config/users.json` or the auth env vars, rebuild and restart:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
rm -rf .next && npm run build:prod && pm2 restart it_cost_dashboard --update-env
|
||||||
|
```
|
||||||
|
|
||||||
|
In the Entra app registration, add the prod **redirect URI**:
|
||||||
|
|
||||||
|
```
|
||||||
|
https://<your-prod-domain>/api/auth/callback/microsoft-entra-id
|
||||||
|
```
|
||||||
|
|
||||||
|
(Dev uses `http://localhost:3000/api/auth/callback/microsoft-entra-id`, configured
|
||||||
|
in the gitignored `.env.local`.) The `AUTH_*` vars are read at both build and
|
||||||
|
runtime, so they must be present before `npm run build:prod` and at `pm2` start.
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
|
||||||
|
- Do **not** run `npm run build` (dev/SQLite) on prod — use `npm run build:prod`.
|
||||||
|
- Both `prisma/schema.prisma` (sqlite) and `prisma/prod/schema.prisma` (mysql)
|
||||||
|
generate to the same default path `node_modules/.prisma/client` (last-writer-wins),
|
||||||
|
and the app imports the bare `@prisma/client`. So the deployed client is whichever
|
||||||
|
schema was generated **last before `next build`**. Two ways prod can end up with the
|
||||||
|
wrong (SQLite) client baked into `.next`:
|
||||||
|
1. **Stale `.next` cache** — an earlier dev `npm run build` left compiled route
|
||||||
|
chunks that `build:prod` reused. Fix: always `rm -rf .next` before building (step 5).
|
||||||
|
2. **Clobbered client** — `npm ci` / `npm install` reset the generated client to the
|
||||||
|
default schema. Fix: re-run `npm run prod:generate` after any install (step 4).
|
||||||
|
- Symptom: every API call 500s with
|
||||||
|
`error: Error validating datasource \`db\`: the URL must start with the protocol \`file:\``
|
||||||
|
even though the runtime `DATABASE_URL` is MySQL.
|
||||||
|
- `DATABASE_URL` set as a real OS/systemd env var always takes precedence over
|
||||||
|
any value in `.env` / `.env.production`, so the committed dev `.env` (SQLite)
|
||||||
|
never leaks into production.
|
||||||
|
- If you change the schema, generate a new MySQL migration against a MySQL dev
|
||||||
|
instance with `prisma migrate dev --schema=prisma/prod/schema.prisma`, then
|
||||||
|
redeploy with `npm run prod:migrate`.
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
Using the figma-console MCP tools, on the currently open Figma file (page "main")
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"Sunny_Ho@trendmicro.com": "admin",
|
||||||
|
"tom_chien@trendmicro.com": "user"
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
/** @type {import('next').NextConfig} */
|
||||||
|
const nextConfig = {};
|
||||||
|
|
||||||
|
export default nextConfig;
|
||||||
Generated
+3732
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,39 @@
|
|||||||
|
{
|
||||||
|
"name": "it_cost_dashboard",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"private": true,
|
||||||
|
"scripts": {
|
||||||
|
"dev": "next dev",
|
||||||
|
"build": "prisma generate && next build",
|
||||||
|
"start": "next start",
|
||||||
|
"lint": "next lint",
|
||||||
|
"seed": "tsx prisma/seed.ts",
|
||||||
|
"build:prod": "prisma generate --schema=prisma/prod/schema.prisma && next build",
|
||||||
|
"prod:generate": "prisma generate --schema=prisma/prod/schema.prisma",
|
||||||
|
"prod:migrate": "prisma migrate deploy --schema=prisma/prod/schema.prisma",
|
||||||
|
"migrate:data": "tsx scripts/migrate-dev-data-to-rds.ts"
|
||||||
|
},
|
||||||
|
"prisma": {
|
||||||
|
"seed": "tsx prisma/seed.ts"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@prisma/client": "^6.1.0",
|
||||||
|
"next": "15.1.4",
|
||||||
|
"next-auth": "^5.0.0-beta.32",
|
||||||
|
"react": "^19.0.0",
|
||||||
|
"react-dom": "^19.0.0",
|
||||||
|
"recharts": "^2.15.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@tailwindcss/postcss": "^4.0.0",
|
||||||
|
"@types/node": "^22.10.5",
|
||||||
|
"@types/react": "^19.0.4",
|
||||||
|
"@types/react-dom": "^19.0.2",
|
||||||
|
"better-sqlite3": "^11.8.1",
|
||||||
|
"mysql2": "^3.12.0",
|
||||||
|
"prisma": "^6.1.0",
|
||||||
|
"tailwindcss": "^4.0.0",
|
||||||
|
"tsx": "^4.19.2",
|
||||||
|
"typescript": "^5.7.3"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
const config = {
|
||||||
|
plugins: {
|
||||||
|
"@tailwindcss/postcss": {},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export default config;
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "CostItem" (
|
||||||
|
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
||||||
|
"name" TEXT NOT NULL,
|
||||||
|
"region" TEXT NOT NULL,
|
||||||
|
"year" INTEGER NOT NULL,
|
||||||
|
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" DATETIME NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "SubCostItem" (
|
||||||
|
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
||||||
|
"name" TEXT NOT NULL,
|
||||||
|
"subCost" REAL NOT NULL,
|
||||||
|
"costItemId" INTEGER NOT NULL,
|
||||||
|
CONSTRAINT "SubCostItem_costItemId_fkey" FOREIGN KEY ("costItemId") REFERENCES "CostItem" ("id") ON DELETE CASCADE ON UPDATE CASCADE
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "TrendAiPercentage" (
|
||||||
|
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
||||||
|
"region" TEXT NOT NULL,
|
||||||
|
"year" INTEGER NOT NULL,
|
||||||
|
"percentage" REAL NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "CostItem_region_year_idx" ON "CostItem"("region", "year");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "SubCostItem_costItemId_idx" ON "SubCostItem"("costItemId");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "TrendAiPercentage_region_year_key" ON "TrendAiPercentage"("region", "year");
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "Year" (
|
||||||
|
"year" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT
|
||||||
|
);
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
# Please do not edit this file manually
|
||||||
|
# It should be added in your version-control system (e.g., Git)
|
||||||
|
provider = "sqlite"
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE `CostItem` (
|
||||||
|
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||||
|
`name` VARCHAR(191) NOT NULL,
|
||||||
|
`region` VARCHAR(191) NOT NULL,
|
||||||
|
`year` INTEGER NOT NULL,
|
||||||
|
`createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||||
|
`updatedAt` DATETIME(3) NOT NULL,
|
||||||
|
|
||||||
|
INDEX `CostItem_region_year_idx`(`region`, `year`),
|
||||||
|
PRIMARY KEY (`id`)
|
||||||
|
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE `SubCostItem` (
|
||||||
|
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||||
|
`name` VARCHAR(191) NOT NULL,
|
||||||
|
`subCost` DOUBLE NOT NULL,
|
||||||
|
`costItemId` INTEGER NOT NULL,
|
||||||
|
|
||||||
|
INDEX `SubCostItem_costItemId_idx`(`costItemId`),
|
||||||
|
PRIMARY KEY (`id`)
|
||||||
|
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE `TrendAiPercentage` (
|
||||||
|
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||||
|
`region` VARCHAR(191) NOT NULL,
|
||||||
|
`year` INTEGER NOT NULL,
|
||||||
|
`percentage` DOUBLE NOT NULL,
|
||||||
|
|
||||||
|
UNIQUE INDEX `TrendAiPercentage_region_year_key`(`region`, `year`),
|
||||||
|
PRIMARY KEY (`id`)
|
||||||
|
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE `Year` (
|
||||||
|
`year` INTEGER NOT NULL,
|
||||||
|
|
||||||
|
PRIMARY KEY (`year`)
|
||||||
|
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE `SubCostItem` ADD CONSTRAINT `SubCostItem_costItemId_fkey` FOREIGN KEY (`costItemId`) REFERENCES `CostItem`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
# Please do not edit this file manually
|
||||||
|
# It should be added in your version-control system (e.g., Git)
|
||||||
|
provider = "mysql"
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
// Production Prisma schema for the IT Cost Dashboard (MySQL / AWS RDS).
|
||||||
|
//
|
||||||
|
// This mirrors prisma/schema.prisma exactly except the datasource provider is
|
||||||
|
// "mysql". Prisma does NOT support env() for the `provider` field, so dev
|
||||||
|
// (SQLite) and prod (MySQL) each need their own schema file + migrations.
|
||||||
|
//
|
||||||
|
// Usage on the production EC2 box (see DEPLOY.md):
|
||||||
|
// npm run prod:generate # prisma generate --schema=prisma/prod/schema.prisma
|
||||||
|
// npm run prod:migrate # prisma migrate deploy --schema=prisma/prod/schema.prisma
|
||||||
|
// npm run build:prod
|
||||||
|
datasource db {
|
||||||
|
provider = "mysql"
|
||||||
|
url = env("DATABASE_URL")
|
||||||
|
}
|
||||||
|
|
||||||
|
generator client {
|
||||||
|
provider = "prisma-client-js"
|
||||||
|
}
|
||||||
|
|
||||||
|
// One row per (name, region, year). e.g. "Cloud Hosting" in AMEA IT 2026 is a
|
||||||
|
// distinct row from "Cloud Hosting" in EMEA IT 2026. Cost is never stored — it is
|
||||||
|
// always derived as SUM(subItems.subCost).
|
||||||
|
model CostItem {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
name String
|
||||||
|
region String
|
||||||
|
year Int
|
||||||
|
subItems SubCostItem[]
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
|
@@index([region, year])
|
||||||
|
}
|
||||||
|
|
||||||
|
model SubCostItem {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
name String
|
||||||
|
subCost Float
|
||||||
|
costItem CostItem @relation(fields: [costItemId], references: [id], onDelete: Cascade)
|
||||||
|
costItemId Int
|
||||||
|
|
||||||
|
@@index([costItemId])
|
||||||
|
}
|
||||||
|
|
||||||
|
// The TrendAI percentage that splits each item's Cost into TrendAI vs TrendLife
|
||||||
|
// for a given region+year. Applies uniformly to all items in that region+year.
|
||||||
|
model TrendAiPercentage {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
region String
|
||||||
|
year Int
|
||||||
|
percentage Float
|
||||||
|
|
||||||
|
@@unique([region, year])
|
||||||
|
}
|
||||||
|
|
||||||
|
// The set of years available for selection across the app. Managed on the Year
|
||||||
|
// Creation page. Cost items reference years by value (not FK) so a year can exist
|
||||||
|
// with no cost data yet.
|
||||||
|
model Year {
|
||||||
|
year Int @id
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
// Prisma schema for the IT Cost Dashboard.
|
||||||
|
//
|
||||||
|
// Datasource provider is hardcoded to "sqlite" for local dev because Prisma does
|
||||||
|
// NOT support env() for the `provider` field (only for `url`). Production on RDS
|
||||||
|
// uses a separate MySQL schema at prisma/prod/schema.prisma with its own
|
||||||
|
// migration history in prisma/prod/migrations (see DEPLOY.md). Keep the two
|
||||||
|
// schemas' models in sync.
|
||||||
|
datasource db {
|
||||||
|
provider = "sqlite"
|
||||||
|
url = env("DATABASE_URL")
|
||||||
|
}
|
||||||
|
|
||||||
|
generator client {
|
||||||
|
provider = "prisma-client-js"
|
||||||
|
}
|
||||||
|
|
||||||
|
// One row per (name, region, year). e.g. "Cloud Hosting" in AMEA IT 2026 is a
|
||||||
|
// distinct row from "Cloud Hosting" in EMEA IT 2026. Cost is never stored — it is
|
||||||
|
// always derived as SUM(subItems.subCost).
|
||||||
|
model CostItem {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
name String
|
||||||
|
region String
|
||||||
|
year Int
|
||||||
|
subItems SubCostItem[]
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
|
@@index([region, year])
|
||||||
|
}
|
||||||
|
|
||||||
|
model SubCostItem {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
name String
|
||||||
|
subCost Float
|
||||||
|
costItem CostItem @relation(fields: [costItemId], references: [id], onDelete: Cascade)
|
||||||
|
costItemId Int
|
||||||
|
|
||||||
|
@@index([costItemId])
|
||||||
|
}
|
||||||
|
|
||||||
|
// The TrendAI percentage that splits each item's Cost into TrendAI vs TrendLife
|
||||||
|
// for a given region+year. Applies uniformly to all items in that region+year.
|
||||||
|
model TrendAiPercentage {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
region String
|
||||||
|
year Int
|
||||||
|
percentage Float
|
||||||
|
|
||||||
|
@@unique([region, year])
|
||||||
|
}
|
||||||
|
|
||||||
|
// The set of years available for selection across the app. Managed on the Year
|
||||||
|
// Creation page. Cost items reference years by value (not FK) so a year can exist
|
||||||
|
// with no cost data yet.
|
||||||
|
model Year {
|
||||||
|
year Int @id
|
||||||
|
}
|
||||||
+130
@@ -0,0 +1,130 @@
|
|||||||
|
import { PrismaClient } from "@prisma/client";
|
||||||
|
|
||||||
|
const prisma = new PrismaClient();
|
||||||
|
|
||||||
|
const REGIONS = ["AMEA IT", "EMEA IT", "NABU IT", "PH IT", "JP IT"] as const;
|
||||||
|
const YEARS = [2022, 2023, 2024, 2025, 2026];
|
||||||
|
|
||||||
|
// Cost item catalog. Each item defines its sub-cost line names and a base cost
|
||||||
|
// per sub-item. Actual seeded sub-costs scale by region + year (below).
|
||||||
|
const ITEMS: { name: string; subs: { name: string; base: number }[] }[] = [
|
||||||
|
{
|
||||||
|
name: "Cloud Hosting",
|
||||||
|
subs: [
|
||||||
|
{ name: "Compute (VMs)", base: 40000 },
|
||||||
|
{ name: "Storage", base: 18000 },
|
||||||
|
{ name: "Networking / Egress", base: 9000 },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Software Licenses",
|
||||||
|
subs: [
|
||||||
|
{ name: "Productivity Suite", base: 22000 },
|
||||||
|
{ name: "Design Tools", base: 8000 },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Security Tools",
|
||||||
|
subs: [
|
||||||
|
{ name: "Endpoint Protection", base: 15000 },
|
||||||
|
{ name: "SIEM", base: 20000 },
|
||||||
|
{ name: "Vulnerability Scanning", base: 6000 },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Support & Maintenance",
|
||||||
|
subs: [{ name: "Vendor Support Contract", base: 30000 }],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Network Infra",
|
||||||
|
subs: [
|
||||||
|
{ name: "Circuits / Bandwidth", base: 25000 },
|
||||||
|
{ name: "Hardware Refresh", base: 12000 },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
// Region weighting so regions differ in magnitude (NABU largest, PH smallest).
|
||||||
|
const REGION_WEIGHT: Record<string, number> = {
|
||||||
|
"NABU IT": 1.4,
|
||||||
|
"EMEA IT": 1.2,
|
||||||
|
"AMEA IT": 1.0,
|
||||||
|
"JP IT": 0.9,
|
||||||
|
"PH IT": 0.7,
|
||||||
|
};
|
||||||
|
|
||||||
|
// TrendAI percentage per region grows over the years (AI adoption ramp).
|
||||||
|
// Value at year Y for a region = base + (Y-2022)*step, clamped.
|
||||||
|
const REGION_AI: Record<string, { base: number; step: number }> = {
|
||||||
|
"NABU IT": { base: 12, step: 6 },
|
||||||
|
"EMEA IT": { base: 10, step: 5 },
|
||||||
|
"AMEA IT": { base: 8, step: 5 },
|
||||||
|
"JP IT": { base: 15, step: 4 },
|
||||||
|
"PH IT": { base: 6, step: 4 },
|
||||||
|
};
|
||||||
|
|
||||||
|
function yearFactor(year: number): number {
|
||||||
|
// Costs grow ~8%/yr off a 2022 base.
|
||||||
|
return Math.pow(1.08, year - 2022);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
console.log("Clearing existing data...");
|
||||||
|
await prisma.subCostItem.deleteMany();
|
||||||
|
await prisma.costItem.deleteMany();
|
||||||
|
await prisma.trendAiPercentage.deleteMany();
|
||||||
|
await prisma.year.deleteMany();
|
||||||
|
|
||||||
|
console.log("Seeding years...");
|
||||||
|
for (const year of YEARS) {
|
||||||
|
await prisma.year.create({ data: { year } });
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log("Seeding cost items + sub-costs...");
|
||||||
|
for (const region of REGIONS) {
|
||||||
|
const weight = REGION_WEIGHT[region];
|
||||||
|
for (const year of YEARS) {
|
||||||
|
const yf = yearFactor(year);
|
||||||
|
for (const item of ITEMS) {
|
||||||
|
await prisma.costItem.create({
|
||||||
|
data: {
|
||||||
|
name: item.name,
|
||||||
|
region,
|
||||||
|
year,
|
||||||
|
subItems: {
|
||||||
|
create: item.subs.map((s) => ({
|
||||||
|
name: s.name,
|
||||||
|
subCost: Math.round((s.base * weight * yf) / 100) * 100,
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log("Seeding TrendAI percentages...");
|
||||||
|
for (const region of REGIONS) {
|
||||||
|
const ai = REGION_AI[region];
|
||||||
|
for (const year of YEARS) {
|
||||||
|
const pct = Math.min(60, ai.base + (year - 2022) * ai.step);
|
||||||
|
await prisma.trendAiPercentage.create({
|
||||||
|
data: { region, year, percentage: pct },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const items = await prisma.costItem.count();
|
||||||
|
const subs = await prisma.subCostItem.count();
|
||||||
|
const pcts = await prisma.trendAiPercentage.count();
|
||||||
|
console.log(`Done. CostItems=${items}, SubCostItems=${subs}, TrendAiPercentage=${pcts}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
main()
|
||||||
|
.catch((e) => {
|
||||||
|
console.error(e);
|
||||||
|
process.exit(1);
|
||||||
|
})
|
||||||
|
.finally(async () => {
|
||||||
|
await prisma.$disconnect();
|
||||||
|
});
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
/**
|
||||||
|
* One-time data migration: copy rows from the local SQLite dev DB
|
||||||
|
* (prisma/dev.db) into the production MySQL/RDS database.
|
||||||
|
*
|
||||||
|
* WHY A STANDALONE SCRIPT (not two PrismaClients): the app generates
|
||||||
|
* @prisma/client to node_modules/.prisma/client from whichever schema was
|
||||||
|
* generated last (see DEPLOY.md — sqlite vs mysql client collision). Rather
|
||||||
|
* than juggling two generated clients, this script talks to both databases
|
||||||
|
* with plain drivers (better-sqlite3 + mysql2), so it can't clobber whatever
|
||||||
|
* client the app currently has generated.
|
||||||
|
*
|
||||||
|
* WHERE TO RUN THIS: the RDS instance is in a private subnet reachable only
|
||||||
|
* from the app EC2 host (per DEPLOY.md). Run this ON THE EC2 HOST, after
|
||||||
|
* copying prisma/dev.db there.
|
||||||
|
*
|
||||||
|
* PREREQS:
|
||||||
|
* 1. npm install better-sqlite3 mysql2 --save-dev (one-time)
|
||||||
|
* 2. Tables must already exist on RDS:
|
||||||
|
* set -a && source .env.production && set +a
|
||||||
|
* npm run prod:migrate
|
||||||
|
* 3. .env.production has the real DATABASE_URL (mysql://...)
|
||||||
|
*
|
||||||
|
* USAGE (from project root on the EC2 host):
|
||||||
|
* set -a && source .env.production && set +a
|
||||||
|
* npx tsx scripts/migrate-dev-data-to-rds.ts # migrate
|
||||||
|
* npx tsx scripts/migrate-dev-data-to-rds.ts --dry-run # preview only
|
||||||
|
* npx tsx scripts/migrate-dev-data-to-rds.ts --wipe # delete existing
|
||||||
|
* # prod rows first
|
||||||
|
*
|
||||||
|
* By default the script refuses to run if the destination tables are
|
||||||
|
* non-empty, to avoid double-importing. Pass --wipe to clear them first
|
||||||
|
* (CostItem/SubCostItem/TrendAiPercentage/Year only — nothing else is touched).
|
||||||
|
*/
|
||||||
|
|
||||||
|
import Database from "better-sqlite3";
|
||||||
|
import mysql from "mysql2/promise";
|
||||||
|
import path from "node:path";
|
||||||
|
|
||||||
|
const DRY_RUN = process.argv.includes("--dry-run");
|
||||||
|
const WIPE = process.argv.includes("--wipe");
|
||||||
|
|
||||||
|
const SQLITE_PATH =
|
||||||
|
process.env.DEV_SQLITE_PATH ?? path.join(__dirname, "..", "prisma", "dev.db");
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const prodUrl = process.env.DATABASE_URL;
|
||||||
|
if (!prodUrl || !prodUrl.startsWith("mysql://")) {
|
||||||
|
throw new Error(
|
||||||
|
"DATABASE_URL is not set to a mysql:// URL. Did you `source .env.production` first?"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`Reading dev data from ${SQLITE_PATH}`);
|
||||||
|
const sqlite = new Database(SQLITE_PATH, { readonly: true });
|
||||||
|
|
||||||
|
const years = sqlite.prepare("SELECT year FROM Year").all() as { year: number }[];
|
||||||
|
const costItems = sqlite
|
||||||
|
.prepare("SELECT id, name, region, year, createdAt, updatedAt FROM CostItem")
|
||||||
|
.all() as {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
region: string;
|
||||||
|
year: number;
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
}[];
|
||||||
|
const subCostItems = sqlite
|
||||||
|
.prepare("SELECT id, name, subCost, costItemId FROM SubCostItem")
|
||||||
|
.all() as { id: number; name: string; subCost: number; costItemId: number }[];
|
||||||
|
const trendAi = sqlite
|
||||||
|
.prepare("SELECT id, region, year, percentage FROM TrendAiPercentage")
|
||||||
|
.all() as { id: number; region: string; year: number; percentage: number }[];
|
||||||
|
|
||||||
|
sqlite.close();
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
`Found: Year=${years.length}, CostItem=${costItems.length}, ` +
|
||||||
|
`SubCostItem=${subCostItems.length}, TrendAiPercentage=${trendAi.length}`
|
||||||
|
);
|
||||||
|
|
||||||
|
if (DRY_RUN) {
|
||||||
|
console.log("--dry-run set: not connecting to RDS. Done.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const conn = await mysql.createConnection(prodUrl);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const [[{ c: yearCount }]]: any = await conn.query(
|
||||||
|
"SELECT COUNT(*) as c FROM `Year`"
|
||||||
|
);
|
||||||
|
const [[{ c: itemCount }]]: any = await conn.query(
|
||||||
|
"SELECT COUNT(*) as c FROM `CostItem`"
|
||||||
|
);
|
||||||
|
if ((yearCount > 0 || itemCount > 0) && !WIPE) {
|
||||||
|
throw new Error(
|
||||||
|
`Destination already has data (Year=${yearCount}, CostItem=${itemCount}). ` +
|
||||||
|
`Re-run with --wipe to clear existing rows first, or investigate before overwriting.`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
await conn.beginTransaction();
|
||||||
|
|
||||||
|
if (WIPE) {
|
||||||
|
console.log("Wiping existing prod rows...");
|
||||||
|
await conn.query("SET FOREIGN_KEY_CHECKS=0");
|
||||||
|
await conn.query("DELETE FROM `SubCostItem`");
|
||||||
|
await conn.query("DELETE FROM `CostItem`");
|
||||||
|
await conn.query("DELETE FROM `TrendAiPercentage`");
|
||||||
|
await conn.query("DELETE FROM `Year`");
|
||||||
|
await conn.query("SET FOREIGN_KEY_CHECKS=1");
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log("Inserting Year...");
|
||||||
|
for (const y of years) {
|
||||||
|
await conn.query("INSERT INTO `Year` (year) VALUES (?)", [y.year]);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log("Inserting CostItem...");
|
||||||
|
for (const c of costItems) {
|
||||||
|
await conn.query(
|
||||||
|
"INSERT INTO `CostItem` (id, name, region, year, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?)",
|
||||||
|
[c.id, c.name, c.region, c.year, new Date(c.createdAt), new Date(c.updatedAt)]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log("Inserting SubCostItem...");
|
||||||
|
for (const s of subCostItems) {
|
||||||
|
await conn.query(
|
||||||
|
"INSERT INTO `SubCostItem` (id, name, subCost, costItemId) VALUES (?, ?, ?, ?)",
|
||||||
|
[s.id, s.name, s.subCost, s.costItemId]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log("Inserting TrendAiPercentage...");
|
||||||
|
for (const t of trendAi) {
|
||||||
|
await conn.query(
|
||||||
|
"INSERT INTO `TrendAiPercentage` (id, region, year, percentage) VALUES (?, ?, ?, ?)",
|
||||||
|
[t.id, t.region, t.year, t.percentage]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Realign AUTO_INCREMENT counters so future inserts don't collide with
|
||||||
|
// the explicit ids we just wrote.
|
||||||
|
for (const table of ["CostItem", "SubCostItem", "TrendAiPercentage"]) {
|
||||||
|
const [[{ maxId }]]: any = await conn.query(
|
||||||
|
`SELECT COALESCE(MAX(id), 0) as maxId FROM \`${table}\``
|
||||||
|
);
|
||||||
|
await conn.query(`ALTER TABLE \`${table}\` AUTO_INCREMENT = ${maxId + 1}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
await conn.commit();
|
||||||
|
|
||||||
|
const [[{ c: finalItems }]]: any = await conn.query(
|
||||||
|
"SELECT COUNT(*) as c FROM `CostItem`"
|
||||||
|
);
|
||||||
|
const [[{ c: finalSubs }]]: any = await conn.query(
|
||||||
|
"SELECT COUNT(*) as c FROM `SubCostItem`"
|
||||||
|
);
|
||||||
|
console.log(
|
||||||
|
`Done. Committed. CostItem=${finalItems}, SubCostItem=${finalSubs} now in RDS.`
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
await conn.rollback();
|
||||||
|
console.error("Migration failed, rolled back:", err);
|
||||||
|
throw err;
|
||||||
|
} finally {
|
||||||
|
await conn.end();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch((e) => {
|
||||||
|
console.error(e);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
import { handlers } from "@/auth";
|
||||||
|
|
||||||
|
export const { GET, POST } = handlers;
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { prisma } from "@/lib/prisma";
|
||||||
|
import { REGIONS, ALL_REGION, isRegion } from "@/lib/regions";
|
||||||
|
|
||||||
|
// POST /api/cost-items/delete { name, region, year }
|
||||||
|
// Deletes the cost item(s) matching name+year. When region = "All", remove every
|
||||||
|
// existing copy across regions (no warning if fewer than 5 exist). Cascades sub-costs.
|
||||||
|
export async function POST(req: NextRequest) {
|
||||||
|
const body = await req.json().catch(() => null);
|
||||||
|
const name = (body?.name ?? "").trim();
|
||||||
|
const region = body?.region ?? "";
|
||||||
|
const year = parseInt(String(body?.year), 10);
|
||||||
|
|
||||||
|
if (!name) {
|
||||||
|
return NextResponse.json({ error: "name is required" }, { status: 400 });
|
||||||
|
}
|
||||||
|
if (Number.isNaN(year)) {
|
||||||
|
return NextResponse.json({ error: "year is required" }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const targets =
|
||||||
|
region === ALL_REGION ? [...REGIONS] : isRegion(region) ? [region] : [];
|
||||||
|
if (targets.length === 0) {
|
||||||
|
return NextResponse.json({ error: "invalid region" }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await prisma.costItem.deleteMany({
|
||||||
|
where: { name, year, region: { in: targets } },
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json({ deleted: result.count });
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { prisma } from "@/lib/prisma";
|
||||||
|
import { REGIONS, ALL_REGION, isRegion } from "@/lib/regions";
|
||||||
|
|
||||||
|
// GET /api/cost-items?region&year -> list of cost items (with derived cost).
|
||||||
|
export async function GET(req: NextRequest) {
|
||||||
|
const { searchParams } = new URL(req.url);
|
||||||
|
const region = searchParams.get("region") ?? ALL_REGION;
|
||||||
|
const yearParam = searchParams.get("year");
|
||||||
|
const year = yearParam ? parseInt(yearParam, 10) : NaN;
|
||||||
|
|
||||||
|
if (Number.isNaN(year)) {
|
||||||
|
return NextResponse.json({ error: "year is required" }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const regions = region === ALL_REGION ? REGIONS : isRegion(region) ? [region] : [];
|
||||||
|
if (regions.length === 0) return NextResponse.json({ items: [] });
|
||||||
|
|
||||||
|
const items = await prisma.costItem.findMany({
|
||||||
|
where: { year, region: { in: [...regions] } },
|
||||||
|
select: { id: true, name: true, region: true, year: true },
|
||||||
|
orderBy: [{ name: "asc" }, { region: "asc" }],
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json({ items });
|
||||||
|
}
|
||||||
|
|
||||||
|
// POST /api/cost-items { name, region, year } -> create instantly.
|
||||||
|
// When region = "All", create in all 5 regions, skipping any that already have it.
|
||||||
|
export async function POST(req: NextRequest) {
|
||||||
|
const body = await req.json().catch(() => null);
|
||||||
|
const name = (body?.name ?? "").trim();
|
||||||
|
const region = body?.region ?? "";
|
||||||
|
const year = parseInt(String(body?.year), 10);
|
||||||
|
|
||||||
|
if (!name) {
|
||||||
|
return NextResponse.json({ error: "name is required" }, { status: 400 });
|
||||||
|
}
|
||||||
|
if (Number.isNaN(year)) {
|
||||||
|
return NextResponse.json({ error: "year is required" }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const targets =
|
||||||
|
region === ALL_REGION ? [...REGIONS] : isRegion(region) ? [region] : [];
|
||||||
|
if (targets.length === 0) {
|
||||||
|
return NextResponse.json({ error: "invalid region" }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
let created = 0;
|
||||||
|
let skipped = 0;
|
||||||
|
for (const r of targets) {
|
||||||
|
const existing = await prisma.costItem.findFirst({
|
||||||
|
where: { name, region: r, year },
|
||||||
|
});
|
||||||
|
if (existing) {
|
||||||
|
skipped++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
await prisma.costItem.create({ data: { name, region: r, year } });
|
||||||
|
created++;
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.json({ created, skipped });
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { prisma } from "@/lib/prisma";
|
||||||
|
import { isRegion } from "@/lib/regions";
|
||||||
|
|
||||||
|
// GET /api/cost-registration?region&year -> cost items + subItems + pct for a
|
||||||
|
// specific region+year (registration requires a specific region).
|
||||||
|
export async function GET(req: NextRequest) {
|
||||||
|
const { searchParams } = new URL(req.url);
|
||||||
|
const region = searchParams.get("region") ?? "";
|
||||||
|
const yearParam = searchParams.get("year");
|
||||||
|
const year = yearParam ? parseInt(yearParam, 10) : NaN;
|
||||||
|
|
||||||
|
if (!isRegion(region)) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "a specific region is required" },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (Number.isNaN(year)) {
|
||||||
|
return NextResponse.json({ error: "year is required" }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const items = await prisma.costItem.findMany({
|
||||||
|
where: { region, year },
|
||||||
|
include: { subItems: { orderBy: { id: "asc" } } },
|
||||||
|
orderBy: { name: "asc" },
|
||||||
|
});
|
||||||
|
|
||||||
|
const pctRow = await prisma.trendAiPercentage.findUnique({
|
||||||
|
where: { region_year: { region, year } },
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
items: items.map((it) => ({
|
||||||
|
id: it.id,
|
||||||
|
name: it.name,
|
||||||
|
subItems: it.subItems.map((s) => ({
|
||||||
|
id: s.id,
|
||||||
|
name: s.name,
|
||||||
|
subCost: s.subCost,
|
||||||
|
})),
|
||||||
|
})),
|
||||||
|
percentage: pctRow?.percentage ?? 0,
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { getDashboardRows } from "@/lib/calc";
|
||||||
|
|
||||||
|
// GET /api/dashboard?region&costItem&year -> aggregated table rows.
|
||||||
|
export async function GET(req: NextRequest) {
|
||||||
|
const { searchParams } = new URL(req.url);
|
||||||
|
const region = searchParams.get("region") ?? "All";
|
||||||
|
const costItem = searchParams.get("costItem") ?? "All";
|
||||||
|
const yearParam = searchParams.get("year");
|
||||||
|
const year = yearParam ? parseInt(yearParam, 10) : NaN;
|
||||||
|
|
||||||
|
if (Number.isNaN(year)) {
|
||||||
|
return NextResponse.json({ error: "year is required" }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const rows = await getDashboardRows({ region, costItem, year });
|
||||||
|
return NextResponse.json({ rows });
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { prisma } from "@/lib/prisma";
|
||||||
|
|
||||||
|
// PATCH /api/sub-items/[id] { name?, subCost? } -> update a sub-item.
|
||||||
|
export async function PATCH(
|
||||||
|
req: NextRequest,
|
||||||
|
{ params }: { params: Promise<{ id: string }> }
|
||||||
|
) {
|
||||||
|
const { id: idStr } = await params;
|
||||||
|
const id = parseInt(idStr, 10);
|
||||||
|
if (Number.isNaN(id)) {
|
||||||
|
return NextResponse.json({ error: "invalid id" }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const body = await req.json().catch(() => null);
|
||||||
|
const data: { name?: string; subCost?: number } = {};
|
||||||
|
if (typeof body?.name === "string") data.name = body.name;
|
||||||
|
if (body?.subCost !== undefined) data.subCost = Number(body.subCost) || 0;
|
||||||
|
|
||||||
|
const updated = await prisma.subCostItem.update({ where: { id }, data });
|
||||||
|
return NextResponse.json({ subItem: updated });
|
||||||
|
}
|
||||||
|
|
||||||
|
// DELETE /api/sub-items/[id] -> remove a sub-item.
|
||||||
|
export async function DELETE(
|
||||||
|
_req: NextRequest,
|
||||||
|
{ params }: { params: Promise<{ id: string }> }
|
||||||
|
) {
|
||||||
|
const { id: idStr } = await params;
|
||||||
|
const id = parseInt(idStr, 10);
|
||||||
|
if (Number.isNaN(id)) {
|
||||||
|
return NextResponse.json({ error: "invalid id" }, { status: 400 });
|
||||||
|
}
|
||||||
|
await prisma.subCostItem.delete({ where: { id } });
|
||||||
|
return NextResponse.json({ ok: true });
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { prisma } from "@/lib/prisma";
|
||||||
|
|
||||||
|
// POST /api/sub-items { costItemId, name?, subCost? } -> append a sub-item.
|
||||||
|
export async function POST(req: NextRequest) {
|
||||||
|
const body = await req.json().catch(() => null);
|
||||||
|
const costItemId = parseInt(String(body?.costItemId), 10);
|
||||||
|
const name = (body?.name ?? "New Sub Cost").trim() || "New Sub Cost";
|
||||||
|
const subCost = Number(body?.subCost ?? 0) || 0;
|
||||||
|
|
||||||
|
if (Number.isNaN(costItemId)) {
|
||||||
|
return NextResponse.json({ error: "costItemId is required" }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const parent = await prisma.costItem.findUnique({ where: { id: costItemId } });
|
||||||
|
if (!parent) {
|
||||||
|
return NextResponse.json({ error: "cost item not found" }, { status: 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const sub = await prisma.subCostItem.create({
|
||||||
|
data: { costItemId, name, subCost },
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json({ subItem: sub });
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { prisma } from "@/lib/prisma";
|
||||||
|
import { isRegion } from "@/lib/regions";
|
||||||
|
|
||||||
|
// GET /api/trend-percentage?region&year -> current TrendAI percentage.
|
||||||
|
export async function GET(req: NextRequest) {
|
||||||
|
const { searchParams } = new URL(req.url);
|
||||||
|
const region = searchParams.get("region") ?? "";
|
||||||
|
const year = parseInt(searchParams.get("year") ?? "", 10);
|
||||||
|
|
||||||
|
if (!isRegion(region) || Number.isNaN(year)) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "region and year are required" },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const row = await prisma.trendAiPercentage.findUnique({
|
||||||
|
where: { region_year: { region, year } },
|
||||||
|
});
|
||||||
|
return NextResponse.json({ percentage: row?.percentage ?? 0 });
|
||||||
|
}
|
||||||
|
|
||||||
|
// PUT /api/trend-percentage { region, year, percentage } -> upsert.
|
||||||
|
export async function PUT(req: NextRequest) {
|
||||||
|
const body = await req.json().catch(() => null);
|
||||||
|
const region = body?.region ?? "";
|
||||||
|
const year = parseInt(String(body?.year), 10);
|
||||||
|
const percentage = Number(body?.percentage);
|
||||||
|
|
||||||
|
if (!isRegion(region) || Number.isNaN(year)) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "region and year are required" },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (Number.isNaN(percentage) || percentage < 0 || percentage > 100) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "percentage must be between 0 and 100" },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const row = await prisma.trendAiPercentage.upsert({
|
||||||
|
where: { region_year: { region, year } },
|
||||||
|
create: { region, year, percentage },
|
||||||
|
update: { percentage },
|
||||||
|
});
|
||||||
|
return NextResponse.json({ percentage: row.percentage });
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { getTrendSeries } from "@/lib/calc";
|
||||||
|
|
||||||
|
// GET /api/trend?region -> series data across all years.
|
||||||
|
export async function GET(req: NextRequest) {
|
||||||
|
const { searchParams } = new URL(req.url);
|
||||||
|
const region = searchParams.get("region") ?? "All";
|
||||||
|
const series = await getTrendSeries({ region });
|
||||||
|
return NextResponse.json(series);
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { prisma } from "@/lib/prisma";
|
||||||
|
|
||||||
|
// POST /api/years/delete { year } -> remove a year and ALL cost data for it
|
||||||
|
// (cost items + their sub-costs via cascade, plus TrendAI percentages).
|
||||||
|
export async function POST(req: NextRequest) {
|
||||||
|
const body = await req.json().catch(() => null);
|
||||||
|
const year = parseInt(String(body?.year), 10);
|
||||||
|
|
||||||
|
if (Number.isNaN(year)) {
|
||||||
|
return NextResponse.json({ error: "invalid year" }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sub-costs cascade when their cost items are deleted.
|
||||||
|
const items = await prisma.costItem.deleteMany({ where: { year } });
|
||||||
|
const pcts = await prisma.trendAiPercentage.deleteMany({ where: { year } });
|
||||||
|
await prisma.year.deleteMany({ where: { year } });
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
year,
|
||||||
|
deletedItems: items.count,
|
||||||
|
deletedPercentages: pcts.count,
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { prisma } from "@/lib/prisma";
|
||||||
|
|
||||||
|
// GET /api/years -> all years (desc) for filter dropdowns + the Year Creation
|
||||||
|
// table. Union of the managed Year table and any years already used by cost
|
||||||
|
// items (so pre-existing data always shows even if not in the Year table).
|
||||||
|
export async function GET() {
|
||||||
|
const [yearRows, itemRows] = await Promise.all([
|
||||||
|
prisma.year.findMany({ select: { year: true } }),
|
||||||
|
prisma.costItem.findMany({
|
||||||
|
distinct: ["year"],
|
||||||
|
select: { year: true },
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
const set = new Set<number>([
|
||||||
|
...yearRows.map((r) => r.year),
|
||||||
|
...itemRows.map((r) => r.year),
|
||||||
|
]);
|
||||||
|
const years = [...set].sort((a, b) => b - a);
|
||||||
|
return NextResponse.json({ years });
|
||||||
|
}
|
||||||
|
|
||||||
|
// POST /api/years { year } -> add a year. Reports whether it was created or
|
||||||
|
// already existed.
|
||||||
|
export async function POST(req: NextRequest) {
|
||||||
|
const body = await req.json().catch(() => null);
|
||||||
|
const year = parseInt(String(body?.year), 10);
|
||||||
|
|
||||||
|
if (Number.isNaN(year) || year < 1900 || year > 3000) {
|
||||||
|
return NextResponse.json({ error: "invalid year" }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const existing = await prisma.year.findUnique({ where: { year } });
|
||||||
|
if (existing) {
|
||||||
|
return NextResponse.json({ created: false, exists: true, year });
|
||||||
|
}
|
||||||
|
await prisma.year.create({ data: { year } });
|
||||||
|
return NextResponse.json({ created: true, exists: false, year });
|
||||||
|
}
|
||||||
@@ -0,0 +1,300 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useMemo, useState } from "react";
|
||||||
|
import FilterBar from "@/components/ui/FilterBar";
|
||||||
|
import Select from "@/components/ui/Select";
|
||||||
|
import Card from "@/components/ui/Card";
|
||||||
|
import { REGIONS, REGION_OPTIONS, ALL_REGION } from "@/lib/regions";
|
||||||
|
|
||||||
|
type Item = { id: number; name: string; region: string; year: number };
|
||||||
|
|
||||||
|
export default function CostItemCreationPage() {
|
||||||
|
const [years, setYears] = useState<number[]>([]);
|
||||||
|
const [region, setRegion] = useState("All");
|
||||||
|
const [year, setYear] = useState<string>("");
|
||||||
|
const [items, setItems] = useState<Item[]>([]);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
|
||||||
|
const [newName, setNewName] = useState("");
|
||||||
|
const [deleteName, setDeleteName] = useState("");
|
||||||
|
const [confirmingDelete, setConfirmingDelete] = useState(false);
|
||||||
|
const [confirmText, setConfirmText] = useState("");
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetch("/api/years")
|
||||||
|
.then((r) => r.json())
|
||||||
|
.then((d: { years: number[] }) => {
|
||||||
|
setYears(d.years);
|
||||||
|
if (d.years.length) setYear(String(d.years[0]));
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
if (!year) return;
|
||||||
|
setLoading(true);
|
||||||
|
const qs = new URLSearchParams({ region, year });
|
||||||
|
const d = await fetch(`/api/cost-items?${qs.toString()}`).then((r) =>
|
||||||
|
r.json()
|
||||||
|
);
|
||||||
|
setItems(d.items ?? []);
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (year) load();
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [region, year]);
|
||||||
|
|
||||||
|
// Distinct item names (sorted) present in the current selection.
|
||||||
|
const names = useMemo(
|
||||||
|
() => [...new Set(items.map((i) => i.name))].sort((a, b) => a.localeCompare(b)),
|
||||||
|
[items]
|
||||||
|
);
|
||||||
|
|
||||||
|
// Set of "name||region" for O(1) presence lookups in the pivot table.
|
||||||
|
const presence = useMemo(() => {
|
||||||
|
const set = new Set<string>();
|
||||||
|
for (const it of items) set.add(`${it.name}||${it.region}`);
|
||||||
|
return set;
|
||||||
|
}, [items]);
|
||||||
|
|
||||||
|
async function addItem() {
|
||||||
|
const name = newName.trim();
|
||||||
|
if (!name) return;
|
||||||
|
setBusy(true);
|
||||||
|
const res = await fetch("/api/cost-items", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ name, region, year }),
|
||||||
|
}).then((r) => r.json());
|
||||||
|
setBusy(false);
|
||||||
|
setNewName("");
|
||||||
|
await load();
|
||||||
|
if (region === ALL_REGION) {
|
||||||
|
window.alert(
|
||||||
|
`Created in ${res.created} region(s)${
|
||||||
|
res.skipped ? `, skipped ${res.skipped} that already had it` : ""
|
||||||
|
}.`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Open the inline type-to-confirm step (no browser message box).
|
||||||
|
function startDelete() {
|
||||||
|
if (!deleteName.trim()) return;
|
||||||
|
setConfirmText("");
|
||||||
|
setConfirmingDelete(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
function cancelDelete() {
|
||||||
|
setConfirmingDelete(false);
|
||||||
|
setConfirmText("");
|
||||||
|
}
|
||||||
|
|
||||||
|
async function confirmDelete() {
|
||||||
|
const name = deleteName.trim();
|
||||||
|
if (!name || confirmText.trim() !== name) return;
|
||||||
|
setBusy(true);
|
||||||
|
const res = await fetch("/api/cost-items/delete", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ name, region, year }),
|
||||||
|
}).then((r) => r.json());
|
||||||
|
setBusy(false);
|
||||||
|
setConfirmingDelete(false);
|
||||||
|
setConfirmText("");
|
||||||
|
setDeleteName("");
|
||||||
|
await load();
|
||||||
|
window.alert(`Deleted ${res.deleted} item(s).`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const deleteScope =
|
||||||
|
region === ALL_REGION ? `every region for ${year}` : `${region} ${year}`;
|
||||||
|
|
||||||
|
const isAll = region === ALL_REGION;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<h1 className="mb-5 text-xl font-semibold text-[#111827]">
|
||||||
|
Cost Item Creation
|
||||||
|
</h1>
|
||||||
|
|
||||||
|
<FilterBar>
|
||||||
|
<Select
|
||||||
|
label="Region"
|
||||||
|
value={region}
|
||||||
|
onChange={setRegion}
|
||||||
|
options={REGION_OPTIONS}
|
||||||
|
className="w-64"
|
||||||
|
/>
|
||||||
|
<Select
|
||||||
|
label="Year"
|
||||||
|
value={year}
|
||||||
|
onChange={setYear}
|
||||||
|
options={years.map(String)}
|
||||||
|
className="w-40"
|
||||||
|
/>
|
||||||
|
</FilterBar>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-1 gap-5 lg:grid-cols-2">
|
||||||
|
<Card title="Add Cost Item">
|
||||||
|
<div className="flex flex-col gap-3">
|
||||||
|
<input
|
||||||
|
value={newName}
|
||||||
|
onChange={(e) => setNewName(e.target.value)}
|
||||||
|
placeholder="Cost item name (e.g. Cloud Hosting)"
|
||||||
|
className="rounded-lg border border-[#E5E7EB] px-3 py-2.5 text-sm outline-none focus:border-[#3B82F6]"
|
||||||
|
/>
|
||||||
|
<p className="text-xs text-[#6B7280]">
|
||||||
|
{isAll
|
||||||
|
? "Region = All → creates in all 5 regions (skips any that already have it)."
|
||||||
|
: `Creates in ${region} for ${year}.`}
|
||||||
|
</p>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={addItem}
|
||||||
|
disabled={busy || !newName.trim()}
|
||||||
|
className="self-start rounded-md bg-[#3B82F6] px-5 py-2 text-sm font-semibold text-white hover:bg-blue-600 disabled:opacity-60"
|
||||||
|
>
|
||||||
|
Add
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card title="Delete Cost Item">
|
||||||
|
<div className="flex flex-col gap-3">
|
||||||
|
<input
|
||||||
|
value={deleteName}
|
||||||
|
onChange={(e) => setDeleteName(e.target.value)}
|
||||||
|
placeholder="Cost item name to delete"
|
||||||
|
disabled={confirmingDelete}
|
||||||
|
className="rounded-lg border border-[#E5E7EB] px-3 py-2.5 text-sm outline-none focus:border-[#EF4444] disabled:bg-gray-50"
|
||||||
|
/>
|
||||||
|
<p className="text-xs text-[#6B7280]">
|
||||||
|
{isAll
|
||||||
|
? "Region = All → removes every copy across regions for this year."
|
||||||
|
: `Removes from ${region} for ${year}.`}
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{confirmingDelete ? (
|
||||||
|
<div className="rounded-lg border border-[#FECACA] bg-[#FEF2F2] p-3">
|
||||||
|
<p className="mb-2 text-sm text-[#111827]">
|
||||||
|
This will{" "}
|
||||||
|
<span className="font-bold text-[#EF4444]">
|
||||||
|
permanently delete
|
||||||
|
</span>{" "}
|
||||||
|
"{deleteName.trim()}" from {deleteScope}, including its
|
||||||
|
sub-costs. Type the item name below to confirm.
|
||||||
|
</p>
|
||||||
|
<input
|
||||||
|
value={confirmText}
|
||||||
|
onChange={(e) => setConfirmText(e.target.value)}
|
||||||
|
placeholder={deleteName.trim()}
|
||||||
|
autoFocus
|
||||||
|
className="mb-3 w-full rounded-lg border border-[#FCA5A5] px-3 py-2 text-sm outline-none focus:border-[#EF4444]"
|
||||||
|
/>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={confirmDelete}
|
||||||
|
disabled={busy || confirmText.trim() !== deleteName.trim()}
|
||||||
|
className="rounded-md bg-[#EF4444] px-4 py-2 text-sm font-semibold text-white hover:bg-red-600 disabled:opacity-60"
|
||||||
|
>
|
||||||
|
Confirm Delete
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={cancelDelete}
|
||||||
|
disabled={busy}
|
||||||
|
className="rounded-md border border-[#E5E7EB] px-4 py-2 text-sm font-medium text-[#111827] hover:bg-gray-50"
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={startDelete}
|
||||||
|
disabled={busy || !deleteName.trim()}
|
||||||
|
className="self-start rounded-md bg-[#EF4444] px-5 py-2 text-sm font-semibold text-white hover:bg-red-600 disabled:opacity-60"
|
||||||
|
>
|
||||||
|
DELETE
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-5">
|
||||||
|
<Card title={`Cost Items — ${region} ${year}`}>
|
||||||
|
<table className="w-full text-sm">
|
||||||
|
<thead>
|
||||||
|
<tr className="border-b border-[#E5E7EB] text-left text-[#6B7280]">
|
||||||
|
<th className="px-3 py-2.5 font-medium">Cost Item</th>
|
||||||
|
{isAll &&
|
||||||
|
REGIONS.map((r) => (
|
||||||
|
<th
|
||||||
|
key={r}
|
||||||
|
className="px-2 py-2.5 text-center text-xs font-medium"
|
||||||
|
>
|
||||||
|
{r}
|
||||||
|
</th>
|
||||||
|
))}
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{loading ? (
|
||||||
|
<tr>
|
||||||
|
<td
|
||||||
|
colSpan={isAll ? 1 + REGIONS.length : 1}
|
||||||
|
className="px-3 py-6 text-center text-[#6B7280]"
|
||||||
|
>
|
||||||
|
Loading…
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
) : names.length === 0 ? (
|
||||||
|
<tr>
|
||||||
|
<td
|
||||||
|
colSpan={isAll ? 1 + REGIONS.length : 1}
|
||||||
|
className="px-3 py-6 text-center text-[#6B7280]"
|
||||||
|
>
|
||||||
|
No cost items yet.
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
) : (
|
||||||
|
names.map((name) => (
|
||||||
|
<tr
|
||||||
|
key={name}
|
||||||
|
className="border-b border-[#F3F4F6] last:border-0"
|
||||||
|
>
|
||||||
|
<td className="px-3 py-2.5 text-[#111827]">{name}</td>
|
||||||
|
{isAll &&
|
||||||
|
REGIONS.map((r) => {
|
||||||
|
const has = presence.has(`${name}||${r}`);
|
||||||
|
return (
|
||||||
|
<td key={r} className="px-2 py-2.5 text-center">
|
||||||
|
{has ? (
|
||||||
|
<span
|
||||||
|
className="font-semibold text-[#10B981]"
|
||||||
|
title={`Exists in ${r}`}
|
||||||
|
>
|
||||||
|
✓
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<span className="text-[#D1D5DB]">–</span>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</tr>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,319 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import FilterBar from "@/components/ui/FilterBar";
|
||||||
|
import Select from "@/components/ui/Select";
|
||||||
|
import Card from "@/components/ui/Card";
|
||||||
|
import { REGIONS, isRegion } from "@/lib/regions";
|
||||||
|
import { formatCurrency } from "@/lib/format";
|
||||||
|
|
||||||
|
type SubItem = { id: number; name: string; subCost: number };
|
||||||
|
type Item = { id: number; name: string; subItems: SubItem[] };
|
||||||
|
|
||||||
|
export default function CostRegistrationPage() {
|
||||||
|
const [years, setYears] = useState<number[]>([]);
|
||||||
|
const [region, setRegion] = useState(""); // placeholder until chosen
|
||||||
|
const [year, setYear] = useState<string>("2026");
|
||||||
|
const [items, setItems] = useState<Item[]>([]);
|
||||||
|
const [percentage, setPercentage] = useState<string>("0");
|
||||||
|
const [collapsed, setCollapsed] = useState<Record<number, boolean>>({});
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
|
||||||
|
const specific = isRegion(region);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetch("/api/years")
|
||||||
|
.then((r) => r.json())
|
||||||
|
.then((d: { years: number[] }) => {
|
||||||
|
setYears(d.years);
|
||||||
|
if (d.years.length && !d.years.includes(2026)) {
|
||||||
|
setYear(String(d.years[0]));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
if (!specific || !year) return;
|
||||||
|
setLoading(true);
|
||||||
|
const qs = new URLSearchParams({ region, year });
|
||||||
|
const d = await fetch(`/api/cost-registration?${qs.toString()}`).then((r) =>
|
||||||
|
r.json()
|
||||||
|
);
|
||||||
|
const loaded: Item[] = d.items ?? [];
|
||||||
|
setItems(loaded);
|
||||||
|
// Fold every cost item by default.
|
||||||
|
setCollapsed(Object.fromEntries(loaded.map((it) => [it.id, true])));
|
||||||
|
setPercentage(String(d.percentage ?? 0));
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (specific && year) load();
|
||||||
|
else setItems([]);
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [region, year]);
|
||||||
|
|
||||||
|
function toggle(itemId: number) {
|
||||||
|
setCollapsed((prev) => ({ ...prev, [itemId]: !prev[itemId] }));
|
||||||
|
}
|
||||||
|
|
||||||
|
function setSub(itemId: number, subId: number, patch: Partial<SubItem>) {
|
||||||
|
setItems((prev) =>
|
||||||
|
prev.map((it) =>
|
||||||
|
it.id !== itemId
|
||||||
|
? it
|
||||||
|
: {
|
||||||
|
...it,
|
||||||
|
subItems: it.subItems.map((s) =>
|
||||||
|
s.id === subId ? { ...s, ...patch } : s
|
||||||
|
),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add a sub-item and splice the created row into local state (no full reload).
|
||||||
|
async function addSub(itemId: number) {
|
||||||
|
const res = await fetch("/api/sub-items", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ costItemId: itemId, name: "New Sub Cost", subCost: 0 }),
|
||||||
|
}).then((r) => r.json());
|
||||||
|
const sub = res.subItem as SubItem;
|
||||||
|
if (!sub) return;
|
||||||
|
setItems((prev) =>
|
||||||
|
prev.map((it) =>
|
||||||
|
it.id === itemId
|
||||||
|
? {
|
||||||
|
...it,
|
||||||
|
subItems: [
|
||||||
|
...it.subItems,
|
||||||
|
{ id: sub.id, name: sub.name, subCost: sub.subCost },
|
||||||
|
],
|
||||||
|
}
|
||||||
|
: it
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove a sub-item and drop it from local state (no full reload).
|
||||||
|
async function removeSub(itemId: number, subId: number) {
|
||||||
|
if (!window.confirm("Remove this sub cost? This cannot be undone.")) return;
|
||||||
|
await fetch(`/api/sub-items/${subId}`, { method: "DELETE" });
|
||||||
|
setItems((prev) =>
|
||||||
|
prev.map((it) =>
|
||||||
|
it.id === itemId
|
||||||
|
? { ...it, subItems: it.subItems.filter((s) => s.id !== subId) }
|
||||||
|
: it
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function update() {
|
||||||
|
setSaving(true);
|
||||||
|
// Persist every sub-item's current name + subCost.
|
||||||
|
await Promise.all(
|
||||||
|
items.flatMap((it) =>
|
||||||
|
it.subItems.map((s) =>
|
||||||
|
fetch(`/api/sub-items/${s.id}`, {
|
||||||
|
method: "PATCH",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ name: s.name, subCost: Number(s.subCost) || 0 }),
|
||||||
|
})
|
||||||
|
)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
// Persist the TrendAI percentage for this region+year.
|
||||||
|
await fetch("/api/trend-percentage", {
|
||||||
|
method: "PUT",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ region, year, percentage: Number(percentage) || 0 }),
|
||||||
|
});
|
||||||
|
setSaving(false);
|
||||||
|
window.alert("Saved. Dashboard TrendAI / TrendLife columns will reflect this.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<h1 className="mb-5 text-xl font-semibold text-[#111827]">
|
||||||
|
Cost Registration
|
||||||
|
</h1>
|
||||||
|
|
||||||
|
<FilterBar>
|
||||||
|
<Select
|
||||||
|
label="Region"
|
||||||
|
value={region}
|
||||||
|
onChange={setRegion}
|
||||||
|
options={[...REGIONS]}
|
||||||
|
placeholder="Please select a Region"
|
||||||
|
className="w-64"
|
||||||
|
/>
|
||||||
|
<Select
|
||||||
|
label="Year"
|
||||||
|
value={year}
|
||||||
|
onChange={setYear}
|
||||||
|
options={years.map(String)}
|
||||||
|
className="w-40"
|
||||||
|
/>
|
||||||
|
</FilterBar>
|
||||||
|
|
||||||
|
{!specific ? (
|
||||||
|
<Card>
|
||||||
|
<p className="py-6 text-center text-[#6B7280]">
|
||||||
|
Please select a Region to register costs.
|
||||||
|
</p>
|
||||||
|
</Card>
|
||||||
|
) : loading ? (
|
||||||
|
<Card>
|
||||||
|
<p className="py-6 text-center text-[#6B7280]">Loading…</p>
|
||||||
|
</Card>
|
||||||
|
) : (
|
||||||
|
<div className="flex flex-col gap-5">
|
||||||
|
<Card title="TrendAI Percentage">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
min={0}
|
||||||
|
max={100}
|
||||||
|
value={percentage}
|
||||||
|
onChange={(e) => setPercentage(e.target.value)}
|
||||||
|
className="w-28 rounded-lg border border-[#E5E7EB] px-3 py-2 text-sm outline-none focus:border-[#3B82F6]"
|
||||||
|
/>
|
||||||
|
<span className="text-sm text-[#6B7280]">
|
||||||
|
% of each item's cost attributed to TrendAI (the rest is
|
||||||
|
TrendLife).
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{items.length === 0 ? (
|
||||||
|
<Card>
|
||||||
|
<p className="py-6 text-center text-[#6B7280]">
|
||||||
|
No cost items for {region} {year}. Create items on the Cost Item
|
||||||
|
Creation page first.
|
||||||
|
</p>
|
||||||
|
</Card>
|
||||||
|
) : (
|
||||||
|
items.map((item) => {
|
||||||
|
const cost = item.subItems.reduce(
|
||||||
|
(a, s) => a + (Number(s.subCost) || 0),
|
||||||
|
0
|
||||||
|
);
|
||||||
|
const isCollapsed = collapsed[item.id] ?? true;
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={item.id}
|
||||||
|
className="rounded-lg border border-[#E5E7EB] bg-white"
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => toggle(item.id)}
|
||||||
|
className="flex w-full items-center gap-2 px-5 py-3.5 text-left"
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
className={`h-4 w-4 text-[#6B7280] transition-transform ${
|
||||||
|
isCollapsed ? "" : "rotate-90"
|
||||||
|
}`}
|
||||||
|
viewBox="0 0 20 20"
|
||||||
|
fill="currentColor"
|
||||||
|
aria-hidden="true"
|
||||||
|
>
|
||||||
|
<path
|
||||||
|
fillRule="evenodd"
|
||||||
|
d="M7.21 5.23a.75.75 0 011.06-.02l4.24 4.24a.75.75 0 010 1.06l-4.24 4.24a.75.75 0 11-1.08-1.04L10.94 10 7.19 6.29a.75.75 0 01.02-1.06z"
|
||||||
|
clipRule="evenodd"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
<span className="text-sm font-semibold text-[#111827]">
|
||||||
|
{item.name}
|
||||||
|
</span>
|
||||||
|
<span className="ml-auto text-sm font-semibold text-[#111827]">
|
||||||
|
{formatCurrency(cost)}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{!isCollapsed && (
|
||||||
|
<div className="border-t border-[#E5E7EB] px-5 py-5">
|
||||||
|
<table className="w-full text-sm">
|
||||||
|
<thead>
|
||||||
|
<tr className="border-b border-[#E5E7EB] text-left text-[#6B7280]">
|
||||||
|
<th className="px-2 py-2 font-medium">
|
||||||
|
Sub Cost Item
|
||||||
|
</th>
|
||||||
|
<th className="px-2 py-2 text-right font-medium">
|
||||||
|
Sub Cost
|
||||||
|
</th>
|
||||||
|
<th className="px-2 py-2 text-right font-medium"></th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{item.subItems.map((s) => (
|
||||||
|
<tr key={s.id} className="border-b border-[#F3F4F6]">
|
||||||
|
<td className="px-2 py-2">
|
||||||
|
<input
|
||||||
|
value={s.name}
|
||||||
|
onChange={(e) =>
|
||||||
|
setSub(item.id, s.id, {
|
||||||
|
name: e.target.value,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
className="w-full rounded-md border border-[#E5E7EB] px-2 py-1.5 outline-none focus:border-[#3B82F6]"
|
||||||
|
/>
|
||||||
|
</td>
|
||||||
|
<td className="px-2 py-2 text-right">
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
value={s.subCost}
|
||||||
|
onChange={(e) =>
|
||||||
|
setSub(item.id, s.id, {
|
||||||
|
subCost: Number(e.target.value),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
className="w-36 rounded-md border border-[#E5E7EB] px-2 py-1.5 text-right outline-none focus:border-[#3B82F6]"
|
||||||
|
/>
|
||||||
|
</td>
|
||||||
|
<td className="px-2 py-2 text-right">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => removeSub(item.id, s.id)}
|
||||||
|
className="text-sm font-medium text-[#EF4444] hover:underline"
|
||||||
|
>
|
||||||
|
× Remove
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => addSub(item.id)}
|
||||||
|
className="mt-3 rounded-md border border-[#E5E7EB] px-3 py-1.5 text-sm font-medium text-[#111827] hover:bg-gray-50"
|
||||||
|
>
|
||||||
|
+ Add Sub
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})
|
||||||
|
)}
|
||||||
|
|
||||||
|
{items.length > 0 && (
|
||||||
|
<div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={update}
|
||||||
|
disabled={saving}
|
||||||
|
className="rounded-md bg-[#3B82F6] px-5 py-2.5 text-sm font-semibold text-white hover:bg-blue-600 disabled:opacity-60"
|
||||||
|
>
|
||||||
|
{saving ? "Updating…" : "Update"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
@import "tailwindcss";
|
||||||
|
|
||||||
|
@theme {
|
||||||
|
--color-ink: #111827;
|
||||||
|
--color-muted: #6b7280;
|
||||||
|
--color-cardborder: #e5e7eb;
|
||||||
|
--color-gridline: #edeff2;
|
||||||
|
--color-accent: #3b82f6;
|
||||||
|
}
|
||||||
|
|
||||||
|
:root {
|
||||||
|
--background: #f9fafb;
|
||||||
|
}
|
||||||
|
|
||||||
|
html,
|
||||||
|
body {
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
background: var(--background);
|
||||||
|
color: #111827;
|
||||||
|
font-family: Inter, ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto,
|
||||||
|
Helvetica, Arial, sans-serif;
|
||||||
|
-webkit-font-smoothing: antialiased;
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import type { Metadata } from "next";
|
||||||
|
import "./globals.css";
|
||||||
|
import TopNav from "@/components/TopNav";
|
||||||
|
import Sidebar from "@/components/Sidebar";
|
||||||
|
import { auth } from "@/auth";
|
||||||
|
|
||||||
|
export const metadata: Metadata = {
|
||||||
|
title: "Global IT Cost Dashboard",
|
||||||
|
description: "Track IT cost across regions",
|
||||||
|
};
|
||||||
|
|
||||||
|
export default async function RootLayout({
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
children: React.ReactNode;
|
||||||
|
}) {
|
||||||
|
const session = await auth();
|
||||||
|
|
||||||
|
// Unauthenticated (e.g. the /login page) -> render a bare shell with no
|
||||||
|
// sidebar/topnav so the sign-in screen shows on its own.
|
||||||
|
if (!session?.user) {
|
||||||
|
return (
|
||||||
|
<html lang="en">
|
||||||
|
<body>{children}</body>
|
||||||
|
</html>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const isAdmin = session.user.role === "admin";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<html lang="en">
|
||||||
|
<body>
|
||||||
|
<div className="flex min-h-screen">
|
||||||
|
<Sidebar isAdmin={isAdmin} />
|
||||||
|
<div className="flex min-w-0 flex-1 flex-col">
|
||||||
|
<TopNav />
|
||||||
|
<main className="flex-1 p-6">{children}</main>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
import { redirect } from "next/navigation";
|
||||||
|
import { AuthError } from "next-auth";
|
||||||
|
import { signIn } from "@/auth";
|
||||||
|
|
||||||
|
// Map Auth.js error codes (passed back via ?error=) to human-readable text.
|
||||||
|
function errorMessage(code: string | undefined): string | null {
|
||||||
|
switch (code) {
|
||||||
|
case "CredentialsSignin":
|
||||||
|
return "Invalid username or password";
|
||||||
|
case "AccessDenied":
|
||||||
|
return "Your account is not authorized — contact the administrator";
|
||||||
|
default:
|
||||||
|
return code ? "Sign-in failed — please try again" : null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Server action: kick off the Microsoft SSO flow.
|
||||||
|
async function microsoftLogin() {
|
||||||
|
"use server";
|
||||||
|
await signIn("microsoft-entra-id", { redirectTo: "/" });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Server action: local username/password login.
|
||||||
|
async function credentialsLogin(formData: FormData) {
|
||||||
|
"use server";
|
||||||
|
try {
|
||||||
|
await signIn("credentials", {
|
||||||
|
username: formData.get("username"),
|
||||||
|
password: formData.get("password"),
|
||||||
|
redirectTo: "/",
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
// A failed credentials check throws an AuthError -> show the banner.
|
||||||
|
if (error instanceof AuthError) {
|
||||||
|
redirect("/login?error=CredentialsSignin");
|
||||||
|
}
|
||||||
|
// Re-throw the Next.js redirect control-flow error (successful sign-in).
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function LoginPage({
|
||||||
|
searchParams,
|
||||||
|
}: {
|
||||||
|
searchParams: Promise<{ error?: string }>;
|
||||||
|
}) {
|
||||||
|
const { error } = await searchParams;
|
||||||
|
const message = errorMessage(error);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-screen items-center justify-center bg-[#F9FAFB] px-4">
|
||||||
|
<div className="w-full max-w-sm rounded-xl border border-[#E5E7EB] bg-white p-8 shadow-sm">
|
||||||
|
<h1 className="text-center text-lg font-semibold text-[#111827]">
|
||||||
|
Global IT Cost Dashboard
|
||||||
|
</h1>
|
||||||
|
<p className="mt-1 text-center text-sm text-[#6B7280]">
|
||||||
|
Sign in to continue
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{message && (
|
||||||
|
<div className="mt-6 rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">
|
||||||
|
{message}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<form action={microsoftLogin} className="mt-6">
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
className="w-full rounded-md bg-[#2F2F2F] px-3 py-2 text-sm font-medium text-white transition-colors hover:bg-black"
|
||||||
|
>
|
||||||
|
Sign in with Microsoft
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<div className="my-6 flex items-center gap-3 text-xs text-[#9CA3AF]">
|
||||||
|
<span className="h-px flex-1 bg-[#E5E7EB]" />
|
||||||
|
OR
|
||||||
|
<span className="h-px flex-1 bg-[#E5E7EB]" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form action={credentialsLogin} className="flex flex-col gap-3">
|
||||||
|
<label className="flex flex-col gap-1 text-sm text-[#374151]">
|
||||||
|
Username
|
||||||
|
<input
|
||||||
|
name="username"
|
||||||
|
type="text"
|
||||||
|
autoComplete="username"
|
||||||
|
required
|
||||||
|
className="rounded-md border border-[#D1D5DB] px-3 py-2 text-sm text-[#111827] outline-none focus:border-[#3B82F6] focus:ring-1 focus:ring-[#3B82F6]"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label className="flex flex-col gap-1 text-sm text-[#374151]">
|
||||||
|
Password
|
||||||
|
<input
|
||||||
|
name="password"
|
||||||
|
type="password"
|
||||||
|
autoComplete="current-password"
|
||||||
|
required
|
||||||
|
className="rounded-md border border-[#D1D5DB] px-3 py-2 text-sm text-[#111827] outline-none focus:border-[#3B82F6] focus:ring-1 focus:ring-[#3B82F6]"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
className="mt-1 w-full rounded-md bg-[#3B82F6] px-3 py-2 text-sm font-medium text-white transition-colors hover:bg-[#2563EB]"
|
||||||
|
>
|
||||||
|
Sign in
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import FilterBar from "@/components/ui/FilterBar";
|
||||||
|
import Select from "@/components/ui/Select";
|
||||||
|
import Card from "@/components/ui/Card";
|
||||||
|
import { REGION_OPTIONS, COST_ITEM_OPTIONS } from "@/lib/regions";
|
||||||
|
import { formatCurrency } from "@/lib/format";
|
||||||
|
|
||||||
|
type Row = {
|
||||||
|
name: string;
|
||||||
|
cost: number;
|
||||||
|
trendAiCost: number;
|
||||||
|
trendLifeCost: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function DashboardPage() {
|
||||||
|
const [years, setYears] = useState<number[]>([]);
|
||||||
|
const [region, setRegion] = useState("All");
|
||||||
|
const [costItem, setCostItem] = useState("All");
|
||||||
|
const [year, setYear] = useState<string>("");
|
||||||
|
const [rows, setRows] = useState<Row[]>([]);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
|
||||||
|
// Load available years once; default to the newest.
|
||||||
|
useEffect(() => {
|
||||||
|
fetch("/api/years")
|
||||||
|
.then((r) => r.json())
|
||||||
|
.then((d: { years: number[] }) => {
|
||||||
|
setYears(d.years);
|
||||||
|
if (d.years.length) setYear(String(d.years[0]));
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Re-fetch table whenever filters change.
|
||||||
|
useEffect(() => {
|
||||||
|
if (!year) return;
|
||||||
|
setLoading(true);
|
||||||
|
const qs = new URLSearchParams({ region, costItem, year });
|
||||||
|
fetch(`/api/dashboard?${qs.toString()}`)
|
||||||
|
.then((r) => r.json())
|
||||||
|
.then((d: { rows: Row[] }) => setRows(d.rows ?? []))
|
||||||
|
.finally(() => setLoading(false));
|
||||||
|
}, [region, costItem, year]);
|
||||||
|
|
||||||
|
const totals = rows.reduce(
|
||||||
|
(acc, r) => {
|
||||||
|
acc.cost += r.cost;
|
||||||
|
acc.ai += r.trendAiCost;
|
||||||
|
acc.life += r.trendLifeCost;
|
||||||
|
return acc;
|
||||||
|
},
|
||||||
|
{ cost: 0, ai: 0, life: 0 }
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<h1 className="mb-5 text-xl font-semibold text-[#111827]">
|
||||||
|
Cost Overview
|
||||||
|
</h1>
|
||||||
|
|
||||||
|
<FilterBar>
|
||||||
|
<Select
|
||||||
|
label="Region"
|
||||||
|
value={region}
|
||||||
|
onChange={setRegion}
|
||||||
|
options={REGION_OPTIONS}
|
||||||
|
className="w-64"
|
||||||
|
/>
|
||||||
|
<Select
|
||||||
|
label="Cost Item"
|
||||||
|
value={costItem}
|
||||||
|
onChange={setCostItem}
|
||||||
|
options={[...COST_ITEM_OPTIONS]}
|
||||||
|
className="w-64"
|
||||||
|
/>
|
||||||
|
<Select
|
||||||
|
label="Year"
|
||||||
|
value={year}
|
||||||
|
onChange={setYear}
|
||||||
|
options={years.map(String)}
|
||||||
|
className="w-40"
|
||||||
|
/>
|
||||||
|
</FilterBar>
|
||||||
|
|
||||||
|
<Card>
|
||||||
|
<table className="w-full text-sm">
|
||||||
|
<thead>
|
||||||
|
<tr className="border-b border-[#E5E7EB] text-left text-[#6B7280]">
|
||||||
|
<th className="px-3 py-2.5 font-medium">Cost Item</th>
|
||||||
|
<th className="px-3 py-2.5 text-right font-medium">Cost</th>
|
||||||
|
<th className="px-3 py-2.5 text-right font-medium">TrendAI Cost</th>
|
||||||
|
<th className="px-3 py-2.5 text-right font-medium">
|
||||||
|
TrendLife Cost
|
||||||
|
</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{loading ? (
|
||||||
|
<tr>
|
||||||
|
<td colSpan={4} className="px-3 py-6 text-center text-[#6B7280]">
|
||||||
|
Loading…
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
) : rows.length === 0 ? (
|
||||||
|
<tr>
|
||||||
|
<td colSpan={4} className="px-3 py-6 text-center text-[#6B7280]">
|
||||||
|
No data for this selection.
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
) : (
|
||||||
|
rows.map((r) => (
|
||||||
|
<tr
|
||||||
|
key={r.name}
|
||||||
|
className="border-b border-[#F3F4F6] last:border-0"
|
||||||
|
>
|
||||||
|
<td className="px-3 py-2.5 text-[#111827]">{r.name}</td>
|
||||||
|
<td className="px-3 py-2.5 text-right text-[#111827]">
|
||||||
|
{formatCurrency(r.cost)}
|
||||||
|
</td>
|
||||||
|
<td className="px-3 py-2.5 text-right text-[#111827]">
|
||||||
|
{formatCurrency(r.trendAiCost)}
|
||||||
|
</td>
|
||||||
|
<td className="px-3 py-2.5 text-right text-[#111827]">
|
||||||
|
{formatCurrency(r.trendLifeCost)}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</tbody>
|
||||||
|
{rows.length > 0 && (
|
||||||
|
<tfoot>
|
||||||
|
<tr className="border-t border-[#E5E7EB] font-semibold text-[#111827]">
|
||||||
|
<td className="px-3 py-2.5">Total</td>
|
||||||
|
<td className="px-3 py-2.5 text-right">
|
||||||
|
{formatCurrency(totals.cost)}
|
||||||
|
</td>
|
||||||
|
<td className="px-3 py-2.5 text-right">
|
||||||
|
{formatCurrency(totals.ai)}
|
||||||
|
</td>
|
||||||
|
<td className="px-3 py-2.5 text-right">
|
||||||
|
{formatCurrency(totals.life)}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tfoot>
|
||||||
|
)}
|
||||||
|
</table>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import FilterBar from "@/components/ui/FilterBar";
|
||||||
|
import Select from "@/components/ui/Select";
|
||||||
|
import Card from "@/components/ui/Card";
|
||||||
|
import TrendChart, { Series } from "@/components/TrendChart";
|
||||||
|
import { REGION_OPTIONS } from "@/lib/regions";
|
||||||
|
|
||||||
|
export default function TrendPage() {
|
||||||
|
const [years, setYears] = useState<number[]>([]);
|
||||||
|
const [region, setRegion] = useState("All");
|
||||||
|
// Year is kept per spec as the default-selected control. A trend line spans
|
||||||
|
// all years, so this selection does not truncate the chart.
|
||||||
|
const [year, setYear] = useState<string>("");
|
||||||
|
const [series, setSeries] = useState<Series | null>(null);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetch("/api/years")
|
||||||
|
.then((r) => r.json())
|
||||||
|
.then((d: { years: number[] }) => {
|
||||||
|
setYears(d.years);
|
||||||
|
if (d.years.length) setYear(String(d.years[0]));
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setLoading(true);
|
||||||
|
const qs = new URLSearchParams({ region });
|
||||||
|
fetch(`/api/trend?${qs.toString()}`)
|
||||||
|
.then((r) => r.json())
|
||||||
|
.then((d: Series) => setSeries(d))
|
||||||
|
.finally(() => setLoading(false));
|
||||||
|
}, [region]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<h1 className="mb-5 text-xl font-semibold text-[#111827]">Cost Trend</h1>
|
||||||
|
|
||||||
|
<FilterBar>
|
||||||
|
<Select
|
||||||
|
label="Region"
|
||||||
|
value={region}
|
||||||
|
onChange={setRegion}
|
||||||
|
options={REGION_OPTIONS}
|
||||||
|
className="w-64"
|
||||||
|
/>
|
||||||
|
<Select
|
||||||
|
label="Year"
|
||||||
|
value={year}
|
||||||
|
onChange={setYear}
|
||||||
|
options={years.map(String)}
|
||||||
|
className="w-40"
|
||||||
|
/>
|
||||||
|
</FilterBar>
|
||||||
|
|
||||||
|
<Card
|
||||||
|
title={
|
||||||
|
region === "All"
|
||||||
|
? "Cost Trend by Region"
|
||||||
|
: `Cost Trend by Cost Item — ${region}`
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{loading || !series ? (
|
||||||
|
<div className="flex h-[420px] items-center justify-center text-[#6B7280]">
|
||||||
|
Loading…
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<TrendChart series={series} />
|
||||||
|
)}
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,207 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import Card from "@/components/ui/Card";
|
||||||
|
|
||||||
|
export default function YearCreationPage() {
|
||||||
|
const [years, setYears] = useState<number[]>([]);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
|
||||||
|
const [newYear, setNewYear] = useState("");
|
||||||
|
const [deleteYear, setDeleteYear] = useState("");
|
||||||
|
const [confirmingDelete, setConfirmingDelete] = useState(false);
|
||||||
|
const [confirmText, setConfirmText] = useState("");
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
setLoading(true);
|
||||||
|
const d = await fetch("/api/years").then((r) => r.json());
|
||||||
|
setYears(d.years ?? []);
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
load();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
async function addYear() {
|
||||||
|
const year = newYear.trim();
|
||||||
|
if (!year) return;
|
||||||
|
setBusy(true);
|
||||||
|
const res = await fetch("/api/years", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ year }),
|
||||||
|
}).then((r) => r.json());
|
||||||
|
setBusy(false);
|
||||||
|
setNewYear("");
|
||||||
|
await load();
|
||||||
|
if (res.error) {
|
||||||
|
window.alert("Please enter a valid year.");
|
||||||
|
} else if (res.exists) {
|
||||||
|
window.alert(`${res.year} already exists.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Open the inline type-to-confirm step (no browser message box).
|
||||||
|
function startDelete() {
|
||||||
|
if (!deleteYear.trim()) return;
|
||||||
|
setConfirmText("");
|
||||||
|
setConfirmingDelete(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
function cancelDelete() {
|
||||||
|
setConfirmingDelete(false);
|
||||||
|
setConfirmText("");
|
||||||
|
}
|
||||||
|
|
||||||
|
async function confirmDelete() {
|
||||||
|
const year = deleteYear.trim();
|
||||||
|
if (!year || confirmText.trim() !== year) return;
|
||||||
|
setBusy(true);
|
||||||
|
const res = await fetch("/api/years/delete", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ year }),
|
||||||
|
}).then((r) => r.json());
|
||||||
|
setBusy(false);
|
||||||
|
setConfirmingDelete(false);
|
||||||
|
setConfirmText("");
|
||||||
|
setDeleteYear("");
|
||||||
|
await load();
|
||||||
|
window.alert(
|
||||||
|
`Deleted ${res.year}. Removed ${res.deletedItems} cost item(s) and ${res.deletedPercentages} TrendAI percentage(s).`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<h1 className="mb-5 text-xl font-semibold text-[#111827]">Year Creation</h1>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-1 gap-5 lg:grid-cols-2">
|
||||||
|
<Card title="Add Year">
|
||||||
|
<div className="flex flex-col gap-3">
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
value={newYear}
|
||||||
|
onChange={(e) => setNewYear(e.target.value)}
|
||||||
|
placeholder="Year (e.g. 2027)"
|
||||||
|
className="rounded-lg border border-[#E5E7EB] px-3 py-2.5 text-sm outline-none focus:border-[#3B82F6]"
|
||||||
|
/>
|
||||||
|
<p className="text-xs text-[#6B7280]">
|
||||||
|
Adds a year available for selection across the app.
|
||||||
|
</p>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={addYear}
|
||||||
|
disabled={busy || !newYear.trim()}
|
||||||
|
className="self-start rounded-md bg-[#3B82F6] px-5 py-2 text-sm font-semibold text-white hover:bg-blue-600 disabled:opacity-60"
|
||||||
|
>
|
||||||
|
Add
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card title="Delete Year">
|
||||||
|
<div className="flex flex-col gap-3">
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
value={deleteYear}
|
||||||
|
onChange={(e) => setDeleteYear(e.target.value)}
|
||||||
|
placeholder="Year to delete"
|
||||||
|
disabled={confirmingDelete}
|
||||||
|
className="rounded-lg border border-[#E5E7EB] px-3 py-2.5 text-sm outline-none focus:border-[#EF4444] disabled:bg-gray-50"
|
||||||
|
/>
|
||||||
|
<p className="text-xs text-[#6B7280]">
|
||||||
|
Removes the year and all of its cost items and sub-costs across
|
||||||
|
every region.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{confirmingDelete ? (
|
||||||
|
<div className="rounded-lg border border-[#FECACA] bg-[#FEF2F2] p-3">
|
||||||
|
<p className="mb-2 text-sm text-[#111827]">
|
||||||
|
This will{" "}
|
||||||
|
<span className="font-bold text-[#EF4444]">
|
||||||
|
permanently delete
|
||||||
|
</span>{" "}
|
||||||
|
year "{deleteYear.trim()}" and all of its cost data.
|
||||||
|
Type the year below to confirm.
|
||||||
|
</p>
|
||||||
|
<input
|
||||||
|
value={confirmText}
|
||||||
|
onChange={(e) => setConfirmText(e.target.value)}
|
||||||
|
placeholder={deleteYear.trim()}
|
||||||
|
autoFocus
|
||||||
|
className="mb-3 w-full rounded-lg border border-[#FCA5A5] px-3 py-2 text-sm outline-none focus:border-[#EF4444]"
|
||||||
|
/>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={confirmDelete}
|
||||||
|
disabled={busy || confirmText.trim() !== deleteYear.trim()}
|
||||||
|
className="rounded-md bg-[#EF4444] px-4 py-2 text-sm font-semibold text-white hover:bg-red-600 disabled:opacity-60"
|
||||||
|
>
|
||||||
|
Confirm Delete
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={cancelDelete}
|
||||||
|
disabled={busy}
|
||||||
|
className="rounded-md border border-[#E5E7EB] px-4 py-2 text-sm font-medium text-[#111827] hover:bg-gray-50"
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={startDelete}
|
||||||
|
disabled={busy || !deleteYear.trim()}
|
||||||
|
className="self-start rounded-md bg-[#EF4444] px-5 py-2 text-sm font-semibold text-white hover:bg-red-600 disabled:opacity-60"
|
||||||
|
>
|
||||||
|
DELETE
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-5">
|
||||||
|
<Card title="Years">
|
||||||
|
<table className="w-full text-sm">
|
||||||
|
<thead>
|
||||||
|
<tr className="border-b border-[#E5E7EB] text-left text-[#6B7280]">
|
||||||
|
<th className="px-3 py-2.5 font-medium">Year</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{loading ? (
|
||||||
|
<tr>
|
||||||
|
<td className="px-3 py-6 text-center text-[#6B7280]">
|
||||||
|
Loading…
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
) : years.length === 0 ? (
|
||||||
|
<tr>
|
||||||
|
<td className="px-3 py-6 text-center text-[#6B7280]">
|
||||||
|
No years yet.
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
) : (
|
||||||
|
years.map((y) => (
|
||||||
|
<tr
|
||||||
|
key={y}
|
||||||
|
className="border-b border-[#F3F4F6] last:border-0"
|
||||||
|
>
|
||||||
|
<td className="px-3 py-2.5 text-[#111827]">{y}</td>
|
||||||
|
</tr>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
import type { NextAuthConfig } from "next-auth";
|
||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import type { Role } from "@/lib/authz";
|
||||||
|
|
||||||
|
// Admin-only page routes. Normal users are redirected away from these.
|
||||||
|
const ADMIN_PAGE_PREFIXES = [
|
||||||
|
"/cost-registration",
|
||||||
|
"/cost-item-creation",
|
||||||
|
"/year-creation",
|
||||||
|
];
|
||||||
|
|
||||||
|
// Edge-safe Auth.js config. This is imported by the middleware, which runs in
|
||||||
|
// the edge runtime, so it MUST NOT import Node APIs (node:fs) or the providers
|
||||||
|
// (Credentials/MicrosoftEntraID pull in Node crypto). The JSON allowlist is read
|
||||||
|
// only at sign-in in src/auth.ts (Node) and the resulting role is baked into the
|
||||||
|
// JWT; here we only read the role off the token.
|
||||||
|
export const authConfig = {
|
||||||
|
// Stateless JWT sessions — no DB adapter, keeps the middleware edge-compatible.
|
||||||
|
session: { strategy: "jwt" },
|
||||||
|
// Custom sign-in page offering both SSO and local username/password.
|
||||||
|
pages: { signIn: "/login" },
|
||||||
|
// Providers are added in the Node config (src/auth.ts). Empty here on purpose.
|
||||||
|
providers: [],
|
||||||
|
callbacks: {
|
||||||
|
// Copy the role from the token onto the session so server components /
|
||||||
|
// layout can read session.user.role.
|
||||||
|
session({ session, token }) {
|
||||||
|
if (session.user) {
|
||||||
|
session.user.role = token.role as Role | undefined;
|
||||||
|
}
|
||||||
|
return session;
|
||||||
|
},
|
||||||
|
// Runs in the middleware on every matched request. Enforces both
|
||||||
|
// authentication and role-based authorization server-side.
|
||||||
|
authorized({ auth, request }) {
|
||||||
|
const { pathname } = request.nextUrl;
|
||||||
|
|
||||||
|
// Always let the sign-in page through, even when unauthenticated.
|
||||||
|
if (pathname === "/login") return true;
|
||||||
|
|
||||||
|
// Not signed in -> Auth.js redirects to the sign-in page.
|
||||||
|
if (!auth?.user) return false;
|
||||||
|
|
||||||
|
const role = auth.user.role;
|
||||||
|
|
||||||
|
// Admin is required for admin page routes and for any write API call
|
||||||
|
// (all mutations are non-GET requests to /api/*).
|
||||||
|
const needsAdmin =
|
||||||
|
ADMIN_PAGE_PREFIXES.some((prefix) => pathname.startsWith(prefix)) ||
|
||||||
|
(pathname.startsWith("/api/") && request.method !== "GET");
|
||||||
|
|
||||||
|
if (needsAdmin && role !== "admin") {
|
||||||
|
if (pathname.startsWith("/api/")) {
|
||||||
|
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
||||||
|
}
|
||||||
|
return NextResponse.redirect(new URL("/", request.url));
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
} satisfies NextAuthConfig;
|
||||||
+71
@@ -0,0 +1,71 @@
|
|||||||
|
import NextAuth from "next-auth";
|
||||||
|
import MicrosoftEntraID from "next-auth/providers/microsoft-entra-id";
|
||||||
|
import Credentials from "next-auth/providers/credentials";
|
||||||
|
import { authConfig } from "@/auth.config";
|
||||||
|
import { lookupRole, safeEqual } from "@/lib/authz";
|
||||||
|
|
||||||
|
// Auth.js v5 (NextAuth). Node-runtime config: spreads the edge-safe authConfig
|
||||||
|
// and adds the providers + Node-only callbacks (signIn/jwt) that need node:fs
|
||||||
|
// via lookupRole. Imported by the API route handler and server components —
|
||||||
|
// NEVER by the edge middleware (which uses src/auth.config.ts instead).
|
||||||
|
//
|
||||||
|
// Two sign-in paths:
|
||||||
|
// 1. Microsoft Entra ID SSO — allowed only if the email is in config/users.json.
|
||||||
|
// 2. Local username/password — break-glass admin, bypasses the JSON allowlist.
|
||||||
|
export const { handlers, auth, signIn, signOut } = NextAuth({
|
||||||
|
...authConfig,
|
||||||
|
providers: [
|
||||||
|
MicrosoftEntraID({
|
||||||
|
clientId: process.env.AUTH_MICROSOFT_ENTRA_ID_ID,
|
||||||
|
clientSecret: process.env.AUTH_MICROSOFT_ENTRA_ID_SECRET,
|
||||||
|
// Tenant-specific issuer restricts sign-in to our organization only.
|
||||||
|
issuer: process.env.AUTH_MICROSOFT_ENTRA_ID_ISSUER,
|
||||||
|
}),
|
||||||
|
Credentials({
|
||||||
|
name: "Local account",
|
||||||
|
credentials: {
|
||||||
|
username: { label: "Username", type: "text" },
|
||||||
|
password: { label: "Password", type: "password" },
|
||||||
|
},
|
||||||
|
authorize(credentials) {
|
||||||
|
const username = String(credentials?.username ?? "");
|
||||||
|
const password = String(credentials?.password ?? "");
|
||||||
|
|
||||||
|
const expectedUser = process.env.LOCAL_ADMIN_USERNAME || "admin";
|
||||||
|
const expectedPass = process.env.LOCAL_ADMIN_PASSWORD ?? "";
|
||||||
|
|
||||||
|
// Empty password env disables local login entirely (fail closed).
|
||||||
|
if (expectedPass === "") return null;
|
||||||
|
|
||||||
|
if (safeEqual(username, expectedUser) && safeEqual(password, expectedPass)) {
|
||||||
|
return { id: "local-admin", name: username, role: "admin" };
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
callbacks: {
|
||||||
|
...authConfig.callbacks,
|
||||||
|
// Gate SSO sign-ins against the JSON allowlist. The local Credentials
|
||||||
|
// account is always allowed (its role is set in authorize()).
|
||||||
|
signIn({ user, account, profile }) {
|
||||||
|
if (account?.provider === "credentials") return true;
|
||||||
|
|
||||||
|
const email =
|
||||||
|
user.email ??
|
||||||
|
(profile?.email as string | undefined) ??
|
||||||
|
(profile?.preferred_username as string | undefined);
|
||||||
|
|
||||||
|
// Returning false surfaces to the login page as ?error=AccessDenied.
|
||||||
|
return lookupRole(email) !== null;
|
||||||
|
},
|
||||||
|
// On first sign-in, bake the role into the JWT so the edge middleware can
|
||||||
|
// read it without touching node:fs.
|
||||||
|
jwt({ token, user }) {
|
||||||
|
if (user) {
|
||||||
|
token.role = user.role ?? lookupRole(user.email) ?? "user";
|
||||||
|
}
|
||||||
|
return token;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import Link from "next/link";
|
||||||
|
import { usePathname } from "next/navigation";
|
||||||
|
|
||||||
|
type NavItem = { label: string; href: string };
|
||||||
|
|
||||||
|
const MAIN: NavItem[] = [
|
||||||
|
{ label: "Overview", href: "/" },
|
||||||
|
{ label: "Trend", href: "/trend" },
|
||||||
|
];
|
||||||
|
|
||||||
|
const ADMIN: NavItem[] = [
|
||||||
|
{ label: "Cost Registration", href: "/cost-registration" },
|
||||||
|
{ label: "Cost Item Creation", href: "/cost-item-creation" },
|
||||||
|
{ label: "Year Creation", href: "/year-creation" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export default function Sidebar({ isAdmin }: { isAdmin: boolean }) {
|
||||||
|
const pathname = usePathname();
|
||||||
|
|
||||||
|
const renderLink = (item: NavItem) => {
|
||||||
|
const active = pathname === item.href;
|
||||||
|
return (
|
||||||
|
<Link
|
||||||
|
key={item.href}
|
||||||
|
href={item.href}
|
||||||
|
className={`block rounded-md px-3 py-2 text-sm font-medium transition-colors ${
|
||||||
|
active
|
||||||
|
? "bg-[#3B82F6] text-white"
|
||||||
|
: "text-gray-700 hover:bg-gray-100"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{item.label}
|
||||||
|
</Link>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<aside className="flex w-60 shrink-0 flex-col border-r border-[#E5E7EB] bg-white">
|
||||||
|
<div className="flex h-14 items-center px-6 text-base font-semibold text-[#111827]">
|
||||||
|
IT Cost
|
||||||
|
</div>
|
||||||
|
<nav className="flex flex-col gap-1 px-3 py-4">
|
||||||
|
{MAIN.map(renderLink)}
|
||||||
|
{isAdmin && (
|
||||||
|
<>
|
||||||
|
<div className="mt-6 mb-1 px-3 text-xs font-semibold uppercase tracking-wide text-[#6B7280]">
|
||||||
|
Admin
|
||||||
|
</div>
|
||||||
|
{ADMIN.map(renderLink)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</nav>
|
||||||
|
</aside>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import { auth, signIn, signOut } from "@/auth";
|
||||||
|
|
||||||
|
export default async function TopNav() {
|
||||||
|
const session = await auth();
|
||||||
|
const user = session?.user;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<header className="flex h-14 items-center justify-between bg-[#111827] px-6 text-white">
|
||||||
|
<span className="text-lg font-semibold">Global IT Cost Dashboard</span>
|
||||||
|
{user ? (
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<span className="text-sm text-white/80">{user.name ?? user.email}</span>
|
||||||
|
<form
|
||||||
|
action={async () => {
|
||||||
|
"use server";
|
||||||
|
await signOut({ redirectTo: "/" });
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
className="rounded-md bg-white/10 px-4 py-1.5 text-sm font-medium hover:bg-white/20"
|
||||||
|
>
|
||||||
|
Logout
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<form
|
||||||
|
action={async () => {
|
||||||
|
"use server";
|
||||||
|
await signIn("microsoft-entra-id");
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
className="rounded-md bg-white/10 px-4 py-1.5 text-sm font-medium hover:bg-white/20"
|
||||||
|
>
|
||||||
|
Login
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
</header>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useMemo, useState } from "react";
|
||||||
|
import {
|
||||||
|
LineChart,
|
||||||
|
Line,
|
||||||
|
XAxis,
|
||||||
|
YAxis,
|
||||||
|
CartesianGrid,
|
||||||
|
Tooltip,
|
||||||
|
Legend,
|
||||||
|
ResponsiveContainer,
|
||||||
|
} from "recharts";
|
||||||
|
import { formatCurrency } from "@/lib/format";
|
||||||
|
|
||||||
|
export type Series = {
|
||||||
|
years: number[];
|
||||||
|
lines: { key: string; values: number[] }[];
|
||||||
|
};
|
||||||
|
|
||||||
|
// Total is blue + emphasized; regions/items cycle through this palette.
|
||||||
|
const TOTAL_COLOR = "#3B82F6";
|
||||||
|
const PALETTE = [
|
||||||
|
"#10B981", // green
|
||||||
|
"#F59E0B", // amber
|
||||||
|
"#EF4444", // red
|
||||||
|
"#8B5CF6", // purple
|
||||||
|
"#06B6D4", // cyan
|
||||||
|
"#EC4899", // pink
|
||||||
|
"#84CC16", // lime
|
||||||
|
];
|
||||||
|
|
||||||
|
export default function TrendChart({ series }: { series: Series }) {
|
||||||
|
// Which single line is isolated (null = show all).
|
||||||
|
const [isolated, setIsolated] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const data = useMemo(() => {
|
||||||
|
return series.years.map((year, i) => {
|
||||||
|
const row: Record<string, number | string> = { year };
|
||||||
|
for (const line of series.lines) row[line.key] = line.values[i] ?? 0;
|
||||||
|
return row;
|
||||||
|
});
|
||||||
|
}, [series]);
|
||||||
|
|
||||||
|
const colorFor = (key: string, idx: number) =>
|
||||||
|
key === "Total" ? TOTAL_COLOR : PALETTE[(idx - 1) % PALETTE.length];
|
||||||
|
|
||||||
|
// Click a legend entry to isolate that line; click it again to restore all.
|
||||||
|
const handleLegendClick = (o: { value?: unknown; dataKey?: unknown }) => {
|
||||||
|
const key =
|
||||||
|
typeof o?.dataKey === "string"
|
||||||
|
? o.dataKey
|
||||||
|
: typeof o?.value === "string"
|
||||||
|
? o.value
|
||||||
|
: "";
|
||||||
|
if (!key) return;
|
||||||
|
setIsolated((cur) => (cur === key ? null : key));
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div className="h-[420px] w-full">
|
||||||
|
<ResponsiveContainer width="100%" height="100%">
|
||||||
|
<LineChart data={data} margin={{ top: 16, right: 24, bottom: 8, left: 8 }}>
|
||||||
|
<CartesianGrid stroke="#EDEFF2" vertical={false} />
|
||||||
|
<XAxis
|
||||||
|
dataKey="year"
|
||||||
|
tick={{ fill: "#6B7280", fontSize: 12 }}
|
||||||
|
axisLine={{ stroke: "#E5E7EB" }}
|
||||||
|
tickLine={false}
|
||||||
|
/>
|
||||||
|
<YAxis
|
||||||
|
tick={{ fill: "#6B7280", fontSize: 12 }}
|
||||||
|
axisLine={{ stroke: "#E5E7EB" }}
|
||||||
|
tickLine={false}
|
||||||
|
tickFormatter={(v: number) => formatCurrency(v)}
|
||||||
|
width={80}
|
||||||
|
/>
|
||||||
|
<Tooltip
|
||||||
|
formatter={(v: number) => formatCurrency(v)}
|
||||||
|
contentStyle={{
|
||||||
|
borderRadius: 8,
|
||||||
|
border: "1px solid #E5E7EB",
|
||||||
|
fontSize: 12,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<Legend
|
||||||
|
onClick={handleLegendClick}
|
||||||
|
wrapperStyle={{ cursor: "pointer", fontSize: 12 }}
|
||||||
|
/>
|
||||||
|
{series.lines.map((line, idx) => {
|
||||||
|
const hidden = isolated !== null && isolated !== line.key;
|
||||||
|
return (
|
||||||
|
<Line
|
||||||
|
key={line.key}
|
||||||
|
type="monotone"
|
||||||
|
dataKey={line.key}
|
||||||
|
stroke={colorFor(line.key, idx)}
|
||||||
|
strokeWidth={line.key === "Total" ? 3 : 2}
|
||||||
|
dot={{ r: 3 }}
|
||||||
|
activeDot={{ r: 5 }}
|
||||||
|
hide={hidden}
|
||||||
|
isAnimationActive={false}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</LineChart>
|
||||||
|
</ResponsiveContainer>
|
||||||
|
</div>
|
||||||
|
<p className="mt-3 text-xs text-[#6B7280]">
|
||||||
|
Tip: click a name in the legend to isolate that line; click it again to
|
||||||
|
show all.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
export default function Card({
|
||||||
|
title,
|
||||||
|
children,
|
||||||
|
className = "",
|
||||||
|
}: {
|
||||||
|
title?: string;
|
||||||
|
children: React.ReactNode;
|
||||||
|
className?: string;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={`rounded-lg border border-[#E5E7EB] bg-white ${className}`}
|
||||||
|
>
|
||||||
|
{title && (
|
||||||
|
<div className="border-b border-[#E5E7EB] px-5 py-3.5 text-sm font-semibold text-[#111827]">
|
||||||
|
{title}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="p-5">{children}</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
export default function FilterBar({ children }: { children: React.ReactNode }) {
|
||||||
|
return (
|
||||||
|
<div className="mb-6 flex flex-wrap items-end gap-6 rounded-lg border border-[#E5E7EB] bg-white p-4">
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
type Option = { value: string; label: string };
|
||||||
|
|
||||||
|
export default function Select({
|
||||||
|
label,
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
options,
|
||||||
|
placeholder,
|
||||||
|
className = "",
|
||||||
|
}: {
|
||||||
|
label?: string;
|
||||||
|
value: string;
|
||||||
|
onChange: (value: string) => void;
|
||||||
|
options: (Option | string)[];
|
||||||
|
placeholder?: string;
|
||||||
|
className?: string;
|
||||||
|
}) {
|
||||||
|
const normalized: Option[] = options.map((o) =>
|
||||||
|
typeof o === "string" ? { value: o, label: o } : o
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={`flex flex-col gap-1.5 ${className}`}>
|
||||||
|
{label && (
|
||||||
|
<span className="text-xs font-medium text-[#6B7280]">{label}</span>
|
||||||
|
)}
|
||||||
|
<div className="relative">
|
||||||
|
<select
|
||||||
|
value={value}
|
||||||
|
onChange={(e) => onChange(e.target.value)}
|
||||||
|
className="w-full appearance-none rounded-lg border border-[#E5E7EB] bg-white px-3 py-2.5 pr-9 text-sm text-[#111827] outline-none focus:border-[#3B82F6]"
|
||||||
|
>
|
||||||
|
{placeholder && (
|
||||||
|
<option value="" disabled>
|
||||||
|
{placeholder}
|
||||||
|
</option>
|
||||||
|
)}
|
||||||
|
{normalized.map((o) => (
|
||||||
|
<option key={o.value} value={o.value}>
|
||||||
|
{o.label}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
<svg
|
||||||
|
className="pointer-events-none absolute right-3 top-1/2 h-4 w-4 -translate-y-1/2 text-[#6B7280]"
|
||||||
|
viewBox="0 0 20 20"
|
||||||
|
fill="currentColor"
|
||||||
|
aria-hidden="true"
|
||||||
|
>
|
||||||
|
<path
|
||||||
|
fillRule="evenodd"
|
||||||
|
d="M5.23 7.21a.75.75 0 011.06.02L10 10.94l3.71-3.71a.75.75 0 111.06 1.06l-4.24 4.24a.75.75 0 01-1.06 0L5.21 8.29a.75.75 0 01.02-1.08z"
|
||||||
|
clipRule="evenodd"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import fs from "node:fs";
|
||||||
|
import path from "node:path";
|
||||||
|
|
||||||
|
// Role model for the app. Access is either full "admin" or read-only "user".
|
||||||
|
// NOTE: this module uses node:fs and MUST only be imported from Node runtime
|
||||||
|
// code (src/auth.ts / server components / API routes) — never from the edge
|
||||||
|
// middleware, or the edge bundle will fail to compile.
|
||||||
|
export type Role = "admin" | "user";
|
||||||
|
|
||||||
|
// Resolve a user's role from the hand-edited allowlist at config/users.json.
|
||||||
|
// Emails are matched case-insensitively. This is FAIL CLOSED: a missing file,
|
||||||
|
// invalid JSON, or an email that is not listed all return null (access denied).
|
||||||
|
export function lookupRole(email: string | null | undefined): Role | null {
|
||||||
|
if (!email) return null;
|
||||||
|
|
||||||
|
let raw: string;
|
||||||
|
try {
|
||||||
|
raw = fs.readFileSync(
|
||||||
|
path.join(process.cwd(), "config", "users.json"),
|
||||||
|
"utf8"
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
// File missing/unreadable -> deny everyone (local admin is the break-glass).
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
let parsed: unknown;
|
||||||
|
try {
|
||||||
|
parsed = JSON.parse(raw);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (!parsed || typeof parsed !== "object") return null;
|
||||||
|
|
||||||
|
// Lowercase every key so the lookup is case-insensitive.
|
||||||
|
const table: Record<string, Role> = {};
|
||||||
|
for (const [key, value] of Object.entries(parsed as Record<string, unknown>)) {
|
||||||
|
if (value === "admin" || value === "user") {
|
||||||
|
table[key.toLowerCase()] = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return table[email.toLowerCase()] ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Constant-time string comparison to avoid leaking secrets via timing.
|
||||||
|
// Pure JS (no node:crypto) so this stays cheap and dependency-free.
|
||||||
|
export function safeEqual(a: string, b: string): boolean {
|
||||||
|
if (a.length !== b.length) return false;
|
||||||
|
let mismatch = 0;
|
||||||
|
for (let i = 0; i < a.length; i++) {
|
||||||
|
mismatch |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
||||||
|
}
|
||||||
|
return mismatch === 0;
|
||||||
|
}
|
||||||
+144
@@ -0,0 +1,144 @@
|
|||||||
|
import { prisma } from "@/lib/prisma";
|
||||||
|
import { REGIONS, ALL_REGION, isRegion } from "@/lib/regions";
|
||||||
|
|
||||||
|
export type DashboardRow = {
|
||||||
|
name: string;
|
||||||
|
cost: number;
|
||||||
|
trendAiCost: number;
|
||||||
|
trendLifeCost: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Sum of a cost item's sub-costs. Cost is always derived, never stored.
|
||||||
|
function sumSubCosts(subItems: { subCost: number }[]): number {
|
||||||
|
return subItems.reduce((acc, s) => acc + (s.subCost || 0), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build a lookup of region+year -> TrendAI percentage (0 if none).
|
||||||
|
async function loadPctMap(
|
||||||
|
year: number,
|
||||||
|
regions: readonly string[]
|
||||||
|
): Promise<Map<string, number>> {
|
||||||
|
const rows = await prisma.trendAiPercentage.findMany({
|
||||||
|
where: { year, region: { in: [...regions] } },
|
||||||
|
});
|
||||||
|
const map = new Map<string, number>();
|
||||||
|
for (const r of rows) map.set(r.region, r.percentage);
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Dashboard aggregation.
|
||||||
|
* - region = "All": group by item name across the 5 regions for the year.
|
||||||
|
* Cost = Σ_region itemCost
|
||||||
|
* TrendAI = Σ_region (itemCost_region × pct_region/100) (mixed pct safe)
|
||||||
|
* TrendLife = Cost − TrendAI
|
||||||
|
* - single region: Cost/TrendAI/TrendLife for that one region+year.
|
||||||
|
* costItem filter: "All" | "Top 5" | "Top 10" (sorted by Cost desc, sliced).
|
||||||
|
*/
|
||||||
|
export async function getDashboardRows(params: {
|
||||||
|
region: string;
|
||||||
|
costItem: string;
|
||||||
|
year: number;
|
||||||
|
}): Promise<DashboardRow[]> {
|
||||||
|
const { region, costItem, year } = params;
|
||||||
|
|
||||||
|
const regions = region === ALL_REGION ? REGIONS : isRegion(region) ? [region] : [];
|
||||||
|
if (regions.length === 0) return [];
|
||||||
|
|
||||||
|
const pctMap = await loadPctMap(year, regions);
|
||||||
|
|
||||||
|
const items = await prisma.costItem.findMany({
|
||||||
|
where: { year, region: { in: [...regions] } },
|
||||||
|
include: { subItems: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
// Aggregate by item name so "All" merges the same item across regions.
|
||||||
|
const byName = new Map<string, { cost: number; trendAi: number }>();
|
||||||
|
for (const item of items) {
|
||||||
|
const itemCost = sumSubCosts(item.subItems);
|
||||||
|
const pct = pctMap.get(item.region) ?? 0;
|
||||||
|
const trendAi = itemCost * (pct / 100);
|
||||||
|
const cur = byName.get(item.name) ?? { cost: 0, trendAi: 0 };
|
||||||
|
cur.cost += itemCost;
|
||||||
|
cur.trendAi += trendAi;
|
||||||
|
byName.set(item.name, cur);
|
||||||
|
}
|
||||||
|
|
||||||
|
let rows: DashboardRow[] = [...byName.entries()].map(([name, v]) => ({
|
||||||
|
name,
|
||||||
|
cost: v.cost,
|
||||||
|
trendAiCost: v.trendAi,
|
||||||
|
trendLifeCost: v.cost - v.trendAi,
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Default sort: Cost desc, then name for stable ties.
|
||||||
|
rows.sort((a, b) => b.cost - a.cost || a.name.localeCompare(b.name));
|
||||||
|
|
||||||
|
if (costItem === "Top 5") rows = rows.slice(0, 5);
|
||||||
|
else if (costItem === "Top 10") rows = rows.slice(0, 10);
|
||||||
|
|
||||||
|
return rows;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type TrendSeries = {
|
||||||
|
years: number[];
|
||||||
|
// Each line: a label plus a cost value per year (aligned to `years`).
|
||||||
|
lines: { key: string; values: number[] }[];
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Trend chart data across ALL years.
|
||||||
|
* - region = "All": Total line + one line per region (region totals per year).
|
||||||
|
* - single region: Total line + one line per cost-item name (item cost per year).
|
||||||
|
*/
|
||||||
|
export async function getTrendSeries(params: {
|
||||||
|
region: string;
|
||||||
|
}): Promise<TrendSeries> {
|
||||||
|
const { region } = params;
|
||||||
|
const regions = region === ALL_REGION ? REGIONS : isRegion(region) ? [region] : [];
|
||||||
|
|
||||||
|
const items = await prisma.costItem.findMany({
|
||||||
|
where: regions.length ? { region: { in: [...regions] } } : undefined,
|
||||||
|
include: { subItems: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
const yearSet = new Set<number>();
|
||||||
|
for (const it of items) yearSet.add(it.year);
|
||||||
|
const years = [...yearSet].sort((a, b) => a - b);
|
||||||
|
const yearIndex = new Map(years.map((y, i) => [y, i]));
|
||||||
|
|
||||||
|
const total = new Array(years.length).fill(0);
|
||||||
|
// group key -> per-year values
|
||||||
|
const groups = new Map<string, number[]>();
|
||||||
|
|
||||||
|
const groupKeyFor = (item: (typeof items)[number]) =>
|
||||||
|
region === ALL_REGION ? item.region : item.name;
|
||||||
|
|
||||||
|
for (const item of items) {
|
||||||
|
const idx = yearIndex.get(item.year)!;
|
||||||
|
const cost = sumSubCosts(item.subItems);
|
||||||
|
total[idx] += cost;
|
||||||
|
const key = groupKeyFor(item);
|
||||||
|
if (!groups.has(key)) groups.set(key, new Array(years.length).fill(0));
|
||||||
|
groups.get(key)![idx] += cost;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Order group lines: regions in canonical order, or items by total cost desc.
|
||||||
|
let orderedKeys = [...groups.keys()];
|
||||||
|
if (region === ALL_REGION) {
|
||||||
|
orderedKeys = (REGIONS as readonly string[]).filter((r) => groups.has(r));
|
||||||
|
} else {
|
||||||
|
orderedKeys.sort((a, b) => {
|
||||||
|
const sa = groups.get(a)!.reduce((x, y) => x + y, 0);
|
||||||
|
const sb = groups.get(b)!.reduce((x, y) => x + y, 0);
|
||||||
|
return sb - sa || a.localeCompare(b);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const lines = [
|
||||||
|
{ key: "Total", values: total },
|
||||||
|
...orderedKeys.map((key) => ({ key, values: groups.get(key)! })),
|
||||||
|
];
|
||||||
|
|
||||||
|
return { years, lines };
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
// Currency formatting for the dashboard, e.g. 120000 -> "$120,000".
|
||||||
|
const currency = new Intl.NumberFormat("en-US", {
|
||||||
|
style: "currency",
|
||||||
|
currency: "USD",
|
||||||
|
maximumFractionDigits: 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
export function formatCurrency(value: number): string {
|
||||||
|
return currency.format(Math.round(value || 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Percentage, e.g. 20 -> "20%".
|
||||||
|
export function formatPercent(value: number): string {
|
||||||
|
return `${Math.round((value || 0) * 100) / 100}%`;
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import { PrismaClient } from "@prisma/client";
|
||||||
|
|
||||||
|
// Reuse a single PrismaClient across hot-reloads in dev to avoid exhausting
|
||||||
|
// database connections.
|
||||||
|
const globalForPrisma = globalThis as unknown as {
|
||||||
|
prisma: PrismaClient | undefined;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const prisma =
|
||||||
|
globalForPrisma.prisma ??
|
||||||
|
new PrismaClient({
|
||||||
|
log: process.env.NODE_ENV === "development" ? ["error", "warn"] : ["error"],
|
||||||
|
});
|
||||||
|
|
||||||
|
if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
// Canonical region labels (spaces normalized), matching the Figma trend legend.
|
||||||
|
export const REGIONS = ["AMEA IT", "EMEA IT", "NABU IT", "PH IT", "JP IT"] as const;
|
||||||
|
export type Region = (typeof REGIONS)[number];
|
||||||
|
|
||||||
|
export const ALL_REGION = "All";
|
||||||
|
|
||||||
|
// Region filter options: "All" plus the five regions.
|
||||||
|
export const REGION_OPTIONS = [ALL_REGION, ...REGIONS];
|
||||||
|
|
||||||
|
// Cost Item filter options for the Dashboard.
|
||||||
|
export const COST_ITEM_OPTIONS = ["All", "Top 5", "Top 10"] as const;
|
||||||
|
export type CostItemFilter = (typeof COST_ITEM_OPTIONS)[number];
|
||||||
|
|
||||||
|
export function isRegion(value: string): value is Region {
|
||||||
|
return (REGIONS as readonly string[]).includes(value);
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import NextAuth from "next-auth";
|
||||||
|
import { authConfig } from "@/auth.config";
|
||||||
|
|
||||||
|
// Protect the whole app with role-aware auth. Runs in the edge runtime, so it
|
||||||
|
// uses the edge-safe authConfig (no node:fs / providers). The `authorized`
|
||||||
|
// callback there redirects unauthenticated users to /login and blocks normal
|
||||||
|
// users from admin pages / write APIs.
|
||||||
|
export const { auth: middleware } = NextAuth(authConfig);
|
||||||
|
|
||||||
|
export const config = {
|
||||||
|
// Run on everything EXCEPT: the auth endpoints (must stay public so users can
|
||||||
|
// sign in), Next.js internals, and static asset requests (files with a dot).
|
||||||
|
matcher: ["/((?!api/auth|_next/static|_next/image|favicon.ico|.*\\.).*)"],
|
||||||
|
};
|
||||||
Vendored
+22
@@ -0,0 +1,22 @@
|
|||||||
|
import type { DefaultSession } from "next-auth";
|
||||||
|
import type { Role } from "@/lib/authz";
|
||||||
|
|
||||||
|
// Bake our custom `role` onto the Auth.js types so the middleware, callbacks,
|
||||||
|
// and server components can read `session.user.role` / `token.role` type-safely.
|
||||||
|
declare module "next-auth" {
|
||||||
|
interface Session {
|
||||||
|
user: {
|
||||||
|
role?: Role;
|
||||||
|
} & DefaultSession["user"];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface User {
|
||||||
|
role?: Role;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
declare module "next-auth/jwt" {
|
||||||
|
interface JWT {
|
||||||
|
role?: Role;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2020",
|
||||||
|
"lib": ["dom", "dom.iterable", "esnext"],
|
||||||
|
"allowJs": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"strict": true,
|
||||||
|
"noEmit": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"module": "esnext",
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"resolveJsonModule": true,
|
||||||
|
"isolatedModules": true,
|
||||||
|
"jsx": "preserve",
|
||||||
|
"incremental": true,
|
||||||
|
"plugins": [{ "name": "next" }],
|
||||||
|
"paths": {
|
||||||
|
"@/*": ["./src/*"]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
|
||||||
|
"exclude": ["node_modules", "scripts"]
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user