summaryrefslogtreecommitdiff
path: root/lib/forms/sedp-actions.ts
blob: 4883a33fce0bc7e2ed0aae0bf3be8cf9b19a8b34 (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
"use server";

import { getSEDPToken } from "@/lib/sedp/sedp-token";

interface SEDPTagData {
  [tableName: string]: Array<{
    TAG_NO: string;
    TAG_DESC: string;
    ATTRIBUTES: Array<{
      ATT_ID: string;
      VALUE: string;
    }>;
  }>;
}

interface SEDPTemplateData {
  templateId: string;
  content: string;
  projectNo: string;
  regTypeId: string;
  [key: string]: any;
}

// ๐Ÿ” ์‹ค์ œ SEDP API ์‘๋‹ต ๊ตฌ์กฐ (๋Œ€๋ฌธ์ž)
interface SEDPTemplateResponse {
  TMPL_ID: string;
  NAME: string;
  TMPL_TYPE: string;
  SPR_LST_SETUP?: {
    ACT_SHEET: string;
    HIDN_SHEETS: string[];
    CONTENT?: string;
    DATA_SHEETS: Array<{
      SHEET_NAME: string;
      REG_TYPE_ID: string;
      MAP_CELL_ATT: Array<{
        ATT_ID: string;
        IN: string;
      }>;
    }>;
  };
  GRD_LST_SETUP?: {
    REG_TYPE_ID: string;
    SPR_ITM_IDS: string[];
    ATTS: any[];
  };
  SPR_ITM_LST_SETUP?: {
    ACT_SHEET: string;
    HIDN_SHEETS: string[];
    CONTENT?: string;
    DATA_SHEETS: Array<{
      SHEET_NAME: string;
      REG_TYPE_ID: string;
      MAP_CELL_ATT: Array<{
        ATT_ID: string;
        IN: string;
      }>;
    }>;
  };
  [key: string]: any;
}

/**
 * SEDP์—์„œ ํƒœ๊ทธ ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€์ ธ์˜ค๋Š” ์„œ๋ฒ„ ์•ก์…˜
 */
export async function fetchTagDataFromSEDP(
  projectCode: string, 
  formCode: string
): Promise<SEDPTagData> {
  try {
    // Get the token
    const apiKey = await getSEDPToken();

    // Define the API base URL
    const SEDP_API_BASE_URL = process.env.SEDP_API_BASE_URL || 'http://sedpwebapi.ship.samsung.co.kr/api';

    // Make the API call
    const response = await fetch(
      `${SEDP_API_BASE_URL}/Data/GetPubData`,
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'accept': '*/*',
          'ApiKey': apiKey,
          'ProjectNo': projectCode
        },
        body: JSON.stringify({
          ProjectNo: projectCode,
          REG_TYPE_ID: formCode,
          ContainDeleted: false
        })
      }
    );

    if (!response.ok) {
      const errorText = await response.text();
      throw new Error(`SEDP API request failed: ${response.status} ${response.statusText} - ${errorText}`);
    }

    const data = await response.json();
    return data as SEDPTagData;
  } catch (error: unknown) {
    console.error('Error calling SEDP API:', error);
    const errorMessage = error instanceof Error ? error.message : 'Unknown error';
    throw new Error(`Failed to fetch data from SEDP API: ${errorMessage}`);
  }
}

/**
 * SEDP์—์„œ ํ…œํ”Œ๋ฆฟ ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€์ ธ์˜ค๋Š” ์„œ๋ฒ„ ์•ก์…˜
 */
export async function fetchTemplateFromSEDP(
  projectCode: string, 
  formCode: string
): Promise<SEDPTemplateResponse[]> {
  try {
    // Get the token
    const apiKey = await getSEDPToken();

    // Define the API base URL
    const SEDP_API_BASE_URL = process.env.SEDP_API_BASE_URL || 'http://sedpwebapi.ship.samsung.co.kr/api';

    const responseAdapter = await fetch(
      `${SEDP_API_BASE_URL}/AdapterDataMapping/GetByToolID`,
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'accept': '*/*',
          'ApiKey': apiKey,
          'ProjectNo': projectCode
        },
        body: JSON.stringify({
          ProjectNo: projectCode,
          "TOOL_ID": "eVCP"
        })
      }
    );

    if (!responseAdapter.ok) {
      throw new Error(`์ƒˆ ๋ ˆ์ง€์Šคํ„ฐ ์š”์ฒญ ์‹คํŒจ: ${responseAdapter.status} ${responseAdapter.statusText}`);
    }

    const dataAdapter = await responseAdapter.json();
    const templateList = dataAdapter.find(v => v.REG_TYPE_ID === formCode)?.MAP_TMPLS || [];

    // ๊ฐ TMPL_ID์— ๋Œ€ํ•ด API ํ˜ธ์ถœ
    const templatePromises = templateList.map(async (tmplId: string) => {
      const response = await fetch(
        `${SEDP_API_BASE_URL}/Template/GetByID`,
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'accept': '*/*',
            'ApiKey': apiKey,
            'ProjectNo': projectCode
          },
          body: JSON.stringify({
            WithContent: true,
            ProjectNo: projectCode,
            TMPL_ID: tmplId
          })
        }
      );

      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(`SEDP Template API request failed for TMPL_ID ${tmplId}: ${response.status} ${response.statusText} - ${errorText}`);
      }

      const data = await response.json();
      
      // ๐Ÿ” API ์‘๋‹ต ๋ฐ์ดํ„ฐ ๊ตฌ์กฐ ํ™•์ธ ๋ฐ ๋กœ๊น…
      console.log('๐Ÿ” SEDP Template API Response for', tmplId, ':', {
        hasTMPL_ID: !!data.TMPL_ID,
        hasTemplateId: !!(data as any).templateId,
        keys: Object.keys(data),
        sample: data
      });
      
      // ๐Ÿ” TMPL_ID ํ•„๋“œ ๊ฒ€์ฆ
      if (!data.TMPL_ID) {
        console.error('โŒ Missing TMPL_ID in API response:', data);
        // templateId๊ฐ€ ์žˆ๋‹ค๋ฉด ๋ณ€ํ™˜ ์‹œ๋„
        if ((data as any).templateId) {
          console.warn('โš ๏ธ Found templateId instead of TMPL_ID, converting...');
          data.TMPL_ID = (data as any).templateId;
        }
      }
      
      return data as SEDPTemplateResponse;
    });

    // ๋ชจ๋“  API ํ˜ธ์ถœ์„ ๋ณ‘๋ ฌ๋กœ ์‹คํ–‰ํ•˜๊ณ  ๊ฒฐ๊ณผ๋ฅผ ์ˆ˜์ง‘
    const templates = await Promise.all(templatePromises);
    
    // ๐Ÿ” null์ด๋‚˜ undefined๊ฐ€ ์•„๋‹Œ ๊ฐ’๋“ค๋งŒ ํ•„ํ„ฐ๋งํ•˜๊ณ  TMPL_ID ๊ฒ€์ฆ
    const validTemplates = templates.filter(template => {
      if (!template) {
        console.warn('โš ๏ธ Null or undefined template received');
        return false;
      }
      if (!template.TMPL_ID) {
        console.error('โŒ Template missing TMPL_ID:', template);
        return false;
      }
      return true;
    });
    
    console.log(`โœ… fetchTemplateFromSEDP completed: ${validTemplates.length} valid templates`);
    validTemplates.forEach(t => console.log(`  - ${t.TMPL_ID}: ${t.NAME} (${t.TMPL_TYPE})`));
    
    return validTemplates;
    
  } catch (error: unknown) {
    console.error('Error calling SEDP Template API:', error);
    const errorMessage = error instanceof Error ? error.message : 'Unknown error';
    throw new Error(`Failed to fetch template from SEDP API: ${errorMessage}`);
  }
}