diff options
| author | dujinkim <dujin.kim@dtsolution.co.kr> | 2025-08-14 11:54:47 +0000 |
|---|---|---|
| committer | dujinkim <dujin.kim@dtsolution.co.kr> | 2025-08-14 11:54:47 +0000 |
| commit | 969c25b56f6d29d7ffa4bc2ce04c5fb4e5846b34 (patch) | |
| tree | 551d335e850e6163792ded0e7a75fa41d96d612a /app/api | |
| parent | dd20ba9785cdbd3d61f6b014d003d3bd9646ad13 (diff) | |
(대표님) 정규벤더등록, 벤더문서관리, 벤더데이터입력, 첨부파일관리
Diffstat (limited to 'app/api')
| -rw-r--r-- | app/api/attachment-delete/route.ts | 76 | ||||
| -rw-r--r-- | app/api/files/[...path]/route.ts | 1 | ||||
| -rw-r--r-- | app/api/revision-attachment/route.ts | 102 | ||||
| -rw-r--r-- | app/api/revision-upload-ship/route.ts | 17 | ||||
| -rw-r--r-- | app/api/sync/batches/route.ts | 2 | ||||
| -rw-r--r-- | app/api/sync/config/route.ts | 8 | ||||
| -rw-r--r-- | app/api/sync/status/route.ts | 2 |
7 files changed, 162 insertions, 46 deletions
diff --git a/app/api/attachment-delete/route.ts b/app/api/attachment-delete/route.ts new file mode 100644 index 00000000..254c579f --- /dev/null +++ b/app/api/attachment-delete/route.ts @@ -0,0 +1,76 @@ +// /api/attachment-delete/route.ts + +import { NextRequest, NextResponse } from 'next/server' +import db from '@/db/db' +import { documentAttachments } from '@/db/schema' // 실제 스키마에 맞게 수정 +import { eq, and } from 'drizzle-orm' +import fs from 'fs/promises' +import path from 'path' + +export async function DELETE(request: NextRequest) { + try { + const { attachmentId, revisionId } = await request.json() + + if (!attachmentId || !revisionId) { + return NextResponse.json( + { error: 'attachmentId and revisionId are required' }, + { status: 400 } + ) + } + + // 1. 데이터베이스에서 첨부파일 정보 조회 + const attachment = await db + .select() + .from(documentAttachments) + .where( + and( + eq(documentAttachments.id, attachmentId), + eq(documentAttachments.revisionId, revisionId) + ) + ) + .limit(1) + + if (!attachment || attachment.length === 0) { + return NextResponse.json( + { error: 'Attachment not found' }, + { status: 404 } + ) + } + + const attachmentData = attachment[0] + + // 2. dolceFilePath 체크 - 있으면 삭제 불가 + if (attachmentData.dolceFilePath && attachmentData.dolceFilePath.trim() !== '') { + return NextResponse.json( + { error: 'Cannot delete processed file' }, + { status: 403 } + ) + } + + // 4. 데이터베이스에서 첨부파일 레코드 삭제 + await db + .delete(documentAttachments) + .where( + and( + eq(documentAttachments.id, attachmentId), + eq(documentAttachments.revisionId, revisionId) + ) + ) + + return NextResponse.json({ + success: true, + message: 'Attachment deleted successfully', + deletedAttachmentId: attachmentId + }) + + } catch (error) { + console.error('Attachment deletion error:', error) + return NextResponse.json( + { + error: 'Internal server error', + details: error instanceof Error ? error.message : 'Unknown error' + }, + { status: 500 } + ) + } +}
\ No newline at end of file diff --git a/app/api/files/[...path]/route.ts b/app/api/files/[...path]/route.ts index 5eab8210..9ef11bc7 100644 --- a/app/api/files/[...path]/route.ts +++ b/app/api/files/[...path]/route.ts @@ -36,6 +36,7 @@ const isAllowedPath = (requestedPath: string): boolean => { 'vendorFormReportSample', 'vendorFormData', 'uploads', + 'documents', 'tech-sales', 'techsales-rfq', 'tech-vendors', diff --git a/app/api/revision-attachment/route.ts b/app/api/revision-attachment/route.ts index 092eed8d..46c2e9c9 100644 --- a/app/api/revision-attachment/route.ts +++ b/app/api/revision-attachment/route.ts @@ -1,8 +1,4 @@ import { NextRequest, NextResponse } from "next/server" -import { writeFile } from "fs/promises" -import { join } from "path" -import { v4 as uuidv4 } from "uuid" -import path from "path" import { revalidateTag } from "next/cache" import db from "@/db/db" @@ -14,6 +10,9 @@ import { } from "@/db/schema/vendorDocu" import { eq } from "drizzle-orm" +/* 보안 강화된 파일 저장 유틸리티 */ +import { saveFile, SaveFileResult, saveFileStream } from "@/lib/file-stroage" + /* change log 유틸 */ import { logAttachmentChange, @@ -35,13 +34,16 @@ export async function POST(request: NextRequest) { if (!attachmentFiles.length) return NextResponse.json({ error: "No files provided" }, { status: 400 }) - const MAX = 50 * 1024 * 1024 // 50MB - for (const f of attachmentFiles) - if (f.size > MAX) + // 기본 파일 크기 검증 (보안 함수에서도 검증하지만 조기 체크) + const MAX = 1024 * 1024 * 1024 // 1GB로 증가 (첫 번째 파일과 동일) + for (const f of attachmentFiles) { + if (f.size > MAX) { return NextResponse.json( - { error: `${f.name} exceeds 50MB limit` }, + { error: `${f.name} exceeds 1GB limit` }, { status: 400 } ) + } + } /* ------- 리비전 및 계약 정보 확보 ------- */ const [revisionInfo] = await db @@ -52,6 +54,7 @@ export async function POST(request: NextRequest) { usageType: revisions.usageType, issueStageId: revisions.issueStageId, projectId: documents.projectId, + vendorId: documents.vendorId, }) .from(revisions) .innerJoin(issueStages, eq(revisions.issueStageId, issueStages.id)) @@ -63,41 +66,60 @@ export async function POST(request: NextRequest) { return NextResponse.json({ error: "Revision not found" }, { status: 404 }) } + // vendorId가 null인 경우 처리 + if (!revisionInfo.vendorId) { + return NextResponse.json({ + error: "Revision must have a valid vendor ID for synchronization" + }, { status: 400 }) + } + /* ------- 트랜잭션 ------- */ const result = await db.transaction(async (tx) => { - /* 첨부파일 처리 */ + /* ------- 보안 강화된 첨부파일 처리 ------- */ const uploadedFiles: any[] = [] - const baseDir = join(process.cwd(), "public", "documents") + const securityFailures: string[] = [] for (const file of attachmentFiles) { - const ext = path.extname(file.name) - const fname = uuidv4() + ext - const dest = join(baseDir, fname) - - await writeFile(dest, Buffer.from(await file.arrayBuffer())) - + console.log(`🔐 보안 검증 시작: ${file.name}`) + + // 보안 강화된 파일 저장 + const saveResult = file.size > 100 * 1024 * 1024 + ? await saveFileStream({ file, directory: "documents", userId: uploaderName || "" }) + : await saveFile({ file, directory: "documents", userId: uploaderName || "" }) + + if (!saveResult.success) { + console.error(`❌ 파일 보안 검증 실패: ${file.name} - ${saveResult.error}`) + securityFailures.push(`${file.name}: ${saveResult.error}`) + continue // 실패한 파일은 건너뛰고 계속 진행 + } + + console.log(`✅ 파일 보안 검증 통과: ${file.name}`) + console.log(`📁 저장된 경로: ${saveResult.publicPath}`) + + // DB에 첨부파일 정보 저장 const [att] = await tx.insert(documentAttachments) .values({ revisionId, - fileName: file.name, - filePath: "/documents/" + fname, - fileSize: file.size, - fileType: ext.slice(1).toLowerCase() || undefined, + fileName: saveResult.originalName!, // 원본 파일명 + filePath: saveResult.publicPath!, // 웹 접근 경로 + fileSize: saveResult.fileSize!, + fileType: saveResult.fileName!.split('.').pop()?.toLowerCase() || undefined, updatedAt: new Date(), }) .returning() uploadedFiles.push({ id: att.id, - fileName: file.name, - fileSize: file.size, - filePath: att.filePath, - fileType: ext.slice(1).toLowerCase() || null, + fileName: saveResult.originalName, + fileSize: saveResult.fileSize, + filePath: saveResult.publicPath, + fileType: saveResult.fileName!.split('.').pop()?.toLowerCase() || null, + securityChecks: saveResult.securityChecks, // 보안 검증 결과 }) // change_logs: attachment CREATE await logAttachmentChange( - revisionInfo.projectId, + revisionInfo.vendorId!, att.id, "CREATE", att, @@ -108,6 +130,16 @@ export async function POST(request: NextRequest) { ) } + // 보안 검증 실패한 파일이 있으면 경고 반환 + if (securityFailures.length > 0) { + console.warn(`⚠️ 일부 파일의 보안 검증 실패:`, securityFailures) + + // 모든 파일이 실패한 경우 에러 반환 + if (uploadedFiles.length === 0) { + throw new Error(`모든 파일의 보안 검증이 실패했습니다: ${securityFailures.join(', ')}`) + } + } + /* 리비전 updatedAt 업데이트 */ await tx.update(revisions) .set({ updatedAt: new Date() }) @@ -119,30 +151,36 @@ export async function POST(request: NextRequest) { usage: revisionInfo.usage, usageType: revisionInfo.usageType, uploadedFiles, - projectId: revisionInfo.projectId + vendorId: revisionInfo.vendorId, + securityFailures // 보안 실패 정보 포함 } }) // 캐시 무효화 try { - // revalidateTag(`enhanced-documents-${result.projectId}`) - revalidateTag(`sync-status-${result.projectId}`) - - console.log(`✅ Cache invalidated for contract ${result.projectId}`) + revalidateTag(`sync-status-${result.vendorId}`) + console.log(`✅ Cache invalidated for contract ${result.vendorId}`) } catch (cacheError) { console.warn('⚠️ Cache invalidation failed:', cacheError) } + // 응답 메시지 구성 + let message = `${result.uploadedFiles.length}개 첨부파일이 추가되었습니다` + if (result.securityFailures.length > 0) { + message += ` (일부 파일 보안 검증 실패: ${result.securityFailures.length}개)` + } + return NextResponse.json({ success: true, - message: `${result.uploadedFiles.length}개 첨부파일이 추가되었습니다`, + message, data: { revisionId: result.revisionId, revision: result.revision, usage: result.usage, usageType: result.usageType, uploadedFiles: result.uploadedFiles, - filesCount: result.uploadedFiles.length + filesCount: result.uploadedFiles.length, + securityFailures: result.securityFailures, // 클라이언트에 보안 실패 정보 전달 }, }) } catch (e) { diff --git a/app/api/revision-upload-ship/route.ts b/app/api/revision-upload-ship/route.ts index 671b8bac..b07a3d9c 100644 --- a/app/api/revision-upload-ship/route.ts +++ b/app/api/revision-upload-ship/route.ts @@ -56,7 +56,8 @@ export async function POST(request: NextRequest) { const [docInfo] = await db .select({ contractId: documents.contractId, - projectId: documents.projectId + projectId: documents.projectId , + vendorId: documents.vendorId , }) .from(documents) .where(eq(documents.id, docId)) @@ -67,7 +68,7 @@ export async function POST(request: NextRequest) { } // projectId가 null인 경우 처리 - if (!docInfo.projectId) { + if (!docInfo.vendorId) { return NextResponse.json({ error: "Document must have a valid project ID for synchronization" }, { status: 400 }) @@ -158,7 +159,7 @@ export async function POST(request: NextRequest) { revisionData = updated await logRevisionChange( - docInfo.projectId!, // null 체크 후이므로 non-null assertion 사용 + docInfo.vendorId!, // null 체크 후이므로 non-null assertion 사용 revisionId, "UPDATE", updated, @@ -188,7 +189,7 @@ export async function POST(request: NextRequest) { revisionData = newRev await logRevisionChange( - docInfo.projectId!, // null 체크 후이므로 non-null assertion 사용 + docInfo.vendorId!, // null 체크 후이므로 non-null assertion 사용 revisionId, "CREATE", newRev, @@ -243,7 +244,7 @@ export async function POST(request: NextRequest) { // change_logs: attachment CREATE await logAttachmentChange( - docInfo.projectId!, + docInfo.vendorId!, att.id, "CREATE", att, @@ -275,7 +276,7 @@ export async function POST(request: NextRequest) { stage, revision, uploadedFiles, - contractId: docInfo.contractId, + vendorId: docInfo.vendorId, usage, usageType, securityFailures // 보안 실패 정보 포함 @@ -284,8 +285,8 @@ export async function POST(request: NextRequest) { // 캐시 무효화 try { - revalidateTag(`sync-status-${result.contractId}`) - console.log(`✅ Cache invalidated for contract ${result.contractId}`) + revalidateTag(`sync-status-${result.vendorId}`) + console.log(`✅ Cache invalidated for contract ${result.vendorId}`) } catch (cacheError) { console.warn('⚠️ Cache invalidation failed:', cacheError) } diff --git a/app/api/sync/batches/route.ts b/app/api/sync/batches/route.ts index 7a72530d..1f37d6e6 100644 --- a/app/api/sync/batches/route.ts +++ b/app/api/sync/batches/route.ts @@ -10,7 +10,7 @@ export async function GET(request: NextRequest) { if (!projectId) { return NextResponse.json( - { error: 'Contract ID is required' }, + { error: 'Vendor ID is required' }, { status: 400 } ) } diff --git a/app/api/sync/config/route.ts b/app/api/sync/config/route.ts index db5d17ca..2e9a073a 100644 --- a/app/api/sync/config/route.ts +++ b/app/api/sync/config/route.ts @@ -6,10 +6,10 @@ import { authOptions } from "@/app/api/auth/[...nextauth]/route" export async function GET(request: NextRequest) { try { const { searchParams } = new URL(request.url) - const projectId = searchParams.get('projectId') + const vendorId = searchParams.get('vendorId') const targetSystem = searchParams.get('targetSystem') || 'SHI' - if (!projectId) { + if (!vendorId) { return NextResponse.json( { error: 'Contract ID is required' }, { status: 400 } @@ -17,7 +17,7 @@ export async function GET(request: NextRequest) { } const config = await syncService.getSyncConfig( - parseInt(projectId), + parseInt(vendorId), targetSystem ) @@ -65,7 +65,7 @@ export async function POST(request: NextRequest) { } await syncService.upsertSyncConfig({ - projectId, + vendorId, targetSystem, endpointUrl, authToken, diff --git a/app/api/sync/status/route.ts b/app/api/sync/status/route.ts index b4b18577..05101d2b 100644 --- a/app/api/sync/status/route.ts +++ b/app/api/sync/status/route.ts @@ -38,7 +38,7 @@ export async function GET(request: NextRequest) { if (!projectId) { return NextResponse.json( - { error: 'Project ID is required' }, + { error: 'project ID is required' }, { status: 400 } ) } |
