merge(dev): release v3.4.11 dev plan, wecom push and bot fixes
CI / verify (push) Has been cancelled
CI / verify (push) Has been cancelled
This commit is contained in:
@@ -47,8 +47,13 @@ import WechatBindingsPage from './pages/WechatBindingsPage';
|
|||||||
import HqPermissionsPage from './pages/HqPermissionsPage';
|
import HqPermissionsPage from './pages/HqPermissionsPage';
|
||||||
import SystemSettingsPage from './pages/SystemSettingsPage';
|
import SystemSettingsPage from './pages/SystemSettingsPage';
|
||||||
import WecomBotsPage from './pages/WecomBotsPage';
|
import WecomBotsPage from './pages/WecomBotsPage';
|
||||||
|
import WecomMessagePushesPage from './pages/WecomMessagePushesPage';
|
||||||
|
import WecomBotLogsPage from './pages/WecomBotLogsPage';
|
||||||
import LlmConfigsPage from './pages/LlmConfigsPage';
|
import LlmConfigsPage from './pages/LlmConfigsPage';
|
||||||
import KnowledgeBasesPage from './pages/KnowledgeBasesPage';
|
import KnowledgeBasesPage from './pages/KnowledgeBasesPage';
|
||||||
|
import DevPlanVersionsPage from './pages/DevPlanVersionsPage';
|
||||||
|
import DevPlanTasksPage from './pages/DevPlanTasksPage';
|
||||||
|
import DevPlanSettingsPage from './pages/DevPlanSettingsPage';
|
||||||
|
|
||||||
function RequireAuth({ children }: { children: React.ReactNode }) {
|
function RequireAuth({ children }: { children: React.ReactNode }) {
|
||||||
if (!getToken()) return <Navigate to="/login" replace />;
|
if (!getToken()) return <Navigate to="/login" replace />;
|
||||||
@@ -75,9 +80,15 @@ export default function App() {
|
|||||||
<Route index element={<PromoCodeDetailPage />} />
|
<Route index element={<PromoCodeDetailPage />} />
|
||||||
<Route path="users" element={<PromoCodeUsersPage />} />
|
<Route path="users" element={<PromoCodeUsersPage />} />
|
||||||
</Route>
|
</Route>
|
||||||
<Route path="/wecom-bots" element={<WecomBotsPage />} />
|
<Route path="/wecom-bots" element={<Navigate to="/wecom/bots" replace />} />
|
||||||
|
<Route path="/wecom/bots" element={<WecomBotsPage />} />
|
||||||
|
<Route path="/wecom/pushes" element={<WecomMessagePushesPage />} />
|
||||||
|
<Route path="/logs/wecom-bots" element={<WecomBotLogsPage />} />
|
||||||
<Route path="/llm-configs" element={<LlmConfigsPage />} />
|
<Route path="/llm-configs" element={<LlmConfigsPage />} />
|
||||||
<Route path="/knowledge-bases" element={<KnowledgeBasesPage />} />
|
<Route path="/knowledge-bases" element={<KnowledgeBasesPage />} />
|
||||||
|
<Route path="/dev-plan/versions" element={<DevPlanVersionsPage />} />
|
||||||
|
<Route path="/dev-plan/tasks" element={<DevPlanTasksPage />} />
|
||||||
|
<Route path="/dev-plan/settings" element={<DevPlanSettingsPage />} />
|
||||||
<Route path="/products" element={<ProductsPage />} />
|
<Route path="/products" element={<ProductsPage />} />
|
||||||
<Route path="/product-detail-templates" element={<ProductDetailTemplatesPage />} />
|
<Route path="/product-detail-templates" element={<ProductDetailTemplatesPage />} />
|
||||||
<Route path="/stores" element={<StoresPage />} />
|
<Route path="/stores" element={<StoresPage />} />
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ import {
|
|||||||
LockOutlined,
|
LockOutlined,
|
||||||
SettingOutlined,
|
SettingOutlined,
|
||||||
AccountBookOutlined,
|
AccountBookOutlined,
|
||||||
|
ProjectOutlined,
|
||||||
} from '@ant-design/icons';
|
} from '@ant-design/icons';
|
||||||
import { hasAnySystemSettingsPermission } from '@dukang/shared-types';
|
import { hasAnySystemSettingsPermission } from '@dukang/shared-types';
|
||||||
import { clearAuth, request, type HqProfile } from '../lib/api';
|
import { clearAuth, request, type HqProfile } from '../lib/api';
|
||||||
@@ -42,7 +43,15 @@ const MENU_ITEMS: MenuProps['items'] = [
|
|||||||
},
|
},
|
||||||
{ key: '/orders', icon: <ShoppingOutlined />, label: '订单' },
|
{ key: '/orders', icon: <ShoppingOutlined />, label: '订单' },
|
||||||
{ key: '/promo-codes', icon: <GiftOutlined />, label: '推广码' },
|
{ key: '/promo-codes', icon: <GiftOutlined />, label: '推广码' },
|
||||||
{ key: '/wecom-bots', icon: <TeamOutlined />, label: '企微机器人' },
|
{
|
||||||
|
key: 'wecom-group',
|
||||||
|
icon: <TeamOutlined />,
|
||||||
|
label: '企微机器人',
|
||||||
|
children: [
|
||||||
|
{ key: '/wecom/bots', label: '智能机器人' },
|
||||||
|
{ key: '/wecom/pushes', label: '消息推送' },
|
||||||
|
],
|
||||||
|
},
|
||||||
{ key: '/llm-configs', icon: <RobotOutlined />, label: '语言模型' },
|
{ key: '/llm-configs', icon: <RobotOutlined />, label: '语言模型' },
|
||||||
{ key: '/knowledge-bases', icon: <FileTextOutlined />, label: '知识库' },
|
{ key: '/knowledge-bases', icon: <FileTextOutlined />, label: '知识库' },
|
||||||
{
|
{
|
||||||
@@ -110,6 +119,16 @@ const MENU_ITEMS: MenuProps['items'] = [
|
|||||||
{ key: '/tickets/support', label: '技术支持' },
|
{ key: '/tickets/support', label: '技术支持' },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
key: 'dev-plan-group',
|
||||||
|
icon: <ProjectOutlined />,
|
||||||
|
label: '开发计划',
|
||||||
|
children: [
|
||||||
|
{ key: '/dev-plan/versions', label: '版本列表' },
|
||||||
|
{ key: '/dev-plan/tasks', label: '任务列表' },
|
||||||
|
{ key: '/dev-plan/settings', label: '开发设置' },
|
||||||
|
],
|
||||||
|
},
|
||||||
{ key: '/invoices', icon: <FileTextOutlined />, label: '发票管理' },
|
{ key: '/invoices', icon: <FileTextOutlined />, label: '发票管理' },
|
||||||
{ key: '/resources', icon: <CloudUploadOutlined />, label: 'OSS 资源库' },
|
{ key: '/resources', icon: <CloudUploadOutlined />, label: 'OSS 资源库' },
|
||||||
{
|
{
|
||||||
@@ -123,6 +142,7 @@ const MENU_ITEMS: MenuProps['items'] = [
|
|||||||
{ key: '/logs/hq', label: 'HQ 操作日志' },
|
{ key: '/logs/hq', label: 'HQ 操作日志' },
|
||||||
{ key: '/logs/third-party', label: '第三方日志' },
|
{ key: '/logs/third-party', label: '第三方日志' },
|
||||||
{ key: '/logs/domain-events', label: '领域事件' },
|
{ key: '/logs/domain-events', label: '领域事件' },
|
||||||
|
{ key: '/logs/wecom-bots', label: '智能机器人日志' },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{ key: '/hq-permissions', icon: <LockOutlined />, label: '权限分配' },
|
{ key: '/hq-permissions', icon: <LockOutlined />, label: '权限分配' },
|
||||||
@@ -134,6 +154,9 @@ function menuAllowed(key: string, permissionKeys: string[]): boolean {
|
|||||||
if (key === 'tickets-group') {
|
if (key === 'tickets-group') {
|
||||||
return permissionKeys.includes('tickets') || permissionKeys.includes('tech_support');
|
return permissionKeys.includes('tickets') || permissionKeys.includes('tech_support');
|
||||||
}
|
}
|
||||||
|
if (key === 'dev-plan-group') {
|
||||||
|
return permissionKeys.includes('dev_plan');
|
||||||
|
}
|
||||||
const map: Record<string, string | 'system_settings_any'> = {
|
const map: Record<string, string | 'system_settings_any'> = {
|
||||||
'/': 'dashboard',
|
'/': 'dashboard',
|
||||||
'/users': 'users',
|
'/users': 'users',
|
||||||
@@ -143,7 +166,9 @@ function menuAllowed(key: string, permissionKeys: string[]): boolean {
|
|||||||
'/product-detail-templates': 'products',
|
'/product-detail-templates': 'products',
|
||||||
'/orders': 'orders',
|
'/orders': 'orders',
|
||||||
'/promo-codes': 'promo_codes',
|
'/promo-codes': 'promo_codes',
|
||||||
'/wecom-bots': 'wecom_bots',
|
'/wecom/bots': 'wecom_bots',
|
||||||
|
'/wecom/pushes': 'wecom_bots',
|
||||||
|
'wecom-group': 'wecom_bots',
|
||||||
'/llm-configs': 'llm_configs',
|
'/llm-configs': 'llm_configs',
|
||||||
'/knowledge-bases': 'knowledge_bases',
|
'/knowledge-bases': 'knowledge_bases',
|
||||||
'stores-group': 'stores',
|
'stores-group': 'stores',
|
||||||
@@ -175,10 +200,15 @@ function menuAllowed(key: string, permissionKeys: string[]): boolean {
|
|||||||
'/deliveries/xiaofeixia': 'deliveries',
|
'/deliveries/xiaofeixia': 'deliveries',
|
||||||
'/tickets': 'tickets',
|
'/tickets': 'tickets',
|
||||||
'/tickets/support': 'tech_support',
|
'/tickets/support': 'tech_support',
|
||||||
|
'dev-plan-group': 'dev_plan',
|
||||||
|
'/dev-plan/versions': 'dev_plan',
|
||||||
|
'/dev-plan/tasks': 'dev_plan',
|
||||||
|
'/dev-plan/settings': 'dev_plan',
|
||||||
'/invoices': 'invoices',
|
'/invoices': 'invoices',
|
||||||
'/resources': 'resources',
|
'/resources': 'resources',
|
||||||
'logs-group': 'logs',
|
'logs-group': 'logs',
|
||||||
'/logs/users': 'logs',
|
'/logs/users': 'logs',
|
||||||
|
'/logs/wecom-bots': 'logs',
|
||||||
'/logs/stores': 'logs',
|
'/logs/stores': 'logs',
|
||||||
'/logs/partners': 'logs',
|
'/logs/partners': 'logs',
|
||||||
'/logs/hq': 'logs',
|
'/logs/hq': 'logs',
|
||||||
|
|||||||
@@ -0,0 +1,103 @@
|
|||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import { Button, Collapse, Form, Input, Select, Typography, message } from 'antd';
|
||||||
|
import type {
|
||||||
|
DevPlanSettingsDto,
|
||||||
|
KnowledgeBaseOptionDto,
|
||||||
|
LlmApiConfigOptionDto,
|
||||||
|
} from '@dukang/shared-types';
|
||||||
|
import { request } from '../lib/api';
|
||||||
|
|
||||||
|
export default function DevPlanSettingsPage() {
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
const [llmOptions, setLlmOptions] = useState<LlmApiConfigOptionDto[]>([]);
|
||||||
|
const [kbOptions, setKbOptions] = useState<KnowledgeBaseOptionDto[]>([]);
|
||||||
|
const [settingsForm] = Form.useForm();
|
||||||
|
|
||||||
|
async function loadAll() {
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
const [s, llm, kb] = await Promise.all([
|
||||||
|
request<DevPlanSettingsDto>('/admin/dev-plan/settings'),
|
||||||
|
request<LlmApiConfigOptionDto[]>('/admin/llm-configs/options'),
|
||||||
|
request<KnowledgeBaseOptionDto[]>('/admin/knowledge-bases/options'),
|
||||||
|
]);
|
||||||
|
setLlmOptions(llm);
|
||||||
|
setKbOptions(kb);
|
||||||
|
settingsForm.setFieldsValue({
|
||||||
|
reviewAssistantLlmConfigId: s.reviewAssistantLlmConfigId,
|
||||||
|
reviewAssistantKnowledgeBaseId: s.reviewAssistantKnowledgeBaseId,
|
||||||
|
reviewAssistantPrompt: s.reviewAssistantPrompt,
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
message.error(e instanceof Error ? e.message : '加载失败');
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void loadAll();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
async function saveSettings() {
|
||||||
|
const values = await settingsForm.validateFields();
|
||||||
|
setSaving(true);
|
||||||
|
try {
|
||||||
|
await request<DevPlanSettingsDto>('/admin/dev-plan/settings', {
|
||||||
|
method: 'PUT',
|
||||||
|
body: JSON.stringify(values),
|
||||||
|
});
|
||||||
|
message.success('设置已保存');
|
||||||
|
} catch (e) {
|
||||||
|
message.error(e instanceof Error ? e.message : '保存失败');
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<Typography.Title level={4}>开发计划 · 开发设置</Typography.Title>
|
||||||
|
<Typography.Paragraph type="secondary">
|
||||||
|
任务评审派发 Webhook 已迁移至「企微机器人 → 消息推送」,勾选「开发任务评审派发」条件即可。
|
||||||
|
</Typography.Paragraph>
|
||||||
|
|
||||||
|
<Collapse
|
||||||
|
defaultActiveKey={['review-ai']}
|
||||||
|
style={{ marginTop: 16 }}
|
||||||
|
items={[
|
||||||
|
{
|
||||||
|
key: 'review-ai',
|
||||||
|
label: '本地审核 AI 助手',
|
||||||
|
children: (
|
||||||
|
<Form form={settingsForm} layout="vertical" disabled={loading}>
|
||||||
|
<Typography.Paragraph type="secondary">
|
||||||
|
仅用于技术支持批量预审(只读知识库 + LLM),preview 阶段不写库。
|
||||||
|
</Typography.Paragraph>
|
||||||
|
<Form.Item name="reviewAssistantLlmConfigId" label="语言模型">
|
||||||
|
<Select
|
||||||
|
allowClear
|
||||||
|
options={llmOptions.map((o) => ({ value: o.id, label: o.name }))}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="reviewAssistantKnowledgeBaseId" label="知识库">
|
||||||
|
<Select
|
||||||
|
allowClear
|
||||||
|
options={kbOptions.map((o) => ({ value: o.id, label: o.name }))}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="reviewAssistantPrompt" label="审核提示词">
|
||||||
|
<Input.TextArea rows={5} />
|
||||||
|
</Form.Item>
|
||||||
|
<Button type="primary" loading={saving} onClick={() => void saveSettings()}>
|
||||||
|
保存
|
||||||
|
</Button>
|
||||||
|
</Form>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,285 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
|
import {
|
||||||
|
Button,
|
||||||
|
Form,
|
||||||
|
Input,
|
||||||
|
Modal,
|
||||||
|
Popconfirm,
|
||||||
|
Select,
|
||||||
|
Space,
|
||||||
|
Table,
|
||||||
|
Tag,
|
||||||
|
Typography,
|
||||||
|
message,
|
||||||
|
} from 'antd';
|
||||||
|
import type { ColumnsType } from 'antd/es/table';
|
||||||
|
import {
|
||||||
|
DEV_PLAN_TASK_STATUS_LABELS,
|
||||||
|
DEV_PLAN_TASK_TYPE_LABELS,
|
||||||
|
type DevPlanTaskDto,
|
||||||
|
type DevPlanTaskStatusDto,
|
||||||
|
type DevPlanTaskTypeDto,
|
||||||
|
} from '@dukang/shared-types';
|
||||||
|
import { request } from '../lib/api';
|
||||||
|
import { fmtTime } from '../lib/constants';
|
||||||
|
import { useAdminList } from '../lib/useAdminList';
|
||||||
|
|
||||||
|
const TYPE_OPTIONS = (Object.keys(DEV_PLAN_TASK_TYPE_LABELS) as DevPlanTaskTypeDto[]).map((v) => ({
|
||||||
|
value: v,
|
||||||
|
label: DEV_PLAN_TASK_TYPE_LABELS[v],
|
||||||
|
}));
|
||||||
|
|
||||||
|
const STATUS_OPTIONS = (Object.keys(DEV_PLAN_TASK_STATUS_LABELS) as DevPlanTaskStatusDto[]).map(
|
||||||
|
(v) => ({ value: v, label: DEV_PLAN_TASK_STATUS_LABELS[v] }),
|
||||||
|
);
|
||||||
|
|
||||||
|
const STATUS_COLOR: Record<DevPlanTaskStatusDto, string> = {
|
||||||
|
TODO: 'default',
|
||||||
|
DEVELOPED: 'blue',
|
||||||
|
RELEASED: 'green',
|
||||||
|
};
|
||||||
|
|
||||||
|
const DEFAULT_DISPATCH_SUPPLEMENT = '请按以下任务进入开发流程';
|
||||||
|
|
||||||
|
export default function DevPlanTasksPage() {
|
||||||
|
const [filters, setFilters] = useState<Record<string, string>>({});
|
||||||
|
const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
|
||||||
|
const [modalOpen, setModalOpen] = useState(false);
|
||||||
|
const [dispatchOpen, setDispatchOpen] = useState(false);
|
||||||
|
const [editing, setEditing] = useState<DevPlanTaskDto | null>(null);
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
const [dispatching, setDispatching] = useState(false);
|
||||||
|
const [form] = Form.useForm();
|
||||||
|
const [dispatchForm] = Form.useForm<{ supplement?: string }>();
|
||||||
|
|
||||||
|
const { data, loading, page, pageSize, setPage, setPageSize, reload } = useAdminList<DevPlanTaskDto>(
|
||||||
|
'/admin/dev-plan/tasks',
|
||||||
|
() => {
|
||||||
|
const qs = new URLSearchParams();
|
||||||
|
if (filters.status) qs.set('status', filters.status);
|
||||||
|
if (filters.type) qs.set('type', filters.type);
|
||||||
|
if (filters.keyword) qs.set('keyword', filters.keyword);
|
||||||
|
return qs;
|
||||||
|
},
|
||||||
|
[filters],
|
||||||
|
);
|
||||||
|
|
||||||
|
function openCreate() {
|
||||||
|
setEditing(null);
|
||||||
|
form.setFieldsValue({ content: '', type: 'BUG', status: 'TODO' });
|
||||||
|
setModalOpen(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
function openEdit(row: DevPlanTaskDto) {
|
||||||
|
setEditing(row);
|
||||||
|
form.setFieldsValue({ content: row.content, type: row.type, status: row.status });
|
||||||
|
setModalOpen(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function save() {
|
||||||
|
const values = await form.validateFields();
|
||||||
|
setSaving(true);
|
||||||
|
try {
|
||||||
|
if (editing) {
|
||||||
|
await request(`/admin/dev-plan/tasks/${editing.id}`, {
|
||||||
|
method: 'PUT',
|
||||||
|
body: JSON.stringify(values),
|
||||||
|
});
|
||||||
|
message.success('已更新');
|
||||||
|
} else {
|
||||||
|
await request('/admin/dev-plan/tasks', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ content: values.content, type: values.type }),
|
||||||
|
});
|
||||||
|
message.success('已创建');
|
||||||
|
}
|
||||||
|
setModalOpen(false);
|
||||||
|
reload();
|
||||||
|
} catch (e) {
|
||||||
|
message.error(e instanceof Error ? e.message : '保存失败');
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function remove(id: string) {
|
||||||
|
try {
|
||||||
|
await request(`/admin/dev-plan/tasks/${id}`, { method: 'DELETE' });
|
||||||
|
message.success('已删除');
|
||||||
|
reload();
|
||||||
|
} catch (e) {
|
||||||
|
message.error(e instanceof Error ? e.message : '删除失败');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function openDispatch() {
|
||||||
|
dispatchForm.setFieldsValue({
|
||||||
|
supplement: DEFAULT_DISPATCH_SUPPLEMENT,
|
||||||
|
});
|
||||||
|
setDispatchOpen(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function submitDispatch() {
|
||||||
|
const values = await dispatchForm.validateFields();
|
||||||
|
setDispatching(true);
|
||||||
|
try {
|
||||||
|
await request('/admin/dev-plan/tasks/dispatch', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({
|
||||||
|
taskIds: selectedRowKeys,
|
||||||
|
supplement: values.supplement?.trim() || undefined,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
message.success('已派发到企微群');
|
||||||
|
setDispatchOpen(false);
|
||||||
|
setSelectedRowKeys([]);
|
||||||
|
reload();
|
||||||
|
} catch (e) {
|
||||||
|
message.error(e instanceof Error ? e.message : '派发失败');
|
||||||
|
} finally {
|
||||||
|
setDispatching(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const columns: ColumnsType<DevPlanTaskDto> = [
|
||||||
|
{ title: '任务号', dataIndex: 'taskNo', width: 160 },
|
||||||
|
{
|
||||||
|
title: '类型',
|
||||||
|
dataIndex: 'type',
|
||||||
|
width: 80,
|
||||||
|
render: (t: DevPlanTaskTypeDto) => DEV_PLAN_TASK_TYPE_LABELS[t],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '状态',
|
||||||
|
dataIndex: 'status',
|
||||||
|
width: 90,
|
||||||
|
render: (s: DevPlanTaskStatusDto) => (
|
||||||
|
<Tag color={STATUS_COLOR[s]}>{DEV_PLAN_TASK_STATUS_LABELS[s]}</Tag>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{ title: '内容', dataIndex: 'content', ellipsis: true },
|
||||||
|
{ title: '来源工单', dataIndex: 'supportTicketNo', width: 140, render: (v) => v || '—' },
|
||||||
|
{ title: '创建人', dataIndex: 'creatorName', width: 90 },
|
||||||
|
{ title: '创建时间', dataIndex: 'createdAt', width: 160, render: fmtTime },
|
||||||
|
{
|
||||||
|
title: '操作',
|
||||||
|
width: 120,
|
||||||
|
render: (_, row) => (
|
||||||
|
<Space>
|
||||||
|
<Button type="link" size="small" onClick={() => openEdit(row)}>
|
||||||
|
编辑
|
||||||
|
</Button>
|
||||||
|
<Popconfirm title="确认删除?" onConfirm={() => void remove(row.id)}>
|
||||||
|
<Button type="link" size="small" danger>
|
||||||
|
删除
|
||||||
|
</Button>
|
||||||
|
</Popconfirm>
|
||||||
|
</Space>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
|
||||||
|
<Typography.Title level={4} style={{ margin: 0 }}>
|
||||||
|
开发计划 · 任务列表
|
||||||
|
</Typography.Title>
|
||||||
|
<Space>
|
||||||
|
<Button disabled={!selectedRowKeys.length} onClick={openDispatch}>
|
||||||
|
评审
|
||||||
|
</Button>
|
||||||
|
<Button type="primary" onClick={openCreate}>
|
||||||
|
新建任务
|
||||||
|
</Button>
|
||||||
|
</Space>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Form
|
||||||
|
layout="inline"
|
||||||
|
style={{ marginBottom: 16 }}
|
||||||
|
onFinish={(v) => {
|
||||||
|
setFilters(v);
|
||||||
|
setPage(1);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Form.Item name="type" label="类型">
|
||||||
|
<Select allowClear style={{ width: 100 }} options={TYPE_OPTIONS} />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="status" label="状态">
|
||||||
|
<Select allowClear style={{ width: 100 }} options={STATUS_OPTIONS} />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="keyword" label="关键词">
|
||||||
|
<Input allowClear placeholder="任务号/内容" style={{ width: 160 }} />
|
||||||
|
</Form.Item>
|
||||||
|
<Button type="primary" htmlType="submit">
|
||||||
|
筛选
|
||||||
|
</Button>
|
||||||
|
</Form>
|
||||||
|
|
||||||
|
<Table
|
||||||
|
rowKey="id"
|
||||||
|
loading={loading}
|
||||||
|
columns={columns}
|
||||||
|
dataSource={data?.items ?? []}
|
||||||
|
rowSelection={{
|
||||||
|
selectedRowKeys,
|
||||||
|
onChange: (keys) => setSelectedRowKeys(keys as string[]),
|
||||||
|
}}
|
||||||
|
scroll={{ x: 1100 }}
|
||||||
|
pagination={{
|
||||||
|
current: page,
|
||||||
|
pageSize,
|
||||||
|
total: data?.total ?? 0,
|
||||||
|
showSizeChanger: true,
|
||||||
|
onChange: (p, ps) => {
|
||||||
|
setPage(p);
|
||||||
|
setPageSize(ps);
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Modal
|
||||||
|
title={editing ? '编辑任务' : '新建任务'}
|
||||||
|
open={modalOpen}
|
||||||
|
onCancel={() => setModalOpen(false)}
|
||||||
|
onOk={() => void save()}
|
||||||
|
confirmLoading={saving}
|
||||||
|
destroyOnClose
|
||||||
|
>
|
||||||
|
<Form form={form} layout="vertical">
|
||||||
|
<Form.Item name="content" label="任务内容" rules={[{ required: true }]}>
|
||||||
|
<Input.TextArea rows={4} maxLength={4000} showCount />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="type" label="类型" rules={[{ required: true }]}>
|
||||||
|
<Select options={TYPE_OPTIONS} />
|
||||||
|
</Form.Item>
|
||||||
|
{editing ? (
|
||||||
|
<Form.Item name="status" label="状态" rules={[{ required: true }]}>
|
||||||
|
<Select options={STATUS_OPTIONS} />
|
||||||
|
</Form.Item>
|
||||||
|
) : null}
|
||||||
|
</Form>
|
||||||
|
</Modal>
|
||||||
|
|
||||||
|
<Modal
|
||||||
|
title="评审派发"
|
||||||
|
open={dispatchOpen}
|
||||||
|
onCancel={() => setDispatchOpen(false)}
|
||||||
|
onOk={() => void submitDispatch()}
|
||||||
|
confirmLoading={dispatching}
|
||||||
|
destroyOnClose
|
||||||
|
>
|
||||||
|
<Typography.Paragraph type="secondary">
|
||||||
|
已选 {selectedRowKeys.length} 条任务,将通过「企微机器人 → 消息推送」中勾选「开发任务评审派发」的实例推送到开发群(@
|
||||||
|
userid 由各推送配置)。
|
||||||
|
</Typography.Paragraph>
|
||||||
|
<Form form={dispatchForm} layout="vertical">
|
||||||
|
<Form.Item name="supplement" label="补充说明">
|
||||||
|
<Input.TextArea rows={3} placeholder="默认任务说明;@ 成员由消息推送配置决定" />
|
||||||
|
</Form.Item>
|
||||||
|
</Form>
|
||||||
|
</Modal>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,241 @@
|
|||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import {
|
||||||
|
Button,
|
||||||
|
Form,
|
||||||
|
Input,
|
||||||
|
Modal,
|
||||||
|
Popconfirm,
|
||||||
|
Select,
|
||||||
|
Space,
|
||||||
|
Table,
|
||||||
|
Tag,
|
||||||
|
Typography,
|
||||||
|
message,
|
||||||
|
} from 'antd';
|
||||||
|
import type { ColumnsType } from 'antd/es/table';
|
||||||
|
import {
|
||||||
|
DEV_PLAN_VERSION_STATUS_LABELS,
|
||||||
|
type DevPlanTaskDto,
|
||||||
|
type DevPlanVersionDto,
|
||||||
|
type DevPlanVersionStatusDto,
|
||||||
|
} from '@dukang/shared-types';
|
||||||
|
import { request } from '../lib/api';
|
||||||
|
import { fmtTime } from '../lib/constants';
|
||||||
|
import { useAdminList } from '../lib/useAdminList';
|
||||||
|
|
||||||
|
|
||||||
|
const STATUS_OPTIONS = (Object.keys(DEV_PLAN_VERSION_STATUS_LABELS) as DevPlanVersionStatusDto[]).map(
|
||||||
|
(v) => ({ value: v, label: DEV_PLAN_VERSION_STATUS_LABELS[v] }),
|
||||||
|
);
|
||||||
|
|
||||||
|
const STATUS_COLOR: Record<DevPlanVersionStatusDto, string> = {
|
||||||
|
PENDING: 'default',
|
||||||
|
IN_PROGRESS: 'processing',
|
||||||
|
TESTING: 'purple',
|
||||||
|
RELEASED: 'green',
|
||||||
|
};
|
||||||
|
|
||||||
|
function formatDuration(minutes?: number | null) {
|
||||||
|
if (minutes == null) return '—';
|
||||||
|
if (minutes < 60) return `${minutes} 分钟`;
|
||||||
|
return `${Math.floor(minutes / 60)} 小时 ${minutes % 60} 分`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function DevPlanVersionsPage() {
|
||||||
|
const [filters, setFilters] = useState<Record<string, string>>({});
|
||||||
|
const [modalOpen, setModalOpen] = useState(false);
|
||||||
|
const [editing, setEditing] = useState<DevPlanVersionDto | null>(null);
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
const [allTasks, setAllTasks] = useState<DevPlanTaskDto[]>([]);
|
||||||
|
const [form] = Form.useForm();
|
||||||
|
|
||||||
|
const { data, loading, page, pageSize, setPage, setPageSize, reload } =
|
||||||
|
useAdminList<DevPlanVersionDto>('/admin/dev-plan/versions', () => {
|
||||||
|
const qs = new URLSearchParams();
|
||||||
|
if (filters.status) qs.set('status', filters.status);
|
||||||
|
return qs;
|
||||||
|
}, [filters]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void request<{ items: DevPlanTaskDto[] }>('/admin/dev-plan/tasks?page=1&pageSize=500')
|
||||||
|
.then((res) => setAllTasks(res.items ?? []))
|
||||||
|
.catch(() => setAllTasks([]));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
async function openEdit(row: DevPlanVersionDto) {
|
||||||
|
const detail = await request<DevPlanVersionDto>(`/admin/dev-plan/versions/${row.id}`);
|
||||||
|
setEditing(detail);
|
||||||
|
form.setFieldsValue({
|
||||||
|
versionNo: detail.versionNo,
|
||||||
|
content: detail.content ?? '',
|
||||||
|
status: detail.status,
|
||||||
|
taskIds: detail.taskIds ?? [],
|
||||||
|
});
|
||||||
|
setModalOpen(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
function openCreate() {
|
||||||
|
setEditing(null);
|
||||||
|
form.setFieldsValue({ versionNo: '', content: '', status: 'PENDING', taskIds: [] });
|
||||||
|
setModalOpen(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function save() {
|
||||||
|
const values = await form.validateFields();
|
||||||
|
setSaving(true);
|
||||||
|
try {
|
||||||
|
const body = {
|
||||||
|
versionNo: values.versionNo.trim(),
|
||||||
|
content: values.content?.trim() || undefined,
|
||||||
|
status: values.status,
|
||||||
|
taskIds: values.taskIds ?? [],
|
||||||
|
};
|
||||||
|
if (editing) {
|
||||||
|
await request(`/admin/dev-plan/versions/${editing.id}`, {
|
||||||
|
method: 'PUT',
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
message.success('已更新');
|
||||||
|
} else {
|
||||||
|
await request('/admin/dev-plan/versions', { method: 'POST', body: JSON.stringify(body) });
|
||||||
|
message.success('已创建');
|
||||||
|
}
|
||||||
|
setModalOpen(false);
|
||||||
|
reload();
|
||||||
|
} catch (e) {
|
||||||
|
message.error(e instanceof Error ? e.message : '保存失败');
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function remove(id: string) {
|
||||||
|
try {
|
||||||
|
await request(`/admin/dev-plan/versions/${id}`, { method: 'DELETE' });
|
||||||
|
message.success('已删除');
|
||||||
|
reload();
|
||||||
|
} catch (e) {
|
||||||
|
message.error(e instanceof Error ? e.message : '删除失败');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const columns: ColumnsType<DevPlanVersionDto> = [
|
||||||
|
{ title: '版本号', dataIndex: 'versionNo', width: 120 },
|
||||||
|
{
|
||||||
|
title: '状态',
|
||||||
|
dataIndex: 'status',
|
||||||
|
width: 100,
|
||||||
|
render: (s: DevPlanVersionStatusDto) => (
|
||||||
|
<Tag color={STATUS_COLOR[s]}>{DEV_PLAN_VERSION_STATUS_LABELS[s]}</Tag>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{ title: '内容', dataIndex: 'content', ellipsis: true, render: (v) => v || '—' },
|
||||||
|
{ title: '开发起始', dataIndex: 'devStartedAt', width: 160, render: (v) => (v ? fmtTime(v) : '—') },
|
||||||
|
{ title: '开发完成', dataIndex: 'devCompletedAt', width: 160, render: (v) => (v ? fmtTime(v) : '—') },
|
||||||
|
{ title: '上线时间', dataIndex: 'releasedAt', width: 160, render: (v) => (v ? fmtTime(v) : '—') },
|
||||||
|
{
|
||||||
|
title: '用时',
|
||||||
|
dataIndex: 'durationMinutes',
|
||||||
|
width: 100,
|
||||||
|
render: (v) => formatDuration(v),
|
||||||
|
},
|
||||||
|
{ title: '创建时间', dataIndex: 'createdAt', width: 160, render: fmtTime },
|
||||||
|
{
|
||||||
|
title: '操作',
|
||||||
|
width: 120,
|
||||||
|
render: (_, row) => (
|
||||||
|
<Space>
|
||||||
|
<Button type="link" size="small" onClick={() => void openEdit(row)}>
|
||||||
|
编辑
|
||||||
|
</Button>
|
||||||
|
<Popconfirm title="确认删除?(不删除关联任务)" onConfirm={() => void remove(row.id)}>
|
||||||
|
<Button type="link" size="small" danger>
|
||||||
|
删除
|
||||||
|
</Button>
|
||||||
|
</Popconfirm>
|
||||||
|
</Space>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
|
||||||
|
<Typography.Title level={4} style={{ margin: 0 }}>
|
||||||
|
开发计划 · 版本列表
|
||||||
|
</Typography.Title>
|
||||||
|
<Button type="primary" onClick={openCreate}>
|
||||||
|
新建版本
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Form
|
||||||
|
layout="inline"
|
||||||
|
style={{ marginBottom: 16 }}
|
||||||
|
onFinish={(v) => {
|
||||||
|
setFilters(v);
|
||||||
|
setPage(1);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Form.Item name="status" label="状态">
|
||||||
|
<Select allowClear style={{ width: 120 }} options={STATUS_OPTIONS} />
|
||||||
|
</Form.Item>
|
||||||
|
<Button type="primary" htmlType="submit">
|
||||||
|
筛选
|
||||||
|
</Button>
|
||||||
|
</Form>
|
||||||
|
|
||||||
|
<Table
|
||||||
|
rowKey="id"
|
||||||
|
loading={loading}
|
||||||
|
columns={columns}
|
||||||
|
dataSource={data?.items ?? []}
|
||||||
|
scroll={{ x: 1100 }}
|
||||||
|
pagination={{
|
||||||
|
current: page,
|
||||||
|
pageSize,
|
||||||
|
total: data?.total ?? 0,
|
||||||
|
showSizeChanger: true,
|
||||||
|
onChange: (p, ps) => {
|
||||||
|
setPage(p);
|
||||||
|
setPageSize(ps);
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Modal
|
||||||
|
title={editing ? '编辑版本' : '新建版本'}
|
||||||
|
open={modalOpen}
|
||||||
|
onCancel={() => setModalOpen(false)}
|
||||||
|
onOk={() => void save()}
|
||||||
|
confirmLoading={saving}
|
||||||
|
destroyOnClose
|
||||||
|
width={640}
|
||||||
|
>
|
||||||
|
<Form form={form} layout="vertical">
|
||||||
|
<Form.Item name="versionNo" label="版本号" rules={[{ required: true }]}>
|
||||||
|
<Input placeholder="如 v3.4.11" maxLength={32} />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="status" label="状态" rules={[{ required: true }]}>
|
||||||
|
<Select options={STATUS_OPTIONS} />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="content" label="内容">
|
||||||
|
<Input.TextArea placeholder="版本描述 / 更新日志" rows={3} maxLength={500} showCount />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="taskIds" label="关联任务">
|
||||||
|
<Select
|
||||||
|
mode="multiple"
|
||||||
|
allowClear
|
||||||
|
showSearch
|
||||||
|
optionFilterProp="label"
|
||||||
|
options={allTasks.map((t) => ({
|
||||||
|
value: t.id,
|
||||||
|
label: `${t.taskNo} · ${t.content.slice(0, 40)}`,
|
||||||
|
}))}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
</Form>
|
||||||
|
</Modal>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import { useState } from 'react';
|
|
||||||
import { Button, Form, Input, Table, Typography } from 'antd';
|
import { Button, Form, Input, Table, Typography } from 'antd';
|
||||||
import type { ColumnsType } from 'antd/es/table';
|
import type { ColumnsType } from 'antd/es/table';
|
||||||
import { useSearchParams } from 'react-router-dom';
|
import { useSearchParams } from 'react-router-dom';
|
||||||
|
|||||||
@@ -1,23 +1,39 @@
|
|||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
import {
|
import {
|
||||||
Button,
|
Button,
|
||||||
Descriptions,
|
Card,
|
||||||
Drawer,
|
Drawer,
|
||||||
Form,
|
Form,
|
||||||
Input,
|
Input,
|
||||||
Modal,
|
Modal,
|
||||||
|
Radio,
|
||||||
Select,
|
Select,
|
||||||
Space,
|
Space,
|
||||||
Table,
|
Table,
|
||||||
Tag,
|
Tag,
|
||||||
|
Timeline,
|
||||||
Typography,
|
Typography,
|
||||||
message,
|
message,
|
||||||
} from 'antd';
|
} from 'antd';
|
||||||
|
import {
|
||||||
|
CheckCircleFilled,
|
||||||
|
CloseCircleFilled,
|
||||||
|
ClockCircleFilled,
|
||||||
|
MinusCircleOutlined,
|
||||||
|
PlusOutlined,
|
||||||
|
SyncOutlined,
|
||||||
|
} from '@ant-design/icons';
|
||||||
import type { ColumnsType } from 'antd/es/table';
|
import type { ColumnsType } from 'antd/es/table';
|
||||||
import {
|
import {
|
||||||
|
DEV_PLAN_TASK_TYPE_LABELS,
|
||||||
SUPPORT_TICKET_STATUS_LABELS,
|
SUPPORT_TICKET_STATUS_LABELS,
|
||||||
SUPPORT_TICKET_TYPE_LABELS,
|
SUPPORT_TICKET_TYPE_LABELS,
|
||||||
|
mapSupportTicketTypeToDevPlanTask,
|
||||||
|
type BatchReviewPreviewItem,
|
||||||
|
type BatchReviewPreviewResponse,
|
||||||
|
type DevPlanTaskTypeDto,
|
||||||
type SupportTicketDto,
|
type SupportTicketDto,
|
||||||
|
type SupportTicketLinkedTaskDto,
|
||||||
type SupportTicketStatusDto,
|
type SupportTicketStatusDto,
|
||||||
type SupportTicketTypeDto,
|
type SupportTicketTypeDto,
|
||||||
} from '@dukang/shared-types';
|
} from '@dukang/shared-types';
|
||||||
@@ -41,30 +57,43 @@ const STATUS_OPTIONS = (Object.keys(SUPPORT_TICKET_STATUS_LABELS) as SupportTick
|
|||||||
(value) => ({ value, label: SUPPORT_TICKET_STATUS_LABELS[value] }),
|
(value) => ({ value, label: SUPPORT_TICKET_STATUS_LABELS[value] }),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const TASK_TYPE_OPTIONS = (Object.keys(DEV_PLAN_TASK_TYPE_LABELS) as DevPlanTaskTypeDto[]).map(
|
||||||
|
(v) => ({ value: v, label: DEV_PLAN_TASK_TYPE_LABELS[v] }),
|
||||||
|
);
|
||||||
|
|
||||||
|
type TicketRow = SupportTicketDto & { linkedTasks?: SupportTicketLinkedTaskDto[] };
|
||||||
|
|
||||||
export default function SupportTicketsPage() {
|
export default function SupportTicketsPage() {
|
||||||
const [profile, setProfile] = useState<HqProfile | null>(null);
|
const [profile, setProfile] = useState<HqProfile | null>(null);
|
||||||
const [filters, setFilters] = useState<Record<string, string>>({});
|
const [filters, setFilters] = useState<Record<string, string>>({});
|
||||||
const { data, loading, page, pageSize, setPage, setPageSize, reload } =
|
const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
|
||||||
useAdminList<SupportTicketDto>('/admin/support-tickets', () => {
|
const { data, loading, page, pageSize, setPage, setPageSize, reload } = useAdminList<TicketRow>(
|
||||||
|
'/admin/support-tickets',
|
||||||
|
() => {
|
||||||
const qs = new URLSearchParams();
|
const qs = new URLSearchParams();
|
||||||
if (filters.ticketType) qs.set('ticketType', filters.ticketType);
|
if (filters.ticketType) qs.set('ticketType', filters.ticketType);
|
||||||
if (filters.status) qs.set('status', filters.status);
|
if (filters.status) qs.set('status', filters.status);
|
||||||
return qs;
|
return qs;
|
||||||
}, [filters]);
|
},
|
||||||
|
[filters],
|
||||||
|
);
|
||||||
|
|
||||||
const [detail, setDetail] = useState<SupportTicketDto | null>(null);
|
const [detail, setDetail] = useState<TicketRow | null>(null);
|
||||||
const [drawerOpen, setDrawerOpen] = useState(false);
|
const [drawerOpen, setDrawerOpen] = useState(false);
|
||||||
const [createOpen, setCreateOpen] = useState(false);
|
const [createOpen, setCreateOpen] = useState(false);
|
||||||
const [creating, setCreating] = useState(false);
|
const [creating, setCreating] = useState(false);
|
||||||
const [acting, setActing] = useState(false);
|
const [acting, setActing] = useState(false);
|
||||||
const [rejectOpen, setRejectOpen] = useState(false);
|
const [reviewOpen, setReviewOpen] = useState(false);
|
||||||
const [createForm] = Form.useForm<{
|
const [createTasksOpen, setCreateTasksOpen] = useState(false);
|
||||||
ticketType: SupportTicketTypeDto;
|
const [batchPreviewOpen, setBatchPreviewOpen] = useState(false);
|
||||||
title: string;
|
const [batchPreview, setBatchPreview] = useState<BatchReviewPreviewItem[]>([]);
|
||||||
content?: string;
|
const [batchConfirming, setBatchConfirming] = useState(false);
|
||||||
remark?: string;
|
const [reviewDecision, setReviewDecision] = useState<'APPROVE' | 'REJECT'>('APPROVE');
|
||||||
}>();
|
|
||||||
const [rejectForm] = Form.useForm<{ rejectReason: string }>();
|
const [createForm] = Form.useForm();
|
||||||
|
const [reviewForm] = Form.useForm<{ decision: 'APPROVE' | 'REJECT'; rejectReason?: string; note?: string }>();
|
||||||
|
const [tasksForm] = Form.useForm<{ tasks: Array<{ content: string; type: DevPlanTaskTypeDto }> }>();
|
||||||
|
const [batchForm] = Form.useForm<{ items: BatchReviewPreviewItem[] }>();
|
||||||
|
|
||||||
const isSuperAdmin = profile?.adminRole === 'SUPER_ADMIN';
|
const isSuperAdmin = profile?.adminRole === 'SUPER_ADMIN';
|
||||||
|
|
||||||
@@ -73,7 +102,7 @@ export default function SupportTicketsPage() {
|
|||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
async function openDetail(id: string) {
|
async function openDetail(id: string) {
|
||||||
setDetail(await request<SupportTicketDto>(`/admin/support-tickets/${id}`));
|
setDetail(await request<TicketRow>(`/admin/support-tickets/${id}`));
|
||||||
setDrawerOpen(true);
|
setDrawerOpen(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -101,15 +130,61 @@ export default function SupportTicketsPage() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function approve() {
|
function openReview() {
|
||||||
if (!detail) return;
|
if (!detail) return;
|
||||||
|
reviewForm.setFieldsValue({ decision: 'APPROVE', note: '', rejectReason: '' });
|
||||||
|
setReviewDecision('APPROVE');
|
||||||
|
setReviewOpen(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function submitReviewStep1() {
|
||||||
|
const values = await reviewForm.validateFields();
|
||||||
|
if (values.decision === 'REJECT') {
|
||||||
|
if (!values.rejectReason?.trim()) {
|
||||||
|
message.error('请填写驳回理由');
|
||||||
|
return;
|
||||||
|
}
|
||||||
setActing(true);
|
setActing(true);
|
||||||
try {
|
try {
|
||||||
await request(`/admin/support-tickets/${detail.id}/approve`, {
|
await request(`/admin/support-tickets/${detail!.id}/review`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: JSON.stringify({}),
|
body: JSON.stringify({ decision: 'REJECT', rejectReason: values.rejectReason.trim() }),
|
||||||
});
|
});
|
||||||
message.success('评审通过,已进入开发');
|
message.success('已驳回');
|
||||||
|
setReviewOpen(false);
|
||||||
|
setDrawerOpen(false);
|
||||||
|
reload();
|
||||||
|
} catch (e) {
|
||||||
|
message.error(e instanceof Error ? e.message : '操作失败');
|
||||||
|
} finally {
|
||||||
|
setActing(false);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setReviewOpen(false);
|
||||||
|
const summary = [detail!.title, detail!.content].filter(Boolean).join('\n').slice(0, 500);
|
||||||
|
tasksForm.setFieldsValue({
|
||||||
|
tasks: [{ content: summary || detail!.title, type: mapSupportTicketTypeToDevPlanTask(detail!.ticketType) }],
|
||||||
|
});
|
||||||
|
setCreateTasksOpen(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function submitCreateTasks() {
|
||||||
|
const values = await tasksForm.validateFields();
|
||||||
|
const note = reviewForm.getFieldValue('note') as string | undefined;
|
||||||
|
setActing(true);
|
||||||
|
try {
|
||||||
|
await request(`/admin/support-tickets/${detail!.id}/review`, {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({
|
||||||
|
decision: 'APPROVE',
|
||||||
|
note: note?.trim() || undefined,
|
||||||
|
tasks: values.tasks.map((t) => ({ content: t.content.trim(), type: t.type })),
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
message.success('审批通过,已创建开发任务');
|
||||||
|
setCreateTasksOpen(false);
|
||||||
setDrawerOpen(false);
|
setDrawerOpen(false);
|
||||||
reload();
|
reload();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -119,27 +194,51 @@ export default function SupportTicketsPage() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function submitReject() {
|
async function startBatchPreview() {
|
||||||
if (!detail) return;
|
if (!selectedRowKeys.length) return;
|
||||||
const values = await rejectForm.validateFields();
|
|
||||||
setActing(true);
|
setActing(true);
|
||||||
try {
|
try {
|
||||||
await request(`/admin/support-tickets/${detail.id}/reject`, {
|
const res = await request<BatchReviewPreviewResponse>('/admin/support-tickets/batch-review/preview', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: JSON.stringify({ rejectReason: values.rejectReason.trim() }),
|
body: JSON.stringify({ ticketIds: selectedRowKeys }),
|
||||||
});
|
});
|
||||||
message.success('已驳回');
|
setBatchPreview(res.items);
|
||||||
setRejectOpen(false);
|
batchForm.setFieldsValue({ items: res.items });
|
||||||
rejectForm.resetFields();
|
setBatchPreviewOpen(true);
|
||||||
setDrawerOpen(false);
|
|
||||||
reload();
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
message.error(e instanceof Error ? e.message : '操作失败');
|
message.error(e instanceof Error ? e.message : 'AI 预审失败');
|
||||||
} finally {
|
} finally {
|
||||||
setActing(false);
|
setActing(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function submitBatchConfirm() {
|
||||||
|
const values = await batchForm.validateFields();
|
||||||
|
setBatchConfirming(true);
|
||||||
|
try {
|
||||||
|
await request('/admin/support-tickets/batch-review/confirm', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({
|
||||||
|
items: values.items.map((item) => ({
|
||||||
|
ticketId: item.ticketId,
|
||||||
|
decision: item.decision,
|
||||||
|
rejectReason: item.rejectReason,
|
||||||
|
note: item.note,
|
||||||
|
tasks: item.decision === 'APPROVE' ? item.suggestedTasks : undefined,
|
||||||
|
})),
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
message.success('批量审批已完成');
|
||||||
|
setBatchPreviewOpen(false);
|
||||||
|
setSelectedRowKeys([]);
|
||||||
|
reload();
|
||||||
|
} catch (e) {
|
||||||
|
message.error(e instanceof Error ? e.message : '批量确认失败');
|
||||||
|
} finally {
|
||||||
|
setBatchConfirming(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function startTesting() {
|
async function startTesting() {
|
||||||
if (!detail) return;
|
if (!detail) return;
|
||||||
setActing(true);
|
setActing(true);
|
||||||
@@ -176,7 +275,7 @@ export default function SupportTicketsPage() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const columns: ColumnsType<SupportTicketDto> = [
|
const columns: ColumnsType<TicketRow> = [
|
||||||
{ title: '工单号', dataIndex: 'ticketNo', width: 180 },
|
{ title: '工单号', dataIndex: 'ticketNo', width: 180 },
|
||||||
{
|
{
|
||||||
title: '类型',
|
title: '类型',
|
||||||
@@ -210,14 +309,9 @@ export default function SupportTicketsPage() {
|
|||||||
if (!detail) return null;
|
if (!detail) return null;
|
||||||
if (detail.status === 'PENDING_REVIEW' && isSuperAdmin) {
|
if (detail.status === 'PENDING_REVIEW' && isSuperAdmin) {
|
||||||
return (
|
return (
|
||||||
<Space>
|
<Button type="primary" loading={acting} onClick={openReview}>
|
||||||
<Button type="primary" loading={acting} onClick={() => void approve()}>
|
审批
|
||||||
评审通过
|
|
||||||
</Button>
|
</Button>
|
||||||
<Button danger loading={acting} onClick={() => setRejectOpen(true)}>
|
|
||||||
驳回
|
|
||||||
</Button>
|
|
||||||
</Space>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (detail.status === 'DEVELOPING') {
|
if (detail.status === 'DEVELOPING') {
|
||||||
@@ -250,9 +344,16 @@ export default function SupportTicketsPage() {
|
|||||||
<Typography.Title level={4} style={{ margin: 0 }}>
|
<Typography.Title level={4} style={{ margin: 0 }}>
|
||||||
技术支持
|
技术支持
|
||||||
</Typography.Title>
|
</Typography.Title>
|
||||||
|
<Space>
|
||||||
|
{isSuperAdmin ? (
|
||||||
|
<Button disabled={!selectedRowKeys.length} loading={acting} onClick={() => void startBatchPreview()}>
|
||||||
|
批量审核
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
<Button type="primary" onClick={() => setCreateOpen(true)}>
|
<Button type="primary" onClick={() => setCreateOpen(true)}>
|
||||||
创建工单
|
创建工单
|
||||||
</Button>
|
</Button>
|
||||||
|
</Space>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Form
|
<Form
|
||||||
@@ -280,6 +381,18 @@ export default function SupportTicketsPage() {
|
|||||||
columns={columns}
|
columns={columns}
|
||||||
dataSource={data?.items ?? []}
|
dataSource={data?.items ?? []}
|
||||||
scroll={{ x: 900 }}
|
scroll={{ x: 900 }}
|
||||||
|
rowSelection={
|
||||||
|
isSuperAdmin
|
||||||
|
? {
|
||||||
|
selectedRowKeys,
|
||||||
|
onChange: (keys, rows) => {
|
||||||
|
const pending = rows.filter((r) => r.status === 'PENDING_REVIEW').map((r) => String(r.id));
|
||||||
|
setSelectedRowKeys(pending.length === rows.length ? (keys as string[]) : pending);
|
||||||
|
},
|
||||||
|
getCheckboxProps: (row) => ({ disabled: row.status !== 'PENDING_REVIEW' }),
|
||||||
|
}
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
pagination={{
|
pagination={{
|
||||||
current: page,
|
current: page,
|
||||||
pageSize,
|
pageSize,
|
||||||
@@ -293,90 +406,393 @@ export default function SupportTicketsPage() {
|
|||||||
/>
|
/>
|
||||||
|
|
||||||
<Drawer
|
<Drawer
|
||||||
title="技术支持详情"
|
title={
|
||||||
width={520}
|
<Space>
|
||||||
|
<span>技术支持详情</span>
|
||||||
|
{detail && (
|
||||||
|
<>
|
||||||
|
<Typography.Text type="secondary" style={{ fontSize: 13 }}>
|
||||||
|
{detail.ticketNo}
|
||||||
|
</Typography.Text>
|
||||||
|
<Tag>{SUPPORT_TICKET_TYPE_LABELS[detail.ticketType] ?? detail.ticketType}</Tag>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Space>
|
||||||
|
}
|
||||||
|
width={680}
|
||||||
open={drawerOpen}
|
open={drawerOpen}
|
||||||
onClose={() => setDrawerOpen(false)}
|
onClose={() => setDrawerOpen(false)}
|
||||||
extra={drawerExtra}
|
extra={drawerExtra}
|
||||||
>
|
>
|
||||||
{detail && (
|
{detail && (
|
||||||
<Descriptions column={1} bordered size="small">
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
|
||||||
<Descriptions.Item label="工单号">{detail.ticketNo}</Descriptions.Item>
|
{/* 状态 + 标签 */}
|
||||||
<Descriptions.Item label="类型">
|
<Card
|
||||||
{SUPPORT_TICKET_TYPE_LABELS[detail.ticketType] ?? detail.ticketType}
|
size="small"
|
||||||
</Descriptions.Item>
|
styles={{ body: { padding: 16 } }}
|
||||||
<Descriptions.Item label="状态">
|
>
|
||||||
<Tag color={STATUS_COLOR[detail.status]}>
|
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
|
||||||
|
<Space size={12}>
|
||||||
|
<Tag
|
||||||
|
color={STATUS_COLOR[detail.status]}
|
||||||
|
style={{ fontSize: 14, padding: '2px 12px', lineHeight: '26px', borderRadius: 6 }}
|
||||||
|
>
|
||||||
{SUPPORT_TICKET_STATUS_LABELS[detail.status] ?? detail.status}
|
{SUPPORT_TICKET_STATUS_LABELS[detail.status] ?? detail.status}
|
||||||
</Tag>
|
</Tag>
|
||||||
</Descriptions.Item>
|
{detail.status === 'REJECTED' && (
|
||||||
<Descriptions.Item label="标题">{detail.title}</Descriptions.Item>
|
<Typography.Text type="danger">此工单已被驳回</Typography.Text>
|
||||||
<Descriptions.Item label="内容">
|
)}
|
||||||
<div style={{ whiteSpace: 'pre-wrap' }}>{detail.content || '—'}</div>
|
{detail.status === 'PASSED' && (
|
||||||
</Descriptions.Item>
|
<Typography.Text type="success">此工单已测试通过</Typography.Text>
|
||||||
<Descriptions.Item label="创建人">{detail.creatorName}</Descriptions.Item>
|
)}
|
||||||
<Descriptions.Item label="创建时间">{fmtTime(detail.createdAt)}</Descriptions.Item>
|
</Space>
|
||||||
<Descriptions.Item label="评审人">{detail.reviewerName || '—'}</Descriptions.Item>
|
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
|
||||||
<Descriptions.Item label="评审时间">
|
创建于 {fmtTime(detail.createdAt)}
|
||||||
{detail.reviewedAt ? fmtTime(detail.reviewedAt) : '—'}
|
</Typography.Text>
|
||||||
</Descriptions.Item>
|
</div>
|
||||||
<Descriptions.Item label="驳回理由">{detail.rejectReason || '—'}</Descriptions.Item>
|
</Card>
|
||||||
<Descriptions.Item label="备注">{detail.remark || '—'}</Descriptions.Item>
|
|
||||||
</Descriptions>
|
{/* 状态流转时间线 */}
|
||||||
|
<Card
|
||||||
|
size="small"
|
||||||
|
title={<Typography.Text strong style={{ fontSize: 14 }}>状态流转</Typography.Text>}
|
||||||
|
styles={{ body: { padding: '12px 16px' } }}
|
||||||
|
>
|
||||||
|
<Timeline
|
||||||
|
items={(() => {
|
||||||
|
const isRejected = detail.status === 'REJECTED';
|
||||||
|
const flowSteps: Array<{ key: SupportTicketStatusDto; time?: string | null; label: string }> = [
|
||||||
|
{ key: 'PENDING_REVIEW', label: '待评审', time: detail.createdAt },
|
||||||
|
...(!isRejected
|
||||||
|
? [
|
||||||
|
{ key: 'DEVELOPING' as SupportTicketStatusDto, label: '开发中', time: detail.reviewedAt },
|
||||||
|
{ key: 'TESTING' as SupportTicketStatusDto, label: '测试中', time: null },
|
||||||
|
{ key: 'PASSED' as SupportTicketStatusDto, label: '已通过', time: detail.completedAt },
|
||||||
|
]
|
||||||
|
: [{ key: 'REJECTED' as SupportTicketStatusDto, label: '已驳回', time: detail.reviewedAt }]),
|
||||||
|
];
|
||||||
|
|
||||||
|
const statusIdx = flowSteps.findIndex((s) => s.key === detail.status);
|
||||||
|
|
||||||
|
return flowSteps.map((step, idx) => {
|
||||||
|
const isCurrent = step.key === detail.status;
|
||||||
|
const isPast = !isRejected
|
||||||
|
? idx < statusIdx
|
||||||
|
: step.key === 'PENDING_REVIEW' && statusIdx >= 1;
|
||||||
|
const isRejectedStep = step.key === 'REJECTED';
|
||||||
|
|
||||||
|
let dot: React.ReactNode;
|
||||||
|
let color: string | undefined;
|
||||||
|
if (isRejectedStep) {
|
||||||
|
dot = <CloseCircleFilled style={{ color: '#ff4d4f', fontSize: 14 }} />;
|
||||||
|
color = 'red';
|
||||||
|
} else if (isCurrent) {
|
||||||
|
if (step.key === 'TESTING') {
|
||||||
|
dot = <SyncOutlined style={{ color: '#722ed1', fontSize: 14 }} />;
|
||||||
|
} else {
|
||||||
|
dot = <ClockCircleFilled style={{ color: STATUS_COLOR[step.key], fontSize: 14 }} />;
|
||||||
|
}
|
||||||
|
} else if (isPast) {
|
||||||
|
dot = <CheckCircleFilled style={{ color: '#52c41a', fontSize: 14 }} />;
|
||||||
|
color = 'green';
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
dot,
|
||||||
|
color,
|
||||||
|
children: (
|
||||||
|
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
||||||
|
<span
|
||||||
|
style={{
|
||||||
|
fontWeight: isCurrent ? 600 : 400,
|
||||||
|
color: isPast || isCurrent ? undefined : '#bbb',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{step.label}
|
||||||
|
</span>
|
||||||
|
{step.time && (
|
||||||
|
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
|
||||||
|
{fmtTime(step.time)}
|
||||||
|
</Typography.Text>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
})()}
|
||||||
|
/>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* 标题 & 内容 */}
|
||||||
|
<Card
|
||||||
|
size="small"
|
||||||
|
styles={{ body: { padding: 16 } }}
|
||||||
|
>
|
||||||
|
<Typography.Title level={5} style={{ marginTop: 0, marginBottom: 12 }}>
|
||||||
|
{detail.title}
|
||||||
|
</Typography.Title>
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
background: '#fafafa',
|
||||||
|
border: '1px solid #f0f0f0',
|
||||||
|
borderRadius: 8,
|
||||||
|
padding: '12px 16px',
|
||||||
|
whiteSpace: 'pre-wrap',
|
||||||
|
fontSize: 14,
|
||||||
|
lineHeight: 1.8,
|
||||||
|
color: '#333',
|
||||||
|
minHeight: detail.content ? undefined : 40,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{detail.content || (
|
||||||
|
<Typography.Text type="secondary">暂无详细说明</Typography.Text>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* 基本信息 */}
|
||||||
|
<Card
|
||||||
|
size="small"
|
||||||
|
title={<Typography.Text strong style={{ fontSize: 14 }}>基本信息</Typography.Text>}
|
||||||
|
styles={{ body: { padding: '12px 16px' } }}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
display: 'grid',
|
||||||
|
gridTemplateColumns: '1fr 1fr',
|
||||||
|
gap: '12px 24px',
|
||||||
|
fontSize: 13,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<Typography.Text type="secondary">创建人</Typography.Text>
|
||||||
|
<div style={{ marginTop: 2 }}>{detail.creatorName}</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<Typography.Text type="secondary">创建时间</Typography.Text>
|
||||||
|
<div style={{ marginTop: 2 }}>{fmtTime(detail.createdAt)}</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<Typography.Text type="secondary">评审人</Typography.Text>
|
||||||
|
<div style={{ marginTop: 2 }}>{detail.reviewerName || '—'}</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<Typography.Text type="secondary">评审时间</Typography.Text>
|
||||||
|
<div style={{ marginTop: 2 }}>{detail.reviewedAt ? fmtTime(detail.reviewedAt) : '—'}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{detail.rejectReason && (
|
||||||
|
<div style={{ marginTop: 16 }}>
|
||||||
|
<Typography.Text type="danger" strong style={{ fontSize: 13 }}>
|
||||||
|
驳回理由
|
||||||
|
</Typography.Text>
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
marginTop: 6,
|
||||||
|
background: '#fff2f0',
|
||||||
|
border: '1px solid #ffccc7',
|
||||||
|
borderRadius: 6,
|
||||||
|
padding: '10px 14px',
|
||||||
|
fontSize: 13,
|
||||||
|
color: '#a8071a',
|
||||||
|
lineHeight: 1.7,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{detail.rejectReason}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{detail.remark && (
|
||||||
|
<div style={{ marginTop: 16 }}>
|
||||||
|
<Typography.Text type="secondary" style={{ fontSize: 13 }}>
|
||||||
|
备注
|
||||||
|
</Typography.Text>
|
||||||
|
<div style={{ marginTop: 4, color: '#555', fontSize: 13, lineHeight: 1.6 }}>
|
||||||
|
{detail.remark}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* 关联开发任务 */}
|
||||||
|
{detail.linkedTasks?.length ? (
|
||||||
|
<Card
|
||||||
|
size="small"
|
||||||
|
title={
|
||||||
|
<Typography.Text strong style={{ fontSize: 14 }}>
|
||||||
|
关联开发任务
|
||||||
|
<Typography.Text type="secondary" style={{ marginLeft: 8, fontWeight: 400 }}>
|
||||||
|
{detail.linkedTasks.length}
|
||||||
|
</Typography.Text>
|
||||||
|
</Typography.Text>
|
||||||
|
}
|
||||||
|
styles={{ body: { padding: 0 } }}
|
||||||
|
>
|
||||||
|
{detail.linkedTasks.map((t, idx) => (
|
||||||
|
<div
|
||||||
|
key={t.id}
|
||||||
|
style={{
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
padding: '10px 16px',
|
||||||
|
borderBottom: idx < detail.linkedTasks!.length - 1 ? '1px solid #f0f0f0' : 'none',
|
||||||
|
gap: 12,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Typography.Text
|
||||||
|
code
|
||||||
|
style={{ fontSize: 12, flexShrink: 0 }}
|
||||||
|
>
|
||||||
|
{t.taskNo}
|
||||||
|
</Typography.Text>
|
||||||
|
<Typography.Text
|
||||||
|
style={{ flex: 1, fontSize: 13 }}
|
||||||
|
ellipsis={{ tooltip: t.content }}
|
||||||
|
>
|
||||||
|
{t.content}
|
||||||
|
</Typography.Text>
|
||||||
|
<Tag style={{ margin: 0, flexShrink: 0 }}>{t.status}</Tag>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</Card>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
</Drawer>
|
</Drawer>
|
||||||
|
|
||||||
<Modal
|
<Modal title="创建技术支持工单" open={createOpen} onCancel={() => setCreateOpen(false)} onOk={() => void submitCreate()} confirmLoading={creating} destroyOnClose okText="提交">
|
||||||
title="创建技术支持工单"
|
|
||||||
open={createOpen}
|
|
||||||
onCancel={() => setCreateOpen(false)}
|
|
||||||
onOk={() => void submitCreate()}
|
|
||||||
confirmLoading={creating}
|
|
||||||
destroyOnClose
|
|
||||||
okText="提交"
|
|
||||||
>
|
|
||||||
<Form form={createForm} layout="vertical" initialValues={{ ticketType: 'BUG' }}>
|
<Form form={createForm} layout="vertical" initialValues={{ ticketType: 'BUG' }}>
|
||||||
<Form.Item
|
<Form.Item name="ticketType" label="类型" rules={[{ required: true }]}>
|
||||||
name="ticketType"
|
|
||||||
label="类型"
|
|
||||||
rules={[{ required: true, message: '请选择类型' }]}
|
|
||||||
>
|
|
||||||
<Select options={TYPE_OPTIONS} />
|
<Select options={TYPE_OPTIONS} />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
<Form.Item
|
<Form.Item name="title" label="标题" rules={[{ required: true }]}>
|
||||||
name="title"
|
<Input maxLength={128} showCount />
|
||||||
label="标题"
|
|
||||||
rules={[{ required: true, message: '请填写标题' }]}
|
|
||||||
>
|
|
||||||
<Input placeholder="简要描述问题或建议" maxLength={128} showCount />
|
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
<Form.Item name="content" label="详细说明">
|
<Form.Item name="content" label="详细说明">
|
||||||
<Input.TextArea rows={5} placeholder="复现步骤、期望结果等" maxLength={4000} showCount />
|
<Input.TextArea rows={5} maxLength={4000} showCount />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
<Form.Item name="remark" label="备注">
|
<Form.Item name="remark" label="备注">
|
||||||
<Input.TextArea rows={2} placeholder="可选" maxLength={512} showCount />
|
<Input.TextArea rows={2} maxLength={512} showCount />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
</Form>
|
</Form>
|
||||||
</Modal>
|
</Modal>
|
||||||
|
|
||||||
<Modal
|
<Modal title="审批" open={reviewOpen} onCancel={() => setReviewOpen(false)} onOk={() => void submitReviewStep1()} confirmLoading={acting} destroyOnClose>
|
||||||
title="驳回技术支持工单"
|
<Form form={reviewForm} layout="vertical">
|
||||||
open={rejectOpen}
|
<Form.Item name="decision" label="审批结果" rules={[{ required: true }]}>
|
||||||
onCancel={() => setRejectOpen(false)}
|
<Radio.Group
|
||||||
onOk={() => void submitReject()}
|
onChange={(e) => setReviewDecision(e.target.value as 'APPROVE' | 'REJECT')}
|
||||||
confirmLoading={acting}
|
options={[
|
||||||
destroyOnClose
|
{ value: 'APPROVE', label: '通过' },
|
||||||
okText="确认驳回"
|
{ value: 'REJECT', label: '驳回' },
|
||||||
okButtonProps={{ danger: true }}
|
]}
|
||||||
>
|
/>
|
||||||
<Form form={rejectForm} layout="vertical">
|
|
||||||
<Form.Item
|
|
||||||
name="rejectReason"
|
|
||||||
label="驳回理由"
|
|
||||||
rules={[{ required: true, message: '请填写驳回理由' }]}
|
|
||||||
>
|
|
||||||
<Input.TextArea rows={4} placeholder="必填" maxLength={512} showCount />
|
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
|
{reviewDecision === 'REJECT' ? (
|
||||||
|
<Form.Item name="rejectReason" label="驳回理由" rules={[{ required: true }]}>
|
||||||
|
<Input.TextArea rows={3} maxLength={512} showCount />
|
||||||
|
</Form.Item>
|
||||||
|
) : (
|
||||||
|
<Form.Item name="note" label="附注">
|
||||||
|
<Input.TextArea rows={2} maxLength={512} showCount />
|
||||||
|
</Form.Item>
|
||||||
|
)}
|
||||||
|
</Form>
|
||||||
|
</Modal>
|
||||||
|
|
||||||
|
<Modal title="创建开发任务" open={createTasksOpen} onCancel={() => setCreateTasksOpen(false)} onOk={() => void submitCreateTasks()} confirmLoading={acting} destroyOnClose width={640}>
|
||||||
|
<Typography.Paragraph type="secondary">审批通过需至少创建 1 条开发计划任务。</Typography.Paragraph>
|
||||||
|
<Form form={tasksForm} layout="vertical">
|
||||||
|
<Form.List name="tasks">
|
||||||
|
{(fields, { add, remove }) => (
|
||||||
|
<>
|
||||||
|
{fields.map(({ key, name, ...rest }) => (
|
||||||
|
<Space key={key} align="baseline" style={{ display: 'flex', marginBottom: 8 }}>
|
||||||
|
<Form.Item {...rest} name={[name, 'content']} rules={[{ required: true }]} style={{ flex: 1 }}>
|
||||||
|
<Input.TextArea rows={2} placeholder="任务内容" />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item {...rest} name={[name, 'type']} rules={[{ required: true }]}>
|
||||||
|
<Select style={{ width: 100 }} options={TASK_TYPE_OPTIONS} />
|
||||||
|
</Form.Item>
|
||||||
|
{fields.length > 1 ? (
|
||||||
|
<MinusCircleOutlined onClick={() => remove(name)} />
|
||||||
|
) : null}
|
||||||
|
</Space>
|
||||||
|
))}
|
||||||
|
<Button type="dashed" onClick={() => add({ content: '', type: 'BUG' })} block icon={<PlusOutlined />}>
|
||||||
|
添加任务
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Form.List>
|
||||||
|
</Form>
|
||||||
|
</Modal>
|
||||||
|
|
||||||
|
<Modal
|
||||||
|
title="批量 AI 审核确认"
|
||||||
|
open={batchPreviewOpen}
|
||||||
|
onCancel={() => setBatchPreviewOpen(false)}
|
||||||
|
onOk={() => void submitBatchConfirm()}
|
||||||
|
confirmLoading={batchConfirming}
|
||||||
|
width={900}
|
||||||
|
destroyOnClose
|
||||||
|
>
|
||||||
|
<Form form={batchForm} layout="vertical">
|
||||||
|
<Form.List name="items">
|
||||||
|
{(fields) => (
|
||||||
|
<>
|
||||||
|
{fields.map(({ key, name }) => {
|
||||||
|
const item = batchPreview[name];
|
||||||
|
if (!item) return null;
|
||||||
|
return (
|
||||||
|
<div key={key} style={{ marginBottom: 24, borderBottom: '1px solid #f0f0f0', paddingBottom: 16 }}>
|
||||||
|
<Typography.Text strong>
|
||||||
|
{item.ticketNo} · {item.title}
|
||||||
|
</Typography.Text>
|
||||||
|
<Form.Item name={[name, 'decision']} label="AI 建议">
|
||||||
|
<Radio.Group
|
||||||
|
options={[
|
||||||
|
{ value: 'APPROVE', label: '通过' },
|
||||||
|
{ value: 'REJECT', label: '驳回' },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name={[name, 'rejectReason']} label="驳回理由">
|
||||||
|
<Input.TextArea rows={2} />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name={[name, 'note']} label="附注">
|
||||||
|
<Input.TextArea rows={2} />
|
||||||
|
</Form.Item>
|
||||||
|
<Typography.Paragraph type="secondary" style={{ whiteSpace: 'pre-wrap' }}>
|
||||||
|
{item.reportMarkdown}
|
||||||
|
</Typography.Paragraph>
|
||||||
|
<Form.List name={[name, 'suggestedTasks']}>
|
||||||
|
{(taskFields, { add, remove }) => (
|
||||||
|
<>
|
||||||
|
<Typography.Text>建议任务</Typography.Text>
|
||||||
|
{taskFields.map(({ key: tk, name: tn, ...rest }) => (
|
||||||
|
<Space key={tk} align="baseline" style={{ display: 'flex' }}>
|
||||||
|
<Form.Item {...rest} name={[tn, 'content']} rules={[{ required: true }]}>
|
||||||
|
<Input.TextArea rows={2} style={{ width: 400 }} />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item {...rest} name={[tn, 'type']} rules={[{ required: true }]}>
|
||||||
|
<Select style={{ width: 100 }} options={TASK_TYPE_OPTIONS} />
|
||||||
|
</Form.Item>
|
||||||
|
<MinusCircleOutlined onClick={() => remove(tn)} />
|
||||||
|
</Space>
|
||||||
|
))}
|
||||||
|
<Button type="dashed" size="small" onClick={() => add({ content: '', type: 'BUG' })}>
|
||||||
|
添加任务
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Form.List>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Form.List>
|
||||||
</Form>
|
</Form>
|
||||||
</Modal>
|
</Modal>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -61,34 +61,6 @@ function MockSmsCodePanel({ codes, loading }: { codes: MockSmsCodeItem[]; loadin
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function WecomAlertTestButton() {
|
|
||||||
const [testing, setTesting] = useState(false);
|
|
||||||
async function onTest() {
|
|
||||||
setTesting(true);
|
|
||||||
try {
|
|
||||||
const res = await request<{ ok: boolean; message: string }>(
|
|
||||||
'/admin/system-config/wecom-alert/test',
|
|
||||||
{ method: 'POST', body: '{}' },
|
|
||||||
);
|
|
||||||
message.success(res.message || '已发送测试告警');
|
|
||||||
} catch (e) {
|
|
||||||
message.error(e instanceof Error ? e.message : '发送失败');
|
|
||||||
} finally {
|
|
||||||
setTesting(false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return (
|
|
||||||
<div style={{ marginTop: -8, marginBottom: 16 }}>
|
|
||||||
<Button size="small" loading={testing} onClick={() => void onTest()}>
|
|
||||||
发送测试告警
|
|
||||||
</Button>
|
|
||||||
<Typography.Text type="secondary" style={{ marginLeft: 8, fontSize: 12 }}>
|
|
||||||
需已配置 WECOM_ALERT_WEBHOOK_URL 并开启上方开关
|
|
||||||
</Typography.Text>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function renderField(
|
function renderField(
|
||||||
field: SystemConfigFieldMeta,
|
field: SystemConfigFieldMeta,
|
||||||
configuredSecrets: string[],
|
configuredSecrets: string[],
|
||||||
@@ -291,8 +263,6 @@ export default function SystemSettingsPage() {
|
|||||||
meta.configuredSecrets,
|
meta.configuredSecrets,
|
||||||
f.key === 'MOCK_SMS' && mockSmsEnabled ? (
|
f.key === 'MOCK_SMS' && mockSmsEnabled ? (
|
||||||
<MockSmsCodePanel codes={meta.mockSmsCodes ?? []} loading={loading} />
|
<MockSmsCodePanel codes={meta.mockSmsCodes ?? []} loading={loading} />
|
||||||
) : f.key === 'WECOM_ALERT_ENABLED' ? (
|
|
||||||
<WecomAlertTestButton />
|
|
||||||
) : undefined,
|
) : undefined,
|
||||||
),
|
),
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -0,0 +1,129 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
|
import { Button, Descriptions, Drawer, Form, Input, Select, Space, Table, Tag, Typography } from 'antd';
|
||||||
|
import type { ColumnsType } from 'antd/es/table';
|
||||||
|
import { useAdminList } from '../lib/useAdminList';
|
||||||
|
import { request } from '../lib/api';
|
||||||
|
import { fmtTime } from '../lib/constants';
|
||||||
|
import type { WecomBotLogDto } from '@dukang/shared-types';
|
||||||
|
|
||||||
|
export default function WecomBotLogsPage() {
|
||||||
|
const [form] = Form.useForm();
|
||||||
|
const [filters, setFilters] = useState<Record<string, string>>({});
|
||||||
|
const [detail, setDetail] = useState<WecomBotLogDto | null>(null);
|
||||||
|
|
||||||
|
const { data, loading, page, pageSize, setPage, setPageSize } = useAdminList<WecomBotLogDto>(
|
||||||
|
'/admin/logs/wecom-bots',
|
||||||
|
() => {
|
||||||
|
const qs = new URLSearchParams();
|
||||||
|
if (filters.botId) qs.set('botId', filters.botId);
|
||||||
|
if (filters.wecomUserId) qs.set('wecomUserId', filters.wecomUserId);
|
||||||
|
if (filters.action) qs.set('action', filters.action);
|
||||||
|
if (filters.success) qs.set('success', filters.success);
|
||||||
|
return qs;
|
||||||
|
},
|
||||||
|
[filters],
|
||||||
|
);
|
||||||
|
|
||||||
|
const columns: ColumnsType<WecomBotLogDto> = [
|
||||||
|
{ title: '时间', dataIndex: 'createdAt', width: 160, render: fmtTime },
|
||||||
|
{ title: '机器人', dataIndex: 'botName', width: 120, ellipsis: true, render: (v, r) => v || r.botKey || '—' },
|
||||||
|
{ title: '企微用户', dataIndex: 'wecomUserId', width: 120, ellipsis: true },
|
||||||
|
{ title: '动作', dataIndex: 'action', width: 160, ellipsis: true },
|
||||||
|
{ title: '权限', dataIndex: 'permission', width: 140, ellipsis: true, render: (v) => v || '—' },
|
||||||
|
{
|
||||||
|
title: '结果',
|
||||||
|
dataIndex: 'success',
|
||||||
|
width: 80,
|
||||||
|
render: (v: boolean) => <Tag color={v ? 'green' : 'red'}>{v ? '成功' : '失败'}</Tag>,
|
||||||
|
},
|
||||||
|
{ title: '耗时(ms)', dataIndex: 'latencyMs', width: 90, render: (v) => v ?? '—' },
|
||||||
|
{ title: '输入摘要', dataIndex: 'inputSummary', ellipsis: true },
|
||||||
|
{
|
||||||
|
title: '操作',
|
||||||
|
width: 80,
|
||||||
|
render: (_, row) => (
|
||||||
|
<Button type="link" size="small" onClick={() => setDetail(row)}>
|
||||||
|
详情
|
||||||
|
</Button>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<Typography.Title level={4}>企微机器人日志</Typography.Title>
|
||||||
|
<Typography.Paragraph type="secondary">
|
||||||
|
记录机器人在企微内的查询与审批操作,含权限点、耗时与成败。
|
||||||
|
</Typography.Paragraph>
|
||||||
|
|
||||||
|
<Form
|
||||||
|
form={form}
|
||||||
|
layout="inline"
|
||||||
|
style={{ marginBottom: 16 }}
|
||||||
|
onFinish={(v) => {
|
||||||
|
setFilters(v);
|
||||||
|
setPage(1);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Form.Item name="botId" label="机器人 ID">
|
||||||
|
<Input allowClear placeholder="wecom_bot.id" style={{ width: 140 }} />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="wecomUserId" label="企微 userid">
|
||||||
|
<Input allowClear placeholder="userid" style={{ width: 140 }} />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="action" label="动作">
|
||||||
|
<Input allowClear placeholder="order.read" style={{ width: 140 }} />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="success" label="结果">
|
||||||
|
<Select
|
||||||
|
allowClear
|
||||||
|
style={{ width: 100 }}
|
||||||
|
options={[
|
||||||
|
{ value: 'true', label: '成功' },
|
||||||
|
{ value: 'false', label: '失败' },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item>
|
||||||
|
<Button type="primary" htmlType="submit">
|
||||||
|
查询
|
||||||
|
</Button>
|
||||||
|
</Form.Item>
|
||||||
|
</Form>
|
||||||
|
|
||||||
|
<Table
|
||||||
|
rowKey="id"
|
||||||
|
loading={loading}
|
||||||
|
columns={columns}
|
||||||
|
dataSource={data?.items ?? []}
|
||||||
|
scroll={{ x: 1100 }}
|
||||||
|
pagination={{
|
||||||
|
current: page,
|
||||||
|
pageSize,
|
||||||
|
total: data?.total ?? 0,
|
||||||
|
showSizeChanger: true,
|
||||||
|
onChange: (p, ps) => {
|
||||||
|
setPage(p);
|
||||||
|
setPageSize(ps);
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Drawer title="日志详情" width={480} open={!!detail} onClose={() => setDetail(null)}>
|
||||||
|
{detail && (
|
||||||
|
<Descriptions column={1} size="small" bordered>
|
||||||
|
<Descriptions.Item label="时间">{fmtTime(detail.createdAt)}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="机器人">{detail.botName || detail.botKey || '—'}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="企微用户">{detail.wecomUserId}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="动作">{detail.action}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="权限">{detail.permission || '—'}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="输入摘要">{detail.inputSummary || '—'}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="结果">{detail.success ? '成功' : '失败'}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="错误">{detail.errorMessage || '—'}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="耗时">{detail.latencyMs != null ? `${detail.latencyMs} ms` : '—'}</Descriptions.Item>
|
||||||
|
</Descriptions>
|
||||||
|
)}
|
||||||
|
</Drawer>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -20,13 +20,14 @@ import {
|
|||||||
} from 'antd';
|
} from 'antd';
|
||||||
import type { ColumnsType } from 'antd/es/table';
|
import type { ColumnsType } from 'antd/es/table';
|
||||||
import {
|
import {
|
||||||
WECOM_BOT_PERMISSIONS,
|
WECOM_BOT_PERMISSION_GROUPS,
|
||||||
WECOM_BOT_PERMISSION_LABELS,
|
WECOM_BOT_PERMISSION_LABELS,
|
||||||
WECOM_BOT_ROLE_DEFAULT_PERMISSIONS,
|
WECOM_BOT_ROLE_DEFAULT_PERMISSIONS,
|
||||||
WECOM_BOT_ROLE_LABELS,
|
WECOM_BOT_ROLE_LABELS,
|
||||||
WECOM_BOT_ROLES,
|
WECOM_BOT_ROLES,
|
||||||
type LlmApiConfigOptionDto,
|
type LlmApiConfigOptionDto,
|
||||||
type KnowledgeBaseOptionDto,
|
type KnowledgeBaseOptionDto,
|
||||||
|
type WecomAibotRuntimeDto,
|
||||||
type WecomBotDto,
|
type WecomBotDto,
|
||||||
type WecomBotPermission,
|
type WecomBotPermission,
|
||||||
type WecomBotRole,
|
type WecomBotRole,
|
||||||
@@ -36,17 +37,6 @@ import { fmtTime } from '../lib/constants';
|
|||||||
import { useAdminList } from '../lib/useAdminList';
|
import { useAdminList } from '../lib/useAdminList';
|
||||||
import OssUpload from '../components/OssUpload';
|
import OssUpload from '../components/OssUpload';
|
||||||
|
|
||||||
type ListRes = {
|
|
||||||
items: WecomBotDto[];
|
|
||||||
total: number;
|
|
||||||
page: number;
|
|
||||||
pageSize: number;
|
|
||||||
runtime?: {
|
|
||||||
masterEnabled: boolean;
|
|
||||||
bots: Array<{ id: string; connected: boolean; lastError: string | null }>;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
type FormValues = {
|
type FormValues = {
|
||||||
name: string;
|
name: string;
|
||||||
role: WecomBotRole;
|
role: WecomBotRole;
|
||||||
@@ -55,6 +45,7 @@ type FormValues = {
|
|||||||
avatarUrl?: string;
|
avatarUrl?: string;
|
||||||
welcome?: string;
|
welcome?: string;
|
||||||
permissions: WecomBotPermission[];
|
permissions: WecomBotPermission[];
|
||||||
|
reviewSuperAdminWecomUserIds?: string;
|
||||||
aiEnabled: boolean;
|
aiEnabled: boolean;
|
||||||
llmConfigId?: string | null;
|
llmConfigId?: string | null;
|
||||||
knowledgeBaseId?: string | null;
|
knowledgeBaseId?: string | null;
|
||||||
@@ -62,18 +53,70 @@ type FormValues = {
|
|||||||
sortOrder: number;
|
sortOrder: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
function parseUserIdLines(text?: string): string[] {
|
||||||
|
if (!text?.trim()) return [];
|
||||||
|
return [...new Set(text.split(/[,,\s\n]+/).map((s) => s.trim()).filter(Boolean))];
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatUserIdLines(ids?: string[]): string {
|
||||||
|
return (ids ?? []).join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
function mapDtoToForm(row: WecomBotDto): FormValues {
|
||||||
|
return {
|
||||||
|
name: row.name,
|
||||||
|
role: row.role,
|
||||||
|
botId: row.botId,
|
||||||
|
secret: '',
|
||||||
|
avatarUrl: row.avatarUrl || '',
|
||||||
|
welcome: row.welcome || '',
|
||||||
|
permissions: [...row.permissions],
|
||||||
|
reviewSuperAdminWecomUserIds: formatUserIdLines(row.reviewSuperAdminWecomUserIds),
|
||||||
|
aiEnabled: row.aiEnabled,
|
||||||
|
llmConfigId: row.llmConfigId,
|
||||||
|
knowledgeBaseId: row.knowledgeBaseId,
|
||||||
|
enabled: row.enabled,
|
||||||
|
sortOrder: row.sortOrder,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function samePermissionSet(a: WecomBotPermission[], b: WecomBotPermission[]): boolean {
|
||||||
|
if (a.length !== b.length) return false;
|
||||||
|
const setB = new Set(b);
|
||||||
|
return a.every((p) => setB.has(p));
|
||||||
|
}
|
||||||
|
|
||||||
|
const CREATE_DEFAULTS: FormValues = {
|
||||||
|
name: '',
|
||||||
|
role: 'CUSTOMER_SERVICE',
|
||||||
|
botId: '',
|
||||||
|
secret: '',
|
||||||
|
avatarUrl: '',
|
||||||
|
welcome: '',
|
||||||
|
permissions: [...WECOM_BOT_ROLE_DEFAULT_PERMISSIONS.CUSTOMER_SERVICE],
|
||||||
|
reviewSuperAdminWecomUserIds: '',
|
||||||
|
aiEnabled: false,
|
||||||
|
llmConfigId: null,
|
||||||
|
knowledgeBaseId: null,
|
||||||
|
enabled: true,
|
||||||
|
sortOrder: 0,
|
||||||
|
};
|
||||||
|
|
||||||
export default function WecomBotsPage() {
|
export default function WecomBotsPage() {
|
||||||
const [filterForm] = Form.useForm();
|
const [filterForm] = Form.useForm();
|
||||||
const [form] = Form.useForm<FormValues>();
|
const [form] = Form.useForm<FormValues>();
|
||||||
const [filters, setFilters] = useState<Record<string, string>>({});
|
const [filters, setFilters] = useState<Record<string, string>>({});
|
||||||
const [modalOpen, setModalOpen] = useState(false);
|
const [modalOpen, setModalOpen] = useState(false);
|
||||||
const [editing, setEditing] = useState<WecomBotDto | null>(null);
|
const [editing, setEditing] = useState<WecomBotDto | null>(null);
|
||||||
|
const [formInitial, setFormInitial] = useState<FormValues | null>(null);
|
||||||
|
const [formReady, setFormReady] = useState(false);
|
||||||
const [saving, setSaving] = useState(false);
|
const [saving, setSaving] = useState(false);
|
||||||
const [detail, setDetail] = useState<WecomBotDto | null>(null);
|
const [detail, setDetail] = useState<WecomBotDto | null>(null);
|
||||||
const [runtime, setRuntime] = useState<ListRes['runtime']>();
|
const [runtime, setRuntime] = useState<WecomAibotRuntimeDto>();
|
||||||
const [llmOptions, setLlmOptions] = useState<LlmApiConfigOptionDto[]>([]);
|
const [llmOptions, setLlmOptions] = useState<LlmApiConfigOptionDto[]>([]);
|
||||||
const [kbOptions, setKbOptions] = useState<KnowledgeBaseOptionDto[]>([]);
|
const [kbOptions, setKbOptions] = useState<KnowledgeBaseOptionDto[]>([]);
|
||||||
const roleWatch = Form.useWatch('role', form);
|
const roleWatch = Form.useWatch('role', form);
|
||||||
|
const permissionsWatch = Form.useWatch('permissions', form) as WecomBotPermission[] | undefined;
|
||||||
|
|
||||||
const { data, loading, page, pageSize, setPage, setPageSize, reload } = useAdminList<WecomBotDto>(
|
const { data, loading, page, pageSize, setPage, setPageSize, reload } = useAdminList<WecomBotDto>(
|
||||||
'/admin/wecom-bots',
|
'/admin/wecom-bots',
|
||||||
@@ -87,11 +130,13 @@ export default function WecomBotsPage() {
|
|||||||
[filters],
|
[filters],
|
||||||
);
|
);
|
||||||
|
|
||||||
useEffect(() => {
|
const loadRuntime = () =>
|
||||||
// useAdminList returns items; runtime comes from same API — fetch once for banner
|
request<WecomAibotRuntimeDto>('/admin/wecom-bots/runtime')
|
||||||
void request<ListRes>('/admin/wecom-bots?page=1&pageSize=1')
|
.then(setRuntime)
|
||||||
.then((res) => setRuntime(res.runtime))
|
|
||||||
.catch(() => {});
|
.catch(() => {});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void loadRuntime();
|
||||||
}, [data]);
|
}, [data]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -109,46 +154,51 @@ export default function WecomBotsPage() {
|
|||||||
});
|
});
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!modalOpen || !formReady || !formInitial) return;
|
||||||
|
form.resetFields();
|
||||||
|
form.setFieldsValue(formInitial);
|
||||||
|
}, [modalOpen, formReady, formInitial, form]);
|
||||||
|
|
||||||
|
function closeModal() {
|
||||||
|
setModalOpen(false);
|
||||||
|
setFormReady(false);
|
||||||
|
setFormInitial(null);
|
||||||
|
setEditing(null);
|
||||||
|
form.resetFields();
|
||||||
|
}
|
||||||
|
|
||||||
function openCreate() {
|
function openCreate() {
|
||||||
setEditing(null);
|
setEditing(null);
|
||||||
form.setFieldsValue({
|
setFormInitial({ ...CREATE_DEFAULTS });
|
||||||
name: '',
|
setFormReady(true);
|
||||||
role: 'CUSTOMER_SERVICE',
|
|
||||||
botId: '',
|
|
||||||
secret: '',
|
|
||||||
avatarUrl: '',
|
|
||||||
welcome: '',
|
|
||||||
permissions: [...WECOM_BOT_ROLE_DEFAULT_PERMISSIONS.CUSTOMER_SERVICE],
|
|
||||||
aiEnabled: false,
|
|
||||||
llmConfigId: null,
|
|
||||||
knowledgeBaseId: null,
|
|
||||||
enabled: true,
|
|
||||||
sortOrder: 0,
|
|
||||||
});
|
|
||||||
setModalOpen(true);
|
setModalOpen(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
function openEdit(row: WecomBotDto) {
|
async function openEdit(row: WecomBotDto) {
|
||||||
setEditing(row);
|
setEditing(row);
|
||||||
form.setFieldsValue({
|
setFormInitial(null);
|
||||||
name: row.name,
|
setFormReady(false);
|
||||||
role: row.role,
|
|
||||||
botId: row.botId,
|
|
||||||
secret: '',
|
|
||||||
avatarUrl: row.avatarUrl || '',
|
|
||||||
welcome: row.welcome || '',
|
|
||||||
permissions: row.permissions,
|
|
||||||
aiEnabled: row.aiEnabled,
|
|
||||||
llmConfigId: row.llmConfigId,
|
|
||||||
knowledgeBaseId: row.knowledgeBaseId,
|
|
||||||
enabled: row.enabled,
|
|
||||||
sortOrder: row.sortOrder,
|
|
||||||
});
|
|
||||||
setModalOpen(true);
|
setModalOpen(true);
|
||||||
|
try {
|
||||||
|
const detail = await request<WecomBotDto>(`/admin/wecom-bots/${row.id}`);
|
||||||
|
setEditing(detail);
|
||||||
|
setFormInitial(mapDtoToForm(detail));
|
||||||
|
} catch (e) {
|
||||||
|
message.error(e instanceof Error ? e.message : '加载机器人详情失败');
|
||||||
|
setFormInitial(mapDtoToForm(row));
|
||||||
|
} finally {
|
||||||
|
setFormReady(true);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function submit() {
|
async function submit() {
|
||||||
const values = await form.validateFields();
|
const values = await form.validateFields();
|
||||||
|
const permissions = (form.getFieldValue('permissions') ?? values.permissions) as WecomBotPermission[];
|
||||||
|
if (!permissions?.length) {
|
||||||
|
message.error('请至少选择一项权限');
|
||||||
|
return;
|
||||||
|
}
|
||||||
setSaving(true);
|
setSaving(true);
|
||||||
try {
|
try {
|
||||||
const payload = {
|
const payload = {
|
||||||
@@ -157,7 +207,8 @@ export default function WecomBotsPage() {
|
|||||||
botId: values.botId.trim(),
|
botId: values.botId.trim(),
|
||||||
avatarUrl: values.avatarUrl?.trim() || null,
|
avatarUrl: values.avatarUrl?.trim() || null,
|
||||||
welcome: values.welcome?.trim() || null,
|
welcome: values.welcome?.trim() || null,
|
||||||
permissions: values.permissions,
|
permissions,
|
||||||
|
reviewSuperAdminWecomUserIds: parseUserIdLines(values.reviewSuperAdminWecomUserIds),
|
||||||
aiEnabled: values.aiEnabled,
|
aiEnabled: values.aiEnabled,
|
||||||
llmConfigId: values.llmConfigId || null,
|
llmConfigId: values.llmConfigId || null,
|
||||||
knowledgeBaseId: values.knowledgeBaseId || null,
|
knowledgeBaseId: values.knowledgeBaseId || null,
|
||||||
@@ -165,13 +216,20 @@ export default function WecomBotsPage() {
|
|||||||
sortOrder: values.sortOrder,
|
sortOrder: values.sortOrder,
|
||||||
};
|
};
|
||||||
if (editing) {
|
if (editing) {
|
||||||
await request(`/admin/wecom-bots/${editing.id}`, {
|
const saved = await request<WecomBotDto>(`/admin/wecom-bots/${editing.id}`, {
|
||||||
method: 'PUT',
|
method: 'PUT',
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
...payload,
|
...payload,
|
||||||
secret: values.secret?.trim() || undefined,
|
secret: values.secret?.trim() || undefined,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
if (!samePermissionSet(permissions, saved.permissions)) {
|
||||||
|
message.warning('权限与保存结果不一致,已用服务端数据刷新表单');
|
||||||
|
setFormInitial(mapDtoToForm(saved));
|
||||||
|
setEditing(saved);
|
||||||
|
reload();
|
||||||
|
return;
|
||||||
|
}
|
||||||
message.success('已更新');
|
message.success('已更新');
|
||||||
} else {
|
} else {
|
||||||
if (!values.secret?.trim()) {
|
if (!values.secret?.trim()) {
|
||||||
@@ -187,7 +245,7 @@ export default function WecomBotsPage() {
|
|||||||
});
|
});
|
||||||
message.success('已创建');
|
message.success('已创建');
|
||||||
}
|
}
|
||||||
setModalOpen(false);
|
closeModal();
|
||||||
reload();
|
reload();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
message.error(e instanceof Error ? e.message : '保存失败');
|
message.error(e instanceof Error ? e.message : '保存失败');
|
||||||
@@ -208,10 +266,10 @@ export default function WecomBotsPage() {
|
|||||||
|
|
||||||
async function reloadConnections() {
|
async function reloadConnections() {
|
||||||
try {
|
try {
|
||||||
const st = await request<{
|
const st = await request<WecomAibotRuntimeDto>('/admin/wecom-bots/reload', {
|
||||||
masterEnabled: boolean;
|
method: 'POST',
|
||||||
bots: Array<{ id: string; connected: boolean; lastError: string | null }>;
|
body: '{}',
|
||||||
}>('/admin/wecom-bots/reload', { method: 'POST', body: '{}' });
|
});
|
||||||
message.success('已重载长连接');
|
message.success('已重载长连接');
|
||||||
setRuntime(st);
|
setRuntime(st);
|
||||||
reload();
|
reload();
|
||||||
@@ -287,7 +345,7 @@ export default function WecomBotsPage() {
|
|||||||
fixed: 'right',
|
fixed: 'right',
|
||||||
render: (_, row) => (
|
render: (_, row) => (
|
||||||
<Space>
|
<Space>
|
||||||
<Button type="link" size="small" onClick={() => openEdit(row)}>
|
<Button type="link" size="small" onClick={() => void openEdit(row)}>
|
||||||
编辑
|
编辑
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
@@ -386,23 +444,39 @@ export default function WecomBotsPage() {
|
|||||||
<Modal
|
<Modal
|
||||||
title={editing ? '编辑企微机器人' : '创建企微机器人'}
|
title={editing ? '编辑企微机器人' : '创建企微机器人'}
|
||||||
open={modalOpen}
|
open={modalOpen}
|
||||||
onCancel={() => setModalOpen(false)}
|
onCancel={closeModal}
|
||||||
onOk={() => void submit()}
|
onOk={() => void submit()}
|
||||||
confirmLoading={saving}
|
confirmLoading={saving}
|
||||||
width={640}
|
width={640}
|
||||||
destroyOnClose
|
destroyOnClose
|
||||||
>
|
>
|
||||||
<Form form={form} layout="vertical">
|
{formReady && formInitial ? (
|
||||||
|
<Form
|
||||||
|
key={editing ? `edit-${editing.id}` : 'create'}
|
||||||
|
form={form}
|
||||||
|
layout="vertical"
|
||||||
|
preserve={false}
|
||||||
|
initialValues={formInitial}
|
||||||
|
>
|
||||||
<Form.Item name="name" label="名称" rules={[{ required: true, message: '请填写名称' }]}>
|
<Form.Item name="name" label="名称" rules={[{ required: true, message: '请填写名称' }]}>
|
||||||
<Input placeholder="如:客服机器人" maxLength={64} />
|
<Input placeholder="如:客服机器人" maxLength={64} />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
<Form.Item name="role" label="角色" rules={[{ required: true }]}>
|
<Form.Item name="role" label="角色" rules={[{ required: true }]}>
|
||||||
<Select
|
<Select
|
||||||
options={WECOM_BOT_ROLES.map((r) => ({ value: r, label: WECOM_BOT_ROLE_LABELS[r] }))}
|
options={WECOM_BOT_ROLES.map((r) => ({ value: r, label: WECOM_BOT_ROLE_LABELS[r] }))}
|
||||||
onChange={(role: WecomBotRole) => {
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item>
|
||||||
|
<Button
|
||||||
|
size="small"
|
||||||
|
onClick={() => {
|
||||||
|
const role = form.getFieldValue('role') as WecomBotRole | undefined;
|
||||||
|
if (!role) return;
|
||||||
form.setFieldValue('permissions', [...WECOM_BOT_ROLE_DEFAULT_PERMISSIONS[role]]);
|
form.setFieldValue('permissions', [...WECOM_BOT_ROLE_DEFAULT_PERMISSIONS[role]]);
|
||||||
}}
|
}}
|
||||||
/>
|
>
|
||||||
|
应用当前角色默认权限
|
||||||
|
</Button>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
<Form.Item name="avatarUrl" label="头像">
|
<Form.Item name="avatarUrl" label="头像">
|
||||||
<OssUpload bizType="WECOM_BOT_AVATAR" />
|
<OssUpload bizType="WECOM_BOT_AVATAR" />
|
||||||
@@ -420,21 +494,48 @@ export default function WecomBotsPage() {
|
|||||||
</Form.Item>
|
</Form.Item>
|
||||||
<Form.Item
|
<Form.Item
|
||||||
name="permissions"
|
name="permissions"
|
||||||
label="权限"
|
label="权限(按模块)"
|
||||||
rules={[{ required: true, message: '请至少选择一项权限' }]}
|
rules={[
|
||||||
|
{
|
||||||
|
validator: (_, v: WecomBotPermission[] | undefined) =>
|
||||||
|
v?.length ? Promise.resolve() : Promise.reject(new Error('请至少选择一项权限')),
|
||||||
|
},
|
||||||
|
]}
|
||||||
extra={
|
extra={
|
||||||
roleWatch
|
<>
|
||||||
|
{roleWatch
|
||||||
? `角色默认:${WECOM_BOT_ROLE_DEFAULT_PERMISSIONS[roleWatch as WecomBotRole]?.map((p) => WECOM_BOT_PERMISSION_LABELS[p]).join('、') || '无'}`
|
? `角色默认:${WECOM_BOT_ROLE_DEFAULT_PERMISSIONS[roleWatch as WecomBotRole]?.map((p) => WECOM_BOT_PERMISSION_LABELS[p]).join('、') || '无'}`
|
||||||
: undefined
|
: null}
|
||||||
|
{permissionsWatch?.length ? (
|
||||||
|
<Typography.Text type="secondary"> · 已选 {permissionsWatch.length} 项</Typography.Text>
|
||||||
|
) : null}
|
||||||
|
</>
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
<Checkbox.Group
|
<Checkbox.Group style={{ width: '100%' }}>
|
||||||
options={WECOM_BOT_PERMISSIONS.map((p) => ({
|
{WECOM_BOT_PERMISSION_GROUPS.map((group) => (
|
||||||
value: p,
|
<div key={group.key} style={{ marginBottom: 12 }}>
|
||||||
label: WECOM_BOT_PERMISSION_LABELS[p],
|
<Typography.Text strong>{group.label}</Typography.Text>
|
||||||
}))}
|
<div style={{ marginTop: 4 }}>
|
||||||
/>
|
{group.permissions.map((p) => (
|
||||||
|
<Checkbox key={p} value={p} style={{ marginInlineStart: 0, marginRight: 12 }}>
|
||||||
|
{WECOM_BOT_PERMISSION_LABELS[p]}
|
||||||
|
</Checkbox>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</Checkbox.Group>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
|
{(roleWatch === 'TECH_SUPPORT' || permissionsWatch?.includes('support_ticket.review')) && (
|
||||||
|
<Form.Item
|
||||||
|
name="reviewSuperAdminWecomUserIds"
|
||||||
|
label="审批白名单(企微 userid)"
|
||||||
|
extra="填写成员企微 userid(如 woDacESQAAD…),不是姓名/昵称;每行或逗号分隔。发「状态」或在服务端日志 inbound user= 可核对"
|
||||||
|
>
|
||||||
|
<Input.TextArea rows={3} placeholder="zhangsan lisi" />
|
||||||
|
</Form.Item>
|
||||||
|
)}
|
||||||
<Form.Item name="welcome" label="欢迎语">
|
<Form.Item name="welcome" label="欢迎语">
|
||||||
<Input.TextArea rows={3} placeholder="进入会话时的欢迎语,可空" />
|
<Input.TextArea rows={3} placeholder="进入会话时的欢迎语,可空" />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
@@ -475,6 +576,9 @@ export default function WecomBotsPage() {
|
|||||||
</Form.Item>
|
</Form.Item>
|
||||||
</Space>
|
</Space>
|
||||||
</Form>
|
</Form>
|
||||||
|
) : (
|
||||||
|
<Typography.Text type="secondary">加载中…</Typography.Text>
|
||||||
|
)}
|
||||||
</Modal>
|
</Modal>
|
||||||
|
|
||||||
<Drawer title="机器人详情" width={480} open={!!detail} onClose={() => setDetail(null)}>
|
<Drawer title="机器人详情" width={480} open={!!detail} onClose={() => setDetail(null)}>
|
||||||
@@ -496,6 +600,11 @@ export default function WecomBotsPage() {
|
|||||||
<Descriptions.Item label="权限">
|
<Descriptions.Item label="权限">
|
||||||
{detail.permissions.map((p) => WECOM_BOT_PERMISSION_LABELS[p] || p).join('、')}
|
{detail.permissions.map((p) => WECOM_BOT_PERMISSION_LABELS[p] || p).join('、')}
|
||||||
</Descriptions.Item>
|
</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="审批白名单">
|
||||||
|
{detail.reviewSuperAdminWecomUserIds?.length
|
||||||
|
? detail.reviewSuperAdminWecomUserIds.join('、')
|
||||||
|
: '—'}
|
||||||
|
</Descriptions.Item>
|
||||||
<Descriptions.Item label="欢迎语">{detail.welcome || '—'}</Descriptions.Item>
|
<Descriptions.Item label="欢迎语">{detail.welcome || '—'}</Descriptions.Item>
|
||||||
<Descriptions.Item label="AI 问答">{detail.aiEnabled ? '开' : '关'}</Descriptions.Item>
|
<Descriptions.Item label="AI 问答">{detail.aiEnabled ? '开' : '关'}</Descriptions.Item>
|
||||||
<Descriptions.Item label="语言模型">{detail.llmConfigName || '—'}</Descriptions.Item>
|
<Descriptions.Item label="语言模型">{detail.llmConfigName || '—'}</Descriptions.Item>
|
||||||
|
|||||||
@@ -0,0 +1,405 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
|
import {
|
||||||
|
Avatar,
|
||||||
|
Button,
|
||||||
|
Checkbox,
|
||||||
|
Descriptions,
|
||||||
|
Form,
|
||||||
|
Input,
|
||||||
|
InputNumber,
|
||||||
|
Modal,
|
||||||
|
Popconfirm,
|
||||||
|
Select,
|
||||||
|
Space,
|
||||||
|
Switch,
|
||||||
|
Table,
|
||||||
|
Tag,
|
||||||
|
Typography,
|
||||||
|
message,
|
||||||
|
} from 'antd';
|
||||||
|
import type { ColumnsType } from 'antd/es/table';
|
||||||
|
import {
|
||||||
|
WECOM_PUSH_CONDITION_GROUPS,
|
||||||
|
WECOM_PUSH_CONDITION_LABELS,
|
||||||
|
type WecomMessagePushDto,
|
||||||
|
type WecomPushCondition,
|
||||||
|
} from '@dukang/shared-types';
|
||||||
|
import { request } from '../lib/api';
|
||||||
|
import { fmtTime } from '../lib/constants';
|
||||||
|
import { useAdminList } from '../lib/useAdminList';
|
||||||
|
import OssUpload from '../components/OssUpload';
|
||||||
|
|
||||||
|
type FormValues = {
|
||||||
|
name: string;
|
||||||
|
avatarUrl?: string;
|
||||||
|
webhookUrl: string;
|
||||||
|
enabled: boolean;
|
||||||
|
mentionWecomUserId?: string;
|
||||||
|
pushConditions: WecomPushCondition[];
|
||||||
|
sortOrder: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
function WecomPushConditionPicker({
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
}: {
|
||||||
|
value?: WecomPushCondition[];
|
||||||
|
onChange?: (next: WecomPushCondition[]) => void;
|
||||||
|
}) {
|
||||||
|
const selected = new Set(value ?? []);
|
||||||
|
|
||||||
|
function toggle(cond: WecomPushCondition, checked: boolean) {
|
||||||
|
const next = new Set(selected);
|
||||||
|
if (checked) next.add(cond);
|
||||||
|
else next.delete(cond);
|
||||||
|
onChange?.([...next]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ width: '100%' }}>
|
||||||
|
{WECOM_PUSH_CONDITION_GROUPS.map((group) => (
|
||||||
|
<div key={group.key} style={{ marginBottom: 12 }}>
|
||||||
|
<Typography.Text strong>{group.label}</Typography.Text>
|
||||||
|
<div style={{ marginTop: 8 }}>
|
||||||
|
{group.conditions.map((c) => (
|
||||||
|
<div key={c}>
|
||||||
|
<Checkbox
|
||||||
|
checked={selected.has(c)}
|
||||||
|
onChange={(e) => toggle(c, e.target.checked)}
|
||||||
|
>
|
||||||
|
{WECOM_PUSH_CONDITION_LABELS[c]}
|
||||||
|
</Checkbox>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function WecomMessagePushesPage() {
|
||||||
|
const [filterForm] = Form.useForm();
|
||||||
|
const [form] = Form.useForm<FormValues>();
|
||||||
|
const [filters, setFilters] = useState<Record<string, string>>({});
|
||||||
|
const [modalOpen, setModalOpen] = useState(false);
|
||||||
|
const [editing, setEditing] = useState<WecomMessagePushDto | null>(null);
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
const [detail, setDetail] = useState<WecomMessagePushDto | null>(null);
|
||||||
|
const [testingId, setTestingId] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const { data, loading, page, pageSize, setPage, setPageSize, reload } =
|
||||||
|
useAdminList<WecomMessagePushDto>(
|
||||||
|
'/admin/wecom-message-pushes',
|
||||||
|
() => {
|
||||||
|
const qs = new URLSearchParams();
|
||||||
|
if (filters.name) qs.set('name', filters.name);
|
||||||
|
if (filters.enabled) qs.set('enabled', filters.enabled);
|
||||||
|
return qs;
|
||||||
|
},
|
||||||
|
[filters],
|
||||||
|
);
|
||||||
|
|
||||||
|
const conditionsWatch = Form.useWatch('pushConditions', form) as WecomPushCondition[] | undefined;
|
||||||
|
|
||||||
|
function openCreate() {
|
||||||
|
setEditing(null);
|
||||||
|
form.resetFields();
|
||||||
|
form.setFieldsValue({
|
||||||
|
enabled: true,
|
||||||
|
pushConditions: ['alert.ops'],
|
||||||
|
sortOrder: 0,
|
||||||
|
});
|
||||||
|
setModalOpen(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
function openEdit(row: WecomMessagePushDto) {
|
||||||
|
setEditing(row);
|
||||||
|
form.setFieldsValue({
|
||||||
|
name: row.name,
|
||||||
|
avatarUrl: row.avatarUrl ?? undefined,
|
||||||
|
webhookUrl: row.webhookUrl,
|
||||||
|
enabled: row.enabled,
|
||||||
|
mentionWecomUserId: row.mentionWecomUserId ?? undefined,
|
||||||
|
pushConditions: row.pushConditions,
|
||||||
|
sortOrder: row.sortOrder,
|
||||||
|
});
|
||||||
|
setModalOpen(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function save() {
|
||||||
|
const values = await form.validateFields();
|
||||||
|
setSaving(true);
|
||||||
|
try {
|
||||||
|
const body = {
|
||||||
|
name: values.name,
|
||||||
|
avatarUrl: values.avatarUrl || null,
|
||||||
|
webhookUrl: values.webhookUrl,
|
||||||
|
enabled: values.enabled,
|
||||||
|
mentionWecomUserId: values.mentionWecomUserId?.trim() || null,
|
||||||
|
pushConditions: values.pushConditions,
|
||||||
|
sortOrder: values.sortOrder ?? 0,
|
||||||
|
};
|
||||||
|
if (editing) {
|
||||||
|
await request(`/admin/wecom-message-pushes/${editing.id}`, {
|
||||||
|
method: 'PUT',
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
message.success('已更新');
|
||||||
|
} else {
|
||||||
|
await request('/admin/wecom-message-pushes', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
message.success('已创建');
|
||||||
|
}
|
||||||
|
setModalOpen(false);
|
||||||
|
reload();
|
||||||
|
} catch (e) {
|
||||||
|
message.error(e instanceof Error ? e.message : '保存失败');
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function remove(id: string) {
|
||||||
|
try {
|
||||||
|
await request(`/admin/wecom-message-pushes/${id}`, { method: 'DELETE' });
|
||||||
|
message.success('已删除');
|
||||||
|
reload();
|
||||||
|
} catch (e) {
|
||||||
|
message.error(e instanceof Error ? e.message : '删除失败');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function testPush(id: string) {
|
||||||
|
setTestingId(id);
|
||||||
|
try {
|
||||||
|
const res = await request<{ ok: boolean; message: string }>(
|
||||||
|
`/admin/wecom-message-pushes/${id}/test`,
|
||||||
|
{ method: 'POST', body: '{}' },
|
||||||
|
);
|
||||||
|
message.success(res.message || '已发送测试消息');
|
||||||
|
} catch (e) {
|
||||||
|
message.error(e instanceof Error ? e.message : '测试失败');
|
||||||
|
} finally {
|
||||||
|
setTestingId(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const columns: ColumnsType<WecomMessagePushDto> = [
|
||||||
|
{
|
||||||
|
title: '名称',
|
||||||
|
dataIndex: 'name',
|
||||||
|
render: (name: string, row) => (
|
||||||
|
<Space>
|
||||||
|
<Avatar src={row.avatarUrl ?? undefined}>{name.slice(0, 1)}</Avatar>
|
||||||
|
<span>{name}</span>
|
||||||
|
</Space>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Webhook',
|
||||||
|
dataIndex: 'webhookUrlMasked',
|
||||||
|
ellipsis: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '推送条件',
|
||||||
|
dataIndex: 'pushConditions',
|
||||||
|
render: (conds: WecomPushCondition[]) =>
|
||||||
|
conds.map((c) => (
|
||||||
|
<Tag key={c} style={{ marginBottom: 4 }}>
|
||||||
|
{WECOM_PUSH_CONDITION_LABELS[c]}
|
||||||
|
</Tag>
|
||||||
|
)),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '启用',
|
||||||
|
dataIndex: 'enabled',
|
||||||
|
width: 72,
|
||||||
|
render: (v: boolean) => (v ? <Tag color="green">是</Tag> : <Tag>否</Tag>),
|
||||||
|
},
|
||||||
|
{ title: '排序', dataIndex: 'sortOrder', width: 64 },
|
||||||
|
{
|
||||||
|
title: '操作',
|
||||||
|
key: 'actions',
|
||||||
|
width: 220,
|
||||||
|
render: (_, row) => (
|
||||||
|
<Space wrap>
|
||||||
|
<Button type="link" size="small" onClick={() => openEdit(row)}>
|
||||||
|
编辑
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="link"
|
||||||
|
size="small"
|
||||||
|
loading={testingId === row.id}
|
||||||
|
onClick={() => void testPush(row.id)}
|
||||||
|
>
|
||||||
|
测试
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="link"
|
||||||
|
size="small"
|
||||||
|
onClick={() => {
|
||||||
|
void request<WecomMessagePushDto>(`/admin/wecom-message-pushes/${row.id}`).then(setDetail);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
详情
|
||||||
|
</Button>
|
||||||
|
<Popconfirm title="确认删除?" onConfirm={() => void remove(row.id)}>
|
||||||
|
<Button type="link" size="small" danger>
|
||||||
|
删除
|
||||||
|
</Button>
|
||||||
|
</Popconfirm>
|
||||||
|
</Space>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<Typography.Title level={4}>企微机器人 · 消息推送</Typography.Title>
|
||||||
|
<Typography.Paragraph type="secondary">
|
||||||
|
配置群机器人 Webhook 多实例,按推送条件分发运营告警、技术支持工单、开发任务派发等消息。运行时不再读取
|
||||||
|
.env 中的 Webhook URL。
|
||||||
|
</Typography.Paragraph>
|
||||||
|
|
||||||
|
<Form
|
||||||
|
form={filterForm}
|
||||||
|
layout="inline"
|
||||||
|
style={{ marginBottom: 16 }}
|
||||||
|
onFinish={(v) => setFilters(v as Record<string, string>)}
|
||||||
|
>
|
||||||
|
<Form.Item name="name" label="名称">
|
||||||
|
<Input allowClear placeholder="搜索" />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="enabled" label="启用">
|
||||||
|
<Select
|
||||||
|
allowClear
|
||||||
|
placeholder="全部"
|
||||||
|
style={{ width: 100 }}
|
||||||
|
options={[
|
||||||
|
{ value: 'true', label: '启用' },
|
||||||
|
{ value: 'false', label: '停用' },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item>
|
||||||
|
<Space>
|
||||||
|
<Button type="primary" htmlType="submit">
|
||||||
|
查询
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
onClick={() => {
|
||||||
|
filterForm.resetFields();
|
||||||
|
setFilters({});
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
重置
|
||||||
|
</Button>
|
||||||
|
<Button type="primary" onClick={openCreate}>
|
||||||
|
新建推送
|
||||||
|
</Button>
|
||||||
|
</Space>
|
||||||
|
</Form.Item>
|
||||||
|
</Form>
|
||||||
|
|
||||||
|
<Table<WecomMessagePushDto>
|
||||||
|
rowKey="id"
|
||||||
|
loading={loading}
|
||||||
|
columns={columns}
|
||||||
|
dataSource={data?.items ?? []}
|
||||||
|
pagination={{
|
||||||
|
current: page,
|
||||||
|
pageSize,
|
||||||
|
total: data?.total ?? 0,
|
||||||
|
showSizeChanger: true,
|
||||||
|
onChange: (p, ps) => {
|
||||||
|
setPage(p);
|
||||||
|
setPageSize(ps);
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Modal
|
||||||
|
title={editing ? '编辑消息推送' : '新建消息推送'}
|
||||||
|
open={modalOpen}
|
||||||
|
onCancel={() => setModalOpen(false)}
|
||||||
|
onOk={() => void save()}
|
||||||
|
confirmLoading={saving}
|
||||||
|
width={640}
|
||||||
|
destroyOnClose
|
||||||
|
>
|
||||||
|
<Form form={form} layout="vertical">
|
||||||
|
<Form.Item name="name" label="名称" rules={[{ required: true, message: '请填写名称' }]}>
|
||||||
|
<Input placeholder="如:运营告警" />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="avatarUrl" label="头像(HQ 列表展示)">
|
||||||
|
<OssUpload />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item
|
||||||
|
name="webhookUrl"
|
||||||
|
label="Webhook URL"
|
||||||
|
rules={[{ required: true, message: '请填写 Webhook URL' }]}
|
||||||
|
>
|
||||||
|
<Input.Password placeholder="企微群机器人 Webhook" />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="enabled" label="启用" valuePropName="checked">
|
||||||
|
<Switch />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item
|
||||||
|
name="mentionWecomUserId"
|
||||||
|
label="企微 userid(可选)"
|
||||||
|
extra="markdown 推送用 <@userid> @ 群成员;任务派发等场景生效"
|
||||||
|
>
|
||||||
|
<Input placeholder="如 woDacESQAAD..." allowClear />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item
|
||||||
|
name="pushConditions"
|
||||||
|
label="推送条件"
|
||||||
|
rules={[
|
||||||
|
{
|
||||||
|
validator: (_, v: WecomPushCondition[] | undefined) =>
|
||||||
|
v?.length ? Promise.resolve() : Promise.reject(new Error('请至少勾选一项推送条件')),
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
<WecomPushConditionPicker />
|
||||||
|
</Form.Item>
|
||||||
|
{conditionsWatch?.length ? (
|
||||||
|
<Typography.Text type="secondary" style={{ display: 'block', marginBottom: 16 }}>
|
||||||
|
已选 {conditionsWatch.length} 项:
|
||||||
|
{conditionsWatch.map((c) => WECOM_PUSH_CONDITION_LABELS[c]).join('、')}
|
||||||
|
</Typography.Text>
|
||||||
|
) : null}
|
||||||
|
<Form.Item name="sortOrder" label="排序">
|
||||||
|
<InputNumber min={0} style={{ width: '100%' }} />
|
||||||
|
</Form.Item>
|
||||||
|
</Form>
|
||||||
|
</Modal>
|
||||||
|
|
||||||
|
<Modal
|
||||||
|
title="消息推送详情"
|
||||||
|
open={!!detail}
|
||||||
|
onCancel={() => setDetail(null)}
|
||||||
|
footer={null}
|
||||||
|
width={560}
|
||||||
|
>
|
||||||
|
{detail ? (
|
||||||
|
<Descriptions column={1} bordered size="small">
|
||||||
|
<Descriptions.Item label="名称">{detail.name}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="Webhook">{detail.webhookUrlMasked}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="启用">{detail.enabled ? '是' : '否'}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="userid">{detail.mentionWecomUserId || '—'}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="推送条件">
|
||||||
|
{detail.pushConditions.map((c) => WECOM_PUSH_CONDITION_LABELS[c]).join('、')}
|
||||||
|
</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="排序">{detail.sortOrder}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="创建时间">{fmtTime(detail.createdAt)}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="更新时间">{fmtTime(detail.updatedAt)}</Descriptions.Item>
|
||||||
|
</Descriptions>
|
||||||
|
) : null}
|
||||||
|
</Modal>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
export type DevPlanTaskStatus = 'TODO' | 'DEVELOPED' | 'RELEASED';
|
||||||
|
export type DevPlanVersionStatus = 'PENDING' | 'IN_PROGRESS' | 'TESTING' | 'RELEASED';
|
||||||
|
|
||||||
|
export function computeDurationMinutes(
|
||||||
|
devStartedAt: Date | null | undefined,
|
||||||
|
devCompletedAt: Date | null | undefined,
|
||||||
|
): number | null {
|
||||||
|
if (!devStartedAt || !devCompletedAt) return null;
|
||||||
|
const ms = devCompletedAt.getTime() - devStartedAt.getTime();
|
||||||
|
if (ms < 0) return null;
|
||||||
|
return Math.round(ms / 60000);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function versionStatusTimestamps(
|
||||||
|
prev: DevPlanVersionStatus,
|
||||||
|
next: DevPlanVersionStatus,
|
||||||
|
current: {
|
||||||
|
devStartedAt?: Date | null;
|
||||||
|
devCompletedAt?: Date | null;
|
||||||
|
releasedAt?: Date | null;
|
||||||
|
},
|
||||||
|
): {
|
||||||
|
devStartedAt?: Date | null;
|
||||||
|
devCompletedAt?: Date | null;
|
||||||
|
releasedAt?: Date | null;
|
||||||
|
durationMinutes?: number | null;
|
||||||
|
} {
|
||||||
|
const patch: {
|
||||||
|
devStartedAt?: Date | null;
|
||||||
|
devCompletedAt?: Date | null;
|
||||||
|
releasedAt?: Date | null;
|
||||||
|
durationMinutes?: number | null;
|
||||||
|
} = {};
|
||||||
|
const now = new Date();
|
||||||
|
|
||||||
|
if (next === 'IN_PROGRESS' && !current.devStartedAt) {
|
||||||
|
patch.devStartedAt = now;
|
||||||
|
}
|
||||||
|
if (next === 'TESTING' && !current.devCompletedAt) {
|
||||||
|
patch.devCompletedAt = now;
|
||||||
|
}
|
||||||
|
if (next === 'RELEASED' && !current.releasedAt) {
|
||||||
|
patch.releasedAt = now;
|
||||||
|
}
|
||||||
|
|
||||||
|
const started = patch.devStartedAt ?? current.devStartedAt ?? null;
|
||||||
|
const completed = patch.devCompletedAt ?? current.devCompletedAt ?? null;
|
||||||
|
const duration = computeDurationMinutes(started, completed);
|
||||||
|
if (duration != null) patch.durationMinutes = duration;
|
||||||
|
|
||||||
|
void prev;
|
||||||
|
return patch;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function taskCompletedAtOnStatus(
|
||||||
|
prev: DevPlanTaskStatus,
|
||||||
|
next: DevPlanTaskStatus,
|
||||||
|
currentCompletedAt?: Date | null,
|
||||||
|
): Date | null | undefined {
|
||||||
|
if (next === 'RELEASED' && !currentCompletedAt) return new Date();
|
||||||
|
void prev;
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
@@ -353,3 +353,4 @@ export function orderTabToStatuses(tab: string): string[] | undefined {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export * from './city-partner';
|
export * from './city-partner';
|
||||||
|
export * from './dev-plan';
|
||||||
|
|||||||
@@ -0,0 +1,235 @@
|
|||||||
|
/** 开发计划任务类型 */
|
||||||
|
|
||||||
|
export type DevPlanTaskTypeDto = 'BUG' | 'REQUIREMENT' | 'OPTIMIZATION';
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
export const DEV_PLAN_TASK_TYPES = ['BUG', 'REQUIREMENT', 'OPTIMIZATION'] as const;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
export const DEV_PLAN_TASK_TYPE_LABELS: Record<DevPlanTaskTypeDto, string> = {
|
||||||
|
|
||||||
|
BUG: 'BUG',
|
||||||
|
|
||||||
|
REQUIREMENT: '需求',
|
||||||
|
|
||||||
|
OPTIMIZATION: '优化',
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/** 开发计划任务状态 */
|
||||||
|
|
||||||
|
export type DevPlanTaskStatusDto = 'TODO' | 'DEVELOPED' | 'RELEASED';
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
export const DEV_PLAN_TASK_STATUSES = ['TODO', 'DEVELOPED', 'RELEASED'] as const;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
export const DEV_PLAN_TASK_STATUS_LABELS: Record<DevPlanTaskStatusDto, string> = {
|
||||||
|
|
||||||
|
TODO: '待开发',
|
||||||
|
|
||||||
|
DEVELOPED: '已开发',
|
||||||
|
|
||||||
|
RELEASED: '已上线',
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/** 开发计划版本状态 */
|
||||||
|
|
||||||
|
export type DevPlanVersionStatusDto = 'PENDING' | 'IN_PROGRESS' | 'TESTING' | 'RELEASED';
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
export const DEV_PLAN_VERSION_STATUSES = ['PENDING', 'IN_PROGRESS', 'TESTING', 'RELEASED'] as const;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
export const DEV_PLAN_VERSION_STATUS_LABELS: Record<DevPlanVersionStatusDto, string> = {
|
||||||
|
|
||||||
|
PENDING: '待启动',
|
||||||
|
|
||||||
|
IN_PROGRESS: '开发中',
|
||||||
|
|
||||||
|
TESTING: '测试',
|
||||||
|
|
||||||
|
RELEASED: '已上线',
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
export interface DevPlanTaskDto {
|
||||||
|
|
||||||
|
id: string;
|
||||||
|
|
||||||
|
taskNo: string;
|
||||||
|
|
||||||
|
content: string;
|
||||||
|
|
||||||
|
type: DevPlanTaskTypeDto;
|
||||||
|
|
||||||
|
status: DevPlanTaskStatusDto;
|
||||||
|
|
||||||
|
creatorHqAccountId: string;
|
||||||
|
|
||||||
|
creatorName?: string | null;
|
||||||
|
|
||||||
|
supportTicketId?: string | null;
|
||||||
|
|
||||||
|
supportTicketNo?: string | null;
|
||||||
|
|
||||||
|
lastDispatchedAt?: string | null;
|
||||||
|
|
||||||
|
createdAt: string;
|
||||||
|
|
||||||
|
completedAt?: string | null;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
export interface DevPlanVersionDto {
|
||||||
|
|
||||||
|
id: string;
|
||||||
|
|
||||||
|
versionNo: string;
|
||||||
|
|
||||||
|
content?: string | null;
|
||||||
|
|
||||||
|
status: DevPlanVersionStatusDto;
|
||||||
|
|
||||||
|
assigneeHqAccountId?: string | null;
|
||||||
|
|
||||||
|
assigneeName?: string | null;
|
||||||
|
|
||||||
|
createdAt: string;
|
||||||
|
|
||||||
|
devStartedAt?: string | null;
|
||||||
|
|
||||||
|
devCompletedAt?: string | null;
|
||||||
|
|
||||||
|
releasedAt?: string | null;
|
||||||
|
|
||||||
|
durationMinutes?: number | null;
|
||||||
|
|
||||||
|
tasks?: DevPlanTaskDto[];
|
||||||
|
|
||||||
|
taskIds?: string[];
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
export interface DevPlanSettingsDto {
|
||||||
|
|
||||||
|
reviewAssistantLlmConfigId?: string | null;
|
||||||
|
|
||||||
|
reviewAssistantKnowledgeBaseId?: string | null;
|
||||||
|
|
||||||
|
reviewAssistantPrompt?: string | null;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
export interface CreateDevPlanTaskInput {
|
||||||
|
|
||||||
|
content: string;
|
||||||
|
|
||||||
|
type: DevPlanTaskTypeDto;
|
||||||
|
|
||||||
|
supportTicketId?: string;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
export interface UpdateDevPlanTaskInput {
|
||||||
|
|
||||||
|
content?: string;
|
||||||
|
|
||||||
|
type?: DevPlanTaskTypeDto;
|
||||||
|
|
||||||
|
status?: DevPlanTaskStatusDto;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
export interface CreateDevPlanVersionInput {
|
||||||
|
|
||||||
|
versionNo: string;
|
||||||
|
|
||||||
|
content?: string;
|
||||||
|
|
||||||
|
status?: DevPlanVersionStatusDto;
|
||||||
|
|
||||||
|
taskIds?: string[];
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
export interface UpdateDevPlanVersionInput {
|
||||||
|
|
||||||
|
versionNo?: string;
|
||||||
|
|
||||||
|
content?: string;
|
||||||
|
|
||||||
|
status?: DevPlanVersionStatusDto;
|
||||||
|
|
||||||
|
taskIds?: string[];
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
export interface DevPlanTaskDispatchInput {
|
||||||
|
|
||||||
|
taskIds: string[];
|
||||||
|
|
||||||
|
supplement?: string;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
export interface DevPlanLinkedTaskSummary {
|
||||||
|
|
||||||
|
id: string;
|
||||||
|
|
||||||
|
taskNo: string;
|
||||||
|
|
||||||
|
content: string;
|
||||||
|
|
||||||
|
status: DevPlanTaskStatusDto;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/** 技术支持工单类型 → 开发任务类型 */
|
||||||
|
|
||||||
|
export function mapSupportTicketTypeToDevPlanTask(
|
||||||
|
|
||||||
|
ticketType: 'BUG' | 'SUGGESTION' | 'OTHER',
|
||||||
|
|
||||||
|
): DevPlanTaskTypeDto {
|
||||||
|
|
||||||
|
if (ticketType === 'BUG') return 'BUG';
|
||||||
|
|
||||||
|
if (ticketType === 'SUGGESTION') return 'REQUIREMENT';
|
||||||
|
|
||||||
|
return 'OPTIMIZATION';
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -17,6 +17,7 @@ export const HQ_PERMISSION_CATALOG = [
|
|||||||
{ key: 'wecom_bots', label: '企微机器人', group: '业务' },
|
{ key: 'wecom_bots', label: '企微机器人', group: '业务' },
|
||||||
{ key: 'llm_configs', label: '语言模型配置', group: '业务' },
|
{ key: 'llm_configs', label: '语言模型配置', group: '业务' },
|
||||||
{ key: 'knowledge_bases', label: '知识库', group: '业务' },
|
{ key: 'knowledge_bases', label: '知识库', group: '业务' },
|
||||||
|
{ key: 'dev_plan', label: '开发计划', group: '业务' },
|
||||||
{ key: 'resources', label: 'OSS 资源库', group: '业务' },
|
{ key: 'resources', label: 'OSS 资源库', group: '业务' },
|
||||||
{ key: 'logs', label: '日志', group: '业务' },
|
{ key: 'logs', label: '日志', group: '业务' },
|
||||||
{ key: 'users_delete', label: '删除用户', group: '危险操作' },
|
{ key: 'users_delete', label: '删除用户', group: '危险操作' },
|
||||||
@@ -114,6 +115,7 @@ export const HQ_ROLE_DEFAULT_PERMISSIONS: Record<string, HqPermissionKey[]> = {
|
|||||||
'wecom_bots',
|
'wecom_bots',
|
||||||
'llm_configs',
|
'llm_configs',
|
||||||
'knowledge_bases',
|
'knowledge_bases',
|
||||||
|
'dev_plan',
|
||||||
'resources',
|
'resources',
|
||||||
'logs',
|
'logs',
|
||||||
'system_settings_wechat_mini',
|
'system_settings_wechat_mini',
|
||||||
|
|||||||
@@ -25,6 +25,8 @@ export * from './city-warehouse';
|
|||||||
export * from './fulfillment-provider';
|
export * from './fulfillment-provider';
|
||||||
export * from './system-config';
|
export * from './system-config';
|
||||||
export * from './wecom-bot';
|
export * from './wecom-bot';
|
||||||
|
export * from './wecom-message-push';
|
||||||
export * from './llm-config';
|
export * from './llm-config';
|
||||||
export * from './knowledge-base';
|
export * from './knowledge-base';
|
||||||
export * from './legal';
|
export * from './legal';
|
||||||
|
export * from './dev-plan';
|
||||||
|
|||||||
@@ -62,3 +62,49 @@ export interface CreateSupportTicketRequest {
|
|||||||
export interface RejectSupportTicketRequest {
|
export interface RejectSupportTicketRequest {
|
||||||
rejectReason: string;
|
rejectReason: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface CreateDevPlanTaskFromTicketInput {
|
||||||
|
content: string;
|
||||||
|
type: 'BUG' | 'REQUIREMENT' | 'OPTIMIZATION';
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ReviewSupportTicketRequest {
|
||||||
|
decision: 'APPROVE' | 'REJECT';
|
||||||
|
rejectReason?: string;
|
||||||
|
note?: string;
|
||||||
|
tasks?: CreateDevPlanTaskFromTicketInput[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SupportTicketLinkedTaskDto {
|
||||||
|
id: string;
|
||||||
|
taskNo: string;
|
||||||
|
content: string;
|
||||||
|
status: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BatchReviewPreviewItem {
|
||||||
|
ticketId: string;
|
||||||
|
ticketNo: string;
|
||||||
|
title: string;
|
||||||
|
decision: 'APPROVE' | 'REJECT';
|
||||||
|
rejectReason?: string;
|
||||||
|
note?: string;
|
||||||
|
reportMarkdown: string;
|
||||||
|
suggestedTasks: CreateDevPlanTaskFromTicketInput[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BatchReviewPreviewResponse {
|
||||||
|
items: BatchReviewPreviewItem[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BatchReviewConfirmItem {
|
||||||
|
ticketId: string;
|
||||||
|
decision: 'APPROVE' | 'REJECT';
|
||||||
|
rejectReason?: string;
|
||||||
|
note?: string;
|
||||||
|
tasks?: CreateDevPlanTaskFromTicketInput[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BatchReviewConfirmRequest {
|
||||||
|
items: BatchReviewConfirmItem[];
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,63 +1,262 @@
|
|||||||
/** 企业微信智能机器人能力权限 */
|
/** 企业微信智能机器人 · 模块化能力权限(v3.4.11 重构) */
|
||||||
export const WECOM_BOT_PERMISSIONS = [
|
export const WECOM_BOT_PERMISSIONS = [
|
||||||
|
'order.read',
|
||||||
|
'delivery.read',
|
||||||
|
'store.read',
|
||||||
|
'redeem.read',
|
||||||
|
'ticket.read',
|
||||||
'ticket.create',
|
'ticket.create',
|
||||||
'user.view_sms',
|
'user.read',
|
||||||
'delivery.view',
|
'user.read_sms',
|
||||||
|
'finance.store_bill.read',
|
||||||
|
'finance.partner_bill.read',
|
||||||
|
'finance.winery_bill.read',
|
||||||
|
'finance.logistics_bill.read',
|
||||||
|
'finance.payout.read',
|
||||||
|
'finance.withdrawal.read',
|
||||||
|
'support_ticket.read',
|
||||||
'support_ticket.create',
|
'support_ticket.create',
|
||||||
'support_ticket.progress',
|
'support_ticket.review',
|
||||||
'handbook.query',
|
'support_ticket.approve',
|
||||||
'server_log.view',
|
'support_ticket.reject',
|
||||||
'api.query',
|
'dev_plan.task.read',
|
||||||
|
'dev_plan.task.create',
|
||||||
|
'dev_plan.task.update_status',
|
||||||
|
'dev_plan.version.read',
|
||||||
|
'dev_plan.version.create',
|
||||||
|
'dev_plan.version.update_status',
|
||||||
|
'dev_plan.version.link_tasks',
|
||||||
|
'server_log.read',
|
||||||
|
'handbook.read',
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
export type WecomBotPermission = (typeof WECOM_BOT_PERMISSIONS)[number];
|
export type WecomBotPermission = (typeof WECOM_BOT_PERMISSIONS)[number];
|
||||||
|
|
||||||
export const WECOM_BOT_PERMISSION_LABELS: Record<WecomBotPermission, string> = {
|
export const WECOM_BOT_PERMISSION_LABELS: Record<WecomBotPermission, string> = {
|
||||||
|
'order.read': '查询订单',
|
||||||
|
'delivery.read': '查询配送/物流',
|
||||||
|
'store.read': '查询门店',
|
||||||
|
'redeem.read': '查询核销记录',
|
||||||
|
'ticket.read': '查询售后工单',
|
||||||
'ticket.create': '创建售后工单',
|
'ticket.create': '创建售后工单',
|
||||||
'user.view_sms': '查用户(短信验证)',
|
'user.read': '查询用户(脱敏)',
|
||||||
'delivery.view': '查快递信息',
|
'user.read_sms': '查用户(短信验证)',
|
||||||
|
'finance.store_bill.read': '查询门店账单',
|
||||||
|
'finance.partner_bill.read': '查询合伙人账单',
|
||||||
|
'finance.winery_bill.read': '查询酒厂账单',
|
||||||
|
'finance.logistics_bill.read': '查询物流账单',
|
||||||
|
'finance.payout.read': '查询门店打款',
|
||||||
|
'finance.withdrawal.read': '查询门店提现',
|
||||||
|
'support_ticket.read': '查询技术支持工单',
|
||||||
'support_ticket.create': '创建技术支持工单',
|
'support_ticket.create': '创建技术支持工单',
|
||||||
'support_ticket.progress': '查看开发进度',
|
'support_ticket.review': '审批技术支持工单(通过/驳回)',
|
||||||
'handbook.query': '查询使用手册',
|
'support_ticket.approve': '通过技术支持工单',
|
||||||
'server_log.view': '查看服务器日志',
|
'support_ticket.reject': '驳回技术支持工单',
|
||||||
'api.query': '查询业务 API(只读)',
|
'dev_plan.task.read': '查询开发任务',
|
||||||
|
'dev_plan.task.create': '新建开发任务',
|
||||||
|
'dev_plan.task.update_status': '修改任务状态',
|
||||||
|
'dev_plan.version.read': '查询开发版本',
|
||||||
|
'dev_plan.version.create': '新建开发版本',
|
||||||
|
'dev_plan.version.update_status': '修改版本状态',
|
||||||
|
'dev_plan.version.link_tasks': '关联任务到版本',
|
||||||
|
'server_log.read': '查看服务器日志',
|
||||||
|
'handbook.read': '查询使用手册',
|
||||||
};
|
};
|
||||||
|
|
||||||
/** 预置机器人角色(创建时可选;权限可按角色带出默认值后自定义) */
|
/** Admin UI 权限分组 */
|
||||||
|
export const WECOM_BOT_PERMISSION_GROUPS: Array<{
|
||||||
|
key: string;
|
||||||
|
label: string;
|
||||||
|
permissions: WecomBotPermission[];
|
||||||
|
}> = [
|
||||||
|
{
|
||||||
|
key: 'order',
|
||||||
|
label: '订单与配送',
|
||||||
|
permissions: ['order.read', 'delivery.read'],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'store_redeem',
|
||||||
|
label: '门店与核销',
|
||||||
|
permissions: ['store.read', 'redeem.read'],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'ticket',
|
||||||
|
label: '售后工单',
|
||||||
|
permissions: ['ticket.read', 'ticket.create'],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'user',
|
||||||
|
label: '用户',
|
||||||
|
permissions: ['user.read', 'user.read_sms'],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'finance',
|
||||||
|
label: '财务',
|
||||||
|
permissions: [
|
||||||
|
'finance.store_bill.read',
|
||||||
|
'finance.partner_bill.read',
|
||||||
|
'finance.winery_bill.read',
|
||||||
|
'finance.logistics_bill.read',
|
||||||
|
'finance.payout.read',
|
||||||
|
'finance.withdrawal.read',
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'support',
|
||||||
|
label: '技术支持',
|
||||||
|
permissions: ['support_ticket.read', 'support_ticket.create', 'support_ticket.review', 'support_ticket.approve', 'support_ticket.reject'],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'dev_plan',
|
||||||
|
label: '开发计划',
|
||||||
|
permissions: ['dev_plan.task.read', 'dev_plan.task.create', 'dev_plan.task.update_status', 'dev_plan.version.read', 'dev_plan.version.create', 'dev_plan.version.update_status', 'dev_plan.version.link_tasks'],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'ops',
|
||||||
|
label: '运维与手册',
|
||||||
|
permissions: ['server_log.read', 'handbook.read'],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
/** 预置机器人角色 */
|
||||||
export const WECOM_BOT_ROLES = [
|
export const WECOM_BOT_ROLES = [
|
||||||
'CUSTOMER_SERVICE',
|
'CUSTOMER_SERVICE',
|
||||||
|
'FINANCE',
|
||||||
|
'OPERATIONS',
|
||||||
'TECH_SUPPORT',
|
'TECH_SUPPORT',
|
||||||
'TEAM_ASSISTANT',
|
|
||||||
'CUSTOM',
|
'CUSTOM',
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
export type WecomBotRole = (typeof WECOM_BOT_ROLES)[number];
|
export type WecomBotRole = (typeof WECOM_BOT_ROLES)[number];
|
||||||
|
|
||||||
|
/** 历史角色名 → 现行角色 */
|
||||||
|
export function normalizeWecomBotRole(raw: string): WecomBotRole {
|
||||||
|
if (raw === 'TEAM_ASSISTANT') return 'OPERATIONS';
|
||||||
|
if ((WECOM_BOT_ROLES as readonly string[]).includes(raw)) return raw as WecomBotRole;
|
||||||
|
return 'CUSTOM';
|
||||||
|
}
|
||||||
|
|
||||||
export const WECOM_BOT_ROLE_LABELS: Record<WecomBotRole, string> = {
|
export const WECOM_BOT_ROLE_LABELS: Record<WecomBotRole, string> = {
|
||||||
CUSTOMER_SERVICE: '客服机器人',
|
CUSTOMER_SERVICE: '客服助手',
|
||||||
TECH_SUPPORT: '技术支持机器人',
|
FINANCE: '财务助手',
|
||||||
TEAM_ASSISTANT: '团队助手',
|
OPERATIONS: '运营助手',
|
||||||
|
TECH_SUPPORT: '技术支持',
|
||||||
CUSTOM: '自定义',
|
CUSTOM: '自定义',
|
||||||
};
|
};
|
||||||
|
|
||||||
export const WECOM_BOT_ROLE_DEFAULT_PERMISSIONS: Record<WecomBotRole, WecomBotPermission[]> = {
|
export const WECOM_BOT_ROLE_DEFAULT_PERMISSIONS: Record<WecomBotRole, WecomBotPermission[]> = {
|
||||||
CUSTOMER_SERVICE: ['ticket.create', 'user.view_sms', 'delivery.view'],
|
CUSTOMER_SERVICE: [
|
||||||
TECH_SUPPORT: ['support_ticket.create', 'support_ticket.progress', 'server_log.view', 'api.query'],
|
'order.read',
|
||||||
TEAM_ASSISTANT: ['handbook.query'],
|
'delivery.read',
|
||||||
|
'store.read',
|
||||||
|
'redeem.read',
|
||||||
|
'ticket.read',
|
||||||
|
'ticket.create',
|
||||||
|
'user.read_sms',
|
||||||
|
],
|
||||||
|
FINANCE: [
|
||||||
|
'finance.store_bill.read',
|
||||||
|
'finance.partner_bill.read',
|
||||||
|
'finance.winery_bill.read',
|
||||||
|
'finance.logistics_bill.read',
|
||||||
|
'finance.payout.read',
|
||||||
|
'finance.withdrawal.read',
|
||||||
|
'order.read',
|
||||||
|
],
|
||||||
|
OPERATIONS: [
|
||||||
|
'order.read',
|
||||||
|
'store.read',
|
||||||
|
'user.read',
|
||||||
|
'redeem.read',
|
||||||
|
'delivery.read',
|
||||||
|
'handbook.read',
|
||||||
|
],
|
||||||
|
TECH_SUPPORT: [
|
||||||
|
'support_ticket.read',
|
||||||
|
'support_ticket.create',
|
||||||
|
'support_ticket.review',
|
||||||
|
'dev_plan.task.read',
|
||||||
|
'dev_plan.task.create',
|
||||||
|
'dev_plan.task.update_status',
|
||||||
|
'dev_plan.version.read',
|
||||||
|
'dev_plan.version.create',
|
||||||
|
'dev_plan.version.update_status',
|
||||||
|
'dev_plan.version.link_tasks',
|
||||||
|
'server_log.read',
|
||||||
|
],
|
||||||
CUSTOM: [],
|
CUSTOM: [],
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** 旧版权限 → 新版权限(读取 DB 时迁移) */
|
||||||
|
const LEGACY_PERMISSION_MAP: Record<string, WecomBotPermission[]> = {
|
||||||
|
'ticket.create': ['ticket.create'],
|
||||||
|
'user.view_sms': ['user.read_sms'],
|
||||||
|
'delivery.view': ['delivery.read'],
|
||||||
|
'support_ticket.create': ['support_ticket.create'],
|
||||||
|
'support_ticket.progress': ['support_ticket.read', 'dev_plan.task.read'],
|
||||||
|
'handbook.query': ['handbook.read'],
|
||||||
|
'server_log.view': ['server_log.read'],
|
||||||
|
'api.query': ['order.read'],
|
||||||
|
'api.read.all': [
|
||||||
|
'order.read',
|
||||||
|
'delivery.read',
|
||||||
|
'store.read',
|
||||||
|
'redeem.read',
|
||||||
|
'support_ticket.read',
|
||||||
|
'dev_plan.task.read',
|
||||||
|
'dev_plan.version.read',
|
||||||
|
'user.read',
|
||||||
|
],
|
||||||
|
'db.read': ['support_ticket.read', 'order.read'],
|
||||||
|
};
|
||||||
|
|
||||||
|
export function migrateWecomBotPermissions(raw: string[]): WecomBotPermission[] {
|
||||||
|
const set = new Set<WecomBotPermission>();
|
||||||
|
const valid = new Set<string>(WECOM_BOT_PERMISSIONS);
|
||||||
|
for (const p of raw) {
|
||||||
|
if (valid.has(p)) {
|
||||||
|
set.add(p as WecomBotPermission);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const mapped = LEGACY_PERMISSION_MAP[p];
|
||||||
|
if (mapped) mapped.forEach((m) => set.add(m));
|
||||||
|
}
|
||||||
|
return [...set];
|
||||||
|
}
|
||||||
|
|
||||||
export function parseWecomBotPermissions(
|
export function parseWecomBotPermissions(
|
||||||
raw?: string | string[] | null,
|
raw?: string | string[] | null,
|
||||||
): WecomBotPermission[] {
|
): WecomBotPermission[] {
|
||||||
const set = new Set<string>(WECOM_BOT_PERMISSIONS);
|
const valid = new Set<string>(WECOM_BOT_PERMISSIONS);
|
||||||
const list = Array.isArray(raw)
|
let list: string[];
|
||||||
? raw
|
|
||||||
: String(raw ?? '')
|
if (Array.isArray(raw)) {
|
||||||
|
list = raw.map(String);
|
||||||
|
} else {
|
||||||
|
const text = String(raw ?? '').trim();
|
||||||
|
if (!text) {
|
||||||
|
list = [];
|
||||||
|
} else if (text.startsWith('[')) {
|
||||||
|
try {
|
||||||
|
const parsed: unknown = JSON.parse(text);
|
||||||
|
list = Array.isArray(parsed) ? parsed.map(String) : [];
|
||||||
|
} catch {
|
||||||
|
list = text
|
||||||
.split(/[,,\s]+/)
|
.split(/[,,\s]+/)
|
||||||
.map((s) => s.trim())
|
.map((s) => s.trim())
|
||||||
.filter(Boolean);
|
.filter(Boolean);
|
||||||
return [...new Set(list.filter((s): s is WecomBotPermission => set.has(s)))];
|
}
|
||||||
|
} else {
|
||||||
|
list = text
|
||||||
|
.split(/[,,\s]+/)
|
||||||
|
.map((s) => s.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const migrated = migrateWecomBotPermissions(list);
|
||||||
|
if (migrated.length) return migrated;
|
||||||
|
return [...new Set(list.filter((s): s is WecomBotPermission => valid.has(s)))];
|
||||||
}
|
}
|
||||||
|
|
||||||
export function resolveWecomBotPermissions(
|
export function resolveWecomBotPermissions(
|
||||||
@@ -69,17 +268,32 @@ export function resolveWecomBotPermissions(
|
|||||||
return [...WECOM_BOT_ROLE_DEFAULT_PERMISSIONS[role]];
|
return [...WECOM_BOT_ROLE_DEFAULT_PERMISSIONS[role]];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function parseWecomUserIdList(raw?: string | string[] | null): string[] {
|
||||||
|
if (Array.isArray(raw)) return [...new Set(raw.map(String).filter(Boolean))];
|
||||||
|
const text = String(raw ?? '').trim();
|
||||||
|
if (!text) return [];
|
||||||
|
if (text.startsWith('[')) {
|
||||||
|
try {
|
||||||
|
const parsed: unknown = JSON.parse(text);
|
||||||
|
return Array.isArray(parsed) ? [...new Set(parsed.map(String).filter(Boolean))] : [];
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return [...new Set(text.split(/[,,\s]+/).map((s) => s.trim()).filter(Boolean))];
|
||||||
|
}
|
||||||
|
|
||||||
export type WecomBotDto = {
|
export type WecomBotDto = {
|
||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
role: WecomBotRole;
|
role: WecomBotRole;
|
||||||
botId: string;
|
botId: string;
|
||||||
/** 列表/详情不返回明文;仅表示是否已配置 */
|
|
||||||
secretConfigured: boolean;
|
secretConfigured: boolean;
|
||||||
avatarUrl: string | null;
|
avatarUrl: string | null;
|
||||||
welcome: string | null;
|
welcome: string | null;
|
||||||
permissions: WecomBotPermission[];
|
permissions: WecomBotPermission[];
|
||||||
/** 未匹配指令时是否调用绑定的语言模型 */
|
/** 可执行 support_ticket.review 的企微 userid 白名单 */
|
||||||
|
reviewSuperAdminWecomUserIds: string[];
|
||||||
aiEnabled: boolean;
|
aiEnabled: boolean;
|
||||||
llmConfigId: string | null;
|
llmConfigId: string | null;
|
||||||
llmConfigName: string | null;
|
llmConfigName: string | null;
|
||||||
@@ -99,6 +313,7 @@ export type CreateWecomBotRequest = {
|
|||||||
avatarUrl?: string | null;
|
avatarUrl?: string | null;
|
||||||
welcome?: string | null;
|
welcome?: string | null;
|
||||||
permissions?: WecomBotPermission[];
|
permissions?: WecomBotPermission[];
|
||||||
|
reviewSuperAdminWecomUserIds?: string[];
|
||||||
aiEnabled?: boolean;
|
aiEnabled?: boolean;
|
||||||
llmConfigId?: string | null;
|
llmConfigId?: string | null;
|
||||||
knowledgeBaseId?: string | null;
|
knowledgeBaseId?: string | null;
|
||||||
@@ -110,14 +325,64 @@ export type UpdateWecomBotRequest = {
|
|||||||
name?: string;
|
name?: string;
|
||||||
role?: WecomBotRole;
|
role?: WecomBotRole;
|
||||||
botId?: string;
|
botId?: string;
|
||||||
/** 空或不传表示不修改 */
|
|
||||||
secret?: string;
|
secret?: string;
|
||||||
avatarUrl?: string | null;
|
avatarUrl?: string | null;
|
||||||
welcome?: string | null;
|
welcome?: string | null;
|
||||||
permissions?: WecomBotPermission[];
|
permissions?: WecomBotPermission[];
|
||||||
|
reviewSuperAdminWecomUserIds?: string[];
|
||||||
aiEnabled?: boolean;
|
aiEnabled?: boolean;
|
||||||
llmConfigId?: string | null;
|
llmConfigId?: string | null;
|
||||||
knowledgeBaseId?: string | null;
|
knowledgeBaseId?: string | null;
|
||||||
enabled?: boolean;
|
enabled?: boolean;
|
||||||
sortOrder?: number;
|
sortOrder?: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** 长连接运行时状态(Admin GET /admin/wecom-bots/runtime) */
|
||||||
|
export type WecomAibotRuntimeDto = {
|
||||||
|
masterEnabled: boolean;
|
||||||
|
bots: Array<{
|
||||||
|
id: string;
|
||||||
|
role: string;
|
||||||
|
key: string;
|
||||||
|
name: string;
|
||||||
|
enabled: boolean;
|
||||||
|
configured: boolean;
|
||||||
|
connected: boolean;
|
||||||
|
botIdMasked: string | null;
|
||||||
|
avatarUrl: string | null;
|
||||||
|
permissions: WecomBotPermission[];
|
||||||
|
lastError: string | null;
|
||||||
|
}>;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Admin 表单 permissions 与 UI 分组/catalog 对齐校验 */
|
||||||
|
export function assertWecomBotPermissionCatalogConsistent(): void {
|
||||||
|
const fromGroups = WECOM_BOT_PERMISSION_GROUPS.flatMap((g) => g.permissions);
|
||||||
|
const catalog = new Set<string>(WECOM_BOT_PERMISSIONS);
|
||||||
|
const groupSet = new Set(fromGroups);
|
||||||
|
for (const p of WECOM_BOT_PERMISSIONS) {
|
||||||
|
if (!groupSet.has(p)) throw new Error(`permission missing in UI groups: ${p}`);
|
||||||
|
if (!WECOM_BOT_PERMISSION_LABELS[p]) throw new Error(`permission missing label: ${p}`);
|
||||||
|
}
|
||||||
|
for (const p of fromGroups) {
|
||||||
|
if (!catalog.has(p)) throw new Error(`unknown permission in UI groups: ${p}`);
|
||||||
|
}
|
||||||
|
if (fromGroups.length !== groupSet.size) {
|
||||||
|
throw new Error('duplicate permission in UI groups');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export type WecomBotLogDto = {
|
||||||
|
id: string;
|
||||||
|
botId: string | null;
|
||||||
|
botName: string | null;
|
||||||
|
botKey: string | null;
|
||||||
|
wecomUserId: string;
|
||||||
|
action: string;
|
||||||
|
permission: string | null;
|
||||||
|
inputSummary: string | null;
|
||||||
|
success: boolean;
|
||||||
|
errorMessage: string | null;
|
||||||
|
latencyMs: number | null;
|
||||||
|
createdAt: string;
|
||||||
|
};
|
||||||
|
|||||||
@@ -0,0 +1,138 @@
|
|||||||
|
/** 企微群机器人 Webhook · 推送条件(v3.4.11) */
|
||||||
|
export const WECOM_PUSH_CONDITIONS = [
|
||||||
|
'alert.ops',
|
||||||
|
'support_ticket.created',
|
||||||
|
'alert.pay',
|
||||||
|
'alert.redeem',
|
||||||
|
'alert.system',
|
||||||
|
'alert.settlement',
|
||||||
|
'dev_plan.task_dispatch',
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
export type WecomPushCondition = (typeof WECOM_PUSH_CONDITIONS)[number];
|
||||||
|
|
||||||
|
export const WECOM_PUSH_CONDITION_LABELS: Record<WecomPushCondition, string> = {
|
||||||
|
'alert.ops': '运营告警(售后工单、客户端错误等)',
|
||||||
|
'support_ticket.created': '新建技术支持工单',
|
||||||
|
'alert.pay': '支付异常',
|
||||||
|
'alert.redeem': '核销异常',
|
||||||
|
'alert.system': '系统监控(5xx、回调、定时任务)',
|
||||||
|
'alert.settlement': '结算任务告警',
|
||||||
|
'dev_plan.task_dispatch': '开发任务评审派发',
|
||||||
|
};
|
||||||
|
|
||||||
|
export const WECOM_PUSH_CONDITION_GROUPS: Array<{
|
||||||
|
key: string;
|
||||||
|
label: string;
|
||||||
|
conditions: WecomPushCondition[];
|
||||||
|
}> = [
|
||||||
|
{
|
||||||
|
key: 'ops',
|
||||||
|
label: '工单与运营',
|
||||||
|
conditions: ['alert.ops', 'support_ticket.created'],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'pay_redeem',
|
||||||
|
label: '支付与核销',
|
||||||
|
conditions: ['alert.pay', 'alert.redeem'],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'system',
|
||||||
|
label: '系统与结算',
|
||||||
|
conditions: ['alert.system', 'alert.settlement'],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'dev_plan',
|
||||||
|
label: '开发计划',
|
||||||
|
conditions: ['dev_plan.task_dispatch'],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
/** 默认「运营告警」推送条件 */
|
||||||
|
export const WECOM_PUSH_DEFAULT_ALERT_CONDITIONS: WecomPushCondition[] = [
|
||||||
|
'alert.ops',
|
||||||
|
'support_ticket.created',
|
||||||
|
'alert.pay',
|
||||||
|
'alert.redeem',
|
||||||
|
'alert.system',
|
||||||
|
'alert.settlement',
|
||||||
|
];
|
||||||
|
|
||||||
|
/** 默认「开发任务派发」推送条件 */
|
||||||
|
export const WECOM_PUSH_DEFAULT_DEV_DISPATCH_CONDITIONS: WecomPushCondition[] = [
|
||||||
|
'dev_plan.task_dispatch',
|
||||||
|
'support_ticket.created',
|
||||||
|
];
|
||||||
|
|
||||||
|
export function parseWecomPushConditions(
|
||||||
|
raw?: string | string[] | null,
|
||||||
|
): WecomPushCondition[] {
|
||||||
|
const valid = new Set<string>(WECOM_PUSH_CONDITIONS);
|
||||||
|
let list: string[];
|
||||||
|
|
||||||
|
if (Array.isArray(raw)) {
|
||||||
|
list = raw.map(String);
|
||||||
|
} else {
|
||||||
|
const text = String(raw ?? '').trim();
|
||||||
|
if (!text) {
|
||||||
|
list = [];
|
||||||
|
} else if (text.startsWith('[')) {
|
||||||
|
try {
|
||||||
|
const parsed: unknown = JSON.parse(text);
|
||||||
|
list = Array.isArray(parsed) ? parsed.map(String) : [];
|
||||||
|
} catch {
|
||||||
|
list = text
|
||||||
|
.split(/[,,\s]+/)
|
||||||
|
.map((s) => s.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
list = text
|
||||||
|
.split(/[,,\s]+/)
|
||||||
|
.map((s) => s.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return [...new Set(list.filter((s): s is WecomPushCondition => valid.has(s)))];
|
||||||
|
}
|
||||||
|
|
||||||
|
export type WecomMessagePushDto = {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
avatarUrl: string | null;
|
||||||
|
webhookUrl: string;
|
||||||
|
webhookUrlMasked: string;
|
||||||
|
enabled: boolean;
|
||||||
|
mentionWecomUserId: string | null;
|
||||||
|
pushConditions: WecomPushCondition[];
|
||||||
|
sortOrder: number;
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type CreateWecomMessagePushRequest = {
|
||||||
|
name: string;
|
||||||
|
avatarUrl?: string | null;
|
||||||
|
webhookUrl: string;
|
||||||
|
enabled?: boolean;
|
||||||
|
mentionWecomUserId?: string | null;
|
||||||
|
pushConditions: WecomPushCondition[];
|
||||||
|
sortOrder?: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type UpdateWecomMessagePushRequest = {
|
||||||
|
name?: string;
|
||||||
|
avatarUrl?: string | null;
|
||||||
|
webhookUrl?: string;
|
||||||
|
enabled?: boolean;
|
||||||
|
mentionWecomUserId?: string | null;
|
||||||
|
pushConditions?: WecomPushCondition[];
|
||||||
|
sortOrder?: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function maskWecomWebhookUrl(url: string): string {
|
||||||
|
const u = url.trim();
|
||||||
|
if (u.length <= 24) return `${u.slice(0, 8)}…`;
|
||||||
|
return `${u.slice(0, 20)}…${u.slice(-8)}`;
|
||||||
|
}
|
||||||
@@ -64,9 +64,10 @@ WX_MINI_MSG_AES_KEY=
|
|||||||
# 企业微信智能机器人总开关(Bot 实例在 HQ「企微机器人」模块创建)
|
# 企业微信智能机器人总开关(Bot 实例在 HQ「企微机器人」模块创建)
|
||||||
WECOM_AIBOT_ENABLED=false
|
WECOM_AIBOT_ENABLED=false
|
||||||
|
|
||||||
# 运营告警:企业微信群机器人 Webhook(单向推送,与智能机器人长连接无关)
|
# 运营告警 Webhook(已废弃运行时读取,仅 seed 一次性导入到 HQ「消息推送」)
|
||||||
WECOM_ALERT_ENABLED=false
|
# 配置后执行 pnpm prisma:seed-wecom-push 或 API 启动时自动 ensureDefaults
|
||||||
WECOM_ALERT_WEBHOOK_URL=
|
# WECOM_ALERT_ENABLED=false
|
||||||
|
# WECOM_ALERT_WEBHOOK_URL=
|
||||||
WECOM_ALERT_ENV_LABEL=local
|
WECOM_ALERT_ENV_LABEL=local
|
||||||
|
|
||||||
# 腾讯位置服务(地理编码 / 逆地理 / 地点搜索选点,服务端调用)
|
# 腾讯位置服务(地理编码 / 逆地理 / 地点搜索选点,服务端调用)
|
||||||
|
|||||||
@@ -53,8 +53,9 @@ WX_MINI_MSG_AES_KEY=
|
|||||||
WECOM_AIBOT_ENABLED=false
|
WECOM_AIBOT_ENABLED=false
|
||||||
|
|
||||||
# 运营告警:企业微信群机器人 Webhook
|
# 运营告警:企业微信群机器人 Webhook
|
||||||
WECOM_ALERT_ENABLED=false
|
# 运营告警 Webhook(已废弃运行时读取,仅 seed 导入 HQ「消息推送」)
|
||||||
WECOM_ALERT_WEBHOOK_URL=
|
# WECOM_ALERT_ENABLED=false
|
||||||
|
# WECOM_ALERT_WEBHOOK_URL=
|
||||||
WECOM_ALERT_ENV_LABEL=production
|
WECOM_ALERT_ENV_LABEL=production
|
||||||
|
|
||||||
OSS_ACCESS_KEY_ID=
|
OSS_ACCESS_KEY_ID=
|
||||||
|
|||||||
@@ -53,8 +53,9 @@ WX_MINI_MSG_AES_KEY=
|
|||||||
WECOM_AIBOT_ENABLED=false
|
WECOM_AIBOT_ENABLED=false
|
||||||
|
|
||||||
# 运营告警:企业微信群机器人 Webhook
|
# 运营告警:企业微信群机器人 Webhook
|
||||||
WECOM_ALERT_ENABLED=false
|
# 运营告警 Webhook(已废弃运行时读取,仅 seed 导入 HQ「消息推送」)
|
||||||
WECOM_ALERT_WEBHOOK_URL=
|
# WECOM_ALERT_ENABLED=false
|
||||||
|
# WECOM_ALERT_WEBHOOK_URL=
|
||||||
WECOM_ALERT_ENV_LABEL=staging
|
WECOM_ALERT_ENV_LABEL=staging
|
||||||
|
|
||||||
OSS_ACCESS_KEY_ID=
|
OSS_ACCESS_KEY_ID=
|
||||||
|
|||||||
@@ -16,6 +16,8 @@
|
|||||||
"prisma:seed-stats": "ts-node --transpile-only prisma/seed-stats-mock.ts",
|
"prisma:seed-stats": "ts-node --transpile-only prisma/seed-stats-mock.ts",
|
||||||
"prisma:migrate-city-partner": "ts-node --transpile-only prisma/migrate-city-partner.ts",
|
"prisma:migrate-city-partner": "ts-node --transpile-only prisma/migrate-city-partner.ts",
|
||||||
"prisma:seed-legacy": "ts-node --transpile-only prisma/seed-prev1.ts",
|
"prisma:seed-legacy": "ts-node --transpile-only prisma/seed-prev1.ts",
|
||||||
|
"prisma:seed-wecom-push": "ts-node --transpile-only prisma/seed-wecom-message-push.ts",
|
||||||
|
"prisma:migrate-wecom-push": "ts-node --transpile-only prisma/migrate-wecom-message-push.ts",
|
||||||
"prisma:upsert-super-admin": "ts-node --transpile-only scripts/upsert-super-admin.ts",
|
"prisma:upsert-super-admin": "ts-node --transpile-only scripts/upsert-super-admin.ts",
|
||||||
"prisma:sync-benefit": "ts-node --transpile-only prisma/sync-benefit-to-price.ts"
|
"prisma:sync-benefit": "ts-node --transpile-only prisma/sync-benefit-to-price.ts"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -0,0 +1,91 @@
|
|||||||
|
/**
|
||||||
|
* 发版前一次性迁移:在 prisma db push 删除 task_dispatch_* 列之前执行。
|
||||||
|
* 创建 wecom_message_push 表(若不存在)并写入默认推送。
|
||||||
|
*/
|
||||||
|
import { PrismaClient } from '@prisma/client';
|
||||||
|
import {
|
||||||
|
WECOM_PUSH_DEFAULT_ALERT_CONDITIONS,
|
||||||
|
WECOM_PUSH_DEFAULT_DEV_DISPATCH_CONDITIONS,
|
||||||
|
} from '@dukang/shared-types';
|
||||||
|
|
||||||
|
const prisma = new PrismaClient();
|
||||||
|
|
||||||
|
async function ensureTable() {
|
||||||
|
await prisma.$executeRawUnsafe(`
|
||||||
|
CREATE TABLE IF NOT EXISTS wecom_message_push (
|
||||||
|
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
name VARCHAR(64) NOT NULL,
|
||||||
|
avatar_url VARCHAR(512) NULL,
|
||||||
|
webhook_url VARCHAR(512) NOT NULL,
|
||||||
|
enabled TINYINT(1) NOT NULL DEFAULT 1,
|
||||||
|
mention_wecom_user_id VARCHAR(64) NULL,
|
||||||
|
push_conditions TEXT NOT NULL,
|
||||||
|
sort_order INT NOT NULL DEFAULT 0,
|
||||||
|
created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||||
|
updated_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
|
||||||
|
INDEX wecom_message_push_enabled_sort_order_idx (enabled, sort_order)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
await ensureTable();
|
||||||
|
const count = await prisma.wecomMessagePush.count();
|
||||||
|
if (count > 0) {
|
||||||
|
console.log(`wecom_message_push already has ${count} row(s), skip`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const alertUrl = (process.env.WECOM_ALERT_WEBHOOK_URL || '').trim();
|
||||||
|
if (alertUrl) {
|
||||||
|
await prisma.wecomMessagePush.create({
|
||||||
|
data: {
|
||||||
|
name: '运营告警',
|
||||||
|
webhookUrl: alertUrl,
|
||||||
|
enabled: process.env.WECOM_ALERT_ENABLED !== 'false',
|
||||||
|
pushConditions: JSON.stringify(WECOM_PUSH_DEFAULT_ALERT_CONDITIONS),
|
||||||
|
sortOrder: 0,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
console.log('migrated: 运营告警');
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const rows = await prisma.$queryRawUnsafe<
|
||||||
|
Array<{
|
||||||
|
task_dispatch_webhook_url: string | null;
|
||||||
|
task_dispatch_wecom_user_id: string | null;
|
||||||
|
task_dispatch_enabled: number | boolean | null;
|
||||||
|
}>
|
||||||
|
>(
|
||||||
|
'SELECT task_dispatch_webhook_url, task_dispatch_wecom_user_id, task_dispatch_enabled FROM dev_plan_settings LIMIT 1',
|
||||||
|
);
|
||||||
|
const row = rows[0];
|
||||||
|
if (row?.task_dispatch_webhook_url?.trim()) {
|
||||||
|
await prisma.wecomMessagePush.create({
|
||||||
|
data: {
|
||||||
|
name: '开发任务派发',
|
||||||
|
webhookUrl: row.task_dispatch_webhook_url.trim(),
|
||||||
|
enabled: !!row.task_dispatch_enabled,
|
||||||
|
mentionWecomUserId: row.task_dispatch_wecom_user_id?.trim() || null,
|
||||||
|
pushConditions: JSON.stringify(WECOM_PUSH_DEFAULT_DEV_DISPATCH_CONDITIONS),
|
||||||
|
sortOrder: 10,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
console.log('migrated: 开发任务派发');
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.log('dev_plan_settings task_dispatch columns unavailable:', e instanceof Error ? e.message : e);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('migrate-wecom-message-push done');
|
||||||
|
}
|
||||||
|
|
||||||
|
main()
|
||||||
|
.catch((e) => {
|
||||||
|
console.error(e);
|
||||||
|
process.exit(1);
|
||||||
|
})
|
||||||
|
.finally(async () => {
|
||||||
|
await prisma.$disconnect();
|
||||||
|
});
|
||||||
@@ -109,6 +109,25 @@ enum SupportTicketStatus {
|
|||||||
PASSED
|
PASSED
|
||||||
}
|
}
|
||||||
|
|
||||||
|
enum DevPlanTaskType {
|
||||||
|
BUG
|
||||||
|
REQUIREMENT
|
||||||
|
OPTIMIZATION
|
||||||
|
}
|
||||||
|
|
||||||
|
enum DevPlanTaskStatus {
|
||||||
|
TODO
|
||||||
|
DEVELOPED
|
||||||
|
RELEASED
|
||||||
|
}
|
||||||
|
|
||||||
|
enum DevPlanVersionStatus {
|
||||||
|
PENDING
|
||||||
|
IN_PROGRESS
|
||||||
|
TESTING
|
||||||
|
RELEASED
|
||||||
|
}
|
||||||
|
|
||||||
enum InvoiceTitleType {
|
enum InvoiceTitleType {
|
||||||
PERSONAL
|
PERSONAL
|
||||||
ENTERPRISE
|
ENTERPRISE
|
||||||
@@ -396,9 +415,10 @@ model WecomBot {
|
|||||||
secret String @db.VarChar(256)
|
secret String @db.VarChar(256)
|
||||||
avatarUrl String? @map("avatar_url") @db.VarChar(512)
|
avatarUrl String? @map("avatar_url") @db.VarChar(512)
|
||||||
welcome String? @db.VarChar(1024)
|
welcome String? @db.VarChar(1024)
|
||||||
/// JSON 字符串数组,如 ["ticket.create","user.view_sms"]
|
/// JSON 字符串数组,模块化权限
|
||||||
permissions String @db.Text
|
permissions String @db.Text
|
||||||
/// 未匹配指令时是否调用语言模型
|
/// 可执行 support_ticket.review 的企微 userid 白名单
|
||||||
|
reviewSuperAdminWecomUserIds String? @map("review_super_admin_wecom_user_ids") @db.Text
|
||||||
aiEnabled Boolean @default(false) @map("ai_enabled")
|
aiEnabled Boolean @default(false) @map("ai_enabled")
|
||||||
llmConfigId BigInt? @map("llm_config_id") @db.UnsignedBigInt
|
llmConfigId BigInt? @map("llm_config_id") @db.UnsignedBigInt
|
||||||
knowledgeBaseId BigInt? @map("knowledge_base_id") @db.UnsignedBigInt
|
knowledgeBaseId BigInt? @map("knowledge_base_id") @db.UnsignedBigInt
|
||||||
@@ -409,6 +429,7 @@ model WecomBot {
|
|||||||
|
|
||||||
llmConfig LlmApiConfig? @relation(fields: [llmConfigId], references: [id], onDelete: SetNull)
|
llmConfig LlmApiConfig? @relation(fields: [llmConfigId], references: [id], onDelete: SetNull)
|
||||||
knowledgeBase KnowledgeBase? @relation(fields: [knowledgeBaseId], references: [id], onDelete: SetNull)
|
knowledgeBase KnowledgeBase? @relation(fields: [knowledgeBaseId], references: [id], onDelete: SetNull)
|
||||||
|
wecomBotLogs LogWecomBot[]
|
||||||
|
|
||||||
@@index([enabled, sortOrder])
|
@@index([enabled, sortOrder])
|
||||||
@@index([llmConfigId])
|
@@index([llmConfigId])
|
||||||
@@ -416,6 +437,46 @@ model WecomBot {
|
|||||||
@@map("wecom_bot")
|
@@map("wecom_bot")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 企微机器人操作审计
|
||||||
|
model LogWecomBot {
|
||||||
|
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||||
|
botId BigInt? @map("bot_id") @db.UnsignedBigInt
|
||||||
|
botKey String? @map("bot_key") @db.VarChar(64)
|
||||||
|
wecomUserId String @map("wecom_user_id") @db.VarChar(64)
|
||||||
|
action String @db.VarChar(64)
|
||||||
|
permission String? @db.VarChar(64)
|
||||||
|
inputSummary String? @map("input_summary") @db.VarChar(512)
|
||||||
|
success Boolean @default(true)
|
||||||
|
errorMessage String? @map("error_message") @db.VarChar(512)
|
||||||
|
latencyMs Int? @map("latency_ms")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
|
||||||
|
|
||||||
|
bot WecomBot? @relation(fields: [botId], references: [id], onDelete: SetNull)
|
||||||
|
|
||||||
|
@@index([botId, createdAt])
|
||||||
|
@@index([wecomUserId, createdAt])
|
||||||
|
@@index([action, createdAt])
|
||||||
|
@@map("log_wecom_bot")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 企微群机器人 Webhook 消息推送(v3.4.11)
|
||||||
|
model WecomMessagePush {
|
||||||
|
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||||
|
name String @db.VarChar(64)
|
||||||
|
avatarUrl String? @map("avatar_url") @db.VarChar(512)
|
||||||
|
webhookUrl String @map("webhook_url") @db.VarChar(512)
|
||||||
|
enabled Boolean @default(true)
|
||||||
|
mentionWecomUserId String? @map("mention_wecom_user_id") @db.VarChar(64)
|
||||||
|
/// JSON 字符串数组,推送条件 key
|
||||||
|
pushConditions String @map("push_conditions") @db.Text
|
||||||
|
sortOrder Int @default(0) @map("sort_order")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at") @db.DateTime(3)
|
||||||
|
|
||||||
|
@@index([enabled, sortOrder])
|
||||||
|
@@map("wecom_message_push")
|
||||||
|
}
|
||||||
|
|
||||||
/// HQ 语言模型 API 配置(非超管仅可见/可开关自己创建的)
|
/// HQ 语言模型 API 配置(非超管仅可见/可开关自己创建的)
|
||||||
model LlmApiConfig {
|
model LlmApiConfig {
|
||||||
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||||
@@ -602,6 +663,87 @@ model CommonSupportTicket {
|
|||||||
@@index([ticketType, status])
|
@@index([ticketType, status])
|
||||||
@@index([creatorId])
|
@@index([creatorId])
|
||||||
@@map("common_support_ticket")
|
@@map("common_support_ticket")
|
||||||
|
|
||||||
|
devPlanTasks DevPlanTask[]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 开发计划 · 任务
|
||||||
|
model DevPlanTask {
|
||||||
|
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||||
|
taskNo String @unique @map("task_no") @db.VarChar(32)
|
||||||
|
content String @db.Text
|
||||||
|
type DevPlanTaskType
|
||||||
|
status DevPlanTaskStatus @default(TODO)
|
||||||
|
creatorHqAccountId BigInt @map("creator_hq_account_id") @db.UnsignedBigInt
|
||||||
|
supportTicketId BigInt? @map("support_ticket_id") @db.UnsignedBigInt
|
||||||
|
lastDispatchedAt DateTime? @map("last_dispatched_at") @db.DateTime(3)
|
||||||
|
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
|
||||||
|
completedAt DateTime? @map("completed_at") @db.DateTime(3)
|
||||||
|
|
||||||
|
supportTicket CommonSupportTicket? @relation(fields: [supportTicketId], references: [id], onDelete: SetNull)
|
||||||
|
versionLinks DevPlanVersionTask[]
|
||||||
|
|
||||||
|
@@index([status, createdAt])
|
||||||
|
@@index([supportTicketId])
|
||||||
|
@@map("dev_plan_task")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 开发计划 · 版本
|
||||||
|
model DevPlanVersion {
|
||||||
|
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||||
|
versionNo String @unique @map("version_no") @db.VarChar(32)
|
||||||
|
content String? @db.Text
|
||||||
|
status DevPlanVersionStatus @default(PENDING)
|
||||||
|
/// @deprecated 不再使用,保留兼容旧数据
|
||||||
|
assigneeHqAccountId BigInt? @map("assignee_hq_account_id") @db.UnsignedBigInt
|
||||||
|
devStartedAt DateTime? @map("dev_started_at") @db.DateTime(3)
|
||||||
|
devCompletedAt DateTime? @map("dev_completed_at") @db.DateTime(3)
|
||||||
|
releasedAt DateTime? @map("released_at") @db.DateTime(3)
|
||||||
|
durationMinutes Int? @map("duration_minutes")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at") @db.DateTime(3)
|
||||||
|
|
||||||
|
taskLinks DevPlanVersionTask[]
|
||||||
|
|
||||||
|
@@index([status, createdAt])
|
||||||
|
@@map("dev_plan_version")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 开发计划 · 版本-任务多对多
|
||||||
|
model DevPlanVersionTask {
|
||||||
|
versionId BigInt @map("version_id") @db.UnsignedBigInt
|
||||||
|
taskId BigInt @map("task_id") @db.UnsignedBigInt
|
||||||
|
sortOrder Int @default(0) @map("sort_order")
|
||||||
|
|
||||||
|
version DevPlanVersion @relation(fields: [versionId], references: [id], onDelete: Cascade)
|
||||||
|
task DevPlanTask @relation(fields: [taskId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
|
@@id([versionId, taskId])
|
||||||
|
@@index([taskId])
|
||||||
|
@@map("dev_plan_version_task")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 开发计划 · 全局设置(单例 id=1)
|
||||||
|
model DevPlanSettings {
|
||||||
|
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||||
|
reviewAssistantLlmConfigId BigInt? @map("review_assistant_llm_config_id") @db.UnsignedBigInt
|
||||||
|
reviewAssistantKnowledgeBaseId BigInt? @map("review_assistant_knowledge_base_id") @db.UnsignedBigInt
|
||||||
|
reviewAssistantPrompt String? @map("review_assistant_prompt") @db.Text
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at") @db.DateTime(3)
|
||||||
|
|
||||||
|
@@map("dev_plan_settings")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 开发计划 · 任务派发审计
|
||||||
|
model DevPlanTaskDispatch {
|
||||||
|
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||||
|
taskIdsJson String @map("task_ids_json") @db.Text
|
||||||
|
supplement String? @db.Text
|
||||||
|
operatorHqAccountId BigInt @map("operator_hq_account_id") @db.UnsignedBigInt
|
||||||
|
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
|
||||||
|
|
||||||
|
@@index([createdAt])
|
||||||
|
@@map("dev_plan_task_dispatch")
|
||||||
}
|
}
|
||||||
|
|
||||||
model CommonProductItem {
|
model CommonProductItem {
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
/**
|
||||||
|
* 一次性迁移:空表时从 .env / 旧 dev_plan_settings 写入默认消息推送。
|
||||||
|
* 也可由 WecomMessagePushService.ensureDefaults() 在 API 启动时执行。
|
||||||
|
*/
|
||||||
|
import { PrismaClient } from '@prisma/client';
|
||||||
|
import {
|
||||||
|
WECOM_PUSH_DEFAULT_ALERT_CONDITIONS,
|
||||||
|
WECOM_PUSH_DEFAULT_DEV_DISPATCH_CONDITIONS,
|
||||||
|
} from '@dukang/shared-types';
|
||||||
|
|
||||||
|
const prisma = new PrismaClient();
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const count = await prisma.wecomMessagePush.count();
|
||||||
|
if (count > 0) {
|
||||||
|
console.log(`wecom_message_push already has ${count} row(s), skip seed`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const alertUrl = (process.env.WECOM_ALERT_WEBHOOK_URL || '').trim();
|
||||||
|
if (alertUrl) {
|
||||||
|
await prisma.wecomMessagePush.create({
|
||||||
|
data: {
|
||||||
|
name: '运营告警',
|
||||||
|
webhookUrl: alertUrl,
|
||||||
|
enabled: process.env.WECOM_ALERT_ENABLED !== 'false',
|
||||||
|
pushConditions: JSON.stringify(WECOM_PUSH_DEFAULT_ALERT_CONDITIONS),
|
||||||
|
sortOrder: 0,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
console.log('created push: 运营告警');
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const rows = await prisma.$queryRawUnsafe<
|
||||||
|
Array<{
|
||||||
|
task_dispatch_webhook_url: string | null;
|
||||||
|
task_dispatch_wecom_user_id: string | null;
|
||||||
|
task_dispatch_enabled: number | boolean | null;
|
||||||
|
}>
|
||||||
|
>(
|
||||||
|
'SELECT task_dispatch_webhook_url, task_dispatch_wecom_user_id, task_dispatch_enabled FROM dev_plan_settings LIMIT 1',
|
||||||
|
);
|
||||||
|
const row = rows[0];
|
||||||
|
if (row?.task_dispatch_webhook_url?.trim()) {
|
||||||
|
await prisma.wecomMessagePush.create({
|
||||||
|
data: {
|
||||||
|
name: '开发任务派发',
|
||||||
|
webhookUrl: row.task_dispatch_webhook_url.trim(),
|
||||||
|
enabled: !!row.task_dispatch_enabled,
|
||||||
|
mentionWecomUserId: row.task_dispatch_wecom_user_id?.trim() || null,
|
||||||
|
pushConditions: JSON.stringify(WECOM_PUSH_DEFAULT_DEV_DISPATCH_CONDITIONS),
|
||||||
|
sortOrder: 10,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
console.log('created push: 开发任务派发');
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.log('dev_plan_settings task_dispatch columns not found, skip dev dispatch migration');
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('wecom message push seed done');
|
||||||
|
}
|
||||||
|
|
||||||
|
main()
|
||||||
|
.catch((e) => {
|
||||||
|
console.error(e);
|
||||||
|
process.exit(1);
|
||||||
|
})
|
||||||
|
.finally(async () => {
|
||||||
|
await prisma.$disconnect();
|
||||||
|
});
|
||||||
@@ -21,6 +21,7 @@ import { CityScopeModule } from './modules/city-scope/city-scope.module';
|
|||||||
import { CommonModule } from './modules/common/common.module';
|
import { CommonModule } from './modules/common/common.module';
|
||||||
import { HqOperationModule } from './common/hq-operation/hq-operation.module';
|
import { HqOperationModule } from './common/hq-operation/hq-operation.module';
|
||||||
import { SystemConfigModule } from './common/system-config/system-config.module';
|
import { SystemConfigModule } from './common/system-config/system-config.module';
|
||||||
|
import { DevPlanModule } from './modules/dev-plan/dev-plan.module';
|
||||||
import { CallbacksModule } from './callbacks/callbacks.module';
|
import { CallbacksModule } from './callbacks/callbacks.module';
|
||||||
import { WecomModule } from './integrations/wecom/wecom.module';
|
import { WecomModule } from './integrations/wecom/wecom.module';
|
||||||
import { LoggingModule } from './common/logging/logging.module';
|
import { LoggingModule } from './common/logging/logging.module';
|
||||||
@@ -53,6 +54,7 @@ import { RequestIdMiddleware } from './common/logging/request-id.middleware';
|
|||||||
PromoModule,
|
PromoModule,
|
||||||
CityScopeModule,
|
CityScopeModule,
|
||||||
CommonModule,
|
CommonModule,
|
||||||
|
DevPlanModule,
|
||||||
HqOperationModule,
|
HqOperationModule,
|
||||||
LoggingModule,
|
LoggingModule,
|
||||||
CallbacksModule,
|
CallbacksModule,
|
||||||
|
|||||||
@@ -2,16 +2,15 @@ import { Global, Module } from '@nestjs/common';
|
|||||||
import { RedisModule } from '../redis/redis.module';
|
import { RedisModule } from '../redis/redis.module';
|
||||||
import { AlertService } from './alert.service';
|
import { AlertService } from './alert.service';
|
||||||
import { PayRedeemAnomalyService } from './pay-redeem-anomaly.service';
|
import { PayRedeemAnomalyService } from './pay-redeem-anomaly.service';
|
||||||
import { WecomWebhookAlertService } from '../../integrations/wecom/wecom-webhook-alert.service';
|
import { WecomMessagePushService } from '../../integrations/wecom/wecom-message-push.service';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 运营告警(企微 Webhook)。Global 以便 Filter / 各业务 Module 注入。
|
* 运营告警(企微 Webhook 多实例)。Global 以便 Filter / 各业务 Module 注入。
|
||||||
* Webhook 发送器在本 Module 注册,避免与 WecomModule↔Common 循环依赖。
|
|
||||||
*/
|
*/
|
||||||
@Global()
|
@Global()
|
||||||
@Module({
|
@Module({
|
||||||
imports: [RedisModule],
|
imports: [RedisModule],
|
||||||
providers: [WecomWebhookAlertService, AlertService, PayRedeemAnomalyService],
|
providers: [WecomMessagePushService, AlertService, PayRedeemAnomalyService],
|
||||||
exports: [WecomWebhookAlertService, AlertService, PayRedeemAnomalyService],
|
exports: [WecomMessagePushService, AlertService, PayRedeemAnomalyService],
|
||||||
})
|
})
|
||||||
export class AlertModule {}
|
export class AlertModule {}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { Injectable, Logger } from '@nestjs/common';
|
import { Injectable, Logger } from '@nestjs/common';
|
||||||
|
import type { WecomPushCondition } from '@dukang/shared-types';
|
||||||
import { RedisService } from '../redis/redis.service';
|
import { RedisService } from '../redis/redis.service';
|
||||||
import { WecomWebhookAlertService } from '../../integrations/wecom/wecom-webhook-alert.service';
|
import { WecomMessagePushService } from '../../integrations/wecom/wecom-message-push.service';
|
||||||
import { ALERT_DEDUPE_TTL_SEC, type AlertLevel } from './alert.constants';
|
import { ALERT_DEDUPE_TTL_SEC, type AlertLevel } from './alert.constants';
|
||||||
|
|
||||||
export type AlertNotifyInput = {
|
export type AlertNotifyInput = {
|
||||||
@@ -10,6 +11,8 @@ export type AlertNotifyInput = {
|
|||||||
detail: string;
|
detail: string;
|
||||||
dedupeKey: string;
|
dedupeKey: string;
|
||||||
dedupeTtlSec?: number;
|
dedupeTtlSec?: number;
|
||||||
|
/** 覆盖默认事件 key 映射 */
|
||||||
|
eventKeys?: WecomPushCondition[];
|
||||||
};
|
};
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
@@ -18,7 +21,7 @@ export class AlertService {
|
|||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly redis: RedisService,
|
private readonly redis: RedisService,
|
||||||
private readonly wecomWebhook: WecomWebhookAlertService,
|
private readonly wecomPush: WecomMessagePushService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
/** 异步告警,不阻塞调用方 */
|
/** 异步告警,不阻塞调用方 */
|
||||||
@@ -29,7 +32,9 @@ export class AlertService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async notifyAsync(input: AlertNotifyInput): Promise<boolean> {
|
async notifyAsync(input: AlertNotifyInput): Promise<boolean> {
|
||||||
if (!this.wecomWebhook.isEnabled()) return false;
|
const eventKeys = resolveAlertEventKeys(input);
|
||||||
|
const hasAny = await Promise.all(eventKeys.map((k) => this.wecomPush.hasEnabledPushes(k)));
|
||||||
|
if (!hasAny.some(Boolean)) return false;
|
||||||
|
|
||||||
const ttl = input.dedupeTtlSec ?? ALERT_DEDUPE_TTL_SEC;
|
const ttl = input.dedupeTtlSec ?? ALERT_DEDUPE_TTL_SEC;
|
||||||
const dedupeRedisKey = `alert:dedupe:${input.dedupeKey}`;
|
const dedupeRedisKey = `alert:dedupe:${input.dedupeKey}`;
|
||||||
@@ -42,38 +47,13 @@ export class AlertService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return this.sendMarkdownNow(input);
|
return this.sendMarkdownNow(input, eventKeys);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** HQ 测试推送:不去重,返回明确结果 */
|
private async sendMarkdownNow(
|
||||||
async sendTestAlert(): Promise<{ ok: boolean; message: string }> {
|
input: AlertNotifyInput,
|
||||||
const url = (process.env.WECOM_ALERT_WEBHOOK_URL || '').trim();
|
eventKeys: WecomPushCondition[],
|
||||||
if (!url) {
|
): Promise<boolean> {
|
||||||
return {
|
|
||||||
ok: false,
|
|
||||||
message: '未配置 WECOM_ALERT_WEBHOOK_URL,请在服务器 .env 中填写群机器人 Webhook',
|
|
||||||
};
|
|
||||||
}
|
|
||||||
if (process.env.WECOM_ALERT_ENABLED !== 'true') {
|
|
||||||
return {
|
|
||||||
ok: false,
|
|
||||||
message: '请先开启「启用企微运营告警 Webhook」并保存后再测试',
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const sent = await this.sendMarkdownNow({
|
|
||||||
level: 'P2',
|
|
||||||
category: 'ops',
|
|
||||||
title: '告警测试',
|
|
||||||
detail: '你好,这是一条告警测试消息',
|
|
||||||
dedupeKey: `test|${Date.now()}`,
|
|
||||||
});
|
|
||||||
return sent
|
|
||||||
? { ok: true, message: '已发送测试告警,请查看企微群' }
|
|
||||||
: { ok: false, message: 'Webhook 调用失败,请检查 URL 或 API 日志' };
|
|
||||||
}
|
|
||||||
|
|
||||||
private async sendMarkdownNow(input: AlertNotifyInput): Promise<boolean> {
|
|
||||||
const envLabel = (process.env.WECOM_ALERT_ENV_LABEL || process.env.NODE_ENV || 'local').trim();
|
const envLabel = (process.env.WECOM_ALERT_ENV_LABEL || process.env.NODE_ENV || 'local').trim();
|
||||||
const now = new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' });
|
const now = new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' });
|
||||||
const content = [
|
const content = [
|
||||||
@@ -85,8 +65,21 @@ export class AlertService {
|
|||||||
escapeMd(input.detail).slice(0, 3500),
|
escapeMd(input.detail).slice(0, 3500),
|
||||||
].join('\n');
|
].join('\n');
|
||||||
|
|
||||||
return this.wecomWebhook.sendMarkdown(content);
|
let sent = 0;
|
||||||
|
for (const eventKey of eventKeys) {
|
||||||
|
sent += await this.wecomPush.dispatchMarkdown(eventKey, content, { applyMention: false });
|
||||||
}
|
}
|
||||||
|
return sent > 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveAlertEventKeys(input: AlertNotifyInput): WecomPushCondition[] {
|
||||||
|
if (input.eventKeys?.length) return [...new Set(input.eventKeys)];
|
||||||
|
if (input.category === 'pay') return ['alert.pay'];
|
||||||
|
if (input.category === 'redeem') return ['alert.redeem'];
|
||||||
|
if (input.category === 'settlement') return ['alert.settlement'];
|
||||||
|
if (input.category === 'ops') return ['alert.ops'];
|
||||||
|
return ['alert.system'];
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 轻量转义,保留企微 markdown 的 <font> 标签可用 */
|
/** 轻量转义,保留企微 markdown 的 <font> 标签可用 */
|
||||||
|
|||||||
@@ -84,6 +84,10 @@ export const HqOperationAction = {
|
|||||||
WECOM_BOT_UPDATE: 'WECOM_BOT_UPDATE',
|
WECOM_BOT_UPDATE: 'WECOM_BOT_UPDATE',
|
||||||
WECOM_BOT_DELETE: 'WECOM_BOT_DELETE',
|
WECOM_BOT_DELETE: 'WECOM_BOT_DELETE',
|
||||||
WECOM_BOT_RELOAD: 'WECOM_BOT_RELOAD',
|
WECOM_BOT_RELOAD: 'WECOM_BOT_RELOAD',
|
||||||
|
WECOM_MESSAGE_PUSH_CREATE: 'WECOM_MESSAGE_PUSH_CREATE',
|
||||||
|
WECOM_MESSAGE_PUSH_UPDATE: 'WECOM_MESSAGE_PUSH_UPDATE',
|
||||||
|
WECOM_MESSAGE_PUSH_DELETE: 'WECOM_MESSAGE_PUSH_DELETE',
|
||||||
|
WECOM_MESSAGE_PUSH_TEST: 'WECOM_MESSAGE_PUSH_TEST',
|
||||||
LLM_CONFIG_CREATE: 'LLM_CONFIG_CREATE',
|
LLM_CONFIG_CREATE: 'LLM_CONFIG_CREATE',
|
||||||
LLM_CONFIG_UPDATE: 'LLM_CONFIG_UPDATE',
|
LLM_CONFIG_UPDATE: 'LLM_CONFIG_UPDATE',
|
||||||
LLM_CONFIG_DELETE: 'LLM_CONFIG_DELETE',
|
LLM_CONFIG_DELETE: 'LLM_CONFIG_DELETE',
|
||||||
@@ -100,6 +104,19 @@ export const HqOperationAction = {
|
|||||||
SYSTEM_CONFIG_SYNC_ENV: 'SYSTEM_CONFIG_SYNC_ENV',
|
SYSTEM_CONFIG_SYNC_ENV: 'SYSTEM_CONFIG_SYNC_ENV',
|
||||||
SYSTEM_CONFIG_IMPORT_ENV: 'SYSTEM_CONFIG_IMPORT_ENV',
|
SYSTEM_CONFIG_IMPORT_ENV: 'SYSTEM_CONFIG_IMPORT_ENV',
|
||||||
WECOM_ALERT_TEST: 'WECOM_ALERT_TEST',
|
WECOM_ALERT_TEST: 'WECOM_ALERT_TEST',
|
||||||
|
DEV_PLAN_TASK_CREATE: 'DEV_PLAN_TASK_CREATE',
|
||||||
|
DEV_PLAN_TASK_UPDATE: 'DEV_PLAN_TASK_UPDATE',
|
||||||
|
DEV_PLAN_TASK_DELETE: 'DEV_PLAN_TASK_DELETE',
|
||||||
|
DEV_PLAN_TASK_DISPATCH: 'DEV_PLAN_TASK_DISPATCH',
|
||||||
|
DEV_PLAN_VERSION_CREATE: 'DEV_PLAN_VERSION_CREATE',
|
||||||
|
DEV_PLAN_VERSION_UPDATE: 'DEV_PLAN_VERSION_UPDATE',
|
||||||
|
DEV_PLAN_VERSION_DELETE: 'DEV_PLAN_VERSION_DELETE',
|
||||||
|
DEV_PLAN_VERSION_LINK_TASKS: 'DEV_PLAN_VERSION_LINK_TASKS',
|
||||||
|
DEV_PLAN_VERSION_ADD_TASKS: 'DEV_PLAN_VERSION_ADD_TASKS',
|
||||||
|
DEV_PLAN_SETTINGS_UPDATE: 'DEV_PLAN_SETTINGS_UPDATE',
|
||||||
|
DEV_PLAN_DISPATCH_TEST: 'DEV_PLAN_DISPATCH_TEST',
|
||||||
|
SUPPORT_TICKET_REVIEW: 'SUPPORT_TICKET_REVIEW',
|
||||||
|
SUPPORT_TICKET_BATCH_REVIEW: 'SUPPORT_TICKET_BATCH_REVIEW',
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
export type HqOperationActionCode = (typeof HqOperationAction)[keyof typeof HqOperationAction];
|
export type HqOperationActionCode = (typeof HqOperationAction)[keyof typeof HqOperationAction];
|
||||||
@@ -189,6 +206,10 @@ export const HQ_OPERATION_ACTION_LABELS: Record<string, string> = {
|
|||||||
[HqOperationAction.WECOM_BOT_UPDATE]: '编辑企微机器人',
|
[HqOperationAction.WECOM_BOT_UPDATE]: '编辑企微机器人',
|
||||||
[HqOperationAction.WECOM_BOT_DELETE]: '删除企微机器人',
|
[HqOperationAction.WECOM_BOT_DELETE]: '删除企微机器人',
|
||||||
[HqOperationAction.WECOM_BOT_RELOAD]: '重载企微机器人连接',
|
[HqOperationAction.WECOM_BOT_RELOAD]: '重载企微机器人连接',
|
||||||
|
[HqOperationAction.WECOM_MESSAGE_PUSH_CREATE]: '创建企微消息推送',
|
||||||
|
[HqOperationAction.WECOM_MESSAGE_PUSH_UPDATE]: '编辑企微消息推送',
|
||||||
|
[HqOperationAction.WECOM_MESSAGE_PUSH_DELETE]: '删除企微消息推送',
|
||||||
|
[HqOperationAction.WECOM_MESSAGE_PUSH_TEST]: '测试企微消息推送',
|
||||||
[HqOperationAction.LLM_CONFIG_CREATE]: '创建语言模型配置',
|
[HqOperationAction.LLM_CONFIG_CREATE]: '创建语言模型配置',
|
||||||
[HqOperationAction.LLM_CONFIG_UPDATE]: '更新语言模型配置',
|
[HqOperationAction.LLM_CONFIG_UPDATE]: '更新语言模型配置',
|
||||||
[HqOperationAction.LLM_CONFIG_DELETE]: '删除语言模型配置',
|
[HqOperationAction.LLM_CONFIG_DELETE]: '删除语言模型配置',
|
||||||
@@ -205,6 +226,19 @@ export const HQ_OPERATION_ACTION_LABELS: Record<string, string> = {
|
|||||||
[HqOperationAction.SYSTEM_CONFIG_SYNC_ENV]: '同步系统配置到 env 文件',
|
[HqOperationAction.SYSTEM_CONFIG_SYNC_ENV]: '同步系统配置到 env 文件',
|
||||||
[HqOperationAction.SYSTEM_CONFIG_IMPORT_ENV]: '从当前环境导入配置',
|
[HqOperationAction.SYSTEM_CONFIG_IMPORT_ENV]: '从当前环境导入配置',
|
||||||
[HqOperationAction.WECOM_ALERT_TEST]: '测试企微运营告警',
|
[HqOperationAction.WECOM_ALERT_TEST]: '测试企微运营告警',
|
||||||
|
[HqOperationAction.DEV_PLAN_TASK_CREATE]: '创建开发计划任务',
|
||||||
|
[HqOperationAction.DEV_PLAN_TASK_UPDATE]: '更新开发计划任务',
|
||||||
|
[HqOperationAction.DEV_PLAN_TASK_DELETE]: '删除开发计划任务',
|
||||||
|
[HqOperationAction.DEV_PLAN_TASK_DISPATCH]: '派发开发计划任务',
|
||||||
|
[HqOperationAction.DEV_PLAN_VERSION_CREATE]: '创建开发计划版本',
|
||||||
|
[HqOperationAction.DEV_PLAN_VERSION_UPDATE]: '更新开发计划版本',
|
||||||
|
[HqOperationAction.DEV_PLAN_VERSION_DELETE]: '删除开发计划版本',
|
||||||
|
[HqOperationAction.DEV_PLAN_VERSION_LINK_TASKS]: '关联版本任务',
|
||||||
|
[HqOperationAction.DEV_PLAN_VERSION_ADD_TASKS]: '追加关联版本任务',
|
||||||
|
[HqOperationAction.DEV_PLAN_SETTINGS_UPDATE]: '更新开发计划设置',
|
||||||
|
[HqOperationAction.DEV_PLAN_DISPATCH_TEST]: '测试任务派发助手',
|
||||||
|
[HqOperationAction.SUPPORT_TICKET_REVIEW]: '技术支持工单审批',
|
||||||
|
[HqOperationAction.SUPPORT_TICKET_BATCH_REVIEW]: '技术支持批量审批',
|
||||||
STORE_PAYOUT: '门店打款确认',
|
STORE_PAYOUT: '门店打款确认',
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -59,15 +59,7 @@ export const SYSTEM_CONFIG_FIELDS: SystemConfigFieldMeta[] = [
|
|||||||
group: G.feature,
|
group: G.feature,
|
||||||
type: 'boolean',
|
type: 'boolean',
|
||||||
requiresRestart: false,
|
requiresRestart: false,
|
||||||
description: '总开关。开启后连接 HQ「企微机器人」模块中已启用且配置完整的 Bot(每 Bot 同时仅 1 条长连接)',
|
description: '总开关。开启后连接 HQ「企微机器人 → 智能机器人」中已启用且配置完整的 Bot(每 Bot 同时仅 1 条长连接)',
|
||||||
},
|
|
||||||
{
|
|
||||||
key: 'WECOM_ALERT_ENABLED',
|
|
||||||
label: '启用企微运营告警 Webhook',
|
|
||||||
group: G.feature,
|
|
||||||
type: 'boolean',
|
|
||||||
requiresRestart: false,
|
|
||||||
description: '开启后向群机器人 Webhook 推送异常告警;Webhook URL 仅在服务器 .env 配置(WECOM_ALERT_WEBHOOK_URL)',
|
|
||||||
},
|
},
|
||||||
|
|
||||||
{ key: 'ALIYUN_SMS_SIGN_NAME', label: '短信签名', group: G.sms, type: 'string', requiresRestart: false },
|
{ key: 'ALIYUN_SMS_SIGN_NAME', label: '短信签名', group: G.sms, type: 'string', requiresRestart: false },
|
||||||
|
|||||||
@@ -6,7 +6,8 @@ import {
|
|||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { WSClient, generateReqId, type WsFrame } from '@wecom/aibot-node-sdk';
|
import { WSClient, generateReqId, type WsFrame } from '@wecom/aibot-node-sdk';
|
||||||
import {
|
import {
|
||||||
WECOM_BOT_ROLES,
|
normalizeWecomBotRole,
|
||||||
|
parseWecomUserIdList,
|
||||||
resolveWecomBotPermissions,
|
resolveWecomBotPermissions,
|
||||||
type WecomBotRole,
|
type WecomBotRole,
|
||||||
} from '@dukang/shared-types';
|
} from '@dukang/shared-types';
|
||||||
@@ -17,11 +18,13 @@ import type { WecomBotRuntimeConfig } from './wecom-bot.types';
|
|||||||
|
|
||||||
const DEFAULT_WELCOMES: Record<WecomBotRole, string> = {
|
const DEFAULT_WELCOMES: Record<WecomBotRole, string> = {
|
||||||
CUSTOMER_SERVICE:
|
CUSTOMER_SERVICE:
|
||||||
'您好,我是杜康好客【客服】助手。发送「帮助」查看:创建售后工单、查用户(需短信验证)、查快递。',
|
'您好,我是杜康好客【客服助手】。发送「帮助」查看:订单、配送、售后工单等指令。',
|
||||||
|
FINANCE:
|
||||||
|
'您好,我是杜康好客【财务助手】。发送「帮助」查看:门店/合伙人/酒厂/物流账单与打款提现查询。',
|
||||||
|
OPERATIONS:
|
||||||
|
'您好,我是杜康好客【运营助手】。发送「帮助」查看:订单、门店、用户、核销等只读查询。',
|
||||||
TECH_SUPPORT:
|
TECH_SUPPORT:
|
||||||
'您好,我是杜康好客【技术支持】助手。发送「帮助」查看:创建技术支持工单、查看开发进度。',
|
'您好,我是杜康好客【技术支持】。发送「帮助」查看:技术支持工单、开发计划与审批指令。',
|
||||||
TEAM_ASSISTANT:
|
|
||||||
'您好,我是杜康好客【团队助手】。发送「帮助」或「手册 关键词」查询系统使用说明。',
|
|
||||||
CUSTOM: '您好!发送「帮助」查看可用指令。',
|
CUSTOM: '您好!发送「帮助」查看可用指令。',
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -50,9 +53,6 @@ type BotRuntime = {
|
|||||||
lastError: string | null;
|
lastError: string | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
function isWecomRole(v: string): v is WecomBotRole {
|
|
||||||
return (WECOM_BOT_ROLES as readonly string[]).includes(v);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class WecomAibotService implements OnModuleInit, OnModuleDestroy {
|
export class WecomAibotService implements OnModuleInit, OnModuleDestroy {
|
||||||
@@ -152,12 +152,13 @@ export class WecomAibotService implements OnModuleInit, OnModuleDestroy {
|
|||||||
avatarUrl: string | null;
|
avatarUrl: string | null;
|
||||||
welcome: string | null;
|
welcome: string | null;
|
||||||
permissions: string;
|
permissions: string;
|
||||||
|
reviewSuperAdminWecomUserIds: string | null;
|
||||||
aiEnabled: boolean;
|
aiEnabled: boolean;
|
||||||
llmConfigId: bigint | null;
|
llmConfigId: bigint | null;
|
||||||
knowledgeBaseId: bigint | null;
|
knowledgeBaseId: bigint | null;
|
||||||
enabled: boolean;
|
enabled: boolean;
|
||||||
}): WecomBotRuntimeConfig {
|
}): WecomBotRuntimeConfig {
|
||||||
const role = (isWecomRole(row.role) ? row.role : 'CUSTOM') as WecomBotRole;
|
const role = normalizeWecomBotRole(row.role);
|
||||||
return {
|
return {
|
||||||
id: row.id.toString(),
|
id: row.id.toString(),
|
||||||
key: `db_${row.id.toString()}`,
|
key: `db_${row.id.toString()}`,
|
||||||
@@ -169,6 +170,7 @@ export class WecomAibotService implements OnModuleInit, OnModuleDestroy {
|
|||||||
avatarUrl: row.avatarUrl,
|
avatarUrl: row.avatarUrl,
|
||||||
welcome: row.welcome?.trim() || DEFAULT_WELCOMES[role],
|
welcome: row.welcome?.trim() || DEFAULT_WELCOMES[role],
|
||||||
permissions: resolveWecomBotPermissions(role, row.permissions),
|
permissions: resolveWecomBotPermissions(role, row.permissions),
|
||||||
|
reviewSuperAdminWecomUserIds: parseWecomUserIdList(row.reviewSuperAdminWecomUserIds),
|
||||||
aiEnabled: row.aiEnabled,
|
aiEnabled: row.aiEnabled,
|
||||||
llmConfigId: row.llmConfigId?.toString() ?? null,
|
llmConfigId: row.llmConfigId?.toString() ?? null,
|
||||||
knowledgeBaseId: row.knowledgeBaseId?.toString() ?? null,
|
knowledgeBaseId: row.knowledgeBaseId?.toString() ?? null,
|
||||||
@@ -257,13 +259,19 @@ export class WecomAibotService implements OnModuleInit, OnModuleDestroy {
|
|||||||
const wecomUserId = String(frame.body?.from?.userid ?? 'unknown');
|
const wecomUserId = String(frame.body?.from?.userid ?? 'unknown');
|
||||||
const lower = content.toLowerCase();
|
const lower = content.toLowerCase();
|
||||||
|
|
||||||
|
this.logger.log(`[${cfg.key}] inbound user=${wecomUserId} text=${content.slice(0, 120)}`);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (!content || lower === '帮助' || lower === 'help' || content === '?' || content === '?') {
|
if (!content || lower === '帮助' || lower === 'help' || content === '?' || content === '?') {
|
||||||
await this.replyText(client, frame, this.actions.buildHelp(cfg));
|
const reply = this.actions.buildHelp(cfg);
|
||||||
|
this.logger.log(`[${cfg.key}] route=help`);
|
||||||
|
await this.replyText(client, frame, reply);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (lower === '状态' || lower === 'status' || lower === 'ping') {
|
if (lower === '状态' || lower === 'status' || lower === 'ping') {
|
||||||
await this.replyText(client, frame, this.formatStatusMarkdown());
|
const reply = this.formatStatusMarkdown();
|
||||||
|
this.logger.log(`[${cfg.key}] route=status`);
|
||||||
|
await this.replyText(client, frame, reply);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const useAi = cfg.aiEnabled && !!cfg.llmConfigId;
|
const useAi = cfg.aiEnabled && !!cfg.llmConfigId;
|
||||||
@@ -271,11 +279,13 @@ export class WecomAibotService implements OnModuleInit, OnModuleDestroy {
|
|||||||
skipNaturalFallback: useAi,
|
skipNaturalFallback: useAi,
|
||||||
});
|
});
|
||||||
if (reply != null) {
|
if (reply != null) {
|
||||||
|
this.logger.log(`[${cfg.key}] route=command len=${reply.length}`);
|
||||||
await this.replyText(client, frame, reply);
|
await this.replyText(client, frame, reply);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (useAi) {
|
if (useAi) {
|
||||||
const aiReply = await this.ai.replyIfConfigured(cfg, content);
|
const aiReply = await this.ai.replyIfConfigured(cfg, content, wecomUserId);
|
||||||
|
this.logger.log(`[${cfg.key}] route=ai len=${aiReply?.length ?? 0}`);
|
||||||
await this.replyText(
|
await this.replyText(
|
||||||
client,
|
client,
|
||||||
frame,
|
frame,
|
||||||
@@ -283,6 +293,7 @@ export class WecomAibotService implements OnModuleInit, OnModuleDestroy {
|
|||||||
);
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
this.logger.log(`[${cfg.key}] route=fallback`);
|
||||||
await this.replyText(client, frame, `未识别指令。\n\n${this.actions.buildHelp(cfg)}`);
|
await this.replyText(client, frame, `未识别指令。\n\n${this.actions.buildHelp(cfg)}`);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const msg = e instanceof Error ? e.message : String(e);
|
const msg = e instanceof Error ? e.message : String(e);
|
||||||
|
|||||||
@@ -1,653 +1,39 @@
|
|||||||
import { Inject, Injectable, Logger } from '@nestjs/common';
|
import { Injectable } from '@nestjs/common';
|
||||||
import {
|
|
||||||
SUPPORT_TICKET_STATUS_LABELS,
|
|
||||||
SUPPORT_TICKET_TYPE_LABELS,
|
|
||||||
TICKET_TYPE_LABELS,
|
|
||||||
type AfterSaleTicketType,
|
|
||||||
type SupportTicketTypeDto,
|
|
||||||
} from '@dukang/shared-types';
|
|
||||||
import { PrismaService } from '../../common/prisma/prisma.module';
|
|
||||||
import { TicketService } from '../../modules/common/ticket.service';
|
|
||||||
import { SupportTicketService } from '../../modules/common/support-ticket.service';
|
|
||||||
import { SMS_PROVIDER } from '../integrations.constants';
|
|
||||||
import type { ISmsProvider } from '../sms/sms.interface';
|
|
||||||
import type { WecomBotRuntimeConfig } from './wecom-bot.types';
|
import type { WecomBotRuntimeConfig } from './wecom-bot.types';
|
||||||
import { wecomBotHasPermission } from './wecom-bot.types';
|
import { WecomBotCapabilityService } from './wecom-bot-capability.service';
|
||||||
import { WecomBotSessionService } from './wecom-bot-session.service';
|
|
||||||
import { searchHandbook } from './wecom-handbook';
|
|
||||||
|
|
||||||
const SMS_SCENE = 'WECOM_USER_VIEW';
|
|
||||||
const PHONE_RE = /^1\d{10}$/;
|
|
||||||
|
|
||||||
const TICKET_TYPE_ALIASES: Record<string, AfterSaleTicketType> = {
|
|
||||||
仅退款: 'REFUND',
|
|
||||||
退款: 'REFUND',
|
|
||||||
refund: 'REFUND',
|
|
||||||
破损补发: 'RESHIPMENT',
|
|
||||||
补发: 'RESHIPMENT',
|
|
||||||
reshipment: 'RESHIPMENT',
|
|
||||||
破损退货: 'DAMAGE_RETURN',
|
|
||||||
退货: 'DAMAGE_RETURN',
|
|
||||||
damage_return: 'DAMAGE_RETURN',
|
|
||||||
退货退款: 'RETURN_REFUND',
|
|
||||||
return_refund: 'RETURN_REFUND',
|
|
||||||
};
|
|
||||||
|
|
||||||
const SUPPORT_TYPE_ALIASES: Record<string, SupportTicketTypeDto> = {
|
|
||||||
bug: 'BUG',
|
|
||||||
BUG: 'BUG',
|
|
||||||
缺陷: 'BUG',
|
|
||||||
建议: 'SUGGESTION',
|
|
||||||
suggestion: 'SUGGESTION',
|
|
||||||
其他: 'OTHER',
|
|
||||||
other: 'OTHER',
|
|
||||||
};
|
|
||||||
|
|
||||||
|
/** 兼容层:AI / Aibot 仍通过 Actions 入口调用 Capability */
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class WecomBotActionsService {
|
export class WecomBotActionsService {
|
||||||
private readonly logger = new Logger(WecomBotActionsService.name);
|
constructor(private readonly capability: WecomBotCapabilityService) {}
|
||||||
|
|
||||||
constructor(
|
|
||||||
private readonly prisma: PrismaService,
|
|
||||||
private readonly ticketService: TicketService,
|
|
||||||
private readonly supportTicketService: SupportTicketService,
|
|
||||||
private readonly session: WecomBotSessionService,
|
|
||||||
@Inject(SMS_PROVIDER) private readonly sms: ISmsProvider,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
buildHelp(bot: WecomBotRuntimeConfig): string {
|
buildHelp(bot: WecomBotRuntimeConfig): string {
|
||||||
const lines = [`**${bot.name}**`, '', '通用:`帮助` · `状态`', ''];
|
return this.capability.buildHelp(bot);
|
||||||
if (wecomBotHasPermission(bot, 'ticket.create')) {
|
|
||||||
lines.push(
|
|
||||||
'**售后工单**',
|
|
||||||
'`工单 <订单号> <类型> [备注]`',
|
|
||||||
'类型:仅退款 / 破损补发 / 破损退货 / 退货退款',
|
|
||||||
'例:`工单 DK123 仅退款 用户要求退款`',
|
|
||||||
'',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (wecomBotHasPermission(bot, 'user.view_sms')) {
|
|
||||||
lines.push(
|
|
||||||
'**查用户(需短信验证)**',
|
|
||||||
'`查用户 <手机号>` → 向该手机发验证码',
|
|
||||||
'`验证 <验证码>` → 验证通过后展示用户摘要',
|
|
||||||
'',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (wecomBotHasPermission(bot, 'delivery.view')) {
|
|
||||||
lines.push('**查快递**', '`快递 <订单号|运单号>`', '');
|
|
||||||
}
|
|
||||||
if (wecomBotHasPermission(bot, 'support_ticket.create')) {
|
|
||||||
lines.push(
|
|
||||||
'**技术支持提单**',
|
|
||||||
'`提单 <BUG|建议|其他> <标题> [| 详情]`',
|
|
||||||
'例:`提单 BUG 支付回调偶发失败 | 订单号xxx`',
|
|
||||||
'',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (wecomBotHasPermission(bot, 'support_ticket.progress')) {
|
|
||||||
lines.push('**开发进度**', '`进度` 最近工单 · `进度 <工单号>` 详情', '');
|
|
||||||
}
|
|
||||||
if (wecomBotHasPermission(bot, 'handbook.query')) {
|
|
||||||
lines.push(
|
|
||||||
'**使用手册**',
|
|
||||||
'`手册` 目录 · `手册 <关键词>` 如:开城、核销、订单、财务',
|
|
||||||
'',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (wecomBotHasPermission(bot, 'server_log.view')) {
|
|
||||||
lines.push(
|
|
||||||
'**服务器日志**',
|
|
||||||
'`日志` 最近客户端报错 · `日志 <关键词>` 搜索',
|
|
||||||
'`三方日志 [provider]` 最近第三方调用日志',
|
|
||||||
'',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (wecomBotHasPermission(bot, 'api.query')) {
|
|
||||||
lines.push(
|
|
||||||
'**业务查询(只读)**',
|
|
||||||
'`查订单 <订单号>` · `用户号 <用户号>`',
|
|
||||||
'',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (bot.aiEnabled && bot.llmConfigId) {
|
|
||||||
lines.push(
|
|
||||||
'**智能问答**',
|
|
||||||
'未匹配指令的自然语言将交由绑定的语言模型回答(可挂知识库)',
|
|
||||||
'',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
lines.push(`当前权限:${bot.permissions.join(', ') || '无'}`);
|
|
||||||
return lines.join('\n');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async handleCommand(
|
handleCommand(
|
||||||
bot: WecomBotRuntimeConfig,
|
bot: WecomBotRuntimeConfig,
|
||||||
wecomUserId: string,
|
wecomUserId: string,
|
||||||
text: string,
|
text: string,
|
||||||
opts?: { skipNaturalFallback?: boolean },
|
opts?: { skipNaturalFallback?: boolean },
|
||||||
): Promise<string | null> {
|
): Promise<string | null> {
|
||||||
const content = text.trim();
|
return this.capability.dispatch(bot, wecomUserId, text, opts);
|
||||||
if (!content) return this.buildHelp(bot);
|
|
||||||
|
|
||||||
// 查用户 / 验证
|
|
||||||
if (/^(查用户|用户)\s+/i.test(content)) {
|
|
||||||
this.requirePerm(bot, 'user.view_sms');
|
|
||||||
const phone = content.replace(/^(查用户|用户)\s+/i, '').trim();
|
|
||||||
return this.startUserView(bot, wecomUserId, phone);
|
|
||||||
}
|
|
||||||
if (/^(验证|verify)\s+/i.test(content)) {
|
|
||||||
this.requirePerm(bot, 'user.view_sms');
|
|
||||||
const code = content.replace(/^(验证|verify)\s+/i, '').trim();
|
|
||||||
return this.verifyUserView(bot, wecomUserId, code);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 快递
|
runTool(
|
||||||
if (/^(快递|配送|物流)\s+/i.test(content)) {
|
bot: WecomBotRuntimeConfig,
|
||||||
this.requirePerm(bot, 'delivery.view');
|
wecomUserId: string,
|
||||||
const q = content.replace(/^(快递|配送|物流)\s+/i, '').trim();
|
toolName: string,
|
||||||
return this.lookupDelivery(q);
|
args: string,
|
||||||
|
): Promise<string> {
|
||||||
|
return this.capability.runTool(bot, wecomUserId, toolName, args);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 售后工单
|
tryNaturalLanguageQuery(
|
||||||
if (/^(工单|创建工单)\s+/i.test(content)) {
|
bot: WecomBotRuntimeConfig,
|
||||||
this.requirePerm(bot, 'ticket.create');
|
wecomUserId: string,
|
||||||
return this.createAfterSaleTicket(content.replace(/^(工单|创建工单)\s+/i, '').trim(), wecomUserId);
|
content: string,
|
||||||
}
|
): Promise<string | null> {
|
||||||
|
return this.capability.tryNaturalLanguageQuery(bot, wecomUserId, content);
|
||||||
// 技术支持提单
|
|
||||||
if (/^(提单|技术支持)\s+/i.test(content)) {
|
|
||||||
this.requirePerm(bot, 'support_ticket.create');
|
|
||||||
return this.createSupportTicket(content.replace(/^(提单|技术支持)\s+/i, '').trim(), wecomUserId);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 进度
|
|
||||||
if (/^(进度|开发进度)/i.test(content)) {
|
|
||||||
this.requirePerm(bot, 'support_ticket.progress');
|
|
||||||
const rest = content.replace(/^(进度|开发进度)\s*/i, '').trim();
|
|
||||||
return this.supportProgress(rest);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 手册
|
|
||||||
if (/^(手册|帮助文档|文档)/i.test(content)) {
|
|
||||||
this.requirePerm(bot, 'handbook.query');
|
|
||||||
const q = content.replace(/^(手册|帮助文档|文档)\s*/i, '').trim();
|
|
||||||
return this.queryHandbook(q);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 服务器日志
|
|
||||||
if (/^(日志|错误日志|服务端日志)/i.test(content)) {
|
|
||||||
this.requirePerm(bot, 'server_log.view');
|
|
||||||
const q = content.replace(/^(日志|错误日志|服务端日志)\s*/i, '').trim();
|
|
||||||
return this.queryServerLogs(q);
|
|
||||||
}
|
|
||||||
if (/^(三方日志|第三方日志)/i.test(content)) {
|
|
||||||
this.requirePerm(bot, 'server_log.view');
|
|
||||||
const q = content.replace(/^(三方日志|第三方日志)\s*/i, '').trim();
|
|
||||||
return this.queryThirdPartyLogs(q);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 业务 API 只读查询
|
|
||||||
if (/^(查订单|订单查询)\s+/i.test(content)) {
|
|
||||||
this.requirePerm(bot, 'api.query');
|
|
||||||
const orderNo = content.replace(/^(查订单|订单查询)\s+/i, '').trim();
|
|
||||||
return this.queryOrder(orderNo);
|
|
||||||
}
|
|
||||||
if (/^(用户号|查用户号)\s+/i.test(content)) {
|
|
||||||
this.requirePerm(bot, 'api.query');
|
|
||||||
const userNo = content.replace(/^(用户号|查用户号)\s+/i, '').trim();
|
|
||||||
return this.queryUserByNo(userNo);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 自然语言手册(仅团队助手有 handbook 权限时;开启 AI 时改由模型+知识库回答)
|
|
||||||
if (
|
|
||||||
!opts?.skipNaturalFallback &&
|
|
||||||
wecomBotHasPermission(bot, 'handbook.query') &&
|
|
||||||
content.length >= 2
|
|
||||||
) {
|
|
||||||
const hit = searchHandbook(content, 1);
|
|
||||||
if (hit.length) {
|
|
||||||
return formatHandbook(hit);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (opts?.skipNaturalFallback) return null;
|
|
||||||
return `未识别指令。\n\n${this.buildHelp(bot)}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
private requirePerm(bot: WecomBotRuntimeConfig, perm: Parameters<typeof wecomBotHasPermission>[1]) {
|
|
||||||
if (!wecomBotHasPermission(bot, perm)) {
|
|
||||||
throw new Error(`当前机器人无权限:${perm}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async startUserView(bot: WecomBotRuntimeConfig, wecomUserId: string, phone: string) {
|
|
||||||
if (!PHONE_RE.test(phone)) return '请输入 11 位手机号,例如:`查用户 13800138000`';
|
|
||||||
const user = await this.prisma.user.findFirst({
|
|
||||||
where: { phone },
|
|
||||||
select: { id: true, userNo: true, phone: true },
|
|
||||||
});
|
|
||||||
if (!user) return `未找到手机号 ${phone} 对应的用户`;
|
|
||||||
|
|
||||||
await this.session.setPendingPhone(bot.key, wecomUserId, phone);
|
|
||||||
await this.sms.send(phone, SMS_SCENE);
|
|
||||||
return [
|
|
||||||
`已向 **${maskPhone(phone)}** 发送验证码(用户 ${user.userNo})。`,
|
|
||||||
'请回复:`验证 123456`',
|
|
||||||
'验证码约 3 分钟有效。',
|
|
||||||
].join('\n');
|
|
||||||
}
|
|
||||||
|
|
||||||
private async verifyUserView(bot: WecomBotRuntimeConfig, wecomUserId: string, code: string) {
|
|
||||||
const sess = await this.session.get(bot.key, wecomUserId);
|
|
||||||
if (!sess?.phone) return '请先发送:`查用户 <手机号>`';
|
|
||||||
if (!code) return '请提供验证码,例如:`验证 123456`';
|
|
||||||
|
|
||||||
try {
|
|
||||||
await this.sms.verify(sess.phone, code, SMS_SCENE);
|
|
||||||
} catch {
|
|
||||||
return '验证码错误或已过期,请重新 `查用户`';
|
|
||||||
}
|
|
||||||
|
|
||||||
const user = await this.prisma.user.findFirst({
|
|
||||||
where: { phone: sess.phone },
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
userNo: true,
|
|
||||||
phone: true,
|
|
||||||
nickname: true,
|
|
||||||
status: true,
|
|
||||||
phoneVerifiedAt: true,
|
|
||||||
createdAt: true,
|
|
||||||
_count: { select: { orders: true } },
|
|
||||||
},
|
|
||||||
});
|
|
||||||
if (!user) return '用户不存在';
|
|
||||||
|
|
||||||
await this.session.markVerified(bot.key, wecomUserId, sess.phone, user.id.toString());
|
|
||||||
|
|
||||||
const coupons = await this.prisma.benefitCoupon.aggregate({
|
|
||||||
where: { userId: user.id, status: 'ACTIVE' },
|
|
||||||
_sum: { balance: true },
|
|
||||||
});
|
|
||||||
|
|
||||||
return [
|
|
||||||
'**用户摘要**(短信验证已通过)',
|
|
||||||
`- 用户号:${user.userNo}`,
|
|
||||||
`- 昵称:${user.nickname || '—'}`,
|
|
||||||
`- 手机:${user.phone}`,
|
|
||||||
`- 手机已验:${user.phoneVerifiedAt ? '是' : '否'}`,
|
|
||||||
`- 状态:${user.status}`,
|
|
||||||
`- 订单数:${user._count.orders}`,
|
|
||||||
`- 权益余额:¥${Number(coupons._sum.balance ?? 0).toFixed(2)}`,
|
|
||||||
`- 注册:${user.createdAt.toISOString().slice(0, 19).replace('T', ' ')}`,
|
|
||||||
].join('\n');
|
|
||||||
}
|
|
||||||
|
|
||||||
private async lookupDelivery(q: string) {
|
|
||||||
if (!q) return '请提供订单号或运单号,例如:`快递 DK123`';
|
|
||||||
|
|
||||||
const byOrder = await this.prisma.orderDelivery.findMany({
|
|
||||||
where: { order: { orderNo: { contains: q } } },
|
|
||||||
take: 5,
|
|
||||||
orderBy: { updatedAt: 'desc' },
|
|
||||||
include: {
|
|
||||||
order: {
|
|
||||||
select: {
|
|
||||||
orderNo: true,
|
|
||||||
status: true,
|
|
||||||
receiverName: true,
|
|
||||||
receiverPhone: true,
|
|
||||||
deliveryType: true,
|
|
||||||
productName: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
const byTrack =
|
|
||||||
byOrder.length > 0
|
|
||||||
? []
|
|
||||||
: await this.prisma.orderDelivery.findMany({
|
|
||||||
where: { trackingNo: { contains: q } },
|
|
||||||
take: 5,
|
|
||||||
orderBy: { updatedAt: 'desc' },
|
|
||||||
include: {
|
|
||||||
order: {
|
|
||||||
select: {
|
|
||||||
orderNo: true,
|
|
||||||
status: true,
|
|
||||||
receiverName: true,
|
|
||||||
receiverPhone: true,
|
|
||||||
deliveryType: true,
|
|
||||||
productName: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const rows = byOrder.length ? byOrder : byTrack;
|
|
||||||
if (!rows.length) return `未找到与「${q}」匹配的配送单`;
|
|
||||||
|
|
||||||
return rows
|
|
||||||
.map((d, i) => {
|
|
||||||
const o = d.order;
|
|
||||||
return [
|
|
||||||
`**配送 ${i + 1}**`,
|
|
||||||
`- 订单:${o.orderNo}(${o.status})`,
|
|
||||||
`- 商品:${o.productName}`,
|
|
||||||
`- 类型:${o.deliveryType}`,
|
|
||||||
`- 承运:${d.provider}`,
|
|
||||||
`- 运单:${d.trackingNo || '—'}`,
|
|
||||||
`- 第三方单号:${d.providerOrderNo || '—'}`,
|
|
||||||
`- 收货:${o.receiverName} ${maskPhone(o.receiverPhone || '')}`,
|
|
||||||
].join('\n');
|
|
||||||
})
|
|
||||||
.join('\n\n');
|
|
||||||
}
|
|
||||||
|
|
||||||
private async createAfterSaleTicket(rest: string, wecomUserId: string) {
|
|
||||||
// 订单号 类型 备注
|
|
||||||
const parts = rest.split(/\s+/).filter(Boolean);
|
|
||||||
if (parts.length < 2) {
|
|
||||||
return '格式:`工单 <订单号> <类型> [备注]`\n类型:仅退款 / 破损补发 / 破损退货 / 退货退款';
|
|
||||||
}
|
|
||||||
const orderNo = parts[0];
|
|
||||||
const typeRaw = parts[1];
|
|
||||||
const remark = parts.slice(2).join(' ') || `企微客服创建 by ${wecomUserId}`;
|
|
||||||
const ticketType = TICKET_TYPE_ALIASES[typeRaw] || TICKET_TYPE_ALIASES[typeRaw.toLowerCase()];
|
|
||||||
if (!ticketType) {
|
|
||||||
return `未知类型「${typeRaw}」。可用:仅退款 / 破损补发 / 破损退货 / 退货退款`;
|
|
||||||
}
|
|
||||||
|
|
||||||
const order = await this.prisma.order.findFirst({ where: { orderNo } });
|
|
||||||
if (!order) return `订单不存在:${orderNo}`;
|
|
||||||
if (order.status === 'PENDING_PAY' || order.status === 'CANCELLED') {
|
|
||||||
return '当前订单状态不可创建售后工单';
|
|
||||||
}
|
|
||||||
|
|
||||||
const pending = await this.prisma.commonTicket.findFirst({
|
|
||||||
where: {
|
|
||||||
ticketType: ticketType as never,
|
|
||||||
refType: 'ORDER',
|
|
||||||
refId: order.id,
|
|
||||||
status: { in: ['PENDING', 'OPEN'] },
|
|
||||||
},
|
|
||||||
});
|
|
||||||
if (pending) return `该类型工单已在处理中:${pending.ticketNo}`;
|
|
||||||
|
|
||||||
const ticket = await this.ticketService.create({
|
|
||||||
ticketType,
|
|
||||||
refType: 'ORDER',
|
|
||||||
refId: order.id.toString(),
|
|
||||||
remark: `${remark} [wecom:${wecomUserId}]`,
|
|
||||||
});
|
|
||||||
|
|
||||||
return [
|
|
||||||
'**售后工单已创建**',
|
|
||||||
`- 工单号:${ticket.ticketNo}`,
|
|
||||||
`- 类型:${TICKET_TYPE_LABELS[ticketType]}`,
|
|
||||||
`- 订单:${orderNo}`,
|
|
||||||
`- 状态:${ticket.status}`,
|
|
||||||
].join('\n');
|
|
||||||
}
|
|
||||||
|
|
||||||
private async createSupportTicket(rest: string, wecomUserId: string) {
|
|
||||||
const m = rest.match(/^(\S+)\s+(.+)$/);
|
|
||||||
if (!m) return '格式:`提单 <BUG|建议|其他> <标题> [| 详情]`';
|
|
||||||
const typeRaw = m[1];
|
|
||||||
const restTitle = m[2];
|
|
||||||
const ticketType =
|
|
||||||
SUPPORT_TYPE_ALIASES[typeRaw] || SUPPORT_TYPE_ALIASES[typeRaw.toLowerCase()];
|
|
||||||
if (!ticketType) return '类型请使用:BUG / 建议 / 其他';
|
|
||||||
|
|
||||||
const [titlePart, ...contentParts] = restTitle.split('|');
|
|
||||||
const title = titlePart.trim();
|
|
||||||
const content = contentParts.join('|').trim();
|
|
||||||
if (!title) return '请填写标题';
|
|
||||||
|
|
||||||
const creator = await this.resolveCreator(wecomUserId);
|
|
||||||
const ticket = await this.supportTicketService.create(
|
|
||||||
{
|
|
||||||
ticketType,
|
|
||||||
title,
|
|
||||||
content: content || undefined,
|
|
||||||
remark: `企微技术支持机器人`,
|
|
||||||
},
|
|
||||||
creator,
|
|
||||||
);
|
|
||||||
|
|
||||||
return [
|
|
||||||
'**技术支持工单已创建**',
|
|
||||||
`- 工单号:${ticket.ticketNo}`,
|
|
||||||
`- 类型:${SUPPORT_TICKET_TYPE_LABELS[ticketType]}`,
|
|
||||||
`- 状态:${SUPPORT_TICKET_STATUS_LABELS[ticket.status as keyof typeof SUPPORT_TICKET_STATUS_LABELS] || ticket.status}`,
|
|
||||||
`- 标题:${title}`,
|
|
||||||
'等待最高管理员评审。',
|
|
||||||
].join('\n');
|
|
||||||
}
|
|
||||||
|
|
||||||
private async supportProgress(ticketNo: string) {
|
|
||||||
if (ticketNo) {
|
|
||||||
const ticket = await this.prisma.commonSupportTicket.findFirst({
|
|
||||||
where: { ticketNo: { contains: ticketNo } },
|
|
||||||
});
|
|
||||||
if (!ticket) return `未找到工单:${ticketNo}`;
|
|
||||||
return [
|
|
||||||
`**${ticket.ticketNo}**`,
|
|
||||||
`- 类型:${SUPPORT_TICKET_TYPE_LABELS[ticket.ticketType as SupportTicketTypeDto] || ticket.ticketType}`,
|
|
||||||
`- 状态:${SUPPORT_TICKET_STATUS_LABELS[ticket.status as keyof typeof SUPPORT_TICKET_STATUS_LABELS] || ticket.status}`,
|
|
||||||
`- 标题:${ticket.title}`,
|
|
||||||
`- 创建人:${ticket.creatorName}`,
|
|
||||||
`- 评审人:${ticket.reviewerName || '—'}`,
|
|
||||||
ticket.rejectReason ? `- 驳回原因:${ticket.rejectReason}` : '',
|
|
||||||
`- 更新:${ticket.updatedAt.toISOString().slice(0, 19).replace('T', ' ')}`,
|
|
||||||
]
|
|
||||||
.filter(Boolean)
|
|
||||||
.join('\n');
|
|
||||||
}
|
|
||||||
|
|
||||||
const items = await this.prisma.commonSupportTicket.findMany({
|
|
||||||
orderBy: { updatedAt: 'desc' },
|
|
||||||
take: 8,
|
|
||||||
});
|
|
||||||
if (!items.length) return '暂无技术支持工单';
|
|
||||||
|
|
||||||
const byStatus = await this.prisma.commonSupportTicket.groupBy({
|
|
||||||
by: ['status'],
|
|
||||||
_count: { _all: true },
|
|
||||||
});
|
|
||||||
const summary = byStatus
|
|
||||||
.map(
|
|
||||||
(s) =>
|
|
||||||
`${SUPPORT_TICKET_STATUS_LABELS[s.status as keyof typeof SUPPORT_TICKET_STATUS_LABELS] || s.status}:${s._count._all}`,
|
|
||||||
)
|
|
||||||
.join(' · ');
|
|
||||||
|
|
||||||
const list = items
|
|
||||||
.map(
|
|
||||||
(t) =>
|
|
||||||
`- ${t.ticketNo} [${SUPPORT_TICKET_STATUS_LABELS[t.status as keyof typeof SUPPORT_TICKET_STATUS_LABELS] || t.status}] ${t.title}`,
|
|
||||||
)
|
|
||||||
.join('\n');
|
|
||||||
|
|
||||||
return [`**开发进度概览**`, summary, '', '**最近工单**', list, '', '详情:`进度 <工单号>`'].join(
|
|
||||||
'\n',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
private queryHandbook(q: string) {
|
|
||||||
if (!q) {
|
|
||||||
const catalog = searchHandbook('', 20)
|
|
||||||
.map((e) => `- ${e.title}(关键词:${e.keywords.slice(0, 4).join('、')})`)
|
|
||||||
.join('\n');
|
|
||||||
return `**手册目录**\n${catalog}\n\n查询:\`手册 <关键词>\``;
|
|
||||||
}
|
|
||||||
const hits = searchHandbook(q, 3);
|
|
||||||
if (!hits.length) return `未找到与「${q}」相关的手册内容。可试:开城、核销、订单、财务、工单`;
|
|
||||||
return formatHandbook(hits);
|
|
||||||
}
|
|
||||||
|
|
||||||
private async queryServerLogs(keyword: string) {
|
|
||||||
const rows = await this.prisma.logUserAnalytics.findMany({
|
|
||||||
where: keyword
|
|
||||||
? {
|
|
||||||
eventName: 'client_error',
|
|
||||||
OR: [
|
|
||||||
{ pagePath: { contains: keyword } },
|
|
||||||
{ extraJson: { string_contains: keyword } },
|
|
||||||
],
|
|
||||||
}
|
|
||||||
: { eventName: 'client_error' },
|
|
||||||
orderBy: { createdAt: 'desc' },
|
|
||||||
take: 8,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!rows.length) {
|
|
||||||
return keyword ? `未找到与「${keyword}」相关的客户端报错日志` : '暂无近期客户端报错日志';
|
|
||||||
}
|
|
||||||
|
|
||||||
return [
|
|
||||||
`**最近客户端报错**${keyword ? `(关键词:${keyword})` : ''}`,
|
|
||||||
...rows.map((row, i) => formatClientErrorLog(row, i + 1)),
|
|
||||||
].join('\n\n');
|
|
||||||
}
|
|
||||||
|
|
||||||
private async queryThirdPartyLogs(provider?: string) {
|
|
||||||
const where = provider ? { provider: provider.toUpperCase() as never } : {};
|
|
||||||
const rows = await this.prisma.logThirdParty.findMany({
|
|
||||||
where,
|
|
||||||
orderBy: { createdAt: 'desc' },
|
|
||||||
take: 8,
|
|
||||||
});
|
|
||||||
if (!rows.length) {
|
|
||||||
return provider ? `未找到 provider=${provider} 的第三方日志` : '暂无近期第三方调用日志';
|
|
||||||
}
|
|
||||||
return [
|
|
||||||
`**最近第三方日志**${provider ? `(${provider})` : ''}`,
|
|
||||||
...rows.map((row, i) => {
|
|
||||||
const err = row.errorMessage ? `\n- 错误:${row.errorMessage.slice(0, 120)}` : '';
|
|
||||||
return [
|
|
||||||
`**${i + 1}. ${row.provider}/${row.scene}**`,
|
|
||||||
`- 状态:${row.status}`,
|
|
||||||
`- 关联:${row.refType || '—'} ${row.refId?.toString() || ''}`,
|
|
||||||
`- 外部单号:${row.externalNo || '—'}${err}`,
|
|
||||||
`- 时间:${row.createdAt.toISOString().slice(0, 19).replace('T', ' ')}`,
|
|
||||||
].join('\n');
|
|
||||||
}),
|
|
||||||
].join('\n\n');
|
|
||||||
}
|
|
||||||
|
|
||||||
private async queryOrder(orderNo: string) {
|
|
||||||
if (!orderNo) return '请提供订单号,例如:`查订单 DK123456`';
|
|
||||||
const order = await this.prisma.order.findFirst({
|
|
||||||
where: { orderNo: { contains: orderNo } },
|
|
||||||
include: {
|
|
||||||
user: { select: { userNo: true, phone: true, nickname: true } },
|
|
||||||
delivery: true,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
if (!order) return `未找到订单:${orderNo}`;
|
|
||||||
|
|
||||||
const deliveryLines = order.delivery
|
|
||||||
? [`- ${order.delivery.provider} ${order.delivery.trackingNo || '—'}`]
|
|
||||||
: ['- 暂无配送单'];
|
|
||||||
|
|
||||||
return [
|
|
||||||
'**订单摘要**',
|
|
||||||
`- 订单号:${order.orderNo}`,
|
|
||||||
`- 状态:${order.status}`,
|
|
||||||
`- 商品:${order.productName}`,
|
|
||||||
`- 数量:${order.quantity}`,
|
|
||||||
`- 实付:¥${Number(order.payAmount).toFixed(2)}`,
|
|
||||||
`- 履约:${order.deliveryType}`,
|
|
||||||
`- 用户:${order.user?.nickname || '—'} / ${order.user?.userNo || '—'} / ${maskPhone(order.user?.phone || '')}`,
|
|
||||||
`- 下单:${order.createdAt.toISOString().slice(0, 19).replace('T', ' ')}`,
|
|
||||||
'**配送**',
|
|
||||||
...deliveryLines,
|
|
||||||
].join('\n');
|
|
||||||
}
|
|
||||||
|
|
||||||
private async queryUserByNo(userNo: string) {
|
|
||||||
if (!userNo) return '请提供用户号,例如:`用户号 U123456`';
|
|
||||||
const user = await this.prisma.user.findFirst({
|
|
||||||
where: { userNo: { contains: userNo } },
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
userNo: true,
|
|
||||||
phone: true,
|
|
||||||
nickname: true,
|
|
||||||
status: true,
|
|
||||||
phoneVerifiedAt: true,
|
|
||||||
createdAt: true,
|
|
||||||
_count: { select: { orders: true } },
|
|
||||||
},
|
|
||||||
});
|
|
||||||
if (!user) return `未找到用户号:${userNo}`;
|
|
||||||
|
|
||||||
const coupons = await this.prisma.benefitCoupon.aggregate({
|
|
||||||
where: { userId: user.id, status: 'ACTIVE' },
|
|
||||||
_sum: { balance: true },
|
|
||||||
});
|
|
||||||
|
|
||||||
return [
|
|
||||||
'**用户摘要**',
|
|
||||||
`- 用户号:${user.userNo}`,
|
|
||||||
`- 昵称:${user.nickname || '—'}`,
|
|
||||||
`- 手机:${maskPhone(user.phone || '')}`,
|
|
||||||
`- 手机已验:${user.phoneVerifiedAt ? '是' : '否'}`,
|
|
||||||
`- 状态:${user.status}`,
|
|
||||||
`- 订单数:${user._count.orders}`,
|
|
||||||
`- 权益余额:¥${Number(coupons._sum.balance ?? 0).toFixed(2)}`,
|
|
||||||
`- 注册:${user.createdAt.toISOString().slice(0, 19).replace('T', ' ')}`,
|
|
||||||
].join('\n');
|
|
||||||
}
|
|
||||||
|
|
||||||
private async resolveCreator(wecomUserId: string) {
|
|
||||||
const admin = await this.prisma.hqAccount.findFirst({
|
|
||||||
where: { status: 'ACTIVE' },
|
|
||||||
orderBy: [{ id: 'asc' }],
|
|
||||||
select: { id: true, name: true },
|
|
||||||
});
|
|
||||||
if (!admin) {
|
|
||||||
this.logger.warn('no hq account for wecom support ticket creator');
|
|
||||||
throw new Error('系统未配置 HQ 账号,无法创建技术支持工单');
|
|
||||||
}
|
|
||||||
return { id: admin.id, name: `${admin.name || 'HQ'}(企微:${wecomUserId})` };
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function maskPhone(phone: string): string {
|
|
||||||
if (!phone || phone.length < 7) return phone || '—';
|
|
||||||
return `${phone.slice(0, 3)}****${phone.slice(-4)}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatHandbook(entries: ReturnType<typeof searchHandbook>): string {
|
|
||||||
return entries.map((e) => `**${e.title}**\n${e.body}`).join('\n\n---\n\n');
|
|
||||||
}
|
|
||||||
|
|
||||||
type ClientErrorLogRow = {
|
|
||||||
id: bigint;
|
|
||||||
clientApp: string | null;
|
|
||||||
pagePath: string | null;
|
|
||||||
extraJson: unknown;
|
|
||||||
createdAt: Date;
|
|
||||||
};
|
|
||||||
|
|
||||||
function formatClientErrorLog(row: ClientErrorLogRow, index: number): string {
|
|
||||||
const extra =
|
|
||||||
row.extraJson && typeof row.extraJson === 'object'
|
|
||||||
? (row.extraJson as Record<string, unknown>)
|
|
||||||
: {};
|
|
||||||
const level = typeof extra.level === 'string' ? extra.level : '—';
|
|
||||||
const category = typeof extra.category === 'string' ? extra.category : '—';
|
|
||||||
const message = typeof extra.message === 'string' ? extra.message.slice(0, 160) : '—';
|
|
||||||
return [
|
|
||||||
`**${index}. [${level}/${category}]**`,
|
|
||||||
`- 端:${row.clientApp || '—'}`,
|
|
||||||
row.pagePath ? `- 页面:${row.pagePath}` : null,
|
|
||||||
`- 消息:${message}`,
|
|
||||||
`- 时间:${row.createdAt.toISOString().slice(0, 19).replace('T', ' ')}`,
|
|
||||||
]
|
|
||||||
.filter(Boolean)
|
|
||||||
.join('\n');
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -2,7 +2,10 @@ import { Injectable, Logger } from '@nestjs/common';
|
|||||||
import { PrismaService } from '../../common/prisma/prisma.module';
|
import { PrismaService } from '../../common/prisma/prisma.module';
|
||||||
import { LlmChatClient } from '../llm/llm-chat.client';
|
import { LlmChatClient } from '../llm/llm-chat.client';
|
||||||
import { KnowledgeRetrievalService } from '../llm/knowledge-retrieval.service';
|
import { KnowledgeRetrievalService } from '../llm/knowledge-retrieval.service';
|
||||||
|
import { WecomBotActionsService } from './wecom-bot-actions.service';
|
||||||
|
import { parseWecomToolLine, sanitizeWecomUserReply } from './wecom-bot-reply.util';
|
||||||
import type { WecomBotRuntimeConfig } from './wecom-bot.types';
|
import type { WecomBotRuntimeConfig } from './wecom-bot.types';
|
||||||
|
import { wecomBotHasPermission } from './wecom-bot.types';
|
||||||
|
|
||||||
const DEFAULT_SYSTEM = [
|
const DEFAULT_SYSTEM = [
|
||||||
'你是杜康好客企业内部助手。',
|
'你是杜康好客企业内部助手。',
|
||||||
@@ -11,6 +14,29 @@ const DEFAULT_SYSTEM = [
|
|||||||
'回答简洁,使用中文。',
|
'回答简洁,使用中文。',
|
||||||
].join('');
|
].join('');
|
||||||
|
|
||||||
|
const TOOL_INSTRUCTION = [
|
||||||
|
'当用户需要查询业务数据时,你必须在回复的第一行输出工具指令(仅一行,用户不可见后续会过滤):',
|
||||||
|
'格式:`TOOL <工具名> [参数]`',
|
||||||
|
'可用工具(按权限):',
|
||||||
|
'- order_read <订单号>',
|
||||||
|
'- delivery_read <单号>',
|
||||||
|
'- store_read <关键词> · redeem_read <核销单号或门店>',
|
||||||
|
'- user_read <用户号>',
|
||||||
|
'- support_tickets_open · support_ticket_read [工单号]',
|
||||||
|
'- support_ticket_approve <工单号> · support_ticket_reject <工单号> <理由>',
|
||||||
|
'- finance_store_bill [门店] · finance_partner_bill · finance_winery_bill · finance_logistics_bill',
|
||||||
|
'- finance_payout · finance_withdrawal',
|
||||||
|
'- dev_plan_tasks [状态] · dev_plan_versions [版本号]',
|
||||||
|
'- dev_plan_task_create <BUG|REQUIREMENT|OPTIMIZATION> <描述>',
|
||||||
|
'- dev_plan_task_update_status <任务编号> <TODO|DEVELOPED|RELEASED>',
|
||||||
|
'- dev_plan_version_create <版本号>',
|
||||||
|
'- dev_plan_version_update_status <版本号> <PENDING|IN_PROGRESS|TESTING|RELEASED>',
|
||||||
|
'- dev_plan_version_link_tasks <版本号> <任务编号1,任务编号2>',
|
||||||
|
'- server_logs [关键词] · handbook_read [关键词]',
|
||||||
|
'禁止输出 JSON、api 字段、「请稍等正在检索」等占位话术。',
|
||||||
|
'若仅需解释概念、无需查库,第一行写 `ANSWER` 后直接回答。',
|
||||||
|
].join('\n');
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class WecomBotAiService {
|
export class WecomBotAiService {
|
||||||
private readonly logger = new Logger(WecomBotAiService.name);
|
private readonly logger = new Logger(WecomBotAiService.name);
|
||||||
@@ -19,9 +45,14 @@ export class WecomBotAiService {
|
|||||||
private readonly prisma: PrismaService,
|
private readonly prisma: PrismaService,
|
||||||
private readonly llm: LlmChatClient,
|
private readonly llm: LlmChatClient,
|
||||||
private readonly kb: KnowledgeRetrievalService,
|
private readonly kb: KnowledgeRetrievalService,
|
||||||
|
private readonly actions: WecomBotActionsService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async replyIfConfigured(bot: WecomBotRuntimeConfig, userText: string): Promise<string | null> {
|
async replyIfConfigured(
|
||||||
|
bot: WecomBotRuntimeConfig,
|
||||||
|
userText: string,
|
||||||
|
wecomUserId: string,
|
||||||
|
): Promise<string | null> {
|
||||||
if (!bot.aiEnabled || !bot.llmConfigId) return null;
|
if (!bot.aiEnabled || !bot.llmConfigId) return null;
|
||||||
|
|
||||||
const cfg = await this.prisma.llmApiConfig.findUnique({
|
const cfg = await this.prisma.llmApiConfig.findUnique({
|
||||||
@@ -42,11 +73,16 @@ export class WecomBotAiService {
|
|||||||
|
|
||||||
const systemParts = [
|
const systemParts = [
|
||||||
cfg.systemPrompt?.trim() || DEFAULT_SYSTEM,
|
cfg.systemPrompt?.trim() || DEFAULT_SYSTEM,
|
||||||
|
this.buildToolHint(bot),
|
||||||
|
TOOL_INSTRUCTION,
|
||||||
kbBlock ? `\n\n以下为知识库检索片段:\n${kbBlock}` : '',
|
kbBlock ? `\n\n以下为知识库检索片段:\n${kbBlock}` : '',
|
||||||
];
|
];
|
||||||
|
|
||||||
try {
|
try {
|
||||||
return await this.llm.chat({
|
this.logger.log(
|
||||||
|
`wecom ai request bot=${bot.key} user=${wecomUserId} text=${userText.slice(0, 80)}`,
|
||||||
|
);
|
||||||
|
const raw = await this.llm.chat({
|
||||||
baseUrl: cfg.baseUrl,
|
baseUrl: cfg.baseUrl,
|
||||||
apiKey: cfg.apiKey,
|
apiKey: cfg.apiKey,
|
||||||
model: cfg.modelName,
|
model: cfg.modelName,
|
||||||
@@ -57,10 +93,57 @@ export class WecomBotAiService {
|
|||||||
{ role: 'user', content: userText },
|
{ role: 'user', content: userText },
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const tool = parseWecomToolLine(raw);
|
||||||
|
if (tool) {
|
||||||
|
this.logger.log(
|
||||||
|
`wecom ai tool=${tool.name} bot=${bot.key} user=${wecomUserId} args=${tool.args.slice(0, 80)}`,
|
||||||
|
);
|
||||||
|
try {
|
||||||
|
const result = await this.actions.runTool(bot, wecomUserId, tool.name, tool.args);
|
||||||
|
return result;
|
||||||
|
} catch (e) {
|
||||||
|
const msg = e instanceof Error ? e.message : String(e);
|
||||||
|
this.logger.warn(`wecom ai tool failed ${tool.name}: ${msg}`);
|
||||||
|
return `查询失败:${msg}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const answerMatch = raw.match(/^ANSWER\s+([\s\S]*)/i);
|
||||||
|
if (answerMatch) {
|
||||||
|
return sanitizeWecomUserReply(answerMatch[1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return sanitizeWecomUserReply(raw);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const msg = e instanceof Error ? e.message : String(e);
|
const msg = e instanceof Error ? e.message : String(e);
|
||||||
this.logger.error(`wecom ai reply failed: ${msg}`);
|
this.logger.error(`wecom ai reply failed: ${msg}`);
|
||||||
return `AI 回复失败:${msg}`;
|
return `AI 回复失败:${msg}`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private buildToolHint(bot: WecomBotRuntimeConfig): string {
|
||||||
|
const tools: string[] = [];
|
||||||
|
if (wecomBotHasPermission(bot, 'order.read')) tools.push('order_read');
|
||||||
|
if (wecomBotHasPermission(bot, 'delivery.read')) tools.push('delivery_read');
|
||||||
|
if (wecomBotHasPermission(bot, 'store.read')) tools.push('store_read');
|
||||||
|
if (wecomBotHasPermission(bot, 'redeem.read')) tools.push('redeem_read');
|
||||||
|
if (wecomBotHasPermission(bot, 'user.read')) tools.push('user_read');
|
||||||
|
if (wecomBotHasPermission(bot, 'support_ticket.read')) {
|
||||||
|
tools.push('support_tickets_open', 'support_ticket_read');
|
||||||
|
}
|
||||||
|
if (wecomBotHasPermission(bot, 'finance.store_bill.read')) tools.push('finance_store_bill');
|
||||||
|
if (wecomBotHasPermission(bot, 'finance.partner_bill.read')) tools.push('finance_partner_bill');
|
||||||
|
if (wecomBotHasPermission(bot, 'finance.winery_bill.read')) tools.push('finance_winery_bill');
|
||||||
|
if (wecomBotHasPermission(bot, 'finance.logistics_bill.read')) tools.push('finance_logistics_bill');
|
||||||
|
if (wecomBotHasPermission(bot, 'finance.payout.read')) tools.push('finance_payout');
|
||||||
|
if (wecomBotHasPermission(bot, 'finance.withdrawal.read')) tools.push('finance_withdrawal');
|
||||||
|
if (wecomBotHasPermission(bot, 'dev_plan.task.read')) tools.push('dev_plan_tasks');
|
||||||
|
if (wecomBotHasPermission(bot, 'dev_plan.version.read')) tools.push('dev_plan_versions');
|
||||||
|
if (wecomBotHasPermission(bot, 'dev_plan.version.link_tasks')) tools.push('dev_plan_version_link_tasks');
|
||||||
|
if (wecomBotHasPermission(bot, 'server_log.read')) tools.push('server_logs');
|
||||||
|
if (wecomBotHasPermission(bot, 'handbook.read')) tools.push('handbook_read');
|
||||||
|
if (!tools.length) return '';
|
||||||
|
return `\n\n当前机器人可用工具:${tools.join(', ')}`;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,128 @@
|
|||||||
|
import { Injectable, Logger } from '@nestjs/common';
|
||||||
|
import { Prisma } from '@prisma/client';
|
||||||
|
import type { WecomBotPermission } from '@dukang/shared-types';
|
||||||
|
import { PrismaService } from '../../common/prisma/prisma.module';
|
||||||
|
import { serializeBigInt } from '../../common/decorators/current-user.decorator';
|
||||||
|
import type { WecomBotRuntimeConfig } from './wecom-bot.types';
|
||||||
|
|
||||||
|
export type WecomBotAuditContext = {
|
||||||
|
bot: WecomBotRuntimeConfig;
|
||||||
|
wecomUserId: string;
|
||||||
|
action: string;
|
||||||
|
permission?: WecomBotPermission | null;
|
||||||
|
inputSummary?: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class WecomBotAuditService {
|
||||||
|
private readonly logger = new Logger(WecomBotAuditService.name);
|
||||||
|
|
||||||
|
constructor(private readonly prisma: PrismaService) {}
|
||||||
|
|
||||||
|
async run<T>(ctx: WecomBotAuditContext, fn: () => Promise<T>): Promise<T> {
|
||||||
|
const started = Date.now();
|
||||||
|
try {
|
||||||
|
const result = await fn();
|
||||||
|
await this.write({ ...ctx, success: true, latencyMs: Date.now() - started });
|
||||||
|
return result;
|
||||||
|
} catch (e) {
|
||||||
|
const msg = e instanceof Error ? e.message : String(e);
|
||||||
|
await this.write({
|
||||||
|
...ctx,
|
||||||
|
success: false,
|
||||||
|
errorMessage: msg.slice(0, 512),
|
||||||
|
latencyMs: Date.now() - started,
|
||||||
|
});
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async write(
|
||||||
|
ctx: WecomBotAuditContext & {
|
||||||
|
success: boolean;
|
||||||
|
errorMessage?: string | null;
|
||||||
|
latencyMs?: number | null;
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
const botId = ctx.bot.id ? BigInt(ctx.bot.id) : null;
|
||||||
|
this.logger.log(
|
||||||
|
`wecom bot audit action=${ctx.action} bot=${ctx.bot.key} user=${ctx.wecomUserId} success=${ctx.success}${ctx.inputSummary ? ` input=${ctx.inputSummary.slice(0, 80)}` : ''}`,
|
||||||
|
);
|
||||||
|
try {
|
||||||
|
await this.prisma.logWecomBot.create({
|
||||||
|
data: {
|
||||||
|
botId,
|
||||||
|
botKey: ctx.bot.key,
|
||||||
|
wecomUserId: ctx.wecomUserId,
|
||||||
|
action: ctx.action,
|
||||||
|
permission: ctx.permission ?? null,
|
||||||
|
inputSummary: ctx.inputSummary?.slice(0, 512) ?? null,
|
||||||
|
success: ctx.success,
|
||||||
|
errorMessage: ctx.errorMessage ?? null,
|
||||||
|
latencyMs: ctx.latencyMs ?? null,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
this.logger.warn(`wecom bot audit write failed: ${String(e)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async list(query: {
|
||||||
|
page?: number;
|
||||||
|
pageSize?: number;
|
||||||
|
botId?: string;
|
||||||
|
wecomUserId?: string;
|
||||||
|
action?: string;
|
||||||
|
success?: string;
|
||||||
|
from?: string;
|
||||||
|
to?: string;
|
||||||
|
}) {
|
||||||
|
const page = query.page ?? 1;
|
||||||
|
const pageSize = query.pageSize ?? 20;
|
||||||
|
const where: Prisma.LogWecomBotWhereInput = {};
|
||||||
|
|
||||||
|
if (query.botId) where.botId = BigInt(query.botId);
|
||||||
|
if (query.wecomUserId?.trim()) where.wecomUserId = { contains: query.wecomUserId.trim() };
|
||||||
|
if (query.action?.trim()) where.action = { contains: query.action.trim() };
|
||||||
|
if (query.success === 'true' || query.success === 'false') {
|
||||||
|
where.success = query.success === 'true';
|
||||||
|
}
|
||||||
|
if (query.from || query.to) {
|
||||||
|
where.createdAt = {
|
||||||
|
...(query.from ? { gte: new Date(query.from) } : {}),
|
||||||
|
...(query.to ? { lte: new Date(query.to) } : {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const [rows, total] = await Promise.all([
|
||||||
|
this.prisma.logWecomBot.findMany({
|
||||||
|
where,
|
||||||
|
orderBy: { createdAt: 'desc' },
|
||||||
|
skip: (page - 1) * pageSize,
|
||||||
|
take: pageSize,
|
||||||
|
include: { bot: { select: { id: true, name: true } } },
|
||||||
|
}),
|
||||||
|
this.prisma.logWecomBot.count({ where }),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return serializeBigInt({
|
||||||
|
items: rows.map((row) => ({
|
||||||
|
id: row.id.toString(),
|
||||||
|
botId: row.botId?.toString() ?? null,
|
||||||
|
botName: row.bot?.name ?? null,
|
||||||
|
botKey: row.botKey,
|
||||||
|
wecomUserId: row.wecomUserId,
|
||||||
|
action: row.action,
|
||||||
|
permission: row.permission,
|
||||||
|
inputSummary: row.inputSummary,
|
||||||
|
success: row.success,
|
||||||
|
errorMessage: row.errorMessage,
|
||||||
|
latencyMs: row.latencyMs,
|
||||||
|
createdAt: row.createdAt.toISOString(),
|
||||||
|
})),
|
||||||
|
total,
|
||||||
|
page,
|
||||||
|
pageSize,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,24 @@
|
|||||||
|
/** 去掉 LLM 误输出的 JSON / API 占位,避免展示给用户 */
|
||||||
|
export function sanitizeWecomUserReply(text: string): string {
|
||||||
|
let s = text.trim();
|
||||||
|
s = s.replace(/```(?:json)?\s*[\s\S]*?```/gi, '').trim();
|
||||||
|
s = s.replace(/\{\s*"api"\s*:[\s\S]*?\}/gi, '').trim();
|
||||||
|
s = s.replace(/请稍等[,,]?系统正在检索[^\n]*/gi, '').trim();
|
||||||
|
s = s.replace(/^我来帮您[^\n]*\n+/i, '').trim();
|
||||||
|
if (!s) {
|
||||||
|
return '未能生成有效回复。请使用「帮助」中的指令,或换一种问法。';
|
||||||
|
}
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 解析 LLM 工具行:TOOL support_tickets_open 或 TOOL order_lookup DK123 */
|
||||||
|
export function parseWecomToolLine(raw: string): { name: string; args: string } | null {
|
||||||
|
const line = raw
|
||||||
|
.split('\n')
|
||||||
|
.map((l) => l.trim())
|
||||||
|
.find((l) => /^TOOL\s+\S+/i.test(l));
|
||||||
|
if (!line) return null;
|
||||||
|
const m = line.match(/^TOOL\s+(\S+)(?:\s+(.*))?$/i);
|
||||||
|
if (!m) return null;
|
||||||
|
return { name: m[1].toLowerCase(), args: (m[2] ?? '').trim() };
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import type { WecomBotPermission, WecomBotRole } from '@dukang/shared-types';
|
import type { WecomBotPermission, WecomBotRole } from '@dukang/shared-types';
|
||||||
|
import { normalizeWecomBotRole } from '@dukang/shared-types';
|
||||||
|
|
||||||
export type WecomBotRuntimeConfig = {
|
export type WecomBotRuntimeConfig = {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -11,6 +12,7 @@ export type WecomBotRuntimeConfig = {
|
|||||||
welcome: string;
|
welcome: string;
|
||||||
avatarUrl: string | null;
|
avatarUrl: string | null;
|
||||||
permissions: WecomBotPermission[];
|
permissions: WecomBotPermission[];
|
||||||
|
reviewSuperAdminWecomUserIds: string[];
|
||||||
aiEnabled: boolean;
|
aiEnabled: boolean;
|
||||||
llmConfigId: string | null;
|
llmConfigId: string | null;
|
||||||
knowledgeBaseId: string | null;
|
knowledgeBaseId: string | null;
|
||||||
@@ -22,3 +24,23 @@ export function wecomBotHasPermission(
|
|||||||
): boolean {
|
): boolean {
|
||||||
return bot.permissions.includes(permission);
|
return bot.permissions.includes(permission);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function wecomBotNormalizeRole(raw: string): WecomBotRole {
|
||||||
|
return normalizeWecomBotRole(raw);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function wecomBotCanReview(
|
||||||
|
bot: WecomBotRuntimeConfig,
|
||||||
|
wecomUserId: string,
|
||||||
|
): boolean {
|
||||||
|
if (
|
||||||
|
!wecomBotHasPermission(bot, 'support_ticket.review') &&
|
||||||
|
!wecomBotHasPermission(bot, 'support_ticket.approve') &&
|
||||||
|
!wecomBotHasPermission(bot, 'support_ticket.reject')
|
||||||
|
) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const ids = bot.reviewSuperAdminWecomUserIds.map((s) => s.trim()).filter(Boolean);
|
||||||
|
if (!ids.length) return false;
|
||||||
|
return ids.includes(wecomUserId.trim());
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,226 @@
|
|||||||
|
import { BadRequestException, Injectable, Logger, OnModuleInit } from '@nestjs/common';
|
||||||
|
import {
|
||||||
|
WECOM_PUSH_CONDITIONS,
|
||||||
|
WECOM_PUSH_DEFAULT_ALERT_CONDITIONS,
|
||||||
|
WECOM_PUSH_DEFAULT_DEV_DISPATCH_CONDITIONS,
|
||||||
|
maskWecomWebhookUrl,
|
||||||
|
parseWecomPushConditions,
|
||||||
|
type WecomMessagePushDto,
|
||||||
|
type WecomPushCondition,
|
||||||
|
} from '@dukang/shared-types';
|
||||||
|
import { PrismaService } from '../../common/prisma/prisma.module';
|
||||||
|
import { applyWecomAtMentionInContent } from '../../modules/dev-plan/dev-plan-wecom-mention.util';
|
||||||
|
|
||||||
|
type PushRow = {
|
||||||
|
id: bigint;
|
||||||
|
name: string;
|
||||||
|
avatarUrl: string | null;
|
||||||
|
webhookUrl: string;
|
||||||
|
enabled: boolean;
|
||||||
|
mentionWecomUserId: string | null;
|
||||||
|
pushConditions: string;
|
||||||
|
sortOrder: number;
|
||||||
|
createdAt: Date;
|
||||||
|
updatedAt: Date;
|
||||||
|
};
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class WecomMessagePushService implements OnModuleInit {
|
||||||
|
private readonly logger = new Logger(WecomMessagePushService.name);
|
||||||
|
|
||||||
|
constructor(private readonly prisma: PrismaService) {}
|
||||||
|
|
||||||
|
async onModuleInit(): Promise<void> {
|
||||||
|
try {
|
||||||
|
await this.ensureDefaults();
|
||||||
|
} catch (e) {
|
||||||
|
this.logger.warn(
|
||||||
|
`wecom message push ensureDefaults failed: ${e instanceof Error ? e.message : String(e)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 表空时从 .env / 旧 dev_plan_settings 迁移默认推送(v3.4.11) */
|
||||||
|
async ensureDefaults(): Promise<void> {
|
||||||
|
const count = await this.prisma.wecomMessagePush.count();
|
||||||
|
if (count > 0) return;
|
||||||
|
|
||||||
|
const alertUrl = (process.env.WECOM_ALERT_WEBHOOK_URL || '').trim();
|
||||||
|
if (alertUrl) {
|
||||||
|
const alertEnabled = process.env.WECOM_ALERT_ENABLED !== 'false';
|
||||||
|
await this.prisma.wecomMessagePush.create({
|
||||||
|
data: {
|
||||||
|
name: '运营告警',
|
||||||
|
webhookUrl: alertUrl,
|
||||||
|
enabled: alertEnabled,
|
||||||
|
pushConditions: JSON.stringify(WECOM_PUSH_DEFAULT_ALERT_CONDITIONS),
|
||||||
|
sortOrder: 0,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
this.logger.log('seeded wecom message push: 运营告警');
|
||||||
|
}
|
||||||
|
|
||||||
|
let devWebhook: string | null = null;
|
||||||
|
let devUserId: string | null = null;
|
||||||
|
let devEnabled = false;
|
||||||
|
try {
|
||||||
|
const rows = await this.prisma.$queryRawUnsafe<
|
||||||
|
Array<{
|
||||||
|
task_dispatch_webhook_url: string | null;
|
||||||
|
task_dispatch_wecom_user_id: string | null;
|
||||||
|
task_dispatch_enabled: number | boolean | null;
|
||||||
|
}>
|
||||||
|
>(
|
||||||
|
'SELECT task_dispatch_webhook_url, task_dispatch_wecom_user_id, task_dispatch_enabled FROM dev_plan_settings LIMIT 1',
|
||||||
|
);
|
||||||
|
const row = rows[0];
|
||||||
|
if (row) {
|
||||||
|
devWebhook = row.task_dispatch_webhook_url;
|
||||||
|
devUserId = row.task_dispatch_wecom_user_id;
|
||||||
|
devEnabled = !!row.task_dispatch_enabled;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// 列已迁移删除,跳过
|
||||||
|
}
|
||||||
|
|
||||||
|
if (devWebhook?.trim()) {
|
||||||
|
await this.prisma.wecomMessagePush.create({
|
||||||
|
data: {
|
||||||
|
name: '开发任务派发',
|
||||||
|
webhookUrl: devWebhook.trim(),
|
||||||
|
enabled: devEnabled,
|
||||||
|
mentionWecomUserId: devUserId?.trim() || null,
|
||||||
|
pushConditions: JSON.stringify(WECOM_PUSH_DEFAULT_DEV_DISPATCH_CONDITIONS),
|
||||||
|
sortOrder: 10,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
this.logger.log('seeded wecom message push: 开发任务派发');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async listMatchingPushes(eventKey: WecomPushCondition): Promise<PushRow[]> {
|
||||||
|
const rows = await this.prisma.wecomMessagePush.findMany({
|
||||||
|
where: { enabled: true },
|
||||||
|
orderBy: [{ sortOrder: 'asc' }, { id: 'asc' }],
|
||||||
|
});
|
||||||
|
return rows.filter((r) => parseWecomPushConditions(r.pushConditions).includes(eventKey));
|
||||||
|
}
|
||||||
|
|
||||||
|
async hasEnabledPushes(eventKey: WecomPushCondition): Promise<boolean> {
|
||||||
|
const pushes = await this.listMatchingPushes(eventKey);
|
||||||
|
return pushes.length > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 向所有匹配 eventKey 的启用推送发送 markdown;返回成功发送数 */
|
||||||
|
async dispatchMarkdown(
|
||||||
|
eventKey: WecomPushCondition,
|
||||||
|
content: string,
|
||||||
|
options?: { applyMention?: boolean },
|
||||||
|
): Promise<number> {
|
||||||
|
const pushes = await this.listMatchingPushes(eventKey);
|
||||||
|
if (!pushes.length) return 0;
|
||||||
|
|
||||||
|
const applyMention = options?.applyMention !== false;
|
||||||
|
let sent = 0;
|
||||||
|
for (const push of pushes) {
|
||||||
|
let text = content.trim();
|
||||||
|
if (applyMention && push.mentionWecomUserId) {
|
||||||
|
text = applyWecomAtMentionInContent(text, push.mentionWecomUserId);
|
||||||
|
}
|
||||||
|
const ok = await this.sendMarkdownToWebhook(push.webhookUrl, text);
|
||||||
|
if (ok) sent += 1;
|
||||||
|
}
|
||||||
|
return sent;
|
||||||
|
}
|
||||||
|
|
||||||
|
async dispatchMarkdownOrThrow(
|
||||||
|
eventKey: WecomPushCondition,
|
||||||
|
content: string,
|
||||||
|
options?: { applyMention?: boolean },
|
||||||
|
): Promise<number> {
|
||||||
|
const sent = await this.dispatchMarkdown(eventKey, content, options);
|
||||||
|
if (sent === 0) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
`没有已启用且勾选「${eventKey}」条件的消息推送,请在 HQ「企微机器人 → 消息推送」中配置`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return sent;
|
||||||
|
}
|
||||||
|
|
||||||
|
async sendMarkdownToWebhook(webhookUrl: string, content: string): Promise<boolean> {
|
||||||
|
const url = (webhookUrl || '').trim();
|
||||||
|
if (!url) return false;
|
||||||
|
try {
|
||||||
|
const res = await fetch(url, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
msgtype: 'markdown',
|
||||||
|
markdown: { content: content.slice(0, 4000) },
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
const data = (await res.json().catch(() => ({}))) as {
|
||||||
|
errcode?: number;
|
||||||
|
errmsg?: string;
|
||||||
|
};
|
||||||
|
if (!res.ok || (data.errcode != null && data.errcode !== 0)) {
|
||||||
|
this.logger.warn(
|
||||||
|
`wecom message push failed: HTTP ${res.status} errcode=${data.errcode} ${data.errmsg ?? ''}`,
|
||||||
|
);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
} catch (e) {
|
||||||
|
this.logger.warn(
|
||||||
|
`wecom message push network error: ${e instanceof Error ? e.message : String(e)}`,
|
||||||
|
);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async sendTest(id: bigint): Promise<{ ok: boolean; message: string }> {
|
||||||
|
const row = await this.prisma.wecomMessagePush.findUnique({ where: { id } });
|
||||||
|
if (!row) throw new BadRequestException('消息推送不存在');
|
||||||
|
if (!row.webhookUrl.trim()) {
|
||||||
|
return { ok: false, message: 'Webhook URL 未配置' };
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' });
|
||||||
|
let content = `**消息推送测试 · ${row.name}**\n时间:${now}`;
|
||||||
|
if (row.mentionWecomUserId) {
|
||||||
|
content = applyWecomAtMentionInContent(content, row.mentionWecomUserId);
|
||||||
|
}
|
||||||
|
const ok = await this.sendMarkdownToWebhook(row.webhookUrl, content);
|
||||||
|
return ok
|
||||||
|
? { ok: true, message: '已发送测试消息,请查看企微群' }
|
||||||
|
: { ok: false, message: 'Webhook 调用失败,请检查 URL 或 API 日志' };
|
||||||
|
}
|
||||||
|
|
||||||
|
toDto(row: PushRow): WecomMessagePushDto {
|
||||||
|
return {
|
||||||
|
id: row.id.toString(),
|
||||||
|
name: row.name,
|
||||||
|
avatarUrl: row.avatarUrl,
|
||||||
|
webhookUrl: row.webhookUrl,
|
||||||
|
webhookUrlMasked: maskWecomWebhookUrl(row.webhookUrl),
|
||||||
|
enabled: row.enabled,
|
||||||
|
mentionWecomUserId: row.mentionWecomUserId,
|
||||||
|
pushConditions: parseWecomPushConditions(row.pushConditions),
|
||||||
|
sortOrder: row.sortOrder,
|
||||||
|
createdAt: row.createdAt.toISOString(),
|
||||||
|
updatedAt: row.updatedAt.toISOString(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
validatePushConditions(conditions: string[]): WecomPushCondition[] {
|
||||||
|
const parsed = parseWecomPushConditions(conditions);
|
||||||
|
if (!parsed.length) {
|
||||||
|
throw new BadRequestException('请至少勾选一项推送条件');
|
||||||
|
}
|
||||||
|
const valid = new Set<string>(WECOM_PUSH_CONDITIONS);
|
||||||
|
for (const c of conditions) {
|
||||||
|
if (!valid.has(c)) throw new BadRequestException(`无效推送条件:${c}`);
|
||||||
|
}
|
||||||
|
return parsed;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
import { Injectable, Logger } from '@nestjs/common';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 企业微信群机器人 Webhook 出站(单向告警,与智能机器人长连接无关)。
|
|
||||||
* @see https://developer.work.weixin.qq.com/document/path/91770
|
|
||||||
*/
|
|
||||||
@Injectable()
|
|
||||||
export class WecomWebhookAlertService {
|
|
||||||
private readonly logger = new Logger(WecomWebhookAlertService.name);
|
|
||||||
|
|
||||||
isEnabled(): boolean {
|
|
||||||
return (
|
|
||||||
process.env.WECOM_ALERT_ENABLED === 'true' &&
|
|
||||||
!!(process.env.WECOM_ALERT_WEBHOOK_URL || '').trim()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
async sendMarkdown(content: string): Promise<boolean> {
|
|
||||||
if (!this.isEnabled()) return false;
|
|
||||||
const url = (process.env.WECOM_ALERT_WEBHOOK_URL || '').trim();
|
|
||||||
try {
|
|
||||||
const res = await fetch(url, {
|
|
||||||
method: 'POST',
|
|
||||||
headers: { 'Content-Type': 'application/json' },
|
|
||||||
body: JSON.stringify({
|
|
||||||
msgtype: 'markdown',
|
|
||||||
markdown: { content: content.slice(0, 4000) },
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
const data = (await res.json().catch(() => ({}))) as {
|
|
||||||
errcode?: number;
|
|
||||||
errmsg?: string;
|
|
||||||
};
|
|
||||||
if (!res.ok || (data.errcode != null && data.errcode !== 0)) {
|
|
||||||
this.logger.warn(
|
|
||||||
`wecom webhook failed: HTTP ${res.status} errcode=${data.errcode} ${data.errmsg ?? ''}`,
|
|
||||||
);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
} catch (e) {
|
|
||||||
this.logger.warn(
|
|
||||||
`wecom webhook network error: ${e instanceof Error ? e.message : String(e)}`,
|
|
||||||
);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,25 +1,33 @@
|
|||||||
import { Module, forwardRef } from '@nestjs/common';
|
import { Module, forwardRef } from '@nestjs/common';
|
||||||
|
|
||||||
|
import { CommonModule } from '../../modules/common/common.module';
|
||||||
|
|
||||||
import { DevPlanModule } from '../../modules/dev-plan/dev-plan.module';
|
import { DevPlanModule } from '../../modules/dev-plan/dev-plan.module';
|
||||||
|
|
||||||
import { SettlementModule } from '../../modules/settlement/settlement.module';
|
import { SettlementModule } from '../../modules/settlement/settlement.module';
|
||||||
|
|
||||||
import { IntegrationsModule } from '../integrations.module';
|
import { IntegrationsModule } from '../integrations.module';
|
||||||
|
|
||||||
|
import { LlmModule } from '../llm/llm.module';
|
||||||
|
|
||||||
import { WecomAibotService } from './wecom-aibot.service';
|
import { WecomAibotService } from './wecom-aibot.service';
|
||||||
/** 企微多机器人:依赖 Common(工单)+ Integrations(短信)+ Llm,不反向被 Integrations 引用 */
|
|
||||||
import { WecomBotActionsService } from './wecom-bot-actions.service';
|
import { WecomBotActionsService } from './wecom-bot-actions.service';
|
||||||
|
|
||||||
import { WecomBotAiService } from './wecom-bot-ai.service';
|
import { WecomBotAiService } from './wecom-bot-ai.service';
|
||||||
|
|
||||||
|
import { WecomBotAuditService } from './wecom-bot-audit.service';
|
||||||
|
|
||||||
import { WecomBotCapabilityService } from './wecom-bot-capability.service';
|
import { WecomBotCapabilityService } from './wecom-bot-capability.service';
|
||||||
|
|
||||||
import { WecomBotSessionService } from './wecom-bot-session.service';
|
import { WecomBotSessionService } from './wecom-bot-session.service';
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/** 企微多机器人:依赖 Common(工单)+ Settlement/DevPlan + Integrations(短信)+ Llm */
|
/** 企微多机器人:依赖 Common(工单)+ Settlement/DevPlan + Integrations(短信)+ Llm */
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
|
|
||||||
exports: [WecomAibotService],
|
imports: [
|
||||||
|
|
||||||
forwardRef(() => CommonModule),
|
forwardRef(() => CommonModule),
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { IamModule } from '../iam/iam.module';
|
|||||||
import { AnalyticsModule } from '../analytics/analytics.module';
|
import { AnalyticsModule } from '../analytics/analytics.module';
|
||||||
import { IntegrationsModule } from '../../integrations/integrations.module';
|
import { IntegrationsModule } from '../../integrations/integrations.module';
|
||||||
import { SystemConfigModule } from '../../common/system-config/system-config.module';
|
import { SystemConfigModule } from '../../common/system-config/system-config.module';
|
||||||
|
import { DevPlanModule } from '../dev-plan/dev-plan.module';
|
||||||
import { ResourceService } from './resource.service';
|
import { ResourceService } from './resource.service';
|
||||||
import { EventService } from './event.service';
|
import { EventService } from './event.service';
|
||||||
import { TicketService } from './ticket.service';
|
import { TicketService } from './ticket.service';
|
||||||
@@ -20,7 +21,7 @@ import { ClientErrorService } from './client-error.service';
|
|||||||
import { ClientErrorController } from './client-error.controller';
|
import { ClientErrorController } from './client-error.controller';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [forwardRef(() => IamModule), IntegrationsModule, SystemConfigModule, forwardRef(() => AnalyticsModule)],
|
imports: [forwardRef(() => IamModule), IntegrationsModule, SystemConfigModule, forwardRef(() => AnalyticsModule), DevPlanModule],
|
||||||
controllers: [
|
controllers: [
|
||||||
ResourceController,
|
ResourceController,
|
||||||
EventController,
|
EventController,
|
||||||
|
|||||||
@@ -5,9 +5,12 @@ import {
|
|||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import type { SupportTicketStatus, SupportTicketType } from '@prisma/client';
|
import type { SupportTicketStatus, SupportTicketType } from '@prisma/client';
|
||||||
import { Prisma } from '@prisma/client';
|
import { Prisma } from '@prisma/client';
|
||||||
|
import type { CreateDevPlanTaskFromTicketInput } from '@dukang/shared-types';
|
||||||
import { PrismaService } from '../../common/prisma/prisma.module';
|
import { PrismaService } from '../../common/prisma/prisma.module';
|
||||||
import { serializeBigInt } from '../../common/decorators/current-user.decorator';
|
import { serializeBigInt } from '../../common/decorators/current-user.decorator';
|
||||||
import { AlertService } from '../../common/alert/alert.service';
|
import { AlertService } from '../../common/alert/alert.service';
|
||||||
|
import { WecomMessagePushService } from '../../integrations/wecom/wecom-message-push.service';
|
||||||
|
import { DevPlanService } from '../dev-plan/dev-plan.service';
|
||||||
import type {
|
import type {
|
||||||
CreateSupportTicketDto,
|
CreateSupportTicketDto,
|
||||||
RejectSupportTicketDto,
|
RejectSupportTicketDto,
|
||||||
@@ -24,6 +27,8 @@ export class SupportTicketService {
|
|||||||
constructor(
|
constructor(
|
||||||
private readonly prisma: PrismaService,
|
private readonly prisma: PrismaService,
|
||||||
private readonly alert: AlertService,
|
private readonly alert: AlertService,
|
||||||
|
private readonly devPlan: DevPlanService,
|
||||||
|
private readonly wecomPush: WecomMessagePushService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async create(
|
async create(
|
||||||
@@ -48,7 +53,26 @@ export class SupportTicketService {
|
|||||||
title: '新建技术支持工单',
|
title: '新建技术支持工单',
|
||||||
detail: `工单 ${ticket.ticketNo}\n类型 ${ticket.ticketType}\n标题 ${ticket.title}\n创建人 ${creator.name}`,
|
detail: `工单 ${ticket.ticketNo}\n类型 ${ticket.ticketType}\n标题 ${ticket.title}\n创建人 ${creator.name}`,
|
||||||
dedupeKey: `support_ticket_create|${ticket.ticketNo}`,
|
dedupeKey: `support_ticket_create|${ticket.ticketNo}`,
|
||||||
|
eventKeys: ['alert.ops'],
|
||||||
});
|
});
|
||||||
|
const envLabel = (process.env.WECOM_ALERT_ENV_LABEL || process.env.NODE_ENV || 'local').trim();
|
||||||
|
const now = new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' });
|
||||||
|
void this.wecomPush
|
||||||
|
.dispatchMarkdown(
|
||||||
|
'support_ticket.created',
|
||||||
|
[
|
||||||
|
`## 新建技术支持工单`,
|
||||||
|
`> 环境:<font color="comment">${envLabel}</font>`,
|
||||||
|
`> 时间:${now}`,
|
||||||
|
'',
|
||||||
|
`**工单号**:${ticket.ticketNo}`,
|
||||||
|
`**类型**:${ticket.ticketType}`,
|
||||||
|
`**标题**:${ticket.title}`,
|
||||||
|
`**创建人**:${creator.name}`,
|
||||||
|
ticket.content ? `\n${ticket.content.slice(0, 2000)}` : '',
|
||||||
|
].join('\n'),
|
||||||
|
)
|
||||||
|
.catch(() => {});
|
||||||
return serializeBigInt(ticket);
|
return serializeBigInt(ticket);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -72,13 +96,32 @@ export class SupportTicketService {
|
|||||||
}),
|
}),
|
||||||
this.prisma.commonSupportTicket.count({ where }),
|
this.prisma.commonSupportTicket.count({ where }),
|
||||||
]);
|
]);
|
||||||
return serializeBigInt({ items, total, page, pageSize });
|
const linkedMap = await this.devPlan.listLinkedTasksByTicketIds(items.map((i) => i.id));
|
||||||
|
const enriched = items.map((ticket) => ({
|
||||||
|
...ticket,
|
||||||
|
linkedTasks: (linkedMap.get(String(ticket.id)) ?? []).map((t) => ({
|
||||||
|
id: t.id,
|
||||||
|
taskNo: t.taskNo,
|
||||||
|
content: t.content,
|
||||||
|
status: t.status,
|
||||||
|
})),
|
||||||
|
}));
|
||||||
|
return serializeBigInt({ items: enriched, total, page, pageSize });
|
||||||
}
|
}
|
||||||
|
|
||||||
async detail(id: bigint) {
|
async detail(id: bigint) {
|
||||||
const ticket = await this.prisma.commonSupportTicket.findUnique({ where: { id } });
|
const ticket = await this.prisma.commonSupportTicket.findUnique({ where: { id } });
|
||||||
if (!ticket) throw new NotFoundException('技术支持工单不存在');
|
if (!ticket) throw new NotFoundException('技术支持工单不存在');
|
||||||
return serializeBigInt(ticket);
|
const linkedMap = await this.devPlan.listLinkedTasksByTicketIds([id]);
|
||||||
|
return serializeBigInt({
|
||||||
|
...ticket,
|
||||||
|
linkedTasks: (linkedMap.get(String(id)) ?? []).map((t) => ({
|
||||||
|
id: t.id,
|
||||||
|
taskNo: t.taskNo,
|
||||||
|
content: t.content,
|
||||||
|
status: t.status,
|
||||||
|
})),
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private async getOrThrow(id: bigint) {
|
private async getOrThrow(id: bigint) {
|
||||||
@@ -137,6 +180,71 @@ export class SupportTicketService {
|
|||||||
return serializeBigInt(updated);
|
return serializeBigInt(updated);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 统一审批:通过时创建开发计划任务 */
|
||||||
|
async review(
|
||||||
|
id: bigint,
|
||||||
|
reviewer: { id: bigint; name: string },
|
||||||
|
input: {
|
||||||
|
decision: 'APPROVE' | 'REJECT';
|
||||||
|
rejectReason?: string;
|
||||||
|
note?: string;
|
||||||
|
tasks?: CreateDevPlanTaskFromTicketInput[];
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
if (input.decision === 'REJECT') {
|
||||||
|
if (!input.rejectReason?.trim()) throw new BadRequestException('请填写驳回理由');
|
||||||
|
return this.reject(id, reviewer, { rejectReason: input.rejectReason });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!input.tasks?.length) throw new BadRequestException('审批通过需至少创建 1 条开发任务');
|
||||||
|
const ticket = await this.getOrThrow(id);
|
||||||
|
if (ticket.status !== 'PENDING_REVIEW') {
|
||||||
|
throw new BadRequestException('仅待评审工单可审批');
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.devPlan.createTasksFromTicket(id, input.tasks, reviewer.id);
|
||||||
|
|
||||||
|
const updated = await this.prisma.commonSupportTicket.update({
|
||||||
|
where: { id },
|
||||||
|
data: {
|
||||||
|
status: 'DEVELOPING',
|
||||||
|
reviewerId: reviewer.id,
|
||||||
|
reviewerName: reviewer.name,
|
||||||
|
reviewedAt: new Date(),
|
||||||
|
remark: input.note?.trim() || ticket.remark,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const linkedMap = await this.devPlan.listLinkedTasksByTicketIds([id]);
|
||||||
|
return serializeBigInt({
|
||||||
|
...updated,
|
||||||
|
linkedTasks: (linkedMap.get(String(id)) ?? []).map((t) => ({
|
||||||
|
id: t.id,
|
||||||
|
taskNo: t.taskNo,
|
||||||
|
content: t.content,
|
||||||
|
status: t.status,
|
||||||
|
})),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 批量确认审批 */
|
||||||
|
async batchReviewConfirm(
|
||||||
|
reviewer: { id: bigint; name: string },
|
||||||
|
items: Array<{
|
||||||
|
ticketId: string;
|
||||||
|
decision: 'APPROVE' | 'REJECT';
|
||||||
|
rejectReason?: string;
|
||||||
|
note?: string;
|
||||||
|
tasks?: CreateDevPlanTaskFromTicketInput[];
|
||||||
|
}>,
|
||||||
|
) {
|
||||||
|
const results: unknown[] = [];
|
||||||
|
for (const item of items) {
|
||||||
|
const result = await this.review(BigInt(item.ticketId), reviewer, item);
|
||||||
|
results.push(result);
|
||||||
|
}
|
||||||
|
return { items: results };
|
||||||
|
}
|
||||||
|
|
||||||
/** 开发完成 → 测试 */
|
/** 开发完成 → 测试 */
|
||||||
async startTesting(id: bigint, dto?: SupportTicketRemarkDto) {
|
async startTesting(id: bigint, dto?: SupportTicketRemarkDto) {
|
||||||
const ticket = await this.getOrThrow(id);
|
const ticket = await this.getOrThrow(id);
|
||||||
|
|||||||
@@ -0,0 +1,167 @@
|
|||||||
|
import {
|
||||||
|
Body,
|
||||||
|
Controller,
|
||||||
|
Delete,
|
||||||
|
Get,
|
||||||
|
NotFoundException,
|
||||||
|
Param,
|
||||||
|
Post,
|
||||||
|
Put,
|
||||||
|
Query,
|
||||||
|
UseGuards,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { HqAuthGuard } from '../../common/guards/hq-auth.guard';
|
||||||
|
import {
|
||||||
|
HqPermissionGuard,
|
||||||
|
RequireHqPermissions,
|
||||||
|
} from '../../common/guards/hq-permission.guard';
|
||||||
|
import { AuthUser } from '../../common/guards/jwt-auth.guard';
|
||||||
|
import { CurrentUser } from '../../common/decorators/current-user.decorator';
|
||||||
|
import { HqOperation } from '../../common/hq-operation/hq-operation.decorator';
|
||||||
|
import { HqOperationAction } from '../../common/hq-operation/hq-operation.constants';
|
||||||
|
import { PrismaService } from '../../common/prisma/prisma.module';
|
||||||
|
import { DevPlanService } from './dev-plan.service';
|
||||||
|
import {
|
||||||
|
CreateDevPlanTaskDto,
|
||||||
|
CreateDevPlanVersionDto,
|
||||||
|
DevPlanTaskDispatchDto,
|
||||||
|
DevPlanTaskListQueryDto,
|
||||||
|
ReplaceVersionTasksDto,
|
||||||
|
UpdateDevPlanSettingsDto,
|
||||||
|
UpdateDevPlanTaskDto,
|
||||||
|
UpdateDevPlanVersionDto,
|
||||||
|
} from './dto/dev-plan.dto';
|
||||||
|
|
||||||
|
@Controller('admin/dev-plan')
|
||||||
|
@UseGuards(HqAuthGuard, HqPermissionGuard)
|
||||||
|
@RequireHqPermissions('dev_plan')
|
||||||
|
export class AdminDevPlanController {
|
||||||
|
constructor(
|
||||||
|
private readonly service: DevPlanService,
|
||||||
|
private readonly prisma: PrismaService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
private async resolveHqAccount(user: AuthUser) {
|
||||||
|
const account = await this.prisma.hqAccount.findUnique({
|
||||||
|
where: { id: user.actorId },
|
||||||
|
select: { id: true, name: true },
|
||||||
|
});
|
||||||
|
if (!account) throw new NotFoundException('HQ 账户不存在');
|
||||||
|
return account;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('tasks')
|
||||||
|
listTasks(@Query() query: DevPlanTaskListQueryDto) {
|
||||||
|
return this.service.listTasks(query);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('tasks')
|
||||||
|
@HqOperation({ action: HqOperationAction.DEV_PLAN_TASK_CREATE, refType: 'DEV_PLAN_TASK', includeBody: true })
|
||||||
|
async createTask(@CurrentUser() user: AuthUser, @Body() body: CreateDevPlanTaskDto) {
|
||||||
|
const account = await this.resolveHqAccount(user);
|
||||||
|
return this.service.createTask(body, account.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('tasks/:id')
|
||||||
|
getTask(@Param('id') id: string) {
|
||||||
|
return this.service.getTask(BigInt(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Put('tasks/:id')
|
||||||
|
@HqOperation({
|
||||||
|
action: HqOperationAction.DEV_PLAN_TASK_UPDATE,
|
||||||
|
refType: 'DEV_PLAN_TASK',
|
||||||
|
refIdParam: 'id',
|
||||||
|
includeBody: true,
|
||||||
|
})
|
||||||
|
updateTask(@Param('id') id: string, @Body() body: UpdateDevPlanTaskDto) {
|
||||||
|
return this.service.updateTask(BigInt(id), body);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Delete('tasks/:id')
|
||||||
|
@HqOperation({ action: HqOperationAction.DEV_PLAN_TASK_DELETE, refType: 'DEV_PLAN_TASK', refIdParam: 'id' })
|
||||||
|
deleteTask(@Param('id') id: string) {
|
||||||
|
return this.service.deleteTask(BigInt(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('tasks/dispatch')
|
||||||
|
@HqOperation({ action: HqOperationAction.DEV_PLAN_TASK_DISPATCH, refType: 'DEV_PLAN_TASK', includeBody: true })
|
||||||
|
async dispatchTasks(@CurrentUser() user: AuthUser, @Body() body: DevPlanTaskDispatchDto) {
|
||||||
|
const account = await this.resolveHqAccount(user);
|
||||||
|
return this.service.dispatchTasks(body, account.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('versions')
|
||||||
|
listVersions(
|
||||||
|
@Query('status') status?: string,
|
||||||
|
@Query('page') page?: string,
|
||||||
|
@Query('pageSize') pageSize?: string,
|
||||||
|
) {
|
||||||
|
return this.service.listVersions({
|
||||||
|
status,
|
||||||
|
page: page ? Number(page) : undefined,
|
||||||
|
pageSize: pageSize ? Number(pageSize) : undefined,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('versions')
|
||||||
|
@HqOperation({ action: HqOperationAction.DEV_PLAN_VERSION_CREATE, refType: 'DEV_PLAN_VERSION', includeBody: true })
|
||||||
|
createVersion(@Body() body: CreateDevPlanVersionDto) {
|
||||||
|
return this.service.createVersion(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('versions/:id')
|
||||||
|
getVersion(@Param('id') id: string) {
|
||||||
|
return this.service.getVersion(BigInt(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Put('versions/:id')
|
||||||
|
@HqOperation({
|
||||||
|
action: HqOperationAction.DEV_PLAN_VERSION_UPDATE,
|
||||||
|
refType: 'DEV_PLAN_VERSION',
|
||||||
|
refIdParam: 'id',
|
||||||
|
includeBody: true,
|
||||||
|
})
|
||||||
|
updateVersion(@Param('id') id: string, @Body() body: UpdateDevPlanVersionDto) {
|
||||||
|
return this.service.updateVersion(BigInt(id), body);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Delete('versions/:id')
|
||||||
|
@HqOperation({ action: HqOperationAction.DEV_PLAN_VERSION_DELETE, refType: 'DEV_PLAN_VERSION', refIdParam: 'id' })
|
||||||
|
deleteVersion(@Param('id') id: string) {
|
||||||
|
return this.service.deleteVersion(BigInt(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Put('versions/:id/tasks')
|
||||||
|
@HqOperation({
|
||||||
|
action: HqOperationAction.DEV_PLAN_VERSION_LINK_TASKS,
|
||||||
|
refType: 'DEV_PLAN_VERSION',
|
||||||
|
refIdParam: 'id',
|
||||||
|
includeBody: true,
|
||||||
|
})
|
||||||
|
replaceVersionTasks(@Param('id') id: string, @Body() body: ReplaceVersionTasksDto) {
|
||||||
|
return this.service.replaceVersionTasksApi(BigInt(id), body.taskIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('versions/:id/tasks')
|
||||||
|
@HqOperation({
|
||||||
|
action: HqOperationAction.DEV_PLAN_VERSION_ADD_TASKS,
|
||||||
|
refType: 'DEV_PLAN_VERSION',
|
||||||
|
refIdParam: 'id',
|
||||||
|
includeBody: true,
|
||||||
|
})
|
||||||
|
addVersionTasks(@Param('id') id: string, @Body() body: ReplaceVersionTasksDto) {
|
||||||
|
return this.service.addVersionTasksApi(BigInt(id), body.taskIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('settings')
|
||||||
|
getSettings() {
|
||||||
|
return this.service.getSettings();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Put('settings')
|
||||||
|
@HqOperation({ action: HqOperationAction.DEV_PLAN_SETTINGS_UPDATE, refType: 'DEV_PLAN_SETTINGS', includeBody: true })
|
||||||
|
updateSettings(@Body() body: UpdateDevPlanSettingsDto) {
|
||||||
|
return this.service.updateSettings(body);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
/**
|
||||||
|
|
||||||
|
* 企微群机器人 markdown/text 消息 @ 成员扩展语法。
|
||||||
|
|
||||||
|
* @see https://developer.work.weixin.qq.com/document/path/91770
|
||||||
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/** 生成 `<@userid>` 片段 */
|
||||||
|
|
||||||
|
export function formatWecomAtMention(wecomUserId?: string | null): string {
|
||||||
|
|
||||||
|
const uid = (wecomUserId || '').trim();
|
||||||
|
|
||||||
|
return uid ? `<@${uid}>` : '';
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
|
||||||
|
import { LlmModule } from '../../integrations/llm/llm.module';
|
||||||
|
|
||||||
|
import { DevPlanService } from './dev-plan.service';
|
||||||
|
|
||||||
|
import { SupportTicketReviewAiService } from './support-ticket-review-ai.service';
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@Module({
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,181 @@
|
|||||||
|
import {
|
||||||
|
ArrayMinSize,
|
||||||
|
IsArray,
|
||||||
|
IsIn,
|
||||||
|
IsNotEmpty,
|
||||||
|
IsOptional,
|
||||||
|
IsString,
|
||||||
|
ValidateIf,
|
||||||
|
ValidateNested,
|
||||||
|
} from 'class-validator';
|
||||||
|
import { Type } from 'class-transformer';
|
||||||
|
import {
|
||||||
|
DEV_PLAN_TASK_STATUSES,
|
||||||
|
DEV_PLAN_TASK_TYPES,
|
||||||
|
DEV_PLAN_VERSION_STATUSES,
|
||||||
|
} from '@dukang/shared-types';
|
||||||
|
|
||||||
|
export class DevPlanTaskListQueryDto {
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
status?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
type?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
keyword?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
page?: number;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
pageSize?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class CreateDevPlanTaskDto {
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
content!: string;
|
||||||
|
|
||||||
|
@IsIn(DEV_PLAN_TASK_TYPES)
|
||||||
|
type!: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
supportTicketId?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class UpdateDevPlanTaskDto {
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
content?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsIn(DEV_PLAN_TASK_TYPES)
|
||||||
|
type?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsIn(DEV_PLAN_TASK_STATUSES)
|
||||||
|
status?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class CreateDevPlanVersionDto {
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
versionNo!: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
content?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsIn(DEV_PLAN_VERSION_STATUSES)
|
||||||
|
status?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsArray()
|
||||||
|
@IsString({ each: true })
|
||||||
|
taskIds?: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export class UpdateDevPlanVersionDto {
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
versionNo?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
content?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsIn(DEV_PLAN_VERSION_STATUSES)
|
||||||
|
status?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsArray()
|
||||||
|
@IsString({ each: true })
|
||||||
|
taskIds?: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ReplaceVersionTasksDto {
|
||||||
|
@IsArray()
|
||||||
|
@IsString({ each: true })
|
||||||
|
taskIds!: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export class UpdateDevPlanSettingsDto {
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
reviewAssistantLlmConfigId?: string | null;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
reviewAssistantKnowledgeBaseId?: string | null;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
reviewAssistantPrompt?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class DevPlanTaskDispatchDto {
|
||||||
|
@IsArray()
|
||||||
|
@ArrayMinSize(1)
|
||||||
|
@IsString({ each: true })
|
||||||
|
taskIds!: string[];
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
supplement?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class DevPlanTaskFromTicketDto {
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
content!: string;
|
||||||
|
|
||||||
|
@IsIn(DEV_PLAN_TASK_TYPES)
|
||||||
|
type!: 'BUG' | 'REQUIREMENT' | 'OPTIMIZATION';
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ReviewSupportTicketDto {
|
||||||
|
@IsIn(['APPROVE', 'REJECT'])
|
||||||
|
decision!: 'APPROVE' | 'REJECT';
|
||||||
|
|
||||||
|
@ValidateIf((o: ReviewSupportTicketDto) => o.decision === 'REJECT')
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
rejectReason?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
note?: string;
|
||||||
|
|
||||||
|
@ValidateIf((o: ReviewSupportTicketDto) => o.decision === 'APPROVE')
|
||||||
|
@IsArray()
|
||||||
|
@ArrayMinSize(1)
|
||||||
|
@ValidateNested({ each: true })
|
||||||
|
@Type(() => DevPlanTaskFromTicketDto)
|
||||||
|
tasks?: DevPlanTaskFromTicketDto[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export class BatchReviewPreviewDto {
|
||||||
|
@IsArray()
|
||||||
|
@IsString({ each: true })
|
||||||
|
ticketIds!: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export class BatchReviewConfirmDto {
|
||||||
|
@IsArray()
|
||||||
|
items!: Array<{
|
||||||
|
ticketId: string;
|
||||||
|
decision: 'APPROVE' | 'REJECT';
|
||||||
|
rejectReason?: string;
|
||||||
|
note?: string;
|
||||||
|
tasks?: Array<{ content: string; type: 'BUG' | 'REQUIREMENT' | 'OPTIMIZATION' }>;
|
||||||
|
}>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,157 @@
|
|||||||
|
import { BadRequestException, Injectable, Logger } from '@nestjs/common';
|
||||||
|
import type { BatchReviewPreviewItem } from '@dukang/shared-types';
|
||||||
|
import { mapSupportTicketTypeToDevPlanTask } from '@dukang/shared-types';
|
||||||
|
import { PrismaService } from '../../common/prisma/prisma.module';
|
||||||
|
import { LlmChatClient } from '../../integrations/llm/llm-chat.client';
|
||||||
|
import { KnowledgeRetrievalService } from '../../integrations/llm/knowledge-retrieval.service';
|
||||||
|
import { DevPlanService } from './dev-plan.service';
|
||||||
|
|
||||||
|
const DEFAULT_REVIEW_PROMPT = [
|
||||||
|
'你是杜康好客技术支持工单审核助手。',
|
||||||
|
'根据工单内容与知识库片段,给出审批建议:通过(APPROVE)或驳回(REJECT)。',
|
||||||
|
'通过时可建议拆分为 1~3 条开发任务(content + type: BUG/REQUIREMENT/OPTIMIZATION)。',
|
||||||
|
'仅输出 JSON,格式:',
|
||||||
|
'{"decision":"APPROVE|REJECT","rejectReason":"驳回时必填","note":"通过时附注","reportMarkdown":"markdown摘要","suggestedTasks":[{"content":"...","type":"BUG"}]}',
|
||||||
|
].join('\n');
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class SupportTicketReviewAiService {
|
||||||
|
private readonly logger = new Logger(SupportTicketReviewAiService.name);
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly prisma: PrismaService,
|
||||||
|
private readonly llm: LlmChatClient,
|
||||||
|
private readonly kb: KnowledgeRetrievalService,
|
||||||
|
private readonly devPlan: DevPlanService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async preview(ticketIds: string[]): Promise<{ items: BatchReviewPreviewItem[] }> {
|
||||||
|
if (!ticketIds.length) throw new BadRequestException('请选择工单');
|
||||||
|
const settings = await this.devPlan.getSettingsRaw();
|
||||||
|
if (!settings.reviewAssistantLlmConfigId) {
|
||||||
|
throw new BadRequestException('请先在开发设置中配置审核 AI 助手的语言模型');
|
||||||
|
}
|
||||||
|
const llmCfg = await this.prisma.llmApiConfig.findUnique({
|
||||||
|
where: { id: settings.reviewAssistantLlmConfigId },
|
||||||
|
});
|
||||||
|
if (!llmCfg?.enabled) throw new BadRequestException('审核 AI 助手绑定的语言模型未启用');
|
||||||
|
|
||||||
|
const ids = ticketIds.map(BigInt);
|
||||||
|
const tickets = await this.prisma.commonSupportTicket.findMany({
|
||||||
|
where: { id: { in: ids }, status: 'PENDING_REVIEW' },
|
||||||
|
});
|
||||||
|
if (tickets.length !== ids.length) {
|
||||||
|
throw new BadRequestException('部分工单不存在或不在待评审状态');
|
||||||
|
}
|
||||||
|
|
||||||
|
const items: BatchReviewPreviewItem[] = [];
|
||||||
|
for (const ticket of tickets) {
|
||||||
|
let kbBlock = '';
|
||||||
|
if (settings.reviewAssistantKnowledgeBaseId) {
|
||||||
|
try {
|
||||||
|
kbBlock = await this.kb.buildContext(
|
||||||
|
settings.reviewAssistantKnowledgeBaseId,
|
||||||
|
`${ticket.title}\n${ticket.content ?? ''}`,
|
||||||
|
);
|
||||||
|
} catch (e) {
|
||||||
|
this.logger.warn(`review kb failed: ${String(e)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const userPrompt = [
|
||||||
|
`工单号:${ticket.ticketNo}`,
|
||||||
|
`类型:${ticket.ticketType}`,
|
||||||
|
`标题:${ticket.title}`,
|
||||||
|
`内容:${ticket.content ?? '(无)'}`,
|
||||||
|
kbBlock ? `\n知识库片段:\n${kbBlock}` : '',
|
||||||
|
].join('\n');
|
||||||
|
|
||||||
|
const system = settings.reviewAssistantPrompt?.trim() || DEFAULT_REVIEW_PROMPT;
|
||||||
|
const raw = await this.llm.chat({
|
||||||
|
baseUrl: llmCfg.baseUrl,
|
||||||
|
apiKey: llmCfg.apiKey,
|
||||||
|
model: llmCfg.modelName,
|
||||||
|
temperature: 0.2,
|
||||||
|
maxTokens: 2048,
|
||||||
|
messages: [
|
||||||
|
{ role: 'system', content: system },
|
||||||
|
{ role: 'user', content: userPrompt },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const parsed = parseReviewJson(raw, ticket.ticketType);
|
||||||
|
items.push({
|
||||||
|
ticketId: String(ticket.id),
|
||||||
|
ticketNo: ticket.ticketNo,
|
||||||
|
title: ticket.title,
|
||||||
|
decision: parsed.decision,
|
||||||
|
rejectReason: parsed.rejectReason,
|
||||||
|
note: parsed.note,
|
||||||
|
reportMarkdown: parsed.reportMarkdown,
|
||||||
|
suggestedTasks: parsed.suggestedTasks,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return { items };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseReviewJson(
|
||||||
|
raw: string,
|
||||||
|
ticketType: 'BUG' | 'SUGGESTION' | 'OTHER',
|
||||||
|
): {
|
||||||
|
decision: 'APPROVE' | 'REJECT';
|
||||||
|
rejectReason?: string;
|
||||||
|
note?: string;
|
||||||
|
reportMarkdown: string;
|
||||||
|
suggestedTasks: Array<{ content: string; type: 'BUG' | 'REQUIREMENT' | 'OPTIMIZATION' }>;
|
||||||
|
} {
|
||||||
|
const jsonMatch = raw.match(/\{[\s\S]*\}/);
|
||||||
|
const fallbackType = mapSupportTicketTypeToDevPlanTask(ticketType);
|
||||||
|
if (!jsonMatch) {
|
||||||
|
return {
|
||||||
|
decision: 'APPROVE',
|
||||||
|
note: 'AI 未返回结构化结果,请人工确认',
|
||||||
|
reportMarkdown: raw.slice(0, 2000),
|
||||||
|
suggestedTasks: [{ content: '待人工填写任务内容', type: fallbackType }],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const obj = JSON.parse(jsonMatch[0]) as {
|
||||||
|
decision?: string;
|
||||||
|
rejectReason?: string;
|
||||||
|
note?: string;
|
||||||
|
reportMarkdown?: string;
|
||||||
|
suggestedTasks?: Array<{ content?: string; type?: string }>;
|
||||||
|
};
|
||||||
|
const decision = obj.decision === 'REJECT' ? 'REJECT' : 'APPROVE';
|
||||||
|
const suggestedTasks =
|
||||||
|
decision === 'APPROVE'
|
||||||
|
? (obj.suggestedTasks ?? [])
|
||||||
|
.filter((t) => t.content?.trim())
|
||||||
|
.map((t) => ({
|
||||||
|
content: t.content!.trim(),
|
||||||
|
type: (['BUG', 'REQUIREMENT', 'OPTIMIZATION'].includes(String(t.type))
|
||||||
|
? t.type
|
||||||
|
: fallbackType) as 'BUG' | 'REQUIREMENT' | 'OPTIMIZATION',
|
||||||
|
}))
|
||||||
|
: [];
|
||||||
|
if (decision === 'APPROVE' && !suggestedTasks.length) {
|
||||||
|
suggestedTasks.push({ content: '待人工填写任务内容', type: fallbackType });
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
decision,
|
||||||
|
rejectReason: obj.rejectReason?.trim() || undefined,
|
||||||
|
note: obj.note?.trim() || undefined,
|
||||||
|
reportMarkdown: obj.reportMarkdown?.trim() || raw.slice(0, 2000),
|
||||||
|
suggestedTasks,
|
||||||
|
};
|
||||||
|
} catch {
|
||||||
|
return {
|
||||||
|
decision: 'APPROVE',
|
||||||
|
note: 'AI 返回解析失败,请人工确认',
|
||||||
|
reportMarkdown: raw.slice(0, 2000),
|
||||||
|
suggestedTasks: [{ content: '待人工填写任务内容', type: fallbackType }],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -16,18 +16,25 @@ import { HqOperation } from '../../common/hq-operation/hq-operation.decorator';
|
|||||||
import { HqOperationAction } from '../../common/hq-operation/hq-operation.constants';
|
import { HqOperationAction } from '../../common/hq-operation/hq-operation.constants';
|
||||||
import { PrismaService } from '../../common/prisma/prisma.module';
|
import { PrismaService } from '../../common/prisma/prisma.module';
|
||||||
import { SupportTicketService } from '../common/support-ticket.service';
|
import { SupportTicketService } from '../common/support-ticket.service';
|
||||||
|
import { SupportTicketReviewAiService } from '../dev-plan/support-ticket-review-ai.service';
|
||||||
import {
|
import {
|
||||||
CreateSupportTicketDto,
|
CreateSupportTicketDto,
|
||||||
RejectSupportTicketDto,
|
RejectSupportTicketDto,
|
||||||
SupportTicketListQueryDto,
|
SupportTicketListQueryDto,
|
||||||
SupportTicketRemarkDto,
|
SupportTicketRemarkDto,
|
||||||
} from '../common/dto/support-ticket.dto';
|
} from '../common/dto/support-ticket.dto';
|
||||||
|
import {
|
||||||
|
BatchReviewConfirmDto,
|
||||||
|
BatchReviewPreviewDto,
|
||||||
|
ReviewSupportTicketDto,
|
||||||
|
} from '../dev-plan/dto/dev-plan.dto';
|
||||||
|
|
||||||
@Controller('admin/support-tickets')
|
@Controller('admin/support-tickets')
|
||||||
@UseGuards(HqAuthGuard)
|
@UseGuards(HqAuthGuard)
|
||||||
export class AdminSupportTicketsController {
|
export class AdminSupportTicketsController {
|
||||||
constructor(
|
constructor(
|
||||||
private readonly service: SupportTicketService,
|
private readonly service: SupportTicketService,
|
||||||
|
private readonly reviewAi: SupportTicketReviewAiService,
|
||||||
private readonly prisma: PrismaService,
|
private readonly prisma: PrismaService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
@@ -57,11 +64,47 @@ export class AdminSupportTicketsController {
|
|||||||
return this.service.create(body, account);
|
return this.service.create(body, account);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Post('batch-review/preview')
|
||||||
|
@UseGuards(SuperAdminGuard)
|
||||||
|
async batchReviewPreview(@Body() body: BatchReviewPreviewDto) {
|
||||||
|
return this.reviewAi.preview(body.ticketIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('batch-review/confirm')
|
||||||
|
@UseGuards(SuperAdminGuard)
|
||||||
|
@HqOperation({
|
||||||
|
action: HqOperationAction.SUPPORT_TICKET_BATCH_REVIEW,
|
||||||
|
refType: 'SUPPORT_TICKET',
|
||||||
|
includeBody: true,
|
||||||
|
batch: true,
|
||||||
|
})
|
||||||
|
async batchReviewConfirm(@CurrentUser() user: AuthUser, @Body() body: BatchReviewConfirmDto) {
|
||||||
|
const account = await this.resolveHqAccount(user);
|
||||||
|
return this.service.batchReviewConfirm(account, body.items);
|
||||||
|
}
|
||||||
|
|
||||||
@Get(':id')
|
@Get(':id')
|
||||||
detail(@Param('id') id: string) {
|
detail(@Param('id') id: string) {
|
||||||
return this.service.detail(BigInt(id));
|
return this.service.detail(BigInt(id));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Post(':id/review')
|
||||||
|
@UseGuards(SuperAdminGuard)
|
||||||
|
@HqOperation({
|
||||||
|
action: HqOperationAction.SUPPORT_TICKET_REVIEW,
|
||||||
|
refType: 'SUPPORT_TICKET',
|
||||||
|
refIdParam: 'id',
|
||||||
|
includeBody: true,
|
||||||
|
})
|
||||||
|
async review(
|
||||||
|
@CurrentUser() user: AuthUser,
|
||||||
|
@Param('id') id: string,
|
||||||
|
@Body() body: ReviewSupportTicketDto,
|
||||||
|
) {
|
||||||
|
const account = await this.resolveHqAccount(user);
|
||||||
|
return this.service.review(BigInt(id), account, body);
|
||||||
|
}
|
||||||
|
|
||||||
@Post(':id/approve')
|
@Post(':id/approve')
|
||||||
@UseGuards(SuperAdminGuard)
|
@UseGuards(SuperAdminGuard)
|
||||||
@HqOperation({
|
@HqOperation({
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { BadRequestException, Body, Controller, Get, Post, Put, UseGuards } from '@nestjs/common';
|
import { Body, Controller, Get, Post, Put, UseGuards } from '@nestjs/common';
|
||||||
import type { SystemConfigUpdateRequest } from '@dukang/shared-types';
|
import type { SystemConfigUpdateRequest } from '@dukang/shared-types';
|
||||||
import {
|
import {
|
||||||
SYSTEM_CONFIG_GROUP_PERMISSION,
|
SYSTEM_CONFIG_GROUP_PERMISSION,
|
||||||
@@ -18,7 +18,6 @@ import { HqOperation } from '../../common/hq-operation/hq-operation.decorator';
|
|||||||
import { HqOperationAction } from '../../common/hq-operation/hq-operation.constants';
|
import { HqOperationAction } from '../../common/hq-operation/hq-operation.constants';
|
||||||
import { SystemConfigService } from '../../common/system-config/system-config.service';
|
import { SystemConfigService } from '../../common/system-config/system-config.service';
|
||||||
import { WecomAibotService } from '../../integrations/wecom/wecom-aibot.service';
|
import { WecomAibotService } from '../../integrations/wecom/wecom-aibot.service';
|
||||||
import { AlertService } from '../../common/alert/alert.service';
|
|
||||||
|
|
||||||
@Controller('admin/system-config')
|
@Controller('admin/system-config')
|
||||||
@UseGuards(HqAuthGuard, HqPermissionGuard)
|
@UseGuards(HqAuthGuard, HqPermissionGuard)
|
||||||
@@ -27,7 +26,6 @@ export class AdminSystemConfigController {
|
|||||||
private readonly systemConfig: SystemConfigService,
|
private readonly systemConfig: SystemConfigService,
|
||||||
private readonly permissions: HqPermissionsResolver,
|
private readonly permissions: HqPermissionsResolver,
|
||||||
private readonly wecomAibot: WecomAibotService,
|
private readonly wecomAibot: WecomAibotService,
|
||||||
private readonly alert: AlertService,
|
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
@Get()
|
@Get()
|
||||||
@@ -79,22 +77,6 @@ export class AdminSystemConfigController {
|
|||||||
importEnv() {
|
importEnv() {
|
||||||
return this.systemConfig.importFromProcessEnv();
|
return this.systemConfig.importFromProcessEnv();
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 向企微群机器人发送一条测试告警 */
|
|
||||||
@Post('wecom-alert/test')
|
|
||||||
@RequireAnySystemSettings()
|
|
||||||
@HqOperation({
|
|
||||||
action: HqOperationAction.WECOM_ALERT_TEST,
|
|
||||||
refType: 'SYSTEM_CONFIG',
|
|
||||||
batch: true,
|
|
||||||
})
|
|
||||||
async testWecomAlert() {
|
|
||||||
const result = await this.alert.sendTestAlert();
|
|
||||||
if (!result.ok) {
|
|
||||||
throw new BadRequestException(result.message);
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function allowedConfigGroups(permissionKeys: HqPermissionKey[]): string[] | null {
|
function allowedConfigGroups(permissionKeys: HqPermissionKey[]): string[] | null {
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import { Controller, Get, Query, UseGuards } from '@nestjs/common';
|
||||||
|
import { HqAuthGuard } from '../../common/guards/hq-auth.guard';
|
||||||
|
import { AdminWecomBotLogsService } from './admin-wecom-bot-logs.service';
|
||||||
|
import { AdminWecomBotLogsQueryDto } from './dto/admin-query.dto';
|
||||||
|
|
||||||
|
@Controller('admin/logs/wecom-bots')
|
||||||
|
@UseGuards(HqAuthGuard)
|
||||||
|
export class AdminWecomBotLogsController {
|
||||||
|
constructor(private readonly service: AdminWecomBotLogsService) {}
|
||||||
|
|
||||||
|
@Get()
|
||||||
|
list(@Query() query: AdminWecomBotLogsQueryDto) {
|
||||||
|
return this.service.list(query);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { WecomBotAuditService } from '../../integrations/wecom/wecom-bot-audit.service';
|
||||||
|
import type { AdminWecomBotLogsQueryDto } from './dto/admin-query.dto';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class AdminWecomBotLogsService {
|
||||||
|
constructor(private readonly audit: WecomBotAuditService) {}
|
||||||
|
|
||||||
|
list(query: AdminWecomBotLogsQueryDto) {
|
||||||
|
return this.audit.list(query);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,25 +3,30 @@ import {
|
|||||||
Controller,
|
Controller,
|
||||||
Delete,
|
Delete,
|
||||||
Get,
|
Get,
|
||||||
|
NotFoundException,
|
||||||
Param,
|
Param,
|
||||||
Post,
|
Post,
|
||||||
Put,
|
Put,
|
||||||
Query,
|
Query,
|
||||||
UseGuards,
|
UseGuards,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import type { CreateWecomBotRequest, UpdateWecomBotRequest } from '@dukang/shared-types';
|
|
||||||
import { HqAuthGuard } from '../../common/guards/hq-auth.guard';
|
import { HqAuthGuard } from '../../common/guards/hq-auth.guard';
|
||||||
import {
|
import {
|
||||||
HqPermissionGuard,
|
HqPermissionGuard,
|
||||||
RequireHqPermissions,
|
RequireHqPermissions,
|
||||||
} from '../../common/guards/hq-permission.guard';
|
} from '../../common/guards/hq-permission.guard';
|
||||||
|
import { SuperAdminGuard } from '../../common/guards/super-admin.guard';
|
||||||
import { HqOperation } from '../../common/hq-operation/hq-operation.decorator';
|
import { HqOperation } from '../../common/hq-operation/hq-operation.decorator';
|
||||||
import { HqOperationAction } from '../../common/hq-operation/hq-operation.constants';
|
import { HqOperationAction } from '../../common/hq-operation/hq-operation.constants';
|
||||||
import { CurrentUser } from '../../common/decorators/current-user.decorator';
|
import { CurrentUser } from '../../common/decorators/current-user.decorator';
|
||||||
import type { AuthUser } from '../../common/guards/jwt-auth.guard';
|
import type { AuthUser } from '../../common/guards/jwt-auth.guard';
|
||||||
|
import { PrismaService } from '../../common/prisma/prisma.module';
|
||||||
|
import { SupportTicketService } from '../common/support-ticket.service';
|
||||||
import { AdminWecomBotsService } from './admin-wecom-bots.service';
|
import { AdminWecomBotsService } from './admin-wecom-bots.service';
|
||||||
import { AdminLlmConfigsService } from './admin-llm-configs.service';
|
import { AdminLlmConfigsService } from './admin-llm-configs.service';
|
||||||
import { AdminKnowledgeBasesService } from './admin-knowledge-bases.service';
|
import { AdminKnowledgeBasesService } from './admin-knowledge-bases.service';
|
||||||
|
import { RejectSupportTicketDto } from '../common/dto/support-ticket.dto';
|
||||||
|
import { CreateWecomBotDto, UpdateWecomBotDto } from './dto/wecom-bot.dto';
|
||||||
|
|
||||||
@Controller('admin/wecom-bots')
|
@Controller('admin/wecom-bots')
|
||||||
@UseGuards(HqAuthGuard, HqPermissionGuard)
|
@UseGuards(HqAuthGuard, HqPermissionGuard)
|
||||||
@@ -31,6 +36,8 @@ export class AdminWecomBotsController {
|
|||||||
private readonly service: AdminWecomBotsService,
|
private readonly service: AdminWecomBotsService,
|
||||||
private readonly llmConfigs: AdminLlmConfigsService,
|
private readonly llmConfigs: AdminLlmConfigsService,
|
||||||
private readonly knowledgeBases: AdminKnowledgeBasesService,
|
private readonly knowledgeBases: AdminKnowledgeBasesService,
|
||||||
|
private readonly supportTicket: SupportTicketService,
|
||||||
|
private readonly prisma: PrismaService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
@Get()
|
@Get()
|
||||||
@@ -50,6 +57,11 @@ export class AdminWecomBotsController {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Get('runtime')
|
||||||
|
runtime() {
|
||||||
|
return this.service.getRuntime();
|
||||||
|
}
|
||||||
|
|
||||||
@Post('reload')
|
@Post('reload')
|
||||||
@HqOperation({
|
@HqOperation({
|
||||||
action: HqOperationAction.WECOM_BOT_RELOAD,
|
action: HqOperationAction.WECOM_BOT_RELOAD,
|
||||||
@@ -81,7 +93,7 @@ export class AdminWecomBotsController {
|
|||||||
refType: 'WECOM_BOT',
|
refType: 'WECOM_BOT',
|
||||||
includeBody: true,
|
includeBody: true,
|
||||||
})
|
})
|
||||||
create(@Body() body: CreateWecomBotRequest) {
|
create(@Body() body: CreateWecomBotDto) {
|
||||||
return this.service.create(body);
|
return this.service.create(body);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -92,7 +104,7 @@ export class AdminWecomBotsController {
|
|||||||
refIdField: 'id',
|
refIdField: 'id',
|
||||||
includeBody: true,
|
includeBody: true,
|
||||||
})
|
})
|
||||||
update(@Param('id') id: string, @Body() body: UpdateWecomBotRequest) {
|
update(@Param('id') id: string, @Body() body: UpdateWecomBotDto) {
|
||||||
return this.service.update(BigInt(id), body);
|
return this.service.update(BigInt(id), body);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -105,4 +117,53 @@ export class AdminWecomBotsController {
|
|||||||
remove(@Param('id') id: string) {
|
remove(@Param('id') id: string) {
|
||||||
return this.service.remove(BigInt(id));
|
return this.service.remove(BigInt(id));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async resolveHqAccount(user: AuthUser) {
|
||||||
|
const account = await this.prisma.hqAccount.findUnique({
|
||||||
|
where: { id: user.actorId },
|
||||||
|
select: { id: true, name: true },
|
||||||
|
});
|
||||||
|
if (!account) throw new NotFoundException('HQ 账户不存在');
|
||||||
|
return account;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 机器人审批通过工单(修改状态:PENDING_REVIEW → DEVELOPING) */
|
||||||
|
@Post('approve')
|
||||||
|
@UseGuards(SuperAdminGuard)
|
||||||
|
@HqOperation({
|
||||||
|
action: HqOperationAction.SUPPORT_TICKET_APPROVE,
|
||||||
|
refType: 'SUPPORT_TICKET',
|
||||||
|
includeBody: true,
|
||||||
|
})
|
||||||
|
async approve(
|
||||||
|
@CurrentUser() user: AuthUser,
|
||||||
|
@Body() body: { ticketNo: string },
|
||||||
|
) {
|
||||||
|
const account = await this.resolveHqAccount(user);
|
||||||
|
const ticket = await this.prisma.commonSupportTicket.findFirst({
|
||||||
|
where: { ticketNo: { contains: body.ticketNo.trim() } },
|
||||||
|
});
|
||||||
|
if (!ticket) throw new NotFoundException(`未找到工单:${body.ticketNo}`);
|
||||||
|
return this.supportTicket.approve(ticket.id, account);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 机器人驳回工单(修改状态:PENDING_REVIEW → REJECTED) */
|
||||||
|
@Post('reject')
|
||||||
|
@UseGuards(SuperAdminGuard)
|
||||||
|
@HqOperation({
|
||||||
|
action: HqOperationAction.SUPPORT_TICKET_REJECT,
|
||||||
|
refType: 'SUPPORT_TICKET',
|
||||||
|
includeBody: true,
|
||||||
|
})
|
||||||
|
async reject(
|
||||||
|
@CurrentUser() user: AuthUser,
|
||||||
|
@Body() body: { ticketNo: string; reason: string },
|
||||||
|
) {
|
||||||
|
const account = await this.resolveHqAccount(user);
|
||||||
|
const ticket = await this.prisma.commonSupportTicket.findFirst({
|
||||||
|
where: { ticketNo: { contains: body.ticketNo.trim() } },
|
||||||
|
});
|
||||||
|
if (!ticket) throw new NotFoundException(`未找到工单:${body.ticketNo}`);
|
||||||
|
return this.supportTicket.reject(ticket.id, account, { rejectReason: body.reason });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,10 +5,10 @@ import {
|
|||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import {
|
import {
|
||||||
WECOM_BOT_ROLES,
|
WECOM_BOT_ROLES,
|
||||||
|
normalizeWecomBotRole,
|
||||||
parseWecomBotPermissions,
|
parseWecomBotPermissions,
|
||||||
resolveWecomBotPermissions,
|
parseWecomUserIdList,
|
||||||
type CreateWecomBotRequest,
|
WECOM_BOT_ROLE_DEFAULT_PERMISSIONS,
|
||||||
type UpdateWecomBotRequest,
|
|
||||||
type WecomBotDto,
|
type WecomBotDto,
|
||||||
type WecomBotPermission,
|
type WecomBotPermission,
|
||||||
type WecomBotRole,
|
type WecomBotRole,
|
||||||
@@ -16,6 +16,7 @@ import {
|
|||||||
import { PrismaService } from '../../common/prisma/prisma.module';
|
import { PrismaService } from '../../common/prisma/prisma.module';
|
||||||
import { serializeBigInt } from '../../common/decorators/current-user.decorator';
|
import { serializeBigInt } from '../../common/decorators/current-user.decorator';
|
||||||
import { WecomAibotService } from '../../integrations/wecom/wecom-aibot.service';
|
import { WecomAibotService } from '../../integrations/wecom/wecom-aibot.service';
|
||||||
|
import type { CreateWecomBotDto, UpdateWecomBotDto } from './dto/wecom-bot.dto';
|
||||||
|
|
||||||
function isWecomRole(v: string): v is WecomBotRole {
|
function isWecomRole(v: string): v is WecomBotRole {
|
||||||
return (WECOM_BOT_ROLES as readonly string[]).includes(v);
|
return (WECOM_BOT_ROLES as readonly string[]).includes(v);
|
||||||
@@ -30,6 +31,7 @@ type WecomRow = {
|
|||||||
avatarUrl: string | null;
|
avatarUrl: string | null;
|
||||||
welcome: string | null;
|
welcome: string | null;
|
||||||
permissions: string;
|
permissions: string;
|
||||||
|
reviewSuperAdminWecomUserIds: string | null;
|
||||||
aiEnabled: boolean;
|
aiEnabled: boolean;
|
||||||
llmConfigId: bigint | null;
|
llmConfigId: bigint | null;
|
||||||
knowledgeBaseId: bigint | null;
|
knowledgeBaseId: bigint | null;
|
||||||
@@ -81,10 +83,13 @@ export class AdminWecomBotsService {
|
|||||||
total,
|
total,
|
||||||
page,
|
page,
|
||||||
pageSize,
|
pageSize,
|
||||||
runtime: this.wecomAibot.getStatus(),
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
getRuntime() {
|
||||||
|
return this.wecomAibot.getStatus();
|
||||||
|
}
|
||||||
|
|
||||||
async detail(id: bigint) {
|
async detail(id: bigint) {
|
||||||
const row = await this.prisma.wecomBot.findUnique({
|
const row = await this.prisma.wecomBot.findUnique({
|
||||||
where: { id },
|
where: { id },
|
||||||
@@ -97,7 +102,7 @@ export class AdminWecomBotsService {
|
|||||||
return this.toDto(row);
|
return this.toDto(row);
|
||||||
}
|
}
|
||||||
|
|
||||||
async create(dto: CreateWecomBotRequest) {
|
async create(dto: CreateWecomBotDto) {
|
||||||
const name = dto.name?.trim();
|
const name = dto.name?.trim();
|
||||||
const botId = dto.botId?.trim();
|
const botId = dto.botId?.trim();
|
||||||
const secret = dto.secret?.trim();
|
const secret = dto.secret?.trim();
|
||||||
@@ -111,7 +116,11 @@ export class AdminWecomBotsService {
|
|||||||
|
|
||||||
const llmConfigId = await this.resolveLlmId(dto.llmConfigId);
|
const llmConfigId = await this.resolveLlmId(dto.llmConfigId);
|
||||||
const knowledgeBaseId = await this.resolveKbId(dto.knowledgeBaseId);
|
const knowledgeBaseId = await this.resolveKbId(dto.knowledgeBaseId);
|
||||||
const permissions = resolveWecomBotPermissions(dto.role, dto.permissions);
|
const permissions = dto.permissions?.length
|
||||||
|
? parseWecomBotPermissions(dto.permissions)
|
||||||
|
: parseWecomBotPermissions(WECOM_BOT_ROLE_DEFAULT_PERMISSIONS[dto.role]);
|
||||||
|
if (!permissions.length) throw new BadRequestException('请至少选择一项权限');
|
||||||
|
const reviewIds = dto.reviewSuperAdminWecomUserIds ?? [];
|
||||||
const row = await this.prisma.wecomBot.create({
|
const row = await this.prisma.wecomBot.create({
|
||||||
data: {
|
data: {
|
||||||
name,
|
name,
|
||||||
@@ -121,6 +130,7 @@ export class AdminWecomBotsService {
|
|||||||
avatarUrl: dto.avatarUrl?.trim() || null,
|
avatarUrl: dto.avatarUrl?.trim() || null,
|
||||||
welcome: dto.welcome?.trim() || null,
|
welcome: dto.welcome?.trim() || null,
|
||||||
permissions: JSON.stringify(permissions),
|
permissions: JSON.stringify(permissions),
|
||||||
|
reviewSuperAdminWecomUserIds: reviewIds.length ? JSON.stringify(reviewIds) : null,
|
||||||
aiEnabled: dto.aiEnabled === true,
|
aiEnabled: dto.aiEnabled === true,
|
||||||
llmConfigId,
|
llmConfigId,
|
||||||
knowledgeBaseId,
|
knowledgeBaseId,
|
||||||
@@ -136,11 +146,11 @@ export class AdminWecomBotsService {
|
|||||||
return this.toDto(row);
|
return this.toDto(row);
|
||||||
}
|
}
|
||||||
|
|
||||||
async update(id: bigint, dto: UpdateWecomBotRequest) {
|
async update(id: bigint, dto: UpdateWecomBotDto) {
|
||||||
const existing = await this.prisma.wecomBot.findUnique({ where: { id } });
|
const existing = await this.prisma.wecomBot.findUnique({ where: { id } });
|
||||||
if (!existing) throw new NotFoundException('机器人不存在');
|
if (!existing) throw new NotFoundException('机器人不存在');
|
||||||
|
|
||||||
const role = dto.role && isWecomRole(dto.role) ? dto.role : (existing.role as WecomBotRole);
|
const role = dto.role && isWecomRole(dto.role) ? dto.role : normalizeWecomBotRole(existing.role);
|
||||||
if (dto.role && !isWecomRole(dto.role)) throw new BadRequestException('无效角色');
|
if (dto.role && !isWecomRole(dto.role)) throw new BadRequestException('无效角色');
|
||||||
|
|
||||||
let botId = existing.botId;
|
let botId = existing.botId;
|
||||||
@@ -154,18 +164,15 @@ export class AdminWecomBotsService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let permissionsJson = existing.permissions;
|
let permissionsJson = existing.permissions;
|
||||||
if (dto.permissions !== undefined || dto.role !== undefined) {
|
if (dto.permissions !== undefined) {
|
||||||
const permissions =
|
const permissions = parseWecomBotPermissions(dto.permissions);
|
||||||
dto.permissions !== undefined
|
if (!permissions.length) {
|
||||||
? parseWecomBotPermissions(dto.permissions)
|
throw new BadRequestException('请至少选择一项权限');
|
||||||
: resolveWecomBotPermissions(role, existing.permissions);
|
}
|
||||||
const finalPerms =
|
permissionsJson = JSON.stringify(permissions);
|
||||||
dto.permissions !== undefined
|
} else if (dto.role !== undefined && dto.role !== normalizeWecomBotRole(existing.role)) {
|
||||||
? permissions.length
|
// 仅改角色且未传 permissions 时,保持库内已存权限,不自动覆盖
|
||||||
? permissions
|
permissionsJson = existing.permissions;
|
||||||
: resolveWecomBotPermissions(role, null)
|
|
||||||
: resolveWecomBotPermissions(role, existing.permissions);
|
|
||||||
permissionsJson = JSON.stringify(finalPerms);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const secret =
|
const secret =
|
||||||
@@ -176,17 +183,24 @@ export class AdminWecomBotsService {
|
|||||||
const knowledgeBaseId =
|
const knowledgeBaseId =
|
||||||
dto.knowledgeBaseId !== undefined ? await this.resolveKbId(dto.knowledgeBaseId) : undefined;
|
dto.knowledgeBaseId !== undefined ? await this.resolveKbId(dto.knowledgeBaseId) : undefined;
|
||||||
|
|
||||||
|
let reviewIdsJson = existing.reviewSuperAdminWecomUserIds;
|
||||||
|
if (dto.reviewSuperAdminWecomUserIds !== undefined) {
|
||||||
|
const ids = dto.reviewSuperAdminWecomUserIds ?? [];
|
||||||
|
reviewIdsJson = ids.length ? JSON.stringify(ids) : null;
|
||||||
|
}
|
||||||
|
|
||||||
const row = await this.prisma.wecomBot.update({
|
const row = await this.prisma.wecomBot.update({
|
||||||
where: { id },
|
where: { id },
|
||||||
data: {
|
data: {
|
||||||
name: dto.name !== undefined ? dto.name.trim() : undefined,
|
name: dto.name !== undefined ? dto.name.trim() : undefined,
|
||||||
role: dto.role,
|
role: dto.role ? normalizeWecomBotRole(dto.role) : undefined,
|
||||||
botId,
|
botId,
|
||||||
secret,
|
secret,
|
||||||
avatarUrl:
|
avatarUrl:
|
||||||
dto.avatarUrl === undefined ? undefined : dto.avatarUrl?.trim() || null,
|
dto.avatarUrl === undefined ? undefined : dto.avatarUrl?.trim() || null,
|
||||||
welcome: dto.welcome === undefined ? undefined : dto.welcome?.trim() || null,
|
welcome: dto.welcome === undefined ? undefined : dto.welcome?.trim() || null,
|
||||||
permissions: permissionsJson,
|
permissions: permissionsJson,
|
||||||
|
reviewSuperAdminWecomUserIds: reviewIdsJson,
|
||||||
aiEnabled: dto.aiEnabled,
|
aiEnabled: dto.aiEnabled,
|
||||||
llmConfigId,
|
llmConfigId,
|
||||||
knowledgeBaseId,
|
knowledgeBaseId,
|
||||||
@@ -233,8 +247,10 @@ export class AdminWecomBotsService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private toDto(row: WecomRow): WecomBotDto {
|
private toDto(row: WecomRow): WecomBotDto {
|
||||||
const role = (isWecomRole(row.role) ? row.role : 'CUSTOM') as WecomBotRole;
|
const role = normalizeWecomBotRole(row.role);
|
||||||
const permissions = resolveWecomBotPermissions(role, row.permissions) as WecomBotPermission[];
|
const stored = parseWecomBotPermissions(row.permissions) as WecomBotPermission[];
|
||||||
|
const permissions =
|
||||||
|
stored.length > 0 ? stored : ([...WECOM_BOT_ROLE_DEFAULT_PERMISSIONS[role]] as WecomBotPermission[]);
|
||||||
return {
|
return {
|
||||||
id: row.id.toString(),
|
id: row.id.toString(),
|
||||||
name: row.name,
|
name: row.name,
|
||||||
@@ -244,6 +260,7 @@ export class AdminWecomBotsService {
|
|||||||
avatarUrl: row.avatarUrl,
|
avatarUrl: row.avatarUrl,
|
||||||
welcome: row.welcome,
|
welcome: row.welcome,
|
||||||
permissions,
|
permissions,
|
||||||
|
reviewSuperAdminWecomUserIds: parseWecomUserIdList(row.reviewSuperAdminWecomUserIds),
|
||||||
aiEnabled: row.aiEnabled,
|
aiEnabled: row.aiEnabled,
|
||||||
llmConfigId: row.llmConfigId?.toString() ?? null,
|
llmConfigId: row.llmConfigId?.toString() ?? null,
|
||||||
llmConfigName: row.llmConfig?.name ?? null,
|
llmConfigName: row.llmConfig?.name ?? null,
|
||||||
|
|||||||
@@ -0,0 +1,94 @@
|
|||||||
|
import {
|
||||||
|
BadRequestException,
|
||||||
|
Body,
|
||||||
|
Controller,
|
||||||
|
Delete,
|
||||||
|
Get,
|
||||||
|
Param,
|
||||||
|
Post,
|
||||||
|
Put,
|
||||||
|
Query,
|
||||||
|
UseGuards,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import type {
|
||||||
|
CreateWecomMessagePushRequest,
|
||||||
|
UpdateWecomMessagePushRequest,
|
||||||
|
} from '@dukang/shared-types';
|
||||||
|
import { HqAuthGuard } from '../../common/guards/hq-auth.guard';
|
||||||
|
import {
|
||||||
|
HqPermissionGuard,
|
||||||
|
RequireHqPermissions,
|
||||||
|
} from '../../common/guards/hq-permission.guard';
|
||||||
|
import { HqOperation } from '../../common/hq-operation/hq-operation.decorator';
|
||||||
|
import { HqOperationAction } from '../../common/hq-operation/hq-operation.constants';
|
||||||
|
import { AdminWecomMessagePushesService } from './admin-wecom-message-pushes.service';
|
||||||
|
|
||||||
|
@Controller('admin/wecom-message-pushes')
|
||||||
|
@UseGuards(HqAuthGuard, HqPermissionGuard)
|
||||||
|
@RequireHqPermissions('wecom_bots')
|
||||||
|
export class AdminWecomMessagePushesController {
|
||||||
|
constructor(private readonly service: AdminWecomMessagePushesService) {}
|
||||||
|
|
||||||
|
@Get()
|
||||||
|
list(
|
||||||
|
@Query('name') name?: string,
|
||||||
|
@Query('enabled') enabled?: string,
|
||||||
|
@Query('page') page?: string,
|
||||||
|
@Query('pageSize') pageSize?: string,
|
||||||
|
) {
|
||||||
|
return this.service.list({
|
||||||
|
name,
|
||||||
|
enabled,
|
||||||
|
page: page ? Number(page) : undefined,
|
||||||
|
pageSize: pageSize ? Number(pageSize) : undefined,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get(':id')
|
||||||
|
detail(@Param('id') id: string) {
|
||||||
|
return this.service.detail(BigInt(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post()
|
||||||
|
@HqOperation({
|
||||||
|
action: HqOperationAction.WECOM_MESSAGE_PUSH_CREATE,
|
||||||
|
refType: 'WECOM_MESSAGE_PUSH',
|
||||||
|
includeBody: true,
|
||||||
|
})
|
||||||
|
create(@Body() body: CreateWecomMessagePushRequest) {
|
||||||
|
return this.service.create(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Put(':id')
|
||||||
|
@HqOperation({
|
||||||
|
action: HqOperationAction.WECOM_MESSAGE_PUSH_UPDATE,
|
||||||
|
refType: 'WECOM_MESSAGE_PUSH',
|
||||||
|
refIdField: 'id',
|
||||||
|
includeBody: true,
|
||||||
|
})
|
||||||
|
update(@Param('id') id: string, @Body() body: UpdateWecomMessagePushRequest) {
|
||||||
|
return this.service.update(BigInt(id), body);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Delete(':id')
|
||||||
|
@HqOperation({
|
||||||
|
action: HqOperationAction.WECOM_MESSAGE_PUSH_DELETE,
|
||||||
|
refType: 'WECOM_MESSAGE_PUSH',
|
||||||
|
refIdField: 'id',
|
||||||
|
})
|
||||||
|
remove(@Param('id') id: string) {
|
||||||
|
return this.service.remove(BigInt(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post(':id/test')
|
||||||
|
@HqOperation({
|
||||||
|
action: HqOperationAction.WECOM_MESSAGE_PUSH_TEST,
|
||||||
|
refType: 'WECOM_MESSAGE_PUSH',
|
||||||
|
refIdField: 'id',
|
||||||
|
})
|
||||||
|
async test(@Param('id') id: string) {
|
||||||
|
const result = await this.service.test(BigInt(id));
|
||||||
|
if (!result.ok) throw new BadRequestException(result.message);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
import {
|
||||||
|
BadRequestException,
|
||||||
|
Injectable,
|
||||||
|
NotFoundException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import type {
|
||||||
|
CreateWecomMessagePushRequest,
|
||||||
|
UpdateWecomMessagePushRequest,
|
||||||
|
WecomMessagePushDto,
|
||||||
|
} from '@dukang/shared-types';
|
||||||
|
import { PrismaService } from '../../common/prisma/prisma.module';
|
||||||
|
import { serializeBigInt } from '../../common/decorators/current-user.decorator';
|
||||||
|
import { WecomMessagePushService } from '../../integrations/wecom/wecom-message-push.service';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class AdminWecomMessagePushesService {
|
||||||
|
constructor(
|
||||||
|
private readonly prisma: PrismaService,
|
||||||
|
private readonly pushService: WecomMessagePushService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async list(query: { name?: string; enabled?: string; page?: number; pageSize?: number }) {
|
||||||
|
const page = query.page ?? 1;
|
||||||
|
const pageSize = query.pageSize ?? 20;
|
||||||
|
const where: { name?: { contains: string }; enabled?: boolean } = {};
|
||||||
|
if (query.name?.trim()) where.name = { contains: query.name.trim() };
|
||||||
|
if (query.enabled === 'true' || query.enabled === 'false') {
|
||||||
|
where.enabled = query.enabled === 'true';
|
||||||
|
}
|
||||||
|
|
||||||
|
const [items, total] = await Promise.all([
|
||||||
|
this.prisma.wecomMessagePush.findMany({
|
||||||
|
where,
|
||||||
|
orderBy: [{ sortOrder: 'asc' }, { id: 'asc' }],
|
||||||
|
skip: (page - 1) * pageSize,
|
||||||
|
take: pageSize,
|
||||||
|
}),
|
||||||
|
this.prisma.wecomMessagePush.count({ where }),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return serializeBigInt({
|
||||||
|
items: items.map((row) => this.pushService.toDto(row)),
|
||||||
|
total,
|
||||||
|
page,
|
||||||
|
pageSize,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async detail(id: bigint): Promise<WecomMessagePushDto> {
|
||||||
|
const row = await this.prisma.wecomMessagePush.findUnique({ where: { id } });
|
||||||
|
if (!row) throw new NotFoundException('消息推送不存在');
|
||||||
|
return this.pushService.toDto(row);
|
||||||
|
}
|
||||||
|
|
||||||
|
async create(dto: CreateWecomMessagePushRequest) {
|
||||||
|
const name = dto.name?.trim();
|
||||||
|
const webhookUrl = dto.webhookUrl?.trim();
|
||||||
|
if (!name) throw new BadRequestException('请填写名称');
|
||||||
|
if (!webhookUrl) throw new BadRequestException('请填写 Webhook URL');
|
||||||
|
|
||||||
|
const pushConditions = this.pushService.validatePushConditions(dto.pushConditions);
|
||||||
|
const row = await this.prisma.wecomMessagePush.create({
|
||||||
|
data: {
|
||||||
|
name,
|
||||||
|
avatarUrl: dto.avatarUrl?.trim() || null,
|
||||||
|
webhookUrl,
|
||||||
|
enabled: dto.enabled !== false,
|
||||||
|
mentionWecomUserId: dto.mentionWecomUserId?.trim() || null,
|
||||||
|
pushConditions: JSON.stringify(pushConditions),
|
||||||
|
sortOrder: dto.sortOrder ?? 0,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return this.pushService.toDto(row);
|
||||||
|
}
|
||||||
|
|
||||||
|
async update(id: bigint, dto: UpdateWecomMessagePushRequest) {
|
||||||
|
const existing = await this.prisma.wecomMessagePush.findUnique({ where: { id } });
|
||||||
|
if (!existing) throw new NotFoundException('消息推送不存在');
|
||||||
|
|
||||||
|
let pushConditionsJson = existing.pushConditions;
|
||||||
|
if (dto.pushConditions !== undefined) {
|
||||||
|
const parsed = this.pushService.validatePushConditions(dto.pushConditions);
|
||||||
|
pushConditionsJson = JSON.stringify(parsed);
|
||||||
|
}
|
||||||
|
|
||||||
|
const row = await this.prisma.wecomMessagePush.update({
|
||||||
|
where: { id },
|
||||||
|
data: {
|
||||||
|
name: dto.name !== undefined ? dto.name.trim() : undefined,
|
||||||
|
avatarUrl:
|
||||||
|
dto.avatarUrl === undefined ? undefined : dto.avatarUrl?.trim() || null,
|
||||||
|
webhookUrl: dto.webhookUrl !== undefined ? dto.webhookUrl.trim() : undefined,
|
||||||
|
enabled: dto.enabled,
|
||||||
|
mentionWecomUserId:
|
||||||
|
dto.mentionWecomUserId === undefined
|
||||||
|
? undefined
|
||||||
|
: dto.mentionWecomUserId?.trim() || null,
|
||||||
|
pushConditions: pushConditionsJson,
|
||||||
|
sortOrder: dto.sortOrder,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return this.pushService.toDto(row);
|
||||||
|
}
|
||||||
|
|
||||||
|
async remove(id: bigint) {
|
||||||
|
const existing = await this.prisma.wecomMessagePush.findUnique({ where: { id } });
|
||||||
|
if (!existing) throw new NotFoundException('消息推送不存在');
|
||||||
|
await this.prisma.wecomMessagePush.delete({ where: { id } });
|
||||||
|
return { ok: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
test(id: bigint) {
|
||||||
|
return this.pushService.sendTest(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -524,3 +524,29 @@ export class AdminWechatBindingsQueryDto extends PaginationQueryDto {
|
|||||||
@IsString()
|
@IsString()
|
||||||
openId?: string;
|
openId?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export class AdminWecomBotLogsQueryDto extends PaginationQueryDto {
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
botId?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
wecomUserId?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
action?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
success?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
from?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
to?: string;
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,86 @@
|
|||||||
|
import {
|
||||||
|
IsArray,
|
||||||
|
IsBoolean,
|
||||||
|
IsIn,
|
||||||
|
IsInt,
|
||||||
|
IsOptional,
|
||||||
|
IsString,
|
||||||
|
MinLength,
|
||||||
|
} from 'class-validator';
|
||||||
|
import { WECOM_BOT_PERMISSIONS, WECOM_BOT_ROLES } from '@dukang/shared-types';
|
||||||
|
|
||||||
|
/** 确保 ValidationPipe whitelist 不会剥掉 permissions 等字段 */
|
||||||
|
export class UpdateWecomBotDto {
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MinLength(1)
|
||||||
|
name?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsIn(WECOM_BOT_ROLES as unknown as string[])
|
||||||
|
role?: (typeof WECOM_BOT_ROLES)[number];
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
botId?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
secret?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
avatarUrl?: string | null;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
welcome?: string | null;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsArray()
|
||||||
|
@IsString({ each: true })
|
||||||
|
@IsIn(WECOM_BOT_PERMISSIONS as unknown as string[], { each: true })
|
||||||
|
permissions?: string[];
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsArray()
|
||||||
|
@IsString({ each: true })
|
||||||
|
reviewSuperAdminWecomUserIds?: string[];
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsBoolean()
|
||||||
|
aiEnabled?: boolean;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
llmConfigId?: string | null;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
knowledgeBaseId?: string | null;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsBoolean()
|
||||||
|
enabled?: boolean;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsInt()
|
||||||
|
sortOrder?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class CreateWecomBotDto extends UpdateWecomBotDto {
|
||||||
|
@IsString()
|
||||||
|
@MinLength(1)
|
||||||
|
name!: string;
|
||||||
|
|
||||||
|
@IsIn(WECOM_BOT_ROLES as unknown as string[])
|
||||||
|
role!: (typeof WECOM_BOT_ROLES)[number];
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@MinLength(1)
|
||||||
|
botId!: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@MinLength(1)
|
||||||
|
secret!: string;
|
||||||
|
}
|
||||||
@@ -67,16 +67,22 @@ import { AdminDeployService } from './admin-deploy.service';
|
|||||||
import { AdminSystemConfigController } from './admin-system-config.controller';
|
import { AdminSystemConfigController } from './admin-system-config.controller';
|
||||||
import { AdminWecomBotsController } from './admin-wecom-bots.controller';
|
import { AdminWecomBotsController } from './admin-wecom-bots.controller';
|
||||||
import { AdminWecomBotsService } from './admin-wecom-bots.service';
|
import { AdminWecomBotsService } from './admin-wecom-bots.service';
|
||||||
|
import { AdminWecomMessagePushesController } from './admin-wecom-message-pushes.controller';
|
||||||
|
import { AdminWecomMessagePushesService } from './admin-wecom-message-pushes.service';
|
||||||
|
import { AdminWecomBotLogsController } from './admin-wecom-bot-logs.controller';
|
||||||
|
import { AdminWecomBotLogsService } from './admin-wecom-bot-logs.service';
|
||||||
import { AdminLlmConfigsController } from './admin-llm-configs.controller';
|
import { AdminLlmConfigsController } from './admin-llm-configs.controller';
|
||||||
import { AdminLlmConfigsService } from './admin-llm-configs.service';
|
import { AdminLlmConfigsService } from './admin-llm-configs.service';
|
||||||
import { AdminKnowledgeBasesController } from './admin-knowledge-bases.controller';
|
import { AdminKnowledgeBasesController } from './admin-knowledge-bases.controller';
|
||||||
import { AdminKnowledgeBasesService } from './admin-knowledge-bases.service';
|
import { AdminKnowledgeBasesService } from './admin-knowledge-bases.service';
|
||||||
|
import { DevPlanModule } from '../dev-plan/dev-plan.module';
|
||||||
|
import { AdminDevPlanController } from '../dev-plan/admin-dev-plan.controller';
|
||||||
import { AdminFulfillmentProvidersController } from './admin-fulfillment-providers.controller';
|
import { AdminFulfillmentProvidersController } from './admin-fulfillment-providers.controller';
|
||||||
import { AdminDomainEventsController } from './admin-domain-events.controller';
|
import { AdminDomainEventsController } from './admin-domain-events.controller';
|
||||||
import { AdminDomainEventsService } from './admin-domain-events.service';
|
import { AdminDomainEventsService } from './admin-domain-events.service';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [CityScopeModule, IamModule, TradeModule, AnalyticsModule, FulfillmentModule, BenefitModule, CommonModule, IntegrationsModule, WecomModule, LlmModule, RedeemModule, StoreModule],
|
imports: [CityScopeModule, IamModule, TradeModule, AnalyticsModule, FulfillmentModule, BenefitModule, CommonModule, IntegrationsModule, WecomModule, LlmModule, RedeemModule, StoreModule, DevPlanModule],
|
||||||
controllers: [
|
controllers: [
|
||||||
AdminDashboardController,
|
AdminDashboardController,
|
||||||
AdminDeployController,
|
AdminDeployController,
|
||||||
@@ -116,8 +122,11 @@ import { AdminDomainEventsService } from './admin-domain-events.service';
|
|||||||
AdminHqPermissionsController,
|
AdminHqPermissionsController,
|
||||||
AdminSystemConfigController,
|
AdminSystemConfigController,
|
||||||
AdminWecomBotsController,
|
AdminWecomBotsController,
|
||||||
|
AdminWecomMessagePushesController,
|
||||||
|
AdminWecomBotLogsController,
|
||||||
AdminLlmConfigsController,
|
AdminLlmConfigsController,
|
||||||
AdminKnowledgeBasesController,
|
AdminKnowledgeBasesController,
|
||||||
|
AdminDevPlanController,
|
||||||
AdminFulfillmentProvidersController,
|
AdminFulfillmentProvidersController,
|
||||||
],
|
],
|
||||||
providers: [
|
providers: [
|
||||||
@@ -147,6 +156,8 @@ import { AdminDomainEventsService } from './admin-domain-events.service';
|
|||||||
AdminHqPermissionsService,
|
AdminHqPermissionsService,
|
||||||
AdminDeployService,
|
AdminDeployService,
|
||||||
AdminWecomBotsService,
|
AdminWecomBotsService,
|
||||||
|
AdminWecomMessagePushesService,
|
||||||
|
AdminWecomBotLogsService,
|
||||||
AdminLlmConfigsService,
|
AdminLlmConfigsService,
|
||||||
AdminKnowledgeBasesService,
|
AdminKnowledgeBasesService,
|
||||||
SuperAdminGuard,
|
SuperAdminGuard,
|
||||||
|
|||||||
+66
-1
@@ -32,6 +32,12 @@
|
|||||||
|------|------|------|
|
|------|------|------|
|
||||||
| **3.4.10** | 2026-08-03 | 新增 §3.9 门店套餐;REQ-P-027 / REQ-S-021 / REQ-H-025 / REQ-U-027;开发设计见 [`杜康好客-门店套餐功能开发文档-v3.4.10.md`](./杜康好客-门店套餐功能开发文档-v3.4.10.md) |
|
| **3.4.10** | 2026-08-03 | 新增 §3.9 门店套餐;REQ-P-027 / REQ-S-021 / REQ-H-025 / REQ-U-027;开发设计见 [`杜康好客-门店套餐功能开发文档-v3.4.10.md`](./杜康好客-门店套餐功能开发文档-v3.4.10.md) |
|
||||||
|
|
||||||
|
### 0.3 变更:3.4.11 开发计划
|
||||||
|
|
||||||
|
| 版本 | 日期 | 说明 |
|
||||||
|
|------|------|------|
|
||||||
|
| **3.4.11** | 2026-08-04 | 新增 §3.10 开发计划、§3.11 企微机器人角色与权限重构;REQ-H-026 ~ REQ-H-028;开发设计见 [`杜康好客-开发计划功能开发文档-v3.4.11.md`](./杜康好客-开发计划功能开发文档-v3.4.11.md) |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 1. 背景与目标
|
## 1. 背景与目标
|
||||||
@@ -277,6 +283,64 @@
|
|||||||
- 用户对核销过程中套餐内容有异议 → 可提交客服申诉
|
- 用户对核销过程中套餐内容有异议 → 可提交客服申诉
|
||||||
- 工单/客服类型新增:**套餐异议**(`PACKAGE_DISPUTE`)
|
- 工单/客服类型新增:**套餐异议**(`PACKAGE_DISPUTE`)
|
||||||
|
|
||||||
|
### 3.10 开发计划(引入于 **3.4.11**)
|
||||||
|
|
||||||
|
> 实现设计见 [`杜康好客-开发计划功能开发文档-v3.4.11.md`](./杜康好客-开发计划功能开发文档-v3.4.11.md)
|
||||||
|
|
||||||
|
总部 admin-web 新增一级菜单 **开发计划**,含版本列表、任务列表、开发设置;与 **技术支持** 工单审批联动(通过后创建开发任务)。
|
||||||
|
|
||||||
|
| 子模块 | 要点 |
|
||||||
|
|--------|------|
|
||||||
|
| 版本 | CRUD;多选关联任务;状态流转自动写时间戳/用时 |
|
||||||
|
| 任务 | 全局任务池 CRUD;勾选 → **评审派发** → 任务派发助手 Webhook(@ 开发者 userid) |
|
||||||
|
| 设置 | 任务派发助手(单例);本地审核 AI 助手 |
|
||||||
|
| 技术支持 | 单一「审批」入口;通过须 ≥1 开发任务;批量 AI 预审 → 人工确认 |
|
||||||
|
|
||||||
|
企微接入:开发计划任务派发、运营告警、技术支持工单通知均走 HQ「企微机器人 → 消息推送」(Webhook 多实例 + 条件勾选);对话能力由「智能机器人」WebSocket SDK 承担。
|
||||||
|
|
||||||
|
### 3.11 企微机器人(引入于 **3.4.11**)
|
||||||
|
|
||||||
|
> HQ 菜单:**企微机器人** → 智能机器人 `/wecom/bots`、消息推送 `/wecom/pushes`、智能机器人日志 `/logs/wecom-bots`
|
||||||
|
|
||||||
|
#### 3.11.1 智能机器人(长连接)
|
||||||
|
|
||||||
|
| 角色 | 默认能力 |
|
||||||
|
|------|----------|
|
||||||
|
| **客服助手** | 订单/配送/门店/核销/售后工单只读 + 创建售后工单 + 短信验证查用户 |
|
||||||
|
| **财务助手** | 门店/合伙人/酒厂/物流账单、打款、提现 **只读** |
|
||||||
|
| **运营助手** | 订单/门店/用户/核销/配送 **只读** |
|
||||||
|
| **技术支持** | 技术支持工单只读/创建;**审批**(通过/驳回);开发计划只读 |
|
||||||
|
| **自定义** | HQ 手工勾选模块化权限 |
|
||||||
|
|
||||||
|
**权限模型**:按模块划分(如 `order.read`、`finance.store_bill.read`、`support_ticket.review`);废弃 `api.read.all`、`db.read`。聊天回复仅 Markdown 业务摘要,禁止 JSON/tool 泄露。
|
||||||
|
|
||||||
|
**审批**:仅机器人配置的 **SuperAdmin 企微 userid 白名单** 可执行 `support_ticket.review`;「通过」须自动从工单标题创建 **1 条** 开发任务(类型映射同 HQ 审批)。
|
||||||
|
|
||||||
|
**审计**:每条查询/审批写入 `log_wecom_bot`,Admin 可筛选 bot、userid、action、时间。
|
||||||
|
|
||||||
|
#### 3.11.2 消息推送(Webhook 多实例,v3.4.11)
|
||||||
|
|
||||||
|
| 字段 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| 名称 / 头像 | HQ 列表展示 |
|
||||||
|
| Webhook URL | 企微群机器人 Webhook(**运行时仅读 DB,不读 .env**) |
|
||||||
|
| 启用 | 列表开关 |
|
||||||
|
| @ userid | 可选,markdown `<@userid>` |
|
||||||
|
| 推送条件 | 多选 eventKey,可同时匹配多条推送 |
|
||||||
|
|
||||||
|
**推送条件(eventKey)**:
|
||||||
|
|
||||||
|
| key | 触发场景 |
|
||||||
|
|-----|----------|
|
||||||
|
| `alert.ops` | 售后工单、客户端错误等运营告警 |
|
||||||
|
| `support_ticket.created` | 新建技术支持工单(独立 Markdown,可与 alert.ops 并行) |
|
||||||
|
| `alert.pay` / `alert.redeem` | 支付/核销异常 |
|
||||||
|
| `alert.system` | 5xx、监控、回调 |
|
||||||
|
| `alert.settlement` | 结算 scheduler |
|
||||||
|
| `dev_plan.task_dispatch` | 开发任务评审派发 |
|
||||||
|
|
||||||
|
**迁移**:首次空表时从 `.env` `WECOM_ALERT_WEBHOOK_URL` seed「运营告警」;原 `dev_plan_settings.task_dispatch_*` seed「开发任务派发」。废弃系统设置 `WECOM_ALERT_ENABLED` 与开发设置任务派发 Webhook UI。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 4. 功能需求(REQ 索引)
|
## 4. 功能需求(REQ 索引)
|
||||||
@@ -326,7 +390,7 @@
|
|||||||
| 扩展 | 代下单(Wave 3);管仓只读(Wave 3) |
|
| 扩展 | 代下单(Wave 3);管仓只读(Wave 3) |
|
||||||
| **门店套餐(3.4.10)** | 拓店套餐页;门店详情套餐列表/编辑/提审(REQ-P-027) |
|
| **门店套餐(3.4.10)** | 拓店套餐页;门店详情套餐列表/编辑/提审(REQ-P-027) |
|
||||||
|
|
||||||
### 4.4 总部端(H5)— REQ-H-001 ~ 025
|
### 4.4 总部端(H5)— REQ-H-001 ~ 028
|
||||||
|
|
||||||
| 模块 | 要点 |
|
| 模块 | 要点 |
|
||||||
|------|------|
|
|------|------|
|
||||||
@@ -336,6 +400,7 @@
|
|||||||
| 结算 | 门店+合伙人双 Tab;提现审;白名单配置;**物流对账**(按承运商月结) |
|
| 结算 | 门店+合伙人双 Tab;提现审;白名单配置;**物流对账**(按承运商月结) |
|
||||||
| 增长 | 推广码;问卷;评价;腾讯位置热力图 |
|
| 增长 | 推广码;问卷;评价;腾讯位置热力图 |
|
||||||
| **门店套餐(3.4.10)** | 门店详情「套餐」Tab 直存;套餐变更审核通过/驳回(REQ-H-025) |
|
| **门店套餐(3.4.10)** | 门店详情「套餐」Tab 直存;套餐变更审核通过/驳回(REQ-H-025) |
|
||||||
|
| **开发计划(3.4.11)** | 版本/任务/设置;企微 Agent;任务评审派发;技术支持审批联动(REQ-H-026~028) |
|
||||||
|
|
||||||
### 4.5 端职责矩阵
|
### 4.5 端职责矩阵
|
||||||
|
|
||||||
|
|||||||
+17
-1
@@ -298,10 +298,26 @@ C2~C7、C14 见 §1.3。
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 8. 变更记录
|
## 8. v3.4.11 开发计划(2026-08-04)
|
||||||
|
|
||||||
|
| 项 | 状态 | 说明 |
|
||||||
|
|----|------|------|
|
||||||
|
| Prisma 六表 + shared-types | ✅ | `dev_plan_*` |
|
||||||
|
| DevPlanModule API | ✅ | `/admin/dev-plan/*` |
|
||||||
|
| 技术支持 review + 批量 AI | ✅ | `SupportTicketReviewAiService` |
|
||||||
|
| admin-web 三页面 + 菜单 | ✅ | `/dev-plan/versions|tasks|settings` |
|
||||||
|
| 企微机器人角色/权限重构 | ✅ | 四类角色、模块化权限、`log_wecom_bot`、Capability 门面 |
|
||||||
|
| 企微菜单重组 | ✅ | 智能机器人 `/wecom/bots`、消息推送 `/wecom/pushes`、日志 |
|
||||||
|
| 消息推送多实例 | ✅ | `wecom_message_push`、eventKey 分发、迁移 env/旧派发配置 |
|
||||||
|
| 文档 | ✅ | PRD §3.10 + §3.11 + 开发文档 v3.4.11 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. 变更记录
|
||||||
|
|
||||||
| 日期 | 说明 |
|
| 日期 | 说明 |
|
||||||
|------|------|
|
|------|------|
|
||||||
|
| 2026-08-04 | v3.4.11 开发计划 + 企微智能机器人/消息推送 + 角色权限重构 |
|
||||||
| 2026-07-12 | **P0 已执行**:C2~C7、C14 代码与文档对齐;§1 改为计划+状态表 |
|
| 2026-07-12 | **P0 已执行**:C2~C7、C14 代码与文档对齐;§1 改为计划+状态表 |
|
||||||
| 2026-07-12 | 明确总部端保持 WebAdmin,不改为 H5 |
|
| 2026-07-12 | 明确总部端保持 WebAdmin,不改为 H5 |
|
||||||
| 2026-07-11 | 首版:V3.0 PRD 全量对照当前 monorepo |
|
| 2026-07-11 | 首版:V3.0 PRD 全量对照当前 monorepo |
|
||||||
|
|||||||
@@ -0,0 +1,177 @@
|
|||||||
|
# 杜康好客 · 开发计划功能开发文档 v3.4.11
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
> 对应 PRD §3.10 · REQ-H-026 ~ REQ-H-028
|
||||||
|
|
||||||
|
> 后端模块:`server/dukang-api/src/modules/dev-plan/`
|
||||||
|
|
||||||
|
> 前端:`apps/admin-web` 开发计划三页面 + 技术支持改造
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## 1. 数据模型
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
| 表 | 说明 |
|
||||||
|
|
||||||
|
|----|------|
|
||||||
|
|
||||||
|
| `dev_plan_task` | 任务池;可选 `support_ticket_id` |
|
||||||
|
|
||||||
|
| `dev_plan_version` | 版本;状态与时间戳 |
|
||||||
|
|
||||||
|
| `dev_plan_version_task` | 版本-任务多对多 |
|
||||||
|
|
||||||
|
| `dev_plan_settings` | 单例:审核助手配置(LLM/知识库/提示词) |
|
||||||
|
| `dev_plan_task_dispatch` | 派发审计 |
|
||||||
|
| `wecom_message_push` | 企微群 Webhook 多实例;推送条件 JSON 数组 |
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
枚举与 DTO:`packages/shared-types/src/dev-plan.ts`、`wecom-message-push.ts`
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
**任务派发**:不再存于 `dev_plan_settings`;改由 HQ「消息推送」勾选 `dev_plan.task_dispatch`。
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## 2. Admin API
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
| 路由 | 说明 |
|
||||||
|
|
||||||
|
|------|------|
|
||||||
|
|
||||||
|
| `GET/POST /admin/dev-plan/tasks` | 任务列表 / 创建 |
|
||||||
|
|
||||||
|
| `GET/PUT/DELETE /admin/dev-plan/tasks/:id` | 任务 CRUD |
|
||||||
|
|
||||||
|
| `POST /admin/dev-plan/tasks/dispatch` | 评审派发(无需 devBotId) |
|
||||||
|
|
||||||
|
| `GET/POST /admin/dev-plan/versions` | 版本列表 / 创建 |
|
||||||
|
|
||||||
|
| `GET/PUT/DELETE /admin/dev-plan/versions/:id` | 版本 CRUD |
|
||||||
|
|
||||||
|
| `PUT /admin/dev-plan/versions/:id/tasks` | 替换关联任务 |
|
||||||
|
|
||||||
|
| `GET/PUT /admin/dev-plan/settings` | 开发设置(审核助手) |
|
||||||
|
|
||||||
|
| `GET/POST/PUT/DELETE /admin/wecom-message-pushes` | 消息推送 CRUD |
|
||||||
|
|
||||||
|
| `POST /admin/wecom-message-pushes/:id/test` | 测试消息推送 |
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
权限:`dev_plan`(`packages/shared-types/src/hq-permissions.ts`)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## 3. 技术支持联动
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
| 路由 | 说明 |
|
||||||
|
|
||||||
|
|------|------|
|
||||||
|
|
||||||
|
| `POST /admin/support-tickets/:id/review` | 统一审批(SuperAdmin) |
|
||||||
|
|
||||||
|
| `POST /admin/support-tickets/batch-review/preview` | 批量 AI 预审 |
|
||||||
|
|
||||||
|
| `POST /admin/support-tickets/batch-review/confirm` | 批量确认落库 |
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
审批通过:`decision=APPROVE` + `tasks[]`(≥1)→ 工单 `DEVELOPING` + 创建 `dev_plan_task`。
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## 4. 企微与开发计划分工
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
| 能力 | 入口 | 说明 |
|
||||||
|
|------|------|------|
|
||||||
|
| **消息推送** | Admin `/wecom/pushes` | Webhook 多实例 + 条件勾选;运营告警 / 工单 / 任务派发 |
|
||||||
|
| **智能机器人** | Admin `/wecom/bots` | 四类角色 + 模块化权限;审计 `/logs/wecom-bots` |
|
||||||
|
| **任务评审派发** | 任务列表 · 评审 | 匹配 `dev_plan.task_dispatch` 的推送实例(可多条) |
|
||||||
|
|
||||||
|
DevPlan Agent(HTTP 回调对话)已移除,避免与「企微机器人」重复。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 附录 A · 企微机器人能力矩阵(v3.4.11 重构)
|
||||||
|
|
||||||
|
| 模块 | 权限 | 指令示例 |
|
||||||
|
|------|------|----------|
|
||||||
|
| 订单 | `order.read` | `查订单 DK123` |
|
||||||
|
| 配送 | `delivery.read` | `快递 DK123` |
|
||||||
|
| 门店 | `store.read` | `查门店 杜康` |
|
||||||
|
| 核销 | `redeem.read` | `核销 门店名` |
|
||||||
|
| 售后工单 | `ticket.read` / `ticket.create` | `售后工单 TK…` / `工单 订单号 仅退款` |
|
||||||
|
| 用户 | `user.read` / `user.read_sms` | `用户号 U…` / `查用户 手机号` |
|
||||||
|
| 财务 | `finance.*.read` | `门店账单` / `合伙人账单` / `门店打款` |
|
||||||
|
| 技术支持 | `support_ticket.*` | `提单 BUG …` / `通过 ST…` / `驳回 ST… 理由` |
|
||||||
|
| 开发计划 | `dev_plan.task.read` / `dev_plan.version.read` | `开发任务` / `版本 v3.4.11` |
|
||||||
|
|
||||||
|
**审批**:`support_ticket.review` + 机器人级 `reviewSuperAdminWecomUserIds` 白名单;通过自动建 1 条 dev_plan_task。
|
||||||
|
|
||||||
|
**废弃**:`api.read.all`、`db.read`、`TEAM_ASSISTANT`(迁移为 `OPERATIONS`)。
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## 5. 验收(ACC)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
- [ ] 侧边栏「开发计划」三子页;无 `dev_plan` 权限不可见
|
||||||
|
- [ ] 侧边栏「企微机器人」:智能机器人 / 消息推送 / 日志
|
||||||
|
- [ ] 消息推送 CRUD + 测试;条件勾选生效
|
||||||
|
- [ ] 任务/版本 CRUD;版本多选关联任务
|
||||||
|
- [ ] 版本状态流转写时间戳;用时正确
|
||||||
|
- [ ] 新建技术支持工单 → `support_ticket.created` 推送;`alert.ops` 可并行
|
||||||
|
- [ ] 技术支持:单一审批、通过创建任务、批量 AI 审核
|
||||||
|
- [ ] 任务勾选评审派发(走消息推送 @ userid)
|
||||||
|
- [ ] 系统设置无企微告警开关;运行时不再读 `WECOM_ALERT_WEBHOOK_URL`
|
||||||
|
- [ ] mutation 有 HQ 操作审计
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## 6. 发版
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
1. `pnpm db:generate` + `prisma db push`(`wecom_message_push` 表;删除 `dev_plan_settings.task_dispatch_*`)
|
||||||
|
2. `pnpm prisma:migrate-wecom-push`(发版前,在 drop `task_dispatch_*` 之前)或 API 启动 `ensureDefaults`
|
||||||
|
3. staging 验证消息推送 + 任务派发 + 工单通知
|
||||||
|
4. tag **`v3.4.11`**
|
||||||
|
|
||||||
|
|
||||||
Reference in New Issue
Block a user