@goplusvn/core 0.1.77 → 0.1.79

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -13,11 +13,22 @@
13
13
  // prisma, getSession, getCrudPermissions, schema: { userNameField: "fullName", ... },
14
14
  // });
15
15
 
16
- import { getRolesData, type RoleServiceSchema } from "./role-service";
16
+ import { getRolesData } from "./role-service";
17
+ import { normalizeLandingPath } from "./landing-path";
17
18
  import {
18
19
  bumpPermissionsVersion,
19
20
  getPermissionsVersion,
20
21
  } from "./permissions-version";
22
+ import {
23
+ DelegationError,
24
+ assertCanDeleteRole,
25
+ assertCanManageRole,
26
+ canManageRole,
27
+ } from "../workspace/delegation";
28
+ import { memberScopeWhere } from "../workspace/scope";
29
+
30
+ import type { RoleQueryScope, RoleServiceSchema } from "./role-service";
31
+ import type { DelegationActor } from "../workspace/delegation";
21
32
 
22
33
  type MaybePromise<T> = T | Promise<T>;
23
34
 
@@ -28,12 +39,81 @@ export interface RbacHandlerDeps {
28
39
  getCrudPermissions: (session: any, resource: string) => Promise<{ read?: boolean; create?: boolean; update?: boolean; delete?: boolean }>;
29
40
  /** Schema field-map when User/Role diverge from defaults. */
30
41
  schema?: RoleServiceSchema;
42
+ /**
43
+ * UỶ QUYỀN (app multi-tenant). Bỏ trống ⇒ handler chạy y như trước: quyền
44
+ * `role:create/update/delete` là toàn quyền trên MỌI vai trò.
45
+ *
46
+ * Truyền vào thì cùng bộ luật D1/D2/D4 của người dùng được áp cho vai trò:
47
+ * quản trị viên đơn vị chỉ thấy vai trò của đơn vị mình (+ vai trò dùng chung,
48
+ * chỉ đọc), tạo vai trò thì bị đóng dấu đơn vị và không nhét được quyền mà
49
+ * chính họ không có. Thiếu cửa này thì chặn *gán* vai trò mạnh là vô nghĩa —
50
+ * họ tự tạo một vai trò mạnh rồi gán.
51
+ */
52
+ getDelegationActor?: (session: any) => MaybePromise<DelegationActor | null>;
31
53
  onError?: (error: unknown, req: Request) => Response | Promise<Response>;
32
54
  }
33
55
 
34
56
  const json = (data: unknown, status = 200) =>
35
57
  new Response(JSON.stringify(data), { status, headers: { "content-type": "application/json" } });
36
58
 
59
+ /** DelegationError → 403 kèm mã bất biến; lỗi khác trả về cho `fail` xử lý. */
60
+ const delegationDenied = (e: unknown) =>
61
+ e instanceof DelegationError ? json({ error: e.message, code: e.code }, 403) : null;
62
+
63
+ /**
64
+ * Phạm vi đọc vai trò của một người thao tác. Export vì TRANG danh sách vai trò
65
+ * (server component) phải nạp đúng bộ dữ liệu mà API sẽ trả — lệch nhau thì
66
+ * lần render đầu hiện vai trò của đơn vị khác rồi mới biến mất sau khi SWR chạy.
67
+ */
68
+ export function roleScopeOf(actor: DelegationActor | null): RoleQueryScope | undefined {
69
+ if (!actor) return undefined;
70
+ return {
71
+ canManageAll: actor.canManageAll,
72
+ adminWorkspaceIds: actor.scope.adminIds,
73
+ userWhere: actor.canManageAll ? undefined : memberScopeWhere(actor.scope),
74
+ };
75
+ }
76
+
77
+ /**
78
+ * Quyền trong vai trò đi trên dây dưới dạng `"action:resource"` (khuôn của
79
+ * `RoleListPage`), còn tầng uỷ quyền nói `"resource:action"`. Đổi chiều ở đúng
80
+ * một chỗ — trộn hai khuôn thì mọi phép so quyền lặng lẽ trả về "không khớp",
81
+ * tức hàng rào D2 vẫn xanh nhưng không chặn gì.
82
+ */
83
+ function toResourceAction(permissions: readonly string[]): string[] {
84
+ return permissions
85
+ .map((p) => {
86
+ const [actionCode, resourceCode] = p.split(":");
87
+ return actionCode && resourceCode ? `${resourceCode}:${actionCode}` : null;
88
+ })
89
+ .filter((p): p is string => Boolean(p));
90
+ }
91
+
92
+ /** Cột uỷ quyền chỉ tồn tại ở app đã migrate — ghi mù là ném `Unknown argument`. */
93
+ const hasRoleField = (prisma: any, field: string) => Boolean(prisma?.role?.fields?.[field]);
94
+
95
+ /** Đọc vai trò trong DB về khuôn `DelegationRole` cho cổng D1/D2/D4. */
96
+ async function loadRoleForDelegation(prisma: any, id: string) {
97
+ const role = await prisma.role.findUnique({
98
+ where: { id },
99
+ include: { rolePermissions: { select: { resourceCode: true, actionCode: true } } },
100
+ });
101
+ if (!role) return null;
102
+ return {
103
+ role,
104
+ delegation: {
105
+ id: role.id,
106
+ code: role.code,
107
+ rank: typeof role.rank === "number" ? role.rank : 100,
108
+ isSystem: Boolean(role.isSystem),
109
+ workspaceId: role.workspaceId ?? null,
110
+ permissions: (role.rolePermissions ?? []).map(
111
+ (p: any) => `${p.resourceCode}:${p.actionCode}`,
112
+ ),
113
+ },
114
+ };
115
+ }
116
+
37
117
  // permissions "action:resource" → RolePermission rows {roleCode,resourceCode,actionCode}.
38
118
  async function writePermissions(tx: any, roleCode: string, permissions: string[]) {
39
119
  await tx.rolePermission.deleteMany({ where: { roleCode } });
@@ -46,9 +126,38 @@ async function writePermissions(tx: any, roleCode: string, permissions: string[]
46
126
  if (rows.length) await tx.rolePermission.createMany({ data: rows, skipDuplicates: true });
47
127
  }
48
128
 
129
+ // ── Trang mở đầu theo vai trò (`Role.landingPath`) ─────────────────────────
130
+ // Cột BỔ SUNG: app nào chưa migrate thì handler phải im lặng bỏ qua, không ném
131
+ // — hai app đang chạy thật vẫn dùng core này. Dò bằng `prisma.role.fields`
132
+ // (Prisma sinh sẵn), rẻ và đúng với schema THẬT của app chứ không đoán.
133
+ const hasLandingPath = (prisma: any) => Boolean(prisma?.role?.fields?.landingPath);
134
+
135
+ /** Mảnh `data` để ghép vào create/update — rỗng khi app chưa có cột. */
136
+ function landingPathData(prisma: any, body: any) {
137
+ if (!hasLandingPath(prisma) || !("landingPath" in (body ?? {}))) return {};
138
+ return { landingPath: normalizeLandingPath(body.landingPath) };
139
+ }
140
+
141
+ // ── Nấc cô lập dữ liệu theo vai trò (`Role.dataScope`) ─────────────────────
142
+ const SCOPE_LEVELS = ["none", "own", "workspace", "subtree", "all"] as const;
143
+
144
+ /**
145
+ * CHỈ VAI VẬN HÀNH đổi được nấc này. Nếu để quản trị viên đơn vị tự đặt, họ chỉ
146
+ * cần tạo một vai trò `all` rồi tự gán — cô lập dữ liệu biến thành tuỳ chọn.
147
+ * `actor === null` (app chưa bật uỷ quyền) thì giữ hành vi cũ: ai sửa vai trò
148
+ * được thì sửa được cột này.
149
+ */
150
+ function dataScopeData(prisma: any, body: any, actor: DelegationActor | null) {
151
+ if (!hasRoleField(prisma, "dataScope") || !("dataScope" in (body ?? {}))) return {};
152
+ if (actor && !actor.canManageAll) return {};
153
+ const raw = body.dataScope;
154
+ if (raw === null || raw === "") return { dataScope: null };
155
+ return SCOPE_LEVELS.includes(raw) ? { dataScope: raw } : {};
156
+ }
157
+
49
158
  // GET (list, schema-tolerant) + POST (create + permissions) for /api/roles.
50
159
  export function createRolesCollectionHandlers(deps: RbacHandlerDeps) {
51
- const { prisma, getSession, getCrudPermissions, schema, onError } = deps;
160
+ const { prisma, getSession, getCrudPermissions, schema, getDelegationActor, onError } = deps;
52
161
  const fail = (e: unknown, req: Request) => (onError ? onError(e, req) : json({ error: "Internal error" }, 500));
53
162
 
54
163
  async function GET(req: Request) {
@@ -58,6 +167,7 @@ export function createRolesCollectionHandlers(deps: RbacHandlerDeps) {
58
167
  const perms = await getCrudPermissions(session, "role");
59
168
  if (!perms.read) return json({ error: "Forbidden" }, 403);
60
169
  const sp = new URL(req.url).searchParams;
170
+ const actor = getDelegationActor ? await getDelegationActor(session) : null;
61
171
  const result = await getRolesData(
62
172
  prisma,
63
173
  {
@@ -67,6 +177,7 @@ export function createRolesCollectionHandlers(deps: RbacHandlerDeps) {
67
177
  status: sp.get("status")?.trim() || undefined,
68
178
  },
69
179
  schema,
180
+ roleScopeOf(actor),
70
181
  );
71
182
  return json(result);
72
183
  } catch (e) {
@@ -85,9 +196,40 @@ export function createRolesCollectionHandlers(deps: RbacHandlerDeps) {
85
196
  const name = (body.name ?? "").trim();
86
197
  if (!code || !name) return json({ error: "Thiếu mã hoặc tên vai trò" }, 400);
87
198
  const permissions: string[] = Array.isArray(body.permissions) ? body.permissions : [];
199
+
200
+ // Cổng uỷ quyền: đóng dấu đơn vị + ép cấp thấp hơn người tạo + chặn quyền
201
+ // vượt trần. Chỉ chạy khi app khai `getDelegationActor`.
202
+ const stamp: Record<string, unknown> = {};
203
+ const actor = getDelegationActor ? await getDelegationActor(session) : null;
204
+ if (actor) {
205
+ try {
206
+ const gate = assertCanManageRole(actor, null, {
207
+ code,
208
+ workspaceId: body.workspaceId ?? undefined,
209
+ rank: typeof body.rank === "number" ? body.rank : undefined,
210
+ isSystem: Boolean(body.isSystem),
211
+ permissions: toResourceAction(permissions),
212
+ });
213
+ if (hasRoleField(prisma, "workspaceId")) stamp.workspaceId = gate.workspaceId;
214
+ if (hasRoleField(prisma, "rank")) stamp.rank = gate.rank;
215
+ } catch (e) {
216
+ const denied = delegationDenied(e);
217
+ if (denied) return denied;
218
+ throw e;
219
+ }
220
+ }
221
+
88
222
  const role = await prisma.$transaction(async (tx: any) => {
89
223
  const created = await tx.role.create({
90
- data: { code, name, description: body.description ?? null, status: body.status ?? "active" },
224
+ data: {
225
+ code,
226
+ name,
227
+ description: body.description ?? null,
228
+ status: body.status ?? "active",
229
+ ...stamp,
230
+ ...landingPathData(prisma, body),
231
+ ...dataScopeData(prisma, body, actor),
232
+ },
91
233
  });
92
234
  await writePermissions(tx, created.code, permissions);
93
235
  return created;
@@ -104,7 +246,7 @@ export function createRolesCollectionHandlers(deps: RbacHandlerDeps) {
104
246
 
105
247
  // GET + PUT (update + replace permissions) + DELETE (guarded by user count) for /api/roles/[id].
106
248
  export function createRoleItemHandlers(deps: RbacHandlerDeps) {
107
- const { prisma, getSession, getCrudPermissions, onError } = deps;
249
+ const { prisma, getSession, getCrudPermissions, getDelegationActor, onError } = deps;
108
250
  const fail = (e: unknown, req: Request) => (onError ? onError(e, req) : json({ error: "Internal error" }, 500));
109
251
  type Ctx = { params: Promise<{ id: string }> };
110
252
 
@@ -115,17 +257,28 @@ export function createRoleItemHandlers(deps: RbacHandlerDeps) {
115
257
  if (!session) return json({ error: "Unauthorized" }, 401);
116
258
  const perms = await getCrudPermissions(session, "role");
117
259
  if (!perms.read) return json({ error: "Forbidden" }, 403);
118
- const role = await prisma.role.findUnique({
119
- where: { id },
120
- include: { rolePermissions: { select: { resourceCode: true, actionCode: true } } },
121
- });
122
- if (!role) return json({ error: "Not found" }, 404);
260
+ const loaded = await loadRoleForDelegation(prisma, id);
261
+ if (!loaded) return json({ error: "Not found" }, 404);
262
+ const { role } = loaded;
263
+ // Vai trò ngoài phạm vi thì coi như KHÔNG TỒN TẠI: trả 403 ở đây là xác
264
+ // nhận "có vai trò id này", đủ để dò danh sách vai trò của đơn vị khác.
265
+ const viewer = getDelegationActor ? await getDelegationActor(session) : null;
266
+ if (viewer && !viewer.canManageAll) {
267
+ const ws = loaded.delegation.workspaceId;
268
+ const visible = !ws || viewer.scope.adminIds.includes(ws);
269
+ if (!visible) return json({ error: "Not found" }, 404);
270
+ }
123
271
  return json({
124
272
  id: role.id,
125
273
  code: role.code,
126
274
  name: role.name,
127
275
  description: role.description ?? "",
128
276
  status: role.status,
277
+ landingPath: role.landingPath ?? null,
278
+ dataScope: role.dataScope ?? null,
279
+ workspaceId: role.workspaceId ?? null,
280
+ isSystem: Boolean(role.isSystem),
281
+ canManage: viewer ? canManageRole(viewer, loaded.delegation) : undefined,
129
282
  permissions: role.rolePermissions.map((p: any) => `${p.actionCode}:${p.resourceCode}`),
130
283
  });
131
284
  } catch (e) {
@@ -141,9 +294,32 @@ export function createRoleItemHandlers(deps: RbacHandlerDeps) {
141
294
  const perms = await getCrudPermissions(session, "role");
142
295
  if (!perms.update) return json({ error: "Forbidden" }, 403);
143
296
  const body = await req.json();
144
- const existing = await prisma.role.findUnique({ where: { id } });
145
- if (!existing) return json({ error: "Not found" }, 404);
297
+ const loaded = await loadRoleForDelegation(prisma, id);
298
+ if (!loaded) return json({ error: "Not found" }, 404);
299
+ const existing = loaded.role;
146
300
  const permissions: string[] = Array.isArray(body.permissions) ? body.permissions : [];
301
+
302
+ // Vai trò hệ thống / vai trò dùng chung / vai trò đơn vị khác: chặn ở đây.
303
+ // Không có cổng này thì quản trị viên đơn vị chỉ cần MỞ vai trò "Quản trị
304
+ // hệ thống" rồi bấm lưu là tự nâng cấp mình.
305
+ const stamp: Record<string, unknown> = {};
306
+ const actor = getDelegationActor ? await getDelegationActor(session) : null;
307
+ if (actor) {
308
+ try {
309
+ const gate = assertCanManageRole(actor, loaded.delegation, {
310
+ code: existing.code,
311
+ workspaceId: loaded.delegation.workspaceId,
312
+ rank: typeof body.rank === "number" ? body.rank : loaded.delegation.rank,
313
+ permissions: toResourceAction(permissions),
314
+ });
315
+ if (hasRoleField(prisma, "rank")) stamp.rank = gate.rank;
316
+ } catch (e) {
317
+ const denied = delegationDenied(e);
318
+ if (denied) return denied;
319
+ throw e;
320
+ }
321
+ }
322
+
147
323
  const role = await prisma.$transaction(async (tx: any) => {
148
324
  const updated = await tx.role.update({
149
325
  where: { id },
@@ -151,6 +327,9 @@ export function createRoleItemHandlers(deps: RbacHandlerDeps) {
151
327
  name: (body.name ?? existing.name).trim(),
152
328
  description: body.description ?? existing.description,
153
329
  status: body.status ?? existing.status,
330
+ ...stamp,
331
+ ...landingPathData(prisma, body),
332
+ ...dataScopeData(prisma, body, actor),
154
333
  },
155
334
  });
156
335
  await writePermissions(tx, updated.code, permissions);
@@ -171,6 +350,18 @@ export function createRoleItemHandlers(deps: RbacHandlerDeps) {
171
350
  if (!session) return json({ error: "Unauthorized" }, 401);
172
351
  const perms = await getCrudPermissions(session, "role");
173
352
  if (!perms.delete) return json({ error: "Forbidden" }, 403);
353
+ const loaded = await loadRoleForDelegation(prisma, id);
354
+ if (!loaded) return json({ error: "Not found" }, 404);
355
+ const actor = getDelegationActor ? await getDelegationActor(session) : null;
356
+ if (actor) {
357
+ try {
358
+ assertCanDeleteRole(actor, loaded.delegation);
359
+ } catch (e) {
360
+ const denied = delegationDenied(e);
361
+ if (denied) return denied;
362
+ throw e;
363
+ }
364
+ }
174
365
  const role = await prisma.role.findUnique({ where: { id }, include: { _count: { select: { userRoles: true } } } });
175
366
  if (!role) return json({ error: "Not found" }, 404);
176
367
  if (role._count.userRoles > 0)
package/src/rbac/types.ts CHANGED
@@ -20,6 +20,15 @@ export type Role = {
20
20
  updatedAt: string;
21
21
  createdBy?: string | null | undefined;
22
22
  updatedBy?: string | null | undefined;
23
+ /** App multi-tenant: đơn vị sở hữu vai trò; `null` = vai trò dùng chung. */
24
+ workspaceId?: string | null;
25
+ isSystem?: boolean;
26
+ rank?: number;
27
+ /**
28
+ * Người đang xem có SỬA/XOÁ được vai trò này không — server tính, client chỉ
29
+ * vẽ theo. `undefined` = app không xét uỷ quyền (hành vi cũ, coi như được).
30
+ */
31
+ canManage?: boolean;
23
32
  };
24
33
 
25
34
  export type Permission = {
@@ -6,6 +6,12 @@ export const roleSchema = z.object({
6
6
  description: z.string().optional(),
7
7
  status: z.enum(["active", "inactive"]).default("active"),
8
8
  permissions: z.array(z.string()).optional(),
9
+ /**
10
+ * Trang mở đầu của vai trò (`Role.landingPath`). Rỗng = "tự suy ra".
11
+ * Route phải lọc lại bằng `normalizeLandingPath` (@goerp/core/rbac/landing-path)
12
+ * trước khi ghi — schema chỉ nhận kiểu, không phán đường dẫn có an toàn không.
13
+ */
14
+ landingPath: z.string().optional().nullable(),
9
15
  });
10
16
 
11
17
  export type RoleFormData = z.infer<typeof roleSchema>;
@@ -47,6 +47,18 @@ export interface SignInFormProps {
47
47
  /** Ghi đè nhãn ô định danh (vd "Email hoặc mã nhân viên"). */
48
48
  identifierLabel?: string;
49
49
  identifierPlaceholder?: string;
50
+ /**
51
+ * Endpoint trả `{ path }` — TRANG MỞ ĐẦU của chính người vừa đăng nhập.
52
+ *
53
+ * Chỉ hỏi được SAU khi đăng nhập xong (trước đó server chưa biết là ai), nên
54
+ * không thể gói vào `?redirectTo=`. Không khai prop này thì mọi thứ y như cũ:
55
+ * về `?redirectTo=` / NEXT_PUBLIC_HOME_PATHNAME / "/".
56
+ *
57
+ * Hỏng mạng hay trả bậy đều bỏ qua, vẫn về đường mặc định — chặn đăng nhập
58
+ * thành công rồi kẹt ở màn hình trắng là cái giá quá đắt cho một gợi ý điều
59
+ * hướng.
60
+ */
61
+ landingEndpoint?: string;
50
62
  }
51
63
 
52
64
  const IDENTIFIER_PRESETS = {
@@ -80,6 +92,7 @@ export function SignInForm({
80
92
  identifier = "email",
81
93
  identifierLabel,
82
94
  identifierPlaceholder,
95
+ landingEndpoint,
83
96
  }: SignInFormProps = {}) {
84
97
  const preset = IDENTIFIER_PRESETS[identifier];
85
98
  const schema = React.useMemo(
@@ -98,10 +111,9 @@ export function SignInForm({
98
111
  const { clearAllCache } = useTabContentCache();
99
112
  const { clearTabs } = useTabNavigation();
100
113
 
114
+ const explicitRedirect = searchParams.get("redirectTo");
101
115
  const redirectPathname =
102
- searchParams.get("redirectTo") ||
103
- process.env.NEXT_PUBLIC_HOME_PATHNAME ||
104
- "/";
116
+ explicitRedirect || process.env.NEXT_PUBLIC_HOME_PATHNAME || "/";
105
117
 
106
118
  const form = useForm<SignInFormType>({
107
119
  resolver: zodResolver(schema),
@@ -145,7 +157,27 @@ export function SignInForm({
145
157
  // Best-effort only
146
158
  }
147
159
 
148
- router.push(redirectPathname);
160
+ // `?redirectTo=` là chỗ người dùng đang muốn tới trước khi bị đòi đăng
161
+ // nhập — luôn thắng trang mở đầu của vai trò.
162
+ let target = redirectPathname;
163
+ if (landingEndpoint && !explicitRedirect) {
164
+ try {
165
+ const res = await fetch(landingEndpoint);
166
+ const data = await res.json();
167
+ // Chỉ nhận đường dẫn nội bộ ("//host" là URL giao thức tương đối).
168
+ if (
169
+ typeof data?.path === "string" &&
170
+ data.path.startsWith("/") &&
171
+ !data.path.startsWith("//")
172
+ ) {
173
+ target = data.path;
174
+ }
175
+ } catch {
176
+ // Giữ đường mặc định — đăng nhập đã thành công rồi.
177
+ }
178
+ }
179
+
180
+ router.push(target);
149
181
  } catch (error) {
150
182
  const rawMessage =
151
183
  error instanceof Error ? error.message : "Đăng nhập thất bại";
@@ -1,5 +1,7 @@
1
+ import { assignableRoles } from "../workspace/delegation";
1
2
  import { memberScopeWhere } from "../workspace/scope";
2
3
 
4
+ import type { DelegationActor, DelegationRole } from "../workspace/delegation";
3
5
  import type { WorkspaceScope } from "../workspace/types";
4
6
  import type { CrudResponse } from "../types";
5
7
 
@@ -441,6 +443,61 @@ export async function getActiveRoles(db: UserPrismaClient) {
441
443
  return roles;
442
444
  }
443
445
 
446
+ /**
447
+ * Vai trò mà NGƯỜI ĐANG THAO TÁC được phép gán — dùng cho ô chọn vai trò trong
448
+ * hộp thoại người dùng.
449
+ *
450
+ * `getActiveRoles` trả về mọi vai trò đang hoạt động, kể cả "Quản trị hệ thống".
451
+ * Bản thân việc gán đã bị `assertCanCreateUser` chặn ở tầng API, nên đây không
452
+ * phải lỗ hổng — nhưng nó là cái bẫy giao diện: quản trị viên đơn vị chọn vai
453
+ * trò, bấm lưu, rồi mới ăn 403. Danh sách này lọc trước bằng CHÍNH luật D4
454
+ * (`assignableRoles`), nên thứ hiện ra là thứ lưu được.
455
+ *
456
+ * App chưa có cột `rank` (một tổ chức, không uỷ quyền) rơi về `getActiveRoles`.
457
+ */
458
+ export async function getAssignableRoles(
459
+ db: UserPrismaClient,
460
+ actor: DelegationActor | null,
461
+ ) {
462
+ if (!actor || actor.canManageAll || !db.role.fields?.rank) {
463
+ return getActiveRoles(db);
464
+ }
465
+
466
+ const rows = await db.role.findMany({
467
+ where: { status: "active" },
468
+ select: {
469
+ id: true,
470
+ code: true,
471
+ name: true,
472
+ status: true,
473
+ rank: true,
474
+ isSystem: db.role.fields?.isSystem ? true : undefined,
475
+ workspaceId: db.role.fields?.workspaceId ? true : undefined,
476
+ rolePermissions: { select: { resourceCode: true, actionCode: true } },
477
+ },
478
+ orderBy: { name: "asc" },
479
+ });
480
+
481
+ const candidates: (DelegationRole & { name: string; status: string })[] = rows.map((r: any) => ({
482
+ id: r.id,
483
+ code: r.code,
484
+ name: r.name,
485
+ status: r.status,
486
+ rank: r.rank,
487
+ isSystem: Boolean(r.isSystem),
488
+ workspaceId: r.workspaceId ?? null,
489
+ permissions: (r.rolePermissions ?? []).map(
490
+ (p: any) => `${p.resourceCode}:${p.actionCode}`,
491
+ ),
492
+ }));
493
+
494
+ return assignableRoles(actor, candidates).map((r) => ({
495
+ code: r.code,
496
+ name: r.name,
497
+ status: r.status,
498
+ }));
499
+ }
500
+
444
501
  /**
445
502
  * Get all active departments for filter dropdown
446
503
  */
@@ -10,8 +10,12 @@ import {
10
10
  assertNotSelf,
11
11
  assertRoleAssignable,
12
12
  assertWorkspacesInScope,
13
+ assertCanDeleteRole,
14
+ assertCanManageRole,
13
15
  assignableRoles,
14
16
  canDelegateUsers,
17
+ canManageRole,
18
+ defaultRoleWorkspaceIdFor,
15
19
  DelegationError,
16
20
  isDangerousPermission,
17
21
  } from "../delegation";
@@ -24,6 +28,7 @@ import type {
24
28
  DelegationActor,
25
29
  DelegationRole,
26
30
  DelegationTarget,
31
+ RoleDraft,
27
32
  } from "../delegation";
28
33
 
29
34
  /**
@@ -361,3 +366,100 @@ describe("cổng tổng hợp", () => {
361
366
  expect(() => assertCanCreateUser(opsAdmin(), [])).not.toThrow();
362
367
  });
363
368
  });
369
+
370
+ describe("Quản trị VAI TRÒ — cổng tạo/sửa/xoá", () => {
371
+ const draft = (over: Partial<RoleDraft> = {}): RoleDraft => ({
372
+ code: "TO_TRUONG",
373
+ permissions: ["meal-order:view"],
374
+ ...over,
375
+ });
376
+
377
+ it("tạo vai trò trong nhánh mình: được đóng dấu workspace + giữ rank", () => {
378
+ const gate = assertCanManageRole(customerAdmin(), null, draft({ rank: 80 }));
379
+ expect(gate.workspaceId).toBe("spa");
380
+ expect(gate.rank).toBe(80);
381
+ });
382
+
383
+ it("không tự tạo được vai trò DÙNG CHUNG (workspaceId null)", () => {
384
+ // Cửa hậu kinh điển: vai trò không mang dấu đơn vị thì đơn vị khác cũng gán
385
+ // được — admin nhánh vừa ghi vào không gian của cả hệ thống.
386
+ const actor = customerAdmin({
387
+ scope: createWorkspaceScope({
388
+ canViewAll: false,
389
+ rootIds: ["spa"],
390
+ allowedIds: ["spa"],
391
+ adminIds: [],
392
+ }),
393
+ });
394
+ expect(() => assertCanManageRole(actor, null, draft())).toThrow(
395
+ DelegationError,
396
+ );
397
+ });
398
+
399
+ it("không tạo được vai trò ngang hoặc mạnh hơn chính mình", () => {
400
+ try {
401
+ assertCanManageRole(customerAdmin(), null, draft({ rank: 50 }));
402
+ throw new Error("đáng lẽ phải ném");
403
+ } catch (error) {
404
+ expect((error as DelegationError).code).toBe("D2_EXCEEDS_CEILING");
405
+ }
406
+ });
407
+
408
+ it("không nhét được quyền quản trị hệ thống vào vai trò mới (D4)", () => {
409
+ try {
410
+ assertCanManageRole(
411
+ customerAdmin(),
412
+ null,
413
+ draft({ rank: 80, permissions: ["role:create"] }),
414
+ );
415
+ throw new Error("đáng lẽ phải ném");
416
+ } catch (error) {
417
+ expect((error as DelegationError).code).toBe("D4_DANGEROUS_ROLE");
418
+ }
419
+ });
420
+
421
+ it("không cấp được quyền mà chính mình không có (D2)", () => {
422
+ try {
423
+ assertCanManageRole(
424
+ customerAdmin(),
425
+ null,
426
+ draft({ rank: 80, permissions: ["payroll:view"] }),
427
+ );
428
+ throw new Error("đáng lẽ phải ném");
429
+ } catch (error) {
430
+ expect((error as DelegationError).code).toBe("D2_EXCEEDS_CEILING");
431
+ expect((error as DelegationError).message).toContain("payroll:view");
432
+ }
433
+ });
434
+
435
+ it("vai trò dùng chung: THẤY nhưng không sửa, không xoá", () => {
436
+ const shared = role({ rank: 100, workspaceId: null });
437
+ expect(canManageRole(customerAdmin(), shared)).toBe(false);
438
+ expect(() =>
439
+ assertCanManageRole(customerAdmin(), shared, draft({ rank: 100 })),
440
+ ).toThrow(DelegationError);
441
+ expect(() => assertCanDeleteRole(customerAdmin(), shared)).toThrow(
442
+ DelegationError,
443
+ );
444
+ });
445
+
446
+ it("vai trò của đơn vị khác / vai trò hệ thống đều không sửa được", () => {
447
+ expect(
448
+ canManageRole(customerAdmin(), role({ workspaceId: "tanloc" })),
449
+ ).toBe(false);
450
+ expect(
451
+ canManageRole(customerAdmin(), role({ workspaceId: "spa", isSystem: true })),
452
+ ).toBe(false);
453
+ expect(canManageRole(customerAdmin(), role({ workspaceId: "spa-qc" }))).toBe(
454
+ true,
455
+ );
456
+ });
457
+
458
+ it("nhóm vận hành miễn mọi luật", () => {
459
+ expect(canManageRole(opsAdmin(), role({ isSystem: true }))).toBe(true);
460
+ expect(() =>
461
+ assertCanManageRole(opsAdmin(), null, draft({ permissions: ["role:create"] })),
462
+ ).not.toThrow();
463
+ expect(defaultRoleWorkspaceIdFor(opsAdmin())).toBeNull();
464
+ });
465
+ });