summaryrefslogtreecommitdiff
path: root/lib/users/knox-service.ts
blob: d67550226dff5e7f379747cd3885e4b987532bc2 (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
"use server";

import { unstable_cache } from "next/cache";
import db from "@/db/db";
import { organization } from "@/db/schema/knox/organization";
import { eq, and, asc } from "drizzle-orm";
import { users } from "@/db/schema/users";
import { employee } from "@/db/schema/knox/employee";

// 조직 트리 노드 타입
export interface DepartmentNode {
  companyCode: string;
  departmentCode: string;
  departmentName: string;
  departmentLevel?: string;
  uprDepartmentCode?: string;
  lowDepartmentYn?: string;
  hiddenDepartmentYn?: string;
  children: DepartmentNode[];
  // UI에서 사용할 추가 필드
  label: string;
  value: string;
  key: string;
}

// 기본 회사 코드 (환경변수에서 가져오되 폴백 제공)
const getCompanyCode = () => {
  const envCodes = process.env.KNOX_COMPANY_CODES;
  if (envCodes) {
    // 쉼표로 구분된 경우 첫 번째 값 사용
    return envCodes.split(',')[0].trim();
  }
  return "D60"; // 폴백 값
};

const DEFAULT_COMPANY_CODE = getCompanyCode();

// 조직 데이터 조회 (hiddenDepartmentYn = 'F'만)
export async function getVisibleOrganizations() {
  return unstable_cache(
    async () => {
      try {
        const organizations = await db
          .select({
            companyCode: organization.companyCode,
            departmentCode: organization.departmentCode,
            departmentName: organization.departmentName,
            departmentLevel: organization.departmentLevel,
            uprDepartmentCode: organization.uprDepartmentCode,
            lowDepartmentYn: organization.lowDepartmentYn,
            hiddenDepartmentYn: organization.hiddenDepartmentYn,
          })
          .from(organization)
          .where(eq(organization.hiddenDepartmentYn, 'F'))
          .orderBy(
            asc(organization.companyCode),
            asc(organization.departmentLevel),
            asc(organization.departmentCode)
          );

        return organizations;
      } catch (error) {
        console.error("조직 데이터 조회 실패:", error);
        return [];
      }
    },
    ["visible-organizations"],
    {
      revalidate: 3600, // 1시간 캐시
      tags: ["knox-organizations"],
    }
  )();
}

// 기본 회사의 부서 트리 구조 조회 (처음부터 모든 데이터 로드)
export async function getAllDepartmentsTree(): Promise<DepartmentNode[]> {
  return unstable_cache(
    async () => {
      try {
        const organizations = await db
          .select({
            companyCode: organization.companyCode,
            departmentCode: organization.departmentCode,
            departmentName: organization.departmentName,
            departmentLevel: organization.departmentLevel,
            uprDepartmentCode: organization.uprDepartmentCode,
            lowDepartmentYn: organization.lowDepartmentYn,
            hiddenDepartmentYn: organization.hiddenDepartmentYn,
          })
          .from(organization)
          .where(
            and(
              eq(organization.companyCode, DEFAULT_COMPANY_CODE),
              eq(organization.hiddenDepartmentYn, 'F')
            )
          )
          .orderBy(
            asc(organization.departmentLevel),
            asc(organization.departmentCode)
          );

        // 트리 구조 생성
        const tree = buildDepartmentTree(organizations);
        return tree;
      } catch (error) {
        console.error("모든 부서 트리 구성 실패:", error);
        return [];
      }
    },
    [`all-departments-tree-${DEFAULT_COMPANY_CODE}`],
    {
      revalidate: 3600,
      tags: ["knox-organizations"],
    }
  )();
}

// 회사별 조직 트리 구조 생성 (기존 호환성 유지)
export async function getDepartmentTreeByCompany(companyCode: string): Promise<DepartmentNode[]> {
  return unstable_cache(
    async () => {
      try {
        const organizations = await db
          .select({
            companyCode: organization.companyCode,
            departmentCode: organization.departmentCode,
            departmentName: organization.departmentName,
            departmentLevel: organization.departmentLevel,
            uprDepartmentCode: organization.uprDepartmentCode,
            lowDepartmentYn: organization.lowDepartmentYn,
            hiddenDepartmentYn: organization.hiddenDepartmentYn,
          })
          .from(organization)
          .where(
            and(
              eq(organization.companyCode, companyCode),
              eq(organization.hiddenDepartmentYn, 'F')
            )
          )
          .orderBy(
            asc(organization.departmentLevel),
            asc(organization.departmentCode)
          );

        // 트리 구조 생성
        const tree = buildDepartmentTree(organizations);
        return tree;
      } catch (error) {
        console.error(`회사 ${companyCode} 조직 트리 구성 실패:`, error);
        return [];
      }
    },
    [`department-tree-${companyCode}`],
    {
      revalidate: 3600,
      tags: ["knox-organizations", `company-${companyCode}`],
    }
  )();
}

// 전체 회사의 조직 트리 구조 생성
export async function getAllDepartmentTrees(): Promise<Record<string, DepartmentNode[]>> {
  return unstable_cache(
    async () => {
      try {
        const organizations = await getVisibleOrganizations();
        
        // 회사별로 그룹화
        const companiesMap = new Map<string, typeof organizations>();
        
        organizations.forEach((org) => {
          if (!companiesMap.has(org.companyCode)) {
            companiesMap.set(org.companyCode, []);
          }
          companiesMap.get(org.companyCode)!.push(org);
        });

        // 각 회사별로 트리 구조 생성
        const result: Record<string, DepartmentNode[]> = {};
        
        for (const [companyCode, orgs] of companiesMap) {
          result[companyCode] = buildDepartmentTree(orgs);
        }

        return result;
      } catch (error) {
        console.error("전체 조직 트리 구성 실패:", error);
        return {};
      }
    },
    ["all-department-trees"],
    {
      revalidate: 3600,
      tags: ["knox-organizations"],
    }
  )();
}

// 부서 트리 구조 빌더 헬퍼 함수 (개선)
function buildDepartmentTree(
  organizations: Array<{
    companyCode: string;
    departmentCode: string;
    departmentName: string | null;
    departmentLevel?: string | null;
    uprDepartmentCode?: string | null;
    lowDepartmentYn?: string | null;
    hiddenDepartmentYn?: string | null;
  }>
): DepartmentNode[] {
  // 맵으로 빠른 조회를 위한 인덱스 생성
  const orgMap = new Map<string, DepartmentNode>();
  const rootNodes: DepartmentNode[] = [];

  // 1단계: 모든 노드를 맵에 추가
  organizations.forEach((org) => {
    const node: DepartmentNode = {
      companyCode: org.companyCode,
      departmentCode: org.departmentCode,
      departmentName: org.departmentName || "",
      departmentLevel: org.departmentLevel || undefined,
      uprDepartmentCode: org.uprDepartmentCode || undefined,
      lowDepartmentYn: org.lowDepartmentYn || undefined,
      hiddenDepartmentYn: org.hiddenDepartmentYn || undefined,
      children: [],
      // UI용 필드
      label: org.departmentName || org.departmentCode,
      value: org.departmentCode,
      key: `${org.companyCode}-${org.departmentCode}`,
    };
    
    orgMap.set(org.departmentCode, node);
  });

  // 2단계: 부모-자식 관계 설정
  organizations.forEach((org) => {
    const currentNode = orgMap.get(org.departmentCode);
    if (!currentNode) return;

    if (org.uprDepartmentCode && orgMap.has(org.uprDepartmentCode)) {
      // 부모가 있으면 부모의 children에 추가
      const parentNode = orgMap.get(org.uprDepartmentCode);
      parentNode!.children.push(currentNode);
    } else {
      // 부모가 없으면 루트 노드로 처리
      // 하지만 상위 부서가 없는 부서들은 depth 1에 배치
      rootNodes.push(currentNode);
    }
  });

  // 3단계: 고립된 부서들 처리 (상위도 하위도 없는 부서들)
  // lowDepartmentYn이 'F'이거나 null이고, uprDepartmentCode가 없거나 존재하지 않는 부서들을 확인
  organizations.forEach((org) => {
    const currentNode = orgMap.get(org.departmentCode);
    if (!currentNode) return;

    // 이미 루트에 추가되었거나 다른 부서의 자식이 된 경우는 스킵
    const isAlreadyPlaced = rootNodes.includes(currentNode) || 
      organizations.some(otherOrg => {
        const otherNode = orgMap.get(otherOrg.departmentCode);
        return otherNode && otherNode.children.includes(currentNode);
      });

    if (!isAlreadyPlaced) {
      // 고립된 부서를 루트에 추가
      rootNodes.push(currentNode);
    }
  });

  // 4단계: 각 노드의 children을 정렬
  const sortChildren = (node: DepartmentNode) => {
    node.children.sort((a, b) => {
      // departmentLevel이 있으면 그걸로 정렬, 없으면 departmentCode로 정렬
      const aLevel = parseInt(a.departmentLevel || "999");
      const bLevel = parseInt(b.departmentLevel || "999");
      
      if (aLevel !== bLevel) {
        return aLevel - bLevel;
      }
      
      return a.departmentCode.localeCompare(b.departmentCode);
    });
    
    // 재귀적으로 자식들도 정렬
    node.children.forEach(sortChildren);
  };

  // 5단계: 루트 노드들도 정렬
  rootNodes.sort((a, b) => {
    const aLevel = parseInt(a.departmentLevel || "1");
    const bLevel = parseInt(b.departmentLevel || "1");
    
    if (aLevel !== bLevel) {
      return aLevel - bLevel;
    }
    
    return a.departmentCode.localeCompare(b.departmentCode);
  });

  rootNodes.forEach(sortChildren);

  return rootNodes;
}

// 특정 부서의 모든 하위 부서 코드 조회 (재귀) - 기본 회사 대상
export async function getChildDepartmentCodes(departmentCode: string): Promise<string[]> {
  const tree = await getAllDepartmentsTree();
  const result: string[] = [];

  const findAndCollectChildren = (nodes: DepartmentNode[], targetCode: string): boolean => {
    for (const node of nodes) {
      if (node.departmentCode === targetCode) {
        // 타겟 노드 발견, 모든 하위 부서 코드 수집
        collectAllDepartmentCodes(node, result);
        return true;
      }
      
      // 자식 노드들에서 재귀 검색
      if (findAndCollectChildren(node.children, targetCode)) {
        return true;
      }
    }
    return false;
  };

  const collectAllDepartmentCodes = (node: DepartmentNode, codes: string[]) => {
    codes.push(node.departmentCode);
    node.children.forEach(child => collectAllDepartmentCodes(child, codes));
  };

  findAndCollectChildren(tree, departmentCode);
  return result;
}

// 회사 목록 조회 (호환성 유지용)
export async function getCompanies(): Promise<Array<{ code: string; name: string }>> {
  return unstable_cache(
    async () => {
      try {
        const companies = await db
          .selectDistinct({
            code: organization.companyCode,
            name: organization.companyName,
          })
          .from(organization)
          .where(eq(organization.hiddenDepartmentYn, 'F'))
          .orderBy(asc(organization.companyCode));

        return companies
          .filter(company => company.code && company.name)
          .map(company => ({
            code: company.code,
            name: company.name!,
          }));
      } catch (error) {
        console.error("회사 목록 조회 실패:", error);
        return [];
      }
    },
    ["companies"],
    {
      revalidate: 3600,
      tags: ["knox-organizations"],
    }
  )();
}

// 현재 사용 중인 회사 코드 반환
export async function getCurrentCompanyCode(): Promise<string> {
  return DEFAULT_COMPANY_CODE;
}

// 현재 사용 중인 회사 정보 반환
export async function getCurrentCompanyInfo(): Promise<{ code: string; name: string }> {
  return {
    code: DEFAULT_COMPANY_CODE,
    name: "삼성중공업"
  };
}

// 사번으로 user Id 찾기
export async function findUserIdByEmployeeNumber(employeeNumber: string): Promise<number | null> {

  try {
    // 1. 사번 기준으로 email 찾기
    const userEmail = await db
    .select({ email: employee.emailAddress })
    .from(employee)
    .where(eq(employee.employeeNumber, employeeNumber))
    .limit(1);

    if (userEmail.length === 0) {
      console.error('사번에 해당하는 이메일 찾기 실패', { employeeNumber });
      return null;
    }

    // 2. 이메일 기준으로 userId 찾기
    const userId = await db
    .select({ id: users.id })
    .from(users)
    .where(eq(users.email, userEmail[0].email));

    if (userId.length === 0) {
      console.error('이메일에 해당하는 사용자 찾기 실패', { email: userEmail[0].email });
      return null;
    }

    return userId[0].id;

  } catch (error) {
    console.error('사번에 해당하는 이메일 찾기 실패', { employeeNumber, error });
    return null;
  }
}