diff options
| author | dujinkim <dujin.kim@dtsolution.co.kr> | 2025-10-01 06:26:44 +0000 |
|---|---|---|
| committer | dujinkim <dujin.kim@dtsolution.co.kr> | 2025-10-01 06:26:44 +0000 |
| commit | d689608ca2a54cab2cd12a12f0b6007a1be39ab2 (patch) | |
| tree | bb93e630c18b3028322f7f7aee87547e893f5df7 /app | |
| parent | 7021eca8f53e398f55f775c6dc431bca9670fabe (diff) | |
(대표님, 최겸) 구매 견적 첨부파일 type 오류 수정, 문서확정, short list 기능 수정
Diffstat (limited to 'app')
| -rw-r--r-- | app/api/partners/rfq-last/[id]/response/route.ts | 104 |
1 files changed, 65 insertions, 39 deletions
diff --git a/app/api/partners/rfq-last/[id]/response/route.ts b/app/api/partners/rfq-last/[id]/response/route.ts index 21a4e7a4..bfbeb246 100644 --- a/app/api/partners/rfq-last/[id]/response/route.ts +++ b/app/api/partners/rfq-last/[id]/response/route.ts @@ -9,7 +9,7 @@ import { rfqLastVendorAttachments, rfqLastVendorResponseHistory } from "@/db/schema" -import { eq, and } from "drizzle-orm" +import { eq, and, inArray } from "drizzle-orm" import { writeFile, mkdir } from "fs/promises" import { createWriteStream } from "fs" import { pipeline } from "stream/promises" @@ -48,15 +48,15 @@ export async function POST( const data = JSON.parse(formData.get('data') as string) const files = formData.getAll('attachments') as File[] - // 업로드 디렉토리 생성 + // 업로드 디렉토리 생성 (벤더 응답용) const isDev = process.env.NODE_ENV === 'development' const uploadDir = isDev ? path.join(process.cwd(), 'public', 'uploads', 'rfq', rfqId.toString()) : path.join(process.env.NAS_PATH || '/nas', 'uploads', 'rfq', rfqId.toString()) await mkdir(uploadDir, { recursive: true }) - - // 트랜잭션 시작 (DB 작업만) + + // 트랜잭션 시작 const result = await db.transaction(async (tx) => { // 1. 벤더 응답 생성 const [vendorResponse] = await tx.insert(rfqLastVendorResponses).values({ @@ -135,31 +135,39 @@ export async function POST( itemRemark: item.itemRemark, deviationReason: item.deviationReason, })) - + await tx.insert(rfqLastVendorQuotationItems).values(quotationItemsData) } - - // 3. 이력 기록 + + // 이력 기록 await tx.insert(rfqLastVendorResponseHistory).values({ - vendorResponseId: vendorResponse.id, - action: "생성", - previousStatus: null, + vendorResponseId: vendorResponseId, + action: isNewResponse ? "생성" : (data.status === "제출완료" ? "제출" : "수정"), + previousStatus: existingResponse?.status || null, newStatus: data.status || "작성중", changeDetails: data, performedBy: session.user.id, }) - - return vendorResponse + + return { id: vendorResponseId, isNew: isNewResponse } }) - // 4. 파일 저장 (트랜잭션 밖에서 처리) + // 파일 저장 (트랜잭션 밖에서 처리) const fileRecords = [] - + if (files.length > 0) { + console.log(`저장할 파일 수: ${files.length}`) + console.log('파일 메타데이터:', data.fileMetadata) + for (let i = 0; i < files.length; i++) { const file = files[i] - const metadata = data.fileMetadata?.[i] // 인덱스로 메타데이터 매칭 - + // 파일 메타데이터에서 attachmentType 정보 가져옴 + const metadata = data.fileMetadata && data.fileMetadata[i] + const attachmentType = metadata?.attachmentType || "기타" + const description = metadata?.description || "" + + console.log(`파일 ${i + 1} 처리: ${file.name}, 파일 객체 타입: ${attachmentType}`) + try { const filename = `${uuidv4()}_${file.name.replace(/[^a-zA-Z0-9.-]/g, '_')}` const filepath = path.join(uploadDir, filename) @@ -171,24 +179,28 @@ export async function POST( const buffer = Buffer.from(await file.arrayBuffer()) await writeFile(filepath, buffer) } - + fileRecords.push({ vendorResponseId: result.id, - attachmentType: metadata?.attachmentType || "기타", // 메타데이터에서 가져옴 + attachmentType: attachmentType, // 파일 객체에서 직접 가져옴 fileName: filename, originalFileName: file.name, filePath: `/uploads/rfq/${rfqId}/${filename}`, fileSize: file.size, - fileType: file.type, - description: metadata?.description || "", // 메타데이터에서 가져옴 + fileType: file.type || path.extname(file.name).slice(1), + description: description, uploadedBy: session.user.id, }) + + console.log(`파일 저장 완료: ${filename}, 타입: ${attachmentType}`) } catch (fileError) { - console.error(`Failed to save file ${file.name}:`, fileError) + console.error(`파일 저장 실패 ${file.name}:`, fileError) } } + // DB에 파일 정보 저장 if (fileRecords.length > 0) { + console.log('DB에 저장할 파일 레코드:', fileRecords) await db.insert(rfqLastVendorAttachments).values(fileRecords) } } @@ -224,14 +236,14 @@ export async function PUT( const data = JSON.parse(formData.get('data') as string) const files = formData.getAll('attachments') as File[] - // 업로드 디렉토리 생성 + // 업로드 디렉토리 생성 (벤더 응답용) const isDev = process.env.NODE_ENV === 'development' - const uploadDir = isDev - ? path.join(process.cwd(), 'public', 'uploads', 'rfq', rfqId.toString()) - : path.join(process.env.NAS_PATH || '/nas', 'uploads', 'rfq', rfqId.toString()) - + const uploadDir = isDev + ? path.join(process.cwd(), 'public', 'uploads', 'rfq-last-vendor-responses') + : path.join(process.env.NAS_PATH || '/nas', 'uploads', 'rfq-last-vendor-responses') + await mkdir(uploadDir, { recursive: true }) - + // 트랜잭션 시작 const result = await db.transaction(async (tx) => { // 1. 기존 응답 찾기 @@ -333,11 +345,22 @@ export async function PUT( return { id: responseId } }) - // 5. 새 첨부파일 추가 (트랜잭션 밖에서) + // 파일 저장 (트랜잭션 밖에서) const fileRecords = [] - + if (files.length > 0) { - for (const file of files) { + console.log(`업데이트 저장할 파일 수: ${files.length}`) + console.log('파일 메타데이터:', data.fileMetadata) + + for (let i = 0; i < files.length; i++) { + const file = files[i] + // 파일 메타데이터에서 attachmentType 정보 가져옴 + const metadata = data.fileMetadata && data.fileMetadata[i] + const attachmentType = metadata?.attachmentType || "기타" + const description = metadata?.description || "" + + console.log(`업데이트 파일 ${i + 1} 처리: ${file.name}, 파일 객체 타입: ${attachmentType}`) + try { const filename = `${uuidv4()}_${file.name.replace(/[^a-zA-Z0-9.-]/g, '_')}` const filepath = path.join(uploadDir, filename) @@ -349,35 +372,38 @@ export async function PUT( const buffer = Buffer.from(await file.arrayBuffer()) await writeFile(filepath, buffer) } - + fileRecords.push({ vendorResponseId: result.id, - attachmentType: (file as any).attachmentType || "기타", + attachmentType: attachmentType, // 파일 객체에서 직접 가져옴 fileName: filename, originalFileName: file.name, filePath: `/uploads/rfq/${rfqId}/${filename}`, fileSize: file.size, - fileType: file.type, - description: (file as any).description, + fileType: file.type || path.extname(file.name).slice(1), + description: description, uploadedBy: session.user.id, }) + + console.log(`업데이트 파일 저장 완료: ${filename}, 타입: ${attachmentType}`) } catch (fileError) { - console.error(`Failed to save file ${file.name}:`, fileError) + console.error(`업데이트 파일 저장 실패 ${file.name}:`, fileError) } } - + if (fileRecords.length > 0) { + console.log('업데이트 DB에 저장할 파일 레코드:', fileRecords) await db.insert(rfqLastVendorAttachments).values(fileRecords) } } - return NextResponse.json({ - success: true, + return NextResponse.json({ + success: true, data: result, message: data.status === "제출완료" ? "견적서가 성공적으로 제출되었습니다." : "견적서가 수정되었습니다.", filesUploaded: fileRecords.length }) - + } catch (error) { console.error("Error updating vendor response:", error) return NextResponse.json( |
