Compare commits
24 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1f7ecffe4c | |||
| 8df0a2bea7 | |||
| 672a995c59 | |||
| 9cb88dc181 | |||
| 345d5db9c9 | |||
| 2610288df0 | |||
| 62652cd072 | |||
| bdbd135318 | |||
| 8ca893efab | |||
| 50ab0f1748 | |||
| fa6fb80d19 | |||
| bd1930f6b1 | |||
| 256526c5ec | |||
| 1c4b986924 | |||
| 442500b1a1 | |||
| 490c26a7e1 | |||
| f80a0f2c27 | |||
| 528669f662 | |||
| 16fa07ceaf | |||
| 02d89e6385 | |||
| 16c386f165 | |||
| 4372018c09 | |||
| 71f508e02b | |||
| 9d96c73246 |
@@ -11,6 +11,7 @@
|
||||
"dependencies": {
|
||||
"@ant-design/icons": "^5.5.1",
|
||||
"@dukang/shared-types": "workspace:*",
|
||||
"@dukang/shared-ui": "workspace:*",
|
||||
"antd": "^5.22.0",
|
||||
"dayjs": "^1.11.13",
|
||||
"echarts": "^6.1.0",
|
||||
|
||||
@@ -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 })}
|
||||
|
||||
@@ -15,8 +15,6 @@ type OssUploadProps = {
|
||||
placeholder?: string;
|
||||
};
|
||||
|
||||
const DEFAULT_MAX_MB = 10;
|
||||
|
||||
export default function OssUpload({
|
||||
value,
|
||||
onChange,
|
||||
@@ -24,7 +22,6 @@ export default function OssUpload({
|
||||
bizType,
|
||||
mediaType = 'IMAGE',
|
||||
accept,
|
||||
maxSizeMb = DEFAULT_MAX_MB,
|
||||
placeholder = '上传后自动填入,或手动粘贴 URL',
|
||||
}: OssUploadProps) {
|
||||
const [uploading, setUploading] = useState(false);
|
||||
@@ -34,12 +31,6 @@ export default function OssUpload({
|
||||
|
||||
const customRequest: UploadProps['customRequest'] = async ({ file, onSuccess, onError }) => {
|
||||
const raw = file as File;
|
||||
if (raw.size > maxSizeMb * 1024 * 1024) {
|
||||
const err = new Error(`文件不能超过 ${maxSizeMb}MB`);
|
||||
message.error(err.message);
|
||||
onError?.(err);
|
||||
return;
|
||||
}
|
||||
setUploading(true);
|
||||
try {
|
||||
const result = await uploadFileToOss(raw, { bizType, mediaType });
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
import { apiBase, CLIENT_APP, getToken, clearAuth } from './api';
|
||||
import {
|
||||
compressImageFileIfNeeded,
|
||||
DEFAULT_OSS_MAX_UPLOAD_BYTES,
|
||||
formatOssMaxSizeMb,
|
||||
} from '@dukang/shared-ui/compressImage';
|
||||
|
||||
export type OssMediaType = 'IMAGE' | 'VIDEO' | 'FILE';
|
||||
|
||||
@@ -9,14 +14,24 @@ export type UploadFileResult = {
|
||||
mock: boolean;
|
||||
};
|
||||
|
||||
async function prepareUploadFile(file: File, mediaType: OssMediaType): Promise<File> {
|
||||
if (mediaType !== 'IMAGE') return file;
|
||||
const compressed = await compressImageFileIfNeeded(file);
|
||||
if (compressed.size > DEFAULT_OSS_MAX_UPLOAD_BYTES) {
|
||||
throw new Error(`图片压缩后仍超过 ${formatOssMaxSizeMb()}MB,请换一张较小的图片`);
|
||||
}
|
||||
return compressed;
|
||||
}
|
||||
|
||||
/** 经 API 服务端转存 OSS,避免浏览器直传跨域 */
|
||||
export async function uploadFileToOss(
|
||||
file: File,
|
||||
options: { bizType: string; mediaType?: OssMediaType },
|
||||
): Promise<UploadFileResult> {
|
||||
const mediaType = options.mediaType ?? (file.type.startsWith('video/') ? 'VIDEO' : 'IMAGE');
|
||||
const prepared = await prepareUploadFile(file, mediaType);
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
formData.append('file', prepared);
|
||||
formData.append('bizType', options.bizType);
|
||||
formData.append('mediaType', mediaType);
|
||||
|
||||
|
||||
@@ -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,382 @@
|
||||
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,
|
||||
SUPPORT_TICKET_STATUS_LABELS,
|
||||
type DevPlanTaskDto,
|
||||
type DevPlanTaskStatusDto,
|
||||
type DevPlanTaskTypeDto,
|
||||
type DevPlanVersionDto,
|
||||
type SupportTicketDto,
|
||||
} 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 [supportTickets, setSupportTickets] = useState<SupportTicketDto[]>([]);
|
||||
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]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!modalOpen || editing) return;
|
||||
request<{ items: SupportTicketDto[] }>('/admin/support-tickets?pageSize=100')
|
||||
.then((res) => setSupportTickets(res.items ?? []))
|
||||
.catch(() => setSupportTickets([]));
|
||||
}, [modalOpen, editing]);
|
||||
|
||||
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', supportTicketId: undefined });
|
||||
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,
|
||||
supportTicketId: values.supportTicketId || undefined,
|
||||
}),
|
||||
});
|
||||
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>
|
||||
) : (
|
||||
<Form.Item name="supportTicketId" label="绑定技术支持工单">
|
||||
<Select
|
||||
allowClear
|
||||
showSearch
|
||||
optionFilterProp="label"
|
||||
placeholder="可选:关联工单"
|
||||
options={supportTickets.map((t) => ({
|
||||
value: t.id,
|
||||
label: `${t.ticketNo} · ${SUPPORT_TICKET_STATUS_LABELS[t.status]} · ${t.title}`,
|
||||
}))}
|
||||
/>
|
||||
</Form.Item>
|
||||
)}
|
||||
</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="故事标题">
|
||||
|
||||
@@ -13,11 +13,16 @@ type Row = {
|
||||
settleAmount: number;
|
||||
channel?: RedeemChannel;
|
||||
createdAt: string;
|
||||
user?: { userNo: string; phone: string | null };
|
||||
user?: { userNo: string; phone: string | null; nickname?: string | null };
|
||||
store?: { name: string; cityName: string };
|
||||
coupon?: { couponNo: string };
|
||||
};
|
||||
|
||||
function maskPhone(phone: string | null | undefined) {
|
||||
if (!phone || phone.length < 7) return phone ?? '—';
|
||||
return `${phone.slice(0, 3)}****${phone.slice(-4)}`;
|
||||
}
|
||||
|
||||
export default function RedeemRecordsPage() {
|
||||
const [form] = Form.useForm();
|
||||
const [filters, setFilters] = useState<Record<string, string>>({});
|
||||
@@ -50,7 +55,19 @@ export default function RedeemRecordsPage() {
|
||||
);
|
||||
},
|
||||
},
|
||||
{ title: '用户', dataIndex: ['user', 'userNo'], width: 110 },
|
||||
{ title: '用户编号', dataIndex: ['user', 'userNo'], width: 110 },
|
||||
{
|
||||
title: '用户昵称',
|
||||
dataIndex: ['user', 'nickname'],
|
||||
width: 100,
|
||||
render: (v: string | null | undefined) => v || '—',
|
||||
},
|
||||
{
|
||||
title: '用户手机',
|
||||
dataIndex: ['user', 'phone'],
|
||||
width: 120,
|
||||
render: (v: string | null | undefined) => maskPhone(v),
|
||||
},
|
||||
{ title: '门店', dataIndex: ['store', 'name'] },
|
||||
{ title: '核销额', dataIndex: 'amount', width: 90, render: (v) => `¥${v}` },
|
||||
{ title: '结算额', dataIndex: 'settleAmount', width: 90, render: (v) => `¥${v}` },
|
||||
@@ -113,7 +130,7 @@ export default function RedeemRecordsPage() {
|
||||
loading={loading}
|
||||
columns={columns}
|
||||
dataSource={data?.items ?? []}
|
||||
scroll={{ x: 1100 }}
|
||||
scroll={{ x: 1300 }}
|
||||
pagination={{
|
||||
current: page,
|
||||
pageSize,
|
||||
@@ -138,6 +155,19 @@ export default function RedeemRecordsPage() {
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="核销额">¥{String(detail.amount)}</Descriptions.Item>
|
||||
<Descriptions.Item label="结算额">¥{String(detail.settleAmount)}</Descriptions.Item>
|
||||
{detail.user && typeof detail.user === 'object' ? (
|
||||
<>
|
||||
<Descriptions.Item label="用户编号">
|
||||
{String((detail.user as { userNo?: string }).userNo ?? '—')}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="用户昵称">
|
||||
{String((detail.user as { nickname?: string | null }).nickname ?? '—')}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="用户手机">
|
||||
{maskPhone((detail.user as { phone?: string | null }).phone)}
|
||||
</Descriptions.Item>
|
||||
</>
|
||||
) : null}
|
||||
<Descriptions.Item label="时间">{fmtTime(String(detail.createdAt))}</Descriptions.Item>
|
||||
</Descriptions>
|
||||
)}
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -258,7 +258,7 @@ export default function WineryBillsPage() {
|
||||
酒厂对账单
|
||||
</Typography.Title>
|
||||
<Typography.Text type="secondary">
|
||||
每日 8:00 汇总昨日已付订单(实付 × {ratePct}%);未打款红色、已打款绿色,可展开订单明细
|
||||
T+3:每日 8:00 汇总 3 天前(自然日)已完成的同城/跨城订单(实付 × {ratePct}%);未打款红色、已打款绿色,可展开订单明细
|
||||
</Typography.Text>
|
||||
</Space>
|
||||
{canEditWineryBank ? (
|
||||
|
||||
@@ -212,6 +212,14 @@ export default function PromoCodeDetailPage() {
|
||||
<Statistic title="扫码进入次数" value={stats?.scanCount ?? detail.scanCount} />
|
||||
</Card>
|
||||
</Col>
|
||||
<Col xs={12} sm={6}>
|
||||
<Card size="small">
|
||||
<Statistic
|
||||
title="归因用户数"
|
||||
value={stats?.attributionCount ?? 0}
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
<Col xs={12} sm={6}>
|
||||
<Card size="small">
|
||||
<Statistic
|
||||
|
||||
@@ -19,8 +19,6 @@ type OssUploadFieldProps = {
|
||||
onWechatReadyChange?: (ready: boolean) => void;
|
||||
};
|
||||
|
||||
const DEFAULT_MAX_MB = 10;
|
||||
|
||||
function isCancelError(msg: string): boolean {
|
||||
return /cancel|取消/i.test(msg);
|
||||
}
|
||||
@@ -79,10 +77,6 @@ export default function OssUploadField({
|
||||
showUploadError('图片读取失败,请重新选择');
|
||||
return;
|
||||
}
|
||||
if (file.size > DEFAULT_MAX_MB * 1024 * 1024) {
|
||||
showUploadError(`文件不能超过 ${DEFAULT_MAX_MB}MB`);
|
||||
return;
|
||||
}
|
||||
const result = await uploadFileToOss(file, { bizType, mediaType });
|
||||
onChange?.(result.url);
|
||||
}
|
||||
|
||||
@@ -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,4 +1,9 @@
|
||||
import { apiBase, request } from './api';
|
||||
import {
|
||||
compressImageFileIfNeeded,
|
||||
DEFAULT_OSS_MAX_UPLOAD_BYTES,
|
||||
formatOssMaxSizeMb,
|
||||
} from '@dukang/shared-ui/compressImage';
|
||||
|
||||
const UPLOAD_TIMEOUT_MS = 120_000;
|
||||
|
||||
@@ -11,13 +16,23 @@ export type UploadFileResult = {
|
||||
mock: boolean;
|
||||
};
|
||||
|
||||
async function prepareUploadFile(file: File, mediaType: OssMediaType): Promise<File> {
|
||||
if (mediaType !== 'IMAGE') return file;
|
||||
const compressed = await compressImageFileIfNeeded(file);
|
||||
if (compressed.size > DEFAULT_OSS_MAX_UPLOAD_BYTES) {
|
||||
throw new Error(`图片压缩后仍超过 ${formatOssMaxSizeMb()}MB,请换一张较小的图片`);
|
||||
}
|
||||
return compressed;
|
||||
}
|
||||
|
||||
async function uploadFileToOssInner(
|
||||
file: File,
|
||||
options: { bizType: string; mediaType?: OssMediaType },
|
||||
): Promise<UploadFileResult> {
|
||||
const mediaType = options.mediaType ?? (file.type.startsWith('video/') ? 'VIDEO' : 'IMAGE');
|
||||
const prepared = await prepareUploadFile(file, mediaType);
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
formData.append('file', prepared);
|
||||
formData.append('bizType', options.bizType);
|
||||
formData.append('mediaType', mediaType);
|
||||
|
||||
|
||||
@@ -168,12 +168,22 @@ export default function LoginPage() {
|
||||
|
||||
async function login() {
|
||||
if (!ensureAgreed()) return;
|
||||
const trimmedPhone = phone.trim();
|
||||
const trimmedCode = code.trim();
|
||||
if (!trimmedPhone) {
|
||||
setMsg('phone should not be empty');
|
||||
return;
|
||||
}
|
||||
if (!trimmedCode) {
|
||||
setMsg('code should not be empty');
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
setMsg('');
|
||||
try {
|
||||
const data = await request<PartnerSessionPayload>('PARTNER_H5', '/partner/auth/login/sms', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ phone, code }),
|
||||
body: JSON.stringify({ phone: trimmedPhone, code: trimmedCode }),
|
||||
silent: true,
|
||||
});
|
||||
saveRememberedSession(data);
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import { apiBase } from './api';
|
||||
import { getStoreProfile } from './api';
|
||||
import {
|
||||
compressImageFileIfNeeded,
|
||||
DEFAULT_OSS_MAX_UPLOAD_BYTES,
|
||||
formatOssMaxSizeMb,
|
||||
} from '@dukang/shared-ui/compressImage';
|
||||
|
||||
const UPLOAD_TIMEOUT_MS = 120_000;
|
||||
|
||||
@@ -15,9 +20,13 @@ 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 compressed = await compressImageFileIfNeeded(file);
|
||||
if (compressed.size > DEFAULT_OSS_MAX_UPLOAD_BYTES) {
|
||||
throw new Error(`图片压缩后仍超过 ${formatOssMaxSizeMb()}MB,请换一张较小的图片`);
|
||||
}
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
formData.append('file', compressed);
|
||||
formData.append('bizType', bizType);
|
||||
formData.append('mediaType', 'IMAGE');
|
||||
|
||||
|
||||
@@ -140,12 +140,22 @@ export default function LoginPage() {
|
||||
|
||||
async function login() {
|
||||
if (!ensureAgreed()) return;
|
||||
const trimmedPhone = phone.trim();
|
||||
const trimmedCode = code.trim();
|
||||
if (!trimmedPhone) {
|
||||
setMsg('phone should not be empty');
|
||||
return;
|
||||
}
|
||||
if (!trimmedCode) {
|
||||
setMsg('code should not be empty');
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
setMsg('');
|
||||
try {
|
||||
const data = await request<ShopSessionPayload>('SHOP_H5', '/shop/auth/login/sms', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ phone, code }),
|
||||
body: JSON.stringify({ phone: trimmedPhone, code: trimmedCode }),
|
||||
});
|
||||
saveRememberedSession(data);
|
||||
applySession(data);
|
||||
|
||||
@@ -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,4 +1,9 @@
|
||||
import { apiBase } from './api';
|
||||
import {
|
||||
compressImageFileIfNeeded,
|
||||
DEFAULT_OSS_MAX_UPLOAD_BYTES,
|
||||
formatOssMaxSizeMb,
|
||||
} from '@dukang/shared-ui/compressImage';
|
||||
|
||||
export type OssMediaType = 'IMAGE' | 'VIDEO' | 'FILE';
|
||||
|
||||
@@ -15,8 +20,15 @@ export async function uploadFileToOss(
|
||||
options: { bizType: string; mediaType?: OssMediaType },
|
||||
): Promise<UploadFileResult> {
|
||||
const mediaType = options.mediaType ?? (file.type.startsWith('video/') ? 'VIDEO' : 'IMAGE');
|
||||
let prepared = file;
|
||||
if (mediaType === 'IMAGE') {
|
||||
prepared = await compressImageFileIfNeeded(file);
|
||||
if (prepared.size > DEFAULT_OSS_MAX_UPLOAD_BYTES) {
|
||||
throw new Error(`图片压缩后仍超过 ${formatOssMaxSizeMb()}MB,请换一张较小的图片`);
|
||||
}
|
||||
}
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
formData.append('file', prepared);
|
||||
formData.append('bizType', options.bizType);
|
||||
formData.append('mediaType', mediaType);
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@dukang/mini-user",
|
||||
"version": "0.1.0",
|
||||
"version": "3.4.13",
|
||||
"private": true,
|
||||
"description": "杜康好客 · C 端用户微信小程序(Taro)",
|
||||
"scripts": {
|
||||
|
||||
@@ -11,6 +11,7 @@ export default defineAppConfig({
|
||||
'pages/pay/index',
|
||||
'pages/orders/index',
|
||||
'pages/order-detail/index',
|
||||
'pages/order-logistics/index',
|
||||
'pages/pickup-receive/index',
|
||||
'pages/addresses/index',
|
||||
'pages/address-edit/index',
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { Text } from '@tarojs/components';
|
||||
import Taro from '@tarojs/taro';
|
||||
import { splitLogisticsText } from '../lib/order-logistics-utils';
|
||||
import { toast } from '../lib/api';
|
||||
|
||||
type LogisticsRichTextProps = {
|
||||
text: string;
|
||||
className?: string;
|
||||
phoneClassName?: string;
|
||||
};
|
||||
|
||||
export default function LogisticsRichText({
|
||||
text,
|
||||
className = '',
|
||||
phoneClassName = 'order-logistics-phone-link',
|
||||
}: LogisticsRichTextProps) {
|
||||
const segments = splitLogisticsText(text);
|
||||
|
||||
function dial(phone: string) {
|
||||
const normalized = phone.replace(/-/g, '');
|
||||
Taro.makePhoneCall({ phoneNumber: normalized }).catch(() => toast('无法拨打电话'));
|
||||
}
|
||||
|
||||
return (
|
||||
<Text className={className}>
|
||||
{segments.map((segment, index) =>
|
||||
segment.type === 'phone' ? (
|
||||
<Text
|
||||
key={`${segment.value}-${index}`}
|
||||
className={phoneClassName}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
dial(segment.value);
|
||||
}}
|
||||
>
|
||||
{segment.value}
|
||||
</Text>
|
||||
) : (
|
||||
<Text key={`${index}-text`}>{segment.value}</Text>
|
||||
),
|
||||
)}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
@@ -1,18 +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';
|
||||
const imageMode = variant === 'store' ? 'aspectFit' : 'aspectFill';
|
||||
|
||||
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`}>
|
||||
@@ -24,7 +39,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={imageMode}
|
||||
alt={alt}
|
||||
onClick={previewable ? () => previewAt(index) : undefined}
|
||||
/>
|
||||
) : (
|
||||
<View className={`${prefix}-placeholder`} />
|
||||
)}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { useEffect, useRef } from 'react';
|
||||
import { finishLoginNavigate, forceReloadAfterAccountMerge, goLogin } from '../lib/auth-nav';
|
||||
import { toast } from '../lib/api';
|
||||
import { capturePromoSceneAndTouchScan } from '../lib/promo';
|
||||
import { initClientVersionChecks } from '../lib/client-version';
|
||||
import { saveWechatLoginResult } from '../lib/pay-wechat';
|
||||
import { applyWechatShare } from '../lib/wechat-share';
|
||||
import { handleWechatAuthCallback } from '../lib/wechat-auth';
|
||||
@@ -38,6 +39,7 @@ export default function WechatShareBootstrap() {
|
||||
|
||||
useEffect(() => {
|
||||
void capturePromoSceneAndTouchScan();
|
||||
initClientVersionChecks();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -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 全局未捕获错误钩子(幂等) */
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import Taro from '@tarojs/taro';
|
||||
import { fetchClientConfig } from './pay-wechat';
|
||||
|
||||
/** 与 package.json version 同步,供服务端 minClientVersion 比对 */
|
||||
export const APP_VERSION = '3.4.13';
|
||||
|
||||
function parseSemver(v: string): number[] {
|
||||
return v.split('.').map((n) => parseInt(n, 10) || 0);
|
||||
}
|
||||
|
||||
export function compareSemver(a: string, b: string): number {
|
||||
const pa = parseSemver(a);
|
||||
const pb = parseSemver(b);
|
||||
const len = Math.max(pa.length, pb.length);
|
||||
for (let i = 0; i < len; i += 1) {
|
||||
const da = pa[i] ?? 0;
|
||||
const db = pb[i] ?? 0;
|
||||
if (da !== db) return da - db;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
export async function checkClientVersionGate() {
|
||||
try {
|
||||
const config = await fetchClientConfig();
|
||||
const min = config.minClientVersion?.trim();
|
||||
if (min && compareSemver(APP_VERSION, min) < 0) {
|
||||
await Taro.showModal({
|
||||
title: '版本过低',
|
||||
content: '当前小程序版本过低,请更新至最新版本后继续使用。',
|
||||
showCancel: false,
|
||||
confirmText: '我知道了',
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
/* 配置拉取失败不阻塞启动 */
|
||||
}
|
||||
}
|
||||
|
||||
export function setupWeappUpdateManager() {
|
||||
if (process.env.TARO_ENV !== 'weapp') return;
|
||||
if (typeof Taro.getUpdateManager !== 'function') return;
|
||||
|
||||
const manager = Taro.getUpdateManager();
|
||||
manager.onCheckForUpdate((res) => {
|
||||
if (!res.hasUpdate) return;
|
||||
manager.onUpdateReady(() => {
|
||||
void Taro.showModal({
|
||||
title: '更新提示',
|
||||
content: '新版本已准备好,是否重启应用?',
|
||||
confirmText: '立即更新',
|
||||
success: (r) => {
|
||||
if (r.confirm) manager.applyUpdate();
|
||||
},
|
||||
});
|
||||
});
|
||||
manager.onUpdateFailed(() => {
|
||||
void Taro.showModal({
|
||||
title: '更新失败',
|
||||
content: '新版本下载失败,请删除小程序后重新搜索打开。',
|
||||
showCancel: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function initClientVersionChecks() {
|
||||
setupWeappUpdateManager();
|
||||
void checkClientVersionGate();
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import Taro from '@tarojs/taro';
|
||||
|
||||
const MAX_BYTES = 10 * 1024 * 1024;
|
||||
|
||||
/** 小程序临时文件超过 10MB 时用 compressImage 压缩后再上传 */
|
||||
export async function compressWeappImageIfNeeded(tempFilePath: string): Promise<string> {
|
||||
if (process.env.TARO_ENV !== 'weapp') return tempFilePath;
|
||||
|
||||
let path = tempFilePath;
|
||||
let size = await getFileSize(path);
|
||||
if (size <= MAX_BYTES) return path;
|
||||
|
||||
const qualities = [80, 65, 50, 40];
|
||||
for (const quality of qualities) {
|
||||
const res = await Taro.compressImage({ src: path, quality });
|
||||
path = res.tempFilePath;
|
||||
size = await getFileSize(path);
|
||||
if (size <= MAX_BYTES) return path;
|
||||
}
|
||||
|
||||
if (size > MAX_BYTES) {
|
||||
throw new Error('图片压缩后仍超过 10MB,请换一张较小的图片');
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
async function getFileSize(filePath: string): Promise<number> {
|
||||
try {
|
||||
const info = await Taro.getFileInfo({ filePath });
|
||||
return typeof info.size === 'number' ? info.size : 0;
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -69,12 +69,15 @@ export function mergeWxDisplayProfile(profile: UserProfile): UserProfile {
|
||||
/** 上传 chooseAvatar 临时文件到 OSS,并返回已登记到当前用户的真实资源。 */
|
||||
export async function uploadAvatarTempFile(tempFilePath: string): Promise<UploadedAvatarResource> {
|
||||
const { API_BASE, CLIENT_APP, getToken } = await import('./api');
|
||||
const { compressWeappImageIfNeeded } = await import('./compress-image');
|
||||
const token = getToken();
|
||||
if (!token) throw new Error('请先登录');
|
||||
|
||||
const filePath = await compressWeappImageIfNeeded(tempFilePath);
|
||||
|
||||
const res = await Taro.uploadFile({
|
||||
url: `${API_BASE}/common/resources/upload`,
|
||||
filePath: tempFilePath,
|
||||
filePath,
|
||||
name: 'file',
|
||||
formData: {
|
||||
bizType: 'AVATAR',
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
import type { OrderTrackDto } from '@dukang/shared-types';
|
||||
import { isXfxProviderCode } from '@dukang/shared-types';
|
||||
import { formatShanghaiDateTime } from './datetime';
|
||||
|
||||
export type OrderDelivery = {
|
||||
provider?: string;
|
||||
trackingNo?: string;
|
||||
logisticsCompany?: string;
|
||||
manualQueryUrl?: string;
|
||||
};
|
||||
|
||||
export type OrderTrackNode = {
|
||||
trackInfo?: string;
|
||||
createTime?: string;
|
||||
createdAt?: string;
|
||||
statusName?: string;
|
||||
};
|
||||
|
||||
export type OrderTrackEstimatedArrival = {
|
||||
arriveTime: string;
|
||||
siteName?: string;
|
||||
};
|
||||
|
||||
export type OrderTrackResponse = OrderTrackDto;
|
||||
|
||||
/** 订单详情页展示物流摘要的状态(配送中) */
|
||||
export const ORDER_LOGISTICS_PREVIEW_STATUSES = ['SHIPPING', 'SHIPPED'] as const;
|
||||
|
||||
const PHONE_PATTERN = /(1[3-9]\d{9}|\d{3,4}-\d{7,8})/g;
|
||||
|
||||
function compareTrackNodeTime(a: OrderTrackNode, b: OrderTrackNode) {
|
||||
const ta = new Date(a.createTime || a.createdAt || 0).getTime();
|
||||
const tb = new Date(b.createTime || b.createdAt || 0).getTime();
|
||||
if (Number.isNaN(ta) && Number.isNaN(tb)) return 0;
|
||||
if (Number.isNaN(ta)) return 1;
|
||||
if (Number.isNaN(tb)) return -1;
|
||||
return ta - tb;
|
||||
}
|
||||
|
||||
export function deliveryProviderLabel(provider?: string, company?: string) {
|
||||
if (company) return company;
|
||||
if (!provider || provider === 'MOCK' || isXfxProviderCode(provider)) {
|
||||
return '小飞侠配送';
|
||||
}
|
||||
if (provider === 'LOGISTICS') return '快递配送';
|
||||
return provider;
|
||||
}
|
||||
|
||||
export function shouldLoadOrderTrack(delivery?: OrderDelivery | null) {
|
||||
if (!delivery) return false;
|
||||
if (delivery.trackingNo) return true;
|
||||
return isXfxProviderCode(delivery.provider || '');
|
||||
}
|
||||
|
||||
export function formatTrackNodeTime(node: OrderTrackNode) {
|
||||
return formatShanghaiDateTime(node.createTime || node.createdAt);
|
||||
}
|
||||
|
||||
export function sortTrackNodesNewestFirst(nodes: OrderTrackNode[]): OrderTrackNode[] {
|
||||
return [...nodes].sort((a, b) => -compareTrackNodeTime(a, b));
|
||||
}
|
||||
|
||||
export function sortTrackNodesOldestFirst(nodes: OrderTrackNode[]): OrderTrackNode[] {
|
||||
return [...nodes].sort(compareTrackNodeTime);
|
||||
}
|
||||
|
||||
export function latestTrackNode(nodes: OrderTrackNode[]) {
|
||||
if (!nodes.length) return null;
|
||||
let latest = nodes[0];
|
||||
for (let i = 1; i < nodes.length; i += 1) {
|
||||
if (compareTrackNodeTime(nodes[i], latest) > 0) {
|
||||
latest = nodes[i];
|
||||
}
|
||||
}
|
||||
return latest;
|
||||
}
|
||||
|
||||
export function isLogisticsNotArrived(nodes: OrderTrackNode[], orderStatus?: string) {
|
||||
if (['PENDING_RECEIVE', 'DELIVERED', 'COMPLETED'].includes(orderStatus || '')) {
|
||||
return false;
|
||||
}
|
||||
if (nodes.length === 0) return true;
|
||||
return !nodes.some(
|
||||
(node) => node.statusName?.includes('签收') || node.trackInfo?.includes('签收'),
|
||||
);
|
||||
}
|
||||
|
||||
export function formatEstimatedArrival(eta?: OrderTrackEstimatedArrival | null) {
|
||||
if (!eta?.arriveTime) return '';
|
||||
const time = formatShanghaiDateTime(eta.arriveTime);
|
||||
if (eta.siteName) return `预计送达:${time}(${eta.siteName})`;
|
||||
return `预计送达:${time}`;
|
||||
}
|
||||
|
||||
export type LogisticsTextSegment = { type: 'text' | 'phone'; value: string };
|
||||
|
||||
export function splitLogisticsText(text: string): LogisticsTextSegment[] {
|
||||
if (!text) return [];
|
||||
const segments: LogisticsTextSegment[] = [];
|
||||
let lastIndex = 0;
|
||||
const regex = new RegExp(PHONE_PATTERN.source, 'g');
|
||||
let match: RegExpExecArray | null;
|
||||
while ((match = regex.exec(text)) !== null) {
|
||||
if (match.index > lastIndex) {
|
||||
segments.push({ type: 'text', value: text.slice(lastIndex, match.index) });
|
||||
}
|
||||
segments.push({ type: 'phone', value: match[0] });
|
||||
lastIndex = match.index + match[0].length;
|
||||
}
|
||||
if (lastIndex < text.length) {
|
||||
segments.push({ type: 'text', value: text.slice(lastIndex) });
|
||||
}
|
||||
return segments.length ? segments : [{ type: 'text', value: text }];
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
export * from './order-logistics-utils';
|
||||
import type { OrderTrackResponse } from './order-logistics-utils';
|
||||
import { request } from './api';
|
||||
|
||||
export async function fetchOrderTrack(orderId: string) {
|
||||
return request<OrderTrackResponse>(`/trade/orders/${orderId}/track`);
|
||||
}
|
||||
@@ -141,6 +141,14 @@ export default function OrderConfirmPickupPage() {
|
||||
const ready = await ensurePayReady(returnPath);
|
||||
if (!ready) return;
|
||||
|
||||
const { confirm } = await Taro.showModal({
|
||||
title: '确认提交订单',
|
||||
content: `确认提交现场提货订单?共 ${quantity} 瓶,应付 ¥${Number(preview?.payAmount ?? 0).toFixed(2)}。`,
|
||||
confirmText: '确认提交',
|
||||
cancelText: '再想想',
|
||||
});
|
||||
if (!confirm) return;
|
||||
|
||||
setLoading(true);
|
||||
setMsg('');
|
||||
try {
|
||||
|
||||
@@ -6,8 +6,19 @@ import SubPageHeader from '../../components/SubPageHeader';
|
||||
import ShareNavButton from '../../components/ShareNavButton';
|
||||
import WechatShareReady from '../../components/WechatShareReady';
|
||||
import ContactCsButton from '../../components/ContactCsButton';
|
||||
import LogisticsRichText from '../../components/LogisticsRichText';
|
||||
import { request, toast } from '../../lib/api';
|
||||
import { buildPayUrl } from '../../lib/checkout-nav';
|
||||
import {
|
||||
formatEstimatedArrival,
|
||||
isLogisticsNotArrived,
|
||||
latestTrackNode,
|
||||
ORDER_LOGISTICS_PREVIEW_STATUSES,
|
||||
shouldLoadOrderTrack,
|
||||
type OrderTrackEstimatedArrival,
|
||||
type OrderTrackNode,
|
||||
} from '../../lib/order-logistics-utils';
|
||||
import { fetchOrderTrack } from '../../lib/order-logistics';
|
||||
import { maskPhone } from '../../lib/phone';
|
||||
import { confirmOrderReceive, type WechatConfirmPayload } from '../../lib/wechat-order-confirm';
|
||||
import {
|
||||
@@ -44,8 +55,15 @@ type OrderDetail = {
|
||||
orderType?: string;
|
||||
isProxyOrder?: boolean;
|
||||
proxyPartnerName?: string | null;
|
||||
deliveryType?: string;
|
||||
items?: OrderItem[];
|
||||
wechatConfirm?: WechatConfirmPayload | null;
|
||||
delivery?: {
|
||||
provider?: string;
|
||||
trackingNo?: string;
|
||||
logisticsCompany?: string;
|
||||
manualQueryUrl?: string;
|
||||
} | null;
|
||||
};
|
||||
|
||||
const STATUS_LABELS: Record<string, string> = {
|
||||
@@ -78,11 +96,41 @@ export default function OrderDetailPage() {
|
||||
usePageView('order_detail_view', orderId ? { orderId } : undefined);
|
||||
const [order, setOrder] = useState<OrderDetail | null>(null);
|
||||
const [confirming, setConfirming] = useState(false);
|
||||
const [latestTrack, setLatestTrack] = useState<OrderTrackNode | null>(null);
|
||||
const [estimatedArrival, setEstimatedArrival] = useState<OrderTrackEstimatedArrival | null>(null);
|
||||
const [trackLoading, setTrackLoading] = useState(false);
|
||||
|
||||
async function loadOrderTrack(delivery: OrderDetail['delivery'], orderStatus?: string) {
|
||||
if (!orderId || !shouldLoadOrderTrack(delivery)) {
|
||||
setLatestTrack(null);
|
||||
setEstimatedArrival(null);
|
||||
return;
|
||||
}
|
||||
setTrackLoading(true);
|
||||
try {
|
||||
const track = await fetchOrderTrack(orderId);
|
||||
const nodes = track.nodes ?? [];
|
||||
setLatestTrack(latestTrackNode(nodes));
|
||||
setEstimatedArrival(
|
||||
isLogisticsNotArrived(nodes, orderStatus) && track.estimatedArrival
|
||||
? track.estimatedArrival
|
||||
: null,
|
||||
);
|
||||
} catch {
|
||||
setLatestTrack(null);
|
||||
setEstimatedArrival(null);
|
||||
} finally {
|
||||
setTrackLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!orderId) return;
|
||||
request<OrderDetail>(`/trade/orders/${orderId}`)
|
||||
.then(setOrder)
|
||||
.then((data) => {
|
||||
setOrder(data);
|
||||
void loadOrderTrack(data.delivery, data.status);
|
||||
})
|
||||
.catch((e) => toast(e instanceof Error ? e.message : '加载失败'));
|
||||
}, [orderId]);
|
||||
|
||||
@@ -90,7 +138,10 @@ export default function OrderDetailPage() {
|
||||
if (!orderId) return;
|
||||
// 从微信确认收货组件返回后刷新
|
||||
request<OrderDetail>(`/trade/orders/${orderId}`)
|
||||
.then(setOrder)
|
||||
.then((data) => {
|
||||
setOrder(data);
|
||||
void loadOrderTrack(data.delivery, data.status);
|
||||
})
|
||||
.catch(() => {});
|
||||
});
|
||||
|
||||
@@ -99,6 +150,18 @@ export default function OrderDetailPage() {
|
||||
const canPay = !!order && order.status === 'PENDING_PAY' && !isReship;
|
||||
const canConfirmReceive =
|
||||
!!order && !isReship && !isProxy && ['PENDING_RECEIVE', 'DELIVERED'].includes(order.status || '');
|
||||
const canViewLogistics =
|
||||
!!order &&
|
||||
order.deliveryType !== 'ON_SITE_PICKUP' &&
|
||||
!isReship &&
|
||||
['PENDING_SHIP', 'OUT_WAREHOUSE', 'SHIPPING', 'SHIPPED', 'PENDING_RECEIVE', 'DELIVERED', 'COMPLETED'].includes(
|
||||
order.status || '',
|
||||
);
|
||||
const showLogisticsPreview =
|
||||
canViewLogistics &&
|
||||
ORDER_LOGISTICS_PREVIEW_STATUSES.includes(
|
||||
(order?.status || '') as (typeof ORDER_LOGISTICS_PREVIEW_STATUSES)[number],
|
||||
);
|
||||
|
||||
const item = order?.items?.[0];
|
||||
const productName = item?.productName || order?.productName || '杜康商品';
|
||||
@@ -134,6 +197,11 @@ export default function OrderDetailPage() {
|
||||
Taro.navigateTo({ url: '/pages/customer-service/index' });
|
||||
}
|
||||
|
||||
function goLogistics() {
|
||||
if (!order) return;
|
||||
Taro.navigateTo({ url: `/pages/order-logistics/index?id=${order.id}` });
|
||||
}
|
||||
|
||||
async function confirmReceive() {
|
||||
if (!order || !canConfirmReceive || confirming) return;
|
||||
|
||||
@@ -211,6 +279,34 @@ export default function OrderDetailPage() {
|
||||
{isProxy && order.proxyPartnerName ? (
|
||||
<Text className="order-proxy-hint">由合伙人 {order.proxyPartnerName} 代下</Text>
|
||||
) : null}
|
||||
{showLogisticsPreview ? (
|
||||
<View className="order-logistics-preview-block">
|
||||
<View className="order-logistics-preview" onClick={goLogistics}>
|
||||
<View className="order-logistics-preview-main">
|
||||
{trackLoading ? (
|
||||
<Text className="order-logistics-preview-info u-muted">物流信息加载中…</Text>
|
||||
) : latestTrack?.trackInfo ? (
|
||||
<LogisticsRichText
|
||||
text={latestTrack.trackInfo}
|
||||
className="order-logistics-preview-info"
|
||||
/>
|
||||
) : order.delivery?.manualQueryUrl ? (
|
||||
<Text className="order-logistics-preview-info u-muted">物流已更新,点击查看详情</Text>
|
||||
) : (
|
||||
<Text className="order-logistics-preview-info u-muted">物流信息待更新,请稍后查看</Text>
|
||||
)}
|
||||
</View>
|
||||
<Text className="order-logistics-preview-link">物流详情</Text>
|
||||
</View>
|
||||
{estimatedArrival ? (
|
||||
<Text className="order-logistics-eta">{formatEstimatedArrival(estimatedArrival)}</Text>
|
||||
) : null}
|
||||
</View>
|
||||
) : canViewLogistics ? (
|
||||
<Text className="order-logistics-link" onClick={goLogistics}>
|
||||
查看物流追踪
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
<View className="order-card">
|
||||
<Text className="order-card-title">商品信息</Text>
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
export default definePageConfig({
|
||||
navigationStyle: 'custom',
|
||||
navigationBarTitleText: '物流详情',
|
||||
});
|
||||
@@ -0,0 +1,209 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { View, Text, Image } from '@tarojs/components';
|
||||
import Taro, { useRouter } from '@tarojs/taro';
|
||||
import PageShell from '../../components/PageShell';
|
||||
import SubPageHeader from '../../components/SubPageHeader';
|
||||
import LogisticsRichText from '../../components/LogisticsRichText';
|
||||
import { request, toast } from '../../lib/api';
|
||||
import {
|
||||
deliveryProviderLabel,
|
||||
formatTrackNodeTime,
|
||||
shouldLoadOrderTrack,
|
||||
sortTrackNodesOldestFirst,
|
||||
type OrderDelivery,
|
||||
type OrderTrackNode,
|
||||
} from '../../lib/order-logistics-utils';
|
||||
import { fetchOrderTrack } from '../../lib/order-logistics';
|
||||
import { usePageView } from '../../lib/usePageView';
|
||||
|
||||
type OrderDetail = {
|
||||
id: string;
|
||||
orderNo?: string;
|
||||
status?: string;
|
||||
delivery?: OrderDelivery | null;
|
||||
};
|
||||
|
||||
export default function OrderLogisticsPage() {
|
||||
const router = useRouter();
|
||||
const orderId = router.params.id ?? '';
|
||||
usePageView('order_logistics_view', orderId ? { orderId } : undefined);
|
||||
const [order, setOrder] = useState<OrderDetail | null>(null);
|
||||
const [trackNodes, setTrackNodes] = useState<OrderTrackNode[]>([]);
|
||||
const [signPhotoUrls, setSignPhotoUrls] = useState<string[]>([]);
|
||||
const [trackLoading, setTrackLoading] = useState(false);
|
||||
|
||||
const sortedTrackNodes = useMemo(
|
||||
() => (Array.isArray(trackNodes) ? sortTrackNodesOldestFirst(trackNodes) : []),
|
||||
[trackNodes],
|
||||
);
|
||||
const timelineComplete = ['PENDING_RECEIVE', 'DELIVERED', 'COMPLETED'].includes(
|
||||
order?.status || '',
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!orderId) return;
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
try {
|
||||
const data = await request<OrderDetail>(`/trade/orders/${orderId}`);
|
||||
if (cancelled) return;
|
||||
setOrder(data);
|
||||
if (!shouldLoadOrderTrack(data.delivery)) {
|
||||
setTrackNodes([]);
|
||||
setSignPhotoUrls([]);
|
||||
return;
|
||||
}
|
||||
setTrackLoading(true);
|
||||
try {
|
||||
const track = await fetchOrderTrack(orderId);
|
||||
if (!cancelled) {
|
||||
setTrackNodes(track.nodes ?? []);
|
||||
setSignPhotoUrls(track.signPhotoUrls ?? []);
|
||||
}
|
||||
} catch {
|
||||
if (!cancelled) {
|
||||
setTrackNodes([]);
|
||||
setSignPhotoUrls([]);
|
||||
}
|
||||
} finally {
|
||||
if (!cancelled) setTrackLoading(false);
|
||||
}
|
||||
} catch (e) {
|
||||
if (!cancelled) toast(e instanceof Error ? e.message : '加载失败');
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [orderId]);
|
||||
|
||||
function openManualQuery() {
|
||||
const url = order?.delivery?.manualQueryUrl?.trim();
|
||||
if (!url) {
|
||||
toast('暂无物流查询链接');
|
||||
return;
|
||||
}
|
||||
if (process.env.TARO_ENV === 'h5' && typeof window !== 'undefined') {
|
||||
window.open(url, '_blank');
|
||||
return;
|
||||
}
|
||||
Taro.setClipboardData({ data: url })
|
||||
.then(() => toast('查询链接已复制,请在浏览器中打开'))
|
||||
.catch(() => toast('无法打开物流查询'));
|
||||
}
|
||||
|
||||
function previewSignPhotos(index: number) {
|
||||
if (signPhotoUrls.length === 0) return;
|
||||
Taro.previewImage({ current: signPhotoUrls[index], urls: signPhotoUrls }).catch(() =>
|
||||
toast('无法预览图片'),
|
||||
);
|
||||
}
|
||||
|
||||
const delivery = order?.delivery;
|
||||
|
||||
return (
|
||||
<PageShell variant="sub" className="order-logistics-page">
|
||||
<SubPageHeader title="物流详情" />
|
||||
<View className="sub-page-body order-logistics-body">
|
||||
{!order ? (
|
||||
<View className="u-empty">加载中…</View>
|
||||
) : (
|
||||
<>
|
||||
<View className="order-card order-logistics-info-card">
|
||||
<Text className="order-card-title">物流信息</Text>
|
||||
<View className="order-row">
|
||||
<Text className="order-row-label">配送方式</Text>
|
||||
<Text className="order-row-value">
|
||||
{deliveryProviderLabel(delivery?.provider, delivery?.logisticsCompany)}
|
||||
</Text>
|
||||
</View>
|
||||
{delivery?.trackingNo ? (
|
||||
<View className="order-row">
|
||||
<Text className="order-row-label">运单号</Text>
|
||||
<Text className="order-row-value">{delivery.trackingNo}</Text>
|
||||
</View>
|
||||
) : null}
|
||||
{delivery?.manualQueryUrl ? (
|
||||
<View className="order-row">
|
||||
<Text className="order-row-label">物流查询</Text>
|
||||
<Text className="order-row-value order-row-value--link" onClick={openManualQuery}>
|
||||
查看物流
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
{!delivery?.trackingNo && !delivery?.manualQueryUrl ? (
|
||||
<Text className="u-muted">物流信息待更新,请稍后查看</Text>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
{signPhotoUrls.length > 0 ? (
|
||||
<View className="order-card">
|
||||
<Text className="order-card-title">签收照片</Text>
|
||||
<View className="order-logistics-sign-photos">
|
||||
{signPhotoUrls.map((url, index) => (
|
||||
<Image
|
||||
key={url}
|
||||
className="order-logistics-sign-photo"
|
||||
src={url}
|
||||
mode="aspectFill"
|
||||
onClick={() => previewSignPhotos(index)}
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{trackLoading ? (
|
||||
<View className="order-card">
|
||||
<Text className="order-card-title">物流动态</Text>
|
||||
<Text className="u-muted">加载中…</Text>
|
||||
</View>
|
||||
) : sortedTrackNodes.length > 0 ? (
|
||||
<View className="order-card">
|
||||
<Text className="order-card-title">物流动态</Text>
|
||||
<View
|
||||
className={`order-logistics-timeline${
|
||||
timelineComplete ? ' order-logistics-timeline--complete' : ''
|
||||
}`}
|
||||
>
|
||||
{sortedTrackNodes.map((node, index) => {
|
||||
const isLatest = index === sortedTrackNodes.length - 1;
|
||||
return (
|
||||
<View
|
||||
key={`${node.trackInfo}-${node.createTime}-${index}`}
|
||||
className={[
|
||||
'order-logistics-timeline-item',
|
||||
'order-logistics-timeline-item--done',
|
||||
isLatest ? 'order-logistics-timeline-item--latest' : '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' ')}
|
||||
>
|
||||
<View className="order-logistics-timeline-dot" />
|
||||
<View className="order-logistics-timeline-body">
|
||||
{node.statusName ? (
|
||||
<Text className="order-logistics-timeline-status">{node.statusName}</Text>
|
||||
) : null}
|
||||
<LogisticsRichText
|
||||
text={node.trackInfo || '—'}
|
||||
className="order-logistics-node-info"
|
||||
/>
|
||||
<Text className="order-logistics-node-time">{formatTrackNodeTime(node)}</Text>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
</View>
|
||||
) : shouldLoadOrderTrack(delivery) ? (
|
||||
<View className="order-card">
|
||||
<Text className="order-card-title">物流动态</Text>
|
||||
<Text className="u-muted">暂无路由信息,请稍后刷新</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
</View>
|
||||
</PageShell>
|
||||
);
|
||||
}
|
||||
@@ -11,7 +11,6 @@ import type { ProductDetailContentDto } from '@dukang/shared-types';
|
||||
import PageShell from '../../components/PageShell';
|
||||
import PageNavBar from '../../components/PageNavBar';
|
||||
import ProductCarousel from '../../components/ProductCarousel';
|
||||
import ShareNavButton from '../../components/ShareNavButton';
|
||||
import WechatShareReady from '../../components/WechatShareReady';
|
||||
import { goLogin } from '../../lib/auth-nav';
|
||||
import { ensurePayReady } from '../../lib/pay-ready';
|
||||
@@ -167,12 +166,11 @@ export default function ProductDetailPage() {
|
||||
solid={headerSolid}
|
||||
titleVisible={headerSolid}
|
||||
onBack={goBack}
|
||||
right={<ShareNavButton payload={sharePayload} />}
|
||||
/>
|
||||
|
||||
<View className="product-detail-main">
|
||||
<View className="product-detail-hero full-bleed">
|
||||
<ProductCarousel images={carouselImages} alt={product.name} variant="detail" />
|
||||
<ProductCarousel images={carouselImages} alt={product.name} variant="detail" previewable />
|
||||
</View>
|
||||
|
||||
<View className="product-detail-info">
|
||||
|
||||
@@ -15,6 +15,8 @@ import ShareNavButton from '../../components/ShareNavButton';
|
||||
import StoreRedeemMarquee from '../../components/StoreRedeemMarquee';
|
||||
import WechatShareReady from '../../components/WechatShareReady';
|
||||
import { request, toast } from '../../lib/api';
|
||||
import { maskPhone } from '../../lib/phone';
|
||||
import { track } from '../../lib/analytics';
|
||||
import { formatShanghaiDateTime } from '../../lib/datetime';
|
||||
import {
|
||||
DEFAULT_SHARE_DESC,
|
||||
@@ -34,6 +36,7 @@ type StorePackage = {
|
||||
dishes: string;
|
||||
usableTime?: string | null;
|
||||
otherNotes?: string | null;
|
||||
imageUrl?: string | null;
|
||||
sortOrder?: number;
|
||||
};
|
||||
|
||||
@@ -153,6 +156,7 @@ export default function StoreDetailPage() {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loadError, setLoadError] = useState('');
|
||||
const [headerSolid, setHeaderSolid] = useState(false);
|
||||
const [expandedPackages, setExpandedPackages] = useState<Record<number, boolean>>({});
|
||||
const storeRef = useRef<Store | null>(null);
|
||||
storeRef.current = store;
|
||||
|
||||
@@ -270,6 +274,7 @@ export default function StoreDetailPage() {
|
||||
toast('暂无门店电话');
|
||||
return;
|
||||
}
|
||||
track('store_phone_call', { storeId: store.id });
|
||||
Taro.makePhoneCall({ phoneNumber: store.phone }).catch(() => toast('无法拨打电话'));
|
||||
}
|
||||
|
||||
@@ -315,11 +320,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 +347,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">
|
||||
@@ -377,7 +378,9 @@ export default function StoreDetailPage() {
|
||||
|
||||
{store.phone ? (
|
||||
<View className="store-detail-row">
|
||||
<Text className="store-detail-meta store-detail-meta--flex">电话: {store.phone}</Text>
|
||||
<Text className="store-detail-meta store-detail-meta--flex">
|
||||
电话: {maskPhone(store.phone)}
|
||||
</Text>
|
||||
<Text className="store-detail-action" onClick={callStore}>
|
||||
拨打
|
||||
</Text>
|
||||
@@ -402,12 +405,32 @@ export default function StoreDetailPage() {
|
||||
{store.packages && store.packages.length > 0 ? (
|
||||
<View className="store-detail-section">
|
||||
<Text className="store-detail-section-title">门店套餐</Text>
|
||||
{store.packages.map((pkg, index) => (
|
||||
<View key={`${pkg.name}-${index}`} className="store-detail-package-card">
|
||||
<Text className="store-detail-package-name">{pkg.name}</Text>
|
||||
<Text className="store-detail-package-body">
|
||||
{formatRedeemAmountYuan(pkg.price)} 元 · {pkg.dishes}
|
||||
</Text>
|
||||
{store.packages.map((pkg, index) => {
|
||||
const expanded = !!expandedPackages[index];
|
||||
const bodyText = `${formatRedeemAmountYuan(pkg.price)} 元 · ${pkg.dishes}`;
|
||||
const longBody = bodyText.length > 48 || (pkg.otherNotes?.length ?? 0) > 40;
|
||||
return (
|
||||
<View
|
||||
key={`${pkg.name}-${index}`}
|
||||
className={`store-detail-package-card${expanded || !longBody ? '' : ' store-detail-package-card--collapsed'}`}
|
||||
>
|
||||
{pkg.imageUrl ? (
|
||||
<Image className="store-detail-package-img" src={pkg.imageUrl} mode="aspectFill" />
|
||||
) : null}
|
||||
<View className="store-detail-package-head">
|
||||
<Text className="store-detail-package-name">{pkg.name}</Text>
|
||||
{longBody ? (
|
||||
<Text
|
||||
className="store-detail-package-toggle"
|
||||
onClick={() =>
|
||||
setExpandedPackages((prev) => ({ ...prev, [index]: !prev[index] }))
|
||||
}
|
||||
>
|
||||
{expanded ? '收起' : '展开'}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
<Text className="store-detail-package-body">{bodyText}</Text>
|
||||
{pkg.usableTime ? (
|
||||
<Text className="store-detail-package-meta">使用时间:{pkg.usableTime}</Text>
|
||||
) : null}
|
||||
@@ -415,7 +438,8 @@ export default function StoreDetailPage() {
|
||||
<Text className="store-detail-package-meta">说明:{pkg.otherNotes}</Text>
|
||||
) : null}
|
||||
</View>
|
||||
))}
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
@@ -443,7 +467,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';
|
||||
@@ -342,10 +343,17 @@ export default function StoresPage() {
|
||||
}
|
||||
|
||||
function formatHours(store: Store) {
|
||||
const parts: string[] = [];
|
||||
if (store.openTime && store.closeTime) parts.push(`${store.openTime}-${store.closeTime}`);
|
||||
if (store.openTime2 && store.closeTime2) parts.push(`${store.openTime2}-${store.closeTime2}`);
|
||||
return parts.length ? `营业时间: ${parts.join(',')}` : '营业时间: 10:00-22:00';
|
||||
// 列表只展示第一段营业时间,避免挤占一行
|
||||
if (store.openTime && store.closeTime) {
|
||||
return `营业时间: ${store.openTime}-${store.closeTime}`;
|
||||
}
|
||||
return '营业时间: 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(
|
||||
@@ -427,31 +435,39 @@ 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">
|
||||
{/* 第1行:标题 + 距离 */}
|
||||
<View className="store-card-row store-card-row--head">
|
||||
<Text className="store-card-name" numberOfLines={1}>
|
||||
{s.name}
|
||||
</Text>
|
||||
<Text className="store-card-distance">
|
||||
{formatDistanceMeters(s.distanceMeters)}
|
||||
</Text>
|
||||
<Text
|
||||
</View>
|
||||
{/* 第2行:状态 + 营业时间(仅第一段) */}
|
||||
<View className="store-card-row store-card-row--meta">
|
||||
<Text className="store-card-status">{formatStatus(s)}</Text>
|
||||
<Text className="store-card-hours" numberOfLines={1}>
|
||||
{formatHours(s)}
|
||||
</Text>
|
||||
</View>
|
||||
{/* 第3行:地址 + 去核销 */}
|
||||
<View className="store-card-row store-card-row--foot">
|
||||
<Text className="store-card-address" numberOfLines={1}>
|
||||
{s.address || (s.district ? `${s.district}` : '地址待完善')}
|
||||
</Text>
|
||||
<View
|
||||
className="store-card-cta"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
Taro.navigateTo({ url: '/pages/redeem/index' });
|
||||
}}
|
||||
>
|
||||
去核销
|
||||
</Text>
|
||||
<Text className="store-card-cta-text">去核销</Text>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
@@ -488,3 +488,188 @@
|
||||
line-height: 1.5;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.order-logistics-page {
|
||||
background: var(--color-background);
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.order-logistics-body {
|
||||
padding-top: 0;
|
||||
}
|
||||
|
||||
.order-logistics-info-card {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.order-logistics-link {
|
||||
display: inline-block;
|
||||
margin-top: 8px;
|
||||
font-size: 14px;
|
||||
color: var(--color-heritage-red);
|
||||
}
|
||||
|
||||
.order-logistics-preview {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
margin-top: 12px;
|
||||
padding: 12px;
|
||||
border-radius: 10px;
|
||||
background: rgba(166, 29, 36, 0.04);
|
||||
}
|
||||
|
||||
.order-logistics-preview-main {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.order-logistics-preview-info {
|
||||
font-size: 13px;
|
||||
color: var(--color-on-surface);
|
||||
line-height: 1.5;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
}
|
||||
|
||||
.order-logistics-preview-link {
|
||||
flex-shrink: 0;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: var(--color-heritage-red);
|
||||
}
|
||||
|
||||
.order-logistics-preview-block {
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.order-logistics-eta {
|
||||
display: block;
|
||||
margin-top: 8px;
|
||||
font-size: 12px;
|
||||
color: var(--color-on-surface-variant);
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.order-logistics-phone-link {
|
||||
color: var(--color-heritage-red);
|
||||
}
|
||||
|
||||
.order-logistics-sign-photos {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.order-logistics-sign-photo {
|
||||
width: 96px;
|
||||
height: 96px;
|
||||
border-radius: 8px;
|
||||
background: var(--color-surface-container);
|
||||
}
|
||||
|
||||
.order-row-value--link {
|
||||
color: var(--color-heritage-red);
|
||||
}
|
||||
|
||||
.order-logistics-timeline {
|
||||
padding-top: 4px;
|
||||
}
|
||||
|
||||
.order-logistics-timeline--complete .order-logistics-timeline-item:not(:last-child)::before {
|
||||
background: rgba(166, 29, 36, 0.35);
|
||||
}
|
||||
|
||||
.order-logistics-timeline-item {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
position: relative;
|
||||
padding-bottom: 16px;
|
||||
}
|
||||
|
||||
.order-logistics-timeline-item:last-child {
|
||||
padding-bottom: 0;
|
||||
}
|
||||
|
||||
.order-logistics-timeline-item:not(:last-child)::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
left: 5px;
|
||||
top: 14px;
|
||||
bottom: 0;
|
||||
width: 1px;
|
||||
background: rgba(0, 0, 0, 0.08);
|
||||
}
|
||||
|
||||
.order-logistics-timeline-item--done .order-logistics-timeline-dot {
|
||||
background: var(--color-heritage-red);
|
||||
box-shadow: 0 0 0 1px var(--color-heritage-red);
|
||||
}
|
||||
|
||||
.order-logistics-timeline-item--done:not(:last-child)::before {
|
||||
background: rgba(166, 29, 36, 0.35);
|
||||
}
|
||||
|
||||
.order-logistics-timeline-dot {
|
||||
flex-shrink: 0;
|
||||
width: 11px;
|
||||
height: 11px;
|
||||
margin-top: 4px;
|
||||
border-radius: 50%;
|
||||
background: var(--color-surface-container-high, #e8e4df);
|
||||
border: 2px solid #fff;
|
||||
box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.08);
|
||||
}
|
||||
|
||||
.order-logistics-timeline-item--latest .order-logistics-timeline-dot {
|
||||
background: var(--color-heritage-red);
|
||||
box-shadow: 0 0 0 2px rgba(166, 29, 36, 0.25);
|
||||
}
|
||||
|
||||
.order-logistics-timeline-body {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.order-logistics-timeline-status {
|
||||
display: block;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: var(--color-on-surface);
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.order-logistics-timeline-item--done .order-logistics-timeline-status {
|
||||
color: var(--color-heritage-red);
|
||||
}
|
||||
|
||||
.order-logistics-timeline-item--latest .order-logistics-timeline-status {
|
||||
color: var(--color-heritage-red);
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.order-logistics-node {
|
||||
padding: 10px 0;
|
||||
border-bottom: 1px solid rgba(0, 0, 0, 0.06);
|
||||
}
|
||||
|
||||
.order-logistics-node:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.order-logistics-node-time {
|
||||
display: block;
|
||||
font-size: 12px;
|
||||
color: var(--color-on-surface-variant);
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.order-logistics-node-info {
|
||||
display: block;
|
||||
font-size: 14px;
|
||||
color: var(--color-on-surface);
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
@@ -10,13 +10,15 @@
|
||||
.store-detail-carousel-wrap {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: 280px;
|
||||
min-height: 200px;
|
||||
max-height: 360px;
|
||||
overflow: hidden;
|
||||
background: var(--color-surface-container);
|
||||
}
|
||||
|
||||
.store-detail-carousel {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
height: 280px;
|
||||
}
|
||||
|
||||
.store-detail-carousel-item,
|
||||
@@ -175,24 +177,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 +243,35 @@
|
||||
border-bottom: 1px solid rgba(0, 0, 0, 0.06);
|
||||
}
|
||||
|
||||
.store-detail-package-card--collapsed .store-detail-package-body,
|
||||
.store-detail-package-card--collapsed .store-detail-package-meta {
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.store-detail-package-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.store-detail-package-toggle {
|
||||
flex-shrink: 0;
|
||||
font-size: 13px;
|
||||
color: var(--color-heritage-red);
|
||||
}
|
||||
|
||||
.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;
|
||||
}
|
||||
|
||||
@@ -144,63 +144,144 @@
|
||||
padding: 4px var(--space-page) 16px;
|
||||
}
|
||||
|
||||
/* 左图右文,卡片等高 */
|
||||
.store-card {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: stretch;
|
||||
gap: 12px;
|
||||
padding: 12px;
|
||||
box-sizing: border-box;
|
||||
background: var(--color-card);
|
||||
border-radius: var(--radius-lg);
|
||||
overflow: hidden;
|
||||
box-shadow: var(--shadow-card);
|
||||
margin-bottom: 16px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.store-card-cover {
|
||||
width: 100%;
|
||||
height: 160px;
|
||||
flex-shrink: 0;
|
||||
width: 96px;
|
||||
height: 96px;
|
||||
border-radius: 8px;
|
||||
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;
|
||||
height: 96px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: space-between;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.store-card-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* 第1行:加粗标题(单行截断)+ 右对齐距离 */
|
||||
.store-card-row--head {
|
||||
gap: 8px;
|
||||
height: 22px;
|
||||
}
|
||||
|
||||
.store-card-name {
|
||||
display: block;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
font-family: var(--font-headline);
|
||||
font-size: 16px;
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
color: var(--color-on-surface);
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.store-card-meta {
|
||||
display: block;
|
||||
font-size: 12px;
|
||||
color: var(--color-subtle-gray);
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.store-card-footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-top: 12px;
|
||||
line-height: 22px;
|
||||
color: #1a1a1a;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.store-card-distance {
|
||||
flex-shrink: 0;
|
||||
max-width: 40%;
|
||||
font-size: 12px;
|
||||
color: var(--color-on-surface-variant);
|
||||
font-weight: 400;
|
||||
line-height: 22px;
|
||||
color: #999;
|
||||
text-align: right;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* 第2行:营业状态 + 营业时间(单行) */
|
||||
.store-card-row--meta {
|
||||
gap: 6px;
|
||||
height: 20px;
|
||||
}
|
||||
|
||||
.store-card-status {
|
||||
flex-shrink: 0;
|
||||
padding: 0 6px;
|
||||
border-radius: 4px;
|
||||
background: rgba(45, 106, 79, 0.12);
|
||||
color: #2d6a4f;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
line-height: 18px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.store-card-hours {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
font-size: 11px;
|
||||
font-weight: 400;
|
||||
line-height: 20px;
|
||||
color: #999;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* 第3行:地址(单行截断)+ 右对齐去核销 */
|
||||
.store-card-row--foot {
|
||||
gap: 8px;
|
||||
height: 28px;
|
||||
}
|
||||
|
||||
.store-card-address {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
font-size: 9px;
|
||||
font-weight: 400;
|
||||
line-height: 28px;
|
||||
color: #999;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.store-card-cta {
|
||||
padding: 6px 14px;
|
||||
border-radius: var(--radius-full);
|
||||
background: rgba(166, 29, 36, 0.08);
|
||||
color: var(--color-heritage-red);
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 0 14px;
|
||||
height: 26px;
|
||||
border-radius: 999px;
|
||||
background: var(--color-heritage-red, #a61d24);
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.store-card-cta-text {
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
line-height: 26px;
|
||||
color: #fff;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -33,11 +33,24 @@ export const SUPPORT_TICKET_STATUS_LABELS: Record<SupportTicketStatusDto, string
|
||||
PASSED: '通过',
|
||||
};
|
||||
|
||||
/** 技术支持工单优先级 */
|
||||
export type SupportTicketPriorityDto = 'LOW' | 'NORMAL' | 'HIGH' | 'URGENT';
|
||||
|
||||
export const SUPPORT_TICKET_PRIORITIES = ['LOW', 'NORMAL', 'HIGH', 'URGENT'] as const;
|
||||
|
||||
export const SUPPORT_TICKET_PRIORITY_LABELS: Record<SupportTicketPriorityDto, string> = {
|
||||
LOW: '低',
|
||||
NORMAL: '普通',
|
||||
HIGH: '高',
|
||||
URGENT: '紧急',
|
||||
};
|
||||
|
||||
export interface SupportTicketDto {
|
||||
id: string;
|
||||
ticketNo: string;
|
||||
ticketType: SupportTicketTypeDto;
|
||||
status: SupportTicketStatusDto;
|
||||
priority: SupportTicketPriorityDto;
|
||||
title: string;
|
||||
content?: string | null;
|
||||
rejectReason?: string | null;
|
||||
@@ -47,6 +60,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 +71,74 @@ export interface CreateSupportTicketRequest {
|
||||
title: string;
|
||||
content?: string;
|
||||
remark?: string;
|
||||
attachmentUrls?: string[];
|
||||
priority?: SupportTicketPriorityDto;
|
||||
}
|
||||
|
||||
export interface UpdateSupportTicketRequest {
|
||||
ticketType?: SupportTicketTypeDto;
|
||||
title?: string;
|
||||
content?: string;
|
||||
remark?: string;
|
||||
attachmentUrls?: string[];
|
||||
priority?: SupportTicketPriorityDto;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -70,6 +70,30 @@ export interface DeliveryDto {
|
||||
deliveredAt?: string;
|
||||
}
|
||||
|
||||
/** 物流路由节点(C 端 track API) */
|
||||
export interface OrderTrackNodeDto {
|
||||
trackInfo: string;
|
||||
createTime: string;
|
||||
statusName?: string;
|
||||
}
|
||||
|
||||
/** 小飞侠 cmd=100301 预估送达 */
|
||||
export interface OrderTrackEstimatedArrivalDto {
|
||||
arriveTime: string;
|
||||
siteName?: string;
|
||||
}
|
||||
|
||||
/** GET /trade/orders/:id/track 响应 */
|
||||
export interface OrderTrackDto {
|
||||
nodes: OrderTrackNodeDto[];
|
||||
signPhotoUrls: string[];
|
||||
estimatedArrival?: OrderTrackEstimatedArrivalDto | null;
|
||||
manualQueryUrl?: string | null;
|
||||
provider?: string;
|
||||
trackingNo?: string | null;
|
||||
logisticsCompany?: string | null;
|
||||
}
|
||||
|
||||
/** 大单拦截原因:≥10 箱不自动推小飞侠 */
|
||||
export const FULFILLMENT_HOLD_REASON_LABELS: Record<string, string> = {
|
||||
LARGE_ORDER_GE_10_BOXES: '大单≥10箱,待总部确认推单/自配送',
|
||||
|
||||
@@ -48,6 +48,8 @@ export type ClientRuntimeConfig = {
|
||||
banners: string[];
|
||||
footerUrl: string | null;
|
||||
};
|
||||
/** 小程序最低兼容版本(semver,如 3.4.13);客户端低于此值时提示更新 */
|
||||
minClientVersion?: string | null;
|
||||
};
|
||||
|
||||
/** 是否展示微信授权入口 */
|
||||
|
||||
@@ -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)}`;
|
||||
}
|
||||
@@ -11,7 +11,8 @@
|
||||
"./CouponBadge": "./src/CouponBadge.tsx",
|
||||
"./OrderStatusTabs": "./src/OrderStatusTabs.tsx",
|
||||
"./AppImage": "./src/AppImage.tsx",
|
||||
"./PullToRefresh": "./src/PullToRefresh.tsx"
|
||||
"./PullToRefresh": "./src/PullToRefresh.tsx",
|
||||
"./compressImage": "./src/compressImage.ts"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": "^18.3.1"
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
/** OSS 单文件上限(与后端 OSS_MAX_UPLOAD_BYTES 默认一致) */
|
||||
export const DEFAULT_OSS_MAX_UPLOAD_BYTES = 10 * 1024 * 1024;
|
||||
|
||||
function isCompressibleImage(file: File): boolean {
|
||||
if (!file.type.startsWith('image/')) return false;
|
||||
if (file.type === 'image/svg+xml' || file.type === 'image/gif') return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
function loadImage(file: File): Promise<HTMLImageElement> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const url = URL.createObjectURL(file);
|
||||
const img = new Image();
|
||||
img.onload = () => {
|
||||
URL.revokeObjectURL(url);
|
||||
resolve(img);
|
||||
};
|
||||
img.onerror = () => {
|
||||
URL.revokeObjectURL(url);
|
||||
reject(new Error('图片读取失败'));
|
||||
};
|
||||
img.src = url;
|
||||
});
|
||||
}
|
||||
|
||||
function canvasToBlob(canvas: HTMLCanvasElement, type: string, quality: number): Promise<Blob> {
|
||||
return new Promise((resolve, reject) => {
|
||||
canvas.toBlob(
|
||||
(blob) => (blob ? resolve(blob) : reject(new Error('图片压缩失败'))),
|
||||
type,
|
||||
quality,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async function renderScaled(
|
||||
img: HTMLImageElement,
|
||||
maxEdge: number,
|
||||
quality: number,
|
||||
mime: string,
|
||||
): Promise<Blob> {
|
||||
const w = img.naturalWidth;
|
||||
const h = img.naturalHeight;
|
||||
const scale = Math.min(1, maxEdge / Math.max(w, h));
|
||||
const cw = Math.max(1, Math.round(w * scale));
|
||||
const ch = Math.max(1, Math.round(h * scale));
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = cw;
|
||||
canvas.height = ch;
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) throw new Error('图片压缩失败');
|
||||
ctx.drawImage(img, 0, 0, cw, ch);
|
||||
return canvasToBlob(canvas, mime, quality);
|
||||
}
|
||||
|
||||
/**
|
||||
* 超过 maxBytes 的图片用 canvas 压缩后再上传;不可压缩或非图片原样返回。
|
||||
*/
|
||||
export async function compressImageFileIfNeeded(
|
||||
file: File,
|
||||
maxBytes = DEFAULT_OSS_MAX_UPLOAD_BYTES,
|
||||
): Promise<File> {
|
||||
if (!isCompressibleImage(file) || file.size <= maxBytes) return file;
|
||||
|
||||
const img = await loadImage(file);
|
||||
const mime = file.type === 'image/png' || file.type === 'image/webp' ? 'image/jpeg' : file.type || 'image/jpeg';
|
||||
const edges = [4096, 3072, 2048, 1536, 1280, 1024, 800];
|
||||
let best: Blob | null = null;
|
||||
|
||||
outer: for (const edge of edges) {
|
||||
for (let quality = 0.92; quality >= 0.5; quality -= 0.08) {
|
||||
const blob = await renderScaled(img, edge, quality, mime);
|
||||
if (!best || blob.size < best.size) best = blob;
|
||||
if (blob.size <= maxBytes) {
|
||||
best = blob;
|
||||
break outer;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!best || best.size >= file.size) return file;
|
||||
|
||||
const ext = mime === 'image/png' ? '.png' : '.jpg';
|
||||
const baseName = file.name.replace(/\.[^.]+$/, '') || 'image';
|
||||
return new File([best], `${baseName}${ext}`, { type: mime, lastModified: Date.now() });
|
||||
}
|
||||
|
||||
export function formatOssMaxSizeMb(maxBytes = DEFAULT_OSS_MAX_UPLOAD_BYTES): number {
|
||||
return Math.floor(maxBytes / 1024 / 1024);
|
||||
}
|
||||
Generated
+3
@@ -29,6 +29,9 @@ importers:
|
||||
'@dukang/shared-types':
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/shared-types
|
||||
'@dukang/shared-ui':
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/shared-ui
|
||||
antd:
|
||||
specifier: ^5.22.0
|
||||
version: 5.29.3(luxon@3.7.2)(moment@2.30.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
|
||||
|
||||
@@ -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,32 @@ enum SupportTicketStatus {
|
||||
PASSED
|
||||
}
|
||||
|
||||
enum SupportTicketPriority {
|
||||
LOW
|
||||
NORMAL
|
||||
HIGH
|
||||
URGENT
|
||||
}
|
||||
|
||||
enum DevPlanTaskType {
|
||||
BUG
|
||||
REQUIREMENT
|
||||
OPTIMIZATION
|
||||
}
|
||||
|
||||
enum DevPlanTaskStatus {
|
||||
TODO
|
||||
DEVELOPED
|
||||
RELEASED
|
||||
}
|
||||
|
||||
enum DevPlanVersionStatus {
|
||||
PENDING
|
||||
IN_PROGRESS
|
||||
TESTING
|
||||
RELEASED
|
||||
}
|
||||
|
||||
enum InvoiceTitleType {
|
||||
PERSONAL
|
||||
ENTERPRISE
|
||||
@@ -389,26 +415,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 +444,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
|
||||
@@ -585,6 +653,7 @@ model CommonSupportTicket {
|
||||
ticketNo String @unique @map("ticket_no") @db.VarChar(32)
|
||||
ticketType SupportTicketType @map("ticket_type")
|
||||
status SupportTicketStatus @default(PENDING_REVIEW)
|
||||
priority SupportTicketPriority @default(NORMAL) @map("priority")
|
||||
title String @db.VarChar(128)
|
||||
content String? @db.Text
|
||||
rejectReason String? @map("reject_reason") @db.VarChar(512)
|
||||
@@ -594,6 +663,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 +672,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 +1287,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,
|
||||
|
||||
@@ -6,9 +6,12 @@ import { WechatPayCallbackController } from './wechat-pay.controller';
|
||||
import { WechatRefundCallbackController } from './wechat-refund.controller';
|
||||
import { WechatMessageCallbackController } from './wechat-message.controller';
|
||||
import { DeliveryCallbackController } from './delivery-track.controller';
|
||||
import { DeliveryCallbackService } from './delivery-callback.service';
|
||||
import { CourierModule } from '../integrations/courier/courier.module';
|
||||
|
||||
@Module({
|
||||
imports: [IntegrationsModule, TradeModule, PrismaModule],
|
||||
imports: [IntegrationsModule, TradeModule, PrismaModule, CourierModule],
|
||||
providers: [DeliveryCallbackService],
|
||||
controllers: [
|
||||
WechatPayCallbackController,
|
||||
WechatRefundCallbackController,
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { PrismaService } from '../common/prisma/prisma.module';
|
||||
import { CourierService } from '../integrations/courier/courier.service';
|
||||
import { XiaofeixiaProvider } from '../integrations/courier/xiaofeixia/xiaofeixia.provider';
|
||||
import { logCourierCall } from '../integrations/courier/courier-log.util';
|
||||
import { TradeService } from '../modules/trade/trade.service';
|
||||
|
||||
const XFX_PROVIDER_ALIASES = new Set(['xfx', 'xiaofeixia']);
|
||||
|
||||
@Injectable()
|
||||
export class DeliveryCallbackService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly courier: CourierService,
|
||||
private readonly xiaofeixiaProvider: XiaofeixiaProvider,
|
||||
private readonly tradeService: TradeService,
|
||||
) {}
|
||||
|
||||
async handleTrackCallback(providerKey: string, body: unknown, requestUrl: string) {
|
||||
const normalized = providerKey.trim().toLowerCase();
|
||||
const baseLog = {
|
||||
scene: 'TRACK_CALLBACK',
|
||||
requestUrl,
|
||||
requestBody: (body && typeof body === 'object' ? body : { value: body }) as Record<
|
||||
string,
|
||||
unknown
|
||||
>,
|
||||
};
|
||||
|
||||
if (!XFX_PROVIDER_ALIASES.has(normalized) && normalized !== 'logistics') {
|
||||
await logCourierCall(this.prisma, {
|
||||
...baseLog,
|
||||
status: 'FAILED',
|
||||
errorMessage: `不支持的承运商: ${providerKey}`,
|
||||
});
|
||||
return this.courier.buildTrackCallbackResponse(false);
|
||||
}
|
||||
|
||||
if (normalized === 'logistics') {
|
||||
await logCourierCall(this.prisma, {
|
||||
...baseLog,
|
||||
status: 'SUCCESS',
|
||||
errorMessage: '跨城物流回调暂未接入,已记录',
|
||||
});
|
||||
return this.courier.buildTrackCallbackResponse(true);
|
||||
}
|
||||
|
||||
const payload = this.xiaofeixiaProvider.parseTrackCallback(body);
|
||||
if (!payload) {
|
||||
await logCourierCall(this.prisma, {
|
||||
...baseLog,
|
||||
status: 'FAILED',
|
||||
errorMessage: '回调体解析失败',
|
||||
});
|
||||
return this.courier.buildTrackCallbackResponse(false);
|
||||
}
|
||||
|
||||
const order = payload.outNumber
|
||||
? await this.prisma.order.findUnique({ where: { orderNo: payload.outNumber } })
|
||||
: payload.trackingNumber
|
||||
? await this.prisma.order.findFirst({
|
||||
where: { delivery: { trackingNo: payload.trackingNumber } },
|
||||
})
|
||||
: null;
|
||||
|
||||
if (!order) {
|
||||
await logCourierCall(this.prisma, {
|
||||
...baseLog,
|
||||
status: 'FAILED',
|
||||
errorMessage: '订单不存在',
|
||||
externalNo: payload.outNumber || payload.trackingNumber,
|
||||
});
|
||||
return this.courier.buildTrackCallbackResponse(false);
|
||||
}
|
||||
|
||||
const targetStatus = this.xiaofeixiaProvider.mapTrackStatus(
|
||||
payload.status,
|
||||
payload.statusName,
|
||||
);
|
||||
let applied = false;
|
||||
if (targetStatus && targetStatus !== order.status) {
|
||||
await this.tradeService.applyStatusTransition(
|
||||
order.id,
|
||||
order.status,
|
||||
targetStatus,
|
||||
'COURIER_TRACK_CALLBACK',
|
||||
payload.trackInfo || payload.statusName,
|
||||
);
|
||||
applied = true;
|
||||
}
|
||||
|
||||
const response = this.courier.buildTrackCallbackResponse(true);
|
||||
await logCourierCall(this.prisma, {
|
||||
...baseLog,
|
||||
responseBody: response,
|
||||
status: 'SUCCESS',
|
||||
externalNo: order.orderNo,
|
||||
ref: { refType: 'ORDER', refId: order.id },
|
||||
errorMessage: applied ? undefined : '状态未变更',
|
||||
});
|
||||
|
||||
return response;
|
||||
}
|
||||
}
|
||||
@@ -1,71 +1,27 @@
|
||||
import { Body, Controller, Post } from '@nestjs/common';
|
||||
import { TradeService } from '../modules/trade/trade.service';
|
||||
import { CourierService } from '../integrations/courier/courier.service';
|
||||
import { PrismaService } from '../common/prisma/prisma.module';
|
||||
import { logCourierCall } from '../integrations/courier/courier-log.util';
|
||||
import { Body, Controller, Param, Post } from '@nestjs/common';
|
||||
import { DeliveryCallbackService } from './delivery-callback.service';
|
||||
|
||||
@Controller('callbacks/delivery')
|
||||
@Controller('callbacks')
|
||||
export class DeliveryCallbackController {
|
||||
constructor(
|
||||
private readonly tradeService: TradeService,
|
||||
private readonly courier: CourierService,
|
||||
private readonly prisma: PrismaService,
|
||||
) {}
|
||||
constructor(private readonly deliveryCallbackService: DeliveryCallbackService) {}
|
||||
|
||||
@Post('track')
|
||||
async track(@Body() body: { orderNo?: string; orderId?: string; status?: string }) {
|
||||
const baseLog = {
|
||||
scene: 'TRACK_CALLBACK',
|
||||
requestUrl: '/api/v1/callbacks/delivery/track',
|
||||
requestBody: body as Record<string, unknown>,
|
||||
};
|
||||
/** 小飞侠/物流路由变化回调(适配器入口) */
|
||||
@Post('courier/:provider/track')
|
||||
trackByProvider(@Param('provider') provider: string, @Body() body: unknown) {
|
||||
return this.deliveryCallbackService.handleTrackCallback(
|
||||
provider,
|
||||
body,
|
||||
`/api/v1/callbacks/courier/${provider}/track`,
|
||||
);
|
||||
}
|
||||
|
||||
if (!body.orderId && !body.orderNo) {
|
||||
await logCourierCall(this.prisma, {
|
||||
...baseLog,
|
||||
status: 'FAILED',
|
||||
errorMessage: '缺少 orderId / orderNo',
|
||||
});
|
||||
return this.courier.buildTrackCallbackResponse(false);
|
||||
}
|
||||
|
||||
const order = body.orderId
|
||||
? await this.prisma.order.findUnique({ where: { id: BigInt(body.orderId) } })
|
||||
: await this.prisma.order.findUnique({ where: { orderNo: body.orderNo! } });
|
||||
|
||||
if (!order) {
|
||||
await logCourierCall(this.prisma, {
|
||||
...baseLog,
|
||||
status: 'FAILED',
|
||||
errorMessage: '订单不存在',
|
||||
externalNo: body.orderNo,
|
||||
});
|
||||
return this.courier.buildTrackCallbackResponse(false);
|
||||
}
|
||||
|
||||
const statusMap: Record<string, string> = {
|
||||
SHIPPED: 'SHIPPING',
|
||||
OUT_WAREHOUSE: 'OUT_WAREHOUSE',
|
||||
DELIVERED: 'COMPLETED',
|
||||
COMPLETED: 'COMPLETED',
|
||||
};
|
||||
const target = statusMap[body.status ?? ''] ?? body.status;
|
||||
let applied = false;
|
||||
if (target && target !== order.status) {
|
||||
await this.tradeService.applyStatusTransition(order.id, order.status, target, 'DELIVERY_CALLBACK');
|
||||
applied = true;
|
||||
}
|
||||
|
||||
const response = this.courier.buildTrackCallbackResponse(true);
|
||||
await logCourierCall(this.prisma, {
|
||||
...baseLog,
|
||||
responseBody: response,
|
||||
status: 'SUCCESS',
|
||||
externalNo: order.orderNo,
|
||||
ref: { refType: 'ORDER', refId: order.id },
|
||||
errorMessage: applied ? undefined : '状态未变更',
|
||||
});
|
||||
|
||||
return response;
|
||||
/** 兼容旧路径,默认按小飞侠解析 */
|
||||
@Post('delivery/track')
|
||||
trackLegacy(@Body() body: unknown) {
|
||||
return this.deliveryCallbackService.handleTrackCallback(
|
||||
'xfx',
|
||||
body,
|
||||
'/api/v1/callbacks/delivery/track',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 },
|
||||
@@ -124,6 +116,15 @@ export const SYSTEM_CONFIG_FIELDS: SystemConfigFieldMeta[] = [
|
||||
requiresRestart: false,
|
||||
description: '小程序商品首页底部 footer,建议比例 15:4;上传后需点击右上角「保存」',
|
||||
},
|
||||
{
|
||||
key: 'MINI_USER_MIN_VERSION',
|
||||
label: '小程序最低版本',
|
||||
group: G.wechat_mini,
|
||||
type: 'string',
|
||||
requiresRestart: false,
|
||||
placeholder: '3.4.13',
|
||||
description: 'semver 格式;客户端低于此版本时提示更新',
|
||||
},
|
||||
|
||||
{ key: 'OSS_ACCESS_KEY_ID', label: 'OSS AccessKey ID', group: G.oss, type: 'password', secret: true, requiresRestart: true },
|
||||
{ key: 'OSS_ACCESS_KEY_SECRET', label: 'OSS AccessKey Secret', group: G.oss, type: 'password', secret: true, requiresRestart: true },
|
||||
|
||||
@@ -9,6 +9,7 @@ const CMD_SCENE: Record<string, string> = {
|
||||
[XIAOFEIXIA_CMD.ESTIMATE_FREIGHT]: 'ESTIMATE_FREIGHT',
|
||||
[XIAOFEIXIA_CMD.BATCH_GET_ORDER]: 'BATCH_GET_SHIPMENT',
|
||||
[XIAOFEIXIA_CMD.DELIVERY_COVERAGE]: 'CHECK_COVERAGE',
|
||||
[XIAOFEIXIA_CMD.SIGN_PHOTOS]: 'GET_SIGN_PHOTOS',
|
||||
};
|
||||
|
||||
export type CourierLogRef = {
|
||||
|
||||
@@ -29,6 +29,6 @@ import type { ICourierProvider } from './courier.types';
|
||||
},
|
||||
CourierService,
|
||||
],
|
||||
exports: [CourierService, CourierConfigService, COURIER_PROVIDER],
|
||||
exports: [CourierService, CourierConfigService, COURIER_PROVIDER, XiaofeixiaProvider],
|
||||
})
|
||||
export class CourierModule {}
|
||||
|
||||
@@ -12,6 +12,8 @@ import type {
|
||||
ShipmentQuery,
|
||||
TrackCallbackResponse,
|
||||
TrackNode,
|
||||
TrackCallbackPayload,
|
||||
CourierMappedOrderStatus,
|
||||
} from './courier.types';
|
||||
|
||||
/**
|
||||
@@ -45,6 +47,10 @@ export class CourierService {
|
||||
return this.provider.getTrack(query, options);
|
||||
}
|
||||
|
||||
getSignPhotos(query: ShipmentQuery, options?: CourierCallOptions): Promise<string[]> {
|
||||
return this.provider.getSignPhotos(query, options);
|
||||
}
|
||||
|
||||
checkDeliveryCoverage(toAddress: string, options?: CourierCallOptions): Promise<DeliveryCoverageResult> {
|
||||
return this.provider.checkDeliveryCoverage(toAddress, options);
|
||||
}
|
||||
@@ -56,4 +62,12 @@ export class CourierService {
|
||||
buildTrackCallbackResponse(success?: boolean): TrackCallbackResponse {
|
||||
return this.provider.buildTrackCallbackResponse(success);
|
||||
}
|
||||
|
||||
parseTrackCallback(body: unknown): TrackCallbackPayload | null {
|
||||
return this.provider.parseTrackCallback(body);
|
||||
}
|
||||
|
||||
mapTrackStatus(status: string, statusName?: string): CourierMappedOrderStatus | null {
|
||||
return this.provider.mapTrackStatus(status, statusName);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -109,6 +109,13 @@ export interface TrackCallbackResponse {
|
||||
message: string;
|
||||
}
|
||||
|
||||
/** 承运商路由回调映射后的订单履约状态 */
|
||||
export type CourierMappedOrderStatus =
|
||||
| 'OUT_WAREHOUSE'
|
||||
| 'SHIPPING'
|
||||
| 'PENDING_RECEIVE'
|
||||
| 'COMPLETED';
|
||||
|
||||
export interface ICourierProvider {
|
||||
readonly code: CourierProviderCode;
|
||||
|
||||
@@ -117,7 +124,10 @@ export interface ICourierProvider {
|
||||
getShipment(query: ShipmentQuery, options?: CourierCallOptions): Promise<ShipmentDetail>;
|
||||
batchGetShipments(query: BatchShipmentQuery, options?: CourierCallOptions): Promise<ShipmentDetail[]>;
|
||||
getTrack(query: ShipmentQuery, options?: CourierCallOptions): Promise<TrackNode[]>;
|
||||
getSignPhotos(query: ShipmentQuery, options?: CourierCallOptions): Promise<string[]>;
|
||||
checkDeliveryCoverage(toAddress: string, options?: CourierCallOptions): Promise<DeliveryCoverageResult>;
|
||||
estimateFreight(weight: number, options?: CourierCallOptions): Promise<FreightEstimateResult>;
|
||||
parseTrackCallback(body: unknown): TrackCallbackPayload | null;
|
||||
mapTrackStatus(status: string, statusName?: string): CourierMappedOrderStatus | null;
|
||||
buildTrackCallbackResponse(success?: boolean): TrackCallbackResponse;
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ export const XIAOFEIXIA_CMD = {
|
||||
GET_ORDER: '100104',
|
||||
ESTIMATE_FREIGHT: '100105',
|
||||
BATCH_GET_ORDER: '100106',
|
||||
SIGN_PHOTOS: '100108',
|
||||
DELIVERY_COVERAGE: '100301',
|
||||
} as const;
|
||||
|
||||
|
||||
@@ -12,7 +12,9 @@ import type {
|
||||
ShipmentDetail,
|
||||
ShipmentQuery,
|
||||
TrackCallbackResponse,
|
||||
TrackCallbackPayload,
|
||||
TrackNode,
|
||||
CourierMappedOrderStatus,
|
||||
} from '../courier.types';
|
||||
import { XiaofeixiaClient } from './xiaofeixia.client';
|
||||
import { XIAOFEIXIA_CMD } from './xiaofeixia.constants';
|
||||
@@ -121,6 +123,59 @@ export class XiaofeixiaProvider implements ICourierProvider {
|
||||
return data ?? [];
|
||||
}
|
||||
|
||||
async getSignPhotos(query: ShipmentQuery, options?: CourierCallOptions): Promise<string[]> {
|
||||
this.assertShipmentQuery(query);
|
||||
const data = await this.client.request<string[]>(
|
||||
XIAOFEIXIA_CMD.SIGN_PHOTOS,
|
||||
{
|
||||
number: query.trackingNumber,
|
||||
outNumber: query.outNumber,
|
||||
},
|
||||
options?.xiaofeixia,
|
||||
);
|
||||
return (data ?? []).filter((item) => typeof item === 'string' && item.trim().length > 0);
|
||||
}
|
||||
|
||||
parseTrackCallback(body: unknown): TrackCallbackPayload | null {
|
||||
if (!body || typeof body !== 'object') return null;
|
||||
const raw = body as Record<string, unknown>;
|
||||
const outNumber = String(raw.outNumber ?? '').trim();
|
||||
const trackingNumber = String(raw.number ?? raw.trackingNumber ?? '').trim();
|
||||
const status = String(raw.status ?? '').trim();
|
||||
const statusName = String(raw.statusName ?? '').trim();
|
||||
const trackInfo = String(raw.trackInfo ?? '').trim();
|
||||
const createTime = String(raw.createTime ?? '').trim();
|
||||
if (!outNumber && !trackingNumber) return null;
|
||||
if (!status && !trackInfo) return null;
|
||||
return {
|
||||
outNumber,
|
||||
trackingNumber,
|
||||
status,
|
||||
statusName,
|
||||
trackInfo,
|
||||
createTime,
|
||||
};
|
||||
}
|
||||
|
||||
mapTrackStatus(status: string, statusName?: string): CourierMappedOrderStatus | null {
|
||||
const name = (statusName || '').trim();
|
||||
if (status === '5' || /签收/.test(name)) {
|
||||
return 'COMPLETED';
|
||||
}
|
||||
switch (String(status).trim()) {
|
||||
case '1':
|
||||
return 'OUT_WAREHOUSE';
|
||||
case '2':
|
||||
case '3':
|
||||
case '4':
|
||||
return 'SHIPPING';
|
||||
case '7':
|
||||
return null;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async checkDeliveryCoverage(toAddress: string, options?: CourierCallOptions): Promise<DeliveryCoverageResult> {
|
||||
const data = await this.client.request<XiaofeixiaDeliveryCoverageData>(
|
||||
XIAOFEIXIA_CMD.DELIVERY_COVERAGE,
|
||||
|
||||
@@ -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(', ')}`;
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user