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
@@ -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);
}
}