mega-plant/app/api/suppliers/route.ts
David cfd54385b3 Add Suppliers list; book purchase orders and petty-cash slips against it
- /expenses/suppliers: terms (cash / 30 / 60 days), PO + petty cash totals per supplier,
  period filters, add/edit/delete, due dates
- POs and slips resolve to a supplier by code then folded name; new PO suppliers start
  with terms unset, new slip suppliers as cash
- Full-user guard on cash-float and job-card write routes

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-22 15:43:57 +02:00

31 lines
1.7 KiB
TypeScript

import { revalidatePath } from "next/cache";
import { serverAuth } from "@/lib/pb";
import { refuseUnlessFull } from "@/lib/require-full";
import { parseTerms, supplierKey } from "@/lib/supplier";
export const dynamic = "force-dynamic";
// POST /api/suppliers { name, code?, terms, notes? } — add a supplier to the list by hand.
export async function POST(req: Request) {
const refused = await refuseUnlessFull();
if (refused) return refused;
let body: { name?: unknown; code?: unknown; terms?: unknown; notes?: unknown } = {};
try { body = await req.json(); } catch { return Response.json({ ok: false, error: "Invalid JSON body" }, { status: 400 }); }
const name = String(body.name ?? "").trim();
const key = supplierKey(name);
if (!name || !key) return Response.json({ ok: false, error: "Enter the supplier's name." }, { status: 400 });
if (name.length > 200) return Response.json({ ok: false, error: "That name is too long." }, { status: 400 });
try {
const pb = await serverAuth();
const clash = (await pb.collection("suppliers").getFullList({ fields: "id,name,key" })).find((s) => s.key === key);
if (clash) return Response.json({ ok: false, error: `"${clash.name}" is already on the list.` }, { status: 409 });
await pb.collection("suppliers").create({
name, key, code: String(body.code ?? "").trim().toUpperCase().slice(0, 40), terms: parseTerms(body.terms),
notes: String(body.notes ?? "").trim().slice(0, 1000), source: "Added in app",
});
revalidatePath("/expenses/suppliers");
return Response.json({ ok: true });
} catch (e: any) {
return Response.json({ ok: false, error: e?.message || "Could not save" }, { status: 500 });
}
}