From ee57cc221ff2edafd3c0f12a181214c602ed257e Mon Sep 17 00:00:00 2001 From: dujinkim Date: Tue, 22 Jul 2025 02:57:00 +0000 Subject: (대표님, 최겸) 이메일 템플릿, 벤더데이터 변경사항 대응, 기술영업 변경요구사항 구현 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/dashboard/partners-service.ts | 28 +- lib/dashboard/service.ts | 9 - .../editor/template-content-editor.tsx | 9 +- lib/email-template/service.ts | 9 +- .../table/template-table-columns.tsx | 14 +- lib/email-template/table/update-template-sheet.tsx | 26 +- lib/file-stroage.ts | 2 +- lib/form-list.zip | Bin 12417 -> 0 bytes lib/sedp/get-form-tags.ts | 124 ++++++--- lib/sedp/sync-form.ts | 18 +- lib/soap/mdg/send/vendor-master/action.ts | 5 +- lib/tech-vendors/repository.ts | 1 - .../table/detail-table/rfq-detail-table.tsx | 4 +- lib/users/auth/verifyCredentails.ts | 1 + lib/users/service.ts | 176 ++++++++++--- lib/vendor-document-list/dolce-upload-service.ts | 107 +++++++- .../enhanced-document-service.ts | 11 +- lib/vendor-document-list/import-service.ts | 287 ++++++++++++--------- .../ship/enhanced-doc-table-columns.tsx | 42 +-- .../ship/enhanced-documents-table.tsx | 76 +++--- .../ship/import-from-dolce-button.tsx | 86 +++--- .../ship/send-to-shi-button.tsx | 286 ++++++++++---------- 22 files changed, 804 insertions(+), 517 deletions(-) delete mode 100644 lib/form-list.zip (limited to 'lib') diff --git a/lib/dashboard/partners-service.ts b/lib/dashboard/partners-service.ts index 327a16a9..ac8ca920 100644 --- a/lib/dashboard/partners-service.ts +++ b/lib/dashboard/partners-service.ts @@ -73,7 +73,6 @@ export async function getPartnersTeamDashboardData(domain: string): Promise { try { - console.log(`\n🔍 파트너 테이블 ${config.tableName} 통계 조회 (회사: ${companyId})`); // 1단계: 회사별 총 개수 확인 const totalQuery = ` @@ -184,10 +181,8 @@ async function getPartnersTableStats(config: TableConfig, companyId: string): Pr FROM "${config.tableName}" WHERE "vendor_id" = '${companyId}' `; - console.log("Total SQL:", totalQuery); const totalResult = await db.execute(sql.raw(totalQuery)); - console.log("Total 결과:", totalResult.rows[0]); // 2단계: 회사별 상태값 분포 확인 const statusQuery = ` @@ -197,10 +192,8 @@ async function getPartnersTableStats(config: TableConfig, companyId: string): Pr GROUP BY "${config.statusField}" ORDER BY count DESC `; - console.log("Status SQL:", statusQuery); const statusResult = await db.execute(sql.raw(statusQuery)); - console.log("Status 결과:", statusResult.rows); // 3단계: 상태별 개수 조회 const pendingValues = Object.entries(config.statusMapping) @@ -215,11 +208,7 @@ async function getPartnersTableStats(config: TableConfig, companyId: string): Pr .filter(([_, mapped]) => mapped === 'completed') .map(([original]) => original); - console.log("파트너 상태 매핑:"); - console.log("- pending:", pendingValues); - console.log("- inProgress:", inProgressValues); - console.log("- completed:", completedValues); - + let pendingCount = 0; let inProgressCount = 0; let completedCount = 0; @@ -235,7 +224,6 @@ async function getPartnersTableStats(config: TableConfig, companyId: string): Pr const pendingResult = await db.execute(sql.raw(pendingQuery)); pendingCount = parseInt(pendingResult.rows[0]?.count || '0'); - console.log("Pending 개수:", pendingCount); } // In Progress 개수 (회사 필터 포함) @@ -249,7 +237,6 @@ async function getPartnersTableStats(config: TableConfig, companyId: string): Pr const inProgressResult = await db.execute(sql.raw(inProgressQuery)); inProgressCount = parseInt(inProgressResult.rows[0]?.count || '0'); - console.log("InProgress 개수:", inProgressCount); } // Completed 개수 (회사 필터 포함) @@ -263,7 +250,6 @@ async function getPartnersTableStats(config: TableConfig, companyId: string): Pr const completedResult = await db.execute(sql.raw(completedQuery)); completedCount = parseInt(completedResult.rows[0]?.count || '0'); - console.log("Completed 개수:", completedCount); } const stats = { @@ -275,7 +261,6 @@ async function getPartnersTableStats(config: TableConfig, companyId: string): Pr completed: completedCount }; - console.log(`✅ 파트너 ${config.tableName} 최종 통계:`, stats); return stats; } catch (error) { console.error(`❌ 파트너 테이블 ${config.tableName} 통계 조회 중 오류:`, error); @@ -288,11 +273,9 @@ async function getPartnersUserTableStats(config: TableConfig, companyId: string, try { // 사용자 필드가 없는 경우 빈 통계 반환 if (!hasUserFields(config)) { - console.log(`⚠️ 파트너 테이블 ${config.tableName}에 사용자 필드가 없습니다.`); return createEmptyPartnersStats(config); } - console.log(`\n👤 파트너 사용자 ${userId}의 ${config.tableName} 통계 조회 (회사: ${companyId})`); // 사용자 조건 생성 (회사 필터 포함) const userConditions = []; @@ -318,10 +301,8 @@ async function getPartnersUserTableStats(config: TableConfig, companyId: string, FROM "${config.tableName}" WHERE "vendor_id" = '${companyId}' AND (${userConditionStr}) `; - console.log("User Total SQL:", userTotalQuery); const userTotalResult = await db.execute(sql.raw(userTotalQuery)); - console.log("User Total 결과:", userTotalResult.rows[0]); // 2. 사용자 + 회사 상태별 개수 const pendingValues = Object.entries(config.statusMapping) @@ -351,7 +332,6 @@ async function getPartnersUserTableStats(config: TableConfig, companyId: string, const userPendingResult = await db.execute(sql.raw(userPendingQuery)); userPendingCount = parseInt(userPendingResult.rows[0]?.count || '0'); - console.log("User Pending 개수:", userPendingCount); } // User + Company In Progress 개수 @@ -365,7 +345,6 @@ async function getPartnersUserTableStats(config: TableConfig, companyId: string, const userInProgressResult = await db.execute(sql.raw(userInProgressQuery)); userInProgressCount = parseInt(userInProgressResult.rows[0]?.count || '0'); - console.log("User InProgress 개수:", userInProgressCount); } // User + Company Completed 개수 @@ -379,7 +358,6 @@ async function getPartnersUserTableStats(config: TableConfig, companyId: string, const userCompletedResult = await db.execute(sql.raw(userCompletedQuery)); userCompletedCount = parseInt(userCompletedResult.rows[0]?.count || '0'); - console.log("User Completed 개수:", userCompletedCount); } const stats = { @@ -391,7 +369,6 @@ async function getPartnersUserTableStats(config: TableConfig, companyId: string, completed: userCompletedCount }; - console.log(`✅ 파트너 사용자 ${config.tableName} 최종 통계:`, stats); return stats; } catch (error) { console.error(`❌ 파트너 테이블 ${config.tableName} 사용자 통계 조회 중 오류:`, error); @@ -418,12 +395,10 @@ function hasUserFields(config: TableConfig): boolean { // 디버깅 함수: Partners 전용 export async function simplePartnersTest(tableName: string, statusField: string, companyId: string) { try { - console.log(`\n🧪 파트너 ${tableName} 간단한 테스트 (회사: ${companyId}):`); // 1. 회사별 총 개수 const totalQuery = `SELECT COUNT(*) as total FROM "${tableName}" WHERE "vendor_id" = '${companyId}'`; const totalResult = await db.execute(sql.raw(totalQuery)); - console.log("회사별 총 개수:", totalResult.rows[0]); // 2. 회사별 상태 분포 const statusQuery = ` @@ -434,7 +409,6 @@ export async function simplePartnersTest(tableName: string, statusField: string, ORDER BY count DESC `; const statusResult = await db.execute(sql.raw(statusQuery)); - console.log("회사별 상태 분포:", statusResult.rows); return { total: totalResult.rows[0], diff --git a/lib/dashboard/service.ts b/lib/dashboard/service.ts index 91ed5eb2..980938ad 100644 --- a/lib/dashboard/service.ts +++ b/lib/dashboard/service.ts @@ -64,7 +64,6 @@ export async function getTeamDashboardData(domain: string): Promise { completed: completedCount }; - console.log(`✅ ${config.tableName} 최종 통계:`, stats); return stats; } catch (error) { console.error(`❌ 테이블 ${config.tableName} 통계 조회 중 오류:`, error); @@ -273,11 +270,9 @@ async function getUserTableStats(config: TableConfig, userId: string): Promise; - updatedBy: string; + updatedBy: number; }) { try { if (data.content) { @@ -850,14 +850,17 @@ export async function previewTemplateAction( slug: string, data: Record, customContent?: string, - // subject: string + subject?: string ) { try { + + const html = await previewTemplate(slug, data, customContent); + const subjectHtml = await previewTemplate(slug, data, subject); return { success: true, - data: { html } + data: { html , subjectHtml} }; } catch (error) { return { diff --git a/lib/email-template/table/template-table-columns.tsx b/lib/email-template/table/template-table-columns.tsx index d20739cc..a678a20a 100644 --- a/lib/email-template/table/template-table-columns.tsx +++ b/lib/email-template/table/template-table-columns.tsx @@ -248,20 +248,20 @@ export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef - + - { setRowAction({ type: "update", row }) }} > + 업데이트 + */} { @@ -269,7 +269,7 @@ export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef @@ -281,7 +281,7 @@ export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef diff --git a/lib/email-template/table/update-template-sheet.tsx b/lib/email-template/table/update-template-sheet.tsx index 58da0626..d3df93f0 100644 --- a/lib/email-template/table/update-template-sheet.tsx +++ b/lib/email-template/table/update-template-sheet.tsx @@ -7,6 +7,7 @@ import { Loader } from "lucide-react" import { useForm } from "react-hook-form" import { toast } from "sonner" import { z } from "zod" +import { useSession } from "next-auth/react" import { Button } from "@/components/ui/button" import { @@ -55,6 +56,13 @@ interface UpdateTemplateSheetProps export function UpdateTemplateSheet({ template, ...props }: UpdateTemplateSheetProps) { const [isUpdatePending, startUpdateTransition] = React.useTransition() + const { data: session } = useSession(); + + // 또는 더 안전하게 + if (!session?.user?.id) { + toast.error("로그인이 필요합니다") + return + } const form = useForm({ resolver: zodResolver(updateTemplateSchema), @@ -85,8 +93,10 @@ export function UpdateTemplateSheet({ template, ...props }: UpdateTemplateSheetP const { error } = await updateTemplateAction(template.slug, { name: input.name, description: input.description || undefined, + category: input.category === "none" ? undefined : input.category, // 여기서 변환 + // category는 일반적으로 수정하지 않는 것이 좋지만, 필요시 포함 - updatedBy: currentUserId, + updatedBy: Number(session.user.id), }) if (error) { @@ -165,13 +175,13 @@ export function UpdateTemplateSheet({ template, ...props }: UpdateTemplateSheetP - 카테고리 없음 - {TEMPLATE_CATEGORY_OPTIONS.map((option) => ( - - {option.label} - - ))} - + 카테고리 없음 + {TEMPLATE_CATEGORY_OPTIONS.map((option) => ( + + {option.label} + + ))} + diff --git a/lib/file-stroage.ts b/lib/file-stroage.ts index beca05ee..eab52364 100644 --- a/lib/file-stroage.ts +++ b/lib/file-stroage.ts @@ -367,7 +367,7 @@ interface SaveBufferOptions { userId?: string; } -interface SaveFileResult { +export interface SaveFileResult { success: boolean; filePath?: string; publicPath?: string; diff --git a/lib/form-list.zip b/lib/form-list.zip deleted file mode 100644 index 7312729e..00000000 Binary files a/lib/form-list.zip and /dev/null differ diff --git a/lib/sedp/get-form-tags.ts b/lib/sedp/get-form-tags.ts index d44e11f5..32f4403e 100644 --- a/lib/sedp/get-form-tags.ts +++ b/lib/sedp/get-form-tags.ts @@ -54,7 +54,7 @@ export async function importTagsFromSEDP( processedCount: number; excludedCount: number; totalEntries: number; - formCreated?: boolean; // 새로 추가: form이 생성되었는지 여부 + formCreated?: boolean; errors?: string[]; }> { try { @@ -67,29 +67,10 @@ export async function importTagsFromSEDP( // SEDP API에서 태그 데이터 가져오기 const tagData = await fetchTagDataFromSEDP(projectCode, formCode); - // 데이터 형식 처리 - const tableName = Object.keys(tagData)[0]; - if (!tableName || !tagData[tableName]) { - throw new Error("Invalid tag data format from SEDP API"); - } - - const tagEntries: TagEntry[] = tagData[tableName]; - if (!Array.isArray(tagEntries) || tagEntries.length === 0) { - return { - processedCount: 0, - excludedCount: 0, - totalEntries: 0, - errors: ["No tag entries found in API response"] - }; - } - - // 진행 상황 보고 - if (progressCallback) progressCallback(20); - // 트랜잭션으로 모든 DB 작업 처리 return await db.transaction(async (tx) => { - // 프로젝트 ID 가져오기 - const projectRecord = await tx.select({ id: projects.id }) + // 프로젝트 정보 가져오기 (type 포함) + const projectRecord = await tx.select({ id: projects.id, type: projects.type }) .from(projects) .where(eq(projects.code, projectCode)) .limit(1); @@ -99,7 +80,74 @@ export async function importTagsFromSEDP( } const projectId = projectRecord[0].id; + const projectType = projectRecord[0].type; + + // 프로젝트 타입에 따라 packageCode를 찾을 ATT_ID 결정 + const packageCodeAttId = projectType === "ship" ? "CM3003" : "ME5074"; + + // packageId로 contractItem과 item 정보 가져오기 + const contractItemRecord = await tx.select({ itemId: contractItems.itemId }) + .from(contractItems) + .where(eq(contractItems.id, packageId)) + .limit(1); + + if (!contractItemRecord || contractItemRecord.length === 0) { + throw new Error(`Contract item not found for packageId: ${packageId}`); + } + + const itemRecord = await tx.select({ packageCode: items.packageCode }) + .from(items) + .where(eq(items.id, contractItemRecord[0].itemId)) + .limit(1); + + if (!itemRecord || itemRecord.length === 0) { + throw new Error(`Item not found for itemId: ${contractItemRecord[0].itemId}`); + } + + const targetPackageCode = itemRecord[0].packageCode; + + // 데이터 형식 처리 - tagData의 첫 번째 키 사용 + const tableName = Object.keys(tagData)[0]; + if (!tableName || !tagData[tableName]) { + throw new Error("Invalid tag data format from SEDP API"); + } + + const allTagEntries: TagEntry[] = tagData[tableName]; + + if (!Array.isArray(allTagEntries) || allTagEntries.length === 0) { + return { + processedCount: 0, + excludedCount: 0, + totalEntries: 0, + errors: ["No tag entries found in API response"] + }; + } + + // packageCode로 필터링 - ATTRIBUTES에서 지정된 ATT_ID의 VALUE와 packageCode 비교 + const tagEntries = allTagEntries.filter(entry => { + if (Array.isArray(entry.ATTRIBUTES)) { + const packageCodeAttr = entry.ATTRIBUTES.find(attr => attr.ATT_ID === packageCodeAttId); + if (packageCodeAttr && packageCodeAttr.VALUE === targetPackageCode) { + return true; + } + } + return false; + }); + + if (tagEntries.length === 0) { + return { + processedCount: 0, + excludedCount: 0, + totalEntries: allTagEntries.length, + errors: [`No tag entries found with ${packageCodeAttId} attribute value matching packageCode: ${targetPackageCode}`] + }; + } + + // 진행 상황 보고 + if (progressCallback) progressCallback(20); + + // 나머지 코드는 기존과 동일... // form ID 가져오기 - 없으면 생성 let formRecord = await tx.select({ id: forms.id }) .from(forms) @@ -139,7 +187,7 @@ export async function importTagsFromSEDP( // tagClass 조회 (CLS_ID -> label) let tagClassLabel = firstTag.CLS_ID; // 기본값 if (firstTag.CLS_ID) { - const tagClassRecord = await tx.select({ id: tagClasses.id, label: tagClasses.label }) // ✅ 수정 + const tagClassRecord = await tx.select({ id: tagClasses.id, label: tagClasses.label }) .from(tagClasses) .where(and( eq(tagClasses.code, firstTag.CLS_ID), @@ -147,8 +195,6 @@ export async function importTagsFromSEDP( )) .limit(1); - - if (tagClassRecord && tagClassRecord.length > 0) { tagClassLabel = tagClassRecord[0].label; } @@ -159,14 +205,11 @@ export async function importTagsFromSEDP( projectId, ); - // ep가 "IMEP"인 것만 필터링 - // const formMappings = allFormMappings?.filter(mapping => mapping.ep === "IMEP") || []; - // 현재 formCode와 일치하는 매핑 찾기 const targetFormMapping = allFormMappings.find(mapping => mapping.formCode === formCode); if (targetFormMapping) { - console.log(`[IMPORT TAGS] Found IMEP form mapping for ${formCode}, creating form...`); + console.log(`[IMPORT TAGS] Found form mapping for ${formCode}, creating form...`); // form 생성 const insertResult = await tx @@ -176,7 +219,7 @@ export async function importTagsFromSEDP( formCode: targetFormMapping.formCode, formName: targetFormMapping.formName, eng: true, // ENG 모드에서 가져오는 것이므로 eng: true - im: targetFormMapping.ep === "IMEP" ? true:false + im: targetFormMapping.ep === "IMEP" ? true : false }) .returning({ id: forms.id }); @@ -185,9 +228,9 @@ export async function importTagsFromSEDP( console.log(`[IMPORT TAGS] Successfully created form:`, insertResult[0]); } else { - console.log(`[IMPORT TAGS] No IMEP form mapping found for formCode: ${formCode}`); - console.log(`[IMPORT TAGS] Available IMEP mappings:`, formMappings.map(m => m.formCode)); - throw new Error(`Form ${formCode} not found and no IMEP mapping available for tag type ${tagTypeDescription}`); + console.log(`[IMPORT TAGS] No form mapping found for formCode: ${formCode}`); + console.log(`[IMPORT TAGS] Available mappings:`, allFormMappings.map(m => m.formCode)); + throw new Error(`Form ${formCode} not found and no mapping available for tag type ${tagTypeDescription}`); } } else { throw new Error(`Form not found for formCode: ${formCode} and contractItemId: ${packageId}, and no tags to derive form mapping`); @@ -232,7 +275,7 @@ export async function importTagsFromSEDP( // tagClass 조회 let tagClassLabel = firstTag.CLS_ID; if (firstTag.CLS_ID) { - const tagClassRecord = await tx.select({ id: tagClasses.id, label: tagClasses.label }) // ✅ 수정 + const tagClassRecord = await tx.select({ id: tagClasses.id, label: tagClasses.label }) .from(tagClasses) .where(and( eq(tagClasses.code, firstTag.CLS_ID), @@ -250,9 +293,6 @@ export async function importTagsFromSEDP( projectId, ); - // ep가 "IMEP"인 것만 필터링 - // const formMappings = allFormMappings?.filter(mapping => mapping.ep === "IMEP") || []; - // 현재 formCode와 일치하는 매핑 찾기 const targetFormMapping = allFormMappings.find(mapping => mapping.formCode === formCode); @@ -292,6 +332,9 @@ export async function importTagsFromSEDP( const formId = formRecord[0].id; + // 나머지 처리 로직은 기존과 동일... + // (양식 메타데이터 가져오기, 태그 처리 등) + // 양식 메타데이터 가져오기 const formMetaRecord = await tx.select({ columns: formMetas.columns }) .from(formMetas) @@ -388,7 +431,7 @@ export async function importTagsFromSEDP( let tagClassLabel = tagEntry.CLS_ID; // 기본값 let tagClassId = null; // 기본값 if (tagEntry.CLS_ID) { - const tagClassRecord = await tx.select({ id: tagClasses.id, label: tagClasses.label }) // ✅ 수정 + const tagClassRecord = await tx.select({ id: tagClasses.id, label: tagClasses.label }) .from(tagClasses) .where(and( eq(tagClasses.code, tagEntry.CLS_ID), @@ -414,7 +457,7 @@ export async function importTagsFromSEDP( contractItemId: packageId, formId: formId, tagNo: tagEntry.TAG_NO, - tagType: tagTypeDescription, + tagType: tagTypeDescription || "", class: tagClassLabel, tagClassId: tagClassId, description: tagEntry.TAG_DESC || null, @@ -644,7 +687,7 @@ export async function importTagsFromSEDP( processedCount, excludedCount, totalEntries: tagEntries.length, - formCreated, // 새로 추가: form이 생성되었는지 여부 + formCreated, errors: errors.length > 0 ? errors : undefined }; }); @@ -654,7 +697,6 @@ export async function importTagsFromSEDP( throw error; } } - /** * SEDP API에서 태그 데이터 가져오기 * diff --git a/lib/sedp/sync-form.ts b/lib/sedp/sync-form.ts index c3c88f07..f9e63caf 100644 --- a/lib/sedp/sync-form.ts +++ b/lib/sedp/sync-form.ts @@ -430,23 +430,7 @@ async function getRegisters(projectCode: string): Promise { } // 결과를 배열로 변환 (단일 객체인 경우 배열로 래핑) - let registers: Register[] = Array.isArray(data) ? data : [data]; - - // MAP_CLS_ID가 비어있지 않고 REMARK가 vd, VD, vD, Vd 중 하나인 레지스터만 필터링 - registers = registers.filter(register => { - // 삭제된 레지스터 제외 - if (register.DELETED) return false; - - // MAP_CLS_ID 배열이 존재하고 요소가 하나 이상 있는지 확인 - const hasValidMapClsId = Array.isArray(register.MAP_CLS_ID) && register.MAP_CLS_ID.length > 0; - - // REMARK가 'vd_' 또는 'vd' 포함 확인 (대소문자 구분 없이) - const remarkLower = register.REMARK && register.REMARK.toLowerCase(); - const hasValidRemark = remarkLower && (remarkLower.includes('vd')); - - // 두 조건 모두 충족해야 함 - return hasValidMapClsId && hasValidRemark; - }); + const registers: Register[] = Array.isArray(data) ? data : [data]; console.log(`프로젝트 ${projectCode}에서 ${registers.length}개의 유효한 레지스터를 가져왔습니다.`); return registers; diff --git a/lib/soap/mdg/send/vendor-master/action.ts b/lib/soap/mdg/send/vendor-master/action.ts index 24112316..ec267bbb 100644 --- a/lib/soap/mdg/send/vendor-master/action.ts +++ b/lib/soap/mdg/send/vendor-master/action.ts @@ -18,6 +18,7 @@ import { } from "@/db/schema/MDG/mdg"; import { eq, sql, desc } from "drizzle-orm"; import { withSoapLogging } from "../../utils"; +// public 경로 사용하지 않음. 형제경로 사용. (처리완료) import fs from 'fs'; import path from 'path'; import { XMLBuilder } from 'fast-xml-parser'; @@ -49,7 +50,7 @@ function parseCsv(content: string): CsvField[] { } // 모듈 초기화 시 CSV 로드 -const CSV_PATH = path.join(process.cwd(), 'public', 'wsdl', 'P2MD3007_AO.csv'); +const CSV_PATH = path.join(__dirname, 'P2MD3007_AO.csv'); let CSV_FIELDS: CsvField[] = []; try { const csvRaw = fs.readFileSync(CSV_PATH, 'utf-8'); @@ -699,5 +700,3 @@ export async function getVendorSendStatistics(): Promise<{ throw error; } } - - diff --git a/lib/tech-vendors/repository.ts b/lib/tech-vendors/repository.ts index a273bf50..6f9aafbf 100644 --- a/lib/tech-vendors/repository.ts +++ b/lib/tech-vendors/repository.ts @@ -349,7 +349,6 @@ export async function getVendorWorkTypes( }) .from(techVendorPossibleItems) .where(eq(techVendorPossibleItems.vendorId, vendorId)); - console.log("possibleItems", possibleItems); if (!possibleItems.length) { return []; } diff --git a/lib/techsales-rfq/table/detail-table/rfq-detail-table.tsx b/lib/techsales-rfq/table/detail-table/rfq-detail-table.tsx index 41572a93..acf67497 100644 --- a/lib/techsales-rfq/table/detail-table/rfq-detail-table.tsx +++ b/lib/techsales-rfq/table/detail-table/rfq-detail-table.tsx @@ -730,14 +730,14 @@ export function RfqDetailTables({ selectedRfq, maxHeight }: RfqDetailTablesProps onSuccess={handleRefreshData} /> - {/* 다중 벤더 삭제 확인 다이얼로그 */} + {/* 다중 벤더 삭제 확인 다이얼로그 + /> */} {/* 견적 히스토리 다이얼로그 */} = 2 && + name.length <= 50 && + !/[<>:"'|?*]/.test(name); + }, +}; + +/** + * 파일 크기를 읽기 쉬운 형태로 변환 + */ +const formatFileSize = (bytes: number): string => { + if (bytes === 0) return '0 Bytes'; + + const k = 1024; + const sizes = ['Bytes', 'KB', 'MB', 'GB']; + const i = Math.floor(Math.log(bytes) / Math.log(k)); + + return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]; +}; + +/** + * 보안 강화된 사용자 프로필 이미지 업데이트 함수 + * (file-storage.ts의 saveFile 함수 활용) + */ +export async function updateUserProfileImage(formData: FormData): Promise { + const startTime = Date.now(); + // 1) FormData에서 데이터 꺼내기 - const file = formData.get("file") as File | null - const userId = Number(formData.get("userId")) - const name = formData.get("name") as string - const email = formData.get("email") as string - - // 2) 기본적인 유효성 검증 - if (!file) { - throw new Error("No file found in the FormData.") - } - if (!userId) { - throw new Error("userId is required.") - } + const file = formData.get("file") as File | null; + const userId = Number(formData.get("userId")); + const name = formData.get("name") as string; + const email = formData.get("email") as string; try { - // 3) 파일 저장 (해시 생성) - const directory = './public/profiles' - const { hashedFileName } = await saveDocument(file, directory) - - // 4) DB 업데이트 - const imageUrl = hashedFileName - const data = { name, email, imageUrl } - const user = await updateUser(userId, data) + // 2) 기본 유효성 검증 + if (!file) { + throw new Error("파일이 제공되지 않았습니다."); + } + + if (!userId || userId <= 0) { + throw new Error("유효한 사용자 ID가 필요합니다."); + } + + // 3) 사용자 정보 검증 (파일 저장 전에 미리 체크) + if (name && !validateUserData.validateName(name)) { + throw new Error("유효하지 않은 이름입니다 (2-50자, 특수문자 제한)."); + } + + if (email && !validateUserData.validateEmail(email)) { + throw new Error("유효하지 않은 이메일 주소입니다."); + } + + console.log("📤 프로필 이미지 업데이트 시작:", { + fileName: file.name, + fileSize: formatFileSize(file.size), + userId, + }); + + // 4) file-storage.ts의 saveFile 함수로 보안 검증 + 저장 (한 번에 처리!) + const saveResult: SaveFileResult = await saveFile({ + file, + directory: 'profiles', // './public/profiles'에서 'profiles'로 변경 + originalName: file.name, + userId: userId.toString(), + }); + + // 5) 파일 저장 실패 시 에러 처리 + if (!saveResult.success) { + throw new Error(saveResult.error || "파일 저장에 실패했습니다."); + } + + console.log("✅ 파일 저장 성공:", { + fileName: saveResult.fileName, + publicPath: saveResult.publicPath, + securityChecks: saveResult.securityChecks, + }); + + // 6) DB 업데이트 (file-storage.ts에서 반환된 publicPath 사용) + const imageUrl = saveResult.publicPath; // 웹에서 접근 가능한 경로 + const data = { name, email, imageUrl }; + const user = await updateUser(userId, data); + if (!user) { - // updateUser가 null을 반환하면, DB 업데이트 실패 혹은 해당 유저가 없음 - throw new Error(`User with id=${userId} not found or update failed.`) + // DB 업데이트 실패 시 업로드된 파일 정리 + // TODO: file-storage.ts의 deleteFile 함수 사용하여 파일 삭제 고려 + throw new Error(`사용자 ID=${userId}를 찾을 수 없거나 업데이트에 실패했습니다.`); } - // 5) 성공 시 성공 정보 반환 - return { success: true, user } + // 7) 성공 반환 + const duration = Date.now() - startTime; + + console.log("🎉 프로필 업데이트 성공:", { + userId, + imageUrl, + duration: `${duration}ms`, + }); + + return { + success: true, + user, + duration, + fileInfo: { + fileName: saveResult.fileName!, + originalName: saveResult.originalName!, + fileSize: formatFileSize(saveResult.fileSize!), + publicPath: saveResult.publicPath!, + }, + securityChecks: saveResult.securityChecks, + }; + } catch (err: any) { - // DB 업데이트 중 발생하는 에러나 saveDocument 내부 에러 등을 처리 - console.error("[updateUserProfileImage] Error:", err) - throw new Error(err.message ?? "Failed to update user profile.") + const duration = Date.now() - startTime; + const errorMessage = err.message ?? "프로필 업데이트 중 오류가 발생했습니다."; + + console.error("❌ [updateUserProfileImage] Error:", err); + + return { + success: false, + error: errorMessage, + duration, + }; } } diff --git a/lib/vendor-document-list/dolce-upload-service.ts b/lib/vendor-document-list/dolce-upload-service.ts index d98a4c70..032b028c 100644 --- a/lib/vendor-document-list/dolce-upload-service.ts +++ b/lib/vendor-document-list/dolce-upload-service.ts @@ -17,6 +17,19 @@ export interface DOLCEUploadResult { } } +interface ResultData { + FileId: string; + UploadId: string; + FileSeq: number; + FileName: string; + FileRelativePath: string; + FileSize: number; + FileCreateDT: string; // ISO string format + FileWriteDT: string; // ISO string format + OwnerUserId: string; +} + + interface FileReaderConfig { baseDir: string; isProduction: boolean; @@ -339,8 +352,10 @@ private async uploadFiles( uploadId: string // 이미 생성된 UploadId를 매개변수로 받음 ): Promise> { const uploadResults = [] + const resultDataArray: ResultData[] = [] - for (const attachment of attachments) { + for (let i = 0; i < attachments.length; i++) { + const attachment = attachments[i] try { // FileId만 새로 생성 (UploadId는 이미 생성된 것 사용) const fileId = uuidv4() @@ -386,6 +401,23 @@ private async uploadFiles( filePath: dolceFilePath }) + // ResultData 객체 생성 (PWPUploadResultService 호출용) + const fileStats = await this.getFileStats(attachment.filePath) // 파일 통계 정보 조회 + + const resultData: ResultData = { + FileId: fileId, + UploadId: uploadId, + FileSeq: i + 1, // 1부터 시작하는 시퀀스 + FileName: attachment.fileName, + FileRelativePath: dolceFilePath, + FileSize: fileStats.size, + FileCreateDT: fileStats.birthtime.toISOString(), + FileWriteDT: fileStats.mtime.toISOString(), + OwnerUserId: userId + } + + resultDataArray.push(resultData) + console.log(`✅ File uploaded successfully: ${attachment.fileName} -> ${dolceFilePath}`) console.log(`✅ DB updated for attachment ID: ${attachment.id}`) @@ -395,9 +427,82 @@ private async uploadFiles( } } + // 모든 파일 업로드가 완료된 후 PWPUploadResultService 호출 + if (resultDataArray.length > 0) { + try { + await this.finalizeUploadResult(resultDataArray) + console.log(`✅ Upload result finalized for UploadId: ${uploadId}`) + } catch (error) { + console.error(`❌ Failed to finalize upload result for UploadId: ${uploadId}`, error) + // 파일 업로드는 성공했지만 결과 저장 실패 - 로그만 남기고 계속 진행 + } + } + return uploadResults } + +private async finalizeUploadResult(resultDataArray: ResultData[]): Promise { + const url = `${this.UPLOAD_SERVICE_URL}/PWPUploadResultService.ashx` + + try { + const jsonData = JSON.stringify(resultDataArray) + const dataBuffer = Buffer.from(jsonData, 'utf-8') + + console.log(`Calling PWPUploadResultService with ${resultDataArray.length} files`) + console.log('ResultData:', JSON.stringify(resultDataArray, null, 2)) + + const response = await fetch(url, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: dataBuffer + }) + + if (!response.ok) { + const errorText = await response.text() + throw new Error(`PWPUploadResultService failed: HTTP ${response.status} - ${errorText}`) + } + + const result = await response.text() + + if (result !== 'Success') { + throw new Error(`PWPUploadResultService returned unexpected result: ${result}`) + } + + console.log('✅ PWPUploadResultService call successful') + + } catch (error) { + console.error('❌ PWPUploadResultService call failed:', error) + throw error + } +} + +// 파일 통계 정보 조회 헬퍼 메서드 (파일시스템에서 파일 정보를 가져옴) +private async getFileStats(filePath: string): Promise<{ size: number, birthtime: Date, mtime: Date }> { + try { + // Node.js 환경이라면 fs.stat 사용 + const fs = require('fs').promises + const stats = await fs.stat(filePath) + + return { + size: stats.size, + birthtime: stats.birthtime, + mtime: stats.mtime + } + } catch (error) { + console.warn(`Could not get file stats for ${filePath}, using defaults`) + // 파일 정보를 가져올 수 없는 경우 기본값 사용 + const now = new Date() + return { + size: 0, + birthtime: now, + mtime: now + } + } +} + /** * 문서 정보 업로드 (DetailDwgReceiptMgmtEdit) */ diff --git a/lib/vendor-document-list/enhanced-document-service.ts b/lib/vendor-document-list/enhanced-document-service.ts index e01283dc..6fe8feb7 100644 --- a/lib/vendor-document-list/enhanced-document-service.ts +++ b/lib/vendor-document-list/enhanced-document-service.ts @@ -20,7 +20,7 @@ import type { Revision } from "@/types/enhanced-documents" import { GetVendorShipDcoumentsSchema } from "./validations" -import { contracts, users } from "@/db/schema" +import { contracts, users, vendors } from "@/db/schema" // 스키마 타입 정의 export interface GetEnhancedDocumentsSchema { @@ -1092,11 +1092,12 @@ export async function getDocumentDetails(documentId: number) { // 벤더 정보 조회 const [vendorInfo] = await tx .select({ - vendorName: simplifiedDocumentsView.vendorName, - vendorCode: simplifiedDocumentsView.vendorCode, + vendorName: vendors.vendorName, + vendorCode: vendors.vendorCode, }) - .from(simplifiedDocumentsView) - .where(eq(simplifiedDocumentsView.contractId, contractIds[0])) + .from(contracts) + .leftJoin(vendors, eq(contracts.vendorId, vendors.id)) + .where(eq(contracts.id, contractIds[0])) .limit(1) return { data, total, drawingKind, vendorInfo } diff --git a/lib/vendor-document-list/import-service.ts b/lib/vendor-document-list/import-service.ts index bc384ea2..c7ba041a 100644 --- a/lib/vendor-document-list/import-service.ts +++ b/lib/vendor-document-list/import-service.ts @@ -1332,156 +1332,189 @@ class ImportService { /** * 가져오기 상태 조회 */ - async getImportStatus( - contractId: number, - sourceSystem: string = 'DOLCE' - ): Promise { - try { - // 마지막 가져오기 시간 조회 - const [lastImport] = await db - .select({ - lastSynced: sql`MAX(${documents.externalSyncedAt})` - }) - .from(documents) - .where(and( - eq(documents.contractId, contractId), - eq(documents.externalSystemType, sourceSystem) - )) + /** + * 가져오기 상태 조회 - 에러 시 안전한 기본값 반환 + */ +async getImportStatus( + contractId: number, + sourceSystem: string = 'DOLCE' +): Promise { + try { + // 마지막 가져오기 시간 조회 + const [lastImport] = await db + .select({ + lastSynced: sql`MAX(${documents.externalSyncedAt})` + }) + .from(documents) + .where(and( + eq(documents.contractId, contractId), + eq(documents.externalSystemType, sourceSystem) + )) - // 프로젝트 코드와 벤더 코드 조회 - const contractInfo = await this.getContractInfoById(contractId) + // 프로젝트 코드와 벤더 코드 조회 + const contractInfo = await this.getContractInfoById(contractId) - if (!contractInfo?.projectCode || !contractInfo?.vendorCode) { - throw new Error(`Project code or vendor code not found for contract ${contractId}`) + // 🔥 계약 정보가 없으면 기본 상태 반환 (에러 throw 하지 않음) + if (!contractInfo?.projectCode || !contractInfo?.vendorCode) { + console.warn(`Project code or vendor code not found for contract ${contractId}`) + return { + lastImportAt: lastImport?.lastSynced ? new Date(lastImport.lastSynced).toISOString() : undefined, + availableDocuments: 0, + newDocuments: 0, + updatedDocuments: 0, + availableRevisions: 0, + newRevisions: 0, + updatedRevisions: 0, + availableAttachments: 0, + newAttachments: 0, + updatedAttachments: 0, + importEnabled: false, // 🔥 계약 정보가 없으면 import 비활성화 + error: `Contract ${contractId}에 대한 프로젝트 코드 또는 벤더 코드를 찾을 수 없습니다.` // 🔥 에러 메시지 추가 } + } - let availableDocuments = 0 - let newDocuments = 0 - let updatedDocuments = 0 - let availableRevisions = 0 - let newRevisions = 0 - let updatedRevisions = 0 - let availableAttachments = 0 - let newAttachments = 0 - let updatedAttachments = 0 + let availableDocuments = 0 + let newDocuments = 0 + let updatedDocuments = 0 + let availableRevisions = 0 + let newRevisions = 0 + let updatedRevisions = 0 + let availableAttachments = 0 + let newAttachments = 0 + let updatedAttachments = 0 - try { - // 각 drawingKind별로 확인 - const drawingKinds = ['B3', 'B4', 'B5'] + try { + // 각 drawingKind별로 확인 + const drawingKinds = ['B3', 'B4', 'B5'] - for (const drawingKind of drawingKinds) { - try { - const externalDocs = await this.fetchFromDOLCE( - contractInfo.projectCode, - contractInfo.vendorCode, - drawingKind - ) - availableDocuments += externalDocs.length - - // 신규/업데이트 문서 수 계산 - for (const externalDoc of externalDocs) { - const existing = await db - .select({ id: documents.id, updatedAt: documents.updatedAt }) - .from(documents) - .where(and( - eq(documents.contractId, contractId), - eq(documents.docNumber, externalDoc.DrawingNo) - )) - .limit(1) - - if (existing.length === 0) { - newDocuments++ - } else { - // DOLCE의 CreateDt와 로컬 updatedAt 비교 - if (externalDoc.CreateDt && existing[0].updatedAt) { - const externalModified = new Date(externalDoc.CreateDt) - const localModified = new Date(existing[0].updatedAt) - if (externalModified > localModified) { - updatedDocuments++ - } + for (const drawingKind of drawingKinds) { + try { + const externalDocs = await this.fetchFromDOLCE( + contractInfo.projectCode, + contractInfo.vendorCode, + drawingKind + ) + availableDocuments += externalDocs.length + + // 신규/업데이트 문서 수 계산 + for (const externalDoc of externalDocs) { + const existing = await db + .select({ id: documents.id, updatedAt: documents.updatedAt }) + .from(documents) + .where(and( + eq(documents.contractId, contractId), + eq(documents.docNumber, externalDoc.DrawingNo) + )) + .limit(1) + + if (existing.length === 0) { + newDocuments++ + } else { + // DOLCE의 CreateDt와 로컬 updatedAt 비교 + if (externalDoc.CreateDt && existing[0].updatedAt) { + const externalModified = new Date(externalDoc.CreateDt) + const localModified = new Date(existing[0].updatedAt) + if (externalModified > localModified) { + updatedDocuments++ } } + } - // revisions 및 attachments 상태도 확인 - try { - const detailDocs = await this.fetchDetailFromDOLCE( - externalDoc.ProjectNo, - externalDoc.DrawingNo, - externalDoc.Discipline, - externalDoc.DrawingKind - ) - availableRevisions += detailDocs.length - - for (const detailDoc of detailDocs) { - const existingRevision = await db - .select({ id: revisions.id }) - .from(revisions) - .where(eq(revisions.registerId, detailDoc.RegisterId)) - .limit(1) - - if (existingRevision.length === 0) { - newRevisions++ - } else { - updatedRevisions++ - } + // revisions 및 attachments 상태도 확인 + try { + const detailDocs = await this.fetchDetailFromDOLCE( + externalDoc.ProjectNo, + externalDoc.DrawingNo, + externalDoc.Discipline, + externalDoc.DrawingKind + ) + availableRevisions += detailDocs.length + + for (const detailDoc of detailDocs) { + const existingRevision = await db + .select({ id: revisions.id }) + .from(revisions) + .where(eq(revisions.registerId, detailDoc.RegisterId)) + .limit(1) + + if (existingRevision.length === 0) { + newRevisions++ + } else { + updatedRevisions++ + } - // FS Category 문서의 첨부파일 확인 - if (detailDoc.Category === 'FS' && detailDoc.UploadId) { - try { - const fileInfos = await this.fetchFileInfoFromDOLCE(detailDoc.UploadId) - availableAttachments += fileInfos.filter(f => f.UseYn === 'Y').length - - for (const fileInfo of fileInfos) { - if (fileInfo.UseYn !== 'Y') continue - - const existingAttachment = await db - .select({ id: documentAttachments.id }) - .from(documentAttachments) - .where(eq(documentAttachments.fileId, fileInfo.FileId)) - .limit(1) - - if (existingAttachment.length === 0) { - newAttachments++ - } else { - updatedAttachments++ - } + // FS Category 문서의 첨부파일 확인 + if (detailDoc.Category === 'FS' && detailDoc.UploadId) { + try { + const fileInfos = await this.fetchFileInfoFromDOLCE(detailDoc.UploadId) + availableAttachments += fileInfos.filter(f => f.UseYn === 'Y').length + + for (const fileInfo of fileInfos) { + if (fileInfo.UseYn !== 'Y') continue + + const existingAttachment = await db + .select({ id: documentAttachments.id }) + .from(documentAttachments) + .where(eq(documentAttachments.fileId, fileInfo.FileId)) + .limit(1) + + if (existingAttachment.length === 0) { + newAttachments++ + } else { + updatedAttachments++ } - } catch (error) { - console.warn(`Failed to check files for ${detailDoc.UploadId}:`, error) } + } catch (error) { + console.warn(`Failed to check files for ${detailDoc.UploadId}:`, error) } } - } catch (error) { - console.warn(`Failed to check revisions for ${externalDoc.DrawingNo}:`, error) } + } catch (error) { + console.warn(`Failed to check revisions for ${externalDoc.DrawingNo}:`, error) } - } catch (error) { - console.warn(`Failed to check ${drawingKind} for status:`, error) } + } catch (error) { + console.warn(`Failed to check ${drawingKind} for status:`, error) } - } catch (error) { - console.warn(`Failed to fetch external data for status: ${error}`) } + } catch (error) { + console.warn(`Failed to fetch external data for status: ${error}`) + // 🔥 외부 API 호출 실패 시에도 기본값 반환 + } - return { - lastImportAt: lastImport?.lastSynced ? new Date(lastImport.lastSynced).toISOString() : undefined, - availableDocuments, - newDocuments, - updatedDocuments, - availableRevisions, - newRevisions, - updatedRevisions, - availableAttachments, - newAttachments, - updatedAttachments, - importEnabled: this.isImportEnabled(sourceSystem) - } + return { + lastImportAt: lastImport?.lastSynced ? new Date(lastImport.lastSynced).toISOString() : undefined, + availableDocuments, + newDocuments, + updatedDocuments, + availableRevisions, + newRevisions, + updatedRevisions, + availableAttachments, + newAttachments, + updatedAttachments, + importEnabled: this.isImportEnabled(sourceSystem) + } - } catch (error) { - console.error('Failed to get import status:', error) - throw error + } catch (error) { + // 🔥 최종적으로 모든 에러를 catch하여 안전한 기본값 반환 + console.error('Failed to get import status:', error) + return { + lastImportAt: undefined, + availableDocuments: 0, + newDocuments: 0, + updatedDocuments: 0, + availableRevisions: 0, + newRevisions: 0, + updatedRevisions: 0, + availableAttachments: 0, + newAttachments: 0, + updatedAttachments: 0, + importEnabled: false, + error: error instanceof Error ? error.message : 'Unknown error occurred' } } +} /** * 가져오기 활성화 여부 확인 diff --git a/lib/vendor-document-list/ship/enhanced-doc-table-columns.tsx b/lib/vendor-document-list/ship/enhanced-doc-table-columns.tsx index 9c13573c..51c104dc 100644 --- a/lib/vendor-document-list/ship/enhanced-doc-table-columns.tsx +++ b/lib/vendor-document-list/ship/enhanced-doc-table-columns.tsx @@ -59,7 +59,7 @@ export function getSimplifiedDocumentColumns({ id: "select", header: ({ table }) => (
- 선택 + Select
), cell: ({ row }) => { @@ -78,7 +78,7 @@ export function getSimplifiedDocumentColumns({ { accessorKey: "docNumber", header: ({ column }) => ( - + ), cell: ({ row }) => { const doc = row.original @@ -90,7 +90,7 @@ export function getSimplifiedDocumentColumns({ size: 120, enableResizing: true, meta: { - excelHeader: "문서번호" + excelHeader: "Document No" }, }, @@ -98,7 +98,7 @@ export function getSimplifiedDocumentColumns({ { accessorKey: "title", header: ({ column }) => ( - + ), cell: ({ row }) => { const doc = row.original @@ -110,7 +110,7 @@ export function getSimplifiedDocumentColumns({ enableResizing: true, maxSize:300, meta: { - excelHeader: "문서명" + excelHeader: "Title" }, }, @@ -118,7 +118,7 @@ export function getSimplifiedDocumentColumns({ { accessorKey: "projectCode", header: ({ column }) => ( - + ), cell: ({ row }) => { const projectCode = row.original.projectCode @@ -131,7 +131,7 @@ export function getSimplifiedDocumentColumns({ maxSize:100, meta: { - excelHeader: "프로젝트" + excelHeader: "Project" }, }, @@ -141,7 +141,7 @@ export function getSimplifiedDocumentColumns({ header: ({ table }) => { // 첫 번째 행의 firstStageName을 그룹 헤더로 사용 const firstRow = table.getRowModel().rows[0]?.original - const stageName = firstRow?.firstStageName || "1차 스테이지" + const stageName = firstRow?.firstStageName || "First Stage" return (
{stageName} @@ -152,27 +152,27 @@ export function getSimplifiedDocumentColumns({ { accessorKey: "firstStagePlanDate", header: ({ column }) => ( - + ), cell: ({ row }) => { return }, enableResizing: true, meta: { - excelHeader: "1차 계획일" + excelHeader: "First Planned Date" }, }, { accessorKey: "firstStageActualDate", header: ({ column }) => ( - + ), cell: ({ row }) => { return }, enableResizing: true, meta: { - excelHeader: "1차 실제일" + excelHeader: "First Actual Date" }, }, ], @@ -184,7 +184,7 @@ export function getSimplifiedDocumentColumns({ header: ({ table }) => { // 첫 번째 행의 secondStageName을 그룹 헤더로 사용 const firstRow = table.getRowModel().rows[0]?.original - const stageName = firstRow?.secondStageName || "2차 스테이지" + const stageName = firstRow?.secondStageName || "Second Stage" return (
{stageName} @@ -195,27 +195,27 @@ export function getSimplifiedDocumentColumns({ { accessorKey: "secondStagePlanDate", header: ({ column }) => ( - + ), cell: ({ row }) => { return }, enableResizing: true, meta: { - excelHeader: "2차 계획일" + excelHeader: "Second Planned Date" }, }, { accessorKey: "secondStageActualDate", header: ({ column }) => ( - + ), cell: ({ row }) => { return }, enableResizing: true, meta: { - excelHeader: "2차 실제일" + excelHeader: "Second Actual Date" }, }, ], @@ -225,7 +225,7 @@ export function getSimplifiedDocumentColumns({ { accessorKey: "attachmentCount", header: ({ column }) => ( - + ), cell: ({ row }) => { const count = row.original.attachmentCount || 0 @@ -237,7 +237,7 @@ export function getSimplifiedDocumentColumns({ size: 60, enableResizing: true, meta: { - excelHeader: "첨부파일" + excelHeader: "Attachments" }, }, @@ -245,7 +245,7 @@ export function getSimplifiedDocumentColumns({ { accessorKey: "updatedAt", header: ({ column }) => ( - + ), cell: ({ cell, row }) => { return ( @@ -254,7 +254,7 @@ export function getSimplifiedDocumentColumns({ }, enableResizing: true, meta: { - excelHeader: "업데이트" + excelHeader: "Updated" }, }, diff --git a/lib/vendor-document-list/ship/enhanced-documents-table.tsx b/lib/vendor-document-list/ship/enhanced-documents-table.tsx index 2354a9be..9885c027 100644 --- a/lib/vendor-document-list/ship/enhanced-documents-table.tsx +++ b/lib/vendor-document-list/ship/enhanced-documents-table.tsx @@ -25,17 +25,17 @@ import { EnhancedDocTableToolbarActions } from "./enhanced-doc-table-toolbar-act const DRAWING_KIND_INFO = { B3: { title: "B3 Vendor", - description: "Approval → Work 단계로 진행되는 승인 중심 도면", + description: "Approval-focused drawings progressing through Approval → Work stages", color: "bg-blue-50 text-blue-700 border-blue-200" }, B4: { title: "B4 GTT", - description: "Pre → Work 단계로 진행되는 DOLCE 연동 도면", + description: "DOLCE-integrated drawings progressing through Pre → Work stages", color: "bg-green-50 text-green-700 border-green-200" }, B5: { title: "B5 FMEA", - description: "First → Second 단계로 진행되는 순차적 도면", + description: "Sequential drawings progressing through First → Second stages", color: "bg-purple-50 text-purple-700 border-purple-200" } } as const @@ -79,22 +79,22 @@ export function SimplifiedDocumentsTable({ const advancedFilterFields: DataTableAdvancedFilterField[] = [ { id: "docNumber", - label: "문서번호", - type: "text", - }, - { - id: "vendorDocNumber", - label: "벤더 문서번호", + label: "Document No", type: "text", }, + // { + // id: "vendorDocNumber", + // label: "Vendor Document No", + // type: "text", + // }, { id: "title", - label: "문서제목", + label: "Document Title", type: "text", }, { id: "drawingKind", - label: "문서종류", + label: "Document Type", type: "select", options: [ { label: "B3", value: "B3" }, @@ -104,78 +104,78 @@ export function SimplifiedDocumentsTable({ }, { id: "projectCode", - label: "프로젝트 코드", + label: "Project Code", type: "text", }, { id: "vendorName", - label: "벤더명", + label: "Vendor Name", type: "text", }, { id: "vendorCode", - label: "벤더 코드", + label: "Vendor Code", type: "text", }, { id: "pic", - label: "담당자", + label: "PIC", type: "text", }, { id: "status", - label: "문서 상태", + label: "Document Status", type: "select", options: [ - { label: "활성", value: "ACTIVE" }, - { label: "비활성", value: "INACTIVE" }, - { label: "보류", value: "PENDING" }, - { label: "완료", value: "COMPLETED" }, + { label: "Active", value: "ACTIVE" }, + { label: "Inactive", value: "INACTIVE" }, + { label: "Pending", value: "PENDING" }, + { label: "Completed", value: "COMPLETED" }, ], }, { id: "firstStageName", - label: "1차 스테이지", + label: "First Stage", type: "text", }, { id: "secondStageName", - label: "2차 스테이지", + label: "Second Stage", type: "text", }, { id: "firstStagePlanDate", - label: "1차 계획일", + label: "First Planned Date", type: "date", }, { id: "firstStageActualDate", - label: "1차 실제일", + label: "First Actual Date", type: "date", }, { id: "secondStagePlanDate", - label: "2차 계획일", + label: "Second Planned Date", type: "date", }, { id: "secondStageActualDate", - label: "2차 실제일", + label: "Second Actual Date", type: "date", }, { id: "issuedDate", - label: "발행일", + label: "Issue Date", type: "date", }, { id: "createdAt", - label: "생성일", + label: "Created Date", type: "date", }, { id: "updatedAt", - label: "수정일", + label: "Updated Date", type: "date", }, ] @@ -184,32 +184,32 @@ export function SimplifiedDocumentsTable({ const b4FilterFields: DataTableAdvancedFilterField[] = [ { id: "cGbn", - label: "C 구분", + label: "C Category", type: "text", }, { id: "dGbn", - label: "D 구분", + label: "D Category", type: "text", }, { id: "degreeGbn", - label: "Degree 구분", + label: "Degree Category", type: "text", }, { id: "deptGbn", - label: "Dept 구분", + label: "Dept Category", type: "text", }, { id: "jGbn", - label: "J 구분", + label: "J Category", type: "text", }, { id: "sGbn", - label: "S 구분", + label: "S Category", type: "text", }, ] @@ -246,17 +246,17 @@ export function SimplifiedDocumentsTable({ {kindInfo && (
- + {/* {kindInfo.title} {kindInfo.description} - + */}
- {total}개 문서 + {total} documents
diff --git a/lib/vendor-document-list/ship/import-from-dolce-button.tsx b/lib/vendor-document-list/ship/import-from-dolce-button.tsx index d4728d22..de9e63bc 100644 --- a/lib/vendor-document-list/ship/import-from-dolce-button.tsx +++ b/lib/vendor-document-list/ship/import-from-dolce-button.tsx @@ -72,7 +72,7 @@ export function ImportFromDOLCEButton({ setVendorContractIds(contractIds) } catch (error) { console.error('Failed to fetch vendor contracts:', error) - toast.error('계약 정보를 가져오는데 실패했습니다.') + toast.error('Failed to fetch contract information.') } finally { setLoadingVendorContracts(false) } @@ -142,7 +142,7 @@ export function ImportFromDOLCEButton({ } catch (error) { console.error('Failed to fetch import statuses:', error) - toast.error('상태를 확인할 수 없습니다. 프로젝트 설정을 확인해주세요.') + toast.error('Unable to check status. Please verify project settings.') } finally { setStatusLoading(false) } @@ -230,16 +230,16 @@ export function ImportFromDOLCEButton({ if (totalResult.success) { toast.success( - `DOLCE 가져오기 완료`, + `DOLCE import completed`, { - description: `신규 ${totalResult.newCount}건, 업데이트 ${totalResult.updatedCount}건, 건너뜀 ${totalResult.skippedCount}건 (${contractIds.length}개 계약)` + description: `New ${totalResult.newCount}, Updated ${totalResult.updatedCount}, Skipped ${totalResult.skippedCount} (${contractIds.length} contracts)` } ) } else { toast.error( - `DOLCE 가져오기 부분 실패`, + `DOLCE import partially failed`, { - description: '일부 계약에서 가져오기에 실패했습니다.' + description: 'Some contracts failed to import.' } ) } @@ -252,34 +252,34 @@ export function ImportFromDOLCEButton({ setImportProgress(0) setIsImporting(false) - toast.error('DOLCE 가져오기 실패', { - description: error instanceof Error ? error.message : '알 수 없는 오류가 발생했습니다.' + toast.error('DOLCE import failed', { + description: error instanceof Error ? error.message : 'An unknown error occurred.' }) } } const getStatusBadge = () => { if (loadingVendorContracts) { - return 계약 정보 로딩 중... + return Loading contract information... } if (statusLoading) { - return DOLCE 연결 확인 중... + return Checking DOLCE connection... } if (importStatusMap.size === 0) { - return DOLCE 연결 오류 + return DOLCE Connection Error } if (!totalStats.importEnabled) { - return DOLCE 가져오기 비활성화 + return DOLCE Import Disabled } if (totalStats.newDocuments > 0 || totalStats.updatedDocuments > 0) { return ( - 업데이트 가능 ({contractIds.length}개 계약) + Updates Available ({contractIds.length} contracts) ) } @@ -287,7 +287,7 @@ export function ImportFromDOLCEButton({ return ( - DOLCE와 동기화됨 + Synchronized with DOLCE ) } @@ -316,7 +316,7 @@ export function ImportFromDOLCEButton({ ) : ( )} - DOLCE에서 가져오기 + Import from DOLCE {totalStats.newDocuments + totalStats.updatedDocuments > 0 && (
-

DOLCE 가져오기 상태

+

DOLCE Import Status

- 현재 상태 + Current Status {getStatusBadge()}
@@ -342,15 +342,15 @@ export function ImportFromDOLCEButton({ {/* 계약 소스 표시 */} {allDocuments.length === 0 && vendorContractIds.length > 0 && (
- 문서가 없어서 전체 계약에서 가져오기를 진행합니다. + No documents found, importing from all contracts.
)} {/* 다중 계약 정보 표시 */} {contractIds.length > 1 && (
-
대상 계약
-
{contractIds.length}개 계약
+
Target Contracts
+
{contractIds.length} contracts
Contract IDs: {contractIds.join(', ')}
@@ -363,25 +363,25 @@ export function ImportFromDOLCEButton({
-
신규 문서
-
{totalStats.newDocuments || 0}건
+
New Documents
+
{totalStats.newDocuments || 0}
-
업데이트
-
{totalStats.updatedDocuments || 0}건
+
Updates
+
{totalStats.updatedDocuments || 0}
-
DOLCE 전체 문서 (B3/B4/B5)
-
{totalStats.availableDocuments || 0}건
+
Total DOLCE Documents (B3/B4/B5)
+
{totalStats.availableDocuments || 0}
{/* 각 계약별 세부 정보 (펼치기/접기 가능) */} {contractIds.length > 1 && (
- 계약별 세부 정보 + Details by Contract
{contractIds.map(contractId => { @@ -391,10 +391,10 @@ export function ImportFromDOLCEButton({
Contract {contractId}
{status ? (
- 신규 {status.newDocuments}건, 업데이트 {status.updatedDocuments}건 + New {status.newDocuments}, Updates {status.updatedDocuments}
) : ( -
상태 확인 실패
+
Status check failed
)}
) @@ -417,12 +417,12 @@ export function ImportFromDOLCEButton({ {isImporting ? ( <> - 가져오는 중... + Importing... ) : ( <> - 지금 가져오기 + Import Now )} @@ -448,10 +448,10 @@ export function ImportFromDOLCEButton({ - DOLCE에서 문서 목록 가져오기 + Import Document List from DOLCE - 삼성중공업 DOLCE 시스템에서 최신 문서 목록을 가져옵니다. - {contractIds.length > 1 && ` (${contractIds.length}개 계약 대상)`} + Import the latest document list from Samsung Heavy Industries DOLCE system. + {contractIds.length > 1 && ` (${contractIds.length} contracts targeted)`} @@ -459,20 +459,20 @@ export function ImportFromDOLCEButton({ {totalStats && (
- 가져올 항목 + Items to Import - {totalStats.newDocuments + totalStats.updatedDocuments}건 + {totalStats.newDocuments + totalStats.updatedDocuments}
- 신규 문서와 업데이트된 문서가 포함됩니다. (B3, B4, B5) + Includes new and updated documents (B3, B4, B5).
- B4 문서의 경우 GTTPreDwg, GTTWorkingDwg 이슈 스테이지가 자동 생성됩니다. + For B4 documents, GTTPreDwg and GTTWorkingDwg issue stages will be auto-generated. {contractIds.length > 1 && ( <>
- {contractIds.length}개 계약에서 순차적으로 가져옵니다. + Will import sequentially from {contractIds.length} contracts. )}
@@ -480,7 +480,7 @@ export function ImportFromDOLCEButton({ {isImporting && (
- 진행률 + Progress {importProgress}%
@@ -495,7 +495,7 @@ export function ImportFromDOLCEButton({ onClick={() => setIsDialogOpen(false)} disabled={isImporting} > - 취소 + Cancel diff --git a/lib/vendor-document-list/ship/send-to-shi-button.tsx b/lib/vendor-document-list/ship/send-to-shi-button.tsx index 61893da5..4607c994 100644 --- a/lib/vendor-document-list/ship/send-to-shi-button.tsx +++ b/lib/vendor-document-list/ship/send-to-shi-button.tsx @@ -1,8 +1,8 @@ -// components/sync/send-to-shi-button.tsx (다중 계약 버전) +// components/sync/send-to-shi-button.tsx (최종 완성 버전) "use client" import * as React from "react" -import { Send, Loader2, CheckCircle, AlertTriangle, Settings } from "lucide-react" +import { Send, Loader2, CheckCircle, AlertTriangle, Settings, RefreshCw } from "lucide-react" import { toast } from "sonner" import { Button } from "@/components/ui/button" @@ -22,7 +22,9 @@ import { Badge } from "@/components/ui/badge" import { Progress } from "@/components/ui/progress" import { Separator } from "@/components/ui/separator" import { ScrollArea } from "@/components/ui/scroll-area" -import { useSyncStatus, useTriggerSync } from "@/hooks/use-sync-status" +import { Alert, AlertDescription } from "@/components/ui/alert" +// ✅ 업데이트된 Hook import +import { useClientSyncStatus, useTriggerSync, syncUtils } from "@/hooks/use-sync-status" import type { EnhancedDocument } from "@/types/enhanced-documents" interface SendToSHIButtonProps { @@ -31,13 +33,6 @@ interface SendToSHIButtonProps { projectType: "ship" | "plant" } -interface ContractSyncStatus { - contractId: number - syncStatus: any - isLoading: boolean - error: any -} - export function SendToSHIButton({ documents = [], onSyncComplete, @@ -49,75 +44,45 @@ export function SendToSHIButton({ const targetSystem = projectType === 'ship' ? "DOLCE" : "SWP" - // documents에서 contractId 목록 추출 + // 문서에서 유효한 계약 ID 목록 추출 const documentsContractIds = React.useMemo(() => { - const uniqueIds = [...new Set(documents.map(doc => doc.contractId).filter(Boolean))] + const validIds = documents + .map(doc => doc.contractId) + .filter((id): id is number => typeof id === 'number' && id > 0) + + const uniqueIds = [...new Set(validIds)] return uniqueIds.sort() }, [documents]) - // 각 contract별 동기화 상태 조회 - const contractStatuses = React.useMemo(() => { - return documentsContractIds.map(contractId => { - const { - syncStatus, - isLoading, - error, - refetch - } = useSyncStatus(contractId, targetSystem) - - return { - contractId, - syncStatus, - isLoading, - error, - refetch - } - }) - }, [documentsContractIds, targetSystem]) - - const { - triggerSync, - isLoading: isSyncing, - error: syncError - } = useTriggerSync() - - // 전체 통계 계산 - const totalStats = React.useMemo(() => { - let totalPending = 0 - let totalSynced = 0 - let totalFailed = 0 - let hasError = false - let isLoading = false - - contractStatuses.forEach(({ syncStatus, error, isLoading: loading }) => { - if (error) hasError = true - if (loading) isLoading = true - if (syncStatus) { - totalPending += syncStatus.pendingChanges || 0 - totalSynced += syncStatus.syncedChanges || 0 - totalFailed += syncStatus.failedChanges || 0 - } - }) - - return { - totalPending, - totalSynced, - totalFailed, - hasError, - isLoading, - canSync: totalPending > 0 && !hasError - } - }, [contractStatuses]) + // ✅ 클라이언트 전용 Hook 사용 (서버 사이드 렌더링 호환) + const { contractStatuses, totalStats, refetchAll } = useClientSyncStatus( + documentsContractIds, + targetSystem + ) + + const { triggerSync, isLoading: isSyncing, error: syncError } = useTriggerSync() - // 에러 상태 표시 + // 개발 환경에서 디버깅 정보 React.useEffect(() => { - if (totalStats.hasError) { - console.warn('Failed to load sync status for some contracts') + if (process.env.NODE_ENV === 'development') { + console.log('SendToSHIButton Debug Info:', { + documentsContractIds, + totalStats, + contractStatuses: contractStatuses.map(({ contractId, syncStatus, error }) => ({ + contractId, + pendingChanges: syncStatus?.pendingChanges, + hasError: !!error + })) + }) } - }, [totalStats.hasError]) + }, [documentsContractIds, totalStats, contractStatuses]) + // 동기화 실행 함수 const handleSync = async () => { - if (documentsContractIds.length === 0) return + if (documentsContractIds.length === 0) { + toast.info('동기화할 계약이 없습니다.') + return + } setSyncProgress(0) let successfulSyncs = 0 @@ -127,9 +92,17 @@ export function SendToSHIButton({ const errors: string[] = [] try { - const contractsToSync = contractStatuses.filter( - ({ syncStatus, error }) => !error && syncStatus?.syncEnabled && syncStatus?.pendingChanges > 0 - ) + // 동기화 가능한 계약들만 필터링 + const contractsToSync = contractStatuses.filter(({ syncStatus, error }) => { + if (error) { + console.warn(`Contract ${contractStatuses.find(c => c.error === error)?.contractId} has error:`, error) + return false + } + if (!syncStatus) return false + if (!syncStatus.syncEnabled) return false + if (syncStatus.pendingChanges <= 0) return false + return true + }) if (contractsToSync.length === 0) { toast.info('동기화할 변경사항이 없습니다.') @@ -137,12 +110,15 @@ export function SendToSHIButton({ return } + console.log(`Starting sync for ${contractsToSync.length} contracts`) + // 각 contract별로 순차 동기화 for (let i = 0; i < contractsToSync.length; i++) { const { contractId } = contractsToSync[i] setCurrentSyncingContract(contractId) try { + console.log(`Syncing contract ${contractId}...`) const result = await triggerSync({ contractId, targetSystem @@ -151,17 +127,19 @@ export function SendToSHIButton({ if (result?.success) { successfulSyncs++ totalSuccessCount += result.successCount || 0 + console.log(`Contract ${contractId} sync successful:`, result) } else { failedSyncs++ totalFailureCount += result?.failureCount || 0 - if (result?.errors?.[0]) { - errors.push(`Contract ${contractId}: ${result.errors[0]}`) - } + const errorMsg = result?.errors?.[0] || result?.message || 'Unknown sync error' + errors.push(`Contract ${contractId}: ${errorMsg}`) + console.error(`Contract ${contractId} sync failed:`, result) } } catch (error) { failedSyncs++ const errorMessage = error instanceof Error ? error.message : '알 수 없는 오류' errors.push(`Contract ${contractId}: ${errorMessage}`) + console.error(`Contract ${contractId} sync exception:`, error) } // 진행률 업데이트 @@ -170,6 +148,7 @@ export function SendToSHIButton({ setCurrentSyncingContract(null) + // 결과 처리 및 토스트 표시 setTimeout(() => { setSyncProgress(0) setIsDialogOpen(false) @@ -185,7 +164,7 @@ export function SendToSHIButton({ toast.warning( `부분 동기화 완료: ${successfulSyncs}개 성공, ${failedSyncs}개 실패`, { - description: errors[0] || '일부 계약 동기화에 실패했습니다.' + description: errors.slice(0, 3).join(', ') + (errors.length > 3 ? ' 외 더보기...' : '') } ) } else { @@ -198,7 +177,7 @@ export function SendToSHIButton({ } // 모든 contract 상태 갱신 - contractStatuses.forEach(({ refetch }) => refetch?.()) + refetchAll() onSyncComplete?.() }, 500) @@ -206,19 +185,32 @@ export function SendToSHIButton({ setSyncProgress(0) setCurrentSyncingContract(null) + const errorMessage = syncUtils.formatError(error as any) toast.error('동기화 실패', { - description: error instanceof Error ? error.message : '알 수 없는 오류가 발생했습니다.' + description: errorMessage }) + console.error('Sync process failed:', error) } } + // 동기화 상태에 따른 뱃지 생성 const getSyncStatusBadge = () => { if (totalStats.isLoading) { - return 확인 중... + return ( + + + 확인 중... + + ) } if (totalStats.hasError) { - return 오류 + return ( + + + 연결 오류 + + ) } if (documentsContractIds.length === 0) { @@ -246,10 +238,6 @@ export function SendToSHIButton({ return 변경사항 없음 } - const refreshAllStatuses = () => { - contractStatuses.forEach(({ refetch }) => refetch?.()) - } - return ( <> @@ -258,7 +246,7 @@ export function SendToSHIButton({
- +
-

SHI 동기화 상태

+
+

SHI 동기화 상태

+ +
+
전체 상태 {getSyncStatusBadge()}
+
- {documentsContractIds.length}개 계약 대상 + {documentsContractIds.length}개 계약 대상 • {targetSystem} 시스템
+ {/* 에러 상태 표시 */} + {totalStats.hasError && ( + + + + 일부 계약의 동기화 상태를 확인할 수 없습니다. 네트워크 연결을 확인해주세요. + {process.env.NODE_ENV === 'development' && ( +
+ Debug: {contractStatuses.filter(({ error }) => error).length}개 계약에서 오류 +
+ )} +
+
+ )} + + {/* 정상 상태일 때 통계 표시 */} {!totalStats.hasError && documentsContractIds.length > 0 && (
-
+
대기 중
-
{totalStats.totalPending}건
+
{totalStats.totalPending}건
-
+
동기화됨
-
{totalStats.totalSynced}건
+
{totalStats.totalSynced}건
-
+
실패
{totalStats.totalFailed}건
@@ -319,17 +340,26 @@ export function SendToSHIButton({
{contractStatuses.map(({ contractId, syncStatus, isLoading, error }) => (
- Contract {contractId} + Contract {contractId} {isLoading ? ( - 로딩... + + + 로딩... + ) : error ? ( - 오류 - ) : syncStatus?.pendingChanges > 0 ? ( + + + 오류 + + ) : syncStatus && syncStatus.pendingChanges > 0 ? ( {syncStatus.pendingChanges}건 대기 ) : ( - 동기화됨 + + + 최신 + )}
))} @@ -340,28 +370,18 @@ export function SendToSHIButton({
)} - {totalStats.hasError && ( -
- -
-
연결 오류
-
일부 계약의 동기화 상태를 확인할 수 없습니다.
-
-
- )} - + {/* 계약 정보가 없는 경우 */} {documentsContractIds.length === 0 && ( -
- -
-
계약 정보 없음
-
동기화할 문서가 없습니다.
-
-
+ + + 동기화할 문서가 없습니다. 문서를 선택해주세요. + + )} + {/* 액션 버튼들 */}
{currentSyncingContract && ( -
+
+ 현재 처리 중: Contract {currentSyncingContract}
)} @@ -444,19 +469,20 @@ export function SendToSHIButton({ )} {totalStats.hasError && ( -
-
- 일부 계약의 동기화 상태를 확인할 수 없습니다. 네트워크 연결을 확인해주세요. -
-
+ + + + 일부 계약의 동기화 상태를 확인할 수 없습니다. 네트워크 연결을 확인하고 다시 시도해주세요. + + )} {documentsContractIds.length === 0 && ( -
-
+ + 동기화할 계약이 없습니다. 문서를 선택해주세요. -
-
+ + )}
-- cgit v1.2.3