init
This commit is contained in:
@@ -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);
|
||||
}
|
||||
Reference in New Issue
Block a user