summaryrefslogtreecommitdiff
path: root/lib/roles/services.ts
blob: 206bf12cf3696ebd4db92fa1aba96a94e4ab82b4 (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
"use server";

import { revalidateTag, unstable_cache, unstable_noStore } from "next/cache";
import db from "@/db/db";
import { roles, RoleView, roleView, userRoles } from "@/db/schema/users";
import { permissions, rolePermissions } from "@/db/schema/permissions";
import { and, or, asc, desc, ilike, eq, inArray, sql } from "drizzle-orm";
import { filterColumns } from "@/lib/filter-columns";
import {
  selectRolesWithUserCount,
  countRoles,
  insertRole,
  getRoleById,
  updateRole,
  deleteRolesByIds,
  deleteUserRolesByIds,
  findAllRoleView,
} from "./repository";
import { CreateRoleSchema, GetRolesSchema, UpdateRoleSchema } from "./validations";
import { getErrorMessage } from "@/lib/handle-error";

interface UpsertPermissionsInput {
  roleIds: number[];
  permissionKeys: string[];
  itemTitle?: string;
}

export async function getRolesWithCount(input: GetRolesSchema) {
  // unstable_cache: 특정 키와 함께 캐싱
  return unstable_cache(
    async () => {
      try {
        // 1) pagination
        const offset = (input.page - 1) * input.perPage;

        // 2) advanced filter
        const advancedWhere = filterColumns({
          table: roleView, // 또는 roleView
          filters: input.filters,
          joinOperator: input.joinOperator,
        });

        // 3) 글로벌 검색
        let globalWhere;
        if (input.search) {
          const s = `%${input.search}%`;
          // 예: roles.name 에 ilike 검색
          globalWhere = or(ilike(roles.name, s));
        }

        // 4) 최종 where
        const finalWhere = and(advancedWhere, globalWhere);

        // (5) 정렬
        const orderBy =
          input.sort.length > 0
            ? input.sort.map((item) =>
              item.desc ? desc(roleView[item.id]) : asc(roleView[item.id])
            )
            : [desc(roleView.created_at)];


        // 6) 트랜잭션 + Repository 호출
        const { data, total } = await db.transaction(async (tx) => {
          // 실제 SELECT
          const data = await selectRolesWithUserCount(tx, {
            where: finalWhere,
            orderBy,
            offset,
            limit: input.perPage,
          });

          // 전체 개수
          const total = await countRoles(tx, finalWhere);

          return { data, total };
        });

        // 7) pageCount
        const pageCount = Math.ceil(total / input.perPage);

        return { data, pageCount };
      } catch (err) {
        // 에러시 기본값
        return { data: [], pageCount: 0 };
      }
    },
    [JSON.stringify(input)], // 캐싱 키
    {
      revalidate: 3600,
      tags: ["roles"], // revalidateTag("roles")로 무효화
    }
  )();
}

export async function createRole(input: CreateRoleSchema) {
  unstable_noStore(); // 캐싱 방지(Next.js 서버 액션용)
  try {

    await db.transaction(async (tx) => {
      const [newRole] = await insertRole(tx, {
        name: input.name,
        domain: input.domain,
        description: input.description ?? "",
        companyId: input.domain === "partners" ? input.companyId ?? null : null,
      });
    });

    revalidateTag("roles");

    return { data: null, error: null };

  } catch (err) {
    return { data: null, error: getErrorMessage(err) };
  }
}


export async function modifiRole(input: UpdateRoleSchema & { id: number }) {
  unstable_noStore();

  try {

    const data = await db.transaction(async (tx) => {
      // 1) 먼저 User 테이블 업데이트
      const [res] = await updateRole(tx, input.id, {
        name: input.name,
        description: input.description,
        domain: input.domain
      });

      return res;
    });

    // 3) 캐시 무효화
    revalidateTag("roles");


    return { data: null, error: null };
  } catch (err) {
    return { data: null, error: getErrorMessage(err) };
  }
}

export async function removeRoles(input: { ids: number[] }) {
  unstable_noStore();

  try {
    await db.transaction(async (tx) => {
      // user_roles도 있으면 먼저 삭제해야 할 수 있음

      await deleteUserRolesByIds(tx, input.ids);
      await deleteRolesByIds(tx, input.ids);

    });

    revalidateTag("roles");
    revalidateTag("user-role-counts");
    revalidateTag("users");

    return { data: null, error: null };
  } catch (err) {
    return { data: null, error: getErrorMessage(err) };
  }
}



export async function assignRolesToUsers(roleIds: number[], userIds: number[]) {
  // Next.js 서버 액션에서 캐싱 방지
  unstable_noStore()

  try {
    await db.transaction(async (tx) => {
      // 1) 기존 userRoles 삭제: userIds, roleIds에 해당하는 레코드만
      await tx
        .delete(userRoles)
        .where(
          and(
            inArray(userRoles.roleId, roleIds),
            inArray(userRoles.userId, userIds)
          )
        )

      // 2) 새로 삽입
      if (roleIds.length > 0 && userIds.length > 0) {
        const newRows = []
        for (const rid of roleIds) {
          for (const uid of userIds) {
            newRows.push({ roleId: rid, userId: uid })
          }
        }
        await tx.insert(userRoles).values(newRows)
      }
    })

    // 캐시 무효화
    revalidateTag("users")
    revalidateTag("roles")

    return { data: null, error: null }
  } catch (err) {
    return { data: null, error: getErrorMessage(err) }
  }
}

export async function getAllRoleView(domain?: "evcp" | "partners"): Promise<RoleView[]> {
  try {
    return await findAllRoleView(domain)
  } catch (err) {
    throw new Error("Failed to get roles")
  }
}

export async function upsertPermissions(input: UpsertPermissionsInput) {
  unstable_noStore(); 
  try {
    const { roleIds, permissionKeys, itemTitle } = input;
    if (!roleIds.length || !permissionKeys.length) {
      return; // nothing to do
    }

    const roleIdNums = roleIds

    await db.transaction(async (tx) => {
      for (const permKey of permissionKeys) {
        // A) Check if permissionKey exists in "permissions" table
        const [existingPerm] = await tx
          .select({ id: permissions.id })
          .from(permissions)
          .where(eq(permissions.permissionKey, permKey))
          .limit(1);

        let permissionId: number;
        if (!existingPerm) {
          // Insert new permission
          // description를 어떻게 만들지는 자유: itemTitle + permKey 등
          const [inserted] = await tx
            .insert(permissions)
            .values({
              permissionKey: permKey,
              description: itemTitle ? `Menu: ${itemTitle} perm: ${permKey}` : permKey,
            })
            .returning({ id: permissions.id });

          permissionId = inserted.id;
        } else {
          permissionId = existingPerm.id;
        }

        // B) now link (roleId, permissionId) in role_permissions
        for (const rId of roleIdNums) {
          // check if already exists
          const [rp] = await tx
            .select({ p: rolePermissions.permissionId })
            .from(rolePermissions)
            .where(and(eq(rolePermissions.roleId, rId), eq(rolePermissions.permissionId, permissionId)))
            .limit(1);

          if (!rp) {
            // insert
            await tx.insert(rolePermissions).values({
              roleId: rId,
              permissionId,
            });
          }
          // if rp exists, skip
        }
      }
    });

    return { data: null, error: null };

  } catch (err) {
    return { data: null, error: getErrorMessage(err) };
  }
}


export async function getMenuPermissions(
  itemKey: string
): Promise<{ roleId: number; permKey: string }[]> {
  // itemKey = "alert-dialog"
  // permKey = "alert-dialog.create", "alert-dialog.viewOwn", ...
  const pattern = `${itemKey}.%`

  // SELECT rp.role_id, p.permission_key
  // FROM role_permissions rp
  // JOIN permissions p ON p.id = rp.permissionId
  // WHERE p.permission_key LIKE 'alert-dialog.%'
  const rows = await db
    .select({
      roleId: rolePermissions.roleId,
      permKey: permissions.permissionKey,
    })
    .from(rolePermissions)
    .innerJoin(permissions, eq(permissions.id, rolePermissions.permissionId))
    .where(ilike(permissions.permissionKey, pattern));

  return rows;
}


export async function checkRegularEvaluationRoleExists(): Promise<boolean> {
  try {
    const existingRoles = await db
      .select({ id: roles.id, name: roles.name })
      .from(roles)
      .where(sql`${roles.name} ILIKE '%정기평가%'`)
      .limit(1)

    return existingRoles.length > 0
  } catch (error) {
    console.error("정기평가 role 체크 중 에러:", error)
    throw new Error("정기평가 role 체크에 실패했습니다")
  }
}



/**
 * 여러 정기평가 role들의 할당 상태를 한번에 체크
 */
export async function checkMultipleRegularEvaluationRolesAssigned(roleIds: number[]): Promise<{[roleId: number]: boolean}> {
  try {
    // 정기평가 role들만 필터링
    const regularEvaluationRoles = await db
      .select({ id: roles.id, name: roles.name })
      .from(roles)
      .where(
        and(
          inArray(roles.id, roleIds),
          sql`${roles.name} ILIKE '%정기평가%'`
        )
      )

    const regularEvaluationRoleIds = regularEvaluationRoles.map(r => r.id)
    const result: {[roleId: number]: boolean} = {}

    // 모든 role ID에 대해 초기값 설정
    roleIds.forEach(roleId => {
      result[roleId] = false
    })

    if (regularEvaluationRoleIds.length > 0) {
      // 할당된 정기평가 role들 체크
      const assignedRoles = await db
        .select({ roleId: userRoles.roleId })
        .from(userRoles)
        .where(inArray(userRoles.roleId, regularEvaluationRoleIds))

      // 할당된 role들을 true로 설정
      assignedRoles.forEach(assignment => {
        result[assignment.roleId] = true
      })
    }

    return result
  } catch (error) {
    console.error("여러 정기평가 role 할당 상태 체크 중 에러:", error)
    throw new Error("정기평가 role 할당 상태 체크에 실패했습니다")
  }
}

/**
 * 특정 유저가 이미 다른 정기평가 role을 가지고 있는지 체크
 */
export async function checkUserHasRegularEvaluationRole(userId: string): Promise<{hasRole: boolean, roleName?: string}> {
  try {
    const userRegularEvaluationRoles = await db
      .select({
        roleId: userRoles.roleId,
        roleName: roles.name
      })
      .from(userRoles)
      .innerJoin(roles, eq(userRoles.roleId, roles.id))
      .where(
        and(
          eq(userRoles.userId, userId),
          sql`${roles.name} ILIKE '%정기평가%'`
        )
      )
      .limit(1)

    return {
      hasRole: userRegularEvaluationRoles.length > 0,
      roleName: userRegularEvaluationRoles[0]?.roleName
    }
  } catch (error) {
    console.error(`유저 ${userId}의 정기평가 role 체크 중 에러:`, error)
    throw new Error("유저 정기평가 role 체크에 실패했습니다")
  }
}


export async function removeRolesFromUsers(roleIds: number[], userIds: number[]) {
  try {
    // userRoles 테이블에서 해당 역할들을 제거하는 로직
    // 구현 필요
  } catch (error) {
    return { error: "역할 제거 실패" }
  }
}