summaryrefslogtreecommitdiff
path: root/lib/avl/history-service.ts
blob: fdad0ab9b769c42deb24906e7acf9f276cff9a33 (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
'use server';

import db from '@/db/db';
import { avlList } from '@/db/schema/avl/avl';
import { eq, and, desc } from 'drizzle-orm';
import { debugLog, debugError } from '@/lib/debug-utils';
import type {
  AvlHistoryRecord,
  VendorSnapshot,
} from './components/avl-history-modal';

/**
 * AVL 히스토리 조회 서비스
 * 프로젝트 AVL과 표준 AVL의 모든 리비전 히스토리를 조회합니다.
 */

/**
 * 프로젝트 AVL 히스토리 조회
 * @param projectCode 프로젝트 코드
 * @returns 모든 리비전의 히스토리 데이터
 */
export async function getProjectAvlHistory(
  projectCode: string
): Promise<AvlHistoryRecord[]> {
  try {
    debugLog('프로젝트 AVL 히스토리 조회 시작', { projectCode });

    // 동일 프로젝트 코드의 모든 AVL 리스트 조회 (isTemplate = false)
    const allRevisions = await db.query.avlList.findMany({
      where: and(
        eq(avlList.projectCode, projectCode),
        eq(avlList.isTemplate, false)
      ),
      orderBy: [desc(avlList.rev)],
    });

    debugLog('프로젝트 AVL 히스토리 조회 결과', {
      projectCode,
      revisionCount: allRevisions.length,
    });

    // 히스토리 레코드로 변환
    const historyData: AvlHistoryRecord[] = allRevisions.map((rev) => ({
      id: rev.id,
      rev: rev.rev || 1,
      createdAt: rev.createdAt?.toISOString() || new Date().toISOString(),
      createdBy: rev.createdBy || 'system',
      vendorInfoSnapshot: (rev.vendorInfoSnapshot as VendorSnapshot[]) || [],
      changeDescription: `리비전 ${
        rev.rev
      } - ${rev.createdAt?.toLocaleDateString('ko-KR')}`,
    }));

    return historyData;
  } catch (error) {
    debugError('프로젝트 AVL 히스토리 조회 실패', { projectCode, error });
    throw new Error(
      `프로젝트 AVL 히스토리 조회 중 오류가 발생했습니다: ${
        error instanceof Error ? error.message : 'Unknown error'
      }`
    );
  }
}

/**
 * 표준 AVL 히스토리 조회
 * @param constructionSector 공사부문
 * @param shipType 선종
 * @param avlKind AVL 종류
 * @param htDivision H/T 구분
 * @returns 모든 리비전의 히스토리 데이터
 */
export async function getStandardAvlHistory(
  constructionSector: string,
  shipType: string,
  avlKind: string,
  htDivision: string
): Promise<AvlHistoryRecord[]> {
  try {
    debugLog('표준 AVL 히스토리 조회 시작', {
      constructionSector,
      shipType,
      avlKind,
      htDivision,
    });

    // 동일 조건의 모든 표준 AVL 리스트 조회 (isTemplate = true)
    const allRevisions = await db.query.avlList.findMany({
      where: and(
        eq(avlList.constructionSector, constructionSector),
        eq(avlList.shipType, shipType),
        eq(avlList.avlKind, avlKind),
        eq(avlList.htDivision, htDivision),
        eq(avlList.isTemplate, true)
      ),
      orderBy: [desc(avlList.rev)],
    });

    debugLog('표준 AVL 히스토리 조회 결과', {
      constructionSector,
      shipType,
      avlKind,
      htDivision,
      revisionCount: allRevisions.length,
    });

    // 히스토리 레코드로 변환
    const historyData: AvlHistoryRecord[] = allRevisions.map((rev) => ({
      id: rev.id,
      rev: rev.rev || 1,
      createdAt: rev.createdAt?.toISOString() || new Date().toISOString(),
      createdBy: rev.createdBy || 'system',
      vendorInfoSnapshot: (rev.vendorInfoSnapshot as VendorSnapshot[]) || [],
      changeDescription: `리비전 ${
        rev.rev
      } - ${rev.createdAt?.toLocaleDateString('ko-KR')}`,
    }));

    return historyData;
  } catch (error) {
    debugError('표준 AVL 히스토리 조회 실패', {
      constructionSector,
      shipType,
      avlKind,
      htDivision,
      error,
    });
    throw new Error(
      `표준 AVL 히스토리 조회 중 오류가 발생했습니다: ${
        error instanceof Error ? error.message : 'Unknown error'
      }`
    );
  }
}

/**
 * AVL 아이템에 따른 히스토리 조회 (통합 함수)
 * @param avlItem AVL 리스트 아이템
 * @returns 해당 AVL의 모든 리비전 히스토리
 */
export async function getAvlHistory(avlItem: any): Promise<AvlHistoryRecord[]> {
  try {
    if (avlItem.isTemplate) {
      // 표준 AVL인 경우
      return await getStandardAvlHistory(
        avlItem.constructionSector,
        avlItem.shipType,
        avlItem.avlKind,
        avlItem.htDivision
      );
    } else {
      // 프로젝트 AVL인 경우
      return await getProjectAvlHistory(avlItem.projectCode);
    }
  } catch (error) {
    debugError('AVL 히스토리 조회 실패', { avlItem, error });
    throw new Error(
      `AVL 히스토리 조회 중 오류가 발생했습니다: ${
        error instanceof Error ? error.message : 'Unknown error'
      }`
    );
  }
}