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