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

import { revalidateTag, unstable_cache, unstable_noStore } from "next/cache";
import db from "@/db/db";
import { permissions, Role, rolePermissions, roles, RoleView, roleView, userRoles } from "@/db/schema/users";
import { and, or, asc, desc, ilike, eq, inArray } 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;
}