AgentEditorPage.tsx
20 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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
import { useEffect, useState } from 'react';
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
import { Button, FormItem, Input, Select, StatePlaceholder, Switch, Textarea } from '../../../packages/ui/src';
import { getPositionTagList, type PositionTagListItem } from '../../api/positionTag';
import { getEmployeeMounts, getAgentDetail, getAgentList, createAgent, updateAgent, type EmployeeMountItem, type AgentDetail, type AgentStatus } from '../../api/agent';
import { getSkillList, type SkillSummary } from '../../api/skill';
import { findSavedAgent, upsertSavedAgent } from './agentLocalStore';
import { buildAgentListSearch, readAgentListRouteState } from './agentRouteState';
import { isApiError } from '../../api/client';
import { useMessage } from '../../hooks/useMessage';
interface PositionOption {
id: string;
name: string;
}
interface AgentFormState {
name: string;
positionIds: number[];
managedUserId: number | string | undefined;
managedEmployeeValue: string | undefined;
managedUserName: string | undefined;
description: string;
skillIds: string[];
status: AgentStatus;
}
const STEWARD_AGENT_NAME = '管家Agent';
const STEWARD_POSITION_LABEL = '系统调度';
const STEWARD_MANAGED_USER_FALLBACK = '专用管家企微员工';
function buildCurrentManagedEmployeeValue(userId: number) {
return `managed:${userId}`;
}
function buildEmployeeValue(employee: EmployeeMountItem) {
return employee.employee_id || employee.wechat_user_id;
}
function buildInitialFormState(): AgentFormState {
return {
name: '',
positionIds: [],
managedUserId: undefined,
managedEmployeeValue: undefined,
managedUserName: undefined,
description: '',
skillIds: [],
status: 'disable',
};
}
function buildFormStateFromDetail(detail: AgentDetail): AgentFormState {
const managedUserId = detail.managed_user?.user_id;
return {
name: detail.name,
positionIds: detail.positions.map((position) => position.id),
managedUserId,
managedEmployeeValue: managedUserId ? buildCurrentManagedEmployeeValue(managedUserId) : undefined,
managedUserName: detail.managed_user?.user_name,
description: detail.description,
skillIds: detail.skill_ids ?? detail.skills.map((skill) => skill.skill_code),
status: detail.status,
};
}
function canSelectEmployee(employee: EmployeeMountItem, mode: 'create' | 'edit', agentId: number | undefined) {
if (employee.agent_count <= 0) {
return true;
}
if (mode === 'create') {
return false;
}
const mountedByCurrentAgent = agentId ? employee.agents.some((agent) => agent.agent_id === agentId) : false;
return mountedByCurrentAgent;
}
export function AgentEditorPage({ mode }: { mode: 'create' | 'edit' }) {
const navigate = useNavigate();
const params = useParams();
const [searchParams] = useSearchParams();
const message = useMessage();
const [detail, setDetail] = useState<AgentDetail | null>(null);
const [detailLoading, setDetailLoading] = useState(mode === 'edit');
const [detailError, setDetailError] = useState(false);
const [stewardIdentity, setStewardIdentity] = useState<boolean | null>(mode === 'create' ? false : null);
const [identityLoading, setIdentityLoading] = useState(mode === 'edit');
const [identityError, setIdentityError] = useState(false);
const savedDetail = findSavedAgent(params.agentId);
const initialFormState = mode === 'edit' && savedDetail
? buildFormStateFromDetail(savedDetail)
: buildInitialFormState();
const [form, setForm] = useState<AgentFormState>(initialFormState);
const [errors, setErrors] = useState<Partial<Record<keyof AgentFormState, string>>>({});
const [positionTags, setPositionTags] = useState<PositionTagListItem[]>([]);
const [positionsLoading, setPositionsLoading] = useState(true);
const [positionsError, setPositionsError] = useState(false);
const [employees, setEmployees] = useState<EmployeeMountItem[]>([]);
const [employeesLoading, setEmployeesLoading] = useState(true);
const [employeesError, setEmployeesError] = useState(false);
const [skills, setSkills] = useState<SkillSummary[]>([]);
const [skillsLoading, setSkillsLoading] = useState(true);
const [skillsError, setSkillsError] = useState(false);
const [saveLoading, setSaveLoading] = useState(false);
const [saveError, setSaveError] = useState<string | null>(null);
const routeState = readAgentListRouteState(searchParams);
const isSteward = stewardIdentity === true;
const fieldWidthClassName = 'w-full max-w-[450px]';
const agentId = params.agentId ? Number(params.agentId) : undefined;
useEffect(() => {
if (mode === 'edit' && agentId && !savedDetail) {
setDetailLoading(true);
setDetailError(false);
getAgentDetail(agentId)
.then((response) => {
setDetail(response);
setForm(buildFormStateFromDetail(response));
setDetailLoading(false);
})
.catch(() => {
setDetailError(true);
setDetailLoading(false);
});
} else if (savedDetail) {
setDetail(savedDetail);
setDetailLoading(false);
}
}, [agentId, mode, savedDetail]);
useEffect(() => {
if (mode !== 'edit') {
setStewardIdentity(false);
setIdentityLoading(false);
setIdentityError(false);
return;
}
if (!agentId) {
setStewardIdentity(null);
setIdentityLoading(false);
setIdentityError(true);
return;
}
const identitySourceName = detail?.name ?? savedDetail?.name;
if (!identitySourceName) {
return;
}
let cancelled = false;
setIdentityLoading(true);
setIdentityError(false);
getAgentList({
keyword: identitySourceName,
page: 1,
page_size: 100,
})
.then((response) => {
if (cancelled) return;
const currentAgent = response.list.find((item) => item.agent_id === agentId);
if (!currentAgent) {
setStewardIdentity(null);
setIdentityError(true);
setIdentityLoading(false);
return;
}
setStewardIdentity(currentAgent.is_steward);
setIdentityError(false);
setIdentityLoading(false);
})
.catch(() => {
if (cancelled) return;
setStewardIdentity(null);
setIdentityError(true);
setIdentityLoading(false);
});
return () => {
cancelled = true;
};
}, [agentId, detail?.name, mode, savedDetail?.name]);
useEffect(() => {
setPositionsLoading(true);
setPositionsError(false);
getPositionTagList({ page: 1, page_size: 100 })
.then((response) => {
setPositionTags(response.list);
setPositionsLoading(false);
})
.catch(() => {
setPositionsError(true);
setPositionsLoading(false);
});
}, []);
useEffect(() => {
setEmployeesLoading(true);
setEmployeesError(false);
getEmployeeMounts()
.then((response) => {
setEmployees(response.employees);
setEmployeesLoading(false);
})
.catch(() => {
setEmployeesError(true);
setEmployeesLoading(false);
});
}, []);
useEffect(() => {
setSkillsLoading(true);
setSkillsError(false);
getSkillList()
.then((response) => {
setSkills(response.list);
setSkillsLoading(false);
})
.catch(() => {
setSkillsError(true);
setSkillsLoading(false);
});
}, []);
const positionOptions: PositionOption[] = positionTags.map((tag) => ({ id: String(tag.tag_id), name: tag.name }));
if (detailLoading || identityLoading) {
return <StatePlaceholder state="empty" title="加载中" description="正在加载 Agent 详情" />;
}
if (mode === 'edit' && detailError) {
return <StatePlaceholder state="error" title="Agent不存在" description="当前 Agent 详情无法加载" />;
}
if (mode === 'edit' && identityError) {
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 (!isSteward && !form.name.trim()) nextErrors.name = '请输入 Agent 名称';
if (!isSteward && form.positionIds.length === 0) nextErrors.positionIds = '请选择所属岗位';
if (!isSteward && !form.managedEmployeeValue) nextErrors.managedUserId = '请选择托管企微员工';
if (!form.description.trim()) nextErrors.description = '请输入 Agent 描述';
if (!isSteward && form.skillIds.length === 0) nextErrors.skillIds = '请至少绑定一个 Skill';
setErrors(nextErrors);
return Object.keys(nextErrors).length === 0;
};
const handleSave = async () => {
if (!validate()) {
return;
}
setSaveLoading(true);
setSaveError(null);
try {
if (mode === 'create') {
const payload = {
name: form.name.trim(),
position_ids: form.positionIds,
managed_user_id: form.managedUserId!,
description: form.description.trim(),
skill_codes: form.skillIds,
status: form.status,
};
await createAgent(payload);
message.success('保存成功');
navigate(
`/agents${buildAgentListSearch({
...routeState,
refreshToken: String(Date.now()),
})}`,
);
} else {
const payload = isSteward
? {
description: form.description.trim(),
skill_codes: form.skillIds,
}
: {
name: form.name.trim(),
position_ids: form.positionIds,
managed_user_id: form.managedUserId,
description: form.description.trim(),
skill_codes: form.skillIds,
status: form.status,
};
const updatedAgent = await updateAgent(agentId!, payload);
upsertSavedAgent(updatedAgent);
message.success('保存成功');
navigate(
`/agents${buildAgentListSearch({
...routeState,
detail: routeState.detail ? String(agentId) : undefined,
refreshToken: String(Date.now()),
})}`,
);
}
} catch (error) {
const errorMessage = isApiError(error) ? error.message : '保存失败,请重试';
setSaveError(errorMessage);
message.error(errorMessage);
} finally {
setSaveLoading(false);
}
};
const title = mode === 'create' ? '新建Agent' : '编辑Agent';
const stewardManagedUserLabel = detail?.managed_user?.user_name ?? form.managedUserName ?? STEWARD_MANAGED_USER_FALLBACK;
const currentManagedOption = typeof form.managedUserId === 'number' && form.managedUserName
? [{
label: form.managedUserName,
value: buildCurrentManagedEmployeeValue(form.managedUserId),
}]
: [];
const employeeOptions = [
...currentManagedOption,
...employees.map((employee) => ({
label: employee.agent_count > 0 ? `${employee.employee_name}(已挂载Agent)` : employee.employee_name,
value: buildEmployeeValue(employee),
disabled: !canSelectEmployee(employee, mode, agentId),
})),
];
const fetchEmployees = () => {
setEmployeesLoading(true);
setEmployeesError(false);
getEmployeeMounts()
.then((response) => {
setEmployees(response.employees);
setEmployeesLoading(false);
})
.catch(() => {
setEmployeesError(true);
setEmployeesLoading(false);
});
};
const skillOptions = skills.map((skill) => ({
label: skill.skill_name,
value: skill.skill_code,
}));
const fetchSkills = () => {
setSkillsLoading(true);
setSkillsError(false);
getSkillList()
.then((response) => {
setSkills(response.list);
setSkillsLoading(false);
})
.catch(() => {
setSkillsError(true);
setSkillsLoading(false);
});
};
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={saveLoading} onClick={handleSave}>保存</Button>
</div>
</header>
{saveError ? (
<StatePlaceholder
state="error"
title="保存失败"
description={saveError}
primaryAction={<Button size="small" onClick={handleSave}>重试</Button>}
/>
) : 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={isSteward}
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">
{positionsError ? (
<StatePlaceholder state="error" title="岗位选项加载失败" description="请重试加载岗位选项" primaryAction={<Button size="small" onClick={() => {
setPositionsLoading(true);
setPositionsError(false);
getPositionTagList({ page: 1, page_size: 100 })
.then((response) => {
setPositionTags(response.list);
setPositionsLoading(false);
})
.catch(() => {
setPositionsError(true);
setPositionsLoading(false);
});
}}>重试</Button>} />
) : isSteward ? (
<Select
aria-label="所属岗位"
className={fieldWidthClassName}
disabled
multiple
options={positionOptions.map((position) => ({ label: position.name, value: position.id }))}
value={form.positionIds.map(String)}
/>
) : (
<Select
aria-label="所属岗位"
className={fieldWidthClassName}
disabled={isSteward}
multiple
options={positionOptions.map((position) => ({ label: position.name, value: position.id }))}
value={form.positionIds.map(String)}
onChange={(value) => {
const nextValue = Array.isArray(value) ? value.map(Number) : [];
setForm((current) => ({ ...current, positionIds: nextValue }));
}}
/>
)}
</span>
</FormItem>
<FormItem
label="托管企微员工"
layout="horizontal"
required
error={errors.managedUserId}
>
<span className="grid gap-2">
{employeesError ? (
<StatePlaceholder state="error" title="托管企微员工加载失败" description="请重试加载托管企微员工选项" primaryAction={<Button size="small" onClick={fetchEmployees}>重试</Button>} />
) : isSteward ? (
<Input
aria-label="托管企微员工"
className={fieldWidthClassName}
disabled
value={stewardManagedUserLabel}
/>
) : (
<Select
aria-label="托管企微员工"
className={fieldWidthClassName}
disabled={isSteward}
options={employeeOptions}
placeholder="请选择托管企微员工"
value={form.managedEmployeeValue}
onChange={(value) => setForm((current) => {
if (!value) {
return {
...current,
managedUserId: undefined,
managedEmployeeValue: undefined,
managedUserName: undefined,
};
}
const currentDetailManagedUser = detail?.managed_user;
if (currentDetailManagedUser && value === buildCurrentManagedEmployeeValue(currentDetailManagedUser.user_id)) {
return {
...current,
managedUserId: currentDetailManagedUser.user_id,
managedEmployeeValue: value,
managedUserName: currentDetailManagedUser.user_name,
};
}
const selectedEmployee = employees.find((employee) => buildEmployeeValue(employee) === value);
return {
...current,
managedUserId: selectedEmployee?.employee_id,
managedEmployeeValue: value,
managedUserName: selectedEmployee?.employee_name,
};
})}
/>
)}
</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={!isSteward} error={errors.skillIds}>
<span className="grid gap-2">
{skillsError ? (
<StatePlaceholder state="error" title="Skill 选项加载失败" description="请重试加载 Skill 选项" primaryAction={<Button size="small" onClick={fetchSkills}>重试</Button>} />
) : (
<Select
aria-label="绑定Skill"
className={fieldWidthClassName}
multiple
options={skillOptions}
value={form.skillIds}
onChange={(value) => setForm((current) => ({ ...current, skillIds: Array.isArray(value) ? value : [] }))}
/>
)}
</span>
</FormItem>
<FormItem label="状态" layout="horizontal" required>
<Switch
aria-label="状态"
checked={isSteward ? true : form.status === 'enable'}
disabled={isSteward}
onChange={(checked) => setForm((current) => ({ ...current, status: checked ? 'enable' : 'disable' }))}
/>
</FormItem>
</div>
</div>
</section>
);
}