feat(rbac): F3 前端 RBAC 按钮级控制
后端: - 新增 GET /user/permissions 端点返回当前用户权限码 - Login 响应附带 permissions 数组 - collectUserPermissionCodes 用 raw SQL JOIN 避免 GORM many2many 表名问题 - admin 用户返回 ['*'] 通配符 前端: - usePermission hook (hasPermission/hasAnyPermission/hasAllPermissions) - <HasPermission> 组件 (permission/anyOf/allOf + fallback) - zustand store 新增 permissions 字段 - Sidebar 菜单递归过滤 (42 菜单项全部标注 permission) - ServerManager: 添加/导入/批量删除按钮按权限显隐 - ServerTableRow: 终端/编辑/文件/删除按权限显隐 - SystemUserTab: 新建/导入/编辑/删除按钮按权限显隐 - MainLayout: 页面刷新自动拉取权限 - Login: 登录时存储 permissions 验证: - admin: permissions=['*'] 通配符 - viewer: 7 个只读权限 (dashboard:view/server:view/...) - viewer 无 server:create/delete - 10/10 回归测试通过 - npm run build 零错误
This commit is contained in:
1 parent
77c234b060
commit
be2a377f01
30 files changed
+2328
-462
No files matched your search
@@ -0,0 +1,677 @@
|
||||
// 审批流程配置 — 参考 OpsxSQL WorkflowPage 工作流模式
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import {
|
||||
Plus, Edit2, Trash2, X, ChevronDown, ChevronUp, ArrowUp, ArrowDown,
|
||||
Play, Loader2, Star, CheckCircle, GitBranch, Users, Shield,
|
||||
} from 'lucide-react';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { toast } from 'sonner';
|
||||
import { http } from '@/services/http';
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Types */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
interface WorkflowStep {
|
||||
id?: number;
|
||||
workflow_id?: number;
|
||||
step_number: number;
|
||||
name: string;
|
||||
step_type: string;
|
||||
approver_ids: string | null;
|
||||
is_required: boolean;
|
||||
timeout_hours: number;
|
||||
auto_approve_on_timeout: boolean;
|
||||
}
|
||||
|
||||
interface WorkflowItem {
|
||||
id: number;
|
||||
name: string;
|
||||
description: string | null;
|
||||
category: string;
|
||||
is_default: boolean;
|
||||
is_active: boolean;
|
||||
created_at: string;
|
||||
steps: WorkflowStep[];
|
||||
}
|
||||
|
||||
interface UserItem {
|
||||
id: number;
|
||||
username: string;
|
||||
display_name: string | null;
|
||||
role: string;
|
||||
is_active?: boolean;
|
||||
}
|
||||
|
||||
interface StepDraft {
|
||||
name: string;
|
||||
step_type: 'submit' | 'audit' | 'execute';
|
||||
approver_ids: number[];
|
||||
}
|
||||
|
||||
const CATEGORY_LABELS: Record<string, string> = {
|
||||
resource: '资源申请',
|
||||
app: '应用申请',
|
||||
permission: '权限审批',
|
||||
};
|
||||
|
||||
const STEP_TYPE_LABELS: Record<string, string> = {
|
||||
submit: '提交阶段',
|
||||
audit: '审核阶段',
|
||||
execute: '执行阶段',
|
||||
};
|
||||
|
||||
const STEP_TYPE_COLORS: Record<string, string> = {
|
||||
submit: 'bg-blue-500/15 text-blue-400 border-blue-500/30',
|
||||
audit: 'bg-purple-500/15 text-purple-400 border-purple-500/30',
|
||||
execute: 'bg-green-500/15 text-green-400 border-green-500/30',
|
||||
};
|
||||
|
||||
const STEP_TYPE_ICONS: Record<string, React.ElementType> = {
|
||||
submit: Users,
|
||||
audit: Shield,
|
||||
execute: Play,
|
||||
};
|
||||
|
||||
const STEP_TYPES = [
|
||||
{ value: 'submit' as const, label: '提交阶段', desc: '工单提交人' },
|
||||
{ value: 'audit' as const, label: '审核阶段', desc: '审核人员审批' },
|
||||
{ value: 'execute' as const, label: '执行阶段', desc: '执行人员操作' },
|
||||
];
|
||||
|
||||
// API helpers
|
||||
const workflowApi = {
|
||||
list: (params?: { category?: string }) => http.get('/approval-workflows', params),
|
||||
get: (id: number) => http.get(`/approval-workflows/${id}`),
|
||||
create: (data: any) => http.post('/approval-workflows', data),
|
||||
update: (id: number, data: any) => http.put(`/approval-workflows/${id}`, data),
|
||||
delete: (id: number) => http.delete(`/approval-workflows/${id}`),
|
||||
setDefault: (id: number) => http.put(`/approval-workflows/${id}/default`),
|
||||
};
|
||||
const userListApi = () => http.get('/admin/users');
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* UserSelectInline */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
function UserSelectInline({
|
||||
users, selectedIds, label, onToggle, onToggleAll, onClear, getUserName,
|
||||
}: {
|
||||
users: UserItem[];
|
||||
selectedIds: number[];
|
||||
label: string;
|
||||
onToggle: (uid: number) => void;
|
||||
onToggleAll: () => void;
|
||||
onClear: () => void;
|
||||
getUserName: (uid: number) => string;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const triggerRef = useRef<HTMLButtonElement>(null);
|
||||
const [pos, setPos] = useState({ top: 0, left: 0, width: 0 });
|
||||
|
||||
const updatePos = () => {
|
||||
if (triggerRef.current) {
|
||||
const rect = triggerRef.current.getBoundingClientRect();
|
||||
setPos({ top: rect.bottom + 4, left: rect.left, width: rect.width });
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
<button
|
||||
ref={triggerRef}
|
||||
type="button"
|
||||
onClick={() => { if (!open) updatePos(); setOpen(!open); }}
|
||||
className={`w-full flex items-center justify-between px-3 py-2 rounded-lg text-sm transition-colors ${
|
||||
selectedIds.length === 0
|
||||
? 'bg-[var(--dg-bg-tertiary)] border border-red-500/40 text-[var(--dg-text-muted)]'
|
||||
: 'bg-[var(--dg-bg-tertiary)] border border-[var(--dg-border)] text-[var(--dg-text-primary)]'
|
||||
}`}
|
||||
>
|
||||
<span className="truncate">
|
||||
{selectedIds.length === 0 ? `${label} * 请选择` : `${label} (${selectedIds.length}人)`}
|
||||
</span>
|
||||
<ChevronDown className={`w-4 h-4 text-[var(--dg-text-muted)] transition-transform ${open ? 'rotate-180' : ''}`} />
|
||||
</button>
|
||||
|
||||
{selectedIds.length > 1 && (
|
||||
<div className="flex flex-wrap gap-1 mt-1.5">
|
||||
{selectedIds.map((uid) => (
|
||||
<span key={uid} className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[11px] bg-blue-500/15 text-blue-400">
|
||||
{getUserName(uid)}
|
||||
<button onClick={() => onToggle(uid)} className="hover:text-red-400"><X className="w-3 h-3" /></button>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{open && (
|
||||
<>
|
||||
<div className="fixed inset-0 z-40" onClick={() => setOpen(false)} />
|
||||
<div className="fixed z-50 bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)] rounded-lg shadow-xl max-h-52 overflow-y-auto"
|
||||
style={{ top: pos.top, left: pos.left, width: pos.width }}>
|
||||
<div className="flex items-center justify-between px-3 py-2 border-b border-[var(--dg-border)]">
|
||||
<button onClick={onToggleAll} className="text-[11px] text-blue-400 hover:text-blue-300">
|
||||
{selectedIds.length === users.length && users.length > 0 ? '取消全选' : '全选'}
|
||||
</button>
|
||||
{selectedIds.length > 0 && (
|
||||
<button onClick={onClear} className="text-[11px] text-red-400 hover:text-red-300">清空</button>
|
||||
)}
|
||||
</div>
|
||||
{users.map((u) => {
|
||||
const checked = selectedIds.includes(u.id);
|
||||
return (
|
||||
<div key={u.id} onClick={() => onToggle(u.id)}
|
||||
className="flex items-center gap-2.5 px-3 py-2 cursor-pointer hover:bg-[var(--dg-bg-hover)] transition-colors">
|
||||
<div className={`w-4 h-4 rounded border flex items-center justify-center flex-shrink-0 ${
|
||||
checked ? 'bg-blue-500 border-blue-500' : 'border-[var(--dg-border)]'
|
||||
}`}>
|
||||
{checked && <CheckCircle className="w-3 h-3 text-white" />}
|
||||
</div>
|
||||
<span className={`text-sm flex-1 ${checked ? 'text-[var(--dg-text-primary)]' : 'text-[var(--dg-text-secondary)]'}`}>
|
||||
{u.display_name || u.username}
|
||||
</span>
|
||||
<span className="text-[10px] text-[var(--dg-text-muted)] px-1.5 py-0.5 rounded bg-[var(--dg-bg-tertiary)]">
|
||||
{u.role}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* WorkflowEditorModal */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
interface EditorProps {
|
||||
workflow?: WorkflowItem | null;
|
||||
users: UserItem[];
|
||||
onClose: () => void;
|
||||
onSaved: () => void;
|
||||
}
|
||||
|
||||
function WorkflowEditorModal({ workflow, users, onClose, onSaved }: EditorProps) {
|
||||
const isEdit = !!workflow;
|
||||
const [name, setName] = useState(workflow?.name || '');
|
||||
const [description, setDescription] = useState(workflow?.description || '');
|
||||
const [category, setCategory] = useState(workflow?.category || 'resource');
|
||||
const [steps, setSteps] = useState<StepDraft[]>([]);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
if (workflow?.steps?.length) {
|
||||
setSteps(
|
||||
workflow.steps.map((s) => ({
|
||||
name: s.name,
|
||||
step_type: (s.step_type === 'serial' || s.step_type === 'parallel')
|
||||
? ('audit' as const)
|
||||
: (s.step_type as 'submit' | 'audit' | 'execute'),
|
||||
approver_ids: parseIds(s.approver_ids),
|
||||
}))
|
||||
);
|
||||
} else {
|
||||
setSteps([
|
||||
{ name: '提交申请', step_type: 'submit', approver_ids: [] },
|
||||
{ name: '审核', step_type: 'audit', approver_ids: [] },
|
||||
]);
|
||||
}
|
||||
}, [workflow]);
|
||||
|
||||
const parseIds = (ids: string | null): number[] => {
|
||||
if (!ids) return [];
|
||||
try {
|
||||
const p = JSON.parse(ids);
|
||||
return Array.isArray(p) ? p : [];
|
||||
} catch { return []; }
|
||||
};
|
||||
|
||||
const addStep = (type: 'submit' | 'audit' | 'execute') => {
|
||||
const labels: Record<string, string> = { submit: '提交', audit: '审核', execute: '执行' };
|
||||
const count = steps.filter((s) => s.step_type === type).length;
|
||||
const suffix = count > 0 ? ` ${count + 1}` : '';
|
||||
setSteps([...steps, { name: `${labels[type]}${suffix}`, step_type: type, approver_ids: [] }]);
|
||||
};
|
||||
|
||||
const removeStep = (idx: number) => setSteps(steps.filter((_, i) => i !== idx));
|
||||
const moveStep = (idx: number, dir: -1 | 1) => {
|
||||
const target = idx + dir;
|
||||
if (target < 0 || target >= steps.length) return;
|
||||
const next = [...steps];
|
||||
[next[idx], next[target]] = [next[target], next[idx]];
|
||||
setSteps(next);
|
||||
};
|
||||
const updateStep = (idx: number, patch: Partial<StepDraft>) => {
|
||||
setSteps(steps.map((s, i) => (i === idx ? { ...s, ...patch } : s)));
|
||||
};
|
||||
const toggleUser = (idx: number, uid: number) => {
|
||||
const step = steps[idx];
|
||||
const has = step.approver_ids.includes(uid);
|
||||
updateStep(idx, { approver_ids: has ? step.approver_ids.filter((id) => id !== uid) : [...step.approver_ids, uid] });
|
||||
};
|
||||
|
||||
const getEligibleUsers = (stepType: string) => {
|
||||
const active = users.filter(u => u.is_active !== false);
|
||||
if (stepType === 'audit') return active;
|
||||
if (stepType === 'execute') return active.filter(u =>
|
||||
['super_admin', 'k8s_admin', 'release_admin', 'resource_admin'].includes(u.role)
|
||||
);
|
||||
return active;
|
||||
};
|
||||
|
||||
const toggleAllUsers = (idx: number) => {
|
||||
const step = steps[idx];
|
||||
const eligible = getEligibleUsers(step.step_type);
|
||||
const allSelected = step.approver_ids.length === eligible.length && eligible.length > 0;
|
||||
updateStep(idx, { approver_ids: allSelected ? [] : eligible.map((u) => u.id) });
|
||||
};
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!name.trim()) { setError('请输入流程名称'); return; }
|
||||
if (steps.length === 0) { setError('请至少添加一个步骤'); return; }
|
||||
for (let i = 0; i < steps.length; i++) {
|
||||
if (steps[i].step_type !== 'submit' && steps[i].approver_ids.length === 0) {
|
||||
setError(`步骤"${steps[i].name}"需要关联至少一个审批人`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
setSubmitting(true);
|
||||
setError('');
|
||||
try {
|
||||
const payload = {
|
||||
name: name.trim(),
|
||||
description: description.trim() || null,
|
||||
category,
|
||||
steps: steps.map((s, i) => ({
|
||||
step_number: i + 1,
|
||||
name: s.name,
|
||||
step_type: s.step_type,
|
||||
approver_ids: s.approver_ids.length > 0 ? JSON.stringify(s.approver_ids) : null,
|
||||
is_required: true,
|
||||
timeout_hours: 24,
|
||||
auto_approve_on_timeout: false,
|
||||
})),
|
||||
};
|
||||
if (isEdit && workflow) {
|
||||
await workflowApi.update(workflow.id, payload);
|
||||
} else {
|
||||
await workflowApi.create(payload);
|
||||
}
|
||||
onSaved();
|
||||
} catch (e: unknown) {
|
||||
const msg = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail || '保存失败';
|
||||
setError(msg);
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const getUserName = (uid: number) => {
|
||||
const u = users.find((u) => u.id === uid);
|
||||
return u ? (u.display_name || u.username) : `#${uid}`;
|
||||
};
|
||||
|
||||
const inputCls = 'w-full px-3 py-2 bg-[var(--dg-bg-tertiary)] border border-[var(--dg-border)] rounded-lg text-sm focus:border-blue-400 focus:outline-none transition-colors text-[var(--dg-text-primary)]';
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center">
|
||||
<div className="absolute inset-0 bg-black/50" onClick={onClose} />
|
||||
<div className="relative bg-[var(--dg-bg-secondary)] rounded-xl shadow-2xl w-full max-w-2xl max-h-[90vh] overflow-y-auto m-4">
|
||||
<div className="flex items-center justify-between px-5 py-4 border-b border-[var(--dg-border)]">
|
||||
<h2 className="text-base font-semibold text-[var(--dg-text-primary)]">
|
||||
{isEdit ? '编辑审批流程' : '新建审批流程'}
|
||||
</h2>
|
||||
<button onClick={onClose} className="p-1.5 rounded-lg hover:bg-[var(--dg-bg-hover)] text-[var(--dg-text-secondary)] transition-colors">
|
||||
<X className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="px-5 pb-5 space-y-4 pt-4">
|
||||
{error && <div className="px-3 py-2 text-sm text-red-400 bg-red-500/10 rounded-lg">{error}</div>}
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-[var(--dg-text-secondary)] mb-1">流程名称 *</label>
|
||||
<input className={inputCls} value={name} onChange={(e) => setName(e.target.value)} placeholder="输入流程名称" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-[var(--dg-text-secondary)] mb-1">所属分类</label>
|
||||
<select className={inputCls} value={category} onChange={(e) => setCategory(e.target.value)}>
|
||||
<option value="resource">资源申请</option>
|
||||
<option value="app">应用申请</option>
|
||||
<option value="permission">权限审批</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-[var(--dg-text-secondary)] mb-1">描述</label>
|
||||
<input className={inputCls} value={description} onChange={(e) => setDescription(e.target.value)} placeholder="可选" />
|
||||
</div>
|
||||
|
||||
{/* Steps */}
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<label className="text-xs font-medium text-[var(--dg-text-secondary)]">流程步骤</label>
|
||||
<div className="flex items-center gap-1">
|
||||
{STEP_TYPES.map((t) => (
|
||||
<button key={t.value} onClick={() => addStep(t.value)}
|
||||
className="flex items-center gap-1 px-2 py-1 text-[11px] font-medium bg-blue-500/10 text-blue-400 hover:bg-blue-500/20 rounded transition-colors">
|
||||
<Plus className="w-3 h-3" />{t.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
{steps.map((step, idx) => {
|
||||
const colorCls = STEP_TYPE_COLORS[step.step_type];
|
||||
const Icon = STEP_TYPE_ICONS[step.step_type] || Shield;
|
||||
return (
|
||||
<div key={idx} className="p-3 bg-[var(--dg-bg-primary)] rounded-lg border border-[var(--dg-border)]">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<div className={`w-7 h-7 rounded-md flex items-center justify-center flex-shrink-0 ${colorCls.split(' ')[0]}`}>
|
||||
<Icon className={`w-3.5 h-3.5 ${colorCls.split(' ')[1]}`} />
|
||||
</div>
|
||||
<input
|
||||
className="flex-1 px-2 py-1 bg-[var(--dg-bg-tertiary)] border border-[var(--dg-border)] rounded text-sm focus:border-blue-400 focus:outline-none text-[var(--dg-text-primary)]"
|
||||
value={step.name} onChange={(e) => updateStep(idx, { name: e.target.value })}
|
||||
placeholder="步骤名称"
|
||||
/>
|
||||
<span className={`text-[10px] px-1.5 py-0.5 rounded ${colorCls}`}>
|
||||
{STEP_TYPE_LABELS[step.step_type]}
|
||||
</span>
|
||||
<div className="flex items-center gap-0.5 ml-1">
|
||||
<button onClick={() => moveStep(idx, -1)} disabled={idx === 0}
|
||||
className="p-1 rounded hover:bg-[var(--dg-bg-hover)] text-[var(--dg-text-muted)] disabled:opacity-20 transition-colors">
|
||||
<ArrowUp className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
<button onClick={() => moveStep(idx, 1)} disabled={idx === steps.length - 1}
|
||||
className="p-1 rounded hover:bg-[var(--dg-bg-hover)] text-[var(--dg-text-muted)] disabled:opacity-20 transition-colors">
|
||||
<ArrowDown className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
<button onClick={() => removeStep(idx)}
|
||||
className="p-1 rounded hover:bg-red-500/10 text-[var(--dg-text-muted)] hover:text-red-400 transition-colors">
|
||||
<Trash2 className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{step.step_type !== 'submit' && (
|
||||
<div className="pl-9 mt-2">
|
||||
<UserSelectInline
|
||||
users={getEligibleUsers(step.step_type)}
|
||||
selectedIds={step.approver_ids}
|
||||
label={step.step_type === 'audit' ? '审核人' : '执行人'}
|
||||
onToggle={(uid) => toggleUser(idx, uid)}
|
||||
onToggleAll={() => toggleAllUsers(idx)}
|
||||
onClear={() => updateStep(idx, { approver_ids: [] })}
|
||||
getUserName={getUserName}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
{steps.length === 0 && (
|
||||
<div className="text-center py-4 text-sm text-[var(--dg-text-muted)]">
|
||||
请点击上方按钮添加流程步骤
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-end gap-3 px-5 py-4 border-t border-[var(--dg-border)]">
|
||||
<button onClick={onClose} className="px-4 py-2 text-sm text-[var(--dg-text-secondary)] hover:bg-[var(--dg-bg-hover)] rounded-lg transition-colors">
|
||||
取消
|
||||
</button>
|
||||
<Button onClick={handleSubmit} disabled={submitting}>
|
||||
{submitting && <Loader2 className="w-4 h-4 animate-spin mr-1" />}
|
||||
{isEdit ? '保存' : '创建'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Main Page */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
export default function ApprovalWorkflowPage() {
|
||||
const [items, setItems] = useState<WorkflowItem[]>([]);
|
||||
const [users, setUsers] = useState<UserItem[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [expandedId, setExpandedId] = useState<number | null>(null);
|
||||
const [editorWorkflow, setEditorWorkflow] = useState<WorkflowItem | null | undefined>(undefined);
|
||||
|
||||
const fetchWorkflows = useCallback(async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
const res: any = await workflowApi.list();
|
||||
const data = Array.isArray(res?.list) ? res.list : (Array.isArray(res) ? res : []);
|
||||
const normalized = data.map((w: any) => ({ ...w, steps: w.steps || [] }));
|
||||
setItems(normalized);
|
||||
} catch {
|
||||
setError('获取审批流程失败');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const fetchUsers = useCallback(async () => {
|
||||
try {
|
||||
const res: any = await userListApi();
|
||||
const data = Array.isArray(res?.list) ? res.list : (Array.isArray(res) ? res : []);
|
||||
// Normalize: extract role code from roles array
|
||||
const normalized = data.map((u: any) => ({
|
||||
...u,
|
||||
role: u.role || (Array.isArray(u.roles) && u.roles.length > 0 ? u.roles[0].code : ''),
|
||||
}));
|
||||
setUsers(normalized);
|
||||
} catch { /* ignore */ }
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
fetchWorkflows();
|
||||
fetchUsers();
|
||||
}, [fetchWorkflows, fetchUsers]);
|
||||
|
||||
const toggleActive = useCallback(async (wf: WorkflowItem) => {
|
||||
try {
|
||||
await workflowApi.update(wf.id, { is_active: !wf.is_active });
|
||||
setItems((prev) => prev.map((w) => (w.id === wf.id ? { ...w, is_active: !w.is_active } : w)));
|
||||
toast.success(wf.is_active ? '已停用' : '已启用');
|
||||
} catch { toast.error('操作失败'); }
|
||||
}, []);
|
||||
|
||||
const handleDelete = useCallback(async (id: number, name: string) => {
|
||||
if (!window.confirm(`确定删除审批流程「${name}」?删除后不可恢复。`)) return;
|
||||
try {
|
||||
await workflowApi.delete(id);
|
||||
setItems((prev) => prev.filter((w) => w.id !== id));
|
||||
toast.success('已删除');
|
||||
} catch { toast.error('删除失败'); }
|
||||
}, []);
|
||||
|
||||
const setDefault = useCallback(async (id: number) => {
|
||||
try {
|
||||
await workflowApi.setDefault(id);
|
||||
setItems((prev) => prev.map((w) => ({ ...w, is_default: w.id === id })));
|
||||
toast.success('已设为默认');
|
||||
} catch { toast.error('操作失败'); }
|
||||
}, []);
|
||||
|
||||
const getUserName = useCallback(
|
||||
(uid: number) => {
|
||||
const u = users.find((u) => u.id === uid);
|
||||
return u ? (u.display_name || u.username) : `#${uid}`;
|
||||
},
|
||||
[users]
|
||||
);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-64">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-blue-400" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center h-64 text-[var(--dg-text-muted)]">
|
||||
<p className="text-sm">{error}</p>
|
||||
<Button variant="outline" onClick={fetchWorkflows} className="mt-3">重试</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold text-[var(--dg-text-primary)]">审批流程配置</h1>
|
||||
<p className="text-sm text-[var(--dg-text-secondary)] mt-1">
|
||||
为资源申请、应用申请、权限审批配置多级审批流程
|
||||
</p>
|
||||
</div>
|
||||
<Button onClick={() => setEditorWorkflow(null)}>
|
||||
<Plus className="w-4 h-4 mr-1.5" />新建流程
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{items.length === 0 ? (
|
||||
<div className="dg-card p-12 text-center">
|
||||
<GitBranch className="w-12 h-12 mx-auto mb-3 opacity-50 text-[var(--dg-text-muted)]" />
|
||||
<p className="text-sm text-[var(--dg-text-muted)] mb-4">暂无审批流程</p>
|
||||
<Button variant="outline" onClick={() => setEditorWorkflow(null)}>创建第一个流程</Button>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{/* Workflow list */}
|
||||
<div className="space-y-4">
|
||||
{items.map((wf) => {
|
||||
const isExpanded = expandedId === wf.id;
|
||||
return (
|
||||
<Card key={wf.id} className={`dg-card overflow-hidden ${!wf.is_active ? 'opacity-50' : ''}`}>
|
||||
<CardContent className="p-5">
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-3 mb-2 flex-wrap">
|
||||
<h3 className="text-lg font-semibold text-[var(--dg-text-primary)]">{wf.name}</h3>
|
||||
{wf.is_default && <span className="text-[10px] px-1.5 py-0.5 rounded bg-yellow-400/15 text-yellow-400 flex items-center gap-1"><Star className="w-3 h-3" />默认</span>}
|
||||
<span className={`text-[10px] px-1.5 py-0.5 rounded ${wf.is_active ? 'bg-green-500/15 text-green-400' : 'bg-red-500/15 text-red-400'}`}>
|
||||
{wf.is_active ? '启用' : '停用'}
|
||||
</span>
|
||||
<span className="text-[10px] px-1.5 py-0.5 rounded bg-blue-500/15 text-blue-400">
|
||||
{CATEGORY_LABELS[wf.category] || wf.category}
|
||||
</span>
|
||||
</div>
|
||||
{wf.description && <p className="text-sm text-[var(--dg-text-secondary)] mb-1">{wf.description}</p>}
|
||||
<div className="flex items-center gap-1.5 mt-2 flex-wrap">
|
||||
{wf.steps?.map((s, i) => (
|
||||
<span key={i} className="flex items-center gap-1">
|
||||
<span className={`text-[10px] px-1.5 py-0.5 rounded ${STEP_TYPE_COLORS[s.step_type] || 'bg-gray-500/15 text-gray-400 border-gray-500/30'}`}>
|
||||
{STEP_TYPE_LABELS[s.step_type] || s.step_type}
|
||||
</span>
|
||||
{i < (wf.steps?.length || 0) - 1 && (
|
||||
<span className="text-[var(--dg-text-muted)] text-[10px]">→</span>
|
||||
)}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1 flex-shrink-0 ml-4">
|
||||
<button onClick={() => setExpandedId(isExpanded ? null : wf.id)}
|
||||
className="p-1.5 rounded hover:bg-[var(--dg-bg-hover)] text-[var(--dg-text-muted)] transition-colors">
|
||||
{isExpanded ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
|
||||
</button>
|
||||
{!wf.is_default && (
|
||||
<button onClick={() => setDefault(wf.id)}
|
||||
className="p-1.5 rounded hover:bg-yellow-500/10 text-[var(--dg-text-muted)] hover:text-yellow-400 transition-colors" title="设为默认">
|
||||
<Star className="w-4 h-4" />
|
||||
</button>
|
||||
)}
|
||||
<button onClick={() => toggleActive(wf)}
|
||||
className={`p-1.5 rounded transition-colors ${wf.is_active ? 'hover:bg-red-500/10 text-green-400 hover:text-red-400' : 'hover:bg-green-500/10 text-red-400 hover:text-green-400'}`}
|
||||
title={wf.is_active ? '停用' : '启用'}>
|
||||
<Play className={`w-4 h-4 ${!wf.is_active ? 'rotate-180' : ''}`} />
|
||||
</button>
|
||||
<button onClick={() => setEditorWorkflow(wf)}
|
||||
className="p-1.5 rounded hover:bg-[var(--dg-bg-hover)] text-[var(--dg-text-muted)] hover:text-blue-400 transition-colors" title="编辑">
|
||||
<Edit2 className="w-4 h-4" />
|
||||
</button>
|
||||
<button onClick={() => handleDelete(wf.id, wf.name)}
|
||||
className="p-1.5 rounded hover:bg-red-500/10 text-[var(--dg-text-muted)] hover:text-red-400 transition-colors" title="删除">
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isExpanded && (
|
||||
<div className="mt-4 pt-4 border-t border-[var(--dg-border)] space-y-3">
|
||||
{wf.steps?.map((s, i) => {
|
||||
const ids = (() => { try { const p = JSON.parse(s.approver_ids || '[]'); return Array.isArray(p) ? p : []; } catch { return []; } })();
|
||||
return (
|
||||
<div key={i} className="flex items-start gap-3 p-3 bg-[var(--dg-bg-primary)] rounded-lg">
|
||||
<div className="w-6 h-6 rounded-full bg-[var(--dg-bg-tertiary)] flex items-center justify-center text-xs font-medium text-[var(--dg-text-secondary)] flex-shrink-0 mt-0.5">
|
||||
{s.step_number}
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<span className="text-sm font-medium text-[var(--dg-text-primary)]">{s.name}</span>
|
||||
<span className={`text-[10px] px-1.5 py-0.5 rounded ${STEP_TYPE_COLORS[s.step_type] || 'bg-gray-500/15 text-gray-400 border-gray-500/30'}`}>
|
||||
{STEP_TYPE_LABELS[s.step_type] || s.step_type}
|
||||
</span>
|
||||
</div>
|
||||
{ids.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{ids.map((uid) => (
|
||||
<span key={uid} className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[11px] bg-blue-500/15 text-blue-400">
|
||||
{getUserName(uid)}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{ids.length === 0 && s.step_type !== 'submit' && (
|
||||
<span className="text-[11px] text-red-400">未关联审批人</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{editorWorkflow !== undefined && (
|
||||
<WorkflowEditorModal
|
||||
workflow={editorWorkflow}
|
||||
users={users}
|
||||
onClose={() => setEditorWorkflow(undefined)}
|
||||
onSaved={() => { setEditorWorkflow(undefined); fetchWorkflows(); }}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user