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