迁移文件: - pages/approval/: ApprovalWorkflowPage + ApprovalCategoryPage + 3 子页面(Resource/App/Permission) - components/approval/: ApprovalFlow + ApprovalProcessTab + ApprovalCreateDialog + ApprovalDetailDialog + ApprovalTemplateTab + helpers 翻译键: approval 命名空间 136 键 (8 子组: category/step/status/col/editor/detail/flow/type/msg) 复用 common.* 通用键 (approve/reject/cancel/save/create/delete/edit/detail/close/loading 等) zh-CN/en-US 完全对齐, 8 命名空间 (common/menu/header/login/dashboard/server/alert/approval) 模式: 组件内 useTranslation() + t(); 模块级常量/helpers 用 i18n.t() labelKey 模式: STATUS_TABS/statusMap 从 label:string 改为 labelKey:string + i18n.t(config.labelKey)
698 lines
31 KiB
TypeScript
698 lines
31 KiB
TypeScript
// 审批流程配置 — 参考 OpsxSQL WorkflowPage 工作流模式
|
|
import { useState, useEffect, useCallback, useRef } from 'react';
|
|
import { useTranslation } from 'react-i18next';
|
|
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 { approvalWorkflowApi, userApi } from '@/api';
|
|
import { useConfirm } from '@/components/ui/confirm-dialog';
|
|
|
|
/* ------------------------------------------------------------------ */
|
|
/* 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 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,
|
|
};
|
|
|
|
|
|
|
|
/* ------------------------------------------------------------------ */
|
|
/* 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 { t } = useTranslation();
|
|
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} * ${t('approval.editor.pleaseSelect')}` : `${label} (${t('approval.editor.people', { count: 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 ? t('approval.editor.deselectAll') : t('approval.editor.selectAll')}
|
|
</button>
|
|
{selectedIds.length > 0 && (
|
|
<button onClick={onClear} className="text-[11px] text-red-400 hover:text-red-300">{t('common.clear')}</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 { t } = useTranslation();
|
|
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('');
|
|
|
|
const categoryLabels: Record<string, string> = {
|
|
resource: t('approval.category.resource'),
|
|
app: t('approval.category.app'),
|
|
permission: t('approval.category.permission'),
|
|
};
|
|
|
|
const stepTypeLabels: Record<string, string> = {
|
|
submit: t('approval.step.submit'),
|
|
audit: t('approval.step.audit'),
|
|
execute: t('approval.step.execute'),
|
|
};
|
|
|
|
const stepTypes = [
|
|
{ value: 'submit' as const, label: t('approval.step.submit') },
|
|
{ value: 'audit' as const, label: t('approval.step.audit') },
|
|
{ value: 'execute' as const, label: t('approval.step.execute') },
|
|
];
|
|
|
|
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: t('approval.detail.submitNode'), step_type: 'submit', approver_ids: [] },
|
|
{ name: t('approval.step.auditShort'), step_type: 'audit', approver_ids: [] },
|
|
]);
|
|
}
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [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: t('approval.step.submitShort'),
|
|
audit: t('approval.step.auditShort'),
|
|
execute: t('approval.step.executeShort'),
|
|
};
|
|
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(t('approval.editor.nameRequired')); return; }
|
|
if (steps.length === 0) { setError(t('approval.editor.addStepRequired')); return; }
|
|
for (let i = 0; i < steps.length; i++) {
|
|
if (steps[i].step_type !== 'submit' && steps[i].approver_ids.length === 0) {
|
|
setError(t('approval.editor.stepNeedsApprover', { name: 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 approvalWorkflowApi.update(workflow.id, payload);
|
|
} else {
|
|
await approvalWorkflowApi.create(payload);
|
|
}
|
|
onSaved();
|
|
} catch (e: unknown) {
|
|
const msg = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail || t('approval.editor.saveFailed');
|
|
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 ? t('approval.editor.editTitle') : t('approval.editor.newTitle')}
|
|
</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">{t('approval.editor.workflowName')} *</label>
|
|
<input className={inputCls} value={name} onChange={(e) => setName(e.target.value)} placeholder={t('approval.editor.enterName')} />
|
|
</div>
|
|
<div>
|
|
<label className="block text-xs font-medium text-[var(--dg-text-secondary)] mb-1">{t('approval.editor.workflowCategory')}</label>
|
|
<select className={inputCls} value={category} onChange={(e) => setCategory(e.target.value)}>
|
|
<option value="resource">{t('approval.category.resource')}</option>
|
|
<option value="app">{t('approval.category.app')}</option>
|
|
<option value="permission">{t('approval.category.permission')}</option>
|
|
</select>
|
|
</div>
|
|
</div>
|
|
|
|
<div>
|
|
<label className="block text-xs font-medium text-[var(--dg-text-secondary)] mb-1">{t('approval.editor.workflowDesc')}</label>
|
|
<input className={inputCls} value={description} onChange={(e) => setDescription(e.target.value)} placeholder={t('common.optional')} />
|
|
</div>
|
|
|
|
{/* Steps */}
|
|
<div>
|
|
<div className="flex items-center justify-between mb-2">
|
|
<label className="text-xs font-medium text-[var(--dg-text-secondary)]">{t('approval.editor.workflowSteps')}</label>
|
|
<div className="flex items-center gap-1">
|
|
{stepTypes.map((tp) => (
|
|
<button key={tp.value} onClick={() => addStep(tp.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" />{tp.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={t('approval.step.name')}
|
|
/>
|
|
<span className={`text-[10px] px-1.5 py-0.5 rounded ${colorCls}`}>
|
|
{stepTypeLabels[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' ? t('approval.editor.auditUser') : t('approval.editor.executeUser')}
|
|
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)]">
|
|
{t('approval.step.addHint')}
|
|
</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">
|
|
{t('common.cancel')}
|
|
</button>
|
|
<Button onClick={handleSubmit} disabled={submitting}>
|
|
{submitting && <Loader2 className="w-4 h-4 animate-spin mr-1" />}
|
|
{isEdit ? t('common.save') : t('common.create')}
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
/* ------------------------------------------------------------------ */
|
|
/* Main Page */
|
|
/* ------------------------------------------------------------------ */
|
|
|
|
export default function ApprovalWorkflowPage() {
|
|
const { t } = useTranslation();
|
|
const confirm = useConfirm();
|
|
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 categoryLabels: Record<string, string> = {
|
|
resource: t('approval.category.resource'),
|
|
app: t('approval.category.app'),
|
|
permission: t('approval.category.permission'),
|
|
};
|
|
|
|
const stepTypeLabels: Record<string, string> = {
|
|
submit: t('approval.step.submit'),
|
|
audit: t('approval.step.audit'),
|
|
execute: t('approval.step.execute'),
|
|
};
|
|
|
|
const fetchWorkflows = useCallback(async () => {
|
|
try {
|
|
setLoading(true);
|
|
setError(null);
|
|
const res: any = await approvalWorkflowApi.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(t('approval.msg.fetchFailed'));
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
}, [t]);
|
|
|
|
const fetchUsers = useCallback(async () => {
|
|
try {
|
|
const res: any = await userApi.getUsers();
|
|
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 approvalWorkflowApi.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 ? t('approval.msg.disabled') : t('approval.msg.enabled'));
|
|
} catch { toast.error(t('common.operationFailed')); }
|
|
}, [t]);
|
|
|
|
const handleDelete = useCallback(async (id: number, name: string) => {
|
|
const ok = await confirm({
|
|
title: t('approval.msg.deleteTitle'),
|
|
description: t('approval.msg.deleteConfirm', { name }),
|
|
confirmText: t('common.delete'),
|
|
variant: 'destructive',
|
|
});
|
|
if (!ok) return;
|
|
try {
|
|
await approvalWorkflowApi.delete(id);
|
|
setItems((prev) => prev.filter((w) => w.id !== id));
|
|
toast.success(t('approval.msg.deleted'));
|
|
} catch { toast.error(t('approval.msg.deleteFailed')); }
|
|
}, [confirm, t]);
|
|
|
|
const setDefault = useCallback(async (id: number) => {
|
|
try {
|
|
await approvalWorkflowApi.setDefault(id);
|
|
setItems((prev) => prev.map((w) => ({ ...w, is_default: w.id === id })));
|
|
toast.success(t('approval.msg.setDefaultSuccess'));
|
|
} catch { toast.error(t('common.operationFailed')); }
|
|
}, [t]);
|
|
|
|
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">{t('approval.retry')}</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)]">{t('approval.workflowTitle')}</h1>
|
|
<p className="text-sm text-[var(--dg-text-secondary)] mt-1">
|
|
{t('approval.workflowSubtitle')}
|
|
</p>
|
|
</div>
|
|
<Button onClick={() => setEditorWorkflow(null)}>
|
|
<Plus className="w-4 h-4 mr-1.5" />{t('approval.newWorkflow')}
|
|
</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">{t('approval.noWorkflows')}</p>
|
|
<Button variant="outline" onClick={() => setEditorWorkflow(null)}>{t('approval.createFirst')}</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" />{t('approval.status.default')}</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 ? t('approval.status.enabled') : t('approval.status.disabled')}
|
|
</span>
|
|
<span className="text-[10px] px-1.5 py-0.5 rounded bg-blue-500/15 text-blue-400">
|
|
{categoryLabels[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'}`}>
|
|
{stepTypeLabels[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={t('approval.msg.setDefaultSuccess')}>
|
|
<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 ? t('approval.status.disabled') : t('approval.status.enabled')}>
|
|
<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={t('common.edit')}>
|
|
<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={t('common.delete')}>
|
|
<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'}`}>
|
|
{stepTypeLabels[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">{t('approval.detail.noApproverLinked')}</span>
|
|
)}
|
|
</div>
|
|
</div>
|
|
);
|
|
})}
|
|
</div>
|
|
)}
|
|
</CardContent>
|
|
</Card>
|
|
);
|
|
})}
|
|
</div>
|
|
</>
|
|
)}
|
|
|
|
{editorWorkflow !== undefined && (
|
|
<WorkflowEditorModal
|
|
workflow={editorWorkflow}
|
|
users={users}
|
|
onClose={() => setEditorWorkflow(undefined)}
|
|
onSaved={() => { setEditorWorkflow(undefined); fetchWorkflows(); }}
|
|
/>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|