summaryrefslogtreecommitdiff
path: root/app/api/sync
diff options
context:
space:
mode:
authordujinkim <dujin.kim@dtsolution.co.kr>2025-07-23 09:08:03 +0000
committerdujinkim <dujin.kim@dtsolution.co.kr>2025-07-23 09:08:03 +0000
commita50bc9baea332f996e6bc3a5d70c69f6d2d0f194 (patch)
tree7493b8a4d9cc7cc3375068f1aa10b0067e85988f /app/api/sync
parent7402e759857d511add0d3eb19f1fa13cb957c1df (diff)
(대표님, 최겸) 기본계약 템플릿 및 에디터, 기술영업 벤더정보, 파일 보안다운로드, 벤더 document sync 상태 서비스, 메뉴 Config, 기술영업 미사용 제거
Diffstat (limited to 'app/api/sync')
-rw-r--r--app/api/sync/import/status/route.ts208
1 files changed, 16 insertions, 192 deletions
diff --git a/app/api/sync/import/status/route.ts b/app/api/sync/import/status/route.ts
index 8b6144d6..c5b4b0bd 100644
--- a/app/api/sync/import/status/route.ts
+++ b/app/api/sync/import/status/route.ts
@@ -1,19 +1,8 @@
-// app/api/sync/status/route.ts
+// app/api/sync/import/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 {
@@ -24,7 +13,7 @@ export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url)
const contractId = searchParams.get('contractId')
- const targetSystem = searchParams.get('targetSystem') || 'SHI'
+ const sourceSystem = searchParams.get('sourceSystem') || 'DOLCE'
if (!contractId) {
return NextResponse.json(
@@ -33,185 +22,20 @@ export async function GET(request: NextRequest) {
)
}
- // 🔥 안전하게 동기화 상태 조회
- 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
- }
+ const status = await importService.getImportStatus(
+ Number(contractId),
+ sourceSystem
+ )
+ return NextResponse.json(status)
} catch (error) {
- 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 : '동기화 상태를 확인할 수 없습니다.'
- }
+ 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 }
+ )
}
} \ No newline at end of file