From 4ee8b24cfadf47452807fa2af801385ed60ab47c Mon Sep 17 00:00:00 2001 From: dujinkim Date: Mon, 15 Sep 2025 14:41:01 +0000 Subject: (대표님) 작업사항 - rfqLast, tbeLast, pdfTron, userAuth MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/admin-users/service.ts | 2 +- lib/basic-contract/gen-service.ts | 33 +- .../viewer/basic-contract-sign-viewer.tsx | 1 + lib/bidding/pre-quote/service.ts | 49 +- lib/export-to-excel.ts | 316 +++++++++ lib/rfq-last/attachment/vendor-response-table.tsx | 387 ++++++++--- lib/rfq-last/compare-action.ts | 500 ++++++++++++++ lib/rfq-last/quotation-compare-view.tsx | 755 +++++++++++++++++++++ lib/rfq-last/service.ts | 376 +++++++++- lib/rfq-last/table/rfq-seal-toggle-cell.tsx | 93 +++ lib/rfq-last/table/rfq-table-columns.tsx | 73 +- lib/rfq-last/table/rfq-table-toolbar-actions.tsx | 222 ++++-- .../editor/vendor-response-editor.tsx | 335 +++++---- lib/rfq-last/vendor-response/service.ts | 175 +---- lib/rfq-last/vendor-response/validations.ts | 4 +- .../vendor-quotations-table-columns.tsx | 2 +- .../vendor-response/vendor-quotations-table.tsx | 2 +- lib/rfq-last/vendor/rfq-vendor-table.tsx | 223 ++++-- lib/soap/ecc/send/pcr-confirm.ts | 2 +- lib/tbe-last/service.ts | 231 ++++++- lib/tbe-last/table/documents-sheet.tsx | 543 +++++++++++++++ lib/tbe-last/table/evaluation-dialog.tsx | 432 ++++++++++++ lib/tbe-last/table/pr-items-dialog.tsx | 83 +++ lib/tbe-last/table/session-detail-dialog.tsx | 103 +++ lib/tbe-last/table/tbe-last-table-columns.tsx | 214 +++--- lib/tbe-last/table/tbe-last-table.tsx | 279 ++------ lib/tbe-last/vendor-tbe-service.ts | 355 ++++++++++ lib/tbe-last/vendor/tbe-table-columns.tsx | 335 +++++++++ lib/tbe-last/vendor/tbe-table.tsx | 222 ++++++ lib/tbe-last/vendor/vendor-comment-dialog.tsx | 313 +++++++++ .../vendor/vendor-document-upload-dialog.tsx | 326 +++++++++ lib/tbe-last/vendor/vendor-documents-sheet.tsx | 602 ++++++++++++++++ .../vendor/vendor-evaluation-view-dialog.tsx | 250 +++++++ lib/tbe-last/vendor/vendor-pr-items-dialog.tsx | 253 +++++++ lib/users/auth/verifyCredentails.ts | 4 +- lib/users/repository.ts | 7 +- 36 files changed, 7118 insertions(+), 984 deletions(-) create mode 100644 lib/export-to-excel.ts create mode 100644 lib/rfq-last/compare-action.ts create mode 100644 lib/rfq-last/quotation-compare-view.tsx create mode 100644 lib/rfq-last/table/rfq-seal-toggle-cell.tsx create mode 100644 lib/tbe-last/table/documents-sheet.tsx create mode 100644 lib/tbe-last/table/evaluation-dialog.tsx create mode 100644 lib/tbe-last/table/pr-items-dialog.tsx create mode 100644 lib/tbe-last/table/session-detail-dialog.tsx create mode 100644 lib/tbe-last/vendor-tbe-service.ts create mode 100644 lib/tbe-last/vendor/tbe-table-columns.tsx create mode 100644 lib/tbe-last/vendor/tbe-table.tsx create mode 100644 lib/tbe-last/vendor/vendor-comment-dialog.tsx create mode 100644 lib/tbe-last/vendor/vendor-document-upload-dialog.tsx create mode 100644 lib/tbe-last/vendor/vendor-documents-sheet.tsx create mode 100644 lib/tbe-last/vendor/vendor-evaluation-view-dialog.tsx create mode 100644 lib/tbe-last/vendor/vendor-pr-items-dialog.tsx (limited to 'lib') diff --git a/lib/admin-users/service.ts b/lib/admin-users/service.ts index c253f481..70c04aa1 100644 --- a/lib/admin-users/service.ts +++ b/lib/admin-users/service.ts @@ -262,7 +262,7 @@ export async function createAdminUser(input: CreateUserSchema & { language?: str // 3. 유저 생성 const [newUser] = await insertUser(tx, { name: input.name, - email: input.email, + email: input.email.toLowerCase(), phone: input.phone?.trim(), // 전화번호 앞뒤 공백 제거 domain: input.domain, companyId: input.companyId ?? null, diff --git a/lib/basic-contract/gen-service.ts b/lib/basic-contract/gen-service.ts index 5619f98e..aa9efbc1 100644 --- a/lib/basic-contract/gen-service.ts +++ b/lib/basic-contract/gen-service.ts @@ -8,6 +8,7 @@ import { eq, and, ilike } from "drizzle-orm"; import { addDays } from "date-fns"; import { writeFile, mkdir } from "fs/promises"; import path from "path"; +import { saveBuffer } from '@/lib/file-storage'; // 추가 interface BasicContractParams { templateName: string; @@ -348,17 +349,19 @@ export async function saveContractPdf({ templateId: number; }) { try { - // 1. PDF 파일 저장 - const outputDir = path.join(process.cwd(), process.env.NAS_PATH, "contracts", "generated"); - await mkdir(outputDir, { recursive: true }); + // 1. PDF 파일 저장 (공용 saveBuffer 사용) + const saveResult = await saveBuffer({ + buffer: Buffer.from(pdfBuffer), + fileName: fileName, // 원본 파일명 (확장자 포함) + directory: 'contracts/generated', + originalName: fileName, // DB에 저장할 원본명 + userId: params.requestedBy // 요청자 ID를 userId로 사용 + }); - const timestamp = Date.now(); - const finalFileName = `${fileName.replace('.pdf', '')}_${timestamp}.pdf`; - const outputPath = path.join(outputDir, finalFileName); - - await writeFile(outputPath, Buffer.from(pdfBuffer)); - - const relativePath = `/contracts/generated/${finalFileName}`; + // 저장 실패 시 에러 처리 + if (!saveResult.success) { + throw new Error(saveResult.error || 'PDF 파일 저장에 실패했습니다.'); + } // 2. DB에 계약서 레코드 생성 const [newContract] = await db @@ -371,8 +374,8 @@ export async function saveContractPdf({ generalContractId: params.generalContractId, requestedBy: params.requestedBy, status: "PENDING", - fileName: finalFileName, - filePath: relativePath, + fileName: saveResult.originalName || fileName, // 원본 파일명 + filePath: saveResult.publicPath, // 웹 접근 가능한 경로 deadline: addDays(new Date(), 10), createdAt: new Date(), updatedAt: new Date(), @@ -385,8 +388,10 @@ export async function saveContractPdf({ templateName: params.templateName, status: newContract.status, deadline: newContract.deadline, - pdfPath: relativePath, - pdfFileName: finalFileName + pdfPath: saveResult.publicPath, // 공용 함수가 반환한 경로 + pdfFileName: saveResult.originalName || fileName, // 원본 파일명 + hashedFileName: saveResult.fileName, // 실제 저장된 해시 파일명 (필요시 사용) + securityChecks: saveResult.securityChecks // 보안 검증 결과 (디버깅용) }; } catch (error) { console.error("PDF 저장 실패:", error); diff --git a/lib/basic-contract/viewer/basic-contract-sign-viewer.tsx b/lib/basic-contract/viewer/basic-contract-sign-viewer.tsx index e52f0d79..5698428e 100644 --- a/lib/basic-contract/viewer/basic-contract-sign-viewer.tsx +++ b/lib/basic-contract/viewer/basic-contract-sign-viewer.tsx @@ -594,6 +594,7 @@ export function BasicContractSignViewer({ isComplete: false }); + console.log(filePath, "filePath") console.log(surveyTemplate, "surveyTemplate") const conditionalHandler = useConditionalSurvey(surveyTemplate); diff --git a/lib/bidding/pre-quote/service.ts b/lib/bidding/pre-quote/service.ts index 680a8ff5..7f054a66 100644 --- a/lib/bidding/pre-quote/service.ts +++ b/lib/bidding/pre-quote/service.ts @@ -11,7 +11,7 @@ import { mkdir, writeFile } from 'fs/promises' import path from 'path' import { revalidateTag, revalidatePath } from 'next/cache' import { basicContract } from '@/db/schema/basicContractDocumnet' -import { saveFile } from '@/lib/file-stroage' +import { saveFile ,saveBuffer} from '@/lib/file-stroage' // userId를 user.name으로 변환하는 유틸리티 함수 async function getUserNameById(userId: string): Promise { @@ -1225,10 +1225,7 @@ export async function sendBiddingBasicContracts( const results = [] const savedContracts = [] - // 트랜잭션 시작 - const contractsDir = path.join(process.cwd(), `${process.env.NAS_PATH}`, "contracts", "generated"); - await mkdir(contractsDir, { recursive: true }); - + // 트랜잭션 시작 - contractsDir 제거 (saveBuffer가 처리) const result = await db.transaction(async (tx) => { // 각 벤더별로 기본계약 생성 및 이메일 발송 for (const vendor of vendorData) { @@ -1288,6 +1285,7 @@ export async function sendBiddingBasicContracts( if (vendor.contractRequirements.projectGtcYn) contractTypes.push({ type: 'Project_GTC', templateName: '기술' }) if (vendor.contractRequirements.agreementYn) contractTypes.push({ type: '기술자료', templateName: '기술자료' }) console.log("contractTypes", contractTypes) + for (const contractType of contractTypes) { // PDF 데이터 찾기 (include를 사용하여 유연하게 찾기) console.log("generatedPdfs", generatedPdfs.map(pdf => pdf.key)) @@ -1301,11 +1299,22 @@ export async function sendBiddingBasicContracts( continue } - // 파일 저장 (rfq-last 방식) + // 파일 저장 - saveBuffer 사용 const fileName = `${contractType.type}_${vendor.vendorCode || vendor.vendorId}_${vendor.biddingCompanyId}_${Date.now()}.pdf` - const filePath = path.join(contractsDir, fileName); + + const saveResult = await saveBuffer({ + buffer: Buffer.from(pdfData.buffer), + fileName: fileName, + directory: 'contracts/generated', + originalName: fileName, + userId: currentUser.id + }) - await writeFile(filePath, Buffer.from(pdfData.buffer)); + // 저장 실패 시 처리 + if (!saveResult.success) { + console.error(`PDF 저장 실패: ${saveResult.error}`) + continue + } // 템플릿 정보 조회 (rfq-last 방식) const [template] = await db @@ -1343,8 +1352,8 @@ export async function sendBiddingBasicContracts( .set({ requestedBy: currentUser.id, status: "PENDING", // 재발송 상태 - fileName: fileName, - filePath: `/contracts/generated/${fileName}`, + fileName: saveResult.originalName || fileName, // 원본 파일명 + filePath: saveResult.publicPath, // saveBuffer가 반환한 공개 경로 deadline: new Date(Date.now() + 10 * 24 * 60 * 60 * 1000), updatedAt: new Date(), }) @@ -1364,8 +1373,8 @@ export async function sendBiddingBasicContracts( generalContractId: null, requestedBy: currentUser.id, status: 'PENDING', - fileName: fileName, - filePath: `/contracts/generated/${fileName}`, + fileName: saveResult.originalName || fileName, // 원본 파일명 + filePath: saveResult.publicPath, // saveBuffer가 반환한 공개 경로 deadline: new Date(Date.now() + 10 * 24 * 60 * 60 * 1000), // 10일 후 createdAt: new Date(), updatedAt: new Date(), @@ -1380,19 +1389,10 @@ export async function sendBiddingBasicContracts( vendorName: vendor.vendorName, contractId: contractRecord.id, contractType: contractType.type, - fileName: fileName, - filePath: `/contracts/generated/${fileName}`, + fileName: saveResult.originalName || fileName, + filePath: saveResult.publicPath, + hashedFileName: saveResult.fileName, // 실제 저장된 파일명 (디버깅용) }) - - // savedContracts에 추가 (rfq-last 방식) - // savedContracts.push({ - // vendorId: vendor.vendorId, - // vendorName: vendor.vendorName, - // templateName: contractType.templateName, - // contractId: contractRecord.id, - // fileName: fileName, - // isUpdated: !!existingContract, // 업데이트 여부 표시 - // }) } // 이메일 발송 (선택사항) @@ -1439,7 +1439,6 @@ export async function sendBiddingBasicContracts( ) } } - // 기존 기본계약 조회 (서버 액션) export async function getExistingBasicContractsForBidding(biddingId: number) { try { diff --git a/lib/export-to-excel.ts b/lib/export-to-excel.ts new file mode 100644 index 00000000..b35c18d6 --- /dev/null +++ b/lib/export-to-excel.ts @@ -0,0 +1,316 @@ +// lib/utils/export-to-excel.ts + +import ExcelJS from 'exceljs' + +interface ExportToExcelOptions { + filename?: string + sheetName?: string + headers?: string[] + dateFormat?: string + autoFilter?: boolean + freezeHeader?: boolean +} + +/** + * 데이터 배열을 Excel 파일로 내보내기 (ExcelJS 사용) + * @param data - 내보낼 데이터 배열 + * @param options - 내보내기 옵션 + */ +export async function exportDataToExcel( + data: Record[], + options: ExportToExcelOptions = {} +) { + const { + filename = 'export', + sheetName = 'Sheet1', + headers, + dateFormat = 'yyyy-mm-dd', + autoFilter = true, + freezeHeader = true + } = options + + try { + // 데이터가 없으면 반환 + if (!data || data.length === 0) { + console.warn('No data to export') + return false + } + + // 워크북 생성 + const workbook = new ExcelJS.Workbook() + workbook.creator = 'TBE System' + workbook.created = new Date() + + // 워크시트 추가 + const worksheet = workbook.addWorksheet(sheetName, { + properties: { + defaultRowHeight: 20 + } + }) + + // 헤더 처리 + const finalHeaders = headers || Object.keys(data[0]) + + // 컬럼 정의 + const columns = finalHeaders.map(header => ({ + header, + key: header, + width: Math.min( + Math.max( + header.length, + ...data.map(row => { + const value = row[header] + if (value === null || value === undefined) return 0 + return String(value).length + }) + ) + 2, + 50 + ) + })) + + worksheet.columns = columns + + // 데이터 추가 + data.forEach(row => { + const rowData: Record = {} + + finalHeaders.forEach(header => { + const value = row[header] + + // null/undefined 처리 + if (value === null || value === undefined) { + rowData[header] = '' + } + // Date 객체 처리 + else if (value instanceof Date) { + rowData[header] = value + } + // boolean 처리 + else if (typeof value === 'boolean') { + rowData[header] = value ? 'Yes' : 'No' + } + // 숫자 처리 + else if (typeof value === 'number') { + rowData[header] = value + } + // 기타 (문자열 등) + else { + rowData[header] = String(value) + } + }) + + worksheet.addRow(rowData) + }) + + // 헤더 스타일링 + const headerRow = worksheet.getRow(1) + headerRow.font = { bold: true } + headerRow.fill = { + type: 'pattern', + pattern: 'solid', + fgColor: { argb: 'FFE0E0E0' } + } + headerRow.alignment = { vertical: 'middle', horizontal: 'center' } + headerRow.height = 25 + + // 헤더 테두리 + headerRow.eachCell((cell) => { + cell.border = { + top: { style: 'thin' }, + left: { style: 'thin' }, + bottom: { style: 'thin' }, + right: { style: 'thin' } + } + }) + + // 데이터 행 스타일링 + worksheet.eachRow((row, rowNumber) => { + if (rowNumber > 1) { + row.alignment = { vertical: 'middle' } + row.eachCell((cell) => { + cell.border = { + top: { style: 'thin' }, + left: { style: 'thin' }, + bottom: { style: 'thin' }, + right: { style: 'thin' } + } + }) + } + }) + + // 자동 필터 추가 + if (autoFilter) { + worksheet.autoFilter = { + from: { row: 1, column: 1 }, + to: { row: data.length + 1, column: columns.length } + } + } + + // 헤더 고정 + if (freezeHeader) { + worksheet.views = [ + { state: 'frozen', ySplit: 1 } + ] + } + + // 날짜 포맷 적용 + worksheet.eachRow((row, rowNumber) => { + if (rowNumber > 1) { + row.eachCell((cell, colNumber) => { + const header = finalHeaders[colNumber - 1] + const value = data[rowNumber - 2][header] + + if (value instanceof Date) { + cell.numFmt = dateFormat === 'yyyy-mm-dd' + ? 'yyyy-mm-dd' + : 'mm/dd/yyyy' + } + // 숫자 포맷 (천단위 구분) + else if (typeof value === 'number' && header.toLowerCase().includes('quantity')) { + cell.numFmt = '#,##0' + } + }) + } + }) + + // 파일 다운로드 + const buffer = await workbook.xlsx.writeBuffer() + const blob = new Blob([buffer], { + type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' + }) + + const url = URL.createObjectURL(blob) + const link = document.createElement('a') + const timestamp = new Date().toISOString().slice(0, 10) + const finalFilename = `${filename}_${timestamp}.xlsx` + + link.href = url + link.download = finalFilename + link.style.display = 'none' + + document.body.appendChild(link) + link.click() + document.body.removeChild(link) + + URL.revokeObjectURL(url) + + return true + } catch (error) { + console.error('Excel export error:', error) + throw new Error('Failed to export Excel file') + } +} + +/** + * Date 객체를 Excel 형식으로 포맷팅 + */ +function formatDateForExcel(date: Date, format: string): string { + const year = date.getFullYear() + const month = String(date.getMonth() + 1).padStart(2, '0') + const day = String(date.getDate()).padStart(2, '0') + + switch (format) { + case 'yyyy-mm-dd': + return `${year}-${month}-${day}` + case 'dd/mm/yyyy': + return `${day}/${month}/${year}` + case 'mm/dd/yyyy': + return `${month}/${day}/${year}` + default: + return date.toLocaleDateString() + } +} + +/** + * CSV 파일로 내보내기 (대안 옵션) + */ +export function exportDataToCSV( + data: Record[], + filename: string = 'export' +) { + try { + if (!data || data.length === 0) { + console.warn('No data to export') + return + } + + // 헤더 추출 + const headers = Object.keys(data[0]) + + // CSV 문자열 생성 + let csvContent = headers.join(',') + '\n' + + data.forEach(row => { + const values = headers.map(header => { + const value = row[header] + + // null/undefined 처리 + if (value === null || value === undefined) return '' + + // 콤마나 줄바꿈이 있으면 따옴표로 감싸기 + const stringValue = String(value) + if (stringValue.includes(',') || stringValue.includes('\n')) { + return `"${stringValue.replace(/"/g, '""')}"` + } + + return stringValue + }) + + csvContent += values.join(',') + '\n' + }) + + // BOM 추가 (Excel에서 UTF-8 인식) + const BOM = '\uFEFF' + const blob = new Blob([BOM + csvContent], { type: 'text/csv;charset=utf-8;' }) + + // 다운로드 링크 생성 + const link = document.createElement('a') + const url = URL.createObjectURL(blob) + + link.setAttribute('href', url) + link.setAttribute('download', `${filename}_${new Date().toISOString().slice(0, 10)}.csv`) + link.style.visibility = 'hidden' + + document.body.appendChild(link) + link.click() + document.body.removeChild(link) + + return true + } catch (error) { + console.error('CSV export error:', error) + throw new Error('Failed to export CSV file') + } +} + +/** + * 간단한 데이터 내보내기 헬퍼 + * Excel이 안되면 CSV로 fallback + */ +export async function exportData( + data: Record[], + options: ExportToExcelOptions & { format?: 'excel' | 'csv' } = {} +) { + const { format = 'excel', ...exportOptions } = options + + try { + if (format === 'csv') { + return exportDataToCSV(data, exportOptions.filename) + } else { + return exportDataToExcel(data, exportOptions) + } + } catch (error) { + console.error(`Failed to export as ${format}, trying CSV as fallback`) + + // Excel 실패 시 CSV로 시도 + if (format === 'excel') { + try { + return exportDataToCSV(data, exportOptions.filename) + } catch (csvError) { + console.error('Both Excel and CSV export failed') + throw csvError + } + } + + throw error + } +} \ No newline at end of file diff --git a/lib/rfq-last/attachment/vendor-response-table.tsx b/lib/rfq-last/attachment/vendor-response-table.tsx index 6e1a02c8..f9388752 100644 --- a/lib/rfq-last/attachment/vendor-response-table.tsx +++ b/lib/rfq-last/attachment/vendor-response-table.tsx @@ -17,7 +17,7 @@ import { FileCode, Building2, Calendar, - AlertCircle + AlertCircle, X } from "lucide-react"; import { format, formatDistanceToNow, isValid, isBefore, isAfter } from "date-fns"; import { ko } from "date-fns/locale"; @@ -46,6 +46,22 @@ import { cn } from "@/lib/utils"; import { getRfqVendorAttachments } from "@/lib/rfq-last/service"; import { downloadFile } from "@/lib/file-download"; import { toast } from "sonner"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog"; + // 타입 정의 interface VendorAttachment { @@ -138,24 +154,79 @@ export function VendorResponseTable({ const [isRefreshing, setIsRefreshing] = React.useState(false); const [selectedRows, setSelectedRows] = React.useState([]); - // 데이터 새로고침 - const handleRefresh = React.useCallback(async () => { - setIsRefreshing(true); + + + const [isUpdating, setIsUpdating] = React.useState(false); + const [showTypeDialog, setShowTypeDialog] = React.useState(false); + const [selectedType, setSelectedType] = React.useState<"구매" | "설계" | "">(""); + console.log(data,"data") + + const [selectedVendor, setSelectedVendor] = React.useState(null); + + const filteredData = React.useMemo(() => { + if (!selectedVendor) return data; + return data.filter(item => item.vendorName === selectedVendor); + }, [data, selectedVendor]); + + + + // 데이터 새로고침 + const handleRefresh = React.useCallback(async () => { + setIsRefreshing(true); + try { + const result = await getRfqVendorAttachments(rfqId); + if (result.vendorSuccess && result.vendorData) { + setData(result.vendorData); + toast.success("데이터를 새로고침했습니다."); + } else { + toast.error("데이터를 불러오는데 실패했습니다."); + } + } catch (error) { + console.error("Refresh error:", error); + toast.error("새로고침 중 오류가 발생했습니다."); + } finally { + setIsRefreshing(false); + } + }, [rfqId]); + + const toggleVendorFilter = (vendor: string) => { + if (selectedVendor === vendor) { + setSelectedVendor(null); // 이미 선택된 벤더를 다시 클릭하면 필터 해제 + } else { + setSelectedVendor(vendor); + // 필터 변경 시 선택 초기화 (옵션) + setSelectedRows([]); + } + }; + + // 문서 유형 일괄 변경 + const handleBulkTypeChange = React.useCallback(async () => { + if (!selectedType || selectedRows.length === 0) return; + + setIsUpdating(true); try { - const result = await getRfqVendorAttachments(rfqId); - if (result.success && result.data) { - setData(result.data); - toast.success("데이터를 새로고침했습니다."); + const ids = selectedRows.map(row => row.id); + const result = await updateAttachmentTypes(ids, selectedType as "구매" | "설계"); + + if (result.success) { + toast.success(result.message); + // 데이터 새로고침 + await handleRefresh(); + // 선택 초기화 + setSelectedRows([]); + setShowTypeDialog(false); + setSelectedType(""); } else { - toast.error("데이터를 불러오는데 실패했습니다."); + toast.error(result.message); } } catch (error) { - console.error("Refresh error:", error); - toast.error("새로고침 중 오류가 발생했습니다."); + toast.error("문서 유형 변경 중 오류가 발생했습니다."); } finally { - setIsRefreshing(false); + setIsUpdating(false); } - }, [rfqId]); + }, [selectedType, selectedRows, handleRefresh]); + + // 액션 처리 const handleAction = React.useCallback(async (action: DataTableRowAction) => { @@ -282,56 +353,56 @@ export function VendorResponseTable({ }, size: 300, }, - { - accessorKey: "description", - header: ({ column }) => , - cell: ({ row }) => ( -
- {row.original.description || "-"} -
- ), - size: 200, - }, - { - accessorKey: "validTo", - header: ({ column }) => , - cell: ({ row }) => { - const { validFrom, validTo } = row.original; - const validity = checkValidity(validTo); + // { + // accessorKey: "description", + // header: ({ column }) => , + // cell: ({ row }) => ( + //
+ // {row.original.description || "-"} + //
+ // ), + // size: 200, + // }, + // { + // accessorKey: "validTo", + // header: ({ column }) => , + // cell: ({ row }) => { + // const { validFrom, validTo } = row.original; + // const validity = checkValidity(validTo); - if (!validTo) return -; + // if (!validTo) return -; - return ( - - - -
- {validity === "expired" && ( - - )} - {validity === "expiring-soon" && ( - - )} - - {format(new Date(validTo), "yyyy-MM-dd")} - -
-
- -

유효기간: {validFrom ? format(new Date(validFrom), "yyyy-MM-dd") : "?"} ~ {format(new Date(validTo), "yyyy-MM-dd")}

- {validity === "expired" &&

만료됨

} - {validity === "expiring-soon" &&

곧 만료 예정

} -
-
-
- ); - }, - size: 120, - }, + // return ( + // + // + // + //
+ // {validity === "expired" && ( + // + // )} + // {validity === "expiring-soon" && ( + // + // )} + // + // {format(new Date(validTo), "yyyy-MM-dd")} + // + //
+ //
+ // + //

유효기간: {validFrom ? format(new Date(validFrom), "yyyy-MM-dd") : "?"} ~ {format(new Date(validTo), "yyyy-MM-dd")}

+ // {validity === "expired" &&

만료됨

} + // {validity === "expiring-soon" &&

곧 만료 예정

} + //
+ //
+ //
+ // ); + // }, + // size: 120, + // }, { accessorKey: "responseStatus", header: ({ column }) => , @@ -424,13 +495,13 @@ export function VendorResponseTable({ label: "문서 유형", type: "select", options: [ - { label: "견적서", value: "견적서" }, - { label: "기술제안서", value: "기술제안서" }, - { label: "인증서", value: "인증서" }, - { label: "카탈로그", value: "카탈로그" }, - { label: "도면", value: "도면" }, - { label: "테스트성적서", value: "테스트성적서" }, - { label: "기타", value: "기타" }, + { label: "구매", value: "구매" }, + { label: "설계", value: "설계" }, + // { label: "인증서", value: "인증서" }, + // { label: "카탈로그", value: "카탈로그" }, + // { label: "도면", value: "도면" }, + // { label: "테스트성적서", value: "테스트성적서" }, + // { label: "기타", value: "기타" }, ] }, { id: "documentNo", label: "문서번호", type: "text" }, @@ -448,23 +519,35 @@ export function VendorResponseTable({ { label: "취소", value: "취소" }, ] }, - { id: "validFrom", label: "유효시작일", type: "date" }, - { id: "validTo", label: "유효종료일", type: "date" }, + // { id: "validFrom", label: "유효시작일", type: "date" }, + // { id: "validTo", label: "유효종료일", type: "date" }, { id: "uploadedAt", label: "업로드일", type: "date" }, ]; - // 추가 액션 버튼들 + // 추가 액션 버튼들 수정 const additionalActions = React.useMemo(() => (
{selectedRows.length > 0 && ( - + <> + {/* 문서 유형 변경 버튼 */} + + + + )}
- ), [selectedRows, isRefreshing, handleBulkDownload, handleRefresh]); + ), [selectedRows, isRefreshing, handleBulkDownload, handleRefresh]) // 벤더별 그룹 카운트 const vendorCounts = React.useMemo(() => { @@ -490,18 +573,71 @@ export function VendorResponseTable({ return (
- {/* 벤더별 요약 정보 */} -
- {Array.from(vendorCounts.entries()).map(([vendor, count]) => ( - - {vendor}: {count} - - ))} + {/* 벤더 필터 섹션 */} +
+ {/* 필터 헤더 */} +
+ + 벤더별 필터 + + {selectedVendor && ( + + )} +
+ + {/* 벤더 버튼들 */} +
+ {/* 전체 보기 버튼 */} + + + {/* 각 벤더별 버튼 */} + {Array.from(vendorCounts.entries()).map(([vendor, count]) => ( + + ))} +
+ + {/* 현재 필터 상태 표시 */} + {selectedVendor && ( +
+ + + "{selectedVendor}" 벤더의 {filteredData.length}개 항목만 표시 중 + +
+ )}
{additionalActions} + + {/* 문서 유형 변경 다이얼로그 */} + + + + 문서 유형 변경 + + 선택한 {selectedRows.length}개 항목의 문서 유형을 변경합니다. + + + +
+
+ + +
+ + {/* 현재 선택된 항목들의 정보 표시 */} +
+

변경될 항목:

+
    + {selectedRows.slice(0, 5).map((row) => ( +
  • + • {row.vendorName} - {row.originalFileName} +
  • + ))} + {selectedRows.length > 5 && ( +
  • + ... 외 {selectedRows.length - 5}개 +
  • + )} +
+
+
+ + + + + +
+
); } \ No newline at end of file diff --git a/lib/rfq-last/compare-action.ts b/lib/rfq-last/compare-action.ts new file mode 100644 index 00000000..5d210631 --- /dev/null +++ b/lib/rfq-last/compare-action.ts @@ -0,0 +1,500 @@ +"use server"; + +import db from "@/db/db"; +import { eq, and, inArray } from "drizzle-orm"; +import { + rfqsLast, + rfqLastDetails, + rfqPrItems, + rfqLastVendorResponses, + rfqLastVendorQuotationItems, + vendors, + paymentTerms, + incoterms, +} from "@/db/schema"; + +export interface ComparisonData { + rfqInfo: { + id: number; + rfqCode: string; + rfqTitle: string; + rfqType: string; + projectCode?: string; + projectName?: string; + dueDate: Date | null; + packageNo?: string; + packageName?: string; + }; + vendors: VendorComparison[]; + prItems: PrItemComparison[]; + summary: { + lowestBidder: string; + highestBidder: string; + priceRange: { + min: number; + max: number; + average: number; + }; + currency: string; + }; +} + +export interface VendorComparison { + vendorId: number; + vendorName: string; + vendorCode: string; + vendorCountry?: string; + + // 응답 정보 + responseId: number; + participationStatus: string; + responseStatus: string; + submittedAt: Date | null; + + // 가격 정보 + totalAmount: number; + currency: string; + rank?: number; + priceVariance?: number; // 평균 대비 차이 % + + // 구매자 제시 조건 + buyerConditions: { + currency: string; + paymentTermsCode: string; + paymentTermsDesc?: string; + incotermsCode: string; + incotermsDesc?: string; + deliveryDate: Date | null; + contractDuration?: string; + taxCode?: string; + placeOfShipping?: string; + placeOfDestination?: string; + + // 추가 조건 + firstYn: boolean; + firstDescription?: string; + sparepartYn: boolean; + sparepartDescription?: string; + materialPriceRelatedYn: boolean; + }; + + // 벤더 제안 조건 + vendorConditions: { + currency?: string; + paymentTermsCode?: string; + paymentTermsDesc?: string; + incotermsCode?: string; + incotermsDesc?: string; + deliveryDate?: Date | null; + contractDuration?: string; + taxCode?: string; + placeOfShipping?: string; + placeOfDestination?: string; + + // 추가 조건 응답 + firstAcceptance?: "수용" | "부분수용" | "거부"; + firstDescription?: string; + sparepartAcceptance?: "수용" | "부분수용" | "거부"; + sparepartDescription?: string; + materialPriceRelatedYn?: boolean; + materialPriceRelatedReason?: string; + }; + + // 조건 차이 분석 + conditionDifferences: { + hasDifferences: boolean; + differences: string[]; + criticalDifferences: string[]; // 중요한 차이점 + }; + + // 비고 + generalRemark?: string; + technicalProposal?: string; +} + +export interface PrItemComparison { + prItemId: number; + prNo: string; + prItem: string; + materialCode: string; + materialDescription: string; + requestedQuantity: number; + uom: string; + requestedDeliveryDate: Date | null; + + vendorQuotes: { + vendorId: number; + vendorName: string; + unitPrice: number; + totalPrice: number; + currency: string; + quotedQuantity: number; + deliveryDate?: Date | null; + leadTime?: number; + manufacturer?: string; + modelNo?: string; + technicalCompliance: boolean; + alternativeProposal?: string; + itemRemark?: string; + priceRank?: number; + }[]; + + priceAnalysis: { + lowestPrice: number; + highestPrice: number; + averagePrice: number; + priceVariance: number; // 표준편차 + }; +} + +export async function getComparisonData( + rfqId: number, + vendorIds: number[] +): Promise { + try { + // 1. RFQ 기본 정보 조회 + const rfqData = await db + .select({ + id: rfqsLast.id, + rfqCode: rfqsLast.rfqCode, + rfqTitle: rfqsLast.rfqTitle, + rfqType: rfqsLast.rfqType, + // projectCode: rfqsLast.projectCode, + // projectName: rfqsLast.projectName, + dueDate: rfqsLast.dueDate, + packageNo: rfqsLast.packageNo, + packageName: rfqsLast.packageName, + }) + .from(rfqsLast) + .where(eq(rfqsLast.id, rfqId)) + .limit(1); + + if (!rfqData[0]) return null; + + // 2. 벤더별 정보 및 응답 조회 + const vendorData = await db + .select({ + // 벤더 정보 + vendorId: vendors.id, + vendorName: vendors.vendorName, + vendorCode: vendors.vendorCode, + vendorCountry: vendors.country, + + // RFQ Details (구매자 조건) + detailId: rfqLastDetails.id, + buyerCurrency: rfqLastDetails.currency, + buyerPaymentTermsCode: rfqLastDetails.paymentTermsCode, + buyerIncotermsCode: rfqLastDetails.incotermsCode, + buyerIncotermsDetail: rfqLastDetails.incotermsDetail, + buyerDeliveryDate: rfqLastDetails.deliveryDate, + buyerContractDuration: rfqLastDetails.contractDuration, + buyerTaxCode: rfqLastDetails.taxCode, + buyerPlaceOfShipping: rfqLastDetails.placeOfShipping, + buyerPlaceOfDestination: rfqLastDetails.placeOfDestination, + buyerFirstYn: rfqLastDetails.firstYn, + buyerFirstDescription: rfqLastDetails.firstDescription, + buyerSparepartYn: rfqLastDetails.sparepartYn, + buyerSparepartDescription: rfqLastDetails.sparepartDescription, + buyerMaterialPriceRelatedYn: rfqLastDetails.materialPriceRelatedYn, + + // 벤더 응답 + responseId: rfqLastVendorResponses.id, + participationStatus: rfqLastVendorResponses.participationStatus, + responseStatus: rfqLastVendorResponses.status, + submittedAt: rfqLastVendorResponses.submittedAt, + totalAmount: rfqLastVendorResponses.totalAmount, + responseCurrency: rfqLastVendorResponses.currency, + + // 벤더 제안 조건 + vendorCurrency: rfqLastVendorResponses.vendorCurrency, + vendorPaymentTermsCode: rfqLastVendorResponses.vendorPaymentTermsCode, + vendorIncotermsCode: rfqLastVendorResponses.vendorIncotermsCode, + vendorIncotermsDetail: rfqLastVendorResponses.vendorIncotermsDetail, + vendorDeliveryDate: rfqLastVendorResponses.vendorDeliveryDate, + vendorContractDuration: rfqLastVendorResponses.vendorContractDuration, + vendorTaxCode: rfqLastVendorResponses.vendorTaxCode, + vendorPlaceOfShipping: rfqLastVendorResponses.vendorPlaceOfShipping, + vendorPlaceOfDestination: rfqLastVendorResponses.vendorPlaceOfDestination, + + // 추가 조건 응답 + vendorFirstAcceptance: rfqLastVendorResponses.vendorFirstAcceptance, + vendorFirstDescription: rfqLastVendorResponses.vendorFirstDescription, + vendorSparepartAcceptance: rfqLastVendorResponses.vendorSparepartAcceptance, + vendorSparepartDescription: rfqLastVendorResponses.vendorSparepartDescription, + vendorMaterialPriceRelatedYn: rfqLastVendorResponses.vendorMaterialPriceRelatedYn, + vendorMaterialPriceRelatedReason: rfqLastVendorResponses.vendorMaterialPriceRelatedReason, + + // 비고 + generalRemark: rfqLastVendorResponses.generalRemark, + technicalProposal: rfqLastVendorResponses.technicalProposal, + }) + .from(vendors) + .innerJoin( + rfqLastDetails, + and( + eq(rfqLastDetails.vendorsId, vendors.id), + eq(rfqLastDetails.rfqsLastId, rfqId), + eq(rfqLastDetails.isLatest, true) + ) + ) + .leftJoin( + rfqLastVendorResponses, + and( + eq(rfqLastVendorResponses.vendorId, vendors.id), + eq(rfqLastVendorResponses.rfqsLastId, rfqId), + eq(rfqLastVendorResponses.isLatest, true) + ) + ) + .where(inArray(vendors.id, vendorIds)); + + // 3. Payment Terms와 Incoterms 설명 조회 + const paymentTermsData = await db + .select({ + code: paymentTerms.code, + description: paymentTerms.description, + }) + .from(paymentTerms); + + const incotermsData = await db + .select({ + code: incoterms.code, + description: incoterms.description, + }) + .from(incoterms); + + const paymentTermsMap = new Map( + paymentTermsData.map(pt => [pt.code, pt.description]) + ); + const incotermsMap = new Map( + incotermsData.map(ic => [ic.code, ic.description]) + ); + + // 4. PR Items 조회 + const prItems = await db + .select({ + id: rfqPrItems.id, + prNo: rfqPrItems.prNo, + prItem: rfqPrItems.prItem, + materialCode: rfqPrItems.materialCode, + materialDescription: rfqPrItems.materialDescription, + quantity: rfqPrItems.quantity, + uom: rfqPrItems.uom, + deliveryDate: rfqPrItems.deliveryDate, + }) + .from(rfqPrItems) + .where(eq(rfqPrItems.rfqsLastId, rfqId)); + + // 5. 벤더별 견적 아이템 조회 + const quotationItems = await db + .select({ + vendorResponseId: rfqLastVendorQuotationItems.vendorResponseId, + prItemId: rfqLastVendorQuotationItems.rfqPrItemId, + unitPrice: rfqLastVendorQuotationItems.unitPrice, + totalPrice: rfqLastVendorQuotationItems.totalPrice, + currency: rfqLastVendorQuotationItems.currency, + quantity: rfqLastVendorQuotationItems.quantity, + deliveryDate: rfqLastVendorQuotationItems.vendorDeliveryDate, + leadTime: rfqLastVendorQuotationItems.leadTime, + manufacturer: rfqLastVendorQuotationItems.manufacturer, + modelNo: rfqLastVendorQuotationItems.modelNo, + technicalCompliance: rfqLastVendorQuotationItems.technicalCompliance, + alternativeProposal: rfqLastVendorQuotationItems.alternativeProposal, + itemRemark: rfqLastVendorQuotationItems.itemRemark, + }) + .from(rfqLastVendorQuotationItems) + .where( + inArray( + rfqLastVendorQuotationItems.vendorResponseId, + vendorData.map(v => v.responseId).filter(id => id != null) + ) + ); + + // 6. 데이터 가공 및 분석 + const validAmounts = vendorData + .map(v => v.totalAmount) + .filter(a => a != null && a > 0); + + const minAmount = Math.min(...validAmounts); + const maxAmount = Math.max(...validAmounts); + const avgAmount = validAmounts.reduce((a, b) => a + b, 0) / validAmounts.length; + + // 벤더별 비교 데이터 구성 + const vendorComparisons: VendorComparison[] = vendorData.map((v, index) => { + const differences: string[] = []; + const criticalDifferences: string[] = []; + + // 조건 차이 분석 + if (v.vendorCurrency && v.vendorCurrency !== v.buyerCurrency) { + criticalDifferences.push(`통화: ${v.buyerCurrency} → ${v.vendorCurrency}`); + } + + if (v.vendorPaymentTermsCode && v.vendorPaymentTermsCode !== v.buyerPaymentTermsCode) { + differences.push(`지급조건: ${v.buyerPaymentTermsCode} → ${v.vendorPaymentTermsCode}`); + } + + if (v.vendorIncotermsCode && v.vendorIncotermsCode !== v.buyerIncotermsCode) { + differences.push(`인코텀즈: ${v.buyerIncotermsCode} → ${v.vendorIncotermsCode}`); + } + + if (v.vendorDeliveryDate && v.buyerDeliveryDate) { + const buyerDate = new Date(v.buyerDeliveryDate); + const vendorDate = new Date(v.vendorDeliveryDate); + if (vendorDate > buyerDate) { + criticalDifferences.push(`납기: ${Math.ceil((vendorDate.getTime() - buyerDate.getTime()) / (1000 * 60 * 60 * 24))}일 지연`); + } + } + + if (v.vendorFirstAcceptance === "거부" && v.buyerFirstYn) { + criticalDifferences.push("초도품 거부"); + } + + if (v.vendorSparepartAcceptance === "거부" && v.buyerSparepartYn) { + criticalDifferences.push("스페어파트 거부"); + } + + return { + vendorId: v.vendorId, + vendorName: v.vendorName, + vendorCode: v.vendorCode, + vendorCountry: v.vendorCountry, + + responseId: v.responseId || 0, + participationStatus: v.participationStatus || "미응답", + responseStatus: v.responseStatus || "대기중", + submittedAt: v.submittedAt, + + totalAmount: v.totalAmount || 0, + currency: v.responseCurrency || v.buyerCurrency || "USD", + rank: 0, // 나중에 계산 + priceVariance: v.totalAmount ? ((v.totalAmount - avgAmount) / avgAmount) * 100 : 0, + + buyerConditions: { + currency: v.buyerCurrency || "USD", + paymentTermsCode: v.buyerPaymentTermsCode || "", + paymentTermsDesc: paymentTermsMap.get(v.buyerPaymentTermsCode || ""), + incotermsCode: v.buyerIncotermsCode || "", + incotermsDesc: incotermsMap.get(v.buyerIncotermsCode || ""), + deliveryDate: v.buyerDeliveryDate, + contractDuration: v.buyerContractDuration, + taxCode: v.buyerTaxCode, + placeOfShipping: v.buyerPlaceOfShipping, + placeOfDestination: v.buyerPlaceOfDestination, + firstYn: v.buyerFirstYn || false, + firstDescription: v.buyerFirstDescription, + sparepartYn: v.buyerSparepartYn || false, + sparepartDescription: v.buyerSparepartDescription, + materialPriceRelatedYn: v.buyerMaterialPriceRelatedYn || false, + }, + + vendorConditions: { + currency: v.vendorCurrency, + paymentTermsCode: v.vendorPaymentTermsCode, + paymentTermsDesc: paymentTermsMap.get(v.vendorPaymentTermsCode || ""), + incotermsCode: v.vendorIncotermsCode, + incotermsDesc: incotermsMap.get(v.vendorIncotermsCode || ""), + deliveryDate: v.vendorDeliveryDate, + contractDuration: v.vendorContractDuration, + taxCode: v.vendorTaxCode, + placeOfShipping: v.vendorPlaceOfShipping, + placeOfDestination: v.vendorPlaceOfDestination, + firstAcceptance: v.vendorFirstAcceptance, + firstDescription: v.vendorFirstDescription, + sparepartAcceptance: v.vendorSparepartAcceptance, + sparepartDescription: v.vendorSparepartDescription, + materialPriceRelatedYn: v.vendorMaterialPriceRelatedYn, + materialPriceRelatedReason: v.vendorMaterialPriceRelatedReason, + }, + + conditionDifferences: { + hasDifferences: differences.length > 0 || criticalDifferences.length > 0, + differences, + criticalDifferences, + }, + + generalRemark: v.generalRemark, + technicalProposal: v.technicalProposal, + }; + }); + + // 가격 순위 계산 + vendorComparisons.sort((a, b) => a.totalAmount - b.totalAmount); + vendorComparisons.forEach((v, index) => { + v.rank = index + 1; + }); + + // PR 아이템별 비교 데이터 구성 + const prItemComparisons: PrItemComparison[] = prItems.map(item => { + const itemQuotes = quotationItems + .filter(q => q.prItemId === item.id) + .map(q => { + const vendor = vendorData.find(v => v.responseId === q.vendorResponseId); + return { + vendorId: vendor?.vendorId || 0, + vendorName: vendor?.vendorName || "", + unitPrice: q.unitPrice || 0, + totalPrice: q.totalPrice || 0, + currency: q.currency || "USD", + quotedQuantity: q.quantity || 0, + deliveryDate: q.deliveryDate, + leadTime: q.leadTime, + manufacturer: q.manufacturer, + modelNo: q.modelNo, + technicalCompliance: q.technicalCompliance || true, + alternativeProposal: q.alternativeProposal, + itemRemark: q.itemRemark, + priceRank: 0, + }; + }); + + // 아이템별 가격 순위 + itemQuotes.sort((a, b) => a.unitPrice - b.unitPrice); + itemQuotes.forEach((q, index) => { + q.priceRank = index + 1; + }); + + const unitPrices = itemQuotes.map(q => q.unitPrice); + const avgPrice = unitPrices.reduce((a, b) => a + b, 0) / unitPrices.length || 0; + const variance = Math.sqrt( + unitPrices.reduce((sum, price) => sum + Math.pow(price - avgPrice, 2), 0) / unitPrices.length + ); + + return { + prItemId: item.id, + prNo: item.prNo || "", + prItem: item.prItem || "", + materialCode: item.materialCode || "", + materialDescription: item.materialDescription || "", + requestedQuantity: item.quantity || 0, + uom: item.uom || "", + requestedDeliveryDate: item.deliveryDate, + vendorQuotes: itemQuotes, + priceAnalysis: { + lowestPrice: Math.min(...unitPrices) || 0, + highestPrice: Math.max(...unitPrices) || 0, + averagePrice: avgPrice, + priceVariance: variance, + }, + }; + }); + + // 최종 데이터 구성 + return { + rfqInfo: rfqData[0], + vendors: vendorComparisons, + prItems: prItemComparisons, + summary: { + lowestBidder: vendorComparisons[0]?.vendorName || "", + highestBidder: vendorComparisons[vendorComparisons.length - 1]?.vendorName || "", + priceRange: { + min: minAmount, + max: maxAmount, + average: avgAmount, + }, + currency: vendorComparisons[0]?.currency || "USD", + }, + }; + } catch (error) { + console.error("견적 비교 데이터 조회 실패:", error); + return null; + } +} \ No newline at end of file diff --git a/lib/rfq-last/quotation-compare-view.tsx b/lib/rfq-last/quotation-compare-view.tsx new file mode 100644 index 00000000..0e15a7bf --- /dev/null +++ b/lib/rfq-last/quotation-compare-view.tsx @@ -0,0 +1,755 @@ +"use client"; + +import * as React from "react"; +import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; +import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { + Trophy, + TrendingUp, + TrendingDown, + AlertCircle, + CheckCircle, + XCircle, + ChevronDown, + ChevronUp, + Info, + DollarSign, + Calendar, + Package, + Globe, + FileText, + Truck, + AlertTriangle, +} from "lucide-react"; +import { cn } from "@/lib/utils"; +import { format } from "date-fns"; +import { ko } from "date-fns/locale"; +import { + Tooltip, + TooltipContent, + TooltipProvider, + TooltipTrigger, +} from "@/components/ui/tooltip"; +import { + Collapsible, + CollapsibleContent, + CollapsibleTrigger, +} from "@/components/ui/collapsible"; +import type { ComparisonData, VendorComparison, PrItemComparison } from "../actions"; + +interface QuotationCompareViewProps { + data: ComparisonData; +} + +export function QuotationCompareView({ data }: QuotationCompareViewProps) { + const [expandedItems, setExpandedItems] = React.useState>(new Set()); + const [selectedMetric, setSelectedMetric] = React.useState<"price" | "delivery" | "compliance">("price"); + + // 아이템 확장/축소 토글 + const toggleItemExpansion = (itemId: number) => { + setExpandedItems((prev) => { + const newSet = new Set(prev); + if (newSet.has(itemId)) { + newSet.delete(itemId); + } else { + newSet.add(itemId); + } + return newSet; + }); + }; + + // 순위에 따른 색상 + const getRankColor = (rank: number) => { + switch (rank) { + case 1: + return "text-green-600 bg-green-50"; + case 2: + return "text-blue-600 bg-blue-50"; + case 3: + return "text-orange-600 bg-orange-50"; + default: + return "text-gray-600 bg-gray-50"; + } + }; + + // 가격 차이 색상 + const getVarianceColor = (variance: number) => { + if (variance < -5) return "text-green-600"; + if (variance > 5) return "text-red-600"; + return "text-gray-600"; + }; + + // 조건 일치 여부 아이콘 + const getComplianceIcon = (matches: boolean) => { + return matches ? ( + + ) : ( + + ); + }; + + // 금액 포맷 + const formatAmount = (amount: number, currency: string = "USD") => { + return new Intl.NumberFormat("ko-KR", { + style: "currency", + currency: currency, + minimumFractionDigits: 0, + maximumFractionDigits: 2, + }).format(amount); + }; + + return ( +
+ {/* 요약 카드 */} +
+ {/* 최저가 벤더 */} + + + + + 최저가 벤더 + + + +

{data.summary.lowestBidder}

+

+ {formatAmount(data.summary.priceRange.min, data.summary.currency)} +

+
+
+ + {/* 평균 가격 */} + + + + + 평균 가격 + + + +

+ {formatAmount(data.summary.priceRange.average, data.summary.currency)} +

+

+ {data.vendors.length}개 업체 평균 +

+
+
+ + {/* 가격 범위 */} + + + + + 가격 범위 + + + +

+ {((data.summary.priceRange.max - data.summary.priceRange.min) / data.summary.priceRange.min * 100).toFixed(1)}% +

+

+ 최저가 대비 최고가 차이 +

+
+
+ + {/* 조건 불일치 */} + + + + + 조건 불일치 + + + +

+ {data.vendors.filter(v => v.conditionDifferences.hasDifferences).length}개 +

+

+ 제시 조건과 차이 있음 +

+
+
+
+ + {/* 탭 뷰 */} + + + 종합 비교 + 조건 비교 + 아이템별 비교 + 상세 분석 + + + {/* 종합 비교 */} + + + + 가격 순위 + + +
+ {data.vendors.map((vendor) => ( +
+
+
+ {vendor.rank} +
+
+

{vendor.vendorName}

+

+ {vendor.vendorCode} • {vendor.vendorCountry} +

+
+
+ +
+ {/* 조건 차이 표시 */} + {vendor.conditionDifferences.criticalDifferences.length > 0 && ( + + + + + + 중요 차이 {vendor.conditionDifferences.criticalDifferences.length} + + + +
+ {vendor.conditionDifferences.criticalDifferences.map((diff, idx) => ( +

{diff}

+ ))} +
+
+
+
+ )} + + {/* 가격 정보 */} +
+

+ {formatAmount(vendor.totalAmount, vendor.currency)} +

+

+ {vendor.priceVariance && vendor.priceVariance > 0 ? "+" : ""} + {vendor.priceVariance?.toFixed(1)}% vs 평균 +

+
+
+
+ ))} +
+
+
+
+ + {/* 조건 비교 */} + + + + 거래 조건 비교 + + + + + + + + {data.vendors.map((vendor) => ( + + ))} + + + + {/* 통화 */} + + + + {data.vendors.map((vendor) => ( + + ))} + + + {/* 지급조건 */} + + + + {data.vendors.map((vendor) => ( + + ))} + + + {/* 인코텀즈 */} + + + + {data.vendors.map((vendor) => ( + + ))} + + + {/* 납기 */} + + + + {data.vendors.map((vendor) => { + const vendorDate = vendor.vendorConditions.deliveryDate || vendor.buyerConditions.deliveryDate; + const isDelayed = vendorDate && vendor.buyerConditions.deliveryDate && + new Date(vendorDate) > new Date(vendor.buyerConditions.deliveryDate); + + return ( + + ); + })} + + + {/* 초도품 */} + + + + {data.vendors.map((vendor) => ( + + ))} + + + {/* 스페어파트 */} + + + + {data.vendors.map((vendor) => ( + + ))} + + + {/* 연동제 */} + + + + {data.vendors.map((vendor) => ( + + ))} + + +
항목구매자 제시 + {vendor.vendorName} +
통화{data.vendors[0]?.buyerConditions.currency} +
+ {vendor.vendorConditions.currency || vendor.buyerConditions.currency} + {vendor.vendorConditions.currency !== vendor.buyerConditions.currency && ( + 변경 + )} +
+
지급조건 + + + + {data.vendors[0]?.buyerConditions.paymentTermsCode} + + + {data.vendors[0]?.buyerConditions.paymentTermsDesc} + + + + +
+ + + + {vendor.vendorConditions.paymentTermsCode || vendor.buyerConditions.paymentTermsCode} + + + {vendor.vendorConditions.paymentTermsDesc || vendor.buyerConditions.paymentTermsDesc} + + + + {vendor.vendorConditions.paymentTermsCode && + vendor.vendorConditions.paymentTermsCode !== vendor.buyerConditions.paymentTermsCode && ( + 변경 + )} +
+
인코텀즈{data.vendors[0]?.buyerConditions.incotermsCode} +
+ {vendor.vendorConditions.incotermsCode || vendor.buyerConditions.incotermsCode} + {vendor.vendorConditions.incotermsCode !== vendor.buyerConditions.incotermsCode && ( + 변경 + )} +
+
납기 + {data.vendors[0]?.buyerConditions.deliveryDate + ? format(new Date(data.vendors[0].buyerConditions.deliveryDate), "yyyy-MM-dd") + : "-"} + +
+ {vendorDate ? format(new Date(vendorDate), "yyyy-MM-dd") : "-"} + {isDelayed && ( + 지연 + )} +
+
초도품 + {data.vendors[0]?.buyerConditions.firstYn ? "요구" : "해당없음"} + + {vendor.buyerConditions.firstYn && ( + + {vendor.vendorConditions.firstAcceptance || "미응답"} + + )} + {!vendor.buyerConditions.firstYn && "-"} +
스페어파트 + {data.vendors[0]?.buyerConditions.sparepartYn ? "요구" : "해당없음"} + + {vendor.buyerConditions.sparepartYn && ( + + {vendor.vendorConditions.sparepartAcceptance || "미응답"} + + )} + {!vendor.buyerConditions.sparepartYn && "-"} +
연동제 + {data.vendors[0]?.buyerConditions.materialPriceRelatedYn ? "적용" : "미적용"} + +
+ {vendor.vendorConditions.materialPriceRelatedYn !== undefined + ? vendor.vendorConditions.materialPriceRelatedYn ? "적용" : "미적용" + : vendor.buyerConditions.materialPriceRelatedYn ? "적용" : "미적용"} + {vendor.vendorConditions.materialPriceRelatedReason && ( + + + + + + +

+ {vendor.vendorConditions.materialPriceRelatedReason} +

+
+
+
+ )} +
+
+
+
+
+ + {/* 아이템별 비교 */} + + + + PR 아이템별 가격 비교 + + +
+ {data.prItems.map((item) => ( + toggleItemExpansion(item.prItemId)} + > +
+ +
+
+
+ {expandedItems.has(item.prItemId) ? ( + + ) : ( + + )} + +
+
+

{item.materialDescription}

+

+ {item.materialCode} • {item.prNo} • {item.requestedQuantity} {item.uom} +

+
+
+
+

단가 범위

+

+ {formatAmount(item.priceAnalysis.lowestPrice)} ~ {formatAmount(item.priceAnalysis.highestPrice)} +

+
+
+
+ + +
+ + + + + + + + + + + + + + {item.vendorQuotes.map((quote) => ( + + + + + + + + + + ))} + +
벤더단가총액수량납기제조사순위
{quote.vendorName} + {formatAmount(quote.unitPrice, quote.currency)} + + {formatAmount(quote.totalPrice, quote.currency)} + {quote.quotedQuantity} + {quote.deliveryDate + ? format(new Date(quote.deliveryDate), "yyyy-MM-dd") + : quote.leadTime + ? `${quote.leadTime}일` + : "-"} + + {quote.manufacturer && ( +
+

{quote.manufacturer}

+ {quote.modelNo && ( +

{quote.modelNo}

+ )} +
+ )} +
+ + #{quote.priceRank} + +
+ + {/* 가격 분석 요약 */} +
+
+
+

평균 단가

+

+ {formatAmount(item.priceAnalysis.averagePrice)} +

+
+
+

가격 편차

+

+ ±{formatAmount(item.priceAnalysis.priceVariance)} +

+
+
+

최저가 업체

+

+ {item.vendorQuotes.find(q => q.priceRank === 1)?.vendorName} +

+
+
+

가격 차이

+

+ {((item.priceAnalysis.highestPrice - item.priceAnalysis.lowestPrice) / + item.priceAnalysis.lowestPrice * 100).toFixed(1)}% +

+
+
+
+
+
+
+
+ ))} +
+
+
+
+ + {/* 상세 분석 */} + +
+ {/* 위험 요소 분석 */} + + + + + 위험 요소 분석 + + + +
+ {data.vendors.map((vendor) => { + if (!vendor.conditionDifferences.hasDifferences) return null; + + return ( +
+

{vendor.vendorName}

+ {vendor.conditionDifferences.criticalDifferences.length > 0 && ( +
+

중요 차이점:

+ {vendor.conditionDifferences.criticalDifferences.map((diff, idx) => ( +

• {diff}

+ ))} +
+ )} + {vendor.conditionDifferences.differences.length > 0 && ( +
+

일반 차이점:

+ {vendor.conditionDifferences.differences.map((diff, idx) => ( +

• {diff}

+ ))} +
+ )} +
+ ); + })} +
+
+
+ + {/* 추천 사항 */} + + + + + 선정 추천 + + + +
+ {/* 가격 기준 추천 */} +
+

가격 우선 선정

+

+ {data.vendors[0]?.vendorName} - {formatAmount(data.vendors[0]?.totalAmount || 0)} +

+ {data.vendors[0]?.conditionDifferences.hasDifferences && ( +

+ ⚠️ 조건 차이 검토 필요 +

+ )} +
+ + {/* 조건 준수 기준 추천 */} +
+

조건 준수 우선 선정

+ {(() => { + const compliantVendor = data.vendors.find(v => !v.conditionDifferences.hasDifferences); + if (compliantVendor) { + return ( +
+

+ {compliantVendor.vendorName} - {formatAmount(compliantVendor.totalAmount)} +

+

+ 모든 조건 충족 (가격 순위: #{compliantVendor.rank}) +

+
+ ); + } + return ( +

+ 모든 조건을 충족하는 벤더 없음 +

+ ); + })()} +
+ + {/* 균형 추천 */} +
+

균형 선정 (추천)

+ {(() => { + // 가격 순위와 조건 차이를 고려한 점수 계산 + const scoredVendors = data.vendors.map(v => ({ + ...v, + score: (v.rank || 10) + v.conditionDifferences.criticalDifferences.length * 3 + + v.conditionDifferences.differences.length + })); + scoredVendors.sort((a, b) => a.score - b.score); + const recommended = scoredVendors[0]; + + return ( +
+

+ {recommended.vendorName} - {formatAmount(recommended.totalAmount)} +

+

+ 가격 순위 #{recommended.rank}, 조건 차이 최소화 +

+
+ ); + })()} +
+
+
+
+
+ + {/* 벤더별 비고사항 */} + {data.vendors.some(v => v.generalRemark || v.technicalProposal) && ( + + + 벤더 제안사항 및 비고 + + +
+ {data.vendors.map((vendor) => { + if (!vendor.generalRemark && !vendor.technicalProposal) return null; + + return ( +
+

{vendor.vendorName}

+ {vendor.generalRemark && ( +
+

일반 비고:

+

{vendor.generalRemark}

+
+ )} + {vendor.technicalProposal && ( +
+

기술 제안:

+

{vendor.technicalProposal}

+
+ )} +
+ ); + })} +
+
+
+ )} +
+
+
+ ); +} \ No newline at end of file diff --git a/lib/rfq-last/service.ts b/lib/rfq-last/service.ts index 9943c02d..02429b6a 100644 --- a/lib/rfq-last/service.ts +++ b/lib/rfq-last/service.ts @@ -2847,7 +2847,7 @@ export async function sendRfqToVendors({ const picInfo = await getPicInfo(rfqData.picId, rfqData.picName); // 3. 프로젝트 정보 조회 - const projectInfo = rfqData.projectId + const projectInfo = rfqData.projectId ? await getProjectInfo(rfqData.projectId) : null; @@ -2856,7 +2856,7 @@ export async function sendRfqToVendors({ const designAttachments = await getDesignAttachments(rfqId); // 5. 벤더별 처리 - const { results, errors, savedContracts, tbeSessionsCreated } = + const { results, errors, savedContracts, tbeSessionsCreated } = await processVendors({ rfqId, rfqData, @@ -2979,17 +2979,26 @@ async function prepareEmailAttachments(rfqId: number, attachmentIds: number[]) { ); const emailAttachments = []; - + for (const { attachment, revision } of attachments) { if (revision?.filePath) { try { - const fullPath = path.join( - process.cwd(), - `${process.env.NAS_PATH}`, + + const isProduction = process.env.NODE_ENV === "production"; + + const fullPath = isProduction + + path.join( + process.cwd(), + `public`, + revision.filePath + ) + : path.join( + `${process.env.NAS_PATH}`, revision.filePath ); const fileBuffer = await fs.readFile(fullPath); - + emailAttachments.push({ filename: revision.originalFileName, content: fileBuffer, @@ -3052,9 +3061,9 @@ async function processVendors({ // PDF 저장 디렉토리 준비 const contractsDir = path.join( - process.cwd(), - `${process.env.NAS_PATH}`, - "contracts", + process.cwd(), + `${process.env.NAS_PATH}`, + "contracts", "generated" ); await mkdir(contractsDir, { recursive: true }); @@ -3077,18 +3086,18 @@ async function processVendors({ }); results.push(vendorResult.result); - + if (vendorResult.contracts) { savedContracts.push(...vendorResult.contracts); } - + if (vendorResult.tbeSession) { tbeSessionsCreated.push(vendorResult.tbeSession); } } catch (error) { console.error(`벤더 ${vendor.vendorName} 처리 실패:`, error); - + errors.push({ vendorId: vendor.vendorId, vendorName: vendor.vendorName, @@ -3182,7 +3191,7 @@ function prepareEmailRecipients(vendor: any, picEmail: string) { vendor.customEmails?.forEach((custom: any) => { if (custom.email !== vendor.selectedMainEmail && - !vendor.additionalEmails.includes(custom.email)) { + !vendor.additionalEmails.includes(custom.email)) { ccEmails.push(custom.email); } }); @@ -3235,14 +3244,14 @@ async function handleRfqDetail({ ); // 새 detail 생성 - const { - id, - updatedBy, - updatedAt, - isLatest, - sendVersion: oldSendVersion, - emailResentCount, - ...restRfqDetail + const { + id, + updatedBy, + updatedAt, + isLatest, + sendVersion: oldSendVersion, + emailResentCount, + ...restRfqDetail } = rfqDetail; const [newRfqDetail] = await tx @@ -3265,7 +3274,7 @@ async function handleRfqDetail({ }) .returning(); - await tx + await tx .update(basicContract) .set({ rfqCompanyId: newRfqDetail.id, @@ -3273,7 +3282,7 @@ async function handleRfqDetail({ .where( and( eq(basicContract.rfqCompanyId, rfqDetail.id), - eq(rfqLastDetails.vendorsId, vendor.vendorId), + eq(basicContract.vendorId, vendor.vendorId), ) ); @@ -3382,7 +3391,7 @@ async function createOrUpdateContract({ }) .where(eq(basicContract.id, existingContract.id)) .returning(); - + return { ...updated, isUpdated: true }; } else { // 새로 생성 @@ -3401,7 +3410,7 @@ async function createOrUpdateContract({ updatedAt: new Date() }) .returning(); - + return { ...created, isUpdated: false }; } } @@ -3503,11 +3512,11 @@ async function handleTbeSession({ sessionType: "initial", status: "준비중", evaluationResult: null, - plannedStartDate: rfqData.dueDate - ? addDays(new Date(rfqData.dueDate), 1) + plannedStartDate: rfqData.dueDate + ? addDays(new Date(rfqData.dueDate), 1) : addDays(new Date(), 14), - plannedEndDate: rfqData.dueDate - ? addDays(new Date(rfqData.dueDate), 7) + plannedEndDate: rfqData.dueDate + ? addDays(new Date(rfqData.dueDate), 7) : addDays(new Date(), 21), leadEvaluatorId: rfqData.picId, createdBy: Number(currentUser.id), @@ -3536,11 +3545,11 @@ async function handleTbeSession({ async function generateTbeSessionCode(tx: any) { const year = new Date().getFullYear(); const pattern = `TBE-${year}-%`; - + const [lastTbeSession] = await tx .select({ sessionCode: rfqLastTbeSessions.sessionCode }) .from(rfqLastTbeSessions) - .where(like(rfqLastTbeSessions.sessionCode,pattern )) + .where(like(rfqLastTbeSessions.sessionCode, pattern)) .orderBy(sql`${rfqLastTbeSessions.sessionCode} DESC`) .limit(1); @@ -3624,7 +3633,7 @@ async function updateRfqStatus(rfqId: number, userId: number) { updatedAt: new Date() }) .where(eq(rfqsLast.id, rfqId)); - } +} export async function updateRfqDueDate( rfqId: number, @@ -4006,4 +4015,305 @@ function getTemplateNameByType( case "기술자료": return "기술"; default: return contractType; } +} + + +export async function updateAttachmentTypes( + attachmentIds: number[], + attachmentType: "구매" | "설계" +) { + try { + // 권한 체크 등 필요시 추가 + + await db + .update(rfqLastVendorAttachments) + .set({ attachmentType }) + .where(inArray(rfqLastVendorAttachments.id, attachmentIds)); + + // 페이지 리밸리데이션 + // revalidatePath("/rfq"); + + return { success: true, message: `${attachmentIds.length}개 항목이 "${attachmentType}"로 변경되었습니다.` }; + } catch (error) { + console.error("Failed to update attachment types:", error); + return { success: false, message: "문서 유형 변경에 실패했습니다." }; + } +} + +// 단일 RFQ 밀봉 토글 +export async function toggleRfqSealed(rfqId: number) { + try { + const session = await getServerSession(authOptions) + + if (!session?.user) { + throw new Error("인증이 필요합니다.") + } + // 현재 상태 조회 + const [currentRfq] = await db + .select({ rfqSealedYn: rfqsLast.rfqSealedYn }) + .from(rfqsLast) + .where(eq(rfqsLast.id, rfqId)); + + if (!currentRfq) { + throw new Error("RFQ를 찾을 수 없습니다."); + } + + // 상태 토글 + const [updated] = await db + .update(rfqsLast) + .set({ + rfqSealedYn: !currentRfq.rfqSealedYn, + updatedBy: Number(session.user.id), + updatedAt: new Date(), + }) + .where(eq(rfqsLast.id, rfqId)) + .returning(); + + revalidatePath("/evcp/rfq-last"); + + return { + success: true, + data: updated, + message: updated.rfqSealedYn ? "견적이 밀봉되었습니다." : "견적 밀봉이 해제되었습니다.", + }; + } catch (error) { + console.error("RFQ 밀봉 상태 변경 실패:", error); + return { + success: false, + error: error instanceof Error ? error.message : "알 수 없는 오류가 발생했습니다.", + }; + } +} + +// 여러 RFQ 일괄 밀봉 +export async function sealMultipleRfqs(rfqIds: number[]) { + try { + const session = await getServerSession(authOptions) + + if (!session?.user) { + throw new Error("인증이 필요합니다.") + } + + if (!rfqIds || rfqIds.length === 0) { + throw new Error("선택된 RFQ가 없습니다."); + } + + const updated = await db + .update(rfqsLast) + .set({ + rfqSealedYn: true, + updatedBy: Number(session.user.id), + updatedAt: new Date(), + }) + .where(inArray(rfqsLast.id, rfqIds)) + .returning(); + + revalidatePath("/evcp/rfq-last"); + + return { + success: true, + count: updated.length, + message: `${updated.length}건의 견적이 밀봉되었습니다.`, + }; + } catch (error) { + console.error("RFQ 일괄 밀봉 실패:", error); + return { + success: false, + error: error instanceof Error ? error.message : "알 수 없는 오류가 발생했습니다.", + }; + } +} + +// 여러 RFQ 일괄 밀봉 해제 +export async function unsealMultipleRfqs(rfqIds: number[]) { + try { + const session = await getServerSession(authOptions) + + if (!session?.user) { + throw new Error("인증이 필요합니다.") + } + if (!rfqIds || rfqIds.length === 0) { + throw new Error("선택된 RFQ가 없습니다."); + } + + const updated = await db + .update(rfqsLast) + .set({ + rfqSealedYn: false, + updatedBy: Number(session.user.id), + updatedAt: new Date(), + }) + .where(inArray(rfqsLast.id, rfqIds)) + .returning(); + + revalidatePath("/evcp/rfq-last"); + + return { + success: true, + count: updated.length, + message: `${updated.length}건의 견적 밀봉이 해제되었습니다.`, + }; + } catch (error) { + console.error("RFQ 밀봉 해제 실패:", error); + return { + success: false, + error: error instanceof Error ? error.message : "알 수 없는 오류가 발생했습니다.", + }; + } +} + +// 단일 RFQ 밀봉 (밀봉만) +export async function sealRfq(rfqId: number) { + try { + const session = await getServerSession(authOptions) + + if (!session?.user) { + throw new Error("인증이 필요합니다.") + } + + const [updated] = await db + .update(rfqsLast) + .set({ + rfqSealedYn: true, + updatedBy: Number(session.user.id), + updatedAt: new Date(), + }) + .where(eq(rfqsLast.id, rfqId)) + .returning(); + + if (!updated) { + throw new Error("RFQ를 찾을 수 없습니다."); + } + + revalidatePath("/evcp/rfq-last"); + + return { + success: true, + data: updated, + message: "견적이 밀봉되었습니다.", + }; + } catch (error) { + console.error("RFQ 밀봉 실패:", error); + return { + success: false, + error: error instanceof Error ? error.message : "알 수 없는 오류가 발생했습니다.", + }; + } +} + +// 단일 RFQ 밀봉 해제 +export async function unsealRfq(rfqId: number) { + try { + const session = await getServerSession(authOptions) + + if (!session?.user) { + throw new Error("인증이 필요합니다.") + } + + const [updated] = await db + .update(rfqsLast) + .set({ + rfqSealedYn: false, + updatedBy: Number(session.user.id), + updatedAt: new Date(), + }) + .where(eq(rfqsLast.id, rfqId)) + .returning(); + + if (!updated) { + throw new Error("RFQ를 찾을 수 없습니다."); + } + + revalidatePath("/evcp/rfq-last"); + + return { + success: true, + data: updated, + message: "견적 밀봉이 해제되었습니다.", + }; + } catch (error) { + console.error("RFQ 밀봉 해제 실패:", error); + return { + success: false, + error: error instanceof Error ? error.message : "알 수 없는 오류가 발생했습니다.", + }; + } +} + + + +export async function updateShortList( + rfqId: number, + vendorIds: number[], + shortListStatus: boolean = true +) { + try { + // 권한 체크 등 필요한 검증 + const session = await getServerSession(authOptions) + + if (!session?.user) { + throw new Error("인증이 필요합니다.") + } + + // 트랜잭션으로 처리 + const result = await db.transaction(async (tx) => { + // 해당 RFQ의 모든 벤더들의 shortList를 먼저 false로 설정 (선택적) + // 만약 선택된 것만 true로 하고 나머지는 그대로 두려면 이 부분 제거 + await tx + .update(rfqLastDetails) + .set({ + shortList: false, + updatedBy: session.user.id, + updatedAt: new Date() + }) + .where( + and( + eq(rfqLastDetails.rfqsLastId, rfqId), + eq(rfqLastDetails.isLatest, true) + ) + ); + + // 선택된 벤더들의 shortList를 true로 설정 + if (vendorIds.length > 0) { + const updates = await Promise.all( + vendorIds.map(vendorId => + tx + .update(rfqLastDetails) + .set({ + shortList: shortListStatus, + updatedBy: session.user.id, + updatedAt: new Date() + }) + .where( + and( + eq(rfqLastDetails.rfqsLastId, rfqId), + eq(rfqLastDetails.vendorsId, vendorId), + eq(rfqLastDetails.isLatest, true) + ) + ) + .returning() + ) + ); + + return { + success: true, + updatedCount: updates.length, + vendorIds + }; + } + + return { + success: true, + updatedCount: 0, + vendorIds: [] + }; + }); + + // revalidatePath(`/buyer/rfq/${rfqId}`); + return result; + + } catch (error) { + console.error("Short List 업데이트 실패:", error); + throw new Error("Short List 업데이트에 실패했습니다."); + } } \ No newline at end of file diff --git a/lib/rfq-last/table/rfq-seal-toggle-cell.tsx b/lib/rfq-last/table/rfq-seal-toggle-cell.tsx new file mode 100644 index 00000000..99360978 --- /dev/null +++ b/lib/rfq-last/table/rfq-seal-toggle-cell.tsx @@ -0,0 +1,93 @@ + +"use client"; + +import * as React from "react"; +import { Lock, LockOpen } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { + Tooltip, + TooltipContent, + TooltipProvider, + TooltipTrigger, +} from "@/components/ui/tooltip"; +import { toast } from "sonner"; +import { toggleRfqSealed } from "../service"; + +interface RfqSealToggleCellProps { + rfqId: number; + isSealed: boolean; + onUpdate?: () => void; +} + +export function RfqSealToggleCell({ + rfqId, + isSealed, + onUpdate +}: RfqSealToggleCellProps) { + const [isLoading, setIsLoading] = React.useState(false); + const [currentSealed, setCurrentSealed] = React.useState(isSealed); + + const handleToggle = async (e: React.MouseEvent) => { + e.stopPropagation(); // 행 선택 방지 + + setIsLoading(true); + try { + const result = await toggleRfqSealed(rfqId); + + if (result.success) { + setCurrentSealed(result.data?.rfqSealedYn ?? !currentSealed); + toast.success(result.message); + onUpdate?.(); // 테이블 데이터 새로고침 + } else { + toast.error(result.error); + } + } catch (error) { + toast.error("밀봉 상태 변경 중 오류가 발생했습니다."); + } finally { + setIsLoading(false); + } + }; + + return ( + + + + + + +

{currentSealed ? "밀봉 해제하기" : "밀봉하기"}

+
+
+
+ ); +} + +export const sealColumn = { + accessorKey: "rfqSealedYn", + header: ({ column }) => , + cell: ({ row, table }) => ( + { + // 테이블 데이터를 새로고침하는 로직 + // 이 부분은 상위 컴포넌트에서 refreshData 함수를 prop으로 전달받아 사용 + const meta = table.options.meta as any; + meta?.refreshData?.(); + }} + /> + ), + size: 80, + }; \ No newline at end of file diff --git a/lib/rfq-last/table/rfq-table-columns.tsx b/lib/rfq-last/table/rfq-table-columns.tsx index 5f5efcb4..eaf00660 100644 --- a/lib/rfq-last/table/rfq-table-columns.tsx +++ b/lib/rfq-last/table/rfq-table-columns.tsx @@ -18,6 +18,7 @@ import { DataTableRowAction } from "@/types/table"; import { format, differenceInDays } from "date-fns"; import { ko } from "date-fns/locale"; import { useRouter } from "next/navigation"; +import { RfqSealToggleCell } from "./rfq-seal-toggle-cell"; type NextRouter = ReturnType; @@ -120,18 +121,18 @@ export function getRfqColumns({ { accessorKey: "rfqSealedYn", header: ({ column }) => , - cell: ({ row }) => { - const isSealed = row.original.rfqSealedYn; - return ( -
- {isSealed ? ( - - ) : ( - - )} -
- ); - }, + cell: ({ row, table }) => ( + { + // 테이블 데이터를 새로고침하는 로직 + // 이 부분은 상위 컴포넌트에서 refreshData 함수를 prop으로 전달받아 사용 + const meta = table.options.meta as any; + meta?.refreshData?.(); + }} + /> + ), size: 80, }, @@ -453,18 +454,18 @@ export function getRfqColumns({ { accessorKey: "rfqSealedYn", header: ({ column }) => , - cell: ({ row }) => { - const isSealed = row.original.rfqSealedYn; - return ( -
- {isSealed ? ( - - ) : ( - - )} -
- ); - }, + cell: ({ row, table }) => ( + { + // 테이블 데이터를 새로고침하는 로직 + // 이 부분은 상위 컴포넌트에서 refreshData 함수를 prop으로 전달받아 사용 + const meta = table.options.meta as any; + meta?.refreshData?.(); + }} + /> + ), size: 80, }, @@ -815,18 +816,18 @@ export function getRfqColumns({ { accessorKey: "rfqSealedYn", header: ({ column }) => , - cell: ({ row }) => { - const isSealed = row.original.rfqSealedYn; - return ( -
- {isSealed ? ( - - ) : ( - - )} -
- ); - }, + cell: ({ row, table }) => ( + { + // 테이블 데이터를 새로고침하는 로직 + // 이 부분은 상위 컴포넌트에서 refreshData 함수를 prop으로 전달받아 사용 + const meta = table.options.meta as any; + meta?.refreshData?.(); + }} + /> + ), size: 80, }, diff --git a/lib/rfq-last/table/rfq-table-toolbar-actions.tsx b/lib/rfq-last/table/rfq-table-toolbar-actions.tsx index 9b696cbd..91b2798f 100644 --- a/lib/rfq-last/table/rfq-table-toolbar-actions.tsx +++ b/lib/rfq-last/table/rfq-table-toolbar-actions.tsx @@ -2,7 +2,7 @@ import * as React from "react"; import { type Table } from "@tanstack/react-table"; -import { Download, RefreshCw, Plus } from "lucide-react"; +import { Download, RefreshCw, Plus, Lock, LockOpen } from "lucide-react"; import { Button } from "@/components/ui/button"; import { @@ -12,8 +12,20 @@ import { DropdownMenuSeparator, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from "@/components/ui/alert-dialog"; +import { toast } from "sonner"; import { RfqsLastView } from "@/db/schema"; import { CreateGeneralRfqDialog } from "./create-general-rfq-dialog"; +import { sealMultipleRfqs, unsealMultipleRfqs } from "../service"; interface RfqTableToolbarActionsProps { table: Table; @@ -27,6 +39,43 @@ export function RfqTableToolbarActions({ rfqCategory = "itb", }: RfqTableToolbarActionsProps) { const [isExporting, setIsExporting] = React.useState(false); + const [isSealing, setIsSealing] = React.useState(false); + const [sealDialogOpen, setSealDialogOpen] = React.useState(false); + const [sealAction, setSealAction] = React.useState<"seal" | "unseal">("seal"); + + const selectedRows = table.getFilteredSelectedRowModel().rows; + const selectedRfqIds = selectedRows.map(row => row.original.id); + + // 선택된 항목들의 밀봉 상태 확인 + const sealedCount = selectedRows.filter(row => row.original.rfqSealedYn).length; + const unsealedCount = selectedRows.filter(row => !row.original.rfqSealedYn).length; + + const handleSealAction = React.useCallback(async (action: "seal" | "unseal") => { + setSealAction(action); + setSealDialogOpen(true); + }, []); + + const confirmSealAction = React.useCallback(async () => { + setIsSealing(true); + try { + const result = sealAction === "seal" + ? await sealMultipleRfqs(selectedRfqIds) + : await unsealMultipleRfqs(selectedRfqIds); + + if (result.success) { + toast.success(result.message); + table.toggleAllRowsSelected(false); // 선택 해제 + onRefresh?.(); // 데이터 새로고침 + } else { + toast.error(result.error); + } + } catch (error) { + toast.error("작업 중 오류가 발생했습니다."); + } finally { + setIsSealing(false); + setSealDialogOpen(false); + } + }, [sealAction, selectedRfqIds, table, onRefresh]); const handleExportCSV = React.useCallback(async () => { setIsExporting(true); @@ -36,6 +85,7 @@ export function RfqTableToolbarActions({ return { "RFQ 코드": original.rfqCode || "", "상태": original.status || "", + "밀봉여부": original.rfqSealedYn ? "밀봉" : "미밀봉", "프로젝트 코드": original.projectCode || "", "프로젝트명": original.projectName || "", "자재코드": original.itemCode || "", @@ -89,6 +139,7 @@ export function RfqTableToolbarActions({ return { "RFQ 코드": original.rfqCode || "", "상태": original.status || "", + "밀봉여부": original.rfqSealedYn ? "밀봉" : "미밀봉", "프로젝트 코드": original.projectCode || "", "프로젝트명": original.projectName || "", "자재코드": original.itemCode || "", @@ -115,48 +166,143 @@ export function RfqTableToolbarActions({ }, [table]); return ( -
- {onRefresh && ( - - )} - - - + <> +
+ {onRefresh && ( - - - - 전체 데이터 내보내기 - - - 선택한 항목 내보내기 ({table.getFilteredSelectedRowModel().rows.length}개) - - - - - {/* rfqCategory가 'general'일 때만 일반견적 생성 다이얼로그 표시 */} - {rfqCategory === "general" && ( - - ) } -
+ )} + + {/* 견적 밀봉/해제 버튼 */} + {selectedRfqIds.length > 0 && ( + + + + + + handleSealAction("seal")} + disabled={unsealedCount === 0} + > + + 선택 항목 밀봉 ({unsealedCount}개) + + handleSealAction("unseal")} + disabled={sealedCount === 0} + > + + 선택 항목 밀봉 해제 ({sealedCount}개) + + +
+ 전체 {selectedRfqIds.length}개 선택됨 +
+
+
+ )} + + + + + + + + 전체 데이터 내보내기 + + + 선택한 항목 내보내기 ({table.getFilteredSelectedRowModel().rows.length}개) + + + + + {/* rfqCategory가 'general'일 때만 일반견적 생성 다이얼로그 표시 */} + {rfqCategory === "general" && ( + + )} +
+ + {/* 밀봉 확인 다이얼로그 */} + + + + + {sealAction === "seal" ? "견적 밀봉 확인" : "견적 밀봉 해제 확인"} + + + {sealAction === "seal" + ? `선택한 ${unsealedCount}개의 견적을 밀봉하시겠습니까? 밀봉된 견적은 업체에서 수정할 수 없습니다.` + : `선택한 ${sealedCount}개의 견적 밀봉을 해제하시겠습니까? 밀봉이 해제되면 업체에서 견적을 수정할 수 있습니다.`} + + + + 취소 + + {isSealing ? "처리 중..." : "확인"} + + + + + ); +} + +// CSV 내보내기 유틸리티 함수 +function exportTableToCSV({ data, filename }: { data: any[]; filename: string }) { + if (!data || data.length === 0) { + console.warn("No data to export"); + return; + } + + const headers = Object.keys(data[0]); + const csvContent = [ + headers.join(","), + ...data.map(row => + headers.map(header => { + const value = row[header]; + // 값에 쉼표, 줄바꿈, 따옴표가 있으면 따옴표로 감싸기 + if (typeof value === "string" && (value.includes(",") || value.includes("\n") || value.includes('"'))) { + return `"${value.replace(/"/g, '""')}"`; + } + return value; + }).join(",") + ) + ].join("\n"); + + const blob = new Blob(["\uFEFF" + csvContent], { type: "text/csv;charset=utf-8;" }); + const link = document.createElement("a"); + link.href = URL.createObjectURL(blob); + link.download = filename; + link.click(); + URL.revokeObjectURL(link.href); } \ No newline at end of file diff --git a/lib/rfq-last/vendor-response/editor/vendor-response-editor.tsx b/lib/rfq-last/vendor-response/editor/vendor-response-editor.tsx index c146e42b..34259d37 100644 --- a/lib/rfq-last/vendor-response/editor/vendor-response-editor.tsx +++ b/lib/rfq-last/vendor-response/editor/vendor-response-editor.tsx @@ -1,6 +1,6 @@ "use client" -import { useState } from "react" +import { useState,useEffect } from "react" import { useForm, FormProvider } from "react-hook-form" import { zodResolver } from "@hookform/resolvers/zod" import * as z from "zod" @@ -163,18 +163,74 @@ export default function VendorResponseEditor({ const methods = useForm({ resolver: zodResolver(vendorResponseSchema), - defaultValues + defaultValues, + mode: 'onChange' // 추가: 실시간 validation }) + const { formState: { errors, isValid } } = methods + + useEffect(() => { + if (Object.keys(errors).length > 0) { + console.log('Validation errors:', errors) + } + }, [errors]) + + + + const handleFormSubmit = (isSubmit: boolean = false) => { + // 임시저장일 경우 validation 없이 바로 저장 + if (!isSubmit) { + const formData = methods.getValues() + onSubmit(formData, false) + return + } + + // 제출일 경우에만 validation 수행 + methods.handleSubmit( + (data) => onSubmit(data, isSubmit), + (errors) => { + console.error('Form validation errors:', errors) + + // 첫 번째 에러 필드로 포커스 이동 + const firstErrorField = Object.keys(errors)[0] + if (firstErrorField) { + // 어느 탭에 에러가 있는지 확인 + if (firstErrorField.startsWith('vendor') && + !firstErrorField.startsWith('vendorFirst') && + !firstErrorField.startsWith('vendorSparepart')) { + setActiveTab('terms') + } else if (firstErrorField === 'quotationItems') { + setActiveTab('items') + } + + // 구체적인 에러 메시지 표시 + if (errors.quotationItems) { + toast.error("견적 품목 정보를 확인해주세요. 모든 품목의 단가와 총액을 입력해야 합니다.") + } else { + toast.error("입력 정보를 확인해주세요.") + } + } + } + )() + } + const onSubmit = async (data: VendorResponseFormData, isSubmit: boolean = false) => { + console.log('onSubmit called with:', { data, isSubmit }) // 디버깅용 + setLoading(true) setUploadProgress(0) try { const formData = new FormData() + const fileMetadata = attachments.map((file: any) => ({ + attachmentType: file.attachmentType || "기타", + description: file.description || "" + })) + + // 기본 데이터 추가 - formData.append('data', JSON.stringify({ + const submitData = { ...data, rfqsLastId: rfq.id, rfqLastDetailsId: rfqDetail.id, @@ -183,69 +239,76 @@ export default function VendorResponseEditor({ submittedAt: isSubmit ? new Date().toISOString() : null, submittedBy: isSubmit ? userId : null, totalAmount: data.quotationItems.reduce((sum, item) => sum + item.totalPrice, 0), - updatedBy: userId - })) + updatedBy: userId, + fileMetadata + } + + console.log('Submitting data:', submitData) // 디버깅용 + + formData.append('data', JSON.stringify(submitData)) // 첨부파일 추가 attachments.forEach((file, index) => { formData.append(`attachments`, file) }) - // const response = await fetch(`/api/partners/rfq-last/${rfq.id}/response`, { - // method: existingResponse ? 'PUT' : 'POST', - // body: formData - // }) - - // if (!response.ok) { - // throw new Error('응답 저장에 실패했습니다.') - // } - - // XMLHttpRequest 사용하여 업로드 진행률 추적 - const xhr = new XMLHttpRequest() - - // Promise로 감싸서 async/await 사용 가능하게 - const uploadPromise = new Promise((resolve, reject) => { - // 업로드 진행률 이벤트 - xhr.upload.addEventListener('progress', (event) => { - if (event.lengthComputable) { - const percentComplete = Math.round((event.loaded / event.total) * 100) - setUploadProgress(percentComplete) - } - }) - - // 완료 이벤트 - xhr.addEventListener('load', () => { - if (xhr.status >= 200 && xhr.status < 300) { - setUploadProgress(100) - resolve(JSON.parse(xhr.responseText)) - } else { - reject(new Error('응답 저장에 실패했습니다.')) + // XMLHttpRequest 사용하여 업로드 진행률 추적 + const xhr = new XMLHttpRequest() + + const uploadPromise = new Promise((resolve, reject) => { + xhr.upload.addEventListener('progress', (event) => { + if (event.lengthComputable) { + const percentComplete = Math.round((event.loaded / event.total) * 100) + setUploadProgress(percentComplete) + } + }) + + xhr.addEventListener('load', () => { + if (xhr.status >= 200 && xhr.status < 300) { + setUploadProgress(100) + try { + const response = JSON.parse(xhr.responseText) + resolve(response) + } catch (e) { + console.error('Response parsing error:', e) + reject(new Error('응답 파싱 실패')) } - }) - - // 에러 이벤트 - xhr.addEventListener('error', () => { - reject(new Error('네트워크 오류가 발생했습니다.')) - }) - - // 요청 전송 - xhr.open(existingResponse ? 'PUT' : 'POST', `/api/partners/rfq-last/${rfq.id}/response`) - xhr.send(formData) + } else { + console.error('Server error:', xhr.status, xhr.responseText) + reject(new Error(`서버 오류: ${xhr.status}`)) + } + }) + + xhr.addEventListener('error', () => { + console.error('Network error') + reject(new Error('네트워크 오류가 발생했습니다.')) }) + + // 요청 전송 + const method = existingResponse ? 'PUT' : 'POST' + const url = `/api/partners/rfq-last/${rfq.id}/response` + + console.log(`Sending ${method} request to ${url}`) // 디버깅용 - await uploadPromise + xhr.open(method, url) + xhr.send(formData) + }) + + await uploadPromise toast.success(isSubmit ? "견적서가 제출되었습니다." : "견적서가 저장되었습니다.") router.push('/partners/rfq-last') router.refresh() } catch (error) { - console.error('Error:', error) - toast.error("오류가 발생했습니다.") + console.error('Submit error:', error) // 더 상세한 에러 로깅 + toast.error(error instanceof Error ? error.message : "오류가 발생했습니다.") } finally { setLoading(false) + setUploadProgress(0) } } + const totalAmount = methods.watch('quotationItems')?.reduce( (sum, item) => sum + (item.totalPrice || 0), 0 ) || 0 @@ -256,7 +319,10 @@ export default function VendorResponseEditor({ return ( -
onSubmit(data, false))}> + { + e.preventDefault() // 기본 submit 동작 방지 + handleFormSubmit(false) + }}>
{/* 헤더 정보 */} @@ -293,92 +359,92 @@ export default function VendorResponseEditor({ - {basicContracts.length > 0 ? ( -
- {/* 계약 목록 - 그리드 레이아웃 */} -
- {basicContracts.map((contract) => ( -
-
-
- -
-
-

- {contract.templateName} -

- - {contract.signedAt ? ( - <> - - 서명완료 - + {basicContracts.length > 0 ? ( +
+ {/* 계약 목록 - 그리드 레이아웃 */} +
+ {basicContracts.map((contract) => ( +
+
+
+ +
+
+

+ {contract.templateName} +

+ + {contract.signedAt ? ( + <> + + 서명완료 + + ) : ( + <> + + 서명대기 + + )} + +

+ {contract.signedAt + ? `${formatDate(new Date(contract.signedAt))}` + : contract.deadline + ? `~${formatDate(new Date(contract.deadline))}` + : '마감일 없음'} +

+
+
+
+ ))} +
+ + {/* 서명 상태 요약 및 액션 */} + {basicContracts.some(contract => !contract.signedAt) ? ( +
+
+ +
+

+ 서명 대기: {basicContracts.filter(c => !c.signedAt).length}/{basicContracts.length}개 +

+

+ 견적서 제출 전 모든 계약서 서명 필요 +

+
+
+ +
+ ) : ( + + + + 모든 기본계약 서명 완료 + + + )} +
) : ( - <> - - 서명대기 - +
+ +

+ 이 RFQ에 요청된 기본계약이 없습니다 +

+
)} -
-

- {contract.signedAt - ? `${formatDate(new Date(contract.signedAt))}` - : contract.deadline - ? `~${formatDate(new Date(contract.deadline))}` - : '마감일 없음'} -

-
-
-
- ))} -
- - {/* 서명 상태 요약 및 액션 */} - {basicContracts.some(contract => !contract.signedAt) ? ( -
-
- -
-

- 서명 대기: {basicContracts.filter(c => !c.signedAt).length}/{basicContracts.length}개 -

-

- 견적서 제출 전 모든 계약서 서명 필요 -

-
-
- -
- ) : ( - - - - 모든 기본계약 서명 완료 - - - )} -
- ) : ( -
- -

- 이 RFQ에 요청된 기본계약이 없습니다 -

-
- )} -
+ @@ -429,8 +495,9 @@ export default function VendorResponseEditor({ 취소 - {selectedRows.length > 0 && ( - <> - - - - )} - -
- ), [selectedRows, isRefreshing, isLoadingSendData, handleBulkSend]); + const additionalActions = React.useMemo(() => { + + // 참여 의사가 있는 선택된 벤더 수 계산 + const participatingCount = selectedRows.length; + const shortListCount = selectedRows.filter(v=>v.shortList).length; + + // 견적서가 있는 선택된 벤더 수 계산 + const quotationCount = selectedRows.filter(row => + row.response?.submission?.submittedAt + ).length; + + return ( +
+ + + {selectedRows.length > 0 && ( + <> + {/* Short List 확정 버튼 */} + + + {/* 견적 비교 버튼 */} + + + {/* 정보 일괄 입력 버튼 */} + + + {/* RFQ 발송 버튼 */} + + + )} + + +
+ ); + }, [selectedRows, isRefreshing, isLoadingSendData, handleBulkSend, handleShortListConfirm, handleQuotationCompare, isUpdatingShortList]); return ( <> diff --git a/lib/soap/ecc/send/pcr-confirm.ts b/lib/soap/ecc/send/pcr-confirm.ts index 439ec6f8..7799d007 100644 --- a/lib/soap/ecc/send/pcr-confirm.ts +++ b/lib/soap/ecc/send/pcr-confirm.ts @@ -43,7 +43,7 @@ export interface PCRConfirmResponse { // 1,ZMM_PCR,PCR_REQ,M,CHAR,10,PCR 요청번호 // 2,ZMM_PCR,PCR_REQ_SEQ,M,NUMC,5,PCR 요청순번 // 3,ZMM_PCR,PCR_DEC_DATE,M,DATS,8,PCR 결정일 -// 4,ZMM_PCR,EBELN,M,CHAR,10,구매오더 +// 4,ZMM_PCR,EBELN,M,CHAR,10,구매오더(PO번호) // 5,ZMM_PCR,EBELP,M,NUMC,5,구매오더 품번 // 6,ZMM_PCR,WAERS,,CUKY,5,PCR 통화 // 7,ZMM_PCR,PCR_NETPR,,CURR,"13,2",PCR 단가 diff --git a/lib/tbe-last/service.ts b/lib/tbe-last/service.ts index 760f66ac..d9046524 100644 --- a/lib/tbe-last/service.ts +++ b/lib/tbe-last/service.ts @@ -6,10 +6,11 @@ import db from "@/db/db"; import { and, desc, asc, eq, sql, or, isNull, isNotNull, ne, inArray } from "drizzle-orm"; import { tbeLastView, tbeDocumentsView } from "@/db/schema"; import { rfqPrItems } from "@/db/schema/rfqLast"; -import { rfqLastTbeDocumentReviews, rfqLastTbePdftronComments, rfqLastTbeVendorDocuments } from "@/db/schema"; +import { rfqLastTbeDocumentReviews, rfqLastTbePdftronComments, rfqLastTbeVendorDocuments,rfqLastTbeSessions } from "@/db/schema"; import { filterColumns } from "@/lib/filter-columns"; import { GetTBELastSchema } from "./validations"; - +import { getServerSession } from "next-auth" +import { authOptions } from "@/app/api/auth/[...nextauth]/route" // ========================================== // 1. TBE 세션 목록 조회 // ========================================== @@ -87,8 +88,8 @@ export async function getAllTBELast(input: GetTBELastSchema) { // 2. TBE 세션 상세 조회 // ========================================== export async function getTBESessionDetail(sessionId: number) { - return unstable_cache( - async () => { + // return unstable_cache( + // async () => { // 세션 기본 정보 const [session] = await db .select() @@ -153,13 +154,13 @@ export async function getTBESessionDetail(sessionId: number) { prItems, documents: documentsWithComments, }; - }, - [`tbe-session-${sessionId}`], - { - revalidate: 60, - tags: [`tbe-session-${sessionId}`], - } - )(); + // }, + // [`tbe-session-${sessionId}`], + // { + // revalidate: 60, + // tags: [`tbe-session-${sessionId}`], + // } + // )(); } // ========================================== @@ -190,25 +191,6 @@ export async function getDocumentComments(documentReviewId: number) { return comments; } -// ========================================== -// 4. TBE 평가 결과 업데이트 -// ========================================== -export async function updateTBEEvaluation( - sessionId: number, - data: { - evaluationResult: "pass" | "conditional_pass" | "non_pass"; - conditionalRequirements?: string; - technicalSummary?: string; - commercialSummary?: string; - overallRemarks?: string; - } -) { - // 실제 업데이트 로직 - // await db.update(rfqLastTbeSessions)... - - // 캐시 무효화 - return { success: true }; -} // ========================================== // 5. 벤더 문서 업로드 @@ -244,4 +226,193 @@ export async function uploadVendorDocument( .returning(); return document; +} + +interface UpdateEvaluationData { + evaluationResult?: "Acceptable" | "Acceptable with Comment" | "Not Acceptable" + conditionalRequirements?: string + conditionsFulfilled?: boolean + technicalSummary?: string + commercialSummary?: string + overallRemarks?: string + approvalRemarks?: string + status?: "준비중" | "진행중" | "검토중" | "보류" | "완료" | "취소" +} + +export async function updateTbeEvaluation( + tbeSessionId: number, + data: UpdateEvaluationData +) { + try { + const session = await getServerSession(authOptions) + if (!session?.user) { + return { success: false, error: "인증이 필요합니다" } + } + + const userId = typeof session.user.id === 'string' ? parseInt(session.user.id) : session.user.id + + // 현재 TBE 세션 조회 + const [currentTbeSession] = await db + .select() + .from(rfqLastTbeSessions) + .where(eq(rfqLastTbeSessions.id, tbeSessionId)) + .limit(1) + + if (!currentTbeSession) { + return { success: false, error: "TBE 세션을 찾을 수 없습니다" } + } + + // 업데이트 데이터 준비 + const updateData: any = { + updatedBy: userId, + updatedAt: new Date() + } + + // 평가 결과 관련 필드 + if (data.evaluationResult !== undefined) { + updateData.evaluationResult = data.evaluationResult + } + + // 조건부 승인 관련 (Acceptable with Comment인 경우) + if (data.evaluationResult === "Acceptable with Comment") { + if (data.conditionalRequirements !== undefined) { + updateData.conditionalRequirements = data.conditionalRequirements + } + if (data.conditionsFulfilled !== undefined) { + updateData.conditionsFulfilled = data.conditionsFulfilled + } + } else if (data.evaluationResult === "Acceptable") { + // Acceptable인 경우 조건부 필드 초기화 + updateData.conditionalRequirements = null + updateData.conditionsFulfilled = true + } else if (data.evaluationResult === "Not Acceptable") { + // Not Acceptable인 경우 조건부 필드 초기화 + updateData.conditionalRequirements = null + updateData.conditionsFulfilled = false + } + + // 평가 요약 필드 + if (data.technicalSummary !== undefined) { + updateData.technicalSummary = data.technicalSummary + } + if (data.commercialSummary !== undefined) { + updateData.commercialSummary = data.commercialSummary + } + if (data.overallRemarks !== undefined) { + updateData.overallRemarks = data.overallRemarks + } + + // 승인 관련 필드 + if (data.approvalRemarks !== undefined) { + updateData.approvalRemarks = data.approvalRemarks + updateData.approvedBy = userId + updateData.approvedAt = new Date() + } + + // 상태 업데이트 + if (data.status !== undefined) { + updateData.status = data.status + + // 완료 상태로 변경 시 종료일 설정 + if (data.status === "완료") { + updateData.actualEndDate = new Date() + } + } + + // TBE 세션 업데이트 + const [updated] = await db + .update(rfqLastTbeSessions) + .set(updateData) + .where(eq(rfqLastTbeSessions.id, tbeSessionId)) + .returning() + + // 캐시 초기화 + revalidateTag(`tbe-session-${tbeSessionId}`) + revalidateTag(`tbe-sessions`) + + // RFQ 관련 캐시도 초기화 + if (currentTbeSession.rfqsLastId) { + revalidateTag(`rfq-${currentTbeSession.rfqsLastId}`) + } + + return { + success: true, + data: updated, + message: "평가가 성공적으로 저장되었습니다" + } + + } catch (error) { + console.error("Failed to update TBE evaluation:", error) + return { + success: false, + error: error instanceof Error ? error.message : "평가 저장에 실패했습니다" + } + } +} + +export async function getTbeVendorDocuments(tbeSessionId: number) { + + try { + const documents = await db + .select({ + id: rfqLastTbeVendorDocuments.id, + documentName: rfqLastTbeVendorDocuments.originalFileName, + documentType: rfqLastTbeVendorDocuments.documentType, + fileName: rfqLastTbeVendorDocuments.fileName, + fileSize: rfqLastTbeVendorDocuments.fileSize, + fileType: rfqLastTbeVendorDocuments.fileType, + documentNo: rfqLastTbeVendorDocuments.documentNo, + revisionNo: rfqLastTbeVendorDocuments.revisionNo, + issueDate: rfqLastTbeVendorDocuments.issueDate, + description: rfqLastTbeVendorDocuments.description, + submittedAt: rfqLastTbeVendorDocuments.submittedAt, + // 검토 정보는 rfqLastTbeDocumentReviews에서 가져옴 + reviewStatus: rfqLastTbeDocumentReviews.reviewStatus, + reviewComments: rfqLastTbeDocumentReviews.reviewComments, + reviewedAt: rfqLastTbeDocumentReviews.reviewedAt, + requiresRevision: rfqLastTbeDocumentReviews.requiresRevision, + technicalCompliance: rfqLastTbeDocumentReviews.technicalCompliance, + qualityAcceptable: rfqLastTbeDocumentReviews.qualityAcceptable, + }) + .from(rfqLastTbeVendorDocuments) + .leftJoin( + rfqLastTbeDocumentReviews, + and( + eq(rfqLastTbeDocumentReviews.vendorAttachmentId, rfqLastTbeVendorDocuments.id), + eq(rfqLastTbeDocumentReviews.documentSource, "vendor") + ) + ) + .where(eq(rfqLastTbeVendorDocuments.tbeSessionId, tbeSessionId)) + .orderBy(rfqLastTbeVendorDocuments.submittedAt) + + // 문서 정보 매핑 (reviewStatus는 이미 한글로 저장되어 있음) + const mappedDocuments = documents.map(doc => ({ + ...doc, + reviewStatus: doc.reviewStatus || "미검토", // null인 경우 기본값 + reviewRequired: doc.requiresRevision || false, // UI 호환성을 위해 필드명 매핑 + })) + + return { + success: true, + documents: mappedDocuments, + } + } catch (error) { + console.error("Failed to fetch vendor documents:", error) + return { + success: false, + error: "벤더 문서를 불러오는데 실패했습니다", + documents: [], + } + } +} +// 리뷰 상태 매핑 함수 +function mapReviewStatus(status: string | null): string { + const statusMap: Record = { + "pending": "미검토", + "reviewing": "검토중", + "approved": "승인", + "rejected": "반려", + } + + return status ? (statusMap[status] || status) : "미검토" } \ No newline at end of file diff --git a/lib/tbe-last/table/documents-sheet.tsx b/lib/tbe-last/table/documents-sheet.tsx new file mode 100644 index 00000000..96e6e178 --- /dev/null +++ b/lib/tbe-last/table/documents-sheet.tsx @@ -0,0 +1,543 @@ +// lib/tbe-last/table/dialogs/documents-sheet.tsx + +"use client" + +import * as React from "react" +import { + Sheet, + SheetContent, + SheetHeader, + SheetTitle, + SheetDescription +} from "@/components/ui/sheet" +import { Badge } from "@/components/ui/badge" +import { Button } from "@/components/ui/button" +import { Input } from "@/components/ui/input" +import { Textarea } from "@/components/ui/textarea" +import { + Table, + TableBody, + TableCell, + TableHead, + TableHeader, + TableRow, +} from "@/components/ui/table" +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select" +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu" +import { ScrollArea } from "@/components/ui/scroll-area" +import { formatDate } from "@/lib/utils" +import { downloadFile, getFileInfo } from "@/lib/file-download" +import { + FileText, + Eye, + Download, + MoreHorizontal, + Filter, + MessageSquare, + CheckCircle, + XCircle, + Clock, + AlertCircle, + Save, +} from "lucide-react" +import { toast } from "sonner" +import { useRouter } from "next/navigation" + +interface DocumentsSheetProps { + open: boolean + onOpenChange: (open: boolean) => void + sessionDetail: any + isLoading: boolean +} + +type CommentCount = { totalCount: number; openCount: number } +type CountMap = Record + +export function DocumentsSheet({ + open, + onOpenChange, + sessionDetail, + isLoading +}: DocumentsSheetProps) { + + console.log(sessionDetail, "sessionDetail") + + const [sourceFilter, setSourceFilter] = React.useState<"all" | "buyer" | "vendor">("all") + const [searchTerm, setSearchTerm] = React.useState("") + const [editingReviewId, setEditingReviewId] = React.useState(null) + const [reviewData, setReviewData] = React.useState>({}) + const [isSaving, setIsSaving] = React.useState>({}) + const [commentCounts, setCommentCounts] = React.useState({}) // <-- 추가 + const [countLoading, setCountLoading] = React.useState(false) + const router = useRouter() + + const allReviewIds = React.useMemo(() => { + const docs = sessionDetail?.documents ?? [] + const ids = new Set() + for (const d of docs) { + const id = Number(d?.documentReviewId) + if (Number.isFinite(id)) ids.add(id) + } + return Array.from(ids) + }, [sessionDetail?.documents]) + + React.useEffect(() => { + let aborted = false + ; (async () => { + if (allReviewIds.length === 0) { + setCommentCounts({}) + return + } + setCountLoading(true) + try { + // 너무 길어질 수 있으니 적당히 나눠서 호출(옵션) + const chunkSize = 100 + const chunks: number[][] = [] + for (let i = 0; i < allReviewIds.length; i += chunkSize) { + chunks.push(allReviewIds.slice(i, i + chunkSize)) + } + + const merged: CountMap = {} + for (const c of chunks) { + const qs = encodeURIComponent(c.join(",")) + const res = await fetch(`/api/pdftron-comments/xfdf/count?ids=${qs}`, { + credentials: "include", + cache: "no-store", + }) + if (!res.ok) throw new Error(`count api ${res.status}`) + const json = await res.json() + if (aborted) return + const data = (json?.data ?? {}) as Record + for (const [k, v] of Object.entries(data)) { + const idNum = Number(k) + if (Number.isFinite(idNum)) { + merged[idNum] = { totalCount: v.totalCount ?? 0, openCount: v.openCount ?? 0 } + } + } + } + if (!aborted) setCommentCounts(merged) + } catch (e) { + console.error("Failed to load comment counts", e) + } finally { + if (!aborted) setCountLoading(false) + } + })() + return () => { + aborted = true + } + }, [allReviewIds.join(",")]) // 의존성: id 목록이 바뀔 때만 + + // 문서 초기 데이터 설정 + React.useEffect(() => { + if (sessionDetail?.documents) { + const initialData: Record = {} + sessionDetail.documents.forEach((doc: any) => { + initialData[doc.documentReviewId] = { + reviewStatus: doc.reviewStatus || "미검토", + reviewComments: doc.reviewComments || "" + } + }) + setReviewData(initialData) + } + }, [sessionDetail]) + + // PDFtron 뷰어 열기 + const handleOpenPDFTron = (doc: any) => { + if (!doc.filePath) { + toast.error("파일 경로를 찾을 수 없습니다") + return + } + + const params = new URLSearchParams({ + filePath: doc.filePath, + documentId: doc.documentId.toString(), + documentReviewId: doc.documentReviewId?.toString() || '', + sessionId: sessionDetail?.session?.tbeSessionId?.toString() || '', + documentName: doc.documentName || '', + mode: 'review' + }) + + window.open(`/pdftron-viewer?${params.toString()}`, '_blank') + } + + // 파일이 PDFtron에서 열 수 있는지 확인 + const canOpenInPDFTron = (filePath: string) => { + if (!filePath) return false + const ext = filePath.split('.').pop()?.toLowerCase() + const supportedFormats = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'jpg', 'jpeg', 'png', 'tiff', 'bmp'] + return supportedFormats.includes(ext || '') + } + + // 파일 다운로드 + const handleDownload = async (doc: any) => { + if (!doc.filePath) { + toast.error("파일 경로를 찾을 수 없습니다") + return + } + + await downloadFile(doc.filePath, doc.originalFileName || doc.documentName, { + action: 'download', + showToast: true, + onError: (error) => { + console.error('Download error:', error) + } + }) + } + + // 리뷰 상태 저장 + const handleSaveReview = async (doc: any) => { + const reviewId = doc.documentReviewId + setIsSaving({ ...isSaving, [reviewId]: true }) + + try { + // API 호출하여 리뷰 상태 저장 + const response = await fetch(`/api/document-reviews/${reviewId}`, { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + reviewStatus: reviewData[reviewId]?.reviewStatus, + reviewComments: reviewData[reviewId]?.reviewComments + }) + }) + + if (!response.ok) throw new Error('Failed to save review') + + toast.success("리뷰 저장 완료") + router.refresh() + setEditingReviewId(null) + } catch (error) { + console.error('Save review error:', error) + toast.error("리뷰 저장 실패") + } finally { + setIsSaving({ ...isSaving, [reviewId]: false }) + } + } + + // 리뷰 상태 아이콘 + const getReviewStatusIcon = (status: string) => { + switch (status) { + case "승인": + return + case "반려": + return + case "보류": + return + default: + return + } + } + + // 필터링된 문서 목록 + const filteredDocuments = React.useMemo(() => { + if (!sessionDetail?.documents) return [] + + return sessionDetail.documents.filter((doc: any) => { + // Source 필터 + if (sourceFilter !== "all" && doc.documentSource !== sourceFilter) { + return false + } + + // 검색어 필터 + if (searchTerm) { + const searchLower = searchTerm.toLowerCase() + return ( + doc.documentName?.toLowerCase().includes(searchLower) || + doc.documentType?.toLowerCase().includes(searchLower) || + doc.reviewComments?.toLowerCase().includes(searchLower) + ) + } + + return true + }) + }, [sessionDetail?.documents, sourceFilter, searchTerm]) + + return ( + + + + Documents & Review Management + + 문서 검토 및 코멘트 관리 + + + + {/* 필터 및 검색 */} +
+
+ + +
+ + setSearchTerm(e.target.value)} + className="max-w-sm" + /> + +
+ + Total: {filteredDocuments.length} + + {sessionDetail?.documents && ( + <> + + Buyer: {sessionDetail.documents.filter((d: any) => d.documentSource === "buyer").length} + + + Vendor: {sessionDetail.documents.filter((d: any) => d.documentSource === "vendor").length} + + + )} +
+
+ + {/* 문서 테이블 */} + {isLoading ? ( +
Loading...
+ ) : ( + + + + + Source + Document Name + Type + Review Status + Comments + Review Notes + Uploaded + Actions + + + + {filteredDocuments.length === 0 ? ( + + + No documents found + + + ) : ( + filteredDocuments.map((doc: any) => ( + + + + {doc.documentSource} + + + + +
+ + {doc.documentName} +
+
+ + {doc.documentType} + + + {editingReviewId === doc.documentReviewId ? ( + + ) : ( +
+ {getReviewStatusIcon(reviewData[doc.documentReviewId]?.reviewStatus || doc.reviewStatus)} + + {reviewData[doc.documentReviewId]?.reviewStatus || doc.reviewStatus || "미검토"} + +
+ )} +
+ + + + {(() => { + const id = Number(doc.documentReviewId) + const counts = Number.isFinite(id) ? commentCounts[id] : undefined + if (countLoading && !counts) { + return Loading… + } + if (!counts || counts.totalCount === 0) { + return - + } + return ( +
+ + + {counts.totalCount} + {counts.openCount > 0 && ( + + ({counts.openCount} open) + + )} + +
+ ) + })()} +
+ + + {editingReviewId === doc.documentReviewId ? ( +