import { NextRequest, NextResponse } from 'next/server'; import { getServerSession } from 'next-auth'; import { authOptions } from '@/lib/auth'; import { prisma } from '@/lib/prisma'; // POST - 初始化3D原图素材记录 export async function POST(request: NextRequest) { try { const session = await getServerSession(authOptions); if (!session) { return NextResponse.json({ error: '请先登录' }, { status: 401 }); } const body = await request.json(); const { taskNo, productModel, categoryName, sceneName, platformName, productCategoryName } = body; // 验证必填字段 if (!productModel || !categoryName || !sceneName) { return NextResponse.json( { error: '缺少必填字段' }, { status: 400 } ); } // 验证任务号格式(如果提供) if (taskNo) { const taskNoRegex = /^TASK\d{12,18}(-\d{2})*$/; if (!taskNoRegex.test(taskNo)) { return NextResponse.json( { error: '任务号格式错误' }, { status: 400 } ); } // 检查任务号是否已存在(排除已删除的素材) const existingMaterial = await prisma.material.findFirst({ where: { taskNo, deletedAt: null, // 只检查未删除的素材 }, select: { id: true, productModel: true, materialType: true }, }); if (existingMaterial) { return NextResponse.json( { error: `任务号 ${taskNo} 已存在,对应素材:${existingMaterial.productModel}(${existingMaterial.materialType})` }, { status: 400 } ); } } // 获取用户信息 const user = await prisma.user.findUnique({ where: { id: (session.user as any).id }, select: { username: true }, }); if (!user) { return NextResponse.json( { error: '用户不存在' }, { status: 404 } ); } // 创建素材记录(使用临时预览图) const material = await prisma.material.create({ data: { materialType: '任务-3D原图', productModel, categoryName, sceneName, platformName: platformName || '', productCategoryName: productCategoryName || '', authorName: user.username, userId: (session.user as any).id, previewUrl: '', // 临时空值,完成上传时更新 zipFilePath: '', // 临时空值,完成上传时更新 zipFileName: '', // 临时空值,完成上传时更新 renderer: '', // 3D原图不需要渲染器 taskNo: taskNo || null, // 任务号(可选) }, }); return NextResponse.json({ success: true, materialId: material.id, }); } catch (error: any) { console.error('[3D Original Init Error]', error); // 捕获 Prisma 唯一约束错误(任务号重复) if (error?.code === 'P2002' && error?.meta?.target?.includes('task_no')) { return NextResponse.json( { error: `任务号已被使用,请检查是否重复提交` }, { status: 400 } ); } return NextResponse.json( { error: error.message || '初始化失败' }, { status: 500 } ); } }