126 lines
4.2 KiB
TypeScript
126 lines
4.2 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 search = searchParams.get("search");
|
|
|
|
let query = `
|
|
SELECT spl.*,
|
|
s.name AS supplier_name,
|
|
s.code AS supplier_code,
|
|
s.email AS supplier_email,
|
|
s.phone AS supplier_phone,
|
|
s.address AS supplier_address,
|
|
s.contact_person AS supplier_contact,
|
|
(SELECT COUNT(*) FROM supplier_packing_list_items spli WHERE spli.supplier_packing_list_id = spl.id) AS item_count,
|
|
(SELECT COALESCE(SUM(spli.quantity), 0) FROM supplier_packing_list_items spli WHERE spli.supplier_packing_list_id = spl.id) AS total_quantity
|
|
FROM supplier_packing_lists spl
|
|
JOIN suppliers s ON s.id = spl.supplier_id
|
|
`;
|
|
const conditions: string[] = [];
|
|
const params: (string | number)[] = [];
|
|
|
|
if (search) {
|
|
params.push(`%${search}%`);
|
|
const i = params.length;
|
|
conditions.push(
|
|
`(spl.packing_number ILIKE $${i} OR s.name ILIKE $${i})`
|
|
);
|
|
}
|
|
|
|
if (conditions.length > 0) {
|
|
query += ` WHERE ${conditions.join(" AND ")}`;
|
|
}
|
|
query += ` ORDER BY spl.created_at DESC`;
|
|
|
|
const rows = await sql(query, params);
|
|
return NextResponse.json(rows);
|
|
} catch (error) {
|
|
console.error("[v0] Supplier packing list GET error:", error);
|
|
return NextResponse.json(
|
|
{ error: error instanceof Error ? error.message : "Failed to fetch supplier packing lists" },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|
|
|
|
export async function POST(request: NextRequest) {
|
|
try {
|
|
const sql = getDb();
|
|
const body = await request.json();
|
|
const { supplier_id, items, notes } = body;
|
|
|
|
if (!supplier_id || !items?.length) {
|
|
return NextResponse.json(
|
|
{ error: "supplier_id and items are required" },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
// Validate items have component_id and quantity
|
|
for (const item of items) {
|
|
if (!item.component_id || !item.quantity || item.quantity <= 0) {
|
|
return NextResponse.json(
|
|
{ error: "Each item must have a component_id and a positive quantity" },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
}
|
|
|
|
// Fetch supplier name for packing number generation
|
|
const supplierRows = await sql(
|
|
`SELECT name FROM suppliers WHERE id = $1`,
|
|
[supplier_id]
|
|
);
|
|
if (supplierRows.length === 0) {
|
|
return NextResponse.json({ error: "Supplier not found" }, { status: 404 });
|
|
}
|
|
const supplierName = String(supplierRows[0].name).replace(/[^a-zA-Z0-9]/g, "").toUpperCase();
|
|
|
|
// Generate packing number: PL-EACH-YYYY_MM_DD-RR-SUPPLIERNAME
|
|
const now = new Date();
|
|
const yyyy = now.getFullYear();
|
|
const mm = String(now.getMonth() + 1).padStart(2, "0");
|
|
const dd = String(now.getDate()).padStart(2, "0");
|
|
const datePrefix = `PL-EACH-${yyyy}_${mm}_${dd}`;
|
|
const dateSuffix = `-${supplierName}`;
|
|
|
|
// Count existing supplier packing lists with same date + supplier to determine revision
|
|
const existingRows = await sql(
|
|
`SELECT COUNT(*) AS cnt FROM supplier_packing_lists WHERE packing_number LIKE $1`,
|
|
[`${datePrefix}-%${dateSuffix}`]
|
|
);
|
|
const revision = Number(existingRows[0].cnt) + 1;
|
|
const packing_number = `${datePrefix}-${String(revision).padStart(2, "0")}${dateSuffix}`;
|
|
|
|
// Create supplier packing list
|
|
const plRows = await sql(
|
|
`INSERT INTO supplier_packing_lists (supplier_id, packing_number, notes)
|
|
VALUES ($1, $2, $3)
|
|
RETURNING *`,
|
|
[supplier_id, packing_number, notes || null]
|
|
);
|
|
const packingList = plRows[0];
|
|
|
|
// Insert items
|
|
for (const item of items) {
|
|
await sql(
|
|
`INSERT INTO supplier_packing_list_items (supplier_packing_list_id, component_id, quantity)
|
|
VALUES ($1, $2, $3)`,
|
|
[packingList.id, item.component_id, item.quantity]
|
|
);
|
|
}
|
|
|
|
return NextResponse.json(packingList, { status: 201 });
|
|
} catch (error) {
|
|
console.error("[v0] Supplier packing list POST error:", error);
|
|
return NextResponse.json(
|
|
{ error: error instanceof Error ? error.message : "Failed to create supplier packing list" },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|