stage 5-6
Build and Push Docker Image / build (push) Successful in 1m11s

This commit is contained in:
jason
2026-04-21 13:14:27 -05:00
parent fc5bce4868
commit 5847a175af
26 changed files with 3031 additions and 29 deletions
+83
View File
@@ -0,0 +1,83 @@
import { type NextRequest } from "next/server";
import { prisma } from "@/lib/prisma";
import { ok, errorResponse, requireRole, parseJson, ApiError } from "@/lib/api";
import { UpdateFastenerSchema } 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 f = await prisma.fastener.findUnique({ where: { id } });
if (!f) throw new ApiError(404, "not_found", "Fastener not found");
return ok({ fastener: f });
} 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 before = await prisma.fastener.findUnique({ where: { id } });
if (!before) throw new ApiError(404, "not_found", "Fastener not found");
const body = await parseJson(req, UpdateFastenerSchema);
const after = await prisma.fastener.update({ where: { id }, data: body });
await audit({
actorId: actor.id,
action: "update",
entity: "Fastener",
entityId: id,
before,
after,
ipAddress: clientIp(req),
});
return ok({ fastener: after });
} catch (err) {
return errorResponse(err);
}
}
/**
* Delete only when no PO lines reference the fastener. If there are lines
* (even on cancelled POs) we refuse, because removing the fastener would
* orphan historical receipt records. Admin can zero the qty + flag the
* description instead if they want to retire it.
*/
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.fastener.findUnique({
where: { id },
include: { _count: { select: { poLines: true } } },
});
if (!before) throw new ApiError(404, "not_found", "Fastener not found");
if (before._count.poLines > 0) {
throw new ApiError(
409,
"fastener_in_use",
"Fastener is referenced by purchase order lines; cancel them first",
);
}
await prisma.fastener.delete({ where: { id } });
await audit({
actorId: actor.id,
action: "delete",
entity: "Fastener",
entityId: id,
before,
ipAddress: clientIp(req),
});
return ok({ ok: true });
} catch (err) {
return errorResponse(err);
}
}
@@ -0,0 +1,79 @@
import { type NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { errorResponse, requireRole, ApiError } from "@/lib/api";
import { renderOperationCard, type OperationCardData } from "@/lib/pdf";
/**
* Admin-only. Stream a one-page traveler card PDF for the given operation.
* We respond with `Content-Disposition: inline` so hitting the link in a
* new tab previews the PDF rather than forcing a download — makes the
* "print for the shop floor" flow a single click.
*/
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 },
include: {
machine: { select: { name: true, kind: true } },
part: {
select: {
code: true,
name: true,
material: true,
qty: true,
assembly: {
select: {
code: true,
name: true,
project: { select: { code: true, name: true } },
},
},
},
},
},
});
if (!op) throw new ApiError(404, "not_found", "Operation not found");
const data: OperationCardData = {
project: op.part.assembly.project,
assembly: { code: op.part.assembly.code, name: op.part.assembly.name },
part: {
code: op.part.code,
name: op.part.name,
material: op.part.material,
qty: op.part.qty,
},
operation: {
id: op.id,
sequence: op.sequence,
name: op.name,
qrToken: op.qrToken,
machineName: op.machine?.name ?? null,
machineKind: op.machine?.kind ?? null,
settings: op.settings,
materialNotes: op.materialNotes,
instructions: op.instructions,
qcRequired: op.qcRequired,
plannedMinutes: op.plannedMinutes,
plannedUnits: op.plannedUnits,
},
};
const pdf = await renderOperationCard(data);
const safeName = `${op.part.code}-op${op.sequence}.pdf`.replace(/[^A-Za-z0-9._-]/g, "_");
return new NextResponse(pdf as unknown as BodyInit, {
status: 200,
headers: {
"Content-Type": "application/pdf",
"Content-Disposition": `inline; filename="${safeName}"`,
"Cache-Control": "private, no-store",
},
});
} catch (err) {
return errorResponse(err);
}
}
@@ -0,0 +1,105 @@
import { type NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { errorResponse, requireRole, ApiError } from "@/lib/api";
import {
renderPartTravelers,
type OperationCardData,
type PartCoverData,
} from "@/lib/pdf";
/**
* Admin-only. Return a single PDF containing:
* Page 1 - cover sheet (part header, file manifest, operation summary)
* Page 2..N - one traveler card per operation, sequence order.
*
* Matches the physical print workflow: staple the stack, the cover goes on
* top for the project binder and the cards go out to the floor.
*/
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: { code: true, name: true } } },
},
stepFile: { select: { originalName: true, sizeBytes: true, sha256: true } },
drawingFile: { select: { originalName: true, sizeBytes: true, sha256: true } },
cutFile: { select: { originalName: true, sizeBytes: true, sha256: true } },
operations: {
orderBy: { sequence: "asc" },
include: { machine: { select: { name: true, kind: true } } },
},
},
});
if (!part) throw new ApiError(404, "not_found", "Part not found");
if (part.operations.length === 0) {
throw new ApiError(400, "no_operations", "This part has no operations to print");
}
const project = part.assembly.project;
const assembly = { code: part.assembly.code, name: part.assembly.name };
const partHeader = {
code: part.code,
name: part.name,
material: part.material,
qty: part.qty,
};
const cover: PartCoverData = {
project,
assembly,
part: { ...partHeader, notes: part.notes },
files: [
{ label: "STEP / 3D", file: part.stepFile },
{ label: "Drawing PDF", file: part.drawingFile },
{ label: "Cut file", file: part.cutFile },
],
operations: part.operations.map((op) => ({
sequence: op.sequence,
name: op.name,
machineName: op.machine?.name ?? null,
qcRequired: op.qcRequired,
qrToken: op.qrToken,
})),
};
const cards: OperationCardData[] = part.operations.map((op) => ({
project,
assembly,
part: partHeader,
operation: {
id: op.id,
sequence: op.sequence,
name: op.name,
qrToken: op.qrToken,
machineName: op.machine?.name ?? null,
machineKind: op.machine?.kind ?? null,
settings: op.settings,
materialNotes: op.materialNotes,
instructions: op.instructions,
qcRequired: op.qcRequired,
plannedMinutes: op.plannedMinutes,
plannedUnits: op.plannedUnits,
},
}));
const pdf = await renderPartTravelers({ cover, cards });
const safeName = `${part.code}-travelers.pdf`.replace(/[^A-Za-z0-9._-]/g, "_");
return new NextResponse(pdf as unknown as BodyInit, {
status: 200,
headers: {
"Content-Type": "application/pdf",
"Content-Disposition": `inline; filename="${safeName}"`,
"Cache-Control": "private, no-store",
},
});
} catch (err) {
return errorResponse(err);
}
}
@@ -0,0 +1,95 @@
import { type NextRequest } from "next/server";
import { prisma } from "@/lib/prisma";
import { ok, errorResponse, requireRole, parseJson, ApiError } from "@/lib/api";
import { CreateFastenerSchema } from "@/lib/schemas";
import { audit } from "@/lib/audit";
import { clientIp } from "@/lib/request";
/**
* List fasteners on a project + compute "remaining to order" per row so the
* PO draft UI can suggest line qtys. remaining = qty - sum(receivedQty on
* open lines). Closed / cancelled PO lines don't count against the need.
*/
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 }, select: { id: true } });
if (!project) throw new ApiError(404, "not_found", "Project not found");
const fasteners = await prisma.fastener.findMany({
where: { projectId: id },
orderBy: [{ supplier: "asc" }, { partNumber: "asc" }],
include: {
poLines: {
select: {
qty: true,
receivedQty: true,
po: { select: { status: true } },
},
},
},
});
const rows = fasteners.map((f) => {
let onOrder = 0;
let received = 0;
for (const line of f.poLines) {
if (line.po.status === "cancelled") continue;
onOrder += line.qty;
received += line.receivedQty;
}
const remaining = Math.max(0, f.qty - received);
const unresolved = Math.max(0, f.qty - onOrder);
return {
...f,
poLines: undefined,
onOrder,
received,
remaining,
unresolved, // qty we haven't put on any PO yet
};
});
return ok({ fasteners: rows });
} 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, CreateFastenerSchema);
const project = await prisma.project.findUnique({ where: { id }, select: { id: true } });
if (!project) throw new ApiError(404, "not_found", "Project not found");
const created = await prisma.fastener.create({
data: {
projectId: id,
partNumber: body.partNumber,
description: body.description,
qty: body.qty,
supplier: body.supplier ?? null,
unitCost: body.unitCost ?? null,
notes: body.notes ?? null,
},
});
await audit({
actorId: actor.id,
action: "create",
entity: "Fastener",
entityId: created.id,
after: created,
ipAddress: clientIp(req),
});
return ok({ fastener: created }, { status: 201 });
} catch (err) {
return errorResponse(err);
}
}
@@ -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 { CreatePOSchema } from "@/lib/schemas";
import { audit } from "@/lib/audit";
import { clientIp } from "@/lib/request";
/**
* List purchase orders on a project with summary totals so the UI can show
* "draft / sent / received" status and a line/dollar summary without a
* second round-trip.
*/
export async function GET(_req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
try {
await requireRole("admin");
const { id } = await ctx.params;
const pos = await prisma.purchaseOrder.findMany({
where: { projectId: id },
orderBy: [{ createdAt: "desc" }],
include: {
lines: {
select: {
qty: true,
receivedQty: true,
unitCost: true,
fastener: { select: { partNumber: true, description: true, unitCost: true } },
},
},
},
});
const rows = pos.map((po) => {
const totalQty = po.lines.reduce((a, l) => a + l.qty, 0);
const totalReceived = po.lines.reduce((a, l) => a + l.receivedQty, 0);
const totalCost = po.lines.reduce((acc, l) => {
const cost = l.unitCost ?? l.fastener.unitCost ?? 0;
return acc + cost * l.qty;
}, 0);
return {
id: po.id,
vendor: po.vendor,
status: po.status,
createdAt: po.createdAt,
sentAt: po.sentAt,
receivedAt: po.receivedAt,
notes: po.notes,
lineCount: po.lines.length,
totalQty,
totalReceived,
totalCost,
};
});
return ok({ purchaseOrders: rows });
} 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, CreatePOSchema);
const project = await prisma.project.findUnique({ where: { id }, select: { id: true } });
if (!project) throw new ApiError(404, "not_found", "Project not found");
// Validate every fastener on every line belongs to this project.
const fastenerIds = [...new Set(body.lines.map((l) => l.fastenerId))];
const fasteners = await prisma.fastener.findMany({
where: { id: { in: fastenerIds }, projectId: id },
select: { id: true },
});
if (fasteners.length !== fastenerIds.length) {
throw new ApiError(
400,
"invalid_fasteners",
"One or more fasteners don't belong to this project",
);
}
const created = await prisma.purchaseOrder.create({
data: {
projectId: id,
vendor: body.vendor,
notes: body.notes ?? null,
status: "draft",
lines: {
create: body.lines.map((l) => ({
fastenerId: l.fastenerId,
qty: l.qty,
unitCost: l.unitCost ?? null,
})),
},
},
include: { lines: true },
});
await audit({
actorId: actor.id,
action: "create",
entity: "PurchaseOrder",
entityId: created.id,
after: created,
ipAddress: clientIp(req),
});
return ok({ purchaseOrder: created }, { status: 201 });
} catch (err) {
return errorResponse(err);
}
}
@@ -0,0 +1,56 @@
import { type NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { errorResponse, requireRole, ApiError } from "@/lib/api";
import { renderPurchaseOrder } from "@/lib/pdf";
export async function GET(_req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
try {
await requireRole("admin");
const { id } = await ctx.params;
const po = await prisma.purchaseOrder.findUnique({
where: { id },
include: {
project: { select: { code: true, name: true } },
lines: {
include: {
fastener: { select: { partNumber: true, description: true, supplier: true, unitCost: true } },
},
},
},
});
if (!po) throw new ApiError(404, "not_found", "Purchase order not found");
const pdf = await renderPurchaseOrder({
po: {
id: po.id,
vendor: po.vendor,
status: po.status,
createdAt: po.createdAt,
sentAt: po.sentAt,
notes: po.notes,
},
project: po.project,
lines: po.lines.map((l) => ({
partNumber: l.fastener.partNumber,
description: l.fastener.description,
supplier: l.fastener.supplier,
qty: l.qty,
// line-level cost overrides the fastener's default if set
unitCost: l.unitCost ?? l.fastener.unitCost ?? null,
})),
});
const safeName = `PO-${po.id.slice(0, 8)}.pdf`;
return new NextResponse(pdf as unknown as BodyInit, {
status: 200,
headers: {
"Content-Type": "application/pdf",
"Content-Disposition": `inline; filename="${safeName}"`,
"Cache-Control": "private, no-store",
},
});
} catch (err) {
return errorResponse(err);
}
}
@@ -0,0 +1,102 @@
import { type NextRequest } from "next/server";
import { prisma } from "@/lib/prisma";
import { ok, errorResponse, requireRole, parseJson, ApiError } from "@/lib/api";
import { ReceivePOSchema } from "@/lib/schemas";
import { audit } from "@/lib/audit";
import { clientIp } from "@/lib/request";
/**
* Record receipt of PO line quantities. Body is an array of
* { lineId, qty } — each qty is ADDED to the line's existing receivedQty.
* Over-receipt (receivedQty > qty) is rejected so accidentally typing two
* zeros doesn't silently corrupt inventory counts.
*
* Post-update, we auto-advance the PO status:
* - every line fully received => "received" (+ receivedAt)
* - any received > 0 but not all full => "partial"
* - otherwise status left as-is (shouldn't happen given we require >=1 receipt).
*/
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, ReceivePOSchema);
const before = await prisma.purchaseOrder.findUnique({
where: { id },
include: { lines: true },
});
if (!before) throw new ApiError(404, "not_found", "Purchase order not found");
if (before.status === "cancelled" || before.status === "received") {
throw new ApiError(409, "po_terminal", `PO is ${before.status}; no more receipts accepted`);
}
const byId = new Map(before.lines.map((l) => [l.id, l]));
// Merge duplicate lineIds from the payload so the caller can post partials.
const deltas = new Map<string, number>();
for (const r of body.receipts) {
deltas.set(r.lineId, (deltas.get(r.lineId) ?? 0) + r.qty);
}
for (const [lineId, qty] of deltas) {
const line = byId.get(lineId);
if (!line) throw new ApiError(400, "unknown_line", `Line ${lineId} not on this PO`);
if (line.receivedQty + qty > line.qty) {
throw new ApiError(
400,
"over_receipt",
`Line ${lineId} would receive ${line.receivedQty + qty} > ordered ${line.qty}`,
);
}
}
await prisma.$transaction(async (tx) => {
for (const [lineId, qty] of deltas) {
await tx.pOLine.update({
where: { id: lineId },
data: { receivedQty: { increment: qty } },
});
}
});
// Re-read to compute the aggregate status.
const after = await prisma.purchaseOrder.findUnique({
where: { id },
include: { lines: true },
});
if (!after) throw new ApiError(500, "internal", "PO vanished mid-transaction");
const allFull = after.lines.every((l) => l.receivedQty >= l.qty);
const anyReceived = after.lines.some((l) => l.receivedQty > 0);
let nextStatus = after.status;
const extra: { receivedAt?: Date } = {};
if (allFull) {
nextStatus = "received";
if (!after.receivedAt) extra.receivedAt = new Date();
} else if (anyReceived) {
nextStatus = "partial";
}
const finalPo =
nextStatus !== after.status || extra.receivedAt
? await prisma.purchaseOrder.update({
where: { id },
data: { status: nextStatus, ...extra },
include: { lines: true },
})
: after;
await audit({
actorId: actor.id,
action: "receive",
entity: "PurchaseOrder",
entityId: id,
before: { status: before.status },
after: { status: finalPo.status, receipts: Array.from(deltas.entries()) },
ipAddress: clientIp(req),
});
return ok({ purchaseOrder: finalPo });
} catch (err) {
return errorResponse(err);
}
}
+141
View File
@@ -0,0 +1,141 @@
import { type NextRequest } from "next/server";
import { prisma } from "@/lib/prisma";
import { ok, errorResponse, requireRole, parseJson, ApiError } from "@/lib/api";
import { UpdatePOSchema } 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 po = await prisma.purchaseOrder.findUnique({
where: { id },
include: {
project: { select: { id: true, code: true, name: true } },
lines: {
include: {
fastener: {
select: {
id: true,
partNumber: true,
description: true,
unitCost: true,
supplier: true,
},
},
},
},
},
});
if (!po) throw new ApiError(404, "not_found", "Purchase order not found");
return ok({ purchaseOrder: po });
} catch (err) {
return errorResponse(err);
}
}
/**
* Update vendor/notes any time. Lines can only be rewritten while the PO is
* still in draft — once sent we freeze the line items so the vendor record
* stays truthful. Rewriting lines is a full replace (delete + insert) so
* the caller passes the complete desired list.
*/
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, UpdatePOSchema);
const before = await prisma.purchaseOrder.findUnique({
where: { id },
include: { lines: true },
});
if (!before) throw new ApiError(404, "not_found", "Purchase order not found");
if (body.lines && before.status !== "draft") {
throw new ApiError(409, "po_locked", "Lines can only be edited on a draft PO");
}
const after = await prisma.$transaction(async (tx) => {
if (body.lines) {
// Validate fastener ownership in the project before mutating anything.
const fastenerIds = [...new Set(body.lines.map((l) => l.fastenerId))];
const owned = await tx.fastener.findMany({
where: { id: { in: fastenerIds }, projectId: before.projectId },
select: { id: true },
});
if (owned.length !== fastenerIds.length) {
throw new ApiError(
400,
"invalid_fasteners",
"One or more fasteners don't belong to this project",
);
}
await tx.pOLine.deleteMany({ where: { poId: id } });
}
const updated = await tx.purchaseOrder.update({
where: { id },
data: {
vendor: body.vendor ?? undefined,
notes: body.notes === undefined ? undefined : (body.notes ?? null),
...(body.lines
? {
lines: {
create: body.lines.map((l) => ({
fastenerId: l.fastenerId,
qty: l.qty,
unitCost: l.unitCost ?? null,
})),
},
}
: {}),
},
include: { lines: true },
});
return updated;
});
await audit({
actorId: actor.id,
action: "update",
entity: "PurchaseOrder",
entityId: id,
before,
after,
ipAddress: clientIp(req),
});
return ok({ purchaseOrder: after });
} 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.purchaseOrder.findUnique({ where: { id } });
if (!before) throw new ApiError(404, "not_found", "Purchase order not found");
// Only allow hard-delete of drafts. Anything further along has to be
// cancelled via the status endpoint, which preserves the audit trail.
if (before.status !== "draft") {
throw new ApiError(409, "po_locked", "Only draft POs can be deleted; cancel instead");
}
await prisma.purchaseOrder.delete({ where: { id } });
await audit({
actorId: actor.id,
action: "delete",
entity: "PurchaseOrder",
entityId: id,
before,
ipAddress: clientIp(req),
});
return ok({ ok: true });
} catch (err) {
return errorResponse(err);
}
}
@@ -0,0 +1,66 @@
import { type NextRequest } from "next/server";
import { prisma } from "@/lib/prisma";
import { ok, errorResponse, requireRole, parseJson, ApiError } from "@/lib/api";
import { UpdatePOStatusSchema } from "@/lib/schemas";
import { audit } from "@/lib/audit";
import { clientIp } from "@/lib/request";
/**
* Allowed manual status transitions. We specifically do NOT allow manually
* jumping to "partial" or "received" from here — those move automatically
* when a receipt is recorded via /receive. Cancelling is possible from any
* pre-terminal state.
*/
const PO_TRANSITIONS: Record<string, string[]> = {
draft: ["sent", "cancelled"],
sent: ["cancelled"],
partial: ["cancelled"],
received: [],
cancelled: [],
};
export async function POST(req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
try {
const actor = await requireRole("admin");
const { id } = await ctx.params;
const { status: next } = await parseJson(req, UpdatePOStatusSchema);
const before = await prisma.purchaseOrder.findUnique({ where: { id } });
if (!before) throw new ApiError(404, "not_found", "Purchase order not found");
const allowed = PO_TRANSITIONS[before.status] ?? [];
if (!allowed.includes(next)) {
throw new ApiError(
409,
"invalid_transition",
`Cannot move PO from ${before.status}${next}`,
);
}
const data: {
status: string;
sentAt?: Date | null;
receivedAt?: Date | null;
} = { status: next };
if (next === "sent" && !before.sentAt) data.sentAt = new Date();
if (next === "cancelled") {
// Keep sent/received timestamps for history; they're part of the audit.
}
const after = await prisma.purchaseOrder.update({ where: { id }, data });
await audit({
actorId: actor.id,
action: "update_status",
entity: "PurchaseOrder",
entityId: id,
before: { status: before.status },
after: { status: after.status },
ipAddress: clientIp(req),
});
return ok({ purchaseOrder: after });
} catch (err) {
return errorResponse(err);
}
}