Files
monkey-ai-web/src/components/settings/CustomerServiceSetting.jsx
T

586 lines
16 KiB
React

/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import {
RefreshCw as ActionRefreshCw,
Plus as ActionPlus,
Upload as ActionUpload,
} from '@/components/common/icons/ActionIcons';
import React, { useState, useEffect, useCallback } from 'react';
import {
Card,
Table,
Button,
Modal,
Form,
Select,
Tag,
Avatar,
Popconfirm,
Typography,
Space,
Banner,
Spin,
Upload,
} from '@/components/ui';
import { Users } from 'lucide-react';
import { API, showError, showSuccess } from '../../helpers';
import { useTranslation } from 'react-i18next';
const { Text } = Typography;
const CustomerServiceSetting = () => {
const { t } = useTranslation();
const [agents, setAgents] = useState([]);
const [loading, setLoading] = useState(false);
const [modalVisible, setModalVisible] = useState(false);
const [editingAgent, setEditingAgent] = useState(null);
const [formApi, setFormApi] = useState(null);
const [uploadingQrcode, setUploadingQrcode] = useState(false);
const [uploadingAvatar, setUploadingAvatar] = useState(false);
// 上传图片
const handleUpload = async (fileInfo, field) => {
const setUploading =
field === 'qrcode_url' ? setUploadingQrcode : setUploadingAvatar;
setUploading(true);
try {
const formData = new FormData();
// Semi UI 的 customRequest 回调中,fileInfo.fileInstance 是原始 File 对象
const file = fileInfo.fileInstance || fileInfo.file;
formData.append('file', file);
const res = await API.post('/api/customer-service/upload', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
});
if (res.data.success && res.data.data?.url) {
formApi?.setValue(field, res.data.data.url);
showSuccess(t('上传成功'));
fileInfo.onSuccess?.();
} else {
showError(res.data.message || t('上传失败'));
fileInfo.onError?.();
}
} catch (err) {
showError(t('上传失败'));
fileInfo.onError?.();
} finally {
setUploading(false);
}
};
// 工作日选项
const workDayOptions = [
{ label: t('周一'), value: '1' },
{ label: t('周二'), value: '2' },
{ label: t('周三'), value: '3' },
{ label: t('周四'), value: '4' },
{ label: t('周五'), value: '5' },
{ label: t('周六'), value: '6' },
{ label: t('周日'), value: '7' },
];
// 获取客服列表
const fetchAgents = useCallback(async () => {
setLoading(true);
try {
const res = await API.get('/api/customer-service/');
if (res.data.success) {
setAgents(res.data.data || []);
} else {
showError(res.data.message);
}
} catch (err) {
showError(t('获取客服列表失败'));
} finally {
setLoading(false);
}
}, [t]);
useEffect(() => {
fetchAgents();
}, [fetchAgents]);
// 打开新建/编辑弹窗
const openModal = (agent = null) => {
setEditingAgent(agent);
setModalVisible(true);
};
// 关闭弹窗
const closeModal = () => {
setModalVisible(false);
setEditingAgent(null);
if (formApi) {
formApi.reset();
}
};
// 提交表单
const handleSubmit = async () => {
if (!formApi) return;
try {
await formApi.validate();
const values = formApi.getValues();
// 处理工作日
const workDays = Array.isArray(values.work_days)
? values.work_days.join(',')
: values.work_days || '1,2,3,4,5';
// 处理工作时间(Form.Input 返回字符串,直接使用)
const workStartTime = values.work_start_time || '';
const workEndTime = values.work_end_time || '';
const payload = {
...values,
work_days: workDays,
work_start_time: workStartTime,
work_end_time: workEndTime,
weight: values.weight || 100,
max_sessions: values.max_sessions || 50,
priority: values.priority || 0,
status: values.status ?? 1,
};
if (editingAgent) {
payload.id = editingAgent.id;
const res = await API.put('/api/customer-service/', payload);
if (res.data.success) {
showSuccess(t('更新成功'));
closeModal();
fetchAgents();
} else {
showError(res.data.message);
}
} else {
const res = await API.post('/api/customer-service/', payload);
if (res.data.success) {
showSuccess(t('创建成功'));
closeModal();
fetchAgents();
} else {
showError(res.data.message);
}
}
} catch (err) {
// 表单验证失败或其他错误
if (err && err.message) {
showError(err.message);
}
}
};
// 删除客服
const handleDelete = async (id) => {
try {
const res = await API.delete(`/api/customer-service/${id}`);
if (res.data.success) {
showSuccess(t('删除成功'));
fetchAgents();
} else {
showError(res.data.message);
}
} catch (err) {
showError(t('删除失败'));
}
};
// 切换状态
const handleToggleStatus = async (agent) => {
const newStatus = agent.status === 1 ? 0 : 1;
try {
const res = await API.put(`/api/customer-service/${agent.id}/status`, {
status: newStatus,
});
if (res.data.success) {
showSuccess(newStatus === 1 ? t('已上线') : t('已下线'));
fetchAgents();
} else {
showError(res.data.message);
}
} catch (err) {
showError(t('操作失败'));
}
};
// 状态标签
const getStatusTag = (status) => {
const statusMap = {
1: { text: t('在线'), color: 'green' },
2: { text: t('忙碌'), color: 'orange' },
0: { text: t('离线'), color: 'grey' },
};
const s = statusMap[status] || statusMap[0];
return <Tag color={s.color}>{s.text}</Tag>;
};
// 表格列定义
const columns = [
{
title: t('客服'),
dataIndex: 'name',
render: (text, record) => (
<Space>
<Avatar
src={record.avatar}
size='small'
style={{ backgroundColor: '#87d068' }}
>
{text?.[0]?.toUpperCase()}
</Avatar>
<Text strong>{text}</Text>
</Space>
),
},
{
title: t('状态'),
dataIndex: 'status',
render: (status) => getStatusTag(status),
},
{
title: t('接待数'),
dataIndex: 'current_sessions',
render: (current, record) => (
<Text>
{current} / {record.max_sessions}
</Text>
),
},
{
title: t('权重'),
dataIndex: 'weight',
},
{
title: t('优先级'),
dataIndex: 'priority',
},
{
title: t('工作时间'),
dataIndex: 'work_start_time',
render: (start, record) => {
if (start && record.work_end_time) {
return `${start} - ${record.work_end_time}`;
}
return t('全天');
},
},
{
title: t('工作日'),
dataIndex: 'work_days',
render: (days) => {
if (!days) return t('工作日');
const dayNames = {
1: t('一'),
2: t('二'),
3: t('三'),
4: t('四'),
5: t('五'),
6: t('六'),
7: t('日'),
};
return days
.split(',')
.map((d) => dayNames[d] || d)
.join('、');
},
},
{
title: t('操作'),
dataIndex: 'action',
render: (_, record) => (
<Space>
<Button
onClick={() => handleToggleStatus(record)}
type='link'
size='small'
danger={(record.status === 1 ? 'danger' : 'primary') === 'danger'}
>
{record.status === 1 ? t('下线') : t('上线')}
</Button>
<Button onClick={() => openModal(record)} type='link' size='small'>
{t('编辑')}
</Button>
<Popconfirm
title={t('确认删除')}
content={t('确定要删除这个客服吗?')}
onConfirm={() => handleDelete(record.id)}
>
<Button type='link' size='small' danger>
{t('删除')}
</Button>
</Popconfirm>
</Space>
),
},
];
// 初始表单值
const getInitialValues = () => {
if (editingAgent) {
return {
...editingAgent,
work_days: editingAgent.work_days
? editingAgent.work_days.split(',')
: ['1', '2', '3', '4', '5'],
};
}
return {
status: 1,
weight: 100,
max_sessions: 50,
priority: 0,
work_days: ['1', '2', '3', '4', '5'],
};
};
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
<Card>
<div style={{ marginBottom: 16 }}>
<Banner
type='info'
description={t(
'配置企业微信客服,支持多客服轮询、加权分配、最少接待等策略。客服链接可在企业微信管理后台的「微信客服」中获取。',
)}
/>
</div>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
marginBottom: 16,
}}
>
<Space>
<Users size={20} />
<Text strong style={{ fontSize: 16 }}>
{t('客服列表')}
</Text>
<Tag color='blue'>
{agents.length} {t('个客服')}
</Tag>
</Space>
<Space>
<Button
icon={<ActionRefreshCw size={14} />}
onClick={fetchAgents}
loading={loading}
>
{t('刷新')}
</Button>
<Button
icon={<ActionPlus size={14} />}
type='primary'
onClick={() => openModal()}
>
{t('添加客服')}
</Button>
</Space>
</div>
<Spin spinning={loading}>
<Table
columns={columns}
dataSource={agents}
rowKey='id'
pagination={false}
empty={t('暂无客服,请点击「添加客服」创建')}
/>
</Spin>
</Card>
{/* 新建/编辑弹窗 */}
<Modal
rootClassName='settings-form-dialog'
title={editingAgent ? t('编辑客服') : t('添加客服')}
visible={modalVisible}
onOk={handleSubmit}
onCancel={closeModal}
okText={t('保存')}
cancelText={t('取消')}
width={600}
>
<Form
getFormApi={(api) => setFormApi(api)}
initValues={getInitialValues()}
labelPosition='left'
labelWidth={100}
>
<Form.Input
field='name'
label={t('客服名称')}
placeholder={t('请输入客服名称')}
rules={[{ required: true, message: t('请输入客服名称') }]}
/>
<Form.Slot label={t('头像')}>
<div style={{ display: 'flex', gap: 8, alignItems: 'flex-start' }}>
<Form.Input
field='avatar'
noLabel
placeholder={t('图片链接或点击上传')}
style={{ flex: 1 }}
/>
<Upload
accept='image/*'
showUploadList={false}
customRequest={(fileInfo) => handleUpload(fileInfo, 'avatar')}
>
<Button
icon={<ActionUpload size={14} />}
loading={uploadingAvatar}
>
{t('上传')}
</Button>
</Upload>
</div>
</Form.Slot>
<Form.TextArea
field='wecom_url'
label={t('客服链接')}
placeholder={t('请输入企业微信客服链接')}
autosize={{ minRows: 2, maxRows: 4 }}
/>
<Form.Slot label={t('二维码')}>
<div
style={{
display: 'flex',
gap: 8,
alignItems: 'flex-start',
flexDirection: 'column',
}}
>
<div style={{ display: 'flex', gap: 8, width: '100%' }}>
<Form.Input
field='qrcode_url'
noLabel
placeholder={t('图片链接或点击上传')}
style={{ flex: 1 }}
/>
<Upload
accept='image/*'
showUploadList={false}
customRequest={(fileInfo) =>
handleUpload(fileInfo, 'qrcode_url')
}
>
<Button
icon={<ActionUpload size={14} />}
loading={uploadingQrcode}
>
{t('上传')}
</Button>
</Upload>
</div>
{formApi?.getValue('qrcode_url') && (
<img
src={formApi.getValue('qrcode_url')}
alt={t('二维码预览')}
style={{
maxWidth: 120,
maxHeight: 120,
borderRadius: 4,
border: '1px solid var(--ui-color-border)',
}}
/>
)}
</div>
</Form.Slot>
<Form.InputNumber
field='weight'
label={t('权重')}
placeholder='100'
min={0}
max={1000}
style={{ width: '100%' }}
extraText={t('权重越高,被分配的概率越大')}
/>
<Form.InputNumber
field='max_sessions'
label={t('最大接待数')}
placeholder='50'
min={1}
max={1000}
style={{ width: '100%' }}
extraText={t('达到最大接待数后将不再分配新用户')}
/>
<Form.InputNumber
field='priority'
label={t('优先级')}
placeholder='0'
min={0}
max={100}
style={{ width: '100%' }}
extraText={t('优先级越高,在优先级策略下优先分配')}
/>
<Form.Select
field='status'
label={t('状态')}
style={{ width: '100%' }}
>
<Select.Option value={1}>{t('在线')}</Select.Option>
<Select.Option value={2}>{t('忙碌')}</Select.Option>
<Select.Option value={0}>{t('离线')}</Select.Option>
</Form.Select>
<Form.CheckboxGroup
field='work_days'
label={t('工作日')}
options={workDayOptions}
direction='horizontal'
/>
<Form.Input
field='work_start_time'
label={t('上班时间')}
placeholder='09:00'
extraText={t('留空表示全天在线,格式:HH:MM')}
/>
<Form.Input
field='work_end_time'
label={t('下班时间')}
placeholder='18:00'
extraText={t('留空表示全天在线,格式:HH:MM')}
/>
<Form.TextArea
field='description'
label={t('描述')}
placeholder={t('请输入客服描述(可选)')}
autosize={{ minRows: 2, maxRows: 4 }}
/>
</Form>
</Modal>
</div>
);
};
export default CustomerServiceSetting;