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