This commit is contained in:
jason
2026-04-20 15:49:01 -05:00
parent 381a31d607
commit b98837a72c
46 changed files with 8883 additions and 37 deletions
+31
View File
@@ -0,0 +1,31 @@
import Link from "next/link";
import { requireAdmin } from "@/lib/auth";
import LogoutButton from "@/components/LogoutButton";
export default async function AdminLayout({ children }: { children: React.ReactNode }) {
const user = await requireAdmin();
return (
<div className="min-h-dvh flex flex-col">
<header className="border-b border-slate-200 bg-white">
<div className="mx-auto max-w-7xl px-4 py-3 flex items-center gap-6">
<Link href="/admin" className="font-semibold tracking-tight">
MRP <span className="text-slate-400 font-normal">· Admin</span>
</Link>
<nav className="flex gap-4 text-sm text-slate-600">
<Link href="/admin" className="hover:text-slate-900">Dashboard</Link>
<Link href="/admin/projects" className="hover:text-slate-900">Projects</Link>
<Link href="/admin/machines" className="hover:text-slate-900">Machines</Link>
<Link href="/admin/operations" className="hover:text-slate-900">Operation templates</Link>
<Link href="/admin/users" className="hover:text-slate-900">Users</Link>
</nav>
<div className="ml-auto flex items-center gap-3 text-sm">
<span className="text-slate-500">{user.name}</span>
<LogoutButton />
</div>
</div>
</header>
<main className="flex-1">{children}</main>
</div>
);
}
+27
View File
@@ -0,0 +1,27 @@
export default function AdminDashboardPage() {
return (
<div className="mx-auto max-w-7xl px-4 py-8">
<h1 className="text-2xl font-semibold">Dashboard</h1>
<p className="text-slate-500 mt-1">
Project planning, machines, operations, and users will appear here as each area is built.
</p>
<div className="mt-8 grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
<Card title="Projects" desc="Plan work: assemblies, parts, and operations." />
<Card title="Machines" desc="Manage shop-floor equipment." />
<Card title="Operation templates" desc="Reusable step recipes." />
<Card title="Fasteners & POs" desc="Aggregate BOM, generate purchase orders." />
<Card title="Users" desc="Admins and operator PIN accounts." />
<Card title="Audit log" desc="Who did what, when." />
</div>
</div>
);
}
function Card({ title, desc }: { title: string; desc: string }) {
return (
<div className="rounded-xl bg-white border border-slate-200 p-5">
<h2 className="font-medium">{title}</h2>
<p className="text-sm text-slate-500 mt-1">{desc}</p>
</div>
);
}
+52
View File
@@ -0,0 +1,52 @@
import { NextResponse, type NextRequest } from "next/server";
import { z } from "zod";
import { prisma } from "@/lib/prisma";
import { verifyPassword } from "@/lib/password";
import { createSession } from "@/lib/session";
import { audit } from "@/lib/audit";
import { clientIp, userAgent } from "@/lib/request";
const Body = z.object({
email: z.string().email(),
password: z.string().min(1),
});
export async function POST(req: NextRequest) {
const parsed = Body.safeParse(await req.json().catch(() => ({})));
if (!parsed.success) {
return NextResponse.json({ error: "Invalid email or password" }, { status: 400 });
}
const { email, password } = parsed.data;
const user = await prisma.user.findUnique({ where: { email } });
const ip = clientIp(req);
const ua = userAgent(req);
if (!user || user.role !== "admin" || !user.active || !user.passwordHash) {
await audit({ action: "login_failed", entity: "User", entityId: user?.id, ipAddress: ip });
return NextResponse.json({ error: "Invalid email or password" }, { status: 401 });
}
const ok = await verifyPassword(password, user.passwordHash);
if (!ok) {
await audit({ action: "login_failed", entity: "User", entityId: user.id, ipAddress: ip });
return NextResponse.json({ error: "Invalid email or password" }, { status: 401 });
}
await createSession({
userId: user.id,
role: "admin",
userAgent: ua,
ipAddress: ip,
});
await prisma.user.update({
where: { id: user.id },
data: { lastLoginAt: new Date(), failedAttempts: 0, lockedUntil: null },
});
await audit({ actorId: user.id, action: "login", entity: "User", entityId: user.id, ipAddress: ip });
return NextResponse.json({ ok: true, redirect: "/admin" });
}
+12
View File
@@ -0,0 +1,12 @@
import { NextResponse } from "next/server";
import { destroyCurrentSession, getSessionUser } from "@/lib/session";
import { audit } from "@/lib/audit";
export async function POST() {
const user = await getSessionUser();
await destroyCurrentSession();
if (user) {
await audit({ actorId: user.id, action: "logout", entity: "User", entityId: user.id });
}
return NextResponse.json({ ok: true });
}
+80
View File
@@ -0,0 +1,80 @@
import { NextResponse, type NextRequest } from "next/server";
import { z } from "zod";
import { prisma } from "@/lib/prisma";
import { verifyPin, isValidPin } from "@/lib/password";
import { createSession } from "@/lib/session";
import { env } from "@/lib/env";
import { audit } from "@/lib/audit";
import { clientIp, userAgent } from "@/lib/request";
const Body = z.object({
operatorId: z.string().min(1),
pin: z.string().regex(/^\d{4}$/, "PIN must be 4 digits"),
});
export async function POST(req: NextRequest) {
const parsed = Body.safeParse(await req.json().catch(() => ({})));
if (!parsed.success) {
return NextResponse.json({ error: "Invalid PIN" }, { status: 400 });
}
const { operatorId, pin } = parsed.data;
if (!isValidPin(pin)) {
return NextResponse.json({ error: "Invalid PIN" }, { status: 400 });
}
const ip = clientIp(req);
const ua = userAgent(req);
const user = await prisma.user.findUnique({ where: { id: operatorId } });
if (!user || user.role !== "operator" || !user.active || !user.pinHash) {
await audit({ action: "login_failed", entity: "User", entityId: user?.id, ipAddress: ip });
return NextResponse.json({ error: "Invalid PIN" }, { status: 401 });
}
if (user.lockedUntil && user.lockedUntil.getTime() > Date.now()) {
const mins = Math.ceil((user.lockedUntil.getTime() - Date.now()) / 60000);
return NextResponse.json(
{ error: `Account locked. Try again in ${mins} minute${mins === 1 ? "" : "s"}.` },
{ status: 423 },
);
}
const ok = await verifyPin(pin, user.pinHash);
if (!ok) {
const attempts = user.failedAttempts + 1;
const shouldLock = attempts >= env.PIN_MAX_ATTEMPTS;
await prisma.user.update({
where: { id: user.id },
data: {
failedAttempts: shouldLock ? 0 : attempts,
lockedUntil: shouldLock ? new Date(Date.now() + env.PIN_LOCKOUT_MINUTES * 60_000) : null,
},
});
await audit({ action: "login_failed", entity: "User", entityId: user.id, ipAddress: ip });
return NextResponse.json(
{
error: shouldLock
? `Too many attempts. Locked for ${env.PIN_LOCKOUT_MINUTES} minutes.`
: "Invalid PIN",
},
{ status: shouldLock ? 423 : 401 },
);
}
await createSession({
userId: user.id,
role: "operator",
userAgent: ua,
ipAddress: ip,
});
await prisma.user.update({
where: { id: user.id },
data: { lastLoginAt: new Date(), failedAttempts: 0, lockedUntil: null },
});
await audit({ actorId: user.id, action: "login", entity: "User", entityId: user.id, ipAddress: ip });
return NextResponse.json({ ok: true, redirect: "/op" });
}
+14
View File
@@ -0,0 +1,14 @@
import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
export async function GET() {
try {
await prisma.$queryRaw`SELECT 1`;
return NextResponse.json({ ok: true, ts: new Date().toISOString() });
} catch (err) {
return NextResponse.json(
{ ok: false, error: err instanceof Error ? err.message : "unknown" },
{ status: 503 },
);
}
}
+13
View File
@@ -0,0 +1,13 @@
import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
// Public-by-design: returns the list of active operators so the login tile
// grid can render. Contains no secrets (no email, no hashes).
export async function GET() {
const operators = await prisma.user.findMany({
where: { role: "operator", active: true },
select: { id: true, name: true },
orderBy: { name: "asc" },
});
return NextResponse.json({ operators });
}
+14
View File
@@ -0,0 +1,14 @@
@import "tailwindcss";
:root {
color-scheme: light;
}
html,
body {
height: 100%;
}
body {
@apply bg-slate-50 text-slate-900 antialiased;
}
+21
View File
@@ -0,0 +1,21 @@
import type { Metadata, Viewport } from "next";
import "./globals.css";
export const metadata: Metadata = {
title: "MRP",
description: "QR-code driven manufacturing resource planning.",
};
export const viewport: Viewport = {
width: "device-width",
initialScale: 1,
themeColor: "#0f172a",
};
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>{children}</body>
</html>
);
}
+95
View File
@@ -0,0 +1,95 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
export default function AdminLoginPage() {
const router = useRouter();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
async function onSubmit(e: React.FormEvent) {
e.preventDefault();
setError(null);
setBusy(true);
try {
const res = await fetch("/api/auth/admin/login", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ email, password }),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
setError(data.error ?? "Sign-in failed");
return;
}
router.push(data.redirect ?? "/admin");
router.refresh();
} catch {
setError("Network error");
} finally {
setBusy(false);
}
}
return (
<main className="min-h-dvh flex items-center justify-center p-6 bg-slate-50">
<form
onSubmit={onSubmit}
className="w-full max-w-sm space-y-5 bg-white rounded-2xl border border-slate-200 p-6 shadow-sm"
>
<div>
<h1 className="text-2xl font-semibold">Admin sign-in</h1>
<p className="text-slate-500 text-sm mt-1">Use your email and password.</p>
</div>
<label className="block">
<span className="block text-sm font-medium text-slate-700 mb-1">Email</span>
<input
type="email"
autoComplete="email"
required
value={email}
onChange={(e) => setEmail(e.target.value)}
className="w-full rounded-lg border border-slate-300 px-3 py-2 text-base outline-none focus:border-slate-900 focus:ring-2 focus:ring-slate-200"
/>
</label>
<label className="block">
<span className="block text-sm font-medium text-slate-700 mb-1">Password</span>
<input
type="password"
autoComplete="current-password"
required
value={password}
onChange={(e) => setPassword(e.target.value)}
className="w-full rounded-lg border border-slate-300 px-3 py-2 text-base outline-none focus:border-slate-900 focus:ring-2 focus:ring-slate-200"
/>
</label>
{error && (
<p className="text-sm text-red-600 bg-red-50 border border-red-200 rounded-md px-3 py-2">
{error}
</p>
)}
<button
type="submit"
disabled={busy}
className="w-full rounded-lg bg-slate-900 text-white py-2.5 font-medium disabled:opacity-60 hover:bg-slate-800 transition"
>
{busy ? "Signing in…" : "Sign in"}
</button>
<div className="text-center">
<Link href="/login" className="text-sm text-slate-500 hover:text-slate-900">
Back
</Link>
</div>
</form>
</main>
);
}
+174
View File
@@ -0,0 +1,174 @@
"use client";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
interface Operator {
id: string;
name: string;
}
export default function OperatorLoginPage() {
const router = useRouter();
const [operators, setOperators] = useState<Operator[] | null>(null);
const [selected, setSelected] = useState<Operator | null>(null);
const [pin, setPin] = useState("");
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
useEffect(() => {
fetch("/api/operators")
.then((r) => r.json())
.then((d) => setOperators(d.operators ?? []))
.catch(() => setOperators([]));
}, []);
function pressKey(k: string) {
setError(null);
if (k === "back") {
setPin((p) => p.slice(0, -1));
return;
}
if (k === "clear") {
setPin("");
return;
}
setPin((p) => (p.length >= 4 ? p : p + k));
}
async function submit() {
if (!selected || pin.length !== 4) return;
setBusy(true);
setError(null);
try {
const res = await fetch("/api/auth/operator/login", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ operatorId: selected.id, pin }),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
setError(data.error ?? "Sign-in failed");
setPin("");
return;
}
router.push(data.redirect ?? "/op");
router.refresh();
} catch {
setError("Network error");
} finally {
setBusy(false);
}
}
useEffect(() => {
if (pin.length === 4 && !busy) {
void submit();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [pin]);
if (operators === null) {
return (
<main className="min-h-dvh flex items-center justify-center p-6 bg-slate-50">
<p className="text-slate-500">Loading</p>
</main>
);
}
if (!selected) {
return (
<main className="min-h-dvh p-6 bg-slate-50">
<div className="mx-auto max-w-2xl">
<div className="text-center mb-6">
<h1 className="text-2xl font-semibold">Who are you?</h1>
<p className="text-slate-500 mt-1">Tap your name to sign in.</p>
</div>
{operators.length === 0 ? (
<div className="rounded-xl bg-white border border-slate-200 p-6 text-center">
<p className="text-slate-700">No operators exist yet.</p>
<p className="text-slate-500 text-sm mt-1">Ask an admin to create your account.</p>
</div>
) : (
<div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
{operators.map((op) => (
<button
key={op.id}
onClick={() => setSelected(op)}
className="rounded-xl bg-white border border-slate-200 px-4 py-5 text-lg font-medium hover:border-slate-900 hover:shadow-sm transition"
>
{op.name}
</button>
))}
</div>
)}
<div className="text-center mt-8">
<Link href="/login" className="text-sm text-slate-500 hover:text-slate-900">
Back
</Link>
</div>
</div>
</main>
);
}
const keys = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "clear", "0", "back"];
return (
<main className="min-h-dvh p-6 bg-slate-50">
<div className="mx-auto max-w-sm">
<div className="text-center mb-4">
<button
onClick={() => {
setSelected(null);
setPin("");
setError(null);
}}
className="text-sm text-slate-500 hover:text-slate-900"
>
Not {selected.name}?
</button>
</div>
<div className="rounded-2xl bg-white border border-slate-200 p-6 shadow-sm">
<h1 className="text-xl font-semibold text-center">Hi, {selected.name}</h1>
<p className="text-slate-500 text-sm text-center mt-1">Enter your 4-digit PIN</p>
<div className="flex justify-center gap-3 my-6">
{[0, 1, 2, 3].map((i) => (
<div
key={i}
className={`w-4 h-4 rounded-full ${pin.length > i ? "bg-slate-900" : "bg-slate-200"}`}
/>
))}
</div>
{error && (
<p className="text-sm text-red-600 bg-red-50 border border-red-200 rounded-md px-3 py-2 mb-4 text-center">
{error}
</p>
)}
<div className="grid grid-cols-3 gap-2">
{keys.map((k) => {
const label = k === "back" ? "⌫" : k === "clear" ? "C" : k;
return (
<button
key={k}
onClick={() => pressKey(k)}
disabled={busy}
className="h-14 rounded-lg bg-slate-100 hover:bg-slate-200 active:bg-slate-300 text-xl font-medium transition disabled:opacity-60"
>
{label}
</button>
);
})}
</div>
</div>
</div>
</main>
);
}
+28
View File
@@ -0,0 +1,28 @@
import Link from "next/link";
export default function LoginChoicePage() {
return (
<main className="min-h-dvh flex items-center justify-center p-6 bg-slate-50">
<div className="w-full max-w-md space-y-6">
<div className="text-center">
<h1 className="text-3xl font-semibold tracking-tight">MRP</h1>
<p className="text-slate-500 mt-1">Sign in to continue</p>
</div>
<div className="grid gap-3">
<Link
href="/login/operator"
className="block rounded-xl bg-slate-900 text-white px-5 py-4 text-center font-medium shadow-sm hover:bg-slate-800 transition"
>
I&apos;m an operator
</Link>
<Link
href="/login/admin"
className="block rounded-xl bg-white border border-slate-200 px-5 py-4 text-center font-medium text-slate-900 hover:bg-slate-100 transition"
>
Admin sign-in
</Link>
</div>
</div>
</main>
);
}
+22
View File
@@ -0,0 +1,22 @@
import Link from "next/link";
import { requireOperator } from "@/lib/auth";
import LogoutButton from "@/components/LogoutButton";
export default async function OperatorLayout({ children }: { children: React.ReactNode }) {
const user = await requireOperator();
return (
<div className="min-h-dvh flex flex-col">
<header className="border-b border-slate-200 bg-white">
<div className="mx-auto max-w-3xl px-4 py-3 flex items-center gap-3">
<Link href="/op" className="font-semibold tracking-tight">
MRP
</Link>
<span className="ml-auto text-sm text-slate-500">{user.name}</span>
<LogoutButton />
</div>
</header>
<main className="flex-1">{children}</main>
</div>
);
}
+16
View File
@@ -0,0 +1,16 @@
export default function OperatorHomePage() {
return (
<div className="mx-auto max-w-3xl px-4 py-10 text-center space-y-6">
<div>
<h1 className="text-2xl font-semibold">Scan a traveler QR code</h1>
<p className="text-slate-500 mt-2">
Use your phone camera to scan the QR on a step card. It will open the step here so you can
start, log time, and close out.
</p>
</div>
<div className="rounded-xl bg-white border border-slate-200 p-6 text-slate-500 text-sm">
<p>Your active steps will appear here once you claim them.</p>
</div>
</div>
);
}
+8
View File
@@ -0,0 +1,8 @@
import { redirect } from "next/navigation";
import { getCurrentUser } from "@/lib/auth";
export default async function IndexPage() {
const user = await getCurrentUser();
if (!user) redirect("/login");
redirect(user.role === "admin" ? "/admin" : "/op");
}