1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
|
// app/api/sync/status/route.ts
import { NextRequest, NextResponse } from "next/server"
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 {
const session = await getServerSession(authOptions)
if (!session?.user?.id) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
}
const { searchParams } = new URL(request.url)
const contractId = searchParams.get('contractId')
const targetSystem = searchParams.get('targetSystem') || 'SHI'
if (!contractId) {
return NextResponse.json(
{ error: 'Contract ID is required' },
{ status: 400 }
)
}
// 🔥 안전하게 동기화 상태 조회
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
}
} 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 : '동기화 상태를 확인할 수 없습니다.'
}
}
}
|