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
+28 -16
View File
@@ -155,24 +155,36 @@ export default function ProjectDetailClient({
</section>
<section className="grid gap-4 sm:grid-cols-2">
<Card>
<div className="p-4">
<h3 className="font-semibold mb-1">Fasteners</h3>
<p className="text-sm text-slate-500 mb-3">
{project.fastenerCount} item{project.fastenerCount === 1 ? "" : "s"} tracked
</p>
<p className="text-xs text-slate-400">Fastener authoring lands in step 6.</p>
<Link
href={`/admin/projects/${project.id}/fasteners`}
className="block rounded-xl bg-white border border-slate-200 shadow-sm p-4 hover:border-slate-900 transition"
>
<div className="flex items-center justify-between">
<h3 className="font-semibold">Fasteners</h3>
<span className="text-sm text-blue-600">Open </span>
</div>
</Card>
<Card>
<div className="p-4">
<h3 className="font-semibold mb-1">Purchase orders</h3>
<p className="text-sm text-slate-500 mb-3">
{project.poCount} PO{project.poCount === 1 ? "" : "s"}
</p>
<p className="text-xs text-slate-400">PO lifecycle and PDFs land in step 6.</p>
<p className="text-sm text-slate-500 mt-1">
{project.fastenerCount} item{project.fastenerCount === 1 ? "" : "s"} tracked
</p>
<p className="text-xs text-slate-400 mt-2">
Add BOM items, suppliers, unit costs, and unresolved-need suggestions for POs.
</p>
</Link>
<Link
href={`/admin/projects/${project.id}/purchase-orders`}
className="block rounded-xl bg-white border border-slate-200 shadow-sm p-4 hover:border-slate-900 transition"
>
<div className="flex items-center justify-between">
<h3 className="font-semibold">Purchase orders</h3>
<span className="text-sm text-blue-600">Open </span>
</div>
</Card>
<p className="text-sm text-slate-500 mt-1">
{project.poCount} PO{project.poCount === 1 ? "" : "s"}
</p>
<p className="text-xs text-slate-400 mt-2">
Draft sent partial received. Download vendor PDFs, record receipts.
</p>
</Link>
</section>
{editOpen && (
@@ -140,9 +140,19 @@ export default function PartDetailClient({
</span>
}
actions={
<Button variant="secondary" onClick={() => setEditOpen(true)}>
Edit part
</Button>
<div className="flex items-center gap-2">
<a
href={`/api/v1/parts/${part.id}/travelers.pdf`}
target="_blank"
rel="noopener"
className="inline-flex items-center rounded-md bg-white border border-slate-300 text-slate-900 text-sm px-3 py-1.5 hover:border-slate-900"
>
Print travelers (PDF)
</a>
<Button variant="secondary" onClick={() => setEditOpen(true)}>
Edit part
</Button>
</div>
}
/>
@@ -328,6 +338,16 @@ function OperationsSection({
<Button variant="ghost" size="sm" onClick={() => setQrFor(op)} disabled={busyId !== null}>
QR
</Button>
<a
href={`/api/v1/operations/${op.id}/card.pdf`}
target="_blank"
rel="noopener"
className={`inline-flex items-center rounded-md px-2 py-1 text-xs text-slate-600 hover:text-slate-900 hover:underline ${
busyId !== null ? "pointer-events-none opacity-50" : ""
}`}
>
Print
</a>
<Button variant="ghost" size="sm" onClick={() => setEdit(op)} disabled={busyId !== null}>
Edit
</Button>
@@ -0,0 +1,290 @@
"use client";
import Link from "next/link";
import { useState } from "react";
import { useRouter } from "next/navigation";
import {
Badge,
Button,
Card,
ErrorBanner,
Field,
Input,
Modal,
PageHeader,
Textarea,
} from "@/components/ui";
import { apiFetch, ApiClientError } from "@/lib/client-api";
export interface FastenerRow {
id: string;
partNumber: string;
description: string;
qty: number;
supplier: string | null;
unitCost: number | null;
notes: string | null;
onOrder: number;
received: number;
remaining: number;
unresolved: number;
}
export default function FastenersClient({
project,
initial,
}: {
project: { id: string; code: string; name: string };
initial: FastenerRow[];
}) {
const router = useRouter();
const [newOpen, setNewOpen] = useState(false);
const [edit, setEdit] = useState<FastenerRow | null>(null);
return (
<div className="mx-auto max-w-6xl px-4 py-8">
<nav className="mb-3 text-sm text-slate-500">
<Link href="/admin/projects" className="hover:underline">
Projects
</Link>
<span className="mx-1"></span>
<Link href={`/admin/projects/${project.id}`} className="hover:underline">
{project.code}
</Link>
<span className="mx-1"></span>
<span>Fasteners</span>
</nav>
<PageHeader
title={<span>Fasteners {project.code}</span>}
description={
<span className="text-slate-500">
Parts that get bought, not built. Lines roll up into purchase order drafts.
</span>
}
actions={
<div className="flex items-center gap-2">
<Link
href={`/admin/projects/${project.id}/purchase-orders`}
className="inline-flex items-center rounded-md bg-white border border-slate-300 text-slate-900 text-sm px-3 py-1.5 hover:border-slate-900"
>
Purchase orders
</Link>
<Button onClick={() => setNewOpen(true)}>Add fastener</Button>
</div>
}
/>
<Card>
<table className="w-full text-sm">
<thead className="bg-slate-50 text-left text-slate-600 border-b border-slate-200">
<tr>
<th className="px-4 py-2 font-medium">Part #</th>
<th className="px-4 py-2 font-medium">Description</th>
<th className="px-4 py-2 font-medium">Supplier</th>
<th className="px-4 py-2 font-medium text-right">Qty</th>
<th className="px-4 py-2 font-medium text-right">On order</th>
<th className="px-4 py-2 font-medium text-right">Received</th>
<th className="px-4 py-2 font-medium text-right">Unit cost</th>
<th className="px-4 py-2"></th>
</tr>
</thead>
<tbody>
{initial.map((f) => (
<tr key={f.id} className="border-b border-slate-100 last:border-0">
<td className="px-4 py-3 font-mono text-slate-700">{f.partNumber}</td>
<td className="px-4 py-3">
<div className="font-medium">{f.description}</div>
{f.notes ? (
<div className="text-xs text-slate-500 line-clamp-2">{f.notes}</div>
) : null}
</td>
<td className="px-4 py-3 text-slate-600">{f.supplier ?? "—"}</td>
<td className="px-4 py-3 text-right tabular-nums">{f.qty}</td>
<td className="px-4 py-3 text-right tabular-nums">
{f.onOrder}
{f.unresolved > 0 ? (
<Badge tone="amber" className="ml-1">
{f.unresolved} to PO
</Badge>
) : null}
</td>
<td className="px-4 py-3 text-right tabular-nums">
{f.received}
{f.remaining === 0 && f.received > 0 ? (
<Badge tone="green" className="ml-1">
full
</Badge>
) : null}
</td>
<td className="px-4 py-3 text-right tabular-nums">
{f.unitCost != null ? f.unitCost.toFixed(2) : "—"}
</td>
<td className="px-4 py-3 text-right">
<Button variant="ghost" size="sm" onClick={() => setEdit(f)}>
Edit
</Button>
</td>
</tr>
))}
{initial.length === 0 && (
<tr>
<td colSpan={8} className="px-4 py-10 text-center text-slate-500">
No fasteners yet. Add the bolts, rivets, inserts, etc. that need to be purchased for this project.
</td>
</tr>
)}
</tbody>
</table>
</Card>
{newOpen && (
<FastenerModal
projectId={project.id}
onClose={() => setNewOpen(false)}
onSaved={() => {
setNewOpen(false);
router.refresh();
}}
/>
)}
{edit && (
<FastenerModal
projectId={project.id}
fastener={edit}
onClose={() => setEdit(null)}
onSaved={() => {
setEdit(null);
router.refresh();
}}
onDeleted={() => {
setEdit(null);
router.refresh();
}}
/>
)}
</div>
);
}
function FastenerModal({
projectId,
fastener,
onClose,
onSaved,
onDeleted,
}: {
projectId: string;
fastener?: FastenerRow;
onClose: () => void;
onSaved: () => void;
onDeleted?: () => void;
}) {
const editing = !!fastener;
const [partNumber, setPartNumber] = useState(fastener?.partNumber ?? "");
const [description, setDescription] = useState(fastener?.description ?? "");
const [qty, setQty] = useState(String(fastener?.qty ?? 1));
const [supplier, setSupplier] = useState(fastener?.supplier ?? "");
const [unitCost, setUnitCost] = useState(fastener?.unitCost != null ? String(fastener.unitCost) : "");
const [notes, setNotes] = useState(fastener?.notes ?? "");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
async function submit(e: React.FormEvent) {
e.preventDefault();
setBusy(true);
setError(null);
try {
const payload = {
partNumber,
description,
qty: Number(qty),
supplier: supplier || null,
unitCost: unitCost ? Number(unitCost) : null,
notes: notes || null,
};
if (editing) {
await apiFetch(`/api/v1/fasteners/${fastener!.id}`, {
method: "PATCH",
body: JSON.stringify(payload),
});
} else {
await apiFetch(`/api/v1/projects/${projectId}/fasteners`, {
method: "POST",
body: JSON.stringify(payload),
});
}
onSaved();
} catch (err) {
setError(err instanceof ApiClientError ? err.message : "Save failed");
setBusy(false);
}
}
async function remove() {
if (!fastener || !onDeleted) return;
if (!confirm(`Delete fastener ${fastener.partNumber}?`)) return;
setBusy(true);
setError(null);
try {
await apiFetch(`/api/v1/fasteners/${fastener.id}`, { method: "DELETE" });
onDeleted();
} catch (err) {
setError(err instanceof ApiClientError ? err.message : "Delete failed");
setBusy(false);
}
}
return (
<Modal
open
onClose={onClose}
title={editing ? `Edit ${fastener!.partNumber}` : "New fastener"}
footer={
<>
{editing && onDeleted ? (
<Button variant="danger" size="sm" onClick={remove} disabled={busy}>
Delete
</Button>
) : null}
<div className="flex-1" />
<Button variant="secondary" onClick={onClose} disabled={busy}>
Cancel
</Button>
<Button type="submit" form="fastener-form" disabled={busy}>
{busy ? "Saving…" : editing ? "Save" : "Create"}
</Button>
</>
}
>
<form id="fastener-form" onSubmit={submit} className="space-y-4">
<Field label="Part number" required>
<Input value={partNumber} onChange={(e) => setPartNumber(e.target.value)} required autoFocus />
</Field>
<Field label="Description" required>
<Input value={description} onChange={(e) => setDescription(e.target.value)} required />
</Field>
<div className="grid grid-cols-2 gap-3">
<Field label="Quantity" required>
<Input type="number" min={1} value={qty} onChange={(e) => setQty(e.target.value)} required />
</Field>
<Field label="Unit cost" hint="Per-each. Overridable on the PO line.">
<Input
type="number"
min={0}
step="0.01"
value={unitCost}
onChange={(e) => setUnitCost(e.target.value)}
/>
</Field>
</div>
<Field label="Supplier">
<Input value={supplier} onChange={(e) => setSupplier(e.target.value)} />
</Field>
<Field label="Notes">
<Textarea value={notes} onChange={(e) => setNotes(e.target.value)} />
</Field>
<ErrorBanner message={error} />
</form>
</Modal>
);
}
@@ -0,0 +1,56 @@
import { notFound } from "next/navigation";
import { prisma } from "@/lib/prisma";
import FastenersClient from "./FastenersClient";
export const dynamic = "force-dynamic";
export default async function FastenersPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const project = await prisma.project.findUnique({
where: { id },
select: { id: true, code: true, name: true },
});
if (!project) notFound();
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 } },
},
},
},
});
// Same rollup the GET /fasteners API does — keep it inline here so the
// initial SSR paint already has remaining/on-order numbers without a
// client-side round-trip.
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;
}
return {
id: f.id,
partNumber: f.partNumber,
description: f.description,
qty: f.qty,
supplier: f.supplier,
unitCost: f.unitCost,
notes: f.notes,
onOrder,
received,
remaining: Math.max(0, f.qty - received),
unresolved: Math.max(0, f.qty - onOrder),
};
});
return <FastenersClient project={project} initial={rows} />;
}
@@ -0,0 +1,380 @@
"use client";
import Link from "next/link";
import { useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import {
Badge,
Button,
Card,
ErrorBanner,
Field,
Input,
Modal,
PageHeader,
Textarea,
} from "@/components/ui";
import { apiFetch, ApiClientError } from "@/lib/client-api";
export interface PORow {
id: string;
vendor: string;
status: string;
createdAt: string;
sentAt: string | null;
receivedAt: string | null;
notes: string | null;
lineCount: number;
totalQty: number;
totalReceived: number;
totalCost: number;
}
export interface FastenerOption {
id: string;
partNumber: string;
description: string;
supplier: string | null;
unitCost: number | null;
qty: number;
unresolved: number; // qty - (on-order on non-cancelled POs)
}
const STATUS_TONE: Record<string, "slate" | "blue" | "green" | "amber" | "red"> = {
draft: "slate",
sent: "blue",
partial: "amber",
received: "green",
cancelled: "red",
};
function formatDate(iso: string | null) {
if (!iso) return "—";
return new Date(iso).toLocaleDateString(undefined, {
year: "numeric",
month: "short",
day: "numeric",
});
}
export default function PurchaseOrdersClient({
project,
initial,
fastenerOptions,
}: {
project: { id: string; code: string; name: string };
initial: PORow[];
fastenerOptions: FastenerOption[];
}) {
const router = useRouter();
const [newOpen, setNewOpen] = useState(false);
return (
<div className="mx-auto max-w-6xl px-4 py-8">
<nav className="mb-3 text-sm text-slate-500">
<Link href="/admin/projects" className="hover:underline">
Projects
</Link>
<span className="mx-1"></span>
<Link href={`/admin/projects/${project.id}`} className="hover:underline">
{project.code}
</Link>
<span className="mx-1"></span>
<span>Purchase orders</span>
</nav>
<PageHeader
title={<span>Purchase orders {project.code}</span>}
description={
<span className="text-slate-500">
Draft sent partial received. One PO per vendor, cancel anything pre-terminal.
</span>
}
actions={
<div className="flex items-center gap-2">
<Link
href={`/admin/projects/${project.id}/fasteners`}
className="inline-flex items-center rounded-md bg-white border border-slate-300 text-slate-900 text-sm px-3 py-1.5 hover:border-slate-900"
>
Fasteners
</Link>
<Button
onClick={() => setNewOpen(true)}
disabled={fastenerOptions.length === 0}
>
New PO
</Button>
</div>
}
/>
<Card>
<table className="w-full text-sm">
<thead className="bg-slate-50 text-left text-slate-600 border-b border-slate-200">
<tr>
<th className="px-4 py-2 font-medium">Vendor</th>
<th className="px-4 py-2 font-medium">Status</th>
<th className="px-4 py-2 font-medium">Created</th>
<th className="px-4 py-2 font-medium">Sent</th>
<th className="px-4 py-2 font-medium text-right">Lines</th>
<th className="px-4 py-2 font-medium text-right">Qty (recv/total)</th>
<th className="px-4 py-2 font-medium text-right">Total</th>
<th className="px-4 py-2"></th>
</tr>
</thead>
<tbody>
{initial.map((po) => (
<tr key={po.id} className="border-b border-slate-100 last:border-0">
<td className="px-4 py-3 font-medium">{po.vendor}</td>
<td className="px-4 py-3">
<Badge tone={STATUS_TONE[po.status] ?? "slate"}>{po.status}</Badge>
</td>
<td className="px-4 py-3 text-slate-600">{formatDate(po.createdAt)}</td>
<td className="px-4 py-3 text-slate-600">{formatDate(po.sentAt)}</td>
<td className="px-4 py-3 text-right tabular-nums">{po.lineCount}</td>
<td className="px-4 py-3 text-right tabular-nums">
{po.totalReceived}/{po.totalQty}
</td>
<td className="px-4 py-3 text-right tabular-nums">
{po.totalCost > 0 ? po.totalCost.toFixed(2) : "—"}
</td>
<td className="px-4 py-3 text-right">
<Link
href={`/admin/projects/${project.id}/purchase-orders/${po.id}`}
className="text-sm text-blue-600 hover:underline"
>
Open
</Link>
</td>
</tr>
))}
{initial.length === 0 && (
<tr>
<td colSpan={8} className="px-4 py-10 text-center text-slate-500">
No purchase orders yet.
{fastenerOptions.length === 0 ? (
<>
{" "}
Add fasteners first (
<Link
href={`/admin/projects/${project.id}/fasteners`}
className="text-blue-600 hover:underline"
>
go to fasteners
</Link>
).
</>
) : (
" Start a draft to build a vendor PO."
)}
</td>
</tr>
)}
</tbody>
</table>
</Card>
{newOpen && (
<NewPOModal
projectId={project.id}
fastenerOptions={fastenerOptions}
onClose={() => setNewOpen(false)}
onSaved={(poId) => {
setNewOpen(false);
router.push(`/admin/projects/${project.id}/purchase-orders/${poId}`);
}}
/>
)}
</div>
);
}
interface LineDraft {
fastenerId: string;
qty: string;
unitCost: string;
}
function NewPOModal({
projectId,
fastenerOptions,
onClose,
onSaved,
}: {
projectId: string;
fastenerOptions: FastenerOption[];
onClose: () => void;
onSaved: (poId: string) => void;
}) {
// Pre-seed the draft with lines for every fastener that still has an
// unresolved (unordered) quantity, so the common case ("put everything I
// haven't bought yet on one PO") is zero-click.
const seeded = useMemo<LineDraft[]>(
() =>
fastenerOptions
.filter((f) => f.unresolved > 0)
.map((f) => ({
fastenerId: f.id,
qty: String(f.unresolved),
unitCost: f.unitCost != null ? String(f.unitCost) : "",
})),
[fastenerOptions],
);
const [vendor, setVendor] = useState("");
const [notes, setNotes] = useState("");
const [lines, setLines] = useState<LineDraft[]>(
seeded.length > 0 ? seeded : [{ fastenerId: "", qty: "1", unitCost: "" }],
);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const total = lines.reduce((a, l) => {
const q = Number(l.qty) || 0;
const c = Number(l.unitCost) || 0;
return a + q * c;
}, 0);
function updateLine(i: number, patch: Partial<LineDraft>) {
setLines((prev) => prev.map((l, idx) => (idx === i ? { ...l, ...patch } : l)));
}
function addLine() {
setLines((prev) => [...prev, { fastenerId: "", qty: "1", unitCost: "" }]);
}
function removeLine(i: number) {
setLines((prev) => prev.filter((_, idx) => idx !== i));
}
async function submit(e: React.FormEvent) {
e.preventDefault();
setError(null);
const clean = lines
.filter((l) => l.fastenerId)
.map((l) => ({
fastenerId: l.fastenerId,
qty: Number(l.qty),
unitCost: l.unitCost ? Number(l.unitCost) : null,
}));
if (clean.length === 0) {
setError("Add at least one fastener line");
return;
}
setBusy(true);
try {
const res = await apiFetch<{ purchaseOrder: { id: string } }>(
`/api/v1/projects/${projectId}/purchase-orders`,
{
method: "POST",
body: JSON.stringify({ vendor, notes: notes || null, lines: clean }),
},
);
onSaved(res.purchaseOrder.id);
} catch (err) {
setError(err instanceof ApiClientError ? err.message : "Create failed");
setBusy(false);
}
}
return (
<Modal
open
onClose={onClose}
title="New purchase order"
footer={
<>
<div className="flex-1" />
<Button variant="secondary" onClick={onClose} disabled={busy}>
Cancel
</Button>
<Button type="submit" form="po-form" disabled={busy}>
{busy ? "Creating…" : "Create draft"}
</Button>
</>
}
>
<form id="po-form" onSubmit={submit} className="space-y-4">
<Field label="Vendor" required>
<Input value={vendor} onChange={(e) => setVendor(e.target.value)} required autoFocus />
</Field>
<Field label="Notes">
<Textarea value={notes} onChange={(e) => setNotes(e.target.value)} />
</Field>
<div>
<div className="flex items-center justify-between mb-2">
<h3 className="font-semibold text-sm">Lines</h3>
<Button type="button" variant="secondary" size="sm" onClick={addLine}>
+ Line
</Button>
</div>
<div className="space-y-2">
{lines.map((l, i) => {
const f = fastenerOptions.find((x) => x.id === l.fastenerId);
return (
<div key={i} className="grid grid-cols-12 gap-2 items-start">
<select
className="col-span-6 rounded-md border border-slate-300 px-2 py-1.5 text-sm"
value={l.fastenerId}
onChange={(e) => {
const next = fastenerOptions.find((x) => x.id === e.target.value);
updateLine(i, {
fastenerId: e.target.value,
qty: next && next.unresolved > 0 ? String(next.unresolved) : l.qty,
unitCost:
next?.unitCost != null && !l.unitCost ? String(next.unitCost) : l.unitCost,
});
}}
>
<option value=""> select fastener </option>
{fastenerOptions.map((f2) => (
<option key={f2.id} value={f2.id}>
{f2.partNumber} {f2.description}
{f2.supplier ? ` (${f2.supplier})` : ""}
</option>
))}
</select>
<Input
className="col-span-2"
type="number"
min={1}
value={l.qty}
onChange={(e) => updateLine(i, { qty: e.target.value })}
placeholder="Qty"
/>
<Input
className="col-span-3"
type="number"
min={0}
step="0.01"
value={l.unitCost}
onChange={(e) => updateLine(i, { unitCost: e.target.value })}
placeholder="Unit cost"
/>
<button
type="button"
className="col-span-1 text-slate-400 hover:text-red-600 text-sm"
onClick={() => removeLine(i)}
aria-label="Remove line"
>
</button>
{f && f.unresolved > 0 && Number(l.qty) !== f.unresolved ? (
<div className="col-span-12 text-[11px] text-amber-700 -mt-1">
Unresolved need for {f.partNumber}: {f.unresolved}.
</div>
) : null}
</div>
);
})}
</div>
{total > 0 ? (
<div className="mt-3 text-right text-sm text-slate-600">
Estimated total: <span className="font-semibold">{total.toFixed(2)}</span>
</div>
) : null}
</div>
<ErrorBanner message={error} />
</form>
</Modal>
);
}
@@ -0,0 +1,309 @@
"use client";
import Link from "next/link";
import { useState } from "react";
import { useRouter } from "next/navigation";
import {
Badge,
Button,
Card,
ErrorBanner,
Input,
PageHeader,
} from "@/components/ui";
import { apiFetch, ApiClientError } from "@/lib/client-api";
interface POInfo {
id: string;
vendor: string;
status: string;
createdAt: string;
sentAt: string | null;
receivedAt: string | null;
notes: string | null;
}
interface LineRow {
id: string;
fastener: {
id: string;
partNumber: string;
description: string;
supplier: string | null;
unitCost: number | null;
};
qty: number;
receivedQty: number;
unitCost: number | null;
}
const STATUS_TONE: Record<string, "slate" | "blue" | "green" | "amber" | "red"> = {
draft: "slate",
sent: "blue",
partial: "amber",
received: "green",
cancelled: "red",
};
function formatDate(iso: string | null) {
if (!iso) return "—";
return new Date(iso).toLocaleDateString(undefined, {
year: "numeric",
month: "short",
day: "numeric",
});
}
export default function POClient({
project,
po,
lines,
}: {
project: { id: string; code: string; name: string };
po: POInfo;
lines: LineRow[];
}) {
const router = useRouter();
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
// Per-line receive input. Keyed by line id so re-renders don't clobber state.
const [receipts, setReceipts] = useState<Record<string, string>>({});
const total = lines.reduce((a, l) => {
const cost = l.unitCost ?? l.fastener.unitCost ?? 0;
return a + cost * l.qty;
}, 0);
const totalReceived = lines.reduce((a, l) => a + l.receivedQty, 0);
const totalQty = lines.reduce((a, l) => a + l.qty, 0);
async function changeStatus(next: string) {
if (!confirm(`Move PO to "${next}"?`)) return;
setBusy(true);
setError(null);
try {
await apiFetch(`/api/v1/purchase-orders/${po.id}/status`, {
method: "POST",
body: JSON.stringify({ status: next }),
});
router.refresh();
} catch (err) {
setError(err instanceof ApiClientError ? err.message : "Status change failed");
} finally {
setBusy(false);
}
}
async function submitReceipts() {
const payload = Object.entries(receipts)
.map(([lineId, qty]) => ({ lineId, qty: Number(qty) }))
.filter((r) => r.qty > 0);
if (payload.length === 0) {
setError("Enter at least one receipt quantity");
return;
}
setBusy(true);
setError(null);
try {
await apiFetch(`/api/v1/purchase-orders/${po.id}/receive`, {
method: "POST",
body: JSON.stringify({ receipts: payload }),
});
setReceipts({});
router.refresh();
} catch (err) {
setError(err instanceof ApiClientError ? err.message : "Receipt failed");
} finally {
setBusy(false);
}
}
async function deleteDraft() {
if (!confirm("Delete this draft PO? This can't be undone.")) return;
setBusy(true);
setError(null);
try {
await apiFetch(`/api/v1/purchase-orders/${po.id}`, { method: "DELETE" });
router.push(`/admin/projects/${project.id}/purchase-orders`);
} catch (err) {
setError(err instanceof ApiClientError ? err.message : "Delete failed");
setBusy(false);
}
}
// Which state transitions are offered here — mirror of PO_TRANSITIONS in the API.
const canSend = po.status === "draft";
const canCancel = po.status !== "received" && po.status !== "cancelled";
const canReceive = po.status === "sent" || po.status === "partial";
const canDeleteDraft = po.status === "draft";
return (
<div className="mx-auto max-w-5xl px-4 py-8">
<nav className="mb-3 text-sm text-slate-500">
<Link href="/admin/projects" className="hover:underline">
Projects
</Link>
<span className="mx-1"></span>
<Link href={`/admin/projects/${project.id}`} className="hover:underline">
{project.code}
</Link>
<span className="mx-1"></span>
<Link
href={`/admin/projects/${project.id}/purchase-orders`}
className="hover:underline"
>
POs
</Link>
<span className="mx-1"></span>
<span className="font-mono text-xs">{po.id.slice(0, 8)}</span>
</nav>
<PageHeader
title={
<span className="flex items-center gap-3">
<span>{po.vendor}</span>
<Badge tone={STATUS_TONE[po.status] ?? "slate"}>{po.status}</Badge>
</span>
}
description={
<span className="flex flex-wrap items-center gap-2 text-slate-500">
<span>PO {po.id.slice(0, 8).toUpperCase()}</span>
<span className="text-slate-400">·</span>
<span>Created {formatDate(po.createdAt)}</span>
<span className="text-slate-400">·</span>
<span>Sent {formatDate(po.sentAt)}</span>
<span className="text-slate-400">·</span>
<span>Received {formatDate(po.receivedAt)}</span>
</span>
}
actions={
<div className="flex flex-wrap items-center gap-2">
<a
href={`/api/v1/purchase-orders/${po.id}/pdf`}
target="_blank"
rel="noopener"
className="inline-flex items-center rounded-md bg-white border border-slate-300 text-slate-900 text-sm px-3 py-1.5 hover:border-slate-900"
>
Download PDF
</a>
{canSend ? (
<Button onClick={() => changeStatus("sent")} disabled={busy}>
Mark sent
</Button>
) : null}
{canCancel ? (
<Button variant="secondary" onClick={() => changeStatus("cancelled")} disabled={busy}>
Cancel PO
</Button>
) : null}
{canDeleteDraft ? (
<Button variant="danger" size="sm" onClick={deleteDraft} disabled={busy}>
Delete draft
</Button>
) : null}
</div>
}
/>
{po.notes ? (
<Card className="mb-4">
<div className="p-4 text-sm text-slate-700 whitespace-pre-wrap">{po.notes}</div>
</Card>
) : null}
<ErrorBanner message={error} />
<Card>
<table className="w-full text-sm">
<thead className="bg-slate-50 text-left text-slate-600 border-b border-slate-200">
<tr>
<th className="px-4 py-2 font-medium">Part #</th>
<th className="px-4 py-2 font-medium">Description</th>
<th className="px-4 py-2 font-medium text-right">Qty</th>
<th className="px-4 py-2 font-medium text-right">Received</th>
<th className="px-4 py-2 font-medium text-right">Unit</th>
<th className="px-4 py-2 font-medium text-right">Line total</th>
{canReceive ? (
<th className="px-4 py-2 font-medium text-right">Receive +</th>
) : null}
</tr>
</thead>
<tbody>
{lines.map((l) => {
const effectiveCost = l.unitCost ?? l.fastener.unitCost ?? null;
const lineTotal = effectiveCost !== null ? effectiveCost * l.qty : null;
const remaining = l.qty - l.receivedQty;
const full = remaining === 0;
return (
<tr key={l.id} className="border-b border-slate-100 last:border-0">
<td className="px-4 py-3 font-mono text-slate-700">
{l.fastener.partNumber}
</td>
<td className="px-4 py-3">
<div className="font-medium">{l.fastener.description}</div>
{l.fastener.supplier ? (
<div className="text-xs text-slate-500">{l.fastener.supplier}</div>
) : null}
</td>
<td className="px-4 py-3 text-right tabular-nums">{l.qty}</td>
<td className="px-4 py-3 text-right tabular-nums">
{l.receivedQty}
{full && l.receivedQty > 0 ? (
<Badge tone="green" className="ml-1">
full
</Badge>
) : null}
</td>
<td className="px-4 py-3 text-right tabular-nums">
{effectiveCost !== null ? effectiveCost.toFixed(2) : "—"}
</td>
<td className="px-4 py-3 text-right tabular-nums">
{lineTotal !== null ? lineTotal.toFixed(2) : "—"}
</td>
{canReceive ? (
<td className="px-4 py-3 text-right">
<Input
type="number"
min={0}
max={remaining}
value={receipts[l.id] ?? ""}
onChange={(e) =>
setReceipts((prev) => ({ ...prev, [l.id]: e.target.value }))
}
placeholder={remaining.toString()}
className="w-20 text-right"
disabled={full || busy}
/>
</td>
) : null}
</tr>
);
})}
</tbody>
<tfoot className="bg-slate-50 border-t border-slate-200">
<tr>
<td className="px-4 py-3" colSpan={2}>
<span className="text-slate-500 text-xs uppercase tracking-wide">Totals</span>
</td>
<td className="px-4 py-3 text-right tabular-nums font-medium">{totalQty}</td>
<td className="px-4 py-3 text-right tabular-nums font-medium">{totalReceived}</td>
<td></td>
<td className="px-4 py-3 text-right tabular-nums font-medium">
{total > 0 ? total.toFixed(2) : "—"}
</td>
{canReceive ? <td></td> : null}
</tr>
</tfoot>
</table>
</Card>
{canReceive ? (
<div className="mt-4 flex justify-end">
<Button onClick={submitReceipts} disabled={busy}>
Record receipts
</Button>
</div>
) : null}
</div>
);
}
@@ -0,0 +1,60 @@
import { notFound } from "next/navigation";
import { prisma } from "@/lib/prisma";
import POClient from "./POClient";
export const dynamic = "force-dynamic";
export default async function POPage({
params,
}: {
params: Promise<{ id: string; poId: string }>;
}) {
const { id: projectId, poId } = await params;
const project = await prisma.project.findUnique({
where: { id: projectId },
select: { id: true, code: true, name: true },
});
if (!project) notFound();
const po = await prisma.purchaseOrder.findUnique({
where: { id: poId },
include: {
lines: {
include: {
fastener: {
select: {
id: true,
partNumber: true,
description: true,
supplier: true,
unitCost: true,
},
},
},
},
},
});
if (!po || po.projectId !== projectId) notFound();
return (
<POClient
project={project}
po={{
id: po.id,
vendor: po.vendor,
status: po.status,
createdAt: po.createdAt.toISOString(),
sentAt: po.sentAt?.toISOString() ?? null,
receivedAt: po.receivedAt?.toISOString() ?? null,
notes: po.notes,
}}
lines={po.lines.map((l) => ({
id: l.id,
fastener: l.fastener,
qty: l.qty,
receivedQty: l.receivedQty,
unitCost: l.unitCost,
}))}
/>
);
}
@@ -0,0 +1,82 @@
import { notFound } from "next/navigation";
import { prisma } from "@/lib/prisma";
import PurchaseOrdersClient from "./PurchaseOrdersClient";
export const dynamic = "force-dynamic";
export default async function POsPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const project = await prisma.project.findUnique({
where: { id },
select: { id: true, code: true, name: true },
});
if (!project) notFound();
const pos = await prisma.purchaseOrder.findMany({
where: { projectId: id },
orderBy: [{ createdAt: "desc" }],
include: {
lines: {
select: {
qty: true,
receivedQty: true,
unitCost: true,
fastener: { select: { unitCost: true } },
},
},
},
});
// Same "unresolved" suggestion for new drafts that /fasteners uses.
const fasteners = await prisma.fastener.findMany({
where: { projectId: id },
orderBy: [{ supplier: "asc" }, { partNumber: "asc" }],
include: {
poLines: {
select: { qty: true, po: { select: { status: true } } },
},
},
});
const fastenerOptions = fasteners.map((f) => {
let onOrder = 0;
for (const l of f.poLines) {
if (l.po.status === "cancelled") continue;
onOrder += l.qty;
}
return {
id: f.id,
partNumber: f.partNumber,
description: f.description,
supplier: f.supplier,
unitCost: f.unitCost,
qty: f.qty,
unresolved: Math.max(0, f.qty - onOrder),
};
});
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.toISOString(),
sentAt: po.sentAt?.toISOString() ?? null,
receivedAt: po.receivedAt?.toISOString() ?? null,
notes: po.notes,
lineCount: po.lines.length,
totalQty,
totalReceived,
totalCost,
};
});
return (
<PurchaseOrdersClient project={project} initial={rows} fastenerOptions={fastenerOptions} />
);
}
+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);
}
}