diff options
| author | dujinkim <dujin.kim@dtsolution.co.kr> | 2025-07-22 02:57:00 +0000 |
|---|---|---|
| committer | dujinkim <dujin.kim@dtsolution.co.kr> | 2025-07-22 02:57:00 +0000 |
| commit | ee57cc221ff2edafd3c0f12a181214c602ed257e (patch) | |
| tree | 148f552f503798f7a350d6eff936b889f16be49f /app/api/sync/import | |
| parent | 14f61e24947fb92dd71ec0a7196a6e815f8e66da (diff) | |
(대표님, 최겸) 이메일 템플릿, 벤더데이터 변경사항 대응, 기술영업 변경요구사항 구현
Diffstat (limited to 'app/api/sync/import')
| -rw-r--r-- | app/api/sync/import/status/route.ts | 208 |
1 files changed, 192 insertions, 16 deletions
diff --git a/app/api/sync/import/status/route.ts b/app/api/sync/import/status/route.ts index c5b4b0bd..8b6144d6 100644 --- a/app/api/sync/import/status/route.ts +++ b/app/api/sync/import/status/route.ts @@ -1,8 +1,19 @@ -// app/api/sync/import/status/route.ts +// app/api/sync/status/route.ts import { NextRequest, NextResponse } from "next/server" -import { importService } from "@/lib/vendor-document-list/import-service" import { getServerSession } from "next-auth" import { authOptions } from "@/app/api/auth/[...nextauth]/route" +import db from "@/db/db" +import { documents, revisions, documentAttachments, contracts, projects, vendors } from "@/db/schema" +import { eq, and, sql, desc } from "drizzle-orm" + +interface SyncStatus { + syncEnabled: boolean + pendingChanges: number + syncedChanges: number + failedChanges: number + lastSyncAt?: string + error?: string +} export async function GET(request: NextRequest) { try { @@ -13,7 +24,7 @@ export async function GET(request: NextRequest) { const { searchParams } = new URL(request.url) const contractId = searchParams.get('contractId') - const sourceSystem = searchParams.get('sourceSystem') || 'DOLCE' + const targetSystem = searchParams.get('targetSystem') || 'SHI' if (!contractId) { return NextResponse.json( @@ -22,20 +33,185 @@ export async function GET(request: NextRequest) { ) } - const status = await importService.getImportStatus( - Number(contractId), - sourceSystem - ) + // 🔥 안전하게 동기화 상태 조회 + const syncStatus = await getSyncStatusSafely(Number(contractId), targetSystem) + + return NextResponse.json(syncStatus) + + } catch (error) { + console.error('Unexpected error in sync status API:', error) + + // 🔥 에러 시에도 200으로 응답하고 error 필드 포함 + return NextResponse.json({ + syncEnabled: false, + pendingChanges: 0, + syncedChanges: 0, + failedChanges: 0, + lastSyncAt: undefined, + error: '시스템 오류가 발생했습니다. 잠시 후 다시 시도해주세요.' + }, { status: 200 }) + } +} + +async function getSyncStatusSafely(contractId: number, targetSystem: string): Promise<SyncStatus> { + try { + // 1. 계약 정보 확인 + const contractInfo = await db + .select({ + projectCode: projects.code, + vendorCode: vendors.vendorCode, + contractStatus: contracts.status + }) + .from(contracts) + .innerJoin(projects, eq(contracts.projectId, projects.id)) + .innerJoin(vendors, eq(contracts.vendorId, vendors.id)) + .where(eq(contracts.id, contractId)) + .limit(1) + + // 계약 정보가 없는 경우 + if (!contractInfo || contractInfo.length === 0) { + return { + syncEnabled: false, + pendingChanges: 0, + syncedChanges: 0, + failedChanges: 0, + error: `계약 ${contractId}를 찾을 수 없습니다.` + } + } + + const contract = contractInfo[0] + + // 프로젝트 코드나 벤더 코드가 없는 경우 + if (!contract.projectCode || !contract.vendorCode) { + return { + syncEnabled: false, + pendingChanges: 0, + syncedChanges: 0, + failedChanges: 0, + error: `계약 ${contractId}에 프로젝트 코드 또는 벤더 코드가 설정되지 않았습니다.` + } + } + + // 2. 마지막 동기화 시간 조회 + const [lastSync] = await db + .select({ + lastSyncAt: sql<string>`MAX(${documents.externalSyncedAt})` + }) + .from(documents) + .where(and( + eq(documents.contractId, contractId), + eq(documents.externalSystemType, targetSystem) + )) + + // 3. 문서별 변경사항 분석 + const documentStats = await db + .select({ + id: documents.id, + docNumber: documents.docNumber, + updatedAt: documents.updatedAt, + externalSyncedAt: documents.externalSyncedAt, + syncStatus: documents.syncStatus + }) + .from(documents) + .where(eq(documents.contractId, contractId)) + + let pendingChanges = 0 + let syncedChanges = 0 + let failedChanges = 0 + + // 각 문서의 동기화 상태 분석 + for (const doc of documentStats) { + // 문서 자체가 변경되었는지 확인 + const docNeedsSync = !doc.externalSyncedAt || + (doc.updatedAt && doc.externalSyncedAt && doc.updatedAt > doc.externalSyncedAt) + + if (docNeedsSync) { + if (doc.syncStatus === 'FAILED') { + failedChanges++ + } else if (doc.syncStatus === 'SYNCED') { + syncedChanges++ + } else { + pendingChanges++ + } + } + + // 해당 문서의 리비전 변경사항 확인 + const revisionStats = await db + .select({ + updatedAt: revisions.updatedAt, + externalSyncedAt: revisions.externalSyncedAt, + syncStatus: revisions.syncStatus + }) + .from(revisions) + .innerJoin(documents, eq(revisions.documentId, documents.id)) + .where(eq(documents.id, doc.id)) + + for (const revision of revisionStats) { + const revisionNeedsSync = !revision.externalSyncedAt || + (revision.updatedAt && revision.externalSyncedAt && revision.updatedAt > revision.externalSyncedAt) + + if (revisionNeedsSync) { + if (revision.syncStatus === 'FAILED') { + failedChanges++ + } else if (revision.syncStatus === 'SYNCED') { + syncedChanges++ + } else { + pendingChanges++ + } + } + } + + // 첨부파일 변경사항 확인 + const attachmentStats = await db + .select({ + updatedAt: documentAttachments.updatedAt, + externalSyncedAt: documentAttachments.externalSyncedAt, + syncStatus: documentAttachments.syncStatus + }) + .from(documentAttachments) + .innerJoin(revisions, eq(documentAttachments.revisionId, revisions.id)) + .innerJoin(documents, eq(revisions.documentId, documents.id)) + .where(eq(documents.id, doc.id)) + + for (const attachment of attachmentStats) { + const attachmentNeedsSync = !attachment.externalSyncedAt || + (attachment.updatedAt && attachment.externalSyncedAt && attachment.updatedAt > attachment.externalSyncedAt) + + if (attachmentNeedsSync) { + if (attachment.syncStatus === 'FAILED') { + failedChanges++ + } else if (attachment.syncStatus === 'SYNCED') { + syncedChanges++ + } else { + pendingChanges++ + } + } + } + } + + // 4. 동기화 활성화 여부 확인 + const syncEnabled = contract.contractStatus === 'ACTIVE' && + Boolean(contract.projectCode) && + Boolean(contract.vendorCode) && + process.env[`SYNC_${targetSystem.toUpperCase()}_ENABLED`] === 'true' + + return { + syncEnabled, + pendingChanges, + syncedChanges, + failedChanges, + lastSyncAt: lastSync?.lastSyncAt ? new Date(lastSync.lastSyncAt).toISOString() : undefined + } - return NextResponse.json(status) } catch (error) { - console.error('Failed to get import status:', error) - return NextResponse.json( - { - error: 'Failed to get import status', - message: error instanceof Error ? error.message : 'Unknown error' - }, - { status: 500 } - ) + console.error(`Failed to get sync status for contract ${contractId}:`, error) + + return { + syncEnabled: false, + pendingChanges: 0, + syncedChanges: 0, + failedChanges: 0, + error: error instanceof Error ? error.message : '동기화 상태를 확인할 수 없습니다.' + } } }
\ No newline at end of file |
