Compare commits

..

2 Commits

Author SHA1 Message Date
guke 4c22f774d8 Merge branch 'main' into codex/ad-count-percentile-fix 2026-07-28 13:50:28 +08:00
linkeyu c4b3fcfedb 修复:统一领券与比价广告数百分位口径 2026-07-28 11:42:13 +08:00
11 changed files with 154 additions and 1672 deletions
@@ -32,24 +32,9 @@ interface Props {
onClose: () => void;
userId: number | null;
phone: string | null; // 报表行已有的手机号:概览拉取失败时兜底展示
dateFrom: string | null;
dateTo: string | null;
appEnv?: 'prod' | 'test';
revenueScope: 'business' | 'all';
feedScene?: 'comparison' | 'coupon' | 'welfare';
}
export default function UserAdRevenueDrawer({
open,
onClose,
userId,
phone,
dateFrom,
dateTo,
appEnv,
revenueScope,
feedScene,
}: Props) {
export default function UserAdRevenueDrawer({ open, onClose, userId, phone }: Props) {
// UserRewardPanel 的 user 快照:它只读 phone/nickname/wechat_nickname/created_at,其余按 snapshot 形状补齐。
const [user, setUser] = useState<WithdrawUserSnapshot | null>(null);
@@ -97,19 +82,7 @@ export default function UserAdRevenueDrawer({
>
{/* userId 就绪即渲染;UserRewardPanel 内部按 userId 自行拉统计与金币记录,user 基本信息随后补上。
statsVariant="ad":统计区只显示 6 项看广告统计(累计提现/现金余额/激励视频观看数+eCPM/draw观看数+eCPM) */}
{userId != null && (
<UserRewardPanel
key={`${userId}-${dateFrom}-${dateTo}-${appEnv}-${revenueScope}-${feedScene}`}
userId={userId}
user={user}
statsVariant="ad"
initialDateFrom={dateFrom ?? undefined}
initialDateTo={dateTo ?? undefined}
appEnv={appEnv}
revenueScope={revenueScope}
feedScene={feedScene}
/>
)}
{userId != null && <UserRewardPanel userId={userId} user={user} statsVariant="ad" />}
</Drawer>
);
}
+2 -34
View File
@@ -470,27 +470,7 @@ export default function AdRevenueReportPage() {
const [loading, setLoading] = useState(false);
const [formulaOpen, setFormulaOpen] = useState(false);
// 点用户手机号弹出的「用户广告收益详情」半屏抽屉(userId + 手机号;null=关闭)
const [userDrawer, setUserDrawer] = useState<{
userId: number;
phone: string | null;
dateFrom: string;
dateTo: string;
appEnv?: 'prod' | 'test';
revenueScope: 'business' | 'all';
feedScene?: 'comparison' | 'coupon' | 'welfare';
} | null>(null);
const [queriedDetailFilters, setQueriedDetailFilters] = useState<{
dateFrom: string;
dateTo: string;
appEnv?: 'prod' | 'test';
revenueScope: 'business' | 'all';
feedScene?: 'comparison' | 'coupon' | 'welfare';
}>({
dateFrom: range[0].format('YYYY-MM-DD'),
dateTo: range[1].format('YYYY-MM-DD'),
appEnv: 'prod',
revenueScope: 'business',
});
const [userDrawer, setUserDrawer] = useState<{ userId: number; phone: string | null } | null>(null);
// 当前选择是否跨多天:跨多天时「按小时」无意义,粒度强制按天
const rangeMultiDay = range[0].format('YYYY-MM-DD') !== range[1].format('YYYY-MM-DD');
@@ -523,13 +503,6 @@ export default function AdRevenueReportPage() {
},
});
setData(res.data);
setQueriedDetailFilters({
dateFrom: from,
dateTo: to,
appEnv: appEnv === 'all' ? undefined : appEnv,
revenueScope,
feedScene: scene as 'comparison' | 'coupon' | 'welfare' | undefined,
});
setPage(targetPage);
setQueriedLimit(targetLimit);
setQueriedGranularity(gran);
@@ -578,7 +551,7 @@ export default function AdRevenueReportPage() {
width: 150,
render: (phone: string | null, r: AdRevenueRow) => (
// 点手机号/用户 → 打开该用户「广告收益详情」半屏抽屉(统计卡 + 金币记录)
<a onClick={() => setUserDrawer({ userId: r.user_id, phone, ...queriedDetailFilters })}>
<a onClick={() => setUserDrawer({ userId: r.user_id, phone })}>
{phone ? (
<span>
{phone}
@@ -1311,11 +1284,6 @@ export default function AdRevenueReportPage() {
open={!!userDrawer}
userId={userDrawer?.userId ?? null}
phone={userDrawer?.phone ?? null}
dateFrom={userDrawer?.dateFrom ?? null}
dateTo={userDrawer?.dateTo ?? null}
appEnv={userDrawer?.appEnv}
revenueScope={userDrawer?.revenueScope ?? 'all'}
feedScene={userDrawer?.feedScene}
onClose={() => setUserDrawer(null)}
/>
</div>
+15 -201
View File
@@ -19,154 +19,19 @@ import type {
const { RangePicker } = DatePicker;
// 主状态只对外呈现生命周期口径;below_minimum/store_closed 是迁移前历史兼容值。
const STATUS_COLOR: Record<string, string> = {
success: 'green',
below_minimum: 'green',
failed: 'red',
store_closed: 'red',
store_not_found: 'red',
items_not_found: 'red',
no_delivery: 'red',
unsupported: 'red',
cancelled: 'default',
running: 'blue',
};
const STATUS_LABEL: Record<string, string> = {
const STATUS_COLOR: Record<string, string> = { success: 'green', failed: 'red', cancelled: 'default' };
const STATUS_LABEL: Record<string, string> = { success: '成功', failed: '失败', cancelled: '中途退出' };
// 「卡在哪一步」: platform_results[*].status 翻成人话(找店/加菜/起送/读价)
const STUCK_LABEL: Record<string, string> = {
success: '成功',
below_minimum: '成功',
store_not_found: '没找到店',
items_not_found: '菜没匹配上',
below_minimum: '未达起送',
unsupported: '平台不支持',
failed: '失败',
store_closed: '失败',
store_not_found: '失败',
items_not_found: '失败',
no_delivery: '失败',
unsupported: '失败',
cancelled: '中途退出',
running: '进行中',
};
type PlatformResultRow = Record<string, unknown> & {
platform_id?: string;
platform_name?: string;
status?: string;
reason?: string;
};
function isRecord(value: unknown): value is Record<string, unknown> {
return value != null && typeof value === 'object' && !Array.isArray(value);
}
function platformResultRows(
platforms: Record<string, unknown>[] | null | undefined,
rawPayload: Record<string, unknown> | null | undefined,
): PlatformResultRow[] {
if ((platforms?.length ?? 0) > 0) return platforms as PlatformResultRow[];
const rawPlatforms = rawPayload?.platforms;
if (Array.isArray(rawPlatforms)) {
const rows = rawPlatforms.filter(isRecord) as PlatformResultRow[];
if (rows.length > 0) return rows;
}
// 灰度期旧记录没有 platforms,才回退 platform_results。这里的 success/source 是旧枚举,
// 展示时兼容折算为逐平台成功态 ok。
const resultValue = rawPayload?.platform_results;
if (Array.isArray(resultValue)) return resultValue.filter(isRecord) as PlatformResultRow[];
if (isRecord(resultValue)) {
return Object.entries(resultValue).flatMap(([platformId, result]) => (
isRecord(result) ? [{ platform_id: platformId, ...result } as PlatformResultRow] : []
));
}
return [];
}
function stringList(value: unknown): string[] {
return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [];
}
function hasDishDiff(row: PlatformResultRow): boolean {
if (typeof row.has_dish_diff === 'boolean') return row.has_dish_diff;
const items = Array.isArray(row.items) ? row.items.filter(isRecord) : [];
return items.some((item) => item.similar === true)
|| stringList(row.approx_dish_names).length > 0
|| stringList(row.skipped_dish_names).length > 0
|| Number(row.skipped_dish_count || 0) > 0;
}
type PlatformDisplay = {
label: string;
color: string;
rawStatus: string;
category: string;
dishDiff: boolean;
fallbackReason: string;
};
function platformDisplay(row: PlatformResultRow): PlatformDisplay {
const rawStatus = typeof row.status === 'string' && row.status ? row.status : 'unknown';
const legacySource = rawStatus === 'source';
const normalizedStatus = rawStatus === 'success' || legacySource ? 'ok' : rawStatus;
const dishDiff = hasDishDiff(row);
if (normalizedStatus === 'ok') {
const isSource = row.role === 'source' || row.is_user_original === true || legacySource;
const isLowest = row.is_best === true && !dishDiff;
return {
label: '成功',
color: 'green',
rawStatus,
category: isLowest ? '#1 全网最低赢家' : isSource ? '#2 原选择' : '#3 其他成功',
dishDiff,
fallbackReason: dishDiff ? '已比出价格,但存在菜品差异,仅供参考' : '已成功比出价格',
};
}
const known: Record<string, Omit<PlatformDisplay, 'rawStatus' | 'dishDiff'>> = {
below_minimum: { label: '未满起送', color: 'gold', category: '#5 未满起送', fallbackReason: '购物车未达到起送门槛' },
store_closed: { label: '门店打烊', color: 'orange', category: '#6 门店打烊', fallbackReason: '门店当前已打烊,无法比价' },
items_not_found: { label: '商品未找到', color: 'orange', category: '#7 没有您点的商品', fallbackReason: '该店没有找到本次所选商品' },
store_not_found: { label: '店铺未找到', color: 'orange', category: '#8 无对应商家', fallbackReason: '未找到可对应的商家' },
failed: { label: '比价失败', color: 'red', category: '#9 失败兜底', fallbackReason: '本平台比价流程未完成' },
unsupported: { label: '比价失败', color: 'red', category: '#9 失败兜底', fallbackReason: '当前版本暂不支持该平台' },
no_delivery: { label: '单点不配送', color: 'orange', category: '表外 · 单点不配送', fallbackReason: '所选商品不支持单点配送' },
not_installed: { label: '未安装', color: 'default', category: '#10 端侧本地 · 未安装', fallbackReason: '该状态仅由 App 端根据装机情况补齐' },
not_compared_this_time: { label: '本次未比', color: 'default', category: '#11 端侧本地 · 未选择', fallbackReason: '该状态仅由 App 端根据本次勾选情况补齐' },
};
const mapped = known[normalizedStatus];
if (mapped) return { ...mapped, rawStatus, dishDiff: false };
return {
label: '比价失败',
color: 'red',
rawStatus,
category: '#9 未知状态兜底',
dishDiff: false,
fallbackReason: `端侧未识别状态 ${rawStatus},按比价失败兜底`,
};
}
function dishDiffSummary(row: PlatformResultRow): string | null {
if (!hasDishDiff(row)) return null;
const parts: string[] = [];
const items = Array.isArray(row.items) ? row.items.filter(isRecord) : [];
const similarPairs = items
.filter((item) => item.similar === true && typeof item.name === 'string')
.map((item) => (typeof item.orig === 'string' ? `${item.orig}${item.name}` : String(item.name)));
if (similarPairs.length) parts.push(`近似替换:${similarPairs.join('、')}`);
const approx = stringList(row.approx_dish_names);
if (approx.length) parts.push(`规格近似:${approx.join('、')}`);
const skipped = stringList(row.skipped_dish_names);
if (skipped.length) parts.push(`完全缺失:${skipped.join('、')}`);
if (!skipped.length && Number(row.skipped_dish_count || 0) > 0) {
parts.push(`缺少 ${Number(row.skipped_dish_count)} 个菜品`);
}
return parts.join('') || '存在菜品差异';
}
function complexSpecSummary(row: PlatformResultRow): string | null {
const names = stringList(row.complex_spec_dish_names);
return names.length > 0 ? `复杂规格需核对:${names.join('、')}` : null;
}
const fmtMs = (ms: number | null) => (ms == null ? '-' : `${(ms / 1000).toFixed(1)}s`);
const cents = (c: number | null) => (c == null ? '-' : yuan(c));
@@ -504,7 +369,8 @@ export default function ComparisonRecordsPage() {
},
];
const platformResults = platformResultRows(detail?.platforms, detail?.raw_payload);
const platformResults =
(detail?.raw_payload?.platform_results as Record<string, unknown>[] | undefined) || [];
return (
<div>
@@ -557,7 +423,6 @@ export default function ComparisonRecordsPage() {
{ value: 'success', label: '成功' },
{ value: 'failed', label: '失败' },
{ value: 'cancelled', label: '中途退出' },
{ value: 'running', label: '进行中' },
]}
/>
<Button type="primary" onClick={search}></Button>
@@ -714,67 +579,16 @@ export default function ComparisonRecordsPage() {
)}
{platformResults.length > 0 && (
<Card size="small" title="逐平台结果卡片判定">
<Typography.Paragraph type="secondary" style={{ marginBottom: 12 }}>
platforms[].status=ok is_bestrolehas_dish_diff #10 #11
App
</Typography.Paragraph>
<Card size="small" title="逐平台结局(卡在哪一步)">
<Table
size="small"
rowKey={(_, i) => String(i)}
pagination={false}
dataSource={platformResults}
scroll={{ x: 1050 }}
columns={[
{
title: '平台', dataIndex: 'platform_name', width: 150,
render: (v, r: PlatformResultRow) => (v as string) || r.platform_id || '-',
},
{
title: '逐平台状态', dataIndex: 'status', width: 135,
render: (_, r: PlatformResultRow) => {
const display = platformDisplay(r);
return (
<Space direction="vertical" size={0}>
<Tag color={display.color}>{display.label}</Tag>
<Typography.Text type="secondary" code>{display.rawStatus}</Typography.Text>
</Space>
);
},
},
{
title: '卡片分类', key: 'category', width: 210,
render: (_, r: PlatformResultRow) => {
const display = platformDisplay(r);
const hasComplexSpec = complexSpecSummary(r) != null;
return (
<Space size={[4, 4]} wrap>
<Tag color={display.color}>{display.category}</Tag>
{display.dishDiff ? <Tag color="gold">#4 </Tag> : null}
{hasComplexSpec ? <Tag color="blue"></Tag> : null}
</Space>
);
},
},
{
title: '价格', dataIndex: 'price', width: 90,
render: (v) => (typeof v === 'number' ? `¥${v.toFixed(2)}` : '-'),
},
{
title: '说明 / 判定字段', key: 'reason',
render: (_, r: PlatformResultRow) => {
const display = platformDisplay(r);
const diff = dishDiffSummary(r);
const complexSpec = complexSpecSummary(r);
return (
<Space direction="vertical" size={0}>
<span>{typeof r.reason === 'string' && r.reason ? r.reason : display.fallbackReason}</span>
{diff ? <Typography.Text type="warning">{diff}</Typography.Text> : null}
{complexSpec ? <Typography.Text type="secondary">{complexSpec}</Typography.Text> : null}
</Space>
);
},
},
{ title: '平台', dataIndex: 'platform_name', render: (v, r: Record<string, unknown>) => (v as string) || (r.platform_id as string) || '-' },
{ title: '结局', dataIndex: 'status', render: (s: string) => <Tag color={s === 'success' ? 'green' : 'orange'}>{STUCK_LABEL[s] || s || '-'}</Tag> },
{ title: '说明', dataIndex: 'reason', render: (v) => (v as string) || '-' },
]}
/>
</Card>
+119 -168
View File
@@ -1,18 +1,7 @@
'use client';
import { useEffect, useState } from 'react';
import {
Button,
Card,
InputNumber,
Space,
Spin,
Switch,
Tag,
Typography,
Upload,
message,
} from 'antd';
import { Button, Card, Space, Spin, Switch, Tag, Typography, Upload, message } from 'antd';
import { DeleteOutlined, UploadOutlined } from '@ant-design/icons';
import { api, errMsg } from '@/lib/api';
import { canDo } from '@/lib/auth';
@@ -20,64 +9,55 @@ import { mediaUrl } from '@/lib/media';
import type { GuideVideoConfig as GuideCfg } from '@/lib/types';
const { Text } = Typography;
/** 后端 media.save_guide_video 只认 MP4 魔数;这里先在浏览器挡一道,省得白传 100MB。 */
const MAX_BYTES = 100 * 1024 * 1024;
type Scene = 'coupon' | 'comparison';
const META: Record<Scene, { title: string; action: string }> = {
coupon: { title: '一键自动领取引导视频', action: '一键自动领取' },
comparison: { title: '开始比价引导视频', action: '开始比价' },
};
function SceneConfig({ scene }: { scene: Scene }) {
const meta = META[scene];
/**
* 领券等候浮层的「新手引导视频」配置。
*
* 用户点首页「一键自动领取」→ 出等候浮层,浮层下方那块位置**前 3 次**放这支引导视频
* (而不是广告),每次固定发 120 金币;播完若浮层还开着,自动接着放广告(原逻辑)。
* 「系统配置 → 领券引导视频」tab 的一个区块。
*
* 后台只管两件事:**开关** 和 **换片**。次数(3)/ 金币(120)走服务端默认值,产品已拍板不再
* 开放配置,所以这里不渲染输入框、PATCH 也不带这两个字段(后端仍保留字段与默认值)。
*/
export default function GuideVideoConfig() {
const [cfg, setCfg] = useState<GuideCfg | null>(null);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [uploading, setUploading] = useState(false);
// 本地编辑态,保存时一次性 PATCH
const [enabled, setEnabled] = useState(true);
const [maxPlays, setMaxPlays] = useState(3);
const [rewardCoin, setRewardCoin] = useState(100);
const canEdit = canDo(['operator']);
const sync = (value: GuideCfg) => {
setCfg(value);
setEnabled(value.enabled);
setMaxPlays(value.max_plays);
setRewardCoin(value.reward_coin);
const sync = (c: GuideCfg) => {
setCfg(c);
setEnabled(c.enabled);
};
const load = async () => {
setLoading(true);
try {
const { data } = await api.get<GuideCfg>('/admin/api/guide-video', {
params: { scene },
});
const { data } = await api.get<GuideCfg>('/admin/api/guide-video');
sync(data);
} catch (e) {
message.error(errMsg(e));
} finally {
setLoading(false);
}
};
useEffect(() => {
void load();
}, [scene]);
load();
}, []);
const save = async () => {
setSaving(true);
try {
const { data } = await api.patch<GuideCfg>(
'/admin/api/guide-video',
{
enabled,
reward_coin: rewardCoin,
...(scene === 'comparison' ? { max_plays: maxPlays } : {}),
},
{ params: { scene } },
);
const { data } = await api.patch<GuideCfg>('/admin/api/guide-video', { enabled });
sync(data);
message.success(`${meta.title}配置已保存,下次触发即生效`);
message.success('已保存,用户下一次进入领券浮层即生效');
} catch (e) {
message.error(errMsg(e));
} finally {
@@ -85,27 +65,11 @@ function SceneConfig({ scene }: { scene: Scene }) {
}
};
const uploadVideo = async (file: File) => {
const form = new FormData();
form.append('file', file);
setUploading(true);
try {
const { data } = await api.post<GuideCfg>(
'/admin/api/guide-video/video',
form,
{ params: { scene } },
);
sync(data);
message.success(`${meta.title}已更新`);
} catch (e) {
message.error(errMsg(e));
} finally {
setUploading(false);
}
};
// antd Upload:beforeUpload 里自行 POST(multipart),返回 false 阻止其默认上传。
const beforeUpload = (file: File) => {
if (file.type !== 'video/mp4' && !/\.mp4$/i.test(file.name)) {
// 有些系统给 .mp4 的 type 是空串,不能只看 type,再兜一层扩展名。
const looksMp4 = file.type === 'video/mp4' || /\.mp4$/i.test(file.name);
if (!looksMp4) {
message.error('仅支持 MP4 视频(H.264 编码)');
return Upload.LIST_IGNORE;
}
@@ -117,15 +81,27 @@ function SceneConfig({ scene }: { scene: Scene }) {
return false;
};
const uploadVideo = async (file: File) => {
const form = new FormData();
form.append('file', file);
setUploading(true);
try {
const { data } = await api.post<GuideCfg>('/admin/api/guide-video/video', form);
sync(data);
message.success('引导视频已更新,用户下一次进入领券浮层即生效');
} catch (e) {
message.error(errMsg(e));
} finally {
setUploading(false);
}
};
const removeVideo = async () => {
setUploading(true);
try {
const { data } = await api.delete<GuideCfg>(
'/admin/api/guide-video/video',
{ params: { scene } },
);
const { data } = await api.delete<GuideCfg>('/admin/api/guide-video/video');
sync(data);
message.success(`已移除${meta.title}`);
message.success('已移除引导视频,领券浮层恢复为只放广告');
} catch (e) {
message.error(errMsg(e));
} finally {
@@ -136,136 +112,111 @@ function SceneConfig({ scene }: { scene: Scene }) {
return (
<Card
size="small"
title={meta.title}
title="领券引导视频(App 领券等候浮层,前 3 次替代广告)"
style={{ marginBottom: 16 }}
extra={
cfg?.updated_at ? (
<Text type="secondary">
<Text type="secondary" style={{ fontSize: 12 }}>
{new Date(cfg.updated_at).toLocaleString('zh-CN')}
</Text>
) : null
}
>
<p style={{ color: '#777', marginTop: 0 }}>
Android {meta.action} {cfg?.max_plays ?? 3}{' '}
广
{scene === 'coupon' &&
'领券引导视频的播放次数上限请在「监控审计 → 限制策略」中调整。'}
<p style={{ color: '#999', marginTop: 0 }}>
广<b> 3 </b>
<b></b> <b>120 </b>广
<b></b><b></b>
<b></b><b></b>
</p>
{loading || !cfg ? (
<Spin style={{ display: 'block', margin: '24px 0' }} />
) : (
<Space align="start" size={32} wrap>
<div style={{ width: 240 }}>
{cfg.video_url ? (
// eslint-disable-next-line jsx-a11y/media-has-caption
<video
src={mediaUrl(cfg.video_url)}
controls
style={{
width: 240,
maxHeight: 420,
borderRadius: 12,
background: '#000',
}}
/>
) : (
<div
style={{
height: 280,
border: '1px dashed #d9d9d9',
borderRadius: 12,
display: 'grid',
placeItems: 'center',
color: '#aaa',
}}
>
{/* 左:视频预览 */}
<div>
<Text type="secondary" style={{ fontSize: 12 }}>
</Text>
<div style={{ marginTop: 8, width: 240 }}>
{cfg.video_url ? (
// eslint-disable-next-line jsx-a11y/media-has-caption
<video
src={mediaUrl(cfg.video_url)}
controls
style={{
width: 240,
maxHeight: 420,
borderRadius: 12,
background: '#000',
border: '1px solid #f0f0f0',
}}
/>
) : (
<div
style={{
width: 240,
height: 320,
borderRadius: 12,
border: '1px dashed #d9d9d9',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
color: '#bbb',
fontSize: 13,
textAlign: 'center',
padding: 16,
}}
>
<br />
广
</div>
)}
</div>
{!enabled && cfg.video_url && (
<div style={{ color: '#fa8c16', fontSize: 12, marginTop: 6 }}>
广
</div>
)}
</div>
<Space direction="vertical" size="middle" style={{ minWidth: 390 }}>
{/* 右:编辑控件 */}
<Space direction="vertical" size="middle" style={{ minWidth: 360 }}>
<Space>
<span></span>
<Switch
checked={enabled}
disabled={!canEdit}
onChange={setEnabled}
/>
<span></span>
<Switch checked={enabled} disabled={!canEdit} onChange={setEnabled} />
{!enabled && <Tag color="orange"></Tag>}
</Space>
{scene === 'comparison' && (
<Space>
<span></span>
<InputNumber
min={0}
max={50}
precision={0}
value={maxPlays}
disabled={!canEdit}
onChange={(value) => setMaxPlays(value ?? 0)}
/>
<Text type="secondary"> N 3</Text>
</Space>
)}
<Space>
<span></span>
<InputNumber
min={0}
max={10000}
precision={0}
value={rewardCoin}
disabled={!canEdit}
onChange={(value) => setRewardCoin(value ?? 0)}
/>
<Text type="secondary"> 100</Text>
</Space>
<Space wrap>
<Upload
accept="video/mp4,.mp4"
showUploadList={false}
beforeUpload={beforeUpload}
disabled={!canEdit}
>
<Button
icon={<UploadOutlined />}
loading={uploading}
disabled={!canEdit}
>
<Upload accept="video/mp4,.mp4" showUploadList={false} beforeUpload={beforeUpload} disabled={!canEdit}>
<Button icon={<UploadOutlined />} loading={uploading} disabled={!canEdit}>
{cfg.video_url ? '更换视频' : '上传视频'}
</Button>
</Upload>
{cfg.video_url && (
<Button icon={<DeleteOutlined />} danger loading={uploading} disabled={!canEdit} onClick={removeVideo}>
<Button
icon={<DeleteOutlined />}
danger
loading={uploading}
disabled={!canEdit}
onClick={removeVideo}
>
</Button>
)}
<Text type="secondary">MP4H.264100MB</Text>
<Text type="secondary" style={{ fontSize: 12 }}>
MP4H.264100MB
</Text>
</Space>
<Button
type="primary"
loading={saving}
disabled={!canEdit}
onClick={save}
>
<Button type="primary" loading={saving} disabled={!canEdit} onClick={save}>
</Button>
<Text type="secondary">
{cfg.total_plays} {cfg.granted_plays}
</Text>
{!canEdit && <Text type="secondary"> operator / super_admin </Text>}
</Space>
</Space>
)}
</Card>
);
}
export default function GuideVideoConfig() {
return (
<>
<SceneConfig scene="coupon" />
<SceneConfig scene="comparison" />
</>
);
}
+1 -1
View File
@@ -165,7 +165,7 @@ export default function ConfigPage() {
},
{ key: 'welfare', label: '福利页', children: welfareConfig },
{ key: 'feedback-qr', label: '反馈二维码', children: <FeedbackQrConfig /> },
{ key: 'guide-video', label: '引导视频奖励', children: <GuideVideoConfig /> },
{ key: 'guide-video', label: '领券引导视频', children: <GuideVideoConfig /> },
]}
/>
</div>
-2
View File
@@ -4,7 +4,6 @@ import { useEffect, useRef, useState } from 'react';
import { usePathname, useRouter } from 'next/navigation';
import {
BarChartOutlined,
ControlOutlined,
DashboardOutlined,
DatabaseOutlined,
FileSearchOutlined,
@@ -106,7 +105,6 @@ const NAV_GROUPS: NavGroup[] = [
{ key: '/analytics-health', icon: <LineChartOutlined />, label: '埋点成功率' },
{ key: '/event-logs', icon: <DatabaseOutlined />, label: '埋点日志' },
{ key: '/audit-logs', icon: <FileSearchOutlined />, label: '审计日志' },
{ key: '/limit-whitelist', icon: <ControlOutlined />, label: '限制策略' },
],
},
];
File diff suppressed because it is too large Load Diff
+6 -75
View File
@@ -19,12 +19,10 @@ import {
CopyOutlined,
DownOutlined,
EditOutlined,
PlusCircleOutlined,
ReloadOutlined,
RightOutlined,
} from '@ant-design/icons';
import dayjs from 'dayjs';
import { useRouter } from 'next/navigation';
import { api, errMsg } from '@/lib/api';
import { formatUtcTime, utcDayjs } from '@/lib/format';
import type {
@@ -71,8 +69,8 @@ type IncidentStatus = 'open' | 'blocked';
const RULE_LIMITS: Record<RiskKind, { min: number; max: number; help: string }> = {
sms: {
min: 1,
max: 100000,
help: '统计成功下发;告警阈值与短信硬限制分别配置。',
max: 5,
help: '统计成功下发;最高5次,与现有每设备每小时发送上限一致。',
},
oneclick: {
min: 1,
@@ -81,8 +79,8 @@ const RULE_LIMITS: Record<RiskKind, { min: number; max: number; help: string }>
},
compare: {
min: 1,
max: 100000,
help: '同一账户按北京时间自然日累计;告警阈值与比价硬限制分别配置。',
max: 100,
help: '同一账户按北京时间自然日累计;最高100次,与比价每日上限一致。',
},
};
const utcTime = (value: string | null, withDate = true) =>
@@ -273,7 +271,6 @@ function DetailTable({
}
export default function RiskMonitorPage() {
const router = useRouter();
const { message, modal } = App.useApp();
const [summary, setSummary] = useState<RiskMonitorSummary | null>(null);
const [lists, setLists] = useState<Partial<Record<RiskKind, RiskIncidentPage>>>({});
@@ -600,40 +597,6 @@ export default function RiskMonitorPage() {
[lists, loadAll, message, modal],
);
const addToWhitelist = useCallback(
(row: RiskIncidentItem) => {
const isCompare = row.kind === 'compare';
const subjectValue = isCompare ? row.phone : row.subject_id;
if (!isCompare && subjectValue?.startsWith('legacy-ip:')) {
void message.error(
'旧客户端未上报真实设备 ID,无法加入设备白名单,请升级客户端后重试',
);
return;
}
if (!subjectValue) {
void message.error(
isCompare
? '该风险记录没有关联手机号,暂时无法加入白名单'
: '该风险记录没有设备 ID,暂时无法加入白名单',
);
return;
}
const ruleCode: Record<RiskKind, string> = {
sms: 'risk.sms.hourly',
oneclick: 'risk.oneclick.daily',
compare: 'risk.compare.daily',
};
const params = new URLSearchParams({
create: '1',
subject_type: isCompare ? 'phone' : 'device',
subject_value: subjectValue,
rule_code: ruleCode[row.kind],
});
router.push(`/limit-whitelist?${params.toString()}`);
},
[message, router],
);
const columns = useCallback(
(kind: RiskKind): ColumnsType<RiskIncidentItem> => {
const actionColumn = {
@@ -641,18 +604,9 @@ export default function RiskMonitorPage() {
key: 'actions',
align: 'right' as const,
fixed: 'right' as const,
width: 280,
width: 180,
render: (_: unknown, row: RiskIncidentItem) => {
const open = expanded.has(row.incident_id);
const whitelistUnavailableReason =
row.kind === 'compare'
? row.phone
? undefined
: '该风险记录没有关联手机号,暂时无法加入白名单'
: row.subject_id.startsWith('legacy-ip:')
? '旧客户端未上报真实设备 ID,无法加入设备白名单'
: undefined;
const canAddToWhitelist = !whitelistUnavailableReason;
return (
<span className={styles.actionGroup}>
<Button
@@ -664,20 +618,6 @@ export default function RiskMonitorPage() {
>
{open ? '收起' : '展开'}
</Button>
<Tooltip
title={whitelistUnavailableReason}
>
<span>
<Button
size="small"
icon={<PlusCircleOutlined />}
disabled={!canAddToWhitelist}
onClick={() => addToWhitelist(row)}
>
</Button>
</span>
</Tooltip>
{row.status === 'open' && (
<>
<Button
@@ -760,16 +700,7 @@ export default function RiskMonitorPage() {
actionColumn,
];
},
[
acting,
addToWhitelist,
copy,
detailLoading,
expanded,
revokeRestriction,
runAction,
toggle,
],
[acting, copy, detailLoading, expanded, revokeRestriction, runAction, toggle],
);
const cards = useMemo(() => {
+4 -20
View File
@@ -44,11 +44,6 @@ interface Props {
withdrawSource?: 'coin_cash' | 'invite_cash';
// 统计区字段集:withdraw(默认,提现详情:含提现细分) / ad(广告收益详情:只看看广告观看统计,对齐参考图 6 项)
statsVariant?: 'withdraw' | 'ad';
initialDateFrom?: string;
initialDateTo?: string;
appEnv?: 'prod' | 'test';
revenueScope?: 'business' | 'all';
feedScene?: 'comparison' | 'coupon' | 'welfare';
}
/** 用户看广告/提现详情:基本信息 + 互斥时间筛选 + 统计区(按 statsVariant 取字段集)+ 金币发放记录表。 */
@@ -57,17 +52,9 @@ export default function UserRewardPanel({
user,
withdrawSource,
statsVariant = 'withdraw',
initialDateFrom,
initialDateTo,
appEnv,
revenueScope = 'all',
feedScene,
}: Props) {
const hasInitialRange = Boolean(initialDateFrom && initialDateTo);
const [mode, setMode] = useState<'all' | 'range'>(hasInitialRange ? 'range' : 'all');
const [range, setRange] = useState<[Dayjs, Dayjs] | null>(() =>
hasInitialRange ? [dayjs(initialDateFrom), dayjs(initialDateTo)] : null,
);
const [mode, setMode] = useState<'all' | 'range'>('all'); // all=注册至今 / range=自定义区间
const [range, setRange] = useState<[Dayjs, Dayjs] | null>(null);
const [stats, setStats] = useState<UserRewardStats | null>(null);
const [statsLoading, setStatsLoading] = useState(false);
@@ -93,9 +80,6 @@ export default function UserRewardPanel({
params: {
...JSON.parse(paramsKey),
...(withdrawSource ? { withdraw_source: withdrawSource } : {}),
...(appEnv ? { app_env: appEnv } : {}),
revenue_scope: revenueScope,
...(feedScene ? { feed_scene: feedScene } : {}),
},
});
setStats(data);
@@ -104,7 +88,7 @@ export default function UserRewardPanel({
} finally {
setStatsLoading(false);
}
}, [userId, paramsKey, withdrawSource, appEnv, revenueScope, feedScene]);
}, [userId, paramsKey, withdrawSource]);
const loadRecords = useCallback(
async (p: number) => {
@@ -252,7 +236,7 @@ export default function UserRewardPanel({
</Descriptions>
<Text type="secondary" style={{ fontSize: 12 }}>
{statsVariant === 'ad'
? '统计继承广告收益页已查询的日期、环境、业务代码位和场景;次数仅统计成功发奖记录,信息流按奖励份数统计;Draw eCPM 按全部实际展示统计(含未发奖)。'
? '统计随上方时间筛选(现金余额除外,为当前快照);次数仅统计成功发奖记录,信息流按奖励份数统计;eCPM 为预估值。'
: '统计随上方时间筛选(现金余额除外,为当前快照);提现按申请提交时间统计;累计收益为已发金币按当前汇率折算,不代表实际已提现金额;eCPM 为预估值。'}
</Text>
+3 -82
View File
@@ -233,7 +233,7 @@ export interface UserRewardStats {
reward_video_avg_ecpm: number; // 平均激励视频 eCPM(分/千次)
reward_video_cash_cents: number; // 激励视频提现
feed_count: number; // 累计信息流广告数(份)
feed_avg_ecpm: number; // 全部 Draw/feed 实际展示的平均 eCPM(分/千次,含未发奖展示)
feed_avg_ecpm: number; // 平均信息流广告 eCPM(分/千次)
feed_cash_cents: number; // 信息流广告提现
}
@@ -414,14 +414,13 @@ export interface FeedbackQrConfig {
updated_at: string | null;
}
/** 领券等候浮层的「新手引导视频」配置(前 3 次用它替代广告,默认每次固定 100 金币)。
/** 领券等候浮层的「新手引导视频」配置(前 3 次用它替代广告,每次固定 120 金币)。
* 后台只开放 enabled + 换片;下面几个字段接口仍返回,但页面不展示、也不回传。 */
export interface GuideVideoConfig {
scene: 'coupon' | 'comparison';
enabled: boolean;
video_url: string | null; // /media/guide_video/xxx.mp4;null = 未配片(浮层照旧只放广告)
max_plays: number; // 每个账号前 N 次浮层放引导视频(服务端默认 3,后台不开放调整)
reward_coin: number; // 每次固定金币(服务端默认 100,播完 / 中途关闭都发)
reward_coin: number; // 每次固定金币(服务端默认 120,播完 / 中途关闭都发)
updated_at: string | null;
total_plays: number; // 只读统计:全站已播次数(后台不再展示)
granted_plays: number; // 只读统计:其中已发币次数(后台不再展示)
@@ -518,7 +517,6 @@ export interface ComparisonRecordDetail extends ComparisonRecordListItem {
skipped_dish_count: number | null;
device_id: string | null;
items: { name: string; qty?: number; specs?: string[] }[];
platforms: Record<string, unknown>[];
comparison_results: Record<string, unknown>[];
skipped_dish_names: string[];
device_manufacturer: string | null;
@@ -896,80 +894,3 @@ export interface HealthTrendPoint extends HealthMetrics {
export interface HealthBreakdownRow extends HealthMetrics {
key: string; // 维度值(event 名 / app_ver / oem);缺失为 "(unknown)"
}
// ===== 统一限制策略 / 白名单 =====
export type LimitSubjectType = 'phone' | 'device';
export type LimitPolicyMode =
| 'inherit'
| 'override'
| 'unlimited'
| 'suppress_alert';
export interface LimitRule {
code: string;
label: string;
group: string;
global_limit: number;
default_limit: number;
window_label: string;
subject_types: LimitSubjectType[];
allowed_modes: LimitPolicyMode[];
min_value: number;
max_value: number;
supports_reset: boolean;
alert_only: boolean;
}
export interface LimitDeviceCandidate {
device_id: string;
source: string;
source_label: string;
user_id: number | null;
username: string | null;
phone: string | null;
nickname: string | null;
device_model: string | null;
last_active_at: string;
}
export interface LimitOverride {
id: number;
subject_type: LimitSubjectType;
subject_value: string;
rule_code: string;
rule_label: string;
rule_group: string;
mode: LimitPolicyMode;
limit_value: number | null;
global_limit: number;
effective_limit: number | null;
enabled: boolean;
starts_at: string | null;
expires_at: string | null;
reset_at: string | null;
reason: string | null;
status: 'active' | 'scheduled' | 'expired' | 'disabled';
created_by_admin_id: number | null;
created_at: string;
updated_at: string;
}
export interface LimitOverrideList {
items: LimitOverride[];
total: number;
}
export interface LimitSubject {
subject_type: LimitSubjectType;
subject_value: string;
group_counts: Record<string, number>;
total_rules: number;
items: LimitOverride[];
created_at: string;
updated_at: string;
}
export interface LimitSubjectList {
items: LimitSubject[];
total: number;
}
+2 -7
View File
@@ -15,7 +15,6 @@ export function usePagedList<T>(
url: string,
filters: Record<string, unknown>,
initialPageSize = 20,
offsetParam: 'cursor' | 'offset' = 'cursor',
) {
const [items, setItems] = useState<T[]>([]);
const [total, setTotal] = useState(0);
@@ -32,11 +31,7 @@ export function usePagedList<T>(
requestSeq.current = seq;
setLoading(true);
try {
const params = {
...JSON.parse(filtersKey),
limit: ps,
[offsetParam]: (p - 1) * ps,
};
const params = { ...JSON.parse(filtersKey), limit: ps, cursor: (p - 1) * ps };
const { data } = await api.get<CursorPage<T>>(url, { params });
if (requestSeq.current !== seq) return; // 丢弃过期响应(快速切页/筛选)
setItems(data.items);
@@ -45,7 +40,7 @@ export function usePagedList<T>(
if (requestSeq.current === seq) setLoading(false);
}
},
[url, filtersKey, offsetParam],
[url, filtersKey],
);
// 筛选变化:回第 1 页重载