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
|
"use server"
import { revalidatePath } from "next/cache"
import db from "@/db/db"
import { codeGroups, comboBoxSettings, documentClasses } from "@/db/schema/docu-list-rule"
import { eq, sql, count } from "drizzle-orm"
import { unstable_noStore } from "next/cache"
// Code Groups 목록 조회
export async function getCodeGroups(input: any) {
unstable_noStore()
try {
const { page, perPage, search, filters, joinOperator } = input
const offset = (page - 1) * perPage
// 검색 조건 (Document Class 제외)
let whereConditions = sql`${codeGroups.groupId} != 'DOC_CLASS'`
// 검색어 필터링
if (search) {
const searchTerm = `%${search}%`
whereConditions = sql`${codeGroups.groupId} != 'DOC_CLASS' AND (
${codeGroups.groupId} ILIKE ${searchTerm} OR
${codeGroups.description} ILIKE ${searchTerm} OR
${codeGroups.codeFormat} ILIKE ${searchTerm} OR
${codeGroups.controlType} ILIKE ${searchTerm}
)`
}
// 고급 필터링 (단순화)
if (filters && filters.length > 0) {
const filterConditions = filters.map(filter => {
const { id, value } = filter
if (!value || Array.isArray(value)) return null
switch (id) {
case "groupId":
return sql`${codeGroups.groupId} ILIKE ${`%${value}%`}`
case "description":
return sql`${codeGroups.description} ILIKE ${`%${value}%`}`
case "codeFormat":
return sql`${codeGroups.codeFormat} ILIKE ${`%${value}%`}`
case "controlType":
return sql`${codeGroups.controlType} = ${value}`
case "isActive":
return sql`${codeGroups.isActive} = ${value === "true"}`
case "createdAt":
return sql`${codeGroups.createdAt}::text ILIKE ${`%${value}%`}`
default:
return null
}
}).filter(Boolean)
if (filterConditions.length > 0) {
const operator = joinOperator === "or" ? sql` OR ` : sql` AND `
const combinedFilters = filterConditions.reduce((acc, condition, index) => {
if (index === 0) return condition
return sql`${acc}${operator}${condition}`
})
whereConditions = sql`${whereConditions} AND (${combinedFilters})`
}
}
// 정렬 (안전한 필드 체크 적용)
let orderBy = sql`${codeGroups.createdAt} DESC`
if (input.sort && input.sort.length > 0) {
const sortField = input.sort[0]
// 안전성 체크: 필드가 실제 테이블에 존재하는지 확인
if (sortField && sortField.id && typeof sortField.id === "string" && sortField.id in codeGroups) {
const direction = sortField.desc ? sql`DESC` : sql`ASC`
const col = codeGroups[sortField.id as keyof typeof codeGroups]
orderBy = sql`${col} ${direction}`
}
}
// 데이터 조회
const data = await db
.select({
id: codeGroups.id,
groupId: codeGroups.groupId,
description: codeGroups.description,
codeFormat: codeGroups.codeFormat,
expressions: codeGroups.expressions,
controlType: codeGroups.controlType,
isActive: codeGroups.isActive,
createdAt: codeGroups.createdAt,
updatedAt: codeGroups.updatedAt,
})
.from(codeGroups)
.where(whereConditions)
.orderBy(orderBy)
.limit(perPage)
.offset(offset)
// 총 개수 조회 (Document Class 제외)
const [{ count: total }] = await db
.select({ count: count() })
.from(codeGroups)
.where(whereConditions)
const pageCount = Math.ceil(total / perPage)
return {
data,
pageCount,
total,
}
} catch (error) {
console.error("Error fetching code groups:", error)
return {
data: [],
pageCount: 0,
total: 0,
}
}
}
// Code Group 생성
export async function createCodeGroup(input: {
description: string
codeFormat?: string
expressions?: string
controlType: string
isActive?: boolean
}) {
try {
// 마지막 Code Group의 groupId를 찾아서 다음 번호 생성 (DOC_CLASS 제외)
const lastCodeGroup = await db
.select({ groupId: codeGroups.groupId })
.from(codeGroups)
.where(sql`${codeGroups.groupId} != 'DOC_CLASS'`)
.orderBy(sql`CAST(SUBSTRING(${codeGroups.groupId}, 6) AS INTEGER) DESC`)
.limit(1)
let nextNumber = 1
if (lastCodeGroup.length > 0 && lastCodeGroup[0].groupId) {
const lastNumber = parseInt(lastCodeGroup[0].groupId.replace('Code_', ''))
if (!isNaN(lastNumber)) {
nextNumber = lastNumber + 1
}
}
const newGroupId = `Code_${nextNumber}`
// 새 Code Group 생성
const [newCodeGroup] = await db
.insert(codeGroups)
.values({
groupId: newGroupId,
description: input.description,
codeFormat: input.codeFormat,
expressions: input.expressions,
controlType: input.controlType,
isActive: input.isActive ?? true,
})
.returning({ id: codeGroups.id, groupId: codeGroups.groupId })
revalidatePath("/evcp/docu-list-rule/code-groups")
return {
success: true,
data: newCodeGroup,
message: "Code Group created successfully"
}
} catch (error) {
console.error("Error creating code group:", error)
return {
success: false,
error: "Failed to create code group"
}
}
}
// Code Group 수정
export async function updateCodeGroup(input: {
id: number
description: string
codeFormat?: string
expressions?: string
controlType: string
isActive?: boolean
}) {
try {
const [updatedCodeGroup] = await db
.update(codeGroups)
.set({
description: input.description,
codeFormat: input.codeFormat,
expressions: input.expressions,
controlType: input.controlType,
isActive: input.isActive,
updatedAt: new Date(),
})
.where(eq(codeGroups.id, input.id))
.returning({ id: codeGroups.id })
revalidatePath("/evcp/docu-list-rule/code-groups")
return {
success: true,
data: updatedCodeGroup,
message: "Code Group updated successfully"
}
} catch (error) {
console.error("Error updating code group:", error)
return {
success: false,
error: "Failed to update code group"
}
}
}
// Code Group 삭제
export async function deleteCodeGroup(id: number) {
try {
// Code Group 정보 조회
const codeGroup = await db
.select({
id: codeGroups.id,
controlType: codeGroups.controlType,
description: codeGroups.description
})
.from(codeGroups)
.where(eq(codeGroups.id, id))
.limit(1)
if (codeGroup.length === 0) {
return {
success: false,
error: "Code Group not found"
}
}
// Control Type이 combobox인 경우 관련 Combo Box 옵션들도 삭제
if (codeGroup[0].controlType === 'combobox') {
// Combo Box 옵션들 삭제
await db
.delete(comboBoxSettings)
.where(eq(comboBoxSettings.codeGroupId, id))
}
// Document Class가 연결된 경우 Document Class도 삭제
await db
.delete(documentClasses)
.where(eq(documentClasses.codeGroupId, id))
// Code Group 삭제
await db
.delete(codeGroups)
.where(eq(codeGroups.id, id))
revalidatePath("/evcp/docu-list-rule/code-groups")
revalidatePath("/evcp/docu-list-rule/combo-box-settings")
revalidatePath("/evcp/docu-list-rule/document-class")
return {
success: true,
message: codeGroup[0].controlType === 'combobox'
? `Code Group과 관련 Combo Box 옵션들이 삭제되었습니다.`
: "Code Group이 삭제되었습니다."
}
} catch (error) {
console.error("Error deleting code group:", error)
return {
success: false,
error: "Failed to delete code group"
}
}
}
// Code Group 단일 조회
export async function getCodeGroupById(id: number) {
try {
const [codeGroup] = await db
.select({
id: codeGroups.id,
groupId: codeGroups.groupId,
description: codeGroups.description,
codeFormat: codeGroups.codeFormat,
expressions: codeGroups.expressions,
controlType: codeGroups.controlType,
isActive: codeGroups.isActive,
createdAt: codeGroups.createdAt,
updatedAt: codeGroups.updatedAt,
})
.from(codeGroups)
.where(eq(codeGroups.id, id))
.limit(1)
return codeGroup || null
} catch (error) {
console.error("Error fetching code group by id:", error)
return null
}
}
|