AgentEditorPage.tsx
10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
import { useMemo, useState } from 'react';
import { useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom';
import { Button, FormItem, Input, Select, StatePlaceholder, Switch, Textarea } from '../../../packages/ui/src';
import {
createAgentRecord,
getAgentDetail,
getAgentEditorFixture,
type AgentDraftPayload,
type AgentEditorScenario,
} from '../../../packages/contracts/agent-editor-mock';
import { findSavedAgent, upsertSavedAgent } from './agentLocalStore';
import { buildAgentListSearch, readAgentListRouteState } from './agentRouteState';
interface AgentFormState {
name: string;
positionIds: string[];
userId?: string;
description: string;
skillIds: string[];
status: 'enable' | 'disable';
}
function buildInitialFormState(agentId?: string): AgentFormState {
const detail = findSavedAgent(agentId) ?? getAgentDetail(agentId);
if (!detail) {
return {
name: '',
positionIds: [],
userId: undefined,
description: '',
skillIds: [],
status: 'disable',
};
}
return {
name: detail.name,
positionIds: detail.positions.map((position) => position.id),
userId: detail.employee_id,
description: detail.description,
skillIds: detail.skill_ids,
status: detail.status,
};
}
export function AgentEditorPage({ mode }: { mode: 'create' | 'edit' }) {
const navigate = useNavigate();
const location = useLocation();
const params = useParams();
const [searchParams] = useSearchParams();
const [form, setForm] = useState<AgentFormState>(() => buildInitialFormState(params.agentId));
const [errors, setErrors] = useState<Partial<Record<keyof AgentFormState, string>>>({});
const routeState = readAgentListRouteState(searchParams);
const scenario = (searchParams.get('scenario') ?? 'normal') as AgentEditorScenario;
const fixture = useMemo(
() => getAgentEditorFixture({ agentId: params.agentId, mode, scenario, positionIds: form.positionIds }),
[form.positionIds, mode, params.agentId, scenario],
);
const detail = findSavedAgent(params.agentId) ?? getAgentDetail(params.agentId);
const isManager = detail?.is_manager ?? false;
const fieldWidthClassName = 'w-full max-w-[450px]';
if (fixture.detailLoading) {
return <StatePlaceholder state="empty" title="加载中" description="正在加载 Agent 详情" />;
}
if (mode === 'edit' && !detail) {
return <StatePlaceholder state="error" title="Agent不存在" description="当前 Agent 详情无法加载" />;
}
const goBackToList = (restoreDetail: boolean) => {
const nextSearch = buildAgentListSearch({
...routeState,
detail: restoreDetail ? routeState.detail : undefined,
});
navigate(`/agents${nextSearch}`);
};
const validate = () => {
const nextErrors: Partial<Record<keyof AgentFormState, string>> = {};
if (!form.name.trim()) nextErrors.name = '请输入 Agent 名称';
if (form.positionIds.length === 0) nextErrors.positionIds = '请选择所属岗位';
if (!form.userId) nextErrors.userId = '请选择托管企微员工';
if (!form.description.trim()) nextErrors.description = '请输入 Agent 描述';
if (!isManager && form.skillIds.length === 0) nextErrors.skillIds = '请至少绑定一个 Skill';
setErrors(nextErrors);
return Object.keys(nextErrors).length === 0;
};
const handleSave = () => {
if (!validate()) {
return;
}
if (fixture.saveError) {
return;
}
const payload: AgentDraftPayload = {
name: form.name.trim(),
positionIds: form.positionIds,
userId: form.userId,
description: form.description.trim(),
skillIds: form.skillIds,
status: form.status,
};
const savedDetail = mode === 'create'
? createAgentRecord(payload)
: {
...detail!,
name: isManager ? detail!.name : payload.name,
positions: isManager ? detail!.positions : fixture.positions.filter((position) => payload.positionIds.includes(position.id)),
employee_id: isManager ? detail!.employee_id : payload.userId ?? '',
employee_name: isManager ? detail!.employee_name : fixture.employees.find((employee) => employee.id === payload.userId)?.name ?? '',
description: payload.description,
skill_ids: payload.skillIds,
status: isManager ? detail!.status : payload.status,
};
upsertSavedAgent(savedDetail);
const nextDetailId = String(savedDetail.agent_id);
navigate(
`/agents${buildAgentListSearch({
...routeState,
detail: mode === 'edit' && routeState.detail ? nextDetailId : undefined,
refreshToken: String(Date.now()),
})}`,
);
};
const title = mode === 'create' ? '新建Agent' : '编辑Agent';
const employeeOptions = fixture.employees.map((employee) => ({
label: employee.status === 'mounted' ? `${employee.name}(已挂载Agent)` : employee.name,
value: employee.id,
disabled: employee.status === 'mounted',
}));
return (
<section className="grid gap-6">
<header className="flex items-center justify-between gap-6 rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 py-6">
<div className="flex items-center gap-4">
<Button variant="outline" onClick={() => goBackToList(Boolean(routeState.detail && mode === 'edit'))}>返回</Button>
<div>
<h2 className="m-0 text-2xl leading-[var(--gl-line-height-xl)]">{title}</h2>
<p className="m-0 mt-1 text-sm text-[var(--gl-color-text-secondary)]">
{mode === 'create' ? '创建新的岗位 Agent 配置' : '编辑已存在的 Agent 配置'}
</p>
</div>
</div>
<div className="flex items-center gap-3">
<Button variant="outline" onClick={() => goBackToList(Boolean(routeState.detail && mode === 'edit'))}>取消</Button>
<Button variant="primary" loading={fixture.saveLoading} onClick={handleSave}>保存</Button>
</div>
</header>
{fixture.saveError ? (
<StatePlaceholder
state="error"
title="保存失败,请重试"
description="当前变更尚未保存成功,请检查表单后重新提交。"
/>
) : null}
<div className="rounded-[var(--gl-radius-md)] border border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-8 py-10">
<div className="mx-auto grid max-w-[760px] gap-6">
<FormItem label="Agent名称" layout="horizontal" required error={errors.name}>
<span className="grid gap-2">
<Input
aria-label="Agent名称"
className={fieldWidthClassName}
disabled={isManager}
maxLength={50}
showCount
value={form.name}
onChange={(value) => setForm((current) => ({ ...current, name: value }))}
/>
</span>
</FormItem>
<FormItem label="所属岗位" layout="horizontal" required error={errors.positionIds}>
<span className="grid gap-2">
{fixture.positionsError ? (
<StatePlaceholder state="error" title="岗位选项加载失败" description="请重试加载岗位选项" primaryAction={<Button size="small">重试</Button>} />
) : (
<Select
aria-label="所属岗位"
className={fieldWidthClassName}
disabled={isManager}
multiple
options={fixture.positions.map((position) => ({ label: position.name, value: position.id }))}
value={form.positionIds}
onChange={(value) => {
const nextValue = Array.isArray(value) ? value : [];
setForm((current) => ({
...current,
positionIds: nextValue,
userId: nextValue.some((positionId) => current.positionIds.includes(positionId)) ? current.userId : undefined,
}));
}}
/>
)}
</span>
</FormItem>
<FormItem
label="托管企微员工"
layout="horizontal"
required
error={errors.userId}
tips={!isManager && form.positionIds.length === 0 ? '请先选择所属岗位' : undefined}
>
<span className="grid gap-2">
{fixture.employeesError ? (
<StatePlaceholder state="error" title="托管企微员工加载失败" description="请重试加载托管企微员工选项" primaryAction={<Button size="small">重试</Button>} />
) : (
<Select
aria-label="托管企微员工"
className={fieldWidthClassName}
disabled={isManager || form.positionIds.length === 0}
options={employeeOptions}
placeholder={form.positionIds.length === 0 ? '请先选择所属岗位' : '请选择托管企微员工'}
value={form.userId}
onChange={(value) => setForm((current) => ({ ...current, userId: typeof value === 'string' ? value : undefined }))}
/>
)}
</span>
</FormItem>
<FormItem label="Agent描述" layout="horizontal" required error={errors.description}>
<Textarea
aria-label="Agent描述"
className={fieldWidthClassName}
maxLength={200}
rows={5}
showCount
value={form.description}
onChange={(value) => setForm((current) => ({ ...current, description: value }))}
/>
</FormItem>
<FormItem label="绑定Skill" layout="horizontal" required={!isManager} error={errors.skillIds}>
<span className="grid gap-2">
{fixture.skillsError ? (
<StatePlaceholder state="error" title="Skill 选项加载失败" description="请重试加载 Skill 选项" primaryAction={<Button size="small">重试</Button>} />
) : (
<Select
aria-label="绑定Skill"
className={fieldWidthClassName}
multiple
options={fixture.skills.map((skill) => ({ label: skill.name, value: skill.id }))}
value={form.skillIds}
onChange={(value) => setForm((current) => ({ ...current, skillIds: Array.isArray(value) ? value : [] }))}
/>
)}
</span>
</FormItem>
<FormItem label="状态" layout="horizontal" required>
<Switch
aria-label="状态"
checked={form.status === 'enable'}
disabled={isManager}
onChange={(checked) => setForm((current) => ({ ...current, status: checked ? 'enable' : 'disable' }))}
/>
</FormItem>
</div>
</div>
</section>
);
}