diff options
Diffstat (limited to 'app')
| -rw-r--r-- | app/[lng]/evcp/(evcp)/b-rfq/[id]/initial/page.tsx | 13 | ||||
| -rw-r--r-- | app/[lng]/evcp/(evcp)/budgetary-tech-sales-ship/page.tsx | 12 | ||||
| -rw-r--r-- | app/[lng]/partners/(partners)/rfq-answer/[vendorId]/[rfqRecordId]/page.tsx | 174 | ||||
| -rw-r--r-- | app/[lng]/partners/(partners)/rfq-answer/page.tsx | 210 | ||||
| -rw-r--r-- | app/[lng]/partners/(partners)/rfq-ship/[id]/page.tsx (renamed from app/[lng]/partners/(partners)/rfq-all/[id]/page.tsx) | 0 | ||||
| -rw-r--r-- | app/[lng]/partners/(partners)/rfq-ship/page.tsx (renamed from app/[lng]/partners/(partners)/rfq-all/page.tsx) | 0 | ||||
| -rw-r--r-- | app/api/ocr/enhanced/route.ts | 2 | ||||
| -rw-r--r-- | app/api/rfq-attachments/download/route.ts | 223 | ||||
| -rw-r--r-- | app/api/vendor-responses/update-comment/route.ts | 60 | ||||
| -rw-r--r-- | app/api/vendor-responses/update/route.ts | 121 | ||||
| -rw-r--r-- | app/api/vendor-responses/upload/route.ts | 105 | ||||
| -rw-r--r-- | app/api/vendor-responses/waive/route.ts | 69 |
12 files changed, 974 insertions, 15 deletions
diff --git a/app/[lng]/evcp/(evcp)/b-rfq/[id]/initial/page.tsx b/app/[lng]/evcp/(evcp)/b-rfq/[id]/initial/page.tsx index 77ebebb1..1af65fbc 100644 --- a/app/[lng]/evcp/(evcp)/b-rfq/[id]/initial/page.tsx +++ b/app/[lng]/evcp/(evcp)/b-rfq/[id]/initial/page.tsx @@ -27,14 +27,11 @@ export default async function RfqPage(props: IndexPageProps) { const search = searchParamsInitialRfqDetailCache.parse(searchParams) const validFilters = getValidFilters(search.filters) - const promises = Promise.all([ - getInitialRfqDetail({ - ...search, - filters: validFilters, - }, - idAsNumber) - ]) - + const promises = getInitialRfqDetail({ + ...search, + filters: validFilters, + }, idAsNumber) + // 4) 렌더링 return ( <div className="space-y-6"> diff --git a/app/[lng]/evcp/(evcp)/budgetary-tech-sales-ship/page.tsx b/app/[lng]/evcp/(evcp)/budgetary-tech-sales-ship/page.tsx index 05b856e5..b7bf9d15 100644 --- a/app/[lng]/evcp/(evcp)/budgetary-tech-sales-ship/page.tsx +++ b/app/[lng]/evcp/(evcp)/budgetary-tech-sales-ship/page.tsx @@ -1,5 +1,5 @@ -import { searchParamsCache } from "@/lib/techsales-rfq/validations" -import { getTechSalesRfqsWithJoin } from "@/lib/techsales-rfq/service" +import { searchParamsShipCache } from "@/lib/techsales-rfq/validations" +import { getTechSalesShipRfqsWithJoin } from "@/lib/techsales-rfq/service" import { getValidFilters } from "@/lib/data-table" import { Shell } from "@/components/shell" import { DataTableSkeleton } from "@/components/data-table/data-table-skeleton" @@ -15,13 +15,13 @@ export default async function RfqPage(props: RfqPageProps) { // searchParams를 await하여 resolve const searchParams = await props.searchParams - // 파라미터 파싱 - const search = searchParamsCache.parse(searchParams); + // 조선용 파라미터 파싱 + const search = searchParamsShipCache.parse(searchParams); const validFilters = getValidFilters(search.filters); // 기술영업 조선 RFQ 데이터를 Promise.all로 감싸서 전달 const promises = Promise.all([ - getTechSalesRfqsWithJoin({ + getTechSalesShipRfqsWithJoin({ ...search, // 모든 파라미터 전달 (page, perPage, sort, basicFilters, filters 등) filters: validFilters, // 고급 필터를 명시적으로 오버라이드 (파싱된 버전) }) @@ -53,7 +53,7 @@ export default async function RfqPage(props: RfqPageProps) { /> } > - <RFQListTable promises={promises} className="h-full" /> + <RFQListTable promises={promises} className="h-full" rfqType="SHIP" /> </React.Suspense> </div> </Shell> diff --git a/app/[lng]/partners/(partners)/rfq-answer/[vendorId]/[rfqRecordId]/page.tsx b/app/[lng]/partners/(partners)/rfq-answer/[vendorId]/[rfqRecordId]/page.tsx new file mode 100644 index 00000000..898dc41b --- /dev/null +++ b/app/[lng]/partners/(partners)/rfq-answer/[vendorId]/[rfqRecordId]/page.tsx @@ -0,0 +1,174 @@ +// app/vendor/responses/[vendorId]/[rfqRecordId]/[rfqType]/page.tsx +import * as React from "react"; +import Link from "next/link"; +import { Metadata } from "next"; +import { getServerSession } from "next-auth/next"; +import { authOptions } from "@/app/api/auth/[...nextauth]/route"; +import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; +import { Button } from "@/components/ui/button"; +import { Badge } from "@/components/ui/badge"; +import { Alert, AlertDescription } from "@/components/ui/alert"; +import { Progress } from "@/components/ui/progress"; +import { + ArrowLeft, + FileText, + AlertTriangle, + TrendingUp, + CheckCircle2, + RefreshCw, + GitBranch, + Clock, + FileCheck, + Calendar +} from "lucide-react"; +import { Shell } from "@/components/shell"; +import { formatDate } from "@/lib/utils"; +import { getRfqAttachmentResponsesWithRevisions } from "@/lib/b-rfq/service"; +import { FinalRfqResponseTable } from "@/lib/b-rfq/vendor-response/response-detail-table"; + +export const metadata: Metadata = { + title: "RFQ 응답 상세", + description: "RFQ 첨부파일별 응답 관리 - 고급 리비전 추적", +}; + +interface RfqResponseDetailPageProps { + params: Promise<{ + vendorId: string; + rfqRecordId: string; + }>; +} + +export default async function RfqResponseDetailPage(props: RfqResponseDetailPageProps) { + const params = await props.params; + const { vendorId, rfqRecordId, rfqType } = params; + + // 인증 확인 + const session = await getServerSession(authOptions); + + if (!session || !session.user) { + return ( + <Shell className="gap-6"> + <div className="text-center py-12"> + <p className="text-muted-foreground">로그인이 필요합니다.</p> + </div> + </Shell> + ); + } + + // 벤더 권한 확인 + if (session.user.domain !== "partners" || String(session.user.companyId) !== vendorId) { + return ( + <Shell className="gap-6"> + <div className="text-center py-12"> + <p className="text-muted-foreground">접근 권한이 없습니다.</p> + </div> + </Shell> + ); + } + + // 데이터 조회 (뷰 기반 고급 리비전 정보 포함) + const { data: responses, rfqInfo, vendorInfo, statistics, progressSummary } = + await getRfqAttachmentResponsesWithRevisions(vendorId, rfqRecordId); + + console.log("Enhanced RFQ Data:", { responses, statistics, progressSummary }); + + if (!rfqInfo) { + return ( + <Shell className="gap-6"> + <div className="text-center py-12"> + <p className="text-muted-foreground">RFQ 정보를 찾을 수 없습니다.</p> + </div> + </Shell> + ); + } + + const stats = statistics; + + return ( + <Shell className="gap-6"> + {/* 헤더 */} + <div className="flex items-center justify-between"> + <div className="flex items-center gap-4"> + <Button variant="ghost" size="sm" asChild> + <Link href="/partners/rfq-answer"> + <ArrowLeft className="h-4 w-4 mr-2" /> + 돌아가기 + </Link> + </Button> + <div> + <h2 className="text-2xl font-bold tracking-tight"> + {rfqInfo.rfqCode} - RFQ 응답 관리 + </h2> + <p className="text-muted-foreground"> + 고급 리비전 추적 및 응답 상태 관리 + </p> + </div> + </div> + + {/* 마감일 표시 */} + {progressSummary?.daysToDeadline !== undefined && ( + <div className="text-right"> + <div className="flex items-center gap-2 text-sm text-muted-foreground"> + <Calendar className="h-4 w-4" /> + <span>마감까지</span> + </div> + <div className={`text-lg font-bold ${ + progressSummary.daysToDeadline < 0 + ? 'text-red-600' + : progressSummary.daysToDeadline <= 3 + ? 'text-orange-600' + : 'text-green-600' + }`}> + {progressSummary.daysToDeadline < 0 + ? `${Math.abs(progressSummary.daysToDeadline)}일 초과` + : `${progressSummary.daysToDeadline}일 남음` + } + </div> + </div> + )} + </div> + + {/* 중요 알림들 */} + <div className="space-y-3"> + {stats.versionMismatch > 0 && ( + <Alert className="border-blue-200 bg-blue-50"> + <RefreshCw className="h-4 w-4 text-blue-600" /> + <AlertDescription className="text-blue-800"> + <strong>{stats.versionMismatch}개 항목</strong>에서 발주처의 최신 리비전과 응답 리비전이 일치하지 않습니다. + 최신 버전으로 업데이트를 권장합니다. + </AlertDescription> + </Alert> + )} + + {progressSummary?.daysToDeadline !== undefined && progressSummary.daysToDeadline <= 3 && progressSummary.daysToDeadline >= 0 && ( + <Alert className="border-orange-200 bg-orange-50"> + <Clock className="h-4 w-4 text-orange-600" /> + <AlertDescription className="text-orange-800"> + 마감일이 <strong>{progressSummary.daysToDeadline}일</strong> 남았습니다. + 미응답 항목({stats.pending}개)의 신속한 처리가 필요합니다. + </AlertDescription> + </Alert> + )} + + {progressSummary?.attachmentsWithMultipleRevisions > 0 && ( + <Alert className="border-purple-200 bg-purple-50"> + <GitBranch className="h-4 w-4 text-purple-600" /> + <AlertDescription className="text-purple-800"> + <strong>{progressSummary.attachmentsWithMultipleRevisions}개 첨부파일</strong>에 + 다중 리비전이 있습니다. 히스토리를 확인하여 올바른 버전으로 응답해주세요. + </AlertDescription> + </Alert> + )} + </div> + <FinalRfqResponseTable + data={responses} + statistics={stats} + showHeader={true} + title="첨부파일별 응답 현황" + /> + + + + </Shell> + ); +}
\ No newline at end of file diff --git a/app/[lng]/partners/(partners)/rfq-answer/page.tsx b/app/[lng]/partners/(partners)/rfq-answer/page.tsx new file mode 100644 index 00000000..1869c74e --- /dev/null +++ b/app/[lng]/partners/(partners)/rfq-answer/page.tsx @@ -0,0 +1,210 @@ +// app/vendor/responses/page.tsx +import * as React from "react"; +import Link from "next/link"; +import { Metadata } from "next"; +import { getServerSession } from "next-auth/next"; +import { authOptions } from "@/app/api/auth/[...nextauth]/route"; +import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; +import { Button } from "@/components/ui/button"; +import { LogIn, FileX, Clock, CheckCircle, AlertTriangle } from "lucide-react"; +import { DataTableSkeleton } from "@/components/data-table/data-table-skeleton"; +import { Shell } from "@/components/shell"; +import { getValidFilters } from "@/lib/data-table"; +import { type SearchParams } from "@/types/table"; +import { searchParamsVendorResponseCache } from "@/lib/b-rfq/validations"; +import { getVendorResponseProgress, getVendorResponseStatusCounts, getVendorRfqResponses } from "@/lib/b-rfq/service"; +import { VendorResponsesTable } from "@/lib/b-rfq/vendor-response/vendor-responses-table"; + +export const metadata: Metadata = { + title: "응답 관리", + description: "RFQ 첨부파일 응답 현황을 관리합니다", +}; + +interface IndexPageProps { + searchParams: Promise<SearchParams> +} + +export default async function IndexPage(props: IndexPageProps) { + const searchParams = await props.searchParams + const search = searchParamsVendorResponseCache.parse(searchParams) + const validFilters = getValidFilters(search.filters) + + // 인증 확인 + const session = await getServerSession(authOptions); + + // 로그인 확인 + if (!session || !session.user) { + return ( + <Shell className="gap-6"> + <div className="flex items-center justify-between"> + <div> + <h2 className="text-2xl font-bold tracking-tight"> + 응답 관리 + </h2> + <p className="text-muted-foreground"> + RFQ 첨부파일 응답 현황을 확인하고 관리합니다. + </p> + </div> + </div> + + <div className="flex flex-col items-center justify-center py-12 text-center"> + <div className="rounded-lg border border-dashed p-10 shadow-sm"> + <h3 className="mb-2 text-xl font-semibold">로그인이 필요합니다</h3> + <p className="mb-6 text-muted-foreground"> + 응답 현황을 확인하려면 먼저 로그인하세요. + </p> + <Button size="lg" asChild> + <Link href="/partners?callbackUrl=/vendor/responses"> + <LogIn className="mr-2 h-4 w-4" /> + 로그인하기 + </Link> + </Button> + </div> + </div> + </Shell> + ); + } + + // 벤더 ID 확인 + const vendorId = session.user.companyId ? String(session.user.companyId) : "0"; + + // 벤더 권한 확인 + if (session.user.domain !== "partners") { + return ( + <Shell className="gap-6"> + <div className="flex items-center justify-between"> + <div> + <h2 className="text-2xl font-bold tracking-tight"> + 접근 권한 없음 + </h2> + </div> + </div> + <div className="flex flex-col items-center justify-center py-12 text-center"> + <div className="rounded-lg border border-dashed p-10 shadow-sm"> + <h3 className="mb-2 text-xl font-semibold">벤더 계정이 필요합니다</h3> + <p className="mb-6 text-muted-foreground"> + 벤더 계정으로 로그인해주세요. + </p> + </div> + </div> + </Shell> + ); + } + + // 데이터 가져오기 + const responsesPromise = getVendorRfqResponses({ + ...search, + filters: validFilters + }, vendorId); + + // 상태별 개수 및 진행률 가져오기 + const [statusCounts, progress] = await Promise.all([ + getVendorResponseStatusCounts(vendorId), + getVendorResponseProgress(vendorId) + ]); + + // 프로미스 배열 + const promises = Promise.all([responsesPromise]); + + return ( + <Shell className="gap-6"> + <div className="flex justify-between items-center"> + <div> + <h2 className="text-2xl font-bold tracking-tight">RFQ 응답 관리</h2> + <p className="text-muted-foreground"> + RFQ 첨부파일 응답 현황을 확인하고 관리합니다. + </p> + </div> + </div> + + {/* 상태별 통계 카드 */} + <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-5"> + <Card> + <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2"> + <CardTitle className="text-sm font-medium">전체 요청</CardTitle> + <FileX className="h-4 w-4 text-muted-foreground" /> + </CardHeader> + <CardContent> + <div className="text-2xl font-bold">{progress.totalRequests}건</div> + <p className="text-xs text-muted-foreground"> + 총 응답 요청 수 + </p> + </CardContent> + </Card> + + <Card> + <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2"> + <CardTitle className="text-sm font-medium">미응답</CardTitle> + <Clock className="h-4 w-4 text-orange-600" /> + </CardHeader> + <CardContent> + <div className="text-2xl font-bold text-orange-600"> + {statusCounts.NOT_RESPONDED || 0}건 + </div> + <p className="text-xs text-muted-foreground"> + 응답 대기 중 + </p> + </CardContent> + </Card> + + <Card> + <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2"> + <CardTitle className="text-sm font-medium">응답완료</CardTitle> + <CheckCircle className="h-4 w-4 text-green-600" /> + </CardHeader> + <CardContent> + <div className="text-2xl font-bold text-green-600"> + {statusCounts.RESPONDED || 0}건 + </div> + <p className="text-xs text-muted-foreground"> + 응답률: {progress.responseRate}% + </p> + </CardContent> + </Card> + + <Card> + <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2"> + <CardTitle className="text-sm font-medium">수정요청</CardTitle> + <AlertTriangle className="h-4 w-4 text-yellow-600" /> + </CardHeader> + <CardContent> + <div className="text-2xl font-bold text-yellow-600"> + {statusCounts.REVISION_REQUESTED || 0}건 + </div> + <p className="text-xs text-muted-foreground"> + 재검토 필요 + </p> + </CardContent> + </Card> + + <Card> + <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2"> + <CardTitle className="text-sm font-medium">포기</CardTitle> + <FileX className="h-4 w-4 text-gray-600" /> + </CardHeader> + <CardContent> + <div className="text-2xl font-bold text-gray-600"> + {statusCounts.WAIVED || 0}건 + </div> + <p className="text-xs text-muted-foreground"> + 완료율: {progress.completionRate}% + </p> + </CardContent> + </Card> + </div> + + <React.Suspense + fallback={ + <DataTableSkeleton + columnCount={8} + searchableColumnCount={2} + filterableColumnCount={3} + cellWidths={["10rem", "12rem", "8rem", "10rem", "10rem", "8rem", "10rem", "8rem"]} + /> + } + > + <VendorResponsesTable promises={promises} /> + </React.Suspense> + </Shell> + ); +}
\ No newline at end of file diff --git a/app/[lng]/partners/(partners)/rfq-all/[id]/page.tsx b/app/[lng]/partners/(partners)/rfq-ship/[id]/page.tsx index 772a9840..772a9840 100644 --- a/app/[lng]/partners/(partners)/rfq-all/[id]/page.tsx +++ b/app/[lng]/partners/(partners)/rfq-ship/[id]/page.tsx diff --git a/app/[lng]/partners/(partners)/rfq-all/page.tsx b/app/[lng]/partners/(partners)/rfq-ship/page.tsx index e7dccb02..e7dccb02 100644 --- a/app/[lng]/partners/(partners)/rfq-all/page.tsx +++ b/app/[lng]/partners/(partners)/rfq-ship/page.tsx diff --git a/app/api/ocr/enhanced/route.ts b/app/api/ocr/enhanced/route.ts index 06cea358..f0a15707 100644 --- a/app/api/ocr/enhanced/route.ts +++ b/app/api/ocr/enhanced/route.ts @@ -1,5 +1,5 @@ // ============================================================================ -// app/api/ocr/rotation-enhanced/route.ts +// app/api/ocr/enhanced/route.ts // 최적화된 OCR API - 통합 처리로 API 호출 최소화 // ============================================================================ diff --git a/app/api/rfq-attachments/download/route.ts b/app/api/rfq-attachments/download/route.ts new file mode 100644 index 00000000..05e87906 --- /dev/null +++ b/app/api/rfq-attachments/download/route.ts @@ -0,0 +1,223 @@ +// app/api/rfq-attachments/download/route.ts +import { NextRequest, NextResponse } from 'next/server'; +import { readFile, access, constants } from 'fs/promises'; +import { join } from 'path'; +import db from '@/db/db'; +import { bRfqAttachmentRevisions, vendorResponseAttachmentsB } from '@/db/schema'; +import { eq, or } from 'drizzle-orm'; +import { getServerSession } from 'next-auth'; +import { authOptions } from '@/app/api/auth/[...nextauth]/route'; + +export async function GET(request: NextRequest) { + try { + // 세션 확인 + const session = await getServerSession(authOptions); + if (!session?.user) { + return NextResponse.json( + { error: "Unauthorized" }, + { status: 401 } + ); + } + + // 파라미터 추출 + const path = request.nextUrl.searchParams.get("path"); + const type = request.nextUrl.searchParams.get("type"); // "client" | "vendor" + const revisionId = request.nextUrl.searchParams.get("revisionId"); + const responseFileId = request.nextUrl.searchParams.get("responseFileId"); + + if (!path) { + return NextResponse.json( + { error: "File path is required" }, + { status: 400 } + ); + } + + // DB에서 파일 정보 조회 + let dbRecord = null; + + if (type === "client" && revisionId) { + // 발주처 첨부파일 리비전 + const [record] = await db + .select({ + fileName: bRfqAttachmentRevisions.fileName, + originalFileName: bRfqAttachmentRevisions.originalFileName, + filePath: bRfqAttachmentRevisions.filePath, + fileSize: bRfqAttachmentRevisions.fileSize, + fileType: bRfqAttachmentRevisions.fileType, + }) + .from(bRfqAttachmentRevisions) + .where(eq(bRfqAttachmentRevisions.id, Number(revisionId))); + + dbRecord = record; + + } else if (type === "vendor" && responseFileId) { + // 벤더 응답 파일 + const [record] = await db + .select({ + fileName: vendorResponseAttachmentsB.fileName, + originalFileName: vendorResponseAttachmentsB.originalFileName, + filePath: vendorResponseAttachmentsB.filePath, + fileSize: vendorResponseAttachmentsB.fileSize, + fileType: vendorResponseAttachmentsB.fileType, + }) + .from(vendorResponseAttachmentsB) + .where(eq(vendorResponseAttachmentsB.id, Number(responseFileId))); + + dbRecord = record; + + } else { + // filePath로 직접 검색 (fallback) + const [clientRecord] = await db + .select({ + fileName: bRfqAttachmentRevisions.fileName, + originalFileName: bRfqAttachmentRevisions.originalFileName, + filePath: bRfqAttachmentRevisions.filePath, + fileSize: bRfqAttachmentRevisions.fileSize, + fileType: bRfqAttachmentRevisions.fileType, + }) + .from(bRfqAttachmentRevisions) + .where(eq(bRfqAttachmentRevisions.filePath, path)); + + if (clientRecord) { + dbRecord = clientRecord; + } else { + // 벤더 파일에서도 검색 + const [vendorRecord] = await db + .select({ + fileName: vendorResponseAttachmentsB.fileName, + originalFileName: vendorResponseAttachmentsB.originalFileName, + filePath: vendorResponseAttachmentsB.filePath, + fileSize: vendorResponseAttachmentsB.fileSize, + fileType: vendorResponseAttachmentsB.fileType, + }) + .from(vendorResponseAttachmentsB) + .where(eq(vendorResponseAttachmentsB.filePath, path)); + + dbRecord = vendorRecord; + } + } + + // 파일 정보 설정 + let fileName; + let fileType; + + if (dbRecord) { + // DB에서 찾은 경우 원본 파일명 사용 + fileName = dbRecord.originalFileName || dbRecord.fileName; + fileType = dbRecord.fileType; + console.log("✅ DB에서 파일 정보 찾음:", { fileName, fileType, path: dbRecord.filePath }); + } else { + // DB에서 찾지 못한 경우 경로에서 파일명 추출 + fileName = path.split('/').pop() || 'download'; + console.log("⚠️ DB에서 파일 정보를 찾지 못함, 경로에서 추출:", fileName); + } + + // 파일 경로 구성 + const storedPath = path.replace(/^\/+/, ""); // 앞쪽 슬래시 제거 + + // 가능한 파일 경로들 + const possiblePaths = [ + join(process.cwd(), "public", storedPath), + join(process.cwd(), "uploads", storedPath), + join(process.cwd(), "storage", storedPath), + join(process.cwd(), storedPath), // 절대 경로인 경우 + ]; + + // 실제 파일 찾기 + let actualPath = null; + for (const testPath of possiblePaths) { + try { + await access(testPath, constants.R_OK); + actualPath = testPath; + console.log("✅ 파일 발견:", testPath); + break; + } catch (err) { + // 조용히 다음 경로 시도 + } + } + + if (!actualPath) { + console.error("❌ 모든 경로에서 파일을 찾을 수 없음:", possiblePaths); + return NextResponse.json( + { + error: "File not found on server", + details: { + path: path, + fileName: fileName, + triedPaths: possiblePaths + } + }, + { status: 404 } + ); + } + + // 파일 읽기 + const fileBuffer = await readFile(actualPath); + + // MIME 타입 결정 + const fileExtension = fileName.split('.').pop()?.toLowerCase() || ''; + let contentType = fileType || 'application/octet-stream'; // DB의 fileType 우선 사용 + + // 확장자에 따른 MIME 타입 매핑 (fallback) + if (!contentType || contentType === 'application/octet-stream') { + const mimeTypes: Record<string, string> = { + 'pdf': 'application/pdf', + 'doc': 'application/msword', + 'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'xls': 'application/vnd.ms-excel', + 'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'ppt': 'application/vnd.ms-powerpoint', + 'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation', + 'txt': 'text/plain', + 'csv': 'text/csv', + 'png': 'image/png', + 'jpg': 'image/jpeg', + 'jpeg': 'image/jpeg', + 'gif': 'image/gif', + 'bmp': 'image/bmp', + 'svg': 'image/svg+xml', + 'dwg': 'application/acad', + 'dxf': 'application/dxf', + 'zip': 'application/zip', + 'rar': 'application/x-rar-compressed', + '7z': 'application/x-7z-compressed', + }; + + contentType = mimeTypes[fileExtension] || 'application/octet-stream'; + } + + // 안전한 파일명 생성 (특수문자 처리) + const safeFileName = fileName.replace(/[^\w\s.-]/gi, '_'); + + // 다운로드용 헤더 설정 + const headers = new Headers(); + headers.set('Content-Type', contentType); + headers.set('Content-Disposition', `attachment; filename*=UTF-8''${encodeURIComponent(safeFileName)}`); + headers.set('Content-Length', fileBuffer.length.toString()); + headers.set('Cache-Control', 'no-cache, no-store, must-revalidate'); + headers.set('Pragma', 'no-cache'); + headers.set('Expires', '0'); + + console.log("✅ 파일 다운로드 성공:", { + fileName: safeFileName, + contentType, + size: fileBuffer.length, + actualPath + }); + + return new NextResponse(fileBuffer, { + status: 200, + headers, + }); + + } catch (error) { + console.error('❌ RFQ 첨부파일 다운로드 오류:', error); + return NextResponse.json( + { + error: 'Failed to download file', + details: error instanceof Error ? error.message : String(error) + }, + { status: 500 } + ); + } +}
\ No newline at end of file diff --git a/app/api/vendor-responses/update-comment/route.ts b/app/api/vendor-responses/update-comment/route.ts new file mode 100644 index 00000000..212173d7 --- /dev/null +++ b/app/api/vendor-responses/update-comment/route.ts @@ -0,0 +1,60 @@ +// app/api/vendor-responses/update-comment/route.ts +import { NextRequest, NextResponse } from "next/server"; +import db from "@/db/db"; +import { vendorAttachmentResponses } from "@/db/schema"; + +import { getServerSession } from "next-auth/next" +import { authOptions } from "@/app/api/auth/[...nextauth]/route" + +export async function POST(request: NextRequest) { + try { + // 인증 확인 + const session = await getServerSession(authOptions); + if (!session?.user?.id) { + return NextResponse.json( + { message: "인증이 필요합니다." }, + { status: 401 } + ); + } + + const body = await request.json(); + const { responseId, responseComment, vendorComment } = body; + + if (!responseId) { + return NextResponse.json( + { message: "응답 ID가 필요합니다." }, + { status: 400 } + ); + } + + // 코멘트만 업데이트 + const [updatedResponse] = await db + .update(vendorAttachmentResponses) + .set({ + responseComment, + vendorComment, + updatedAt: new Date(), + }) + .where(eq(vendorAttachmentResponses.id, parseInt(responseId))) + .returning(); + + if (!updatedResponse) { + return NextResponse.json( + { message: "응답을 찾을 수 없습니다." }, + { status: 404 } + ); + } + + return NextResponse.json({ + message: "코멘트가 성공적으로 업데이트되었습니다.", + response: updatedResponse, + }); + + } catch (error) { + console.error("Comment update error:", error); + return NextResponse.json( + { message: "코멘트 업데이트 중 오류가 발생했습니다." }, + { status: 500 } + ); + } +}
\ No newline at end of file diff --git a/app/api/vendor-responses/update/route.ts b/app/api/vendor-responses/update/route.ts new file mode 100644 index 00000000..8771b062 --- /dev/null +++ b/app/api/vendor-responses/update/route.ts @@ -0,0 +1,121 @@ +// app/api/vendor-responses/update/route.ts +import { NextRequest, NextResponse } from "next/server"; +import db from "@/db/db"; +import { vendorAttachmentResponses } from "@/db/schema"; +import { eq } from "drizzle-orm"; +import { getServerSession } from "next-auth/next" +import { authOptions } from "@/app/api/auth/[...nextauth]/route" + +// 리비전 번호를 증가시키는 헬퍼 함수 +function getNextRevision(currentRevision?: string): string { + if (!currentRevision) { + return "Rev.1"; // 첫 번째 응답 + } + + // "Rev.1" -> 1, "Rev.2" -> 2 형태로 숫자 추출 + const match = currentRevision.match(/Rev\.(\d+)/); + if (match) { + const currentNumber = parseInt(match[1]); + return `Rev.${currentNumber + 1}`; + } + + // 형식이 다르면 기본값 반환 + return "Rev.1"; +} + +export async function POST(request: NextRequest) { + try { + // 인증 확인 + const session = await getServerSession(authOptions); + if (!session?.user?.id) { + return NextResponse.json( + { message: "인증이 필요합니다." }, + { status: 401 } + ); + } + + const body = await request.json(); + const { + responseId, + responseStatus, + responseComment, + vendorComment, + respondedAt, + } = body; + + if (!responseId) { + return NextResponse.json( + { message: "응답 ID가 필요합니다." }, + { status: 400 } + ); + } + + // 1. 기존 응답 정보 조회 (현재 respondedRevision 확인) + const existingResponse = await db + .select() + .from(vendorAttachmentResponses) + .where(eq(vendorAttachmentResponses.id, parseInt(responseId))) + .limit(1); + + if (!existingResponse || existingResponse.length === 0) { + return NextResponse.json( + { message: "응답을 찾을 수 없습니다." }, + { status: 404 } + ); + } + + const currentResponse = existingResponse[0]; + + // 2. 벤더 응답 리비전 결정 + let nextRespondedRevision: string; + + if (responseStatus === "RESPONDED") { + // 새로운 응답이거나 수정 응답인 경우 리비전 증가 + if (currentResponse.responseStatus === "NOT_RESPONDED" || + currentResponse.responseStatus === "REVISION_REQUESTED") { + // 첫 응답이거나 수정 요청 후 재응답인 경우 리비전 증가 + nextRespondedRevision = getNextRevision(currentResponse.respondedRevision); + } else { + // 이미 응답된 상태에서 다시 업데이트하는 경우 (코멘트 수정 등) + nextRespondedRevision = currentResponse.respondedRevision || "Rev.1"; + } + } else { + // WAIVED 등 다른 상태는 기존 리비전 유지 + nextRespondedRevision = currentResponse.respondedRevision || ""; + } + + // 3. vendor response 업데이트 + const [updatedResponse] = await db + .update(vendorAttachmentResponses) + .set({ + responseStatus, + respondedRevision: nextRespondedRevision, + responseComment, + vendorComment, + respondedAt: respondedAt ? new Date(respondedAt) : null, + updatedAt: new Date(), + }) + .where(eq(vendorAttachmentResponses.id, parseInt(responseId))) + .returning(); + + if (!updatedResponse) { + return NextResponse.json( + { message: "응답 업데이트에 실패했습니다." }, + { status: 500 } + ); + } + + return NextResponse.json({ + message: "응답이 성공적으로 업데이트되었습니다.", + response: updatedResponse, + newRevision: nextRespondedRevision, // 새로운 리비전 정보 반환 + }); + + } catch (error) { + console.error("Response update error:", error); + return NextResponse.json( + { message: "응답 업데이트 중 오류가 발생했습니다." }, + { status: 500 } + ); + } +}
\ No newline at end of file diff --git a/app/api/vendor-responses/upload/route.ts b/app/api/vendor-responses/upload/route.ts new file mode 100644 index 00000000..111e4bd4 --- /dev/null +++ b/app/api/vendor-responses/upload/route.ts @@ -0,0 +1,105 @@ +// app/api/vendor-response-attachments/upload/route.ts +import { NextRequest, NextResponse } from "next/server"; +import { writeFile, mkdir } from "fs/promises"; +import { existsSync } from "fs"; +import path from "path"; +import db from "@/db/db"; +import { vendorResponseAttachmentsB } from "@/db/schema"; +import { getServerSession } from "next-auth/next" +import { authOptions } from "@/app/api/auth/[...nextauth]/route" + +export async function POST(request: NextRequest) { + try { + // 인증 확인 + const session = await getServerSession(authOptions); + if (!session?.user?.id) { + return NextResponse.json( + { message: "인증이 필요합니다." }, + { status: 401 } + ); + } + + const formData = await request.formData(); + const responseId = formData.get("responseId") as string; + const file = formData.get("file") as File; + const description = formData.get("description") as string; + + if (!responseId) { + return NextResponse.json( + { message: "응답 ID가 필요합니다." }, + { status: 400 } + ); + } + + if (!file) { + return NextResponse.json( + { message: "파일이 선택되지 않았습니다." }, + { status: 400 } + ); + } + + // 파일 크기 검증 (10MB) + if (file.size > 10 * 1024 * 1024) { + return NextResponse.json( + { message: "파일이 너무 큽니다. (최대 10MB)" }, + { status: 400 } + ); + } + + // 업로드 디렉토리 생성 + const uploadDir = path.join( + process.cwd(), + "public", + "uploads", + "vendor-responses", + responseId + ); + + if (!existsSync(uploadDir)) { + await mkdir(uploadDir, { recursive: true }); + } + + // 고유한 파일명 생성 + const timestamp = Date.now(); + const sanitizedName = file.name.replace(/[^a-zA-Z0-9.-]/g, "_"); + const fileName = `${timestamp}_${sanitizedName}`; + const filePath = `/uploads/vendor-responses/${responseId}/${fileName}`; + const fullPath = path.join(uploadDir, fileName); + + // 파일 저장 + const buffer = Buffer.from(await file.arrayBuffer()); + await writeFile(fullPath, buffer); + + // DB에 파일 정보 저장 + const [insertedFile] = await db + .insert(vendorResponseAttachmentsB) + .values({ + vendorResponseId: parseInt(responseId), + fileName, + originalFileName: file.name, + filePath, + fileSize: file.size, + fileType: file.type || path.extname(file.name).slice(1), + description: description || null, + uploadedBy: parseInt(session.user.id), + }) + .returning(); + + return NextResponse.json({ + id: insertedFile.id, + fileName, + originalFileName: file.name, + filePath, + fileSize: file.size, + fileType: file.type || path.extname(file.name).slice(1), + message: "파일이 성공적으로 업로드되었습니다.", + }); + + } catch (error) { + console.error("File upload error:", error); + return NextResponse.json( + { message: "파일 업로드 중 오류가 발생했습니다." }, + { status: 500 } + ); + } +}
\ No newline at end of file diff --git a/app/api/vendor-responses/waive/route.ts b/app/api/vendor-responses/waive/route.ts new file mode 100644 index 00000000..e732e8d2 --- /dev/null +++ b/app/api/vendor-responses/waive/route.ts @@ -0,0 +1,69 @@ +// app/api/vendor-responses/waive/route.ts +import { NextRequest, NextResponse } from "next/server"; +import db from "@/db/db"; +import { getServerSession } from "next-auth/next" +import { authOptions } from "@/app/api/auth/[...nextauth]/route" +import { eq } from "drizzle-orm"; +import { vendorAttachmentResponses } from "@/db/schema"; + +export async function POST(request: NextRequest) { + try { + // 인증 확인 + const session = await getServerSession(authOptions); + if (!session?.user?.id) { + return NextResponse.json( + { message: "인증이 필요합니다." }, + { status: 401 } + ); + } + + const body = await request.json(); + const { responseId, responseComment, vendorComment } = body; + + if (!responseId) { + return NextResponse.json( + { message: "응답 ID가 필요합니다." }, + { status: 400 } + ); + } + + if (!responseComment) { + return NextResponse.json( + { message: "포기 사유를 입력해주세요." }, + { status: 400 } + ); + } + + // vendor response를 WAIVED 상태로 업데이트 + const [updatedResponse] = await db + .update(vendorAttachmentResponses) + .set({ + responseStatus: "WAIVED", + responseComment, + vendorComment, + respondedAt: new Date(), + updatedAt: new Date(), + }) + .where(eq(vendorAttachmentResponses.id, parseInt(responseId))) + .returning(); + + if (!updatedResponse) { + return NextResponse.json( + { message: "응답을 찾을 수 없습니다." }, + { status: 404 } + ); + } + + return NextResponse.json({ + message: "응답이 성공적으로 포기 처리되었습니다.", + response: updatedResponse, + }); + + } catch (error) { + console.error("Waive response error:", error); + return NextResponse.json( + { message: "응답 포기 처리 중 오류가 발생했습니다." }, + { status: 500 } + ); + } +}
\ No newline at end of file |
