summaryrefslogtreecommitdiff
path: root/lib/menu-list/servcie.ts
blob: cd414ab4c8bf613b39be48231f42a292ca046be8 (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
// app/evcp/menu-list/actions.ts

"use server";

import db  from "@/db/db";
import { menuAssignments, users, pageInformation, notice } from "@/db/schema";
import { eq, and } from "drizzle-orm";
import { revalidatePath, revalidateTag } from "next/cache";
import { mainNav, mainNavVendor, additionalNav, additionalNavVendor } from "@/config/menuConfig";

// 메뉴 데이터 타입 정의
interface MenuData {
  menuPath: string;
  menuTitle: string;
  menuDescription?: string;
  menuGroup?: string;
  sectionTitle: string;
  domain: "evcp" | "partners";
}

// Config에서 메뉴 데이터 추출
function extractMenusFromConfig(): MenuData[] {
  const menus: MenuData[] = [];

  // EVCP 메인 네비게이션
  mainNav.forEach(section => {
    section.items.forEach(item => {
      menus.push({
        menuPath: item.href,
        menuTitle: item.titleKey,
        menuDescription: item.descriptionKey,
        menuGroup: item.groupKey,
        sectionTitle: section.titleKey,
        domain: "evcp"
      });
    });
  });

  // EVCP 추가 네비게이션
  additionalNav.forEach(item => {
    menus.push({
      menuPath: item.href,
      menuTitle: item.titleKey,
      menuDescription: item.descriptionKey,
      menuGroup: undefined,
      sectionTitle: "추가 메뉴",
      domain: "evcp"
    });
  });

  // Partners 메인 네비게이션
  mainNavVendor.forEach(section => {
    section.items.forEach(item => {
      menus.push({
        menuPath: item.href,
        menuTitle: item.titleKey,
        menuDescription: item.descriptionKey,
        menuGroup: item.groupKey,
        sectionTitle: section.titleKey,
        domain: "partners"
      });
    });
  });

  // Partners 추가 네비게이션
  additionalNavVendor.forEach(item => {
    menus.push({
      menuPath: item.href,
      menuTitle: item.titleKey,
      menuDescription: item.descriptionKey,
      menuGroup: undefined,
      sectionTitle: "추가 메뉴",
      domain: "partners"
    });
  });

  return menus;
}

// 초기 메뉴 데이터 생성 또는 업데이트
export async function initializeMenuAssignments() {
  try {
    const configMenus = extractMenusFromConfig();
    const existingMenus = await db.select().from(menuAssignments);
    const existingPaths = new Set(existingMenus.map(m => m.menuPath));

    // 새로운 메뉴만 추가 (특정 경로 예외처리)
    const newMenus = configMenus.filter(menu => !existingPaths.has(menu.menuPath));

    console.log(newMenus, newMenus)

    if (newMenus.length > 0) {
      // 개별적으로 insert하여 중복 오류 처리
      for (const menu of newMenus) {
        try {
          await db.insert(menuAssignments).values({
            menuPath: menu.menuPath,
            menuTitle: menu.menuTitle,
            menuDescription: menu.menuDescription || null,
            menuGroup: menu.menuGroup || null,
            sectionTitle: menu.sectionTitle,
            domain: menu.domain,
            isActive: true,
          });
        } catch (insertError: any) {
          // /partners/vendor-data 경로의 중복 오류는 무시
          if (insertError?.code === '23505' && menu.menuPath === '/partners/vendor-data') {
            console.warn(`중복 메뉴 경로 건너뛰기: ${menu.menuPath}`);
            continue;
          }
          // 다른 오류는 다시 throw
          throw insertError;
        }
      }
    }

    // 기존 메뉴 정보 업데이트 (title, description 등이 변경될 수 있음)
    for (const configMenu of configMenus) {
      if (existingPaths.has(configMenu.menuPath)) {
        await db
          .update(menuAssignments)
          .set({
            menuTitle: configMenu.menuTitle,
            menuDescription: configMenu.menuDescription || null,
            menuGroup: configMenu.menuGroup || null,
            sectionTitle: configMenu.sectionTitle,
            updatedAt: new Date(),
          })
          .where(eq(menuAssignments.menuPath, configMenu.menuPath));
      }
    }

    revalidatePath("/evcp/menu-list");
    return { success: true, message: `${newMenus.length}개의 새로운 메뉴가 추가되었습니다.` };
  } catch (error) {
    console.error("메뉴 초기화 오류:", error);
    return { success: false, message: "메뉴 초기화 중 오류가 발생했습니다." };
  }
}

// 메뉴 담당자 업데이트
export async function updateMenuManager(
  menuPath: string, 
  manager1Id?: number | null, 
  manager2Id?: number | null
) {
  try {

    console.log(menuPath, manager1Id)

    await db
      .update(menuAssignments)
      .set({
        manager1Id: manager1Id || null,
        manager2Id: manager2Id || null,
        updatedAt: new Date(),
      })
      .where(eq(menuAssignments.menuPath, menuPath));

    revalidatePath("/evcp/menu-list");
    // 인포메이션 편집 권한 캐시 무효화
    revalidateTag("information-edit-permission")

    return { success: true, message: "담당자가 업데이트되었습니다." };
  } catch (error) {
    console.error("담당자 업데이트 오류:", error);
    return { success: false, message: "담당자 업데이트 중 오류가 발생했습니다." };
  }
}

// 메뉴 리스트 조회 (담당자 정보 포함)
export async function getMenuAssignments(domain?: "evcp" | "partners") {
  try {
    const whereCondition = domain 
      ? eq(menuAssignments.domain, domain)
      : undefined;

    const result = await db
      .select({
        id: menuAssignments.id,
        menuPath: menuAssignments.menuPath,
        menuTitle: menuAssignments.menuTitle,
        menuDescription: menuAssignments.menuDescription,
        menuGroup: menuAssignments.menuGroup,
        sectionTitle: menuAssignments.sectionTitle,
        domain: menuAssignments.domain,
        isActive: menuAssignments.isActive,
        createdAt: menuAssignments.createdAt,
        updatedAt: menuAssignments.updatedAt,
        manager1Id: menuAssignments.manager1Id,
        manager2Id: menuAssignments.manager2Id,
        manager1Name: users.name,
        manager1Email: users.email,
        manager2Name: users.name,
        manager2Email: users.email,
      })
      .from(menuAssignments)
      .leftJoin(users, eq(menuAssignments.manager1Id, users.id))
      .where(whereCondition)
      .orderBy(menuAssignments.sectionTitle, menuAssignments.menuGroup, menuAssignments.menuTitle);

    return { success: true, data: result };
  } catch (error) {
    console.error("메뉴 조회 오류:", error);
    return { success: false, message: "메뉴 조회 중 오류가 발생했습니다.", data: [] };
  }
}

// 활성 사용자 리스트 조회
export async function getActiveUsers(domain?: "evcp" | "partners") {
  try {
    const whereCondition = and(
      eq(users.isActive, true),
      domain ? eq(users.domain, domain) : undefined
    );

    const result = await db
      .select({
        id: users.id,
        name: users.name,
        email: users.email,
        domain: users.domain,
      })
      .from(users)
      .where(whereCondition)
      .orderBy(users.name);

    return { success: true, data: result };
  } catch (error) {
    console.error("사용자 조회 오류:", error);
    return { success: false, message: "사용자 조회 중 오류가 발생했습니다.", data: [] };
  }
}

// 메뉴 활성화/비활성화
export async function toggleMenuActive(menuPath: string, isActive: boolean) {
  try {
    await db
      .update(menuAssignments)
      .set({
        isActive,
        updatedAt: new Date(),
      })
      .where(eq(menuAssignments.menuPath, menuPath));

      revalidatePath("/evcp/menu-list");

    return { success: true, message: `메뉴가 ${isActive ? '활성화' : '비활성화'}되었습니다.` };
  } catch (error) {
    console.error("메뉴 상태 변경 오류:", error);
    return { success: false, message: "메뉴 상태 변경 중 오류가 발생했습니다." };
  }
}