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
|
import { unstable_cache } from "next/cache"
import { and, desc, asc, eq, or, ilike, count, max } from "drizzle-orm"
import db from "@/db/db"
import { gtcDocuments, type GtcDocument, type GtcDocumentWithRelations } from "@/db/schema/gtc"
import { projects } from "@/db/schema/projects"
import { users } from "@/db/schema/users"
import { filterColumns } from "@/lib/filter-columns"
import type { GetGtcDocumentsSchema, CreateGtcDocumentSchema, UpdateGtcDocumentSchema, CreateNewRevisionSchema } from "./validations"
/**
* 프로젝트 존재 여부 확인
*/
export async function checkProjectExists(projectId: number): Promise<boolean> {
const result = await db
.select({ id: projects.id })
.from(projects)
.where(eq(projects.id, projectId))
.limit(1)
return result.length > 0
}
/**
* GTC 문서 관련 뷰/조인 쿼리를 위한 기본 select
*/
function selectGtcDocumentsWithRelations() {
return db
.select({
id: gtcDocuments.id,
type: gtcDocuments.type,
projectId: gtcDocuments.projectId,
revision: gtcDocuments.revision,
createdAt: gtcDocuments.createdAt,
createdById: gtcDocuments.createdById,
updatedAt: gtcDocuments.updatedAt,
updatedById: gtcDocuments.updatedById,
editReason: gtcDocuments.editReason,
isActive: gtcDocuments.isActive,
// 관계 데이터
project: {
id: projects.id,
code: projects.code,
name: projects.name,
},
createdBy: {
id: users.id,
name: users.name,
email: users.email,
},
updatedBy: {
id: users.id,
name: users.name,
email: users.email,
},
})
.from(gtcDocuments)
.leftJoin(projects, eq(gtcDocuments.projectId, projects.id))
.leftJoin(users, eq(gtcDocuments.createdById, users.id))
.leftJoin(users, eq(gtcDocuments.updatedById, users.id))
}
/**
* GTC 문서 개수 조회
*/
async function countGtcDocuments(tx: any, where: any) {
const result = await tx
.select({ count: count() })
.from(gtcDocuments)
.where(where)
return result[0]?.count ?? 0
}
/**
* GTC 문서 목록 조회 (필터링, 정렬, 페이징 지원)
*/
export async function getGtcDocuments(input: GetGtcDocumentsSchema) {
return unstable_cache(
async () => {
try {
const offset = (input.page - 1) * input.perPage
// (1) advancedWhere - 고급 필터
const advancedWhere = filterColumns({
table: gtcDocuments,
filters: input.filters,
joinOperator: input.joinOperator,
})
// (2) globalWhere - 전역 검색
let globalWhere
if (input.search) {
const s = `%${input.search}%`
globalWhere = or(
ilike(gtcDocuments.editReason, s),
ilike(projects.name, s),
ilike(projects.code, s)
)
}
// (3) 기본 필터들
const basicFilters = []
if (input.type && input.type !== "") {
basicFilters.push(eq(gtcDocuments.type, input.type))
}
if (input.projectId && input.projectId > 0) {
basicFilters.push(eq(gtcDocuments.projectId, input.projectId))
}
// 활성 문서만 조회 (기본값)
basicFilters.push(eq(gtcDocuments.isActive, true))
// (4) 최종 where 조건
const finalWhere = and(
advancedWhere,
globalWhere,
...basicFilters
)
// (5) 정렬
const orderBy =
input.sort.length > 0
? input.sort.map((item) => {
const column = gtcDocuments[item.id as keyof typeof gtcDocuments]
return item.desc ? desc(column) : asc(column)
})
: [desc(gtcDocuments.updatedAt)]
// (6) 데이터 조회
const { data, total } = await db.transaction(async (tx) => {
const data = await selectGtcDocumentsWithRelations()
.where(finalWhere)
.orderBy(...orderBy)
.offset(offset)
.limit(input.perPage)
const total = await countGtcDocuments(tx, finalWhere)
return { data, total }
})
const pageCount = Math.ceil(total / input.perPage)
return { data, pageCount }
} catch (err) {
console.error("Error fetching GTC documents:", err)
return { data: [], pageCount: 0 }
}
},
[JSON.stringify(input)],
{
revalidate: 3600,
tags: ["gtc-documents"],
}
)()
}
/**
* 특정 GTC 문서 조회
*/
export async function getGtcDocumentById(id: number): Promise<GtcDocumentWithRelations | null> {
const result = await selectGtcDocumentsWithRelations()
.where(eq(gtcDocuments.id, id))
.limit(1)
return result[0] || null
}
/**
* 다음 리비전 번호 조회
*/
export async function getNextRevision(type: "standard" | "project", projectId?: number): Promise<number> {
const where = projectId
? and(eq(gtcDocuments.type, type), eq(gtcDocuments.projectId, projectId))
: and(eq(gtcDocuments.type, type), eq(gtcDocuments.projectId, null))
const result = await db
.select({ maxRevision: max(gtcDocuments.revision) })
.from(gtcDocuments)
.where(where)
return (result[0]?.maxRevision ?? -1) + 1
}
/**
* GTC 문서 생성
*/
export async function createGtcDocument(
data: CreateGtcDocumentSchema & { createdById: number }
): Promise<GtcDocument> {
// 리비전 번호가 없는 경우 자동 생성
if (!data.revision && data.revision !== 0) {
data.revision = await getNextRevision(data.type, data.projectId || undefined)
}
const [newDocument] = await db
.insert(gtcDocuments)
.values({
...data,
updatedById: data.createdById, // 생성시에는 생성자와 수정자가 동일
})
.returning()
return newDocument
}
/**
* GTC 문서 업데이트
*/
export async function updateGtcDocument(
id: number,
data: UpdateGtcDocumentSchema & { updatedById: number }
): Promise<GtcDocument | null> {
const [updatedDocument] = await db
.update(gtcDocuments)
.set({
...data,
updatedAt: new Date(),
})
.where(eq(gtcDocuments.id, id))
.returning()
return updatedDocument || null
}
/**
* 새 리비전 생성
*/
export async function createNewRevision(
originalId: number,
data: CreateNewRevisionSchema & { createdById: number }
): Promise<GtcDocument | null> {
// 원본 문서 조회
const original = await getGtcDocumentById(originalId)
if (!original) {
throw new Error("Original document not found")
}
// 다음 리비전 번호 계산
const nextRevision = await getNextRevision(
original.type,
original.projectId || undefined
)
// 새 리비전 생성
const [newRevision] = await db
.insert(gtcDocuments)
.values({
type: original.type,
projectId: original.projectId,
revision: nextRevision,
editReason: data.editReason,
createdById: data.createdById,
updatedById: data.createdById,
})
.returning()
return newRevision
}
/**
* GTC 문서 삭제 (소프트 삭제)
*/
export async function deleteGtcDocument(
id: number,
updatedById: number
): Promise<boolean> {
const [updated] = await db
.update(gtcDocuments)
.set({
isActive: false,
updatedById,
updatedAt: new Date(),
})
.where(eq(gtcDocuments.id, id))
.returning()
return !!updated
}
/**
* 프로젝트별 GTC 문서 목록 조회
*/
export async function getGtcDocumentsByProject(projectId: number): Promise<GtcDocumentWithRelations[]> {
return await selectGtcDocumentsWithRelations()
.where(
and(
eq(gtcDocuments.projectId, projectId),
eq(gtcDocuments.isActive, true)
)
)
.orderBy(desc(gtcDocuments.revision))
}
/**
* 표준 GTC 문서 목록 조회
*/
export async function getStandardGtcDocuments(): Promise<GtcDocumentWithRelations[]> {
return await selectGtcDocumentsWithRelations()
.where(
and(
eq(gtcDocuments.type, "standard"),
eq(gtcDocuments.isActive, true)
)
)
.orderBy(desc(gtcDocuments.revision))
}
// 타입 정의
export type ProjectForFilter = {
id: number
code: string
name: string
}
export type UserForFilter = {
id: number
name: string
email: string
}
/**
* 프로젝트 목록 조회 (필터용)
*/
export async function getProjectsForFilter(): Promise<ProjectForFilter[]> {
return await db
.select({
id: projects.id,
code: projects.code,
name: projects.name,
})
.from(projects)
.orderBy(projects.name)
}
/**
* 프로젝트 목록 조회 (선택용)
*/
export async function getProjectsForSelect(): Promise<ProjectForFilter[]> {
return await db
.select({
id: projects.id,
code: projects.code,
name: projects.name,
})
.from(projects)
.orderBy(projects.name)
}
/**
* 사용자 목록 조회 (필터용)
*/
export async function getUsersForFilter(): Promise<UserForFilter[]> {
return await db
.select({
id: users.id,
name: users.name,
email: users.email,
})
.from(users)
.where(eq(users.isActive, true)) // 활성 사용자만
.orderBy(users.name)
}
|