summaryrefslogtreecommitdiff
path: root/lib/docu-list-rule/number-types/service.ts
blob: c4a0cdacbd551f43a7b86a46d23e8df014d30a59 (plain)
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
"use server"

import { revalidatePath } from "next/cache"
import db from "@/db/db"
import { documentNumberTypes, documentNumberTypeConfigs, codeGroups } from "@/db/schema/docu-list-rule"
import { projects } from "@/db/schema/projects"
import { eq, sql, and } from "drizzle-orm"
import { unstable_noStore } from "next/cache"

// Number Types 목록 조회
export async function getNumberTypes(input: {
  page: number
  perPage: number
  search?: string
  sort?: Array<{ id: string; desc: boolean }>
  filters?: Array<{ id: string; value: string }>
  joinOperator?: "and" | "or"
  flags?: string[]
  numberTypeId?: string
  description?: string
  isActive?: string
  projectId?: string
}) {
  unstable_noStore()
  
  try {
    const { page, perPage, sort, search, filters, joinOperator } = input
    const offset = (page - 1) * perPage

    // 기본 조건 (plant 타입 프로젝트만)
    let whereConditions = sql`${projects.type} = 'plant'`
    
    // 프로젝트 ID 필터링
    if (input.projectId) {
      whereConditions = sql`${whereConditions} AND ${documentNumberTypes.projectId} = ${parseInt(input.projectId)}`
    }
    
    // 검색 조건
    if (search) {
      const searchTerm = `%${search}%`
      whereConditions = sql`${whereConditions} AND (
        ${documentNumberTypes.name} ILIKE ${searchTerm} OR
        ${documentNumberTypes.description} ILIKE ${searchTerm} OR
        ${projects.code} ILIKE ${searchTerm}
      )`
    }

    // 고급 필터링
    if (filters && filters.length > 0) {
      const filterConditions = filters.map(filter => {
        const { id, value } = filter
        if (!value) return null
        
        switch (id) {
          case "name":
            return sql`${documentNumberTypes.name} ILIKE ${`%${value}%`}`
          case "description":
            return sql`${documentNumberTypes.description} ILIKE ${`%${value}%`}`
          case "isActive":
            return sql`${documentNumberTypes.isActive} = ${value === "true"}`
          case "createdAt":
            return sql`${documentNumberTypes.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`${documentNumberTypes.name} ASC`
    if (sort && sort.length > 0) {
      const sortField = sort[0]
      // 안전성 체크: 필드가 실제 테이블에 존재하는지 확인
      if (sortField && sortField.id && typeof sortField.id === "string") {
        const direction = sortField.desc ? sql`DESC` : sql`ASC`
        
        // 프로젝트 코드 정렬 처리
        if (sortField.id === "projectCode") {
          orderBy = sql`${projects.code} ${direction}`
        } else if (sortField.id in documentNumberTypes) {
          const col = documentNumberTypes[sortField.id as keyof typeof documentNumberTypes]
          orderBy = sql`${col} ${direction}`
        }
      }
    }

    // 데이터 조회 (프로젝트 정보 포함)
    const data = await db
      .select({
        id: documentNumberTypes.id,
        name: documentNumberTypes.name,
        description: documentNumberTypes.description,
        isActive: documentNumberTypes.isActive,
        createdAt: documentNumberTypes.createdAt,
        updatedAt: documentNumberTypes.updatedAt,
        projectId: documentNumberTypes.projectId,
        projectCode: projects.code,
        projectName: projects.name,
      })
      .from(documentNumberTypes)
      .leftJoin(projects, eq(documentNumberTypes.projectId, projects.id))
      .where(whereConditions)
      .orderBy(orderBy)
      .limit(perPage)
      .offset(offset)

    // 총 개수 조회 (프로젝트 정보 포함)
    const totalCountResult = await db
      .select({ count: sql<number>`count(*)` })
      .from(documentNumberTypes)
      .leftJoin(projects, eq(documentNumberTypes.projectId, projects.id))
      .where(whereConditions)

    const totalCount = totalCountResult[0]?.count || 0

    return {
      data,
      totalCount,
      pageCount: Math.ceil(totalCount / perPage),
    }
  } catch (error) {
    console.error("Error fetching number types:", error)
    return {
      data: [],
      totalCount: 0,
      pageCount: 0,
    }
  }
}

// Number Type 생성
export async function createNumberType(input: {
  projectId: number
  name: string
  description?: string
  isActive?: boolean
}) {
  try {
    // 해당 프로젝트에서 중복 이름 체크
    const existing = await db
      .select({ id: documentNumberTypes.id })
      .from(documentNumberTypes)
      .where(and(
        eq(documentNumberTypes.projectId, input.projectId),
        eq(documentNumberTypes.name, input.name)
      ))
      .limit(1)

    if (existing.length > 0) {
      return {
        success: false,
        error: "Number Type with this name already exists in this project"
      }
    }

    const [newNumberType] = await db
      .insert(documentNumberTypes)
      .values({
        projectId: input.projectId,
        name: input.name,
        description: input.description,
        isActive: input.isActive ?? true,
      })
      .returning({ id: documentNumberTypes.id })

    revalidatePath("/evcp/docu-list-rule/number-types")
    
    return {
      success: true,
      data: newNumberType,
      message: "Number Type created successfully"
    }
  } catch (error) {
    console.error("Error creating number type:", error)
    return {
      success: false,
      error: "Failed to create number type"
    }
  }
}

// Number Type 수정
export async function updateNumberType(input: {
  id: number
  name: string
  description?: string
  isActive?: boolean
}) {
  try {
    // 다른 Number Type에서 같은 이름 사용하는지 체크
    const existing = await db
      .select({ id: documentNumberTypes.id })
      .from(documentNumberTypes)
      .where(sql`${documentNumberTypes.name} = ${input.name} AND ${documentNumberTypes.id} != ${input.id}`)
      .limit(1)

    if (existing.length > 0) {
      return {
        success: false,
        error: "Number Type with this name already exists"
      }
    }

    const [updatedNumberType] = await db
      .update(documentNumberTypes)
      .set({
        name: input.name,
        description: input.description,
        isActive: input.isActive,
        updatedAt: new Date(),
      })
      .where(eq(documentNumberTypes.id, input.id))
      .returning({ id: documentNumberTypes.id })

    if (!updatedNumberType) {
      return {
        success: false,
        error: "Number Type not found"
      }
    }

    revalidatePath("/evcp/docu-list-rule/number-types")
    
    return {
      success: true,
      data: updatedNumberType,
      message: "Number Type updated successfully"
    }
  } catch (error) {
    console.error("Error updating number type:", error)
    return {
      success: false,
      error: "Failed to update number type"
    }
  }
}

// Number Type 삭제
export async function deleteNumberType(id: number) {
  try {
    // Number Type 정보 조회
    const numberType = await db
      .select({
        id: documentNumberTypes.id,
        name: documentNumberTypes.name,
        description: documentNumberTypes.description
      })
      .from(documentNumberTypes)
      .where(eq(documentNumberTypes.id, id))
      .limit(1)

    if (numberType.length === 0) {
      return {
        success: false,
        error: "Number Type not found"
      }
    }

    // 관련된 config가 있는지 확인 (Code Group 정보 포함)
    const relatedConfigs = await db
      .select({
        id: documentNumberTypeConfigs.id,
        codeGroupDescription: codeGroups.description
      })
      .from(documentNumberTypeConfigs)
      .leftJoin(codeGroups, eq(documentNumberTypeConfigs.codeGroupId, codeGroups.id))
      .where(eq(documentNumberTypeConfigs.documentNumberTypeId, id))

    // 설정 정보를 반환 (삭제는 허용하되 경고용)
    const configInfo = relatedConfigs.length > 0 ? {
      hasConfigs: true,
      codeGroupNames: relatedConfigs.map(config => 
        config.codeGroupDescription || "Unknown Code Group"
      )
    } : {
      hasConfigs: false,
      codeGroupNames: []
    }

    // Number Type 삭제 (CASCADE로 관련 config들도 자동 삭제됨)
    await db
      .delete(documentNumberTypes)
      .where(eq(documentNumberTypes.id, id))

    revalidatePath("/evcp/docu-list-rule/number-types")
    
    return {
      success: true,
      message: configInfo.hasConfigs 
        ? `Number Type "${numberType[0].name}"이(가) 설정과 함께 삭제되었습니다.`
        : "Number Type deleted successfully",
      configInfo
    }
  } catch (error) {
    console.error("Error deleting number type:", error)
    return {
      success: false,
      error: "Failed to delete number type"
    }
  }
}

// Number Type 설정 정보 확인 (삭제하지 않고 정보만 반환)
export async function checkNumberTypeConfigs(id: number) {
  try {
    // Number Type 정보 조회
    const numberType = await db
      .select({
        id: documentNumberTypes.id,
        name: documentNumberTypes.name,
        description: documentNumberTypes.description
      })
      .from(documentNumberTypes)
      .where(eq(documentNumberTypes.id, id))
      .limit(1)

    if (numberType.length === 0) {
      return {
        success: false,
        error: "Number Type not found"
      }
    }

    // 관련된 config가 있는지 확인 (Code Group 정보 포함)
    const relatedConfigs = await db
      .select({
        id: documentNumberTypeConfigs.id,
        codeGroupDescription: codeGroups.description
      })
      .from(documentNumberTypeConfigs)
      .leftJoin(codeGroups, eq(documentNumberTypeConfigs.codeGroupId, codeGroups.id))
      .where(eq(documentNumberTypeConfigs.documentNumberTypeId, id))

    const configInfo = relatedConfigs.length > 0 ? {
      hasConfigs: true,
      codeGroupNames: relatedConfigs.map(config => 
        config.codeGroupDescription || "Unknown Code Group"
      )
    } : {
      hasConfigs: false,
      codeGroupNames: []
    }

    return {
      success: true,
      data: {
        numberType: numberType[0],
        configInfo
      }
    }
  } catch (error) {
    console.error("Error checking number type configs:", error)
    return {
      success: false,
      error: "Failed to check number type configs"
    }
  }
}

// Number Types 목록 조회 (설정 정보 포함)
export async function getNumberTypesWithConfigs(input: {
  page: number
  perPage: number
  search?: string
  sort?: Array<{ id: string; desc: boolean }>
  filters?: Array<{ id: string; value: string }>
  joinOperator?: "and" | "or"
  flags?: string[]
  numberTypeId?: string
  description?: string
  isActive?: string
  projectId?: string
}) {
  unstable_noStore()
  
  try {
    const { page, perPage, sort, search, filters, joinOperator } = input
    const offset = (page - 1) * perPage

    // 기본 조건 (plant 타입 프로젝트만)
    let whereConditions = sql`${projects.type} = 'plant'`
    
    // 프로젝트 ID 필터링
    if (input.projectId) {
      whereConditions = sql`${whereConditions} AND ${documentNumberTypes.projectId} = ${parseInt(input.projectId)}`
    }
    
    // 검색 조건
    if (search) {
      const searchTerm = `%${search}%`
      whereConditions = sql`${whereConditions} AND (
        ${documentNumberTypes.name} ILIKE ${searchTerm} OR
        ${documentNumberTypes.description} ILIKE ${searchTerm} OR
        ${projects.code} ILIKE ${searchTerm}
      )`
    }

    // 고급 필터링
    if (filters && filters.length > 0) {
      const filterConditions = filters.map(filter => {
        const { id, value } = filter
        if (!value) return null
        
        switch (id) {
          case "name":
            return sql`${documentNumberTypes.name} ILIKE ${`%${value}%`}`
          case "description":
            return sql`${documentNumberTypes.description} ILIKE ${`%${value}%`}`
          case "isActive":
            return sql`${documentNumberTypes.isActive} = ${value === "true"}`
          case "createdAt":
            return sql`${documentNumberTypes.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`${documentNumberTypes.name} ASC`
    if (sort && sort.length > 0) {
      const sortField = sort[0]
      // 안전성 체크: 필드가 실제 테이블에 존재하는지 확인
      if (sortField && sortField.id && typeof sortField.id === "string") {
        const direction = sortField.desc ? sql`DESC` : sql`ASC`
        
        // 프로젝트 코드 정렬 처리
        if (sortField.id === "projectCode") {
          orderBy = sql`${projects.code} ${direction}`
        } else if (sortField.id in documentNumberTypes) {
          const col = documentNumberTypes[sortField.id as keyof typeof documentNumberTypes]
          orderBy = sql`${col} ${direction}`
        }
      }
    }

    // 데이터 조회 (프로젝트 정보 포함)
    const data = await db
      .select({
        id: documentNumberTypes.id,
        name: documentNumberTypes.name,
        description: documentNumberTypes.description,
        isActive: documentNumberTypes.isActive,
        createdAt: documentNumberTypes.createdAt,
        updatedAt: documentNumberTypes.updatedAt,
        projectId: documentNumberTypes.projectId,
        projectCode: projects.code,
        projectName: projects.name,
        projectType: projects.type,
      })
      .from(documentNumberTypes)
      .leftJoin(projects, eq(documentNumberTypes.projectId, projects.id))
      .where(whereConditions)
      .orderBy(orderBy)
      .limit(perPage)
      .offset(offset)

    // 각 Number Type에 대한 설정 정보 조회
    const dataWithConfigs = await Promise.all(
      data.map(async (numberType) => {
        const relatedConfigs = await db
          .select({
            id: documentNumberTypeConfigs.id,
            codeGroupDescription: codeGroups.description
          })
          .from(documentNumberTypeConfigs)
          .leftJoin(codeGroups, eq(documentNumberTypeConfigs.codeGroupId, codeGroups.id))
          .where(eq(documentNumberTypeConfigs.documentNumberTypeId, numberType.id))

        const configInfo = relatedConfigs.length > 0 ? {
          hasConfigs: true,
          codeGroupNames: relatedConfigs.map(config => 
            config.codeGroupDescription || "Unknown Code Group"
          )
        } : {
          hasConfigs: false,
          codeGroupNames: []
        }

        return {
          ...numberType,
          configInfo
        }
      })
    )

    // 전체 개수 조회
    const totalCount = await db
      .select({ count: sql<number>`count(*)` })
      .from(documentNumberTypes)
      .leftJoin(projects, eq(documentNumberTypes.projectId, projects.id))
      .where(whereConditions)

    return {
      data: dataWithConfigs,
      totalCount: totalCount[0].count,
      pageCount: Math.ceil(totalCount[0].count / perPage),
    }
  } catch (error) {
    console.error("Error fetching number types with configs:", error)
    return {
      data: [],
      totalCount: 0,
      pageCount: 0,
    }
  }
} 

export async function checkNumberTypesExist(projectId: number, names: string[]): Promise<boolean> {
  try {
    const existing = await db
      .select({ name: documentNumberTypes.name })
      .from(documentNumberTypes)
      .where(and(
        eq(documentNumberTypes.projectId, projectId),
        inArray(documentNumberTypes.name, names)
      ))

    // 모든 name이 존재하는지 체크
    return existing.length === names.length
  } catch (error) {
    console.error("Error checking number types:", error)
    return false
  }
}