Files
ipv6-sims/app/api/payments/create-order/route.ts
T
2026-05-19 12:48:41 +07:00

84 lines
2.3 KiB
TypeScript

export const runtime = "nodejs";
import { NextRequest, NextResponse } from "next/server";
import { createPayPalOrder } from "@/lib/paypal";
import { createRegistrationWithPayment } from "@/lib/summit-requests";
import type { AdminRequestRow } from "@/types/admin-submission";
interface CreateOrderBody {
fullName: string;
phone?: string;
email: string;
company?: string;
jobTitle?: string;
industry?: string;
industryLabel?: string;
notes?: string;
}
export async function POST(req: NextRequest): Promise<NextResponse> {
let body: CreateOrderBody;
try {
body = (await req.json()) as CreateOrderBody;
} catch {
return NextResponse.json({ error: "Invalid JSON body." }, { status: 400 });
}
// Validate required fields
if (!body.fullName || !body.email) {
console.error("[create-order] Validation failed — fullName:", JSON.stringify(body.fullName), "email:", JSON.stringify(body.email));
return NextResponse.json(
{ error: "fullName and email are required." },
{ status: 400 }
);
}
// Generate a short unique public ID
const publicId = "V6-" + crypto.randomUUID().slice(0, 8).toUpperCase();
// Build the AdminRequestRow
const row: AdminRequestRow = {
id: publicId,
submittedAt: new Date().toISOString().slice(0, 10),
displayDate: new Date()
.toLocaleDateString("en-GB", {
day: "2-digit",
month: "short",
year: "numeric",
})
.toUpperCase(),
fullName: body.fullName,
jobTitle: body.jobTitle ?? "",
company: body.company ?? "",
segment: body.industry ?? "",
email: body.email,
phone: body.phone ?? "",
status: "pending",
notes: body.notes ?? "",
source: "registration",
};
// Create the PayPal order
let orderId: string;
let approvalUrl: string;
try {
const result = await createPayPalOrder(publicId);
orderId = result.orderId;
approvalUrl = result.approvalUrl;
} catch (err) {
const message = err instanceof Error ? err.message : "PayPal order creation failed.";
console.error("[create-order] PayPal error:", message);
return NextResponse.json({ error: message }, { status: 502 });
}
// Persist the registration with the pending payment
await createRegistrationWithPayment(row, orderId);
return NextResponse.json(
{ approvalUrl, registrationId: publicId },
{ status: 200 }
);
}