roles update
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Loader2, Plus, ShieldCheck } from 'lucide-react';
|
||||
import { Loader2, Pencil, Plus, ShieldCheck, Trash2 } from 'lucide-react';
|
||||
import { AdminShell } from '@/components/id/admin-shell';
|
||||
import { useAuth } from '@/components/id/auth-provider';
|
||||
import { useToast } from '@/components/id/toast-provider';
|
||||
@@ -11,15 +11,31 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/u
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { AdminPermission, AdminRole, apiFetch } from '@/lib/api';
|
||||
|
||||
type RoleFormState = {
|
||||
slug: string;
|
||||
name: string;
|
||||
description: string;
|
||||
permissionSlugs: string[];
|
||||
};
|
||||
|
||||
const emptyForm: RoleFormState = { slug: '', name: '', description: '', permissionSlugs: [] };
|
||||
|
||||
export default function AdminRbacPage() {
|
||||
const { token, user } = useAuth();
|
||||
const { showToast } = useToast();
|
||||
const [roles, setRoles] = useState<AdminRole[]>([]);
|
||||
const [permissions, setPermissions] = useState<AdminPermission[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [creating, setCreating] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [dialogOpen, setDialogOpen] = useState(false);
|
||||
const [form, setForm] = useState({ slug: '', name: '', description: '', permissionSlugs: [] as string[] });
|
||||
const [editingRole, setEditingRole] = useState<AdminRole | null>(null);
|
||||
const [form, setForm] = useState<RoleFormState>(emptyForm);
|
||||
|
||||
async function reloadRoles() {
|
||||
if (!token) return;
|
||||
const response = await apiFetch<{ roles: AdminRole[] }>('/admin/rbac/roles', {}, token);
|
||||
setRoles(response.roles ?? []);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!token || !user?.canManageRoles) return;
|
||||
@@ -35,30 +51,74 @@ export default function AdminRbacPage() {
|
||||
.finally(() => setLoading(false));
|
||||
}, [showToast, token, user?.canManageRoles]);
|
||||
|
||||
async function handleCreateRole() {
|
||||
function openCreateDialog() {
|
||||
setEditingRole(null);
|
||||
setForm(emptyForm);
|
||||
setDialogOpen(true);
|
||||
}
|
||||
|
||||
function openEditDialog(role: AdminRole) {
|
||||
setEditingRole(role);
|
||||
setForm({
|
||||
slug: role.slug,
|
||||
name: role.name,
|
||||
description: role.description ?? '',
|
||||
permissionSlugs: role.permissions.map((permission) => permission.slug)
|
||||
});
|
||||
setDialogOpen(true);
|
||||
}
|
||||
|
||||
async function handleSaveRole() {
|
||||
if (!token) return;
|
||||
setCreating(true);
|
||||
setSaving(true);
|
||||
try {
|
||||
await apiFetch('/admin/rbac/roles', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(form)
|
||||
}, token);
|
||||
showToast('Роль создана');
|
||||
if (editingRole) {
|
||||
await apiFetch(`/admin/rbac/roles/${editingRole.slug}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify({
|
||||
name: form.name,
|
||||
description: form.description || undefined,
|
||||
permissionSlugs: form.permissionSlugs
|
||||
})
|
||||
}, token);
|
||||
showToast('Роль обновлена');
|
||||
} else {
|
||||
await apiFetch('/admin/rbac/roles', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(form)
|
||||
}, token);
|
||||
showToast('Роль создана');
|
||||
}
|
||||
setDialogOpen(false);
|
||||
setForm({ slug: '', name: '', description: '', permissionSlugs: [] });
|
||||
const response = await apiFetch<{ roles: AdminRole[] }>('/admin/rbac/roles', {}, token);
|
||||
setRoles(response.roles ?? []);
|
||||
setForm(emptyForm);
|
||||
setEditingRole(null);
|
||||
await reloadRoles();
|
||||
} catch (error) {
|
||||
showToast(error instanceof Error ? error.message : 'Не удалось создать роль');
|
||||
showToast(error instanceof Error ? error.message : 'Не удалось сохранить роль');
|
||||
} finally {
|
||||
setCreating(false);
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDeleteRole(role: AdminRole) {
|
||||
if (!token || role.isSystem) return;
|
||||
if (!window.confirm(`Удалить роль «${role.name}»? Она будет снята со всех пользователей.`)) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
await apiFetch(`/admin/rbac/roles/${role.slug}`, { method: 'DELETE' }, token);
|
||||
showToast('Роль удалена');
|
||||
await reloadRoles();
|
||||
} catch (error) {
|
||||
showToast(error instanceof Error ? error.message : 'Не удалось удалить роль');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (!user?.canManageRoles) {
|
||||
return (
|
||||
<AdminShell active="/admin/rbac">
|
||||
<p className="text-[#667085]">Управление ролями доступно только супер-администратору.</p>
|
||||
<p className="text-[#667085]">Управление ролями доступно пользователям с правом rbac.manage.</p>
|
||||
</AdminShell>
|
||||
);
|
||||
}
|
||||
@@ -68,9 +128,9 @@ export default function AdminRbacPage() {
|
||||
<div className="mb-6 flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<h2 className="text-2xl font-medium">Роли и права</h2>
|
||||
<p className="text-sm text-[#667085]">Только супер-администратор может создавать роли и назначать их пользователям</p>
|
||||
<p className="text-sm text-[#667085]">Редактируйте роли, назначайте права всем пользователям или отдельным аккаунтам</p>
|
||||
</div>
|
||||
<Button onClick={() => setDialogOpen(true)}>
|
||||
<Button onClick={openCreateDialog}>
|
||||
<Plus className="h-4 w-4" />
|
||||
Создать роль
|
||||
</Button>
|
||||
@@ -86,17 +146,37 @@ export default function AdminRbacPage() {
|
||||
{roles.map((role) => (
|
||||
<Card key={role.id} className="bg-[#f8f9fb] shadow-none">
|
||||
<CardHeader>
|
||||
<ShieldCheck className="h-6 w-6" />
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<ShieldCheck className="h-6 w-6 shrink-0" />
|
||||
<div className="flex gap-1">
|
||||
<Button variant="ghost" size="icon" aria-label="Редактировать роль" onClick={() => openEditDialog(role)}>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
{!role.isSystem ? (
|
||||
<Button variant="ghost" size="icon" aria-label="Удалить роль" disabled={saving} onClick={() => void handleDeleteRole(role)}>
|
||||
<Trash2 className="h-4 w-4 text-red-600" />
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
<CardTitle>{role.name}</CardTitle>
|
||||
<CardDescription>{role.permissions.length} прав · {role.slug}</CardDescription>
|
||||
<CardDescription>
|
||||
{role.permissions.length} прав · {role.slug}
|
||||
{role.isSystem ? ' · системная' : ''}
|
||||
{role.isDefault ? ' · по умолчанию' : ''}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2">
|
||||
{role.permissions.map((permission) => (
|
||||
<div key={permission.id} className="rounded-xl bg-white px-3 py-2 text-sm">
|
||||
<div className="font-medium">{permission.name}</div>
|
||||
<div className="text-xs text-[#667085]">{permission.slug}</div>
|
||||
</div>
|
||||
))}
|
||||
{role.permissions.length ? (
|
||||
role.permissions.map((permission) => (
|
||||
<div key={permission.id} className="rounded-xl bg-white px-3 py-2 text-sm">
|
||||
<div className="font-medium">{permission.name}</div>
|
||||
<div className="text-xs text-[#667085]">{permission.slug}</div>
|
||||
</div>
|
||||
))
|
||||
) : (
|
||||
<p className="text-sm text-[#667085]">Права не назначены</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
@@ -106,10 +186,14 @@ export default function AdminRbacPage() {
|
||||
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
|
||||
<DialogContent className="max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Новая роль</DialogTitle>
|
||||
<DialogTitle>{editingRole ? `Редактирование: ${editingRole.name}` : 'Новая роль'}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4">
|
||||
<Input value={form.slug} onChange={(event) => setForm((current) => ({ ...current, slug: event.target.value }))} placeholder="slug, например support" />
|
||||
{!editingRole ? (
|
||||
<Input value={form.slug} onChange={(event) => setForm((current) => ({ ...current, slug: event.target.value }))} placeholder="slug, например support" />
|
||||
) : (
|
||||
<p className="rounded-xl bg-[#f4f5f8] px-3 py-2 text-sm text-[#667085]">Slug: {editingRole.slug}</p>
|
||||
)}
|
||||
<Input value={form.name} onChange={(event) => setForm((current) => ({ ...current, name: event.target.value }))} placeholder="Название роли" />
|
||||
<Input value={form.description} onChange={(event) => setForm((current) => ({ ...current, description: event.target.value }))} placeholder="Описание" />
|
||||
<div className="space-y-2">
|
||||
@@ -132,8 +216,8 @@ export default function AdminRbacPage() {
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<Button className="w-full" disabled={creating} onClick={() => void handleCreateRole()}>
|
||||
{creating ? <Loader2 className="h-4 w-4 animate-spin" /> : 'Создать роль'}
|
||||
<Button className="w-full" disabled={saving || !form.name.trim() || (!editingRole && !form.slug.trim())} onClick={() => void handleSaveRole()}>
|
||||
{saving ? <Loader2 className="h-4 w-4 animate-spin" /> : editingRole ? 'Сохранить изменения' : 'Создать роль'}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
|
||||
Reference in New Issue
Block a user