phase 2 and 3

This commit is contained in:
jason
2026-04-21 08:56:51 -05:00
parent b98837a72c
commit d79aaf6ef8
42 changed files with 4962 additions and 19 deletions
+54
View File
@@ -0,0 +1,54 @@
import { type NextRequest } from "next/server";
import { prisma } from "@/lib/prisma";
import { ok, errorResponse, requireRole, parseJson, ApiError } from "@/lib/api";
import { CreatePartSchema } from "@/lib/schemas";
import { audit } from "@/lib/audit";
import { clientIp } from "@/lib/request";
export async function GET(_req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
try {
await requireRole("admin");
const { id } = await ctx.params;
const parts = await prisma.part.findMany({
where: { assemblyId: id },
orderBy: { code: "asc" },
include: { _count: { select: { operations: true } } },
});
return ok({ parts });
} catch (err) {
return errorResponse(err);
}
}
export async function POST(req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
try {
const actor = await requireRole("admin");
const { id } = await ctx.params;
const body = await parseJson(req, CreatePartSchema);
const assembly = await prisma.assembly.findUnique({ where: { id } });
if (!assembly) throw new ApiError(404, "not_found", "Assembly not found");
const created = await prisma.part.create({
data: {
assemblyId: id,
code: body.code,
name: body.name,
material: body.material ?? null,
qty: body.qty,
notes: body.notes ?? null,
},
});
await audit({
actorId: actor.id,
action: "create",
entity: "Part",
entityId: created.id,
after: created,
ipAddress: clientIp(req),
});
return ok({ part: created }, { status: 201 });
} catch (err) {
return errorResponse(err);
}
}
+78
View File
@@ -0,0 +1,78 @@
import { type NextRequest } from "next/server";
import { prisma } from "@/lib/prisma";
import { ok, errorResponse, requireRole, parseJson, ApiError } from "@/lib/api";
import { UpdateAssemblySchema } from "@/lib/schemas";
import { audit } from "@/lib/audit";
import { clientIp } from "@/lib/request";
export async function GET(_req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
try {
await requireRole("admin");
const { id } = await ctx.params;
const assembly = await prisma.assembly.findUnique({
where: { id },
include: {
project: { select: { id: true, code: true, name: true } },
parts: { orderBy: { code: "asc" } },
},
});
if (!assembly) throw new ApiError(404, "not_found", "Assembly not found");
return ok({ assembly });
} catch (err) {
return errorResponse(err);
}
}
export async function PATCH(req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
try {
const actor = await requireRole("admin");
const { id } = await ctx.params;
const body = await parseJson(req, UpdateAssemblySchema);
const before = await prisma.assembly.findUnique({ where: { id } });
if (!before) throw new ApiError(404, "not_found", "Assembly not found");
const updated = await prisma.assembly.update({
where: { id },
data: {
...(body.code !== undefined ? { code: body.code } : {}),
...(body.name !== undefined ? { name: body.name } : {}),
...(body.qty !== undefined ? { qty: body.qty } : {}),
...(body.notes !== undefined ? { notes: body.notes } : {}),
},
});
await audit({
actorId: actor.id,
action: "update",
entity: "Assembly",
entityId: id,
before,
after: updated,
ipAddress: clientIp(req),
});
return ok({ assembly: updated });
} catch (err) {
return errorResponse(err);
}
}
export async function DELETE(req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
try {
const actor = await requireRole("admin");
const { id } = await ctx.params;
const before = await prisma.assembly.findUnique({ where: { id } });
if (!before) throw new ApiError(404, "not_found", "Assembly not found");
await prisma.assembly.delete({ where: { id } });
await audit({
actorId: actor.id,
action: "delete",
entity: "Assembly",
entityId: id,
before,
ipAddress: clientIp(req),
});
return ok({ ok: true });
} catch (err) {
return errorResponse(err);
}
}
+33
View File
@@ -0,0 +1,33 @@
import { NextResponse, type NextRequest } from "next/server";
import { prisma } from "@/lib/prisma";
import { errorResponse, ApiError } from "@/lib/api";
import { getSessionUser } from "@/lib/session";
import { mimeForKind, readFileBytes, type FileKind } from "@/lib/files";
// Any signed-in user can download; mime/extension derived from the asset.
export async function GET(_req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
try {
const user = await getSessionUser();
if (!user) throw new ApiError(401, "unauthenticated", "Sign in required");
const { id } = await ctx.params;
const file = await prisma.fileAsset.findUnique({ where: { id } });
if (!file) throw new ApiError(404, "not_found", "File not found");
const bytes = await readFileBytes(file.path);
const mime = mimeForKind(file.kind as FileKind, file.mimeType);
const body = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
return new NextResponse(body as ArrayBuffer, {
status: 200,
headers: {
"content-type": mime,
"content-length": String(bytes.byteLength),
"content-disposition": `inline; filename="${encodeURIComponent(file.originalName)}"`,
"cache-control": "private, max-age=3600",
},
});
} catch (err) {
return errorResponse(err);
}
}
+64
View File
@@ -0,0 +1,64 @@
import { type NextRequest } from "next/server";
import { prisma } from "@/lib/prisma";
import { ok, errorResponse, requireRole, ApiError } from "@/lib/api";
import { deleteFileFromDisk } from "@/lib/files";
import { audit } from "@/lib/audit";
import { clientIp } from "@/lib/request";
export async function GET(_req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
try {
await requireRole("admin");
const { id } = await ctx.params;
const file = await prisma.fileAsset.findUnique({ where: { id } });
if (!file) throw new ApiError(404, "not_found", "File not found");
return ok({ file });
} catch (err) {
return errorResponse(err);
}
}
export async function DELETE(req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
try {
const user = await requireRole("admin");
const { id } = await ctx.params;
const file = await prisma.fileAsset.findUnique({
where: { id },
include: {
_count: {
select: { partStep: true, partDrawing: true, partCut: true, poPdfs: true },
},
},
});
if (!file) throw new ApiError(404, "not_found", "File not found");
const refs =
file._count.partStep +
file._count.partDrawing +
file._count.partCut +
file._count.poPdfs;
if (refs > 0) {
throw new ApiError(
409,
"file_in_use",
`File is referenced by ${refs} record(s). Detach it first.`,
);
}
await prisma.fileAsset.delete({ where: { id } });
await deleteFileFromDisk(file.path);
await audit({
actorId: user.id,
action: "delete",
entity: "FileAsset",
entityId: id,
before: { sha256: file.sha256, originalName: file.originalName },
ipAddress: clientIp(req),
});
return ok({ ok: true });
} catch (err) {
return errorResponse(err);
}
}
+53
View File
@@ -0,0 +1,53 @@
import { type NextRequest } from "next/server";
import { prisma } from "@/lib/prisma";
import { ok, errorResponse, requireRole, ApiError } from "@/lib/api";
import { saveUploadedFile } from "@/lib/files";
import { audit } from "@/lib/audit";
import { clientIp } from "@/lib/request";
export async function GET() {
try {
await requireRole("admin");
const files = await prisma.fileAsset.findMany({
orderBy: { uploadedAt: "desc" },
take: 200,
});
return ok({ files });
} catch (err) {
return errorResponse(err);
}
}
export async function POST(req: NextRequest) {
try {
const user = await requireRole("admin");
const form = await req.formData().catch(() => null);
if (!form) throw new ApiError(400, "invalid_form", "Expected multipart/form-data");
const file = form.get("file");
if (!(file instanceof File)) {
throw new ApiError(400, "missing_file", "Missing 'file' field");
}
const saved = await saveUploadedFile(file, user.id);
if (!saved.deduped) {
await audit({
actorId: user.id,
action: "create",
entity: "FileAsset",
entityId: saved.id,
after: { sha256: saved.sha256, kind: saved.kind, originalName: saved.originalName },
ipAddress: clientIp(req),
});
}
return ok({ file: saved }, { status: saved.deduped ? 200 : 201 });
} catch (err) {
if (err instanceof Error && /Empty file|File too large/.test(err.message)) {
return errorResponse(new ApiError(413, "file_rejected", err.message));
}
return errorResponse(err);
}
}
+79
View File
@@ -0,0 +1,79 @@
import { type NextRequest } from "next/server";
import { prisma } from "@/lib/prisma";
import { ok, errorResponse, requireRole, parseJson, ApiError } from "@/lib/api";
import { UpdateMachineSchema } from "@/lib/schemas";
import { audit } from "@/lib/audit";
import { clientIp } from "@/lib/request";
export async function GET(_req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
try {
await requireRole("admin");
const { id } = await ctx.params;
const machine = await prisma.machine.findUnique({ where: { id } });
if (!machine) throw new ApiError(404, "not_found", "Machine not found");
return ok({ machine });
} catch (err) {
return errorResponse(err);
}
}
export async function PATCH(req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
try {
const actor = await requireRole("admin");
const { id } = await ctx.params;
const body = await parseJson(req, UpdateMachineSchema);
const before = await prisma.machine.findUnique({ where: { id } });
if (!before) throw new ApiError(404, "not_found", "Machine not found");
const updated = await prisma.machine.update({
where: { id },
data: {
...(body.name !== undefined ? { name: body.name } : {}),
...(body.kind !== undefined ? { kind: body.kind } : {}),
...(body.location !== undefined ? { location: body.location } : {}),
...(body.notes !== undefined ? { notes: body.notes } : {}),
...(body.active !== undefined ? { active: body.active } : {}),
},
});
await audit({
actorId: actor.id,
action: "update",
entity: "Machine",
entityId: id,
before,
after: updated,
ipAddress: clientIp(req),
});
return ok({ machine: updated });
} catch (err) {
return errorResponse(err);
}
}
export async function DELETE(req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
try {
const actor = await requireRole("admin");
const { id } = await ctx.params;
const before = await prisma.machine.findUnique({ where: { id } });
if (!before) throw new ApiError(404, "not_found", "Machine not found");
// soft-delete to preserve references on historical operations
const updated = await prisma.machine.update({
where: { id },
data: { active: false },
});
await audit({
actorId: actor.id,
action: "deactivate",
entity: "Machine",
entityId: id,
before,
after: updated,
ipAddress: clientIp(req),
});
return ok({ ok: true });
} catch (err) {
return errorResponse(err);
}
}
+46
View File
@@ -0,0 +1,46 @@
import { type NextRequest } from "next/server";
import { prisma } from "@/lib/prisma";
import { ok, errorResponse, requireRole, parseJson } from "@/lib/api";
import { CreateMachineSchema } from "@/lib/schemas";
import { audit } from "@/lib/audit";
import { clientIp } from "@/lib/request";
export async function GET(req: NextRequest) {
try {
await requireRole("admin");
const includeInactive = req.nextUrl.searchParams.get("includeInactive") === "1";
const machines = await prisma.machine.findMany({
where: includeInactive ? undefined : { active: true },
orderBy: [{ active: "desc" }, { name: "asc" }],
});
return ok({ machines });
} catch (err) {
return errorResponse(err);
}
}
export async function POST(req: NextRequest) {
try {
const actor = await requireRole("admin");
const body = await parseJson(req, CreateMachineSchema);
const created = await prisma.machine.create({
data: {
name: body.name,
kind: body.kind,
location: body.location ?? null,
notes: body.notes ?? null,
},
});
await audit({
actorId: actor.id,
action: "create",
entity: "Machine",
entityId: created.id,
after: created,
ipAddress: clientIp(req),
});
return ok({ machine: created }, { status: 201 });
} catch (err) {
return errorResponse(err);
}
}
@@ -0,0 +1,84 @@
import { type NextRequest } from "next/server";
import { prisma } from "@/lib/prisma";
import { ok, errorResponse, requireRole, parseJson, ApiError } from "@/lib/api";
import { UpdateTemplateSchema } from "@/lib/schemas";
import { audit } from "@/lib/audit";
import { clientIp } from "@/lib/request";
export async function GET(_req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
try {
await requireRole("admin");
const { id } = await ctx.params;
const template = await prisma.operationTemplate.findUnique({
where: { id },
include: { machine: true },
});
if (!template) throw new ApiError(404, "not_found", "Template not found");
return ok({ template });
} catch (err) {
return errorResponse(err);
}
}
export async function PATCH(req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
try {
const actor = await requireRole("admin");
const { id } = await ctx.params;
const body = await parseJson(req, UpdateTemplateSchema);
const before = await prisma.operationTemplate.findUnique({ where: { id } });
if (!before) throw new ApiError(404, "not_found", "Template not found");
const updated = await prisma.operationTemplate.update({
where: { id },
data: {
...(body.name !== undefined ? { name: body.name } : {}),
...(body.machineId !== undefined ? { machineId: body.machineId } : {}),
...(body.defaultSettings !== undefined ? { defaultSettings: body.defaultSettings } : {}),
...(body.defaultInstructions !== undefined
? { defaultInstructions: body.defaultInstructions }
: {}),
...(body.qcRequired !== undefined ? { qcRequired: body.qcRequired } : {}),
...(body.active !== undefined ? { active: body.active } : {}),
},
});
await audit({
actorId: actor.id,
action: "update",
entity: "OperationTemplate",
entityId: id,
before,
after: updated,
ipAddress: clientIp(req),
});
return ok({ template: updated });
} catch (err) {
return errorResponse(err);
}
}
export async function DELETE(req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
try {
const actor = await requireRole("admin");
const { id } = await ctx.params;
const before = await prisma.operationTemplate.findUnique({ where: { id } });
if (!before) throw new ApiError(404, "not_found", "Template not found");
const updated = await prisma.operationTemplate.update({
where: { id },
data: { active: false },
});
await audit({
actorId: actor.id,
action: "deactivate",
entity: "OperationTemplate",
entityId: id,
before,
after: updated,
ipAddress: clientIp(req),
});
return ok({ ok: true });
} catch (err) {
return errorResponse(err);
}
}
+48
View File
@@ -0,0 +1,48 @@
import { type NextRequest } from "next/server";
import { prisma } from "@/lib/prisma";
import { ok, errorResponse, requireRole, parseJson } from "@/lib/api";
import { CreateTemplateSchema } from "@/lib/schemas";
import { audit } from "@/lib/audit";
import { clientIp } from "@/lib/request";
export async function GET(req: NextRequest) {
try {
await requireRole("admin");
const includeInactive = req.nextUrl.searchParams.get("includeInactive") === "1";
const templates = await prisma.operationTemplate.findMany({
where: includeInactive ? undefined : { active: true },
include: { machine: { select: { id: true, name: true, kind: true, active: true } } },
orderBy: [{ active: "desc" }, { name: "asc" }],
});
return ok({ templates });
} catch (err) {
return errorResponse(err);
}
}
export async function POST(req: NextRequest) {
try {
const actor = await requireRole("admin");
const body = await parseJson(req, CreateTemplateSchema);
const created = await prisma.operationTemplate.create({
data: {
name: body.name,
machineId: body.machineId ?? null,
defaultSettings: body.defaultSettings ?? null,
defaultInstructions: body.defaultInstructions ?? null,
qcRequired: body.qcRequired,
},
});
await audit({
actorId: actor.id,
action: "create",
entity: "OperationTemplate",
entityId: created.id,
after: created,
ipAddress: clientIp(req),
});
return ok({ template: created }, { status: 201 });
} catch (err) {
return errorResponse(err);
}
}
+126
View File
@@ -0,0 +1,126 @@
import { type NextRequest } from "next/server";
import { prisma } from "@/lib/prisma";
import { ok, errorResponse, requireRole, parseJson, ApiError } from "@/lib/api";
import { UpdateOperationSchema } from "@/lib/schemas";
import { audit } from "@/lib/audit";
import { clientIp } from "@/lib/request";
export async function GET(_req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
try {
await requireRole("admin");
const { id } = await ctx.params;
const operation = await prisma.operation.findUnique({
where: { id },
include: {
machine: { select: { id: true, name: true } },
template: { select: { id: true, name: true } },
claimedBy: { select: { id: true, name: true } },
part: {
select: {
id: true,
code: true,
name: true,
assembly: {
select: {
id: true,
code: true,
project: { select: { id: true, code: true, name: true } },
},
},
},
},
},
});
if (!operation) throw new ApiError(404, "not_found", "Operation not found");
return ok({ operation });
} catch (err) {
return errorResponse(err);
}
}
export async function PATCH(req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
try {
const actor = await requireRole("admin");
const { id } = await ctx.params;
const body = await parseJson(req, UpdateOperationSchema);
const before = await prisma.operation.findUnique({ where: { id } });
if (!before) throw new ApiError(404, "not_found", "Operation not found");
// Refuse to mutate a claimed / in-progress op's sequence — it would scramble
// the QR card the operator is currently holding. Content edits are allowed.
if (body.sequence !== undefined && body.sequence !== before.sequence) {
if (before.status !== "pending") {
throw new ApiError(
409,
"op_not_pending",
"Cannot resequence an operation that is already in progress or completed",
);
}
const conflict = await prisma.operation.findUnique({
where: { partId_sequence: { partId: before.partId, sequence: body.sequence } },
select: { id: true },
});
if (conflict && conflict.id !== id)
throw new ApiError(409, "sequence_taken", `Sequence ${body.sequence} already in use`);
}
const updated = await prisma.operation.update({
where: { id },
data: {
...(body.templateId !== undefined ? { templateId: body.templateId } : {}),
...(body.name !== undefined ? { name: body.name } : {}),
...(body.machineId !== undefined ? { machineId: body.machineId } : {}),
...(body.settings !== undefined ? { settings: body.settings } : {}),
...(body.materialNotes !== undefined ? { materialNotes: body.materialNotes } : {}),
...(body.instructions !== undefined ? { instructions: body.instructions } : {}),
...(body.qcRequired !== undefined ? { qcRequired: body.qcRequired } : {}),
...(body.plannedMinutes !== undefined ? { plannedMinutes: body.plannedMinutes } : {}),
...(body.plannedUnits !== undefined ? { plannedUnits: body.plannedUnits } : {}),
...(body.sequence !== undefined ? { sequence: body.sequence } : {}),
...(body.status !== undefined ? { status: body.status } : {}),
},
});
await audit({
actorId: actor.id,
action: "update",
entity: "Operation",
entityId: id,
before,
after: updated,
ipAddress: clientIp(req),
});
return ok({ operation: updated });
} catch (err) {
return errorResponse(err);
}
}
export async function DELETE(req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
try {
const actor = await requireRole("admin");
const { id } = await ctx.params;
const before = await prisma.operation.findUnique({ where: { id } });
if (!before) throw new ApiError(404, "not_found", "Operation not found");
if (before.status === "in_progress") {
throw new ApiError(
409,
"op_in_progress",
"Release the claim before deleting an in-progress operation",
);
}
await prisma.operation.delete({ where: { id } });
await audit({
actorId: actor.id,
action: "delete",
entity: "Operation",
entityId: id,
before,
ipAddress: clientIp(req),
});
return ok({ ok: true });
} catch (err) {
return errorResponse(err);
}
}
@@ -0,0 +1,87 @@
import { type NextRequest } from "next/server";
import { prisma } from "@/lib/prisma";
import { ok, errorResponse, requireRole, parseJson, ApiError } from "@/lib/api";
import { ReorderOperationsSchema } from "@/lib/schemas";
import { audit } from "@/lib/audit";
import { clientIp } from "@/lib/request";
/**
* Resequence the operations on a part. Body: { order: [opId, opId, ...] }
* The list must contain every operation currently on the part, in the
* desired top-to-bottom order. Uses a two-phase update to stay inside the
* (partId, sequence) unique constraint.
*/
export async function POST(req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
try {
const actor = await requireRole("admin");
const { id: partId } = await ctx.params;
const { order } = await parseJson(req, ReorderOperationsSchema);
const existing = await prisma.operation.findMany({
where: { partId },
select: { id: true, sequence: true, status: true },
orderBy: { sequence: "asc" },
});
if (existing.length === 0) throw new ApiError(404, "not_found", "No operations on this part");
if (order.length !== existing.length) {
throw new ApiError(
400,
"incomplete_order",
"Order must list every operation on this part exactly once",
);
}
const ids = new Set(existing.map((o) => o.id));
const seen = new Set<string>();
for (const id of order) {
if (!ids.has(id)) throw new ApiError(400, "unknown_op", `Operation ${id} is not on this part`);
if (seen.has(id)) throw new ApiError(400, "duplicate_op", `Operation ${id} listed twice`);
seen.add(id);
}
// Refuse if any non-pending op would land at a different sequence number.
const byId = new Map(existing.map((o) => [o.id, o]));
for (let i = 0; i < order.length; i++) {
const target = i + 1;
const op = byId.get(order[i])!;
if (op.sequence !== target && op.status !== "pending") {
throw new ApiError(
409,
"op_not_pending",
`Cannot move operation ${op.id} — it is already ${op.status}`,
);
}
}
await prisma.$transaction(async (tx) => {
// Phase 1: park every row at a negative sequence to clear the unique slot.
for (let i = 0; i < order.length; i++) {
await tx.operation.update({
where: { id: order[i] },
data: { sequence: -(i + 1) },
});
}
// Phase 2: write the final sequence values.
for (let i = 0; i < order.length; i++) {
await tx.operation.update({
where: { id: order[i] },
data: { sequence: i + 1 },
});
}
});
await audit({
actorId: actor.id,
action: "reorder",
entity: "Part",
entityId: partId,
before: existing,
after: order.map((id, i) => ({ id, sequence: i + 1 })),
ipAddress: clientIp(req),
});
return ok({ ok: true });
} catch (err) {
return errorResponse(err);
}
}
+133
View File
@@ -0,0 +1,133 @@
import { type NextRequest } from "next/server";
import { prisma } from "@/lib/prisma";
import { ok, errorResponse, requireRole, parseJson, ApiError } from "@/lib/api";
import { CreateOperationSchema } from "@/lib/schemas";
import { audit } from "@/lib/audit";
import { clientIp } from "@/lib/request";
import { generateQrToken } from "@/lib/qr";
export async function GET(_req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
try {
await requireRole("admin");
const { id } = await ctx.params;
const operations = await prisma.operation.findMany({
where: { partId: id },
orderBy: { sequence: "asc" },
include: {
machine: { select: { id: true, name: true } },
template: { select: { id: true, name: true } },
},
});
return ok({ operations });
} catch (err) {
return errorResponse(err);
}
}
export async function POST(req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
try {
const actor = await requireRole("admin");
const { id } = await ctx.params;
const body = await parseJson(req, CreateOperationSchema);
const part = await prisma.part.findUnique({ where: { id } });
if (!part) throw new ApiError(404, "not_found", "Part not found");
// If a template is referenced, fetch it so we can inherit unspecified defaults.
let template: {
id: string;
machineId: string | null;
defaultSettings: string | null;
defaultInstructions: string | null;
qcRequired: boolean;
active: boolean;
} | null = null;
if (body.templateId) {
template = await prisma.operationTemplate.findUnique({
where: { id: body.templateId },
select: {
id: true,
machineId: true,
defaultSettings: true,
defaultInstructions: true,
qcRequired: true,
active: true,
},
});
if (!template || !template.active)
throw new ApiError(400, "invalid_template", "Operation template not available");
}
// Resolve sequence: explicit value wins, else append to end.
let sequence = body.sequence;
if (!sequence) {
const max = await prisma.operation.aggregate({
where: { partId: id },
_max: { sequence: true },
});
sequence = (max._max.sequence ?? 0) + 1;
} else {
const conflict = await prisma.operation.findUnique({
where: { partId_sequence: { partId: id, sequence } },
select: { id: true },
});
if (conflict)
throw new ApiError(409, "sequence_taken", `Sequence ${sequence} already in use on this part`);
}
// Derive effective values, falling back to the template where the caller left fields blank.
const effectiveMachineId =
body.machineId !== undefined ? body.machineId : (template?.machineId ?? null);
const effectiveSettings =
body.settings !== undefined && body.settings !== null
? body.settings
: (template?.defaultSettings ?? null);
const effectiveInstructions =
body.instructions !== undefined && body.instructions !== null
? body.instructions
: (template?.defaultInstructions ?? null);
const effectiveQcRequired = body.qcRequired || template?.qcRequired || false;
// Generate a unique qrToken. Collisions at 192 bits are vanishingly rare; retry anyway.
let qrToken = generateQrToken();
for (let attempt = 0; attempt < 5; attempt++) {
const existing = await prisma.operation.findUnique({
where: { qrToken },
select: { id: true },
});
if (!existing) break;
qrToken = generateQrToken();
if (attempt === 4) throw new ApiError(500, "qr_collision", "Unable to allocate QR token");
}
const created = await prisma.operation.create({
data: {
partId: id,
sequence,
templateId: template?.id ?? null,
name: body.name,
machineId: effectiveMachineId,
settings: effectiveSettings,
materialNotes: body.materialNotes ?? null,
instructions: effectiveInstructions,
qcRequired: effectiveQcRequired,
plannedMinutes: body.plannedMinutes ?? null,
plannedUnits: body.plannedUnits ?? null,
qrToken,
},
});
await audit({
actorId: actor.id,
action: "create",
entity: "Operation",
entityId: created.id,
after: created,
ipAddress: clientIp(req),
});
return ok({ operation: created }, { status: 201 });
} catch (err) {
return errorResponse(err);
}
}
+90
View File
@@ -0,0 +1,90 @@
import { type NextRequest } from "next/server";
import { prisma } from "@/lib/prisma";
import { ok, errorResponse, requireRole, parseJson, ApiError } from "@/lib/api";
import { UpdatePartSchema } from "@/lib/schemas";
import { audit } from "@/lib/audit";
import { clientIp } from "@/lib/request";
export async function GET(_req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
try {
await requireRole("admin");
const { id } = await ctx.params;
const part = await prisma.part.findUnique({
where: { id },
include: {
assembly: {
include: { project: { select: { id: true, code: true, name: true } } },
},
stepFile: true,
drawingFile: true,
cutFile: true,
operations: {
orderBy: { sequence: "asc" },
include: { machine: { select: { id: true, name: true } } },
},
},
});
if (!part) throw new ApiError(404, "not_found", "Part not found");
return ok({ part });
} catch (err) {
return errorResponse(err);
}
}
export async function PATCH(req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
try {
const actor = await requireRole("admin");
const { id } = await ctx.params;
const body = await parseJson(req, UpdatePartSchema);
const before = await prisma.part.findUnique({ where: { id } });
if (!before) throw new ApiError(404, "not_found", "Part not found");
const updated = await prisma.part.update({
where: { id },
data: {
...(body.code !== undefined ? { code: body.code } : {}),
...(body.name !== undefined ? { name: body.name } : {}),
...(body.material !== undefined ? { material: body.material } : {}),
...(body.qty !== undefined ? { qty: body.qty } : {}),
...(body.notes !== undefined ? { notes: body.notes } : {}),
...(body.stepFileId !== undefined ? { stepFileId: body.stepFileId } : {}),
...(body.drawingFileId !== undefined ? { drawingFileId: body.drawingFileId } : {}),
...(body.cutFileId !== undefined ? { cutFileId: body.cutFileId } : {}),
},
});
await audit({
actorId: actor.id,
action: "update",
entity: "Part",
entityId: id,
before,
after: updated,
ipAddress: clientIp(req),
});
return ok({ part: updated });
} catch (err) {
return errorResponse(err);
}
}
export async function DELETE(req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
try {
const actor = await requireRole("admin");
const { id } = await ctx.params;
const before = await prisma.part.findUnique({ where: { id } });
if (!before) throw new ApiError(404, "not_found", "Part not found");
await prisma.part.delete({ where: { id } });
await audit({
actorId: actor.id,
action: "delete",
entity: "Part",
entityId: id,
before,
ipAddress: clientIp(req),
});
return ok({ ok: true });
} catch (err) {
return errorResponse(err);
}
}
@@ -0,0 +1,53 @@
import { type NextRequest } from "next/server";
import { prisma } from "@/lib/prisma";
import { ok, errorResponse, requireRole, parseJson, ApiError } from "@/lib/api";
import { CreateAssemblySchema } from "@/lib/schemas";
import { audit } from "@/lib/audit";
import { clientIp } from "@/lib/request";
export async function GET(_req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
try {
await requireRole("admin");
const { id } = await ctx.params;
const assemblies = await prisma.assembly.findMany({
where: { projectId: id },
orderBy: { code: "asc" },
include: { _count: { select: { parts: true } } },
});
return ok({ assemblies });
} catch (err) {
return errorResponse(err);
}
}
export async function POST(req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
try {
const actor = await requireRole("admin");
const { id } = await ctx.params;
const body = await parseJson(req, CreateAssemblySchema);
const project = await prisma.project.findUnique({ where: { id } });
if (!project) throw new ApiError(404, "not_found", "Project not found");
const created = await prisma.assembly.create({
data: {
projectId: id,
code: body.code,
name: body.name,
qty: body.qty,
notes: body.notes ?? null,
},
});
await audit({
actorId: actor.id,
action: "create",
entity: "Assembly",
entityId: created.id,
after: created,
ipAddress: clientIp(req),
});
return ok({ assembly: created }, { status: 201 });
} catch (err) {
return errorResponse(err);
}
}
+84
View File
@@ -0,0 +1,84 @@
import { type NextRequest } from "next/server";
import { prisma } from "@/lib/prisma";
import { ok, errorResponse, requireRole, parseJson, ApiError } from "@/lib/api";
import { UpdateProjectSchema } from "@/lib/schemas";
import { audit } from "@/lib/audit";
import { clientIp } from "@/lib/request";
export async function GET(_req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
try {
await requireRole("admin");
const { id } = await ctx.params;
const project = await prisma.project.findUnique({
where: { id },
include: {
assemblies: {
orderBy: { code: "asc" },
include: { _count: { select: { parts: true } } },
},
fasteners: true,
purchaseOrders: { orderBy: { createdAt: "desc" } },
},
});
if (!project) throw new ApiError(404, "not_found", "Project not found");
return ok({ project });
} catch (err) {
return errorResponse(err);
}
}
export async function PATCH(req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
try {
const actor = await requireRole("admin");
const { id } = await ctx.params;
const body = await parseJson(req, UpdateProjectSchema);
const before = await prisma.project.findUnique({ where: { id } });
if (!before) throw new ApiError(404, "not_found", "Project not found");
const updated = await prisma.project.update({
where: { id },
data: {
...(body.code !== undefined ? { code: body.code } : {}),
...(body.name !== undefined ? { name: body.name } : {}),
...(body.customerCode !== undefined ? { customerCode: body.customerCode } : {}),
...(body.dueDate !== undefined ? { dueDate: body.dueDate } : {}),
...(body.status !== undefined ? { status: body.status } : {}),
...(body.notes !== undefined ? { notes: body.notes } : {}),
},
});
await audit({
actorId: actor.id,
action: "update",
entity: "Project",
entityId: id,
before,
after: updated,
ipAddress: clientIp(req),
});
return ok({ project: updated });
} catch (err) {
return errorResponse(err);
}
}
export async function DELETE(req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
try {
const actor = await requireRole("admin");
const { id } = await ctx.params;
const before = await prisma.project.findUnique({ where: { id } });
if (!before) throw new ApiError(404, "not_found", "Project not found");
await prisma.project.delete({ where: { id } });
await audit({
actorId: actor.id,
action: "delete",
entity: "Project",
entityId: id,
before,
ipAddress: clientIp(req),
});
return ok({ ok: true });
} catch (err) {
return errorResponse(err);
}
}
+48
View File
@@ -0,0 +1,48 @@
import { type NextRequest } from "next/server";
import { prisma } from "@/lib/prisma";
import { ok, errorResponse, requireRole, parseJson } from "@/lib/api";
import { CreateProjectSchema } from "@/lib/schemas";
import { audit } from "@/lib/audit";
import { clientIp } from "@/lib/request";
export async function GET() {
try {
await requireRole("admin");
const projects = await prisma.project.findMany({
orderBy: [{ createdAt: "desc" }],
include: {
_count: { select: { assemblies: true } },
},
});
return ok({ projects });
} catch (err) {
return errorResponse(err);
}
}
export async function POST(req: NextRequest) {
try {
const actor = await requireRole("admin");
const body = await parseJson(req, CreateProjectSchema);
const created = await prisma.project.create({
data: {
code: body.code,
name: body.name,
customerCode: body.customerCode ?? null,
dueDate: body.dueDate ?? null,
notes: body.notes ?? null,
},
});
await audit({
actorId: actor.id,
action: "create",
entity: "Project",
entityId: created.id,
after: created,
ipAddress: clientIp(req),
});
return ok({ project: created }, { status: 201 });
} catch (err) {
return errorResponse(err);
}
}
+114
View File
@@ -0,0 +1,114 @@
import { type NextRequest } from "next/server";
import { prisma } from "@/lib/prisma";
import { ok, errorResponse, requireRole, parseJson, ApiError } from "@/lib/api";
import { UpdateUserSchema } from "@/lib/schemas";
import { hashPassword, hashPin } from "@/lib/password";
import { audit } from "@/lib/audit";
import { clientIp } from "@/lib/request";
export async function PATCH(req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
try {
const actor = await requireRole("admin");
const { id } = await ctx.params;
const body = await parseJson(req, UpdateUserSchema);
const user = await prisma.user.findUnique({ where: { id } });
if (!user) throw new ApiError(404, "not_found", "User not found");
const data: Record<string, unknown> = {};
if (body.name !== undefined) data.name = body.name;
if (body.active !== undefined) data.active = body.active;
if (user.role === "admin") {
if (body.email) {
const dup = await prisma.user.findFirst({
where: { email: body.email, id: { not: id } },
});
if (dup) throw new ApiError(409, "duplicate", "Email already in use");
data.email = body.email;
}
if (body.password) data.passwordHash = await hashPassword(body.password);
if (body.pin) {
throw new ApiError(400, "invalid_field", "Admins don't have PINs");
}
} else {
if (body.email || body.password) {
throw new ApiError(400, "invalid_field", "Operators use PIN, not email/password");
}
if (body.pin) {
data.pinHash = await hashPin(body.pin);
data.failedAttempts = 0;
data.lockedUntil = null;
}
if (body.name && body.name !== user.name) {
const dup = await prisma.user.findFirst({
where: { role: "operator", name: body.name, id: { not: id } },
});
if (dup) throw new ApiError(409, "duplicate", "Operator name already in use");
}
}
const updated = await prisma.user.update({
where: { id },
data,
select: { id: true, role: true, name: true, email: true, active: true },
});
await audit({
actorId: actor.id,
action: "update",
entity: "User",
entityId: id,
after: {
changed: Object.keys(data).filter((k) => k !== "passwordHash" && k !== "pinHash"),
secretsChanged: "passwordHash" in data || "pinHash" in data,
},
ipAddress: clientIp(req),
});
return ok({ user: updated });
} catch (err) {
return errorResponse(err);
}
}
export async function DELETE(req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
try {
const actor = await requireRole("admin");
const { id } = await ctx.params;
if (id === actor.id) {
throw new ApiError(400, "self_delete", "You cannot delete your own account");
}
const user = await prisma.user.findUnique({ where: { id } });
if (!user) throw new ApiError(404, "not_found", "User not found");
if (user.role === "admin") {
const otherAdmins = await prisma.user.count({
where: { role: "admin", active: true, id: { not: id } },
});
if (otherAdmins === 0) {
throw new ApiError(400, "last_admin", "Cannot remove the last active admin");
}
}
// soft-delete: deactivate and remove all sessions
await prisma.$transaction([
prisma.session.deleteMany({ where: { userId: id } }),
prisma.user.update({ where: { id }, data: { active: false } }),
]);
await audit({
actorId: actor.id,
action: "deactivate",
entity: "User",
entityId: id,
ipAddress: clientIp(req),
});
return ok({ ok: true });
} catch (err) {
return errorResponse(err);
}
}
+81
View File
@@ -0,0 +1,81 @@
import { type NextRequest } from "next/server";
import { prisma } from "@/lib/prisma";
import { ok, errorResponse, requireRole, parseJson, ApiError } from "@/lib/api";
import { CreateUserSchema } from "@/lib/schemas";
import { hashPassword, hashPin } from "@/lib/password";
import { audit } from "@/lib/audit";
import { clientIp } from "@/lib/request";
export async function GET() {
try {
await requireRole("admin");
const users = await prisma.user.findMany({
orderBy: [{ role: "asc" }, { name: "asc" }],
select: {
id: true,
role: true,
name: true,
email: true,
active: true,
lastLoginAt: true,
createdAt: true,
},
});
return ok({ users });
} catch (err) {
return errorResponse(err);
}
}
export async function POST(req: NextRequest) {
try {
const actor = await requireRole("admin");
const body = await parseJson(req, CreateUserSchema);
if (body.role === "admin") {
const existing = await prisma.user.findUnique({ where: { email: body.email } });
if (existing) throw new ApiError(409, "duplicate", "Email already in use");
const passwordHash = await hashPassword(body.password);
const created = await prisma.user.create({
data: { role: "admin", name: body.name, email: body.email, passwordHash },
select: { id: true, role: true, name: true, email: true, active: true, createdAt: true },
});
await audit({
actorId: actor.id,
action: "create",
entity: "User",
entityId: created.id,
after: { role: "admin", name: created.name, email: created.email },
ipAddress: clientIp(req),
});
return ok({ user: created }, { status: 201 });
}
// operator: name must be unique (case-insensitive) so login tile grid is unambiguous
const nameNorm = body.name.trim();
const dupe = await prisma.user.findFirst({
where: {
role: "operator",
name: { equals: nameNorm },
},
});
if (dupe) throw new ApiError(409, "duplicate", "Operator name already in use");
const pinHash = await hashPin(body.pin);
const created = await prisma.user.create({
data: { role: "operator", name: nameNorm, pinHash },
select: { id: true, role: true, name: true, email: true, active: true, createdAt: true },
});
await audit({
actorId: actor.id,
action: "create",
entity: "User",
entityId: created.id,
after: { role: "operator", name: created.name },
ipAddress: clientIp(req),
});
return ok({ user: created }, { status: 201 });
} catch (err) {
return errorResponse(err);
}
}