summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authordujinkim <dujin.kim@dtsolution.co.kr>2025-07-22 02:57:00 +0000
committerdujinkim <dujin.kim@dtsolution.co.kr>2025-07-22 02:57:00 +0000
commitee57cc221ff2edafd3c0f12a181214c602ed257e (patch)
tree148f552f503798f7a350d6eff936b889f16be49f /lib
parent14f61e24947fb92dd71ec0a7196a6e815f8e66da (diff)
(대표님, 최겸) 이메일 템플릿, 벤더데이터 변경사항 대응, 기술영업 변경요구사항 구현
Diffstat (limited to 'lib')
-rw-r--r--lib/dashboard/partners-service.ts28
-rw-r--r--lib/dashboard/service.ts9
-rw-r--r--lib/email-template/editor/template-content-editor.tsx9
-rw-r--r--lib/email-template/service.ts9
-rw-r--r--lib/email-template/table/template-table-columns.tsx14
-rw-r--r--lib/email-template/table/update-template-sheet.tsx26
-rw-r--r--lib/file-stroage.ts2
-rw-r--r--lib/form-list.zipbin12417 -> 0 bytes
-rw-r--r--lib/sedp/get-form-tags.ts124
-rw-r--r--lib/sedp/sync-form.ts18
-rw-r--r--lib/soap/mdg/send/vendor-master/action.ts5
-rw-r--r--lib/tech-vendors/repository.ts1
-rw-r--r--lib/techsales-rfq/table/detail-table/rfq-detail-table.tsx4
-rw-r--r--lib/users/auth/verifyCredentails.ts1
-rw-r--r--lib/users/service.ts176
-rw-r--r--lib/vendor-document-list/dolce-upload-service.ts107
-rw-r--r--lib/vendor-document-list/enhanced-document-service.ts11
-rw-r--r--lib/vendor-document-list/import-service.ts287
-rw-r--r--lib/vendor-document-list/ship/enhanced-doc-table-columns.tsx42
-rw-r--r--lib/vendor-document-list/ship/enhanced-documents-table.tsx76
-rw-r--r--lib/vendor-document-list/ship/import-from-dolce-button.tsx86
-rw-r--r--lib/vendor-document-list/ship/send-to-shi-button.tsx286
22 files changed, 804 insertions, 517 deletions
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<Part
}
});
- console.log('📊 파트너 팀 대시보드 결과:', successfulResults);
return successfulResults;
} catch (error) {
console.error("파트너 팀 대시보드 데이터 조회 실패:", error);
@@ -98,7 +97,6 @@ export async function getPartnersUserDashboardData(domain: string): Promise<Part
return [];
}
- console.log(`👤 사용자 ID: ${userId}, 회사 ID: ${companyId}`);
// 병렬 처리로 성능 향상
const results = await Promise.allSettled(
@@ -176,7 +174,6 @@ export async function getPartnersDashboardData(domain: string): Promise<Partners
// Partners 테이블별 전체 통계 조회 (회사 필터링 포함)
async function getPartnersTableStats(config: TableConfig, companyId: string): Promise<PartnersDashboardStats> {
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<DashboardSta
}
});
- console.log('📊 팀 대시보드 결과:', successfulResults);
return successfulResults;
} catch (error) {
@@ -90,7 +89,6 @@ export async function getUserDashboardData(domain: string): Promise<UserDashboar
return [];
}
- console.log(`👤 사용자 ID: ${userId}`);
// 병렬 처리로 성능 향상
const results = await Promise.allSettled(
@@ -259,7 +257,6 @@ async function getTableStats(config: TableConfig): Promise<DashboardStats> {
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<D
try {
// 사용자 필드가 없는 경우 빈 통계 반환
if (!hasUserFields(config)) {
- console.log(`⚠️ 테이블 ${config.tableName}에 사용자 필드가 없습니다.`);
return createEmptyStats(config);
}
- console.log(`\n👤 사용자 ${userId}의 ${config.tableName} 통계 조회`);
// 사용자 조건 생성
const userConditions = [];
@@ -334,7 +329,6 @@ async function getUserTableStats(config: TableConfig, userId: string): Promise<D
const userPendingResult = await db.execute(sql.raw(userPendingQuery));
userPendingCount = parseInt(userPendingResult.rows[0]?.count || '0');
- console.log("User Pending 개수:", userPendingCount);
}
// User In Progress 개수
@@ -411,16 +405,13 @@ export async function simpleTest(tableName: string, statusField: string) {
ORDER BY count DESC
`;
const statusResult = await db.execute(sql.raw(statusQuery));
- console.log("상태 분포:", statusResult.rows);
// 3. 특정 상태 테스트
const draftQuery = `SELECT COUNT(*) as count FROM "${tableName}" WHERE "${statusField}" = 'DRAFT'`;
const draftResult = await db.execute(sql.raw(draftQuery));
- console.log("DRAFT 개수:", draftResult.rows[0]);
const docConfirmedQuery = `SELECT COUNT(*) as count FROM "${tableName}" WHERE "${statusField}" = 'Doc. Confirmed'`;
const docConfirmedResult = await db.execute(sql.raw(docConfirmedQuery));
- console.log("Doc. Confirmed 개수:", docConfirmedResult.rows[0]);
return {
total: totalResult.rows[0],
diff --git a/lib/email-template/editor/template-content-editor.tsx b/lib/email-template/editor/template-content-editor.tsx
index 4d31753c..08de53d2 100644
--- a/lib/email-template/editor/template-content-editor.tsx
+++ b/lib/email-template/editor/template-content-editor.tsx
@@ -167,7 +167,7 @@ export function TemplateContentEditor({ template, onUpdate }: TemplateContentEdi
subject,
content,
sampleData,
- version: template.version + 1
+ version: template.version ? template.version + 1 :0
})
} else {
toast.error(result.error || '저장에 실패했습니다.')
@@ -188,12 +188,13 @@ export function TemplateContentEditor({ template, onUpdate }: TemplateContentEdi
template.slug,
sampleData,
content,
- // subject // 주석 해제
+ subject // 주석 해제
)
- if (result.success) {
+
+ if (result.success && result.data) {
setPreviewHtml(result.data.html)
- setPreviewSubject(result.data.subject)
+ setPreviewSubject(result.data.subjectHtml)
if (!silent) toast.success('미리보기가 생성되었습니다.')
} else {
if (!silent) toast.error(result.error || '미리보기 생성에 실패했습니다.')
diff --git a/lib/email-template/service.ts b/lib/email-template/service.ts
index 13aba77b..e3ab9bed 100644
--- a/lib/email-template/service.ts
+++ b/lib/email-template/service.ts
@@ -789,7 +789,7 @@ export async function updateTemplateAction(slug: string, data: {
content?: string;
description?: string;
sampleData?: Record<string, any>;
- updatedBy: string;
+ updatedBy: number;
}) {
try {
if (data.content) {
@@ -850,14 +850,17 @@ export async function previewTemplateAction(
slug: string,
data: Record<string, any>,
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<Templat
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-40">
<DropdownMenuItem asChild>
- <Link href={`/evcp/templates/${template.slug}`}>
+ <Link href={`/evcp/email-template/${template.slug}`}>
<Eye className="mr-2 size-4" aria-hidden="true" />
- 보기
+ 상세 보기
</Link>
</DropdownMenuItem>
- <DropdownMenuItem
+ {/* <DropdownMenuItem
onClick={() => {
setRowAction({ type: "update", row })
}}
>
<Edit className="mr-2 size-4" aria-hidden="true" />
- 수정
- </DropdownMenuItem>
+ 업데이트
+ </DropdownMenuItem> */}
<DropdownMenuItem
onClick={() => {
@@ -269,7 +269,7 @@ export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<Templat
}}
>
<Copy className="mr-2 size-4" aria-hidden="true" />
- 복제
+ 복제하기
</DropdownMenuItem>
<DropdownMenuSeparator />
@@ -281,7 +281,7 @@ export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<Templat
className="text-destructive focus:text-destructive"
>
<Trash className="mr-2 size-4" aria-hidden="true" />
- 삭제
+ 삭제하기
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
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<UpdateTemplateSchema>({
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
</SelectTrigger>
</FormControl>
<SelectContent>
- <SelectItem value="">카테고리 없음</SelectItem>
- {TEMPLATE_CATEGORY_OPTIONS.map((option) => (
- <SelectItem key={option.value} value={option.value}>
- {option.label}
- </SelectItem>
- ))}
- </SelectContent>
+ <SelectItem value="none">카테고리 없음</SelectItem>
+ {TEMPLATE_CATEGORY_OPTIONS.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+</SelectContent>
</Select>
<FormMessage />
</FormItem>
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
--- a/lib/form-list.zip
+++ /dev/null
Binary files 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<Register[]> {
}
// 결과를 배열로 변환 (단일 객체인 경우 배열로 래핑)
- 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}
/>
- {/* 다중 벤더 삭제 확인 다이얼로그 */}
+ {/* 다중 벤더 삭제 확인 다이얼로그
<DeleteVendorDialog
open={deleteConfirmDialogOpen}
onOpenChange={setDeleteConfirmDialogOpen}
vendors={selectedRows}
onConfirm={executeDeleteVendors}
isLoading={isDeletingVendors}
- />
+ /> */}
{/* 견적 히스토리 다이얼로그 */}
<QuotationHistoryDialog
diff --git a/lib/users/auth/verifyCredentails.ts b/lib/users/auth/verifyCredentails.ts
index 83a2f276..a5dbab41 100644
--- a/lib/users/auth/verifyCredentails.ts
+++ b/lib/users/auth/verifyCredentails.ts
@@ -3,6 +3,7 @@
import bcrypt from 'bcryptjs';
import crypto from 'crypto';
+// (처리 불필요) 키 암호화를 위한 fs 모듈 사용, 형제 경로 사용하며 public 경로 아니므로 파일이 노출되지 않음.
import fs from 'fs';
import path from 'path';
import { eq, and, desc, gte, count } from 'drizzle-orm';
diff --git a/lib/users/service.ts b/lib/users/service.ts
index 7a635113..80c346fa 100644
--- a/lib/users/service.ts
+++ b/lib/users/service.ts
@@ -5,7 +5,6 @@ import { Otp } from '@/types/user';
import { getAllUsers, createUser, getUserById, updateUser, deleteUser, getUserByEmail, createOtp,getOtpByEmailAndToken, updateOtp, findOtpByEmail ,getOtpByEmailAndCode, findAllRoles, getRoleAssignedUsers} from './repository';
import logger from '@/lib/logger';
import { Role, roles, userRoles, users, userView, type User } from '@/db/schema/users';
-import { saveDocument } from '../storage';
import { GetSimpleUsersSchema, GetUsersSchema } from '../admin-users/validations';
import { revalidatePath, revalidateTag, unstable_cache, unstable_noStore } from 'next/cache';
import { filterColumns } from '../filter-columns';
@@ -15,6 +14,7 @@ import { getErrorMessage } from "@/lib/handle-error";
import { getServerSession } from "next-auth/next"
import { authOptions } from "@/app/api/auth/[...nextauth]/route"
import { and, or, desc, asc, ilike, eq, isNull, sql, count, inArray, ne } from "drizzle-orm";
+import { SaveFileResult, saveFile } from '../file-stroage';
interface AssignUsersArgs {
roleId: number
@@ -232,41 +232,159 @@ export async function findEmailTemp(email: string) {
}
}
-export async function updateUserProfileImage(formData: FormData) {
+/**
+ * 프로필 업데이트 결과 인터페이스
+ */
+interface ProfileUpdateResult {
+ success: boolean;
+ user?: any;
+ error?: string;
+ duration?: number;
+ fileInfo?: {
+ fileName: string;
+ originalName: string;
+ fileSize: string;
+ publicPath: string;
+ };
+ securityChecks?: {
+ extensionCheck: boolean;
+ fileNameCheck: boolean;
+ sizeCheck: boolean;
+ mimeTypeCheck: boolean;
+ contentCheck: boolean;
+ };
+}
+
+/**
+ * 사용자 데이터 검증 (프로필 업데이트용)
+ */
+const validateUserData = {
+ validateEmail(email: string): boolean {
+ const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
+ return emailRegex.test(email);
+ },
+
+ validateName(name: string): boolean {
+ return name.length >= 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<ProfileUpdateResult> {
+ 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<Array<{ uploadId: string, fileId: string, filePath: string }>> {
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<void> {
+ 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<ImportStatus> {
- try {
- // 마지막 가져오기 시간 조회
- const [lastImport] = await db
- .select({
- lastSynced: sql<string>`MAX(${documents.externalSyncedAt})`
- })
- .from(documents)
- .where(and(
- eq(documents.contractId, contractId),
- eq(documents.externalSystemType, sourceSystem)
- ))
+ /**
+ * 가져오기 상태 조회 - 에러 시 안전한 기본값 반환
+ */
+async getImportStatus(
+ contractId: number,
+ sourceSystem: string = 'DOLCE'
+): Promise<ImportStatus> {
+ try {
+ // 마지막 가져오기 시간 조회
+ const [lastImport] = await db
+ .select({
+ lastSynced: sql<string>`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 }) => (
<div className="flex items-center justify-center">
- <span className="text-xs text-gray-500">선택</span>
+ <span className="text-xs text-gray-500">Select</span>
</div>
),
cell: ({ row }) => {
@@ -78,7 +78,7 @@ export function getSimplifiedDocumentColumns({
{
accessorKey: "docNumber",
header: ({ column }) => (
- <DataTableColumnHeaderSimple column={column} title="문서번호" />
+ <DataTableColumnHeaderSimple column={column} title="Document No" />
),
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 }) => (
- <DataTableColumnHeaderSimple column={column} title="문서명" />
+ <DataTableColumnHeaderSimple column={column} title="Title" />
),
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 }) => (
- <DataTableColumnHeaderSimple column={column} title="프로젝트" />
+ <DataTableColumnHeaderSimple column={column} title="Project" />
),
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 (
<div className="text-center font-medium text-gray-700">
{stageName}
@@ -152,27 +152,27 @@ export function getSimplifiedDocumentColumns({
{
accessorKey: "firstStagePlanDate",
header: ({ column }) => (
- <DataTableColumnHeaderSimple column={column} title="계획일" />
+ <DataTableColumnHeaderSimple column={column} title="Planned Date" />
),
cell: ({ row }) => {
return <FirstStagePlanDateCell row={row} />
},
enableResizing: true,
meta: {
- excelHeader: "1차 계획일"
+ excelHeader: "First Planned Date"
},
},
{
accessorKey: "firstStageActualDate",
header: ({ column }) => (
- <DataTableColumnHeaderSimple column={column} title="실제일" />
+ <DataTableColumnHeaderSimple column={column} title="Actual Date" />
),
cell: ({ row }) => {
return <FirstStageActualDateCell row={row} />
},
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 (
<div className="text-center font-medium text-gray-700">
{stageName}
@@ -195,27 +195,27 @@ export function getSimplifiedDocumentColumns({
{
accessorKey: "secondStagePlanDate",
header: ({ column }) => (
- <DataTableColumnHeaderSimple column={column} title="계획일" />
+ <DataTableColumnHeaderSimple column={column} title="Planned Date" />
),
cell: ({ row }) => {
return <SecondStagePlanDateCell row={row} />
},
enableResizing: true,
meta: {
- excelHeader: "2차 계획일"
+ excelHeader: "Second Planned Date"
},
},
{
accessorKey: "secondStageActualDate",
header: ({ column }) => (
- <DataTableColumnHeaderSimple column={column} title="실제일" />
+ <DataTableColumnHeaderSimple column={column} title="Actual Date" />
),
cell: ({ row }) => {
return <SecondStageActualDateCell row={row} />
},
enableResizing: true,
meta: {
- excelHeader: "2차 실제일"
+ excelHeader: "Second Actual Date"
},
},
],
@@ -225,7 +225,7 @@ export function getSimplifiedDocumentColumns({
{
accessorKey: "attachmentCount",
header: ({ column }) => (
- <DataTableColumnHeaderSimple column={column} title="파일" />
+ <DataTableColumnHeaderSimple column={column} title="Files" />
),
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 }) => (
- <DataTableColumnHeaderSimple column={column} title="업데이트" />
+ <DataTableColumnHeaderSimple column={column} title="Updated" />
),
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<SimplifiedDocumentsView>[] = [
{
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<SimplifiedDocumentsView>[] = [
{
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 && (
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
- <Badge variant="default" className="flex items-center gap-1 text-sm">
+ {/* <Badge variant="default" className="flex items-center gap-1 text-sm">
<FileText className="w-4 h-4" />
{kindInfo.title}
</Badge>
<span className="text-sm text-muted-foreground">
{kindInfo.description}
- </span>
+ </span> */}
</div>
<div className="flex items-center gap-2">
<Badge variant="outline">
- {total}개 문서
+ {total} documents
</Badge>
</div>
</div>
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 <Badge variant="secondary">계약 정보 로딩 중...</Badge>
+ return <Badge variant="secondary">Loading contract information...</Badge>
}
if (statusLoading) {
- return <Badge variant="secondary">DOLCE 연결 확인 중...</Badge>
+ return <Badge variant="secondary">Checking DOLCE connection...</Badge>
}
if (importStatusMap.size === 0) {
- return <Badge variant="destructive">DOLCE 연결 오류</Badge>
+ return <Badge variant="destructive">DOLCE Connection Error</Badge>
}
if (!totalStats.importEnabled) {
- return <Badge variant="secondary">DOLCE 가져오기 비활성화</Badge>
+ return <Badge variant="secondary">DOLCE Import Disabled</Badge>
}
if (totalStats.newDocuments > 0 || totalStats.updatedDocuments > 0) {
return (
<Badge variant="samsung" className="gap-1">
<AlertTriangle className="w-3 h-3" />
- 업데이트 가능 ({contractIds.length}개 계약)
+ Updates Available ({contractIds.length} contracts)
</Badge>
)
}
@@ -287,7 +287,7 @@ export function ImportFromDOLCEButton({
return (
<Badge variant="default" className="gap-1 bg-green-500 hover:bg-green-600">
<CheckCircle className="w-3 h-3" />
- DOLCE와 동기화됨
+ Synchronized with DOLCE
</Badge>
)
}
@@ -316,7 +316,7 @@ export function ImportFromDOLCEButton({
) : (
<Download className="w-4 h-4" />
)}
- <span className="hidden sm:inline">DOLCE에서 가져오기</span>
+ <span className="hidden sm:inline">Import from DOLCE</span>
{totalStats.newDocuments + totalStats.updatedDocuments > 0 && (
<Badge
variant="samsung"
@@ -332,9 +332,9 @@ export function ImportFromDOLCEButton({
<PopoverContent className="w-96">
<div className="space-y-4">
<div className="space-y-2">
- <h4 className="font-medium">DOLCE 가져오기 상태</h4>
+ <h4 className="font-medium">DOLCE Import Status</h4>
<div className="flex items-center justify-between">
- <span className="text-sm text-muted-foreground">현재 상태</span>
+ <span className="text-sm text-muted-foreground">Current Status</span>
{getStatusBadge()}
</div>
</div>
@@ -342,15 +342,15 @@ export function ImportFromDOLCEButton({
{/* 계약 소스 표시 */}
{allDocuments.length === 0 && vendorContractIds.length > 0 && (
<div className="text-xs text-blue-600 bg-blue-50 p-2 rounded">
- 문서가 없어서 전체 계약에서 가져오기를 진행합니다.
+ No documents found, importing from all contracts.
</div>
)}
{/* 다중 계약 정보 표시 */}
{contractIds.length > 1 && (
<div className="text-sm">
- <div className="text-muted-foreground">대상 계약</div>
- <div className="font-medium">{contractIds.length}개 계약</div>
+ <div className="text-muted-foreground">Target Contracts</div>
+ <div className="font-medium">{contractIds.length} contracts</div>
<div className="text-xs text-muted-foreground">
Contract IDs: {contractIds.join(', ')}
</div>
@@ -363,25 +363,25 @@ export function ImportFromDOLCEButton({
<div className="grid grid-cols-2 gap-4 text-sm">
<div>
- <div className="text-muted-foreground">신규 문서</div>
- <div className="font-medium">{totalStats.newDocuments || 0}건</div>
+ <div className="text-muted-foreground">New Documents</div>
+ <div className="font-medium">{totalStats.newDocuments || 0}</div>
</div>
<div>
- <div className="text-muted-foreground">업데이트</div>
- <div className="font-medium">{totalStats.updatedDocuments || 0}건</div>
+ <div className="text-muted-foreground">Updates</div>
+ <div className="font-medium">{totalStats.updatedDocuments || 0}</div>
</div>
</div>
<div className="text-sm">
- <div className="text-muted-foreground">DOLCE 전체 문서 (B3/B4/B5)</div>
- <div className="font-medium">{totalStats.availableDocuments || 0}건</div>
+ <div className="text-muted-foreground">Total DOLCE Documents (B3/B4/B5)</div>
+ <div className="font-medium">{totalStats.availableDocuments || 0}</div>
</div>
{/* 각 계약별 세부 정보 (펼치기/접기 가능) */}
{contractIds.length > 1 && (
<details className="text-sm">
<summary className="cursor-pointer text-muted-foreground hover:text-foreground">
- 계약별 세부 정보
+ Details by Contract
</summary>
<div className="mt-2 space-y-2 pl-2 border-l-2 border-muted">
{contractIds.map(contractId => {
@@ -391,10 +391,10 @@ export function ImportFromDOLCEButton({
<div className="font-medium">Contract {contractId}</div>
{status ? (
<div className="text-muted-foreground">
- 신규 {status.newDocuments}건, 업데이트 {status.updatedDocuments}건
+ New {status.newDocuments}, Updates {status.updatedDocuments}
</div>
) : (
- <div className="text-destructive">상태 확인 실패</div>
+ <div className="text-destructive">Status check failed</div>
)}
</div>
)
@@ -417,12 +417,12 @@ export function ImportFromDOLCEButton({
{isImporting ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
- 가져오는 중...
+ Importing...
</>
) : (
<>
<Download className="w-4 h-4 mr-2" />
- 지금 가져오기
+ Import Now
</>
)}
</Button>
@@ -448,10 +448,10 @@ export function ImportFromDOLCEButton({
<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
- <DialogTitle>DOLCE에서 문서 목록 가져오기</DialogTitle>
+ <DialogTitle>Import Document List from DOLCE</DialogTitle>
<DialogDescription>
- 삼성중공업 DOLCE 시스템에서 최신 문서 목록을 가져옵니다.
- {contractIds.length > 1 && ` (${contractIds.length}개 계약 대상)`}
+ Import the latest document list from Samsung Heavy Industries DOLCE system.
+ {contractIds.length > 1 && ` (${contractIds.length} contracts targeted)`}
</DialogDescription>
</DialogHeader>
@@ -459,20 +459,20 @@ export function ImportFromDOLCEButton({
{totalStats && (
<div className="rounded-lg border p-4 space-y-3">
<div className="flex items-center justify-between text-sm">
- <span>가져올 항목</span>
+ <span>Items to Import</span>
<span className="font-medium">
- {totalStats.newDocuments + totalStats.updatedDocuments}건
+ {totalStats.newDocuments + totalStats.updatedDocuments}
</span>
</div>
<div className="text-xs text-muted-foreground">
- 신규 문서와 업데이트된 문서가 포함됩니다. (B3, B4, B5)
+ Includes new and updated documents (B3, B4, B5).
<br />
- B4 문서의 경우 GTTPreDwg, GTTWorkingDwg 이슈 스테이지가 자동 생성됩니다.
+ For B4 documents, GTTPreDwg and GTTWorkingDwg issue stages will be auto-generated.
{contractIds.length > 1 && (
<>
<br />
- {contractIds.length}개 계약에서 순차적으로 가져옵니다.
+ Will import sequentially from {contractIds.length} contracts.
</>
)}
</div>
@@ -480,7 +480,7 @@ export function ImportFromDOLCEButton({
{isImporting && (
<div className="space-y-2">
<div className="flex items-center justify-between text-sm">
- <span>진행률</span>
+ <span>Progress</span>
<span>{importProgress}%</span>
</div>
<Progress value={importProgress} className="h-2" />
@@ -495,7 +495,7 @@ export function ImportFromDOLCEButton({
onClick={() => setIsDialogOpen(false)}
disabled={isImporting}
>
- 취소
+ Cancel
</Button>
<Button
onClick={handleImport}
@@ -504,12 +504,12 @@ export function ImportFromDOLCEButton({
{isImporting ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
- 가져오는 중...
+ Importing...
</>
) : (
<>
<Download className="w-4 h-4 mr-2" />
- 가져오기 시작
+ Start Import
</>
)}
</Button>
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 <Badge variant="secondary">확인 중...</Badge>
+ return (
+ <Badge variant="secondary" className="gap-1">
+ <Loader2 className="w-3 h-3 animate-spin" />
+ 확인 중...
+ </Badge>
+ )
}
if (totalStats.hasError) {
- return <Badge variant="destructive">오류</Badge>
+ return (
+ <Badge variant="destructive" className="gap-1">
+ <AlertTriangle className="w-3 h-3" />
+ 연결 오류
+ </Badge>
+ )
}
if (documentsContractIds.length === 0) {
@@ -246,10 +238,6 @@ export function SendToSHIButton({
return <Badge variant="secondary">변경사항 없음</Badge>
}
- const refreshAllStatuses = () => {
- contractStatuses.forEach(({ refetch }) => refetch?.())
- }
-
return (
<>
<Popover>
@@ -258,7 +246,7 @@ export function SendToSHIButton({
<Button
variant="default"
size="sm"
- className="flex items-center bg-blue-600 hover:bg-blue-700"
+ className="flex items-center gap-2 bg-blue-600 hover:bg-blue-700"
disabled={isSyncing || totalStats.isLoading || documentsContractIds.length === 0}
>
{isSyncing ? (
@@ -270,7 +258,7 @@ export function SendToSHIButton({
{totalStats.totalPending > 0 && (
<Badge
variant="destructive"
- className="h-5 w-5 p-0 text-xs flex items-center justify-center"
+ className="h-5 w-5 p-0 text-xs flex items-center justify-center ml-1"
>
{totalStats.totalPending}
</Badge>
@@ -279,33 +267,66 @@ export function SendToSHIButton({
</div>
</PopoverTrigger>
- <PopoverContent className="w-96">
+ <PopoverContent className="w-96" align="end">
<div className="space-y-4">
<div className="space-y-2">
- <h4 className="font-medium">SHI 동기화 상태</h4>
+ <div className="flex items-center justify-between">
+ <h4 className="font-medium">SHI 동기화 상태</h4>
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={refetchAll}
+ disabled={totalStats.isLoading}
+ className="h-6 w-6 p-0"
+ >
+ {totalStats.isLoading ? (
+ <Loader2 className="w-3 h-3 animate-spin" />
+ ) : (
+ <RefreshCw className="w-3 h-3" />
+ )}
+ </Button>
+ </div>
+
<div className="flex items-center justify-between">
<span className="text-sm text-muted-foreground">전체 상태</span>
{getSyncStatusBadge()}
</div>
+
<div className="text-xs text-muted-foreground">
- {documentsContractIds.length}개 계약 대상
+ {documentsContractIds.length}개 계약 대상 • {targetSystem} 시스템
</div>
</div>
+ {/* 에러 상태 표시 */}
+ {totalStats.hasError && (
+ <Alert variant="destructive">
+ <AlertTriangle className="h-4 w-4" />
+ <AlertDescription>
+ 일부 계약의 동기화 상태를 확인할 수 없습니다. 네트워크 연결을 확인해주세요.
+ {process.env.NODE_ENV === 'development' && (
+ <div className="text-xs mt-1 font-mono">
+ Debug: {contractStatuses.filter(({ error }) => error).length}개 계약에서 오류
+ </div>
+ )}
+ </AlertDescription>
+ </Alert>
+ )}
+
+ {/* 정상 상태일 때 통계 표시 */}
{!totalStats.hasError && documentsContractIds.length > 0 && (
<div className="space-y-3">
<Separator />
<div className="grid grid-cols-3 gap-4 text-sm">
- <div>
+ <div className="text-center">
<div className="text-muted-foreground">대기 중</div>
- <div className="font-medium">{totalStats.totalPending}건</div>
+ <div className="font-medium text-orange-600">{totalStats.totalPending}건</div>
</div>
- <div>
+ <div className="text-center">
<div className="text-muted-foreground">동기화됨</div>
- <div className="font-medium">{totalStats.totalSynced}건</div>
+ <div className="font-medium text-green-600">{totalStats.totalSynced}건</div>
</div>
- <div>
+ <div className="text-center">
<div className="text-muted-foreground">실패</div>
<div className="font-medium text-red-600">{totalStats.totalFailed}건</div>
</div>
@@ -319,17 +340,26 @@ export function SendToSHIButton({
<div className="space-y-2">
{contractStatuses.map(({ contractId, syncStatus, isLoading, error }) => (
<div key={contractId} className="flex items-center justify-between text-xs p-2 rounded border">
- <span>Contract {contractId}</span>
+ <span className="font-medium">Contract {contractId}</span>
{isLoading ? (
- <Badge variant="secondary" className="text-xs">로딩...</Badge>
+ <Badge variant="secondary" className="text-xs">
+ <Loader2 className="w-3 h-3 mr-1 animate-spin" />
+ 로딩...
+ </Badge>
) : error ? (
- <Badge variant="destructive" className="text-xs">오류</Badge>
- ) : syncStatus?.pendingChanges > 0 ? (
+ <Badge variant="destructive" className="text-xs">
+ <AlertTriangle className="w-3 h-3 mr-1" />
+ 오류
+ </Badge>
+ ) : syncStatus && syncStatus.pendingChanges > 0 ? (
<Badge variant="destructive" className="text-xs">
{syncStatus.pendingChanges}건 대기
</Badge>
) : (
- <Badge variant="secondary" className="text-xs">동기화됨</Badge>
+ <Badge variant="secondary" className="text-xs">
+ <CheckCircle className="w-3 h-3 mr-1" />
+ 최신
+ </Badge>
)}
</div>
))}
@@ -340,28 +370,18 @@ export function SendToSHIButton({
</div>
)}
- {totalStats.hasError && (
- <div className="space-y-2">
- <Separator />
- <div className="text-sm text-red-600">
- <div className="font-medium">연결 오류</div>
- <div className="text-xs">일부 계약의 동기화 상태를 확인할 수 없습니다.</div>
- </div>
- </div>
- )}
-
+ {/* 계약 정보가 없는 경우 */}
{documentsContractIds.length === 0 && (
- <div className="space-y-2">
- <Separator />
- <div className="text-sm text-muted-foreground">
- <div className="font-medium">계약 정보 없음</div>
- <div className="text-xs">동기화할 문서가 없습니다.</div>
- </div>
- </div>
+ <Alert>
+ <AlertDescription>
+ 동기화할 문서가 없습니다. 문서를 선택해주세요.
+ </AlertDescription>
+ </Alert>
)}
<Separator />
+ {/* 액션 버튼들 */}
<div className="flex gap-2">
<Button
onClick={() => setIsDialogOpen(true)}
@@ -385,8 +405,9 @@ export function SendToSHIButton({
<Button
variant="outline"
size="sm"
- onClick={refreshAllStatuses}
+ onClick={refetchAll}
disabled={totalStats.isLoading}
+ className="px-3"
>
{totalStats.isLoading ? (
<Loader2 className="w-4 h-4 animate-spin" />
@@ -403,9 +424,12 @@ export function SendToSHIButton({
<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
- <DialogTitle>SHI 시스템으로 동기화</DialogTitle>
+ <DialogTitle className="flex items-center gap-2">
+ <Send className="w-5 h-5" />
+ SHI 시스템으로 동기화
+ </DialogTitle>
<DialogDescription>
- {documentsContractIds.length}개 계약의 변경된 문서 데이터를 SHI 시스템으로 전송합니다.
+ {documentsContractIds.length}개 계약의 변경된 문서 데이터를 {targetSystem} 시스템으로 전송합니다.
</DialogDescription>
</DialogHeader>
@@ -434,7 +458,8 @@ export function SendToSHIButton({
</div>
<Progress value={syncProgress} className="h-2" />
{currentSyncingContract && (
- <div className="text-xs text-muted-foreground">
+ <div className="text-xs text-muted-foreground flex items-center gap-1">
+ <Loader2 className="w-3 h-3 animate-spin" />
현재 처리 중: Contract {currentSyncingContract}
</div>
)}
@@ -444,19 +469,20 @@ export function SendToSHIButton({
)}
{totalStats.hasError && (
- <div className="rounded-lg border border-red-200 p-4">
- <div className="text-sm text-red-600">
- 일부 계약의 동기화 상태를 확인할 수 없습니다. 네트워크 연결을 확인해주세요.
- </div>
- </div>
+ <Alert variant="destructive">
+ <AlertTriangle className="h-4 w-4" />
+ <AlertDescription>
+ 일부 계약의 동기화 상태를 확인할 수 없습니다. 네트워크 연결을 확인하고 다시 시도해주세요.
+ </AlertDescription>
+ </Alert>
)}
{documentsContractIds.length === 0 && (
- <div className="rounded-lg border border-yellow-200 p-4">
- <div className="text-sm text-yellow-700">
+ <Alert>
+ <AlertDescription>
동기화할 계약이 없습니다. 문서를 선택해주세요.
- </div>
- </div>
+ </AlertDescription>
+ </Alert>
)}
<div className="flex justify-end gap-2">