- Undo Vessel→Cost Centre rename in admin (admin shows "Vessel Management" again) - Sidebar: "Cost Centres"→"Vessels", "Accounts"→"Accounting Codes" - PO forms (new/edit/import/manager-edit) now show both Vessels (with code) and Sites in the Cost Centre dropdown, encoded as v:<id> / s:<id> via a costCentreRef field - vesselId on PurchaseOrder is now nullable; siteId is set when a site is the cost centre - History, approvals, dashboard, my-orders, payments display vessel.name ?? site.name as Cost Centre - History and approvals cost centre filters use costCentreRef URL param supporting both types - Admin vessel form: adds Site assignment dropdown - Admin accounts: renamed to "Accounting Code" throughout (pages, forms, sidebar) - PO detail and exports: "Account" label renamed to "Accounting Code" - Site detail: "Assigned Vessels (Cost Centres)" heading; vessel detail breadcrumb fixed - Create PO links from vessel/site detail use ?costCentreRef= param - Export routes handle costCentreRef filter param (with legacy vesselId fallback) - DB migration: ALTER TABLE PurchaseOrder ALTER COLUMN vesselId DROP NOT NULL - CLAUDE.md updated with Cost Centre Model documentation Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
131 lines
4.7 KiB
TypeScript
131 lines
4.7 KiB
TypeScript
import { auth } from "@/auth";
|
|
import { db } from "@/lib/db";
|
|
import { hasPermission } from "@/lib/permissions";
|
|
import { NextRequest, NextResponse } from "next/server";
|
|
import type { POStatus } from "@prisma/client";
|
|
|
|
const PO_STATUS_LABELS: Record<string, string> = {
|
|
DRAFT: "Draft", SUBMITTED: "Submitted", MGR_REVIEW: "Pending Approval",
|
|
VENDOR_ID_PENDING: "Vendor ID Pending", EDITS_REQUESTED: "Edits Requested",
|
|
REJECTED: "Rejected", MGR_APPROVED: "Approved", SENT_FOR_PAYMENT: "Sent for Payment",
|
|
PAID_DELIVERED: "Paid / Delivered", CLOSED: "Closed",
|
|
};
|
|
|
|
export async function GET(request: NextRequest) {
|
|
const session = await auth();
|
|
if (!session?.user) {
|
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
}
|
|
if (!hasPermission(session.user.role, "export_reports")) {
|
|
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
|
}
|
|
|
|
const sp = request.nextUrl.searchParams;
|
|
const format = sp.get("format") ?? "csv";
|
|
const dateFrom = sp.get("dateFrom");
|
|
const dateTo = sp.get("dateTo");
|
|
const costCentreRef = sp.get("costCentreRef") ?? sp.get("vesselId");
|
|
const status = sp.get("status");
|
|
|
|
const where: NonNullable<Parameters<typeof db.purchaseOrder.findMany>[0]>["where"] = {};
|
|
if (dateFrom || dateTo) {
|
|
const createdAt: { gte?: Date; lt?: Date } = {};
|
|
if (dateFrom) createdAt.gte = new Date(dateFrom);
|
|
if (dateTo) {
|
|
const end = new Date(dateTo);
|
|
end.setDate(end.getDate() + 1);
|
|
createdAt.lt = end;
|
|
}
|
|
where.createdAt = createdAt;
|
|
}
|
|
if (costCentreRef) {
|
|
if (costCentreRef.startsWith("v:")) where.vesselId = costCentreRef.slice(2);
|
|
else if (costCentreRef.startsWith("s:")) where.siteId = costCentreRef.slice(2);
|
|
else where.vesselId = costCentreRef; // legacy plain vesselId
|
|
}
|
|
if (status) where.status = status as POStatus;
|
|
|
|
const orders = await db.purchaseOrder.findMany({
|
|
where,
|
|
include: { submitter: true, vessel: true, site: { select: { name: true } }, account: true, vendor: true },
|
|
orderBy: { createdAt: "desc" },
|
|
});
|
|
|
|
if (format === "pdf") {
|
|
const rows = orders.map((po) => `
|
|
<tr>
|
|
<td>${po.poNumber}</td>
|
|
<td>${po.title}</td>
|
|
<td>${PO_STATUS_LABELS[po.status] ?? po.status}</td>
|
|
<td>${po.vessel?.name ?? po.site?.name ?? "—"}</td>
|
|
<td>${po.submitter.name}</td>
|
|
<td>${po.vendor?.name ?? "—"}</td>
|
|
<td style="text-align:right">${Number(po.totalAmount).toLocaleString("en-IN", { style: "currency", currency: "INR" })}</td>
|
|
<td>${po.createdAt.toLocaleDateString("en-IN")}</td>
|
|
</tr>`).join("");
|
|
|
|
const html = `<!DOCTYPE html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="UTF-8" />
|
|
<title>PO Export — PPMS</title>
|
|
<style>
|
|
body { font-family: Arial, sans-serif; font-size: 11px; margin: 20px; color: #111; }
|
|
h1 { font-size: 16px; margin-bottom: 4px; }
|
|
p { font-size: 10px; color: #555; margin-bottom: 12px; }
|
|
table { width: 100%; border-collapse: collapse; }
|
|
th { background: #f0f0f0; border: 1px solid #ccc; padding: 5px 8px; text-align: left; font-size: 10px; }
|
|
td { border: 1px solid #ddd; padding: 4px 8px; vertical-align: top; }
|
|
tr:nth-child(even) td { background: #fafafa; }
|
|
.no-print { margin-bottom: 12px; }
|
|
@media print { .no-print { display: none; } }
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<div class="no-print">
|
|
<button onclick="window.print()" style="padding:6px 16px;font-size:13px;cursor:pointer;">Print / Save as PDF</button>
|
|
</div>
|
|
<h1>Purchase Order Report — PPMS</h1>
|
|
<p>Generated: ${new Date().toLocaleString("en-IN")} · ${orders.length} orders</p>
|
|
<table>
|
|
<thead>
|
|
<tr>
|
|
<th>PO Number</th><th>Title</th><th>Status</th><th>Cost Centre</th>
|
|
<th>Submitter</th><th>Vendor</th><th style="text-align:right">Amount</th><th>Created</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>${rows}</tbody>
|
|
</table>
|
|
<script>window.onload = function() { window.print(); };</script>
|
|
</body>
|
|
</html>`;
|
|
|
|
return new NextResponse(html, {
|
|
headers: { "Content-Type": "text/html; charset=utf-8" },
|
|
});
|
|
}
|
|
|
|
// Default: CSV
|
|
const headers = ["PO Number", "Title", "Status", "Cost Centre", "Account", "Vendor", "Submitter", "Amount", "Currency", "Created"];
|
|
const csvRows = orders.map((po) => [
|
|
po.poNumber,
|
|
`"${po.title.replace(/"/g, '""')}"`,
|
|
po.status,
|
|
po.vessel?.name ?? po.site?.name ?? "",
|
|
po.account.name,
|
|
po.vendor?.name ?? "",
|
|
po.submitter.name,
|
|
po.totalAmount.toString(),
|
|
po.currency,
|
|
po.createdAt.toISOString(),
|
|
]);
|
|
|
|
const csv = [headers.join(","), ...csvRows.map((r) => r.join(","))].join("\n");
|
|
|
|
return new NextResponse(csv, {
|
|
headers: {
|
|
"Content-Type": "text/csv",
|
|
"Content-Disposition": `attachment; filename="pelagia-po-export-${Date.now()}.csv"`,
|
|
},
|
|
});
|
|
}
|