30 lines
1.3 KiB
TypeScript
30 lines
1.3 KiB
TypeScript
import { NextResponse } from 'next/server';
|
|
import { getCurrentUser } from '@/lib/server/auth';
|
|
import { checkoutSchema, createOrder } from '@/lib/server/store';
|
|
import { recordAudit } from '@/lib/server/audit';
|
|
import { sendEmail } from '@/lib/server/email';
|
|
|
|
export const dynamic = 'force-dynamic';
|
|
|
|
export async function POST(request: Request) {
|
|
const parsed = checkoutSchema.safeParse(await request.json().catch(() => ({})));
|
|
if (!parsed.success) {
|
|
return NextResponse.json({ error: 'Please provide a valid email, address and cart.' }, { status: 400 });
|
|
}
|
|
const user = await getCurrentUser();
|
|
const result = await createOrder(parsed.data, user?.id);
|
|
if (!result.ok) return NextResponse.json({ error: result.error }, { status: 409 });
|
|
|
|
await recordAudit({ actorId: user?.id ?? null, action: 'order.created', target: result.order.providerRef ?? result.order.id, meta: { total: result.order.total } });
|
|
await sendEmail({
|
|
to: result.order.email,
|
|
subject: `Order ${result.order.id.slice(0, 8)} confirmed`,
|
|
html: `<p>Thanks! Your order of $${(result.order.total / 100).toFixed(2)} is confirmed.</p>`,
|
|
}).catch((e) => console.error('[email] order', e));
|
|
|
|
return NextResponse.json(
|
|
{ order: { id: result.order.id, status: result.order.status, total: result.order.total } },
|
|
{ status: 201 },
|
|
);
|
|
}
|