This commit is contained in:
@@ -4,13 +4,16 @@ A single-container, self-hosted Manufacturing Resource Planning (MRP) app built
|
||||
|
||||
## Status
|
||||
|
||||
Steps 1 – 3 of the build plan are in this repo:
|
||||
Steps 1 – 6 of the build plan are in this repo:
|
||||
|
||||
- **1.** Scaffold + auth (admin email/password, operator name/4-digit PIN with 12 h device session, PIN lockout, audited sessions).
|
||||
- **2.** Admin CRUD (users, machines, operation templates, projects / assemblies / parts) with content-addressed STEP / PDF / DXF / SVG file uploads.
|
||||
- **3.** Operation authoring with per-operation QR tokens (192-bit, base64url).
|
||||
- **4.** Operator scan flow — phone scan resolves `/op/scan/<token>`, single-claim enforced at DB level, Start / Pause / Done with inline QC for steps that require it, TimeLog rows for every claim.
|
||||
- **5.** PDF traveler generation — per-operation card + per-part cover sheet with the full operation list and file manifest. Printed via `pdf-lib` (no native deps).
|
||||
- **6.** Fasteners + purchase orders — per-project BOM of fasteners with unresolved-need rollups, PO lifecycle (`draft → sent → partial → received`, or `cancelled`), per-line receipt entry with auto-advance, and vendor-ready PDF downloads.
|
||||
|
||||
Planned (not yet shipped): operator scan flow → PDF traveler print → fasteners & POs → dashboard → STEP viewer → QC records → OpenAPI docs + backups. See [`docs/BUILD-PLAN.md`](docs/BUILD-PLAN.md).
|
||||
Planned (not yet shipped): dashboard → STEP viewer → dedicated QC operations → OpenAPI docs + backups. See [`docs/BUILD-PLAN.md`](docs/BUILD-PLAN.md).
|
||||
|
||||
## Core concepts
|
||||
|
||||
|
||||
@@ -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">
|
||||
<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>
|
||||
<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">Fastener authoring lands in step 6.</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>
|
||||
<Card>
|
||||
<div className="p-4">
|
||||
<h3 className="font-semibold mb-1">Purchase orders</h3>
|
||||
<p className="text-sm text-slate-500 mb-3">
|
||||
<p className="text-sm text-slate-500 mt-1">
|
||||
{project.poCount} PO{project.poCount === 1 ? "" : "s"}
|
||||
</p>
|
||||
<p className="text-xs text-slate-400">PO lifecycle and PDFs land in step 6.</p>
|
||||
</div>
|
||||
</Card>
|
||||
<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={
|
||||
<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} />
|
||||
);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
+9
-1
@@ -207,9 +207,11 @@ export function Modal({
|
||||
export function Badge({
|
||||
children,
|
||||
tone = "slate",
|
||||
className,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
tone?: "slate" | "green" | "amber" | "red" | "blue";
|
||||
className?: string;
|
||||
}) {
|
||||
const tones: Record<string, string> = {
|
||||
slate: "bg-slate-100 text-slate-700",
|
||||
@@ -219,7 +221,13 @@ export function Badge({
|
||||
blue: "bg-blue-100 text-blue-700",
|
||||
};
|
||||
return (
|
||||
<span className={cx("inline-flex items-center rounded-md px-2 py-0.5 text-xs font-medium", tones[tone])}>
|
||||
<span
|
||||
className={cx(
|
||||
"inline-flex items-center rounded-md px-2 py-0.5 text-xs font-medium",
|
||||
tones[tone],
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</span>
|
||||
);
|
||||
|
||||
+6
-6
@@ -4,12 +4,12 @@ The roadmap agreed at project kickoff. Each step is committed separately so the
|
||||
|
||||
| # | Step | Status |
|
||||
| - | ---- | ------ |
|
||||
| 1 | Repo scaffold, Dockerfile, Prisma schema, auth (admin email/password, operator PIN, 12h session) | **In progress** |
|
||||
| 2 | Admin CRUD: Machines, Operation Templates, Projects → Assemblies → Parts, file uploads | planned |
|
||||
| 3 | Operation authoring (template or ad-hoc) + QR token generation | planned |
|
||||
| 4 | Operator scan flow: claim → start → units/notes → QC prompt → close | planned |
|
||||
| 5 | PDF generation: per-operation card + per-part cover sheet | planned |
|
||||
| 6 | Fasteners + PO (PDF + lifecycle: draft → sent → partial → received) | planned |
|
||||
| 1 | Repo scaffold, Dockerfile, Prisma schema, auth (admin email/password, operator PIN, 12h session) | **done** |
|
||||
| 2 | Admin CRUD: Machines, Operation Templates, Projects → Assemblies → Parts, file uploads | **done** |
|
||||
| 3 | Operation authoring (template or ad-hoc) + QR token generation | **done** |
|
||||
| 4 | Operator scan flow: claim → start → units/notes → QC prompt → close | **done** |
|
||||
| 5 | PDF generation: per-operation card + per-part cover sheet | **done** |
|
||||
| 6 | Fasteners + PO (PDF + lifecycle: draft → sent → partial → received) | **done** |
|
||||
| 7 | Admin dashboard (WIP, overdue, plan-vs-actual) + audit log viewer | planned |
|
||||
| 8 | In-browser STEP viewer + server-side thumbnails | planned |
|
||||
| 9 | QC records (inline checkboxes + dedicated QC operation type) | planned |
|
||||
|
||||
+803
@@ -0,0 +1,803 @@
|
||||
import { PDFDocument, StandardFonts, rgb, type PDFFont, type PDFPage } from "pdf-lib";
|
||||
import { renderQrPngBuffer, scanUrlForToken } from "@/lib/qr";
|
||||
|
||||
/**
|
||||
* Traveler PDF generation. Shipped as pdf-lib (pure JS, no system deps) so
|
||||
* the Docker image stays slim. Two public entry points:
|
||||
*
|
||||
* - renderOperationCard(op) -> single Letter page, big QR
|
||||
* - renderPartTravelers({cover, ops}) -> cover sheet + one card per op
|
||||
*
|
||||
* Everything else in this file is layout glue. Nothing here hits the DB — the
|
||||
* route handlers load the data and hand fully-denormalised structs down so
|
||||
* this module stays easy to unit-test later.
|
||||
*/
|
||||
|
||||
// Letter @ 72 dpi. Points (pt) are the native pdf-lib unit.
|
||||
const PAGE_WIDTH = 612;
|
||||
const PAGE_HEIGHT = 792;
|
||||
const MARGIN = 48; // 2/3"
|
||||
|
||||
export interface OperationCardData {
|
||||
project: { code: string; name: string };
|
||||
assembly: { code: string; name: string };
|
||||
part: { code: string; name: string; material: string | null; qty: number };
|
||||
operation: {
|
||||
id: string;
|
||||
sequence: number;
|
||||
name: string;
|
||||
qrToken: string;
|
||||
machineName: string | null;
|
||||
machineKind: string | null;
|
||||
settings: string | null;
|
||||
materialNotes: string | null;
|
||||
instructions: string | null;
|
||||
qcRequired: boolean;
|
||||
plannedMinutes: number | null;
|
||||
plannedUnits: number | null;
|
||||
};
|
||||
}
|
||||
|
||||
export interface PurchaseOrderPdfData {
|
||||
po: {
|
||||
id: string;
|
||||
vendor: string;
|
||||
status: string;
|
||||
createdAt: Date;
|
||||
sentAt: Date | null;
|
||||
notes: string | null;
|
||||
};
|
||||
project: { code: string; name: string };
|
||||
lines: {
|
||||
partNumber: string;
|
||||
description: string;
|
||||
supplier: string | null;
|
||||
qty: number;
|
||||
unitCost: number | null;
|
||||
}[];
|
||||
}
|
||||
|
||||
export interface PartCoverData {
|
||||
project: { code: string; name: string };
|
||||
assembly: { code: string; name: string };
|
||||
part: {
|
||||
code: string;
|
||||
name: string;
|
||||
material: string | null;
|
||||
qty: number;
|
||||
notes: string | null;
|
||||
};
|
||||
files: {
|
||||
label: string;
|
||||
file: { originalName: string; sizeBytes: number; sha256: string } | null;
|
||||
}[];
|
||||
operations: {
|
||||
sequence: number;
|
||||
name: string;
|
||||
machineName: string | null;
|
||||
qcRequired: boolean;
|
||||
qrToken: string;
|
||||
}[];
|
||||
}
|
||||
|
||||
/** Entry point: render a single operation card as a PDF byte array. */
|
||||
export async function renderOperationCard(data: OperationCardData): Promise<Uint8Array> {
|
||||
const doc = await PDFDocument.create();
|
||||
const fonts = await embedFonts(doc);
|
||||
const page = doc.addPage([PAGE_WIDTH, PAGE_HEIGHT]);
|
||||
await drawOperationCard(doc, page, fonts, data);
|
||||
return doc.save();
|
||||
}
|
||||
|
||||
/** Entry point: render a purchase order PDF for sending to a vendor. */
|
||||
export async function renderPurchaseOrder(data: PurchaseOrderPdfData): Promise<Uint8Array> {
|
||||
const doc = await PDFDocument.create();
|
||||
const fonts = await embedFonts(doc);
|
||||
const page = doc.addPage([PAGE_WIDTH, PAGE_HEIGHT]);
|
||||
drawPurchaseOrder(page, fonts, data);
|
||||
return doc.save();
|
||||
}
|
||||
|
||||
/** Entry point: cover sheet + every operation card, all in one PDF. */
|
||||
export async function renderPartTravelers(payload: {
|
||||
cover: PartCoverData;
|
||||
cards: OperationCardData[];
|
||||
}): Promise<Uint8Array> {
|
||||
const doc = await PDFDocument.create();
|
||||
const fonts = await embedFonts(doc);
|
||||
|
||||
const coverPage = doc.addPage([PAGE_WIDTH, PAGE_HEIGHT]);
|
||||
await drawCoverSheet(doc, coverPage, fonts, payload.cover);
|
||||
|
||||
for (const card of payload.cards) {
|
||||
const page = doc.addPage([PAGE_WIDTH, PAGE_HEIGHT]);
|
||||
await drawOperationCard(doc, page, fonts, card);
|
||||
}
|
||||
|
||||
return doc.save();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Layout helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
interface Fonts {
|
||||
regular: PDFFont;
|
||||
bold: PDFFont;
|
||||
mono: PDFFont;
|
||||
}
|
||||
|
||||
async function embedFonts(doc: PDFDocument): Promise<Fonts> {
|
||||
return {
|
||||
regular: await doc.embedFont(StandardFonts.Helvetica),
|
||||
bold: await doc.embedFont(StandardFonts.HelveticaBold),
|
||||
mono: await doc.embedFont(StandardFonts.Courier),
|
||||
};
|
||||
}
|
||||
|
||||
// pdf-lib uses a Y-up coordinate system anchored at the page's bottom-left.
|
||||
// We track the cursor from the top to keep drawing code readable; `top` is
|
||||
// the y-coordinate of the next line's baseline in pt.
|
||||
interface Cursor {
|
||||
top: number;
|
||||
}
|
||||
|
||||
function drawText(
|
||||
page: PDFPage,
|
||||
text: string,
|
||||
opts: { x: number; y: number; font: PDFFont; size: number; color?: ReturnType<typeof rgb> },
|
||||
): void {
|
||||
page.drawText(text, {
|
||||
x: opts.x,
|
||||
y: opts.y,
|
||||
font: opts.font,
|
||||
size: opts.size,
|
||||
color: opts.color ?? rgb(0.07, 0.09, 0.15),
|
||||
});
|
||||
}
|
||||
|
||||
// Break a long string into lines that fit a given width, honouring \n. We
|
||||
// measure in pt with the font's width table so it actually matches the output.
|
||||
function wrapLines(text: string, font: PDFFont, size: number, maxWidth: number): string[] {
|
||||
const out: string[] = [];
|
||||
for (const rawLine of text.split(/\r?\n/)) {
|
||||
if (rawLine.length === 0) {
|
||||
out.push("");
|
||||
continue;
|
||||
}
|
||||
const words = rawLine.split(/\s+/);
|
||||
let line = "";
|
||||
for (const word of words) {
|
||||
const candidate = line.length === 0 ? word : `${line} ${word}`;
|
||||
if (font.widthOfTextAtSize(candidate, size) <= maxWidth) {
|
||||
line = candidate;
|
||||
} else {
|
||||
if (line.length > 0) out.push(line);
|
||||
// Word itself overflows — hard-chop so we don't stall.
|
||||
if (font.widthOfTextAtSize(word, size) > maxWidth) {
|
||||
let chunk = "";
|
||||
for (const ch of word) {
|
||||
if (font.widthOfTextAtSize(chunk + ch, size) > maxWidth) {
|
||||
out.push(chunk);
|
||||
chunk = ch;
|
||||
} else {
|
||||
chunk += ch;
|
||||
}
|
||||
}
|
||||
line = chunk;
|
||||
} else {
|
||||
line = word;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (line.length > 0) out.push(line);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Operation card
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function drawOperationCard(
|
||||
doc: PDFDocument,
|
||||
page: PDFPage,
|
||||
fonts: Fonts,
|
||||
data: OperationCardData,
|
||||
): Promise<void> {
|
||||
const cursor: Cursor = { top: PAGE_HEIGHT - MARGIN };
|
||||
const contentWidth = PAGE_WIDTH - MARGIN * 2;
|
||||
|
||||
// --- Header strip: project / assembly ------------------------------------
|
||||
drawText(page, "TRAVELER CARD", {
|
||||
x: MARGIN,
|
||||
y: cursor.top - 10,
|
||||
font: fonts.bold,
|
||||
size: 10,
|
||||
color: rgb(0.4, 0.4, 0.45),
|
||||
});
|
||||
drawText(page, `${data.project.code} · ${data.assembly.code}`, {
|
||||
x: PAGE_WIDTH - MARGIN,
|
||||
y: cursor.top - 10,
|
||||
font: fonts.regular,
|
||||
size: 10,
|
||||
color: rgb(0.4, 0.4, 0.45),
|
||||
});
|
||||
// Right-align fix: pdf-lib doesn't do alignment for us, so re-measure.
|
||||
const rightLabel = `${data.project.code} · ${data.assembly.code}`;
|
||||
const rightLabelW = fonts.regular.widthOfTextAtSize(rightLabel, 10);
|
||||
page.drawRectangle({
|
||||
x: MARGIN,
|
||||
y: cursor.top - 16,
|
||||
width: contentWidth,
|
||||
height: 0,
|
||||
color: rgb(1, 1, 1),
|
||||
});
|
||||
// Redraw the right label at the correct x now that we know its width.
|
||||
page.drawRectangle({
|
||||
x: PAGE_WIDTH - MARGIN - rightLabelW - 1,
|
||||
y: cursor.top - 14,
|
||||
width: rightLabelW + 2,
|
||||
height: 14,
|
||||
color: rgb(1, 1, 1),
|
||||
});
|
||||
drawText(page, rightLabel, {
|
||||
x: PAGE_WIDTH - MARGIN - rightLabelW,
|
||||
y: cursor.top - 10,
|
||||
font: fonts.regular,
|
||||
size: 10,
|
||||
color: rgb(0.4, 0.4, 0.45),
|
||||
});
|
||||
cursor.top -= 20;
|
||||
|
||||
// --- Part name (big) ----------------------------------------------------
|
||||
const partTitle = data.part.name;
|
||||
const partLines = wrapLines(partTitle, fonts.bold, 22, contentWidth);
|
||||
for (const line of partLines) {
|
||||
cursor.top -= 24;
|
||||
drawText(page, line, { x: MARGIN, y: cursor.top, font: fonts.bold, size: 22 });
|
||||
}
|
||||
cursor.top -= 14;
|
||||
const partMeta = [
|
||||
`Part ${data.part.code}`,
|
||||
data.part.material ? `${data.part.material}` : null,
|
||||
`qty ${data.part.qty}`,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" · ");
|
||||
drawText(page, partMeta, {
|
||||
x: MARGIN,
|
||||
y: cursor.top,
|
||||
font: fonts.regular,
|
||||
size: 11,
|
||||
color: rgb(0.35, 0.4, 0.5),
|
||||
});
|
||||
cursor.top -= 18;
|
||||
|
||||
// Divider
|
||||
page.drawLine({
|
||||
start: { x: MARGIN, y: cursor.top },
|
||||
end: { x: PAGE_WIDTH - MARGIN, y: cursor.top },
|
||||
thickness: 0.75,
|
||||
color: rgb(0.8, 0.82, 0.88),
|
||||
});
|
||||
cursor.top -= 24;
|
||||
|
||||
// --- Step header + QR side-by-side --------------------------------------
|
||||
// Left column: step label, name, machine, plan. Right column: QR image.
|
||||
const qrSize = 156; // pt -> ~2.2" on paper, well above the 20 mm phone minimum
|
||||
const qrX = PAGE_WIDTH - MARGIN - qrSize;
|
||||
const qrY = cursor.top - qrSize;
|
||||
const qrBytes = await renderQrPngBuffer(data.operation.qrToken);
|
||||
const qrImage = await doc.embedPng(qrBytes);
|
||||
page.drawImage(qrImage, { x: qrX, y: qrY, width: qrSize, height: qrSize });
|
||||
|
||||
// Text under QR: scan URL + last 8 of token for manual lookup if it smudges.
|
||||
const scanUrl = scanUrlForToken(data.operation.qrToken);
|
||||
const scanLines = wrapLines(scanUrl, fonts.mono, 7, qrSize);
|
||||
let scanY = qrY - 10;
|
||||
for (const l of scanLines) {
|
||||
drawText(page, l, {
|
||||
x: qrX,
|
||||
y: scanY,
|
||||
font: fonts.mono,
|
||||
size: 7,
|
||||
color: rgb(0.4, 0.4, 0.45),
|
||||
});
|
||||
scanY -= 9;
|
||||
}
|
||||
|
||||
// Left column content, constrained so it doesn't collide with the QR.
|
||||
const leftColWidth = qrX - MARGIN - 18;
|
||||
|
||||
drawText(page, `STEP ${data.operation.sequence}`, {
|
||||
x: MARGIN,
|
||||
y: cursor.top,
|
||||
font: fonts.bold,
|
||||
size: 11,
|
||||
color: rgb(0.38, 0.45, 0.85),
|
||||
});
|
||||
cursor.top -= 6;
|
||||
|
||||
const stepNameLines = wrapLines(data.operation.name, fonts.bold, 18, leftColWidth);
|
||||
for (const line of stepNameLines) {
|
||||
cursor.top -= 22;
|
||||
drawText(page, line, { x: MARGIN, y: cursor.top, font: fonts.bold, size: 18 });
|
||||
}
|
||||
cursor.top -= 10;
|
||||
|
||||
const metaRows: [string, string][] = [];
|
||||
if (data.operation.machineName) {
|
||||
metaRows.push([
|
||||
"Machine",
|
||||
data.operation.machineKind
|
||||
? `${data.operation.machineName} (${data.operation.machineKind})`
|
||||
: data.operation.machineName,
|
||||
]);
|
||||
}
|
||||
if (data.operation.plannedMinutes) metaRows.push(["Planned time", `${data.operation.plannedMinutes} min`]);
|
||||
if (data.operation.plannedUnits) metaRows.push(["Planned units", `${data.operation.plannedUnits}`]);
|
||||
if (data.operation.qcRequired) metaRows.push(["QC", "Required on close-out"]);
|
||||
|
||||
for (const [k, v] of metaRows) {
|
||||
cursor.top -= 13;
|
||||
drawText(page, k.toUpperCase(), {
|
||||
x: MARGIN,
|
||||
y: cursor.top,
|
||||
font: fonts.bold,
|
||||
size: 7,
|
||||
color: rgb(0.45, 0.5, 0.6),
|
||||
});
|
||||
const valueLines = wrapLines(v, fonts.regular, 11, leftColWidth);
|
||||
for (let i = 0; i < valueLines.length; i++) {
|
||||
if (i > 0) cursor.top -= 13;
|
||||
drawText(page, valueLines[i], {
|
||||
x: MARGIN + 80,
|
||||
y: cursor.top,
|
||||
font: fonts.regular,
|
||||
size: 11,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Align the cursor below whichever column is taller (QR column vs. left).
|
||||
cursor.top = Math.min(cursor.top, qrY - 10 - scanLines.length * 9);
|
||||
cursor.top -= 26;
|
||||
|
||||
// --- Full-width sections -------------------------------------------------
|
||||
drawSection(page, fonts, cursor, "Instructions", data.operation.instructions, contentWidth);
|
||||
drawSection(page, fonts, cursor, "Material notes", data.operation.materialNotes, contentWidth);
|
||||
drawSection(page, fonts, cursor, "Settings", data.operation.settings, contentWidth, fonts.mono);
|
||||
|
||||
// --- Footer: sign-off strip ---------------------------------------------
|
||||
const footerY = MARGIN + 20;
|
||||
page.drawLine({
|
||||
start: { x: MARGIN, y: footerY + 14 },
|
||||
end: { x: PAGE_WIDTH - MARGIN, y: footerY + 14 },
|
||||
thickness: 0.5,
|
||||
color: rgb(0.82, 0.84, 0.88),
|
||||
});
|
||||
drawText(page, "Operator", {
|
||||
x: MARGIN,
|
||||
y: footerY,
|
||||
font: fonts.bold,
|
||||
size: 7,
|
||||
color: rgb(0.45, 0.5, 0.6),
|
||||
});
|
||||
drawText(page, "Start / End", {
|
||||
x: MARGIN + 180,
|
||||
y: footerY,
|
||||
font: fonts.bold,
|
||||
size: 7,
|
||||
color: rgb(0.45, 0.5, 0.6),
|
||||
});
|
||||
drawText(page, "Units", {
|
||||
x: MARGIN + 340,
|
||||
y: footerY,
|
||||
font: fonts.bold,
|
||||
size: 7,
|
||||
color: rgb(0.45, 0.5, 0.6),
|
||||
});
|
||||
drawText(page, "QC", {
|
||||
x: MARGIN + 420,
|
||||
y: footerY,
|
||||
font: fonts.bold,
|
||||
size: 7,
|
||||
color: rgb(0.45, 0.5, 0.6),
|
||||
});
|
||||
}
|
||||
|
||||
// Inline helper that renders a labelled prose block and advances the cursor.
|
||||
// Silently does nothing if `body` is empty, so we don't leave orphan labels.
|
||||
function drawSection(
|
||||
page: PDFPage,
|
||||
fonts: Fonts,
|
||||
cursor: Cursor,
|
||||
label: string,
|
||||
body: string | null,
|
||||
width: number,
|
||||
font: PDFFont = fonts.regular,
|
||||
): void {
|
||||
if (!body || !body.trim()) return;
|
||||
|
||||
drawText(page, label.toUpperCase(), {
|
||||
x: MARGIN,
|
||||
y: cursor.top,
|
||||
font: fonts.bold,
|
||||
size: 8,
|
||||
color: rgb(0.45, 0.5, 0.6),
|
||||
});
|
||||
cursor.top -= 12;
|
||||
|
||||
const lines = wrapLines(body.trim(), font, 10, width);
|
||||
for (const line of lines) {
|
||||
drawText(page, line, { x: MARGIN, y: cursor.top, font, size: 10 });
|
||||
cursor.top -= 13;
|
||||
}
|
||||
cursor.top -= 8;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Cover sheet
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function drawCoverSheet(
|
||||
doc: PDFDocument,
|
||||
page: PDFPage,
|
||||
fonts: Fonts,
|
||||
data: PartCoverData,
|
||||
): Promise<void> {
|
||||
const cursor: Cursor = { top: PAGE_HEIGHT - MARGIN };
|
||||
const contentWidth = PAGE_WIDTH - MARGIN * 2;
|
||||
|
||||
drawText(page, "WORK ORDER", {
|
||||
x: MARGIN,
|
||||
y: cursor.top - 10,
|
||||
font: fonts.bold,
|
||||
size: 10,
|
||||
color: rgb(0.4, 0.4, 0.45),
|
||||
});
|
||||
cursor.top -= 28;
|
||||
|
||||
const title = `${data.project.code} · ${data.assembly.code} · ${data.part.code}`;
|
||||
drawText(page, title, { x: MARGIN, y: cursor.top, font: fonts.bold, size: 20 });
|
||||
cursor.top -= 26;
|
||||
drawText(page, data.part.name, {
|
||||
x: MARGIN,
|
||||
y: cursor.top,
|
||||
font: fonts.regular,
|
||||
size: 14,
|
||||
color: rgb(0.2, 0.25, 0.35),
|
||||
});
|
||||
cursor.top -= 18;
|
||||
|
||||
const meta = [
|
||||
data.part.material ? `Material: ${data.part.material}` : null,
|
||||
`Quantity: ${data.part.qty}`,
|
||||
`Project: ${data.project.name}`,
|
||||
`Assembly: ${data.assembly.name}`,
|
||||
].filter(Boolean) as string[];
|
||||
for (const line of meta) {
|
||||
drawText(page, line, {
|
||||
x: MARGIN,
|
||||
y: cursor.top,
|
||||
font: fonts.regular,
|
||||
size: 10,
|
||||
color: rgb(0.35, 0.4, 0.5),
|
||||
});
|
||||
cursor.top -= 13;
|
||||
}
|
||||
cursor.top -= 6;
|
||||
|
||||
if (data.part.notes && data.part.notes.trim()) {
|
||||
drawSection(page, fonts, cursor, "Part notes", data.part.notes, contentWidth);
|
||||
}
|
||||
|
||||
// --- Files manifest ------------------------------------------------------
|
||||
const filesWithContent = data.files.filter((f) => f.file !== null);
|
||||
if (filesWithContent.length > 0) {
|
||||
drawText(page, "FILES", {
|
||||
x: MARGIN,
|
||||
y: cursor.top,
|
||||
font: fonts.bold,
|
||||
size: 8,
|
||||
color: rgb(0.45, 0.5, 0.6),
|
||||
});
|
||||
cursor.top -= 14;
|
||||
|
||||
for (const f of filesWithContent) {
|
||||
if (!f.file) continue;
|
||||
drawText(page, `${f.label}`, {
|
||||
x: MARGIN,
|
||||
y: cursor.top,
|
||||
font: fonts.bold,
|
||||
size: 10,
|
||||
});
|
||||
drawText(page, f.file.originalName, {
|
||||
x: MARGIN + 110,
|
||||
y: cursor.top,
|
||||
font: fonts.regular,
|
||||
size: 10,
|
||||
});
|
||||
drawText(page, `${formatBytes(f.file.sizeBytes)} · sha256 ${f.file.sha256.slice(0, 12)}…`, {
|
||||
x: MARGIN + 110,
|
||||
y: cursor.top - 11,
|
||||
font: fonts.mono,
|
||||
size: 8,
|
||||
color: rgb(0.5, 0.5, 0.55),
|
||||
});
|
||||
cursor.top -= 26;
|
||||
}
|
||||
cursor.top -= 6;
|
||||
}
|
||||
|
||||
// --- Operations table ----------------------------------------------------
|
||||
drawText(page, "OPERATIONS", {
|
||||
x: MARGIN,
|
||||
y: cursor.top,
|
||||
font: fonts.bold,
|
||||
size: 8,
|
||||
color: rgb(0.45, 0.5, 0.6),
|
||||
});
|
||||
cursor.top -= 14;
|
||||
|
||||
const rowThumb = 44; // QR thumbnail side (pt)
|
||||
const rowGap = 10;
|
||||
const rowHeight = rowThumb + rowGap;
|
||||
|
||||
for (const op of data.operations) {
|
||||
// Stop drawing if we run out of room; the cards that follow are the
|
||||
// authoritative per-step references anyway.
|
||||
if (cursor.top - rowHeight < MARGIN + 30) {
|
||||
drawText(page, `… ${data.operations.length} operations total (see following pages)`, {
|
||||
x: MARGIN,
|
||||
y: cursor.top,
|
||||
font: fonts.regular,
|
||||
size: 9,
|
||||
color: rgb(0.5, 0.5, 0.55),
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
const thumbBytes = await renderQrPngBuffer(op.qrToken, 256);
|
||||
const thumbImg = await doc.embedPng(thumbBytes);
|
||||
const thumbY = cursor.top - rowThumb;
|
||||
page.drawImage(thumbImg, {
|
||||
x: MARGIN,
|
||||
y: thumbY,
|
||||
width: rowThumb,
|
||||
height: rowThumb,
|
||||
});
|
||||
|
||||
const textX = MARGIN + rowThumb + 12;
|
||||
drawText(page, `${op.sequence}. ${op.name}`, {
|
||||
x: textX,
|
||||
y: cursor.top - 12,
|
||||
font: fonts.bold,
|
||||
size: 11,
|
||||
});
|
||||
|
||||
const subline = [
|
||||
op.machineName ?? "no machine",
|
||||
op.qcRequired ? "QC" : null,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" · ");
|
||||
drawText(page, subline, {
|
||||
x: textX,
|
||||
y: cursor.top - 26,
|
||||
font: fonts.regular,
|
||||
size: 9,
|
||||
color: rgb(0.4, 0.45, 0.55),
|
||||
});
|
||||
|
||||
drawText(page, scanUrlForToken(op.qrToken), {
|
||||
x: textX,
|
||||
y: cursor.top - 40,
|
||||
font: fonts.mono,
|
||||
size: 7,
|
||||
color: rgb(0.5, 0.5, 0.55),
|
||||
});
|
||||
|
||||
cursor.top -= rowHeight;
|
||||
}
|
||||
|
||||
// --- Footer timestamp ----------------------------------------------------
|
||||
drawText(page, `Printed ${new Date().toISOString().slice(0, 16).replace("T", " ")}Z`, {
|
||||
x: MARGIN,
|
||||
y: MARGIN - 10,
|
||||
font: fonts.regular,
|
||||
size: 8,
|
||||
color: rgb(0.55, 0.58, 0.65),
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Purchase order
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function drawPurchaseOrder(page: PDFPage, fonts: Fonts, data: PurchaseOrderPdfData): void {
|
||||
const cursor: Cursor = { top: PAGE_HEIGHT - MARGIN };
|
||||
const contentWidth = PAGE_WIDTH - MARGIN * 2;
|
||||
|
||||
// --- Header --------------------------------------------------------------
|
||||
drawText(page, "PURCHASE ORDER", {
|
||||
x: MARGIN,
|
||||
y: cursor.top - 10,
|
||||
font: fonts.bold,
|
||||
size: 10,
|
||||
color: rgb(0.4, 0.4, 0.45),
|
||||
});
|
||||
|
||||
const poRef = `PO-${data.po.id.slice(0, 8).toUpperCase()}`;
|
||||
const poRefW = fonts.bold.widthOfTextAtSize(poRef, 10);
|
||||
drawText(page, poRef, {
|
||||
x: PAGE_WIDTH - MARGIN - poRefW,
|
||||
y: cursor.top - 10,
|
||||
font: fonts.bold,
|
||||
size: 10,
|
||||
});
|
||||
cursor.top -= 28;
|
||||
|
||||
drawText(page, data.po.vendor, {
|
||||
x: MARGIN,
|
||||
y: cursor.top,
|
||||
font: fonts.bold,
|
||||
size: 22,
|
||||
});
|
||||
cursor.top -= 26;
|
||||
|
||||
const meta: string[] = [
|
||||
`Project: ${data.project.code} — ${data.project.name}`,
|
||||
`Status: ${data.po.status}`,
|
||||
`Issued: ${(data.po.sentAt ?? data.po.createdAt).toISOString().slice(0, 10)}`,
|
||||
];
|
||||
for (const m of meta) {
|
||||
drawText(page, m, {
|
||||
x: MARGIN,
|
||||
y: cursor.top,
|
||||
font: fonts.regular,
|
||||
size: 10,
|
||||
color: rgb(0.35, 0.4, 0.5),
|
||||
});
|
||||
cursor.top -= 13;
|
||||
}
|
||||
cursor.top -= 10;
|
||||
|
||||
// --- Line table ---------------------------------------------------------
|
||||
const cols = {
|
||||
partNo: MARGIN,
|
||||
desc: MARGIN + 110,
|
||||
qty: MARGIN + 360,
|
||||
unit: MARGIN + 410,
|
||||
total: MARGIN + 480,
|
||||
};
|
||||
const headerRow = cursor.top;
|
||||
|
||||
drawText(page, "PART NO.", { x: cols.partNo, y: headerRow, font: fonts.bold, size: 8, color: rgb(0.45, 0.5, 0.6) });
|
||||
drawText(page, "DESCRIPTION", { x: cols.desc, y: headerRow, font: fonts.bold, size: 8, color: rgb(0.45, 0.5, 0.6) });
|
||||
drawText(page, "QTY", { x: cols.qty, y: headerRow, font: fonts.bold, size: 8, color: rgb(0.45, 0.5, 0.6) });
|
||||
drawText(page, "UNIT", { x: cols.unit, y: headerRow, font: fonts.bold, size: 8, color: rgb(0.45, 0.5, 0.6) });
|
||||
drawText(page, "TOTAL", { x: cols.total, y: headerRow, font: fonts.bold, size: 8, color: rgb(0.45, 0.5, 0.6) });
|
||||
cursor.top -= 4;
|
||||
page.drawLine({
|
||||
start: { x: MARGIN, y: cursor.top },
|
||||
end: { x: PAGE_WIDTH - MARGIN, y: cursor.top },
|
||||
thickness: 0.75,
|
||||
color: rgb(0.82, 0.84, 0.88),
|
||||
});
|
||||
cursor.top -= 10;
|
||||
|
||||
const lineSize = 10;
|
||||
const descWidth = cols.qty - cols.desc - 10;
|
||||
let grandTotal = 0;
|
||||
let hasAnyCost = false;
|
||||
for (const l of data.lines) {
|
||||
const descLines = wrapLines(l.description, fonts.regular, lineSize, descWidth);
|
||||
const rowHeight = Math.max(14, descLines.length * 13) + 4;
|
||||
|
||||
// Page break guard — if we run out of space, stop. (Multi-page POs can
|
||||
// be added later; for now a single page is fine for typical line counts.)
|
||||
if (cursor.top - rowHeight < MARGIN + 60) {
|
||||
drawText(page, `… additional ${data.lines.length} lines truncated`, {
|
||||
x: MARGIN,
|
||||
y: cursor.top,
|
||||
font: fonts.regular,
|
||||
size: 8,
|
||||
color: rgb(0.5, 0.5, 0.55),
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
drawText(page, l.partNumber, {
|
||||
x: cols.partNo,
|
||||
y: cursor.top - 2,
|
||||
font: fonts.mono,
|
||||
size: lineSize,
|
||||
});
|
||||
for (let i = 0; i < descLines.length; i++) {
|
||||
drawText(page, descLines[i], {
|
||||
x: cols.desc,
|
||||
y: cursor.top - 2 - i * 13,
|
||||
font: fonts.regular,
|
||||
size: lineSize,
|
||||
});
|
||||
}
|
||||
drawText(page, String(l.qty), {
|
||||
x: cols.qty,
|
||||
y: cursor.top - 2,
|
||||
font: fonts.regular,
|
||||
size: lineSize,
|
||||
});
|
||||
|
||||
if (l.unitCost !== null && l.unitCost !== undefined) {
|
||||
hasAnyCost = true;
|
||||
const total = l.unitCost * l.qty;
|
||||
grandTotal += total;
|
||||
drawText(page, l.unitCost.toFixed(2), {
|
||||
x: cols.unit,
|
||||
y: cursor.top - 2,
|
||||
font: fonts.regular,
|
||||
size: lineSize,
|
||||
});
|
||||
drawText(page, total.toFixed(2), {
|
||||
x: cols.total,
|
||||
y: cursor.top - 2,
|
||||
font: fonts.regular,
|
||||
size: lineSize,
|
||||
});
|
||||
} else {
|
||||
drawText(page, "—", {
|
||||
x: cols.unit,
|
||||
y: cursor.top - 2,
|
||||
font: fonts.regular,
|
||||
size: lineSize,
|
||||
color: rgb(0.55, 0.58, 0.65),
|
||||
});
|
||||
}
|
||||
|
||||
cursor.top -= rowHeight;
|
||||
}
|
||||
|
||||
// --- Totals --------------------------------------------------------------
|
||||
if (hasAnyCost) {
|
||||
cursor.top -= 8;
|
||||
page.drawLine({
|
||||
start: { x: cols.unit, y: cursor.top + 10 },
|
||||
end: { x: PAGE_WIDTH - MARGIN, y: cursor.top + 10 },
|
||||
thickness: 0.5,
|
||||
color: rgb(0.82, 0.84, 0.88),
|
||||
});
|
||||
drawText(page, "TOTAL", {
|
||||
x: cols.unit,
|
||||
y: cursor.top,
|
||||
font: fonts.bold,
|
||||
size: 10,
|
||||
});
|
||||
drawText(page, grandTotal.toFixed(2), {
|
||||
x: cols.total,
|
||||
y: cursor.top,
|
||||
font: fonts.bold,
|
||||
size: 10,
|
||||
});
|
||||
cursor.top -= 16;
|
||||
}
|
||||
|
||||
// --- Notes --------------------------------------------------------------
|
||||
drawSection(page, fonts, cursor, "Notes", data.po.notes, contentWidth);
|
||||
|
||||
// --- Footer -------------------------------------------------------------
|
||||
drawText(page, `Generated ${new Date().toISOString().slice(0, 16).replace("T", " ")}Z`, {
|
||||
x: MARGIN,
|
||||
y: MARGIN - 10,
|
||||
font: fonts.regular,
|
||||
size: 8,
|
||||
color: rgb(0.55, 0.58, 0.65),
|
||||
});
|
||||
}
|
||||
|
||||
function formatBytes(n: number): string {
|
||||
if (n < 1024) return `${n} B`;
|
||||
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
|
||||
return `${(n / (1024 * 1024)).toFixed(1)} MB`;
|
||||
}
|
||||
@@ -37,3 +37,16 @@ export async function renderQrPng(token: string): Promise<string> {
|
||||
width: 256,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Same QR, but as a raw PNG buffer for embedding into pdf-lib documents.
|
||||
* We bump width up so the vector→raster downscale at print time stays crisp;
|
||||
* 512 px at 35 mm = ~370 dpi which beats any office printer we'll see.
|
||||
*/
|
||||
export async function renderQrPngBuffer(token: string, width = 512): Promise<Buffer> {
|
||||
return QRCode.toBuffer(scanUrlForToken(token), {
|
||||
errorCorrectionLevel: "M",
|
||||
margin: 1,
|
||||
width,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -240,6 +240,87 @@ export const ReorderOperationsSchema = z.object({
|
||||
|
||||
// A scan-page "Pause" — stops the clock but does not complete the step. The
|
||||
// operator can enter a partial unit count before dropping the claim.
|
||||
// ---- fasteners ----------------------------------------------------------
|
||||
|
||||
export const CreateFastenerSchema = z.object({
|
||||
partNumber: z.string().trim().min(1).max(120),
|
||||
description: NonEmpty,
|
||||
qty: z.coerce.number().int().positive().max(1_000_000),
|
||||
supplier: z
|
||||
.string()
|
||||
.trim()
|
||||
.max(200)
|
||||
.transform((v) => (v.length === 0 ? null : v))
|
||||
.nullable()
|
||||
.optional(),
|
||||
unitCost: z.coerce.number().min(0).max(1_000_000).nullable().optional(),
|
||||
notes: OptionalText,
|
||||
});
|
||||
|
||||
export const UpdateFastenerSchema = z
|
||||
.object({
|
||||
partNumber: z.string().trim().min(1).max(120).optional(),
|
||||
description: NonEmpty.optional(),
|
||||
qty: z.coerce.number().int().positive().max(1_000_000).optional(),
|
||||
supplier: z
|
||||
.string()
|
||||
.trim()
|
||||
.max(200)
|
||||
.transform((v) => (v.length === 0 ? null : v))
|
||||
.nullable()
|
||||
.optional(),
|
||||
unitCost: z.coerce.number().min(0).max(1_000_000).nullable().optional(),
|
||||
notes: OptionalText,
|
||||
})
|
||||
.strict();
|
||||
|
||||
// ---- purchase orders ----------------------------------------------------
|
||||
|
||||
export const PoStatuses = ["draft", "sent", "partial", "received", "cancelled"] as const;
|
||||
|
||||
// A single line on a draft PO. Fastener must belong to the same project (the
|
||||
// route handler verifies that; we keep the schema pure).
|
||||
const PoLineInput = z.object({
|
||||
fastenerId: z.string().min(1),
|
||||
qty: z.coerce.number().int().positive().max(1_000_000),
|
||||
unitCost: z.coerce.number().min(0).max(1_000_000).nullable().optional(),
|
||||
});
|
||||
|
||||
export const CreatePOSchema = z.object({
|
||||
vendor: NonEmpty,
|
||||
notes: OptionalText,
|
||||
lines: z.array(PoLineInput).min(1, "Add at least one line"),
|
||||
});
|
||||
|
||||
// PATCH: vendor + notes are free to change any time. Lines can only be
|
||||
// rewritten while the PO is in draft — the route enforces that.
|
||||
export const UpdatePOSchema = z
|
||||
.object({
|
||||
vendor: NonEmpty.optional(),
|
||||
notes: OptionalText,
|
||||
lines: z.array(PoLineInput).min(1).optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
// Status transitions are validated in the route (see PO_TRANSITIONS).
|
||||
export const UpdatePOStatusSchema = z.object({
|
||||
status: z.enum(PoStatuses),
|
||||
});
|
||||
|
||||
// Receipt: bump receivedQty by `qty` for each listed line. If every line on
|
||||
// the PO is fully received the route auto-moves status to "received";
|
||||
// otherwise it moves to "partial".
|
||||
export const ReceivePOSchema = z.object({
|
||||
receipts: z
|
||||
.array(
|
||||
z.object({
|
||||
lineId: z.string().min(1),
|
||||
qty: z.coerce.number().int().positive().max(1_000_000),
|
||||
}),
|
||||
)
|
||||
.min(1),
|
||||
});
|
||||
|
||||
export const ReleaseOperationSchema = z.object({
|
||||
unitsProcessed: z.coerce.number().int().min(0).max(1_000_000).nullable().optional(),
|
||||
note: OptionalText,
|
||||
|
||||
Generated
+43
@@ -11,6 +11,7 @@
|
||||
"@prisma/client": "^5.22.0",
|
||||
"bcryptjs": "^2.4.3",
|
||||
"next": "^15.1.0",
|
||||
"pdf-lib": "^1.17.1",
|
||||
"qrcode": "^1.5.4",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
@@ -1452,6 +1453,24 @@
|
||||
"node": ">=12.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@pdf-lib/standard-fonts": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@pdf-lib/standard-fonts/-/standard-fonts-1.0.0.tgz",
|
||||
"integrity": "sha512-hU30BK9IUN/su0Mn9VdlVKsWBS6GyhVfqjwl1FjZN4TxP6cCw0jP2w7V3Hf5uX7M0AZJ16vey9yE0ny7Sa59ZA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"pako": "^1.0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/@pdf-lib/upng": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/@pdf-lib/upng/-/upng-1.0.1.tgz",
|
||||
"integrity": "sha512-dQK2FUMQtowVP00mtIksrlZhdFXQZPC+taih1q4CvPZ5vqdxR/LKBaFg0oAfzd1GlHZXXSPdQfzQnt+ViGvEIQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"pako": "^1.0.10"
|
||||
}
|
||||
},
|
||||
"node_modules/@prisma/client": {
|
||||
"version": "5.22.0",
|
||||
"resolved": "https://registry.npmjs.org/@prisma/client/-/client-5.22.0.tgz",
|
||||
@@ -5562,6 +5581,12 @@
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/pako": {
|
||||
"version": "1.0.11",
|
||||
"resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz",
|
||||
"integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==",
|
||||
"license": "(MIT AND Zlib)"
|
||||
},
|
||||
"node_modules/parent-module": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz",
|
||||
@@ -5601,6 +5626,24 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/pdf-lib": {
|
||||
"version": "1.17.1",
|
||||
"resolved": "https://registry.npmjs.org/pdf-lib/-/pdf-lib-1.17.1.tgz",
|
||||
"integrity": "sha512-V/mpyJAoTsN4cnP31vc0wfNA1+p20evqqnap0KLoRUN0Yk/p3wN52DOEsL4oBFcLdb76hlpKPtzJIgo67j/XLw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@pdf-lib/standard-fonts": "^1.0.0",
|
||||
"@pdf-lib/upng": "^1.0.1",
|
||||
"pako": "^1.0.11",
|
||||
"tslib": "^1.11.1"
|
||||
}
|
||||
},
|
||||
"node_modules/pdf-lib/node_modules/tslib": {
|
||||
"version": "1.14.1",
|
||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz",
|
||||
"integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==",
|
||||
"license": "0BSD"
|
||||
},
|
||||
"node_modules/picocolors": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
"@prisma/client": "^5.22.0",
|
||||
"bcryptjs": "^2.4.3",
|
||||
"next": "^15.1.0",
|
||||
"pdf-lib": "^1.17.1",
|
||||
"qrcode": "^1.5.4",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
|
||||
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user