Compare commits
11 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f5e523a425 | |||
| 16fa07ceaf | |||
| b21403a47c | |||
| 02d89e6385 | |||
| f9a5b6e81a | |||
| 16c386f165 | |||
| 1c787ed576 | |||
| 4372018c09 | |||
| aca3df4bf2 | |||
| 71f508e02b | |||
| 9d96c73246 |
@@ -47,8 +47,13 @@ import WechatBindingsPage from './pages/WechatBindingsPage';
|
||||
import HqPermissionsPage from './pages/HqPermissionsPage';
|
||||
import SystemSettingsPage from './pages/SystemSettingsPage';
|
||||
import WecomBotsPage from './pages/WecomBotsPage';
|
||||
import WecomMessagePushesPage from './pages/WecomMessagePushesPage';
|
||||
import WecomBotLogsPage from './pages/WecomBotLogsPage';
|
||||
import LlmConfigsPage from './pages/LlmConfigsPage';
|
||||
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 }) {
|
||||
if (!getToken()) return <Navigate to="/login" replace />;
|
||||
@@ -75,9 +80,15 @@ export default function App() {
|
||||
<Route index element={<PromoCodeDetailPage />} />
|
||||
<Route path="users" element={<PromoCodeUsersPage />} />
|
||||
</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="/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="/product-detail-templates" element={<ProductDetailTemplatesPage />} />
|
||||
<Route path="/stores" element={<StoresPage />} />
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Alert, Button, Form, Input, InputNumber, Space, Typography, message } from 'antd';
|
||||
import { Alert, Button, Form, Input, InputNumber, Modal, Space, Typography, message } from 'antd';
|
||||
import { DownOutlined, UpOutlined } from '@ant-design/icons';
|
||||
import type { StorePackageItemDto } from '@dukang/shared-types';
|
||||
import { STORE_PACKAGE_MAX_COUNT } from '@dukang/shared-types';
|
||||
import { request } from '../lib/api';
|
||||
|
||||
import OssUpload from './OssUpload';
|
||||
type PackageRow = StorePackageItemDto;
|
||||
|
||||
function emptyRow(index = 0): PackageRow {
|
||||
return { name: '', price: '0', dishes: '', usableTime: '', otherNotes: '', sortOrder: index };
|
||||
return { name: '', price: '0', dishes: '', usableTime: '', otherNotes: '', imageUrl: '', sortOrder: index };
|
||||
}
|
||||
|
||||
export default function AdminStorePackagesSection({ storeId }: { storeId: string }) {
|
||||
@@ -41,18 +41,33 @@ export default function AdminStorePackagesSection({ storeId }: { storeId: string
|
||||
}
|
||||
|
||||
function removeAt(index: number) {
|
||||
setItems((prev) => prev.filter((_, i) => i !== index).map((item, i) => ({ ...item, sortOrder: i })));
|
||||
setCollapsed((prev) => {
|
||||
const next: Record<number, boolean> = {};
|
||||
Object.entries(prev).forEach(([k, v]) => {
|
||||
const i = Number(k);
|
||||
if (i < index) next[i] = v;
|
||||
else if (i > index) next[i - 1] = v;
|
||||
const run = () => {
|
||||
setItems((prev) => {
|
||||
const next = prev.filter((_, i) => i !== index).map((item, i) => ({ ...item, sortOrder: i }));
|
||||
return next.length ? next : [];
|
||||
});
|
||||
return next;
|
||||
});
|
||||
setCollapsed((prev) => {
|
||||
const next: Record<number, boolean> = {};
|
||||
Object.entries(prev).forEach(([k, v]) => {
|
||||
const i = Number(k);
|
||||
if (i < index) next[i] = v;
|
||||
else if (i > index) next[i - 1] = v;
|
||||
});
|
||||
return next;
|
||||
});
|
||||
};
|
||||
if (items.length === 1) {
|
||||
Modal.confirm({
|
||||
title: '清空门店套餐',
|
||||
content: '删除最后一条套餐后,该门店将无展示套餐,确认继续?',
|
||||
okText: '确认删除',
|
||||
cancelText: '取消',
|
||||
onOk: run,
|
||||
});
|
||||
return;
|
||||
}
|
||||
run();
|
||||
}
|
||||
|
||||
function toggleCollapse(index: number) {
|
||||
setCollapsed((prev) => ({ ...prev, [index]: !prev[index] }));
|
||||
}
|
||||
@@ -65,6 +80,7 @@ export default function AdminStorePackagesSection({ storeId }: { storeId: string
|
||||
dishes: item.dishes.trim(),
|
||||
usableTime: item.usableTime?.trim() || null,
|
||||
otherNotes: item.otherNotes?.trim() || null,
|
||||
imageUrl: item.imageUrl?.trim() || null,
|
||||
sortOrder: index,
|
||||
}))
|
||||
.filter((item) => item.name || item.dishes || item.price);
|
||||
@@ -106,8 +122,21 @@ export default function AdminStorePackagesSection({ storeId }: { storeId: string
|
||||
return <Typography.Text type="secondary">加载套餐中…</Typography.Text>;
|
||||
}
|
||||
|
||||
return (
|
||||
<Form layout="vertical" requiredMark={false}>
|
||||
if (!items.length) {
|
||||
return (
|
||||
<Form layout="vertical" requiredMark={false}>
|
||||
<Alert type="info" showIcon style={{ marginBottom: 16 }} message="该门店暂无套餐,可添加或保存为空。" />
|
||||
<Button onClick={addRow} style={{ marginBottom: 16 }}>
|
||||
添加套餐
|
||||
</Button>
|
||||
<Button type="primary" loading={saving} onClick={() => void save()}>
|
||||
保存套餐
|
||||
</Button>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
|
||||
return ( <Form layout="vertical" requiredMark={false}>
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
@@ -140,12 +169,11 @@ export default function AdminStorePackagesSection({ storeId }: { storeId: string
|
||||
{displayName}
|
||||
</Typography.Title>
|
||||
</Button>
|
||||
{items.length > 1 ? (
|
||||
{items.length > 0 ? (
|
||||
<Button type="link" danger onClick={() => removeAt(index)}>
|
||||
删除
|
||||
</Button>
|
||||
) : null}
|
||||
</Space>
|
||||
) : null} </Space>
|
||||
|
||||
{!isCollapsed ? (
|
||||
<>
|
||||
@@ -186,8 +214,16 @@ export default function AdminStorePackagesSection({ storeId }: { storeId: string
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="其他说明" style={{ marginBottom: 0 }}>
|
||||
<Input
|
||||
<Form.Item label="套餐图片" style={{ marginBottom: 12 }}>
|
||||
<OssUpload
|
||||
bizType="STORE_PACKAGE"
|
||||
mediaType="IMAGE"
|
||||
value={item.imageUrl || undefined}
|
||||
onChange={(url) => updateAt(index, { imageUrl: url })}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="其他说明" style={{ marginBottom: 0 }}> <Input
|
||||
placeholder="不可叠加"
|
||||
value={item.otherNotes || ''}
|
||||
onChange={(e) => updateAt(index, { otherNotes: e.target.value })}
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
LockOutlined,
|
||||
SettingOutlined,
|
||||
AccountBookOutlined,
|
||||
ProjectOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import { hasAnySystemSettingsPermission } from '@dukang/shared-types';
|
||||
import { clearAuth, request, type HqProfile } from '../lib/api';
|
||||
@@ -42,7 +43,15 @@ const MENU_ITEMS: MenuProps['items'] = [
|
||||
},
|
||||
{ key: '/orders', icon: <ShoppingOutlined />, 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: '/knowledge-bases', icon: <FileTextOutlined />, label: '知识库' },
|
||||
{
|
||||
@@ -110,6 +119,16 @@ const MENU_ITEMS: MenuProps['items'] = [
|
||||
{ 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: '/resources', icon: <CloudUploadOutlined />, label: 'OSS 资源库' },
|
||||
{
|
||||
@@ -123,6 +142,7 @@ const MENU_ITEMS: MenuProps['items'] = [
|
||||
{ key: '/logs/hq', label: 'HQ 操作日志' },
|
||||
{ key: '/logs/third-party', label: '第三方日志' },
|
||||
{ key: '/logs/domain-events', label: '领域事件' },
|
||||
{ key: '/logs/wecom-bots', label: '智能机器人日志' },
|
||||
],
|
||||
},
|
||||
{ key: '/hq-permissions', icon: <LockOutlined />, label: '权限分配' },
|
||||
@@ -134,6 +154,9 @@ function menuAllowed(key: string, permissionKeys: string[]): boolean {
|
||||
if (key === 'tickets-group') {
|
||||
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'> = {
|
||||
'/': 'dashboard',
|
||||
'/users': 'users',
|
||||
@@ -143,7 +166,9 @@ function menuAllowed(key: string, permissionKeys: string[]): boolean {
|
||||
'/product-detail-templates': 'products',
|
||||
'/orders': 'orders',
|
||||
'/promo-codes': 'promo_codes',
|
||||
'/wecom-bots': 'wecom_bots',
|
||||
'/wecom/bots': 'wecom_bots',
|
||||
'/wecom/pushes': 'wecom_bots',
|
||||
'wecom-group': 'wecom_bots',
|
||||
'/llm-configs': 'llm_configs',
|
||||
'/knowledge-bases': 'knowledge_bases',
|
||||
'stores-group': 'stores',
|
||||
@@ -175,10 +200,15 @@ function menuAllowed(key: string, permissionKeys: string[]): boolean {
|
||||
'/deliveries/xiaofeixia': 'deliveries',
|
||||
'/tickets': 'tickets',
|
||||
'/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',
|
||||
'/resources': 'resources',
|
||||
'logs-group': 'logs',
|
||||
'/logs/users': 'logs',
|
||||
'/logs/wecom-bots': 'logs',
|
||||
'/logs/stores': 'logs',
|
||||
'/logs/partners': '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,355 @@
|
||||
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_TASK_STATUS_LABELS,
|
||||
DEV_PLAN_TASK_TYPE_LABELS,
|
||||
type DevPlanTaskDto,
|
||||
type DevPlanTaskStatusDto,
|
||||
type DevPlanTaskTypeDto,
|
||||
type DevPlanVersionDto,
|
||||
} 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 [batchEditOpen, setBatchEditOpen] = useState(false);
|
||||
const [batchSaving, setBatchSaving] = useState(false);
|
||||
const [versions, setVersions] = useState<DevPlanVersionDto[]>([]);
|
||||
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 [batchForm] = Form.useForm<{ status?: DevPlanTaskStatusDto; versionId?: string }>();
|
||||
|
||||
useEffect(() => {
|
||||
if (!batchEditOpen) return;
|
||||
request<{ items: DevPlanVersionDto[] }>('/admin/dev-plan/versions?pageSize=100')
|
||||
.then((res) => setVersions(res.items ?? []))
|
||||
.catch(() => setVersions([]));
|
||||
}, [batchEditOpen]);
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
function openBatchEdit() {
|
||||
batchForm.setFieldsValue({ status: undefined, versionId: undefined });
|
||||
setBatchEditOpen(true);
|
||||
}
|
||||
|
||||
async function submitBatchEdit() {
|
||||
const values = await batchForm.validateFields();
|
||||
if (!values.status && !values.versionId) {
|
||||
message.warning('请至少选择状态或关联版本');
|
||||
return;
|
||||
}
|
||||
setBatchSaving(true);
|
||||
try {
|
||||
await request('/admin/dev-plan/tasks/batch-update', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
taskIds: selectedRowKeys,
|
||||
status: values.status || undefined,
|
||||
versionId: values.versionId || undefined,
|
||||
}),
|
||||
});
|
||||
message.success('批量更新成功');
|
||||
setBatchEditOpen(false);
|
||||
setSelectedRowKeys([]);
|
||||
reload();
|
||||
} catch (e) {
|
||||
message.error(e instanceof Error ? e.message : '批量更新失败');
|
||||
} finally {
|
||||
setBatchSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
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={openBatchEdit}>
|
||||
批量编辑
|
||||
</Button>
|
||||
<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>
|
||||
|
||||
<Modal
|
||||
title="批量编辑任务"
|
||||
open={batchEditOpen}
|
||||
onCancel={() => setBatchEditOpen(false)}
|
||||
onOk={() => void submitBatchEdit()}
|
||||
confirmLoading={batchSaving}
|
||||
destroyOnClose
|
||||
>
|
||||
<Typography.Paragraph type="secondary">已选 {selectedRowKeys.length} 条任务</Typography.Paragraph>
|
||||
<Form form={batchForm} layout="vertical">
|
||||
<Form.Item name="status" label="状态(不修改请留空)">
|
||||
<Select allowClear placeholder="不修改" options={STATUS_OPTIONS} />
|
||||
</Form.Item>
|
||||
<Form.Item name="versionId" label="关联版本(追加关联,不修改请留空)">
|
||||
<Select
|
||||
allowClear
|
||||
placeholder="不修改"
|
||||
options={versions.map((v) => ({ value: v.id, label: v.versionNo }))}
|
||||
/>
|
||||
</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>
|
||||
);
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import type { ColumnsType } from 'antd/es/table';
|
||||
import { UploadOutlined } from '@ant-design/icons';
|
||||
import type {
|
||||
KnowledgeBaseDto,
|
||||
KnowledgeDocumentDetailDto,
|
||||
KnowledgeDocumentDto,
|
||||
} from '@dukang/shared-types';
|
||||
import { request } from '../lib/api';
|
||||
@@ -49,6 +50,10 @@ export default function KnowledgeBasesPage() {
|
||||
const [docsLoading, setDocsLoading] = useState(false);
|
||||
const [docModalOpen, setDocModalOpen] = useState(false);
|
||||
const [docSaving, setDocSaving] = useState(false);
|
||||
const [editingDoc, setEditingDoc] = useState<KnowledgeDocumentDto | null>(null);
|
||||
const [editDocModalOpen, setEditDocModalOpen] = useState(false);
|
||||
const [editDocSaving, setEditDocSaving] = useState(false);
|
||||
const [editDocForm] = Form.useForm<DocForm>();
|
||||
|
||||
const { data, loading, page, pageSize, setPage, setPageSize, reload } =
|
||||
useAdminList<KnowledgeBaseDto>(
|
||||
@@ -195,28 +200,52 @@ export default function KnowledgeBasesPage() {
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
width: 80,
|
||||
width: 140,
|
||||
render: (_, row) =>
|
||||
drawerKb?.canEditFull ? (
|
||||
<Popconfirm
|
||||
title="删除文档?"
|
||||
onConfirm={async () => {
|
||||
try {
|
||||
await request(`/admin/knowledge-bases/${drawerKb.id}/documents/${row.id}`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
message.success('已删除');
|
||||
void loadDocs(drawerKb);
|
||||
reload();
|
||||
} catch (e) {
|
||||
message.error(e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Button type="link" size="small" danger>
|
||||
删除
|
||||
<Space>
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
onClick={async () => {
|
||||
if (!drawerKb) return;
|
||||
try {
|
||||
const detail = await request<KnowledgeDocumentDetailDto>(
|
||||
`/admin/knowledge-bases/${drawerKb.id}/documents/${row.id}`,
|
||||
);
|
||||
setEditingDoc(row);
|
||||
editDocForm.setFieldsValue({
|
||||
title: detail.title,
|
||||
contentText: detail.contentText || '',
|
||||
});
|
||||
setEditDocModalOpen(true);
|
||||
} catch (e) {
|
||||
message.error(e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
}}
|
||||
>
|
||||
编辑
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
<Popconfirm
|
||||
title="删除文档?"
|
||||
onConfirm={async () => {
|
||||
try {
|
||||
await request(`/admin/knowledge-bases/${drawerKb.id}/documents/${row.id}`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
message.success('已删除');
|
||||
void loadDocs(drawerKb);
|
||||
reload();
|
||||
} catch (e) {
|
||||
message.error(e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Button type="link" size="small" danger>
|
||||
删除
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
) : null,
|
||||
},
|
||||
];
|
||||
@@ -398,6 +427,50 @@ export default function KnowledgeBasesPage() {
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
title="编辑知识文档"
|
||||
open={editDocModalOpen}
|
||||
onCancel={() => {
|
||||
setEditDocModalOpen(false);
|
||||
setEditingDoc(null);
|
||||
}}
|
||||
confirmLoading={editDocSaving}
|
||||
onOk={async () => {
|
||||
if (!drawerKb || !editingDoc) return;
|
||||
const values = await editDocForm.validateFields();
|
||||
setEditDocSaving(true);
|
||||
try {
|
||||
await request(`/admin/knowledge-bases/${drawerKb.id}/documents/${editingDoc.id}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({
|
||||
title: values.title,
|
||||
contentText: values.contentText || null,
|
||||
}),
|
||||
});
|
||||
message.success('已保存');
|
||||
setEditDocModalOpen(false);
|
||||
setEditingDoc(null);
|
||||
void loadDocs(drawerKb);
|
||||
reload();
|
||||
} catch (e) {
|
||||
message.error(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setEditDocSaving(false);
|
||||
}
|
||||
}}
|
||||
destroyOnClose
|
||||
width={640}
|
||||
>
|
||||
<Form form={editDocForm} layout="vertical">
|
||||
<Form.Item name="title" label="标题" rules={[{ required: true }]}>
|
||||
<Input />
|
||||
</Form.Item>
|
||||
<Form.Item name="contentText" label="正文(可粘贴)">
|
||||
<Input.TextArea rows={8} placeholder="支持 Markdown / 纯文本" />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -168,10 +168,10 @@ function ProductDetailFields({ form, aromaType }: { form: FormInstance; aromaTyp
|
||||
<>
|
||||
<ProductDetailTemplatePicker form={form} aromaType={aromaType} />
|
||||
<Divider />
|
||||
<Typography.Text type="secondary">详情页轮播(CAROUSEL)</Typography.Text>
|
||||
<Typography.Text type="secondary">详情页轮播(CAROUSEL,单张最大 10MB)</Typography.Text>
|
||||
<ImageUrlList name="carouselUrls" label="轮播图" bizType="CAROUSEL" />
|
||||
<Divider />
|
||||
<Typography.Text type="secondary">详情长图(DETAIL,可逐张修改)</Typography.Text>
|
||||
<Typography.Text type="secondary">详情长图(DETAIL,可逐张修改,单张最大 10MB)</Typography.Text>
|
||||
<DetailImageUrlList label="详情图" bizType="DETAIL" />
|
||||
<Divider />
|
||||
<Form.Item name="storyTitle" label="故事标题">
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { useState } from 'react';
|
||||
import { useState } from 'react';
|
||||
import { Button, Form, Input, Table, Typography } from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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(
|
||||
field: SystemConfigFieldMeta,
|
||||
configuredSecrets: string[],
|
||||
@@ -291,8 +263,6 @@ export default function SystemSettingsPage() {
|
||||
meta.configuredSecrets,
|
||||
f.key === 'MOCK_SMS' && mockSmsEnabled ? (
|
||||
<MockSmsCodePanel codes={meta.mockSmsCodes ?? []} loading={loading} />
|
||||
) : f.key === 'WECOM_ALERT_ENABLED' ? (
|
||||
<WecomAlertTestButton />
|
||||
) : 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';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import {
|
||||
WECOM_BOT_PERMISSIONS,
|
||||
WECOM_BOT_PERMISSION_GROUPS,
|
||||
WECOM_BOT_PERMISSION_LABELS,
|
||||
WECOM_BOT_ROLE_DEFAULT_PERMISSIONS,
|
||||
WECOM_BOT_ROLE_LABELS,
|
||||
WECOM_BOT_ROLES,
|
||||
type LlmApiConfigOptionDto,
|
||||
type KnowledgeBaseOptionDto,
|
||||
type WecomAibotRuntimeDto,
|
||||
type WecomBotDto,
|
||||
type WecomBotPermission,
|
||||
type WecomBotRole,
|
||||
@@ -36,17 +37,6 @@ import { fmtTime } from '../lib/constants';
|
||||
import { useAdminList } from '../lib/useAdminList';
|
||||
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 = {
|
||||
name: string;
|
||||
role: WecomBotRole;
|
||||
@@ -55,6 +45,7 @@ type FormValues = {
|
||||
avatarUrl?: string;
|
||||
welcome?: string;
|
||||
permissions: WecomBotPermission[];
|
||||
reviewSuperAdminWecomUserIds?: string;
|
||||
aiEnabled: boolean;
|
||||
llmConfigId?: string | null;
|
||||
knowledgeBaseId?: string | null;
|
||||
@@ -62,18 +53,70 @@ type FormValues = {
|
||||
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() {
|
||||
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<WecomBotDto | null>(null);
|
||||
const [formInitial, setFormInitial] = useState<FormValues | null>(null);
|
||||
const [formReady, setFormReady] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [detail, setDetail] = useState<WecomBotDto | null>(null);
|
||||
const [runtime, setRuntime] = useState<ListRes['runtime']>();
|
||||
const [runtime, setRuntime] = useState<WecomAibotRuntimeDto>();
|
||||
const [llmOptions, setLlmOptions] = useState<LlmApiConfigOptionDto[]>([]);
|
||||
const [kbOptions, setKbOptions] = useState<KnowledgeBaseOptionDto[]>([]);
|
||||
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>(
|
||||
'/admin/wecom-bots',
|
||||
@@ -87,11 +130,13 @@ export default function WecomBotsPage() {
|
||||
[filters],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
// useAdminList returns items; runtime comes from same API — fetch once for banner
|
||||
void request<ListRes>('/admin/wecom-bots?page=1&pageSize=1')
|
||||
.then((res) => setRuntime(res.runtime))
|
||||
const loadRuntime = () =>
|
||||
request<WecomAibotRuntimeDto>('/admin/wecom-bots/runtime')
|
||||
.then(setRuntime)
|
||||
.catch(() => {});
|
||||
|
||||
useEffect(() => {
|
||||
void loadRuntime();
|
||||
}, [data]);
|
||||
|
||||
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() {
|
||||
setEditing(null);
|
||||
form.setFieldsValue({
|
||||
name: '',
|
||||
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,
|
||||
});
|
||||
setFormInitial({ ...CREATE_DEFAULTS });
|
||||
setFormReady(true);
|
||||
setModalOpen(true);
|
||||
}
|
||||
|
||||
function openEdit(row: WecomBotDto) {
|
||||
async function openEdit(row: WecomBotDto) {
|
||||
setEditing(row);
|
||||
form.setFieldsValue({
|
||||
name: row.name,
|
||||
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,
|
||||
});
|
||||
setFormInitial(null);
|
||||
setFormReady(false);
|
||||
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() {
|
||||
const values = await form.validateFields();
|
||||
const permissions = (form.getFieldValue('permissions') ?? values.permissions) as WecomBotPermission[];
|
||||
if (!permissions?.length) {
|
||||
message.error('请至少选择一项权限');
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
const payload = {
|
||||
@@ -157,7 +207,8 @@ export default function WecomBotsPage() {
|
||||
botId: values.botId.trim(),
|
||||
avatarUrl: values.avatarUrl?.trim() || null,
|
||||
welcome: values.welcome?.trim() || null,
|
||||
permissions: values.permissions,
|
||||
permissions,
|
||||
reviewSuperAdminWecomUserIds: parseUserIdLines(values.reviewSuperAdminWecomUserIds),
|
||||
aiEnabled: values.aiEnabled,
|
||||
llmConfigId: values.llmConfigId || null,
|
||||
knowledgeBaseId: values.knowledgeBaseId || null,
|
||||
@@ -165,13 +216,20 @@ export default function WecomBotsPage() {
|
||||
sortOrder: values.sortOrder,
|
||||
};
|
||||
if (editing) {
|
||||
await request(`/admin/wecom-bots/${editing.id}`, {
|
||||
const saved = await request<WecomBotDto>(`/admin/wecom-bots/${editing.id}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({
|
||||
...payload,
|
||||
secret: values.secret?.trim() || undefined,
|
||||
}),
|
||||
});
|
||||
if (!samePermissionSet(permissions, saved.permissions)) {
|
||||
message.warning('权限与保存结果不一致,已用服务端数据刷新表单');
|
||||
setFormInitial(mapDtoToForm(saved));
|
||||
setEditing(saved);
|
||||
reload();
|
||||
return;
|
||||
}
|
||||
message.success('已更新');
|
||||
} else {
|
||||
if (!values.secret?.trim()) {
|
||||
@@ -187,7 +245,7 @@ export default function WecomBotsPage() {
|
||||
});
|
||||
message.success('已创建');
|
||||
}
|
||||
setModalOpen(false);
|
||||
closeModal();
|
||||
reload();
|
||||
} catch (e) {
|
||||
message.error(e instanceof Error ? e.message : '保存失败');
|
||||
@@ -208,10 +266,10 @@ export default function WecomBotsPage() {
|
||||
|
||||
async function reloadConnections() {
|
||||
try {
|
||||
const st = await request<{
|
||||
masterEnabled: boolean;
|
||||
bots: Array<{ id: string; connected: boolean; lastError: string | null }>;
|
||||
}>('/admin/wecom-bots/reload', { method: 'POST', body: '{}' });
|
||||
const st = await request<WecomAibotRuntimeDto>('/admin/wecom-bots/reload', {
|
||||
method: 'POST',
|
||||
body: '{}',
|
||||
});
|
||||
message.success('已重载长连接');
|
||||
setRuntime(st);
|
||||
reload();
|
||||
@@ -287,7 +345,7 @@ export default function WecomBotsPage() {
|
||||
fixed: 'right',
|
||||
render: (_, row) => (
|
||||
<Space>
|
||||
<Button type="link" size="small" onClick={() => openEdit(row)}>
|
||||
<Button type="link" size="small" onClick={() => void openEdit(row)}>
|
||||
编辑
|
||||
</Button>
|
||||
<Button
|
||||
@@ -386,23 +444,39 @@ export default function WecomBotsPage() {
|
||||
<Modal
|
||||
title={editing ? '编辑企微机器人' : '创建企微机器人'}
|
||||
open={modalOpen}
|
||||
onCancel={() => setModalOpen(false)}
|
||||
onCancel={closeModal}
|
||||
onOk={() => void submit()}
|
||||
confirmLoading={saving}
|
||||
width={640}
|
||||
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: '请填写名称' }]}>
|
||||
<Input placeholder="如:客服机器人" maxLength={64} />
|
||||
</Form.Item>
|
||||
<Form.Item name="role" label="角色" rules={[{ required: true }]}>
|
||||
<Select
|
||||
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]]);
|
||||
}}
|
||||
/>
|
||||
>
|
||||
应用当前角色默认权限
|
||||
</Button>
|
||||
</Form.Item>
|
||||
<Form.Item name="avatarUrl" label="头像">
|
||||
<OssUpload bizType="WECOM_BOT_AVATAR" />
|
||||
@@ -420,21 +494,48 @@ export default function WecomBotsPage() {
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="permissions"
|
||||
label="权限"
|
||||
rules={[{ required: true, message: '请至少选择一项权限' }]}
|
||||
label="权限(按模块)"
|
||||
rules={[
|
||||
{
|
||||
validator: (_, v: WecomBotPermission[] | undefined) =>
|
||||
v?.length ? Promise.resolve() : Promise.reject(new Error('请至少选择一项权限')),
|
||||
},
|
||||
]}
|
||||
extra={
|
||||
roleWatch
|
||||
? `角色默认:${WECOM_BOT_ROLE_DEFAULT_PERMISSIONS[roleWatch as WecomBotRole]?.map((p) => WECOM_BOT_PERMISSION_LABELS[p]).join('、') || '无'}`
|
||||
: undefined
|
||||
<>
|
||||
{roleWatch
|
||||
? `角色默认:${WECOM_BOT_ROLE_DEFAULT_PERMISSIONS[roleWatch as WecomBotRole]?.map((p) => WECOM_BOT_PERMISSION_LABELS[p]).join('、') || '无'}`
|
||||
: null}
|
||||
{permissionsWatch?.length ? (
|
||||
<Typography.Text type="secondary"> · 已选 {permissionsWatch.length} 项</Typography.Text>
|
||||
) : null}
|
||||
</>
|
||||
}
|
||||
>
|
||||
<Checkbox.Group
|
||||
options={WECOM_BOT_PERMISSIONS.map((p) => ({
|
||||
value: p,
|
||||
label: WECOM_BOT_PERMISSION_LABELS[p],
|
||||
}))}
|
||||
/>
|
||||
<Checkbox.Group style={{ width: '100%' }}>
|
||||
{WECOM_BOT_PERMISSION_GROUPS.map((group) => (
|
||||
<div key={group.key} style={{ marginBottom: 12 }}>
|
||||
<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>
|
||||
{(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="欢迎语">
|
||||
<Input.TextArea rows={3} placeholder="进入会话时的欢迎语,可空" />
|
||||
</Form.Item>
|
||||
@@ -475,6 +576,9 @@ export default function WecomBotsPage() {
|
||||
</Form.Item>
|
||||
</Space>
|
||||
</Form>
|
||||
) : (
|
||||
<Typography.Text type="secondary">加载中…</Typography.Text>
|
||||
)}
|
||||
</Modal>
|
||||
|
||||
<Drawer title="机器人详情" width={480} open={!!detail} onClose={() => setDetail(null)}>
|
||||
@@ -496,6 +600,11 @@ export default function WecomBotsPage() {
|
||||
<Descriptions.Item label="权限">
|
||||
{detail.permissions.map((p) => WECOM_BOT_PERMISSION_LABELS[p] || p).join('、')}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="审批白名单">
|
||||
{detail.reviewSuperAdminWecomUserIds?.length
|
||||
? detail.reviewSuperAdminWecomUserIds.join('、')
|
||||
: '—'}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="欢迎语">{detail.welcome || '—'}</Descriptions.Item>
|
||||
<Descriptions.Item label="AI 问答">{detail.aiEnabled ? '开' : '关'}</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>
|
||||
);
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { useState } from 'react';
|
||||
import type { PackageFormItem } from '../lib/storePackages';
|
||||
import { STORE_PACKAGE_MAX_COUNT } from '@dukang/shared-types';
|
||||
import { emptyPackage } from '../lib/storePackages';
|
||||
import OssUploadField from './OssUploadField';
|
||||
|
||||
type Props = {
|
||||
items: PackageFormItem[];
|
||||
@@ -129,6 +130,16 @@ export default function StorePackagesForm({ items, onChange, disabled, embedded
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="partner-field">
|
||||
<label>套餐图片</label>
|
||||
<OssUploadField
|
||||
bizType="STORE_PACKAGE"
|
||||
value={item.imageUrl || ''}
|
||||
disabled={disabled}
|
||||
onChange={(url) => updateAt(index, { imageUrl: url })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="partner-field">
|
||||
<label>其他说明</label>
|
||||
<div className="partner-field-input">
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { PartnerMe, PartnerStaffRole } from '@dukang/shared-types';
|
||||
import { reportApiError } from '@dukang/client-logging';
|
||||
import { isOnAppPath, toAppPath } from '@dukang/weixin-sdk';
|
||||
import { showPartnerToast } from './toast';
|
||||
|
||||
@@ -159,6 +160,12 @@ async function rawRequest<T>(
|
||||
if (json.code !== 0) {
|
||||
const err = new Error(json.message || '请求失败') as Error & { status?: number };
|
||||
err.status = json.code === 401 ? 401 : json.code;
|
||||
if (json.code === 400) {
|
||||
reportApiError(
|
||||
{ apiBase, clientApp: CLIENT_APP, getToken: () => localStorage.getItem(ACCESS_TOKEN) },
|
||||
{ message: json.message || '请求失败', status: 400, url: path, category: 'validation_error' },
|
||||
);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
return json.data as T;
|
||||
|
||||
@@ -10,6 +10,7 @@ export function emptyPackage(index = 0): PackageFormItem {
|
||||
dishes: '',
|
||||
usableTime: '',
|
||||
otherNotes: '',
|
||||
imageUrl: '',
|
||||
sortOrder: index,
|
||||
};
|
||||
}
|
||||
@@ -22,9 +23,13 @@ export function normalizePackageFormItems(raw: PackageFormItem[]): PackageFormIt
|
||||
dishes: item.dishes.trim(),
|
||||
usableTime: item.usableTime?.trim() || '',
|
||||
otherNotes: item.otherNotes?.trim() || '',
|
||||
imageUrl: item.imageUrl?.trim() || '',
|
||||
sortOrder: index,
|
||||
}))
|
||||
.filter((item) => item.name || item.price || item.dishes || item.usableTime || item.otherNotes);
|
||||
.filter(
|
||||
(item) =>
|
||||
item.name || item.price || item.dishes || item.usableTime || item.otherNotes || item.imageUrl,
|
||||
);
|
||||
}
|
||||
|
||||
export function validatePackageFormItems(items: PackageFormItem[]): string | null {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useState } from 'react';
|
||||
import { useRef, useState } from 'react';
|
||||
import { STORE_PACKAGE_MAX_COUNT } from '@dukang/shared-types';
|
||||
import { emptyPackage, type PackageFormItem } from '../lib/storePackages';
|
||||
import { uploadFileToOss } from '../lib/upload';
|
||||
|
||||
type Props = {
|
||||
items: PackageFormItem[];
|
||||
@@ -10,6 +11,19 @@ type Props = {
|
||||
|
||||
export default function ShopPackagesForm({ items, onChange, disabled }: Props) {
|
||||
const [collapsed, setCollapsed] = useState<Record<number, boolean>>({});
|
||||
const [uploadingIndex, setUploadingIndex] = useState<number | null>(null);
|
||||
const fileRefs = useRef<Record<number, HTMLInputElement | null>>({});
|
||||
|
||||
async function pickPackageImage(index: number, file?: File | null) {
|
||||
if (!file || disabled) return;
|
||||
setUploadingIndex(index);
|
||||
try {
|
||||
const result = await uploadFileToOss(file, 'STORE_PACKAGE');
|
||||
updateAt(index, { imageUrl: result.url });
|
||||
} finally {
|
||||
setUploadingIndex(null);
|
||||
}
|
||||
}
|
||||
|
||||
function updateAt(index: number, patch: Partial<PackageFormItem>) {
|
||||
onChange(items.map((item, i) => (i === index ? { ...item, ...patch } : item)));
|
||||
@@ -116,6 +130,36 @@ export default function ShopPackagesForm({ items, onChange, disabled }: Props) {
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="shop-packages-field">
|
||||
<span className="shop-packages-label">套餐图片</span>
|
||||
{item.imageUrl ? (
|
||||
<img
|
||||
src={item.imageUrl}
|
||||
alt=""
|
||||
style={{ width: '100%', maxHeight: 160, objectFit: 'cover', borderRadius: 8, marginBottom: 8 }}
|
||||
/>
|
||||
) : null}
|
||||
<input
|
||||
ref={(el) => {
|
||||
fileRefs.current[index] = el;
|
||||
}}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
hidden
|
||||
disabled={disabled}
|
||||
onChange={(e) => void pickPackageImage(index, e.target.files?.[0])}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
className="shop-packages-add"
|
||||
style={{ marginTop: 0 }}
|
||||
disabled={disabled || uploadingIndex === index}
|
||||
onClick={() => fileRefs.current[index]?.click()}
|
||||
>
|
||||
{uploadingIndex === index ? '上传中…' : item.imageUrl ? '更换图片' : '上传图片'}
|
||||
</button>
|
||||
</label>
|
||||
|
||||
<label className="shop-packages-field">
|
||||
<span className="shop-packages-label">其他说明</span>
|
||||
<input
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { reportApiError } from '@dukang/client-logging';
|
||||
|
||||
export const apiBase = '/api/v1';
|
||||
const CLIENT_APP = 'SHOP_H5';
|
||||
|
||||
@@ -213,6 +215,12 @@ async function rawRequest<T>(
|
||||
if (json.code !== 0) {
|
||||
const err = new Error(json.message || '请求失败') as Error & { status?: number };
|
||||
err.status = res.status >= 500 ? res.status : json.code;
|
||||
if (json.code === 400) {
|
||||
reportApiError(
|
||||
{ apiBase, clientApp: CLIENT_APP, getToken: () => localStorage.getItem(ACCESS_TOKEN) },
|
||||
{ message: json.message || '请求失败', status: 400, url: path, category: 'validation_error' },
|
||||
);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
return json.data as T;
|
||||
|
||||
@@ -10,6 +10,7 @@ export function emptyPackage(index = 0): PackageFormItem {
|
||||
dishes: '',
|
||||
usableTime: '',
|
||||
otherNotes: '',
|
||||
imageUrl: '',
|
||||
sortOrder: index,
|
||||
};
|
||||
}
|
||||
@@ -22,9 +23,13 @@ export function normalizePackageFormItems(raw: PackageFormItem[]): PackageFormIt
|
||||
dishes: item.dishes.trim(),
|
||||
usableTime: item.usableTime?.trim() || '',
|
||||
otherNotes: item.otherNotes?.trim() || '',
|
||||
imageUrl: item.imageUrl?.trim() || '',
|
||||
sortOrder: index,
|
||||
}))
|
||||
.filter((item) => item.name || item.price || item.dishes || item.usableTime || item.otherNotes);
|
||||
.filter(
|
||||
(item) =>
|
||||
item.name || item.price || item.dishes || item.usableTime || item.otherNotes || item.imageUrl,
|
||||
);
|
||||
}
|
||||
|
||||
export function validatePackageFormItems(items: PackageFormItem[]): string | null {
|
||||
|
||||
@@ -15,7 +15,7 @@ export type RegisteredResource = {
|
||||
url: string;
|
||||
};
|
||||
|
||||
async function uploadFileToOss(file: File, bizType: string): Promise<UploadFileResult> {
|
||||
export async function uploadFileToOss(file: File, bizType: string): Promise<UploadFileResult> {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
formData.append('bizType', bizType);
|
||||
|
||||
@@ -80,7 +80,6 @@ export default function WithdrawPage() {
|
||||
const canApply =
|
||||
!!summary?.isPrimary &&
|
||||
summary.availableAmount > 0 &&
|
||||
!summary.hasPendingRequest &&
|
||||
summary.hasBankAccount &&
|
||||
!submitting;
|
||||
|
||||
@@ -126,7 +125,6 @@ export default function WithdrawPage() {
|
||||
info
|
||||
</span>
|
||||
单日上限 ¥{formatMoney(summary?.dailyLimit ?? 5000)}
|
||||
{summary?.hasPendingRequest ? ' · 已有待审核申请' : ''}
|
||||
{!summary?.hasBankAccount ? ' · 请先完善收款账户' : ''}
|
||||
</p>
|
||||
</section>
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { reportApiError } from '@dukang/client-logging';
|
||||
|
||||
export const BRAND = {
|
||||
red: '#A02D30',
|
||||
yellow: '#FFC107',
|
||||
@@ -83,6 +85,12 @@ async function rawRequest<T>(
|
||||
if (json.code !== 0) {
|
||||
const err = new Error(json.message || '请求失败') as Error & { status?: number };
|
||||
err.status = json.code;
|
||||
if (json.code === 400) {
|
||||
reportApiError(
|
||||
{ apiBase, clientApp: CLIENT_APP, getToken: () => localStorage.getItem(ACCESS_TOKEN) },
|
||||
{ message: json.message || '请求失败', status: 400, url: path, category: 'validation_error' },
|
||||
);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
return json.data as T;
|
||||
|
||||
@@ -1,19 +1,33 @@
|
||||
import { useState } from 'react';
|
||||
import { View, Image, Swiper, SwiperItem } from '@tarojs/components';
|
||||
import Taro from '@tarojs/taro';
|
||||
|
||||
type ProductCarouselProps = {
|
||||
images: string[];
|
||||
alt: string;
|
||||
variant?: 'home' | 'detail' | 'store';
|
||||
previewable?: boolean;
|
||||
};
|
||||
|
||||
/** 商品/门店轮播(对齐 h5 ProductCarousel 三变体) */
|
||||
export default function ProductCarousel({ images, alt, variant = 'detail' }: ProductCarouselProps) {
|
||||
export default function ProductCarousel({
|
||||
images,
|
||||
alt,
|
||||
variant = 'detail',
|
||||
previewable = false,
|
||||
}: ProductCarouselProps) {
|
||||
const slides = images.length > 0 ? images : [''];
|
||||
const [activeIndex, setActiveIndex] = useState(0);
|
||||
const prefix =
|
||||
variant === 'store' ? 'store-detail-carousel' : variant === 'home' ? 'home-carousel' : 'detail-carousel';
|
||||
|
||||
function previewAt(index: number) {
|
||||
const urls = slides.filter(Boolean);
|
||||
if (!urls.length) return;
|
||||
const current = slides[index] || urls[0];
|
||||
Taro.previewImage({ current, urls }).catch(() => undefined);
|
||||
}
|
||||
|
||||
return (
|
||||
<View className={`${prefix}-wrap`}>
|
||||
<Swiper
|
||||
@@ -24,7 +38,13 @@ export default function ProductCarousel({ images, alt, variant = 'detail' }: Pro
|
||||
{slides.map((src, index) => (
|
||||
<SwiperItem key={`${src}-${index}`} className={`${prefix}-item`}>
|
||||
{src ? (
|
||||
<Image className={`${prefix}-image`} src={src} mode="aspectFill" alt={alt} />
|
||||
<Image
|
||||
className={`${prefix}-image`}
|
||||
src={src}
|
||||
mode="aspectFill"
|
||||
alt={alt}
|
||||
onClick={previewable ? () => previewAt(index) : undefined}
|
||||
/>
|
||||
) : (
|
||||
<View className={`${prefix}-placeholder`} />
|
||||
)}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { ClientApp } from '@dukang/shared-types';
|
||||
import { forceReloadAfterAccountMerge } from './auth-nav';
|
||||
import { resetStoresSessionBootstrap } from './stores-session';
|
||||
import { resetHomeCatalogBootstrap } from './home-catalog-session';
|
||||
import { reportClientValidationError } from './client-error';
|
||||
|
||||
function resolveApiBase(): string {
|
||||
const origin =
|
||||
@@ -113,6 +114,12 @@ export async function request<T = unknown>(path: string, options: ReqOptions = {
|
||||
throw new Error('接口不可达,请确认 API 服务已启动');
|
||||
}
|
||||
if (status >= 400 || body.code !== 0) {
|
||||
if (status === 400 || body?.code === 400) {
|
||||
reportClientValidationError({
|
||||
message: body?.message || `请求失败(${status})`,
|
||||
apiPath: path,
|
||||
});
|
||||
}
|
||||
throw new Error(body?.message || `请求失败(${status})`);
|
||||
}
|
||||
return (res.data as { data: T }).data;
|
||||
|
||||
@@ -6,6 +6,7 @@ export type ClientErrorCategory =
|
||||
| 'js_error'
|
||||
| 'unhandled_rejection'
|
||||
| 'api_error'
|
||||
| 'validation_error'
|
||||
| 'network'
|
||||
| 'render'
|
||||
| 'bridge'
|
||||
@@ -57,6 +58,17 @@ export function reportClientError(payload: ClientErrorPayload): void {
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
/** 上报 API 400 验证错误(失败静默) */
|
||||
export function reportClientValidationError(input: { message: string; apiPath?: string }): void {
|
||||
if (input.apiPath?.includes('/common/client-errors')) return;
|
||||
reportClientError({
|
||||
level: 'warn',
|
||||
category: 'validation_error',
|
||||
message: input.message,
|
||||
extra: { status: 400, url: input.apiPath },
|
||||
});
|
||||
}
|
||||
|
||||
let installed = false;
|
||||
|
||||
/** 安装小程序/H5 全局未捕获错误钩子(幂等) */
|
||||
|
||||
@@ -34,6 +34,7 @@ type StorePackage = {
|
||||
dishes: string;
|
||||
usableTime?: string | null;
|
||||
otherNotes?: string | null;
|
||||
imageUrl?: string | null;
|
||||
sortOrder?: number;
|
||||
};
|
||||
|
||||
@@ -315,11 +316,7 @@ export default function StoreDetailPage() {
|
||||
}
|
||||
|
||||
const envPhotos = envPhotoUrls(store);
|
||||
const images = uniqueUrls([
|
||||
store.coverUrl,
|
||||
...(store.carouselUrls || []),
|
||||
...envPhotos,
|
||||
]);
|
||||
const heroImages = uniqueUrls([store.coverUrl, ...(store.carouselUrls || [])]);
|
||||
|
||||
const intro = store.intro?.trim() || '';
|
||||
const benefitRuleRaw = store.benefitUsageRule?.trim() || '';
|
||||
@@ -346,7 +343,7 @@ export default function StoreDetailPage() {
|
||||
/>
|
||||
|
||||
<View className="store-detail-hero full-bleed">
|
||||
<ProductCarousel images={images} alt={store.name} variant="store" />
|
||||
<ProductCarousel images={heroImages} alt={store.name} variant="store" previewable />
|
||||
</View>
|
||||
|
||||
<View className="store-detail-info-card">
|
||||
@@ -404,6 +401,9 @@ export default function StoreDetailPage() {
|
||||
<Text className="store-detail-section-title">门店套餐</Text>
|
||||
{store.packages.map((pkg, index) => (
|
||||
<View key={`${pkg.name}-${index}`} className="store-detail-package-card">
|
||||
{pkg.imageUrl ? (
|
||||
<Image className="store-detail-package-img" src={pkg.imageUrl} mode="aspectFill" />
|
||||
) : null}
|
||||
<Text className="store-detail-package-name">{pkg.name}</Text>
|
||||
<Text className="store-detail-package-body">
|
||||
{formatRedeemAmountYuan(pkg.price)} 元 · {pkg.dishes}
|
||||
@@ -443,7 +443,7 @@ export default function StoreDetailPage() {
|
||||
className="store-detail-env-item"
|
||||
onClick={() => previewEnv(index)}
|
||||
>
|
||||
<Image className="store-detail-env-img" src={url} mode="aspectFill" />
|
||||
<Image className="store-detail-env-img" src={url} mode="widthFix" />
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { View, Text, Image, Input } from '@tarojs/components';
|
||||
import Taro, { useDidShow, usePullDownRefresh, useShareAppMessage, useShareTimeline } from '@tarojs/taro';
|
||||
import { StoreStatus, STORE_STATUS_LABELS } from '@dukang/shared-types';
|
||||
import PageShell from '../../components/PageShell';
|
||||
import TabMainHeader from '../../components/TabMainHeader';
|
||||
import WechatShareReady from '../../components/WechatShareReady';
|
||||
@@ -348,6 +349,12 @@ export default function StoresPage() {
|
||||
return parts.length ? `营业时间: ${parts.join(',')}` : '营业时间: 10:00-22:00';
|
||||
}
|
||||
|
||||
function formatStatus(store: Store) {
|
||||
const status = store.status as StoreStatus | undefined;
|
||||
if (status && STORE_STATUS_LABELS[status]) return STORE_STATUS_LABELS[status];
|
||||
return STORE_STATUS_LABELS[StoreStatus.OPEN];
|
||||
}
|
||||
|
||||
const sharePayload = useMemo(
|
||||
() => ({
|
||||
title: '杜康好客门店',
|
||||
@@ -427,22 +434,24 @@ export default function StoresPage() {
|
||||
{s.coverUrl ? (
|
||||
<Image className="store-card-cover" src={s.coverUrl} mode="aspectFill" />
|
||||
) : (
|
||||
<View className="store-card-cover--empty" />
|
||||
<View className="store-card-cover store-card-cover--empty" />
|
||||
)}
|
||||
<View className="store-card-body">
|
||||
<Text className="store-card-name">{s.name}</Text>
|
||||
<Text className="store-card-meta">
|
||||
{s.district ? `${s.district} · ` : ''}
|
||||
{s.address || '地址待完善'}
|
||||
</Text>
|
||||
<Text className="store-card-meta">{formatHours(s)}</Text>
|
||||
{s.avgPrice != null && Number(s.avgPrice) > 0 ? (
|
||||
<Text className="store-card-meta">人均¥{Number(s.avgPrice).toFixed(0)}</Text>
|
||||
) : null}
|
||||
<View className="store-card-footer">
|
||||
<View className="store-card-head">
|
||||
<Text className="store-card-name">{s.name}</Text>
|
||||
<Text className="store-card-distance">
|
||||
{formatDistanceMeters(s.distanceMeters)}
|
||||
</Text>
|
||||
</View>
|
||||
<View className="store-card-status-row">
|
||||
<Text className="store-card-status">{formatStatus(s)}</Text>
|
||||
<Text className="store-card-hours">{formatHours(s)}</Text>
|
||||
</View>
|
||||
<Text className="store-card-address">
|
||||
{s.address || (s.district ? `${s.district}` : '地址待完善')}
|
||||
</Text>
|
||||
<View className="store-card-footer">
|
||||
<View className="store-card-footer-spacer" />
|
||||
<Text
|
||||
className="store-card-cta"
|
||||
onClick={(e) => {
|
||||
|
||||
@@ -175,24 +175,25 @@
|
||||
}
|
||||
|
||||
.store-detail-env-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: 8px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.store-detail-env-item {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
aspect-ratio: 1;
|
||||
border-radius: var(--radius-md, 8px);
|
||||
overflow: hidden;
|
||||
background: var(--color-surface-container);
|
||||
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
|
||||
}
|
||||
|
||||
.store-detail-env-img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
height: auto;
|
||||
display: block;
|
||||
vertical-align: top;
|
||||
}
|
||||
|
||||
.store-detail-bar {
|
||||
@@ -240,6 +241,14 @@
|
||||
border-bottom: 1px solid rgba(0, 0, 0, 0.06);
|
||||
}
|
||||
|
||||
.store-detail-package-img {
|
||||
width: 100%;
|
||||
height: 160px;
|
||||
border-radius: var(--radius-md, 8px);
|
||||
margin-bottom: 8px;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.store-detail-package-card:last-of-type {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
@@ -145,62 +145,124 @@
|
||||
}
|
||||
|
||||
.store-card {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: stretch;
|
||||
gap: 12px;
|
||||
padding: 12px;
|
||||
background: var(--color-card);
|
||||
border-radius: var(--radius-lg);
|
||||
overflow: hidden;
|
||||
box-shadow: var(--shadow-card);
|
||||
margin-bottom: 16px;
|
||||
margin-bottom: 12px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.store-card-cover {
|
||||
width: 100%;
|
||||
height: 160px;
|
||||
flex-shrink: 0;
|
||||
width: 96px;
|
||||
height: 96px;
|
||||
border-radius: var(--radius-md);
|
||||
background: var(--color-surface-container);
|
||||
display: block;
|
||||
}
|
||||
|
||||
.store-card-cover--empty {
|
||||
height: 160px;
|
||||
background: var(--color-surface-container);
|
||||
}
|
||||
|
||||
.store-card-body {
|
||||
padding: 14px 16px 16px;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.store-card-name {
|
||||
display: block;
|
||||
font-family: var(--font-headline);
|
||||
font-size: 16px;
|
||||
font-weight: 700;
|
||||
color: var(--color-on-surface);
|
||||
.store-card-head {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.store-card-meta {
|
||||
display: block;
|
||||
.store-card-name {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
font-family: var(--font-headline);
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
line-height: 1.35;
|
||||
color: var(--color-on-surface);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
}
|
||||
|
||||
.store-card-distance {
|
||||
flex-shrink: 0;
|
||||
font-size: 12px;
|
||||
line-height: 1.35;
|
||||
color: var(--color-subtle-gray);
|
||||
}
|
||||
|
||||
.store-card-status-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.store-card-status {
|
||||
flex-shrink: 0;
|
||||
padding: 2px 8px;
|
||||
border-radius: var(--radius-sm);
|
||||
background: rgba(45, 106, 79, 0.12);
|
||||
color: var(--color-success-green);
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.store-card-hours {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
font-size: 11px;
|
||||
line-height: 1.4;
|
||||
color: var(--color-subtle-gray);
|
||||
}
|
||||
|
||||
.store-card-address {
|
||||
font-size: 12px;
|
||||
line-height: 1.45;
|
||||
color: var(--color-subtle-gray);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
}
|
||||
|
||||
.store-card-footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-top: 12px;
|
||||
margin-top: auto;
|
||||
padding-top: 8px;
|
||||
}
|
||||
|
||||
.store-card-distance {
|
||||
font-size: 12px;
|
||||
color: var(--color-on-surface-variant);
|
||||
.store-card-footer-spacer {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.store-card-cta {
|
||||
padding: 6px 14px;
|
||||
flex-shrink: 0;
|
||||
padding: 6px 16px;
|
||||
border-radius: var(--radius-full);
|
||||
background: rgba(166, 29, 36, 0.08);
|
||||
color: var(--color-heritage-red);
|
||||
background: var(--color-heritage-red);
|
||||
color: #fff;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ export type ClientErrorCategory =
|
||||
| 'js_error'
|
||||
| 'unhandled_rejection'
|
||||
| 'api_error'
|
||||
| 'validation_error'
|
||||
| 'network'
|
||||
| 'render'
|
||||
| 'bridge'
|
||||
@@ -73,6 +74,7 @@ export function reportApiError(
|
||||
input: { message: string; status?: number; url?: string; category?: ClientErrorCategory },
|
||||
) {
|
||||
if (typeof window === 'undefined') return;
|
||||
if (input.url?.includes('/common/client-errors')) return;
|
||||
const token = opts.getToken?.() ?? localStorage.getItem('accessToken');
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -85,7 +87,7 @@ export function reportApiError(
|
||||
headers,
|
||||
body: {
|
||||
level: 'warn',
|
||||
category: input.category ?? 'api_error',
|
||||
category: input.category ?? (input.status === 400 ? 'validation_error' : 'api_error'),
|
||||
message: input.message.slice(0, 1000),
|
||||
pagePath: window.location.pathname,
|
||||
clientApp: opts.clientApp,
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -251,7 +251,6 @@ describe('validateStoreWithdraw', () => {
|
||||
requestAmount: 200,
|
||||
todayApplied: 0,
|
||||
dailyLimit: 5000,
|
||||
hasPendingRequest: false,
|
||||
hasBankAccount: true,
|
||||
};
|
||||
|
||||
@@ -261,8 +260,7 @@ describe('validateStoreWithdraw', () => {
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects pending request / missing bank / over available', () => {
|
||||
expect(validateStoreWithdraw({ ...base, hasPendingRequest: true }).ok).toBe(false);
|
||||
it('rejects missing bank / over available', () => {
|
||||
expect(validateStoreWithdraw({ ...base, hasBankAccount: false }).ok).toBe(false);
|
||||
expect(validateStoreWithdraw({ ...base, requestAmount: 1001 }).ok).toBe(false);
|
||||
});
|
||||
|
||||
@@ -105,20 +105,16 @@ export type ValidateStoreWithdrawInput = {
|
||||
requestAmount: number;
|
||||
todayApplied: number;
|
||||
dailyLimit: number;
|
||||
hasPendingRequest: boolean;
|
||||
hasBankAccount: boolean;
|
||||
};
|
||||
|
||||
/** 门店未出账提现护栏(FIN-002 单日上限 + 幂等/账户) */
|
||||
/** 门店未出账提现护栏(FIN-002 单日上限 + 账户) */
|
||||
export function validateStoreWithdraw(
|
||||
input: ValidateStoreWithdrawInput,
|
||||
): { ok: boolean; message?: string } {
|
||||
if (!input.hasBankAccount) {
|
||||
return { ok: false, message: '请先完善入驻收款账户后再提现' };
|
||||
}
|
||||
if (input.hasPendingRequest) {
|
||||
return { ok: false, message: '已有待审核提现申请,请等待处理完成' };
|
||||
}
|
||||
if (!(input.requestAmount > 0)) {
|
||||
return { ok: false, message: '提现金额必须大于 0' };
|
||||
}
|
||||
@@ -353,3 +349,5 @@ export function orderTabToStatuses(tab: string): string[] | undefined {
|
||||
}
|
||||
|
||||
export * from './city-partner';
|
||||
export * from './dev-plan';
|
||||
export * from './support-ticket';
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { validateSupportTicketStatusTransition } from './support-ticket';
|
||||
|
||||
describe('validateSupportTicketStatusTransition', () => {
|
||||
it('allows DEVELOPING -> TESTING', () => {
|
||||
expect(
|
||||
validateSupportTicketStatusTransition('DEVELOPING', 'TESTING', {
|
||||
linkedTaskCount: 1,
|
||||
isSuperAdmin: true,
|
||||
}).ok,
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('blocks PENDING_REVIEW -> DEVELOPING without tasks', () => {
|
||||
expect(
|
||||
validateSupportTicketStatusTransition('PENDING_REVIEW', 'DEVELOPING', {
|
||||
linkedTaskCount: 0,
|
||||
isSuperAdmin: true,
|
||||
}).ok,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('blocks rollback PASSED -> DEVELOPING', () => {
|
||||
expect(
|
||||
validateSupportTicketStatusTransition('PASSED', 'DEVELOPING', {
|
||||
linkedTaskCount: 1,
|
||||
isSuperAdmin: true,
|
||||
}).ok,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('requires super admin and reason for REJECTED', () => {
|
||||
expect(
|
||||
validateSupportTicketStatusTransition('DEVELOPING', 'REJECTED', {
|
||||
linkedTaskCount: 1,
|
||||
isSuperAdmin: false,
|
||||
rejectReason: 'x',
|
||||
}).ok,
|
||||
).toBe(false);
|
||||
expect(
|
||||
validateSupportTicketStatusTransition('DEVELOPING', 'REJECTED', {
|
||||
linkedTaskCount: 1,
|
||||
isSuperAdmin: true,
|
||||
rejectReason: '',
|
||||
}).ok,
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
export type SupportTicketStatus =
|
||||
| 'PENDING_REVIEW'
|
||||
| 'REJECTED'
|
||||
| 'DEVELOPING'
|
||||
| 'TESTING'
|
||||
| 'PASSED';
|
||||
|
||||
export type SupportTicketStatusTransitionContext = {
|
||||
linkedTaskCount: number;
|
||||
isSuperAdmin: boolean;
|
||||
rejectReason?: string;
|
||||
};
|
||||
|
||||
const FORWARD_TRANSITIONS: Record<SupportTicketStatus, SupportTicketStatus[]> = {
|
||||
PENDING_REVIEW: ['DEVELOPING', 'REJECTED'],
|
||||
DEVELOPING: ['TESTING', 'REJECTED'],
|
||||
TESTING: ['PASSED', 'REJECTED'],
|
||||
REJECTED: [],
|
||||
PASSED: [],
|
||||
};
|
||||
|
||||
/** 技术支持工单批量/人工改状态校验(禁止回退) */
|
||||
export function validateSupportTicketStatusTransition(
|
||||
from: SupportTicketStatus,
|
||||
to: SupportTicketStatus,
|
||||
ctx: SupportTicketStatusTransitionContext,
|
||||
): { ok: boolean; message?: string } {
|
||||
if (from === to) return { ok: true };
|
||||
|
||||
const allowed = FORWARD_TRANSITIONS[from] ?? [];
|
||||
if (!allowed.includes(to)) {
|
||||
return { ok: false, message: `不允许从「${from}」变更为「${to}」` };
|
||||
}
|
||||
|
||||
if (to === 'REJECTED') {
|
||||
if (!ctx.isSuperAdmin) return { ok: false, message: '仅最高管理员可驳回工单' };
|
||||
if (!ctx.rejectReason?.trim()) return { ok: false, message: '请填写驳回理由' };
|
||||
}
|
||||
|
||||
if (from === 'PENDING_REVIEW' && to === 'DEVELOPING' && ctx.linkedTaskCount < 1) {
|
||||
return { ok: false, message: '待评审工单转入开发须至少 1 条关联开发任务' };
|
||||
}
|
||||
|
||||
return { ok: true };
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
/** 开发计划任务类型 */
|
||||
|
||||
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 DevPlanTaskBatchUpdateInput {
|
||||
|
||||
taskIds: string[];
|
||||
|
||||
status?: DevPlanTaskStatusDto;
|
||||
|
||||
versionId?: string | null;
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
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: 'llm_configs', label: '语言模型配置', group: '业务' },
|
||||
{ key: 'knowledge_bases', label: '知识库', group: '业务' },
|
||||
{ key: 'dev_plan', label: '开发计划', group: '业务' },
|
||||
{ key: 'resources', label: 'OSS 资源库', group: '业务' },
|
||||
{ key: 'logs', label: '日志', group: '业务' },
|
||||
{ key: 'users_delete', label: '删除用户', group: '危险操作' },
|
||||
@@ -114,6 +115,7 @@ export const HQ_ROLE_DEFAULT_PERMISSIONS: Record<string, HqPermissionKey[]> = {
|
||||
'wecom_bots',
|
||||
'llm_configs',
|
||||
'knowledge_bases',
|
||||
'dev_plan',
|
||||
'resources',
|
||||
'logs',
|
||||
'system_settings_wechat_mini',
|
||||
|
||||
@@ -25,6 +25,8 @@ export * from './city-warehouse';
|
||||
export * from './fulfillment-provider';
|
||||
export * from './system-config';
|
||||
export * from './wecom-bot';
|
||||
export * from './wecom-message-push';
|
||||
export * from './llm-config';
|
||||
export * from './knowledge-base';
|
||||
export * from './legal';
|
||||
export * from './dev-plan';
|
||||
|
||||
@@ -50,6 +50,20 @@ export type CreateKnowledgeDocumentRequest = {
|
||||
sizeBytes?: number | null;
|
||||
};
|
||||
|
||||
export type UpdateKnowledgeDocumentRequest = {
|
||||
title?: string;
|
||||
contentText?: string | null;
|
||||
fileName?: string | null;
|
||||
fileUrl?: string | null;
|
||||
mimeType?: string | null;
|
||||
sizeBytes?: number | null;
|
||||
};
|
||||
|
||||
/** 编辑文档时含正文 */
|
||||
export type KnowledgeDocumentDetailDto = KnowledgeDocumentDto & {
|
||||
contentText: string | null;
|
||||
};
|
||||
|
||||
export type KnowledgeBaseOptionDto = {
|
||||
id: string;
|
||||
name: string;
|
||||
|
||||
@@ -63,7 +63,6 @@ export interface StoreWithdrawSummaryDto {
|
||||
remainingDailyLimit: number;
|
||||
isPrimary: boolean;
|
||||
hasBankAccount: boolean;
|
||||
hasPendingRequest: boolean;
|
||||
bankAccount?: StoreWithdrawBankAccountDto | null;
|
||||
}
|
||||
|
||||
@@ -184,6 +183,9 @@ export const STORE_SETTLEMENT_DEFAULT_RATE = 0.6;
|
||||
/** 酒厂账单结算比例(酒单实付 × 比例),暂定 30% */
|
||||
export const WINERY_SETTLEMENT_RATE = 0.3;
|
||||
|
||||
/** 酒厂账单出账滞后自然日(T+3:支付日 + 3 天后纳入账单) */
|
||||
export const WINERY_SETTLEMENT_LAG_DAYS = 3;
|
||||
|
||||
export type { LogisticsSettlementMethod } from './enums';
|
||||
export { LOGISTICS_SETTLEMENT_METHOD_LABELS } from './enums';
|
||||
import type { LogisticsSettlementMethod } from './enums';
|
||||
|
||||
@@ -5,6 +5,7 @@ export interface StorePackageItemDto {
|
||||
dishes: string;
|
||||
usableTime?: string | null;
|
||||
otherNotes?: string | null;
|
||||
imageUrl?: string | null;
|
||||
sortOrder: number;
|
||||
}
|
||||
|
||||
|
||||
@@ -47,6 +47,7 @@ export interface SupportTicketDto {
|
||||
reviewerName?: string | null;
|
||||
reviewedAt?: string | null;
|
||||
remark?: string | null;
|
||||
attachmentUrls?: string[] | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
completedAt?: string | null;
|
||||
@@ -57,8 +58,72 @@ export interface CreateSupportTicketRequest {
|
||||
title: string;
|
||||
content?: string;
|
||||
remark?: string;
|
||||
attachmentUrls?: string[];
|
||||
}
|
||||
|
||||
export interface UpdateSupportTicketRequest {
|
||||
ticketType?: SupportTicketTypeDto;
|
||||
title?: string;
|
||||
content?: string;
|
||||
remark?: string;
|
||||
attachmentUrls?: string[];
|
||||
}
|
||||
|
||||
export interface RejectSupportTicketRequest {
|
||||
rejectReason: string;
|
||||
}
|
||||
|
||||
export interface CreateDevPlanTaskFromTicketInput {
|
||||
content: string;
|
||||
type: 'BUG' | 'REQUIREMENT' | 'OPTIMIZATION';
|
||||
}
|
||||
|
||||
export interface ReviewSupportTicketRequest {
|
||||
decision: 'APPROVE' | 'REJECT';
|
||||
rejectReason?: string;
|
||||
note?: string;
|
||||
tasks?: CreateDevPlanTaskFromTicketInput[];
|
||||
dispatchToWecom?: boolean;
|
||||
dispatchSupplement?: string;
|
||||
}
|
||||
|
||||
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[];
|
||||
}
|
||||
|
||||
export interface BatchUpdateSupportTicketStatusRequest {
|
||||
ticketIds: string[];
|
||||
status: SupportTicketStatusDto;
|
||||
rejectReason?: string;
|
||||
note?: string;
|
||||
}
|
||||
|
||||
@@ -1,63 +1,262 @@
|
||||
/** 企业微信智能机器人能力权限 */
|
||||
/** 企业微信智能机器人 · 模块化能力权限(v3.4.11 重构) */
|
||||
export const WECOM_BOT_PERMISSIONS = [
|
||||
'order.read',
|
||||
'delivery.read',
|
||||
'store.read',
|
||||
'redeem.read',
|
||||
'ticket.read',
|
||||
'ticket.create',
|
||||
'user.view_sms',
|
||||
'delivery.view',
|
||||
'user.read',
|
||||
'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.progress',
|
||||
'handbook.query',
|
||||
'server_log.view',
|
||||
'api.query',
|
||||
'support_ticket.review',
|
||||
'support_ticket.approve',
|
||||
'support_ticket.reject',
|
||||
'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;
|
||||
|
||||
export type WecomBotPermission = (typeof WECOM_BOT_PERMISSIONS)[number];
|
||||
|
||||
export const WECOM_BOT_PERMISSION_LABELS: Record<WecomBotPermission, string> = {
|
||||
'order.read': '查询订单',
|
||||
'delivery.read': '查询配送/物流',
|
||||
'store.read': '查询门店',
|
||||
'redeem.read': '查询核销记录',
|
||||
'ticket.read': '查询售后工单',
|
||||
'ticket.create': '创建售后工单',
|
||||
'user.view_sms': '查用户(短信验证)',
|
||||
'delivery.view': '查快递信息',
|
||||
'user.read': '查询用户(脱敏)',
|
||||
'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.progress': '查看开发进度',
|
||||
'handbook.query': '查询使用手册',
|
||||
'server_log.view': '查看服务器日志',
|
||||
'api.query': '查询业务 API(只读)',
|
||||
'support_ticket.review': '审批技术支持工单(通过/驳回)',
|
||||
'support_ticket.approve': '通过技术支持工单',
|
||||
'support_ticket.reject': '驳回技术支持工单',
|
||||
'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 = [
|
||||
'CUSTOMER_SERVICE',
|
||||
'FINANCE',
|
||||
'OPERATIONS',
|
||||
'TECH_SUPPORT',
|
||||
'TEAM_ASSISTANT',
|
||||
'CUSTOM',
|
||||
] as const;
|
||||
|
||||
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> = {
|
||||
CUSTOMER_SERVICE: '客服机器人',
|
||||
TECH_SUPPORT: '技术支持机器人',
|
||||
TEAM_ASSISTANT: '团队助手',
|
||||
CUSTOMER_SERVICE: '客服助手',
|
||||
FINANCE: '财务助手',
|
||||
OPERATIONS: '运营助手',
|
||||
TECH_SUPPORT: '技术支持',
|
||||
CUSTOM: '自定义',
|
||||
};
|
||||
|
||||
export const WECOM_BOT_ROLE_DEFAULT_PERMISSIONS: Record<WecomBotRole, WecomBotPermission[]> = {
|
||||
CUSTOMER_SERVICE: ['ticket.create', 'user.view_sms', 'delivery.view'],
|
||||
TECH_SUPPORT: ['support_ticket.create', 'support_ticket.progress', 'server_log.view', 'api.query'],
|
||||
TEAM_ASSISTANT: ['handbook.query'],
|
||||
CUSTOMER_SERVICE: [
|
||||
'order.read',
|
||||
'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: [],
|
||||
};
|
||||
|
||||
/** 旧版权限 → 新版权限(读取 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(
|
||||
raw?: string | string[] | null,
|
||||
): WecomBotPermission[] {
|
||||
const set = new Set<string>(WECOM_BOT_PERMISSIONS);
|
||||
const list = Array.isArray(raw)
|
||||
? raw
|
||||
: String(raw ?? '')
|
||||
const valid = new Set<string>(WECOM_BOT_PERMISSIONS);
|
||||
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 WecomBotPermission => set.has(s)))];
|
||||
}
|
||||
}
|
||||
|
||||
const migrated = migrateWecomBotPermissions(list);
|
||||
if (migrated.length) return migrated;
|
||||
return [...new Set(list.filter((s): s is WecomBotPermission => valid.has(s)))];
|
||||
}
|
||||
|
||||
export function resolveWecomBotPermissions(
|
||||
@@ -69,17 +268,32 @@ export function resolveWecomBotPermissions(
|
||||
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 = {
|
||||
id: string;
|
||||
name: string;
|
||||
role: WecomBotRole;
|
||||
botId: string;
|
||||
/** 列表/详情不返回明文;仅表示是否已配置 */
|
||||
secretConfigured: boolean;
|
||||
avatarUrl: string | null;
|
||||
welcome: string | null;
|
||||
permissions: WecomBotPermission[];
|
||||
/** 未匹配指令时是否调用绑定的语言模型 */
|
||||
/** 可执行 support_ticket.review 的企微 userid 白名单 */
|
||||
reviewSuperAdminWecomUserIds: string[];
|
||||
aiEnabled: boolean;
|
||||
llmConfigId: string | null;
|
||||
llmConfigName: string | null;
|
||||
@@ -99,6 +313,7 @@ export type CreateWecomBotRequest = {
|
||||
avatarUrl?: string | null;
|
||||
welcome?: string | null;
|
||||
permissions?: WecomBotPermission[];
|
||||
reviewSuperAdminWecomUserIds?: string[];
|
||||
aiEnabled?: boolean;
|
||||
llmConfigId?: string | null;
|
||||
knowledgeBaseId?: string | null;
|
||||
@@ -110,14 +325,64 @@ export type UpdateWecomBotRequest = {
|
||||
name?: string;
|
||||
role?: WecomBotRole;
|
||||
botId?: string;
|
||||
/** 空或不传表示不修改 */
|
||||
secret?: string;
|
||||
avatarUrl?: string | null;
|
||||
welcome?: string | null;
|
||||
permissions?: WecomBotPermission[];
|
||||
reviewSuperAdminWecomUserIds?: string[];
|
||||
aiEnabled?: boolean;
|
||||
llmConfigId?: string | null;
|
||||
knowledgeBaseId?: string | null;
|
||||
enabled?: boolean;
|
||||
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「企微机器人」模块创建)
|
||||
WECOM_AIBOT_ENABLED=false
|
||||
|
||||
# 运营告警:企业微信群机器人 Webhook(单向推送,与智能机器人长连接无关)
|
||||
WECOM_ALERT_ENABLED=false
|
||||
WECOM_ALERT_WEBHOOK_URL=
|
||||
# 运营告警 Webhook(已废弃运行时读取,仅 seed 一次性导入到 HQ「消息推送」)
|
||||
# 配置后执行 pnpm prisma:seed-wecom-push 或 API 启动时自动 ensureDefaults
|
||||
# WECOM_ALERT_ENABLED=false
|
||||
# WECOM_ALERT_WEBHOOK_URL=
|
||||
WECOM_ALERT_ENV_LABEL=local
|
||||
|
||||
# 腾讯位置服务(地理编码 / 逆地理 / 地点搜索选点,服务端调用)
|
||||
|
||||
@@ -53,8 +53,9 @@ WX_MINI_MSG_AES_KEY=
|
||||
WECOM_AIBOT_ENABLED=false
|
||||
|
||||
# 运营告警:企业微信群机器人 Webhook
|
||||
WECOM_ALERT_ENABLED=false
|
||||
WECOM_ALERT_WEBHOOK_URL=
|
||||
# 运营告警 Webhook(已废弃运行时读取,仅 seed 导入 HQ「消息推送」)
|
||||
# WECOM_ALERT_ENABLED=false
|
||||
# WECOM_ALERT_WEBHOOK_URL=
|
||||
WECOM_ALERT_ENV_LABEL=production
|
||||
|
||||
OSS_ACCESS_KEY_ID=
|
||||
|
||||
@@ -53,8 +53,9 @@ WX_MINI_MSG_AES_KEY=
|
||||
WECOM_AIBOT_ENABLED=false
|
||||
|
||||
# 运营告警:企业微信群机器人 Webhook
|
||||
WECOM_ALERT_ENABLED=false
|
||||
WECOM_ALERT_WEBHOOK_URL=
|
||||
# 运营告警 Webhook(已废弃运行时读取,仅 seed 导入 HQ「消息推送」)
|
||||
# WECOM_ALERT_ENABLED=false
|
||||
# WECOM_ALERT_WEBHOOK_URL=
|
||||
WECOM_ALERT_ENV_LABEL=staging
|
||||
|
||||
OSS_ACCESS_KEY_ID=
|
||||
|
||||
@@ -16,6 +16,8 @@
|
||||
"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: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: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
|
||||
}
|
||||
|
||||
enum DevPlanTaskType {
|
||||
BUG
|
||||
REQUIREMENT
|
||||
OPTIMIZATION
|
||||
}
|
||||
|
||||
enum DevPlanTaskStatus {
|
||||
TODO
|
||||
DEVELOPED
|
||||
RELEASED
|
||||
}
|
||||
|
||||
enum DevPlanVersionStatus {
|
||||
PENDING
|
||||
IN_PROGRESS
|
||||
TESTING
|
||||
RELEASED
|
||||
}
|
||||
|
||||
enum InvoiceTitleType {
|
||||
PERSONAL
|
||||
ENTERPRISE
|
||||
@@ -389,26 +408,28 @@ model SystemConfig {
|
||||
|
||||
/// 企业微信智能机器人(HQ 可创建多实例,长连接)
|
||||
model WecomBot {
|
||||
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||
name String @db.VarChar(64)
|
||||
role String @db.VarChar(32)
|
||||
botId String @unique @map("bot_id") @db.VarChar(128)
|
||||
secret String @db.VarChar(256)
|
||||
avatarUrl String? @map("avatar_url") @db.VarChar(512)
|
||||
welcome String? @db.VarChar(1024)
|
||||
/// JSON 字符串数组,如 ["ticket.create","user.view_sms"]
|
||||
permissions String @db.Text
|
||||
/// 未匹配指令时是否调用语言模型
|
||||
aiEnabled Boolean @default(false) @map("ai_enabled")
|
||||
llmConfigId BigInt? @map("llm_config_id") @db.UnsignedBigInt
|
||||
knowledgeBaseId BigInt? @map("knowledge_base_id") @db.UnsignedBigInt
|
||||
enabled Boolean @default(true)
|
||||
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)
|
||||
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||
name String @db.VarChar(64)
|
||||
role String @db.VarChar(32)
|
||||
botId String @unique @map("bot_id") @db.VarChar(128)
|
||||
secret String @db.VarChar(256)
|
||||
avatarUrl String? @map("avatar_url") @db.VarChar(512)
|
||||
welcome String? @db.VarChar(1024)
|
||||
/// JSON 字符串数组,模块化权限
|
||||
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")
|
||||
llmConfigId BigInt? @map("llm_config_id") @db.UnsignedBigInt
|
||||
knowledgeBaseId BigInt? @map("knowledge_base_id") @db.UnsignedBigInt
|
||||
enabled Boolean @default(true)
|
||||
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)
|
||||
|
||||
llmConfig LlmApiConfig? @relation(fields: [llmConfigId], references: [id], onDelete: SetNull)
|
||||
knowledgeBase KnowledgeBase? @relation(fields: [knowledgeBaseId], references: [id], onDelete: SetNull)
|
||||
wecomBotLogs LogWecomBot[]
|
||||
|
||||
@@index([enabled, sortOrder])
|
||||
@@index([llmConfigId])
|
||||
@@ -416,6 +437,46 @@ model WecomBot {
|
||||
@@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 配置(非超管仅可见/可开关自己创建的)
|
||||
model LlmApiConfig {
|
||||
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||
@@ -594,6 +655,7 @@ model CommonSupportTicket {
|
||||
reviewerName String? @map("reviewer_name") @db.VarChar(64)
|
||||
reviewedAt DateTime? @map("reviewed_at") @db.DateTime(3)
|
||||
remark String? @db.VarChar(512)
|
||||
attachmentUrls Json? @map("attachment_urls")
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
|
||||
updatedAt DateTime @updatedAt @map("updated_at") @db.DateTime(3)
|
||||
completedAt DateTime? @map("completed_at") @db.DateTime(3)
|
||||
@@ -602,6 +664,87 @@ model CommonSupportTicket {
|
||||
@@index([ticketType, status])
|
||||
@@index([creatorId])
|
||||
@@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 {
|
||||
@@ -1136,6 +1279,7 @@ model StorePackage {
|
||||
dishes String @db.Text
|
||||
usableTime String? @map("usable_time") @db.VarChar(256)
|
||||
otherNotes String? @map("other_notes") @db.VarChar(512)
|
||||
imageUrl String? @map("image_url") @db.VarChar(512)
|
||||
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)
|
||||
|
||||
@@ -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 { HqOperationModule } from './common/hq-operation/hq-operation.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 { WecomModule } from './integrations/wecom/wecom.module';
|
||||
import { LoggingModule } from './common/logging/logging.module';
|
||||
@@ -53,6 +54,7 @@ import { RequestIdMiddleware } from './common/logging/request-id.middleware';
|
||||
PromoModule,
|
||||
CityScopeModule,
|
||||
CommonModule,
|
||||
DevPlanModule,
|
||||
HqOperationModule,
|
||||
LoggingModule,
|
||||
CallbacksModule,
|
||||
|
||||
@@ -2,16 +2,15 @@ import { Global, Module } from '@nestjs/common';
|
||||
import { RedisModule } from '../redis/redis.module';
|
||||
import { AlertService } from './alert.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 发送器在本 Module 注册,避免与 WecomModule↔Common 循环依赖。
|
||||
* 运营告警(企微 Webhook 多实例)。Global 以便 Filter / 各业务 Module 注入。
|
||||
*/
|
||||
@Global()
|
||||
@Module({
|
||||
imports: [RedisModule],
|
||||
providers: [WecomWebhookAlertService, AlertService, PayRedeemAnomalyService],
|
||||
exports: [WecomWebhookAlertService, AlertService, PayRedeemAnomalyService],
|
||||
providers: [WecomMessagePushService, AlertService, PayRedeemAnomalyService],
|
||||
exports: [WecomMessagePushService, AlertService, PayRedeemAnomalyService],
|
||||
})
|
||||
export class AlertModule {}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import type { WecomPushCondition } from '@dukang/shared-types';
|
||||
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';
|
||||
|
||||
export type AlertNotifyInput = {
|
||||
@@ -10,6 +11,8 @@ export type AlertNotifyInput = {
|
||||
detail: string;
|
||||
dedupeKey: string;
|
||||
dedupeTtlSec?: number;
|
||||
/** 覆盖默认事件 key 映射 */
|
||||
eventKeys?: WecomPushCondition[];
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
@@ -18,7 +21,7 @@ export class AlertService {
|
||||
|
||||
constructor(
|
||||
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> {
|
||||
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 dedupeRedisKey = `alert:dedupe:${input.dedupeKey}`;
|
||||
@@ -42,38 +47,13 @@ export class AlertService {
|
||||
);
|
||||
}
|
||||
|
||||
return this.sendMarkdownNow(input);
|
||||
return this.sendMarkdownNow(input, eventKeys);
|
||||
}
|
||||
|
||||
/** HQ 测试推送:不去重,返回明确结果 */
|
||||
async sendTestAlert(): Promise<{ ok: boolean; message: string }> {
|
||||
const url = (process.env.WECOM_ALERT_WEBHOOK_URL || '').trim();
|
||||
if (!url) {
|
||||
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> {
|
||||
private async sendMarkdownNow(
|
||||
input: AlertNotifyInput,
|
||||
eventKeys: WecomPushCondition[],
|
||||
): Promise<boolean> {
|
||||
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 content = [
|
||||
@@ -85,10 +65,23 @@ export class AlertService {
|
||||
escapeMd(input.detail).slice(0, 3500),
|
||||
].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> 标签可用 */
|
||||
function escapeMd(s: string): string {
|
||||
return s.replace(/([\\`*_[\]])/g, '\\$1');
|
||||
|
||||
@@ -84,6 +84,10 @@ export const HqOperationAction = {
|
||||
WECOM_BOT_UPDATE: 'WECOM_BOT_UPDATE',
|
||||
WECOM_BOT_DELETE: 'WECOM_BOT_DELETE',
|
||||
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_UPDATE: 'LLM_CONFIG_UPDATE',
|
||||
LLM_CONFIG_DELETE: 'LLM_CONFIG_DELETE',
|
||||
@@ -92,6 +96,7 @@ export const HqOperationAction = {
|
||||
KNOWLEDGE_BASE_UPDATE: 'KNOWLEDGE_BASE_UPDATE',
|
||||
KNOWLEDGE_BASE_DELETE: 'KNOWLEDGE_BASE_DELETE',
|
||||
KNOWLEDGE_DOC_CREATE: 'KNOWLEDGE_DOC_CREATE',
|
||||
KNOWLEDGE_DOC_UPDATE: 'KNOWLEDGE_DOC_UPDATE',
|
||||
KNOWLEDGE_DOC_DELETE: 'KNOWLEDGE_DOC_DELETE',
|
||||
REDEEM_PENDING_COMPLETE: 'REDEEM_PENDING_COMPLETE',
|
||||
REDEEM_PENDING_REJECT: 'REDEEM_PENDING_REJECT',
|
||||
@@ -100,6 +105,19 @@ export const HqOperationAction = {
|
||||
SYSTEM_CONFIG_SYNC_ENV: 'SYSTEM_CONFIG_SYNC_ENV',
|
||||
SYSTEM_CONFIG_IMPORT_ENV: 'SYSTEM_CONFIG_IMPORT_ENV',
|
||||
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;
|
||||
|
||||
export type HqOperationActionCode = (typeof HqOperationAction)[keyof typeof HqOperationAction];
|
||||
@@ -189,6 +207,10 @@ export const HQ_OPERATION_ACTION_LABELS: Record<string, string> = {
|
||||
[HqOperationAction.WECOM_BOT_UPDATE]: '编辑企微机器人',
|
||||
[HqOperationAction.WECOM_BOT_DELETE]: '删除企微机器人',
|
||||
[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_UPDATE]: '更新语言模型配置',
|
||||
[HqOperationAction.LLM_CONFIG_DELETE]: '删除语言模型配置',
|
||||
@@ -197,6 +219,7 @@ export const HQ_OPERATION_ACTION_LABELS: Record<string, string> = {
|
||||
[HqOperationAction.KNOWLEDGE_BASE_UPDATE]: '更新知识库',
|
||||
[HqOperationAction.KNOWLEDGE_BASE_DELETE]: '删除知识库',
|
||||
[HqOperationAction.KNOWLEDGE_DOC_CREATE]: '上传知识库文档',
|
||||
[HqOperationAction.KNOWLEDGE_DOC_UPDATE]: '编辑知识库文档',
|
||||
[HqOperationAction.KNOWLEDGE_DOC_DELETE]: '删除知识库文档',
|
||||
[HqOperationAction.REDEEM_PENDING_COMPLETE]: '弱网待处理单-补核销',
|
||||
[HqOperationAction.REDEEM_PENDING_REJECT]: '弱网待处理单-驳回',
|
||||
@@ -205,6 +228,19 @@ export const HQ_OPERATION_ACTION_LABELS: Record<string, string> = {
|
||||
[HqOperationAction.SYSTEM_CONFIG_SYNC_ENV]: '同步系统配置到 env 文件',
|
||||
[HqOperationAction.SYSTEM_CONFIG_IMPORT_ENV]: '从当前环境导入配置',
|
||||
[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: '门店打款确认',
|
||||
};
|
||||
|
||||
|
||||
@@ -59,15 +59,7 @@ export const SYSTEM_CONFIG_FIELDS: SystemConfigFieldMeta[] = [
|
||||
group: G.feature,
|
||||
type: 'boolean',
|
||||
requiresRestart: false,
|
||||
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)',
|
||||
description: '总开关。开启后连接 HQ「企微机器人 → 智能机器人」中已启用且配置完整的 Bot(每 Bot 同时仅 1 条长连接)',
|
||||
},
|
||||
|
||||
{ key: 'ALIYUN_SMS_SIGN_NAME', label: '短信签名', group: G.sms, type: 'string', requiresRestart: false },
|
||||
|
||||
@@ -6,7 +6,8 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import { WSClient, generateReqId, type WsFrame } from '@wecom/aibot-node-sdk';
|
||||
import {
|
||||
WECOM_BOT_ROLES,
|
||||
normalizeWecomBotRole,
|
||||
parseWecomUserIdList,
|
||||
resolveWecomBotPermissions,
|
||||
type WecomBotRole,
|
||||
} from '@dukang/shared-types';
|
||||
@@ -17,11 +18,13 @@ import type { WecomBotRuntimeConfig } from './wecom-bot.types';
|
||||
|
||||
const DEFAULT_WELCOMES: Record<WecomBotRole, string> = {
|
||||
CUSTOMER_SERVICE:
|
||||
'您好,我是杜康好客【客服】助手。发送「帮助」查看:创建售后工单、查用户(需短信验证)、查快递。',
|
||||
'您好,我是杜康好客【客服助手】。发送「帮助」查看:订单、配送、售后工单等指令。',
|
||||
FINANCE:
|
||||
'您好,我是杜康好客【财务助手】。发送「帮助」查看:门店/合伙人/酒厂/物流账单与打款提现查询。',
|
||||
OPERATIONS:
|
||||
'您好,我是杜康好客【运营助手】。发送「帮助」查看:订单、门店、用户、核销等只读查询。',
|
||||
TECH_SUPPORT:
|
||||
'您好,我是杜康好客【技术支持】助手。发送「帮助」查看:创建技术支持工单、查看开发进度。',
|
||||
TEAM_ASSISTANT:
|
||||
'您好,我是杜康好客【团队助手】。发送「帮助」或「手册 关键词」查询系统使用说明。',
|
||||
'您好,我是杜康好客【技术支持】。发送「帮助」查看:技术支持工单、开发计划与审批指令。',
|
||||
CUSTOM: '您好!发送「帮助」查看可用指令。',
|
||||
};
|
||||
|
||||
@@ -50,9 +53,6 @@ type BotRuntime = {
|
||||
lastError: string | null;
|
||||
};
|
||||
|
||||
function isWecomRole(v: string): v is WecomBotRole {
|
||||
return (WECOM_BOT_ROLES as readonly string[]).includes(v);
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class WecomAibotService implements OnModuleInit, OnModuleDestroy {
|
||||
@@ -152,12 +152,13 @@ export class WecomAibotService implements OnModuleInit, OnModuleDestroy {
|
||||
avatarUrl: string | null;
|
||||
welcome: string | null;
|
||||
permissions: string;
|
||||
reviewSuperAdminWecomUserIds: string | null;
|
||||
aiEnabled: boolean;
|
||||
llmConfigId: bigint | null;
|
||||
knowledgeBaseId: bigint | null;
|
||||
enabled: boolean;
|
||||
}): WecomBotRuntimeConfig {
|
||||
const role = (isWecomRole(row.role) ? row.role : 'CUSTOM') as WecomBotRole;
|
||||
const role = normalizeWecomBotRole(row.role);
|
||||
return {
|
||||
id: row.id.toString(),
|
||||
key: `db_${row.id.toString()}`,
|
||||
@@ -169,6 +170,7 @@ export class WecomAibotService implements OnModuleInit, OnModuleDestroy {
|
||||
avatarUrl: row.avatarUrl,
|
||||
welcome: row.welcome?.trim() || DEFAULT_WELCOMES[role],
|
||||
permissions: resolveWecomBotPermissions(role, row.permissions),
|
||||
reviewSuperAdminWecomUserIds: parseWecomUserIdList(row.reviewSuperAdminWecomUserIds),
|
||||
aiEnabled: row.aiEnabled,
|
||||
llmConfigId: row.llmConfigId?.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 lower = content.toLowerCase();
|
||||
|
||||
this.logger.log(`[${cfg.key}] inbound user=${wecomUserId} text=${content.slice(0, 120)}`);
|
||||
|
||||
try {
|
||||
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;
|
||||
}
|
||||
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;
|
||||
}
|
||||
const useAi = cfg.aiEnabled && !!cfg.llmConfigId;
|
||||
@@ -271,11 +279,13 @@ export class WecomAibotService implements OnModuleInit, OnModuleDestroy {
|
||||
skipNaturalFallback: useAi,
|
||||
});
|
||||
if (reply != null) {
|
||||
this.logger.log(`[${cfg.key}] route=command len=${reply.length}`);
|
||||
await this.replyText(client, frame, reply);
|
||||
return;
|
||||
}
|
||||
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(
|
||||
client,
|
||||
frame,
|
||||
@@ -283,6 +293,7 @@ export class WecomAibotService implements OnModuleInit, OnModuleDestroy {
|
||||
);
|
||||
return;
|
||||
}
|
||||
this.logger.log(`[${cfg.key}] route=fallback`);
|
||||
await this.replyText(client, frame, `未识别指令。\n\n${this.actions.buildHelp(cfg)}`);
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
|
||||
@@ -1,653 +1,39 @@
|
||||
import { Inject, Injectable, Logger } 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 { Injectable } from '@nestjs/common';
|
||||
import type { WecomBotRuntimeConfig } from './wecom-bot.types';
|
||||
import { wecomBotHasPermission } from './wecom-bot.types';
|
||||
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',
|
||||
};
|
||||
import { WecomBotCapabilityService } from './wecom-bot-capability.service';
|
||||
|
||||
/** 兼容层:AI / Aibot 仍通过 Actions 入口调用 Capability */
|
||||
@Injectable()
|
||||
export class WecomBotActionsService {
|
||||
private readonly logger = new Logger(WecomBotActionsService.name);
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly ticketService: TicketService,
|
||||
private readonly supportTicketService: SupportTicketService,
|
||||
private readonly session: WecomBotSessionService,
|
||||
@Inject(SMS_PROVIDER) private readonly sms: ISmsProvider,
|
||||
) {}
|
||||
constructor(private readonly capability: WecomBotCapabilityService) {}
|
||||
|
||||
buildHelp(bot: WecomBotRuntimeConfig): string {
|
||||
const lines = [`**${bot.name}**`, '', '通用:`帮助` · `状态`', ''];
|
||||
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');
|
||||
return this.capability.buildHelp(bot);
|
||||
}
|
||||
|
||||
async handleCommand(
|
||||
handleCommand(
|
||||
bot: WecomBotRuntimeConfig,
|
||||
wecomUserId: string,
|
||||
text: string,
|
||||
opts?: { skipNaturalFallback?: boolean },
|
||||
): Promise<string | null> {
|
||||
const content = text.trim();
|
||||
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);
|
||||
}
|
||||
|
||||
// 快递
|
||||
if (/^(快递|配送|物流)\s+/i.test(content)) {
|
||||
this.requirePerm(bot, 'delivery.view');
|
||||
const q = content.replace(/^(快递|配送|物流)\s+/i, '').trim();
|
||||
return this.lookupDelivery(q);
|
||||
}
|
||||
|
||||
// 售后工单
|
||||
if (/^(工单|创建工单)\s+/i.test(content)) {
|
||||
this.requirePerm(bot, 'ticket.create');
|
||||
return this.createAfterSaleTicket(content.replace(/^(工单|创建工单)\s+/i, '').trim(), wecomUserId);
|
||||
}
|
||||
|
||||
// 技术支持提单
|
||||
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)}`;
|
||||
return this.capability.dispatch(bot, wecomUserId, text, opts);
|
||||
}
|
||||
|
||||
private requirePerm(bot: WecomBotRuntimeConfig, perm: Parameters<typeof wecomBotHasPermission>[1]) {
|
||||
if (!wecomBotHasPermission(bot, perm)) {
|
||||
throw new Error(`当前机器人无权限:${perm}`);
|
||||
}
|
||||
runTool(
|
||||
bot: WecomBotRuntimeConfig,
|
||||
wecomUserId: string,
|
||||
toolName: string,
|
||||
args: string,
|
||||
): Promise<string> {
|
||||
return this.capability.runTool(bot, wecomUserId, toolName, args);
|
||||
}
|
||||
|
||||
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})` };
|
||||
tryNaturalLanguageQuery(
|
||||
bot: WecomBotRuntimeConfig,
|
||||
wecomUserId: string,
|
||||
content: string,
|
||||
): Promise<string | null> {
|
||||
return this.capability.tryNaturalLanguageQuery(bot, wecomUserId, content);
|
||||
}
|
||||
}
|
||||
|
||||
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 { LlmChatClient } from '../llm/llm-chat.client';
|
||||
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 { wecomBotHasPermission } from './wecom-bot.types';
|
||||
|
||||
const DEFAULT_SYSTEM = [
|
||||
'你是杜康好客企业内部助手。',
|
||||
@@ -11,6 +14,29 @@ const DEFAULT_SYSTEM = [
|
||||
'回答简洁,使用中文。',
|
||||
].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()
|
||||
export class WecomBotAiService {
|
||||
private readonly logger = new Logger(WecomBotAiService.name);
|
||||
@@ -19,9 +45,14 @@ export class WecomBotAiService {
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly llm: LlmChatClient,
|
||||
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;
|
||||
|
||||
const cfg = await this.prisma.llmApiConfig.findUnique({
|
||||
@@ -42,11 +73,16 @@ export class WecomBotAiService {
|
||||
|
||||
const systemParts = [
|
||||
cfg.systemPrompt?.trim() || DEFAULT_SYSTEM,
|
||||
this.buildToolHint(bot),
|
||||
TOOL_INSTRUCTION,
|
||||
kbBlock ? `\n\n以下为知识库检索片段:\n${kbBlock}` : '',
|
||||
];
|
||||
|
||||
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,
|
||||
apiKey: cfg.apiKey,
|
||||
model: cfg.modelName,
|
||||
@@ -57,10 +93,57 @@ export class WecomBotAiService {
|
||||
{ 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) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
this.logger.error(`wecom ai reply failed: ${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 { normalizeWecomBotRole } from '@dukang/shared-types';
|
||||
|
||||
export type WecomBotRuntimeConfig = {
|
||||
id: string;
|
||||
@@ -11,6 +12,7 @@ export type WecomBotRuntimeConfig = {
|
||||
welcome: string;
|
||||
avatarUrl: string | null;
|
||||
permissions: WecomBotPermission[];
|
||||
reviewSuperAdminWecomUserIds: string[];
|
||||
aiEnabled: boolean;
|
||||
llmConfigId: string | null;
|
||||
knowledgeBaseId: string | null;
|
||||
@@ -22,3 +24,23 @@ export function wecomBotHasPermission(
|
||||
): boolean {
|
||||
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 { CommonModule } from '../../modules/common/common.module';
|
||||
import { IntegrationsModule } from '../integrations.module';
|
||||
import { LlmModule } from '../llm/llm.module';
|
||||
import { WecomAibotService } from './wecom-aibot.service';
|
||||
import { WecomBotActionsService } from './wecom-bot-actions.service';
|
||||
import { WecomBotAiService } from './wecom-bot-ai.service';
|
||||
import { WecomBotSessionService } from './wecom-bot-session.service';
|
||||
|
||||
/** 企微多机器人:依赖 Common(工单)+ Integrations(短信)+ Llm,不反向被 Integrations 引用 */
|
||||
@Module({
|
||||
imports: [
|
||||
forwardRef(() => CommonModule),
|
||||
forwardRef(() => IntegrationsModule),
|
||||
LlmModule,
|
||||
],
|
||||
providers: [
|
||||
WecomBotSessionService,
|
||||
WecomBotActionsService,
|
||||
WecomBotAiService,
|
||||
WecomAibotService,
|
||||
],
|
||||
exports: [WecomAibotService],
|
||||
})
|
||||
export class WecomModule {}
|
||||
import { Module, forwardRef } from '@nestjs/common';
|
||||
|
||||
import { CommonModule } from '../../modules/common/common.module';
|
||||
|
||||
import { DevPlanModule } from '../../modules/dev-plan/dev-plan.module';
|
||||
|
||||
import { SettlementModule } from '../../modules/settlement/settlement.module';
|
||||
|
||||
import { IntegrationsModule } from '../integrations.module';
|
||||
|
||||
import { LlmModule } from '../llm/llm.module';
|
||||
|
||||
import { WecomAibotService } from './wecom-aibot.service';
|
||||
|
||||
import { WecomBotActionsService } from './wecom-bot-actions.service';
|
||||
|
||||
import { WecomBotAiService } from './wecom-bot-ai.service';
|
||||
|
||||
import { WecomBotAuditService } from './wecom-bot-audit.service';
|
||||
|
||||
import { WecomBotCapabilityService } from './wecom-bot-capability.service';
|
||||
|
||||
import { WecomBotSessionService } from './wecom-bot-session.service';
|
||||
|
||||
|
||||
|
||||
/** 企微多机器人:依赖 Common(工单)+ Settlement/DevPlan + Integrations(短信)+ Llm */
|
||||
|
||||
@Module({
|
||||
|
||||
imports: [
|
||||
|
||||
forwardRef(() => CommonModule),
|
||||
|
||||
@@ -5,6 +5,7 @@ import { AlertService } from '../../common/alert/alert.service';
|
||||
import type { AlertLevel } from '../../common/alert/alert.constants';
|
||||
import type { AuthUser } from '../../common/guards/jwt-auth.guard';
|
||||
import type { ReportClientErrorDto } from './dto/client-error.dto';
|
||||
import { SupportTicketService } from './support-ticket.service';
|
||||
|
||||
const WECOM_LEVELS = new Set(['fatal', 'error']);
|
||||
|
||||
@@ -15,6 +16,7 @@ export class ClientErrorService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly alert: AlertService,
|
||||
private readonly supportTicket: SupportTicketService,
|
||||
) {}
|
||||
|
||||
async report(dto: ReportClientErrorDto, user?: AuthUser, headerClientApp?: string) {
|
||||
@@ -107,6 +109,25 @@ export class ClientErrorService {
|
||||
);
|
||||
}
|
||||
|
||||
if (dto.category === 'validation_error') {
|
||||
const apiPath =
|
||||
dto.extra && typeof dto.extra.url === 'string' ? dto.extra.url.slice(0, 256) : undefined;
|
||||
void this.supportTicket
|
||||
.createFromClientValidation({
|
||||
clientApp,
|
||||
message,
|
||||
pagePath,
|
||||
apiPath,
|
||||
actorLabel:
|
||||
user?.actorId != null ? `${user.actorType}:${String(user.actorId)}` : undefined,
|
||||
})
|
||||
.catch((e) => {
|
||||
this.logger.warn(
|
||||
`auto support ticket failed: ${e instanceof Error ? e.message : String(e)}`,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
return { ok: true };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { IamModule } from '../iam/iam.module';
|
||||
import { AnalyticsModule } from '../analytics/analytics.module';
|
||||
import { IntegrationsModule } from '../../integrations/integrations.module';
|
||||
import { SystemConfigModule } from '../../common/system-config/system-config.module';
|
||||
import { DevPlanModule } from '../dev-plan/dev-plan.module';
|
||||
import { ResourceService } from './resource.service';
|
||||
import { EventService } from './event.service';
|
||||
import { TicketService } from './ticket.service';
|
||||
@@ -20,7 +21,7 @@ import { ClientErrorService } from './client-error.service';
|
||||
import { ClientErrorController } from './client-error.controller';
|
||||
|
||||
@Module({
|
||||
imports: [forwardRef(() => IamModule), IntegrationsModule, SystemConfigModule, forwardRef(() => AnalyticsModule)],
|
||||
imports: [forwardRef(() => IamModule), IntegrationsModule, SystemConfigModule, forwardRef(() => AnalyticsModule), DevPlanModule],
|
||||
controllers: [
|
||||
ResourceController,
|
||||
EventController,
|
||||
|
||||
@@ -9,6 +9,7 @@ export const CLIENT_ERROR_CATEGORIES = [
|
||||
'js_error',
|
||||
'unhandled_rejection',
|
||||
'api_error',
|
||||
'validation_error',
|
||||
'network',
|
||||
'render',
|
||||
'bridge',
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { IsIn, IsNotEmpty, IsOptional, IsString, MaxLength } from 'class-validator';
|
||||
import { ArrayMinSize, IsArray, IsBoolean, IsIn, IsNotEmpty, IsOptional, IsString, MaxLength, ValidateIf, ValidateNested } from 'class-validator';
|
||||
import { Type } from 'class-transformer';
|
||||
import { IsInt, Min } from 'class-validator';
|
||||
|
||||
@@ -41,6 +41,84 @@ export class CreateSupportTicketDto {
|
||||
@IsString()
|
||||
@MaxLength(512)
|
||||
remark?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@IsString({ each: true })
|
||||
attachmentUrls?: string[];
|
||||
}
|
||||
|
||||
export class UpdateSupportTicketDto {
|
||||
@IsOptional()
|
||||
@IsIn(['BUG', 'SUGGESTION', 'OTHER'])
|
||||
ticketType?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@MaxLength(128)
|
||||
title?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
content?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(512)
|
||||
remark?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@IsString({ each: true })
|
||||
attachmentUrls?: string[];
|
||||
}
|
||||
|
||||
export class BatchUpdateSupportTicketStatusDto {
|
||||
@IsArray()
|
||||
@ArrayMinSize(1)
|
||||
@IsString({ each: true })
|
||||
ticketIds!: string[];
|
||||
|
||||
@IsIn(['PENDING_REVIEW', 'REJECTED', 'DEVELOPING', 'TESTING', 'PASSED'])
|
||||
status!: string;
|
||||
|
||||
@ValidateIf((o: BatchUpdateSupportTicketStatusDto) => o.status === 'REJECTED')
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@MaxLength(512)
|
||||
rejectReason?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(512)
|
||||
note?: string;
|
||||
}
|
||||
|
||||
export class BatchCreateSupportTicketTasksDto {
|
||||
@IsArray()
|
||||
@ArrayMinSize(1)
|
||||
@IsString({ each: true })
|
||||
ticketIds!: string[];
|
||||
}
|
||||
|
||||
export class BatchPublishSupportTicketsDto {
|
||||
@IsArray()
|
||||
@ArrayMinSize(1)
|
||||
@IsString({ each: true })
|
||||
ticketIds!: string[];
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
versionId!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
dispatchToWecom?: boolean;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
dispatchSupplement?: string;
|
||||
}
|
||||
|
||||
export class RejectSupportTicketDto {
|
||||
|
||||
@@ -5,25 +5,55 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import type { SupportTicketStatus, SupportTicketType } from '@prisma/client';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import type { CreateDevPlanTaskFromTicketInput } from '@dukang/shared-types';
|
||||
import { mapSupportTicketTypeToDevPlanTask } from '@dukang/shared-types';
|
||||
import { validateSupportTicketStatusTransition } from '@dukang/domain';
|
||||
import { PrismaService } from '../../common/prisma/prisma.module';
|
||||
import { serializeBigInt } from '../../common/decorators/current-user.decorator';
|
||||
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 {
|
||||
CreateSupportTicketDto,
|
||||
RejectSupportTicketDto,
|
||||
SupportTicketListQueryDto,
|
||||
SupportTicketRemarkDto,
|
||||
UpdateSupportTicketDto,
|
||||
} from './dto/support-ticket.dto';
|
||||
|
||||
function normalizeAttachmentUrls(raw: unknown): string[] | null {
|
||||
if (!Array.isArray(raw)) return null;
|
||||
const urls = raw.map((u) => String(u || '').trim()).filter(Boolean);
|
||||
return urls.length ? urls : null;
|
||||
}
|
||||
|
||||
function mapSupportTicketRow<T extends { attachmentUrls?: unknown }>(ticket: T) {
|
||||
return {
|
||||
...ticket,
|
||||
attachmentUrls: normalizeAttachmentUrls(ticket.attachmentUrls),
|
||||
};
|
||||
}
|
||||
|
||||
function generateSupportTicketNo() {
|
||||
return `ST${Date.now()}${Math.floor(Math.random() * 900 + 100)}`;
|
||||
}
|
||||
|
||||
const AUTO_VALIDATION_TICKET_APPS = new Set([
|
||||
'USER_H5',
|
||||
'USER_MINI',
|
||||
'SHOP_H5',
|
||||
'PARTNER_H5',
|
||||
]);
|
||||
|
||||
@Injectable()
|
||||
export class SupportTicketService {
|
||||
private systemCreatorCache: { id: bigint; name: string } | null = null;
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly alert: AlertService,
|
||||
private readonly devPlan: DevPlanService,
|
||||
private readonly wecomPush: WecomMessagePushService,
|
||||
) {}
|
||||
|
||||
async create(
|
||||
@@ -38,6 +68,9 @@ export class SupportTicketService {
|
||||
title: dto.title.trim(),
|
||||
content: dto.content?.trim() || null,
|
||||
remark: dto.remark?.trim() || null,
|
||||
attachmentUrls: dto.attachmentUrls?.length
|
||||
? (dto.attachmentUrls.map((u) => u.trim()).filter(Boolean) as unknown as Prisma.InputJsonValue)
|
||||
: undefined,
|
||||
creatorId: creator.id,
|
||||
creatorName: creator.name,
|
||||
},
|
||||
@@ -48,8 +81,160 @@ export class SupportTicketService {
|
||||
title: '新建技术支持工单',
|
||||
detail: `工单 ${ticket.ticketNo}\n类型 ${ticket.ticketType}\n标题 ${ticket.title}\n创建人 ${creator.name}`,
|
||||
dedupeKey: `support_ticket_create|${ticket.ticketNo}`,
|
||||
eventKeys: ['alert.ops'],
|
||||
});
|
||||
return serializeBigInt(ticket);
|
||||
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(mapSupportTicketRow(ticket));
|
||||
}
|
||||
|
||||
/** 客户端 400 验证错误自动建单(1 小时内同标题去重) */
|
||||
async createFromClientValidation(input: {
|
||||
clientApp: string;
|
||||
message: string;
|
||||
pagePath?: string;
|
||||
apiPath?: string;
|
||||
actorLabel?: string;
|
||||
}) {
|
||||
if (!AUTO_VALIDATION_TICKET_APPS.has(input.clientApp)) {
|
||||
return { skipped: true as const, reason: 'unsupported_app' as const };
|
||||
}
|
||||
|
||||
const title = `[客户端验证] ${input.clientApp}${input.pagePath ? ` · ${input.pagePath}` : ''} · ${input.message.slice(0, 60)}`;
|
||||
const oneHourAgo = new Date(Date.now() - 3600_000);
|
||||
const existing = await this.prisma.commonSupportTicket.findFirst({
|
||||
where: { title, createdAt: { gte: oneHourAgo } },
|
||||
select: { id: true },
|
||||
});
|
||||
if (existing) {
|
||||
return { skipped: true as const, ticketId: existing.id.toString() };
|
||||
}
|
||||
|
||||
const creator = await this.resolveSystemCreator();
|
||||
const content = [
|
||||
`端:${input.clientApp}`,
|
||||
input.pagePath ? `页面:${input.pagePath}` : null,
|
||||
input.apiPath ? `接口:${input.apiPath}` : null,
|
||||
input.actorLabel ? `用户:${input.actorLabel}` : null,
|
||||
'',
|
||||
input.message,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join('\n');
|
||||
|
||||
const ticket = await this.create(
|
||||
{
|
||||
ticketType: 'BUG',
|
||||
title,
|
||||
content,
|
||||
remark: '客户端验证错误自动上报',
|
||||
},
|
||||
creator,
|
||||
);
|
||||
return { skipped: false as const, ticketId: String(ticket.id) };
|
||||
}
|
||||
|
||||
private async resolveSystemCreator() {
|
||||
if (this.systemCreatorCache) return this.systemCreatorCache;
|
||||
const account = await this.prisma.hqAccount.findFirst({
|
||||
where: { adminRole: 'SUPER_ADMIN', status: 'ACTIVE' },
|
||||
orderBy: { id: 'asc' },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!account) {
|
||||
throw new BadRequestException('未找到系统管理员账号,无法自动创建工单');
|
||||
}
|
||||
this.systemCreatorCache = { id: account.id, name: '系统自动' };
|
||||
return this.systemCreatorCache;
|
||||
}
|
||||
|
||||
async update(id: bigint, dto: UpdateSupportTicketDto) {
|
||||
const ticket = await this.getOrThrow(id);
|
||||
if (ticket.status !== 'PENDING_REVIEW') {
|
||||
throw new BadRequestException('仅待评审工单可编辑');
|
||||
}
|
||||
const data: Prisma.CommonSupportTicketUpdateInput = {};
|
||||
if (dto.ticketType != null) data.ticketType = dto.ticketType as SupportTicketType;
|
||||
if (dto.title != null) data.title = dto.title.trim();
|
||||
if (dto.content !== undefined) data.content = dto.content?.trim() || null;
|
||||
if (dto.remark !== undefined) data.remark = dto.remark?.trim() || null;
|
||||
if (dto.attachmentUrls !== undefined) {
|
||||
const urls = dto.attachmentUrls.map((u) => u.trim()).filter(Boolean);
|
||||
data.attachmentUrls = urls.length ? (urls as unknown as Prisma.InputJsonValue) : Prisma.JsonNull;
|
||||
}
|
||||
const updated = await this.prisma.commonSupportTicket.update({ where: { id }, data });
|
||||
return serializeBigInt(mapSupportTicketRow(updated));
|
||||
}
|
||||
|
||||
async batchUpdateStatus(
|
||||
ticketIds: bigint[],
|
||||
status: SupportTicketStatus,
|
||||
ctx: {
|
||||
isSuperAdmin: boolean;
|
||||
rejectReason?: string;
|
||||
note?: string;
|
||||
reviewer?: { id: bigint; name: string };
|
||||
},
|
||||
) {
|
||||
const results: Array<{ ticketId: string; ok: boolean; message?: string }> = [];
|
||||
for (const id of ticketIds) {
|
||||
try {
|
||||
const ticket = await this.getOrThrow(id);
|
||||
const linkedMap = await this.devPlan.listLinkedTasksByTicketIds([id]);
|
||||
const linkedTaskCount = linkedMap.get(String(id))?.length ?? 0;
|
||||
const guard = validateSupportTicketStatusTransition(
|
||||
ticket.status as 'PENDING_REVIEW' | 'REJECTED' | 'DEVELOPING' | 'TESTING' | 'PASSED',
|
||||
status as 'PENDING_REVIEW' | 'REJECTED' | 'DEVELOPING' | 'TESTING' | 'PASSED',
|
||||
{
|
||||
linkedTaskCount,
|
||||
isSuperAdmin: ctx.isSuperAdmin,
|
||||
rejectReason: ctx.rejectReason,
|
||||
},
|
||||
);
|
||||
if (!guard.ok) {
|
||||
results.push({ ticketId: String(id), ok: false, message: guard.message });
|
||||
continue;
|
||||
}
|
||||
const data: Prisma.CommonSupportTicketUpdateInput = { status };
|
||||
if (ctx.note?.trim()) data.remark = ctx.note.trim();
|
||||
if (status === 'REJECTED') {
|
||||
data.rejectReason = ctx.rejectReason!.trim();
|
||||
data.completedAt = new Date();
|
||||
if (ctx.reviewer) {
|
||||
data.reviewerId = ctx.reviewer.id;
|
||||
data.reviewerName = ctx.reviewer.name;
|
||||
data.reviewedAt = new Date();
|
||||
}
|
||||
}
|
||||
if (status === 'PASSED') data.completedAt = new Date();
|
||||
await this.prisma.commonSupportTicket.update({ where: { id }, data });
|
||||
results.push({ ticketId: String(id), ok: true });
|
||||
} catch (err) {
|
||||
results.push({
|
||||
ticketId: String(id),
|
||||
ok: false,
|
||||
message: err instanceof Error ? err.message : '更新失败',
|
||||
});
|
||||
}
|
||||
}
|
||||
const successCount = results.filter((r) => r.ok).length;
|
||||
return { results, successCount, failCount: results.length - successCount };
|
||||
}
|
||||
|
||||
async list(query: SupportTicketListQueryDto) {
|
||||
@@ -72,13 +257,32 @@ export class SupportTicketService {
|
||||
}),
|
||||
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) => ({
|
||||
...mapSupportTicketRow(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) {
|
||||
const ticket = await this.prisma.commonSupportTicket.findUnique({ where: { id } });
|
||||
if (!ticket) throw new NotFoundException('技术支持工单不存在');
|
||||
return serializeBigInt(ticket);
|
||||
const linkedMap = await this.devPlan.listLinkedTasksByTicketIds([id]);
|
||||
return serializeBigInt({
|
||||
...mapSupportTicketRow(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) {
|
||||
@@ -137,6 +341,223 @@ export class SupportTicketService {
|
||||
return serializeBigInt(updated);
|
||||
}
|
||||
|
||||
/** 统一审批:通过时创建开发计划任务 */
|
||||
async review(
|
||||
id: bigint,
|
||||
reviewer: { id: bigint; name: string },
|
||||
input: {
|
||||
decision: 'APPROVE' | 'REJECT';
|
||||
rejectReason?: string;
|
||||
note?: string;
|
||||
tasks?: CreateDevPlanTaskFromTicketInput[];
|
||||
dispatchToWecom?: boolean;
|
||||
dispatchSupplement?: string;
|
||||
},
|
||||
) {
|
||||
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('仅待评审工单可审批');
|
||||
}
|
||||
|
||||
const createdTasks = 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,
|
||||
},
|
||||
});
|
||||
|
||||
if (input.dispatchToWecom) {
|
||||
try {
|
||||
await this.devPlan.dispatchTasks(
|
||||
{
|
||||
taskIds: createdTasks.map((t) => t.id),
|
||||
supplement: input.dispatchSupplement,
|
||||
},
|
||||
reviewer.id,
|
||||
);
|
||||
} catch (err) {
|
||||
this.alert.notify({
|
||||
level: 'P2',
|
||||
category: 'ops',
|
||||
title: '审批后企微派发失败',
|
||||
detail: `工单 ${ticket.ticketNo}\n${err instanceof Error ? err.message : String(err)}`,
|
||||
dedupeKey: `support_review_dispatch_fail|${ticket.ticketNo}`,
|
||||
dedupeTtlSec: 120,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const linkedMap = await this.devPlan.listLinkedTasksByTicketIds([id]);
|
||||
return serializeBigInt({
|
||||
...mapSupportTicketRow(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 };
|
||||
}
|
||||
|
||||
/** 批量一键创建开发任务(每工单 1 条,内容取自标题/说明) */
|
||||
async batchCreateTasks(
|
||||
ticketIds: bigint[],
|
||||
operator: { id: bigint; name: string },
|
||||
) {
|
||||
const results: Array<{
|
||||
ticketId: string;
|
||||
ok: boolean;
|
||||
message?: string;
|
||||
taskIds?: string[];
|
||||
}> = [];
|
||||
|
||||
for (const id of ticketIds) {
|
||||
try {
|
||||
const ticket = await this.getOrThrow(id);
|
||||
const linkedMap = await this.devPlan.listLinkedTasksByTicketIds([id]);
|
||||
const existing = linkedMap.get(String(id)) ?? [];
|
||||
if (existing.length > 0) {
|
||||
results.push({ ticketId: String(id), ok: false, message: '已有开发任务,已跳过' });
|
||||
continue;
|
||||
}
|
||||
|
||||
const summary = [ticket.title, ticket.content].filter(Boolean).join('\n').slice(0, 500);
|
||||
const createdTasks = await this.devPlan.createTasksFromTicket(
|
||||
id,
|
||||
[
|
||||
{
|
||||
content: summary || ticket.title,
|
||||
type: mapSupportTicketTypeToDevPlanTask(ticket.ticketType as 'BUG' | 'SUGGESTION' | 'OTHER'),
|
||||
},
|
||||
],
|
||||
operator.id,
|
||||
);
|
||||
|
||||
if (ticket.status === 'PENDING_REVIEW') {
|
||||
await this.prisma.commonSupportTicket.update({
|
||||
where: { id },
|
||||
data: {
|
||||
status: 'DEVELOPING',
|
||||
reviewerId: operator.id,
|
||||
reviewerName: operator.name,
|
||||
reviewedAt: new Date(),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
results.push({
|
||||
ticketId: String(id),
|
||||
ok: true,
|
||||
taskIds: createdTasks.map((t) => t.id),
|
||||
});
|
||||
} catch (err) {
|
||||
results.push({
|
||||
ticketId: String(id),
|
||||
ok: false,
|
||||
message: err instanceof Error ? err.message : '创建失败',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const successCount = results.filter((r) => r.ok).length;
|
||||
return { results, successCount, failCount: results.length - successCount };
|
||||
}
|
||||
|
||||
/** 批量一键发布:关联开发版本,可选企微派发 */
|
||||
async batchPublish(
|
||||
ticketIds: bigint[],
|
||||
input: {
|
||||
versionId: string;
|
||||
dispatchToWecom?: boolean;
|
||||
dispatchSupplement?: string;
|
||||
},
|
||||
operator: { id: bigint; name: string },
|
||||
) {
|
||||
const perTicket: Array<{ ticketId: string; ok: boolean; message?: string }> = [];
|
||||
const taskIdSet = new Set<string>();
|
||||
|
||||
for (const id of ticketIds) {
|
||||
const linkedMap = await this.devPlan.listLinkedTasksByTicketIds([id]);
|
||||
const linked = linkedMap.get(String(id)) ?? [];
|
||||
if (!linked.length) {
|
||||
perTicket.push({ ticketId: String(id), ok: false, message: '无关联开发任务' });
|
||||
continue;
|
||||
}
|
||||
linked.forEach((t) => taskIdSet.add(t.id));
|
||||
perTicket.push({ ticketId: String(id), ok: true });
|
||||
}
|
||||
|
||||
const taskIds = [...taskIdSet];
|
||||
if (!taskIds.length) {
|
||||
return {
|
||||
results: perTicket,
|
||||
successCount: 0,
|
||||
failCount: perTicket.length,
|
||||
linkedTaskCount: 0,
|
||||
};
|
||||
}
|
||||
|
||||
await this.devPlan.batchUpdateTasks({ taskIds, versionId: input.versionId });
|
||||
|
||||
if (input.dispatchToWecom) {
|
||||
try {
|
||||
await this.devPlan.dispatchTasks(
|
||||
{ taskIds, supplement: input.dispatchSupplement },
|
||||
operator.id,
|
||||
);
|
||||
} catch (err) {
|
||||
this.alert.notify({
|
||||
level: 'P2',
|
||||
category: 'ops',
|
||||
title: '批量发布企微派发失败',
|
||||
detail: err instanceof Error ? err.message : String(err),
|
||||
dedupeKey: `support_batch_publish_dispatch_fail|${Date.now()}`,
|
||||
dedupeTtlSec: 120,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const successCount = perTicket.filter((r) => r.ok).length;
|
||||
return {
|
||||
results: perTicket,
|
||||
successCount,
|
||||
failCount: perTicket.length - successCount,
|
||||
linkedTaskCount: taskIds.length,
|
||||
versionId: input.versionId,
|
||||
};
|
||||
}
|
||||
|
||||
/** 开发完成 → 测试 */
|
||||
async startTesting(id: bigint, dto?: SupportTicketRemarkDto) {
|
||||
const ticket = await this.getOrThrow(id);
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
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,
|
||||
DevPlanTaskBatchUpdateDto,
|
||||
} 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);
|
||||
}
|
||||
|
||||
@Post('tasks/batch-update')
|
||||
@HqOperation({ action: HqOperationAction.DEV_PLAN_TASK_UPDATE, refType: 'DEV_PLAN_TASK', includeBody: true, batch: true })
|
||||
batchUpdateTasks(@Body() body: DevPlanTaskBatchUpdateDto) {
|
||||
return this.service.batchUpdateTasks(body);
|
||||
}
|
||||
|
||||
@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,195 @@
|
||||
import { ArrayMinSize, IsArray, IsBoolean, 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[];
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
dispatchToWecom?: boolean;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
dispatchSupplement?: string;
|
||||
}
|
||||
|
||||
export class DevPlanTaskBatchUpdateDto {
|
||||
@IsArray()
|
||||
@ArrayMinSize(1)
|
||||
@IsString({ each: true })
|
||||
taskIds!: string[];
|
||||
|
||||
@IsOptional()
|
||||
@IsIn(DEV_PLAN_TASK_STATUSES)
|
||||
status?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
versionId?: string | null;
|
||||
}
|
||||
|
||||
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 }],
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import type {
|
||||
CreateKnowledgeBaseRequest,
|
||||
CreateKnowledgeDocumentRequest,
|
||||
UpdateKnowledgeBaseRequest,
|
||||
UpdateKnowledgeDocumentRequest,
|
||||
} from '@dukang/shared-types';
|
||||
import { HqAuthGuard } from '../../common/guards/hq-auth.guard';
|
||||
import {
|
||||
@@ -119,6 +120,33 @@ export class AdminKnowledgeBasesController {
|
||||
return this.service.addDocument(actor, BigInt(id), body);
|
||||
}
|
||||
|
||||
@Get(':id/documents/:docId')
|
||||
async getDocument(
|
||||
@CurrentUser() user: AuthUser,
|
||||
@Param('id') id: string,
|
||||
@Param('docId') docId: string,
|
||||
) {
|
||||
const actor = await this.service.resolveActor(user.actorId);
|
||||
return this.service.getDocument(actor, BigInt(id), BigInt(docId));
|
||||
}
|
||||
|
||||
@Put(':id/documents/:docId')
|
||||
@HqOperation({
|
||||
action: HqOperationAction.KNOWLEDGE_DOC_UPDATE,
|
||||
refType: 'KNOWLEDGE_DOCUMENT',
|
||||
refIdField: 'docId',
|
||||
includeBody: true,
|
||||
})
|
||||
async updateDocument(
|
||||
@CurrentUser() user: AuthUser,
|
||||
@Param('id') id: string,
|
||||
@Param('docId') docId: string,
|
||||
@Body() body: UpdateKnowledgeDocumentRequest,
|
||||
) {
|
||||
const actor = await this.service.resolveActor(user.actorId);
|
||||
return this.service.updateDocument(actor, BigInt(id), BigInt(docId), body);
|
||||
}
|
||||
|
||||
@Delete(':id/documents/:docId')
|
||||
@HqOperation({
|
||||
action: HqOperationAction.KNOWLEDGE_DOC_DELETE,
|
||||
|
||||
@@ -9,8 +9,10 @@ import type {
|
||||
CreateKnowledgeDocumentRequest,
|
||||
KnowledgeBaseDto,
|
||||
KnowledgeBaseOptionDto,
|
||||
KnowledgeDocumentDetailDto,
|
||||
KnowledgeDocumentDto,
|
||||
UpdateKnowledgeBaseRequest,
|
||||
UpdateKnowledgeDocumentRequest,
|
||||
} from '@dukang/shared-types';
|
||||
import { PrismaService } from '../../common/prisma/prisma.module';
|
||||
import { serializeBigInt } from '../../common/decorators/current-user.decorator';
|
||||
@@ -228,6 +230,113 @@ export class AdminKnowledgeBasesService {
|
||||
return this.toDocDto(row);
|
||||
}
|
||||
|
||||
async getDocument(actor: ActorCtx, kbId: bigint, docId: bigint): Promise<KnowledgeDocumentDetailDto> {
|
||||
await this.requireKb(actor, kbId);
|
||||
const doc = await this.prisma.knowledgeDocument.findFirst({
|
||||
where: { id: docId, knowledgeBaseId: kbId },
|
||||
});
|
||||
if (!doc) throw new NotFoundException('文档不存在');
|
||||
return {
|
||||
...this.toDocDto(doc),
|
||||
contentText: doc.contentText,
|
||||
};
|
||||
}
|
||||
|
||||
async updateDocument(
|
||||
actor: ActorCtx,
|
||||
kbId: bigint,
|
||||
docId: bigint,
|
||||
dto: UpdateKnowledgeDocumentRequest,
|
||||
) {
|
||||
const kb = await this.requireKb(actor, kbId);
|
||||
this.requireWrite(actor, kb);
|
||||
const doc = await this.prisma.knowledgeDocument.findFirst({
|
||||
where: { id: docId, knowledgeBaseId: kbId },
|
||||
});
|
||||
if (!doc) throw new NotFoundException('文档不存在');
|
||||
|
||||
const data: {
|
||||
title?: string;
|
||||
fileName?: string | null;
|
||||
fileUrl?: string | null;
|
||||
mimeType?: string | null;
|
||||
sizeBytes?: number | null;
|
||||
contentText?: string | null;
|
||||
status?: 'READY' | 'EMPTY' | 'FAILED';
|
||||
errorMessage?: string | null;
|
||||
} = {};
|
||||
|
||||
if (dto.title !== undefined) {
|
||||
const title = dto.title.trim();
|
||||
if (!title) throw new BadRequestException('请填写标题');
|
||||
data.title = title;
|
||||
}
|
||||
|
||||
const hasContentInput =
|
||||
dto.contentText !== undefined ||
|
||||
dto.fileUrl !== undefined ||
|
||||
dto.fileName !== undefined ||
|
||||
dto.mimeType !== undefined;
|
||||
|
||||
if (hasContentInput) {
|
||||
let contentText = dto.contentText !== undefined ? dto.contentText?.trim() || '' : doc.contentText?.trim() || '';
|
||||
let status: 'READY' | 'EMPTY' | 'FAILED' = doc.status as 'READY' | 'EMPTY' | 'FAILED';
|
||||
let errorMessage: string | null = doc.errorMessage;
|
||||
|
||||
if (dto.contentText !== undefined) {
|
||||
if (contentText) {
|
||||
status = 'READY';
|
||||
errorMessage = null;
|
||||
} else if (!dto.fileUrl?.trim() && !doc.fileUrl) {
|
||||
status = 'EMPTY';
|
||||
errorMessage = null;
|
||||
}
|
||||
data.contentText = contentText || null;
|
||||
}
|
||||
|
||||
if (dto.fileUrl !== undefined) data.fileUrl = dto.fileUrl?.trim() || null;
|
||||
if (dto.fileName !== undefined) data.fileName = dto.fileName?.trim() || null;
|
||||
if (dto.mimeType !== undefined) data.mimeType = dto.mimeType?.trim() || null;
|
||||
if (dto.sizeBytes !== undefined) data.sizeBytes = dto.sizeBytes ?? null;
|
||||
|
||||
const fileUrl = dto.fileUrl?.trim() || doc.fileUrl;
|
||||
const fileName = dto.fileName?.trim() || doc.fileName || '';
|
||||
const mimeType = dto.mimeType?.trim() || doc.mimeType;
|
||||
|
||||
if (dto.fileUrl?.trim() && dto.contentText === undefined) {
|
||||
if (TEXT_EXT.test(fileName) || isLikelyTextMime(mimeType)) {
|
||||
try {
|
||||
contentText = await fetchText(dto.fileUrl.trim());
|
||||
data.contentText = contentText || null;
|
||||
status = contentText.trim() ? 'READY' : 'EMPTY';
|
||||
errorMessage = contentText.trim() ? null : '文件内容为空';
|
||||
} catch (e) {
|
||||
status = 'FAILED';
|
||||
errorMessage = e instanceof Error ? e.message : String(e);
|
||||
}
|
||||
} else {
|
||||
status = 'EMPTY';
|
||||
errorMessage = '非文本文件未抽取正文,请粘贴文本或上传 .txt/.md';
|
||||
}
|
||||
} else if (dto.contentText !== undefined && contentText) {
|
||||
status = 'READY';
|
||||
errorMessage = null;
|
||||
} else if (dto.contentText !== undefined && !contentText && !fileUrl) {
|
||||
status = 'EMPTY';
|
||||
errorMessage = null;
|
||||
}
|
||||
|
||||
data.status = status;
|
||||
data.errorMessage = errorMessage;
|
||||
}
|
||||
|
||||
const updated = await this.prisma.knowledgeDocument.update({
|
||||
where: { id: docId },
|
||||
data,
|
||||
});
|
||||
return this.toDocDto(updated);
|
||||
}
|
||||
|
||||
async removeDocument(actor: ActorCtx, kbId: bigint, docId: bigint) {
|
||||
const kb = await this.requireKb(actor, kbId);
|
||||
this.requireWrite(actor, kb);
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
Get,
|
||||
NotFoundException,
|
||||
Param,
|
||||
Patch,
|
||||
Post,
|
||||
Query,
|
||||
UseGuards,
|
||||
@@ -16,18 +17,29 @@ 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 { SupportTicketService } from '../common/support-ticket.service';
|
||||
import { SupportTicketReviewAiService } from '../dev-plan/support-ticket-review-ai.service';
|
||||
import {
|
||||
CreateSupportTicketDto,
|
||||
RejectSupportTicketDto,
|
||||
SupportTicketListQueryDto,
|
||||
SupportTicketRemarkDto,
|
||||
UpdateSupportTicketDto,
|
||||
BatchUpdateSupportTicketStatusDto,
|
||||
BatchCreateSupportTicketTasksDto,
|
||||
BatchPublishSupportTicketsDto,
|
||||
} from '../common/dto/support-ticket.dto';
|
||||
import {
|
||||
BatchReviewConfirmDto,
|
||||
BatchReviewPreviewDto,
|
||||
ReviewSupportTicketDto,
|
||||
} from '../dev-plan/dto/dev-plan.dto';
|
||||
|
||||
@Controller('admin/support-tickets')
|
||||
@UseGuards(HqAuthGuard)
|
||||
export class AdminSupportTicketsController {
|
||||
constructor(
|
||||
private readonly service: SupportTicketService,
|
||||
private readonly reviewAi: SupportTicketReviewAiService,
|
||||
private readonly prisma: PrismaService,
|
||||
) {}
|
||||
|
||||
@@ -57,11 +69,95 @@ export class AdminSupportTicketsController {
|
||||
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);
|
||||
}
|
||||
|
||||
@Post('batch-update-status')
|
||||
@UseGuards(SuperAdminGuard)
|
||||
async batchUpdateStatus(
|
||||
@CurrentUser() user: AuthUser,
|
||||
@Body() body: BatchUpdateSupportTicketStatusDto,
|
||||
) {
|
||||
const account = await this.resolveHqAccount(user);
|
||||
const profile = await this.prisma.hqAccount.findUnique({
|
||||
where: { id: user.actorId },
|
||||
select: { adminRole: true },
|
||||
});
|
||||
return this.service.batchUpdateStatus(
|
||||
body.ticketIds.map(BigInt),
|
||||
body.status as never,
|
||||
{
|
||||
isSuperAdmin: profile?.adminRole === 'SUPER_ADMIN',
|
||||
rejectReason: body.rejectReason,
|
||||
note: body.note,
|
||||
reviewer: account,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@Post('batch-create-tasks')
|
||||
@UseGuards(SuperAdminGuard)
|
||||
async batchCreateTasks(
|
||||
@CurrentUser() user: AuthUser,
|
||||
@Body() body: BatchCreateSupportTicketTasksDto,
|
||||
) {
|
||||
const account = await this.resolveHqAccount(user);
|
||||
return this.service.batchCreateTasks(body.ticketIds.map(BigInt), account);
|
||||
}
|
||||
|
||||
@Post('batch-publish')
|
||||
@UseGuards(SuperAdminGuard)
|
||||
async batchPublish(
|
||||
@CurrentUser() user: AuthUser,
|
||||
@Body() body: BatchPublishSupportTicketsDto,
|
||||
) {
|
||||
const account = await this.resolveHqAccount(user);
|
||||
return this.service.batchPublish(body.ticketIds.map(BigInt), body, account);
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
detail(@Param('id') id: string) {
|
||||
return this.service.detail(BigInt(id));
|
||||
}
|
||||
|
||||
@Patch(':id')
|
||||
async update(@Param('id') id: string, @Body() body: UpdateSupportTicketDto) {
|
||||
return this.service.update(BigInt(id), body);
|
||||
}
|
||||
|
||||
@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')
|
||||
@UseGuards(SuperAdminGuard)
|
||||
@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 {
|
||||
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 { SystemConfigService } from '../../common/system-config/system-config.service';
|
||||
import { WecomAibotService } from '../../integrations/wecom/wecom-aibot.service';
|
||||
import { AlertService } from '../../common/alert/alert.service';
|
||||
|
||||
@Controller('admin/system-config')
|
||||
@UseGuards(HqAuthGuard, HqPermissionGuard)
|
||||
@@ -27,7 +26,6 @@ export class AdminSystemConfigController {
|
||||
private readonly systemConfig: SystemConfigService,
|
||||
private readonly permissions: HqPermissionsResolver,
|
||||
private readonly wecomAibot: WecomAibotService,
|
||||
private readonly alert: AlertService,
|
||||
) {}
|
||||
|
||||
@Get()
|
||||
@@ -79,22 +77,6 @@ export class AdminSystemConfigController {
|
||||
importEnv() {
|
||||
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 {
|
||||
|
||||
@@ -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,
|
||||
Delete,
|
||||
Get,
|
||||
NotFoundException,
|
||||
Param,
|
||||
Post,
|
||||
Put,
|
||||
Query,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import type { CreateWecomBotRequest, UpdateWecomBotRequest } from '@dukang/shared-types';
|
||||
import { HqAuthGuard } from '../../common/guards/hq-auth.guard';
|
||||
import {
|
||||
HqPermissionGuard,
|
||||
RequireHqPermissions,
|
||||
} from '../../common/guards/hq-permission.guard';
|
||||
import { SuperAdminGuard } from '../../common/guards/super-admin.guard';
|
||||
import { HqOperation } from '../../common/hq-operation/hq-operation.decorator';
|
||||
import { HqOperationAction } from '../../common/hq-operation/hq-operation.constants';
|
||||
import { CurrentUser } from '../../common/decorators/current-user.decorator';
|
||||
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 { AdminLlmConfigsService } from './admin-llm-configs.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')
|
||||
@UseGuards(HqAuthGuard, HqPermissionGuard)
|
||||
@@ -31,6 +36,8 @@ export class AdminWecomBotsController {
|
||||
private readonly service: AdminWecomBotsService,
|
||||
private readonly llmConfigs: AdminLlmConfigsService,
|
||||
private readonly knowledgeBases: AdminKnowledgeBasesService,
|
||||
private readonly supportTicket: SupportTicketService,
|
||||
private readonly prisma: PrismaService,
|
||||
) {}
|
||||
|
||||
@Get()
|
||||
@@ -50,6 +57,11 @@ export class AdminWecomBotsController {
|
||||
});
|
||||
}
|
||||
|
||||
@Get('runtime')
|
||||
runtime() {
|
||||
return this.service.getRuntime();
|
||||
}
|
||||
|
||||
@Post('reload')
|
||||
@HqOperation({
|
||||
action: HqOperationAction.WECOM_BOT_RELOAD,
|
||||
@@ -81,7 +93,7 @@ export class AdminWecomBotsController {
|
||||
refType: 'WECOM_BOT',
|
||||
includeBody: true,
|
||||
})
|
||||
create(@Body() body: CreateWecomBotRequest) {
|
||||
create(@Body() body: CreateWecomBotDto) {
|
||||
return this.service.create(body);
|
||||
}
|
||||
|
||||
@@ -92,7 +104,7 @@ export class AdminWecomBotsController {
|
||||
refIdField: 'id',
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -105,4 +117,53 @@ export class AdminWecomBotsController {
|
||||
remove(@Param('id') id: string) {
|
||||
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';
|
||||
import {
|
||||
WECOM_BOT_ROLES,
|
||||
normalizeWecomBotRole,
|
||||
parseWecomBotPermissions,
|
||||
resolveWecomBotPermissions,
|
||||
type CreateWecomBotRequest,
|
||||
type UpdateWecomBotRequest,
|
||||
parseWecomUserIdList,
|
||||
WECOM_BOT_ROLE_DEFAULT_PERMISSIONS,
|
||||
type WecomBotDto,
|
||||
type WecomBotPermission,
|
||||
type WecomBotRole,
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
import { PrismaService } from '../../common/prisma/prisma.module';
|
||||
import { serializeBigInt } from '../../common/decorators/current-user.decorator';
|
||||
import { WecomAibotService } from '../../integrations/wecom/wecom-aibot.service';
|
||||
import type { CreateWecomBotDto, UpdateWecomBotDto } from './dto/wecom-bot.dto';
|
||||
|
||||
function isWecomRole(v: string): v is WecomBotRole {
|
||||
return (WECOM_BOT_ROLES as readonly string[]).includes(v);
|
||||
@@ -30,6 +31,7 @@ type WecomRow = {
|
||||
avatarUrl: string | null;
|
||||
welcome: string | null;
|
||||
permissions: string;
|
||||
reviewSuperAdminWecomUserIds: string | null;
|
||||
aiEnabled: boolean;
|
||||
llmConfigId: bigint | null;
|
||||
knowledgeBaseId: bigint | null;
|
||||
@@ -81,10 +83,13 @@ export class AdminWecomBotsService {
|
||||
total,
|
||||
page,
|
||||
pageSize,
|
||||
runtime: this.wecomAibot.getStatus(),
|
||||
});
|
||||
}
|
||||
|
||||
getRuntime() {
|
||||
return this.wecomAibot.getStatus();
|
||||
}
|
||||
|
||||
async detail(id: bigint) {
|
||||
const row = await this.prisma.wecomBot.findUnique({
|
||||
where: { id },
|
||||
@@ -97,7 +102,7 @@ export class AdminWecomBotsService {
|
||||
return this.toDto(row);
|
||||
}
|
||||
|
||||
async create(dto: CreateWecomBotRequest) {
|
||||
async create(dto: CreateWecomBotDto) {
|
||||
const name = dto.name?.trim();
|
||||
const botId = dto.botId?.trim();
|
||||
const secret = dto.secret?.trim();
|
||||
@@ -111,7 +116,11 @@ export class AdminWecomBotsService {
|
||||
|
||||
const llmConfigId = await this.resolveLlmId(dto.llmConfigId);
|
||||
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({
|
||||
data: {
|
||||
name,
|
||||
@@ -121,6 +130,7 @@ export class AdminWecomBotsService {
|
||||
avatarUrl: dto.avatarUrl?.trim() || null,
|
||||
welcome: dto.welcome?.trim() || null,
|
||||
permissions: JSON.stringify(permissions),
|
||||
reviewSuperAdminWecomUserIds: reviewIds.length ? JSON.stringify(reviewIds) : null,
|
||||
aiEnabled: dto.aiEnabled === true,
|
||||
llmConfigId,
|
||||
knowledgeBaseId,
|
||||
@@ -136,11 +146,11 @@ export class AdminWecomBotsService {
|
||||
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 } });
|
||||
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('无效角色');
|
||||
|
||||
let botId = existing.botId;
|
||||
@@ -154,18 +164,15 @@ export class AdminWecomBotsService {
|
||||
}
|
||||
|
||||
let permissionsJson = existing.permissions;
|
||||
if (dto.permissions !== undefined || dto.role !== undefined) {
|
||||
const permissions =
|
||||
dto.permissions !== undefined
|
||||
? parseWecomBotPermissions(dto.permissions)
|
||||
: resolveWecomBotPermissions(role, existing.permissions);
|
||||
const finalPerms =
|
||||
dto.permissions !== undefined
|
||||
? permissions.length
|
||||
? permissions
|
||||
: resolveWecomBotPermissions(role, null)
|
||||
: resolveWecomBotPermissions(role, existing.permissions);
|
||||
permissionsJson = JSON.stringify(finalPerms);
|
||||
if (dto.permissions !== undefined) {
|
||||
const permissions = parseWecomBotPermissions(dto.permissions);
|
||||
if (!permissions.length) {
|
||||
throw new BadRequestException('请至少选择一项权限');
|
||||
}
|
||||
permissionsJson = JSON.stringify(permissions);
|
||||
} else if (dto.role !== undefined && dto.role !== normalizeWecomBotRole(existing.role)) {
|
||||
// 仅改角色且未传 permissions 时,保持库内已存权限,不自动覆盖
|
||||
permissionsJson = existing.permissions;
|
||||
}
|
||||
|
||||
const secret =
|
||||
@@ -176,17 +183,24 @@ export class AdminWecomBotsService {
|
||||
const knowledgeBaseId =
|
||||
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({
|
||||
where: { id },
|
||||
data: {
|
||||
name: dto.name !== undefined ? dto.name.trim() : undefined,
|
||||
role: dto.role,
|
||||
role: dto.role ? normalizeWecomBotRole(dto.role) : undefined,
|
||||
botId,
|
||||
secret,
|
||||
avatarUrl:
|
||||
dto.avatarUrl === undefined ? undefined : dto.avatarUrl?.trim() || null,
|
||||
welcome: dto.welcome === undefined ? undefined : dto.welcome?.trim() || null,
|
||||
permissions: permissionsJson,
|
||||
reviewSuperAdminWecomUserIds: reviewIdsJson,
|
||||
aiEnabled: dto.aiEnabled,
|
||||
llmConfigId,
|
||||
knowledgeBaseId,
|
||||
@@ -233,8 +247,10 @@ export class AdminWecomBotsService {
|
||||
}
|
||||
|
||||
private toDto(row: WecomRow): WecomBotDto {
|
||||
const role = (isWecomRole(row.role) ? row.role : 'CUSTOM') as WecomBotRole;
|
||||
const permissions = resolveWecomBotPermissions(role, row.permissions) as WecomBotPermission[];
|
||||
const role = normalizeWecomBotRole(row.role);
|
||||
const stored = parseWecomBotPermissions(row.permissions) as WecomBotPermission[];
|
||||
const permissions =
|
||||
stored.length > 0 ? stored : ([...WECOM_BOT_ROLE_DEFAULT_PERMISSIONS[role]] as WecomBotPermission[]);
|
||||
return {
|
||||
id: row.id.toString(),
|
||||
name: row.name,
|
||||
@@ -244,6 +260,7 @@ export class AdminWecomBotsService {
|
||||
avatarUrl: row.avatarUrl,
|
||||
welcome: row.welcome,
|
||||
permissions,
|
||||
reviewSuperAdminWecomUserIds: parseWecomUserIdList(row.reviewSuperAdminWecomUserIds),
|
||||
aiEnabled: row.aiEnabled,
|
||||
llmConfigId: row.llmConfigId?.toString() ?? 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()
|
||||
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 { AdminWecomBotsController } from './admin-wecom-bots.controller';
|
||||
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 { AdminLlmConfigsService } from './admin-llm-configs.service';
|
||||
import { AdminKnowledgeBasesController } from './admin-knowledge-bases.controller';
|
||||
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 { AdminDomainEventsController } from './admin-domain-events.controller';
|
||||
import { AdminDomainEventsService } from './admin-domain-events.service';
|
||||
|
||||
@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: [
|
||||
AdminDashboardController,
|
||||
AdminDeployController,
|
||||
@@ -116,8 +122,11 @@ import { AdminDomainEventsService } from './admin-domain-events.service';
|
||||
AdminHqPermissionsController,
|
||||
AdminSystemConfigController,
|
||||
AdminWecomBotsController,
|
||||
AdminWecomMessagePushesController,
|
||||
AdminWecomBotLogsController,
|
||||
AdminLlmConfigsController,
|
||||
AdminKnowledgeBasesController,
|
||||
AdminDevPlanController,
|
||||
AdminFulfillmentProvidersController,
|
||||
],
|
||||
providers: [
|
||||
@@ -147,6 +156,8 @@ import { AdminDomainEventsService } from './admin-domain-events.service';
|
||||
AdminHqPermissionsService,
|
||||
AdminDeployService,
|
||||
AdminWecomBotsService,
|
||||
AdminWecomMessagePushesService,
|
||||
AdminWecomBotLogsService,
|
||||
AdminLlmConfigsService,
|
||||
AdminKnowledgeBasesService,
|
||||
SuperAdminGuard,
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Prisma } from '@prisma/client';
|
||||
import {
|
||||
DEFAULT_STORE_WITHDRAW_DAILY_LIMIT,
|
||||
DEFAULT_XFX_LOGISTICS_PRICING,
|
||||
WINERY_SETTLEMENT_LAG_DAYS,
|
||||
WINERY_SETTLEMENT_RATE,
|
||||
} from '@dukang/shared-types';
|
||||
import {
|
||||
@@ -40,6 +41,15 @@ function dayWindow(anchor = new Date()) {
|
||||
return { start, end, billDate: start };
|
||||
}
|
||||
|
||||
function wineryDayWindow(anchor = new Date(), lagDays = WINERY_SETTLEMENT_LAG_DAYS) {
|
||||
const billDate = startOfDay(anchor);
|
||||
billDate.setDate(billDate.getDate() - lagDays);
|
||||
const start = billDate;
|
||||
const end = new Date(start);
|
||||
end.setDate(end.getDate() + 1);
|
||||
return { start, end, billDate: start };
|
||||
}
|
||||
|
||||
function round2(n: number) {
|
||||
return Math.round(n * 100) / 100;
|
||||
}
|
||||
@@ -205,7 +215,6 @@ export class SettlementService {
|
||||
remainingDailyLimit: Math.max(0, round2(dailyLimit - todayApplied)),
|
||||
isPrimary: account.isPrimary === 1,
|
||||
hasBankAccount,
|
||||
hasPendingRequest: !!pending,
|
||||
bankAccount: {
|
||||
bankAccountName: account.bankAccountName,
|
||||
bankAccountNo: account.bankAccountNo,
|
||||
@@ -264,7 +273,6 @@ export class SettlementService {
|
||||
requestAmount,
|
||||
todayApplied,
|
||||
dailyLimit,
|
||||
hasPendingRequest: !!pending,
|
||||
hasBankAccount,
|
||||
});
|
||||
if (!guard.ok) throw new BadRequestException(guard.message);
|
||||
@@ -276,14 +284,6 @@ export class SettlementService {
|
||||
if (!picked.ok) throw new BadRequestException(picked.message);
|
||||
|
||||
const created = await this.prisma.$transaction(async (tx) => {
|
||||
const stillPending = await tx.storeWithdrawRequest.findFirst({
|
||||
where: { storeId, status: 'PENDING_REVIEW' },
|
||||
select: { id: true },
|
||||
});
|
||||
if (stillPending) {
|
||||
throw new BadRequestException('已有待审核提现申请,请等待处理完成');
|
||||
}
|
||||
|
||||
const payoutIds = picked.selected.map((p) => p.id);
|
||||
const locked = await tx.storePayout.findMany({
|
||||
where: {
|
||||
@@ -1573,7 +1573,7 @@ export class SettlementService {
|
||||
// ─── Winery bills ────────────────────────────────────
|
||||
|
||||
async generateWineryBillForDay(anchor = new Date()) {
|
||||
const { start, end, billDate } = dayWindow(anchor);
|
||||
const { start, end, billDate } = wineryDayWindow(anchor);
|
||||
const rate = WINERY_SETTLEMENT_RATE;
|
||||
|
||||
const existing = await this.prisma.wineryBill.findUnique({ where: { billDate } });
|
||||
|
||||
@@ -44,6 +44,9 @@ export class StorePackageService {
|
||||
const otherNotes = item.otherNotes != null && String(item.otherNotes).trim()
|
||||
? String(item.otherNotes).trim()
|
||||
: null;
|
||||
const imageUrl = item.imageUrl != null && String(item.imageUrl).trim()
|
||||
? String(item.imageUrl).trim()
|
||||
: null;
|
||||
const sortOrder = item.sortOrder != null ? Number(item.sortOrder) : index;
|
||||
return {
|
||||
name,
|
||||
@@ -51,6 +54,7 @@ export class StorePackageService {
|
||||
dishes,
|
||||
usableTime,
|
||||
otherNotes,
|
||||
imageUrl,
|
||||
sortOrder: Number.isFinite(sortOrder) ? sortOrder : index,
|
||||
};
|
||||
}
|
||||
@@ -62,6 +66,7 @@ export class StorePackageService {
|
||||
dishes: string;
|
||||
usableTime: string | null;
|
||||
otherNotes: string | null;
|
||||
imageUrl: string | null;
|
||||
sortOrder: number;
|
||||
}) {
|
||||
return {
|
||||
@@ -71,6 +76,7 @@ export class StorePackageService {
|
||||
dishes: row.dishes,
|
||||
usableTime: row.usableTime,
|
||||
otherNotes: row.otherNotes,
|
||||
imageUrl: row.imageUrl,
|
||||
sortOrder: row.sortOrder,
|
||||
};
|
||||
}
|
||||
@@ -214,6 +220,7 @@ export class StorePackageService {
|
||||
dishes: pkg.dishes,
|
||||
usableTime: pkg.usableTime ?? null,
|
||||
otherNotes: pkg.otherNotes ?? null,
|
||||
imageUrl: pkg.imageUrl ?? null,
|
||||
sortOrder: pkg.sortOrder ?? index,
|
||||
},
|
||||
}),
|
||||
|
||||
@@ -225,6 +225,7 @@ export class StoreService {
|
||||
dishes: p.dishes,
|
||||
usableTime: p.usableTime,
|
||||
otherNotes: p.otherNotes,
|
||||
imageUrl: p.imageUrl,
|
||||
sortOrder: p.sortOrder,
|
||||
})),
|
||||
}),
|
||||
|
||||
@@ -593,6 +593,22 @@ export class TradeService {
|
||||
try {
|
||||
refundResult = await this.payProvider.refundOrder(orderId, outRefundNo, remark);
|
||||
} catch (err) {
|
||||
await this.prisma.order.update({
|
||||
where: { id: orderId },
|
||||
data: { status: fromStatus, payStatus: 'PAID' },
|
||||
});
|
||||
await this.prisma.commonEvent.create({
|
||||
data: buildOrderStatusEvent({
|
||||
orderId,
|
||||
fromStatus: 'REFUNDING',
|
||||
toStatus: fromStatus,
|
||||
operator: actorType,
|
||||
remark: `退款发起失败,已恢复:${err instanceof Error ? err.message : String(err)}`.slice(
|
||||
0,
|
||||
500,
|
||||
),
|
||||
}),
|
||||
});
|
||||
this.alert.notify({
|
||||
level: 'P0',
|
||||
category: 'pay',
|
||||
|
||||
+72
-1
@@ -32,6 +32,18 @@
|
||||
|------|------|------|
|
||||
| **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) |
|
||||
|
||||
### 0.4 变更:3.4.12 工单迭代
|
||||
|
||||
| 版本 | 日期 | 说明 |
|
||||
|------|------|------|
|
||||
| **3.4.12** | 2026-08-04 | 售后退款回滚、mini-user 门店详情、酒厂 T+3、门店多笔提现、开发计划批量编辑/审批企微派发、技术支持编辑/附件/批量改状态、套餐 imageUrl;开发设计见 [`杜康好客-v3.4.12-工单迭代开发文档.md`](./杜康好客-v3.4.12-工单迭代开发文档.md) |
|
||||
|
||||
---
|
||||
|
||||
## 1. 背景与目标
|
||||
@@ -277,6 +289,64 @@
|
||||
- 用户对核销过程中套餐内容有异议 → 可提交客服申诉
|
||||
- 工单/客服类型新增:**套餐异议**(`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 索引)
|
||||
@@ -326,7 +396,7 @@
|
||||
| 扩展 | 代下单(Wave 3);管仓只读(Wave 3) |
|
||||
| **门店套餐(3.4.10)** | 拓店套餐页;门店详情套餐列表/编辑/提审(REQ-P-027) |
|
||||
|
||||
### 4.4 总部端(H5)— REQ-H-001 ~ 025
|
||||
### 4.4 总部端(H5)— REQ-H-001 ~ 028
|
||||
|
||||
| 模块 | 要点 |
|
||||
|------|------|
|
||||
@@ -336,6 +406,7 @@
|
||||
| 结算 | 门店+合伙人双 Tab;提现审;白名单配置;**物流对账**(按承运商月结) |
|
||||
| 增长 | 推广码;问卷;评价;腾讯位置热力图 |
|
||||
| **门店套餐(3.4.10)** | 门店详情「套餐」Tab 直存;套餐变更审核通过/驳回(REQ-H-025) |
|
||||
| **开发计划(3.4.11)** | 版本/任务/设置;企微 Agent;任务评审派发;技术支持审批联动(REQ-H-026~028) |
|
||||
|
||||
### 4.5 端职责矩阵
|
||||
|
||||
|
||||
+35
-1
@@ -298,10 +298,44 @@ 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. v3.4.12 工单迭代(2026-08-04)
|
||||
|
||||
| 项 | 状态 | 说明 |
|
||||
|----|------|------|
|
||||
| P0 售后退款回滚 | ✅ | `initiateRefund` 微信失败恢复 PAID |
|
||||
| mini-user 门店详情 | ✅ | 门头轮播 preview + 环境图双列 |
|
||||
| 酒厂 T+3 | ✅ | `WINERY_SETTLEMENT_LAG_DAYS=3` |
|
||||
| 门店多笔提现 | ✅ | 移除单 pending 限制 |
|
||||
| 审批企微派发 | ✅ | review `dispatchToWecom` |
|
||||
| 开发任务批量编辑 | ✅ | `POST /admin/dev-plan/tasks/batch-update` |
|
||||
| 技术支持编辑/附件 | ✅ | `PATCH /admin/support-tickets/:id` + `attachmentUrls` |
|
||||
| 技术支持批量改状态 | ✅ | domain 状态机 + batch API |
|
||||
| 套餐 imageUrl | ✅ | 四端 + Prisma |
|
||||
| 文档 | ✅ | PRD §0.4 + v3.4.12 开发文档 |
|
||||
|
||||
---
|
||||
|
||||
## 10. 变更记录
|
||||
|
||||
| 日期 | 说明 |
|
||||
|------|------|
|
||||
| 2026-08-04 | v3.4.12 工单迭代(退款/财务/C端/开发计划/技术支持/套餐) |
|
||||
| 2026-08-04 | v3.4.11 开发计划 + 企微智能机器人/消息推送 + 角色权限重构 |
|
||||
| 2026-07-12 | **P0 已执行**:C2~C7、C14 代码与文档对齐;§1 改为计划+状态表 |
|
||||
| 2026-07-12 | 明确总部端保持 WebAdmin,不改为 H5 |
|
||||
| 2026-07-11 | 首版:V3.0 PRD 全量对照当前 monorepo |
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
# 杜康好客 · v3.4.12 工单迭代开发文档
|
||||
|
||||
> 版本:**v3.4.12** · 日期:2026-08-04
|
||||
> 需求源:ST 工单 + 开发计划/技术支持批量能力补充
|
||||
|
||||
## 1. 范围
|
||||
|
||||
| 模块 | 内容 |
|
||||
|------|------|
|
||||
| P0 售后 | `initiateRefund` 微信失败回滚订单状态 |
|
||||
| mini-user | 门店详情门头 preview、环境图双列 |
|
||||
| 财务 | 酒厂账单 T+3;门店可多笔 pending 提现 |
|
||||
| 开发计划 | 审批创建任务可选企微派发;任务批量改状态/关联版本 |
|
||||
| 技术支持 | 单条编辑/附件;批量改状态(状态机) |
|
||||
| 套餐 | `StorePackage.imageUrl` 四端;HQ 删除至 0 条 UX |
|
||||
|
||||
**不在本版**:ST1785812832352437(门店列表,已完成)
|
||||
|
||||
## 2. 后端 API
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
|------|------|------|
|
||||
| — | `trade.initiateRefund` | 失败时 `REFUNDING→原状态` + 事件 |
|
||||
| — | `settlement.generateWineryBillForDay` | `wineryDayWindow(lag=3)` |
|
||||
| — | `validateStoreWithdraw` | 移除 `hasPendingRequest` |
|
||||
| POST | `/admin/dev-plan/tasks/batch-update` | `{ taskIds, status?, versionId? }` |
|
||||
| POST | `/admin/support-tickets/:id/review` | 扩展 `dispatchToWecom`, `dispatchSupplement` |
|
||||
| PATCH | `/admin/support-tickets/:id` | 待评审可编辑 |
|
||||
| POST | `/admin/support-tickets/batch-update-status` | 批量改状态 |
|
||||
|
||||
## 3. 数据表
|
||||
|
||||
- `common_support_ticket.attachment_urls` JSON
|
||||
- `store_package.image_url` VARCHAR(512)
|
||||
|
||||
## 4. 验收
|
||||
|
||||
- [ ] 售后 REFUND 审批后 Mock 退款成功
|
||||
- [ ] mini-user 门头点击大图、环境图双列
|
||||
- [ ] 酒厂账单滞后 3 天;门店第二笔提现可提交
|
||||
- [ ] 审批勾选企微后开发群收到任务
|
||||
- [ ] 任务多选批量改状态/关联版本
|
||||
- [ ] 技术支持待评审可编辑附件;批量 TESTING→PASSED
|
||||
- [ ] 套餐 imageUrl 四端展示;HQ 可删至 0 条
|
||||
@@ -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