stage 4
Build and Push Docker Image / build (push) Successful in 1m6s

This commit is contained in:
jason
2026-04-21 09:29:44 -05:00
parent 41b06f89c0
commit fc5bce4868
19 changed files with 1469 additions and 190 deletions
+72
View File
@@ -0,0 +1,72 @@
import { type NextRequest } from "next/server";
import { prisma } from "@/lib/prisma";
import { ok, errorResponse, requireRole, ApiError } from "@/lib/api";
import { audit } from "@/lib/audit";
import { clientIp } from "@/lib/request";
/**
* Claim an operation for the current operator. We enforce the "single claim"
* invariant at the DB level: updateMany's where clause includes
* { claimedByUserId: null, status: "pending" }, so a second operator racing
* us will match 0 rows and we reject with 409. No transaction needed.
*
* On success we also open a TimeLog row so "hours on machine" telemetry
* later lines up with actual floor time.
*/
export async function POST(req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
try {
const actor = await requireRole("operator");
const { id } = await ctx.params;
const existing = await prisma.operation.findUnique({
where: { id },
select: { id: true, status: true, claimedByUserId: true, name: true },
});
if (!existing) throw new ApiError(404, "not_found", "Operation not found");
if (existing.status === "completed") {
throw new ApiError(409, "op_completed", "This step is already completed");
}
if (existing.claimedByUserId && existing.claimedByUserId !== actor.id) {
throw new ApiError(409, "op_claimed", "Another operator is already working on this step");
}
if (existing.claimedByUserId === actor.id) {
// Idempotent: scanning again while already holding the claim is a no-op.
const op = await prisma.operation.findUnique({ where: { id } });
return ok({ operation: op, alreadyClaimed: true });
}
const now = new Date();
const updateResult = await prisma.operation.updateMany({
where: { id, claimedByUserId: null, status: "pending" },
data: {
status: "in_progress",
claimedByUserId: actor.id,
claimedAt: now,
},
});
if (updateResult.count === 0) {
// Lost a race to another operator between the check above and the update.
throw new ApiError(409, "op_claimed", "Another operator just claimed this step");
}
await prisma.timeLog.create({
data: { operationId: id, operatorId: actor.id, startedAt: now },
});
const op = await prisma.operation.findUnique({ where: { id } });
await audit({
actorId: actor.id,
action: "claim_op",
entity: "Operation",
entityId: id,
after: { status: "in_progress", claimedByUserId: actor.id },
ipAddress: clientIp(req),
});
return ok({ operation: op });
} catch (err) {
return errorResponse(err);
}
}
+98
View File
@@ -0,0 +1,98 @@
import { type NextRequest } from "next/server";
import { prisma } from "@/lib/prisma";
import { ok, errorResponse, requireRole, parseJson, ApiError } from "@/lib/api";
import { CloseOperationSchema } from "@/lib/schemas";
import { audit } from "@/lib/audit";
import { clientIp } from "@/lib/request";
/**
* Complete an operation. Only the current claim holder may close, and if
* the operation is flagged qcRequired the payload must include an inline
* QC block (pass/fail + optional measurements). Close does four things
* atomically:
*
* 1. marks the operation completed + records completedAt,
* 2. closes the open TimeLog with unitsProcessed / note if provided,
* 3. writes a QCRecord if this op requires QC (or if the operator passed
* one in voluntarily),
* 4. audits the close for later reporting.
*/
export async function POST(req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
try {
const actor = await requireRole("operator");
const { id } = await ctx.params;
const body = await parseJson(req, CloseOperationSchema);
const existing = await prisma.operation.findUnique({
where: { id },
select: { id: true, status: true, claimedByUserId: true, qcRequired: true },
});
if (!existing) throw new ApiError(404, "not_found", "Operation not found");
if (existing.claimedByUserId !== actor.id) {
throw new ApiError(409, "not_claim_holder", "Only the current operator can complete this step");
}
if (existing.status !== "in_progress") {
throw new ApiError(409, "op_not_active", "Step is not active");
}
if (existing.qcRequired && !body.qc) {
throw new ApiError(400, "qc_required", "This step requires an inline QC check before completing");
}
const now = new Date();
await prisma.$transaction(async (tx) => {
const openLog = await tx.timeLog.findFirst({
where: { operationId: id, operatorId: actor.id, endedAt: null },
orderBy: { startedAt: "desc" },
});
if (openLog) {
await tx.timeLog.update({
where: { id: openLog.id },
data: {
endedAt: now,
unitsProcessed: body.unitsProcessed ?? null,
note: body.note ?? null,
},
});
}
if (body.qc) {
await tx.qCRecord.create({
data: {
operationId: id,
operatorId: actor.id,
kind: "inline",
passed: body.qc.passed,
measurements: body.qc.measurements ?? null,
notes: body.qc.notes ?? null,
},
});
}
await tx.operation.update({
where: { id },
data: {
status: "completed",
completedAt: now,
claimedByUserId: null,
claimedAt: null,
},
});
});
const op = await prisma.operation.findUnique({ where: { id } });
await audit({
actorId: actor.id,
action: "close_op",
entity: "Operation",
entityId: id,
after: {
status: "completed",
unitsProcessed: body.unitsProcessed ?? null,
qcPassed: body.qc?.passed ?? null,
},
ipAddress: clientIp(req),
});
return ok({ operation: op });
} catch (err) {
return errorResponse(err);
}
}
+35
View File
@@ -0,0 +1,35 @@
import { type NextRequest } from "next/server";
import { prisma } from "@/lib/prisma";
import { ok, errorResponse, requireRole, ApiError } from "@/lib/api";
import { renderQrPng, scanUrlForToken } from "@/lib/qr";
/**
* Admin-only. Render the operation's QR token as a data-URL PNG so the part
* detail UI can preview (and later print) the traveler. We keep token
* generation out of band from rendering so the DB remains the single source
* of truth for the token value.
*/
export async function GET(_req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
try {
await requireRole("admin");
const { id } = await ctx.params;
const op = await prisma.operation.findUnique({
where: { id },
select: { id: true, qrToken: true, sequence: true, name: true },
});
if (!op) throw new ApiError(404, "not_found", "Operation not found");
const dataUrl = await renderQrPng(op.qrToken);
return ok({
operationId: op.id,
sequence: op.sequence,
name: op.name,
token: op.qrToken,
scanUrl: scanUrlForToken(op.qrToken),
dataUrl,
});
} catch (err) {
return errorResponse(err);
}
}
@@ -0,0 +1,71 @@
import { type NextRequest } from "next/server";
import { prisma } from "@/lib/prisma";
import { ok, errorResponse, requireRole, parseJson, ApiError } from "@/lib/api";
import { ReleaseOperationSchema } from "@/lib/schemas";
import { audit } from "@/lib/audit";
import { clientIp } from "@/lib/request";
/**
* Pause an in-progress operation: drop the claim, close the open TimeLog,
* and send the step back to pending so any operator can pick it up next.
* Only the current claim holder may release (admins get their own escape
* hatch via the PATCH endpoint if we ever need one).
*/
export async function POST(req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
try {
const actor = await requireRole("operator");
const { id } = await ctx.params;
const body = await parseJson(req, ReleaseOperationSchema);
const existing = await prisma.operation.findUnique({
where: { id },
select: { id: true, status: true, claimedByUserId: true },
});
if (!existing) throw new ApiError(404, "not_found", "Operation not found");
if (existing.claimedByUserId !== actor.id) {
throw new ApiError(409, "not_claim_holder", "Only the current operator can pause this step");
}
if (existing.status !== "in_progress") {
throw new ApiError(409, "op_not_active", "Step is not active");
}
const now = new Date();
await prisma.$transaction(async (tx) => {
// Close the most recent open TimeLog for (op, operator). We accept that
// if two rows are open for the same pair something has gone wrong
// elsewhere; close the newest and let the audit log preserve history.
const openLog = await tx.timeLog.findFirst({
where: { operationId: id, operatorId: actor.id, endedAt: null },
orderBy: { startedAt: "desc" },
});
if (openLog) {
await tx.timeLog.update({
where: { id: openLog.id },
data: {
endedAt: now,
unitsProcessed: body.unitsProcessed ?? null,
note: body.note ?? null,
},
});
}
await tx.operation.update({
where: { id },
data: { status: "pending", claimedByUserId: null, claimedAt: null },
});
});
const op = await prisma.operation.findUnique({ where: { id } });
await audit({
actorId: actor.id,
action: "release_op",
entity: "Operation",
entityId: id,
after: { status: "pending", unitsProcessed: body.unitsProcessed ?? null },
ipAddress: clientIp(req),
});
return ok({ operation: op });
} catch (err) {
return errorResponse(err);
}
}
@@ -0,0 +1,60 @@
import { type NextRequest } from "next/server";
import { prisma } from "@/lib/prisma";
import { ok, errorResponse, ApiError } from "@/lib/api";
import { getSessionUser } from "@/lib/session";
/**
* Resolve a scanned QR token into enough context for the operator scan page.
*
* A scan can happen from:
* - An admin still logged in on their laptop (shouldn't happen in the field
* but we allow it for testing the print flow).
* - An operator with a valid device session.
* - An unauthenticated phone (the page redirects to /login/operator?next=...
* before calling this route, so in practice we require a session here).
*
* We intentionally return only the operation fields the operator needs. Admin-
* only stuff (audit logs, full file SHAs, etc.) is off-limits.
*/
export async function GET(_req: NextRequest, ctx: { params: Promise<{ token: string }> }) {
try {
const user = await getSessionUser();
if (!user) throw new ApiError(401, "unauthenticated", "Sign in required");
const { token } = await ctx.params;
const op = await prisma.operation.findUnique({
where: { qrToken: token },
include: {
machine: { select: { id: true, name: true, kind: true } },
part: {
select: {
id: true,
code: true,
name: true,
material: true,
qty: true,
stepFileId: true,
drawingFileId: true,
cutFileId: true,
assembly: {
select: {
id: true,
code: true,
name: true,
project: { select: { id: true, code: true, name: true } },
},
},
},
},
claimedBy: { select: { id: true, name: true } },
},
});
if (!op) throw new ApiError(404, "unknown_token", "That QR code isn't recognised");
const claimedByMe = op.claimedByUserId === user.id;
return ok({ operation: op, viewer: { id: user.id, role: user.role, claimedByMe } });
} catch (err) {
return errorResponse(err);
}
}