mirror of
https://github.com/chillpadclub/bedolaga-cabinet.git
synced 2026-07-30 10:27:49 +00:00
refactor: replace role/policy modals with separate pages
- Create AdminRoleEdit.tsx for /admin/roles/create and /admin/roles/:id/edit - Create AdminPolicyEdit.tsx for /admin/policies/create and /admin/policies/:id/edit - Remove create/edit modals from AdminRoles.tsx and AdminPolicies.tsx - Add new lazy routes in App.tsx with proper permission gates - Keep delete confirmation as small inline modal (appropriate for destructive action)
This commit is contained in:
42
src/App.tsx
42
src/App.tsx
@@ -91,8 +91,10 @@ const AdminPinnedMessageCreate = lazy(() => import('./pages/AdminPinnedMessageCr
|
|||||||
const AdminChannelSubscriptions = lazy(() => import('./pages/AdminChannelSubscriptions'));
|
const AdminChannelSubscriptions = lazy(() => import('./pages/AdminChannelSubscriptions'));
|
||||||
const AdminEmailTemplatePreview = lazy(() => import('./pages/AdminEmailTemplatePreview'));
|
const AdminEmailTemplatePreview = lazy(() => import('./pages/AdminEmailTemplatePreview'));
|
||||||
const AdminRoles = lazy(() => import('./pages/AdminRoles'));
|
const AdminRoles = lazy(() => import('./pages/AdminRoles'));
|
||||||
|
const AdminRoleEdit = lazy(() => import('./pages/AdminRoleEdit'));
|
||||||
const AdminRoleAssign = lazy(() => import('./pages/AdminRoleAssign'));
|
const AdminRoleAssign = lazy(() => import('./pages/AdminRoleAssign'));
|
||||||
const AdminPolicies = lazy(() => import('./pages/AdminPolicies'));
|
const AdminPolicies = lazy(() => import('./pages/AdminPolicies'));
|
||||||
|
const AdminPolicyEdit = lazy(() => import('./pages/AdminPolicyEdit'));
|
||||||
const AdminAuditLog = lazy(() => import('./pages/AdminAuditLog'));
|
const AdminAuditLog = lazy(() => import('./pages/AdminAuditLog'));
|
||||||
|
|
||||||
function ProtectedRoute({ children }: { children: React.ReactNode }) {
|
function ProtectedRoute({ children }: { children: React.ReactNode }) {
|
||||||
@@ -892,6 +894,26 @@ function App() {
|
|||||||
</PermissionRoute>
|
</PermissionRoute>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
<Route
|
||||||
|
path="/admin/roles/create"
|
||||||
|
element={
|
||||||
|
<PermissionRoute permission="roles:create">
|
||||||
|
<LazyPage>
|
||||||
|
<AdminRoleEdit />
|
||||||
|
</LazyPage>
|
||||||
|
</PermissionRoute>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path="/admin/roles/:id/edit"
|
||||||
|
element={
|
||||||
|
<PermissionRoute permission="roles:edit">
|
||||||
|
<LazyPage>
|
||||||
|
<AdminRoleEdit />
|
||||||
|
</LazyPage>
|
||||||
|
</PermissionRoute>
|
||||||
|
}
|
||||||
|
/>
|
||||||
<Route
|
<Route
|
||||||
path="/admin/roles/assign"
|
path="/admin/roles/assign"
|
||||||
element={
|
element={
|
||||||
@@ -912,6 +934,26 @@ function App() {
|
|||||||
</PermissionRoute>
|
</PermissionRoute>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
<Route
|
||||||
|
path="/admin/policies/create"
|
||||||
|
element={
|
||||||
|
<PermissionRoute permission="roles:create">
|
||||||
|
<LazyPage>
|
||||||
|
<AdminPolicyEdit />
|
||||||
|
</LazyPage>
|
||||||
|
</PermissionRoute>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path="/admin/policies/:id/edit"
|
||||||
|
element={
|
||||||
|
<PermissionRoute permission="roles:edit">
|
||||||
|
<LazyPage>
|
||||||
|
<AdminPolicyEdit />
|
||||||
|
</LazyPage>
|
||||||
|
</PermissionRoute>
|
||||||
|
}
|
||||||
|
/>
|
||||||
<Route
|
<Route
|
||||||
path="/admin/audit-log"
|
path="/admin/audit-log"
|
||||||
element={
|
element={
|
||||||
|
|||||||
@@ -2,13 +2,7 @@ import { useState, useCallback, useMemo } from 'react';
|
|||||||
import { useNavigate } from 'react-router';
|
import { useNavigate } from 'react-router';
|
||||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import {
|
import { rbacApi, AccessPolicy, AdminRole } from '@/api/rbac';
|
||||||
rbacApi,
|
|
||||||
AccessPolicy,
|
|
||||||
AdminRole,
|
|
||||||
CreatePolicyPayload,
|
|
||||||
UpdatePolicyPayload,
|
|
||||||
} from '@/api/rbac';
|
|
||||||
import { PermissionGate } from '@/components/auth/PermissionGate';
|
import { PermissionGate } from '@/components/auth/PermissionGate';
|
||||||
import { usePlatform } from '@/platform/hooks/usePlatform';
|
import { usePlatform } from '@/platform/hooks/usePlatform';
|
||||||
|
|
||||||
@@ -52,12 +46,6 @@ const TrashIcon = () => (
|
|||||||
</svg>
|
</svg>
|
||||||
);
|
);
|
||||||
|
|
||||||
const XMarkIcon = () => (
|
|
||||||
<svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
|
|
||||||
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
|
|
||||||
</svg>
|
|
||||||
);
|
|
||||||
|
|
||||||
const ShieldIcon = () => (
|
const ShieldIcon = () => (
|
||||||
<svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
|
<svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
|
||||||
<path
|
<path
|
||||||
@@ -98,55 +86,14 @@ const BoltIcon = () => (
|
|||||||
</svg>
|
</svg>
|
||||||
);
|
);
|
||||||
|
|
||||||
// === Types ===
|
// === Helpers ===
|
||||||
|
|
||||||
interface PolicyConditions {
|
interface PolicyConditions {
|
||||||
time_range?: {
|
time_range?: { start: string; end: string };
|
||||||
start: string;
|
|
||||||
end: string;
|
|
||||||
};
|
|
||||||
ip_whitelist?: string[];
|
ip_whitelist?: string[];
|
||||||
rate_limit?: number;
|
rate_limit?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface PolicyFormData {
|
|
||||||
name: string;
|
|
||||||
description: string;
|
|
||||||
effect: 'allow' | 'deny';
|
|
||||||
resource: string;
|
|
||||||
actions: string[];
|
|
||||||
role_id: number | null;
|
|
||||||
priority: number;
|
|
||||||
conditions: PolicyConditions;
|
|
||||||
conditionsEnabled: {
|
|
||||||
time_range: boolean;
|
|
||||||
ip_whitelist: boolean;
|
|
||||||
rate_limit: boolean;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const INITIAL_FORM: PolicyFormData = {
|
|
||||||
name: '',
|
|
||||||
description: '',
|
|
||||||
effect: 'allow',
|
|
||||||
resource: '',
|
|
||||||
actions: [],
|
|
||||||
role_id: null,
|
|
||||||
priority: 0,
|
|
||||||
conditions: {
|
|
||||||
time_range: { start: '09:00', end: '18:00' },
|
|
||||||
ip_whitelist: [],
|
|
||||||
rate_limit: 100,
|
|
||||||
},
|
|
||||||
conditionsEnabled: {
|
|
||||||
time_range: false,
|
|
||||||
ip_whitelist: false,
|
|
||||||
rate_limit: false,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
// === Helpers ===
|
|
||||||
|
|
||||||
function parseConditions(raw: Record<string, unknown>): PolicyConditions {
|
function parseConditions(raw: Record<string, unknown>): PolicyConditions {
|
||||||
const result: PolicyConditions = {};
|
const result: PolicyConditions = {};
|
||||||
|
|
||||||
@@ -168,25 +115,6 @@ function parseConditions(raw: Record<string, unknown>): PolicyConditions {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildConditionsPayload(
|
|
||||||
conditions: PolicyConditions,
|
|
||||||
enabled: PolicyFormData['conditionsEnabled'],
|
|
||||||
): Record<string, unknown> {
|
|
||||||
const result: Record<string, unknown> = {};
|
|
||||||
|
|
||||||
if (enabled.time_range && conditions.time_range) {
|
|
||||||
result.time_range = conditions.time_range;
|
|
||||||
}
|
|
||||||
if (enabled.ip_whitelist && conditions.ip_whitelist && conditions.ip_whitelist.length > 0) {
|
|
||||||
result.ip_whitelist = conditions.ip_whitelist;
|
|
||||||
}
|
|
||||||
if (enabled.rate_limit && conditions.rate_limit !== undefined) {
|
|
||||||
result.rate_limit = conditions.rate_limit;
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
// === Sub-components ===
|
// === Sub-components ===
|
||||||
|
|
||||||
interface EffectBadgeProps {
|
interface EffectBadgeProps {
|
||||||
@@ -211,109 +139,6 @@ function EffectBadge({ effect, className }: EffectBadgeProps) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
interface IpTagInputProps {
|
|
||||||
values: string[];
|
|
||||||
onChange: (values: string[]) => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
function IpTagInput({ values, onChange }: IpTagInputProps) {
|
|
||||||
const { t } = useTranslation();
|
|
||||||
const [inputValue, setInputValue] = useState('');
|
|
||||||
|
|
||||||
const handleKeyDown = useCallback(
|
|
||||||
(e: React.KeyboardEvent<HTMLInputElement>) => {
|
|
||||||
if (e.key === 'Enter' || e.key === ',') {
|
|
||||||
e.preventDefault();
|
|
||||||
const trimmed = inputValue.trim().replace(/,+$/, '');
|
|
||||||
if (trimmed && !values.includes(trimmed)) {
|
|
||||||
onChange([...values, trimmed]);
|
|
||||||
}
|
|
||||||
setInputValue('');
|
|
||||||
} else if (e.key === 'Backspace' && !inputValue && values.length > 0) {
|
|
||||||
onChange(values.slice(0, -1));
|
|
||||||
}
|
|
||||||
},
|
|
||||||
[inputValue, values, onChange],
|
|
||||||
);
|
|
||||||
|
|
||||||
const removeIp = useCallback(
|
|
||||||
(ip: string) => {
|
|
||||||
onChange(values.filter((v) => v !== ip));
|
|
||||||
},
|
|
||||||
[values, onChange],
|
|
||||||
);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="flex flex-wrap items-center gap-1.5 rounded-lg border border-dark-600 bg-dark-900 px-3 py-2">
|
|
||||||
{values.map((ip) => (
|
|
||||||
<span
|
|
||||||
key={ip}
|
|
||||||
className="inline-flex items-center gap-1 rounded-md bg-dark-700 px-2 py-0.5 text-xs text-dark-200"
|
|
||||||
>
|
|
||||||
{ip}
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => removeIp(ip)}
|
|
||||||
className="text-dark-400 transition-colors hover:text-dark-200"
|
|
||||||
aria-label={t('admin.policies.conditions.removeIp', { ip })}
|
|
||||||
>
|
|
||||||
<svg
|
|
||||||
className="h-3 w-3"
|
|
||||||
fill="none"
|
|
||||||
viewBox="0 0 24 24"
|
|
||||||
stroke="currentColor"
|
|
||||||
strokeWidth={2}
|
|
||||||
>
|
|
||||||
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
|
|
||||||
</svg>
|
|
||||||
</button>
|
|
||||||
</span>
|
|
||||||
))}
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
value={inputValue}
|
|
||||||
onChange={(e) => setInputValue(e.target.value)}
|
|
||||||
onKeyDown={handleKeyDown}
|
|
||||||
className="min-w-[120px] flex-1 bg-transparent text-sm text-dark-100 placeholder-dark-500 outline-none"
|
|
||||||
placeholder={values.length === 0 ? t('admin.policies.conditions.ipPlaceholder') : ''}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ConditionToggleProps {
|
|
||||||
label: string;
|
|
||||||
enabled: boolean;
|
|
||||||
onToggle: () => void;
|
|
||||||
children: React.ReactNode;
|
|
||||||
}
|
|
||||||
|
|
||||||
function ConditionToggle({ label, enabled, onToggle, children }: ConditionToggleProps) {
|
|
||||||
return (
|
|
||||||
<div className="rounded-lg border border-dark-700/50 bg-dark-800/30">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={onToggle}
|
|
||||||
className="flex w-full items-center justify-between px-3 py-2"
|
|
||||||
>
|
|
||||||
<span className="text-sm font-medium text-dark-200">{label}</span>
|
|
||||||
<div
|
|
||||||
className={`relative h-5 w-9 rounded-full transition-colors ${
|
|
||||||
enabled ? 'bg-accent-500' : 'bg-dark-600'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<div
|
|
||||||
className={`absolute top-0.5 h-4 w-4 rounded-full bg-white transition-transform ${
|
|
||||||
enabled ? 'translate-x-4' : 'translate-x-0.5'
|
|
||||||
}`}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</button>
|
|
||||||
{enabled && <div className="border-t border-dark-700/50 px-3 py-2.5">{children}</div>}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// === Main Page ===
|
// === Main Page ===
|
||||||
|
|
||||||
export default function AdminPolicies() {
|
export default function AdminPolicies() {
|
||||||
@@ -322,10 +147,6 @@ export default function AdminPolicies() {
|
|||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const { capabilities } = usePlatform();
|
const { capabilities } = usePlatform();
|
||||||
|
|
||||||
// Modal state
|
|
||||||
const [modalOpen, setModalOpen] = useState(false);
|
|
||||||
const [editingPolicy, setEditingPolicy] = useState<AccessPolicy | null>(null);
|
|
||||||
const [formData, setFormData] = useState<PolicyFormData>(INITIAL_FORM);
|
|
||||||
const [deleteConfirm, setDeleteConfirm] = useState<number | null>(null);
|
const [deleteConfirm, setDeleteConfirm] = useState<number | null>(null);
|
||||||
const [formError, setFormError] = useState<string | null>(null);
|
const [formError, setFormError] = useState<string | null>(null);
|
||||||
|
|
||||||
@@ -344,35 +165,7 @@ export default function AdminPolicies() {
|
|||||||
queryFn: rbacApi.getRoles,
|
queryFn: rbacApi.getRoles,
|
||||||
});
|
});
|
||||||
|
|
||||||
const { data: permissionRegistry } = useQuery({
|
|
||||||
queryKey: ['admin-permission-registry'],
|
|
||||||
queryFn: rbacApi.getPermissionRegistry,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Mutations
|
// Mutations
|
||||||
const createMutation = useMutation({
|
|
||||||
mutationFn: (payload: CreatePolicyPayload) => rbacApi.createPolicy(payload),
|
|
||||||
onSuccess: () => {
|
|
||||||
queryClient.invalidateQueries({ queryKey: ['admin-policies'] });
|
|
||||||
closeModal();
|
|
||||||
},
|
|
||||||
onError: () => {
|
|
||||||
setFormError(t('admin.policies.errors.createFailed'));
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const updateMutation = useMutation({
|
|
||||||
mutationFn: ({ id, payload }: { id: number; payload: UpdatePolicyPayload }) =>
|
|
||||||
rbacApi.updatePolicy(id, payload),
|
|
||||||
onSuccess: () => {
|
|
||||||
queryClient.invalidateQueries({ queryKey: ['admin-policies'] });
|
|
||||||
closeModal();
|
|
||||||
},
|
|
||||||
onError: () => {
|
|
||||||
setFormError(t('admin.policies.errors.updateFailed'));
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const deleteMutation = useMutation({
|
const deleteMutation = useMutation({
|
||||||
mutationFn: rbacApi.deletePolicy,
|
mutationFn: rbacApi.deletePolicy,
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
@@ -396,138 +189,11 @@ export default function AdminPolicies() {
|
|||||||
return map;
|
return map;
|
||||||
}, [roles]);
|
}, [roles]);
|
||||||
|
|
||||||
const resourceSections = useMemo(() => {
|
|
||||||
if (!permissionRegistry) return [];
|
|
||||||
return permissionRegistry;
|
|
||||||
}, [permissionRegistry]);
|
|
||||||
|
|
||||||
const selectedResourceActions = useMemo(() => {
|
|
||||||
if (!formData.resource || !permissionRegistry) return [];
|
|
||||||
const section = permissionRegistry.find((s) => s.section === formData.resource);
|
|
||||||
return section?.actions ?? [];
|
|
||||||
}, [formData.resource, permissionRegistry]);
|
|
||||||
|
|
||||||
const sortedPolicies = useMemo(() => {
|
const sortedPolicies = useMemo(() => {
|
||||||
if (!policies) return [];
|
if (!policies) return [];
|
||||||
return [...policies].sort((a, b) => b.priority - a.priority);
|
return [...policies].sort((a, b) => b.priority - a.priority);
|
||||||
}, [policies]);
|
}, [policies]);
|
||||||
|
|
||||||
// Handlers
|
|
||||||
const closeModal = useCallback(() => {
|
|
||||||
setModalOpen(false);
|
|
||||||
setEditingPolicy(null);
|
|
||||||
setFormData(INITIAL_FORM);
|
|
||||||
setFormError(null);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const openCreateModal = useCallback(() => {
|
|
||||||
setEditingPolicy(null);
|
|
||||||
setFormData(INITIAL_FORM);
|
|
||||||
setFormError(null);
|
|
||||||
setModalOpen(true);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const openEditModal = useCallback((policy: AccessPolicy) => {
|
|
||||||
const parsed = parseConditions(policy.conditions);
|
|
||||||
|
|
||||||
const actions = Array.isArray(policy.actions) ? policy.actions : [];
|
|
||||||
|
|
||||||
setEditingPolicy(policy);
|
|
||||||
setFormData({
|
|
||||||
name: policy.name,
|
|
||||||
description: policy.description ?? '',
|
|
||||||
effect: policy.effect,
|
|
||||||
resource: policy.resource,
|
|
||||||
actions,
|
|
||||||
role_id: policy.role_id ?? null,
|
|
||||||
priority: policy.priority,
|
|
||||||
conditions: {
|
|
||||||
time_range: parsed.time_range ?? { start: '09:00', end: '18:00' },
|
|
||||||
ip_whitelist: parsed.ip_whitelist ?? [],
|
|
||||||
rate_limit: parsed.rate_limit ?? 100,
|
|
||||||
},
|
|
||||||
conditionsEnabled: {
|
|
||||||
time_range: !!parsed.time_range,
|
|
||||||
ip_whitelist: !!parsed.ip_whitelist && parsed.ip_whitelist.length > 0,
|
|
||||||
rate_limit: parsed.rate_limit !== undefined,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
setFormError(null);
|
|
||||||
setModalOpen(true);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const handleToggleAction = useCallback((action: string) => {
|
|
||||||
setFormData((prev) => {
|
|
||||||
const has = prev.actions.includes(action);
|
|
||||||
return {
|
|
||||||
...prev,
|
|
||||||
actions: has ? prev.actions.filter((a) => a !== action) : [...prev.actions, action],
|
|
||||||
};
|
|
||||||
});
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const handleResourceChange = useCallback((resource: string) => {
|
|
||||||
setFormData((prev) => ({
|
|
||||||
...prev,
|
|
||||||
resource,
|
|
||||||
actions: [],
|
|
||||||
}));
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const handleSubmit = useCallback(
|
|
||||||
(e: React.FormEvent) => {
|
|
||||||
e.preventDefault();
|
|
||||||
setFormError(null);
|
|
||||||
|
|
||||||
if (!formData.name.trim()) {
|
|
||||||
setFormError(t('admin.policies.errors.nameRequired'));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!formData.resource) {
|
|
||||||
setFormError(t('admin.policies.errors.resourceRequired'));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (formData.actions.length === 0) {
|
|
||||||
setFormError(t('admin.policies.errors.actionsRequired'));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const conditionsPayload = buildConditionsPayload(
|
|
||||||
formData.conditions,
|
|
||||||
formData.conditionsEnabled,
|
|
||||||
);
|
|
||||||
|
|
||||||
if (editingPolicy) {
|
|
||||||
const payload: UpdatePolicyPayload = {
|
|
||||||
name: formData.name.trim(),
|
|
||||||
description: formData.description.trim() || null,
|
|
||||||
effect: formData.effect,
|
|
||||||
resource: formData.resource,
|
|
||||||
actions: formData.actions,
|
|
||||||
conditions: conditionsPayload,
|
|
||||||
priority: formData.priority,
|
|
||||||
role_id: formData.role_id,
|
|
||||||
};
|
|
||||||
updateMutation.mutate({ id: editingPolicy.id, payload });
|
|
||||||
} else {
|
|
||||||
const payload: CreatePolicyPayload = {
|
|
||||||
name: formData.name.trim(),
|
|
||||||
description: formData.description.trim() || null,
|
|
||||||
effect: formData.effect,
|
|
||||||
resource: formData.resource,
|
|
||||||
actions: formData.actions,
|
|
||||||
conditions: conditionsPayload,
|
|
||||||
priority: formData.priority,
|
|
||||||
role_id: formData.role_id,
|
|
||||||
};
|
|
||||||
createMutation.mutate(payload);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
[formData, editingPolicy, createMutation, updateMutation, t],
|
|
||||||
);
|
|
||||||
|
|
||||||
const isSaving = createMutation.isPending || updateMutation.isPending;
|
|
||||||
|
|
||||||
// Condition icons renderer
|
// Condition icons renderer
|
||||||
const renderConditionIcons = useCallback(
|
const renderConditionIcons = useCallback(
|
||||||
(conditions: Record<string, unknown>) => {
|
(conditions: Record<string, unknown>) => {
|
||||||
@@ -608,7 +274,7 @@ export default function AdminPolicies() {
|
|||||||
</div>
|
</div>
|
||||||
<PermissionGate permission="roles:create">
|
<PermissionGate permission="roles:create">
|
||||||
<button
|
<button
|
||||||
onClick={openCreateModal}
|
onClick={() => navigate('/admin/policies/create')}
|
||||||
className="flex items-center justify-center gap-2 rounded-lg bg-accent-500 px-4 py-2 text-white transition-colors hover:bg-accent-600"
|
className="flex items-center justify-center gap-2 rounded-lg bg-accent-500 px-4 py-2 text-white transition-colors hover:bg-accent-600"
|
||||||
>
|
>
|
||||||
<PlusIcon />
|
<PlusIcon />
|
||||||
@@ -617,6 +283,13 @@ export default function AdminPolicies() {
|
|||||||
</PermissionGate>
|
</PermissionGate>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Error message */}
|
||||||
|
{formError && (
|
||||||
|
<div className="mb-4 rounded-lg border border-error-500/30 bg-error-500/10 p-3">
|
||||||
|
<p className="text-sm text-error-400">{formError}</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Stats Overview */}
|
{/* Stats Overview */}
|
||||||
{sortedPolicies.length > 0 && (
|
{sortedPolicies.length > 0 && (
|
||||||
<div className="mb-6 grid grid-cols-2 gap-3 sm:grid-cols-4">
|
<div className="mb-6 grid grid-cols-2 gap-3 sm:grid-cols-4">
|
||||||
@@ -716,7 +389,7 @@ export default function AdminPolicies() {
|
|||||||
<div className="flex items-center gap-2 border-t border-dark-700 pt-3 sm:border-0 sm:pt-0">
|
<div className="flex items-center gap-2 border-t border-dark-700 pt-3 sm:border-0 sm:pt-0">
|
||||||
<PermissionGate permission="roles:edit">
|
<PermissionGate permission="roles:edit">
|
||||||
<button
|
<button
|
||||||
onClick={() => openEditModal(policy)}
|
onClick={() => navigate(`/admin/policies/${policy.id}/edit`)}
|
||||||
className="flex-1 rounded-lg bg-dark-700 p-2 text-dark-300 transition-colors hover:bg-dark-600 hover:text-dark-100 sm:flex-none"
|
className="flex-1 rounded-lg bg-dark-700 p-2 text-dark-300 transition-colors hover:bg-dark-600 hover:text-dark-100 sm:flex-none"
|
||||||
title={t('admin.policies.actions.edit')}
|
title={t('admin.policies.actions.edit')}
|
||||||
>
|
>
|
||||||
@@ -740,362 +413,6 @@ export default function AdminPolicies() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Create / Edit Modal */}
|
|
||||||
{modalOpen && (
|
|
||||||
<div className="fixed inset-0 z-50 flex items-start justify-center overflow-y-auto p-4 pt-[5vh]">
|
|
||||||
{/* Backdrop */}
|
|
||||||
<div className="fixed inset-0 bg-black/60" onClick={closeModal} aria-hidden="true" />
|
|
||||||
{/* Modal content */}
|
|
||||||
<div className="relative w-full max-w-lg rounded-xl border border-dark-700 bg-dark-800 p-6 shadow-xl">
|
|
||||||
{/* Modal header */}
|
|
||||||
<div className="mb-5 flex items-center justify-between">
|
|
||||||
<h2 className="text-lg font-semibold text-dark-100">
|
|
||||||
{editingPolicy
|
|
||||||
? t('admin.policies.modal.editTitle')
|
|
||||||
: t('admin.policies.modal.createTitle')}
|
|
||||||
</h2>
|
|
||||||
<button
|
|
||||||
onClick={closeModal}
|
|
||||||
className="rounded-lg p-1 text-dark-400 transition-colors hover:bg-dark-700 hover:text-dark-200"
|
|
||||||
aria-label={t('admin.policies.modal.close')}
|
|
||||||
>
|
|
||||||
<XMarkIcon />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<form onSubmit={handleSubmit} className="space-y-4">
|
|
||||||
{/* Name */}
|
|
||||||
<div>
|
|
||||||
<label
|
|
||||||
htmlFor="policy-name"
|
|
||||||
className="mb-1 block text-sm font-medium text-dark-200"
|
|
||||||
>
|
|
||||||
{t('admin.policies.form.name')}
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
id="policy-name"
|
|
||||||
type="text"
|
|
||||||
value={formData.name}
|
|
||||||
onChange={(e) => setFormData((prev) => ({ ...prev, name: e.target.value }))}
|
|
||||||
className="w-full rounded-lg border border-dark-600 bg-dark-900 px-3 py-2 text-dark-100 placeholder-dark-500 outline-none transition-colors focus:border-accent-500"
|
|
||||||
placeholder={t('admin.policies.form.namePlaceholder')}
|
|
||||||
autoFocus
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Description */}
|
|
||||||
<div>
|
|
||||||
<label
|
|
||||||
htmlFor="policy-description"
|
|
||||||
className="mb-1 block text-sm font-medium text-dark-200"
|
|
||||||
>
|
|
||||||
{t('admin.policies.form.description')}
|
|
||||||
</label>
|
|
||||||
<textarea
|
|
||||||
id="policy-description"
|
|
||||||
value={formData.description}
|
|
||||||
onChange={(e) =>
|
|
||||||
setFormData((prev) => ({ ...prev, description: e.target.value }))
|
|
||||||
}
|
|
||||||
className="w-full rounded-lg border border-dark-600 bg-dark-900 px-3 py-2 text-dark-100 placeholder-dark-500 outline-none transition-colors focus:border-accent-500"
|
|
||||||
placeholder={t('admin.policies.form.descriptionPlaceholder')}
|
|
||||||
rows={2}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Effect toggle */}
|
|
||||||
<div>
|
|
||||||
<label className="mb-1 block text-sm font-medium text-dark-200">
|
|
||||||
{t('admin.policies.form.effect')}
|
|
||||||
</label>
|
|
||||||
<div className="flex gap-2">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setFormData((prev) => ({ ...prev, effect: 'allow' }))}
|
|
||||||
className={`flex-1 rounded-lg border px-3 py-2 text-sm font-medium transition-colors ${
|
|
||||||
formData.effect === 'allow'
|
|
||||||
? 'border-green-500/50 bg-green-500/10 text-green-400'
|
|
||||||
: 'border-dark-600 bg-dark-900 text-dark-400 hover:border-dark-500'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{t('admin.policies.effectAllow')}
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setFormData((prev) => ({ ...prev, effect: 'deny' }))}
|
|
||||||
className={`flex-1 rounded-lg border px-3 py-2 text-sm font-medium transition-colors ${
|
|
||||||
formData.effect === 'deny'
|
|
||||||
? 'border-red-500/50 bg-red-500/10 text-red-400'
|
|
||||||
: 'border-dark-600 bg-dark-900 text-dark-400 hover:border-dark-500'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{t('admin.policies.effectDeny')}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Resource dropdown */}
|
|
||||||
<div>
|
|
||||||
<label
|
|
||||||
htmlFor="policy-resource"
|
|
||||||
className="mb-1 block text-sm font-medium text-dark-200"
|
|
||||||
>
|
|
||||||
{t('admin.policies.form.resource')}
|
|
||||||
</label>
|
|
||||||
<select
|
|
||||||
id="policy-resource"
|
|
||||||
value={formData.resource}
|
|
||||||
onChange={(e) => handleResourceChange(e.target.value)}
|
|
||||||
className="w-full rounded-lg border border-dark-600 bg-dark-900 px-3 py-2 text-dark-100 outline-none transition-colors focus:border-accent-500"
|
|
||||||
>
|
|
||||||
<option value="">{t('admin.policies.form.selectResource')}</option>
|
|
||||||
{resourceSections.map((section) => (
|
|
||||||
<option key={section.section} value={section.section}>
|
|
||||||
{section.section}
|
|
||||||
</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Actions checkboxes */}
|
|
||||||
{formData.resource && selectedResourceActions.length > 0 && (
|
|
||||||
<div>
|
|
||||||
<label className="mb-1 block text-sm font-medium text-dark-200">
|
|
||||||
{t('admin.policies.form.actions')}
|
|
||||||
</label>
|
|
||||||
<div className="flex flex-wrap gap-2 rounded-lg border border-dark-600 bg-dark-900/50 p-3">
|
|
||||||
{selectedResourceActions.map((action) => {
|
|
||||||
const selected = formData.actions.includes(action);
|
|
||||||
return (
|
|
||||||
<button
|
|
||||||
key={action}
|
|
||||||
type="button"
|
|
||||||
onClick={() => handleToggleAction(action)}
|
|
||||||
className={`rounded-md px-2.5 py-1 text-xs font-medium transition-colors ${
|
|
||||||
selected
|
|
||||||
? 'bg-accent-500/20 text-accent-400'
|
|
||||||
: 'bg-dark-700/50 text-dark-400 hover:bg-dark-700 hover:text-dark-300'
|
|
||||||
}`}
|
|
||||||
aria-pressed={selected}
|
|
||||||
>
|
|
||||||
{action}
|
|
||||||
</button>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Role dropdown (optional) */}
|
|
||||||
<div>
|
|
||||||
<label
|
|
||||||
htmlFor="policy-role"
|
|
||||||
className="mb-1 block text-sm font-medium text-dark-200"
|
|
||||||
>
|
|
||||||
{t('admin.policies.form.role')}
|
|
||||||
</label>
|
|
||||||
<select
|
|
||||||
id="policy-role"
|
|
||||||
value={formData.role_id ?? ''}
|
|
||||||
onChange={(e) =>
|
|
||||||
setFormData((prev) => ({
|
|
||||||
...prev,
|
|
||||||
role_id: e.target.value ? Number(e.target.value) : null,
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
className="w-full rounded-lg border border-dark-600 bg-dark-900 px-3 py-2 text-dark-100 outline-none transition-colors focus:border-accent-500"
|
|
||||||
>
|
|
||||||
<option value="">{t('admin.policies.form.globalOption')}</option>
|
|
||||||
{roles?.map((role) => (
|
|
||||||
<option key={role.id} value={role.id}>
|
|
||||||
{role.name}
|
|
||||||
</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
<p className="mt-1 text-xs text-dark-500">{t('admin.policies.form.roleHint')}</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Priority */}
|
|
||||||
<div>
|
|
||||||
<label
|
|
||||||
htmlFor="policy-priority"
|
|
||||||
className="mb-1 block text-sm font-medium text-dark-200"
|
|
||||||
>
|
|
||||||
{t('admin.policies.form.priority')}
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
id="policy-priority"
|
|
||||||
type="number"
|
|
||||||
min={0}
|
|
||||||
max={999}
|
|
||||||
value={formData.priority}
|
|
||||||
onChange={(e) =>
|
|
||||||
setFormData((prev) => ({
|
|
||||||
...prev,
|
|
||||||
priority: Math.min(999, Math.max(0, Number(e.target.value) || 0)),
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
className="w-full rounded-lg border border-dark-600 bg-dark-900 px-3 py-2 text-dark-100 outline-none transition-colors focus:border-accent-500"
|
|
||||||
/>
|
|
||||||
<p className="mt-1 text-xs text-dark-500">
|
|
||||||
{t('admin.policies.form.priorityHint')}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Conditions builder */}
|
|
||||||
<div>
|
|
||||||
<label className="mb-2 block text-sm font-medium text-dark-200">
|
|
||||||
{t('admin.policies.form.conditions')}
|
|
||||||
</label>
|
|
||||||
<div className="space-y-2">
|
|
||||||
{/* Time range */}
|
|
||||||
<ConditionToggle
|
|
||||||
label={t('admin.policies.conditions.timeRange')}
|
|
||||||
enabled={formData.conditionsEnabled.time_range}
|
|
||||||
onToggle={() =>
|
|
||||||
setFormData((prev) => ({
|
|
||||||
...prev,
|
|
||||||
conditionsEnabled: {
|
|
||||||
...prev.conditionsEnabled,
|
|
||||||
time_range: !prev.conditionsEnabled.time_range,
|
|
||||||
},
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<input
|
|
||||||
type="time"
|
|
||||||
value={formData.conditions.time_range?.start ?? '09:00'}
|
|
||||||
onChange={(e) =>
|
|
||||||
setFormData((prev) => ({
|
|
||||||
...prev,
|
|
||||||
conditions: {
|
|
||||||
...prev.conditions,
|
|
||||||
time_range: {
|
|
||||||
start: e.target.value,
|
|
||||||
end: prev.conditions.time_range?.end ?? '18:00',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
className="rounded-lg border border-dark-600 bg-dark-900 px-2 py-1.5 text-sm text-dark-100 outline-none focus:border-accent-500"
|
|
||||||
aria-label={t('admin.policies.conditions.timeStart')}
|
|
||||||
/>
|
|
||||||
<span className="text-dark-500">-</span>
|
|
||||||
<input
|
|
||||||
type="time"
|
|
||||||
value={formData.conditions.time_range?.end ?? '18:00'}
|
|
||||||
onChange={(e) =>
|
|
||||||
setFormData((prev) => ({
|
|
||||||
...prev,
|
|
||||||
conditions: {
|
|
||||||
...prev.conditions,
|
|
||||||
time_range: {
|
|
||||||
start: prev.conditions.time_range?.start ?? '09:00',
|
|
||||||
end: e.target.value,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
className="rounded-lg border border-dark-600 bg-dark-900 px-2 py-1.5 text-sm text-dark-100 outline-none focus:border-accent-500"
|
|
||||||
aria-label={t('admin.policies.conditions.timeEnd')}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</ConditionToggle>
|
|
||||||
|
|
||||||
{/* IP whitelist */}
|
|
||||||
<ConditionToggle
|
|
||||||
label={t('admin.policies.conditions.ipWhitelist')}
|
|
||||||
enabled={formData.conditionsEnabled.ip_whitelist}
|
|
||||||
onToggle={() =>
|
|
||||||
setFormData((prev) => ({
|
|
||||||
...prev,
|
|
||||||
conditionsEnabled: {
|
|
||||||
...prev.conditionsEnabled,
|
|
||||||
ip_whitelist: !prev.conditionsEnabled.ip_whitelist,
|
|
||||||
},
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<IpTagInput
|
|
||||||
values={formData.conditions.ip_whitelist ?? []}
|
|
||||||
onChange={(ips) =>
|
|
||||||
setFormData((prev) => ({
|
|
||||||
...prev,
|
|
||||||
conditions: {
|
|
||||||
...prev.conditions,
|
|
||||||
ip_whitelist: ips,
|
|
||||||
},
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
</ConditionToggle>
|
|
||||||
|
|
||||||
{/* Rate limit */}
|
|
||||||
<ConditionToggle
|
|
||||||
label={t('admin.policies.conditions.rateLimit')}
|
|
||||||
enabled={formData.conditionsEnabled.rate_limit}
|
|
||||||
onToggle={() =>
|
|
||||||
setFormData((prev) => ({
|
|
||||||
...prev,
|
|
||||||
conditionsEnabled: {
|
|
||||||
...prev.conditionsEnabled,
|
|
||||||
rate_limit: !prev.conditionsEnabled.rate_limit,
|
|
||||||
},
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<input
|
|
||||||
type="number"
|
|
||||||
min={1}
|
|
||||||
max={10000}
|
|
||||||
value={formData.conditions.rate_limit ?? 100}
|
|
||||||
onChange={(e) =>
|
|
||||||
setFormData((prev) => ({
|
|
||||||
...prev,
|
|
||||||
conditions: {
|
|
||||||
...prev.conditions,
|
|
||||||
rate_limit: Math.max(1, Number(e.target.value) || 1),
|
|
||||||
},
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
className="w-24 rounded-lg border border-dark-600 bg-dark-900 px-2 py-1.5 text-sm text-dark-100 outline-none focus:border-accent-500"
|
|
||||||
aria-label={t('admin.policies.conditions.rateLimitValue')}
|
|
||||||
/>
|
|
||||||
<span className="text-xs text-dark-500">
|
|
||||||
{t('admin.policies.conditions.perHour')}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</ConditionToggle>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Error */}
|
|
||||||
{formError && <p className="text-sm text-error-400">{formError}</p>}
|
|
||||||
|
|
||||||
{/* Actions */}
|
|
||||||
<div className="flex justify-end gap-3 pt-2">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={closeModal}
|
|
||||||
className="px-4 py-2 text-dark-300 transition-colors hover:text-dark-100"
|
|
||||||
>
|
|
||||||
{t('admin.policies.form.cancel')}
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="submit"
|
|
||||||
disabled={isSaving}
|
|
||||||
className="rounded-lg bg-accent-500 px-4 py-2 text-white transition-colors hover:bg-accent-600 disabled:opacity-50"
|
|
||||||
>
|
|
||||||
{isSaving ? t('admin.policies.form.saving') : t('admin.policies.form.save')}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Delete Confirmation */}
|
{/* Delete Confirmation */}
|
||||||
{deleteConfirm !== null && (
|
{deleteConfirm !== null && (
|
||||||
<div className="fixed inset-0 z-50 flex items-center justify-center p-4">
|
<div className="fixed inset-0 z-50 flex items-center justify-center p-4">
|
||||||
|
|||||||
716
src/pages/AdminPolicyEdit.tsx
Normal file
716
src/pages/AdminPolicyEdit.tsx
Normal file
@@ -0,0 +1,716 @@
|
|||||||
|
import { useState, useCallback, useMemo } from 'react';
|
||||||
|
import { useNavigate, useParams } from 'react-router';
|
||||||
|
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { rbacApi, AccessPolicy, CreatePolicyPayload, UpdatePolicyPayload } from '@/api/rbac';
|
||||||
|
import { AdminBackButton } from '@/components/admin';
|
||||||
|
|
||||||
|
// === Types ===
|
||||||
|
|
||||||
|
interface PolicyConditions {
|
||||||
|
time_range?: { start: string; end: string };
|
||||||
|
ip_whitelist?: string[];
|
||||||
|
rate_limit?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface PolicyFormData {
|
||||||
|
name: string;
|
||||||
|
description: string;
|
||||||
|
effect: 'allow' | 'deny';
|
||||||
|
resource: string;
|
||||||
|
actions: string[];
|
||||||
|
role_id: number | null;
|
||||||
|
priority: number;
|
||||||
|
conditions: PolicyConditions;
|
||||||
|
conditionsEnabled: {
|
||||||
|
time_range: boolean;
|
||||||
|
ip_whitelist: boolean;
|
||||||
|
rate_limit: boolean;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const INITIAL_FORM: PolicyFormData = {
|
||||||
|
name: '',
|
||||||
|
description: '',
|
||||||
|
effect: 'allow',
|
||||||
|
resource: '',
|
||||||
|
actions: [],
|
||||||
|
role_id: null,
|
||||||
|
priority: 0,
|
||||||
|
conditions: {
|
||||||
|
time_range: { start: '09:00', end: '18:00' },
|
||||||
|
ip_whitelist: [],
|
||||||
|
rate_limit: 100,
|
||||||
|
},
|
||||||
|
conditionsEnabled: {
|
||||||
|
time_range: false,
|
||||||
|
ip_whitelist: false,
|
||||||
|
rate_limit: false,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
// === Helpers ===
|
||||||
|
|
||||||
|
function parseConditions(raw: Record<string, unknown>): PolicyConditions {
|
||||||
|
const result: PolicyConditions = {};
|
||||||
|
|
||||||
|
if (raw.time_range && typeof raw.time_range === 'object') {
|
||||||
|
const tr = raw.time_range as Record<string, unknown>;
|
||||||
|
if (typeof tr.start === 'string' && typeof tr.end === 'string') {
|
||||||
|
result.time_range = { start: tr.start, end: tr.end };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Array.isArray(raw.ip_whitelist)) {
|
||||||
|
result.ip_whitelist = raw.ip_whitelist.filter((ip): ip is string => typeof ip === 'string');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof raw.rate_limit === 'number') {
|
||||||
|
result.rate_limit = raw.rate_limit;
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildConditionsPayload(
|
||||||
|
conditions: PolicyConditions,
|
||||||
|
enabled: PolicyFormData['conditionsEnabled'],
|
||||||
|
): Record<string, unknown> {
|
||||||
|
const result: Record<string, unknown> = {};
|
||||||
|
|
||||||
|
if (enabled.time_range && conditions.time_range) {
|
||||||
|
result.time_range = conditions.time_range;
|
||||||
|
}
|
||||||
|
if (enabled.ip_whitelist && conditions.ip_whitelist && conditions.ip_whitelist.length > 0) {
|
||||||
|
result.ip_whitelist = conditions.ip_whitelist;
|
||||||
|
}
|
||||||
|
if (enabled.rate_limit && conditions.rate_limit !== undefined) {
|
||||||
|
result.rate_limit = conditions.rate_limit;
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
// === Sub-components ===
|
||||||
|
|
||||||
|
interface IpTagInputProps {
|
||||||
|
values: string[];
|
||||||
|
onChange: (values: string[]) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
function IpTagInput({ values, onChange }: IpTagInputProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [inputValue, setInputValue] = useState('');
|
||||||
|
|
||||||
|
const handleKeyDown = useCallback(
|
||||||
|
(e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||||
|
if (e.key === 'Enter' || e.key === ',') {
|
||||||
|
e.preventDefault();
|
||||||
|
const trimmed = inputValue.trim().replace(/,+$/, '');
|
||||||
|
if (trimmed && !values.includes(trimmed)) {
|
||||||
|
onChange([...values, trimmed]);
|
||||||
|
}
|
||||||
|
setInputValue('');
|
||||||
|
} else if (e.key === 'Backspace' && !inputValue && values.length > 0) {
|
||||||
|
onChange(values.slice(0, -1));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[inputValue, values, onChange],
|
||||||
|
);
|
||||||
|
|
||||||
|
const removeIp = useCallback(
|
||||||
|
(ip: string) => {
|
||||||
|
onChange(values.filter((v) => v !== ip));
|
||||||
|
},
|
||||||
|
[values, onChange],
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-wrap items-center gap-1.5 rounded-lg border border-dark-600 bg-dark-900 px-3 py-2">
|
||||||
|
{values.map((ip) => (
|
||||||
|
<span
|
||||||
|
key={ip}
|
||||||
|
className="inline-flex items-center gap-1 rounded-md bg-dark-700 px-2 py-0.5 text-xs text-dark-200"
|
||||||
|
>
|
||||||
|
{ip}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => removeIp(ip)}
|
||||||
|
className="text-dark-400 transition-colors hover:text-dark-200"
|
||||||
|
aria-label={t('admin.policies.conditions.removeIp', { ip })}
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
className="h-3 w-3"
|
||||||
|
fill="none"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth={2}
|
||||||
|
>
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={inputValue}
|
||||||
|
onChange={(e) => setInputValue(e.target.value)}
|
||||||
|
onKeyDown={handleKeyDown}
|
||||||
|
className="min-w-[120px] flex-1 bg-transparent text-sm text-dark-100 placeholder-dark-500 outline-none"
|
||||||
|
placeholder={values.length === 0 ? t('admin.policies.conditions.ipPlaceholder') : ''}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ConditionToggleProps {
|
||||||
|
label: string;
|
||||||
|
enabled: boolean;
|
||||||
|
onToggle: () => void;
|
||||||
|
children: React.ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ConditionToggle({ label, enabled, onToggle, children }: ConditionToggleProps) {
|
||||||
|
return (
|
||||||
|
<div className="rounded-lg border border-dark-700/50 bg-dark-800/30">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onToggle}
|
||||||
|
className="flex w-full items-center justify-between px-3 py-2"
|
||||||
|
>
|
||||||
|
<span className="text-sm font-medium text-dark-200">{label}</span>
|
||||||
|
<div
|
||||||
|
className={`relative h-5 w-9 rounded-full transition-colors ${
|
||||||
|
enabled ? 'bg-accent-500' : 'bg-dark-600'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className={`absolute top-0.5 h-4 w-4 rounded-full bg-white transition-transform ${
|
||||||
|
enabled ? 'translate-x-4' : 'translate-x-0.5'
|
||||||
|
}`}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
{enabled && <div className="border-t border-dark-700/50 px-3 py-2.5">{children}</div>}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// === Main Page ===
|
||||||
|
|
||||||
|
export default function AdminPolicyEdit() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const { id } = useParams<{ id: string }>();
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const isEdit = !!id;
|
||||||
|
|
||||||
|
const [formData, setFormData] = useState<PolicyFormData>(INITIAL_FORM);
|
||||||
|
const [formError, setFormError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// Fetch policy for editing
|
||||||
|
const { isLoading: isLoadingPolicy } = useQuery({
|
||||||
|
queryKey: ['admin-policy', id],
|
||||||
|
queryFn: () => rbacApi.getPolicies(),
|
||||||
|
enabled: isEdit,
|
||||||
|
select: useCallback(
|
||||||
|
(policies: AccessPolicy[]) => {
|
||||||
|
const policy = policies.find((p) => p.id === Number(id));
|
||||||
|
if (policy) {
|
||||||
|
const parsed = parseConditions(policy.conditions);
|
||||||
|
const actions = Array.isArray(policy.actions) ? policy.actions : [];
|
||||||
|
|
||||||
|
setFormData({
|
||||||
|
name: policy.name,
|
||||||
|
description: policy.description ?? '',
|
||||||
|
effect: policy.effect,
|
||||||
|
resource: policy.resource,
|
||||||
|
actions,
|
||||||
|
role_id: policy.role_id ?? null,
|
||||||
|
priority: policy.priority,
|
||||||
|
conditions: {
|
||||||
|
time_range: parsed.time_range ?? { start: '09:00', end: '18:00' },
|
||||||
|
ip_whitelist: parsed.ip_whitelist ?? [],
|
||||||
|
rate_limit: parsed.rate_limit ?? 100,
|
||||||
|
},
|
||||||
|
conditionsEnabled: {
|
||||||
|
time_range: !!parsed.time_range,
|
||||||
|
ip_whitelist: !!parsed.ip_whitelist && parsed.ip_whitelist.length > 0,
|
||||||
|
rate_limit: parsed.rate_limit !== undefined,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return policy;
|
||||||
|
},
|
||||||
|
[id],
|
||||||
|
),
|
||||||
|
});
|
||||||
|
|
||||||
|
const { data: roles } = useQuery({
|
||||||
|
queryKey: ['admin-roles'],
|
||||||
|
queryFn: rbacApi.getRoles,
|
||||||
|
});
|
||||||
|
|
||||||
|
const { data: permissionRegistry } = useQuery({
|
||||||
|
queryKey: ['admin-permission-registry'],
|
||||||
|
queryFn: rbacApi.getPermissionRegistry,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Mutations
|
||||||
|
const createMutation = useMutation({
|
||||||
|
mutationFn: (payload: CreatePolicyPayload) => rbacApi.createPolicy(payload),
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['admin-policies'] });
|
||||||
|
navigate('/admin/policies');
|
||||||
|
},
|
||||||
|
onError: () => {
|
||||||
|
setFormError(t('admin.policies.errors.createFailed'));
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const updateMutation = useMutation({
|
||||||
|
mutationFn: ({ policyId, payload }: { policyId: number; payload: UpdatePolicyPayload }) =>
|
||||||
|
rbacApi.updatePolicy(policyId, payload),
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['admin-policies'] });
|
||||||
|
navigate('/admin/policies');
|
||||||
|
},
|
||||||
|
onError: () => {
|
||||||
|
setFormError(t('admin.policies.errors.updateFailed'));
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Derived data
|
||||||
|
const selectedResourceActions = useMemo(() => {
|
||||||
|
if (!formData.resource || !permissionRegistry) return [];
|
||||||
|
const section = permissionRegistry.find((s) => s.section === formData.resource);
|
||||||
|
return section?.actions ?? [];
|
||||||
|
}, [formData.resource, permissionRegistry]);
|
||||||
|
|
||||||
|
// Handlers
|
||||||
|
const handleToggleAction = useCallback((action: string) => {
|
||||||
|
setFormData((prev) => {
|
||||||
|
const has = prev.actions.includes(action);
|
||||||
|
return {
|
||||||
|
...prev,
|
||||||
|
actions: has ? prev.actions.filter((a) => a !== action) : [...prev.actions, action],
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleResourceChange = useCallback((resource: string) => {
|
||||||
|
setFormData((prev) => ({
|
||||||
|
...prev,
|
||||||
|
resource,
|
||||||
|
actions: [],
|
||||||
|
}));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleSubmit = useCallback(
|
||||||
|
(e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setFormError(null);
|
||||||
|
|
||||||
|
if (!formData.name.trim()) {
|
||||||
|
setFormError(t('admin.policies.errors.nameRequired'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!formData.resource) {
|
||||||
|
setFormError(t('admin.policies.errors.resourceRequired'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (formData.actions.length === 0) {
|
||||||
|
setFormError(t('admin.policies.errors.actionsRequired'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const conditionsPayload = buildConditionsPayload(
|
||||||
|
formData.conditions,
|
||||||
|
formData.conditionsEnabled,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (isEdit) {
|
||||||
|
const payload: UpdatePolicyPayload = {
|
||||||
|
name: formData.name.trim(),
|
||||||
|
description: formData.description.trim() || null,
|
||||||
|
effect: formData.effect,
|
||||||
|
resource: formData.resource,
|
||||||
|
actions: formData.actions,
|
||||||
|
conditions: conditionsPayload,
|
||||||
|
priority: formData.priority,
|
||||||
|
role_id: formData.role_id,
|
||||||
|
};
|
||||||
|
updateMutation.mutate({ policyId: Number(id), payload });
|
||||||
|
} else {
|
||||||
|
const payload: CreatePolicyPayload = {
|
||||||
|
name: formData.name.trim(),
|
||||||
|
description: formData.description.trim() || null,
|
||||||
|
effect: formData.effect,
|
||||||
|
resource: formData.resource,
|
||||||
|
actions: formData.actions,
|
||||||
|
conditions: conditionsPayload,
|
||||||
|
priority: formData.priority,
|
||||||
|
role_id: formData.role_id,
|
||||||
|
};
|
||||||
|
createMutation.mutate(payload);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[formData, isEdit, id, createMutation, updateMutation, t],
|
||||||
|
);
|
||||||
|
|
||||||
|
const isSaving = createMutation.isPending || updateMutation.isPending;
|
||||||
|
|
||||||
|
// Loading state
|
||||||
|
if (isEdit && isLoadingPolicy) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center justify-center py-12">
|
||||||
|
<div className="h-8 w-8 animate-spin rounded-full border-2 border-accent-500 border-t-transparent" />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="animate-fade-in space-y-6">
|
||||||
|
{/* Header */}
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<AdminBackButton to="/admin/policies" />
|
||||||
|
<div>
|
||||||
|
<h1 className="text-xl font-semibold text-dark-100">
|
||||||
|
{isEdit ? t('admin.policies.modal.editTitle') : t('admin.policies.modal.createTitle')}
|
||||||
|
</h1>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Form */}
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-6">
|
||||||
|
{/* Basic info */}
|
||||||
|
<div className="rounded-xl border border-dark-700 bg-dark-800 p-4 sm:p-6">
|
||||||
|
<div className="space-y-4">
|
||||||
|
{/* Name */}
|
||||||
|
<div>
|
||||||
|
<label htmlFor="policy-name" className="mb-1 block text-sm font-medium text-dark-200">
|
||||||
|
{t('admin.policies.form.name')}
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="policy-name"
|
||||||
|
type="text"
|
||||||
|
value={formData.name}
|
||||||
|
onChange={(e) => setFormData((prev) => ({ ...prev, name: e.target.value }))}
|
||||||
|
className="w-full rounded-lg border border-dark-600 bg-dark-900 px-3 py-2 text-dark-100 placeholder-dark-500 outline-none transition-colors focus:border-accent-500"
|
||||||
|
placeholder={t('admin.policies.form.namePlaceholder')}
|
||||||
|
autoFocus
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Description */}
|
||||||
|
<div>
|
||||||
|
<label
|
||||||
|
htmlFor="policy-description"
|
||||||
|
className="mb-1 block text-sm font-medium text-dark-200"
|
||||||
|
>
|
||||||
|
{t('admin.policies.form.description')}
|
||||||
|
</label>
|
||||||
|
<textarea
|
||||||
|
id="policy-description"
|
||||||
|
value={formData.description}
|
||||||
|
onChange={(e) => setFormData((prev) => ({ ...prev, description: e.target.value }))}
|
||||||
|
className="w-full rounded-lg border border-dark-600 bg-dark-900 px-3 py-2 text-dark-100 placeholder-dark-500 outline-none transition-colors focus:border-accent-500"
|
||||||
|
placeholder={t('admin.policies.form.descriptionPlaceholder')}
|
||||||
|
rows={2}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Effect toggle */}
|
||||||
|
<div>
|
||||||
|
<label className="mb-1 block text-sm font-medium text-dark-200">
|
||||||
|
{t('admin.policies.form.effect')}
|
||||||
|
</label>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setFormData((prev) => ({ ...prev, effect: 'allow' }))}
|
||||||
|
className={`flex-1 rounded-lg border px-3 py-2 text-sm font-medium transition-colors ${
|
||||||
|
formData.effect === 'allow'
|
||||||
|
? 'border-green-500/50 bg-green-500/10 text-green-400'
|
||||||
|
: 'border-dark-600 bg-dark-900 text-dark-400 hover:border-dark-500'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{t('admin.policies.effectAllow')}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setFormData((prev) => ({ ...prev, effect: 'deny' }))}
|
||||||
|
className={`flex-1 rounded-lg border px-3 py-2 text-sm font-medium transition-colors ${
|
||||||
|
formData.effect === 'deny'
|
||||||
|
? 'border-red-500/50 bg-red-500/10 text-red-400'
|
||||||
|
: 'border-dark-600 bg-dark-900 text-dark-400 hover:border-dark-500'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{t('admin.policies.effectDeny')}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Resource & Actions */}
|
||||||
|
<div className="rounded-xl border border-dark-700 bg-dark-800 p-4 sm:p-6">
|
||||||
|
<div className="space-y-4">
|
||||||
|
{/* Resource dropdown */}
|
||||||
|
<div>
|
||||||
|
<label
|
||||||
|
htmlFor="policy-resource"
|
||||||
|
className="mb-1 block text-sm font-medium text-dark-200"
|
||||||
|
>
|
||||||
|
{t('admin.policies.form.resource')}
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
id="policy-resource"
|
||||||
|
value={formData.resource}
|
||||||
|
onChange={(e) => handleResourceChange(e.target.value)}
|
||||||
|
className="w-full rounded-lg border border-dark-600 bg-dark-900 px-3 py-2 text-dark-100 outline-none transition-colors focus:border-accent-500"
|
||||||
|
>
|
||||||
|
<option value="">{t('admin.policies.form.selectResource')}</option>
|
||||||
|
{permissionRegistry?.map((section) => (
|
||||||
|
<option key={section.section} value={section.section}>
|
||||||
|
{section.section}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Actions checkboxes */}
|
||||||
|
{formData.resource && selectedResourceActions.length > 0 && (
|
||||||
|
<div>
|
||||||
|
<label className="mb-1 block text-sm font-medium text-dark-200">
|
||||||
|
{t('admin.policies.form.actions')}
|
||||||
|
</label>
|
||||||
|
<div className="flex flex-wrap gap-2 rounded-lg border border-dark-600 bg-dark-900/50 p-3">
|
||||||
|
{selectedResourceActions.map((action) => {
|
||||||
|
const selected = formData.actions.includes(action);
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={action}
|
||||||
|
type="button"
|
||||||
|
onClick={() => handleToggleAction(action)}
|
||||||
|
className={`rounded-md px-2.5 py-1 text-xs font-medium transition-colors ${
|
||||||
|
selected
|
||||||
|
? 'bg-accent-500/20 text-accent-400'
|
||||||
|
: 'bg-dark-700/50 text-dark-400 hover:bg-dark-700 hover:text-dark-300'
|
||||||
|
}`}
|
||||||
|
aria-pressed={selected}
|
||||||
|
>
|
||||||
|
{action}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Role dropdown */}
|
||||||
|
<div>
|
||||||
|
<label htmlFor="policy-role" className="mb-1 block text-sm font-medium text-dark-200">
|
||||||
|
{t('admin.policies.form.role')}
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
id="policy-role"
|
||||||
|
value={formData.role_id ?? ''}
|
||||||
|
onChange={(e) =>
|
||||||
|
setFormData((prev) => ({
|
||||||
|
...prev,
|
||||||
|
role_id: e.target.value ? Number(e.target.value) : null,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
className="w-full rounded-lg border border-dark-600 bg-dark-900 px-3 py-2 text-dark-100 outline-none transition-colors focus:border-accent-500"
|
||||||
|
>
|
||||||
|
<option value="">{t('admin.policies.form.globalOption')}</option>
|
||||||
|
{roles?.map((role) => (
|
||||||
|
<option key={role.id} value={role.id}>
|
||||||
|
{role.name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
<p className="mt-1 text-xs text-dark-500">{t('admin.policies.form.roleHint')}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Priority */}
|
||||||
|
<div>
|
||||||
|
<label
|
||||||
|
htmlFor="policy-priority"
|
||||||
|
className="mb-1 block text-sm font-medium text-dark-200"
|
||||||
|
>
|
||||||
|
{t('admin.policies.form.priority')}
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="policy-priority"
|
||||||
|
type="number"
|
||||||
|
min={0}
|
||||||
|
max={999}
|
||||||
|
value={formData.priority}
|
||||||
|
onChange={(e) =>
|
||||||
|
setFormData((prev) => ({
|
||||||
|
...prev,
|
||||||
|
priority: Math.min(999, Math.max(0, Number(e.target.value) || 0)),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
className="w-full rounded-lg border border-dark-600 bg-dark-900 px-3 py-2 text-dark-100 outline-none transition-colors focus:border-accent-500"
|
||||||
|
/>
|
||||||
|
<p className="mt-1 text-xs text-dark-500">{t('admin.policies.form.priorityHint')}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Conditions */}
|
||||||
|
<div className="rounded-xl border border-dark-700 bg-dark-800 p-4 sm:p-6">
|
||||||
|
<label className="mb-3 block text-sm font-medium text-dark-200">
|
||||||
|
{t('admin.policies.form.conditions')}
|
||||||
|
</label>
|
||||||
|
<div className="space-y-2">
|
||||||
|
{/* Time range */}
|
||||||
|
<ConditionToggle
|
||||||
|
label={t('admin.policies.conditions.timeRange')}
|
||||||
|
enabled={formData.conditionsEnabled.time_range}
|
||||||
|
onToggle={() =>
|
||||||
|
setFormData((prev) => ({
|
||||||
|
...prev,
|
||||||
|
conditionsEnabled: {
|
||||||
|
...prev.conditionsEnabled,
|
||||||
|
time_range: !prev.conditionsEnabled.time_range,
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<input
|
||||||
|
type="time"
|
||||||
|
value={formData.conditions.time_range?.start ?? '09:00'}
|
||||||
|
onChange={(e) =>
|
||||||
|
setFormData((prev) => ({
|
||||||
|
...prev,
|
||||||
|
conditions: {
|
||||||
|
...prev.conditions,
|
||||||
|
time_range: {
|
||||||
|
start: e.target.value,
|
||||||
|
end: prev.conditions.time_range?.end ?? '18:00',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
className="rounded-lg border border-dark-600 bg-dark-900 px-2 py-1.5 text-sm text-dark-100 outline-none focus:border-accent-500"
|
||||||
|
aria-label={t('admin.policies.conditions.timeStart')}
|
||||||
|
/>
|
||||||
|
<span className="text-dark-500">-</span>
|
||||||
|
<input
|
||||||
|
type="time"
|
||||||
|
value={formData.conditions.time_range?.end ?? '18:00'}
|
||||||
|
onChange={(e) =>
|
||||||
|
setFormData((prev) => ({
|
||||||
|
...prev,
|
||||||
|
conditions: {
|
||||||
|
...prev.conditions,
|
||||||
|
time_range: {
|
||||||
|
start: prev.conditions.time_range?.start ?? '09:00',
|
||||||
|
end: e.target.value,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
className="rounded-lg border border-dark-600 bg-dark-900 px-2 py-1.5 text-sm text-dark-100 outline-none focus:border-accent-500"
|
||||||
|
aria-label={t('admin.policies.conditions.timeEnd')}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</ConditionToggle>
|
||||||
|
|
||||||
|
{/* IP whitelist */}
|
||||||
|
<ConditionToggle
|
||||||
|
label={t('admin.policies.conditions.ipWhitelist')}
|
||||||
|
enabled={formData.conditionsEnabled.ip_whitelist}
|
||||||
|
onToggle={() =>
|
||||||
|
setFormData((prev) => ({
|
||||||
|
...prev,
|
||||||
|
conditionsEnabled: {
|
||||||
|
...prev.conditionsEnabled,
|
||||||
|
ip_whitelist: !prev.conditionsEnabled.ip_whitelist,
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<IpTagInput
|
||||||
|
values={formData.conditions.ip_whitelist ?? []}
|
||||||
|
onChange={(ips) =>
|
||||||
|
setFormData((prev) => ({
|
||||||
|
...prev,
|
||||||
|
conditions: {
|
||||||
|
...prev.conditions,
|
||||||
|
ip_whitelist: ips,
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</ConditionToggle>
|
||||||
|
|
||||||
|
{/* Rate limit */}
|
||||||
|
<ConditionToggle
|
||||||
|
label={t('admin.policies.conditions.rateLimit')}
|
||||||
|
enabled={formData.conditionsEnabled.rate_limit}
|
||||||
|
onToggle={() =>
|
||||||
|
setFormData((prev) => ({
|
||||||
|
...prev,
|
||||||
|
conditionsEnabled: {
|
||||||
|
...prev.conditionsEnabled,
|
||||||
|
rate_limit: !prev.conditionsEnabled.rate_limit,
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
min={1}
|
||||||
|
max={10000}
|
||||||
|
value={formData.conditions.rate_limit ?? 100}
|
||||||
|
onChange={(e) =>
|
||||||
|
setFormData((prev) => ({
|
||||||
|
...prev,
|
||||||
|
conditions: {
|
||||||
|
...prev.conditions,
|
||||||
|
rate_limit: Math.max(1, Number(e.target.value) || 1),
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
className="w-24 rounded-lg border border-dark-600 bg-dark-900 px-2 py-1.5 text-sm text-dark-100 outline-none focus:border-accent-500"
|
||||||
|
aria-label={t('admin.policies.conditions.rateLimitValue')}
|
||||||
|
/>
|
||||||
|
<span className="text-xs text-dark-500">
|
||||||
|
{t('admin.policies.conditions.perHour')}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</ConditionToggle>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Error & Submit */}
|
||||||
|
<div className="rounded-xl border border-dark-700 bg-dark-800 p-4 sm:p-6">
|
||||||
|
{formError && <p className="mb-4 text-sm text-error-400">{formError}</p>}
|
||||||
|
<div className="flex justify-end gap-3">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => navigate('/admin/policies')}
|
||||||
|
className="px-4 py-2 text-dark-300 transition-colors hover:text-dark-100"
|
||||||
|
>
|
||||||
|
{t('admin.policies.form.cancel')}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={isSaving}
|
||||||
|
className="rounded-lg bg-accent-500 px-4 py-2 text-white transition-colors hover:bg-accent-600 disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{isSaving ? t('admin.policies.form.saving') : t('admin.policies.form.save')}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
536
src/pages/AdminRoleEdit.tsx
Normal file
536
src/pages/AdminRoleEdit.tsx
Normal file
@@ -0,0 +1,536 @@
|
|||||||
|
import { useState, useCallback } from 'react';
|
||||||
|
import { useNavigate, useParams } from 'react-router';
|
||||||
|
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { rbacApi, PermissionSection, CreateRolePayload, UpdateRolePayload } from '@/api/rbac';
|
||||||
|
import { AdminBackButton } from '@/components/admin';
|
||||||
|
|
||||||
|
// === Icons ===
|
||||||
|
|
||||||
|
const ChevronDownIcon = ({ className }: { className?: string }) => (
|
||||||
|
<svg
|
||||||
|
className={className || 'h-4 w-4'}
|
||||||
|
fill="none"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth={2}
|
||||||
|
>
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5" />
|
||||||
|
</svg>
|
||||||
|
);
|
||||||
|
|
||||||
|
// === Constants ===
|
||||||
|
|
||||||
|
const ROLE_COLORS = [
|
||||||
|
'#6366f1',
|
||||||
|
'#8b5cf6',
|
||||||
|
'#a855f7',
|
||||||
|
'#ec4899',
|
||||||
|
'#ef4444',
|
||||||
|
'#f97316',
|
||||||
|
'#eab308',
|
||||||
|
'#22c55e',
|
||||||
|
'#14b8a6',
|
||||||
|
'#06b6d4',
|
||||||
|
'#3b82f6',
|
||||||
|
'#6b7280',
|
||||||
|
];
|
||||||
|
|
||||||
|
const PRESETS: Record<string, string[]> = {
|
||||||
|
moderator: ['users:read', 'users:edit', 'users:block', 'tickets:*', 'ban_system:*'],
|
||||||
|
marketer: [
|
||||||
|
'campaigns:*',
|
||||||
|
'broadcasts:*',
|
||||||
|
'promocodes:*',
|
||||||
|
'promo_offers:*',
|
||||||
|
'promo_groups:*',
|
||||||
|
'stats:read',
|
||||||
|
'pinned_messages:*',
|
||||||
|
'wheel:*',
|
||||||
|
],
|
||||||
|
support: ['tickets:read', 'tickets:reply', 'users:read'],
|
||||||
|
};
|
||||||
|
|
||||||
|
// === Types ===
|
||||||
|
|
||||||
|
interface RoleFormData {
|
||||||
|
name: string;
|
||||||
|
description: string;
|
||||||
|
level: number;
|
||||||
|
color: string;
|
||||||
|
permissions: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const INITIAL_FORM: RoleFormData = {
|
||||||
|
name: '',
|
||||||
|
description: '',
|
||||||
|
level: 50,
|
||||||
|
color: ROLE_COLORS[0],
|
||||||
|
permissions: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
// === Sub-components ===
|
||||||
|
|
||||||
|
interface PermissionMatrixProps {
|
||||||
|
registry: PermissionSection[];
|
||||||
|
selectedPermissions: string[];
|
||||||
|
onToggle: (perm: string) => void;
|
||||||
|
onToggleSection: (section: string, actions: string[]) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
function PermissionMatrix({
|
||||||
|
registry,
|
||||||
|
selectedPermissions,
|
||||||
|
onToggle,
|
||||||
|
onToggleSection,
|
||||||
|
}: PermissionMatrixProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [expanded, setExpanded] = useState<Record<string, boolean>>({});
|
||||||
|
|
||||||
|
const toggleExpand = useCallback((section: string) => {
|
||||||
|
setExpanded((prev) => ({ ...prev, [section]: !prev[section] }));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const isSectionFullySelected = useCallback(
|
||||||
|
(section: string, actions: string[]) => {
|
||||||
|
return actions.every((action) => {
|
||||||
|
const perm = `${section}:${action}`;
|
||||||
|
return selectedPermissions.includes(perm) || selectedPermissions.includes(`${section}:*`);
|
||||||
|
});
|
||||||
|
},
|
||||||
|
[selectedPermissions],
|
||||||
|
);
|
||||||
|
|
||||||
|
const isSectionPartiallySelected = useCallback(
|
||||||
|
(section: string, actions: string[]) => {
|
||||||
|
const hasAny = actions.some((action) => {
|
||||||
|
const perm = `${section}:${action}`;
|
||||||
|
return selectedPermissions.includes(perm) || selectedPermissions.includes(`${section}:*`);
|
||||||
|
});
|
||||||
|
return hasAny && !isSectionFullySelected(section, actions);
|
||||||
|
},
|
||||||
|
[selectedPermissions, isSectionFullySelected],
|
||||||
|
);
|
||||||
|
|
||||||
|
const isPermSelected = useCallback(
|
||||||
|
(section: string, action: string) => {
|
||||||
|
const perm = `${section}:${action}`;
|
||||||
|
return selectedPermissions.includes(perm) || selectedPermissions.includes(`${section}:*`);
|
||||||
|
},
|
||||||
|
[selectedPermissions],
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label className="text-sm font-medium text-dark-200">
|
||||||
|
{t('admin.roles.form.permissions')}
|
||||||
|
</label>
|
||||||
|
<div className="space-y-1 rounded-lg border border-dark-600 bg-dark-900/50 p-2">
|
||||||
|
{registry.map((section) => {
|
||||||
|
const isExpanded = expanded[section.section] ?? false;
|
||||||
|
const allSelected = isSectionFullySelected(section.section, section.actions);
|
||||||
|
const partialSelected = isSectionPartiallySelected(section.section, section.actions);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={section.section}
|
||||||
|
className="rounded-lg border border-dark-700/50 bg-dark-800/30"
|
||||||
|
>
|
||||||
|
<div className="flex items-center gap-2 px-3 py-2">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => onToggleSection(section.section, section.actions)}
|
||||||
|
className={`flex h-4 w-4 shrink-0 items-center justify-center rounded border transition-colors ${
|
||||||
|
allSelected
|
||||||
|
? 'border-accent-500 bg-accent-500'
|
||||||
|
: partialSelected
|
||||||
|
? 'border-accent-500 bg-accent-500/40'
|
||||||
|
: 'border-dark-500 hover:border-dark-400'
|
||||||
|
}`}
|
||||||
|
aria-label={t('admin.roles.form.toggleSection', { section: section.section })}
|
||||||
|
>
|
||||||
|
{(allSelected || partialSelected) && (
|
||||||
|
<svg
|
||||||
|
className="h-3 w-3 text-white"
|
||||||
|
fill="none"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth={3}
|
||||||
|
>
|
||||||
|
{allSelected ? (
|
||||||
|
<path
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
d="M4.5 12.75l6 6 9-13.5"
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" d="M5 12h14" />
|
||||||
|
)}
|
||||||
|
</svg>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => toggleExpand(section.section)}
|
||||||
|
className="flex flex-1 items-center justify-between"
|
||||||
|
>
|
||||||
|
<span className="text-sm font-medium text-dark-200">{section.section}</span>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="text-xs text-dark-500">
|
||||||
|
{section.actions.filter((a) => isPermSelected(section.section, a)).length}/
|
||||||
|
{section.actions.length}
|
||||||
|
</span>
|
||||||
|
<ChevronDownIcon
|
||||||
|
className={`h-4 w-4 text-dark-400 transition-transform ${
|
||||||
|
isExpanded ? 'rotate-180' : ''
|
||||||
|
}`}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{isExpanded && (
|
||||||
|
<div className="border-t border-dark-700/50 px-3 py-2">
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{section.actions.map((action) => {
|
||||||
|
const perm = `${section.section}:${action}`;
|
||||||
|
const selected = isPermSelected(section.section, action);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={perm}
|
||||||
|
type="button"
|
||||||
|
onClick={() => onToggle(perm)}
|
||||||
|
className={`rounded-md px-2.5 py-1 text-xs font-medium transition-colors ${
|
||||||
|
selected
|
||||||
|
? 'bg-accent-500/20 text-accent-400'
|
||||||
|
: 'bg-dark-700/50 text-dark-400 hover:bg-dark-700 hover:text-dark-300'
|
||||||
|
}`}
|
||||||
|
aria-pressed={selected}
|
||||||
|
>
|
||||||
|
{action}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// === Main Page ===
|
||||||
|
|
||||||
|
export default function AdminRoleEdit() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const { id } = useParams<{ id: string }>();
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const isEdit = !!id;
|
||||||
|
|
||||||
|
const [formData, setFormData] = useState<RoleFormData>(INITIAL_FORM);
|
||||||
|
const [formError, setFormError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// Fetch role for editing
|
||||||
|
const { isLoading: isLoadingRole } = useQuery({
|
||||||
|
queryKey: ['admin-role', id],
|
||||||
|
queryFn: () => rbacApi.getRoles(),
|
||||||
|
enabled: isEdit,
|
||||||
|
select: useCallback(
|
||||||
|
(roles: import('@/api/rbac').AdminRole[]) => {
|
||||||
|
const role = roles.find((r) => r.id === Number(id));
|
||||||
|
if (role) {
|
||||||
|
setFormData({
|
||||||
|
name: role.name,
|
||||||
|
description: role.description || '',
|
||||||
|
level: role.level,
|
||||||
|
color: role.color || ROLE_COLORS[0],
|
||||||
|
permissions: [...role.permissions],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return role;
|
||||||
|
},
|
||||||
|
[id],
|
||||||
|
),
|
||||||
|
});
|
||||||
|
|
||||||
|
const { data: permissionRegistry } = useQuery({
|
||||||
|
queryKey: ['admin-permission-registry'],
|
||||||
|
queryFn: rbacApi.getPermissionRegistry,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Mutations
|
||||||
|
const createMutation = useMutation({
|
||||||
|
mutationFn: (payload: CreateRolePayload) => rbacApi.createRole(payload),
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['admin-roles'] });
|
||||||
|
navigate('/admin/roles');
|
||||||
|
},
|
||||||
|
onError: () => {
|
||||||
|
setFormError(t('admin.roles.errors.createFailed'));
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const updateMutation = useMutation({
|
||||||
|
mutationFn: ({ roleId, payload }: { roleId: number; payload: UpdateRolePayload }) =>
|
||||||
|
rbacApi.updateRole(roleId, payload),
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['admin-roles'] });
|
||||||
|
navigate('/admin/roles');
|
||||||
|
},
|
||||||
|
onError: () => {
|
||||||
|
setFormError(t('admin.roles.errors.updateFailed'));
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Handlers
|
||||||
|
const handleTogglePermission = useCallback((perm: string) => {
|
||||||
|
setFormData((prev) => {
|
||||||
|
const has = prev.permissions.includes(perm);
|
||||||
|
return {
|
||||||
|
...prev,
|
||||||
|
permissions: has ? prev.permissions.filter((p) => p !== perm) : [...prev.permissions, perm],
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleToggleSection = useCallback((section: string, actions: string[]) => {
|
||||||
|
setFormData((prev) => {
|
||||||
|
const allPerms = actions.map((a) => `${section}:${a}`);
|
||||||
|
const allSelected = allPerms.every(
|
||||||
|
(p) => prev.permissions.includes(p) || prev.permissions.includes(`${section}:*`),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (allSelected) {
|
||||||
|
const sectionPerms = new Set([...allPerms, `${section}:*`]);
|
||||||
|
return {
|
||||||
|
...prev,
|
||||||
|
permissions: prev.permissions.filter((p) => !sectionPerms.has(p)),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const withoutSection = prev.permissions.filter((p) => !p.startsWith(`${section}:`));
|
||||||
|
return {
|
||||||
|
...prev,
|
||||||
|
permissions: [...withoutSection, `${section}:*`],
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleApplyPreset = useCallback((presetKey: string) => {
|
||||||
|
const presetPerms = PRESETS[presetKey];
|
||||||
|
if (!presetPerms) return;
|
||||||
|
setFormData((prev) => ({
|
||||||
|
...prev,
|
||||||
|
permissions: [...presetPerms],
|
||||||
|
}));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleSubmit = useCallback(
|
||||||
|
(e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setFormError(null);
|
||||||
|
|
||||||
|
if (!formData.name.trim()) {
|
||||||
|
setFormError(t('admin.roles.errors.nameRequired'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
name: formData.name.trim(),
|
||||||
|
description: formData.description.trim() || null,
|
||||||
|
level: formData.level,
|
||||||
|
permissions: formData.permissions,
|
||||||
|
color: formData.color,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (isEdit) {
|
||||||
|
updateMutation.mutate({ roleId: Number(id), payload });
|
||||||
|
} else {
|
||||||
|
createMutation.mutate(payload);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[formData, isEdit, id, createMutation, updateMutation, t],
|
||||||
|
);
|
||||||
|
|
||||||
|
const isSaving = createMutation.isPending || updateMutation.isPending;
|
||||||
|
|
||||||
|
// Loading state
|
||||||
|
if (isEdit && isLoadingRole) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center justify-center py-12">
|
||||||
|
<div className="h-8 w-8 animate-spin rounded-full border-2 border-accent-500 border-t-transparent" />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="animate-fade-in space-y-6">
|
||||||
|
{/* Header */}
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<AdminBackButton to="/admin/roles" />
|
||||||
|
<div>
|
||||||
|
<h1 className="text-xl font-semibold text-dark-100">
|
||||||
|
{isEdit ? t('admin.roles.modal.editTitle') : t('admin.roles.modal.createTitle')}
|
||||||
|
</h1>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Form */}
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-6">
|
||||||
|
<div className="rounded-xl border border-dark-700 bg-dark-800 p-4 sm:p-6">
|
||||||
|
<div className="space-y-4">
|
||||||
|
{/* Name */}
|
||||||
|
<div>
|
||||||
|
<label htmlFor="role-name" className="mb-1 block text-sm font-medium text-dark-200">
|
||||||
|
{t('admin.roles.form.name')}
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="role-name"
|
||||||
|
type="text"
|
||||||
|
value={formData.name}
|
||||||
|
onChange={(e) => setFormData((prev) => ({ ...prev, name: e.target.value }))}
|
||||||
|
className="w-full rounded-lg border border-dark-600 bg-dark-900 px-3 py-2 text-dark-100 placeholder-dark-500 outline-none transition-colors focus:border-accent-500"
|
||||||
|
placeholder={t('admin.roles.form.namePlaceholder')}
|
||||||
|
autoFocus
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Description */}
|
||||||
|
<div>
|
||||||
|
<label
|
||||||
|
htmlFor="role-description"
|
||||||
|
className="mb-1 block text-sm font-medium text-dark-200"
|
||||||
|
>
|
||||||
|
{t('admin.roles.form.description')}
|
||||||
|
</label>
|
||||||
|
<textarea
|
||||||
|
id="role-description"
|
||||||
|
value={formData.description}
|
||||||
|
onChange={(e) => setFormData((prev) => ({ ...prev, description: e.target.value }))}
|
||||||
|
className="w-full rounded-lg border border-dark-600 bg-dark-900 px-3 py-2 text-dark-100 placeholder-dark-500 outline-none transition-colors focus:border-accent-500"
|
||||||
|
placeholder={t('admin.roles.form.descriptionPlaceholder')}
|
||||||
|
rows={2}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Level */}
|
||||||
|
<div>
|
||||||
|
<label htmlFor="role-level" className="mb-1 block text-sm font-medium text-dark-200">
|
||||||
|
{t('admin.roles.form.level')}
|
||||||
|
</label>
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<input
|
||||||
|
id="role-level"
|
||||||
|
type="range"
|
||||||
|
min={0}
|
||||||
|
max={999}
|
||||||
|
value={formData.level}
|
||||||
|
onChange={(e) =>
|
||||||
|
setFormData((prev) => ({ ...prev, level: Number(e.target.value) }))
|
||||||
|
}
|
||||||
|
className="flex-1 accent-accent-500"
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
min={0}
|
||||||
|
max={999}
|
||||||
|
value={formData.level}
|
||||||
|
onChange={(e) =>
|
||||||
|
setFormData((prev) => ({
|
||||||
|
...prev,
|
||||||
|
level: Math.min(999, Math.max(0, Number(e.target.value) || 0)),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
className="w-20 rounded-lg border border-dark-600 bg-dark-900 px-2 py-1.5 text-center text-sm text-dark-100 outline-none focus:border-accent-500"
|
||||||
|
aria-label={t('admin.roles.form.levelValue')}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<p className="mt-1 text-xs text-dark-500">{t('admin.roles.form.levelHint')}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Color picker */}
|
||||||
|
<div>
|
||||||
|
<label className="mb-1 block text-sm font-medium text-dark-200">
|
||||||
|
{t('admin.roles.form.color')}
|
||||||
|
</label>
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{ROLE_COLORS.map((color) => (
|
||||||
|
<button
|
||||||
|
key={color}
|
||||||
|
type="button"
|
||||||
|
onClick={() => setFormData((prev) => ({ ...prev, color }))}
|
||||||
|
className={`h-7 w-7 rounded-full border-2 transition-transform hover:scale-110 ${
|
||||||
|
formData.color === color ? 'scale-110 border-white' : 'border-transparent'
|
||||||
|
}`}
|
||||||
|
style={{ backgroundColor: color }}
|
||||||
|
aria-label={color}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Preset buttons */}
|
||||||
|
<div>
|
||||||
|
<label className="mb-1 block text-sm font-medium text-dark-200">
|
||||||
|
{t('admin.roles.form.presets')}
|
||||||
|
</label>
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{Object.keys(PRESETS).map((key) => (
|
||||||
|
<button
|
||||||
|
key={key}
|
||||||
|
type="button"
|
||||||
|
onClick={() => handleApplyPreset(key)}
|
||||||
|
className="rounded-lg border border-dark-600 bg-dark-700 px-3 py-1.5 text-xs font-medium text-dark-300 transition-colors hover:border-accent-500/50 hover:bg-accent-500/10 hover:text-accent-400"
|
||||||
|
>
|
||||||
|
{t(`admin.roles.presets.${key}`)}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Permission Matrix */}
|
||||||
|
{permissionRegistry && permissionRegistry.length > 0 && (
|
||||||
|
<div className="rounded-xl border border-dark-700 bg-dark-800 p-4 sm:p-6">
|
||||||
|
<PermissionMatrix
|
||||||
|
registry={permissionRegistry}
|
||||||
|
selectedPermissions={formData.permissions}
|
||||||
|
onToggle={handleTogglePermission}
|
||||||
|
onToggleSection={handleToggleSection}
|
||||||
|
/>
|
||||||
|
<p className="mt-2 text-xs text-dark-500">
|
||||||
|
{t('admin.roles.form.selectedPermissions', { count: formData.permissions.length })}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Error & Submit */}
|
||||||
|
<div className="rounded-xl border border-dark-700 bg-dark-800 p-4 sm:p-6">
|
||||||
|
{formError && <p className="mb-4 text-sm text-error-400">{formError}</p>}
|
||||||
|
<div className="flex justify-end gap-3">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => navigate('/admin/roles')}
|
||||||
|
className="px-4 py-2 text-dark-300 transition-colors hover:text-dark-100"
|
||||||
|
>
|
||||||
|
{t('admin.roles.form.cancel')}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={isSaving}
|
||||||
|
className="rounded-lg bg-accent-500 px-4 py-2 text-white transition-colors hover:bg-accent-600 disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{isSaving ? t('admin.roles.form.saving') : t('admin.roles.form.save')}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,14 +1,8 @@
|
|||||||
import { useState, useCallback, useMemo } from 'react';
|
import { useState, useMemo } from 'react';
|
||||||
import { useNavigate } from 'react-router';
|
import { useNavigate } from 'react-router';
|
||||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import {
|
import { rbacApi } from '@/api/rbac';
|
||||||
rbacApi,
|
|
||||||
AdminRole,
|
|
||||||
PermissionSection,
|
|
||||||
CreateRolePayload,
|
|
||||||
UpdateRolePayload,
|
|
||||||
} from '@/api/rbac';
|
|
||||||
import { PermissionGate } from '@/components/auth/PermissionGate';
|
import { PermissionGate } from '@/components/auth/PermissionGate';
|
||||||
import { usePermissionStore } from '@/store/permissions';
|
import { usePermissionStore } from '@/store/permissions';
|
||||||
import { usePlatform } from '@/platform/hooks/usePlatform';
|
import { usePlatform } from '@/platform/hooks/usePlatform';
|
||||||
@@ -53,24 +47,6 @@ const TrashIcon = () => (
|
|||||||
</svg>
|
</svg>
|
||||||
);
|
);
|
||||||
|
|
||||||
const ChevronDownIcon = ({ className }: { className?: string }) => (
|
|
||||||
<svg
|
|
||||||
className={className || 'h-4 w-4'}
|
|
||||||
fill="none"
|
|
||||||
viewBox="0 0 24 24"
|
|
||||||
stroke="currentColor"
|
|
||||||
strokeWidth={2}
|
|
||||||
>
|
|
||||||
<path strokeLinecap="round" strokeLinejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5" />
|
|
||||||
</svg>
|
|
||||||
);
|
|
||||||
|
|
||||||
const XMarkIcon = () => (
|
|
||||||
<svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
|
|
||||||
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
|
|
||||||
</svg>
|
|
||||||
);
|
|
||||||
|
|
||||||
const ShieldIcon = () => (
|
const ShieldIcon = () => (
|
||||||
<svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
|
<svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
|
||||||
<path
|
<path
|
||||||
@@ -81,214 +57,6 @@ const ShieldIcon = () => (
|
|||||||
</svg>
|
</svg>
|
||||||
);
|
);
|
||||||
|
|
||||||
// === Constants ===
|
|
||||||
|
|
||||||
const ROLE_COLORS = [
|
|
||||||
'#6366f1', // indigo
|
|
||||||
'#8b5cf6', // violet
|
|
||||||
'#a855f7', // purple
|
|
||||||
'#ec4899', // pink
|
|
||||||
'#ef4444', // red
|
|
||||||
'#f97316', // orange
|
|
||||||
'#eab308', // yellow
|
|
||||||
'#22c55e', // green
|
|
||||||
'#14b8a6', // teal
|
|
||||||
'#06b6d4', // cyan
|
|
||||||
'#3b82f6', // blue
|
|
||||||
'#6b7280', // gray
|
|
||||||
];
|
|
||||||
|
|
||||||
const PRESETS: Record<string, string[]> = {
|
|
||||||
moderator: ['users:read', 'users:edit', 'users:block', 'tickets:*', 'ban_system:*'],
|
|
||||||
marketer: [
|
|
||||||
'campaigns:*',
|
|
||||||
'broadcasts:*',
|
|
||||||
'promocodes:*',
|
|
||||||
'promo_offers:*',
|
|
||||||
'promo_groups:*',
|
|
||||||
'stats:read',
|
|
||||||
'pinned_messages:*',
|
|
||||||
'wheel:*',
|
|
||||||
],
|
|
||||||
support: ['tickets:read', 'tickets:reply', 'users:read'],
|
|
||||||
};
|
|
||||||
|
|
||||||
// === Types ===
|
|
||||||
|
|
||||||
interface RoleFormData {
|
|
||||||
name: string;
|
|
||||||
description: string;
|
|
||||||
level: number;
|
|
||||||
color: string;
|
|
||||||
permissions: string[];
|
|
||||||
}
|
|
||||||
|
|
||||||
const INITIAL_FORM: RoleFormData = {
|
|
||||||
name: '',
|
|
||||||
description: '',
|
|
||||||
level: 50,
|
|
||||||
color: ROLE_COLORS[0],
|
|
||||||
permissions: [],
|
|
||||||
};
|
|
||||||
|
|
||||||
// === Sub-components ===
|
|
||||||
|
|
||||||
interface PermissionMatrixProps {
|
|
||||||
registry: PermissionSection[];
|
|
||||||
selectedPermissions: string[];
|
|
||||||
onToggle: (perm: string) => void;
|
|
||||||
onToggleSection: (section: string, actions: string[]) => void;
|
|
||||||
}
|
|
||||||
|
|
||||||
function PermissionMatrix({
|
|
||||||
registry,
|
|
||||||
selectedPermissions,
|
|
||||||
onToggle,
|
|
||||||
onToggleSection,
|
|
||||||
}: PermissionMatrixProps) {
|
|
||||||
const { t } = useTranslation();
|
|
||||||
const [expanded, setExpanded] = useState<Record<string, boolean>>({});
|
|
||||||
|
|
||||||
const toggleExpand = useCallback((section: string) => {
|
|
||||||
setExpanded((prev) => ({ ...prev, [section]: !prev[section] }));
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const isSectionFullySelected = useCallback(
|
|
||||||
(section: string, actions: string[]) => {
|
|
||||||
return actions.every((action) => {
|
|
||||||
const perm = `${section}:${action}`;
|
|
||||||
return selectedPermissions.includes(perm) || selectedPermissions.includes(`${section}:*`);
|
|
||||||
});
|
|
||||||
},
|
|
||||||
[selectedPermissions],
|
|
||||||
);
|
|
||||||
|
|
||||||
const isSectionPartiallySelected = useCallback(
|
|
||||||
(section: string, actions: string[]) => {
|
|
||||||
const hasAny = actions.some((action) => {
|
|
||||||
const perm = `${section}:${action}`;
|
|
||||||
return selectedPermissions.includes(perm) || selectedPermissions.includes(`${section}:*`);
|
|
||||||
});
|
|
||||||
return hasAny && !isSectionFullySelected(section, actions);
|
|
||||||
},
|
|
||||||
[selectedPermissions, isSectionFullySelected],
|
|
||||||
);
|
|
||||||
|
|
||||||
const isPermSelected = useCallback(
|
|
||||||
(section: string, action: string) => {
|
|
||||||
const perm = `${section}:${action}`;
|
|
||||||
return selectedPermissions.includes(perm) || selectedPermissions.includes(`${section}:*`);
|
|
||||||
},
|
|
||||||
[selectedPermissions],
|
|
||||||
);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="space-y-2">
|
|
||||||
<label className="text-sm font-medium text-dark-200">
|
|
||||||
{t('admin.roles.form.permissions')}
|
|
||||||
</label>
|
|
||||||
<div className="max-h-80 space-y-1 overflow-y-auto rounded-lg border border-dark-600 bg-dark-900/50 p-2">
|
|
||||||
{registry.map((section) => {
|
|
||||||
const isExpanded = expanded[section.section] ?? false;
|
|
||||||
const allSelected = isSectionFullySelected(section.section, section.actions);
|
|
||||||
const partialSelected = isSectionPartiallySelected(section.section, section.actions);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
key={section.section}
|
|
||||||
className="rounded-lg border border-dark-700/50 bg-dark-800/30"
|
|
||||||
>
|
|
||||||
{/* Section header */}
|
|
||||||
<div className="flex items-center gap-2 px-3 py-2">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => onToggleSection(section.section, section.actions)}
|
|
||||||
className={`flex h-4 w-4 shrink-0 items-center justify-center rounded border transition-colors ${
|
|
||||||
allSelected
|
|
||||||
? 'border-accent-500 bg-accent-500'
|
|
||||||
: partialSelected
|
|
||||||
? 'border-accent-500 bg-accent-500/40'
|
|
||||||
: 'border-dark-500 hover:border-dark-400'
|
|
||||||
}`}
|
|
||||||
aria-label={t('admin.roles.form.toggleSection', {
|
|
||||||
section: section.section,
|
|
||||||
})}
|
|
||||||
>
|
|
||||||
{(allSelected || partialSelected) && (
|
|
||||||
<svg
|
|
||||||
className="h-3 w-3 text-white"
|
|
||||||
fill="none"
|
|
||||||
viewBox="0 0 24 24"
|
|
||||||
stroke="currentColor"
|
|
||||||
strokeWidth={3}
|
|
||||||
>
|
|
||||||
{allSelected ? (
|
|
||||||
<path
|
|
||||||
strokeLinecap="round"
|
|
||||||
strokeLinejoin="round"
|
|
||||||
d="M4.5 12.75l6 6 9-13.5"
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<path strokeLinecap="round" strokeLinejoin="round" d="M5 12h14" />
|
|
||||||
)}
|
|
||||||
</svg>
|
|
||||||
)}
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => toggleExpand(section.section)}
|
|
||||||
className="flex flex-1 items-center justify-between"
|
|
||||||
>
|
|
||||||
<span className="text-sm font-medium text-dark-200">{section.section}</span>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<span className="text-xs text-dark-500">
|
|
||||||
{section.actions.filter((a) => isPermSelected(section.section, a)).length}/
|
|
||||||
{section.actions.length}
|
|
||||||
</span>
|
|
||||||
<ChevronDownIcon
|
|
||||||
className={`h-4 w-4 text-dark-400 transition-transform ${
|
|
||||||
isExpanded ? 'rotate-180' : ''
|
|
||||||
}`}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Actions list */}
|
|
||||||
{isExpanded && (
|
|
||||||
<div className="border-t border-dark-700/50 px-3 py-2">
|
|
||||||
<div className="flex flex-wrap gap-2">
|
|
||||||
{section.actions.map((action) => {
|
|
||||||
const perm = `${section.section}:${action}`;
|
|
||||||
const selected = isPermSelected(section.section, action);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<button
|
|
||||||
key={perm}
|
|
||||||
type="button"
|
|
||||||
onClick={() => onToggle(perm)}
|
|
||||||
className={`rounded-md px-2.5 py-1 text-xs font-medium transition-colors ${
|
|
||||||
selected
|
|
||||||
? 'bg-accent-500/20 text-accent-400'
|
|
||||||
: 'bg-dark-700/50 text-dark-400 hover:bg-dark-700 hover:text-dark-300'
|
|
||||||
}`}
|
|
||||||
aria-pressed={selected}
|
|
||||||
>
|
|
||||||
{action}
|
|
||||||
</button>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// === Main Page ===
|
// === Main Page ===
|
||||||
|
|
||||||
export default function AdminRoles() {
|
export default function AdminRoles() {
|
||||||
@@ -298,10 +66,6 @@ export default function AdminRoles() {
|
|||||||
const { capabilities } = usePlatform();
|
const { capabilities } = usePlatform();
|
||||||
const canManageRole = usePermissionStore((s) => s.canManageRole);
|
const canManageRole = usePermissionStore((s) => s.canManageRole);
|
||||||
|
|
||||||
// Modal state
|
|
||||||
const [modalOpen, setModalOpen] = useState(false);
|
|
||||||
const [editingRole, setEditingRole] = useState<AdminRole | null>(null);
|
|
||||||
const [formData, setFormData] = useState<RoleFormData>(INITIAL_FORM);
|
|
||||||
const [deleteConfirm, setDeleteConfirm] = useState<number | null>(null);
|
const [deleteConfirm, setDeleteConfirm] = useState<number | null>(null);
|
||||||
const [formError, setFormError] = useState<string | null>(null);
|
const [formError, setFormError] = useState<string | null>(null);
|
||||||
|
|
||||||
@@ -315,35 +79,7 @@ export default function AdminRoles() {
|
|||||||
queryFn: rbacApi.getRoles,
|
queryFn: rbacApi.getRoles,
|
||||||
});
|
});
|
||||||
|
|
||||||
const { data: permissionRegistry } = useQuery({
|
|
||||||
queryKey: ['admin-permission-registry'],
|
|
||||||
queryFn: rbacApi.getPermissionRegistry,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Mutations
|
// Mutations
|
||||||
const createMutation = useMutation({
|
|
||||||
mutationFn: (payload: CreateRolePayload) => rbacApi.createRole(payload),
|
|
||||||
onSuccess: () => {
|
|
||||||
queryClient.invalidateQueries({ queryKey: ['admin-roles'] });
|
|
||||||
closeModal();
|
|
||||||
},
|
|
||||||
onError: () => {
|
|
||||||
setFormError(t('admin.roles.errors.createFailed'));
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const updateMutation = useMutation({
|
|
||||||
mutationFn: ({ id, payload }: { id: number; payload: UpdateRolePayload }) =>
|
|
||||||
rbacApi.updateRole(id, payload),
|
|
||||||
onSuccess: () => {
|
|
||||||
queryClient.invalidateQueries({ queryKey: ['admin-roles'] });
|
|
||||||
closeModal();
|
|
||||||
},
|
|
||||||
onError: () => {
|
|
||||||
setFormError(t('admin.roles.errors.updateFailed'));
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const deleteMutation = useMutation({
|
const deleteMutation = useMutation({
|
||||||
mutationFn: rbacApi.deleteRole,
|
mutationFn: rbacApi.deleteRole,
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
@@ -356,107 +92,6 @@ export default function AdminRoles() {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// Handlers
|
|
||||||
const closeModal = useCallback(() => {
|
|
||||||
setModalOpen(false);
|
|
||||||
setEditingRole(null);
|
|
||||||
setFormData(INITIAL_FORM);
|
|
||||||
setFormError(null);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const openCreateModal = useCallback(() => {
|
|
||||||
setEditingRole(null);
|
|
||||||
setFormData(INITIAL_FORM);
|
|
||||||
setFormError(null);
|
|
||||||
setModalOpen(true);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const openEditModal = useCallback((role: AdminRole) => {
|
|
||||||
setEditingRole(role);
|
|
||||||
setFormData({
|
|
||||||
name: role.name,
|
|
||||||
description: role.description || '',
|
|
||||||
level: role.level,
|
|
||||||
color: role.color || ROLE_COLORS[0],
|
|
||||||
permissions: [...role.permissions],
|
|
||||||
});
|
|
||||||
setFormError(null);
|
|
||||||
setModalOpen(true);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const handleTogglePermission = useCallback((perm: string) => {
|
|
||||||
setFormData((prev) => {
|
|
||||||
const has = prev.permissions.includes(perm);
|
|
||||||
return {
|
|
||||||
...prev,
|
|
||||||
permissions: has ? prev.permissions.filter((p) => p !== perm) : [...prev.permissions, perm],
|
|
||||||
};
|
|
||||||
});
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const handleToggleSection = useCallback((section: string, actions: string[]) => {
|
|
||||||
setFormData((prev) => {
|
|
||||||
const allPerms = actions.map((a) => `${section}:${a}`);
|
|
||||||
const allSelected = allPerms.every(
|
|
||||||
(p) => prev.permissions.includes(p) || prev.permissions.includes(`${section}:*`),
|
|
||||||
);
|
|
||||||
|
|
||||||
if (allSelected) {
|
|
||||||
// Deselect all in this section (both individual and wildcard)
|
|
||||||
const sectionPerms = new Set([...allPerms, `${section}:*`]);
|
|
||||||
return {
|
|
||||||
...prev,
|
|
||||||
permissions: prev.permissions.filter((p) => !sectionPerms.has(p)),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Select all: use wildcard
|
|
||||||
const withoutSection = prev.permissions.filter((p) => !p.startsWith(`${section}:`));
|
|
||||||
return {
|
|
||||||
...prev,
|
|
||||||
permissions: [...withoutSection, `${section}:*`],
|
|
||||||
};
|
|
||||||
});
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const handleApplyPreset = useCallback((presetKey: string) => {
|
|
||||||
const presetPerms = PRESETS[presetKey];
|
|
||||||
if (!presetPerms) return;
|
|
||||||
setFormData((prev) => ({
|
|
||||||
...prev,
|
|
||||||
permissions: [...presetPerms],
|
|
||||||
}));
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const handleSubmit = useCallback(
|
|
||||||
(e: React.FormEvent) => {
|
|
||||||
e.preventDefault();
|
|
||||||
setFormError(null);
|
|
||||||
|
|
||||||
if (!formData.name.trim()) {
|
|
||||||
setFormError(t('admin.roles.errors.nameRequired'));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const payload = {
|
|
||||||
name: formData.name.trim(),
|
|
||||||
description: formData.description.trim() || null,
|
|
||||||
level: formData.level,
|
|
||||||
permissions: formData.permissions,
|
|
||||||
color: formData.color,
|
|
||||||
};
|
|
||||||
|
|
||||||
if (editingRole) {
|
|
||||||
updateMutation.mutate({ id: editingRole.id, payload });
|
|
||||||
} else {
|
|
||||||
createMutation.mutate(payload);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
[formData, editingRole, createMutation, updateMutation, t],
|
|
||||||
);
|
|
||||||
|
|
||||||
const isSaving = createMutation.isPending || updateMutation.isPending;
|
|
||||||
|
|
||||||
// Sorted roles by level descending
|
// Sorted roles by level descending
|
||||||
const sortedRoles = useMemo(() => {
|
const sortedRoles = useMemo(() => {
|
||||||
if (!roles) return [];
|
if (!roles) return [];
|
||||||
@@ -483,7 +118,7 @@ export default function AdminRoles() {
|
|||||||
</div>
|
</div>
|
||||||
<PermissionGate permission="roles:create">
|
<PermissionGate permission="roles:create">
|
||||||
<button
|
<button
|
||||||
onClick={openCreateModal}
|
onClick={() => navigate('/admin/roles/create')}
|
||||||
className="flex items-center justify-center gap-2 rounded-lg bg-accent-500 px-4 py-2 text-white transition-colors hover:bg-accent-600"
|
className="flex items-center justify-center gap-2 rounded-lg bg-accent-500 px-4 py-2 text-white transition-colors hover:bg-accent-600"
|
||||||
>
|
>
|
||||||
<PlusIcon />
|
<PlusIcon />
|
||||||
@@ -492,6 +127,13 @@ export default function AdminRoles() {
|
|||||||
</PermissionGate>
|
</PermissionGate>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Error message */}
|
||||||
|
{formError && (
|
||||||
|
<div className="mb-4 rounded-lg border border-error-500/30 bg-error-500/10 p-3">
|
||||||
|
<p className="text-sm text-error-400">{formError}</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Stats Overview */}
|
{/* Stats Overview */}
|
||||||
{sortedRoles.length > 0 && (
|
{sortedRoles.length > 0 && (
|
||||||
<div className="mb-6 grid grid-cols-2 gap-3 sm:grid-cols-3">
|
<div className="mb-6 grid grid-cols-2 gap-3 sm:grid-cols-3">
|
||||||
@@ -577,7 +219,7 @@ export default function AdminRoles() {
|
|||||||
<div className="flex items-center gap-2 border-t border-dark-700 pt-3 sm:border-0 sm:pt-0">
|
<div className="flex items-center gap-2 border-t border-dark-700 pt-3 sm:border-0 sm:pt-0">
|
||||||
<PermissionGate permission="roles:edit">
|
<PermissionGate permission="roles:edit">
|
||||||
<button
|
<button
|
||||||
onClick={() => openEditModal(role)}
|
onClick={() => navigate(`/admin/roles/${role.id}/edit`)}
|
||||||
disabled={role.is_system || !canManageRole(role.level)}
|
disabled={role.is_system || !canManageRole(role.level)}
|
||||||
className="flex-1 rounded-lg bg-dark-700 p-2 text-dark-300 transition-colors hover:bg-dark-600 hover:text-dark-100 disabled:cursor-not-allowed disabled:opacity-40 sm:flex-none"
|
className="flex-1 rounded-lg bg-dark-700 p-2 text-dark-300 transition-colors hover:bg-dark-600 hover:text-dark-100 disabled:cursor-not-allowed disabled:opacity-40 sm:flex-none"
|
||||||
title={t('admin.roles.actions.edit')}
|
title={t('admin.roles.actions.edit')}
|
||||||
@@ -602,189 +244,6 @@ export default function AdminRoles() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Create / Edit Modal */}
|
|
||||||
{modalOpen && (
|
|
||||||
<div className="fixed inset-0 z-50 flex items-start justify-center overflow-y-auto p-4 pt-[5vh]">
|
|
||||||
{/* Backdrop */}
|
|
||||||
<div className="fixed inset-0 bg-black/60" onClick={closeModal} aria-hidden="true" />
|
|
||||||
{/* Modal content */}
|
|
||||||
<div className="relative w-full max-w-lg rounded-xl border border-dark-700 bg-dark-800 p-6 shadow-xl">
|
|
||||||
{/* Modal header */}
|
|
||||||
<div className="mb-5 flex items-center justify-between">
|
|
||||||
<h2 className="text-lg font-semibold text-dark-100">
|
|
||||||
{editingRole
|
|
||||||
? t('admin.roles.modal.editTitle')
|
|
||||||
: t('admin.roles.modal.createTitle')}
|
|
||||||
</h2>
|
|
||||||
<button
|
|
||||||
onClick={closeModal}
|
|
||||||
className="rounded-lg p-1 text-dark-400 transition-colors hover:bg-dark-700 hover:text-dark-200"
|
|
||||||
aria-label={t('admin.roles.modal.close')}
|
|
||||||
>
|
|
||||||
<XMarkIcon />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<form onSubmit={handleSubmit} className="space-y-4">
|
|
||||||
{/* Name */}
|
|
||||||
<div>
|
|
||||||
<label htmlFor="role-name" className="mb-1 block text-sm font-medium text-dark-200">
|
|
||||||
{t('admin.roles.form.name')}
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
id="role-name"
|
|
||||||
type="text"
|
|
||||||
value={formData.name}
|
|
||||||
onChange={(e) => setFormData((prev) => ({ ...prev, name: e.target.value }))}
|
|
||||||
className="w-full rounded-lg border border-dark-600 bg-dark-900 px-3 py-2 text-dark-100 placeholder-dark-500 outline-none transition-colors focus:border-accent-500"
|
|
||||||
placeholder={t('admin.roles.form.namePlaceholder')}
|
|
||||||
autoFocus
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Description */}
|
|
||||||
<div>
|
|
||||||
<label
|
|
||||||
htmlFor="role-description"
|
|
||||||
className="mb-1 block text-sm font-medium text-dark-200"
|
|
||||||
>
|
|
||||||
{t('admin.roles.form.description')}
|
|
||||||
</label>
|
|
||||||
<textarea
|
|
||||||
id="role-description"
|
|
||||||
value={formData.description}
|
|
||||||
onChange={(e) =>
|
|
||||||
setFormData((prev) => ({ ...prev, description: e.target.value }))
|
|
||||||
}
|
|
||||||
className="w-full rounded-lg border border-dark-600 bg-dark-900 px-3 py-2 text-dark-100 placeholder-dark-500 outline-none transition-colors focus:border-accent-500"
|
|
||||||
placeholder={t('admin.roles.form.descriptionPlaceholder')}
|
|
||||||
rows={2}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Level */}
|
|
||||||
<div>
|
|
||||||
<label
|
|
||||||
htmlFor="role-level"
|
|
||||||
className="mb-1 block text-sm font-medium text-dark-200"
|
|
||||||
>
|
|
||||||
{t('admin.roles.form.level')}
|
|
||||||
</label>
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<input
|
|
||||||
id="role-level"
|
|
||||||
type="range"
|
|
||||||
min={0}
|
|
||||||
max={999}
|
|
||||||
value={formData.level}
|
|
||||||
onChange={(e) =>
|
|
||||||
setFormData((prev) => ({
|
|
||||||
...prev,
|
|
||||||
level: Number(e.target.value),
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
className="flex-1 accent-accent-500"
|
|
||||||
/>
|
|
||||||
<input
|
|
||||||
type="number"
|
|
||||||
min={0}
|
|
||||||
max={999}
|
|
||||||
value={formData.level}
|
|
||||||
onChange={(e) =>
|
|
||||||
setFormData((prev) => ({
|
|
||||||
...prev,
|
|
||||||
level: Math.min(999, Math.max(0, Number(e.target.value) || 0)),
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
className="w-20 rounded-lg border border-dark-600 bg-dark-900 px-2 py-1.5 text-center text-sm text-dark-100 outline-none focus:border-accent-500"
|
|
||||||
aria-label={t('admin.roles.form.levelValue')}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<p className="mt-1 text-xs text-dark-500">{t('admin.roles.form.levelHint')}</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Color picker */}
|
|
||||||
<div>
|
|
||||||
<label className="mb-1 block text-sm font-medium text-dark-200">
|
|
||||||
{t('admin.roles.form.color')}
|
|
||||||
</label>
|
|
||||||
<div className="flex flex-wrap gap-2">
|
|
||||||
{ROLE_COLORS.map((color) => (
|
|
||||||
<button
|
|
||||||
key={color}
|
|
||||||
type="button"
|
|
||||||
onClick={() => setFormData((prev) => ({ ...prev, color }))}
|
|
||||||
className={`h-7 w-7 rounded-full border-2 transition-transform hover:scale-110 ${
|
|
||||||
formData.color === color ? 'scale-110 border-white' : 'border-transparent'
|
|
||||||
}`}
|
|
||||||
style={{ backgroundColor: color }}
|
|
||||||
aria-label={color}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Preset buttons */}
|
|
||||||
<div>
|
|
||||||
<label className="mb-1 block text-sm font-medium text-dark-200">
|
|
||||||
{t('admin.roles.form.presets')}
|
|
||||||
</label>
|
|
||||||
<div className="flex flex-wrap gap-2">
|
|
||||||
{Object.keys(PRESETS).map((key) => (
|
|
||||||
<button
|
|
||||||
key={key}
|
|
||||||
type="button"
|
|
||||||
onClick={() => handleApplyPreset(key)}
|
|
||||||
className="rounded-lg border border-dark-600 bg-dark-700 px-3 py-1.5 text-xs font-medium text-dark-300 transition-colors hover:border-accent-500/50 hover:bg-accent-500/10 hover:text-accent-400"
|
|
||||||
>
|
|
||||||
{t(`admin.roles.presets.${key}`)}
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Permission Matrix */}
|
|
||||||
{permissionRegistry && permissionRegistry.length > 0 && (
|
|
||||||
<PermissionMatrix
|
|
||||||
registry={permissionRegistry}
|
|
||||||
selectedPermissions={formData.permissions}
|
|
||||||
onToggle={handleTogglePermission}
|
|
||||||
onToggleSection={handleToggleSection}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Selected count */}
|
|
||||||
<p className="text-xs text-dark-500">
|
|
||||||
{t('admin.roles.form.selectedPermissions', {
|
|
||||||
count: formData.permissions.length,
|
|
||||||
})}
|
|
||||||
</p>
|
|
||||||
|
|
||||||
{/* Error */}
|
|
||||||
{formError && <p className="text-sm text-error-400">{formError}</p>}
|
|
||||||
|
|
||||||
{/* Actions */}
|
|
||||||
<div className="flex justify-end gap-3 pt-2">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={closeModal}
|
|
||||||
className="px-4 py-2 text-dark-300 transition-colors hover:text-dark-100"
|
|
||||||
>
|
|
||||||
{t('admin.roles.form.cancel')}
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="submit"
|
|
||||||
disabled={isSaving}
|
|
||||||
className="rounded-lg bg-accent-500 px-4 py-2 text-white transition-colors hover:bg-accent-600 disabled:opacity-50"
|
|
||||||
>
|
|
||||||
{isSaving ? t('admin.roles.form.saving') : t('admin.roles.form.save')}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Delete Confirmation */}
|
{/* Delete Confirmation */}
|
||||||
{deleteConfirm !== null && (
|
{deleteConfirm !== null && (
|
||||||
<div className="fixed inset-0 z-50 flex items-center justify-center p-4">
|
<div className="fixed inset-0 z-50 flex items-center justify-center p-4">
|
||||||
|
|||||||
Reference in New Issue
Block a user