Enhance checkout flow with new components and validation
- Added AddressForm and CheckoutForm components for user input during checkout. - Implemented validation using Zod and VeeValidate for billing address fields. - Created OrderSummary and MockPayPalButton components for order confirmation and payment simulation. - Updated CartSheet and CartSidebar to navigate to the new checkout page at '/kasse'. - Introduced new API endpoints for validating checkout data and creating orders. - Enhanced user experience with responsive design and error handling. These changes complete the checkout functionality, allowing users to enter billing information, simulate payment, and confirm orders.
This commit is contained in:
89
server/api/orders/[id].get.ts
Normal file
89
server/api/orders/[id].get.ts
Normal file
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* GET /api/orders/[id]
|
||||
*
|
||||
* Fetch order details by ID
|
||||
*
|
||||
* Security:
|
||||
* - Requires authentication
|
||||
* - Users can only access their own orders
|
||||
*
|
||||
* Response:
|
||||
* {
|
||||
* id: string
|
||||
* orderNumber: string
|
||||
* totalAmount: string
|
||||
* status: string
|
||||
* billingAddress: BillingAddress
|
||||
* items: OrderItem[]
|
||||
* createdAt: Date
|
||||
* }
|
||||
*/
|
||||
|
||||
import { eq, and } from 'drizzle-orm'
|
||||
import { orders, orderItems } from '../../database/schema'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
// Require authentication
|
||||
const { user } = await requireUserSession(event)
|
||||
|
||||
// Get order ID from URL parameter
|
||||
const orderId = getRouterParam(event, 'id')
|
||||
|
||||
if (!orderId) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: 'Order ID is required',
|
||||
})
|
||||
}
|
||||
|
||||
const db = useDatabase()
|
||||
|
||||
// Fetch order with items
|
||||
const order = await db.query.orders.findFirst({
|
||||
where: and(eq(orders.id, orderId), eq(orders.userId, user.id)),
|
||||
with: {
|
||||
items: {
|
||||
with: {
|
||||
product: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if (!order) {
|
||||
throw createError({
|
||||
statusCode: 404,
|
||||
statusMessage: 'Order not found',
|
||||
})
|
||||
}
|
||||
|
||||
// Transform items to include price and product snapshot data
|
||||
const transformedItems = order.items.map((item: any) => ({
|
||||
id: item.id,
|
||||
orderId: item.orderId,
|
||||
productId: item.productId,
|
||||
quantity: item.quantity,
|
||||
priceSnapshot: item.priceSnapshot,
|
||||
productSnapshot: item.productSnapshot,
|
||||
product: {
|
||||
id: item.product.id,
|
||||
name: item.product.name,
|
||||
description: item.product.description,
|
||||
imageUrl: item.product.imageUrl,
|
||||
},
|
||||
subtotal: Number.parseFloat(item.priceSnapshot) * item.quantity,
|
||||
}))
|
||||
|
||||
return {
|
||||
id: order.id,
|
||||
orderNumber: order.orderNumber,
|
||||
totalAmount: order.totalAmount,
|
||||
status: order.status,
|
||||
billingAddress: order.billingAddress,
|
||||
items: transformedItems,
|
||||
paymentId: order.paymentId,
|
||||
paymentCompletedAt: order.paymentCompletedAt,
|
||||
createdAt: order.createdAt,
|
||||
updatedAt: order.updatedAt,
|
||||
}
|
||||
})
|
||||
85
server/api/orders/confirm/[id].post.ts
Normal file
85
server/api/orders/confirm/[id].post.ts
Normal file
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* POST /api/orders/confirm/[id]
|
||||
*
|
||||
* Confirm an order after mock payment
|
||||
*
|
||||
* Security:
|
||||
* - Requires authentication
|
||||
* - Users can only confirm their own orders
|
||||
* - Order must be in 'pending' status
|
||||
*
|
||||
* Behavior:
|
||||
* - Updates order status: 'pending' → 'completed'
|
||||
* - Stores completion timestamp
|
||||
* - Clears user's cart
|
||||
* - Returns order details
|
||||
*
|
||||
* Response:
|
||||
* {
|
||||
* success: true
|
||||
* order: Order
|
||||
* message: string
|
||||
* }
|
||||
*/
|
||||
|
||||
import { eq, and } from 'drizzle-orm'
|
||||
import { orders, cartItems } from '../../../database/schema'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
// Require authentication
|
||||
const { user } = await requireUserSession(event)
|
||||
|
||||
// Get order ID from URL parameter
|
||||
const orderId = getRouterParam(event, 'id')
|
||||
|
||||
if (!orderId) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: 'Order ID is required',
|
||||
})
|
||||
}
|
||||
|
||||
const db = useDatabase()
|
||||
|
||||
// Fetch order
|
||||
const order = await db.query.orders.findFirst({
|
||||
where: and(eq(orders.id, orderId), eq(orders.userId, user.id)),
|
||||
})
|
||||
|
||||
if (!order) {
|
||||
throw createError({
|
||||
statusCode: 404,
|
||||
statusMessage: 'Order not found',
|
||||
})
|
||||
}
|
||||
|
||||
// Validate order status
|
||||
if (order.status !== 'pending') {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: `Order cannot be confirmed. Current status: ${order.status}`,
|
||||
})
|
||||
}
|
||||
|
||||
// Update order status to completed
|
||||
const [updatedOrder] = await db
|
||||
.update(orders)
|
||||
.set({
|
||||
status: 'completed',
|
||||
paymentCompletedAt: new Date(),
|
||||
paymentId: `MOCK-${Date.now()}`, // Mock payment ID
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(eq(orders.id, orderId))
|
||||
.returning()
|
||||
|
||||
// Clear user's cart
|
||||
const cart = await getOrCreateCart(event)
|
||||
await db.delete(cartItems).where(eq(cartItems.cartId, cart.id))
|
||||
|
||||
return {
|
||||
success: true,
|
||||
order: updatedOrder,
|
||||
message: 'Bestellung erfolgreich bestätigt',
|
||||
}
|
||||
})
|
||||
145
server/api/orders/create.post.ts
Normal file
145
server/api/orders/create.post.ts
Normal file
@@ -0,0 +1,145 @@
|
||||
/**
|
||||
* POST /api/orders/create
|
||||
*
|
||||
* Create a new order from the user's cart
|
||||
*
|
||||
* Request Body:
|
||||
* {
|
||||
* salutation: 'male' | 'female' | 'other'
|
||||
* firstName: string
|
||||
* lastName: string
|
||||
* dateOfBirth: string (YYYY-MM-DD)
|
||||
* street: string
|
||||
* postCode: string
|
||||
* city: string
|
||||
* countryCode: string
|
||||
* saveAddress: boolean (optional, default: false)
|
||||
* }
|
||||
*
|
||||
* Behavior:
|
||||
* - Creates order with status 'pending'
|
||||
* - Copies cart items to order_items with price snapshot
|
||||
* - Stores billing address snapshot in order
|
||||
* - Generates unique order number (format: EXP-2025-00001)
|
||||
* - Optionally saves address to user profile
|
||||
* - Does NOT clear cart (cart is cleared after order confirmation)
|
||||
*
|
||||
* Response:
|
||||
* {
|
||||
* success: true
|
||||
* orderId: string
|
||||
* orderNumber: string
|
||||
* message: string
|
||||
* }
|
||||
*/
|
||||
|
||||
import { checkoutSchema } from '../../utils/schemas/checkout'
|
||||
import { orders, orderItems, users } from '../../database/schema'
|
||||
import { eq, desc, sql } from 'drizzle-orm'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
// Require authentication
|
||||
const { user } = await requireUserSession(event)
|
||||
|
||||
// Validate request body
|
||||
const body = await readBody(event)
|
||||
const checkoutData = await checkoutSchema.parseAsync(body)
|
||||
|
||||
const db = useDatabase()
|
||||
|
||||
// Get user's cart
|
||||
const cart = await getOrCreateCart(event)
|
||||
const cartSummary = await getCartWithItems(cart.id)
|
||||
|
||||
// Validate cart has items
|
||||
if (cartSummary.items.length === 0) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: 'Warenkorb ist leer',
|
||||
})
|
||||
}
|
||||
|
||||
// Generate unique order number
|
||||
// Format: EXP-YYYY-NNNNN (e.g., EXP-2025-00001)
|
||||
const year = new Date().getFullYear()
|
||||
|
||||
// Get the highest order number for this year
|
||||
const lastOrder = await db.query.orders.findFirst({
|
||||
where: sql`${orders.orderNumber} LIKE ${`EXP-${year}-%`}`,
|
||||
orderBy: desc(orders.createdAt),
|
||||
})
|
||||
|
||||
let sequenceNumber = 1
|
||||
if (lastOrder) {
|
||||
// Extract sequence number from last order number (EXP-2025-00123 -> 123)
|
||||
const match = lastOrder.orderNumber.match(/EXP-\d{4}-(\d{5})/)
|
||||
if (match) {
|
||||
sequenceNumber = Number.parseInt(match[1], 10) + 1
|
||||
}
|
||||
}
|
||||
|
||||
const orderNumber = `EXP-${year}-${String(sequenceNumber).padStart(5, '0')}`
|
||||
|
||||
// Prepare billing address (exclude saveAddress flag)
|
||||
const billingAddress = {
|
||||
salutation: checkoutData.salutation,
|
||||
firstName: checkoutData.firstName,
|
||||
lastName: checkoutData.lastName,
|
||||
dateOfBirth: checkoutData.dateOfBirth,
|
||||
street: checkoutData.street,
|
||||
postCode: checkoutData.postCode,
|
||||
city: checkoutData.city,
|
||||
countryCode: checkoutData.countryCode,
|
||||
}
|
||||
|
||||
// Create order
|
||||
const [order] = await db
|
||||
.insert(orders)
|
||||
.values({
|
||||
orderNumber,
|
||||
userId: user.id,
|
||||
totalAmount: cartSummary.total.toFixed(2),
|
||||
status: 'pending', // Order starts as pending (awaiting mock payment)
|
||||
billingAddress,
|
||||
})
|
||||
.returning()
|
||||
|
||||
// Create order items with price snapshots
|
||||
const orderItemsData = cartSummary.items.map((item) => ({
|
||||
orderId: order.id,
|
||||
productId: item.productId,
|
||||
quantity: item.quantity,
|
||||
priceSnapshot: item.product.price, // Snapshot price at time of order
|
||||
productSnapshot: {
|
||||
name: item.product.name,
|
||||
description: item.product.description,
|
||||
navProductId: item.product.navProductId,
|
||||
category: item.product.category,
|
||||
},
|
||||
}))
|
||||
|
||||
await db.insert(orderItems).values(orderItemsData)
|
||||
|
||||
// Optionally save address to user profile
|
||||
if (checkoutData.saveAddress) {
|
||||
await db
|
||||
.update(users)
|
||||
.set({
|
||||
salutation: checkoutData.salutation,
|
||||
dateOfBirth: new Date(checkoutData.dateOfBirth),
|
||||
street: checkoutData.street,
|
||||
postCode: checkoutData.postCode,
|
||||
city: checkoutData.city,
|
||||
countryCode: checkoutData.countryCode,
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(eq(users.id, user.id))
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
orderId: order.id,
|
||||
orderNumber: order.orderNumber,
|
||||
message: 'Bestellung erfolgreich erstellt',
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user