pelagia-portal/App/app/api/reports/export/route.ts
Claude (review-bot) fd7b31e64d
All checks were successful
PR checks / checks (pull_request) Successful in 49s
PR checks / integration (pull_request) Successful in 32s
feat(reports): drill from cost centre / accounting code into PO History (#126)
Report detail pages now link to the underlying POs, addressing the PR #126
review comment: drilling into a cost centre or accounting code opens PO
History pre-filtered to that dimension and the period in view.

- Cost Centre / Accounting Code detail pages gain a "View POs" link.
- periodRange() maps the on-screen period onto History's approved-date
  window (weekly→month, monthly→FY, yearly→full span); spend is dated by
  approvedAt.
- PO History gains an accountId filter (any tree node, expanded to leaves
  via accountLeafIds()) matching PO-level OR line-item accounts — the same
  basis the reports use.
- History page + CSV/PDF export share one buildPoHistoryWhere() builder so
  they never diverge.
- Tests: unit (periodRange, accountLeafIds) + integration (History account
  filter across PO-level/line-item, with the approved window).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 16:09:54 +05:30

122 lines
4.1 KiB
TypeScript

import { auth } from "@/auth";
import { db } from "@/lib/db";
import { hasPermission, submitterCanViewAll } from "@/lib/permissions";
import { buildPoHistoryWhere } from "@/lib/history-filter";
import { NextRequest, NextResponse } from "next/server";
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", CANCELLED: "Cancelled",
};
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") &&
!submitterCanViewAll(session.user.role)
) {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const sp = request.nextUrl.searchParams;
const format = sp.get("format") ?? "csv";
const where = await buildPoHistoryWhere({
dateFrom: sp.get("dateFrom"),
dateTo: sp.get("dateTo"),
approvedFrom: sp.get("approvedFrom"),
approvedTo: sp.get("approvedTo"),
vesselId: sp.get("vesselId"),
accountId: sp.get("accountId"),
statuses: sp.getAll("status"),
});
const orders = await db.purchaseOrder.findMany({
where,
include: { submitter: true, vessel: 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}</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.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"`,
},
});
}