summaryrefslogtreecommitdiff
path: root/lib/esg-check-list/service.ts
blob: 500cd82c241e0368dddd30f564d0a78611af0110 (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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
'use server'

import { and, asc, desc, ilike, or } from 'drizzle-orm';
import db  from '@/db/db';
import { filterColumns } from "@/lib/filter-columns";


import { 
  esgEvaluations, 
  esgEvaluationItems, 
  esgAnswerOptions,
  NewEsgEvaluation,
  NewEsgEvaluationItem,
  NewEsgAnswerOption,
  EsgEvaluationWithItems,
  esgEvaluationsView
} from '@/db/schema';
import { eq } from 'drizzle-orm';
import { GetEsgEvaluationsSchema } from './validation';
import { countEsgEvaluations, getEsgEvaluationWithDetails, selectEsgEvaluations } from './repository';

// ============ 조회 함수들 ============

export async function getEsgEvaluations(input: GetEsgEvaluationsSchema) {
  try {
    const offset = (input.page - 1) * input.perPage;
    
    // 고급 필터링
    const advancedWhere = filterColumns({
      table: esgEvaluationsView,
      filters: input.filters,
      joinOperator: input.joinOperator,
    });

    // 전역 검색
    let globalWhere;
    if (input.search) {
      const s = `%${input.search}%`;
      globalWhere = or(
        ilike(esgEvaluationsView.serialNumber, s),
        ilike(esgEvaluationsView.category, s),
        ilike(esgEvaluationsView.inspectionItem, s)
      );
    }

    const finalWhere = and(advancedWhere, globalWhere);

    // 정렬
    const orderBy = input.sort.length > 0
      ? input.sort.map((item) => {
          return item.desc
            ? desc(esgEvaluationsView[item.id])
            : asc(esgEvaluationsView[item.id]);
        })
      : [desc(esgEvaluationsView.createdAt)];

    // 데이터 조회
    const { data, total } = await db.transaction(async (tx) => {
      const data = await selectEsgEvaluations(tx, {
        where: finalWhere,
        orderBy,
        offset,
        limit: input.perPage,
      });

      const total = await countEsgEvaluations(tx, finalWhere);
      return { data, total };
    });

    const pageCount = Math.ceil(total / input.perPage);
    return { data, pageCount };
  } catch (err) {
    console.error('Error in getEsgEvaluations:', err);
    return { data: [], pageCount: 0 };
  }
}

// 단일 평가표 상세 조회 (평가항목과 답변 옵션 포함)
export async function getEsgEvaluationDetails(id: number) {
  try {
    return await db.transaction(async (tx) => {
      return await getEsgEvaluationWithDetails(tx, id);
    });
  } catch (err) {
    console.error('Error in getEsgEvaluationDetails:', err);
    return null;
  }
}

// ============ 생성 함수들 ============

export async function createEsgEvaluation(data: NewEsgEvaluation) {
  try {
    return await db.transaction(async (tx) => {
      const [result] = await tx
        .insert(esgEvaluations)
        .values(data)
        .returning();
      return result;
    });
  } catch (err) {
    console.error('Error creating ESG evaluation:', err);
    throw new Error('Failed to create ESG evaluation');
  }
}

export async function createEsgEvaluationWithItems(
  evaluationData: NewEsgEvaluation,
  items: Array<{
    evaluationItem: string;
    orderIndex?: number;
    answerOptions: Array<{
      answerText: string;
      score: number;
      orderIndex?: number;
    }>;
  }>
) {
  try {
    return await db.transaction(async (tx) => {
      // 1. 평가표 생성
      const [evaluation] = await tx
        .insert(esgEvaluations)
        .values(evaluationData)
        .returning();

      // 2. 평가항목들 생성
      for (let i = 0; i < items.length; i++) {
        const item = items[i];
        const [evaluationItem] = await tx
          .insert(esgEvaluationItems)
          .values({
            esgEvaluationId: evaluation.id,
            evaluationItem: item.evaluationItem,
            orderIndex: item.orderIndex ?? i,
          })
          .returning();

        // 3. 답변 옵션들 생성
        if (item.answerOptions.length > 0) {
          await tx.insert(esgAnswerOptions).values(
            item.answerOptions.map((option, optionIndex) => ({
              esgEvaluationItemId: evaluationItem.id,
              answerText: option.answerText,
              score: option.score.toString(),
              orderIndex: option.orderIndex ?? optionIndex,
            }))
          );
        }
      }

      return evaluation;
    });
  } catch (err) {
    console.error('Error creating ESG evaluation with items:', err);
    throw new Error('Failed to create ESG evaluation with items');
  }
}

// ============ 수정 함수들 ============

export async function updateEsgEvaluation(
  id: number,
  data: Partial<NewEsgEvaluation>
) {
  try {
    return await db.transaction(async (tx) => {
      const [result] = await tx
        .update(esgEvaluations)
        .set({ ...data, updatedAt: new Date() })
        .where(eq(esgEvaluations.id, id))
        .returning();
      return result;
    });
  } catch (err) {
    console.error('Error updating ESG evaluation:', err);
    throw new Error('Failed to update ESG evaluation');
  }
}

export async function updateEsgEvaluationItem(
  id: number,
  data: Partial<NewEsgEvaluationItem>
) {
  try {
    return await db.transaction(async (tx) => {
      const [result] = await tx
        .update(esgEvaluationItems)
        .set({ ...data, updatedAt: new Date() })
        .where(eq(esgEvaluationItems.id, id))
        .returning();
      return result;
    });
  } catch (err) {
    console.error('Error updating ESG evaluation item:', err);
    throw new Error('Failed to update ESG evaluation item');
  }
}

export async function updateEsgAnswerOption(
  id: number,
  data: Partial<NewEsgAnswerOption>
) {
  try {
    return await db.transaction(async (tx) => {
      const [result] = await tx
        .update(esgAnswerOptions)
        .set({ ...data, updatedAt: new Date() })
        .where(eq(esgAnswerOptions.id, id))
        .returning();
      return result;
    });
  } catch (err) {
    console.error('Error updating ESG answer option:', err);
    throw new Error('Failed to update ESG answer option');
  }
}

// ============ 삭제 함수들 ============

export async function deleteEsgEvaluation(id: number) {
  try {
    return await db.transaction(async (tx) => {
      // Cascade delete가 설정되어 있어서 평가항목과 답변옵션들도 자동 삭제됨
      const [result] = await tx
        .delete(esgEvaluations)
        .where(eq(esgEvaluations.id, id))
        .returning();
      return result;
    });
  } catch (err) {
    console.error('Error deleting ESG evaluation:', err);
    throw new Error('Failed to delete ESG evaluation');
  }
}

export async function deleteEsgEvaluationItem(id: number) {
  try {
    return await db.transaction(async (tx) => {
      // Cascade delete가 설정되어 있어서 답변옵션들도 자동 삭제됨
      const [result] = await tx
        .delete(esgEvaluationItems)
        .where(eq(esgEvaluationItems.id, id))
        .returning();
      return result;
    });
  } catch (err) {
    console.error('Error deleting ESG evaluation item:', err);
    throw new Error('Failed to delete ESG evaluation item');
  }
}

export async function deleteEsgAnswerOption(id: number) {
  try {
    return await db.transaction(async (tx) => {
      const [result] = await tx
        .delete(esgAnswerOptions)
        .where(eq(esgAnswerOptions.id, id))
        .returning();
      return result;
    });
  } catch (err) {
    console.error('Error deleting ESG answer option:', err);
    throw new Error('Failed to delete ESG answer option');
  }
}

// ============ 소프트 삭제 함수들 ============

export async function softDeleteEsgEvaluation(id: number) {
  return updateEsgEvaluation(id, { isActive: false });
}

export async function softDeleteEsgEvaluationItem(id: number) {
  return updateEsgEvaluationItem(id, { isActive: false });
}

export async function softDeleteEsgAnswerOption(id: number) {
  return updateEsgAnswerOption(id, { isActive: false });
}



export async function updateEsgEvaluationWithItems(
  id: number,
  evaluationData: {
    serialNumber: string;
    category: string;
    inspectionItem: string;
  },
  items: Array<{
    evaluationItem: string;
    evaluationItemDescription: string;
    answerOptions: Array<{
      answerText: string;
      score: number;
    }>;
  }>
) {
  try {
    return await db.transaction(async (tx) => {
      // 1. 기본 정보 수정
      const [updatedEvaluation] = await tx
        .update(esgEvaluations)
        .set({
          ...evaluationData,
          updatedAt: new Date(),
        })
        .where(eq(esgEvaluations.id, id))
        .returning();

      // 2. 기존 평가항목들과 답변 옵션들 모두 삭제 (cascade delete로 답변옵션도 함께 삭제됨)
      await tx
        .delete(esgEvaluationItems)
        .where(eq(esgEvaluationItems.esgEvaluationId, id));

      // 3. 새로운 평가항목들과 답변 옵션들 생성
      for (let i = 0; i < items.length; i++) {
        const item = items[i];
        
        const [evaluationItem] = await tx
          .insert(esgEvaluationItems)
          .values({
            esgEvaluationId: id,
            evaluationItem: item.evaluationItem,
            orderIndex: i,
          })
          .returning();

        // 답변 옵션들 생성
        if (item.answerOptions.length > 0) {
          await tx.insert(esgAnswerOptions).values(
            item.answerOptions.map((option, optionIndex) => ({
              esgEvaluationItemId: evaluationItem.id,
              answerText: option.answerText,
              score: option.score.toString(),
              orderIndex: optionIndex,
            }))
          );
        }
      }

      return updatedEvaluation;
    });
  } catch (err) {
    console.error('Error updating ESG evaluation with items:', err);
    
    // 시리얼 번호 중복 에러 처리
    if (err instanceof Error && err.message.includes('unique')) {
      throw new Error('이미 존재하는 시리얼번호입니다.');
    }
    
    throw new Error('평가표 수정에 실패했습니다.');
  }
}

// ============ 소프트 삭제 버전 (데이터 보존) ============

export async function updateEsgEvaluationWithItemsSoft(
  id: number,
  evaluationData: {
    serialNumber: string;
    category: string;
    inspectionItem: string;
  },
  items: Array<{
    evaluationItem: string;
    answerOptions: Array<{
      answerText: string;
      score: number;
    }>;
  }>
) {
  try {
    return await db.transaction(async (tx) => {
      // 1. 기본 정보 수정
      const [updatedEvaluation] = await tx
        .update(esgEvaluations)
        .set({
          ...evaluationData,
          updatedAt: new Date(),
        })
        .where(eq(esgEvaluations.id, id))
        .returning();

      // 2. 기존 평가항목들 소프트 삭제
      await tx
        .update(esgEvaluationItems)
        .set({ isActive: false, updatedAt: new Date() })
        .where(eq(esgEvaluationItems.esgEvaluationId, id));

      // 기존 답변 옵션들도 소프트 삭제
      const existingItems = await tx
        .select({ id: esgEvaluationItems.id })
        .from(esgEvaluationItems)
        .where(eq(esgEvaluationItems.esgEvaluationId, id));

      for (const item of existingItems) {
        await tx
          .update(esgAnswerOptions)
          .set({ isActive: false, updatedAt: new Date() })
          .where(eq(esgAnswerOptions.esgEvaluationItemId, item.id));
      }

      // 3. 새로운 평가항목들과 답변 옵션들 생성
      for (let i = 0; i < items.length; i++) {
        const item = items[i];
        
        const [evaluationItem] = await tx
          .insert(esgEvaluationItems)
          .values({
            esgEvaluationId: id,
            evaluationItem: item.evaluationItem,
            orderIndex: i,
          })
          .returning();

        // 답변 옵션들 생성
        if (item.answerOptions.length > 0) {
          await tx.insert(esgAnswerOptions).values(
            item.answerOptions.map((option, optionIndex) => ({
              esgEvaluationItemId: evaluationItem.id,
              answerText: option.answerText,
              score: option.score.toString(),
              orderIndex: optionIndex,
            }))
          );
        }
      }

      return updatedEvaluation;
    });
  } catch (err) {
    console.error('Error updating ESG evaluation with items (soft):', err);
    
    if (err instanceof Error && err.message.includes('unique')) {
      throw new Error('이미 존재하는 시리얼번호입니다.');
    }
    
    throw new Error('평가표 수정에 실패했습니다.');
  }
}

// ============ 생성 함수 개선 (에러 처리 추가) ============

export async function createEsgEvaluationWithItemsEnhanced(
  evaluationData: {
    serialNumber: string;
    category: string;
    inspectionItem: string;
  },
  items: Array<{
    evaluationItem: string;
    evaluationItemDescription: string;
    answerOptions: Array<{
      answerText: string;
      score: number;
    }>;
  }>
) {
  try {
    return await db.transaction(async (tx) => {
      // 1. 평가표 생성
      const [evaluation] = await tx
        .insert(esgEvaluations)
        .values(evaluationData)
        .returning();

      // 2. 평가항목들과 답변 옵션들 생성
      for (let i = 0; i < items.length; i++) {
        const item = items[i];
        
        const [evaluationItem] = await tx
          .insert(esgEvaluationItems)
          .values({
            esgEvaluationId: evaluation.id,
            evaluationItem: item.evaluationItem,
            evaluationItemDescription: item.evaluationItemDescription,
            orderIndex: i,
          })
          .returning();

        // 답변 옵션들 생성
        if (item.answerOptions.length > 0) {
          await tx.insert(esgAnswerOptions).values(
            item.answerOptions.map((option, optionIndex) => ({
              esgEvaluationItemId: evaluationItem.id,
              answerText: option.answerText,
              score: option.score.toString(),
              orderIndex: optionIndex,
            }))
          );
        }
      }

      return evaluation;
    });
  } catch (err) {
    console.error('Error creating ESG evaluation with items:', err);
    
    // 시리얼 번호 중복 에러 처리
    if (err instanceof Error && err.message.includes('unique')) {
      throw new Error('이미 존재하는 시리얼번호입니다.');
    }
    
    throw new Error('평가표 생성에 실패했습니다.');
  }
}

export async function deleteEsgEvaluationsBatch(ids: number[]) {
  try {
    if (ids.length === 0) {
      throw new Error('삭제할 평가표가 없습니다.');
    }

    return await db.transaction(async (tx) => {
      let deletedCount = 0;
      
      for (const id of ids) {
        try {
          // 각 평가표 삭제 (cascade delete로 관련 데이터도 함께 삭제됨)
          await tx
            .delete(esgEvaluations)
            .where(eq(esgEvaluations.id, id));
          
          deletedCount++;
        } catch (error) {
          console.error(`Error deleting evaluation ${id}:`, error);
          // 개별 삭제 실패는 로그만 남기고 계속 진행
        }
      }

      return {
        total: ids.length,
        deleted: deletedCount,
        failed: ids.length - deletedCount
      };
    });
  } catch (err) {
    console.error('Error in batch delete ESG evaluations:', err);
    throw new Error('평가표 일괄 삭제에 실패했습니다.');
  }
}

export async function softDeleteEsgEvaluationsBatch(ids: number[]) {
  try {
    if (ids.length === 0) {
      throw new Error('삭제할 평가표가 없습니다.');
    }

    return await db.transaction(async (tx) => {
      let deletedCount = 0;
      
      for (const id of ids) {
        try {
          // 평가표 소프트 삭제
          await tx
            .update(esgEvaluations)
            .set({ 
              isActive: false,
              updatedAt: new Date(),
            })
            .where(eq(esgEvaluations.id, id));

          // 관련 평가항목들 소프트 삭제
          await tx
            .update(esgEvaluationItems)
            .set({ isActive: false, updatedAt: new Date() })
            .where(eq(esgEvaluationItems.esgEvaluationId, id));

          // 관련 답변 옵션들 소프트 삭제
          const evaluationItems = await tx
            .select({ id: esgEvaluationItems.id })
            .from(esgEvaluationItems)
            .where(eq(esgEvaluationItems.esgEvaluationId, id));

          for (const item of evaluationItems) {
            await tx
              .update(esgAnswerOptions)
              .set({ isActive: false, updatedAt: new Date() })
              .where(eq(esgAnswerOptions.esgEvaluationItemId, item.id));
          }
          
          deletedCount++;
        } catch (error) {
          console.error(`Error soft deleting evaluation ${id}:`, error);
          // 개별 삭제 실패는 로그만 남기고 계속 진행
        }
      }

      return {
        total: ids.length,
        deleted: deletedCount,
        failed: ids.length - deletedCount
      };
    });
  } catch (err) {
    console.error('Error in batch soft delete ESG evaluations:', err);
    throw new Error('평가표 일괄 삭제에 실패했습니다.');
  }
}