61 lines
2.0 KiB
TypeScript
61 lines
2.0 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { getDb } from "@/lib/db";
|
|
|
|
export async function GET(request: NextRequest) {
|
|
try {
|
|
const sql = getDb();
|
|
const { searchParams } = new URL(request.url);
|
|
const source = searchParams.get("source") || "all";
|
|
const productIds = searchParams.get("productIds") || "";
|
|
|
|
let query = `
|
|
SELECT DISTINCT c.id, c.part_number, c.name, c.stock_quantity, c.shelf_location,
|
|
c.customer_supplied, c.customer_id, c.min_stock_level,
|
|
cat.name as category_name,
|
|
cust.name as customer_name
|
|
FROM components c
|
|
LEFT JOIN categories cat ON c.category_id = cat.id
|
|
LEFT JOIN customers cust ON c.customer_id = cust.id
|
|
`;
|
|
|
|
const params: (string | number)[] = [];
|
|
const conditions: string[] = [];
|
|
|
|
// If product filter is specified, join through BOM
|
|
if (productIds) {
|
|
const ids = productIds.split(",").map(Number).filter(Boolean);
|
|
if (ids.length > 0) {
|
|
query += ` INNER JOIN bom_items bi ON bi.component_id = c.id`;
|
|
const placeholders = ids.map((id, idx) => {
|
|
params.push(id);
|
|
return `$${params.length}`;
|
|
});
|
|
conditions.push(`bi.product_id IN (${placeholders.join(",")})`);
|
|
}
|
|
}
|
|
|
|
// Source filter
|
|
if (source === "standard") {
|
|
conditions.push(`(c.customer_supplied = false OR c.customer_supplied IS NULL)`);
|
|
} else if (source.startsWith("customer-")) {
|
|
const customerId = Number(source.replace("customer-", ""));
|
|
if (customerId) {
|
|
params.push(customerId);
|
|
conditions.push(`c.customer_supplied = true AND c.customer_id = $${params.length}`);
|
|
}
|
|
}
|
|
|
|
if (conditions.length > 0) {
|
|
query += ` WHERE ` + conditions.join(" AND ");
|
|
}
|
|
|
|
query += ` ORDER BY c.part_number ASC`;
|
|
|
|
const rows = await sql(query, params);
|
|
return NextResponse.json(rows);
|
|
} catch (error) {
|
|
console.error("Stock take error:", error);
|
|
return NextResponse.json({ error: "Failed to fetch stock take data" }, { status: 500 });
|
|
}
|
|
}
|