2025-06-22 11:34:32 +08:00

166 lines
3.7 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'
import { verifyToken } from '@/lib/auth'
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const { id } = await params
const authHeader = request.headers.get('authorization')
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return NextResponse.json(
{ message: '请先登录' },
{ status: 401 }
)
}
const token = authHeader.substring(7)
const decoded = verifyToken(token)
if (!decoded) {
return NextResponse.json(
{ message: '登录已过期' },
{ status: 401 }
)
}
const order = await prisma.order.findFirst({
where: {
id: id,
userId: decoded.userId
},
include: {
orderItems: {
include: {
component: {
include: {
componentType: true
}
}
}
},
user: {
select: {
username: true,
email: true
}
}
}
})
if (!order) {
return NextResponse.json(
{ message: '订单不存在' },
{ status: 404 }
)
}
return NextResponse.json(order)
} catch (error) {
console.error('获取订单详情失败:', error)
return NextResponse.json(
{ message: '获取订单详情失败' },
{ status: 500 }
)
}
}
export async function PUT(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const { id } = await params
const authHeader = request.headers.get('authorization')
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return NextResponse.json(
{ message: '请先登录' },
{ status: 401 }
)
}
const token = authHeader.substring(7)
const decoded = verifyToken(token)
if (!decoded) {
return NextResponse.json(
{ message: '登录已过期' },
{ status: 401 }
)
}
const { action } = await request.json()
// 查找订单
const order = await prisma.order.findFirst({
where: {
id: id,
userId: decoded.userId
},
include: {
orderItems: true
}
})
if (!order) {
return NextResponse.json(
{ message: '订单不存在' },
{ status: 404 }
)
}
// 处理不同的操作
if (action === 'cancel') {
// 只有待确认状态的订单可以取消
if (order.status !== 'PENDING') {
return NextResponse.json(
{ message: '当前订单状态不允许取消' },
{ status: 400 }
)
} // 更新订单状态为取消
const updatedOrder = await prisma.order.update({
where: { id: id },
data: { status: 'CANCELLED' },
include: {
orderItems: {
include: {
component: {
include: {
componentType: true
}
}
}
}
}
})
// 恢复库存
for (const item of order.orderItems) {
await prisma.component.update({
where: { id: item.componentId },
data: {
stock: {
increment: item.quantity
}
}
})
}
return NextResponse.json(updatedOrder)
}
return NextResponse.json(
{ message: '不支持的操作' },
{ status: 400 }
)
} catch (error) {
console.error('更新订单失败:', error)
return NextResponse.json(
{ message: '更新订单失败' },
{ status: 500 }
)
}
}