import { auth } from "@/auth"; import { db } from "@/lib/db"; import { hasPermission } from "@/lib/permissions"; import { redirect } from "next/navigation"; import { NewPoForm } from "./new-po-form"; import type { CostCentreOption } from "./new-po-form"; import type { Metadata } from "next"; import type { LineItemInput } from "@/lib/validations/po"; import type { CartItem } from "@/lib/cart"; export const metadata: Metadata = { title: "New Purchase Order" }; interface Props { searchParams: Promise<{ cart?: string; costCentreRef?: string }>; } export default async function NewPoPage({ searchParams }: Props) { const session = await auth(); if (!session?.user) redirect("/login"); if (!hasPermission(session.user.role, "create_po")) { redirect("/dashboard"); } const { cart, costCentreRef: initialCostCentreRef } = await searchParams; let initialLineItems: LineItemInput[] | undefined; let initialVendorId: string | undefined; if (cart) { try { const cartItems: CartItem[] = JSON.parse(decodeURIComponent(cart)); if (Array.isArray(cartItems) && cartItems.length > 0) { initialLineItems = cartItems.map((item) => ({ name: item.name, description: item.description ?? "", quantity: item.quantity, unit: item.unit, size: "", unitPrice: item.unitPrice, gstRate: 0.18, productId: item.productId, })); // Pre-fill vendor only when all items share the same vendor const vendorIds = [...new Set(cartItems.map((i) => i.vendorId).filter(Boolean))]; if (vendorIds.length === 1) initialVendorId = vendorIds[0]; } } catch { // malformed cart param — ignore and start empty } } const [vessels, sites, accounts, vendors] = 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" } }), ]); const costCentres: CostCentreOption[] = [ ...vessels.map((v) => ({ ref: `v:${v.id}` as const, label: `${v.code} — ${v.name}`, group: "Vessels" as const })), ...sites.map((s) => ({ ref: `s:${s.id}` as const, label: `${s.code} — ${s.name}`, group: "Sites" as const })), ]; return (
Fill in the details below. You can save as draft or submit directly for approval.