87 lines
2.3 KiB
JavaScript
87 lines
2.3 KiB
JavaScript
import { NextResponse } from "next/server";
|
|
import { prisma } from "@/lib/prisma";
|
|
|
|
// GET all inventory items
|
|
export async function GET() {
|
|
try {
|
|
const items = await prisma.inventoryItem.findMany({
|
|
orderBy: { createdAt: "desc" },
|
|
});
|
|
return NextResponse.json(items);
|
|
} catch (error) {
|
|
return NextResponse.json({ error: "Failed to fetch inventory" }, { status: 500 });
|
|
}
|
|
}
|
|
|
|
// POST a new item (or update if exists)
|
|
export async function POST(req) {
|
|
try {
|
|
const body = await req.json();
|
|
const { qrCodeId, name, quantity, price, category, description } = body;
|
|
|
|
const newItem = await prisma.inventoryItem.upsert({
|
|
where: { qrCodeId },
|
|
update: {
|
|
name,
|
|
quantity: quantity || 0,
|
|
price: price || 0.0,
|
|
category: category || "",
|
|
description: description || "",
|
|
},
|
|
create: {
|
|
qrCodeId,
|
|
name,
|
|
quantity: quantity || 0,
|
|
price: price || 0.0,
|
|
category: category || "",
|
|
description: description || "",
|
|
},
|
|
});
|
|
|
|
return NextResponse.json(newItem, { status: 201 });
|
|
} catch (error) {
|
|
return NextResponse.json({ error: "Failed to create or update item", details: error.message }, { status: 500 });
|
|
}
|
|
}
|
|
|
|
// PUT (Update) an existing item
|
|
export async function PUT(req) {
|
|
try {
|
|
const body = await req.json();
|
|
const { id, ...updateData } = body;
|
|
|
|
if (!id) {
|
|
return NextResponse.json({ error: "Item ID is required" }, { status: 400 });
|
|
}
|
|
|
|
const updatedItem = await prisma.inventoryItem.update({
|
|
where: { id },
|
|
data: updateData,
|
|
});
|
|
|
|
return NextResponse.json(updatedItem, { status: 200 });
|
|
} catch (error) {
|
|
return NextResponse.json({ error: "Failed to update item", details: error.message }, { status: 500 });
|
|
}
|
|
}
|
|
|
|
// DELETE an item
|
|
export async function DELETE(req) {
|
|
try {
|
|
const { searchParams } = new URL(req.url);
|
|
const id = searchParams.get("id");
|
|
|
|
if (!id) {
|
|
return NextResponse.json({ error: "Item ID is required" }, { status: 400 });
|
|
}
|
|
|
|
await prisma.inventoryItem.delete({
|
|
where: { id },
|
|
});
|
|
|
|
return NextResponse.json({ message: "Item deleted successfully" }, { status: 200 });
|
|
} catch (error) {
|
|
return NextResponse.json({ error: "Failed to delete item", details: error.message }, { status: 500 });
|
|
}
|
|
}
|