import { auth } from "@/auth"; import { db } from "@/lib/db"; import { notFound, redirect } from "next/navigation"; import { EditPoForm } from "./edit-po-form"; import type { CostCentreOption } from "@/app/(portal)/po/new/new-po-form"; import type { Metadata } from "next"; interface Props { params: Promise<{ id: string }>; } export const metadata: Metadata = { title: "Edit Purchase Order" }; export default async function EditPoPage({ params }: Props) { const session = await auth(); if (!session?.user) redirect("/login"); const { id } = await params; const po = await db.purchaseOrder.findUnique({ where: { id }, include: { lineItems: { orderBy: { sortOrder: "asc" } } }, }); if (!po) notFound(); if (!["DRAFT", "EDITS_REQUESTED"].includes(po.status)) redirect(`/po/${id}`); const canEdit = po.submitterId === session.user.id || session.user.role === "SUPERUSER"; if (!canEdit) redirect(`/po/${id}`); const [vessels, sites, accounts, vendors, noteAction] = await Promise.all([ db.vessel.findMany({ where: { isActive: true }, orderBy: { name: "asc" }, select: { id: true, name: true, code: true } }), db.site.findMany({ where: { isActive: true }, orderBy: { name: "asc" }, select: { id: true, name: true, code: true } }), db.account.findMany({ where: { isActive: true }, orderBy: { name: "asc" } }), db.vendor.findMany({ where: { isActive: true }, orderBy: { name: "asc" } }), po.status === "EDITS_REQUESTED" ? db.pOAction.findFirst({ where: { poId: po.id, actionType: "EDITS_REQUESTED", note: { not: null } }, orderBy: { createdAt: "desc" }, include: { actor: { select: { name: true } } }, }) : Promise.resolve(null), ]); const costCentres: CostCentreOption[] = [ ...vessels.map((v) => ({ ref: `v:${v.id}`, label: `${v.code} — ${v.name}`, group: "Vessels" as const })), ...sites.map((s) => ({ ref: `s:${s.id}`, label: `${s.code} — ${s.name}`, group: "Sites" as const })), ]; const initialCostCentreRef = po.vesselId ? `v:${po.vesselId}` : po.siteId ? `s:${po.siteId}` : ""; const serializedPo = { ...po, totalAmount: po.totalAmount.toNumber(), lineItems: po.lineItems.map((li) => ({ ...li, quantity: li.quantity.toNumber(), unitPrice: li.unitPrice.toNumber(), totalPrice: li.totalPrice.toNumber(), gstRate: li.gstRate.toNumber(), })), }; return (
{po.poNumber}