Compare commits
52 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 0181af09c5 | |||
| 9cd0c9508a | |||
| 4f363fa9e7 | |||
| 291137a15d | |||
| e2a5f21f9d | |||
| 3ef4432b2f | |||
| 33b868dfac | |||
| 5c4ad1d8db | |||
| a346fae7a4 | |||
| 37bc297d1a | |||
| bc1616c3f7 | |||
| 46a200e0ba | |||
| 429eaabe6b | |||
| 607a0224cd | |||
| 53e0db6a98 | |||
| 456b3af461 | |||
| 1f7ecffe4c | |||
| 8df0a2bea7 | |||
| 672a995c59 | |||
| 69f52921a7 | |||
| 9cb88dc181 | |||
| 345d5db9c9 | |||
| 7c9240fc84 | |||
| 2610288df0 | |||
| 62652cd072 | |||
| 9d49ed5e70 | |||
| bdbd135318 | |||
| 8ca893efab | |||
| d0ab838da6 | |||
| 50ab0f1748 | |||
| fa6fb80d19 | |||
| bd1930f6b1 | |||
| dc4295d1bd | |||
| 256526c5ec | |||
| 1c4b986924 | |||
| bf501d2374 | |||
| 442500b1a1 | |||
| 490c26a7e1 | |||
| b40eb83f27 | |||
| f80a0f2c27 | |||
| 528669f662 | |||
| f5e523a425 | |||
| 16fa07ceaf | |||
| b21403a47c | |||
| 02d89e6385 | |||
| f9a5b6e81a | |||
| 16c386f165 | |||
| 1c787ed576 | |||
| 4372018c09 | |||
| aca3df4bf2 | |||
| 71f508e02b | |||
| 9d96c73246 |
@@ -11,6 +11,7 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ant-design/icons": "^5.5.1",
|
"@ant-design/icons": "^5.5.1",
|
||||||
"@dukang/shared-types": "workspace:*",
|
"@dukang/shared-types": "workspace:*",
|
||||||
|
"@dukang/shared-ui": "workspace:*",
|
||||||
"antd": "^5.22.0",
|
"antd": "^5.22.0",
|
||||||
"dayjs": "^1.11.13",
|
"dayjs": "^1.11.13",
|
||||||
"echarts": "^6.1.0",
|
"echarts": "^6.1.0",
|
||||||
|
|||||||
@@ -47,8 +47,13 @@ import WechatBindingsPage from './pages/WechatBindingsPage';
|
|||||||
import HqPermissionsPage from './pages/HqPermissionsPage';
|
import HqPermissionsPage from './pages/HqPermissionsPage';
|
||||||
import SystemSettingsPage from './pages/SystemSettingsPage';
|
import SystemSettingsPage from './pages/SystemSettingsPage';
|
||||||
import WecomBotsPage from './pages/WecomBotsPage';
|
import WecomBotsPage from './pages/WecomBotsPage';
|
||||||
|
import WecomMessagePushesPage from './pages/WecomMessagePushesPage';
|
||||||
|
import WecomBotLogsPage from './pages/WecomBotLogsPage';
|
||||||
import LlmConfigsPage from './pages/LlmConfigsPage';
|
import LlmConfigsPage from './pages/LlmConfigsPage';
|
||||||
import KnowledgeBasesPage from './pages/KnowledgeBasesPage';
|
import KnowledgeBasesPage from './pages/KnowledgeBasesPage';
|
||||||
|
import DevPlanVersionsPage from './pages/DevPlanVersionsPage';
|
||||||
|
import DevPlanTasksPage from './pages/DevPlanTasksPage';
|
||||||
|
import DevPlanSettingsPage from './pages/DevPlanSettingsPage';
|
||||||
|
|
||||||
function RequireAuth({ children }: { children: React.ReactNode }) {
|
function RequireAuth({ children }: { children: React.ReactNode }) {
|
||||||
if (!getToken()) return <Navigate to="/login" replace />;
|
if (!getToken()) return <Navigate to="/login" replace />;
|
||||||
@@ -75,9 +80,15 @@ export default function App() {
|
|||||||
<Route index element={<PromoCodeDetailPage />} />
|
<Route index element={<PromoCodeDetailPage />} />
|
||||||
<Route path="users" element={<PromoCodeUsersPage />} />
|
<Route path="users" element={<PromoCodeUsersPage />} />
|
||||||
</Route>
|
</Route>
|
||||||
<Route path="/wecom-bots" element={<WecomBotsPage />} />
|
<Route path="/wecom-bots" element={<Navigate to="/wecom/bots" replace />} />
|
||||||
|
<Route path="/wecom/bots" element={<WecomBotsPage />} />
|
||||||
|
<Route path="/wecom/pushes" element={<WecomMessagePushesPage />} />
|
||||||
|
<Route path="/logs/wecom-bots" element={<WecomBotLogsPage />} />
|
||||||
<Route path="/llm-configs" element={<LlmConfigsPage />} />
|
<Route path="/llm-configs" element={<LlmConfigsPage />} />
|
||||||
<Route path="/knowledge-bases" element={<KnowledgeBasesPage />} />
|
<Route path="/knowledge-bases" element={<KnowledgeBasesPage />} />
|
||||||
|
<Route path="/dev-plan/versions" element={<DevPlanVersionsPage />} />
|
||||||
|
<Route path="/dev-plan/tasks" element={<DevPlanTasksPage />} />
|
||||||
|
<Route path="/dev-plan/settings" element={<DevPlanSettingsPage />} />
|
||||||
<Route path="/products" element={<ProductsPage />} />
|
<Route path="/products" element={<ProductsPage />} />
|
||||||
<Route path="/product-detail-templates" element={<ProductDetailTemplatesPage />} />
|
<Route path="/product-detail-templates" element={<ProductDetailTemplatesPage />} />
|
||||||
<Route path="/stores" element={<StoresPage />} />
|
<Route path="/stores" element={<StoresPage />} />
|
||||||
|
|||||||
@@ -1,14 +1,14 @@
|
|||||||
import { useEffect, useState } from 'react';
|
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 { DownOutlined, UpOutlined } from '@ant-design/icons';
|
||||||
import type { StorePackageItemDto } from '@dukang/shared-types';
|
import type { StorePackageItemDto } from '@dukang/shared-types';
|
||||||
import { STORE_PACKAGE_MAX_COUNT } from '@dukang/shared-types';
|
import { STORE_PACKAGE_MAX_COUNT } from '@dukang/shared-types';
|
||||||
import { request } from '../lib/api';
|
import { request } from '../lib/api';
|
||||||
|
import OssUpload from './OssUpload';
|
||||||
type PackageRow = StorePackageItemDto;
|
type PackageRow = StorePackageItemDto;
|
||||||
|
|
||||||
function emptyRow(index = 0): PackageRow {
|
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 }) {
|
export default function AdminStorePackagesSection({ storeId }: { storeId: string }) {
|
||||||
@@ -41,7 +41,11 @@ export default function AdminStorePackagesSection({ storeId }: { storeId: string
|
|||||||
}
|
}
|
||||||
|
|
||||||
function removeAt(index: number) {
|
function removeAt(index: number) {
|
||||||
setItems((prev) => prev.filter((_, i) => i !== index).map((item, i) => ({ ...item, sortOrder: i })));
|
const run = () => {
|
||||||
|
setItems((prev) => {
|
||||||
|
const next = prev.filter((_, i) => i !== index).map((item, i) => ({ ...item, sortOrder: i }));
|
||||||
|
return next.length ? next : [];
|
||||||
|
});
|
||||||
setCollapsed((prev) => {
|
setCollapsed((prev) => {
|
||||||
const next: Record<number, boolean> = {};
|
const next: Record<number, boolean> = {};
|
||||||
Object.entries(prev).forEach(([k, v]) => {
|
Object.entries(prev).forEach(([k, v]) => {
|
||||||
@@ -51,8 +55,19 @@ export default function AdminStorePackagesSection({ storeId }: { storeId: string
|
|||||||
});
|
});
|
||||||
return next;
|
return next;
|
||||||
});
|
});
|
||||||
|
};
|
||||||
|
if (items.length === 1) {
|
||||||
|
Modal.confirm({
|
||||||
|
title: '清空门店套餐',
|
||||||
|
content: '删除最后一条套餐后,该门店将无展示套餐,确认继续?',
|
||||||
|
okText: '确认删除',
|
||||||
|
cancelText: '取消',
|
||||||
|
onOk: run,
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
run();
|
||||||
}
|
}
|
||||||
|
|
||||||
function toggleCollapse(index: number) {
|
function toggleCollapse(index: number) {
|
||||||
setCollapsed((prev) => ({ ...prev, [index]: !prev[index] }));
|
setCollapsed((prev) => ({ ...prev, [index]: !prev[index] }));
|
||||||
}
|
}
|
||||||
@@ -65,6 +80,7 @@ export default function AdminStorePackagesSection({ storeId }: { storeId: string
|
|||||||
dishes: item.dishes.trim(),
|
dishes: item.dishes.trim(),
|
||||||
usableTime: item.usableTime?.trim() || null,
|
usableTime: item.usableTime?.trim() || null,
|
||||||
otherNotes: item.otherNotes?.trim() || null,
|
otherNotes: item.otherNotes?.trim() || null,
|
||||||
|
imageUrl: item.imageUrl?.trim() || null,
|
||||||
sortOrder: index,
|
sortOrder: index,
|
||||||
}))
|
}))
|
||||||
.filter((item) => item.name || item.dishes || item.price);
|
.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 <Typography.Text type="secondary">加载套餐中…</Typography.Text>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!items.length) {
|
||||||
return (
|
return (
|
||||||
<Form layout="vertical" requiredMark={false}>
|
<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
|
<Alert
|
||||||
type="info"
|
type="info"
|
||||||
showIcon
|
showIcon
|
||||||
@@ -140,12 +169,11 @@ export default function AdminStorePackagesSection({ storeId }: { storeId: string
|
|||||||
{displayName}
|
{displayName}
|
||||||
</Typography.Title>
|
</Typography.Title>
|
||||||
</Button>
|
</Button>
|
||||||
{items.length > 1 ? (
|
{items.length > 0 ? (
|
||||||
<Button type="link" danger onClick={() => removeAt(index)}>
|
<Button type="link" danger onClick={() => removeAt(index)}>
|
||||||
删除
|
删除
|
||||||
</Button>
|
</Button>
|
||||||
) : null}
|
) : null} </Space>
|
||||||
</Space>
|
|
||||||
|
|
||||||
{!isCollapsed ? (
|
{!isCollapsed ? (
|
||||||
<>
|
<>
|
||||||
@@ -186,8 +214,16 @@ export default function AdminStorePackagesSection({ storeId }: { storeId: string
|
|||||||
/>
|
/>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
|
|
||||||
<Form.Item label="其他说明" style={{ marginBottom: 0 }}>
|
<Form.Item label="套餐图片" style={{ marginBottom: 12 }}>
|
||||||
<Input
|
<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="不可叠加"
|
placeholder="不可叠加"
|
||||||
value={item.otherNotes || ''}
|
value={item.otherNotes || ''}
|
||||||
onChange={(e) => updateAt(index, { otherNotes: e.target.value })}
|
onChange={(e) => updateAt(index, { otherNotes: e.target.value })}
|
||||||
|
|||||||
@@ -15,8 +15,6 @@ type OssUploadProps = {
|
|||||||
placeholder?: string;
|
placeholder?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
const DEFAULT_MAX_MB = 10;
|
|
||||||
|
|
||||||
export default function OssUpload({
|
export default function OssUpload({
|
||||||
value,
|
value,
|
||||||
onChange,
|
onChange,
|
||||||
@@ -24,7 +22,6 @@ export default function OssUpload({
|
|||||||
bizType,
|
bizType,
|
||||||
mediaType = 'IMAGE',
|
mediaType = 'IMAGE',
|
||||||
accept,
|
accept,
|
||||||
maxSizeMb = DEFAULT_MAX_MB,
|
|
||||||
placeholder = '上传后自动填入,或手动粘贴 URL',
|
placeholder = '上传后自动填入,或手动粘贴 URL',
|
||||||
}: OssUploadProps) {
|
}: OssUploadProps) {
|
||||||
const [uploading, setUploading] = useState(false);
|
const [uploading, setUploading] = useState(false);
|
||||||
@@ -34,12 +31,6 @@ export default function OssUpload({
|
|||||||
|
|
||||||
const customRequest: UploadProps['customRequest'] = async ({ file, onSuccess, onError }) => {
|
const customRequest: UploadProps['customRequest'] = async ({ file, onSuccess, onError }) => {
|
||||||
const raw = file as File;
|
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);
|
setUploading(true);
|
||||||
try {
|
try {
|
||||||
const result = await uploadFileToOss(raw, { bizType, mediaType });
|
const result = await uploadFileToOss(raw, { bizType, mediaType });
|
||||||
|
|||||||
@@ -0,0 +1,84 @@
|
|||||||
|
import { Descriptions } from 'antd';
|
||||||
|
import { REDEEM_CHANNEL_LABELS, type RedeemChannel } from '@dukang/shared-types';
|
||||||
|
import { fmtTime } from '../lib/constants';
|
||||||
|
|
||||||
|
function maskPhone(phone: string | null | undefined) {
|
||||||
|
if (!phone || phone.length < 7) return phone ?? '—';
|
||||||
|
return `${phone.slice(0, 3)}****${phone.slice(-4)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
detail: Record<string, unknown>;
|
||||||
|
/** 列表页已脱敏展示时可设为 false,详情抽屉展示完整手机号 */
|
||||||
|
maskUserPhone?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function RedeemRecordDetailDescriptions({ detail, maskUserPhone = false }: Props) {
|
||||||
|
const user = detail.user as
|
||||||
|
| { userNo?: string; nickname?: string | null; phone?: string | null }
|
||||||
|
| undefined;
|
||||||
|
const store = detail.store as
|
||||||
|
| {
|
||||||
|
name?: string;
|
||||||
|
cityName?: string;
|
||||||
|
address?: string;
|
||||||
|
partnerAccount?: { companyName?: string };
|
||||||
|
}
|
||||||
|
| undefined;
|
||||||
|
const coupon = detail.coupon as { couponNo?: string; order?: { orderNo?: string } } | undefined;
|
||||||
|
const channel = detail.channel === 'PHONE' ? 'PHONE' : 'SCAN';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Descriptions column={1} bordered size="small">
|
||||||
|
<Descriptions.Item label="核销号">{String(detail.redeemNo ?? '—')}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="方式">{REDEEM_CHANNEL_LABELS[channel as RedeemChannel]}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="核销额">¥{Number(detail.amount ?? 0).toFixed(2)}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="结算额">¥{Number(detail.settleAmount ?? 0).toFixed(2)}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="时间">{fmtTime(String(detail.createdAt ?? ''))}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="用户编号">{user?.userNo ?? '—'}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="用户昵称">{user?.nickname?.trim() || '—'}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="用户手机">
|
||||||
|
{maskUserPhone ? maskPhone(user?.phone) : user?.phone || '—'}
|
||||||
|
</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="门店">
|
||||||
|
{store?.name ?? '—'}
|
||||||
|
{store?.cityName ? `(${store.cityName})` : ''}
|
||||||
|
</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="门店地址">{store?.address ?? '—'}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="合伙人">{store?.partnerAccount?.companyName ?? '—'}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="权益券号">{coupon?.couponNo ?? '—'}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="关联订单">{coupon?.order?.orderNo ?? '—'}</Descriptions.Item>
|
||||||
|
{Array.isArray(detail.allocations) && (detail.allocations as unknown[]).length > 0 ? (
|
||||||
|
<Descriptions.Item label="券分摊">
|
||||||
|
{(
|
||||||
|
detail.allocations as Array<{
|
||||||
|
couponNo?: string;
|
||||||
|
orderNo?: string | null;
|
||||||
|
amount?: number;
|
||||||
|
}>
|
||||||
|
)
|
||||||
|
.map((a, idx) => {
|
||||||
|
const role = idx === 0 ? '主' : '次';
|
||||||
|
return `${role} ${a.couponNo ?? '—'}¥${Number(a.amount ?? 0).toFixed(2)}${
|
||||||
|
a.orderNo ? `(订单 ${a.orderNo})` : ''
|
||||||
|
}`;
|
||||||
|
})
|
||||||
|
.join(';')}
|
||||||
|
</Descriptions.Item>
|
||||||
|
) : null}
|
||||||
|
{detail.payout ? (
|
||||||
|
<Descriptions.Item label="门店结算单">
|
||||||
|
¥{Number((detail.payout as { settleAmount?: number }).settleAmount ?? 0).toFixed(2)}
|
||||||
|
{' / '}
|
||||||
|
{String((detail.payout as { status?: string }).status ?? '—')}
|
||||||
|
</Descriptions.Item>
|
||||||
|
) : null}
|
||||||
|
{detail.rating ? (
|
||||||
|
<Descriptions.Item label="评价">
|
||||||
|
服务 {(detail.rating as { serviceScore?: number }).serviceScore ?? '—'} 分 / 环境{' '}
|
||||||
|
{(detail.rating as { envScore?: number }).envScore ?? '—'} 分
|
||||||
|
</Descriptions.Item>
|
||||||
|
) : null}
|
||||||
|
</Descriptions>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -18,6 +18,7 @@ import {
|
|||||||
LockOutlined,
|
LockOutlined,
|
||||||
SettingOutlined,
|
SettingOutlined,
|
||||||
AccountBookOutlined,
|
AccountBookOutlined,
|
||||||
|
ProjectOutlined,
|
||||||
} from '@ant-design/icons';
|
} from '@ant-design/icons';
|
||||||
import { hasAnySystemSettingsPermission } from '@dukang/shared-types';
|
import { hasAnySystemSettingsPermission } from '@dukang/shared-types';
|
||||||
import { clearAuth, request, type HqProfile } from '../lib/api';
|
import { clearAuth, request, type HqProfile } from '../lib/api';
|
||||||
@@ -42,7 +43,15 @@ const MENU_ITEMS: MenuProps['items'] = [
|
|||||||
},
|
},
|
||||||
{ key: '/orders', icon: <ShoppingOutlined />, label: '订单' },
|
{ key: '/orders', icon: <ShoppingOutlined />, label: '订单' },
|
||||||
{ key: '/promo-codes', icon: <GiftOutlined />, label: '推广码' },
|
{ key: '/promo-codes', icon: <GiftOutlined />, label: '推广码' },
|
||||||
{ key: '/wecom-bots', icon: <TeamOutlined />, label: '企微机器人' },
|
{
|
||||||
|
key: 'wecom-group',
|
||||||
|
icon: <TeamOutlined />,
|
||||||
|
label: '企微机器人',
|
||||||
|
children: [
|
||||||
|
{ key: '/wecom/bots', label: '智能机器人' },
|
||||||
|
{ key: '/wecom/pushes', label: '消息推送' },
|
||||||
|
],
|
||||||
|
},
|
||||||
{ key: '/llm-configs', icon: <RobotOutlined />, label: '语言模型' },
|
{ key: '/llm-configs', icon: <RobotOutlined />, label: '语言模型' },
|
||||||
{ key: '/knowledge-bases', icon: <FileTextOutlined />, label: '知识库' },
|
{ key: '/knowledge-bases', icon: <FileTextOutlined />, label: '知识库' },
|
||||||
{
|
{
|
||||||
@@ -110,6 +119,16 @@ const MENU_ITEMS: MenuProps['items'] = [
|
|||||||
{ key: '/tickets/support', label: '技术支持' },
|
{ key: '/tickets/support', label: '技术支持' },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
key: 'dev-plan-group',
|
||||||
|
icon: <ProjectOutlined />,
|
||||||
|
label: '开发计划',
|
||||||
|
children: [
|
||||||
|
{ key: '/dev-plan/versions', label: '版本列表' },
|
||||||
|
{ key: '/dev-plan/tasks', label: '任务列表' },
|
||||||
|
{ key: '/dev-plan/settings', label: '开发设置' },
|
||||||
|
],
|
||||||
|
},
|
||||||
{ key: '/invoices', icon: <FileTextOutlined />, label: '发票管理' },
|
{ key: '/invoices', icon: <FileTextOutlined />, label: '发票管理' },
|
||||||
{ key: '/resources', icon: <CloudUploadOutlined />, label: 'OSS 资源库' },
|
{ key: '/resources', icon: <CloudUploadOutlined />, label: 'OSS 资源库' },
|
||||||
{
|
{
|
||||||
@@ -123,6 +142,7 @@ const MENU_ITEMS: MenuProps['items'] = [
|
|||||||
{ key: '/logs/hq', label: 'HQ 操作日志' },
|
{ key: '/logs/hq', label: 'HQ 操作日志' },
|
||||||
{ key: '/logs/third-party', label: '第三方日志' },
|
{ key: '/logs/third-party', label: '第三方日志' },
|
||||||
{ key: '/logs/domain-events', label: '领域事件' },
|
{ key: '/logs/domain-events', label: '领域事件' },
|
||||||
|
{ key: '/logs/wecom-bots', label: '智能机器人日志' },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{ key: '/hq-permissions', icon: <LockOutlined />, label: '权限分配' },
|
{ key: '/hq-permissions', icon: <LockOutlined />, label: '权限分配' },
|
||||||
@@ -134,6 +154,9 @@ function menuAllowed(key: string, permissionKeys: string[]): boolean {
|
|||||||
if (key === 'tickets-group') {
|
if (key === 'tickets-group') {
|
||||||
return permissionKeys.includes('tickets') || permissionKeys.includes('tech_support');
|
return permissionKeys.includes('tickets') || permissionKeys.includes('tech_support');
|
||||||
}
|
}
|
||||||
|
if (key === 'dev-plan-group') {
|
||||||
|
return permissionKeys.includes('dev_plan');
|
||||||
|
}
|
||||||
const map: Record<string, string | 'system_settings_any'> = {
|
const map: Record<string, string | 'system_settings_any'> = {
|
||||||
'/': 'dashboard',
|
'/': 'dashboard',
|
||||||
'/users': 'users',
|
'/users': 'users',
|
||||||
@@ -143,7 +166,9 @@ function menuAllowed(key: string, permissionKeys: string[]): boolean {
|
|||||||
'/product-detail-templates': 'products',
|
'/product-detail-templates': 'products',
|
||||||
'/orders': 'orders',
|
'/orders': 'orders',
|
||||||
'/promo-codes': 'promo_codes',
|
'/promo-codes': 'promo_codes',
|
||||||
'/wecom-bots': 'wecom_bots',
|
'/wecom/bots': 'wecom_bots',
|
||||||
|
'/wecom/pushes': 'wecom_bots',
|
||||||
|
'wecom-group': 'wecom_bots',
|
||||||
'/llm-configs': 'llm_configs',
|
'/llm-configs': 'llm_configs',
|
||||||
'/knowledge-bases': 'knowledge_bases',
|
'/knowledge-bases': 'knowledge_bases',
|
||||||
'stores-group': 'stores',
|
'stores-group': 'stores',
|
||||||
@@ -175,10 +200,15 @@ function menuAllowed(key: string, permissionKeys: string[]): boolean {
|
|||||||
'/deliveries/xiaofeixia': 'deliveries',
|
'/deliveries/xiaofeixia': 'deliveries',
|
||||||
'/tickets': 'tickets',
|
'/tickets': 'tickets',
|
||||||
'/tickets/support': 'tech_support',
|
'/tickets/support': 'tech_support',
|
||||||
|
'dev-plan-group': 'dev_plan',
|
||||||
|
'/dev-plan/versions': 'dev_plan',
|
||||||
|
'/dev-plan/tasks': 'dev_plan',
|
||||||
|
'/dev-plan/settings': 'dev_plan',
|
||||||
'/invoices': 'invoices',
|
'/invoices': 'invoices',
|
||||||
'/resources': 'resources',
|
'/resources': 'resources',
|
||||||
'logs-group': 'logs',
|
'logs-group': 'logs',
|
||||||
'/logs/users': 'logs',
|
'/logs/users': 'logs',
|
||||||
|
'/logs/wecom-bots': 'logs',
|
||||||
'/logs/stores': 'logs',
|
'/logs/stores': 'logs',
|
||||||
'/logs/partners': 'logs',
|
'/logs/partners': 'logs',
|
||||||
'/logs/hq': 'logs',
|
'/logs/hq': 'logs',
|
||||||
|
|||||||
@@ -1,4 +1,9 @@
|
|||||||
import { apiBase, CLIENT_APP, getToken, clearAuth } from './api';
|
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';
|
export type OssMediaType = 'IMAGE' | 'VIDEO' | 'FILE';
|
||||||
|
|
||||||
@@ -9,14 +14,24 @@ export type UploadFileResult = {
|
|||||||
mock: boolean;
|
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,避免浏览器直传跨域 */
|
/** 经 API 服务端转存 OSS,避免浏览器直传跨域 */
|
||||||
export async function uploadFileToOss(
|
export async function uploadFileToOss(
|
||||||
file: File,
|
file: File,
|
||||||
options: { bizType: string; mediaType?: OssMediaType },
|
options: { bizType: string; mediaType?: OssMediaType },
|
||||||
): Promise<UploadFileResult> {
|
): Promise<UploadFileResult> {
|
||||||
const mediaType = options.mediaType ?? (file.type.startsWith('video/') ? 'VIDEO' : 'IMAGE');
|
const mediaType = options.mediaType ?? (file.type.startsWith('video/') ? 'VIDEO' : 'IMAGE');
|
||||||
|
const prepared = await prepareUploadFile(file, mediaType);
|
||||||
const formData = new FormData();
|
const formData = new FormData();
|
||||||
formData.append('file', file);
|
formData.append('file', prepared);
|
||||||
formData.append('bizType', options.bizType);
|
formData.append('bizType', options.bizType);
|
||||||
formData.append('mediaType', mediaType);
|
formData.append('mediaType', mediaType);
|
||||||
|
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ import type { ColumnsType } from 'antd/es/table';
|
|||||||
import type { AdminBenefitGrantRequest } from '@dukang/shared-types';
|
import type { AdminBenefitGrantRequest } from '@dukang/shared-types';
|
||||||
import { request } from '../lib/api';
|
import { request } from '../lib/api';
|
||||||
import { COUPON_STATUS_LABELS, fmtTime } from '../lib/constants';
|
import { COUPON_STATUS_LABELS, fmtTime } from '../lib/constants';
|
||||||
|
import RedeemRecordDetailDescriptions from '../components/RedeemRecordDetailDescriptions';
|
||||||
import { useAdminList } from '../lib/useAdminList';
|
import { useAdminList } from '../lib/useAdminList';
|
||||||
|
|
||||||
type Row = {
|
type Row = {
|
||||||
@@ -242,7 +243,8 @@ export default function BenefitCouponsPage() {
|
|||||||
|
|
||||||
<Drawer
|
<Drawer
|
||||||
title="权益券详情"
|
title="权益券详情"
|
||||||
width={720}
|
width={980}
|
||||||
|
styles={{ body: { paddingBottom: 24 } }}
|
||||||
open={drawerOpen}
|
open={drawerOpen}
|
||||||
onClose={() => setDrawerOpen(false)}
|
onClose={() => setDrawerOpen(false)}
|
||||||
extra={
|
extra={
|
||||||
@@ -310,14 +312,15 @@ export default function BenefitCouponsPage() {
|
|||||||
size="small"
|
size="small"
|
||||||
rowKey="id"
|
rowKey="id"
|
||||||
pagination={false}
|
pagination={false}
|
||||||
|
tableLayout="fixed"
|
||||||
locale={{ emptyText: '暂无关联核销单' }}
|
locale={{ emptyText: '暂无关联核销单' }}
|
||||||
dataSource={detail.redeemRecords ?? []}
|
dataSource={detail.redeemRecords ?? []}
|
||||||
columns={[
|
columns={[
|
||||||
{ title: '核销号', dataIndex: 'redeemNo', width: 160, ellipsis: true },
|
{ title: '核销号', dataIndex: 'redeemNo', ellipsis: true },
|
||||||
{
|
{
|
||||||
title: '角色',
|
title: '角色',
|
||||||
dataIndex: 'role',
|
dataIndex: 'role',
|
||||||
width: 70,
|
width: 72,
|
||||||
render: (v: string | undefined) =>
|
render: (v: string | undefined) =>
|
||||||
v === 'SECONDARY' ? <Tag color="orange">次券</Tag> : <Tag color="blue">主券</Tag>,
|
v === 'SECONDARY' ? <Tag color="orange">次券</Tag> : <Tag color="blue">主券</Tag>,
|
||||||
},
|
},
|
||||||
@@ -331,31 +334,31 @@ export default function BenefitCouponsPage() {
|
|||||||
{
|
{
|
||||||
title: '本券分摊',
|
title: '本券分摊',
|
||||||
dataIndex: 'couponAmount',
|
dataIndex: 'couponAmount',
|
||||||
width: 95,
|
width: 96,
|
||||||
render: (v: number | undefined, row: CouponRedeemRecord) =>
|
render: (v: number | undefined, row: CouponRedeemRecord) =>
|
||||||
`¥${Number(v ?? row.amount).toFixed(2)}`,
|
`¥${Number(v ?? row.amount).toFixed(2)}`,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '核销总额',
|
title: '核销总额',
|
||||||
dataIndex: 'amount',
|
dataIndex: 'amount',
|
||||||
width: 90,
|
width: 96,
|
||||||
render: (v: number) => `¥${Number(v).toFixed(2)}`,
|
render: (v: number) => `¥${Number(v).toFixed(2)}`,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '结算额',
|
title: '结算额',
|
||||||
dataIndex: 'settleAmount',
|
dataIndex: 'settleAmount',
|
||||||
width: 90,
|
width: 96,
|
||||||
render: (v: number) => `¥${Number(v).toFixed(2)}`,
|
render: (v: number) => `¥${Number(v).toFixed(2)}`,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '时间',
|
title: '时间',
|
||||||
dataIndex: 'createdAt',
|
dataIndex: 'createdAt',
|
||||||
width: 150,
|
width: 148,
|
||||||
render: (v: string) => fmtTime(v),
|
render: (v: string) => fmtTime(v),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '操作',
|
title: '操作',
|
||||||
width: 70,
|
width: 64,
|
||||||
render: (_: unknown, row: CouponRedeemRecord) => (
|
render: (_: unknown, row: CouponRedeemRecord) => (
|
||||||
<Button type="link" size="small" onClick={() => void openRedeemDetail(row.id)}>
|
<Button type="link" size="small" onClick={() => void openRedeemDetail(row.id)}>
|
||||||
详情
|
详情
|
||||||
@@ -374,7 +377,7 @@ export default function BenefitCouponsPage() {
|
|||||||
|
|
||||||
<Drawer
|
<Drawer
|
||||||
title="核销单详情"
|
title="核销单详情"
|
||||||
width={520}
|
width={640}
|
||||||
open={redeemDrawerOpen}
|
open={redeemDrawerOpen}
|
||||||
onClose={() => {
|
onClose={() => {
|
||||||
setRedeemDrawerOpen(false);
|
setRedeemDrawerOpen(false);
|
||||||
@@ -385,79 +388,7 @@ export default function BenefitCouponsPage() {
|
|||||||
{redeemDetailLoading ? (
|
{redeemDetailLoading ? (
|
||||||
<Typography.Text type="secondary">加载中…</Typography.Text>
|
<Typography.Text type="secondary">加载中…</Typography.Text>
|
||||||
) : redeemDetail ? (
|
) : redeemDetail ? (
|
||||||
<Descriptions column={1} bordered size="small">
|
<RedeemRecordDetailDescriptions detail={redeemDetail} />
|
||||||
<Descriptions.Item label="核销号">{String(redeemDetail.redeemNo ?? '—')}</Descriptions.Item>
|
|
||||||
<Descriptions.Item label="核销额">
|
|
||||||
¥{Number(redeemDetail.amount ?? 0).toFixed(2)}
|
|
||||||
</Descriptions.Item>
|
|
||||||
<Descriptions.Item label="结算额">
|
|
||||||
¥{Number(redeemDetail.settleAmount ?? 0).toFixed(2)}
|
|
||||||
</Descriptions.Item>
|
|
||||||
<Descriptions.Item label="时间">{fmtTime(String(redeemDetail.createdAt ?? ''))}</Descriptions.Item>
|
|
||||||
<Descriptions.Item label="用户">
|
|
||||||
{String((redeemDetail.user as { userNo?: string } | undefined)?.userNo ?? '—')}
|
|
||||||
{(redeemDetail.user as { phone?: string | null } | undefined)?.phone
|
|
||||||
? ` / ${(redeemDetail.user as { phone?: string | null }).phone}`
|
|
||||||
: ''}
|
|
||||||
</Descriptions.Item>
|
|
||||||
<Descriptions.Item label="门店">
|
|
||||||
{String((redeemDetail.store as { name?: string } | undefined)?.name ?? '—')}
|
|
||||||
{(redeemDetail.store as { cityName?: string } | undefined)?.cityName
|
|
||||||
? `(${(redeemDetail.store as { cityName?: string }).cityName})`
|
|
||||||
: ''}
|
|
||||||
</Descriptions.Item>
|
|
||||||
<Descriptions.Item label="门店地址">
|
|
||||||
{String((redeemDetail.store as { address?: string } | undefined)?.address ?? '—')}
|
|
||||||
</Descriptions.Item>
|
|
||||||
<Descriptions.Item label="合伙人">
|
|
||||||
{String(
|
|
||||||
(redeemDetail.store as { partnerAccount?: { companyName?: string } } | undefined)
|
|
||||||
?.partnerAccount?.companyName ?? '—',
|
|
||||||
)}
|
|
||||||
</Descriptions.Item>
|
|
||||||
<Descriptions.Item label="权益券号">
|
|
||||||
{String((redeemDetail.coupon as { couponNo?: string } | undefined)?.couponNo ?? '—')}
|
|
||||||
</Descriptions.Item>
|
|
||||||
<Descriptions.Item label="关联订单">
|
|
||||||
{String(
|
|
||||||
(redeemDetail.coupon as { order?: { orderNo?: string } } | undefined)?.order?.orderNo ??
|
|
||||||
'—',
|
|
||||||
)}
|
|
||||||
</Descriptions.Item>
|
|
||||||
{Array.isArray(redeemDetail.allocations) &&
|
|
||||||
(redeemDetail.allocations as unknown[]).length > 0 ? (
|
|
||||||
<Descriptions.Item label="券分摊">
|
|
||||||
{(
|
|
||||||
redeemDetail.allocations as Array<{
|
|
||||||
couponNo?: string;
|
|
||||||
orderNo?: string | null;
|
|
||||||
amount?: number;
|
|
||||||
sortOrder?: number;
|
|
||||||
}>
|
|
||||||
)
|
|
||||||
.map((a, idx) => {
|
|
||||||
const role = idx === 0 ? '主' : '次';
|
|
||||||
return `${role} ${a.couponNo ?? '—'}¥${Number(a.amount ?? 0).toFixed(2)}${
|
|
||||||
a.orderNo ? `(订单 ${a.orderNo})` : ''
|
|
||||||
}`;
|
|
||||||
})
|
|
||||||
.join(';')}
|
|
||||||
</Descriptions.Item>
|
|
||||||
) : null}
|
|
||||||
{redeemDetail.payout ? (
|
|
||||||
<Descriptions.Item label="门店结算单">
|
|
||||||
¥{Number((redeemDetail.payout as { settleAmount?: number }).settleAmount ?? 0).toFixed(2)}
|
|
||||||
{' / '}
|
|
||||||
{String((redeemDetail.payout as { status?: string }).status ?? '—')}
|
|
||||||
</Descriptions.Item>
|
|
||||||
) : null}
|
|
||||||
{redeemDetail.rating ? (
|
|
||||||
<Descriptions.Item label="评价">
|
|
||||||
服务 {(redeemDetail.rating as { serviceScore?: number }).serviceScore ?? '—'} 分 / 环境{' '}
|
|
||||||
{(redeemDetail.rating as { envScore?: number }).envScore ?? '—'} 分
|
|
||||||
</Descriptions.Item>
|
|
||||||
) : null}
|
|
||||||
</Descriptions>
|
|
||||||
) : null}
|
) : null}
|
||||||
</Drawer>
|
</Drawer>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -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 { UploadOutlined } from '@ant-design/icons';
|
||||||
import type {
|
import type {
|
||||||
KnowledgeBaseDto,
|
KnowledgeBaseDto,
|
||||||
|
KnowledgeDocumentDetailDto,
|
||||||
KnowledgeDocumentDto,
|
KnowledgeDocumentDto,
|
||||||
} from '@dukang/shared-types';
|
} from '@dukang/shared-types';
|
||||||
import { request } from '../lib/api';
|
import { request } from '../lib/api';
|
||||||
@@ -49,6 +50,10 @@ export default function KnowledgeBasesPage() {
|
|||||||
const [docsLoading, setDocsLoading] = useState(false);
|
const [docsLoading, setDocsLoading] = useState(false);
|
||||||
const [docModalOpen, setDocModalOpen] = useState(false);
|
const [docModalOpen, setDocModalOpen] = useState(false);
|
||||||
const [docSaving, setDocSaving] = 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 } =
|
const { data, loading, page, pageSize, setPage, setPageSize, reload } =
|
||||||
useAdminList<KnowledgeBaseDto>(
|
useAdminList<KnowledgeBaseDto>(
|
||||||
@@ -195,9 +200,32 @@ export default function KnowledgeBasesPage() {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '操作',
|
title: '操作',
|
||||||
width: 80,
|
width: 140,
|
||||||
render: (_, row) =>
|
render: (_, row) =>
|
||||||
drawerKb?.canEditFull ? (
|
drawerKb?.canEditFull ? (
|
||||||
|
<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="删除文档?"
|
title="删除文档?"
|
||||||
onConfirm={async () => {
|
onConfirm={async () => {
|
||||||
@@ -217,6 +245,7 @@ export default function KnowledgeBasesPage() {
|
|||||||
删除
|
删除
|
||||||
</Button>
|
</Button>
|
||||||
</Popconfirm>
|
</Popconfirm>
|
||||||
|
</Space>
|
||||||
) : null,
|
) : null,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
@@ -398,6 +427,50 @@ export default function KnowledgeBasesPage() {
|
|||||||
</Form.Item>
|
</Form.Item>
|
||||||
</Form>
|
</Form>
|
||||||
</Modal>
|
</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>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -168,10 +168,10 @@ function ProductDetailFields({ form, aromaType }: { form: FormInstance; aromaTyp
|
|||||||
<>
|
<>
|
||||||
<ProductDetailTemplatePicker form={form} aromaType={aromaType} />
|
<ProductDetailTemplatePicker form={form} aromaType={aromaType} />
|
||||||
<Divider />
|
<Divider />
|
||||||
<Typography.Text type="secondary">详情页轮播(CAROUSEL)</Typography.Text>
|
<Typography.Text type="secondary">详情页轮播(CAROUSEL,单张最大 10MB)</Typography.Text>
|
||||||
<ImageUrlList name="carouselUrls" label="轮播图" bizType="CAROUSEL" />
|
<ImageUrlList name="carouselUrls" label="轮播图" bizType="CAROUSEL" />
|
||||||
<Divider />
|
<Divider />
|
||||||
<Typography.Text type="secondary">详情长图(DETAIL,可逐张修改)</Typography.Text>
|
<Typography.Text type="secondary">详情长图(DETAIL,可逐张修改,单张最大 10MB)</Typography.Text>
|
||||||
<DetailImageUrlList label="详情图" bizType="DETAIL" />
|
<DetailImageUrlList label="详情图" bizType="DETAIL" />
|
||||||
<Divider />
|
<Divider />
|
||||||
<Form.Item name="storyTitle" label="故事标题">
|
<Form.Item name="storyTitle" label="故事标题">
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import { Button, Descriptions, Drawer, Form, Input, Select, Table, Tag, Typography } from 'antd';
|
import { Button, Drawer, Form, Input, Select, Table, Tag, Typography } from 'antd';
|
||||||
import type { ColumnsType } from 'antd/es/table';
|
import type { ColumnsType } from 'antd/es/table';
|
||||||
import { REDEEM_CHANNEL_LABELS, type RedeemChannel } from '@dukang/shared-types';
|
import { REDEEM_CHANNEL_LABELS, type RedeemChannel } from '@dukang/shared-types';
|
||||||
|
import RedeemRecordDetailDescriptions from '../components/RedeemRecordDetailDescriptions';
|
||||||
import { request } from '../lib/api';
|
import { request } from '../lib/api';
|
||||||
import { fmtTime } from '../lib/constants';
|
import { fmtTime } from '../lib/constants';
|
||||||
import { useAdminList } from '../lib/useAdminList';
|
import { useAdminList } from '../lib/useAdminList';
|
||||||
@@ -13,11 +14,16 @@ type Row = {
|
|||||||
settleAmount: number;
|
settleAmount: number;
|
||||||
channel?: RedeemChannel;
|
channel?: RedeemChannel;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
user?: { userNo: string; phone: string | null };
|
user?: { userNo: string; phone: string | null; nickname?: string | null };
|
||||||
store?: { name: string; cityName: string };
|
store?: { name: string; cityName: string };
|
||||||
coupon?: { couponNo: 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() {
|
export default function RedeemRecordsPage() {
|
||||||
const [form] = Form.useForm();
|
const [form] = Form.useForm();
|
||||||
const [filters, setFilters] = useState<Record<string, string>>({});
|
const [filters, setFilters] = useState<Record<string, string>>({});
|
||||||
@@ -34,6 +40,17 @@ export default function RedeemRecordsPage() {
|
|||||||
);
|
);
|
||||||
const [detail, setDetail] = useState<Record<string, unknown> | null>(null);
|
const [detail, setDetail] = useState<Record<string, unknown> | null>(null);
|
||||||
const [drawerOpen, setDrawerOpen] = useState(false);
|
const [drawerOpen, setDrawerOpen] = useState(false);
|
||||||
|
const [detailLoading, setDetailLoading] = useState(false);
|
||||||
|
|
||||||
|
async function openDetail(id: string) {
|
||||||
|
setDetailLoading(true);
|
||||||
|
setDrawerOpen(true);
|
||||||
|
try {
|
||||||
|
setDetail(await request(`/admin/redeem-records/${id}`));
|
||||||
|
} finally {
|
||||||
|
setDetailLoading(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const columns: ColumnsType<Row> = [
|
const columns: ColumnsType<Row> = [
|
||||||
{ title: '核销号', dataIndex: 'redeemNo', width: 180 },
|
{ title: '核销号', dataIndex: 'redeemNo', width: 180 },
|
||||||
@@ -50,7 +67,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: ['store', 'name'] },
|
||||||
{ title: '核销额', dataIndex: 'amount', width: 90, render: (v) => `¥${v}` },
|
{ title: '核销额', dataIndex: 'amount', width: 90, render: (v) => `¥${v}` },
|
||||||
{ title: '结算额', dataIndex: 'settleAmount', width: 90, render: (v) => `¥${v}` },
|
{ title: '结算额', dataIndex: 'settleAmount', width: 90, render: (v) => `¥${v}` },
|
||||||
@@ -60,14 +89,7 @@ export default function RedeemRecordsPage() {
|
|||||||
title: '操作',
|
title: '操作',
|
||||||
width: 80,
|
width: 80,
|
||||||
render: (_, row) => (
|
render: (_, row) => (
|
||||||
<Button
|
<Button type="link" size="small" onClick={() => void openDetail(row.id)}>
|
||||||
type="link"
|
|
||||||
size="small"
|
|
||||||
onClick={async () => {
|
|
||||||
setDetail(await request(`/admin/redeem-records/${row.id}`));
|
|
||||||
setDrawerOpen(true);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
详情
|
详情
|
||||||
</Button>
|
</Button>
|
||||||
),
|
),
|
||||||
@@ -113,7 +135,7 @@ export default function RedeemRecordsPage() {
|
|||||||
loading={loading}
|
loading={loading}
|
||||||
columns={columns}
|
columns={columns}
|
||||||
dataSource={data?.items ?? []}
|
dataSource={data?.items ?? []}
|
||||||
scroll={{ x: 1100 }}
|
scroll={{ x: 1300 }}
|
||||||
pagination={{
|
pagination={{
|
||||||
current: page,
|
current: page,
|
||||||
pageSize,
|
pageSize,
|
||||||
@@ -125,22 +147,21 @@ export default function RedeemRecordsPage() {
|
|||||||
},
|
},
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<Drawer title="核销详情" width={520} open={drawerOpen} onClose={() => setDrawerOpen(false)}>
|
<Drawer
|
||||||
{detail && (
|
title="核销详情"
|
||||||
<Descriptions column={1} bordered size="small">
|
width={640}
|
||||||
<Descriptions.Item label="核销号">{String(detail.redeemNo)}</Descriptions.Item>
|
open={drawerOpen}
|
||||||
<Descriptions.Item label="方式">
|
onClose={() => {
|
||||||
{
|
setDrawerOpen(false);
|
||||||
REDEEM_CHANNEL_LABELS[
|
setDetail(null);
|
||||||
(detail.channel === 'PHONE' ? 'PHONE' : 'SCAN') as RedeemChannel
|
}}
|
||||||
]
|
destroyOnClose
|
||||||
}
|
>
|
||||||
</Descriptions.Item>
|
{detailLoading ? (
|
||||||
<Descriptions.Item label="核销额">¥{String(detail.amount)}</Descriptions.Item>
|
<Typography.Text type="secondary">加载中…</Typography.Text>
|
||||||
<Descriptions.Item label="结算额">¥{String(detail.settleAmount)}</Descriptions.Item>
|
) : detail ? (
|
||||||
<Descriptions.Item label="时间">{fmtTime(String(detail.createdAt))}</Descriptions.Item>
|
<RedeemRecordDetailDescriptions detail={detail} />
|
||||||
</Descriptions>
|
) : null}
|
||||||
)}
|
|
||||||
</Drawer>
|
</Drawer>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import { useState } from 'react';
|
|
||||||
import { Button, Form, Input, Table, Typography } from 'antd';
|
import { Button, Form, Input, Table, Typography } from 'antd';
|
||||||
import type { ColumnsType } from 'antd/es/table';
|
import type { ColumnsType } from 'antd/es/table';
|
||||||
import { useSearchParams } from 'react-router-dom';
|
import { useSearchParams } from 'react-router-dom';
|
||||||
|
|||||||
@@ -376,7 +376,7 @@ type StoreRow = {
|
|||||||
visibilityWhitelistEnabled?: boolean;
|
visibilityWhitelistEnabled?: boolean;
|
||||||
visibilityPhones?: string[];
|
visibilityPhones?: string[];
|
||||||
cityRef?: { name: string; code: string };
|
cityRef?: { name: string; code: string };
|
||||||
partner?: { companyName: string };
|
partner?: { id?: string; companyName?: string | null; name?: string | null; phone?: string | null };
|
||||||
account?: {
|
account?: {
|
||||||
phone: string;
|
phone: string;
|
||||||
name: string;
|
name: string;
|
||||||
@@ -394,13 +394,14 @@ type StoreRow = {
|
|||||||
category?: { id: string; name: string; parentId?: string | null } | null;
|
category?: { id: string; name: string; parentId?: string | null } | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
type PartnerOption = { id: string; companyName: string; name?: string };
|
type PartnerOption = { id: string; companyName?: string | null; name?: string | null; phone?: string | null };
|
||||||
|
|
||||||
function partnerOptionLabel(p: PartnerOption): string {
|
function partnerOptionLabel(p: PartnerOption): string {
|
||||||
const company = (p.companyName || '').trim();
|
const company = (p.companyName || '').trim();
|
||||||
const person = (p.name || '').trim();
|
const person = (p.name || '').trim();
|
||||||
|
const phone = (p.phone || '').trim();
|
||||||
if (company && person) return `${company}-${person}`;
|
if (company && person) return `${company}-${person}`;
|
||||||
return company || person || p.id;
|
return company || person || phone || p.id;
|
||||||
}
|
}
|
||||||
type CityOption = {
|
type CityOption = {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -867,7 +868,13 @@ export default function StoresPage() {
|
|||||||
);
|
);
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{ title: '开城合伙人', dataIndex: ['partner', 'companyName'], width: 120 },
|
{
|
||||||
|
title: '开城合伙人',
|
||||||
|
dataIndex: 'partner',
|
||||||
|
width: 140,
|
||||||
|
render: (partner: StoreRow['partner']) =>
|
||||||
|
partner ? partnerOptionLabel({ id: partner.id ?? '', ...partner }) : '—',
|
||||||
|
},
|
||||||
{
|
{
|
||||||
title: '可见',
|
title: '可见',
|
||||||
dataIndex: 'visibilityWhitelistEnabled',
|
dataIndex: 'visibilityWhitelistEnabled',
|
||||||
|
|||||||
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(
|
function renderField(
|
||||||
field: SystemConfigFieldMeta,
|
field: SystemConfigFieldMeta,
|
||||||
configuredSecrets: string[],
|
configuredSecrets: string[],
|
||||||
@@ -291,8 +263,6 @@ export default function SystemSettingsPage() {
|
|||||||
meta.configuredSecrets,
|
meta.configuredSecrets,
|
||||||
f.key === 'MOCK_SMS' && mockSmsEnabled ? (
|
f.key === 'MOCK_SMS' && mockSmsEnabled ? (
|
||||||
<MockSmsCodePanel codes={meta.mockSmsCodes ?? []} loading={loading} />
|
<MockSmsCodePanel codes={meta.mockSmsCodes ?? []} loading={loading} />
|
||||||
) : f.key === 'WECOM_ALERT_ENABLED' ? (
|
|
||||||
<WecomAlertTestButton />
|
|
||||||
) : undefined,
|
) : undefined,
|
||||||
),
|
),
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -10,11 +10,18 @@ import {
|
|||||||
Select,
|
Select,
|
||||||
Space,
|
Space,
|
||||||
Table,
|
Table,
|
||||||
|
Tag,
|
||||||
Typography,
|
Typography,
|
||||||
message,
|
message,
|
||||||
} from 'antd';
|
} from 'antd';
|
||||||
import type { ColumnsType } from 'antd/es/table';
|
import type { ColumnsType } from 'antd/es/table';
|
||||||
import { TICKET_TYPE_LABELS, type TicketTypeDto } from '@dukang/shared-types';
|
import {
|
||||||
|
TICKET_STATUS_LABELS,
|
||||||
|
TICKET_TYPE_LABELS,
|
||||||
|
ticketStatusLabel,
|
||||||
|
type TicketStatusDto,
|
||||||
|
type TicketTypeDto,
|
||||||
|
} from '@dukang/shared-types';
|
||||||
import { request } from '../lib/api';
|
import { request } from '../lib/api';
|
||||||
import { fmtTime } from '../lib/constants';
|
import { fmtTime } from '../lib/constants';
|
||||||
import { useAdminList } from '../lib/useAdminList';
|
import { useAdminList } from '../lib/useAdminList';
|
||||||
@@ -31,6 +38,21 @@ type Row = {
|
|||||||
createdAt: string;
|
createdAt: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const STATUS_COLOR: Partial<Record<TicketStatusDto, string>> = {
|
||||||
|
PENDING: 'orange',
|
||||||
|
OPEN: 'blue',
|
||||||
|
COLLABORATING: 'cyan',
|
||||||
|
RESOLVED: 'green',
|
||||||
|
REJECTED: 'red',
|
||||||
|
COMPLETED: 'green',
|
||||||
|
CLOSED: 'default',
|
||||||
|
};
|
||||||
|
|
||||||
|
const STATUS_OPTIONS = (Object.keys(TICKET_STATUS_LABELS) as TicketStatusDto[]).map((value) => ({
|
||||||
|
value,
|
||||||
|
label: TICKET_STATUS_LABELS[value],
|
||||||
|
}));
|
||||||
|
|
||||||
export default function TicketsPage() {
|
export default function TicketsPage() {
|
||||||
const [filters, setFilters] = useState<Record<string, string>>({});
|
const [filters, setFilters] = useState<Record<string, string>>({});
|
||||||
const { data, loading, page, pageSize, setPage, setPageSize, reload } = useAdminList<Row>(
|
const { data, loading, page, pageSize, setPage, setPageSize, reload } = useAdminList<Row>(
|
||||||
@@ -101,7 +123,14 @@ export default function TicketsPage() {
|
|||||||
width: 110,
|
width: 110,
|
||||||
render: (t: TicketTypeDto) => TICKET_TYPE_LABELS[t] ?? t,
|
render: (t: TicketTypeDto) => TICKET_TYPE_LABELS[t] ?? t,
|
||||||
},
|
},
|
||||||
{ title: '状态', dataIndex: 'status', width: 90 },
|
{
|
||||||
|
title: '状态',
|
||||||
|
dataIndex: 'status',
|
||||||
|
width: 100,
|
||||||
|
render: (s: string) => (
|
||||||
|
<Tag color={STATUS_COLOR[s as TicketStatusDto] ?? 'default'}>{ticketStatusLabel(s)}</Tag>
|
||||||
|
),
|
||||||
|
},
|
||||||
{ title: '关联', width: 140, render: (_, r) => `${r.refType}#${r.refId}` },
|
{ title: '关联', width: 140, render: (_, r) => `${r.refType}#${r.refId}` },
|
||||||
{ title: '备注', dataIndex: 'remark', ellipsis: true },
|
{ title: '备注', dataIndex: 'remark', ellipsis: true },
|
||||||
{ title: '时间', dataIndex: 'createdAt', width: 160, render: fmtTime },
|
{ title: '时间', dataIndex: 'createdAt', width: 160, render: fmtTime },
|
||||||
@@ -165,7 +194,7 @@ export default function TicketsPage() {
|
|||||||
/>
|
/>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
<Form.Item name="status" label="状态">
|
<Form.Item name="status" label="状态">
|
||||||
<Input allowClear placeholder="PENDING" />
|
<Select allowClear style={{ width: 140 }} placeholder="全部" options={STATUS_OPTIONS} />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
<Button type="primary" htmlType="submit">
|
<Button type="primary" htmlType="submit">
|
||||||
筛选
|
筛选
|
||||||
@@ -212,7 +241,11 @@ export default function TicketsPage() {
|
|||||||
<Descriptions.Item label="类型">
|
<Descriptions.Item label="类型">
|
||||||
{TICKET_TYPE_LABELS[detail.ticketType] ?? detail.ticketType}
|
{TICKET_TYPE_LABELS[detail.ticketType] ?? detail.ticketType}
|
||||||
</Descriptions.Item>
|
</Descriptions.Item>
|
||||||
<Descriptions.Item label="状态">{String(detail.status)}</Descriptions.Item>
|
<Descriptions.Item label="状态">
|
||||||
|
<Tag color={STATUS_COLOR[detail.status as TicketStatusDto] ?? 'default'}>
|
||||||
|
{ticketStatusLabel(detail.status)}
|
||||||
|
</Tag>
|
||||||
|
</Descriptions.Item>
|
||||||
<Descriptions.Item label="关联">
|
<Descriptions.Item label="关联">
|
||||||
{String(detail.refType)} #{String(detail.refId)}
|
{String(detail.refType)} #{String(detail.refId)}
|
||||||
</Descriptions.Item>
|
</Descriptions.Item>
|
||||||
|
|||||||
@@ -0,0 +1,129 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
|
import { Button, Descriptions, Drawer, Form, Input, Select, Space, Table, Tag, Typography } from 'antd';
|
||||||
|
import type { ColumnsType } from 'antd/es/table';
|
||||||
|
import { useAdminList } from '../lib/useAdminList';
|
||||||
|
import { request } from '../lib/api';
|
||||||
|
import { fmtTime } from '../lib/constants';
|
||||||
|
import type { WecomBotLogDto } from '@dukang/shared-types';
|
||||||
|
|
||||||
|
export default function WecomBotLogsPage() {
|
||||||
|
const [form] = Form.useForm();
|
||||||
|
const [filters, setFilters] = useState<Record<string, string>>({});
|
||||||
|
const [detail, setDetail] = useState<WecomBotLogDto | null>(null);
|
||||||
|
|
||||||
|
const { data, loading, page, pageSize, setPage, setPageSize } = useAdminList<WecomBotLogDto>(
|
||||||
|
'/admin/logs/wecom-bots',
|
||||||
|
() => {
|
||||||
|
const qs = new URLSearchParams();
|
||||||
|
if (filters.botId) qs.set('botId', filters.botId);
|
||||||
|
if (filters.wecomUserId) qs.set('wecomUserId', filters.wecomUserId);
|
||||||
|
if (filters.action) qs.set('action', filters.action);
|
||||||
|
if (filters.success) qs.set('success', filters.success);
|
||||||
|
return qs;
|
||||||
|
},
|
||||||
|
[filters],
|
||||||
|
);
|
||||||
|
|
||||||
|
const columns: ColumnsType<WecomBotLogDto> = [
|
||||||
|
{ title: '时间', dataIndex: 'createdAt', width: 160, render: fmtTime },
|
||||||
|
{ title: '机器人', dataIndex: 'botName', width: 120, ellipsis: true, render: (v, r) => v || r.botKey || '—' },
|
||||||
|
{ title: '企微用户', dataIndex: 'wecomUserId', width: 120, ellipsis: true },
|
||||||
|
{ title: '动作', dataIndex: 'action', width: 160, ellipsis: true },
|
||||||
|
{ title: '权限', dataIndex: 'permission', width: 140, ellipsis: true, render: (v) => v || '—' },
|
||||||
|
{
|
||||||
|
title: '结果',
|
||||||
|
dataIndex: 'success',
|
||||||
|
width: 80,
|
||||||
|
render: (v: boolean) => <Tag color={v ? 'green' : 'red'}>{v ? '成功' : '失败'}</Tag>,
|
||||||
|
},
|
||||||
|
{ title: '耗时(ms)', dataIndex: 'latencyMs', width: 90, render: (v) => v ?? '—' },
|
||||||
|
{ title: '输入摘要', dataIndex: 'inputSummary', ellipsis: true },
|
||||||
|
{
|
||||||
|
title: '操作',
|
||||||
|
width: 80,
|
||||||
|
render: (_, row) => (
|
||||||
|
<Button type="link" size="small" onClick={() => setDetail(row)}>
|
||||||
|
详情
|
||||||
|
</Button>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<Typography.Title level={4}>企微机器人日志</Typography.Title>
|
||||||
|
<Typography.Paragraph type="secondary">
|
||||||
|
记录机器人在企微内的查询与审批操作,含权限点、耗时与成败。
|
||||||
|
</Typography.Paragraph>
|
||||||
|
|
||||||
|
<Form
|
||||||
|
form={form}
|
||||||
|
layout="inline"
|
||||||
|
style={{ marginBottom: 16 }}
|
||||||
|
onFinish={(v) => {
|
||||||
|
setFilters(v);
|
||||||
|
setPage(1);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Form.Item name="botId" label="机器人 ID">
|
||||||
|
<Input allowClear placeholder="wecom_bot.id" style={{ width: 140 }} />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="wecomUserId" label="企微 userid">
|
||||||
|
<Input allowClear placeholder="userid" style={{ width: 140 }} />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="action" label="动作">
|
||||||
|
<Input allowClear placeholder="order.read" style={{ width: 140 }} />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="success" label="结果">
|
||||||
|
<Select
|
||||||
|
allowClear
|
||||||
|
style={{ width: 100 }}
|
||||||
|
options={[
|
||||||
|
{ value: 'true', label: '成功' },
|
||||||
|
{ value: 'false', label: '失败' },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item>
|
||||||
|
<Button type="primary" htmlType="submit">
|
||||||
|
查询
|
||||||
|
</Button>
|
||||||
|
</Form.Item>
|
||||||
|
</Form>
|
||||||
|
|
||||||
|
<Table
|
||||||
|
rowKey="id"
|
||||||
|
loading={loading}
|
||||||
|
columns={columns}
|
||||||
|
dataSource={data?.items ?? []}
|
||||||
|
scroll={{ x: 1100 }}
|
||||||
|
pagination={{
|
||||||
|
current: page,
|
||||||
|
pageSize,
|
||||||
|
total: data?.total ?? 0,
|
||||||
|
showSizeChanger: true,
|
||||||
|
onChange: (p, ps) => {
|
||||||
|
setPage(p);
|
||||||
|
setPageSize(ps);
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Drawer title="日志详情" width={480} open={!!detail} onClose={() => setDetail(null)}>
|
||||||
|
{detail && (
|
||||||
|
<Descriptions column={1} size="small" bordered>
|
||||||
|
<Descriptions.Item label="时间">{fmtTime(detail.createdAt)}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="机器人">{detail.botName || detail.botKey || '—'}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="企微用户">{detail.wecomUserId}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="动作">{detail.action}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="权限">{detail.permission || '—'}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="输入摘要">{detail.inputSummary || '—'}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="结果">{detail.success ? '成功' : '失败'}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="错误">{detail.errorMessage || '—'}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="耗时">{detail.latencyMs != null ? `${detail.latencyMs} ms` : '—'}</Descriptions.Item>
|
||||||
|
</Descriptions>
|
||||||
|
)}
|
||||||
|
</Drawer>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -20,13 +20,14 @@ import {
|
|||||||
} from 'antd';
|
} from 'antd';
|
||||||
import type { ColumnsType } from 'antd/es/table';
|
import type { ColumnsType } from 'antd/es/table';
|
||||||
import {
|
import {
|
||||||
WECOM_BOT_PERMISSIONS,
|
WECOM_BOT_PERMISSION_GROUPS,
|
||||||
WECOM_BOT_PERMISSION_LABELS,
|
WECOM_BOT_PERMISSION_LABELS,
|
||||||
WECOM_BOT_ROLE_DEFAULT_PERMISSIONS,
|
WECOM_BOT_ROLE_DEFAULT_PERMISSIONS,
|
||||||
WECOM_BOT_ROLE_LABELS,
|
WECOM_BOT_ROLE_LABELS,
|
||||||
WECOM_BOT_ROLES,
|
WECOM_BOT_ROLES,
|
||||||
type LlmApiConfigOptionDto,
|
type LlmApiConfigOptionDto,
|
||||||
type KnowledgeBaseOptionDto,
|
type KnowledgeBaseOptionDto,
|
||||||
|
type WecomAibotRuntimeDto,
|
||||||
type WecomBotDto,
|
type WecomBotDto,
|
||||||
type WecomBotPermission,
|
type WecomBotPermission,
|
||||||
type WecomBotRole,
|
type WecomBotRole,
|
||||||
@@ -36,17 +37,6 @@ import { fmtTime } from '../lib/constants';
|
|||||||
import { useAdminList } from '../lib/useAdminList';
|
import { useAdminList } from '../lib/useAdminList';
|
||||||
import OssUpload from '../components/OssUpload';
|
import OssUpload from '../components/OssUpload';
|
||||||
|
|
||||||
type ListRes = {
|
|
||||||
items: WecomBotDto[];
|
|
||||||
total: number;
|
|
||||||
page: number;
|
|
||||||
pageSize: number;
|
|
||||||
runtime?: {
|
|
||||||
masterEnabled: boolean;
|
|
||||||
bots: Array<{ id: string; connected: boolean; lastError: string | null }>;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
type FormValues = {
|
type FormValues = {
|
||||||
name: string;
|
name: string;
|
||||||
role: WecomBotRole;
|
role: WecomBotRole;
|
||||||
@@ -55,6 +45,7 @@ type FormValues = {
|
|||||||
avatarUrl?: string;
|
avatarUrl?: string;
|
||||||
welcome?: string;
|
welcome?: string;
|
||||||
permissions: WecomBotPermission[];
|
permissions: WecomBotPermission[];
|
||||||
|
reviewSuperAdminWecomUserIds?: string;
|
||||||
aiEnabled: boolean;
|
aiEnabled: boolean;
|
||||||
llmConfigId?: string | null;
|
llmConfigId?: string | null;
|
||||||
knowledgeBaseId?: string | null;
|
knowledgeBaseId?: string | null;
|
||||||
@@ -62,18 +53,70 @@ type FormValues = {
|
|||||||
sortOrder: number;
|
sortOrder: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
function parseUserIdLines(text?: string): string[] {
|
||||||
|
if (!text?.trim()) return [];
|
||||||
|
return [...new Set(text.split(/[,,\s\n]+/).map((s) => s.trim()).filter(Boolean))];
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatUserIdLines(ids?: string[]): string {
|
||||||
|
return (ids ?? []).join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
function mapDtoToForm(row: WecomBotDto): FormValues {
|
||||||
|
return {
|
||||||
|
name: row.name,
|
||||||
|
role: row.role,
|
||||||
|
botId: row.botId,
|
||||||
|
secret: '',
|
||||||
|
avatarUrl: row.avatarUrl || '',
|
||||||
|
welcome: row.welcome || '',
|
||||||
|
permissions: [...row.permissions],
|
||||||
|
reviewSuperAdminWecomUserIds: formatUserIdLines(row.reviewSuperAdminWecomUserIds),
|
||||||
|
aiEnabled: row.aiEnabled,
|
||||||
|
llmConfigId: row.llmConfigId,
|
||||||
|
knowledgeBaseId: row.knowledgeBaseId,
|
||||||
|
enabled: row.enabled,
|
||||||
|
sortOrder: row.sortOrder,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function samePermissionSet(a: WecomBotPermission[], b: WecomBotPermission[]): boolean {
|
||||||
|
if (a.length !== b.length) return false;
|
||||||
|
const setB = new Set(b);
|
||||||
|
return a.every((p) => setB.has(p));
|
||||||
|
}
|
||||||
|
|
||||||
|
const CREATE_DEFAULTS: FormValues = {
|
||||||
|
name: '',
|
||||||
|
role: 'CUSTOMER_SERVICE',
|
||||||
|
botId: '',
|
||||||
|
secret: '',
|
||||||
|
avatarUrl: '',
|
||||||
|
welcome: '',
|
||||||
|
permissions: [...WECOM_BOT_ROLE_DEFAULT_PERMISSIONS.CUSTOMER_SERVICE],
|
||||||
|
reviewSuperAdminWecomUserIds: '',
|
||||||
|
aiEnabled: false,
|
||||||
|
llmConfigId: null,
|
||||||
|
knowledgeBaseId: null,
|
||||||
|
enabled: true,
|
||||||
|
sortOrder: 0,
|
||||||
|
};
|
||||||
|
|
||||||
export default function WecomBotsPage() {
|
export default function WecomBotsPage() {
|
||||||
const [filterForm] = Form.useForm();
|
const [filterForm] = Form.useForm();
|
||||||
const [form] = Form.useForm<FormValues>();
|
const [form] = Form.useForm<FormValues>();
|
||||||
const [filters, setFilters] = useState<Record<string, string>>({});
|
const [filters, setFilters] = useState<Record<string, string>>({});
|
||||||
const [modalOpen, setModalOpen] = useState(false);
|
const [modalOpen, setModalOpen] = useState(false);
|
||||||
const [editing, setEditing] = useState<WecomBotDto | null>(null);
|
const [editing, setEditing] = useState<WecomBotDto | null>(null);
|
||||||
|
const [formInitial, setFormInitial] = useState<FormValues | null>(null);
|
||||||
|
const [formReady, setFormReady] = useState(false);
|
||||||
const [saving, setSaving] = useState(false);
|
const [saving, setSaving] = useState(false);
|
||||||
const [detail, setDetail] = useState<WecomBotDto | null>(null);
|
const [detail, setDetail] = useState<WecomBotDto | null>(null);
|
||||||
const [runtime, setRuntime] = useState<ListRes['runtime']>();
|
const [runtime, setRuntime] = useState<WecomAibotRuntimeDto>();
|
||||||
const [llmOptions, setLlmOptions] = useState<LlmApiConfigOptionDto[]>([]);
|
const [llmOptions, setLlmOptions] = useState<LlmApiConfigOptionDto[]>([]);
|
||||||
const [kbOptions, setKbOptions] = useState<KnowledgeBaseOptionDto[]>([]);
|
const [kbOptions, setKbOptions] = useState<KnowledgeBaseOptionDto[]>([]);
|
||||||
const roleWatch = Form.useWatch('role', form);
|
const roleWatch = Form.useWatch('role', form);
|
||||||
|
const permissionsWatch = Form.useWatch('permissions', form) as WecomBotPermission[] | undefined;
|
||||||
|
|
||||||
const { data, loading, page, pageSize, setPage, setPageSize, reload } = useAdminList<WecomBotDto>(
|
const { data, loading, page, pageSize, setPage, setPageSize, reload } = useAdminList<WecomBotDto>(
|
||||||
'/admin/wecom-bots',
|
'/admin/wecom-bots',
|
||||||
@@ -87,11 +130,13 @@ export default function WecomBotsPage() {
|
|||||||
[filters],
|
[filters],
|
||||||
);
|
);
|
||||||
|
|
||||||
useEffect(() => {
|
const loadRuntime = () =>
|
||||||
// useAdminList returns items; runtime comes from same API — fetch once for banner
|
request<WecomAibotRuntimeDto>('/admin/wecom-bots/runtime')
|
||||||
void request<ListRes>('/admin/wecom-bots?page=1&pageSize=1')
|
.then(setRuntime)
|
||||||
.then((res) => setRuntime(res.runtime))
|
|
||||||
.catch(() => {});
|
.catch(() => {});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void loadRuntime();
|
||||||
}, [data]);
|
}, [data]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -109,46 +154,51 @@ export default function WecomBotsPage() {
|
|||||||
});
|
});
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!modalOpen || !formReady || !formInitial) return;
|
||||||
|
form.resetFields();
|
||||||
|
form.setFieldsValue(formInitial);
|
||||||
|
}, [modalOpen, formReady, formInitial, form]);
|
||||||
|
|
||||||
|
function closeModal() {
|
||||||
|
setModalOpen(false);
|
||||||
|
setFormReady(false);
|
||||||
|
setFormInitial(null);
|
||||||
|
setEditing(null);
|
||||||
|
form.resetFields();
|
||||||
|
}
|
||||||
|
|
||||||
function openCreate() {
|
function openCreate() {
|
||||||
setEditing(null);
|
setEditing(null);
|
||||||
form.setFieldsValue({
|
setFormInitial({ ...CREATE_DEFAULTS });
|
||||||
name: '',
|
setFormReady(true);
|
||||||
role: 'CUSTOMER_SERVICE',
|
|
||||||
botId: '',
|
|
||||||
secret: '',
|
|
||||||
avatarUrl: '',
|
|
||||||
welcome: '',
|
|
||||||
permissions: [...WECOM_BOT_ROLE_DEFAULT_PERMISSIONS.CUSTOMER_SERVICE],
|
|
||||||
aiEnabled: false,
|
|
||||||
llmConfigId: null,
|
|
||||||
knowledgeBaseId: null,
|
|
||||||
enabled: true,
|
|
||||||
sortOrder: 0,
|
|
||||||
});
|
|
||||||
setModalOpen(true);
|
setModalOpen(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
function openEdit(row: WecomBotDto) {
|
async function openEdit(row: WecomBotDto) {
|
||||||
setEditing(row);
|
setEditing(row);
|
||||||
form.setFieldsValue({
|
setFormInitial(null);
|
||||||
name: row.name,
|
setFormReady(false);
|
||||||
role: row.role,
|
|
||||||
botId: row.botId,
|
|
||||||
secret: '',
|
|
||||||
avatarUrl: row.avatarUrl || '',
|
|
||||||
welcome: row.welcome || '',
|
|
||||||
permissions: row.permissions,
|
|
||||||
aiEnabled: row.aiEnabled,
|
|
||||||
llmConfigId: row.llmConfigId,
|
|
||||||
knowledgeBaseId: row.knowledgeBaseId,
|
|
||||||
enabled: row.enabled,
|
|
||||||
sortOrder: row.sortOrder,
|
|
||||||
});
|
|
||||||
setModalOpen(true);
|
setModalOpen(true);
|
||||||
|
try {
|
||||||
|
const detail = await request<WecomBotDto>(`/admin/wecom-bots/${row.id}`);
|
||||||
|
setEditing(detail);
|
||||||
|
setFormInitial(mapDtoToForm(detail));
|
||||||
|
} catch (e) {
|
||||||
|
message.error(e instanceof Error ? e.message : '加载机器人详情失败');
|
||||||
|
setFormInitial(mapDtoToForm(row));
|
||||||
|
} finally {
|
||||||
|
setFormReady(true);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function submit() {
|
async function submit() {
|
||||||
const values = await form.validateFields();
|
const values = await form.validateFields();
|
||||||
|
const permissions = (form.getFieldValue('permissions') ?? values.permissions) as WecomBotPermission[];
|
||||||
|
if (!permissions?.length) {
|
||||||
|
message.error('请至少选择一项权限');
|
||||||
|
return;
|
||||||
|
}
|
||||||
setSaving(true);
|
setSaving(true);
|
||||||
try {
|
try {
|
||||||
const payload = {
|
const payload = {
|
||||||
@@ -157,7 +207,8 @@ export default function WecomBotsPage() {
|
|||||||
botId: values.botId.trim(),
|
botId: values.botId.trim(),
|
||||||
avatarUrl: values.avatarUrl?.trim() || null,
|
avatarUrl: values.avatarUrl?.trim() || null,
|
||||||
welcome: values.welcome?.trim() || null,
|
welcome: values.welcome?.trim() || null,
|
||||||
permissions: values.permissions,
|
permissions,
|
||||||
|
reviewSuperAdminWecomUserIds: parseUserIdLines(values.reviewSuperAdminWecomUserIds),
|
||||||
aiEnabled: values.aiEnabled,
|
aiEnabled: values.aiEnabled,
|
||||||
llmConfigId: values.llmConfigId || null,
|
llmConfigId: values.llmConfigId || null,
|
||||||
knowledgeBaseId: values.knowledgeBaseId || null,
|
knowledgeBaseId: values.knowledgeBaseId || null,
|
||||||
@@ -165,13 +216,20 @@ export default function WecomBotsPage() {
|
|||||||
sortOrder: values.sortOrder,
|
sortOrder: values.sortOrder,
|
||||||
};
|
};
|
||||||
if (editing) {
|
if (editing) {
|
||||||
await request(`/admin/wecom-bots/${editing.id}`, {
|
const saved = await request<WecomBotDto>(`/admin/wecom-bots/${editing.id}`, {
|
||||||
method: 'PUT',
|
method: 'PUT',
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
...payload,
|
...payload,
|
||||||
secret: values.secret?.trim() || undefined,
|
secret: values.secret?.trim() || undefined,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
if (!samePermissionSet(permissions, saved.permissions)) {
|
||||||
|
message.warning('权限与保存结果不一致,已用服务端数据刷新表单');
|
||||||
|
setFormInitial(mapDtoToForm(saved));
|
||||||
|
setEditing(saved);
|
||||||
|
reload();
|
||||||
|
return;
|
||||||
|
}
|
||||||
message.success('已更新');
|
message.success('已更新');
|
||||||
} else {
|
} else {
|
||||||
if (!values.secret?.trim()) {
|
if (!values.secret?.trim()) {
|
||||||
@@ -187,7 +245,7 @@ export default function WecomBotsPage() {
|
|||||||
});
|
});
|
||||||
message.success('已创建');
|
message.success('已创建');
|
||||||
}
|
}
|
||||||
setModalOpen(false);
|
closeModal();
|
||||||
reload();
|
reload();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
message.error(e instanceof Error ? e.message : '保存失败');
|
message.error(e instanceof Error ? e.message : '保存失败');
|
||||||
@@ -208,10 +266,10 @@ export default function WecomBotsPage() {
|
|||||||
|
|
||||||
async function reloadConnections() {
|
async function reloadConnections() {
|
||||||
try {
|
try {
|
||||||
const st = await request<{
|
const st = await request<WecomAibotRuntimeDto>('/admin/wecom-bots/reload', {
|
||||||
masterEnabled: boolean;
|
method: 'POST',
|
||||||
bots: Array<{ id: string; connected: boolean; lastError: string | null }>;
|
body: '{}',
|
||||||
}>('/admin/wecom-bots/reload', { method: 'POST', body: '{}' });
|
});
|
||||||
message.success('已重载长连接');
|
message.success('已重载长连接');
|
||||||
setRuntime(st);
|
setRuntime(st);
|
||||||
reload();
|
reload();
|
||||||
@@ -287,7 +345,7 @@ export default function WecomBotsPage() {
|
|||||||
fixed: 'right',
|
fixed: 'right',
|
||||||
render: (_, row) => (
|
render: (_, row) => (
|
||||||
<Space>
|
<Space>
|
||||||
<Button type="link" size="small" onClick={() => openEdit(row)}>
|
<Button type="link" size="small" onClick={() => void openEdit(row)}>
|
||||||
编辑
|
编辑
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
@@ -386,23 +444,39 @@ export default function WecomBotsPage() {
|
|||||||
<Modal
|
<Modal
|
||||||
title={editing ? '编辑企微机器人' : '创建企微机器人'}
|
title={editing ? '编辑企微机器人' : '创建企微机器人'}
|
||||||
open={modalOpen}
|
open={modalOpen}
|
||||||
onCancel={() => setModalOpen(false)}
|
onCancel={closeModal}
|
||||||
onOk={() => void submit()}
|
onOk={() => void submit()}
|
||||||
confirmLoading={saving}
|
confirmLoading={saving}
|
||||||
width={640}
|
width={640}
|
||||||
destroyOnClose
|
destroyOnClose
|
||||||
>
|
>
|
||||||
<Form form={form} layout="vertical">
|
{formReady && formInitial ? (
|
||||||
|
<Form
|
||||||
|
key={editing ? `edit-${editing.id}` : 'create'}
|
||||||
|
form={form}
|
||||||
|
layout="vertical"
|
||||||
|
preserve={false}
|
||||||
|
initialValues={formInitial}
|
||||||
|
>
|
||||||
<Form.Item name="name" label="名称" rules={[{ required: true, message: '请填写名称' }]}>
|
<Form.Item name="name" label="名称" rules={[{ required: true, message: '请填写名称' }]}>
|
||||||
<Input placeholder="如:客服机器人" maxLength={64} />
|
<Input placeholder="如:客服机器人" maxLength={64} />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
<Form.Item name="role" label="角色" rules={[{ required: true }]}>
|
<Form.Item name="role" label="角色" rules={[{ required: true }]}>
|
||||||
<Select
|
<Select
|
||||||
options={WECOM_BOT_ROLES.map((r) => ({ value: r, label: WECOM_BOT_ROLE_LABELS[r] }))}
|
options={WECOM_BOT_ROLES.map((r) => ({ value: r, label: WECOM_BOT_ROLE_LABELS[r] }))}
|
||||||
onChange={(role: WecomBotRole) => {
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item>
|
||||||
|
<Button
|
||||||
|
size="small"
|
||||||
|
onClick={() => {
|
||||||
|
const role = form.getFieldValue('role') as WecomBotRole | undefined;
|
||||||
|
if (!role) return;
|
||||||
form.setFieldValue('permissions', [...WECOM_BOT_ROLE_DEFAULT_PERMISSIONS[role]]);
|
form.setFieldValue('permissions', [...WECOM_BOT_ROLE_DEFAULT_PERMISSIONS[role]]);
|
||||||
}}
|
}}
|
||||||
/>
|
>
|
||||||
|
应用当前角色默认权限
|
||||||
|
</Button>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
<Form.Item name="avatarUrl" label="头像">
|
<Form.Item name="avatarUrl" label="头像">
|
||||||
<OssUpload bizType="WECOM_BOT_AVATAR" />
|
<OssUpload bizType="WECOM_BOT_AVATAR" />
|
||||||
@@ -420,21 +494,48 @@ export default function WecomBotsPage() {
|
|||||||
</Form.Item>
|
</Form.Item>
|
||||||
<Form.Item
|
<Form.Item
|
||||||
name="permissions"
|
name="permissions"
|
||||||
label="权限"
|
label="权限(按模块)"
|
||||||
rules={[{ required: true, message: '请至少选择一项权限' }]}
|
rules={[
|
||||||
|
{
|
||||||
|
validator: (_, v: WecomBotPermission[] | undefined) =>
|
||||||
|
v?.length ? Promise.resolve() : Promise.reject(new Error('请至少选择一项权限')),
|
||||||
|
},
|
||||||
|
]}
|
||||||
extra={
|
extra={
|
||||||
roleWatch
|
<>
|
||||||
|
{roleWatch
|
||||||
? `角色默认:${WECOM_BOT_ROLE_DEFAULT_PERMISSIONS[roleWatch as WecomBotRole]?.map((p) => WECOM_BOT_PERMISSION_LABELS[p]).join('、') || '无'}`
|
? `角色默认:${WECOM_BOT_ROLE_DEFAULT_PERMISSIONS[roleWatch as WecomBotRole]?.map((p) => WECOM_BOT_PERMISSION_LABELS[p]).join('、') || '无'}`
|
||||||
: undefined
|
: null}
|
||||||
|
{permissionsWatch?.length ? (
|
||||||
|
<Typography.Text type="secondary"> · 已选 {permissionsWatch.length} 项</Typography.Text>
|
||||||
|
) : null}
|
||||||
|
</>
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
<Checkbox.Group
|
<Checkbox.Group style={{ width: '100%' }}>
|
||||||
options={WECOM_BOT_PERMISSIONS.map((p) => ({
|
{WECOM_BOT_PERMISSION_GROUPS.map((group) => (
|
||||||
value: p,
|
<div key={group.key} style={{ marginBottom: 12 }}>
|
||||||
label: WECOM_BOT_PERMISSION_LABELS[p],
|
<Typography.Text strong>{group.label}</Typography.Text>
|
||||||
}))}
|
<div style={{ marginTop: 4 }}>
|
||||||
/>
|
{group.permissions.map((p) => (
|
||||||
|
<Checkbox key={p} value={p} style={{ marginInlineStart: 0, marginRight: 12 }}>
|
||||||
|
{WECOM_BOT_PERMISSION_LABELS[p]}
|
||||||
|
</Checkbox>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</Checkbox.Group>
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
|
{(roleWatch === 'TECH_SUPPORT' || permissionsWatch?.includes('support_ticket.review')) && (
|
||||||
|
<Form.Item
|
||||||
|
name="reviewSuperAdminWecomUserIds"
|
||||||
|
label="审批白名单(企微 userid)"
|
||||||
|
extra="填写成员企微 userid(如 woDacESQAAD…),不是姓名/昵称;每行或逗号分隔。发「状态」或在服务端日志 inbound user= 可核对"
|
||||||
|
>
|
||||||
|
<Input.TextArea rows={3} placeholder="zhangsan lisi" />
|
||||||
|
</Form.Item>
|
||||||
|
)}
|
||||||
<Form.Item name="welcome" label="欢迎语">
|
<Form.Item name="welcome" label="欢迎语">
|
||||||
<Input.TextArea rows={3} placeholder="进入会话时的欢迎语,可空" />
|
<Input.TextArea rows={3} placeholder="进入会话时的欢迎语,可空" />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
@@ -475,6 +576,9 @@ export default function WecomBotsPage() {
|
|||||||
</Form.Item>
|
</Form.Item>
|
||||||
</Space>
|
</Space>
|
||||||
</Form>
|
</Form>
|
||||||
|
) : (
|
||||||
|
<Typography.Text type="secondary">加载中…</Typography.Text>
|
||||||
|
)}
|
||||||
</Modal>
|
</Modal>
|
||||||
|
|
||||||
<Drawer title="机器人详情" width={480} open={!!detail} onClose={() => setDetail(null)}>
|
<Drawer title="机器人详情" width={480} open={!!detail} onClose={() => setDetail(null)}>
|
||||||
@@ -496,6 +600,11 @@ export default function WecomBotsPage() {
|
|||||||
<Descriptions.Item label="权限">
|
<Descriptions.Item label="权限">
|
||||||
{detail.permissions.map((p) => WECOM_BOT_PERMISSION_LABELS[p] || p).join('、')}
|
{detail.permissions.map((p) => WECOM_BOT_PERMISSION_LABELS[p] || p).join('、')}
|
||||||
</Descriptions.Item>
|
</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="审批白名单">
|
||||||
|
{detail.reviewSuperAdminWecomUserIds?.length
|
||||||
|
? detail.reviewSuperAdminWecomUserIds.join('、')
|
||||||
|
: '—'}
|
||||||
|
</Descriptions.Item>
|
||||||
<Descriptions.Item label="欢迎语">{detail.welcome || '—'}</Descriptions.Item>
|
<Descriptions.Item label="欢迎语">{detail.welcome || '—'}</Descriptions.Item>
|
||||||
<Descriptions.Item label="AI 问答">{detail.aiEnabled ? '开' : '关'}</Descriptions.Item>
|
<Descriptions.Item label="AI 问答">{detail.aiEnabled ? '开' : '关'}</Descriptions.Item>
|
||||||
<Descriptions.Item label="语言模型">{detail.llmConfigName || '—'}</Descriptions.Item>
|
<Descriptions.Item label="语言模型">{detail.llmConfigName || '—'}</Descriptions.Item>
|
||||||
|
|||||||
@@ -0,0 +1,405 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
|
import {
|
||||||
|
Avatar,
|
||||||
|
Button,
|
||||||
|
Checkbox,
|
||||||
|
Descriptions,
|
||||||
|
Form,
|
||||||
|
Input,
|
||||||
|
InputNumber,
|
||||||
|
Modal,
|
||||||
|
Popconfirm,
|
||||||
|
Select,
|
||||||
|
Space,
|
||||||
|
Switch,
|
||||||
|
Table,
|
||||||
|
Tag,
|
||||||
|
Typography,
|
||||||
|
message,
|
||||||
|
} from 'antd';
|
||||||
|
import type { ColumnsType } from 'antd/es/table';
|
||||||
|
import {
|
||||||
|
WECOM_PUSH_CONDITION_GROUPS,
|
||||||
|
WECOM_PUSH_CONDITION_LABELS,
|
||||||
|
type WecomMessagePushDto,
|
||||||
|
type WecomPushCondition,
|
||||||
|
} from '@dukang/shared-types';
|
||||||
|
import { request } from '../lib/api';
|
||||||
|
import { fmtTime } from '../lib/constants';
|
||||||
|
import { useAdminList } from '../lib/useAdminList';
|
||||||
|
import OssUpload from '../components/OssUpload';
|
||||||
|
|
||||||
|
type FormValues = {
|
||||||
|
name: string;
|
||||||
|
avatarUrl?: string;
|
||||||
|
webhookUrl: string;
|
||||||
|
enabled: boolean;
|
||||||
|
mentionWecomUserId?: string;
|
||||||
|
pushConditions: WecomPushCondition[];
|
||||||
|
sortOrder: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
function WecomPushConditionPicker({
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
}: {
|
||||||
|
value?: WecomPushCondition[];
|
||||||
|
onChange?: (next: WecomPushCondition[]) => void;
|
||||||
|
}) {
|
||||||
|
const selected = new Set(value ?? []);
|
||||||
|
|
||||||
|
function toggle(cond: WecomPushCondition, checked: boolean) {
|
||||||
|
const next = new Set(selected);
|
||||||
|
if (checked) next.add(cond);
|
||||||
|
else next.delete(cond);
|
||||||
|
onChange?.([...next]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ width: '100%' }}>
|
||||||
|
{WECOM_PUSH_CONDITION_GROUPS.map((group) => (
|
||||||
|
<div key={group.key} style={{ marginBottom: 12 }}>
|
||||||
|
<Typography.Text strong>{group.label}</Typography.Text>
|
||||||
|
<div style={{ marginTop: 8 }}>
|
||||||
|
{group.conditions.map((c) => (
|
||||||
|
<div key={c}>
|
||||||
|
<Checkbox
|
||||||
|
checked={selected.has(c)}
|
||||||
|
onChange={(e) => toggle(c, e.target.checked)}
|
||||||
|
>
|
||||||
|
{WECOM_PUSH_CONDITION_LABELS[c]}
|
||||||
|
</Checkbox>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function WecomMessagePushesPage() {
|
||||||
|
const [filterForm] = Form.useForm();
|
||||||
|
const [form] = Form.useForm<FormValues>();
|
||||||
|
const [filters, setFilters] = useState<Record<string, string>>({});
|
||||||
|
const [modalOpen, setModalOpen] = useState(false);
|
||||||
|
const [editing, setEditing] = useState<WecomMessagePushDto | null>(null);
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
const [detail, setDetail] = useState<WecomMessagePushDto | null>(null);
|
||||||
|
const [testingId, setTestingId] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const { data, loading, page, pageSize, setPage, setPageSize, reload } =
|
||||||
|
useAdminList<WecomMessagePushDto>(
|
||||||
|
'/admin/wecom-message-pushes',
|
||||||
|
() => {
|
||||||
|
const qs = new URLSearchParams();
|
||||||
|
if (filters.name) qs.set('name', filters.name);
|
||||||
|
if (filters.enabled) qs.set('enabled', filters.enabled);
|
||||||
|
return qs;
|
||||||
|
},
|
||||||
|
[filters],
|
||||||
|
);
|
||||||
|
|
||||||
|
const conditionsWatch = Form.useWatch('pushConditions', form) as WecomPushCondition[] | undefined;
|
||||||
|
|
||||||
|
function openCreate() {
|
||||||
|
setEditing(null);
|
||||||
|
form.resetFields();
|
||||||
|
form.setFieldsValue({
|
||||||
|
enabled: true,
|
||||||
|
pushConditions: ['alert.ops'],
|
||||||
|
sortOrder: 0,
|
||||||
|
});
|
||||||
|
setModalOpen(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
function openEdit(row: WecomMessagePushDto) {
|
||||||
|
setEditing(row);
|
||||||
|
form.setFieldsValue({
|
||||||
|
name: row.name,
|
||||||
|
avatarUrl: row.avatarUrl ?? undefined,
|
||||||
|
webhookUrl: row.webhookUrl,
|
||||||
|
enabled: row.enabled,
|
||||||
|
mentionWecomUserId: row.mentionWecomUserId ?? undefined,
|
||||||
|
pushConditions: row.pushConditions,
|
||||||
|
sortOrder: row.sortOrder,
|
||||||
|
});
|
||||||
|
setModalOpen(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function save() {
|
||||||
|
const values = await form.validateFields();
|
||||||
|
setSaving(true);
|
||||||
|
try {
|
||||||
|
const body = {
|
||||||
|
name: values.name,
|
||||||
|
avatarUrl: values.avatarUrl || null,
|
||||||
|
webhookUrl: values.webhookUrl,
|
||||||
|
enabled: values.enabled,
|
||||||
|
mentionWecomUserId: values.mentionWecomUserId?.trim() || null,
|
||||||
|
pushConditions: values.pushConditions,
|
||||||
|
sortOrder: values.sortOrder ?? 0,
|
||||||
|
};
|
||||||
|
if (editing) {
|
||||||
|
await request(`/admin/wecom-message-pushes/${editing.id}`, {
|
||||||
|
method: 'PUT',
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
message.success('已更新');
|
||||||
|
} else {
|
||||||
|
await request('/admin/wecom-message-pushes', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
message.success('已创建');
|
||||||
|
}
|
||||||
|
setModalOpen(false);
|
||||||
|
reload();
|
||||||
|
} catch (e) {
|
||||||
|
message.error(e instanceof Error ? e.message : '保存失败');
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function remove(id: string) {
|
||||||
|
try {
|
||||||
|
await request(`/admin/wecom-message-pushes/${id}`, { method: 'DELETE' });
|
||||||
|
message.success('已删除');
|
||||||
|
reload();
|
||||||
|
} catch (e) {
|
||||||
|
message.error(e instanceof Error ? e.message : '删除失败');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function testPush(id: string) {
|
||||||
|
setTestingId(id);
|
||||||
|
try {
|
||||||
|
const res = await request<{ ok: boolean; message: string }>(
|
||||||
|
`/admin/wecom-message-pushes/${id}/test`,
|
||||||
|
{ method: 'POST', body: '{}' },
|
||||||
|
);
|
||||||
|
message.success(res.message || '已发送测试消息');
|
||||||
|
} catch (e) {
|
||||||
|
message.error(e instanceof Error ? e.message : '测试失败');
|
||||||
|
} finally {
|
||||||
|
setTestingId(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const columns: ColumnsType<WecomMessagePushDto> = [
|
||||||
|
{
|
||||||
|
title: '名称',
|
||||||
|
dataIndex: 'name',
|
||||||
|
render: (name: string, row) => (
|
||||||
|
<Space>
|
||||||
|
<Avatar src={row.avatarUrl ?? undefined}>{name.slice(0, 1)}</Avatar>
|
||||||
|
<span>{name}</span>
|
||||||
|
</Space>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Webhook',
|
||||||
|
dataIndex: 'webhookUrlMasked',
|
||||||
|
ellipsis: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '推送条件',
|
||||||
|
dataIndex: 'pushConditions',
|
||||||
|
render: (conds: WecomPushCondition[]) =>
|
||||||
|
conds.map((c) => (
|
||||||
|
<Tag key={c} style={{ marginBottom: 4 }}>
|
||||||
|
{WECOM_PUSH_CONDITION_LABELS[c]}
|
||||||
|
</Tag>
|
||||||
|
)),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '启用',
|
||||||
|
dataIndex: 'enabled',
|
||||||
|
width: 72,
|
||||||
|
render: (v: boolean) => (v ? <Tag color="green">是</Tag> : <Tag>否</Tag>),
|
||||||
|
},
|
||||||
|
{ title: '排序', dataIndex: 'sortOrder', width: 64 },
|
||||||
|
{
|
||||||
|
title: '操作',
|
||||||
|
key: 'actions',
|
||||||
|
width: 220,
|
||||||
|
render: (_, row) => (
|
||||||
|
<Space wrap>
|
||||||
|
<Button type="link" size="small" onClick={() => openEdit(row)}>
|
||||||
|
编辑
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="link"
|
||||||
|
size="small"
|
||||||
|
loading={testingId === row.id}
|
||||||
|
onClick={() => void testPush(row.id)}
|
||||||
|
>
|
||||||
|
测试
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="link"
|
||||||
|
size="small"
|
||||||
|
onClick={() => {
|
||||||
|
void request<WecomMessagePushDto>(`/admin/wecom-message-pushes/${row.id}`).then(setDetail);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
详情
|
||||||
|
</Button>
|
||||||
|
<Popconfirm title="确认删除?" onConfirm={() => void remove(row.id)}>
|
||||||
|
<Button type="link" size="small" danger>
|
||||||
|
删除
|
||||||
|
</Button>
|
||||||
|
</Popconfirm>
|
||||||
|
</Space>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<Typography.Title level={4}>企微机器人 · 消息推送</Typography.Title>
|
||||||
|
<Typography.Paragraph type="secondary">
|
||||||
|
配置群机器人 Webhook 多实例,按推送条件分发运营告警、技术支持工单、开发任务派发等消息。运行时不再读取
|
||||||
|
.env 中的 Webhook URL。
|
||||||
|
</Typography.Paragraph>
|
||||||
|
|
||||||
|
<Form
|
||||||
|
form={filterForm}
|
||||||
|
layout="inline"
|
||||||
|
style={{ marginBottom: 16 }}
|
||||||
|
onFinish={(v) => setFilters(v as Record<string, string>)}
|
||||||
|
>
|
||||||
|
<Form.Item name="name" label="名称">
|
||||||
|
<Input allowClear placeholder="搜索" />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="enabled" label="启用">
|
||||||
|
<Select
|
||||||
|
allowClear
|
||||||
|
placeholder="全部"
|
||||||
|
style={{ width: 100 }}
|
||||||
|
options={[
|
||||||
|
{ value: 'true', label: '启用' },
|
||||||
|
{ value: 'false', label: '停用' },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item>
|
||||||
|
<Space>
|
||||||
|
<Button type="primary" htmlType="submit">
|
||||||
|
查询
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
onClick={() => {
|
||||||
|
filterForm.resetFields();
|
||||||
|
setFilters({});
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
重置
|
||||||
|
</Button>
|
||||||
|
<Button type="primary" onClick={openCreate}>
|
||||||
|
新建推送
|
||||||
|
</Button>
|
||||||
|
</Space>
|
||||||
|
</Form.Item>
|
||||||
|
</Form>
|
||||||
|
|
||||||
|
<Table<WecomMessagePushDto>
|
||||||
|
rowKey="id"
|
||||||
|
loading={loading}
|
||||||
|
columns={columns}
|
||||||
|
dataSource={data?.items ?? []}
|
||||||
|
pagination={{
|
||||||
|
current: page,
|
||||||
|
pageSize,
|
||||||
|
total: data?.total ?? 0,
|
||||||
|
showSizeChanger: true,
|
||||||
|
onChange: (p, ps) => {
|
||||||
|
setPage(p);
|
||||||
|
setPageSize(ps);
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Modal
|
||||||
|
title={editing ? '编辑消息推送' : '新建消息推送'}
|
||||||
|
open={modalOpen}
|
||||||
|
onCancel={() => setModalOpen(false)}
|
||||||
|
onOk={() => void save()}
|
||||||
|
confirmLoading={saving}
|
||||||
|
width={640}
|
||||||
|
destroyOnClose
|
||||||
|
>
|
||||||
|
<Form form={form} layout="vertical">
|
||||||
|
<Form.Item name="name" label="名称" rules={[{ required: true, message: '请填写名称' }]}>
|
||||||
|
<Input placeholder="如:运营告警" />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="avatarUrl" label="头像(HQ 列表展示)">
|
||||||
|
<OssUpload />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item
|
||||||
|
name="webhookUrl"
|
||||||
|
label="Webhook URL"
|
||||||
|
rules={[{ required: true, message: '请填写 Webhook URL' }]}
|
||||||
|
>
|
||||||
|
<Input.Password placeholder="企微群机器人 Webhook" />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item name="enabled" label="启用" valuePropName="checked">
|
||||||
|
<Switch />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item
|
||||||
|
name="mentionWecomUserId"
|
||||||
|
label="企微 userid(可选)"
|
||||||
|
extra="markdown 推送用 <@userid> @ 群成员;任务派发等场景生效"
|
||||||
|
>
|
||||||
|
<Input placeholder="如 woDacESQAAD..." allowClear />
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item
|
||||||
|
name="pushConditions"
|
||||||
|
label="推送条件"
|
||||||
|
rules={[
|
||||||
|
{
|
||||||
|
validator: (_, v: WecomPushCondition[] | undefined) =>
|
||||||
|
v?.length ? Promise.resolve() : Promise.reject(new Error('请至少勾选一项推送条件')),
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
<WecomPushConditionPicker />
|
||||||
|
</Form.Item>
|
||||||
|
{conditionsWatch?.length ? (
|
||||||
|
<Typography.Text type="secondary" style={{ display: 'block', marginBottom: 16 }}>
|
||||||
|
已选 {conditionsWatch.length} 项:
|
||||||
|
{conditionsWatch.map((c) => WECOM_PUSH_CONDITION_LABELS[c]).join('、')}
|
||||||
|
</Typography.Text>
|
||||||
|
) : null}
|
||||||
|
<Form.Item name="sortOrder" label="排序">
|
||||||
|
<InputNumber min={0} style={{ width: '100%' }} />
|
||||||
|
</Form.Item>
|
||||||
|
</Form>
|
||||||
|
</Modal>
|
||||||
|
|
||||||
|
<Modal
|
||||||
|
title="消息推送详情"
|
||||||
|
open={!!detail}
|
||||||
|
onCancel={() => setDetail(null)}
|
||||||
|
footer={null}
|
||||||
|
width={560}
|
||||||
|
>
|
||||||
|
{detail ? (
|
||||||
|
<Descriptions column={1} bordered size="small">
|
||||||
|
<Descriptions.Item label="名称">{detail.name}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="Webhook">{detail.webhookUrlMasked}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="启用">{detail.enabled ? '是' : '否'}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="userid">{detail.mentionWecomUserId || '—'}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="推送条件">
|
||||||
|
{detail.pushConditions.map((c) => WECOM_PUSH_CONDITION_LABELS[c]).join('、')}
|
||||||
|
</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="排序">{detail.sortOrder}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="创建时间">{fmtTime(detail.createdAt)}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="更新时间">{fmtTime(detail.updatedAt)}</Descriptions.Item>
|
||||||
|
</Descriptions>
|
||||||
|
) : null}
|
||||||
|
</Modal>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -258,7 +258,7 @@ export default function WineryBillsPage() {
|
|||||||
酒厂对账单
|
酒厂对账单
|
||||||
</Typography.Title>
|
</Typography.Title>
|
||||||
<Typography.Text type="secondary">
|
<Typography.Text type="secondary">
|
||||||
每日 8:00 汇总昨日已付订单(实付 × {ratePct}%);未打款红色、已打款绿色,可展开订单明细
|
T+3:每日 8:00 汇总 3 天前(自然日)已完成的同城/跨城订单(实付 × {ratePct}%);未打款红色、已打款绿色,可展开订单明细
|
||||||
</Typography.Text>
|
</Typography.Text>
|
||||||
</Space>
|
</Space>
|
||||||
{canEditWineryBank ? (
|
{canEditWineryBank ? (
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ import {
|
|||||||
import { request } from '../../lib/api';
|
import { request } from '../../lib/api';
|
||||||
import { fmtTime } from '../../lib/constants';
|
import { fmtTime } from '../../lib/constants';
|
||||||
import type { PromoCodeDetailContext } from './PromoCodeDetailLayout';
|
import type { PromoCodeDetailContext } from './PromoCodeDetailLayout';
|
||||||
|
import PromoCodeMetricsPanel from './PromoCodeMetricsPanel';
|
||||||
|
|
||||||
const descLabelStyle: CSSProperties = {
|
const descLabelStyle: CSSProperties = {
|
||||||
whiteSpace: 'nowrap',
|
whiteSpace: 'nowrap',
|
||||||
@@ -212,6 +213,14 @@ export default function PromoCodeDetailPage() {
|
|||||||
<Statistic title="扫码进入次数" value={stats?.scanCount ?? detail.scanCount} />
|
<Statistic title="扫码进入次数" value={stats?.scanCount ?? detail.scanCount} />
|
||||||
</Card>
|
</Card>
|
||||||
</Col>
|
</Col>
|
||||||
|
<Col xs={12} sm={6}>
|
||||||
|
<Card size="small">
|
||||||
|
<Statistic
|
||||||
|
title="归因用户数"
|
||||||
|
value={stats?.attributionCount ?? 0}
|
||||||
|
/>
|
||||||
|
</Card>
|
||||||
|
</Col>
|
||||||
<Col xs={12} sm={6}>
|
<Col xs={12} sm={6}>
|
||||||
<Card size="small">
|
<Card size="small">
|
||||||
<Statistic
|
<Statistic
|
||||||
@@ -235,6 +244,8 @@ export default function PromoCodeDetailPage() {
|
|||||||
</Col>
|
</Col>
|
||||||
</Row>
|
</Row>
|
||||||
|
|
||||||
|
<PromoCodeMetricsPanel promoId={detail.id} />
|
||||||
|
|
||||||
<Modal
|
<Modal
|
||||||
title="编辑推广码"
|
title="编辑推广码"
|
||||||
open={editOpen}
|
open={editOpen}
|
||||||
|
|||||||
@@ -0,0 +1,258 @@
|
|||||||
|
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||||
|
import {
|
||||||
|
Card,
|
||||||
|
DatePicker,
|
||||||
|
Radio,
|
||||||
|
Select,
|
||||||
|
Space,
|
||||||
|
Table,
|
||||||
|
Typography,
|
||||||
|
message,
|
||||||
|
} from 'antd';
|
||||||
|
import type { ColumnsType } from 'antd/es/table';
|
||||||
|
import dayjs, { type Dayjs } from 'dayjs';
|
||||||
|
import ReactECharts from 'echarts-for-react';
|
||||||
|
import type { EChartsOption } from 'echarts';
|
||||||
|
import {
|
||||||
|
PROMO_METRIC_EVENT_LABELS,
|
||||||
|
type PromoMetricEventItem,
|
||||||
|
type PromoMetricEventType,
|
||||||
|
type PromoMetricTimelineDto,
|
||||||
|
} from '@dukang/shared-types';
|
||||||
|
import { request, type Paginated } from '../../lib/api';
|
||||||
|
import { fmtTime } from '../../lib/constants';
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
promoId: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const SERIES = [
|
||||||
|
{ key: 'scan', name: '扫码进入', color: '#1677ff' },
|
||||||
|
{ key: 'attribution', name: '归因用户', color: '#52c41a' },
|
||||||
|
{ key: 'register', name: '扫码注册', color: '#faad14' },
|
||||||
|
{ key: 'order', name: '订单', color: '#eb2f96' },
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
function buildTimelineQs(promoId: string, range: [Dayjs, Dayjs], granularity: 'day' | 'hour') {
|
||||||
|
const qs = new URLSearchParams();
|
||||||
|
qs.set('dateFrom', range[0].format('YYYY-MM-DD'));
|
||||||
|
qs.set('dateTo', range[1].format('YYYY-MM-DD'));
|
||||||
|
qs.set('granularity', granularity);
|
||||||
|
return `/admin/promo-codes/${promoId}/metrics/timeline?${qs.toString()}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildEventsQs(
|
||||||
|
promoId: string,
|
||||||
|
page: number,
|
||||||
|
pageSize: number,
|
||||||
|
range: [Dayjs, Dayjs],
|
||||||
|
eventType?: PromoMetricEventType,
|
||||||
|
) {
|
||||||
|
const qs = new URLSearchParams();
|
||||||
|
qs.set('page', String(page));
|
||||||
|
qs.set('pageSize', String(pageSize));
|
||||||
|
qs.set('dateFrom', range[0].format('YYYY-MM-DD'));
|
||||||
|
qs.set('dateTo', range[1].format('YYYY-MM-DD'));
|
||||||
|
if (eventType) qs.set('eventType', eventType);
|
||||||
|
return `/admin/promo-codes/${promoId}/metrics/events?${qs.toString()}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatRefId(row: PromoMetricEventItem): string {
|
||||||
|
if (row.orderId) return `订单 ${row.orderId}`;
|
||||||
|
if (row.userId) return `用户 ${row.userId}`;
|
||||||
|
if (row.sessionId) return `会话 ${row.sessionId}`;
|
||||||
|
return '—';
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatLocation(row: PromoMetricEventItem): string {
|
||||||
|
const parts = [row.ipProvince, row.ipCity].filter(Boolean);
|
||||||
|
if (parts.length) return parts.join(' ');
|
||||||
|
return '—';
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function PromoCodeMetricsPanel({ promoId }: Props) {
|
||||||
|
const [range, setRange] = useState<[Dayjs, Dayjs]>([dayjs().subtract(6, 'day'), dayjs()]);
|
||||||
|
const [granularity, setGranularity] = useState<'day' | 'hour'>('day');
|
||||||
|
const [timeline, setTimeline] = useState<PromoMetricTimelineDto | null>(null);
|
||||||
|
const [timelineLoading, setTimelineLoading] = useState(false);
|
||||||
|
const [eventType, setEventType] = useState<PromoMetricEventType | undefined>();
|
||||||
|
const [eventsPage, setEventsPage] = useState(1);
|
||||||
|
const [events, setEvents] = useState<Paginated<PromoMetricEventItem> | null>(null);
|
||||||
|
const [eventsLoading, setEventsLoading] = useState(false);
|
||||||
|
|
||||||
|
const loadTimeline = useCallback(() => {
|
||||||
|
setTimelineLoading(true);
|
||||||
|
return request<PromoMetricTimelineDto>(buildTimelineQs(promoId, range, granularity))
|
||||||
|
.then(setTimeline)
|
||||||
|
.catch((e) => {
|
||||||
|
message.error(e instanceof Error ? e.message : '加载趋势失败');
|
||||||
|
setTimeline(null);
|
||||||
|
})
|
||||||
|
.finally(() => setTimelineLoading(false));
|
||||||
|
}, [promoId, range, granularity]);
|
||||||
|
|
||||||
|
const loadEvents = useCallback(() => {
|
||||||
|
setEventsLoading(true);
|
||||||
|
return request<Paginated<PromoMetricEventItem>>(
|
||||||
|
buildEventsQs(promoId, eventsPage, 20, range, eventType),
|
||||||
|
)
|
||||||
|
.then(setEvents)
|
||||||
|
.catch((e) => {
|
||||||
|
message.error(e instanceof Error ? e.message : '加载事件失败');
|
||||||
|
setEvents(null);
|
||||||
|
})
|
||||||
|
.finally(() => setEventsLoading(false));
|
||||||
|
}, [promoId, eventsPage, range, eventType]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void loadTimeline();
|
||||||
|
}, [loadTimeline]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void loadEvents();
|
||||||
|
}, [loadEvents]);
|
||||||
|
|
||||||
|
const chartOption = useMemo<EChartsOption>(() => {
|
||||||
|
const buckets = timeline?.buckets ?? [];
|
||||||
|
const xData = buckets.map((b) => b.key);
|
||||||
|
|
||||||
|
return {
|
||||||
|
tooltip: { trigger: 'axis' },
|
||||||
|
legend: { data: SERIES.map((s) => s.name), bottom: 0 },
|
||||||
|
grid: { left: 48, right: 24, top: 24, bottom: 48 },
|
||||||
|
xAxis: {
|
||||||
|
type: 'category',
|
||||||
|
data: xData,
|
||||||
|
axisLabel: {
|
||||||
|
rotate: granularity === 'hour' ? 45 : 0,
|
||||||
|
formatter: (v: string) => (granularity === 'hour' ? v.slice(5, 16) : v.slice(5)),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
yAxis: { type: 'value', minInterval: 1 },
|
||||||
|
series: SERIES.map((s) => ({
|
||||||
|
name: s.name,
|
||||||
|
type: 'line',
|
||||||
|
smooth: true,
|
||||||
|
data: buckets.map((b) => b[s.key]),
|
||||||
|
itemStyle: { color: s.color },
|
||||||
|
markPoint: {
|
||||||
|
symbol: 'pin',
|
||||||
|
symbolSize: 42,
|
||||||
|
data: (() => {
|
||||||
|
const peak = timeline?.peak[s.key];
|
||||||
|
if (!peak || peak.count <= 0) return [];
|
||||||
|
return [{ name: '高峰', coord: [peak.key, peak.count], value: peak.count }];
|
||||||
|
})(),
|
||||||
|
},
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}, [timeline, granularity]);
|
||||||
|
|
||||||
|
const columns: ColumnsType<PromoMetricEventItem> = [
|
||||||
|
{
|
||||||
|
title: '时间',
|
||||||
|
dataIndex: 'createdAt',
|
||||||
|
width: 168,
|
||||||
|
render: (v: string) => fmtTime(v),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '类型',
|
||||||
|
dataIndex: 'eventType',
|
||||||
|
width: 108,
|
||||||
|
render: (v: PromoMetricEventType) => PROMO_METRIC_EVENT_LABELS[v],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'ID',
|
||||||
|
key: 'ref',
|
||||||
|
render: (_, row) => formatRefId(row),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'IP',
|
||||||
|
dataIndex: 'clientIp',
|
||||||
|
width: 128,
|
||||||
|
render: (v: string | null) => v ?? '—',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '地点',
|
||||||
|
key: 'location',
|
||||||
|
width: 120,
|
||||||
|
render: (_, row) => formatLocation(row),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card
|
||||||
|
title="数据趋势"
|
||||||
|
style={{ marginTop: 16 }}
|
||||||
|
extra={
|
||||||
|
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
|
||||||
|
仅统计功能上线后的新事件
|
||||||
|
</Typography.Text>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Space wrap style={{ marginBottom: 16 }}>
|
||||||
|
<DatePicker.RangePicker
|
||||||
|
value={range}
|
||||||
|
onChange={(v) => {
|
||||||
|
if (v?.[0] && v[1]) {
|
||||||
|
setRange([v[0], v[1]]);
|
||||||
|
setEventsPage(1);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
allowClear={false}
|
||||||
|
/>
|
||||||
|
<Radio.Group
|
||||||
|
value={granularity}
|
||||||
|
onChange={(e) => setGranularity(e.target.value as 'day' | 'hour')}
|
||||||
|
optionType="button"
|
||||||
|
buttonStyle="solid"
|
||||||
|
options={[
|
||||||
|
{ label: '按日', value: 'day' },
|
||||||
|
{ label: '按时', value: 'hour' },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</Space>
|
||||||
|
|
||||||
|
<ReactECharts
|
||||||
|
option={chartOption}
|
||||||
|
style={{ height: 360 }}
|
||||||
|
showLoading={timelineLoading}
|
||||||
|
notMerge
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Typography.Title level={5} style={{ marginTop: 24, marginBottom: 12 }}>
|
||||||
|
事件日志
|
||||||
|
</Typography.Title>
|
||||||
|
<Space wrap style={{ marginBottom: 12 }}>
|
||||||
|
<Select
|
||||||
|
allowClear
|
||||||
|
placeholder="全部类型"
|
||||||
|
style={{ width: 160 }}
|
||||||
|
value={eventType}
|
||||||
|
onChange={(v) => {
|
||||||
|
setEventType(v);
|
||||||
|
setEventsPage(1);
|
||||||
|
}}
|
||||||
|
options={Object.entries(PROMO_METRIC_EVENT_LABELS).map(([value, label]) => ({
|
||||||
|
value,
|
||||||
|
label,
|
||||||
|
}))}
|
||||||
|
/>
|
||||||
|
</Space>
|
||||||
|
<Table
|
||||||
|
rowKey="id"
|
||||||
|
size="small"
|
||||||
|
columns={columns}
|
||||||
|
dataSource={events?.items ?? []}
|
||||||
|
loading={eventsLoading}
|
||||||
|
pagination={{
|
||||||
|
current: eventsPage,
|
||||||
|
pageSize: events?.pageSize ?? 20,
|
||||||
|
total: events?.total ?? 0,
|
||||||
|
showSizeChanger: false,
|
||||||
|
onChange: (p) => setEventsPage(p),
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -19,8 +19,6 @@ type OssUploadFieldProps = {
|
|||||||
onWechatReadyChange?: (ready: boolean) => void;
|
onWechatReadyChange?: (ready: boolean) => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
const DEFAULT_MAX_MB = 10;
|
|
||||||
|
|
||||||
function isCancelError(msg: string): boolean {
|
function isCancelError(msg: string): boolean {
|
||||||
return /cancel|取消/i.test(msg);
|
return /cancel|取消/i.test(msg);
|
||||||
}
|
}
|
||||||
@@ -79,10 +77,6 @@ export default function OssUploadField({
|
|||||||
showUploadError('图片读取失败,请重新选择');
|
showUploadError('图片读取失败,请重新选择');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (file.size > DEFAULT_MAX_MB * 1024 * 1024) {
|
|
||||||
showUploadError(`文件不能超过 ${DEFAULT_MAX_MB}MB`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const result = await uploadFileToOss(file, { bizType, mediaType });
|
const result = await uploadFileToOss(file, { bizType, mediaType });
|
||||||
onChange?.(result.url);
|
onChange?.(result.url);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { useState } from 'react';
|
|||||||
import type { PackageFormItem } from '../lib/storePackages';
|
import type { PackageFormItem } from '../lib/storePackages';
|
||||||
import { STORE_PACKAGE_MAX_COUNT } from '@dukang/shared-types';
|
import { STORE_PACKAGE_MAX_COUNT } from '@dukang/shared-types';
|
||||||
import { emptyPackage } from '../lib/storePackages';
|
import { emptyPackage } from '../lib/storePackages';
|
||||||
|
import OssUploadField from './OssUploadField';
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
items: PackageFormItem[];
|
items: PackageFormItem[];
|
||||||
@@ -129,6 +130,16 @@ export default function StorePackagesForm({ items, onChange, disabled, embedded
|
|||||||
</div>
|
</div>
|
||||||
</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">
|
<div className="partner-field">
|
||||||
<label>其他说明</label>
|
<label>其他说明</label>
|
||||||
<div className="partner-field-input">
|
<div className="partner-field-input">
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import type { PartnerMe, PartnerStaffRole } from '@dukang/shared-types';
|
import type { PartnerMe, PartnerStaffRole } from '@dukang/shared-types';
|
||||||
|
import { reportApiError } from '@dukang/client-logging';
|
||||||
import { isOnAppPath, toAppPath } from '@dukang/weixin-sdk';
|
import { isOnAppPath, toAppPath } from '@dukang/weixin-sdk';
|
||||||
import { showPartnerToast } from './toast';
|
import { showPartnerToast } from './toast';
|
||||||
|
|
||||||
@@ -159,6 +160,12 @@ async function rawRequest<T>(
|
|||||||
if (json.code !== 0) {
|
if (json.code !== 0) {
|
||||||
const err = new Error(json.message || '请求失败') as Error & { status?: number };
|
const err = new Error(json.message || '请求失败') as Error & { status?: number };
|
||||||
err.status = json.code === 401 ? 401 : json.code;
|
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;
|
throw err;
|
||||||
}
|
}
|
||||||
return json.data as T;
|
return json.data as T;
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ export function emptyPackage(index = 0): PackageFormItem {
|
|||||||
dishes: '',
|
dishes: '',
|
||||||
usableTime: '',
|
usableTime: '',
|
||||||
otherNotes: '',
|
otherNotes: '',
|
||||||
|
imageUrl: '',
|
||||||
sortOrder: index,
|
sortOrder: index,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -22,9 +23,13 @@ export function normalizePackageFormItems(raw: PackageFormItem[]): PackageFormIt
|
|||||||
dishes: item.dishes.trim(),
|
dishes: item.dishes.trim(),
|
||||||
usableTime: item.usableTime?.trim() || '',
|
usableTime: item.usableTime?.trim() || '',
|
||||||
otherNotes: item.otherNotes?.trim() || '',
|
otherNotes: item.otherNotes?.trim() || '',
|
||||||
|
imageUrl: item.imageUrl?.trim() || '',
|
||||||
sortOrder: index,
|
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 {
|
export function validatePackageFormItems(items: PackageFormItem[]): string | null {
|
||||||
|
|||||||
@@ -1,4 +1,9 @@
|
|||||||
import { apiBase, request } from './api';
|
import { apiBase, request } from './api';
|
||||||
|
import {
|
||||||
|
compressImageFileIfNeeded,
|
||||||
|
DEFAULT_OSS_MAX_UPLOAD_BYTES,
|
||||||
|
formatOssMaxSizeMb,
|
||||||
|
} from '@dukang/shared-ui/compressImage';
|
||||||
|
|
||||||
const UPLOAD_TIMEOUT_MS = 120_000;
|
const UPLOAD_TIMEOUT_MS = 120_000;
|
||||||
|
|
||||||
@@ -11,13 +16,23 @@ export type UploadFileResult = {
|
|||||||
mock: boolean;
|
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(
|
async function uploadFileToOssInner(
|
||||||
file: File,
|
file: File,
|
||||||
options: { bizType: string; mediaType?: OssMediaType },
|
options: { bizType: string; mediaType?: OssMediaType },
|
||||||
): Promise<UploadFileResult> {
|
): Promise<UploadFileResult> {
|
||||||
const mediaType = options.mediaType ?? (file.type.startsWith('video/') ? 'VIDEO' : 'IMAGE');
|
const mediaType = options.mediaType ?? (file.type.startsWith('video/') ? 'VIDEO' : 'IMAGE');
|
||||||
|
const prepared = await prepareUploadFile(file, mediaType);
|
||||||
const formData = new FormData();
|
const formData = new FormData();
|
||||||
formData.append('file', file);
|
formData.append('file', prepared);
|
||||||
formData.append('bizType', options.bizType);
|
formData.append('bizType', options.bizType);
|
||||||
formData.append('mediaType', mediaType);
|
formData.append('mediaType', mediaType);
|
||||||
|
|
||||||
|
|||||||
@@ -48,6 +48,19 @@ export async function canPartnerUseWechatLogin(options: {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 短信登录/发码前:校验手机号对应合伙人存在且未暂停 */
|
||||||
|
export async function checkPartnerPhoneForLogin(phone: string): Promise<PartnerPhoneCheckResponse> {
|
||||||
|
const normalized = phone.trim();
|
||||||
|
if (!/^1\d{10}$/.test(normalized)) {
|
||||||
|
throw new Error('请输入正确的手机号');
|
||||||
|
}
|
||||||
|
return request<PartnerPhoneCheckResponse>('PARTNER_H5', '/partner/auth/phone/check', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ phone: normalized }),
|
||||||
|
silent: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
export async function fetchClientConfig(): Promise<ClientRuntimeConfig> {
|
export async function fetchClientConfig(): Promise<ClientRuntimeConfig> {
|
||||||
return request<ClientRuntimeConfig>('PARTNER_H5', '/common/client-config');
|
return request<ClientRuntimeConfig>('PARTNER_H5', '/common/client-config');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,8 +12,10 @@ import {
|
|||||||
} from '../lib/api';
|
} from '../lib/api';
|
||||||
import { usePartnerSession } from '../contexts/PartnerSessionContext';
|
import { usePartnerSession } from '../contexts/PartnerSessionContext';
|
||||||
import { partnerHomePath } from '../lib/partnerAccess';
|
import { partnerHomePath } from '../lib/partnerAccess';
|
||||||
|
import type { PartnerPhoneCheckResponse } from '@dukang/shared-types';
|
||||||
import {
|
import {
|
||||||
bindPartnerWechatAfterSmsLogin,
|
bindPartnerWechatAfterSmsLogin,
|
||||||
|
checkPartnerPhoneForLogin,
|
||||||
fetchClientConfig,
|
fetchClientConfig,
|
||||||
loginPartnerWithWechat,
|
loginPartnerWithWechat,
|
||||||
} from '../lib/wechat-auth';
|
} from '../lib/wechat-auth';
|
||||||
@@ -69,14 +71,17 @@ function formatPartnerError(e: unknown): string {
|
|||||||
if (text.includes('合伙人账号不存在') || text.includes('未找到合伙人账号')) {
|
if (text.includes('合伙人账号不存在') || text.includes('未找到合伙人账号')) {
|
||||||
return '未找到合伙人账号';
|
return '未找到合伙人账号';
|
||||||
}
|
}
|
||||||
if (text.includes('合伙人账号已停用')) {
|
if (text.includes('合伙人账号已停用') || text.includes('账号已停用')) {
|
||||||
return '合伙人账号已停用';
|
return '合伙人账号已暂停,无法登录';
|
||||||
}
|
}
|
||||||
return text;
|
return text;
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatWechatError(e: unknown): string {
|
function formatWechatError(e: unknown): string {
|
||||||
const text = e instanceof Error ? e.message : '微信登录失败';
|
const text = e instanceof Error ? e.message : '微信登录失败';
|
||||||
|
if (text.includes('合伙人账号已停用') || text.includes('账号已停用')) {
|
||||||
|
return '合伙人账号已暂停,无法登录';
|
||||||
|
}
|
||||||
if (text.includes('首次登录') || text.includes('手机验证码')) {
|
if (text.includes('首次登录') || text.includes('手机验证码')) {
|
||||||
return '该微信尚未绑定合伙人账号,请先使用手机验证码登录,登录后将自动关联微信';
|
return '该微信尚未绑定合伙人账号,请先使用手机验证码登录,登录后将自动关联微信';
|
||||||
}
|
}
|
||||||
@@ -138,11 +143,21 @@ export default function LoginPage() {
|
|||||||
|
|
||||||
async function sendCode() {
|
async function sendCode() {
|
||||||
if (!ensureAgreed()) return;
|
if (!ensureAgreed()) return;
|
||||||
|
const trimmedPhone = phone.trim();
|
||||||
|
if (!trimmedPhone) {
|
||||||
|
setMsg('请输入手机号');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!/^1\d{10}$/.test(trimmedPhone)) {
|
||||||
|
setMsg('请输入正确的手机号');
|
||||||
|
return;
|
||||||
|
}
|
||||||
setMsg('');
|
setMsg('');
|
||||||
try {
|
try {
|
||||||
|
await checkPartnerPhoneForLogin(trimmedPhone);
|
||||||
await request('PARTNER_H5', '/partner/auth/sms/send', {
|
await request('PARTNER_H5', '/partner/auth/sms/send', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: JSON.stringify({ phone, scene: 'PARTNER_LOGIN' }),
|
body: JSON.stringify({ phone: trimmedPhone, scene: 'PARTNER_LOGIN' }),
|
||||||
silent: true,
|
silent: true,
|
||||||
});
|
});
|
||||||
setMsg('验证码已发送');
|
setMsg('验证码已发送');
|
||||||
@@ -168,12 +183,27 @@ export default function LoginPage() {
|
|||||||
|
|
||||||
async function login() {
|
async function login() {
|
||||||
if (!ensureAgreed()) return;
|
if (!ensureAgreed()) return;
|
||||||
|
const trimmedPhone = phone.trim();
|
||||||
|
const trimmedCode = code.trim();
|
||||||
|
if (!trimmedPhone) {
|
||||||
|
setMsg('请输入手机号');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!/^1\d{10}$/.test(trimmedPhone)) {
|
||||||
|
setMsg('请输入正确的手机号');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!trimmedCode) {
|
||||||
|
setMsg('请输入验证码');
|
||||||
|
return;
|
||||||
|
}
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setMsg('');
|
setMsg('');
|
||||||
try {
|
try {
|
||||||
|
await checkPartnerPhoneForLogin(trimmedPhone);
|
||||||
const data = await request<PartnerSessionPayload>('PARTNER_H5', '/partner/auth/login/sms', {
|
const data = await request<PartnerSessionPayload>('PARTNER_H5', '/partner/auth/login/sms', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: JSON.stringify({ phone, code }),
|
body: JSON.stringify({ phone: trimmedPhone, code: trimmedCode }),
|
||||||
silent: true,
|
silent: true,
|
||||||
});
|
});
|
||||||
saveRememberedSession(data);
|
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 { STORE_PACKAGE_MAX_COUNT } from '@dukang/shared-types';
|
||||||
import { emptyPackage, type PackageFormItem } from '../lib/storePackages';
|
import { emptyPackage, type PackageFormItem } from '../lib/storePackages';
|
||||||
|
import { uploadFileToOss } from '../lib/upload';
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
items: PackageFormItem[];
|
items: PackageFormItem[];
|
||||||
@@ -10,6 +11,19 @@ type Props = {
|
|||||||
|
|
||||||
export default function ShopPackagesForm({ items, onChange, disabled }: Props) {
|
export default function ShopPackagesForm({ items, onChange, disabled }: Props) {
|
||||||
const [collapsed, setCollapsed] = useState<Record<number, boolean>>({});
|
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>) {
|
function updateAt(index: number, patch: Partial<PackageFormItem>) {
|
||||||
onChange(items.map((item, i) => (i === index ? { ...item, ...patch } : item)));
|
onChange(items.map((item, i) => (i === index ? { ...item, ...patch } : item)));
|
||||||
@@ -116,6 +130,36 @@ export default function ShopPackagesForm({ items, onChange, disabled }: Props) {
|
|||||||
/>
|
/>
|
||||||
</label>
|
</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">
|
<label className="shop-packages-field">
|
||||||
<span className="shop-packages-label">其他说明</span>
|
<span className="shop-packages-label">其他说明</span>
|
||||||
<input
|
<input
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ import {
|
|||||||
import {
|
import {
|
||||||
fetchClientConfig,
|
fetchClientConfig,
|
||||||
handleShopWechatCallback,
|
handleShopWechatCallback,
|
||||||
|
handleShopWechatCallbackOnce,
|
||||||
handleShopWechatLoginResult,
|
handleShopWechatLoginResult,
|
||||||
isShopWechatUnboundError,
|
isShopWechatUnboundError,
|
||||||
SHOP_WX_NEED_PHONE_LOGIN_MSG,
|
SHOP_WX_NEED_PHONE_LOGIN_MSG,
|
||||||
@@ -79,7 +80,7 @@ export function StoreSessionProvider({ children }: { children: ReactNode }) {
|
|||||||
try {
|
try {
|
||||||
const config = await fetchClientConfig();
|
const config = await fetchClientConfig();
|
||||||
if (isWxAuthorizeEnabled(config)) {
|
if (isWxAuthorizeEnabled(config)) {
|
||||||
const result = await handleShopWechatCallback();
|
const result = await handleShopWechatCallbackOnce();
|
||||||
if (result && !cancelled) {
|
if (result && !cancelled) {
|
||||||
const session = handleShopWechatLoginResult(result);
|
const session = handleShopWechatLoginResult(result);
|
||||||
if (session) applySession(session);
|
if (session) applySession(session);
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { reportApiError } from '@dukang/client-logging';
|
||||||
|
|
||||||
export const apiBase = '/api/v1';
|
export const apiBase = '/api/v1';
|
||||||
const CLIENT_APP = 'SHOP_H5';
|
const CLIENT_APP = 'SHOP_H5';
|
||||||
|
|
||||||
@@ -213,6 +215,12 @@ async function rawRequest<T>(
|
|||||||
if (json.code !== 0) {
|
if (json.code !== 0) {
|
||||||
const err = new Error(json.message || '请求失败') as Error & { status?: number };
|
const err = new Error(json.message || '请求失败') as Error & { status?: number };
|
||||||
err.status = res.status >= 500 ? res.status : json.code;
|
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;
|
throw err;
|
||||||
}
|
}
|
||||||
return json.data as T;
|
return json.data as T;
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import { isIosDevice } from '@dukang/weixin-sdk';
|
||||||
|
|
||||||
|
/** 扫码前发起 OAuth 时标记,回跳后在首页续扫 */
|
||||||
|
export const SHOP_PENDING_SCAN_KEY = 'shop_pending_scan';
|
||||||
|
|
||||||
|
export function markPendingScanAfterAuth(): void {
|
||||||
|
try {
|
||||||
|
sessionStorage.setItem(SHOP_PENDING_SCAN_KEY, '1');
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function peekPendingScanAfterAuth(): boolean {
|
||||||
|
try {
|
||||||
|
return sessionStorage.getItem(SHOP_PENDING_SCAN_KEY) === '1';
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clearPendingScanAfterAuth(): void {
|
||||||
|
try {
|
||||||
|
sessionStorage.removeItem(SHOP_PENDING_SCAN_KEY);
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** OAuth 回跳后延迟再调 scanQRCode(iOS JSSDK 离线校验更慢) */
|
||||||
|
export function getPostAuthScanDelayMs(): number {
|
||||||
|
return isIosDevice() ? 1200 : 600;
|
||||||
|
}
|
||||||
@@ -10,6 +10,7 @@ export function emptyPackage(index = 0): PackageFormItem {
|
|||||||
dishes: '',
|
dishes: '',
|
||||||
usableTime: '',
|
usableTime: '',
|
||||||
otherNotes: '',
|
otherNotes: '',
|
||||||
|
imageUrl: '',
|
||||||
sortOrder: index,
|
sortOrder: index,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -22,9 +23,13 @@ export function normalizePackageFormItems(raw: PackageFormItem[]): PackageFormIt
|
|||||||
dishes: item.dishes.trim(),
|
dishes: item.dishes.trim(),
|
||||||
usableTime: item.usableTime?.trim() || '',
|
usableTime: item.usableTime?.trim() || '',
|
||||||
otherNotes: item.otherNotes?.trim() || '',
|
otherNotes: item.otherNotes?.trim() || '',
|
||||||
|
imageUrl: item.imageUrl?.trim() || '',
|
||||||
sortOrder: index,
|
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 {
|
export function validatePackageFormItems(items: PackageFormItem[]): string | null {
|
||||||
|
|||||||
@@ -1,5 +1,10 @@
|
|||||||
import { apiBase } from './api';
|
import { apiBase } from './api';
|
||||||
import { getStoreProfile } 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;
|
const UPLOAD_TIMEOUT_MS = 120_000;
|
||||||
|
|
||||||
@@ -15,9 +20,13 @@ export type RegisteredResource = {
|
|||||||
url: string;
|
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();
|
const formData = new FormData();
|
||||||
formData.append('file', file);
|
formData.append('file', compressed);
|
||||||
formData.append('bizType', bizType);
|
formData.append('bizType', bizType);
|
||||||
formData.append('mediaType', 'IMAGE');
|
formData.append('mediaType', 'IMAGE');
|
||||||
|
|
||||||
|
|||||||
@@ -138,6 +138,20 @@ export async function handleShopWechatCallback(): Promise<WechatLoginResult | nu
|
|||||||
return weixinSdk.handleOAuthCallback();
|
return weixinSdk.handleOAuthCallback();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let oauthCallbackInflight: Promise<WechatLoginResult | null> | null = null;
|
||||||
|
|
||||||
|
/** 全局单例:避免 Context 与页面 effect 重复消费 OAuth code */
|
||||||
|
export async function handleShopWechatCallbackOnce(): Promise<WechatLoginResult | null> {
|
||||||
|
if (!isWechatEnv()) return null;
|
||||||
|
const params = new URLSearchParams(window.location.search);
|
||||||
|
if (!params.get('code')) return null;
|
||||||
|
if (oauthCallbackInflight) return oauthCallbackInflight;
|
||||||
|
oauthCallbackInflight = handleShopWechatCallback().finally(() => {
|
||||||
|
oauthCallbackInflight = null;
|
||||||
|
});
|
||||||
|
return oauthCallbackInflight;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 微信一键登录(已绑定微信的门店账号免验证码)。
|
* 微信一键登录(已绑定微信的门店账号免验证码)。
|
||||||
* 返回 session = 已登录;void = 已跳转授权页等待回调。
|
* 返回 session = 已登录;void = 已跳转授权页等待回调。
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { useCallback, useEffect, useState } from 'react';
|
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||||
|
|
||||||
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
|
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
|
||||||
|
|
||||||
import PullToRefresh from '@dukang/shared-ui/PullToRefresh';
|
import PullToRefresh from '@dukang/shared-ui/PullToRefresh';
|
||||||
|
|
||||||
import { isScanPermissionWarmupError } from '@dukang/weixin-sdk';
|
import { isScanPermissionWarmupError } from '@dukang/weixin-sdk';
|
||||||
@@ -8,27 +9,31 @@ import {
|
|||||||
import { useStoreSession } from '../contexts/StoreSessionContext';
|
import { useStoreSession } from '../contexts/StoreSessionContext';
|
||||||
|
|
||||||
import { request } from '../lib/api';
|
import { request } from '../lib/api';
|
||||||
handleShopWechatCallback,
|
|
||||||
handleShopWechatLoginResult,
|
|
||||||
|
|
||||||
import { parseRedeemTokenFromScan } from '../lib/redeem-scan';
|
import { parseRedeemTokenFromScan } from '../lib/redeem-scan';
|
||||||
import { stripOAuthParamsFromLocation } from '@dukang/weixin-sdk';
|
|
||||||
|
import {
|
||||||
|
|
||||||
|
authorizeShopWechat,
|
||||||
|
|
||||||
|
checkNeedsWechatAuth,
|
||||||
|
|
||||||
fetchShopAccount,
|
fetchShopAccount,
|
||||||
|
|
||||||
} from '../lib/wechat-auth';
|
} from '../lib/wechat-auth';
|
||||||
const PENDING_SCAN_KEY = 'shop_pending_scan';
|
|
||||||
|
|
||||||
|
|
||||||
import { isWechatEnv, weixinSdk } from '../lib/weixin';
|
import { isWechatEnv, weixinSdk } from '../lib/weixin';
|
||||||
|
|
||||||
import {
|
import {
|
||||||
function formatScanError(e: unknown): string {
|
|
||||||
clearPendingScanAfterAuth,
|
clearPendingScanAfterAuth,
|
||||||
|
|
||||||
getPostAuthScanDelayMs,
|
getPostAuthScanDelayMs,
|
||||||
|
|
||||||
if (/offline verifying|权限验证中|接口未就绪/i.test(msg)) {
|
markPendingScanAfterAuth,
|
||||||
|
|
||||||
|
peekPendingScanAfterAuth,
|
||||||
|
|
||||||
} from '../lib/shop-scan-auth';
|
} from '../lib/shop-scan-auth';
|
||||||
|
|
||||||
import WechatScanAuthModal from '../components/WechatScanAuthModal';
|
import WechatScanAuthModal from '../components/WechatScanAuthModal';
|
||||||
@@ -37,14 +42,15 @@ function formatScanError(e: unknown): string {
|
|||||||
|
|
||||||
import { trackStore } from '../lib/analytics';
|
import { trackStore } from '../lib/analytics';
|
||||||
|
|
||||||
const { applySession } = useStoreSession();
|
|
||||||
const [searchParams, setSearchParams] = useSearchParams();
|
|
||||||
function formatMoney(n: number) {
|
function formatMoney(n: number) {
|
||||||
|
|
||||||
return n.toLocaleString('zh-CN', { minimumFractionDigits: 0, maximumFractionDigits: 2 });
|
return n.toLocaleString('zh-CN', { minimumFractionDigits: 0, maximumFractionDigits: 2 });
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
function formatScanError(e: unknown, opts?: { afterAuth?: boolean }): string {
|
function formatScanError(e: unknown, opts?: { afterAuth?: boolean }): string {
|
||||||
|
|
||||||
@@ -76,16 +82,18 @@ export default function HomePage() {
|
|||||||
|
|
||||||
export default function HomePage() {
|
export default function HomePage() {
|
||||||
|
|
||||||
async function runScan(opts?: { postAuthWarmup?: boolean }) {
|
useStorePageView('store_home_view');
|
||||||
|
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
|
||||||
const { ready, authenticated } = useStoreSession();
|
const { ready, authenticated } = useStoreSession();
|
||||||
|
|
||||||
const [searchParams] = useSearchParams();
|
const [searchParams] = useSearchParams();
|
||||||
|
|
||||||
|
const [dash, setDash] = useState<Record<string, unknown> | null>(null);
|
||||||
|
|
||||||
|
const [scanMsg, setScanMsg] = useState('');
|
||||||
|
|
||||||
// 授权回跳后强制重签,避免沿用带 code 的旧签名态
|
|
||||||
const [scanning, setScanning] = useState(false);
|
const [scanning, setScanning] = useState(false);
|
||||||
|
|
||||||
const [authModalOpen, setAuthModalOpen] = useState(false);
|
const [authModalOpen, setAuthModalOpen] = useState(false);
|
||||||
@@ -104,37 +112,33 @@ export default function HomePage() {
|
|||||||
|
|
||||||
.then((d) => {
|
.then((d) => {
|
||||||
|
|
||||||
setScanMsg(formatScanError(e));
|
setDash(d);
|
||||||
|
|
||||||
})
|
})
|
||||||
|
|
||||||
}
|
.catch(() => {});
|
||||||
|
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
if (!isWechatEnv() || !searchParams.get('code')) return;
|
useEffect(() => {
|
||||||
void handleShopWechatCallback()
|
|
||||||
.then((result) => {
|
void loadDashboard();
|
||||||
if (!result) return;
|
|
||||||
const session = handleShopWechatLoginResult(result);
|
}, [loadDashboard]);
|
||||||
if (session) {
|
|
||||||
applySession(session);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// 先清 OAuth 参数再扫,保证 JSSDK 签名 URL 与当前页一致
|
|
||||||
stripOAuthParamsFromLocation();
|
function onResume() {
|
||||||
setSearchParams({}, { replace: true });
|
|
||||||
const shouldScan = sessionStorage.getItem(PENDING_SCAN_KEY) === '1';
|
setScanning(false);
|
||||||
sessionStorage.removeItem(PENDING_SCAN_KEY);
|
|
||||||
if (shouldScan) {
|
void loadDashboard();
|
||||||
// OAuth 回跳后微信权限离线校验未完成;稍候再扫,失败可再点一次
|
|
||||||
window.setTimeout(() => void runScan({ postAuthWarmup: true }), 400);
|
}
|
||||||
}
|
|
||||||
})
|
|
||||||
.catch((e) => {
|
|
||||||
setAuthError(e instanceof Error ? e.message : '微信授权失败');
|
|
||||||
});
|
|
||||||
}, [searchParams, applySession, setSearchParams]);
|
|
||||||
|
|
||||||
function onVisibility() {
|
function onVisibility() {
|
||||||
|
|
||||||
@@ -145,6 +149,7 @@ export default function HomePage() {
|
|||||||
document.addEventListener('visibilitychange', onVisibility);
|
document.addEventListener('visibilitychange', onVisibility);
|
||||||
|
|
||||||
window.addEventListener('pageshow', onResume);
|
window.addEventListener('pageshow', onResume);
|
||||||
|
|
||||||
window.addEventListener('focus', onResume);
|
window.addEventListener('focus', onResume);
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
@@ -158,10 +163,11 @@ export default function HomePage() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
}, [loadDashboard]);
|
}, [loadDashboard]);
|
||||||
sessionStorage.setItem(PENDING_SCAN_KEY, '1');
|
|
||||||
|
|
||||||
|
|
||||||
const runScan = useCallback(
|
const runScan = useCallback(
|
||||||
sessionStorage.removeItem(PENDING_SCAN_KEY);
|
|
||||||
async (opts?: { postAuthWarmup?: boolean }) => {
|
async (opts?: { postAuthWarmup?: boolean }) => {
|
||||||
|
|
||||||
trackStore('store_redeem_scan_start');
|
trackStore('store_redeem_scan_start');
|
||||||
@@ -277,9 +283,11 @@ export default function HomePage() {
|
|||||||
|
|
||||||
|
|
||||||
async function handleScan() {
|
async function handleScan() {
|
||||||
sessionStorage.removeItem(PENDING_SCAN_KEY);
|
|
||||||
|
setScanMsg('');
|
||||||
|
|
||||||
if (!isWechatEnv()) {
|
if (!isWechatEnv()) {
|
||||||
|
|
||||||
setScanMsg('请在微信内打开门店端进行扫码核销');
|
setScanMsg('请在微信内打开门店端进行扫码核销');
|
||||||
|
|
||||||
|
return;
|
||||||
@@ -18,7 +18,7 @@ import {
|
|||||||
consumeShopWechatLoginHint,
|
consumeShopWechatLoginHint,
|
||||||
fetchClientConfig,
|
fetchClientConfig,
|
||||||
formatShopWechatError,
|
formatShopWechatError,
|
||||||
handleShopWechatCallback,
|
handleShopWechatCallbackOnce,
|
||||||
handleShopWechatLoginResult,
|
handleShopWechatLoginResult,
|
||||||
loginShopWithWechat,
|
loginShopWithWechat,
|
||||||
} from '../lib/wechat-auth';
|
} from '../lib/wechat-auth';
|
||||||
@@ -88,7 +88,7 @@ export default function LoginPage() {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isWechatEnv() || !wxAuthorize || !params.get('code')) return;
|
if (!isWechatEnv() || !wxAuthorize || !params.get('code')) return;
|
||||||
void handleShopWechatCallback()
|
void handleShopWechatCallbackOnce()
|
||||||
.then((result) => {
|
.then((result) => {
|
||||||
if (!result) return;
|
if (!result) return;
|
||||||
const session = handleShopWechatLoginResult(result);
|
const session = handleShopWechatLoginResult(result);
|
||||||
@@ -140,12 +140,22 @@ export default function LoginPage() {
|
|||||||
|
|
||||||
async function login() {
|
async function login() {
|
||||||
if (!ensureAgreed()) return;
|
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);
|
setLoading(true);
|
||||||
setMsg('');
|
setMsg('');
|
||||||
try {
|
try {
|
||||||
const data = await request<ShopSessionPayload>('SHOP_H5', '/shop/auth/login/sms', {
|
const data = await request<ShopSessionPayload>('SHOP_H5', '/shop/auth/login/sms', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: JSON.stringify({ phone, code }),
|
body: JSON.stringify({ phone: trimmedPhone, code: trimmedCode }),
|
||||||
});
|
});
|
||||||
saveRememberedSession(data);
|
saveRememberedSession(data);
|
||||||
applySession(data);
|
applySession(data);
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import {
|
|||||||
authorizeShopWechat,
|
authorizeShopWechat,
|
||||||
fetchClientConfig,
|
fetchClientConfig,
|
||||||
fetchShopAccount,
|
fetchShopAccount,
|
||||||
handleShopWechatCallback,
|
handleShopWechatCallbackOnce,
|
||||||
handleShopWechatLoginResult,
|
handleShopWechatLoginResult,
|
||||||
} from '../lib/wechat-auth';
|
} from '../lib/wechat-auth';
|
||||||
import { isWechatEnv } from '../lib/weixin';
|
import { isWechatEnv } from '../lib/weixin';
|
||||||
@@ -45,7 +45,7 @@ export default function MinePage() {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isWechatEnv() || !wxAuthorize || !searchParams.get('code')) return;
|
if (!isWechatEnv() || !wxAuthorize || !searchParams.get('code')) return;
|
||||||
void handleShopWechatCallback()
|
void handleShopWechatCallbackOnce()
|
||||||
.then((result) => {
|
.then((result) => {
|
||||||
if (!result) return;
|
if (!result) return;
|
||||||
const session = handleShopWechatLoginResult(result);
|
const session = handleShopWechatLoginResult(result);
|
||||||
|
|||||||
@@ -80,7 +80,6 @@ export default function WithdrawPage() {
|
|||||||
const canApply =
|
const canApply =
|
||||||
!!summary?.isPrimary &&
|
!!summary?.isPrimary &&
|
||||||
summary.availableAmount > 0 &&
|
summary.availableAmount > 0 &&
|
||||||
!summary.hasPendingRequest &&
|
|
||||||
summary.hasBankAccount &&
|
summary.hasBankAccount &&
|
||||||
!submitting;
|
!submitting;
|
||||||
|
|
||||||
@@ -126,7 +125,6 @@ export default function WithdrawPage() {
|
|||||||
info
|
info
|
||||||
</span>
|
</span>
|
||||||
单日上限 ¥{formatMoney(summary?.dailyLimit ?? 5000)}
|
单日上限 ¥{formatMoney(summary?.dailyLimit ?? 5000)}
|
||||||
{summary?.hasPendingRequest ? ' · 已有待审核申请' : ''}
|
|
||||||
{!summary?.hasBankAccount ? ' · 请先完善收款账户' : ''}
|
{!summary?.hasBankAccount ? ' · 请先完善收款账户' : ''}
|
||||||
</p>
|
</p>
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { reportApiError } from '@dukang/client-logging';
|
||||||
|
|
||||||
export const BRAND = {
|
export const BRAND = {
|
||||||
red: '#A02D30',
|
red: '#A02D30',
|
||||||
yellow: '#FFC107',
|
yellow: '#FFC107',
|
||||||
@@ -83,6 +85,12 @@ async function rawRequest<T>(
|
|||||||
if (json.code !== 0) {
|
if (json.code !== 0) {
|
||||||
const err = new Error(json.message || '请求失败') as Error & { status?: number };
|
const err = new Error(json.message || '请求失败') as Error & { status?: number };
|
||||||
err.status = json.code;
|
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;
|
throw err;
|
||||||
}
|
}
|
||||||
return json.data as T;
|
return json.data as T;
|
||||||
|
|||||||
@@ -1,4 +1,9 @@
|
|||||||
import { apiBase } from './api';
|
import { apiBase } from './api';
|
||||||
|
import {
|
||||||
|
compressImageFileIfNeeded,
|
||||||
|
DEFAULT_OSS_MAX_UPLOAD_BYTES,
|
||||||
|
formatOssMaxSizeMb,
|
||||||
|
} from '@dukang/shared-ui/compressImage';
|
||||||
|
|
||||||
export type OssMediaType = 'IMAGE' | 'VIDEO' | 'FILE';
|
export type OssMediaType = 'IMAGE' | 'VIDEO' | 'FILE';
|
||||||
|
|
||||||
@@ -15,8 +20,15 @@ export async function uploadFileToOss(
|
|||||||
options: { bizType: string; mediaType?: OssMediaType },
|
options: { bizType: string; mediaType?: OssMediaType },
|
||||||
): Promise<UploadFileResult> {
|
): Promise<UploadFileResult> {
|
||||||
const mediaType = options.mediaType ?? (file.type.startsWith('video/') ? 'VIDEO' : 'IMAGE');
|
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();
|
const formData = new FormData();
|
||||||
formData.append('file', file);
|
formData.append('file', prepared);
|
||||||
formData.append('bizType', options.bizType);
|
formData.append('bizType', options.bizType);
|
||||||
formData.append('mediaType', mediaType);
|
formData.append('mediaType', mediaType);
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@dukang/mini-user",
|
"name": "@dukang/mini-user",
|
||||||
"version": "0.1.0",
|
"version": "3.4.13",
|
||||||
"private": true,
|
"private": true,
|
||||||
"description": "杜康好客 · C 端用户微信小程序(Taro)",
|
"description": "杜康好客 · C 端用户微信小程序(Taro)",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ export default defineAppConfig({
|
|||||||
'pages/pay/index',
|
'pages/pay/index',
|
||||||
'pages/orders/index',
|
'pages/orders/index',
|
||||||
'pages/order-detail/index',
|
'pages/order-detail/index',
|
||||||
|
'pages/order-logistics/index',
|
||||||
'pages/pickup-receive/index',
|
'pages/pickup-receive/index',
|
||||||
'pages/addresses/index',
|
'pages/addresses/index',
|
||||||
'pages/address-edit/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 { useState } from 'react';
|
||||||
import { View, Image, Swiper, SwiperItem } from '@tarojs/components';
|
import { View, Image, Swiper, SwiperItem } from '@tarojs/components';
|
||||||
|
import Taro from '@tarojs/taro';
|
||||||
|
|
||||||
type ProductCarouselProps = {
|
type ProductCarouselProps = {
|
||||||
images: string[];
|
images: string[];
|
||||||
alt: string;
|
alt: string;
|
||||||
variant?: 'home' | 'detail' | 'store';
|
variant?: 'home' | 'detail' | 'store';
|
||||||
|
previewable?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
/** 商品/门店轮播(对齐 h5 ProductCarousel 三变体) */
|
/** 商品/门店轮播(对齐 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 slides = images.length > 0 ? images : [''];
|
||||||
const [activeIndex, setActiveIndex] = useState(0);
|
const [activeIndex, setActiveIndex] = useState(0);
|
||||||
const prefix =
|
const prefix =
|
||||||
variant === 'store' ? 'store-detail-carousel' : variant === 'home' ? 'home-carousel' : 'detail-carousel';
|
variant === 'store' ? 'store-detail-carousel' : variant === 'home' ? 'home-carousel' : 'detail-carousel';
|
||||||
|
const imageMode = '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 (
|
return (
|
||||||
<View className={`${prefix}-wrap`}>
|
<View className={`${prefix}-wrap`}>
|
||||||
@@ -24,7 +39,13 @@ export default function ProductCarousel({ images, alt, variant = 'detail' }: Pro
|
|||||||
{slides.map((src, index) => (
|
{slides.map((src, index) => (
|
||||||
<SwiperItem key={`${src}-${index}`} className={`${prefix}-item`}>
|
<SwiperItem key={`${src}-${index}`} className={`${prefix}-item`}>
|
||||||
{src ? (
|
{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`} />
|
<View className={`${prefix}-placeholder`} />
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { useEffect, useRef } from 'react';
|
|||||||
import { finishLoginNavigate, forceReloadAfterAccountMerge, goLogin } from '../lib/auth-nav';
|
import { finishLoginNavigate, forceReloadAfterAccountMerge, goLogin } from '../lib/auth-nav';
|
||||||
import { toast } from '../lib/api';
|
import { toast } from '../lib/api';
|
||||||
import { capturePromoSceneAndTouchScan } from '../lib/promo';
|
import { capturePromoSceneAndTouchScan } from '../lib/promo';
|
||||||
|
import { initClientVersionChecks } from '../lib/client-version';
|
||||||
import { saveWechatLoginResult } from '../lib/pay-wechat';
|
import { saveWechatLoginResult } from '../lib/pay-wechat';
|
||||||
import { applyWechatShare } from '../lib/wechat-share';
|
import { applyWechatShare } from '../lib/wechat-share';
|
||||||
import { handleWechatAuthCallback } from '../lib/wechat-auth';
|
import { handleWechatAuthCallback } from '../lib/wechat-auth';
|
||||||
@@ -38,6 +39,7 @@ export default function WechatShareBootstrap() {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
void capturePromoSceneAndTouchScan();
|
void capturePromoSceneAndTouchScan();
|
||||||
|
initClientVersionChecks();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { ClientApp } from '@dukang/shared-types';
|
|||||||
import { forceReloadAfterAccountMerge } from './auth-nav';
|
import { forceReloadAfterAccountMerge } from './auth-nav';
|
||||||
import { resetStoresSessionBootstrap } from './stores-session';
|
import { resetStoresSessionBootstrap } from './stores-session';
|
||||||
import { resetHomeCatalogBootstrap } from './home-catalog-session';
|
import { resetHomeCatalogBootstrap } from './home-catalog-session';
|
||||||
|
import { reportClientValidationError } from './client-error';
|
||||||
|
|
||||||
function resolveApiBase(): string {
|
function resolveApiBase(): string {
|
||||||
const origin =
|
const origin =
|
||||||
@@ -113,6 +114,12 @@ export async function request<T = unknown>(path: string, options: ReqOptions = {
|
|||||||
throw new Error('接口不可达,请确认 API 服务已启动');
|
throw new Error('接口不可达,请确认 API 服务已启动');
|
||||||
}
|
}
|
||||||
if (status >= 400 || body.code !== 0) {
|
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})`);
|
throw new Error(body?.message || `请求失败(${status})`);
|
||||||
}
|
}
|
||||||
return (res.data as { data: T }).data;
|
return (res.data as { data: T }).data;
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ export type ClientErrorCategory =
|
|||||||
| 'js_error'
|
| 'js_error'
|
||||||
| 'unhandled_rejection'
|
| 'unhandled_rejection'
|
||||||
| 'api_error'
|
| 'api_error'
|
||||||
|
| 'validation_error'
|
||||||
| 'network'
|
| 'network'
|
||||||
| 'render'
|
| 'render'
|
||||||
| 'bridge'
|
| 'bridge'
|
||||||
@@ -57,6 +58,17 @@ export function reportClientError(payload: ClientErrorPayload): void {
|
|||||||
}).catch(() => {});
|
}).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;
|
let installed = false;
|
||||||
|
|
||||||
/** 安装小程序/H5 全局未捕获错误钩子(幂等) */
|
/** 安装小程序/H5 全局未捕获错误钩子(幂等) */
|
||||||
|
|||||||
@@ -0,0 +1,131 @@
|
|||||||
|
import Taro from '@tarojs/taro';
|
||||||
|
import { fetchClientConfig } from './pay-wechat';
|
||||||
|
|
||||||
|
/** 与 package.json version 同步,供服务端 minClientVersion 比对 */
|
||||||
|
export const APP_VERSION = '3.4.13';
|
||||||
|
|
||||||
|
export const APP_VERSION_LABEL = `v${APP_VERSION}`;
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
function exitMiniProgramIfSupported() {
|
||||||
|
if (process.env.TARO_ENV !== 'weapp') return;
|
||||||
|
if (typeof Taro.exitMiniProgram !== 'function') return;
|
||||||
|
void Taro.exitMiniProgram({});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 微信 CDN 有新包时引导 applyUpdate;返回是否已触发更新流程 */
|
||||||
|
function tryWeappForceUpdate(min: string): Promise<boolean> {
|
||||||
|
if (process.env.TARO_ENV !== 'weapp' || typeof Taro.getUpdateManager !== 'function') {
|
||||||
|
return Promise.resolve(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
const manager = Taro.getUpdateManager();
|
||||||
|
let settled = false;
|
||||||
|
const finish = (updated: boolean) => {
|
||||||
|
if (settled) return;
|
||||||
|
settled = true;
|
||||||
|
resolve(updated);
|
||||||
|
};
|
||||||
|
|
||||||
|
manager.onCheckForUpdate((res) => {
|
||||||
|
if (!res.hasUpdate) {
|
||||||
|
finish(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
manager.onUpdateReady(() => {
|
||||||
|
void Taro.showModal({
|
||||||
|
title: '版本过低',
|
||||||
|
content: `当前 ${APP_VERSION_LABEL} 低于要求版本 v${min},已检测到新版本,请立即更新后继续使用。`,
|
||||||
|
showCancel: false,
|
||||||
|
confirmText: '立即更新',
|
||||||
|
success: (r) => {
|
||||||
|
if (r.confirm) {
|
||||||
|
manager.applyUpdate();
|
||||||
|
finish(true);
|
||||||
|
} else {
|
||||||
|
finish(false);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
fail: () => finish(false),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
manager.onUpdateFailed(() => finish(false));
|
||||||
|
});
|
||||||
|
|
||||||
|
setTimeout(() => finish(false), 4000);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function enforceMinClientVersion(min: string) {
|
||||||
|
const updated = await tryWeappForceUpdate(min);
|
||||||
|
if (updated) return;
|
||||||
|
|
||||||
|
await Taro.showModal({
|
||||||
|
title: '版本过低',
|
||||||
|
content: `当前 ${APP_VERSION_LABEL} 低于要求版本 v${min},请更新至最新版本后继续使用。`,
|
||||||
|
showCancel: false,
|
||||||
|
confirmText: '我知道了',
|
||||||
|
});
|
||||||
|
|
||||||
|
exitMiniProgramIfSupported();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function checkClientVersionGate() {
|
||||||
|
try {
|
||||||
|
const config = await fetchClientConfig();
|
||||||
|
const min = config.minClientVersion?.trim();
|
||||||
|
if (min && compareSemver(APP_VERSION, min) < 0) {
|
||||||
|
await enforceMinClientVersion(min);
|
||||||
|
}
|
||||||
|
} 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,并返回已登记到当前用户的真实资源。 */
|
/** 上传 chooseAvatar 临时文件到 OSS,并返回已登记到当前用户的真实资源。 */
|
||||||
export async function uploadAvatarTempFile(tempFilePath: string): Promise<UploadedAvatarResource> {
|
export async function uploadAvatarTempFile(tempFilePath: string): Promise<UploadedAvatarResource> {
|
||||||
const { API_BASE, CLIENT_APP, getToken } = await import('./api');
|
const { API_BASE, CLIENT_APP, getToken } = await import('./api');
|
||||||
|
const { compressWeappImageIfNeeded } = await import('./compress-image');
|
||||||
const token = getToken();
|
const token = getToken();
|
||||||
if (!token) throw new Error('请先登录');
|
if (!token) throw new Error('请先登录');
|
||||||
|
|
||||||
|
const filePath = await compressWeappImageIfNeeded(tempFilePath);
|
||||||
|
|
||||||
const res = await Taro.uploadFile({
|
const res = await Taro.uploadFile({
|
||||||
url: `${API_BASE}/common/resources/upload`,
|
url: `${API_BASE}/common/resources/upload`,
|
||||||
filePath: tempFilePath,
|
filePath,
|
||||||
name: 'file',
|
name: 'file',
|
||||||
formData: {
|
formData: {
|
||||||
bizType: 'AVATAR',
|
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`);
|
||||||
|
}
|
||||||
@@ -23,6 +23,7 @@ import {
|
|||||||
} from '../../lib/mini-wechat-profile';
|
} from '../../lib/mini-wechat-profile';
|
||||||
import { isLoggedIn, logout, request, toast, type UserProfile } from '../../lib/api';
|
import { isLoggedIn, logout, request, toast, type UserProfile } from '../../lib/api';
|
||||||
import { isWechatEnv } from '../../lib/weixin';
|
import { isWechatEnv } from '../../lib/weixin';
|
||||||
|
import { APP_VERSION_LABEL } from '../../lib/client-version';
|
||||||
import { maskPhone } from '../../lib/phone';
|
import { maskPhone } from '../../lib/phone';
|
||||||
import {
|
import {
|
||||||
DEFAULT_SHARE_DESC,
|
DEFAULT_SHARE_DESC,
|
||||||
@@ -499,7 +500,7 @@ export default function MinePage() {
|
|||||||
</View>
|
</View>
|
||||||
|
|
||||||
<View className="mine-footer">
|
<View className="mine-footer">
|
||||||
<Text className="mine-version">杜康好客</Text>
|
<Text className="mine-version">杜康好客 {APP_VERSION_LABEL}</Text>
|
||||||
<Text className="mine-logout" onClick={() => logout()}>
|
<Text className="mine-logout" onClick={() => logout()}>
|
||||||
退出登录
|
退出登录
|
||||||
</Text>
|
</Text>
|
||||||
|
|||||||
@@ -141,6 +141,14 @@ export default function OrderConfirmPickupPage() {
|
|||||||
const ready = await ensurePayReady(returnPath);
|
const ready = await ensurePayReady(returnPath);
|
||||||
if (!ready) return;
|
if (!ready) return;
|
||||||
|
|
||||||
|
const { confirm } = await Taro.showModal({
|
||||||
|
title: '确认提交订单',
|
||||||
|
content: `确认提交现场提货订单?共 ${quantity} 瓶,应付 ¥${Number(preview?.payAmount ?? 0).toFixed(2)}。`,
|
||||||
|
confirmText: '确认提交',
|
||||||
|
cancelText: '再想想',
|
||||||
|
});
|
||||||
|
if (!confirm) return;
|
||||||
|
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setMsg('');
|
setMsg('');
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -6,8 +6,19 @@ import SubPageHeader from '../../components/SubPageHeader';
|
|||||||
import ShareNavButton from '../../components/ShareNavButton';
|
import ShareNavButton from '../../components/ShareNavButton';
|
||||||
import WechatShareReady from '../../components/WechatShareReady';
|
import WechatShareReady from '../../components/WechatShareReady';
|
||||||
import ContactCsButton from '../../components/ContactCsButton';
|
import ContactCsButton from '../../components/ContactCsButton';
|
||||||
|
import LogisticsRichText from '../../components/LogisticsRichText';
|
||||||
import { request, toast } from '../../lib/api';
|
import { request, toast } from '../../lib/api';
|
||||||
import { buildPayUrl } from '../../lib/checkout-nav';
|
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 { maskPhone } from '../../lib/phone';
|
||||||
import { confirmOrderReceive, type WechatConfirmPayload } from '../../lib/wechat-order-confirm';
|
import { confirmOrderReceive, type WechatConfirmPayload } from '../../lib/wechat-order-confirm';
|
||||||
import {
|
import {
|
||||||
@@ -44,8 +55,15 @@ type OrderDetail = {
|
|||||||
orderType?: string;
|
orderType?: string;
|
||||||
isProxyOrder?: boolean;
|
isProxyOrder?: boolean;
|
||||||
proxyPartnerName?: string | null;
|
proxyPartnerName?: string | null;
|
||||||
|
deliveryType?: string;
|
||||||
items?: OrderItem[];
|
items?: OrderItem[];
|
||||||
wechatConfirm?: WechatConfirmPayload | null;
|
wechatConfirm?: WechatConfirmPayload | null;
|
||||||
|
delivery?: {
|
||||||
|
provider?: string;
|
||||||
|
trackingNo?: string;
|
||||||
|
logisticsCompany?: string;
|
||||||
|
manualQueryUrl?: string;
|
||||||
|
} | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
const STATUS_LABELS: Record<string, string> = {
|
const STATUS_LABELS: Record<string, string> = {
|
||||||
@@ -78,11 +96,41 @@ export default function OrderDetailPage() {
|
|||||||
usePageView('order_detail_view', orderId ? { orderId } : undefined);
|
usePageView('order_detail_view', orderId ? { orderId } : undefined);
|
||||||
const [order, setOrder] = useState<OrderDetail | null>(null);
|
const [order, setOrder] = useState<OrderDetail | null>(null);
|
||||||
const [confirming, setConfirming] = useState(false);
|
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(() => {
|
useEffect(() => {
|
||||||
if (!orderId) return;
|
if (!orderId) return;
|
||||||
request<OrderDetail>(`/trade/orders/${orderId}`)
|
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 : '加载失败'));
|
.catch((e) => toast(e instanceof Error ? e.message : '加载失败'));
|
||||||
}, [orderId]);
|
}, [orderId]);
|
||||||
|
|
||||||
@@ -90,7 +138,10 @@ export default function OrderDetailPage() {
|
|||||||
if (!orderId) return;
|
if (!orderId) return;
|
||||||
// 从微信确认收货组件返回后刷新
|
// 从微信确认收货组件返回后刷新
|
||||||
request<OrderDetail>(`/trade/orders/${orderId}`)
|
request<OrderDetail>(`/trade/orders/${orderId}`)
|
||||||
.then(setOrder)
|
.then((data) => {
|
||||||
|
setOrder(data);
|
||||||
|
void loadOrderTrack(data.delivery, data.status);
|
||||||
|
})
|
||||||
.catch(() => {});
|
.catch(() => {});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -99,6 +150,18 @@ export default function OrderDetailPage() {
|
|||||||
const canPay = !!order && order.status === 'PENDING_PAY' && !isReship;
|
const canPay = !!order && order.status === 'PENDING_PAY' && !isReship;
|
||||||
const canConfirmReceive =
|
const canConfirmReceive =
|
||||||
!!order && !isReship && !isProxy && ['PENDING_RECEIVE', 'DELIVERED'].includes(order.status || '');
|
!!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 item = order?.items?.[0];
|
||||||
const productName = item?.productName || order?.productName || '杜康商品';
|
const productName = item?.productName || order?.productName || '杜康商品';
|
||||||
@@ -134,6 +197,11 @@ export default function OrderDetailPage() {
|
|||||||
Taro.navigateTo({ url: '/pages/customer-service/index' });
|
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() {
|
async function confirmReceive() {
|
||||||
if (!order || !canConfirmReceive || confirming) return;
|
if (!order || !canConfirmReceive || confirming) return;
|
||||||
|
|
||||||
@@ -211,6 +279,34 @@ export default function OrderDetailPage() {
|
|||||||
{isProxy && order.proxyPartnerName ? (
|
{isProxy && order.proxyPartnerName ? (
|
||||||
<Text className="order-proxy-hint">由合伙人 {order.proxyPartnerName} 代下</Text>
|
<Text className="order-proxy-hint">由合伙人 {order.proxyPartnerName} 代下</Text>
|
||||||
) : null}
|
) : 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>
|
||||||
<View className="order-card">
|
<View className="order-card">
|
||||||
<Text className="order-card-title">商品信息</Text>
|
<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 PageShell from '../../components/PageShell';
|
||||||
import PageNavBar from '../../components/PageNavBar';
|
import PageNavBar from '../../components/PageNavBar';
|
||||||
import ProductCarousel from '../../components/ProductCarousel';
|
import ProductCarousel from '../../components/ProductCarousel';
|
||||||
import ShareNavButton from '../../components/ShareNavButton';
|
|
||||||
import WechatShareReady from '../../components/WechatShareReady';
|
import WechatShareReady from '../../components/WechatShareReady';
|
||||||
import { goLogin } from '../../lib/auth-nav';
|
import { goLogin } from '../../lib/auth-nav';
|
||||||
import { ensurePayReady } from '../../lib/pay-ready';
|
import { ensurePayReady } from '../../lib/pay-ready';
|
||||||
@@ -167,12 +166,11 @@ export default function ProductDetailPage() {
|
|||||||
solid={headerSolid}
|
solid={headerSolid}
|
||||||
titleVisible={headerSolid}
|
titleVisible={headerSolid}
|
||||||
onBack={goBack}
|
onBack={goBack}
|
||||||
right={<ShareNavButton payload={sharePayload} />}
|
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<View className="product-detail-main">
|
<View className="product-detail-main">
|
||||||
<View className="product-detail-hero full-bleed">
|
<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>
|
||||||
|
|
||||||
<View className="product-detail-info">
|
<View className="product-detail-info">
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||||
import { View, Text, Image } from '@tarojs/components';
|
import { View, Text, Image, ScrollView } from '@tarojs/components';
|
||||||
import Taro, {
|
import Taro, {
|
||||||
useDidShow,
|
useDidShow,
|
||||||
useLoad,
|
useLoad,
|
||||||
@@ -15,6 +15,8 @@ import ShareNavButton from '../../components/ShareNavButton';
|
|||||||
import StoreRedeemMarquee from '../../components/StoreRedeemMarquee';
|
import StoreRedeemMarquee from '../../components/StoreRedeemMarquee';
|
||||||
import WechatShareReady from '../../components/WechatShareReady';
|
import WechatShareReady from '../../components/WechatShareReady';
|
||||||
import { request, toast } from '../../lib/api';
|
import { request, toast } from '../../lib/api';
|
||||||
|
import { maskPhone } from '../../lib/phone';
|
||||||
|
import { track } from '../../lib/analytics';
|
||||||
import { formatShanghaiDateTime } from '../../lib/datetime';
|
import { formatShanghaiDateTime } from '../../lib/datetime';
|
||||||
import {
|
import {
|
||||||
DEFAULT_SHARE_DESC,
|
DEFAULT_SHARE_DESC,
|
||||||
@@ -34,6 +36,7 @@ type StorePackage = {
|
|||||||
dishes: string;
|
dishes: string;
|
||||||
usableTime?: string | null;
|
usableTime?: string | null;
|
||||||
otherNotes?: string | null;
|
otherNotes?: string | null;
|
||||||
|
imageUrl?: string | null;
|
||||||
sortOrder?: number;
|
sortOrder?: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -153,9 +156,14 @@ export default function StoreDetailPage() {
|
|||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [loadError, setLoadError] = useState('');
|
const [loadError, setLoadError] = useState('');
|
||||||
const [headerSolid, setHeaderSolid] = useState(false);
|
const [headerSolid, setHeaderSolid] = useState(false);
|
||||||
|
const [activePackageIndex, setActivePackageIndex] = useState(0);
|
||||||
const storeRef = useRef<Store | null>(null);
|
const storeRef = useRef<Store | null>(null);
|
||||||
storeRef.current = store;
|
storeRef.current = store;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setActivePackageIndex(0);
|
||||||
|
}, [store?.id]);
|
||||||
|
|
||||||
usePageScroll(({ scrollTop }) => {
|
usePageScroll(({ scrollTop }) => {
|
||||||
setHeaderSolid(scrollTop > 100);
|
setHeaderSolid(scrollTop > 100);
|
||||||
});
|
});
|
||||||
@@ -270,6 +278,7 @@ export default function StoreDetailPage() {
|
|||||||
toast('暂无门店电话');
|
toast('暂无门店电话');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
track('store_phone_call', { storeId: store.id });
|
||||||
Taro.makePhoneCall({ phoneNumber: store.phone }).catch(() => toast('无法拨打电话'));
|
Taro.makePhoneCall({ phoneNumber: store.phone }).catch(() => toast('无法拨打电话'));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -315,11 +324,9 @@ export default function StoreDetailPage() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const envPhotos = envPhotoUrls(store);
|
const envPhotos = envPhotoUrls(store);
|
||||||
const images = uniqueUrls([
|
const heroImages = uniqueUrls([store.coverUrl, ...(store.carouselUrls || [])]);
|
||||||
store.coverUrl,
|
const packages = store.packages ?? [];
|
||||||
...(store.carouselUrls || []),
|
const activePackage = packages[activePackageIndex] ?? packages[0];
|
||||||
...envPhotos,
|
|
||||||
]);
|
|
||||||
|
|
||||||
const intro = store.intro?.trim() || '';
|
const intro = store.intro?.trim() || '';
|
||||||
const benefitRuleRaw = store.benefitUsageRule?.trim() || '';
|
const benefitRuleRaw = store.benefitUsageRule?.trim() || '';
|
||||||
@@ -346,7 +353,7 @@ export default function StoreDetailPage() {
|
|||||||
/>
|
/>
|
||||||
|
|
||||||
<View className="store-detail-hero full-bleed">
|
<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>
|
||||||
|
|
||||||
<View className="store-detail-info-card">
|
<View className="store-detail-info-card">
|
||||||
@@ -377,7 +384,9 @@ export default function StoreDetailPage() {
|
|||||||
|
|
||||||
{store.phone ? (
|
{store.phone ? (
|
||||||
<View className="store-detail-row">
|
<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 className="store-detail-action" onClick={callStore}>
|
||||||
拨打
|
拨打
|
||||||
</Text>
|
</Text>
|
||||||
@@ -399,24 +408,50 @@ export default function StoreDetailPage() {
|
|||||||
</View>
|
</View>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{store.packages && store.packages.length > 0 ? (
|
{packages.length > 0 && activePackage ? (
|
||||||
<View className="store-detail-section">
|
<View className="store-detail-section store-detail-section--packages">
|
||||||
<Text className="store-detail-section-title">门店套餐</Text>
|
<Text className="store-detail-section-title">门店套餐</Text>
|
||||||
{store.packages.map((pkg, index) => (
|
{packages.length > 1 ? (
|
||||||
<View key={`${pkg.name}-${index}`} className="store-detail-package-card">
|
<ScrollView className="store-detail-package-tabs" scrollX showScrollbar={false} enhanced>
|
||||||
<Text className="store-detail-package-name">{pkg.name}</Text>
|
<View className="store-detail-package-tabs-inner">
|
||||||
<Text className="store-detail-package-body">
|
{packages.map((pkg, index) => (
|
||||||
{formatRedeemAmountYuan(pkg.price)} 元 · {pkg.dishes}
|
<View
|
||||||
</Text>
|
key={`${pkg.name}-${index}`}
|
||||||
{pkg.usableTime ? (
|
className={`store-detail-package-tab${
|
||||||
<Text className="store-detail-package-meta">使用时间:{pkg.usableTime}</Text>
|
index === activePackageIndex ? ' store-detail-package-tab--active' : ''
|
||||||
) : null}
|
}`}
|
||||||
{pkg.otherNotes ? (
|
onClick={() => setActivePackageIndex(index)}
|
||||||
<Text className="store-detail-package-meta">说明:{pkg.otherNotes}</Text>
|
>
|
||||||
) : null}
|
<Text className="store-detail-package-tab-text">{pkg.name}</Text>
|
||||||
</View>
|
</View>
|
||||||
))}
|
))}
|
||||||
</View>
|
</View>
|
||||||
|
</ScrollView>
|
||||||
|
) : null}
|
||||||
|
<View className="store-detail-package-panel">
|
||||||
|
{activePackage.imageUrl ? (
|
||||||
|
<Image
|
||||||
|
className="store-detail-package-thumb"
|
||||||
|
src={activePackage.imageUrl}
|
||||||
|
mode="aspectFill"
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
<View className="store-detail-package-panel-body">
|
||||||
|
{packages.length === 1 ? (
|
||||||
|
<Text className="store-detail-package-name">{activePackage.name}</Text>
|
||||||
|
) : null}
|
||||||
|
<Text className="store-detail-package-body">
|
||||||
|
{formatRedeemAmountYuan(activePackage.price)} 元 · {activePackage.dishes}
|
||||||
|
</Text>
|
||||||
|
{activePackage.usableTime ? (
|
||||||
|
<Text className="store-detail-package-meta">使用时间:{activePackage.usableTime}</Text>
|
||||||
|
) : null}
|
||||||
|
{activePackage.otherNotes ? (
|
||||||
|
<Text className="store-detail-package-meta">说明:{activePackage.otherNotes}</Text>
|
||||||
|
) : null}
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
|
</View>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{intro ? (
|
{intro ? (
|
||||||
@@ -443,7 +478,7 @@ export default function StoreDetailPage() {
|
|||||||
className="store-detail-env-item"
|
className="store-detail-env-item"
|
||||||
onClick={() => previewEnv(index)}
|
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>
|
||||||
))}
|
))}
|
||||||
</View>
|
</View>
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||||
import { View, Text, Image, Input } from '@tarojs/components';
|
import { View, Text, Image, Input } from '@tarojs/components';
|
||||||
import Taro, { useDidShow, usePullDownRefresh, useShareAppMessage, useShareTimeline } from '@tarojs/taro';
|
import Taro, { useDidShow, usePullDownRefresh, useShareAppMessage, useShareTimeline } from '@tarojs/taro';
|
||||||
|
import { StoreStatus, STORE_STATUS_LABELS } from '@dukang/shared-types';
|
||||||
import PageShell from '../../components/PageShell';
|
import PageShell from '../../components/PageShell';
|
||||||
import TabMainHeader from '../../components/TabMainHeader';
|
import TabMainHeader from '../../components/TabMainHeader';
|
||||||
import WechatShareReady from '../../components/WechatShareReady';
|
import WechatShareReady from '../../components/WechatShareReady';
|
||||||
@@ -348,6 +349,12 @@ export default function StoresPage() {
|
|||||||
return parts.length ? `营业时间: ${parts.join(',')}` : '营业时间: 10:00-22:00';
|
return parts.length ? `营业时间: ${parts.join(',')}` : '营业时间: 10:00-22:00';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function formatStatus(store: Store) {
|
||||||
|
const status = store.status as StoreStatus | undefined;
|
||||||
|
if (status && STORE_STATUS_LABELS[status]) return STORE_STATUS_LABELS[status];
|
||||||
|
return STORE_STATUS_LABELS[StoreStatus.OPEN];
|
||||||
|
}
|
||||||
|
|
||||||
const sharePayload = useMemo(
|
const sharePayload = useMemo(
|
||||||
() => ({
|
() => ({
|
||||||
title: '杜康好客门店',
|
title: '杜康好客门店',
|
||||||
@@ -427,31 +434,37 @@ export default function StoresPage() {
|
|||||||
{s.coverUrl ? (
|
{s.coverUrl ? (
|
||||||
<Image className="store-card-cover" src={s.coverUrl} mode="aspectFill" />
|
<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">
|
<View className="store-card-body">
|
||||||
<Text className="store-card-name">{s.name}</Text>
|
{/* 第1行:标题 + 距离 */}
|
||||||
<Text className="store-card-meta">
|
<View className="store-card-row store-card-row--head">
|
||||||
{s.district ? `${s.district} · ` : ''}
|
<Text className="store-card-name" numberOfLines={1}>
|
||||||
{s.address || '地址待完善'}
|
{s.name}
|
||||||
</Text>
|
</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">
|
|
||||||
<Text className="store-card-distance">
|
<Text className="store-card-distance">
|
||||||
{formatDistanceMeters(s.distanceMeters)}
|
{formatDistanceMeters(s.distanceMeters)}
|
||||||
</Text>
|
</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">{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"
|
className="store-card-cta"
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
Taro.navigateTo({ url: '/pages/redeem/index' });
|
Taro.navigateTo({ url: '/pages/redeem/index' });
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
去核销
|
<Text className="store-card-cta-text">去核销</Text>
|
||||||
</Text>
|
</View>
|
||||||
</View>
|
</View>
|
||||||
</View>
|
</View>
|
||||||
</View>
|
</View>
|
||||||
|
|||||||
@@ -488,3 +488,188 @@
|
|||||||
line-height: 1.5;
|
line-height: 1.5;
|
||||||
text-align: center;
|
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,8 +10,9 @@
|
|||||||
.store-detail-carousel-wrap {
|
.store-detail-carousel-wrap {
|
||||||
position: relative;
|
position: relative;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
height: 280px;
|
aspect-ratio: 4 / 3;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
|
background: var(--color-surface-container);
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-detail-carousel {
|
.store-detail-carousel {
|
||||||
@@ -26,6 +27,11 @@
|
|||||||
height: 100%;
|
height: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.store-detail-carousel-image {
|
||||||
|
object-fit: cover;
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
.store-detail-carousel-placeholder {
|
.store-detail-carousel-placeholder {
|
||||||
background: var(--color-surface-container);
|
background: var(--color-surface-container);
|
||||||
}
|
}
|
||||||
@@ -175,24 +181,25 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.store-detail-env-grid {
|
.store-detail-env-grid {
|
||||||
display: grid;
|
display: flex;
|
||||||
grid-template-columns: repeat(3, 1fr);
|
flex-direction: column;
|
||||||
gap: 8px;
|
gap: 12px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-detail-env-item {
|
.store-detail-env-item {
|
||||||
position: relative;
|
position: relative;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
aspect-ratio: 1;
|
|
||||||
border-radius: var(--radius-md, 8px);
|
border-radius: var(--radius-md, 8px);
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
background: var(--color-surface-container);
|
background: var(--color-surface-container);
|
||||||
|
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-detail-env-img {
|
.store-detail-env-img {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
height: 100%;
|
height: auto;
|
||||||
display: block;
|
display: block;
|
||||||
|
vertical-align: top;
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-detail-bar {
|
.store-detail-bar {
|
||||||
@@ -235,33 +242,102 @@
|
|||||||
margin-right: 0;
|
margin-right: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-detail-package-card {
|
.store-detail-section--packages {
|
||||||
padding: 12px 0;
|
overflow: hidden;
|
||||||
border-bottom: 1px solid rgba(0, 0, 0, 0.06);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-detail-package-card:last-of-type {
|
.store-detail-package-tabs {
|
||||||
border-bottom: none;
|
width: 100%;
|
||||||
|
margin-bottom: 10px;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-detail-package-tabs-inner {
|
||||||
|
display: inline-flex;
|
||||||
|
flex-wrap: nowrap;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 2px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-detail-package-tab {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
flex-shrink: 0;
|
||||||
|
max-width: 132px;
|
||||||
|
padding: 6px 12px;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: rgba(0, 0, 0, 0.04);
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-detail-package-tab--active {
|
||||||
|
background: rgba(166, 29, 36, 0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-detail-package-tab-text {
|
||||||
|
font-size: 12px;
|
||||||
|
line-height: 18px;
|
||||||
|
color: var(--color-text-secondary, #666);
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-detail-package-tab--active .store-detail-package-tab-text {
|
||||||
|
color: var(--color-heritage-red, #a61d24);
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-detail-package-panel {
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 10px;
|
||||||
|
border-radius: var(--radius-md, 8px);
|
||||||
|
background: var(--color-surface-container, #f7f7f7);
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-detail-package-thumb {
|
||||||
|
width: 72px;
|
||||||
|
height: 72px;
|
||||||
|
border-radius: 6px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
background: rgba(0, 0, 0, 0.04);
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-detail-package-panel-body {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-detail-package-body,
|
||||||
|
.store-detail-package-meta {
|
||||||
|
display: -webkit-box;
|
||||||
|
-webkit-line-clamp: 2;
|
||||||
|
-webkit-box-orient: vertical;
|
||||||
|
overflow: hidden;
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-detail-package-name {
|
.store-detail-package-name {
|
||||||
display: block;
|
display: block;
|
||||||
font-size: 16px;
|
font-size: 15px;
|
||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
color: var(--color-text-primary, #1a1a1a);
|
color: var(--color-text-primary, #1a1a1a);
|
||||||
margin-bottom: 6px;
|
margin-bottom: 4px;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-detail-package-body {
|
.store-detail-package-body {
|
||||||
display: block;
|
font-size: 13px;
|
||||||
font-size: 14px;
|
|
||||||
color: var(--color-text-secondary, #666);
|
color: var(--color-text-secondary, #666);
|
||||||
line-height: 1.5;
|
line-height: 1.45;
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-detail-package-meta {
|
.store-detail-package-meta {
|
||||||
display: block;
|
font-size: 12px;
|
||||||
font-size: 13px;
|
|
||||||
color: var(--color-text-tertiary, #999);
|
color: var(--color-text-tertiary, #999);
|
||||||
margin-top: 4px;
|
margin-top: 4px;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -144,63 +144,143 @@
|
|||||||
padding: 4px var(--space-page) 16px;
|
padding: 4px var(--space-page) 16px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* 左图右文,卡片等高 */
|
||||||
.store-card {
|
.store-card {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: row;
|
||||||
|
align-items: stretch;
|
||||||
|
gap: 12px;
|
||||||
|
padding: 12px;
|
||||||
|
box-sizing: border-box;
|
||||||
background: var(--color-card);
|
background: var(--color-card);
|
||||||
border-radius: var(--radius-lg);
|
border-radius: var(--radius-lg);
|
||||||
overflow: hidden;
|
|
||||||
box-shadow: var(--shadow-card);
|
box-shadow: var(--shadow-card);
|
||||||
margin-bottom: 16px;
|
margin-bottom: 12px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-card-cover {
|
.store-card-cover {
|
||||||
width: 100%;
|
flex-shrink: 0;
|
||||||
height: 160px;
|
width: 96px;
|
||||||
|
height: 96px;
|
||||||
|
border-radius: 8px;
|
||||||
background: var(--color-surface-container);
|
background: var(--color-surface-container);
|
||||||
display: block;
|
display: block;
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-card-cover--empty {
|
.store-card-cover--empty {
|
||||||
height: 160px;
|
|
||||||
background: var(--color-surface-container);
|
background: var(--color-surface-container);
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-card-body {
|
.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 {
|
.store-card-name {
|
||||||
display: block;
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
font-family: var(--font-headline);
|
font-family: var(--font-headline);
|
||||||
font-size: 16px;
|
font-size: 15px;
|
||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
color: var(--color-on-surface);
|
line-height: 22px;
|
||||||
margin-bottom: 6px;
|
color: #1a1a1a;
|
||||||
}
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
.store-card-meta {
|
white-space: nowrap;
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.store-card-distance {
|
.store-card-distance {
|
||||||
|
flex-shrink: 0;
|
||||||
|
max-width: 40%;
|
||||||
font-size: 12px;
|
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;
|
||||||
|
min-height: 20px;
|
||||||
|
align-items: flex-start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.store-card-status {
|
||||||
|
flex-shrink: 0;
|
||||||
|
padding: 0 6px;
|
||||||
|
margin-top: 1px;
|
||||||
|
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: 16px;
|
||||||
|
color: #999;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 第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 {
|
.store-card-cta {
|
||||||
padding: 6px 14px;
|
flex-shrink: 0;
|
||||||
border-radius: var(--radius-full);
|
display: flex;
|
||||||
background: rgba(166, 29, 36, 0.08);
|
align-items: center;
|
||||||
color: var(--color-heritage-red);
|
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-size: 12px;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
|
line-height: 26px;
|
||||||
|
color: #fff;
|
||||||
|
white-space: nowrap;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ export type ClientErrorCategory =
|
|||||||
| 'js_error'
|
| 'js_error'
|
||||||
| 'unhandled_rejection'
|
| 'unhandled_rejection'
|
||||||
| 'api_error'
|
| 'api_error'
|
||||||
|
| 'validation_error'
|
||||||
| 'network'
|
| 'network'
|
||||||
| 'render'
|
| 'render'
|
||||||
| 'bridge'
|
| 'bridge'
|
||||||
@@ -73,6 +74,7 @@ export function reportApiError(
|
|||||||
input: { message: string; status?: number; url?: string; category?: ClientErrorCategory },
|
input: { message: string; status?: number; url?: string; category?: ClientErrorCategory },
|
||||||
) {
|
) {
|
||||||
if (typeof window === 'undefined') return;
|
if (typeof window === 'undefined') return;
|
||||||
|
if (input.url?.includes('/common/client-errors')) return;
|
||||||
const token = opts.getToken?.() ?? localStorage.getItem('accessToken');
|
const token = opts.getToken?.() ?? localStorage.getItem('accessToken');
|
||||||
const headers: Record<string, string> = {
|
const headers: Record<string, string> = {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
@@ -85,7 +87,7 @@ export function reportApiError(
|
|||||||
headers,
|
headers,
|
||||||
body: {
|
body: {
|
||||||
level: 'warn',
|
level: 'warn',
|
||||||
category: input.category ?? 'api_error',
|
category: input.category ?? (input.status === 400 ? 'validation_error' : 'api_error'),
|
||||||
message: input.message.slice(0, 1000),
|
message: input.message.slice(0, 1000),
|
||||||
pagePath: window.location.pathname,
|
pagePath: window.location.pathname,
|
||||||
clientApp: opts.clientApp,
|
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,
|
requestAmount: 200,
|
||||||
todayApplied: 0,
|
todayApplied: 0,
|
||||||
dailyLimit: 5000,
|
dailyLimit: 5000,
|
||||||
hasPendingRequest: false,
|
|
||||||
hasBankAccount: true,
|
hasBankAccount: true,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -261,8 +260,7 @@ describe('validateStoreWithdraw', () => {
|
|||||||
).toBe(false);
|
).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('rejects pending request / missing bank / over available', () => {
|
it('rejects missing bank / over available', () => {
|
||||||
expect(validateStoreWithdraw({ ...base, hasPendingRequest: true }).ok).toBe(false);
|
|
||||||
expect(validateStoreWithdraw({ ...base, hasBankAccount: false }).ok).toBe(false);
|
expect(validateStoreWithdraw({ ...base, hasBankAccount: false }).ok).toBe(false);
|
||||||
expect(validateStoreWithdraw({ ...base, requestAmount: 1001 }).ok).toBe(false);
|
expect(validateStoreWithdraw({ ...base, requestAmount: 1001 }).ok).toBe(false);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -105,20 +105,16 @@ export type ValidateStoreWithdrawInput = {
|
|||||||
requestAmount: number;
|
requestAmount: number;
|
||||||
todayApplied: number;
|
todayApplied: number;
|
||||||
dailyLimit: number;
|
dailyLimit: number;
|
||||||
hasPendingRequest: boolean;
|
|
||||||
hasBankAccount: boolean;
|
hasBankAccount: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
/** 门店未出账提现护栏(FIN-002 单日上限 + 幂等/账户) */
|
/** 门店未出账提现护栏(FIN-002 单日上限 + 账户) */
|
||||||
export function validateStoreWithdraw(
|
export function validateStoreWithdraw(
|
||||||
input: ValidateStoreWithdrawInput,
|
input: ValidateStoreWithdrawInput,
|
||||||
): { ok: boolean; message?: string } {
|
): { ok: boolean; message?: string } {
|
||||||
if (!input.hasBankAccount) {
|
if (!input.hasBankAccount) {
|
||||||
return { ok: false, message: '请先完善入驻收款账户后再提现' };
|
return { ok: false, message: '请先完善入驻收款账户后再提现' };
|
||||||
}
|
}
|
||||||
if (input.hasPendingRequest) {
|
|
||||||
return { ok: false, message: '已有待审核提现申请,请等待处理完成' };
|
|
||||||
}
|
|
||||||
if (!(input.requestAmount > 0)) {
|
if (!(input.requestAmount > 0)) {
|
||||||
return { ok: false, message: '提现金额必须大于 0' };
|
return { ok: false, message: '提现金额必须大于 0' };
|
||||||
}
|
}
|
||||||
@@ -353,3 +349,5 @@ export function orderTabToStatuses(tab: string): string[] | undefined {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export * from './city-partner';
|
export * from './city-partner';
|
||||||
|
export * from './dev-plan';
|
||||||
|
export * from './support-ticket';
|
||||||
|
|||||||
@@ -0,0 +1,57 @@
|
|||||||
|
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('allows PASSED -> PUBLISHED', () => {
|
||||||
|
expect(
|
||||||
|
validateSupportTicketStatusTransition('PASSED', 'PUBLISHED', {
|
||||||
|
linkedTaskCount: 1,
|
||||||
|
isSuperAdmin: true,
|
||||||
|
}).ok,
|
||||||
|
).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
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,47 @@
|
|||||||
|
export type SupportTicketStatus =
|
||||||
|
| 'PENDING_REVIEW'
|
||||||
|
| 'REJECTED'
|
||||||
|
| 'DEVELOPING'
|
||||||
|
| 'TESTING'
|
||||||
|
| 'PASSED'
|
||||||
|
| 'PUBLISHED';
|
||||||
|
|
||||||
|
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: ['PUBLISHED'],
|
||||||
|
PUBLISHED: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 技术支持工单批量/人工改状态校验(禁止回退) */
|
||||||
|
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: 'wecom_bots', label: '企微机器人', group: '业务' },
|
||||||
{ key: 'llm_configs', label: '语言模型配置', group: '业务' },
|
{ key: 'llm_configs', label: '语言模型配置', group: '业务' },
|
||||||
{ key: 'knowledge_bases', label: '知识库', group: '业务' },
|
{ key: 'knowledge_bases', label: '知识库', group: '业务' },
|
||||||
|
{ key: 'dev_plan', label: '开发计划', group: '业务' },
|
||||||
{ key: 'resources', label: 'OSS 资源库', group: '业务' },
|
{ key: 'resources', label: 'OSS 资源库', group: '业务' },
|
||||||
{ key: 'logs', label: '日志', group: '业务' },
|
{ key: 'logs', label: '日志', group: '业务' },
|
||||||
{ key: 'users_delete', label: '删除用户', group: '危险操作' },
|
{ key: 'users_delete', label: '删除用户', group: '危险操作' },
|
||||||
@@ -114,6 +115,7 @@ export const HQ_ROLE_DEFAULT_PERMISSIONS: Record<string, HqPermissionKey[]> = {
|
|||||||
'wecom_bots',
|
'wecom_bots',
|
||||||
'llm_configs',
|
'llm_configs',
|
||||||
'knowledge_bases',
|
'knowledge_bases',
|
||||||
|
'dev_plan',
|
||||||
'resources',
|
'resources',
|
||||||
'logs',
|
'logs',
|
||||||
'system_settings_wechat_mini',
|
'system_settings_wechat_mini',
|
||||||
|
|||||||
@@ -25,6 +25,8 @@ export * from './city-warehouse';
|
|||||||
export * from './fulfillment-provider';
|
export * from './fulfillment-provider';
|
||||||
export * from './system-config';
|
export * from './system-config';
|
||||||
export * from './wecom-bot';
|
export * from './wecom-bot';
|
||||||
|
export * from './wecom-message-push';
|
||||||
export * from './llm-config';
|
export * from './llm-config';
|
||||||
export * from './knowledge-base';
|
export * from './knowledge-base';
|
||||||
export * from './legal';
|
export * from './legal';
|
||||||
|
export * from './dev-plan';
|
||||||
|
|||||||
@@ -50,6 +50,20 @@ export type CreateKnowledgeDocumentRequest = {
|
|||||||
sizeBytes?: number | null;
|
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 = {
|
export type KnowledgeBaseOptionDto = {
|
||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
|
|||||||
@@ -85,6 +85,50 @@ export function promoConversion(scan: number, orders: number): string {
|
|||||||
return `${Math.round((orders / scan) * 1000) / 10}%`;
|
return `${Math.round((orders / scan) * 1000) / 10}%`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type PromoMetricEventType = 'SCAN' | 'ATTRIBUTION' | 'REGISTER' | 'ORDER';
|
||||||
|
|
||||||
|
export const PROMO_METRIC_EVENT_LABELS: Record<PromoMetricEventType, string> = {
|
||||||
|
SCAN: '扫码进入',
|
||||||
|
ATTRIBUTION: '归因用户',
|
||||||
|
REGISTER: '扫码注册',
|
||||||
|
ORDER: '订单',
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PromoMetricEventItem = {
|
||||||
|
id: string;
|
||||||
|
eventType: PromoMetricEventType;
|
||||||
|
userId: string | null;
|
||||||
|
orderId: string | null;
|
||||||
|
sessionId: string | null;
|
||||||
|
clientIp: string | null;
|
||||||
|
ipProvince: string | null;
|
||||||
|
ipCity: string | null;
|
||||||
|
createdAt: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PromoMetricTimelineBucket = {
|
||||||
|
key: string;
|
||||||
|
scan: number;
|
||||||
|
attribution: number;
|
||||||
|
register: number;
|
||||||
|
order: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PromoMetricTimelinePeak = {
|
||||||
|
scan: { key: string; count: number } | null;
|
||||||
|
attribution: { key: string; count: number } | null;
|
||||||
|
register: { key: string; count: number } | null;
|
||||||
|
order: { key: string; count: number } | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PromoMetricTimelineDto = {
|
||||||
|
granularity: 'day' | 'hour';
|
||||||
|
dateFrom: string;
|
||||||
|
dateTo: string;
|
||||||
|
buckets: PromoMetricTimelineBucket[];
|
||||||
|
peak: PromoMetricTimelinePeak;
|
||||||
|
};
|
||||||
|
|
||||||
export function buildPromoLandingUrl(baseUrl: string, code: string, qrcodeId: string): string {
|
export function buildPromoLandingUrl(baseUrl: string, code: string, qrcodeId: string): string {
|
||||||
const base = baseUrl.replace(/\/$/, '');
|
const base = baseUrl.replace(/\/$/, '');
|
||||||
return `${base}/?promo=${encodeURIComponent(code)}&pid=${encodeURIComponent(qrcodeId)}`;
|
return `${base}/?promo=${encodeURIComponent(code)}&pid=${encodeURIComponent(qrcodeId)}`;
|
||||||
|
|||||||
@@ -63,7 +63,6 @@ export interface StoreWithdrawSummaryDto {
|
|||||||
remainingDailyLimit: number;
|
remainingDailyLimit: number;
|
||||||
isPrimary: boolean;
|
isPrimary: boolean;
|
||||||
hasBankAccount: boolean;
|
hasBankAccount: boolean;
|
||||||
hasPendingRequest: boolean;
|
|
||||||
bankAccount?: StoreWithdrawBankAccountDto | null;
|
bankAccount?: StoreWithdrawBankAccountDto | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -184,6 +183,9 @@ export const STORE_SETTLEMENT_DEFAULT_RATE = 0.6;
|
|||||||
/** 酒厂账单结算比例(酒单实付 × 比例),暂定 30% */
|
/** 酒厂账单结算比例(酒单实付 × 比例),暂定 30% */
|
||||||
export const WINERY_SETTLEMENT_RATE = 0.3;
|
export const WINERY_SETTLEMENT_RATE = 0.3;
|
||||||
|
|
||||||
|
/** 酒厂账单出账滞后自然日(T+3:订单完成日 + 3 天后纳入账单) */
|
||||||
|
export const WINERY_SETTLEMENT_LAG_DAYS = 3;
|
||||||
|
|
||||||
export type { LogisticsSettlementMethod } from './enums';
|
export type { LogisticsSettlementMethod } from './enums';
|
||||||
export { LOGISTICS_SETTLEMENT_METHOD_LABELS } from './enums';
|
export { LOGISTICS_SETTLEMENT_METHOD_LABELS } from './enums';
|
||||||
import type { LogisticsSettlementMethod } from './enums';
|
import type { LogisticsSettlementMethod } from './enums';
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ export interface StorePackageItemDto {
|
|||||||
dishes: string;
|
dishes: string;
|
||||||
usableTime?: string | null;
|
usableTime?: string | null;
|
||||||
otherNotes?: string | null;
|
otherNotes?: string | null;
|
||||||
|
imageUrl?: string | null;
|
||||||
sortOrder: number;
|
sortOrder: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -15,7 +15,8 @@ export type SupportTicketStatusDto =
|
|||||||
| 'REJECTED'
|
| 'REJECTED'
|
||||||
| 'DEVELOPING'
|
| 'DEVELOPING'
|
||||||
| 'TESTING'
|
| 'TESTING'
|
||||||
| 'PASSED';
|
| 'PASSED'
|
||||||
|
| 'PUBLISHED';
|
||||||
|
|
||||||
export const SUPPORT_TICKET_STATUSES = [
|
export const SUPPORT_TICKET_STATUSES = [
|
||||||
'PENDING_REVIEW',
|
'PENDING_REVIEW',
|
||||||
@@ -23,6 +24,7 @@ export const SUPPORT_TICKET_STATUSES = [
|
|||||||
'DEVELOPING',
|
'DEVELOPING',
|
||||||
'TESTING',
|
'TESTING',
|
||||||
'PASSED',
|
'PASSED',
|
||||||
|
'PUBLISHED',
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
export const SUPPORT_TICKET_STATUS_LABELS: Record<SupportTicketStatusDto, string> = {
|
export const SUPPORT_TICKET_STATUS_LABELS: Record<SupportTicketStatusDto, string> = {
|
||||||
@@ -31,6 +33,19 @@ export const SUPPORT_TICKET_STATUS_LABELS: Record<SupportTicketStatusDto, string
|
|||||||
DEVELOPING: '开发',
|
DEVELOPING: '开发',
|
||||||
TESTING: '测试',
|
TESTING: '测试',
|
||||||
PASSED: '通过',
|
PASSED: '通过',
|
||||||
|
PUBLISHED: '已发布',
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 技术支持工单优先级 */
|
||||||
|
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 {
|
export interface SupportTicketDto {
|
||||||
@@ -38,6 +53,7 @@ export interface SupportTicketDto {
|
|||||||
ticketNo: string;
|
ticketNo: string;
|
||||||
ticketType: SupportTicketTypeDto;
|
ticketType: SupportTicketTypeDto;
|
||||||
status: SupportTicketStatusDto;
|
status: SupportTicketStatusDto;
|
||||||
|
priority: SupportTicketPriorityDto;
|
||||||
title: string;
|
title: string;
|
||||||
content?: string | null;
|
content?: string | null;
|
||||||
rejectReason?: string | null;
|
rejectReason?: string | null;
|
||||||
@@ -47,9 +63,12 @@ export interface SupportTicketDto {
|
|||||||
reviewerName?: string | null;
|
reviewerName?: string | null;
|
||||||
reviewedAt?: string | null;
|
reviewedAt?: string | null;
|
||||||
remark?: string | null;
|
remark?: string | null;
|
||||||
|
attachmentUrls?: string[] | null;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
completedAt?: string | null;
|
completedAt?: string | null;
|
||||||
|
releasedVersionNo?: string | null;
|
||||||
|
publishedAt?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CreateSupportTicketRequest {
|
export interface CreateSupportTicketRequest {
|
||||||
@@ -57,8 +76,74 @@ export interface CreateSupportTicketRequest {
|
|||||||
title: string;
|
title: string;
|
||||||
content?: string;
|
content?: string;
|
||||||
remark?: 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 {
|
export interface RejectSupportTicketRequest {
|
||||||
rejectReason: string;
|
rejectReason: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface CreateDevPlanTaskFromTicketInput {
|
||||||
|
content: string;
|
||||||
|
type: 'BUG' | 'REQUIREMENT' | 'OPTIMIZATION';
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ReviewSupportTicketRequest {
|
||||||
|
decision: 'APPROVE' | 'REJECT';
|
||||||
|
rejectReason?: string;
|
||||||
|
note?: string;
|
||||||
|
tasks?: CreateDevPlanTaskFromTicketInput[];
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|||||||
@@ -27,6 +27,30 @@ export const TICKET_TYPE_LABELS: Record<TicketTypeDto, string> = {
|
|||||||
PACKAGE_DISPUTE: '套餐异议',
|
PACKAGE_DISPUTE: '套餐异议',
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** 售后工单状态(common_ticket.status) */
|
||||||
|
export type TicketStatusDto =
|
||||||
|
| 'PENDING'
|
||||||
|
| 'OPEN'
|
||||||
|
| 'COLLABORATING'
|
||||||
|
| 'RESOLVED'
|
||||||
|
| 'REJECTED'
|
||||||
|
| 'COMPLETED'
|
||||||
|
| 'CLOSED';
|
||||||
|
|
||||||
|
export const TICKET_STATUS_LABELS: Record<TicketStatusDto, string> = {
|
||||||
|
PENDING: '待处理',
|
||||||
|
OPEN: '处理中',
|
||||||
|
COLLABORATING: '协同中',
|
||||||
|
RESOLVED: '已解决',
|
||||||
|
REJECTED: '已驳回',
|
||||||
|
COMPLETED: '已完成',
|
||||||
|
CLOSED: '已关闭',
|
||||||
|
};
|
||||||
|
|
||||||
|
export function ticketStatusLabel(status: string): string {
|
||||||
|
return TICKET_STATUS_LABELS[status as TicketStatusDto] ?? status;
|
||||||
|
}
|
||||||
|
|
||||||
export interface TicketDto {
|
export interface TicketDto {
|
||||||
id: string;
|
id: string;
|
||||||
ticketNo: string;
|
ticketNo: string;
|
||||||
|
|||||||
@@ -70,6 +70,30 @@ export interface DeliveryDto {
|
|||||||
deliveredAt?: string;
|
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 箱不自动推小飞侠 */
|
/** 大单拦截原因:≥10 箱不自动推小飞侠 */
|
||||||
export const FULFILLMENT_HOLD_REASON_LABELS: Record<string, string> = {
|
export const FULFILLMENT_HOLD_REASON_LABELS: Record<string, string> = {
|
||||||
LARGE_ORDER_GE_10_BOXES: '大单≥10箱,待总部确认推单/自配送',
|
LARGE_ORDER_GE_10_BOXES: '大单≥10箱,待总部确认推单/自配送',
|
||||||
|
|||||||
@@ -48,6 +48,8 @@ export type ClientRuntimeConfig = {
|
|||||||
banners: string[];
|
banners: string[];
|
||||||
footerUrl: string | null;
|
footerUrl: string | null;
|
||||||
};
|
};
|
||||||
|
/** 小程序最低兼容版本(semver,如 3.4.13);客户端低于此值时提示更新 */
|
||||||
|
minClientVersion?: string | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
/** 是否展示微信授权入口 */
|
/** 是否展示微信授权入口 */
|
||||||
|
|||||||
@@ -1,63 +1,262 @@
|
|||||||
/** 企业微信智能机器人能力权限 */
|
/** 企业微信智能机器人 · 模块化能力权限(v3.4.11 重构) */
|
||||||
export const WECOM_BOT_PERMISSIONS = [
|
export const WECOM_BOT_PERMISSIONS = [
|
||||||
|
'order.read',
|
||||||
|
'delivery.read',
|
||||||
|
'store.read',
|
||||||
|
'redeem.read',
|
||||||
|
'ticket.read',
|
||||||
'ticket.create',
|
'ticket.create',
|
||||||
'user.view_sms',
|
'user.read',
|
||||||
'delivery.view',
|
'user.read_sms',
|
||||||
|
'finance.store_bill.read',
|
||||||
|
'finance.partner_bill.read',
|
||||||
|
'finance.winery_bill.read',
|
||||||
|
'finance.logistics_bill.read',
|
||||||
|
'finance.payout.read',
|
||||||
|
'finance.withdrawal.read',
|
||||||
|
'support_ticket.read',
|
||||||
'support_ticket.create',
|
'support_ticket.create',
|
||||||
'support_ticket.progress',
|
'support_ticket.review',
|
||||||
'handbook.query',
|
'support_ticket.approve',
|
||||||
'server_log.view',
|
'support_ticket.reject',
|
||||||
'api.query',
|
'dev_plan.task.read',
|
||||||
|
'dev_plan.task.create',
|
||||||
|
'dev_plan.task.update_status',
|
||||||
|
'dev_plan.version.read',
|
||||||
|
'dev_plan.version.create',
|
||||||
|
'dev_plan.version.update_status',
|
||||||
|
'dev_plan.version.link_tasks',
|
||||||
|
'server_log.read',
|
||||||
|
'handbook.read',
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
export type WecomBotPermission = (typeof WECOM_BOT_PERMISSIONS)[number];
|
export type WecomBotPermission = (typeof WECOM_BOT_PERMISSIONS)[number];
|
||||||
|
|
||||||
export const WECOM_BOT_PERMISSION_LABELS: Record<WecomBotPermission, string> = {
|
export const WECOM_BOT_PERMISSION_LABELS: Record<WecomBotPermission, string> = {
|
||||||
|
'order.read': '查询订单',
|
||||||
|
'delivery.read': '查询配送/物流',
|
||||||
|
'store.read': '查询门店',
|
||||||
|
'redeem.read': '查询核销记录',
|
||||||
|
'ticket.read': '查询售后工单',
|
||||||
'ticket.create': '创建售后工单',
|
'ticket.create': '创建售后工单',
|
||||||
'user.view_sms': '查用户(短信验证)',
|
'user.read': '查询用户(脱敏)',
|
||||||
'delivery.view': '查快递信息',
|
'user.read_sms': '查用户(短信验证)',
|
||||||
|
'finance.store_bill.read': '查询门店账单',
|
||||||
|
'finance.partner_bill.read': '查询合伙人账单',
|
||||||
|
'finance.winery_bill.read': '查询酒厂账单',
|
||||||
|
'finance.logistics_bill.read': '查询物流账单',
|
||||||
|
'finance.payout.read': '查询门店打款',
|
||||||
|
'finance.withdrawal.read': '查询门店提现',
|
||||||
|
'support_ticket.read': '查询技术支持工单',
|
||||||
'support_ticket.create': '创建技术支持工单',
|
'support_ticket.create': '创建技术支持工单',
|
||||||
'support_ticket.progress': '查看开发进度',
|
'support_ticket.review': '审批技术支持工单(通过/驳回)',
|
||||||
'handbook.query': '查询使用手册',
|
'support_ticket.approve': '通过技术支持工单',
|
||||||
'server_log.view': '查看服务器日志',
|
'support_ticket.reject': '驳回技术支持工单',
|
||||||
'api.query': '查询业务 API(只读)',
|
'dev_plan.task.read': '查询开发任务',
|
||||||
|
'dev_plan.task.create': '新建开发任务',
|
||||||
|
'dev_plan.task.update_status': '修改任务状态',
|
||||||
|
'dev_plan.version.read': '查询开发版本',
|
||||||
|
'dev_plan.version.create': '新建开发版本',
|
||||||
|
'dev_plan.version.update_status': '修改版本状态',
|
||||||
|
'dev_plan.version.link_tasks': '关联任务到版本',
|
||||||
|
'server_log.read': '查看服务器日志',
|
||||||
|
'handbook.read': '查询使用手册',
|
||||||
};
|
};
|
||||||
|
|
||||||
/** 预置机器人角色(创建时可选;权限可按角色带出默认值后自定义) */
|
/** Admin UI 权限分组 */
|
||||||
|
export const WECOM_BOT_PERMISSION_GROUPS: Array<{
|
||||||
|
key: string;
|
||||||
|
label: string;
|
||||||
|
permissions: WecomBotPermission[];
|
||||||
|
}> = [
|
||||||
|
{
|
||||||
|
key: 'order',
|
||||||
|
label: '订单与配送',
|
||||||
|
permissions: ['order.read', 'delivery.read'],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'store_redeem',
|
||||||
|
label: '门店与核销',
|
||||||
|
permissions: ['store.read', 'redeem.read'],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'ticket',
|
||||||
|
label: '售后工单',
|
||||||
|
permissions: ['ticket.read', 'ticket.create'],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'user',
|
||||||
|
label: '用户',
|
||||||
|
permissions: ['user.read', 'user.read_sms'],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'finance',
|
||||||
|
label: '财务',
|
||||||
|
permissions: [
|
||||||
|
'finance.store_bill.read',
|
||||||
|
'finance.partner_bill.read',
|
||||||
|
'finance.winery_bill.read',
|
||||||
|
'finance.logistics_bill.read',
|
||||||
|
'finance.payout.read',
|
||||||
|
'finance.withdrawal.read',
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'support',
|
||||||
|
label: '技术支持',
|
||||||
|
permissions: ['support_ticket.read', 'support_ticket.create', 'support_ticket.review', 'support_ticket.approve', 'support_ticket.reject'],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'dev_plan',
|
||||||
|
label: '开发计划',
|
||||||
|
permissions: ['dev_plan.task.read', 'dev_plan.task.create', 'dev_plan.task.update_status', 'dev_plan.version.read', 'dev_plan.version.create', 'dev_plan.version.update_status', 'dev_plan.version.link_tasks'],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'ops',
|
||||||
|
label: '运维与手册',
|
||||||
|
permissions: ['server_log.read', 'handbook.read'],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
/** 预置机器人角色 */
|
||||||
export const WECOM_BOT_ROLES = [
|
export const WECOM_BOT_ROLES = [
|
||||||
'CUSTOMER_SERVICE',
|
'CUSTOMER_SERVICE',
|
||||||
|
'FINANCE',
|
||||||
|
'OPERATIONS',
|
||||||
'TECH_SUPPORT',
|
'TECH_SUPPORT',
|
||||||
'TEAM_ASSISTANT',
|
|
||||||
'CUSTOM',
|
'CUSTOM',
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
export type WecomBotRole = (typeof WECOM_BOT_ROLES)[number];
|
export type WecomBotRole = (typeof WECOM_BOT_ROLES)[number];
|
||||||
|
|
||||||
|
/** 历史角色名 → 现行角色 */
|
||||||
|
export function normalizeWecomBotRole(raw: string): WecomBotRole {
|
||||||
|
if (raw === 'TEAM_ASSISTANT') return 'OPERATIONS';
|
||||||
|
if ((WECOM_BOT_ROLES as readonly string[]).includes(raw)) return raw as WecomBotRole;
|
||||||
|
return 'CUSTOM';
|
||||||
|
}
|
||||||
|
|
||||||
export const WECOM_BOT_ROLE_LABELS: Record<WecomBotRole, string> = {
|
export const WECOM_BOT_ROLE_LABELS: Record<WecomBotRole, string> = {
|
||||||
CUSTOMER_SERVICE: '客服机器人',
|
CUSTOMER_SERVICE: '客服助手',
|
||||||
TECH_SUPPORT: '技术支持机器人',
|
FINANCE: '财务助手',
|
||||||
TEAM_ASSISTANT: '团队助手',
|
OPERATIONS: '运营助手',
|
||||||
|
TECH_SUPPORT: '技术支持',
|
||||||
CUSTOM: '自定义',
|
CUSTOM: '自定义',
|
||||||
};
|
};
|
||||||
|
|
||||||
export const WECOM_BOT_ROLE_DEFAULT_PERMISSIONS: Record<WecomBotRole, WecomBotPermission[]> = {
|
export const WECOM_BOT_ROLE_DEFAULT_PERMISSIONS: Record<WecomBotRole, WecomBotPermission[]> = {
|
||||||
CUSTOMER_SERVICE: ['ticket.create', 'user.view_sms', 'delivery.view'],
|
CUSTOMER_SERVICE: [
|
||||||
TECH_SUPPORT: ['support_ticket.create', 'support_ticket.progress', 'server_log.view', 'api.query'],
|
'order.read',
|
||||||
TEAM_ASSISTANT: ['handbook.query'],
|
'delivery.read',
|
||||||
|
'store.read',
|
||||||
|
'redeem.read',
|
||||||
|
'ticket.read',
|
||||||
|
'ticket.create',
|
||||||
|
'user.read_sms',
|
||||||
|
],
|
||||||
|
FINANCE: [
|
||||||
|
'finance.store_bill.read',
|
||||||
|
'finance.partner_bill.read',
|
||||||
|
'finance.winery_bill.read',
|
||||||
|
'finance.logistics_bill.read',
|
||||||
|
'finance.payout.read',
|
||||||
|
'finance.withdrawal.read',
|
||||||
|
'order.read',
|
||||||
|
],
|
||||||
|
OPERATIONS: [
|
||||||
|
'order.read',
|
||||||
|
'store.read',
|
||||||
|
'user.read',
|
||||||
|
'redeem.read',
|
||||||
|
'delivery.read',
|
||||||
|
'handbook.read',
|
||||||
|
],
|
||||||
|
TECH_SUPPORT: [
|
||||||
|
'support_ticket.read',
|
||||||
|
'support_ticket.create',
|
||||||
|
'support_ticket.review',
|
||||||
|
'dev_plan.task.read',
|
||||||
|
'dev_plan.task.create',
|
||||||
|
'dev_plan.task.update_status',
|
||||||
|
'dev_plan.version.read',
|
||||||
|
'dev_plan.version.create',
|
||||||
|
'dev_plan.version.update_status',
|
||||||
|
'dev_plan.version.link_tasks',
|
||||||
|
'server_log.read',
|
||||||
|
],
|
||||||
CUSTOM: [],
|
CUSTOM: [],
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** 旧版权限 → 新版权限(读取 DB 时迁移) */
|
||||||
|
const LEGACY_PERMISSION_MAP: Record<string, WecomBotPermission[]> = {
|
||||||
|
'ticket.create': ['ticket.create'],
|
||||||
|
'user.view_sms': ['user.read_sms'],
|
||||||
|
'delivery.view': ['delivery.read'],
|
||||||
|
'support_ticket.create': ['support_ticket.create'],
|
||||||
|
'support_ticket.progress': ['support_ticket.read', 'dev_plan.task.read'],
|
||||||
|
'handbook.query': ['handbook.read'],
|
||||||
|
'server_log.view': ['server_log.read'],
|
||||||
|
'api.query': ['order.read'],
|
||||||
|
'api.read.all': [
|
||||||
|
'order.read',
|
||||||
|
'delivery.read',
|
||||||
|
'store.read',
|
||||||
|
'redeem.read',
|
||||||
|
'support_ticket.read',
|
||||||
|
'dev_plan.task.read',
|
||||||
|
'dev_plan.version.read',
|
||||||
|
'user.read',
|
||||||
|
],
|
||||||
|
'db.read': ['support_ticket.read', 'order.read'],
|
||||||
|
};
|
||||||
|
|
||||||
|
export function migrateWecomBotPermissions(raw: string[]): WecomBotPermission[] {
|
||||||
|
const set = new Set<WecomBotPermission>();
|
||||||
|
const valid = new Set<string>(WECOM_BOT_PERMISSIONS);
|
||||||
|
for (const p of raw) {
|
||||||
|
if (valid.has(p)) {
|
||||||
|
set.add(p as WecomBotPermission);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const mapped = LEGACY_PERMISSION_MAP[p];
|
||||||
|
if (mapped) mapped.forEach((m) => set.add(m));
|
||||||
|
}
|
||||||
|
return [...set];
|
||||||
|
}
|
||||||
|
|
||||||
export function parseWecomBotPermissions(
|
export function parseWecomBotPermissions(
|
||||||
raw?: string | string[] | null,
|
raw?: string | string[] | null,
|
||||||
): WecomBotPermission[] {
|
): WecomBotPermission[] {
|
||||||
const set = new Set<string>(WECOM_BOT_PERMISSIONS);
|
const valid = new Set<string>(WECOM_BOT_PERMISSIONS);
|
||||||
const list = Array.isArray(raw)
|
let list: string[];
|
||||||
? raw
|
|
||||||
: String(raw ?? '')
|
if (Array.isArray(raw)) {
|
||||||
|
list = raw.map(String);
|
||||||
|
} else {
|
||||||
|
const text = String(raw ?? '').trim();
|
||||||
|
if (!text) {
|
||||||
|
list = [];
|
||||||
|
} else if (text.startsWith('[')) {
|
||||||
|
try {
|
||||||
|
const parsed: unknown = JSON.parse(text);
|
||||||
|
list = Array.isArray(parsed) ? parsed.map(String) : [];
|
||||||
|
} catch {
|
||||||
|
list = text
|
||||||
.split(/[,,\s]+/)
|
.split(/[,,\s]+/)
|
||||||
.map((s) => s.trim())
|
.map((s) => s.trim())
|
||||||
.filter(Boolean);
|
.filter(Boolean);
|
||||||
return [...new Set(list.filter((s): s is WecomBotPermission => set.has(s)))];
|
}
|
||||||
|
} else {
|
||||||
|
list = text
|
||||||
|
.split(/[,,\s]+/)
|
||||||
|
.map((s) => s.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const migrated = migrateWecomBotPermissions(list);
|
||||||
|
if (migrated.length) return migrated;
|
||||||
|
return [...new Set(list.filter((s): s is WecomBotPermission => valid.has(s)))];
|
||||||
}
|
}
|
||||||
|
|
||||||
export function resolveWecomBotPermissions(
|
export function resolveWecomBotPermissions(
|
||||||
@@ -69,17 +268,32 @@ export function resolveWecomBotPermissions(
|
|||||||
return [...WECOM_BOT_ROLE_DEFAULT_PERMISSIONS[role]];
|
return [...WECOM_BOT_ROLE_DEFAULT_PERMISSIONS[role]];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function parseWecomUserIdList(raw?: string | string[] | null): string[] {
|
||||||
|
if (Array.isArray(raw)) return [...new Set(raw.map(String).filter(Boolean))];
|
||||||
|
const text = String(raw ?? '').trim();
|
||||||
|
if (!text) return [];
|
||||||
|
if (text.startsWith('[')) {
|
||||||
|
try {
|
||||||
|
const parsed: unknown = JSON.parse(text);
|
||||||
|
return Array.isArray(parsed) ? [...new Set(parsed.map(String).filter(Boolean))] : [];
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return [...new Set(text.split(/[,,\s]+/).map((s) => s.trim()).filter(Boolean))];
|
||||||
|
}
|
||||||
|
|
||||||
export type WecomBotDto = {
|
export type WecomBotDto = {
|
||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
role: WecomBotRole;
|
role: WecomBotRole;
|
||||||
botId: string;
|
botId: string;
|
||||||
/** 列表/详情不返回明文;仅表示是否已配置 */
|
|
||||||
secretConfigured: boolean;
|
secretConfigured: boolean;
|
||||||
avatarUrl: string | null;
|
avatarUrl: string | null;
|
||||||
welcome: string | null;
|
welcome: string | null;
|
||||||
permissions: WecomBotPermission[];
|
permissions: WecomBotPermission[];
|
||||||
/** 未匹配指令时是否调用绑定的语言模型 */
|
/** 可执行 support_ticket.review 的企微 userid 白名单 */
|
||||||
|
reviewSuperAdminWecomUserIds: string[];
|
||||||
aiEnabled: boolean;
|
aiEnabled: boolean;
|
||||||
llmConfigId: string | null;
|
llmConfigId: string | null;
|
||||||
llmConfigName: string | null;
|
llmConfigName: string | null;
|
||||||
@@ -99,6 +313,7 @@ export type CreateWecomBotRequest = {
|
|||||||
avatarUrl?: string | null;
|
avatarUrl?: string | null;
|
||||||
welcome?: string | null;
|
welcome?: string | null;
|
||||||
permissions?: WecomBotPermission[];
|
permissions?: WecomBotPermission[];
|
||||||
|
reviewSuperAdminWecomUserIds?: string[];
|
||||||
aiEnabled?: boolean;
|
aiEnabled?: boolean;
|
||||||
llmConfigId?: string | null;
|
llmConfigId?: string | null;
|
||||||
knowledgeBaseId?: string | null;
|
knowledgeBaseId?: string | null;
|
||||||
@@ -110,14 +325,64 @@ export type UpdateWecomBotRequest = {
|
|||||||
name?: string;
|
name?: string;
|
||||||
role?: WecomBotRole;
|
role?: WecomBotRole;
|
||||||
botId?: string;
|
botId?: string;
|
||||||
/** 空或不传表示不修改 */
|
|
||||||
secret?: string;
|
secret?: string;
|
||||||
avatarUrl?: string | null;
|
avatarUrl?: string | null;
|
||||||
welcome?: string | null;
|
welcome?: string | null;
|
||||||
permissions?: WecomBotPermission[];
|
permissions?: WecomBotPermission[];
|
||||||
|
reviewSuperAdminWecomUserIds?: string[];
|
||||||
aiEnabled?: boolean;
|
aiEnabled?: boolean;
|
||||||
llmConfigId?: string | null;
|
llmConfigId?: string | null;
|
||||||
knowledgeBaseId?: string | null;
|
knowledgeBaseId?: string | null;
|
||||||
enabled?: boolean;
|
enabled?: boolean;
|
||||||
sortOrder?: number;
|
sortOrder?: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** 长连接运行时状态(Admin GET /admin/wecom-bots/runtime) */
|
||||||
|
export type WecomAibotRuntimeDto = {
|
||||||
|
masterEnabled: boolean;
|
||||||
|
bots: Array<{
|
||||||
|
id: string;
|
||||||
|
role: string;
|
||||||
|
key: string;
|
||||||
|
name: string;
|
||||||
|
enabled: boolean;
|
||||||
|
configured: boolean;
|
||||||
|
connected: boolean;
|
||||||
|
botIdMasked: string | null;
|
||||||
|
avatarUrl: string | null;
|
||||||
|
permissions: WecomBotPermission[];
|
||||||
|
lastError: string | null;
|
||||||
|
}>;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Admin 表单 permissions 与 UI 分组/catalog 对齐校验 */
|
||||||
|
export function assertWecomBotPermissionCatalogConsistent(): void {
|
||||||
|
const fromGroups = WECOM_BOT_PERMISSION_GROUPS.flatMap((g) => g.permissions);
|
||||||
|
const catalog = new Set<string>(WECOM_BOT_PERMISSIONS);
|
||||||
|
const groupSet = new Set(fromGroups);
|
||||||
|
for (const p of WECOM_BOT_PERMISSIONS) {
|
||||||
|
if (!groupSet.has(p)) throw new Error(`permission missing in UI groups: ${p}`);
|
||||||
|
if (!WECOM_BOT_PERMISSION_LABELS[p]) throw new Error(`permission missing label: ${p}`);
|
||||||
|
}
|
||||||
|
for (const p of fromGroups) {
|
||||||
|
if (!catalog.has(p)) throw new Error(`unknown permission in UI groups: ${p}`);
|
||||||
|
}
|
||||||
|
if (fromGroups.length !== groupSet.size) {
|
||||||
|
throw new Error('duplicate permission in UI groups');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export type WecomBotLogDto = {
|
||||||
|
id: string;
|
||||||
|
botId: string | null;
|
||||||
|
botName: string | null;
|
||||||
|
botKey: string | null;
|
||||||
|
wecomUserId: string;
|
||||||
|
action: string;
|
||||||
|
permission: string | null;
|
||||||
|
inputSummary: string | null;
|
||||||
|
success: boolean;
|
||||||
|
errorMessage: string | null;
|
||||||
|
latencyMs: number | null;
|
||||||
|
createdAt: string;
|
||||||
|
};
|
||||||
|
|||||||
@@ -0,0 +1,138 @@
|
|||||||
|
/** 企微群机器人 Webhook · 推送条件(v3.4.11) */
|
||||||
|
export const WECOM_PUSH_CONDITIONS = [
|
||||||
|
'alert.ops',
|
||||||
|
'support_ticket.created',
|
||||||
|
'alert.pay',
|
||||||
|
'alert.redeem',
|
||||||
|
'alert.system',
|
||||||
|
'alert.settlement',
|
||||||
|
'dev_plan.task_dispatch',
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
export type WecomPushCondition = (typeof WECOM_PUSH_CONDITIONS)[number];
|
||||||
|
|
||||||
|
export const WECOM_PUSH_CONDITION_LABELS: Record<WecomPushCondition, string> = {
|
||||||
|
'alert.ops': '运营告警(售后工单、客户端错误等)',
|
||||||
|
'support_ticket.created': '新建技术支持工单',
|
||||||
|
'alert.pay': '支付异常',
|
||||||
|
'alert.redeem': '核销异常',
|
||||||
|
'alert.system': '系统监控(5xx、回调、定时任务)',
|
||||||
|
'alert.settlement': '结算任务告警',
|
||||||
|
'dev_plan.task_dispatch': '开发任务评审派发',
|
||||||
|
};
|
||||||
|
|
||||||
|
export const WECOM_PUSH_CONDITION_GROUPS: Array<{
|
||||||
|
key: string;
|
||||||
|
label: string;
|
||||||
|
conditions: WecomPushCondition[];
|
||||||
|
}> = [
|
||||||
|
{
|
||||||
|
key: 'ops',
|
||||||
|
label: '工单与运营',
|
||||||
|
conditions: ['alert.ops', 'support_ticket.created'],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'pay_redeem',
|
||||||
|
label: '支付与核销',
|
||||||
|
conditions: ['alert.pay', 'alert.redeem'],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'system',
|
||||||
|
label: '系统与结算',
|
||||||
|
conditions: ['alert.system', 'alert.settlement'],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'dev_plan',
|
||||||
|
label: '开发计划',
|
||||||
|
conditions: ['dev_plan.task_dispatch'],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
/** 默认「运营告警」推送条件 */
|
||||||
|
export const WECOM_PUSH_DEFAULT_ALERT_CONDITIONS: WecomPushCondition[] = [
|
||||||
|
'alert.ops',
|
||||||
|
'support_ticket.created',
|
||||||
|
'alert.pay',
|
||||||
|
'alert.redeem',
|
||||||
|
'alert.system',
|
||||||
|
'alert.settlement',
|
||||||
|
];
|
||||||
|
|
||||||
|
/** 默认「开发任务派发」推送条件 */
|
||||||
|
export const WECOM_PUSH_DEFAULT_DEV_DISPATCH_CONDITIONS: WecomPushCondition[] = [
|
||||||
|
'dev_plan.task_dispatch',
|
||||||
|
'support_ticket.created',
|
||||||
|
];
|
||||||
|
|
||||||
|
export function parseWecomPushConditions(
|
||||||
|
raw?: string | string[] | null,
|
||||||
|
): WecomPushCondition[] {
|
||||||
|
const valid = new Set<string>(WECOM_PUSH_CONDITIONS);
|
||||||
|
let list: string[];
|
||||||
|
|
||||||
|
if (Array.isArray(raw)) {
|
||||||
|
list = raw.map(String);
|
||||||
|
} else {
|
||||||
|
const text = String(raw ?? '').trim();
|
||||||
|
if (!text) {
|
||||||
|
list = [];
|
||||||
|
} else if (text.startsWith('[')) {
|
||||||
|
try {
|
||||||
|
const parsed: unknown = JSON.parse(text);
|
||||||
|
list = Array.isArray(parsed) ? parsed.map(String) : [];
|
||||||
|
} catch {
|
||||||
|
list = text
|
||||||
|
.split(/[,,\s]+/)
|
||||||
|
.map((s) => s.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
list = text
|
||||||
|
.split(/[,,\s]+/)
|
||||||
|
.map((s) => s.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return [...new Set(list.filter((s): s is WecomPushCondition => valid.has(s)))];
|
||||||
|
}
|
||||||
|
|
||||||
|
export type WecomMessagePushDto = {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
avatarUrl: string | null;
|
||||||
|
webhookUrl: string;
|
||||||
|
webhookUrlMasked: string;
|
||||||
|
enabled: boolean;
|
||||||
|
mentionWecomUserId: string | null;
|
||||||
|
pushConditions: WecomPushCondition[];
|
||||||
|
sortOrder: number;
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type CreateWecomMessagePushRequest = {
|
||||||
|
name: string;
|
||||||
|
avatarUrl?: string | null;
|
||||||
|
webhookUrl: string;
|
||||||
|
enabled?: boolean;
|
||||||
|
mentionWecomUserId?: string | null;
|
||||||
|
pushConditions: WecomPushCondition[];
|
||||||
|
sortOrder?: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type UpdateWecomMessagePushRequest = {
|
||||||
|
name?: string;
|
||||||
|
avatarUrl?: string | null;
|
||||||
|
webhookUrl?: string;
|
||||||
|
enabled?: boolean;
|
||||||
|
mentionWecomUserId?: string | null;
|
||||||
|
pushConditions?: WecomPushCondition[];
|
||||||
|
sortOrder?: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function maskWecomWebhookUrl(url: string): string {
|
||||||
|
const u = url.trim();
|
||||||
|
if (u.length <= 24) return `${u.slice(0, 8)}…`;
|
||||||
|
return `${u.slice(0, 20)}…${u.slice(-8)}`;
|
||||||
|
}
|
||||||
@@ -11,7 +11,8 @@
|
|||||||
"./CouponBadge": "./src/CouponBadge.tsx",
|
"./CouponBadge": "./src/CouponBadge.tsx",
|
||||||
"./OrderStatusTabs": "./src/OrderStatusTabs.tsx",
|
"./OrderStatusTabs": "./src/OrderStatusTabs.tsx",
|
||||||
"./AppImage": "./src/AppImage.tsx",
|
"./AppImage": "./src/AppImage.tsx",
|
||||||
"./PullToRefresh": "./src/PullToRefresh.tsx"
|
"./PullToRefresh": "./src/PullToRefresh.tsx",
|
||||||
|
"./compressImage": "./src/compressImage.ts"
|
||||||
},
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"react": "^18.3.1"
|
"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);
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
export { isWechatBrowser, isMiniProgram, getRuntimePlatform } from './env';
|
export { isWechatBrowser, isMiniProgram, getRuntimePlatform, isIosDevice, isWechatDevTools } from './env';
|
||||||
export { getRouterBasename, toAppPath, isOnAppPath } from './app-path';
|
export { getRouterBasename, toAppPath, isOnAppPath } from './app-path';
|
||||||
export {
|
export {
|
||||||
initWechatJssdk,
|
initWechatJssdk,
|
||||||
@@ -10,7 +10,7 @@ export {
|
|||||||
resetJssdkConfig,
|
resetJssdkConfig,
|
||||||
stripOAuthParamsFromLocation,
|
stripOAuthParamsFromLocation,
|
||||||
} from './jssdk';
|
} from './jssdk';
|
||||||
export { formatScanFailMessage } from './scan';
|
export { formatScanFailMessage, isScanPermissionWarmupError } from './scan';
|
||||||
export {
|
export {
|
||||||
getWechatLocation,
|
getWechatLocation,
|
||||||
getWechatLocationDetailed,
|
getWechatLocationDetailed,
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ export function formatScanFailMessage(errMsg: string): string {
|
|||||||
return msg;
|
return msg;
|
||||||
}
|
}
|
||||||
|
|
||||||
function isScanPermissionWarmupError(msg: string): boolean {
|
export function isScanPermissionWarmupError(msg: string): boolean {
|
||||||
return /offline verifying|permission value is offline|权限验证中|接口未就绪|invalid signature|config:fail|signature/i.test(
|
return /offline verifying|permission value is offline|权限验证中|接口未就绪|invalid signature|config:fail|signature/i.test(
|
||||||
msg,
|
msg,
|
||||||
);
|
);
|
||||||
@@ -134,15 +134,13 @@ export async function scanQrCode(
|
|||||||
throw new Error('当前微信版本不支持扫码,请升级微信后重试');
|
throw new Error('当前微信版本不支持扫码,请升级微信后重试');
|
||||||
}
|
}
|
||||||
|
|
||||||
// wx.ready ≠ 权限离线校验完成;授权回跳后更明显
|
const ios = isIosDevice() && !isWechatDevTools();
|
||||||
const warmupMs = options.postAuthWarmup
|
|
||||||
? 1200
|
// wx.ready ≠ 权限离线校验完成;OAuth 回跳后 iOS 更明显
|
||||||
: isIosDevice() && !isWechatDevTools()
|
const warmupMs = options.postAuthWarmup ? (ios ? 1600 : 1000) : ios ? 800 : 300;
|
||||||
? 800
|
|
||||||
: 300;
|
|
||||||
await delay(warmupMs);
|
await delay(warmupMs);
|
||||||
|
|
||||||
const maxAttempts = options.postAuthWarmup ? 3 : 2;
|
const maxAttempts = options.postAuthWarmup ? (ios ? 4 : 3) : 2;
|
||||||
let lastError: Error | null = null;
|
let lastError: Error | null = null;
|
||||||
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
||||||
if (attempt > 0) {
|
if (attempt > 0) {
|
||||||
@@ -151,7 +149,8 @@ export async function scanQrCode(
|
|||||||
await initWechatJssdk({ ...jssdkOptions, url: getJssdkSignUrl() });
|
await initWechatJssdk({ ...jssdkOptions, url: getJssdkSignUrl() });
|
||||||
await checkJsApi('scanQRCode');
|
await checkJsApi('scanQRCode');
|
||||||
}
|
}
|
||||||
await delay(700 + attempt * 500);
|
const retryDelay = options.postAuthWarmup && ios ? 900 + attempt * 700 : 700 + attempt * 500;
|
||||||
|
await delay(retryDelay);
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
return await invokeScanQrCode();
|
return await invokeScanQrCode();
|
||||||
|
|||||||
Generated
+3
@@ -29,6 +29,9 @@ importers:
|
|||||||
'@dukang/shared-types':
|
'@dukang/shared-types':
|
||||||
specifier: workspace:*
|
specifier: workspace:*
|
||||||
version: link:../../packages/shared-types
|
version: link:../../packages/shared-types
|
||||||
|
'@dukang/shared-ui':
|
||||||
|
specifier: workspace:*
|
||||||
|
version: link:../../packages/shared-ui
|
||||||
antd:
|
antd:
|
||||||
specifier: ^5.22.0
|
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)
|
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「企微机器人」模块创建)
|
# 企业微信智能机器人总开关(Bot 实例在 HQ「企微机器人」模块创建)
|
||||||
WECOM_AIBOT_ENABLED=false
|
WECOM_AIBOT_ENABLED=false
|
||||||
|
|
||||||
# 运营告警:企业微信群机器人 Webhook(单向推送,与智能机器人长连接无关)
|
# 运营告警 Webhook(已废弃运行时读取,仅 seed 一次性导入到 HQ「消息推送」)
|
||||||
WECOM_ALERT_ENABLED=false
|
# 配置后执行 pnpm prisma:seed-wecom-push 或 API 启动时自动 ensureDefaults
|
||||||
WECOM_ALERT_WEBHOOK_URL=
|
# WECOM_ALERT_ENABLED=false
|
||||||
|
# WECOM_ALERT_WEBHOOK_URL=
|
||||||
WECOM_ALERT_ENV_LABEL=local
|
WECOM_ALERT_ENV_LABEL=local
|
||||||
|
|
||||||
# 腾讯位置服务(地理编码 / 逆地理 / 地点搜索选点,服务端调用)
|
# 腾讯位置服务(地理编码 / 逆地理 / 地点搜索选点,服务端调用)
|
||||||
|
|||||||
@@ -53,8 +53,9 @@ WX_MINI_MSG_AES_KEY=
|
|||||||
WECOM_AIBOT_ENABLED=false
|
WECOM_AIBOT_ENABLED=false
|
||||||
|
|
||||||
# 运营告警:企业微信群机器人 Webhook
|
# 运营告警:企业微信群机器人 Webhook
|
||||||
WECOM_ALERT_ENABLED=false
|
# 运营告警 Webhook(已废弃运行时读取,仅 seed 导入 HQ「消息推送」)
|
||||||
WECOM_ALERT_WEBHOOK_URL=
|
# WECOM_ALERT_ENABLED=false
|
||||||
|
# WECOM_ALERT_WEBHOOK_URL=
|
||||||
WECOM_ALERT_ENV_LABEL=production
|
WECOM_ALERT_ENV_LABEL=production
|
||||||
|
|
||||||
OSS_ACCESS_KEY_ID=
|
OSS_ACCESS_KEY_ID=
|
||||||
|
|||||||
@@ -53,8 +53,9 @@ WX_MINI_MSG_AES_KEY=
|
|||||||
WECOM_AIBOT_ENABLED=false
|
WECOM_AIBOT_ENABLED=false
|
||||||
|
|
||||||
# 运营告警:企业微信群机器人 Webhook
|
# 运营告警:企业微信群机器人 Webhook
|
||||||
WECOM_ALERT_ENABLED=false
|
# 运营告警 Webhook(已废弃运行时读取,仅 seed 导入 HQ「消息推送」)
|
||||||
WECOM_ALERT_WEBHOOK_URL=
|
# WECOM_ALERT_ENABLED=false
|
||||||
|
# WECOM_ALERT_WEBHOOK_URL=
|
||||||
WECOM_ALERT_ENV_LABEL=staging
|
WECOM_ALERT_ENV_LABEL=staging
|
||||||
|
|
||||||
OSS_ACCESS_KEY_ID=
|
OSS_ACCESS_KEY_ID=
|
||||||
|
|||||||
@@ -16,6 +16,8 @@
|
|||||||
"prisma:seed-stats": "ts-node --transpile-only prisma/seed-stats-mock.ts",
|
"prisma:seed-stats": "ts-node --transpile-only prisma/seed-stats-mock.ts",
|
||||||
"prisma:migrate-city-partner": "ts-node --transpile-only prisma/migrate-city-partner.ts",
|
"prisma:migrate-city-partner": "ts-node --transpile-only prisma/migrate-city-partner.ts",
|
||||||
"prisma:seed-legacy": "ts-node --transpile-only prisma/seed-prev1.ts",
|
"prisma:seed-legacy": "ts-node --transpile-only prisma/seed-prev1.ts",
|
||||||
|
"prisma:seed-wecom-push": "ts-node --transpile-only prisma/seed-wecom-message-push.ts",
|
||||||
|
"prisma:migrate-wecom-push": "ts-node --transpile-only prisma/migrate-wecom-message-push.ts",
|
||||||
"prisma:upsert-super-admin": "ts-node --transpile-only scripts/upsert-super-admin.ts",
|
"prisma:upsert-super-admin": "ts-node --transpile-only scripts/upsert-super-admin.ts",
|
||||||
"prisma:sync-benefit": "ts-node --transpile-only prisma/sync-benefit-to-price.ts"
|
"prisma:sync-benefit": "ts-node --transpile-only prisma/sync-benefit-to-price.ts"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -0,0 +1,91 @@
|
|||||||
|
/**
|
||||||
|
* 发版前一次性迁移:在 prisma db push 删除 task_dispatch_* 列之前执行。
|
||||||
|
* 创建 wecom_message_push 表(若不存在)并写入默认推送。
|
||||||
|
*/
|
||||||
|
import { PrismaClient } from '@prisma/client';
|
||||||
|
import {
|
||||||
|
WECOM_PUSH_DEFAULT_ALERT_CONDITIONS,
|
||||||
|
WECOM_PUSH_DEFAULT_DEV_DISPATCH_CONDITIONS,
|
||||||
|
} from '@dukang/shared-types';
|
||||||
|
|
||||||
|
const prisma = new PrismaClient();
|
||||||
|
|
||||||
|
async function ensureTable() {
|
||||||
|
await prisma.$executeRawUnsafe(`
|
||||||
|
CREATE TABLE IF NOT EXISTS wecom_message_push (
|
||||||
|
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
name VARCHAR(64) NOT NULL,
|
||||||
|
avatar_url VARCHAR(512) NULL,
|
||||||
|
webhook_url VARCHAR(512) NOT NULL,
|
||||||
|
enabled TINYINT(1) NOT NULL DEFAULT 1,
|
||||||
|
mention_wecom_user_id VARCHAR(64) NULL,
|
||||||
|
push_conditions TEXT NOT NULL,
|
||||||
|
sort_order INT NOT NULL DEFAULT 0,
|
||||||
|
created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||||
|
updated_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
|
||||||
|
INDEX wecom_message_push_enabled_sort_order_idx (enabled, sort_order)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
|
||||||
|
`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
await ensureTable();
|
||||||
|
const count = await prisma.wecomMessagePush.count();
|
||||||
|
if (count > 0) {
|
||||||
|
console.log(`wecom_message_push already has ${count} row(s), skip`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const alertUrl = (process.env.WECOM_ALERT_WEBHOOK_URL || '').trim();
|
||||||
|
if (alertUrl) {
|
||||||
|
await prisma.wecomMessagePush.create({
|
||||||
|
data: {
|
||||||
|
name: '运营告警',
|
||||||
|
webhookUrl: alertUrl,
|
||||||
|
enabled: process.env.WECOM_ALERT_ENABLED !== 'false',
|
||||||
|
pushConditions: JSON.stringify(WECOM_PUSH_DEFAULT_ALERT_CONDITIONS),
|
||||||
|
sortOrder: 0,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
console.log('migrated: 运营告警');
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const rows = await prisma.$queryRawUnsafe<
|
||||||
|
Array<{
|
||||||
|
task_dispatch_webhook_url: string | null;
|
||||||
|
task_dispatch_wecom_user_id: string | null;
|
||||||
|
task_dispatch_enabled: number | boolean | null;
|
||||||
|
}>
|
||||||
|
>(
|
||||||
|
'SELECT task_dispatch_webhook_url, task_dispatch_wecom_user_id, task_dispatch_enabled FROM dev_plan_settings LIMIT 1',
|
||||||
|
);
|
||||||
|
const row = rows[0];
|
||||||
|
if (row?.task_dispatch_webhook_url?.trim()) {
|
||||||
|
await prisma.wecomMessagePush.create({
|
||||||
|
data: {
|
||||||
|
name: '开发任务派发',
|
||||||
|
webhookUrl: row.task_dispatch_webhook_url.trim(),
|
||||||
|
enabled: !!row.task_dispatch_enabled,
|
||||||
|
mentionWecomUserId: row.task_dispatch_wecom_user_id?.trim() || null,
|
||||||
|
pushConditions: JSON.stringify(WECOM_PUSH_DEFAULT_DEV_DISPATCH_CONDITIONS),
|
||||||
|
sortOrder: 10,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
console.log('migrated: 开发任务派发');
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.log('dev_plan_settings task_dispatch columns unavailable:', e instanceof Error ? e.message : e);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('migrate-wecom-message-push done');
|
||||||
|
}
|
||||||
|
|
||||||
|
main()
|
||||||
|
.catch((e) => {
|
||||||
|
console.error(e);
|
||||||
|
process.exit(1);
|
||||||
|
})
|
||||||
|
.finally(async () => {
|
||||||
|
await prisma.$disconnect();
|
||||||
|
});
|
||||||
@@ -107,6 +107,33 @@ enum SupportTicketStatus {
|
|||||||
DEVELOPING
|
DEVELOPING
|
||||||
TESTING
|
TESTING
|
||||||
PASSED
|
PASSED
|
||||||
|
PUBLISHED
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
enum InvoiceTitleType {
|
||||||
@@ -155,6 +182,13 @@ enum PromoCodeScene {
|
|||||||
OTHER
|
OTHER
|
||||||
}
|
}
|
||||||
|
|
||||||
|
enum PromoMetricEventType {
|
||||||
|
SCAN
|
||||||
|
ATTRIBUTION
|
||||||
|
REGISTER
|
||||||
|
ORDER
|
||||||
|
}
|
||||||
|
|
||||||
enum CityStatus {
|
enum CityStatus {
|
||||||
PENDING
|
PENDING
|
||||||
ACTIVE
|
ACTIVE
|
||||||
@@ -396,9 +430,10 @@ model WecomBot {
|
|||||||
secret String @db.VarChar(256)
|
secret String @db.VarChar(256)
|
||||||
avatarUrl String? @map("avatar_url") @db.VarChar(512)
|
avatarUrl String? @map("avatar_url") @db.VarChar(512)
|
||||||
welcome String? @db.VarChar(1024)
|
welcome String? @db.VarChar(1024)
|
||||||
/// JSON 字符串数组,如 ["ticket.create","user.view_sms"]
|
/// JSON 字符串数组,模块化权限
|
||||||
permissions String @db.Text
|
permissions String @db.Text
|
||||||
/// 未匹配指令时是否调用语言模型
|
/// 可执行 support_ticket.review 的企微 userid 白名单
|
||||||
|
reviewSuperAdminWecomUserIds String? @map("review_super_admin_wecom_user_ids") @db.Text
|
||||||
aiEnabled Boolean @default(false) @map("ai_enabled")
|
aiEnabled Boolean @default(false) @map("ai_enabled")
|
||||||
llmConfigId BigInt? @map("llm_config_id") @db.UnsignedBigInt
|
llmConfigId BigInt? @map("llm_config_id") @db.UnsignedBigInt
|
||||||
knowledgeBaseId BigInt? @map("knowledge_base_id") @db.UnsignedBigInt
|
knowledgeBaseId BigInt? @map("knowledge_base_id") @db.UnsignedBigInt
|
||||||
@@ -409,6 +444,7 @@ model WecomBot {
|
|||||||
|
|
||||||
llmConfig LlmApiConfig? @relation(fields: [llmConfigId], references: [id], onDelete: SetNull)
|
llmConfig LlmApiConfig? @relation(fields: [llmConfigId], references: [id], onDelete: SetNull)
|
||||||
knowledgeBase KnowledgeBase? @relation(fields: [knowledgeBaseId], references: [id], onDelete: SetNull)
|
knowledgeBase KnowledgeBase? @relation(fields: [knowledgeBaseId], references: [id], onDelete: SetNull)
|
||||||
|
wecomBotLogs LogWecomBot[]
|
||||||
|
|
||||||
@@index([enabled, sortOrder])
|
@@index([enabled, sortOrder])
|
||||||
@@index([llmConfigId])
|
@@index([llmConfigId])
|
||||||
@@ -416,6 +452,46 @@ model WecomBot {
|
|||||||
@@map("wecom_bot")
|
@@map("wecom_bot")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 企微机器人操作审计
|
||||||
|
model LogWecomBot {
|
||||||
|
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||||
|
botId BigInt? @map("bot_id") @db.UnsignedBigInt
|
||||||
|
botKey String? @map("bot_key") @db.VarChar(64)
|
||||||
|
wecomUserId String @map("wecom_user_id") @db.VarChar(64)
|
||||||
|
action String @db.VarChar(64)
|
||||||
|
permission String? @db.VarChar(64)
|
||||||
|
inputSummary String? @map("input_summary") @db.VarChar(512)
|
||||||
|
success Boolean @default(true)
|
||||||
|
errorMessage String? @map("error_message") @db.VarChar(512)
|
||||||
|
latencyMs Int? @map("latency_ms")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
|
||||||
|
|
||||||
|
bot WecomBot? @relation(fields: [botId], references: [id], onDelete: SetNull)
|
||||||
|
|
||||||
|
@@index([botId, createdAt])
|
||||||
|
@@index([wecomUserId, createdAt])
|
||||||
|
@@index([action, createdAt])
|
||||||
|
@@map("log_wecom_bot")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 企微群机器人 Webhook 消息推送(v3.4.11)
|
||||||
|
model WecomMessagePush {
|
||||||
|
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||||
|
name String @db.VarChar(64)
|
||||||
|
avatarUrl String? @map("avatar_url") @db.VarChar(512)
|
||||||
|
webhookUrl String @map("webhook_url") @db.VarChar(512)
|
||||||
|
enabled Boolean @default(true)
|
||||||
|
mentionWecomUserId String? @map("mention_wecom_user_id") @db.VarChar(64)
|
||||||
|
/// JSON 字符串数组,推送条件 key
|
||||||
|
pushConditions String @map("push_conditions") @db.Text
|
||||||
|
sortOrder Int @default(0) @map("sort_order")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at") @db.DateTime(3)
|
||||||
|
|
||||||
|
@@index([enabled, sortOrder])
|
||||||
|
@@map("wecom_message_push")
|
||||||
|
}
|
||||||
|
|
||||||
/// HQ 语言模型 API 配置(非超管仅可见/可开关自己创建的)
|
/// HQ 语言模型 API 配置(非超管仅可见/可开关自己创建的)
|
||||||
model LlmApiConfig {
|
model LlmApiConfig {
|
||||||
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||||
@@ -585,6 +661,7 @@ model CommonSupportTicket {
|
|||||||
ticketNo String @unique @map("ticket_no") @db.VarChar(32)
|
ticketNo String @unique @map("ticket_no") @db.VarChar(32)
|
||||||
ticketType SupportTicketType @map("ticket_type")
|
ticketType SupportTicketType @map("ticket_type")
|
||||||
status SupportTicketStatus @default(PENDING_REVIEW)
|
status SupportTicketStatus @default(PENDING_REVIEW)
|
||||||
|
priority SupportTicketPriority @default(NORMAL) @map("priority")
|
||||||
title String @db.VarChar(128)
|
title String @db.VarChar(128)
|
||||||
content String? @db.Text
|
content String? @db.Text
|
||||||
rejectReason String? @map("reject_reason") @db.VarChar(512)
|
rejectReason String? @map("reject_reason") @db.VarChar(512)
|
||||||
@@ -594,6 +671,9 @@ model CommonSupportTicket {
|
|||||||
reviewerName String? @map("reviewer_name") @db.VarChar(64)
|
reviewerName String? @map("reviewer_name") @db.VarChar(64)
|
||||||
reviewedAt DateTime? @map("reviewed_at") @db.DateTime(3)
|
reviewedAt DateTime? @map("reviewed_at") @db.DateTime(3)
|
||||||
remark String? @db.VarChar(512)
|
remark String? @db.VarChar(512)
|
||||||
|
attachmentUrls Json? @map("attachment_urls")
|
||||||
|
releasedVersionNo String? @map("released_version_no") @db.VarChar(32)
|
||||||
|
publishedAt DateTime? @map("published_at") @db.DateTime(3)
|
||||||
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
|
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
|
||||||
updatedAt DateTime @updatedAt @map("updated_at") @db.DateTime(3)
|
updatedAt DateTime @updatedAt @map("updated_at") @db.DateTime(3)
|
||||||
completedAt DateTime? @map("completed_at") @db.DateTime(3)
|
completedAt DateTime? @map("completed_at") @db.DateTime(3)
|
||||||
@@ -601,7 +681,89 @@ model CommonSupportTicket {
|
|||||||
@@index([status, createdAt])
|
@@index([status, createdAt])
|
||||||
@@index([ticketType, status])
|
@@index([ticketType, status])
|
||||||
@@index([creatorId])
|
@@index([creatorId])
|
||||||
|
@@index([releasedVersionNo])
|
||||||
@@map("common_support_ticket")
|
@@map("common_support_ticket")
|
||||||
|
|
||||||
|
devPlanTasks DevPlanTask[]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 开发计划 · 任务
|
||||||
|
model DevPlanTask {
|
||||||
|
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||||
|
taskNo String @unique @map("task_no") @db.VarChar(32)
|
||||||
|
content String @db.Text
|
||||||
|
type DevPlanTaskType
|
||||||
|
status DevPlanTaskStatus @default(TODO)
|
||||||
|
creatorHqAccountId BigInt @map("creator_hq_account_id") @db.UnsignedBigInt
|
||||||
|
supportTicketId BigInt? @map("support_ticket_id") @db.UnsignedBigInt
|
||||||
|
lastDispatchedAt DateTime? @map("last_dispatched_at") @db.DateTime(3)
|
||||||
|
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
|
||||||
|
completedAt DateTime? @map("completed_at") @db.DateTime(3)
|
||||||
|
|
||||||
|
supportTicket CommonSupportTicket? @relation(fields: [supportTicketId], references: [id], onDelete: SetNull)
|
||||||
|
versionLinks DevPlanVersionTask[]
|
||||||
|
|
||||||
|
@@index([status, createdAt])
|
||||||
|
@@index([supportTicketId])
|
||||||
|
@@map("dev_plan_task")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 开发计划 · 版本
|
||||||
|
model DevPlanVersion {
|
||||||
|
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||||
|
versionNo String @unique @map("version_no") @db.VarChar(32)
|
||||||
|
content String? @db.Text
|
||||||
|
status DevPlanVersionStatus @default(PENDING)
|
||||||
|
/// @deprecated 不再使用,保留兼容旧数据
|
||||||
|
assigneeHqAccountId BigInt? @map("assignee_hq_account_id") @db.UnsignedBigInt
|
||||||
|
devStartedAt DateTime? @map("dev_started_at") @db.DateTime(3)
|
||||||
|
devCompletedAt DateTime? @map("dev_completed_at") @db.DateTime(3)
|
||||||
|
releasedAt DateTime? @map("released_at") @db.DateTime(3)
|
||||||
|
durationMinutes Int? @map("duration_minutes")
|
||||||
|
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at") @db.DateTime(3)
|
||||||
|
|
||||||
|
taskLinks DevPlanVersionTask[]
|
||||||
|
|
||||||
|
@@index([status, createdAt])
|
||||||
|
@@map("dev_plan_version")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 开发计划 · 版本-任务多对多
|
||||||
|
model DevPlanVersionTask {
|
||||||
|
versionId BigInt @map("version_id") @db.UnsignedBigInt
|
||||||
|
taskId BigInt @map("task_id") @db.UnsignedBigInt
|
||||||
|
sortOrder Int @default(0) @map("sort_order")
|
||||||
|
|
||||||
|
version DevPlanVersion @relation(fields: [versionId], references: [id], onDelete: Cascade)
|
||||||
|
task DevPlanTask @relation(fields: [taskId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
|
@@id([versionId, taskId])
|
||||||
|
@@index([taskId])
|
||||||
|
@@map("dev_plan_version_task")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 开发计划 · 全局设置(单例 id=1)
|
||||||
|
model DevPlanSettings {
|
||||||
|
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||||
|
reviewAssistantLlmConfigId BigInt? @map("review_assistant_llm_config_id") @db.UnsignedBigInt
|
||||||
|
reviewAssistantKnowledgeBaseId BigInt? @map("review_assistant_knowledge_base_id") @db.UnsignedBigInt
|
||||||
|
reviewAssistantPrompt String? @map("review_assistant_prompt") @db.Text
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at") @db.DateTime(3)
|
||||||
|
|
||||||
|
@@map("dev_plan_settings")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 开发计划 · 任务派发审计
|
||||||
|
model DevPlanTaskDispatch {
|
||||||
|
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||||
|
taskIdsJson String @map("task_ids_json") @db.Text
|
||||||
|
supplement String? @db.Text
|
||||||
|
operatorHqAccountId BigInt @map("operator_hq_account_id") @db.UnsignedBigInt
|
||||||
|
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
|
||||||
|
|
||||||
|
@@index([createdAt])
|
||||||
|
@@map("dev_plan_task_dispatch")
|
||||||
}
|
}
|
||||||
|
|
||||||
model CommonProductItem {
|
model CommonProductItem {
|
||||||
@@ -705,6 +867,7 @@ model CommonPromoCode {
|
|||||||
qrcodeResource CommonResource? @relation("PromoQrcode", fields: [qrcodeResourceId], references: [id], onDelete: SetNull)
|
qrcodeResource CommonResource? @relation("PromoQrcode", fields: [qrcodeResourceId], references: [id], onDelete: SetNull)
|
||||||
attributions UserPromoAttribution[]
|
attributions UserPromoAttribution[]
|
||||||
orders Order[]
|
orders Order[]
|
||||||
|
metricEvents LogPromoEvent[]
|
||||||
|
|
||||||
@@index([ownerUserId])
|
@@index([ownerUserId])
|
||||||
@@index([scene, status])
|
@@index([scene, status])
|
||||||
@@ -1136,6 +1299,7 @@ model StorePackage {
|
|||||||
dishes String @db.Text
|
dishes String @db.Text
|
||||||
usableTime String? @map("usable_time") @db.VarChar(256)
|
usableTime String? @map("usable_time") @db.VarChar(256)
|
||||||
otherNotes String? @map("other_notes") @db.VarChar(512)
|
otherNotes String? @map("other_notes") @db.VarChar(512)
|
||||||
|
imageUrl String? @map("image_url") @db.VarChar(512)
|
||||||
sortOrder Int @default(0) @map("sort_order")
|
sortOrder Int @default(0) @map("sort_order")
|
||||||
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
|
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
|
||||||
updatedAt DateTime @updatedAt @map("updated_at") @db.DateTime(3)
|
updatedAt DateTime @updatedAt @map("updated_at") @db.DateTime(3)
|
||||||
@@ -1607,6 +1771,25 @@ model LogThirdParty {
|
|||||||
@@map("log_third_party")
|
@@map("log_third_party")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
model LogPromoEvent {
|
||||||
|
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||||
|
promoCodeId BigInt @map("promo_code_id") @db.UnsignedBigInt
|
||||||
|
eventType PromoMetricEventType @map("event_type")
|
||||||
|
userId BigInt? @map("user_id") @db.UnsignedBigInt
|
||||||
|
orderId BigInt? @map("order_id") @db.UnsignedBigInt
|
||||||
|
sessionId String? @map("session_id") @db.VarChar(64)
|
||||||
|
clientIp String? @map("client_ip") @db.VarChar(45)
|
||||||
|
ipProvince String? @map("ip_province") @db.VarChar(32)
|
||||||
|
ipCity String? @map("ip_city") @db.VarChar(32)
|
||||||
|
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
|
||||||
|
|
||||||
|
promoCode CommonPromoCode @relation(fields: [promoCodeId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
|
@@index([promoCodeId, eventType, createdAt])
|
||||||
|
@@index([createdAt])
|
||||||
|
@@map("log_promo_event")
|
||||||
|
}
|
||||||
|
|
||||||
model LogUserAnalytics {
|
model LogUserAnalytics {
|
||||||
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||||
userId BigInt? @map("user_id") @db.UnsignedBigInt
|
userId BigInt? @map("user_id") @db.UnsignedBigInt
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
/**
|
||||||
|
* 一次性迁移:空表时从 .env / 旧 dev_plan_settings 写入默认消息推送。
|
||||||
|
* 也可由 WecomMessagePushService.ensureDefaults() 在 API 启动时执行。
|
||||||
|
*/
|
||||||
|
import { PrismaClient } from '@prisma/client';
|
||||||
|
import {
|
||||||
|
WECOM_PUSH_DEFAULT_ALERT_CONDITIONS,
|
||||||
|
WECOM_PUSH_DEFAULT_DEV_DISPATCH_CONDITIONS,
|
||||||
|
} from '@dukang/shared-types';
|
||||||
|
|
||||||
|
const prisma = new PrismaClient();
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const count = await prisma.wecomMessagePush.count();
|
||||||
|
if (count > 0) {
|
||||||
|
console.log(`wecom_message_push already has ${count} row(s), skip seed`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const alertUrl = (process.env.WECOM_ALERT_WEBHOOK_URL || '').trim();
|
||||||
|
if (alertUrl) {
|
||||||
|
await prisma.wecomMessagePush.create({
|
||||||
|
data: {
|
||||||
|
name: '运营告警',
|
||||||
|
webhookUrl: alertUrl,
|
||||||
|
enabled: process.env.WECOM_ALERT_ENABLED !== 'false',
|
||||||
|
pushConditions: JSON.stringify(WECOM_PUSH_DEFAULT_ALERT_CONDITIONS),
|
||||||
|
sortOrder: 0,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
console.log('created push: 运营告警');
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const rows = await prisma.$queryRawUnsafe<
|
||||||
|
Array<{
|
||||||
|
task_dispatch_webhook_url: string | null;
|
||||||
|
task_dispatch_wecom_user_id: string | null;
|
||||||
|
task_dispatch_enabled: number | boolean | null;
|
||||||
|
}>
|
||||||
|
>(
|
||||||
|
'SELECT task_dispatch_webhook_url, task_dispatch_wecom_user_id, task_dispatch_enabled FROM dev_plan_settings LIMIT 1',
|
||||||
|
);
|
||||||
|
const row = rows[0];
|
||||||
|
if (row?.task_dispatch_webhook_url?.trim()) {
|
||||||
|
await prisma.wecomMessagePush.create({
|
||||||
|
data: {
|
||||||
|
name: '开发任务派发',
|
||||||
|
webhookUrl: row.task_dispatch_webhook_url.trim(),
|
||||||
|
enabled: !!row.task_dispatch_enabled,
|
||||||
|
mentionWecomUserId: row.task_dispatch_wecom_user_id?.trim() || null,
|
||||||
|
pushConditions: JSON.stringify(WECOM_PUSH_DEFAULT_DEV_DISPATCH_CONDITIONS),
|
||||||
|
sortOrder: 10,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
console.log('created push: 开发任务派发');
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.log('dev_plan_settings task_dispatch columns not found, skip dev dispatch migration');
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('wecom message push seed done');
|
||||||
|
}
|
||||||
|
|
||||||
|
main()
|
||||||
|
.catch((e) => {
|
||||||
|
console.error(e);
|
||||||
|
process.exit(1);
|
||||||
|
})
|
||||||
|
.finally(async () => {
|
||||||
|
await prisma.$disconnect();
|
||||||
|
});
|
||||||
@@ -21,6 +21,7 @@ import { CityScopeModule } from './modules/city-scope/city-scope.module';
|
|||||||
import { CommonModule } from './modules/common/common.module';
|
import { CommonModule } from './modules/common/common.module';
|
||||||
import { HqOperationModule } from './common/hq-operation/hq-operation.module';
|
import { HqOperationModule } from './common/hq-operation/hq-operation.module';
|
||||||
import { SystemConfigModule } from './common/system-config/system-config.module';
|
import { SystemConfigModule } from './common/system-config/system-config.module';
|
||||||
|
import { DevPlanModule } from './modules/dev-plan/dev-plan.module';
|
||||||
import { CallbacksModule } from './callbacks/callbacks.module';
|
import { CallbacksModule } from './callbacks/callbacks.module';
|
||||||
import { WecomModule } from './integrations/wecom/wecom.module';
|
import { WecomModule } from './integrations/wecom/wecom.module';
|
||||||
import { LoggingModule } from './common/logging/logging.module';
|
import { LoggingModule } from './common/logging/logging.module';
|
||||||
@@ -53,6 +54,7 @@ import { RequestIdMiddleware } from './common/logging/request-id.middleware';
|
|||||||
PromoModule,
|
PromoModule,
|
||||||
CityScopeModule,
|
CityScopeModule,
|
||||||
CommonModule,
|
CommonModule,
|
||||||
|
DevPlanModule,
|
||||||
HqOperationModule,
|
HqOperationModule,
|
||||||
LoggingModule,
|
LoggingModule,
|
||||||
CallbacksModule,
|
CallbacksModule,
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user