Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 1x 1x 1x 1x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 3x 3x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 6x 10x 1x 1x 5x 5x 5x 5x 5x 5x 10x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 6x 6x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 6x 6x 6x 6x 6x 6x 3x 3x 3x 3x 3x 4x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 2x 2x 2x 2x 2x 1x 1x | import { NextRequest, NextResponse } from 'next/server';
import {
withAuth,
withErrorHandling,
createdResponse,
ApiError,
ApiSuccessResponse,
ApiErrorResponse } from "@/lib/api";
import { RouteContext } from "@/lib/api/middleware";
import { prisma } from "@/lib/prisma";
import Stripe from "stripe";
import { z } from "zod";
import { Prisma } from "@prisma/client";
import { Session } from "next-auth";
// Lazy initialization to avoid build-time errors when STRIPE_SECRET_KEY is not set
let stripeClient: Stripe | null = null;
function getStripe(): Stripe {
if (!stripeClient) {
const key = process.env.STRIPE_SECRET_KEY;
if (!key) {
throw new Error("STRIPE_SECRET_KEY is not configured");
}
stripeClient = new Stripe(key);
}
return stripeClient;
}
// Checkout schema
const CheckoutSchema = z.object({
shippingAddress: z.object({
street: z.string().min(5, "Street address must be at least 5 characters"),
city: z.string().min(2, "City must be at least 2 characters"),
state: z.string().min(2, "State must be at least 2 characters"),
zipCode: z.string().min(5, "Zip code must be at least 5 characters"),
country: z.string().min(2, "Country must be at least 2 characters") }),
billingAddress: z.object({
street: z.string().min(5, "Street address must be at least 5 characters"),
city: z.string().min(2, "City must be at least 2 characters"),
state: z.string().min(2, "State must be at least 2 characters"),
zipCode: z.string().min(5, "Zip code must be at least 5 characters"),
country: z.string().min(2, "Country must be at least 2 characters") }),
paymentMethod: z.enum(["credit_card", "paypal", "apple_pay"]).optional() });
// Response type for checkout
interface CheckoutResponse {
order: {
id: number;
status: string;
total: number;
items: Array<{
id: number;
productId: number;
quantity: number;
price: number;
product: {
id: number;
title: string;
sku: string | null;
images: Array<{
url: string;
thumbnailUrl: string | null;
order: number;
}>;
};
}>;
};
payment: {
clientSecret: string | null;
amount: number;
};
}
// POST /api/checkout - Process checkout
async function handlePost(
request: NextRequest,
_context: RouteContext | undefined,
session: Session
): Promise<NextResponse<ApiSuccessResponse<CheckoutResponse> | ApiErrorResponse>> {
const userId = session.user.id;
const body = await request.json();
// Validate input
const validationResult = CheckoutSchema.safeParse(body);
if (!validationResult.success) {
throw ApiError.validation("Invalid checkout data", validationResult.error.issues);
}
const validatedData = validationResult.data;
// Get user's cart with product details
const cartItems = await prisma.cart.findMany({
where: { userId },
include: {
product: {
select: {
id: true,
title: true,
discountedPrice: true,
stock: true,
sku: true } } } });
if (cartItems.length === 0) {
throw ApiError.cartEmpty();
}
// Check inventory availability for all items
const insufficientStock = cartItems.find(
(item) => item.product.stock < item.quantity
);
if (insufficientStock) {
throw ApiError.validation("Insufficient inventory", [
{
code: "custom",
message: `Insufficient stock for ${insufficientStock.product.title}`,
path: ["items", insufficientStock.productId.toString()],
params: {
productId: insufficientStock.productId,
productTitle: insufficientStock.product.title,
requested: insufficientStock.quantity,
available: insufficientStock.product.stock } },
]);
}
// Calculate total
const total = cartItems.reduce(
(sum: number, item) => sum + item.product.discountedPrice * item.quantity,
0
);
// Create order and payment intent in transaction
const result = await prisma.$transaction(async (tx: Prisma.TransactionClient) => {
// Create order
const newOrder = await tx.order.create({
data: {
userId,
status: "PROCESSING",
total,
shippingAddress: JSON.stringify(validatedData.shippingAddress),
billingAddress: JSON.stringify(validatedData.billingAddress),
items: {
createMany: {
data: cartItems.map((item) => ({
productId: item.productId,
quantity: item.quantity,
price: item.product.discountedPrice })) } } },
include: {
items: {
include: {
product: {
select: {
id: true,
title: true,
sku: true,
images: {
select: {
url: true,
thumbnailUrl: true,
order: true },
take: 1,
orderBy: {
order: "asc" as const } } } } } } } });
// Update inventory for all products
for (const item of cartItems) {
await tx.product.update({
where: { id: item.productId },
data: {
stock: {
decrement: item.quantity } } });
}
// Clear cart
await tx.cart.deleteMany({ where: { userId } });
return newOrder;
});
// Create Stripe payment intent
const paymentIntent = await getStripe().paymentIntents.create({
amount: Math.round(total * 100), // Convert to cents
currency: "usd",
metadata: {
orderId: result.id.toString(),
userId: userId.toString() } });
return createdResponse({
order: result,
payment: {
clientSecret: paymentIntent.client_secret,
amount: total } });
}
export const POST = withErrorHandling(withAuth(handlePost));
|