This commit is contained in:
Tom Chien (IQ-AS)
2026-09-08 17:46:28 +08:00
commit e25c995560
55 changed files with 6928 additions and 0 deletions
+3
View File
@@ -0,0 +1,3 @@
import { handlers } from "@/auth";
export const { GET, POST } = handlers;
+32
View File
@@ -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 });
}
+64
View File
@@ -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 });
}
+45
View File
@@ -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,
});
}
+18
View File
@@ -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 });
}
+36
View File
@@ -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 });
}
+25
View File
@@ -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 });
}
+50
View File
@@ -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 });
}
+10
View File
@@ -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);
}
+24
View File
@@ -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,
});
}
+39
View File
@@ -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 });
}
+300
View File
@@ -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>{" "}
&quot;{deleteName.trim()}&quot; 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>
);
}
+319
View File
@@ -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&apos;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>
);
}
+26
View File
@@ -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;
}
+44
View File
@@ -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>
);
}
+112
View File
@@ -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>
);
}
+151
View File
@@ -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>
);
}
+75
View File
@@ -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>
);
}
+207
View File
@@ -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 &quot;{deleteYear.trim()}&quot; 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>
);
}
+62
View File
@@ -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
View File
@@ -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;
},
},
});
+57
View File
@@ -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>
);
}
+44
View File
@@ -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>
);
}
+116
View File
@@ -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>
);
}
+22
View File
@@ -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>
);
}
+7
View File
@@ -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>
);
}
+61
View File
@@ -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>
);
}
+55
View File
@@ -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
View File
@@ -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 };
}
+15
View File
@@ -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}%`;
}
+15
View File
@@ -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;
+16
View File
@@ -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);
}
+14
View File
@@ -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|.*\\.).*)"],
};
+22
View File
@@ -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;
}
}