68 lines
2.1 KiB
TypeScript
68 lines
2.1 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { getDb } from "@/lib/db";
|
|
|
|
export async function GET(
|
|
_request: NextRequest,
|
|
{ params }: { params: Promise<{ id: string }> }
|
|
) {
|
|
try {
|
|
const { id } = await params;
|
|
const sql = getDb();
|
|
|
|
const planRows = await sql(
|
|
`SELECT * FROM planning_history WHERE id = $1`,
|
|
[Number(id)]
|
|
);
|
|
if (planRows.length === 0) {
|
|
return NextResponse.json({ error: "Not found" }, { status: 404 });
|
|
}
|
|
|
|
// Fetch items with PO info only if the component actually exists in the PO
|
|
const items = await sql(
|
|
`SELECT phi.*, phi.stock_at_time AS stock_snapshot,
|
|
(SELECT sp.po_number FROM supplier_pos sp
|
|
JOIN supplier_po_items spi ON spi.supplier_po_id = sp.id
|
|
WHERE sp.planning_id = phi.planning_id
|
|
AND spi.component_id = phi.component_id
|
|
ORDER BY sp.created_at DESC
|
|
LIMIT 1) AS po_number,
|
|
(SELECT sp.status FROM supplier_pos sp
|
|
JOIN supplier_po_items spi ON spi.supplier_po_id = sp.id
|
|
WHERE sp.planning_id = phi.planning_id
|
|
AND spi.component_id = phi.component_id
|
|
ORDER BY sp.created_at DESC
|
|
LIMIT 1) AS po_status
|
|
FROM planning_history_items phi
|
|
WHERE phi.planning_id = $1 ORDER BY phi.component_name ASC`,
|
|
[Number(id)]
|
|
);
|
|
|
|
return NextResponse.json({ ...planRows[0], items });
|
|
} catch (error) {
|
|
console.error("Error fetching planning detail:", error);
|
|
return NextResponse.json(
|
|
{ error: "Failed to fetch planning detail" },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|
|
|
|
export async function DELETE(
|
|
_request: NextRequest,
|
|
{ params }: { params: Promise<{ id: string }> }
|
|
) {
|
|
try {
|
|
const { id } = await params;
|
|
const sql = getDb();
|
|
await sql(`DELETE FROM planning_history_items WHERE planning_id = $1`, [Number(id)]);
|
|
await sql(`DELETE FROM planning_history WHERE id = $1`, [Number(id)]);
|
|
return NextResponse.json({ success: true });
|
|
} catch (error) {
|
|
console.error("Error deleting planning:", error);
|
|
return NextResponse.json(
|
|
{ error: "Failed to delete planning" },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|