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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
|
'use server'
import db from '@/db/db'
import { policyVersions, userConsents, consentLogs } from '@/db/schema'
import { eq, desc, and } from 'drizzle-orm'
import { revalidatePath } from 'next/cache'
// 정책 버전 생성
export async function createPolicyVersion(data: {
policyType: 'privacy_policy' | 'terms_of_service'
locale: 'ko' | 'en'
version: string
content: string
effectiveDate: Date
}) {
try {
// 트랜잭션으로 처리
const result = await db.transaction(async (tx) => {
// 기존의 현재 정책들을 비활성화 (같은 locale, 같은 policyType)
await tx
.update(policyVersions)
.set({ isCurrent: false })
.where(and(
eq(policyVersions.policyType, data.policyType),
eq(policyVersions.locale, data.locale)
))
// 새 정책 버전 생성
const [newPolicy] = await tx
.insert(policyVersions)
.values({
policyType: data.policyType,
locale: data.locale,
version: data.version,
content: data.content,
effectiveDate: data.effectiveDate,
isCurrent: true,
})
.returning()
return newPolicy
})
revalidatePath('/evcp/policies')
return { success: true, policy: result }
} catch (error) {
console.error('Error creating policy version:', error)
return {
success: false,
error: error instanceof Error ? error.message : '정책 생성에 실패했습니다.'
}
}
}
// 정책 버전 활성화
export async function activatePolicyVersion(policyId: number) {
try {
// 먼저 해당 정책의 타입을 조회
const targetPolicy = await db
.select()
.from(policyVersions)
.where(eq(policyVersions.id, policyId))
.limit(1)
if (targetPolicy.length === 0) {
return { success: false, error: '정책을 찾을 수 없습니다.' }
}
// 트랜잭션으로 처리
await db.transaction(async (tx) => {
// 해당 정책 타입의 모든 버전을 비활성화
await tx
.update(policyVersions)
.set({ isCurrent: false })
.where(eq(policyVersions.policyType, targetPolicy[0].policyType))
// 선택한 버전만 활성화
await tx
.update(policyVersions)
.set({ isCurrent: true })
.where(eq(policyVersions.id, policyId))
})
revalidatePath('/admin/policies')
return { success: true }
} catch (error) {
console.error('Error activating policy version:', error)
return {
success: false,
error: error instanceof Error ? error.message : '정책 활성화에 실패했습니다.'
}
}
}
// 정책 히스토리 조회
export async function getPolicyHistory(policyType: 'privacy_policy' | 'terms_of_service', locale?: string) {
try {
const whereConditions = [eq(policyVersions.policyType, policyType)]
// locale이 지정된 경우 해당 locale만 조회
if (locale) {
whereConditions.push(eq(policyVersions.locale, locale))
}
const history = await db
.select()
.from(policyVersions)
.where(and(...whereConditions))
.orderBy(desc(policyVersions.createdAt))
return { success: true, data: history }
} catch (error) {
console.error('Error fetching policy history:', error)
return {
success: false,
error: error instanceof Error ? error.message : '히스토리 조회에 실패했습니다.'
}
}
}
// 현재 활성 정책들 조회 (locale별)
export async function getCurrentPolicies(locale?: string) {
try {
const whereConditions = [eq(policyVersions.isCurrent, true)]
// locale이 지정된 경우 해당 locale만 조회
if (locale) {
whereConditions.push(eq(policyVersions.locale, locale))
}
const currentPolicies = await db
.select()
.from(policyVersions)
.where(and(...whereConditions))
// locale별로 정책 타입별 그룹화
const grouped = currentPolicies.reduce((acc, policy) => {
if (!acc[policy.locale]) {
acc[policy.locale] = {}
}
acc[policy.locale][policy.policyType] = policy
return acc
}, {} as Record<string, Record<string, any>>)
return { success: true, data: grouped }
} catch (error) {
console.error('Error fetching current policies:', error)
return {
success: false,
error: error instanceof Error ? error.message : '정책 조회에 실패했습니다.'
}
}
}
// 모든 정책 조회 (관리자용)
export async function getAllPolicies() {
try {
const allPolicies = await db
.select()
.from(policyVersions)
.orderBy(desc(policyVersions.createdAt))
// 정책 타입별로 그룹화
const grouped = allPolicies.reduce((acc, policy) => {
if (!acc[policy.policyType]) {
acc[policy.policyType] = []
}
acc[policy.policyType].push(policy)
return acc
}, {} as Record<string, any[]>)
return { success: true, data: grouped }
} catch (error) {
console.error('Error fetching all policies:', error)
return {
success: false,
error: error instanceof Error ? error.message : '정책 조회에 실패했습니다.'
}
}
}
// 정책 통계 조회
export async function getPolicyStats() {
try {
// 각 정책별 버전 수와 최신 업데이트 날짜
const stats = await db
.select({
policyType: policyVersions.policyType,
totalVersions: 'COUNT(*)',
latestUpdate: 'MAX(created_at)',
currentVersion: policyVersions.version,
})
.from(policyVersions)
.where(eq(policyVersions.isCurrent, true))
.groupBy(policyVersions.policyType, policyVersions.version)
return { success: true, data: stats }
} catch (error) {
console.error('Error fetching policy stats:', error)
return {
success: false,
error: error instanceof Error ? error.message : '통계 조회에 실패했습니다.'
}
}
}
// 사용자 동의 기록
export async function recordUserConsent(data: {
userId: number
consents: Array<{
consentType: 'privacy_policy' | 'terms_of_service' | 'marketing' | 'optional'
consentStatus: boolean
policyVersion: string
}>
ipAddress?: string
userAgent?: string
}) {
try {
const result = await db.transaction(async (tx) => {
const consentRecords = []
const logRecords = []
for (const consent of data.consents) {
// 사용자 동의 기록
const [consentRecord] = await tx
.insert(userConsents)
.values({
userId: data.userId,
consentType: consent.consentType,
consentStatus: consent.consentStatus,
policyVersion: consent.policyVersion,
ipAddress: data.ipAddress,
userAgent: data.userAgent,
})
.returning()
consentRecords.push(consentRecord)
// 동의 로그 기록
const [logRecord] = await tx
.insert(consentLogs)
.values({
userId: data.userId,
consentType: consent.consentType,
action: 'consent',
oldStatus: null,
newStatus: consent.consentStatus,
policyVersion: consent.policyVersion,
ipAddress: data.ipAddress,
userAgent: data.userAgent,
})
.returning()
logRecords.push(logRecord)
}
return { consents: consentRecords, logs: logRecords }
})
return { success: true, data: result }
} catch (error) {
console.error('Error recording user consent:', error)
return {
success: false,
error: error instanceof Error ? error.message : '동의 기록에 실패했습니다.'
}
}
}
// 사용자 동의 상태 조회
export async function getUserConsentStatus(userId: number) {
try {
const consents = await db
.select()
.from(userConsents)
.where(eq(userConsents.userId, userId))
.orderBy(desc(userConsents.consentedAt))
// 각 동의 타입별 최신 상태만 반환
const latestConsents = consents.reduce((acc, consent) => {
if (!acc[consent.consentType] ||
new Date(consent.consentedAt) > new Date(acc[consent.consentType].consentedAt)) {
acc[consent.consentType] = consent
}
return acc
}, {} as Record<string, any>)
return { success: true, data: latestConsents }
} catch (error) {
console.error('Error fetching user consent status:', error)
return {
success: false,
error: error instanceof Error ? error.message : '동의 상태 조회에 실패했습니다.'
}
}
}
// 사용자 동의 철회
export async function revokeUserConsent(data: {
userId: number
consentType: 'privacy_policy' | 'terms_of_service' | 'marketing' | 'optional'
revokeReason?: string
ipAddress?: string
userAgent?: string
}) {
try {
// 현재 동의 상태 조회
const currentConsent = await db
.select()
.from(userConsents)
.where(
and(
eq(userConsents.userId, data.userId),
eq(userConsents.consentType, data.consentType)
)
)
.orderBy(desc(userConsents.consentedAt))
.limit(1)
if (currentConsent.length === 0) {
return { success: false, error: '동의 기록을 찾을 수 없습니다.' }
}
const result = await db.transaction(async (tx) => {
// 동의 철회 기록
const [updatedConsent] = await tx
.update(userConsents)
.set({
consentStatus: false,
revokedAt: new Date(),
revokeReason: data.revokeReason,
})
.where(eq(userConsents.id, currentConsent[0].id))
.returning()
// 철회 로그 기록
const [logRecord] = await tx
.insert(consentLogs)
.values({
userId: data.userId,
consentType: data.consentType,
action: 'revoke',
oldStatus: currentConsent[0].consentStatus,
newStatus: false,
policyVersion: currentConsent[0].policyVersion,
ipAddress: data.ipAddress,
userAgent: data.userAgent,
additionalData: data.revokeReason ? { revokeReason: data.revokeReason } : null,
})
.returning()
return { consent: updatedConsent, log: logRecord }
})
return { success: true, data: result }
} catch (error) {
console.error('Error revoking user consent:', error)
return {
success: false,
error: error instanceof Error ? error.message : '동의 철회에 실패했습니다.'
}
}
}
|