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 customerId = searchParams.get("customerId"); const status = searchParams.get("status"); const search = searchParams.get("search") || ""; let query = ` SELECT po.*, c.name AS customer_name, c.code AS customer_code, COUNT(poi.id) AS item_count, COALESCE(SUM(poi.quantity * poi.unit_price), 0) AS total_value, COALESCE(SUM(poi.quantity), 0) AS total_ordered, COALESCE(SUM(poi.shipped_quantity), 0) AS total_shipped FROM purchase_orders po JOIN customers c ON c.id = po.customer_id LEFT JOIN purchase_order_items poi ON poi.purchase_order_id = po.id `; const conditions: string[] = []; const params: (string | number)[] = []; let idx = 1; if (customerId) { conditions.push(`po.customer_id = $${idx++}`); params.push(Number(customerId)); } if (status) { const statuses = status.split(",").map((s) => s.trim()); const placeholders = statuses.map(() => `$${idx++}`).join(", "); conditions.push(`po.status IN (${placeholders})`); params.push(...statuses); } if (search) { conditions.push( `(po.po_number ILIKE $${idx} OR c.name ILIKE $${idx} OR po.customer_ref ILIKE $${idx})` ); params.push(`%${search}%`); idx++; } if (conditions.length > 0) { query += ` WHERE ${conditions.join(" AND ")}`; } query += ` GROUP BY po.id, c.name, c.code ORDER BY po.created_at DESC`; const rows = await sql(query, params); return NextResponse.json(rows); } catch (error) { console.error("[v0] Orders GET error:", error); return NextResponse.json( { error: error instanceof Error ? error.message : "Failed to fetch orders" }, { status: 500 } ); } } export async function POST(request: NextRequest) { try { const sql = getDb(); const body = await request.json(); const { customer_id, po_number, customer_ref, status, order_date, due_date, notes, items, } = body; if (!customer_id || !po_number) { return NextResponse.json( { error: "Customer and PO number are required" }, { status: 400 } ); } // Create the order const orderRows = await sql( `INSERT INTO purchase_orders (customer_id, po_number, customer_ref, status, order_date, due_date, notes) VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING *`, [ customer_id, po_number, customer_ref || null, status || "draft", order_date || new Date().toISOString().slice(0, 10), due_date || null, notes || null, ] ); const order = orderRows[0]; // Create items if provided if (items && Array.isArray(items) && items.length > 0) { for (const item of items) { await sql( `INSERT INTO purchase_order_items (purchase_order_id, product_id, quantity, unit_price, notes) VALUES ($1, $2, $3, $4, $5)`, [ order.id, item.product_id, item.quantity, item.unit_price || 0, item.notes || null, ] ); } } return NextResponse.json(order, { status: 201 }); } catch (error) { console.error("[v0] Orders POST error:", error); return NextResponse.json( { error: error instanceof Error ? error.message : "Failed to create order" }, { status: 500 } ); } }