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
|
"use server"
import { getErrorMessage } from "@/lib/handle-error"
import { desc, or, eq } from "drizzle-orm"
import db from "@/db/db"
import { pageInformation, menuTreeNodes, users } from "@/db/schema"
import { saveDRMFile } from "@/lib/file-stroage"
import { decryptWithServerAction } from "@/components/drm/drmUtils"
import type {
UpdateInformationSchema
} from "./validations"
import {
getInformationByPagePathWithAttachments,
updateInformation,
getInformationWithAttachments,
addInformationAttachment,
deleteInformationAttachment,
getAttachmentById
} from "./repository"
import type { PageInformation, InformationAttachment } from "@/db/schema/information"
// 간단한 인포메이션 목록 조회 (페이지네이션 없이 전체 조회)
export async function getInformationLists() {
try {
// 전체 데이터 조회 (클라이언트에서 검색 처리, 생성자/수정자 정보 포함)
const data = await db
.select({
id: pageInformation.id,
pagePath: pageInformation.pagePath,
pageName: pageInformation.pageName,
informationContent: pageInformation.informationContent,
isActive: pageInformation.isActive,
createdBy: pageInformation.createdBy,
createdAt: pageInformation.createdAt,
updatedBy: pageInformation.updatedBy,
updatedAt: pageInformation.updatedAt,
updatedByName: users.name,
updatedByEmail: users.email,
})
.from(pageInformation)
.leftJoin(users, eq(pageInformation.updatedBy, users.id))
.orderBy(desc(pageInformation.createdAt))
return { data }
} catch (err) {
console.error("Failed to get information lists:", err)
return { data: [] }
}
}
// 페이지별 인포메이션 조회 (첨부파일 포함)
export async function getPageInformation(pagePath: string) {
try {
console.log('🔍 Information Service - 조회 시작:', { pagePath })
const result = await getInformationByPagePathWithAttachments(pagePath)
console.log('📊 Information Service - 조회 결과:', {
pagePath,
found: !!result,
resultData: result ? {
id: result.id,
pagePath: result.pagePath,
pageName: result.pageName,
attachmentsCount: result.attachments?.length || 0
} : null
})
return result
} catch (error) {
console.error(`Failed to get information for page ${pagePath}:`, error)
return null
}
}
// 페이지별 인포메이션 조회 (직접 호출용)
export async function getPageInformationDirect(pagePath: string) {
return await getPageInformation(pagePath)
}
// 인포메이션 수정 (내용과 첨부파일만)
export async function updateInformationData(input: UpdateInformationSchema, userId?: string) {
try {
const { id, ...updateData } = input
// 수정 가능한 필드만 허용
const allowedFields = {
informationContent: updateData.informationContent,
isActive: updateData.isActive,
updatedBy: userId ? parseInt(userId) : null,
updatedAt: new Date()
}
const result = await updateInformation(id, allowedFields)
if (!result) {
return {
success: false,
message: "인포메이션을 찾을 수 없거나 수정에 실패했습니다."
}
}
// 캐시 무효화 제거됨
return {
success: true,
message: "인포메이션이 성공적으로 수정되었습니다."
}
} catch (error) {
console.error("Failed to update information:", error)
return {
success: false,
message: getErrorMessage(error)
}
}
}
// ID로 인포메이션 조회 (첨부파일 포함)
export async function getInformationDetail(id: number) {
try {
return await getInformationWithAttachments(id)
} catch (error) {
console.error(`Failed to get information detail for id ${id}:`, error)
return null
}
}
// 인포메이션 편집 권한 확인
export async function checkInformationEditPermission(pagePath: string, userId: string): Promise<boolean> {
try {
// pagePath 정규화 (앞의 / 제거)
const normalizedPagePath = pagePath.startsWith('/') ? pagePath.slice(1) : pagePath
// pagePath를 menuPath로 변환 (pagePath가 menuPath의 마지막 부분이라고 가정)
// 예: pagePath "vendor-list" -> menuPath "/evcp/vendor-list" 또는 "/partners/vendor-list"
const menuPathQueries = [
`/evcp/${normalizedPagePath}`,
`/partners/${normalizedPagePath}`,
`/${normalizedPagePath}`, // 루트 경로
normalizedPagePath, // 정확한 매칭
`/${pagePath}`, // 원본 경로도 체크
pagePath // 원본 경로 정확한 매칭
]
// menu_tree_nodes에서 해당 pagePath와 매칭되는 메뉴 찾기
const menuNode = await db
.select()
.from(menuTreeNodes)
.where(
or(
...menuPathQueries.map(path => eq(menuTreeNodes.menuPath, path))
)
)
.limit(1)
if (menuNode.length === 0) {
// 매칭되는 메뉴가 없으면 권한 없음
return false
}
const node = menuNode[0]
const userIdNumber = parseInt(userId)
// 현재 사용자가 manager1 또는 manager2인지 확인
return node.manager1Id === userIdNumber || node.manager2Id === userIdNumber
} catch (error) {
console.error("Failed to check information edit permission:", error)
return false
}
}
// 권한 확인 (직접 호출용)
export async function getEditPermissionDirect(pagePath: string, userId: string) {
return await checkInformationEditPermission(pagePath, userId)
}
// menu_tree_nodes 기반으로 page_information 동기화
export async function syncInformationFromMenuAssignments() {
try {
// menu_tree_nodes에서 메뉴 타입 노드만 가져오기 (menuPath가 있는 것)
const menuItems = await db.select()
.from(menuTreeNodes)
.where(eq(menuTreeNodes.nodeType, 'menu'));
let processedCount = 0;
// upsert를 사용하여 각 메뉴 항목 처리
for (const menu of menuItems) {
try {
if (!menu.menuPath) continue;
// 맨 앞의 / 제거하여 pagePath 정규화
const normalizedPagePath = menu.menuPath.startsWith('/')
? menu.menuPath.slice(1)
: menu.menuPath;
await db.insert(pageInformation)
.values({
pagePath: normalizedPagePath,
pageName: menu.titleKo,
informationContent: "",
isActive: true // 기본값으로 활성화
})
.onConflictDoUpdate({
target: pageInformation.pagePath,
set: {
pageName: menu.titleKo,
updatedAt: new Date()
}
});
processedCount++;
} catch (itemError: any) {
console.warn(`메뉴 항목 처리 실패: ${menu.menuPath}`, itemError);
continue;
}
}
return {
success: true,
message: `페이지 정보 동기화 완료: ${processedCount}개 처리됨`
};
} catch (error) {
console.error("Information 동기화 오류:", error);
return {
success: false,
message: "페이지 정보 동기화 중 오류가 발생했습니다."
};
}
}
// 첨부파일 업로드
export async function uploadInformationAttachment(formData: FormData) {
try {
const informationId = parseInt(formData.get("informationId") as string)
const file = formData.get("file") as File
if (!informationId || !file) {
return {
success: false,
message: "필수 매개변수가 누락되었습니다."
}
}
// 파일 저장
const saveResult = await saveDRMFile(
file,
decryptWithServerAction,
`information/${informationId}`,
// userId는 필요시 추가
)
if (!saveResult.success) {
return {
success: false,
message: saveResult.error || "파일 저장에 실패했습니다."
}
}
// DB에 첨부파일 정보 저장
const attachment = await addInformationAttachment({
informationId,
fileName: file.name,
filePath: saveResult.publicPath || "",
fileSize: saveResult.fileSize ? String(saveResult.fileSize) : String(file.size)
})
if (!attachment) {
return {
success: false,
message: "첨부파일 정보 저장에 실패했습니다."
}
}
// 캐시 무효화 제거됨
return {
success: true,
message: "첨부파일이 성공적으로 업로드되었습니다.",
data: attachment
}
} catch (error) {
console.error("Failed to upload attachment:", error)
return {
success: false,
message: getErrorMessage(error)
}
}
}
// 첨부파일 삭제
export async function deleteInformationAttachmentAction(attachmentId: number) {
try {
const attachment = await getAttachmentById(attachmentId)
if (!attachment) {
return {
success: false,
message: "첨부파일을 찾을 수 없습니다."
}
}
// DB에서 삭제
const deleted = await deleteInformationAttachment(attachmentId)
if (!deleted) {
return {
success: false,
message: "첨부파일 삭제에 실패했습니다."
}
}
// 캐시 무효화 제거됨
return {
success: true,
message: "첨부파일이 성공적으로 삭제되었습니다."
}
} catch (error) {
console.error("Failed to delete attachment:", error)
return {
success: false,
message: getErrorMessage(error)
}
}
}
// 첨부파일 다운로드
export async function downloadInformationAttachment(attachmentId: number) {
try {
const attachment = await getAttachmentById(attachmentId)
if (!attachment) {
return {
success: false,
message: "첨부파일을 찾을 수 없습니다."
}
}
// 파일 다운로드 (클라이언트에서 사용)
return {
success: true,
data: {
filePath: attachment.filePath,
fileName: attachment.fileName,
fileSize: attachment.fileSize
}
}
} catch (error) {
console.error("Failed to download attachment:", error)
return {
success: false,
message: getErrorMessage(error)
}
}
}
|