diff options
Diffstat (limited to 'app')
| -rw-r--r-- | app/[lng]/evcp/(evcp)/rfq-last/[id]/layout.tsx | 95 | ||||
| -rw-r--r-- | app/[lng]/evcp/(evcp)/rfq-last/[id]/vendor/page.tsx | 4 | ||||
| -rw-r--r-- | app/[lng]/evcp/(evcp)/tbe-last/page.tsx | 74 | ||||
| -rw-r--r-- | app/[lng]/partners/(partners)/rfq-last/[id]/page.tsx | 151 | ||||
| -rw-r--r-- | app/[lng]/partners/(partners)/rfq-last/page.tsx | 193 | ||||
| -rw-r--r-- | app/[lng]/partners/dtsocrshi/layout.tsx (renamed from app/[lng]/partners/ocr/layout.tsx) | 0 | ||||
| -rw-r--r-- | app/[lng]/partners/dtsocrshi/page.tsx (renamed from app/[lng]/partners/ocr/page.tsx) | 0 | ||||
| -rw-r--r-- | app/api/auth/signup-with-vendor/route.ts | 2 | ||||
| -rw-r--r-- | app/api/contracts/get-template/route.ts | 33 | ||||
| -rw-r--r-- | app/api/contracts/prepare-template/route.ts | 83 | ||||
| -rw-r--r-- | app/api/contracts/template/route.ts | 32 | ||||
| -rw-r--r-- | app/api/partners/rfq-last/[id]/response/route.ts | 384 | ||||
| -rw-r--r-- | app/api/rfq/attachments/download-all/route.ts | 179 | ||||
| -rw-r--r-- | app/globals.css | 2 |
14 files changed, 1197 insertions, 35 deletions
diff --git a/app/[lng]/evcp/(evcp)/rfq-last/[id]/layout.tsx b/app/[lng]/evcp/(evcp)/rfq-last/[id]/layout.tsx index 999bfe8b..20281f9c 100644 --- a/app/[lng]/evcp/(evcp)/rfq-last/[id]/layout.tsx +++ b/app/[lng]/evcp/(evcp)/rfq-last/[id]/layout.tsx @@ -5,11 +5,12 @@ import { SidebarNav } from "@/components/layout/sidebar-nav" import { formatDate } from "@/lib/utils" import { Button } from "@/components/ui/button" import { Badge } from "@/components/ui/badge" -import { ArrowLeft, Clock, AlertTriangle, CheckCircle, XCircle, AlertCircle } from "lucide-react" +import { ArrowLeft, Clock, AlertTriangle, CheckCircle, XCircle, AlertCircle, Calendar, CalendarDays } from "lucide-react" import { RfqsLastView } from "@/db/schema" import { findRfqLastById } from "@/lib/rfq-last/service" import { differenceInDays } from "date-fns" import { Alert, AlertTitle, AlertDescription } from "@/components/ui/alert" +import { DueDateEditButton } from "@/lib/rfq-last/due-date-edit-button" export const metadata: Metadata = { title: "견적 목록 상세", @@ -61,11 +62,11 @@ export default async function RfqLayout({ // Due Date 상태 계산 함수 const getDueDateStatus = (dueDate: Date | string | null) => { if (!dueDate) return null; - + const now = new Date(); const due = new Date(dueDate); const daysLeft = differenceInDays(due, now); - + if (daysLeft < 0) { return { icon: <XCircle className="h-4 w-4" />, @@ -111,36 +112,68 @@ export default async function RfqLayout({ <div className="container py-6"> <section className="overflow-hidden rounded-[0.5rem] border bg-background shadow"> <div className="hidden space-y-6 p-10 pb-16 md:block"> - <div className="flex items-center justify-end mb-4"> - <Link href={`/${lng}/evcp/rfq-last`} passHref> - <Button variant="ghost" className="flex items-center text-primary hover:text-primary/80 transition-colors p-0 h-auto"> - <ArrowLeft className="mr-1 h-4 w-4" /> - <span>견적 목록으로 돌아가기</span> - </Button> - </Link> - </div> <div className="space-y-0.5"> - {/* 제목 로직 수정: rfqTitle 있으면 사용, 없으면 rfqCode만 표시 */} - <h2 className="text-2xl font-bold tracking-tight"> - {rfq - ? rfq.rfqTitle - ? `견적 상세 관리 ${rfq.rfqCode ?? ""} | ${rfq.rfqTitle}` - : `견적 상세 관리 ${rfq.rfqCode ?? ""}` - : "Loading RFQ..."} - </h2> - - {/* <p className="text-muted-foreground"> - RFQ 관리하는 화면입니다. - </p> */} + {/* 제목과 버튼을 같은 라인에 배치 */} + <div className="flex items-center justify-between"> + <h2 className="text-2xl font-bold tracking-tight"> + {rfq + ? rfq.rfqTitle + ? `견적 상세 관리 ${rfq.rfqCode ?? ""} | ${rfq.rfqTitle}` + : `견적 상세 관리 ${rfq.rfqCode ?? ""}` + : "Loading RFQ..."} + </h2> + <Link href={`/${lng}/evcp/rfq-last`} passHref> + <Button variant="ghost" className="flex items-center text-primary hover:text-primary/80 transition-colors"> + <ArrowLeft className="mr-1 h-4 w-4" /> + <span>견적 목록으로 돌아가기</span> + </Button> + </Link> + </div> + + {/* 생성일과 마감일 표시 */} + {rfq && ( + <div className="flex items-center gap-6 pt-3"> + {/* 생성일 */} + <div className="flex items-center gap-2"> + <Calendar className="h-4 w-4 text-muted-foreground" /> + <span className="text-sm font-medium text-muted-foreground">생성일:</span> + <strong className="text-sm">{formatDate(rfq.createdAt, "KR")}</strong> + </div> + + {/* 구분선 */} + <div className="h-4 w-px bg-border" /> - {/* Due Date 표시 개선 */} - {rfq?.dueDate && dueDateStatus && ( - <div className="flex items-center gap-3 pt-2"> - <span className="text-sm font-medium text-muted-foreground">Due Date:</span> - <strong className="text-sm">{formatDate(rfq.dueDate, "KR")}</strong> - <div className={`flex items-center gap-1.5 px-2.5 py-1 rounded-full ${dueDateStatus.bgClassName} ${dueDateStatus.className}`}> - {dueDateStatus.icon} - <span className="text-xs font-medium">{dueDateStatus.text}</span> + {/* 마감일 */} + <div className="flex items-center gap-2"> + <CalendarDays className="h-4 w-4 text-muted-foreground" /> + <span className="text-sm font-medium text-muted-foreground">마감일:</span> + {rfq.dueDate ? ( + <> + <strong className="text-sm">{formatDate(rfq.dueDate, "KR")}</strong> + {dueDateStatus && ( + <div className={`flex items-center gap-1.5 px-2.5 py-1 rounded-full ${dueDateStatus.bgClassName} ${dueDateStatus.className}`}> + {dueDateStatus.icon} + <span className="text-xs font-medium">{dueDateStatus.text}</span> + </div> + )} + <DueDateEditButton + rfqId={rfqId} + currentDueDate={rfq.dueDate} + rfqCode={rfq.rfqCode || ''} + rfqTitle={rfq.rfqTitle || ''} + /> + </> + ) : ( + <> + <span className="text-sm text-muted-foreground">미설정</span> + <DueDateEditButton + rfqId={rfqId} + currentDueDate={null} + rfqCode={rfq.rfqCode || ''} + rfqTitle={rfq.rfqTitle || ''} + /> + </> + )} </div> </div> )} diff --git a/app/[lng]/evcp/(evcp)/rfq-last/[id]/vendor/page.tsx b/app/[lng]/evcp/(evcp)/rfq-last/[id]/vendor/page.tsx index 012296ca..296e46fe 100644 --- a/app/[lng]/evcp/(evcp)/rfq-last/[id]/vendor/page.tsx +++ b/app/[lng]/evcp/(evcp)/rfq-last/[id]/vendor/page.tsx @@ -36,7 +36,7 @@ export default async function VendorPage(props: VendorPageProps) { const { data: vendorResponses, success: responsesSuccess } = await getRfqVendorResponses(rfqId); - if (!rfqSuccess || !rfqData) { + if (!rfqSuccess || !rfqData ||!responsesSuccess||!vendorResponses) { return ( <div className="p-4"> <Alert variant="destructive"> @@ -50,7 +50,7 @@ export default async function VendorPage(props: VendorPageProps) { // 응답 상태별 집계 const statusSummary = { - total: vendorResponses?.length || 0, + total: rfqData?.details.length || 0, invited: vendorResponses?.filter(v => v.status === "초대됨").length || 0, drafting: vendorResponses?.filter(v => v.status === "작성중").length || 0, submitted: vendorResponses?.filter(v => v.status === "제출완료").length || 0, diff --git a/app/[lng]/evcp/(evcp)/tbe-last/page.tsx b/app/[lng]/evcp/(evcp)/tbe-last/page.tsx new file mode 100644 index 00000000..61e7ce05 --- /dev/null +++ b/app/[lng]/evcp/(evcp)/tbe-last/page.tsx @@ -0,0 +1,74 @@ +// app/[lng]/tbe-last/page.tsx + +import * as React from "react" +import { type SearchParams } from "@/types/table" +import { getValidFilters } from "@/lib/data-table" +import { getAllTBELast } from "@/lib/tbe-last/service" +import { searchParamsTBELastCache } from "@/lib/tbe-last/validations" +import { TbeLastTable } from "@/lib/tbe-last/table/tbe-last-table" +import { Shell } from "@/components/shell" +import { DataTableSkeleton } from "@/components/data-table/data-table-skeleton" +import { Button } from "@/components/ui/button" +import { Plus } from "lucide-react" + +interface TbeLastPageProps { + params: { + lng: string + } + searchParams: Promise<SearchParams> +} + +export default async function TbeLastPage(props: TbeLastPageProps) { + const resolvedParams = await props.params + const lng = resolvedParams.lng + + const searchParams = await props.searchParams + + // Parse search params + const search = searchParamsTBELastCache.parse(searchParams) + const validFilters = getValidFilters(search.filters) + + // Load data + const promises = Promise.all([ + getAllTBELast({ + ...search, + filters: validFilters, + }) + ]) + + return ( + <Shell className="gap-2"> + <div className="flex items-center justify-between"> + <div> + <h2 className="text-2xl font-bold tracking-tight"> + Technical Bid Evaluation (TBE) + </h2> + <p className="text-muted-foreground"> + RFQ 발송 후 기술 평가를 진행하고 문서를 검토합니다. + </p> + </div> + + </div> + + <React.Suspense + fallback={ + <DataTableSkeleton + columnCount={12} + searchableColumnCount={1} + filterableColumnCount={2} + cellWidths={["10rem", "12rem", "20rem", "10rem", "15rem", "15rem", "20rem", "20rem", "10rem", "10rem", "8rem", "8rem"]} + shrinkZero + /> + } + > + <TbeLastTable promises={promises} /> + </React.Suspense> + </Shell> + ) +} + +// Metadata +export const metadata = { + title: "TBE Management", + description: "Technical Bid Evaluation for RFQ responses", +}
\ No newline at end of file diff --git a/app/[lng]/partners/(partners)/rfq-last/[id]/page.tsx b/app/[lng]/partners/(partners)/rfq-last/[id]/page.tsx new file mode 100644 index 00000000..b14df5c3 --- /dev/null +++ b/app/[lng]/partners/(partners)/rfq-last/[id]/page.tsx @@ -0,0 +1,151 @@ +// app/partners/rfq-last/[id]/page.tsx +import { Metadata } from "next" +import { notFound } from "next/navigation" +import db from "@/db/db" +import { eq, and } from "drizzle-orm" +import { + rfqsLast, + rfqLastDetails, + rfqLastVendorResponses, + rfqPrItems,basicContractTemplates,basicContract, + vendors +} from "@/db/schema" +import { getServerSession } from "next-auth/next" +import { authOptions } from "@/app/api/auth/[...nextauth]/route" +import VendorResponseEditor from "@/lib/rfq-last/vendor-response/editor/vendor-response-editor" + +interface PageProps { + params: { + id: string + } +} + +export async function generateMetadata({ params }: PageProps): Promise<Metadata> { + return { + title: "견적서 작성", + description: "RFQ에 대한 견적서 작성 및 제출", + } +} + +export default async function VendorResponsePage({ params }: PageProps) { + const rfqId = parseInt(params.id) + + if (isNaN(rfqId)) { + notFound() + } + + // 인증 확인 + const session = await getServerSession(authOptions) + + if (!session?.user) { + return ( + <div className="flex h-full items-center justify-center"> + <div className="text-center"> + <h2 className="text-xl font-bold">로그인이 필요합니다</h2> + <p className="mt-2 text-muted-foreground">견적서 작성을 위해 로그인해주세요.</p> + </div> + </div> + ) + } + + // 벤더 정보 가져오기 + const vendor = await db.query.vendors.findFirst({ + where: eq(vendors.id, session.user.companyId) + }) + + if (!vendor || session.user.domain !== "partners") { + return ( + <div className="flex h-full items-center justify-center"> + <div className="text-center"> + <h2 className="text-xl font-bold">접근 권한이 없습니다</h2> + <p className="mt-2 text-muted-foreground">벤더 계정으로 로그인해주세요.</p> + </div> + </div> + ) + } + + // RFQ 정보 가져오기 + const rfq = await db.query.rfqsLast.findFirst({ + where: eq(rfqsLast.id, rfqId), + with: { + project: true, + rfqDetails: { + where: and(eq(rfqLastDetails.vendorsId, vendor.id),eq(rfqLastDetails.isLatest, true)), + with: { + vendor: true, + paymentTerms: true, + incoterms: true, + } + }, + rfqPrItems: true, + } + }) + + if (!rfq || !rfq.rfqDetails[0]) { + notFound() + } + + const rfqDetail = rfq.rfqDetails[0] + + // 기존 응답 가져오기 (있는 경우) + const existingResponse = await db.query.rfqLastVendorResponses.findFirst({ + where: and( + eq(rfqLastVendorResponses.rfqsLastId, rfqId), + eq(rfqLastVendorResponses.vendorId, vendor.id), + eq(rfqLastVendorResponses.isLatest, true) + ), + with: { + quotationItems: true, + attachments: true, + } + }) + + // PR Items 가져오기 + const prItems = await db.query.rfqPrItems.findMany({ + where: eq(rfqPrItems.rfqsLastId, rfqId), + orderBy: (items, { asc }) => [asc(items.rfqItem)] + }) + + const basicContracts = await db + .select({ + id: basicContract.id, + // templateId: basicContract.templateId, + templateName: basicContractTemplates.templateName, + status: basicContract.status, + // fileName: basicContract.fileName, + // filePath: basicContract.filePath, + deadline: basicContract.deadline, + signedAt: basicContract.vendorSignedAt, + // rejectedAt: basicContract.rejectedAt, + // rejectionReason: basicContract.rejectionReason, + createdAt: basicContract.createdAt, + }) + .from(basicContract) + .leftJoin( + basicContractTemplates, + eq(basicContract.templateId, basicContractTemplates.id) + ) + .where( + and( + eq(basicContract.vendorId, vendor.id), + eq(basicContract.rfqCompanyId, rfqDetail.id) + ) + ) + .orderBy(basicContract.createdAt) + + + return ( + <div className="container mx-auto py-8"> + <VendorResponseEditor + rfq={rfq} + rfqDetail={rfqDetail} + prItems={prItems} + vendor={vendor} + existingResponse={existingResponse} + userId={session.user.id} + basicContracts={basicContracts} // 추가 + + /> + </div> + ) +}
\ No newline at end of file diff --git a/app/[lng]/partners/(partners)/rfq-last/page.tsx b/app/[lng]/partners/(partners)/rfq-last/page.tsx new file mode 100644 index 00000000..cddb45dd --- /dev/null +++ b/app/[lng]/partners/(partners)/rfq-last/page.tsx @@ -0,0 +1,193 @@ +// app/vendor/quotations/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 } 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 { searchParamsVendorRfqCache } from "@/lib/rfq-last/vendor-response/validations"; +import { InformationButton } from "@/components/information/information-button" +import { getVendorQuotationsLast,getQuotationStatusCountsLast } from "@/lib/rfq-last/vendor-response/service"; +import { VendorQuotationsTableLast } from "@/lib/rfq-last/vendor-response/vendor-quotations-table"; + +export const metadata: Metadata = { + title: "견적 목록", + description: "진행 중인 견적서 목록", +}; + +interface IndexPageProps { + searchParams: Promise<SearchParams> +} + + +export default async function IndexPage(props: IndexPageProps) { + const searchParams = await props.searchParams + const search = searchParamsVendorRfqCache.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> + <div className="flex items-center gap-2"> + <h2 className="text-2xl font-bold tracking-tight"> + 견적 목록 + </h2> + <InformationButton pagePath="partners/rfq-ship" /> + </div> + {/* <p className="text-muted-foreground"> + 진행 중인 견적서 목록을 확인하고 관리합니다. + </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/quotations"> + <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 quotationsPromise = getVendorQuotationsLast({ + ...search, + filters: validFilters + }, vendorId); + + // 상태별 개수 가져오기 + const statusCountsPromise = getQuotationStatusCountsLast(vendorId); + + // 모든 프로미스 병렬 실행 + const promises = Promise.all([quotationsPromise]); + const statusCounts = await statusCountsPromise; + + return ( + <Shell className="gap-6"> + <div className="flex justify-between items-center"> + <div> + <h2 className="text-2xl font-bold tracking-tight">견적 목록</h2> + <p className="text-muted-foreground"> + 진행 중인 견적서 목록을 확인하고 관리합니다. + </p> + </div> + </div> + + <div className="grid gap-4 md:grid-cols-5"> + <Card> + <CardHeader className="py-4"> + <CardTitle className="text-base">전체 견적</CardTitle> + </CardHeader> + <CardContent> + <div className="text-2xl font-bold"> + {Object.values(statusCounts).reduce((sum, count) => sum + count, 0)}건 + </div> + </CardContent> + </Card> + + <Card> + <CardHeader className="py-4"> + <CardTitle className="text-base">응답 대기</CardTitle> + </CardHeader> + <CardContent> + <div className="text-2xl font-bold text-orange-600"> + {statusCounts["미응답"] || 0}건 + </div> + </CardContent> + </Card> + + <Card> + <CardHeader className="py-4"> + <CardTitle className="text-base">작성 중</CardTitle> + </CardHeader> + <CardContent> + <div className="text-2xl font-bold text-blue-600"> + {statusCounts["작성중"] || 0}건 + </div> + </CardContent> + </Card> + + <Card> + <CardHeader className="py-4"> + <CardTitle className="text-base">제출 완료</CardTitle> + </CardHeader> + <CardContent> + <div className="text-2xl font-bold text-green-600"> + {(statusCounts["제출완료"] || 0) + (statusCounts["최종확정"] || 0)}건 + </div> + </CardContent> + </Card> + + <Card> + <CardHeader className="py-4"> + <CardTitle className="text-base">불참</CardTitle> + </CardHeader> + <CardContent> + <div className="text-2xl font-bold text-gray-500"> + {statusCounts["불참"] || 0}건 + </div> + </CardContent> + </Card> + </div> + + <React.Suspense + fallback={ + <DataTableSkeleton + columnCount={7} + searchableColumnCount={2} + filterableColumnCount={3} + cellWidths={["10rem", "10rem", "8rem", "10rem", "10rem", "10rem", "8rem"]} + /> + } + > + <VendorQuotationsTableLast promises={promises} /> + </React.Suspense> + </Shell> + ); +}
\ No newline at end of file diff --git a/app/[lng]/partners/ocr/layout.tsx b/app/[lng]/partners/dtsocrshi/layout.tsx index f1654bf2..f1654bf2 100644 --- a/app/[lng]/partners/ocr/layout.tsx +++ b/app/[lng]/partners/dtsocrshi/layout.tsx diff --git a/app/[lng]/partners/ocr/page.tsx b/app/[lng]/partners/dtsocrshi/page.tsx index 7a12b75d..7a12b75d 100644 --- a/app/[lng]/partners/ocr/page.tsx +++ b/app/[lng]/partners/dtsocrshi/page.tsx diff --git a/app/api/auth/signup-with-vendor/route.ts b/app/api/auth/signup-with-vendor/route.ts index 930deef2..4585778c 100644 --- a/app/api/auth/signup-with-vendor/route.ts +++ b/app/api/auth/signup-with-vendor/route.ts @@ -147,7 +147,7 @@ async function saveVendorMaterials( await tx.insert(vendorPossibleMaterials).values({ vendorId, itemCode: material.materialGroupCode, - itemName: material.materialName, + itemName: material.materialGroupDesc, registerUserId: userId, registerUserName: userName, isConfirmed: false, // 업체 입력 정보이므로 확정되지 않음 diff --git a/app/api/contracts/get-template/route.ts b/app/api/contracts/get-template/route.ts new file mode 100644 index 00000000..c987c527 --- /dev/null +++ b/app/api/contracts/get-template/route.ts @@ -0,0 +1,33 @@ +import { NextRequest, NextResponse } from "next/server"; +import { readFile } from "fs/promises"; +import path from "path"; + +export async function POST(request: NextRequest) { + try { + const { templatePath } = await request.json(); + + if (!templatePath) { + return NextResponse.json( + { error: "템플릿 경로가 필요합니다." }, + { status: 400 } + ); + } + + const fullPath = path.join(process.cwd(), `${process.env.NAS_PATH}`, templatePath); + const fileBuffer = await readFile(fullPath); + + return new NextResponse(fileBuffer, { + headers: { + 'Content-Type': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'Content-Disposition': `attachment; filename="template.docx"` + } + }); + + } catch (error) { + console.error("템플릿 파일 읽기 실패:", error); + return NextResponse.json( + { error: "템플릿 파일을 읽을 수 없습니다." }, + { status: 500 } + ); + } +}
\ No newline at end of file diff --git a/app/api/contracts/prepare-template/route.ts b/app/api/contracts/prepare-template/route.ts new file mode 100644 index 00000000..189643b5 --- /dev/null +++ b/app/api/contracts/prepare-template/route.ts @@ -0,0 +1,83 @@ +import { NextRequest, NextResponse } from "next/server"; +import db from "@/db/db"; +import { basicContractTemplates, vendors } from "@/db/schema"; +import { eq, and, ilike } from "drizzle-orm"; + +export async function POST(request: NextRequest) { + try { + const { templateName, vendorId } = await request.json(); + + // 템플릿 조회 + const [template] = await db + .select() + .from(basicContractTemplates) + .where( + and( + ilike(basicContractTemplates.templateName, `%${templateName}%`), + eq(basicContractTemplates.status, "ACTIVE") + ) + ) + .limit(1); + + + + if (!template) { + return NextResponse.json( + { error: "템플릿을 찾을 수 없습니다." }, + { status: 404 } + ); + } + + // 벤더 정보 조회 + const [vendor] = await db + .select() + .from(vendors) + .where(eq(vendors.id, vendorId)) + .limit(1); + + if (!vendor) { + return NextResponse.json( + { error: "벤더를 찾을 수 없습니다." }, + { status: 404 } + ); + } + + // 템플릿 데이터 준비 + const templateData = { + company_name: vendor.vendorName || '협력업체명', + company_address: vendor.address || '주소', + company_address_detail: vendor.addressDetail || '', + company_postal_code: vendor.postalCode || '', + company_country: vendor.country || '대한민국', + representative_name: vendor.representativeName || '대표자명', + representative_email: vendor.representativeEmail || '', + representative_phone: vendor.representativePhone || '', + tax_id: vendor.taxId || '사업자번호', + corporate_registration_number: vendor.corporateRegistrationNumber || '', + phone_number: vendor.phone || '전화번호', + email: vendor.email || '', + website: vendor.website || '', + signature_date: new Date().toLocaleDateString('ko-KR'), + contract_date: new Date().toISOString().split('T')[0], + effective_date: new Date().toISOString().split('T')[0], + expiry_date: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000).toISOString().split('T')[0], + vendor_code: vendor.vendorCode || '', + business_size: vendor.businessSize || '', + credit_rating: vendor.creditRating || '', + template_type: templateName, + contract_number: `BC-${new Date().getFullYear()}-${String(vendorId).padStart(4, '0')}-${Date.now()}`, + }; + + return NextResponse.json({ + template, + templateData + }); + + } catch (error) { + console.log("템플릿 준비 실패:", error); + return NextResponse.json( + { error: "템플릿 준비 중 오류가 발생했습니다." }, + { status: 500 } + ); + } +}
\ No newline at end of file diff --git a/app/api/contracts/template/route.ts b/app/api/contracts/template/route.ts new file mode 100644 index 00000000..c66fea0e --- /dev/null +++ b/app/api/contracts/template/route.ts @@ -0,0 +1,32 @@ +import { NextRequest, NextResponse } from "next/server"; +import { readFile } from "fs/promises"; +import path from "path"; + +export async function POST(request: NextRequest) { + try { + const { templatePath } = await request.json(); + + if (!templatePath) { + return NextResponse.json( + { error: "템플릿 경로가 필요합니다." }, + { status: 400 } + ); + } + + const fullPath = path.join(process.cwd(), process.env.NAS_PATH, templatePath); + const fileBuffer = await readFile(fullPath); + + return new NextResponse(fileBuffer, { + headers: { + 'Content-Type': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'Content-Disposition': `attachment; filename="template.docx"` + } + }); + } catch (error) { + console.error("템플릿 파일 읽기 실패:", error); + return NextResponse.json( + { error: "템플릿 파일을 읽을 수 없습니다." }, + { status: 500 } + ); + } +}
\ No newline at end of file diff --git a/app/api/partners/rfq-last/[id]/response/route.ts b/app/api/partners/rfq-last/[id]/response/route.ts new file mode 100644 index 00000000..db320dde --- /dev/null +++ b/app/api/partners/rfq-last/[id]/response/route.ts @@ -0,0 +1,384 @@ +// app/api/partners/rfq-last/[id]/response/route.ts +import { NextRequest, NextResponse } from "next/server" +import { getServerSession } from "next-auth/next" +import { authOptions } from "@/app/api/auth/[...nextauth]/route" +import db from "@/db/db" +import { + rfqLastVendorResponses, + rfqLastVendorQuotationItems, + rfqLastVendorAttachments, + rfqLastVendorResponseHistory +} from "@/db/schema" +import { eq, and } from "drizzle-orm" +import { writeFile, mkdir } from "fs/promises" +import { createWriteStream } from "fs" +import { pipeline } from "stream/promises" +import path from "path" +import { v4 as uuidv4 } from "uuid" + +// 1GB 파일 지원을 위한 설정 +export const config = { + api: { + bodyParser: { + sizeLimit: '1gb', + }, + responseLimit: false, + }, +} + +// 스트리밍으로 파일 저장 +async function saveFileStream(file: File, filepath: string) { + const stream = file.stream() + const writeStream = createWriteStream(filepath) + await pipeline(stream, writeStream) +} + +export async function POST( + request: NextRequest, + { params }: { params: { id: string } } +) { + try { + const session = await getServerSession(authOptions) + if (!session?.user || session.user.domain !== "partners") { + return NextResponse.json({ error: "Unauthorized" }, { status: 401 }) + } + + const rfqId = parseInt(params.id) + const formData = await request.formData() + 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({ + rfqsLastId: data.rfqsLastId, + rfqLastDetailsId: data.rfqLastDetailsId, + vendorId: data.vendorId, + responseVersion: 1, + isLatest: true, + participationStatus: "참여", + participationRepliedAt: new Date(), + participationRepliedBy: session.user.id, + status: data.status || "작성중", + submittedAt: data.submittedAt ? new Date(data.submittedAt) : null, + submittedBy: data.submittedBy, + totalAmount: data.totalAmount, + currency: data.vendorCurrency || "USD", + + // 벤더 제안 조건 + vendorCurrency: data.vendorCurrency, + vendorPaymentTermsCode: data.vendorPaymentTermsCode, + vendorIncotermsCode: data.vendorIncotermsCode, + vendorIncotermsDetail: data.vendorIncotermsDetail, + vendorDeliveryDate: data.vendorDeliveryDate ? new Date(data.vendorDeliveryDate) : null, + vendorContractDuration: data.vendorContractDuration, + vendorTaxCode: data.vendorTaxCode, + vendorPlaceOfShipping: data.vendorPlaceOfShipping, + vendorPlaceOfDestination: data.vendorPlaceOfDestination, + + // 특수 조건 응답 + vendorFirstYn: data.vendorFirstYn, + vendorFirstDescription: data.vendorFirstDescription, + vendorFirstAcceptance: data.vendorFirstAcceptance, + vendorSparepartYn: data.vendorSparepartYn, + vendorSparepartDescription: data.vendorSparepartDescription, + vendorSparepartAcceptance: data.vendorSparepartAcceptance, + vendorMaterialPriceRelatedYn: data.vendorMaterialPriceRelatedYn, + vendorMaterialPriceRelatedReason: data.vendorMaterialPriceRelatedReason, + + // 변경 사유 + currencyReason: data.currencyReason, + paymentTermsReason: data.paymentTermsReason, + deliveryDateReason: data.deliveryDateReason, + incotermsReason: data.incotermsReason, + taxReason: data.taxReason, + shippingReason: data.shippingReason, + + // 비고 + generalRemark: data.generalRemark, + technicalProposal: data.technicalProposal, + + createdBy: session.user.id, + updatedBy: session.user.id, + }).returning() + + // 2. 견적 아이템 저장 + if (data.quotationItems && data.quotationItems.length > 0) { + const quotationItemsData = data.quotationItems.map((item: any) => ({ + vendorResponseId: vendorResponse.id, + rfqPrItemId: item.rfqPrItemId, + prNo: item.prNo, + materialCode: item.materialCode, + materialDescription: item.materialDescription, + quantity: item.quantity || 0, + uom: item.uom, + unitPrice: item.unitPrice || 0, + totalPrice: item.totalPrice || 0, + currency: data.vendorCurrency || "USD", + vendorDeliveryDate: item.vendorDeliveryDate ? new Date(item.vendorDeliveryDate) : null, + leadTime: item.leadTime, + manufacturer: item.manufacturer, + manufacturerCountry: item.manufacturerCountry, + modelNo: item.modelNo, + technicalCompliance: item.technicalCompliance ?? true, + alternativeProposal: item.alternativeProposal, + discountRate: item.discountRate, + itemRemark: item.itemRemark, + deviationReason: item.deviationReason, + })) + + await tx.insert(rfqLastVendorQuotationItems).values(quotationItemsData) + } + + // 3. 이력 기록 + await tx.insert(rfqLastVendorResponseHistory).values({ + vendorResponseId: vendorResponse.id, + action: "생성", + previousStatus: null, + newStatus: data.status || "작성중", + changeDetails: data, + performedBy: session.user.id, + }) + + return vendorResponse + }) + + // 4. 파일 저장 (트랜잭션 밖에서 처리) + const fileRecords = [] + + if (files.length > 0) { + for (const file of files) { + try { + const filename = `${uuidv4()}_${file.name.replace(/[^a-zA-Z0-9.-]/g, '_')}` + const filepath = path.join(uploadDir, filename) + + // 대용량 파일은 스트리밍으로 저장 + if (file.size > 50 * 1024 * 1024) { // 50MB 이상 + await saveFileStream(file, filepath) + } else { + // 작은 파일은 기존 방식 + const buffer = Buffer.from(await file.arrayBuffer()) + await writeFile(filepath, buffer) + } + + fileRecords.push({ + vendorResponseId: result.id, + attachmentType: (file as any).attachmentType || "기타", + fileName: filename, + originalFileName: file.name, + filePath: `/uploads/rfq/${rfqId}/${filename}`, + fileSize: file.size, + fileType: file.type, + description: (file as any).description, + uploadedBy: session.user.id, + }) + } catch (fileError) { + console.error(`Failed to save file ${file.name}:`, fileError) + // 파일 저장 실패 시 계속 진행 (다른 파일들은 저장) + } + } + + // DB에 파일 정보 저장 + if (fileRecords.length > 0) { + await db.insert(rfqLastVendorAttachments).values(fileRecords) + } + } + + return NextResponse.json({ + success: true, + data: result, + message: data.status === "제출완료" ? "견적서가 성공적으로 제출되었습니다." : "견적서가 저장되었습니다.", + filesUploaded: fileRecords.length + }) + + } catch (error) { + console.error("Error creating vendor response:", error) + return NextResponse.json( + { error: "Failed to create vendor response" }, + { status: 500 } + ) + } +} + +export async function PUT( + request: NextRequest, + { params }: { params: { id: string } } +) { + try { + const session = await getServerSession(authOptions) + if (!session?.user || session.user.domain !== "partners") { + return NextResponse.json({ error: "Unauthorized" }, { status: 401 }) + } + + const rfqId = parseInt(params.id) + const formData = await request.formData() + 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 }) + + // 트랜잭션 시작 + const result = await db.transaction(async (tx) => { + // 1. 기존 응답 찾기 + const existingResponse = await tx.query.rfqLastVendorResponses.findFirst({ + where: and( + eq(rfqLastVendorResponses.rfqsLastId, rfqId), + eq(rfqLastVendorResponses.vendorId, data.vendorId), + eq(rfqLastVendorResponses.isLatest, true) + ) + }) + + if (!existingResponse) { + throw new Error("Response not found") + } + + const previousStatus = existingResponse.status + + // 2. 새 버전 생성 (제출 시) 또는 기존 버전 업데이트 + let responseId = existingResponse.id + + if (data.status === "제출완료" && previousStatus !== "제출완료") { + // 기존 버전을 비활성화 + await tx.update(rfqLastVendorResponses) + .set({ isLatest: false }) + .where(eq(rfqLastVendorResponses.id, existingResponse.id)) + + // 새 버전 생성 + const [newResponse] = await tx.insert(rfqLastVendorResponses).values({ + ...data, + vendorDeliveryDate: data.vendorDeliveryDate ? new Date(data.vendorDeliveryDate) : null, + submittedAt: data.submittedAt ? new Date(data.submittedAt) : null, + responseVersion: existingResponse.responseVersion + 1, + isLatest: true, + createdBy: existingResponse.createdBy, + updatedBy: session.user.id, + }).returning() + + responseId = newResponse.id + } else { + // 기존 버전 업데이트 + await tx.update(rfqLastVendorResponses) + .set({ + ...data, + vendorDeliveryDate: data.vendorDeliveryDate ? new Date(data.vendorDeliveryDate) : null, + submittedAt: data.submittedAt ? new Date(data.submittedAt) : null, + updatedBy: session.user.id, + updatedAt: new Date(), + }) + .where(eq(rfqLastVendorResponses.id, existingResponse.id)) + } + + // 3. 견적 아이템 업데이트 + // 기존 아이템 삭제 + await tx.delete(rfqLastVendorQuotationItems) + .where(eq(rfqLastVendorQuotationItems.vendorResponseId, responseId)) + + // 새 아이템 추가 + if (data.quotationItems && data.quotationItems.length > 0) { + const quotationItemsData = data.quotationItems.map((item: any) => ({ + vendorResponseId: responseId, + rfqPrItemId: item.rfqPrItemId, + prNo: item.prNo, + materialCode: item.materialCode, + materialDescription: item.materialDescription, + quantity: item.quantity || 0, + uom: item.uom, + unitPrice: item.unitPrice || 0, + totalPrice: item.totalPrice || 0, + currency: data.vendorCurrency || "USD", + vendorDeliveryDate: item.vendorDeliveryDate ? new Date(item.vendorDeliveryDate) : null, + leadTime: item.leadTime, + manufacturer: item.manufacturer, + manufacturerCountry: item.manufacturerCountry, + modelNo: item.modelNo, + technicalCompliance: item.technicalCompliance ?? true, + alternativeProposal: item.alternativeProposal, + discountRate: item.discountRate, + itemRemark: item.itemRemark, + deviationReason: item.deviationReason, + })) + + await tx.insert(rfqLastVendorQuotationItems).values(quotationItemsData) + } + + // 4. 이력 기록 + await tx.insert(rfqLastVendorResponseHistory).values({ + vendorResponseId: responseId, + action: data.status === "제출완료" ? "제출" : "수정", + previousStatus: previousStatus, + newStatus: data.status, + changeDetails: data, + performedBy: session.user.id, + }) + + return { id: responseId } + }) + + // 5. 새 첨부파일 추가 (트랜잭션 밖에서) + const fileRecords = [] + + if (files.length > 0) { + for (const file of files) { + try { + const filename = `${uuidv4()}_${file.name.replace(/[^a-zA-Z0-9.-]/g, '_')}` + const filepath = path.join(uploadDir, filename) + + // 대용량 파일은 스트리밍으로 저장 + if (file.size > 50 * 1024 * 1024) { // 50MB 이상 + await saveFileStream(file, filepath) + } else { + const buffer = Buffer.from(await file.arrayBuffer()) + await writeFile(filepath, buffer) + } + + fileRecords.push({ + vendorResponseId: result.id, + attachmentType: (file as any).attachmentType || "기타", + fileName: filename, + originalFileName: file.name, + filePath: `/uploads/rfq/${rfqId}/${filename}`, + fileSize: file.size, + fileType: file.type, + description: (file as any).description, + uploadedBy: session.user.id, + }) + } catch (fileError) { + console.error(`Failed to save file ${file.name}:`, fileError) + } + } + + if (fileRecords.length > 0) { + await db.insert(rfqLastVendorAttachments).values(fileRecords) + } + } + + 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( + { error: "Failed to update vendor response" }, + { status: 500 } + ) + } +}
\ No newline at end of file diff --git a/app/api/rfq/attachments/download-all/route.ts b/app/api/rfq/attachments/download-all/route.ts new file mode 100644 index 00000000..0ff6a071 --- /dev/null +++ b/app/api/rfq/attachments/download-all/route.ts @@ -0,0 +1,179 @@ +import { NextRequest, NextResponse } from 'next/server'; +import db from '@/db/db'; +import { sql } from 'drizzle-orm'; +import JSZip from 'jszip'; +import fs from 'fs/promises'; +import path from 'path'; + +export async function POST(request: NextRequest) { + try { + // 1. 요청 데이터 파싱 + const body = await request.json(); + const { rfqId, files } = body; + + // 2. 입력값 검증 + if (!rfqId || !Array.isArray(files) || files.length === 0) { + return NextResponse.json( + { error: '유효하지 않은 요청입니다' }, + { status: 400 } + ); + } + + // 파일 개수 제한 (보안) + if (files.length > 100) { + return NextResponse.json( + { error: '한 번에 다운로드할 수 있는 최대 파일 수는 100개입니다' }, + { status: 400 } + ); + } + + // 3. DB에서 RFQ 정보 확인 (권한 검증용) + const rfqResult = await db.execute(sql` + SELECT rfq_code, rfq_title + FROM rfqs_last_view + WHERE id = ${rfqId} + `); + + if (rfqResult.rows.length === 0) { + return NextResponse.json( + { error: 'RFQ를 찾을 수 없습니다' }, + { status: 404 } + ); + } + + const rfqInfo = rfqResult.rows[0] as any; + + // 4. NAS 경로 설정 + const nasPath = process.env.NAS_PATH; + if (!nasPath) { + console.error('NAS_PATH 환경 변수가 설정되지 않았습니다'); + return NextResponse.json( + { error: '서버 설정 오류' }, + { status: 500 } + ); + } + + // 5. ZIP 객체 생성 + const zip = new JSZip(); + let addedFiles = 0; + const errors: string[] = []; + + // 6. 파일들을 ZIP에 추가 + for (const file of files) { + if (!file.path || !file.name) { + errors.push(`잘못된 파일 정보: ${file.name || 'unknown'}`); + continue; + } + + try { + // 경로 정규화 및 보안 검증 + const filePath = file.path.startsWith('/') + ? path.join(nasPath, file.path) + : path.join(nasPath, '/', file.path); + + // 경로 탐색 공격 방지 + // const normalizedPath = path.normalize(filePath); + // if (!normalizedPath.startsWith(nasPath)) { + // console.error(`보안 위반: 허용되지 않은 경로 접근 시도 - ${file.path}`); + // errors.push(`보안 오류: ${file.name}`); + // continue; + // } + + // 파일 읽기 + const fileContent = await fs.readFile(filePath); + + // 중복 파일명 처리 + let fileName = file.name; + let counter = 1; + while (zip.file(fileName)) { + const ext = path.extname(file.name); + const baseName = path.basename(file.name, ext); + fileName = `${baseName}_${counter}${ext}`; + counter++; + } + + // ZIP에 파일 추가 + zip.file(fileName, fileContent, { + binary: true, + createFolders: false, + date: new Date(), + comment: `RFQ: ${rfqId}` + }); + + addedFiles++; + + } catch (error) { + console.error(`파일 처리 실패: ${file.name}`, error); + errors.push(`파일 읽기 실패: ${file.name}`); + } + } + + // 7. 추가된 파일이 없으면 오류 + if (addedFiles === 0) { + return NextResponse.json( + { + error: '다운로드할 수 있는 파일이 없습니다', + details: errors + }, + { status: 404 } + ); + } + + // 8. ZIP 파일 생성 (압축 레벨 설정) + const zipBuffer = await zip.generateAsync({ + type: 'nodebuffer', + compression: 'DEFLATE', + compressionOptions: { + level: 9 // 최대 압축 + }, + comment: `RFQ ${rfqInfo.rfq_code} 첨부파일`, + platform: 'UNIX' // 파일 권한 보존 + }); + + // 9. 파일명 생성 + const fileName = `RFQ_${rfqInfo.rfq_code}_attachments_${new Date().toISOString().slice(0, 10)}.zip`; + + // 10. 로그 기록 + console.log(`ZIP 생성 완료: ${fileName}, 파일 수: ${addedFiles}/${files.length}, 크기: ${(zipBuffer.length / 1024).toFixed(2)}KB`); + + if (errors.length > 0) { + console.warn('처리 중 오류 발생:', errors); + } + + // 11. 응답 반환 + return new NextResponse(zipBuffer, { + status: 200, + headers: { + 'Content-Type': 'application/zip', + 'Content-Disposition': `attachment; filename="${fileName}"`, + 'Content-Length': zipBuffer.length.toString(), + 'Cache-Control': 'no-cache, no-store, must-revalidate', + 'X-Files-Count': addedFiles.toString(), + 'X-Total-Files': files.length.toString(), + 'X-Errors-Count': errors.length.toString(), + }, + }); + + } catch (error) { + console.error('전체 다운로드 오류:', error); + return NextResponse.json( + { + error: '파일 다운로드 중 오류가 발생했습니다', + details: error instanceof Error ? error.message : 'Unknown error' + }, + { status: 500 } + ); + } +} + +// OPTIONS 요청 처리 (CORS) +export async function OPTIONS(request: NextRequest) { + return new NextResponse(null, { + status: 200, + headers: { + 'Access-Control-Allow-Origin': '*', + 'Access-Control-Allow-Methods': 'POST, OPTIONS', + 'Access-Control-Allow-Headers': 'Content-Type', + }, + }); +}
\ No newline at end of file diff --git a/app/globals.css b/app/globals.css index dba67fc8..d9815aeb 100644 --- a/app/globals.css +++ b/app/globals.css @@ -164,7 +164,7 @@ body { /* 원본 */ /* @apply px-4 xl:px-6 2xl:px-4 mx-auto max-w-[1800px]; */ /* @apply px-4 xl:px-6 2xl:px-4 mx-auto; */ - @apply py-6 px-6 min-w-full mx-auto; + @apply min-w-full mx-auto; } |
