Compare commits

..

4 Commits

Author SHA1 Message Date
linkeyu 9d8fed49c8 fix(admin): label unfilled coupon ad revenue 2026-07-21 10:11:31 +08:00
linkeyu f25d5f0b17 fix(dashboard): consume backend comparison aggregates 2026-07-20 20:01:38 +08:00
linkeyu 30dad5d4e0 fix(admin): address dashboard review feedback 2026-07-20 10:36:06 +08:00
linkeyu 7ab623d6aa feat(admin): 优化后台看板及数据记录页 2026-07-19 11:58:36 +08:00
24 changed files with 1239 additions and 4102 deletions
-14
View File
@@ -32,20 +32,6 @@ server {
proxy_read_timeout 60s;
}
# 新手引导视频上传:视频比图片大一个量级,单独放宽到 100MB(对齐后端
# settings.GUIDE_VIDEO_MAX_BYTES)。不放宽全站上限,避免其它接口被大 body 打。
# 上传大文件耗时长,读超时同步放宽到 300s。
location = /admin/api/guide-video/video {
client_max_body_size 100m;
proxy_pass http://127.0.0.1:8771;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 300s;
proxy_send_timeout 300s;
proxy_request_buffering off;
}
# 用户上传媒体(上报截图 / 反馈截图 / 反馈二维码)由 App 后端(:8770)的 /media 托管。
# admin 页面要展示这些图,经此同域反代过去(免跨域 + 免 https 页面引 http 图被拦)。
# 前提:App 后端与本 admin 同机;若分机,把 127.0.0.1:8770 换成 App 后端可达地址。
@@ -15,8 +15,6 @@ interface UserOverviewResp {
id: number;
phone: string;
nickname: string | null;
is_high_risk: boolean;
high_risk_note: string | null;
status: string;
wechat_nickname: string | null;
created_at: string;
@@ -51,8 +49,6 @@ export default function UserAdRevenueDrawer({ open, onClose, userId, phone }: Pr
id: o.user.id,
phone: o.user.phone,
nickname: o.user.nickname,
is_high_risk: o.user.is_high_risk,
high_risk_note: o.user.high_risk_note,
status: o.user.status,
wechat_nickname: o.user.wechat_nickname, // 概览接口已返回微信昵称
wechat_avatar_url: null,
+27 -144
View File
@@ -66,101 +66,21 @@ const APP_TAG: Record<string, { color: string; label: string }> = {
test: { color: 'default', label: '测试应用' },
};
const REWARD_STATUS_HINT: Record<string, string> = {
granted: '已完成金币发放',
capped: '次数超限,未发金币',
ecpm_missing: '缺少有效 eCPM,未发金币',
too_short: '播放时长未达到发奖条件,未发金币',
closed_early: '用户提前关闭广告,未发金币',
};
const PLAYBACK_STATUS_TAG: Record<string, { color: string; label: string }> = {
completed: { color: 'green', label: '已完成' },
too_short: { color: 'gold', label: '观看时长不足' },
// 发奖状态 → 颜色 + 中文(含「不发金币的原因」:提前关闭/未满10秒/缺eCPM/次数超限)
const STATUS_TAG: Record<string, { color: string; label: string }> = {
granted: { color: 'green', label: '已发' },
capped: { color: 'orange', label: '次数超限' },
ecpm_missing: { color: 'red', label: '缺 eCPM' },
too_short: { color: 'gold', label: '未满10秒' },
closed_early: { color: 'default', label: '提前关闭' },
unknown: { color: 'default', label: '未知' },
};
const ZERO_REVENUE_REWARD_VIDEO_STATUSES = new Set(['closed_early', 'too_short']);
function rewardStatuses(row: AdRevenueRow): string[] {
if (row.sub_rewards?.length) return row.sub_rewards.map((reward) => reward.status);
return row.status ? [row.status] : [];
}
function effectiveRevenueYuan(row: AdRevenueRow): number {
if (
row.ad_type === 'reward_video'
&& rewardStatuses(row).some((status) => ZERO_REVENUE_REWARD_VIDEO_STATUSES.has(status))
) {
return 0;
}
return row.row_revenue_yuan ?? row.revenue_yuan;
}
function rewardStatusTag(row: AdRevenueRow) {
const statuses = rewardStatuses(row);
if (!row.has_reward || statuses.length === 0) {
return { color: 'default', label: '无记录', hint: '仅记录到广告展示,没有对应发奖记录。' };
}
const grantedCount = statuses.filter((status) => status === 'granted').length;
const reasonSummary = Object.entries(
statuses
.filter((status) => status !== 'granted')
.reduce<Record<string, number>>((counts, status) => {
counts[status] = (counts[status] ?? 0) + 1;
return counts;
}, {}),
)
.map(([status, count]) => `${REWARD_STATUS_HINT[status] ?? status} ${count}`)
.join('');
if (grantedCount === statuses.length) {
return { color: 'green', label: '已发', hint: `已完成金币发放${statuses.length > 1 ? ` ${statuses.length}` : ''}` };
}
if (grantedCount > 0) {
return {
color: 'blue',
label: '部分已发',
hint: `已发 ${grantedCount} 条,未发 ${statuses.length - grantedCount}${reasonSummary ? `${reasonSummary}` : ''}`,
};
}
return { color: 'default', label: '未发', hint: reasonSummary ? `${reasonSummary}` : '未发放金币。' };
}
function playbackStatusTag(row: AdRevenueRow) {
const statuses = rewardStatuses(row);
if (statuses.length === 0) {
return row.has_impression
? { color: 'blue', label: '仅展示', hint: '记录到广告展示,但没有对应的播放结果。' }
: { color: 'default', label: '无记录', hint: '没有可用的广告播放记录。' };
}
const playbackCounts = statuses.reduce<Record<string, number>>((counts, status) => {
const playbackStatus =
status === 'too_short' || status === 'closed_early'
? status
: status === 'granted' || status === 'capped' || status === 'ecpm_missing'
? 'completed'
: 'unknown';
counts[playbackStatus] = (counts[playbackStatus] ?? 0) + 1;
return counts;
}, {});
const entries = Object.entries(playbackCounts);
if (entries.length === 1) {
const [status, count] = entries[0];
const tag = PLAYBACK_STATUS_TAG[status];
return {
...tag,
hint: `${tag.label}${count > 1 ? ` ${count}` : ''}`,
};
}
const hint = entries
.map(([status, count]) => `${PLAYBACK_STATUS_TAG[status].label} ${count}`)
.join('');
return { color: 'purple', label: '部分完成', hint: `${hint}` };
}
const STATUS_HINT: Record<string, string> = {
granted: '已满足当前客户端发奖条件并完成金币发放。',
too_short: '旧版 Draw 信息流观看不足 10 秒,不发金币;新版按观看比例发放时会记为已发。',
closed_early: '用户在达到发奖条件前主动关闭,不发金币。',
capped: '已达到次数上限,不再发金币。',
ecpm_missing: '缺少有效 eCPM,无法计算金币。',
};
const fmtFactorRange = (a: number | null, b: number | null) => {
if (a == null) return '-';
@@ -380,8 +300,6 @@ export default function AdRevenueReportPage() {
const { message } = App.useApp();
const [range, setRange] = useState<[Dayjs, Dayjs]>([dayjs().subtract(1, 'day'), dayjs().subtract(1, 'day')]);
const [userId, setUserId] = useState<number | null>(null);
const [appEnv, setAppEnv] = useState<'prod' | 'test' | 'all'>('prod');
const [revenueScope, setRevenueScope] = useState<'business' | 'all'>('business');
const [adType, setAdType] = useState<string | undefined>();
// 「场景」作为后端全局筛选(feed_scene):同时影响明细 / 合计 / 趋势,与「用户 / 类型」一致,点「查询」生效。
const [scene, setScene] = useState<string | undefined>();
@@ -415,8 +333,6 @@ export default function AdRevenueReportPage() {
date_from: from,
date_to: to,
user_id: userId ?? undefined,
app_env: appEnv === 'all' ? undefined : appEnv,
revenue_scope: revenueScope,
ad_type: adType ?? undefined,
feed_scene: scene ?? undefined,
granularity: gran,
@@ -458,7 +374,7 @@ export default function AdRevenueReportPage() {
setLoading(false);
}
},
[range, userId, appEnv, revenueScope, adType, scene, granularity, limit, sortBy],
[range, userId, adType, scene, granularity, limit, sortBy],
);
useEffect(() => {
@@ -558,25 +474,19 @@ export default function AdRevenueReportPage() {
width: 110,
align: 'right',
// 一次比价/领券聚合行用 row_revenue_yuan(该次发奖广告 eCPM 折算之和),其它行用展示侧 revenue_yuan
// 激励视频提前关闭/时长不足时防御性显示 0,与后端有效收益口径一致。
render: (_v: number, r: AdRevenueRow) => effectiveRevenueYuan(r).toFixed(4),
},
{
title: '发奖状态',
key: 'reward_status',
width: 100,
render: (_: unknown, row: AdRevenueRow) => {
const tag = rewardStatusTag(row);
return <Tooltip title={tag.hint}><Tag color={tag.color}>{tag.label}</Tag></Tooltip>;
render: (v: number, r: AdRevenueRow) => {
const rev = r.row_revenue_yuan ?? v;
return rev.toFixed(4);
},
},
{
title: '广告播放状态',
key: 'playback_status',
width: 120,
render: (_: unknown, row: AdRevenueRow) => {
const tag = playbackStatusTag(row);
return <Tooltip title={tag.hint}><Tag color={tag.color}>{tag.label}</Tag></Tooltip>;
title: '发奖状态',
dataIndex: 'status',
width: 100,
render: (s: string | null) => {
if (!s) return <Tooltip title="仅记录广告展示,没有对应发奖事件。"><Tag></Tag></Tooltip>;
const t = STATUS_TAG[s] ?? { color: 'default', label: s };
return <Tooltip title={STATUS_HINT[s]}><Tag color={t.color}>{t.label}</Tag></Tooltip>;
},
},
{
@@ -618,8 +528,7 @@ export default function AdRevenueReportPage() {
'ecpm_yuan',
'revenue_yuan',
'actual_coin',
'reward_status',
'playback_status',
'status',
'ad_type',
'app_env',
'our_code_id',
@@ -705,14 +614,13 @@ export default function AdRevenueReportPage() {
<br />
<br />
广(onAdShow) eCPM ( ÷1000
);<b> 0 </b>, eCPM 穿,
),<b>广</b>;穿/,,
<b>穿</b> 0广ID / ,
<br />
<br />
<b>穿(T+1)</b>穿 GroMore API(,):
<b>穿</b>= revenue<b>API</b>= ADN 穿//,
<b></b>(//);穿
+ ;广
<b></b>(//);,
</div>
}
>
@@ -747,31 +655,6 @@ export default function AdRevenueReportPage() {
style={{ width: 130 }}
/>
</Space>
<Space size={6}>
<Typography.Text type="secondary"></Typography.Text>
<Select
value={appEnv}
onChange={setAppEnv}
style={{ width: 130 }}
options={[
{ value: 'prod', label: '正式(prod)' },
{ value: 'test', label: '测试(dev)' },
{ value: 'all', label: '全部' },
]}
/>
</Space>
<Space size={6}>
<Typography.Text type="secondary"></Typography.Text>
<Select
value={revenueScope}
onChange={setRevenueScope}
style={{ width: 150 }}
options={[
{ value: 'business', label: '业务代码位' },
{ value: 'all', label: '全部代码位' },
]}
/>
</Space>
<Space size={6}>
<Typography.Text type="secondary"></Typography.Text>
<Select
+95 -67
View File
@@ -1,6 +1,6 @@
'use client';
import { useEffect, useState } from 'react';
import { useEffect, useMemo, useState } from 'react';
import type { CSSProperties, ReactNode } from 'react';
import {
App, Button, Card, Col, Collapse, DatePicker, Descriptions, Divider, Drawer, Input, InputNumber,
@@ -9,13 +9,8 @@ import {
import type { ColumnsType } from 'antd/es/table';
import dayjs, { type Dayjs } from 'dayjs';
import { api, errMsg } from '@/lib/api';
import { formatWallTime, yuan } from '@/lib/format';
import type {
ComparisonRecordDetail,
ComparisonRecordListItem,
ComparisonRecordsSummary,
CursorPage,
} from '@/lib/types';
import { formatWallTime, percentile, yuan } from '@/lib/format';
import type { ComparisonRecordDetail, ComparisonRecordListItem, CursorPage } from '@/lib/types';
const { RangePicker } = DatePicker;
@@ -110,11 +105,8 @@ export default function ComparisonRecordsPage() {
date_from: dayjs().subtract(1, 'day').format('YYYY-MM-DD'),
date_to: dayjs().subtract(1, 'day').format('YYYY-MM-DD'),
});
const [items, setItems] = useState<ComparisonRecordListItem[]>([]);
const [total, setTotal] = useState(0);
const [overview, setOverview] = useState<ComparisonRecordsSummary | null>(null);
const [listLoading, setListLoading] = useState(false);
const [summaryLoading, setSummaryLoading] = useState(false);
const [allItems, setAllItems] = useState<ComparisonRecordListItem[]>([]);
const [loading, setLoading] = useState(false);
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(20);
// LLM 单价(元/百万 token),本地持久化;仅用于前端估算成本,不入库、不影响其它页面
@@ -133,8 +125,7 @@ export default function ComparisonRecordsPage() {
const [detail, setDetail] = useState<ComparisonRecordDetail | null>(null);
const [detailLoading, setDetailLoading] = useState(false);
const search = () => {
setPage(1);
const search = () =>
setApplied({
date_from: range[0].format('YYYY-MM-DD'),
date_to: range[1].format('YYYY-MM-DD'),
@@ -144,7 +135,6 @@ export default function ComparisonRecordsPage() {
store: store.trim() || undefined,
product: product.trim() || undefined,
});
};
const reset = () => {
setUserId(null);
@@ -153,7 +143,6 @@ export default function ComparisonRecordsPage() {
setStore('');
setProduct('');
const yesterday = dayjs().subtract(1, 'day');
setPage(1);
setRange([yesterday, yesterday]);
setApplied({
date_from: yesterday.format('YYYY-MM-DD'),
@@ -163,50 +152,49 @@ export default function ComparisonRecordsPage() {
useEffect(() => {
let alive = true;
const loadPage = async () => {
setListLoading(true);
const loadAll = async () => {
setLoading(true);
try {
const { data } = await api.get<CursorPage<ComparisonRecordListItem>>(
'/admin/api/comparison-records',
{ params: { ...applied, limit: pageSize, cursor: (page - 1) * pageSize } },
);
const serverFilters = { ...applied };
delete serverFilters.date_from;
delete serverFilters.date_to;
const rows: ComparisonRecordListItem[] = [];
let cursor = 0;
for (let pageIndex = 0; pageIndex < 200; pageIndex += 1) {
const { data } = await api.get<CursorPage<ComparisonRecordListItem>>(
'/admin/api/comparison-records',
{ params: { ...serverFilters, limit: 100, cursor } },
);
rows.push(...data.items);
if (data.next_cursor == null || data.items.length === 0) break;
cursor = data.next_cursor;
}
if (alive) {
setItems(data.items);
setTotal(data.total ?? 0);
setAllItems(rows);
setPage(1);
}
} catch (e) {
if (alive) message.error(errMsg(e));
} finally {
if (alive) setListLoading(false);
if (alive) setLoading(false);
}
};
loadPage();
return () => {
alive = false;
};
}, [applied, message, page, pageSize]);
useEffect(() => {
let alive = true;
const loadSummary = async () => {
setSummaryLoading(true);
try {
const { data } = await api.get<ComparisonRecordsSummary>(
'/admin/api/comparison-records/summary',
{ params: applied },
);
if (alive) setOverview(data);
} catch (e) {
if (alive) message.error(errMsg(e));
} finally {
if (alive) setSummaryLoading(false);
}
};
loadSummary();
loadAll();
return () => {
alive = false;
};
}, [applied, message]);
const filteredItems = useMemo(() => {
const from = String(applied.date_from ?? '');
const to = String(applied.date_to ?? '');
return allItems.filter((item) => {
const date = dayjs(item.created_at).format('YYYY-MM-DD');
return (!from || date >= from) && (!to || date <= to);
});
}, [allItems, applied]);
const total = filteredItems.length;
const items = filteredItems.slice((page - 1) * pageSize, page * pageSize);
const onChange = (nextPage: number, nextPageSize: number) => {
setPageSize(nextPageSize);
setPage(nextPageSize === pageSize ? nextPage : 1);
@@ -230,6 +218,46 @@ export default function ComparisonRecordsPage() {
setDetailLoading(false);
};
const overview = useMemo(() => {
const completed = filteredItems.filter(
(item) => item.status === 'success' || item.status === 'failed',
);
const cancelled = filteredItems.filter((item) => item.status === 'cancelled');
const success = filteredItems.filter((item) => item.status === 'success');
const successRateDenominator = filteredItems.length - cancelled.length;
const completedDurations = completed
.map((item) => item.total_ms)
.filter((value): value is number => value != null);
const cancelledDurations = cancelled
.map((item) => item.total_ms)
.filter((value): value is number => value != null);
const costs = filteredItems
.map((item) => item.llm_cost_yuan)
.filter((value): value is number => value != null);
const avg = (values: number[]) =>
values.length ? values.reduce((sum, value) => sum + value, 0) / values.length : null;
return {
started: filteredItems.length,
completed: completed.length,
success: success.length,
successRate: successRateDenominator ? success.length / successRateDenominator : null,
avgTokenCost: avg(costs),
lowerPriceRate: success.length
? success.filter((item) => (item.saved_amount_cents ?? 0) > 0).length / success.length
: null,
avgMs: avg(completedDurations),
p5Ms: percentile(completedDurations, 0.05),
p50Ms: percentile(completedDurations, 0.5),
p95Ms: percentile(completedDurations, 0.95),
p99Ms: percentile(completedDurations, 0.99),
cancelled: cancelled.length,
cancelledRate: filteredItems.length ? cancelled.length / filteredItems.length : null,
cancelledP5Ms: percentile(cancelledDurations, 0.05),
cancelledP50Ms: percentile(cancelledDurations, 0.5),
cancelledP95Ms: percentile(cancelledDurations, 0.95),
};
}, [filteredItems]);
const columns: ColumnsType<ComparisonRecordListItem> = [
{ title: '时间', dataIndex: 'created_at', width: 150, render: (v: string) => formatWallTime(v) },
{
@@ -396,28 +424,28 @@ export default function ComparisonRecordsPage() {
</Space>
</Card>
<Card size="small" style={{ marginBottom: 16 }} loading={summaryLoading}>
<Card size="small" style={{ marginBottom: 16 }} loading={loading}>
<Divider orientation="left" plain style={{ marginTop: 0 }}></Divider>
<Row gutter={[16, 16]}>
<Col xs={12} md={6}><Statistic title="比价发起数" value={overview?.started ?? 0} /></Col>
<Col xs={12} md={6}><Statistic title="比价完成数" value={overview?.completed ?? 0} /></Col>
<Col xs={12} md={6}><Statistic title="比价成功次数" value={overview?.success ?? 0} /></Col>
<Col xs={12} md={6}><Statistic title="比价成功率" value={fmtRate(overview?.success_rate ?? null)} /></Col>
<Col xs={12} md={6}><Statistic title="平均 TOKEN 成本" value={overview?.avg_token_cost ?? '-'} precision={4} prefix="¥" /></Col>
<Col xs={12} md={6}><Statistic title="比出更低价率" value={fmtRate(overview?.lower_price_rate ?? null)} /></Col>
<Col xs={12} md={6}><Statistic title="耗时平均数" value={fmtMs(overview?.avg_duration_ms ?? null)} /></Col>
<Col xs={12} md={6}><Statistic title="耗时 5 分位" value={fmtMs(overview?.p5_duration_ms ?? null)} /></Col>
<Col xs={12} md={6}><Statistic title="耗时 50 分位" value={fmtMs(overview?.p50_duration_ms ?? null)} /></Col>
<Col xs={12} md={6}><Statistic title="耗时 95 分位" value={fmtMs(overview?.p95_duration_ms ?? null)} /></Col>
<Col xs={12} md={6}><Statistic title="耗时 99 分位" value={fmtMs(overview?.p99_duration_ms ?? null)} /></Col>
<Col xs={12} md={6}><Statistic title="比价发起数" value={overview.started} /></Col>
<Col xs={12} md={6}><Statistic title="比价完成数" value={overview.completed} /></Col>
<Col xs={12} md={6}><Statistic title="比价成功次数" value={overview.success} /></Col>
<Col xs={12} md={6}><Statistic title="比价成功率" value={fmtRate(overview.successRate)} /></Col>
<Col xs={12} md={6}><Statistic title="平均 TOKEN 成本" value={overview.avgTokenCost ?? '-'} precision={4} prefix="¥" /></Col>
<Col xs={12} md={6}><Statistic title="比出更低价率" value={fmtRate(overview.lowerPriceRate)} /></Col>
<Col xs={12} md={6}><Statistic title="耗时平均数" value={fmtMs(overview.avgMs)} /></Col>
<Col xs={12} md={6}><Statistic title="耗时 5 分位" value={fmtMs(overview.p5Ms)} /></Col>
<Col xs={12} md={6}><Statistic title="耗时 50 分位" value={fmtMs(overview.p50Ms)} /></Col>
<Col xs={12} md={6}><Statistic title="耗时 95 分位" value={fmtMs(overview.p95Ms)} /></Col>
<Col xs={12} md={6}><Statistic title="耗时 99 分位" value={fmtMs(overview.p99Ms)} /></Col>
</Row>
<Divider orientation="left" plain>退</Divider>
<Row gutter={[16, 16]}>
<Col flex="1 1 180px"><Statistic title="中途退出次数" value={overview?.cancelled ?? 0} /></Col>
<Col flex="1 1 180px"><Statistic title="中途退出率" value={fmtRate(overview?.cancelled_rate ?? null)} /></Col>
<Col flex="1 1 180px"><Statistic title="退出耗时 5 分位" value={fmtMs(overview?.cancelled_p5_ms ?? null)} /></Col>
<Col flex="1 1 180px"><Statistic title="退出耗时 50 分位" value={fmtMs(overview?.cancelled_p50_ms ?? null)} /></Col>
<Col flex="1 1 180px"><Statistic title="退出耗时 95 分位" value={fmtMs(overview?.cancelled_p95_ms ?? null)} /></Col>
<Col xs={12} md={6}><Statistic title="中途退出次数" value={overview.cancelled} /></Col>
<Col xs={12} md={6}><Statistic title="中途退出率" value={fmtRate(overview.cancelledRate)} /></Col>
<Col xs={12} md={6}><Statistic title="退出耗时 5 分位" value={fmtMs(overview.cancelledP5Ms)} /></Col>
<Col xs={12} md={6}><Statistic title="退出耗时 50 分位" value={fmtMs(overview.cancelledP50Ms)} /></Col>
<Col xs={12} md={6}><Statistic title="退出耗时 95 分位" value={fmtMs(overview.cancelledP95Ms)} /></Col>
</Row>
</Card>
@@ -425,7 +453,7 @@ export default function ComparisonRecordsPage() {
rowKey="id"
columns={columns}
dataSource={items}
loading={listLoading}
loading={loading}
pagination={{
current: page,
pageSize,
-222
View File
@@ -1,222 +0,0 @@
'use client';
import { useEffect, useState } from 'react';
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';
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;
/**
* 领券等候浮层的「新手引导视频」配置。
*
* 用户点首页「一键自动领取」→ 出等候浮层,浮层下方那块位置**前 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 canEdit = canDo(['operator']);
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');
sync(data);
} finally {
setLoading(false);
}
};
useEffect(() => {
load();
}, []);
const save = async () => {
setSaving(true);
try {
const { data } = await api.patch<GuideCfg>('/admin/api/guide-video', { enabled });
sync(data);
message.success('已保存,用户下一次进入领券浮层即生效');
} catch (e) {
message.error(errMsg(e));
} finally {
setSaving(false);
}
};
// antd Upload:beforeUpload 里自行 POST(multipart),返回 false 阻止其默认上传。
const beforeUpload = (file: File) => {
// 有些系统给 .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;
}
if (file.size > MAX_BYTES) {
message.error('视频不能超过 100MB');
return Upload.LIST_IGNORE;
}
void uploadVideo(file);
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');
sync(data);
message.success('已移除引导视频,领券浮层恢复为只放广告');
} catch (e) {
message.error(errMsg(e));
} finally {
setUploading(false);
}
};
return (
<Card
size="small"
title="领券引导视频(App 领券等候浮层,前 3 次替代广告)"
style={{ marginBottom: 16 }}
extra={
cfg?.updated_at ? (
<Text type="secondary" style={{ fontSize: 12 }}>
{new Date(cfg.updated_at).toLocaleString('zh-CN')}
</Text>
) : null
}
>
<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>
<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: 360 }}>
<Space>
<span></span>
<Switch checked={enabled} disabled={!canEdit} onChange={setEnabled} />
{!enabled && <Tag color="orange"></Tag>}
</Space>
<Space wrap>
<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>
)}
<Text type="secondary" style={{ fontSize: 12 }}>
MP4H.264100MB
</Text>
</Space>
<Button type="primary" loading={saving} disabled={!canEdit} onClick={save}>
</Button>
{!canEdit && <Text type="secondary"> operator / super_admin </Text>}
</Space>
</Space>
)}
</Card>
);
}
-2
View File
@@ -6,7 +6,6 @@ import { api, errMsg } from '@/lib/api';
import HomeMarqueeSeeds from './HomeMarqueeSeeds';
import HomeStatsConfig from './HomeStatsConfig';
import FeedbackQrConfig from './FeedbackQrConfig';
import GuideVideoConfig from './GuideVideoConfig';
interface ConfigItem {
key: string;
@@ -165,7 +164,6 @@ export default function ConfigPage() {
},
{ key: 'welfare', label: '福利页', children: welfareConfig },
{ key: 'feedback-qr', label: '反馈二维码', children: <FeedbackQrConfig /> },
{ key: 'guide-video', label: '领券引导视频', children: <GuideVideoConfig /> },
]}
/>
</div>
+22 -156
View File
@@ -10,11 +10,9 @@ import {
DatePicker,
Divider,
Input,
Popover,
Row,
Select,
Space,
Spin,
Statistic,
Table,
Tag,
@@ -74,23 +72,9 @@ interface CouponDataRow {
app_env: string | null;
started_at: string;
claimed_count: number | null;
point_success_count: number | null;
point_total_count: number | null;
// 兼容旧后端的内嵌明细;新后端不再返回,改为点击后按 trace 加载。
point_details?: CouponPointDetail[];
trace_url: string | null;
ad_revenue_yuan: number | null; // 本次领券看的信息流广告预估收益(元);未填充为 null
}
interface CouponPointDetail {
coupon_id: string;
coupon_name: string | null;
status: string;
reason: string | null;
}
interface CouponPointDetailsOut {
trace_id: string;
items: CouponPointDetail[];
}
interface CouponDataReport {
date_from: string;
date_to: string;
@@ -132,103 +116,6 @@ const STATUS_TAG: Record<string, { color: string; label: string }> = {
abandoned: { color: 'orange', label: '中途退出' },
};
const POINT_STATUS_TAG: Record<string, { color: string; label: string }> = {
success: { color: 'success', label: '成功' },
already_claimed: { color: 'processing', label: '已领' },
failed: { color: 'error', label: '失败' },
skipped: { color: 'default', label: '跳过' },
};
function PointScorePopover({ row }: { row: CouponDataRow }) {
const { message } = App.useApp();
const [details, setDetails] = useState<CouponPointDetail[] | null>(row.point_details ?? null);
const [loading, setLoading] = useState(false);
const [loadError, setLoadError] = useState<string | null>(null);
if (row.point_success_count == null || row.point_total_count == null || row.point_total_count <= 0) {
return <Typography.Text type="secondary">-</Typography.Text>;
}
const score = `${row.point_success_count}/${row.point_total_count}`;
const scoreWithRate = `${score}${(
row.point_success_count / row.point_total_count * 100
).toFixed(1)}%`;
const scoreColor =
row.point_success_count === row.point_total_count
? STATUS_TAG.completed.color
: STATUS_TAG.abandoned.color;
const loadDetails = async () => {
if (details !== null || loading) return;
setLoading(true);
setLoadError(null);
try {
const response = await api.get<CouponPointDetailsOut>('/admin/api/coupon-data/point-details', {
params: { trace_id: row.trace_id },
});
setDetails(response.data.items);
} catch (error) {
const errorMessage = errMsg(error);
setLoadError(errorMessage);
message.error(errorMessage);
} finally {
setLoading(false);
}
};
return (
<Popover
trigger="click"
placement="bottomLeft"
title={`点位明细(${score}`}
onOpenChange={(open) => {
if (open) void loadDetails();
}}
content={(
<div style={{ width: 380, maxHeight: 360, overflowY: 'auto' }}>
{loading || (details === null && loadError === null) ? (
<Spin size="small" style={{ display: 'block', margin: '24px auto' }} />
) : loadError ? (
<Typography.Text type="danger"></Typography.Text>
) : details && details.length > 0 ? details.map((point, index) => {
const status = POINT_STATUS_TAG[point.status] ?? {
color: 'default', label: point.status,
};
return (
<div
key={`${point.coupon_id}-${index}`}
style={{
padding: '8px 0',
borderBottom: index < details.length - 1 ? '1px solid #f0f0f0' : undefined,
}}
>
<div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
<div style={{ flex: 1, minWidth: 0 }}>
<Typography.Text>{point.coupon_name || point.coupon_id}</Typography.Text>
{point.coupon_name ? (
<div><Typography.Text type="secondary">{point.coupon_id}</Typography.Text></div>
) : null}
</div>
<Tag color={status.color} style={{ marginInlineEnd: 0 }}>{status.label}</Tag>
</div>
{point.reason ? (
<div style={{ marginTop: 4 }}>
<Typography.Text type="danger">{point.reason}</Typography.Text>
</div>
) : null}
</div>
);
}) : (
<Typography.Text type="secondary"></Typography.Text>
)}
</div>
)}
>
<Button type="link" size="small" style={{ height: 'auto', padding: 0, color: scoreColor }}>
{scoreWithRate}
</Button>
</Popover>
);
}
// ms → "1.5s"(空值显示 -)
const fmtSec = (ms: number | null | undefined): string =>
ms == null ? '-' : `${(ms / 1000).toFixed(1)}s`;
@@ -250,6 +137,11 @@ const slotRateMean = (rows: CouponSlotRow[]): number | null => {
return rates.length ? rates.reduce((a, b) => a + b, 0) / rates.length : null;
};
// 汇总卡成功率口径 tooltip 文案
const POINT_RATE_HINT =
'点位成功率(合计):当前区间内全部券成功率的算术平均(每张券等权);' +
'单券成功率=成功(含已领)÷尝试(不含跳过),源自领券每券记录。';
// 按券表:coupon_id 平台 → 中文
const SLOT_PLATFORM: Record<string, string> = {
'meituan-waimai': '美团',
@@ -605,10 +497,20 @@ export default function CouponDataPage() {
render: (v: number | null) => fmtSec(v),
},
{
title: '单券成功率',
title: '点位成功率',
key: 'point_success_rate',
width: 150,
render: (_: unknown, r: CouponDataRow) => <PointScorePopover row={r} />,
width: 110,
render: (_: unknown, r: CouponDataRow) => (
<Tooltip title="当前接口未返回本场应领点位及逐点结果,前端不使用全局均值冒充本场成功率。">
{r.trace_url ? (
<a href={r.trace_url} target="_blank" rel="noreferrer">
</a>
) : (
<Typography.Text type="secondary"></Typography.Text>
)}
</Tooltip>
),
},
{
title: '广告收益',
@@ -695,10 +597,6 @@ export default function CouponDataPage() {
const successDenominator = summary ? Math.max(0, summary.started_count - abandonedCount) : 0;
const couponSuccessRate =
summary && successDenominator > 0 ? summary.completed_count / successDenominator : null;
const validCouponSlots = couponSlots.filter((r) => r.success_rate != null);
const pointSuccessRate = slotRateMean(validCouponSlots);
const pointSucceededTotal = validCouponSlots.reduce((total, r) => total + r.succeeded, 0);
const pointTriedTotal = validCouponSlots.reduce((total, r) => total + r.tried, 0);
const items = data?.items ?? [];
return (
@@ -816,19 +714,8 @@ export default function CouponDataPage() {
<Statistic
title={
<span>
{' '}
<Tooltip
overlayStyle={{ maxWidth: 520 }}
title={
<div>
<div> ÷退</div>
<div style={{ marginTop: 6 }}>
{summary.completed_count} ÷{summary.started_count}{abandonedCount}
{fmtPct(couponSuccessRate)}
</div>
</div>
}
>
{' '}
<Tooltip title="领券完成数 ÷(领券发起数-中途退出数)">
<InfoCircleOutlined style={{ color: '#999' }} />
</Tooltip>
</span>
@@ -841,33 +728,12 @@ export default function CouponDataPage() {
title={
<span>
{' '}
<Tooltip
overlayStyle={{ maxWidth: 560 }}
title={
<div>
<div></div>
<div>÷ </div>
<div style={{ marginTop: 6 }}>
{validCouponSlots.length}
</div>
{validCouponSlots.map((slot) => (
<div key={slot.coupon_id}>
{slot.coupon_name || slot.coupon_id}{slot.succeeded} ÷ {slot.tried}
{fmtPct(slot.success_rate)}
</div>
))}
<div style={{ marginTop: 6 }}>
{fmtPct(pointSuccessRate)}/
{pointSucceededTotal}/{pointTriedTotal}
</div>
</div>
}
>
<Tooltip title={POINT_RATE_HINT}>
<InfoCircleOutlined style={{ color: '#999' }} />
</Tooltip>
</span>
}
value={fmtPct(pointSuccessRate)}
value={fmtPct(slotRateMean(couponSlots))}
/>
</Col>
<Col flex="1 1 0">
+7 -3
View File
@@ -499,7 +499,12 @@ export default function DashboardPage() {
const tokenCostYuan = periodData?.comparison.token_cost_total_yuan ?? null;
const couponRewardCoinTotal = periodData?.coins.coupon_reward_coin_total;
const comparisonRewardCoinTotal = periodData?.coins.comparison_reward_coin_total;
const regularTaskCoinTotal = periodData?.coins.regular_task_coin_total;
const signinCoinTotal = periodData?.coins.signin_coin_total;
const signinBoostCoinTotal = periodData?.coins.signin_boost_coin_total;
const taskCoinTotal = periodData?.coins.task_coin_total;
const regularTaskCoinTotal =
periodData?.coins.regular_task_coin_total ??
((signinCoinTotal ?? 0) + (signinBoostCoinTotal ?? 0) + (taskCoinTotal ?? 0));
const cpsAvailable = data?.cps.available === true;
const meituanCpsCommissionCents = data?.cps.meituan_commission_cents;
const jdCpsCommissionCents = data?.cps.jd_commission_cents;
@@ -1065,14 +1070,13 @@ export default function DashboardPage() {
value={fmtInt(periodData?.coins.reward_video_coin_total)}
delta={rewardVideoCoinRatio.value}
deltaTone={rewardVideoCoinRatio.tone}
hint="普通看视频与历史签到膨胀的实发金币之和,不再重复计入领券奖励或常规任务。"
hint="独立统计看视频发放,不再重复计入领券奖励。"
/>
<StatCard
title="常规任务金币"
value={fmtInt(regularTaskCoinTotal)}
delta={regularTaskCoinRatio.value}
deltaTone={regularTaskCoinRatio.tone}
hint="每日签到、通知/其他任务、上报更低价和反馈采纳的实发金币之和。"
/>
<StatCard
title="本期提现金额"
+2 -208
View File
@@ -4,15 +4,11 @@ import { useEffect, useState } from 'react';
import type { ColumnsType } from 'antd/es/table';
import type { SorterResult } from 'antd/es/table/interface';
import {
App,
Button,
Card,
DatePicker,
Form,
Image,
Input,
InputNumber,
Modal,
Select,
Space,
Statistic,
@@ -21,12 +17,9 @@ import {
Typography,
} from 'antd';
import type { Dayjs } from 'dayjs';
import { api, errMsg } from '@/lib/api';
import { api } from '@/lib/api';
import { canDo } from '@/lib/auth';
import { formatWallTime } from '@/lib/format';
import { refreshReviewBadge } from '@/lib/reviewBadge';
import { BULK_REVIEW_MAX, bulkFailureReasonText, failedReviewIds } from '@/lib/bulkAction';
import type { BulkReviewResult } from '@/lib/bulkAction';
import { usePagedList } from '@/lib/usePagedList';
import type { Feedback, FeedbackSummary } from '@/lib/types';
import FeedbackHandleDrawer from './FeedbackHandleDrawer';
@@ -34,7 +27,6 @@ import UserRecordsDrawer from '@/components/UserRecordsDrawer';
const { Text, Paragraph } = Typography;
const { RangePicker } = DatePicker;
const REWARD_MAX = 10000;
// 截图是 app-server 的 /media 相对路径,本地由 :8770 提供(NEXT_PUBLIC_MEDIA_BASE);生产同域走 nginx 代理。
const MEDIA_BASE = process.env.NEXT_PUBLIC_MEDIA_BASE || '';
@@ -162,8 +154,6 @@ const RECORD_COLUMNS: ColumnsType<Feedback> = [
];
export default function FeedbacksPage() {
const { message } = App.useApp();
const [bulkForm] = Form.useForm();
// 筛选草稿:点「查询」才应用(避免输入即刷新)
const [status, setStatus] = useState<string | undefined>();
const [source, setSource] = useState<string | undefined>();
@@ -180,19 +170,6 @@ export default function FeedbacksPage() {
usePagedList<Feedback>('/admin/api/feedbacks', filters);
const canReview = canDo(['operator']);
const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
const [bulkAction, setBulkAction] = useState<'approve' | 'reject' | null>(null);
const [bulkSubmitting, setBulkSubmitting] = useState(false);
const selectedFeedbacks = items.filter(
(item) => selectedRowKeys.includes(item.id) && isPending(item.status),
);
useEffect(() => {
const visiblePendingIds = new Set(
items.filter((item) => isPending(item.status)).map((item) => item.id),
);
setSelectedRowKeys((keys) => keys.filter((id) => visiblePendingIds.has(id)));
}, [items]);
const [summary, setSummary] = useState<FeedbackSummary | null>(null);
const loadSummary = async () => {
@@ -258,61 +235,6 @@ export default function FeedbacksPage() {
const sortOrderOf = (field: SortField) =>
sortBy === field ? (sortOrder === 'asc' ? 'ascend' : 'descend') : null;
const openBulkModal = (action: 'approve' | 'reject') => {
if (!selectedFeedbacks.length) return;
if (selectedFeedbacks.length > BULK_REVIEW_MAX) {
message.warning(`单次最多审核 ${BULK_REVIEW_MAX} 条反馈`);
return;
}
bulkForm.resetFields();
setBulkAction(action);
};
const submitBulkReview = async () => {
if (!bulkAction || !selectedFeedbacks.length) return;
const values = await bulkForm.validateFields();
const targets = selectedFeedbacks;
setBulkSubmitting(true);
try {
const { data } = await api.post<BulkReviewResult>(
`/admin/api/feedbacks/bulk/${bulkAction}`,
bulkAction === 'approve'
? {
ids: targets.map((item) => item.id),
reward_coins: values.reward_coins,
note: values.note?.trim() || null,
reply: values.reply?.trim() || null,
}
: {
ids: targets.map((item) => item.id),
reason: values.reason.trim(),
note: values.note?.trim() || null,
reply: values.reply?.trim() || null,
},
);
const failedIds = failedReviewIds(data);
setSelectedRowKeys(failedIds);
setBulkAction(null);
bulkForm.resetFields();
if (failedIds.length) reload();
else onPageChange(1, pageSize);
loadSummary();
refreshReviewBadge('/feedbacks');
const label = bulkAction === 'approve' ? '批量采纳' : '批量拒绝';
if (failedIds.length) {
message.warning(
`${label}完成:成功 ${data.success} 条,失败 ${failedIds.length} 条;失败项已保留勾选${bulkFailureReasonText(data)}`,
);
} else {
message.success(`${label}完成:成功 ${data.success}`);
}
} catch (e) {
message.error(errMsg(e));
} finally {
setBulkSubmitting(false);
}
};
const columns: ColumnsType<Feedback> = [
{
title: '用户ID',
@@ -488,58 +410,16 @@ export default function FeedbacksPage() {
<Button onClick={resetFilters}></Button>
</Space>
{canReview && (
<Space wrap style={{ display: 'flex', marginBottom: 12 }}>
<Text> <Text strong>{selectedFeedbacks.length}</Text> </Text>
<Button
type="primary"
disabled={!selectedFeedbacks.length || selectedFeedbacks.length > BULK_REVIEW_MAX}
onClick={() => openBulkModal('approve')}
>
</Button>
<Button
danger
disabled={!selectedFeedbacks.length || selectedFeedbacks.length > BULK_REVIEW_MAX}
onClick={() => openBulkModal('reject')}
>
</Button>
{!!selectedFeedbacks.length && (
<Button onClick={() => setSelectedRowKeys([])}></Button>
)}
</Space>
)}
<Table
rowKey="id"
columns={columns}
dataSource={items}
rowSelection={
canReview
? {
selectedRowKeys,
onChange: (keys) => {
const ids = keys as number[];
if (ids.length > BULK_REVIEW_MAX) {
message.warning(`单次最多选择 ${BULK_REVIEW_MAX} 条待审核反馈`);
}
setSelectedRowKeys(ids.slice(0, BULK_REVIEW_MAX));
},
getCheckboxProps: (record) => ({
disabled: !isPending(record.status),
name: `选择反馈 #${record.id}`,
}),
}
: undefined
}
loading={loading}
pagination={{
current: page,
pageSize,
total,
showSizeChanger: true,
pageSizeOptions: [10, 20, 50],
showTotal: (t) => `${t} 条反馈`,
onChange: onPageChange,
}}
@@ -547,97 +427,11 @@ export default function FeedbacksPage() {
scroll={{ x: 1720 }}
/>
<Modal
title={
bulkAction === 'approve'
? `批量采纳 ${selectedFeedbacks.length} 条反馈`
: `批量拒绝 ${selectedFeedbacks.length} 条反馈`
}
open={bulkAction != null}
okText={bulkAction === 'approve' ? '批量采纳并发金币' : '确认批量拒绝'}
okButtonProps={{ danger: bulkAction === 'reject' }}
confirmLoading={bulkSubmitting}
onOk={submitBulkReview}
onCancel={() => {
if (bulkSubmitting) return;
setBulkAction(null);
bulkForm.resetFields();
}}
destroyOnHidden
>
<Text type="secondary">
{selectedFeedbacks.length}
</Text>
<Form form={bulkForm} layout="vertical" preserve={false} style={{ marginTop: 16 }}>
{bulkAction === 'approve' ? (
<Form.Item
name="reward_coins"
label={`每条奖励金币(必填,1 ~ ${REWARD_MAX}`}
rules={[
{ required: true, message: '请输入每条反馈的奖励金币' },
{ type: 'number', min: 1, max: REWARD_MAX, message: `请输入 1 ~ ${REWARD_MAX}` },
]}
>
<InputNumber
min={1}
max={REWARD_MAX}
style={{ width: '100%' }}
placeholder="每条反馈发放相同金币"
/>
</Form.Item>
) : (
<Form.Item
name="reason"
label="未采纳原因(必填,用户可见)"
rules={[
{ required: true, whitespace: true, message: '请填写未采纳原因' },
{ max: 256, message: '最多 256 字' },
]}
>
<Input.TextArea
rows={3}
maxLength={256}
showCount
placeholder="同一原因将发送给全部已选用户"
/>
</Form.Item>
)}
<Form.Item
name="note"
label={
bulkAction === 'approve'
? '采纳要点 / 审核备注(选填,内部)'
: '内部备注(选填)'
}
rules={[{ max: 256, message: '最多 256 字' }]}
>
<Input.TextArea rows={2} maxLength={256} showCount />
</Form.Item>
<Form.Item
name="reply"
label="给用户的回复(选填,用户可见)"
rules={[{ max: 256, message: '最多 256 字' }]}
>
<Input.TextArea
rows={2}
maxLength={256}
showCount
placeholder="同一回复将发送给全部已选用户"
/>
</Form.Item>
</Form>
</Modal>
<FeedbackHandleDrawer
feedback={drawerFb}
open={drawerOpen}
onClose={() => setDrawerOpen(false)}
onDone={() => {
reload();
loadSummary();
refreshReviewBadge('/feedbacks');
}}
onDone={() => { reload(); loadSummary(); }}
/>
<UserRecordsDrawer<Feedback>
-103
View File
@@ -1,103 +0,0 @@
'use client';
import { useCallback, useEffect, useState } from 'react';
import { Alert, App, Button, Card, Descriptions, Radio, Skeleton, Tag } from 'antd';
import { api, errMsg } from '@/lib/api';
import { formatUtcTime } from '@/lib/format';
// 华为审核开关:控制新手引导「快速设置」权限步能否被用户退出。
// 华为应用市场审核要求该页必须可关闭(引导视频页不在要求内),平时保持「不能关闭」以保住权限开启率,
// 送审期间切「可关闭」。落在 app_config 的 huawei_review 行,客户端经 /api/v1/platform/huawei-review 拉。
type Mode = 'default' | 'review';
interface HuaweiReview {
mode: Mode;
updated_at: string | null;
}
const MODE_LABEL: Record<Mode, string> = {
default: '不能关闭',
review: '可关闭',
};
export default function HuaweiReviewPage() {
const { message } = App.useApp();
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
// saved = 服务端当前值(用于「有没有改动」判断);mode = 编辑中的值
const [saved, setSaved] = useState<HuaweiReview | null>(null);
const [mode, setMode] = useState<Mode>('default');
const load = useCallback(async () => {
try {
const r = await api.get<HuaweiReview>('/admin/api/huawei-review');
setSaved(r.data);
setMode(r.data.mode);
} catch (e) {
message.error(errMsg(e, '华为审核开关加载失败'));
} finally {
setLoading(false);
}
}, [message]);
useEffect(() => {
load();
}, [load]);
const save = async () => {
setSaving(true);
try {
const r = await api.patch<HuaweiReview>('/admin/api/huawei-review', { mode });
setSaved(r.data);
setMode(r.data.mode);
message.success('已保存。客户端下次进新手引导时拉取生效');
} catch (e) {
message.error(errMsg(e, '保存失败'));
} finally {
setSaving(false);
}
};
const dirty = saved !== null && saved.mode !== mode;
return (
<Card
title="华为审核开关"
extra={
<Button type="primary" loading={saving} disabled={loading || !dirty} onClick={save}>
</Button>
}
>
<Alert
type="info"
style={{ marginBottom: 16 }}
message="华为应用市场审核要求「快速设置」页必须可以关闭。切到「可关闭」后,该页左上角出现退出按钮(返回键同样可退出),用户点了直接进 App 首页、本次引导视为已完成。"
description="① 只对华为机型(HarmonyOS / EMUI)生效,荣耀 MagicOS 及其它机型不受影响;② 只影响快速设置权限步,引导视频页照旧必须看完;③ 客户端在进引导前拉一次并缓存,已经停在引导页的用户要重进 App 才会变;④ 审核通过后记得切回「不能关闭」,不然会一直损失权限开启率。"
/>
{loading ? (
<Skeleton active paragraph={{ rows: 3 }} />
) : (
<>
<Descriptions column={1} style={{ marginBottom: 16 }}>
<Descriptions.Item label="当前生效">
{saved ? (
<Tag color={saved.mode === 'review' ? 'orange' : 'green'}>{MODE_LABEL[saved.mode]}</Tag>
) : (
'-'
)}
</Descriptions.Item>
<Descriptions.Item label="最后修改">
{saved?.updated_at ? formatUtcTime(saved.updated_at) : '从未修改过(默认不能关闭)'}
</Descriptions.Item>
</Descriptions>
<div style={{ marginBottom: 8 }}></div>
<Radio.Group value={mode} onChange={(e) => setMode(e.target.value as Mode)}>
<Radio.Button value="default"></Radio.Button>
<Radio.Button value="review"></Radio.Button>
</Radio.Group>
</>
)}
</Card>
);
}
-5
View File
@@ -1,5 +0,0 @@
import { WithdrawReviewPage } from '../withdraws/WithdrawReviewPage';
export default function InviteWithdrawsPage() {
return <WithdrawReviewPage mode="invite" />;
}
+9 -122
View File
@@ -1,6 +1,6 @@
'use client';
import { useEffect, useRef, useState } from 'react';
import { useEffect, useState } from 'react';
import { usePathname, useRouter } from 'next/navigation';
import {
BarChartOutlined,
@@ -16,8 +16,6 @@ import {
MoneyCollectOutlined,
NotificationOutlined,
ProfileOutlined,
SafetyCertificateOutlined,
SecurityScanOutlined,
SettingOutlined,
ShareAltOutlined,
TeamOutlined,
@@ -26,16 +24,7 @@ import {
import { Avatar, Dropdown, Layout, Tooltip } from 'antd';
import { api } from '@/lib/api';
import { clearAuth, getAdmin, getToken, setAuth } from '@/lib/auth';
import {
REVIEW_BADGE_REFRESH_EVENT,
type ReviewBadgeKey,
} from '@/lib/reviewBadge';
import type {
AdminInfo,
FeedbackSummary,
PriceReportSummary,
WithdrawSummary,
} from '@/lib/types';
import type { AdminInfo } from '@/lib/types';
const { Sider, Header, Content } = Layout;
@@ -68,6 +57,8 @@ const NAV_GROUPS: NavGroup[] = [
{ key: '/comparison-records', icon: <ProfileOutlined />, label: '比价记录' },
{ key: '/coupon-data', icon: <GiftOutlined />, label: '领券记录' },
{ key: '/cps', icon: <ShareAltOutlined />, label: 'CPS收益' },
{ key: '/device-liveness', icon: <HeartOutlined />, label: '设备存活' },
{ key: '/analytics-health', icon: <LineChartOutlined />, label: '埋点成功率' },
],
},
{
@@ -75,8 +66,7 @@ const NAV_GROUPS: NavGroup[] = [
icon: <MoneyCollectOutlined />,
label: '奖励审核',
children: [
{ key: '/invite-withdraws', icon: <MoneyCollectOutlined />, label: '邀请提现审核' },
{ key: '/withdraws', icon: <MoneyCollectOutlined />, label: '其他提现审核' },
{ key: '/withdraws', icon: <MoneyCollectOutlined />, label: '提现审核' },
{ key: '/price-reports', icon: <FlagOutlined />, label: '低价审核' },
{ key: '/feedbacks', icon: <MessageOutlined />, label: '用户反馈' },
],
@@ -88,23 +78,12 @@ const NAV_GROUPS: NavGroup[] = [
children: [
{ key: '/config', icon: <SettingOutlined />, label: '系统配置' },
{ key: '/ad-revenue', icon: <NotificationOutlined />, label: '广告配置' },
{ key: '/huawei-review', icon: <SafetyCertificateOutlined />, label: '华为审核开关' },
{ key: '/users', icon: <UserOutlined />, label: '用户管理' },
],
},
{
key: 'monitoring-audit',
icon: <FileSearchOutlined />,
label: '监控审计',
children: [
{ key: '/risk-monitor', icon: <SecurityScanOutlined />, label: '风控监控' },
{ key: '/device-liveness', icon: <HeartOutlined />, label: '设备存活' },
{ key: '/analytics-health', icon: <LineChartOutlined />, label: '埋点成功率' },
{ key: '/event-logs', icon: <DatabaseOutlined />, label: '埋点日志' },
{ key: '/audit-logs', icon: <FileSearchOutlined />, label: '审计日志' },
],
},
{ key: '/admins', icon: <TeamOutlined />, label: '权限管理' },
{ key: '/event-logs', icon: <DatabaseOutlined />, label: '埋点日志' },
{ key: '/audit-logs', icon: <FileSearchOutlined />, label: '审计日志' },
];
// 导航项 key(/dashboard)→ 权限页 key(dashboard),与后端 permissions.py 目录对齐
@@ -115,8 +94,6 @@ export default function MainLayout({ children }: { children: React.ReactNode })
const pathname = usePathname();
const [admin, setAdmin] = useState<AdminInfo | null>(null);
const [collapsed, setCollapsed] = useState(false);
const [pendingReviewCounts, setPendingReviewCounts] = useState<Partial<Record<ReviewBadgeKey, number>>>({});
const reviewRefreshVersion = useRef<Partial<Record<ReviewBadgeKey, number>>>({});
useEffect(() => {
const token = getToken();
@@ -135,50 +112,6 @@ export default function MainLayout({ children }: { children: React.ReactNode })
.catch(() => {});
}, [router]);
useEffect(() => {
if (!admin) return;
const canAccess = (page: string) =>
admin.role === 'super_admin' || !admin.pages || admin.pages.includes(page);
const refresh = async (key: ReviewBadgeKey) => {
if (!canAccess(key.slice(1))) return;
const version = (reviewRefreshVersion.current[key] ?? 0) + 1;
reviewRefreshVersion.current[key] = version;
let count: number;
if (key === '/withdraws' || key === '/invite-withdraws') {
const source = key === '/invite-withdraws' ? 'invite_cash' : 'coin_cash';
count = (
await api.get<WithdrawSummary>('/admin/api/withdraws/summary', {
params: { source },
})
).data.reviewing_count;
} else if (key === '/price-reports') {
count = (await api.get<PriceReportSummary>('/admin/api/price-reports/summary')).data.pending;
} else {
count = (await api.get<FeedbackSummary>('/admin/api/feedbacks/summary')).data.pending;
}
if (reviewRefreshVersion.current[key] !== version) return;
setPendingReviewCounts((current) => ({ ...current, [key]: count }));
};
const refreshSafely = (key: ReviewBadgeKey) => refresh(key).catch(() => {});
void Promise.all([
refreshSafely('/withdraws'),
refreshSafely('/invite-withdraws'),
refreshSafely('/price-reports'),
refreshSafely('/feedbacks'),
]);
const onReviewCompleted = (event: Event) => {
const key = (event as CustomEvent<ReviewBadgeKey>).detail;
if (key) void refreshSafely(key);
};
window.addEventListener(REVIEW_BADGE_REFRESH_EVENT, onReviewCompleted);
return () => {
window.removeEventListener(REVIEW_BADGE_REFRESH_EVENT, onReviewCompleted);
};
}, [admin]);
if (!admin) return null; // 守卫期间不闪烁内容
// 选中态:取路径一级(/users/123 -> /users)
@@ -197,20 +130,6 @@ export default function MainLayout({ children }: { children: React.ReactNode })
hasChildren(group) ? group.children : [group],
);
const reviewBadge = (key: string) => {
const count = pendingReviewCounts[key as ReviewBadgeKey] ?? 0;
if (count <= 0) return null;
return (
<span
className="nav-review-badge"
aria-label={`${count} 条未审核`}
title={`${count} 条未审核`}
>
{count}
</span>
);
};
const logout = () => {
clearAuth();
router.replace('/login');
@@ -245,7 +164,6 @@ export default function MainLayout({ children }: { children: React.ReactNode })
aria-label={item.label}
>
{item.icon}
{reviewBadge(item.key)}
</button>
</Tooltip>
))
@@ -263,8 +181,7 @@ export default function MainLayout({ children }: { children: React.ReactNode })
onClick={() => router.push(group.key)}
>
<span className="nav-primary-icon">{group.icon}</span>
<span className="nav-item-label">{group.label}</span>
{reviewBadge(group.key)}
<span>{group.label}</span>
</button>
);
}
@@ -283,8 +200,7 @@ export default function MainLayout({ children }: { children: React.ReactNode })
onClick={() => router.push(child.key)}
>
<span className="nav-child-icon">{child.icon}</span>
<span className="nav-item-label">{child.label}</span>
{reviewBadge(child.key)}
<span>{child.label}</span>
</button>
))}
</div>
@@ -351,29 +267,6 @@ export default function MainLayout({ children }: { children: React.ReactNode })
color: rgba(255, 255, 255, 0.72);
font-size: 16px;
}
.nav-item-label {
min-width: 0;
flex: 1;
}
.nav-review-badge {
display: inline-flex;
align-items: center;
justify-content: center;
box-sizing: border-box;
flex: 0 0 auto;
min-width: 18px;
height: 18px;
padding: 0 5px;
border-radius: 9px;
background: #ff4d4f;
color: #fff;
font-size: 11px;
font-weight: 600;
line-height: 18px;
white-space: nowrap;
font-variant-numeric: tabular-nums;
box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.08);
}
.nav-direct,
.nav-child,
.nav-icon-button {
@@ -437,7 +330,6 @@ export default function MainLayout({ children }: { children: React.ReactNode })
padding: 0 8px 14px;
}
.nav-icon-button {
position: relative;
display: inline-flex;
align-items: center;
justify-content: center;
@@ -448,11 +340,6 @@ export default function MainLayout({ children }: { children: React.ReactNode })
color: rgba(255, 255, 255, 0.72);
font-size: 17px;
}
.nav-icon-button .nav-review-badge {
position: absolute;
top: 1px;
right: -6px;
}
.nav-icon-button:hover,
.nav-icon-button.is-selected {
background: #1677ff;
+10 -139
View File
@@ -22,9 +22,6 @@ import dayjs from 'dayjs';
import { api, errMsg } from '@/lib/api';
import { canDo } from '@/lib/auth';
import { mediaUrl } from '@/lib/media';
import { refreshReviewBadge } from '@/lib/reviewBadge';
import { BULK_REVIEW_MAX, bulkFailureReasonText, failedReviewIds } from '@/lib/bulkAction';
import type { BulkReviewResult } from '@/lib/bulkAction';
import { usePagedList } from '@/lib/usePagedList';
import type { PriceReport, PriceReportSummary } from '@/lib/types';
import UserRecordsDrawer from '@/components/UserRecordsDrawer';
@@ -134,10 +131,7 @@ export default function PriceReportsPage() {
const [activeStatus, setActiveStatus] = useState('pending');
const [summary, setSummary] = useState<PriceReportSummary | null>(null);
const [rejecting, setRejecting] = useState<PriceReport | null>(null);
const [bulkRejecting, setBulkRejecting] = useState<PriceReport[]>([]);
const [rejectReason, setRejectReason] = useState('');
const [rejectSubmitting, setRejectSubmitting] = useState(false);
const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
// 提交时间列服务端排序(默认按提交时间倒序,最新在前)
const [sortBy, setSortBy] = useState<SortField>('created_at');
const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc');
@@ -170,16 +164,6 @@ export default function PriceReportsPage() {
};
const canReview = canDo(['operator']);
const selectedReports = items.filter(
(item) => selectedRowKeys.includes(item.id) && item.status === 'pending',
);
useEffect(() => {
const visiblePendingIds = new Set(
items.filter((item) => item.status === 'pending').map((item) => item.id),
);
setSelectedRowKeys((keys) => keys.filter((id) => visiblePendingIds.has(id)));
}, [items]);
const loadSummary = async () => {
try {
@@ -198,49 +182,6 @@ export default function PriceReportsPage() {
loadSummary();
};
const reportBulkResult = (label: string, result: BulkReviewResult) => {
const failedIds = failedReviewIds(result);
setSelectedRowKeys(failedIds);
refreshReviewBadge('/price-reports');
loadSummary();
if (failedIds.length) reload();
else onPageChange(1, pageSize);
if (failedIds.length) {
message.warning(
`${label}完成:成功 ${result.success} 条,失败 ${failedIds.length} 条;失败项已保留勾选${bulkFailureReasonText(result)}`,
);
} else {
message.success(`${label}完成:成功 ${result.success}`);
}
};
const bulkApprove = () => {
const targets = selectedReports;
if (!targets.length) return;
if (targets.length > BULK_REVIEW_MAX) {
message.warning(`单次最多审核 ${BULK_REVIEW_MAX} 条记录`);
return;
}
modal.confirm({
title: `确认批量通过 ${targets.length} 条低价上报?`,
icon: <CheckCircleOutlined style={{ color: '#52c41a' }} />,
content: `通过后将向每位用户发放 1000 金币,共发放 ${targets.length * 1000} 金币。请确认已逐条核实截图。`,
okText: '批量通过并发金币',
onOk: async () => {
try {
const { data } = await api.post<BulkReviewResult>(
'/admin/api/price-reports/bulk/approve',
{ ids: targets.map((item) => item.id) },
);
reportBulkResult('批量通过', data);
} catch (e) {
message.error(errMsg(e));
throw e;
}
},
});
};
const approve = (r: PriceReport) => {
modal.confirm({
title: '确认通过该上报?',
@@ -261,7 +202,6 @@ export default function PriceReportsPage() {
onOk: async () => {
try {
await api.post(`/admin/api/price-reports/${r.id}/approve`);
refreshReviewBadge('/price-reports');
message.success('已通过,已发放 1000 金币');
refreshAfterChange();
} catch (e) {
@@ -272,38 +212,20 @@ export default function PriceReportsPage() {
};
const confirmReject = async () => {
const targets = bulkRejecting.length ? bulkRejecting : rejecting ? [rejecting] : [];
if (!targets.length) return;
if (targets.length > BULK_REVIEW_MAX) {
message.warning(`单次最多审核 ${BULK_REVIEW_MAX} 条记录`);
return;
}
if (!rejecting) return;
const reason = rejectReason.trim();
if (!reason) {
message.warning('请填写拒绝理由');
return;
}
setRejectSubmitting(true);
try {
if (bulkRejecting.length) {
const { data } = await api.post<BulkReviewResult>(
'/admin/api/price-reports/bulk/reject',
{ ids: targets.map((item) => item.id), reason },
);
reportBulkResult('批量拒绝', data);
} else {
await api.post(`/admin/api/price-reports/${targets[0].id}/reject`, { reason });
refreshReviewBadge('/price-reports');
message.success('已拒绝');
refreshAfterChange();
}
await api.post(`/admin/api/price-reports/${rejecting.id}/reject`, { reason });
message.success('已拒绝');
setRejecting(null);
setBulkRejecting([]);
setRejectReason('');
refreshAfterChange();
} catch (e) {
message.error(errMsg(e));
} finally {
setRejectSubmitting(false);
}
};
@@ -468,56 +390,10 @@ export default function PriceReportsPage() {
onChange={setActiveStatus}
items={STATUS_TABS.map((t) => ({ key: t.key, label: t.label }))}
/>
{canReview && (
<Space wrap style={{ marginBottom: 16 }}>
<Text> <Text strong>{selectedReports.length}</Text> </Text>
<Button
type="primary"
icon={<CheckCircleOutlined />}
disabled={!selectedReports.length || selectedReports.length > BULK_REVIEW_MAX}
onClick={bulkApprove}
>
</Button>
<Button
danger
icon={<CloseCircleOutlined />}
disabled={!selectedReports.length || selectedReports.length > BULK_REVIEW_MAX}
onClick={() => {
setRejecting(null);
setBulkRejecting(selectedReports);
setRejectReason('');
}}
>
</Button>
{!!selectedReports.length && (
<Button onClick={() => setSelectedRowKeys([])}></Button>
)}
</Space>
)}
<Table
rowKey="id"
columns={columns}
dataSource={items}
rowSelection={
canReview
? {
selectedRowKeys,
onChange: (keys) => {
const ids = keys as number[];
if (ids.length > BULK_REVIEW_MAX) {
message.warning(`单次最多选择 ${BULK_REVIEW_MAX} 条待审核记录`);
}
setSelectedRowKeys(ids.slice(0, BULK_REVIEW_MAX));
},
getCheckboxProps: (record) => ({
disabled: record.status !== 'pending',
name: `选择低价上报 #${record.id}`,
}),
}
: undefined
}
loading={loading}
onChange={onTableChange}
pagination={{
@@ -525,7 +401,6 @@ export default function PriceReportsPage() {
pageSize,
total,
showSizeChanger: true,
pageSizeOptions: [10, 20, 50],
showTotal: (t) => `${t}`,
onChange: onPageChange,
}}
@@ -534,25 +409,21 @@ export default function PriceReportsPage() {
</Card>
<Modal
title={bulkRejecting.length ? `批量拒绝 ${bulkRejecting.length} 条低价上报` : '拒绝上报'}
open={!!(rejecting || bulkRejecting.length)}
title="拒绝上报"
open={!!rejecting}
okText="确认拒绝"
confirmLoading={rejectSubmitting}
okButtonProps={{ danger: true, icon: <CloseCircleOutlined /> }}
onOk={confirmReject}
onCancel={() => {
setRejecting(null);
setBulkRejecting([]);
setRejectReason('');
}}
>
{(rejecting || bulkRejecting.length > 0) && (
{rejecting && (
<Space direction="vertical" style={{ width: '100%' }}>
{bulkRejecting.length ? (
<Text type="secondary"> {bulkRejecting.length} </Text>
) : rejecting ? (
<Text> #{rejecting.user_id} · {rejecting.store_name || '-'}</Text>
) : null}
<Text>
#{rejecting.user_id} · {rejecting.store_name || '-'}
</Text>
<Space wrap>
{REJECT_TEMPLATES.map((tpl) => (
<Button size="small" key={tpl} onClick={() => setRejectReason(tpl)}>
-356
View File
@@ -1,356 +0,0 @@
.page {
min-height: calc(100vh - 112px);
margin: -24px;
padding: 0 16px 28px;
background: #f5f5f3;
color: #171717;
}
.hero {
display: flex;
align-items: center;
justify-content: space-between;
min-height: 72px;
margin: 0 -16px 18px;
padding: 0 24px;
border-bottom: 1px solid #e8e8e6;
background: #fff;
}
.titleCluster,
.brandLine,
.updated,
.rule,
.deviceCell,
.actionGroup,
.factRow {
display: flex;
align-items: center;
}
.back {
margin-right: 18px;
color: #555;
font-size: 13px;
}
.brandMark {
display: inline-flex;
align-items: center;
justify-content: center;
width: 34px;
height: 34px;
margin-right: 12px;
border-radius: 10px;
background: #ffd400;
color: #111;
font-size: 17px;
font-weight: 800;
}
.title {
margin: 0;
font-size: 18px;
font-weight: 700;
line-height: 1.2;
}
.subtitle {
margin-top: 3px;
color: #929292;
font-size: 12px;
}
.updated {
gap: 7px;
color: #898989;
font-size: 12px;
}
.updatedMeta {
display: flex;
align-items: center;
gap: 7px;
}
.dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: #9b9b9b;
}
.summaryGrid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 14px;
margin-bottom: 16px;
}
.statusToolbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
margin-bottom: 2px;
padding: 12px 16px;
border: 1px solid #ecece8;
border-radius: 12px;
background: #fff;
}
.statusToolbar > div {
display: flex;
flex-direction: column;
gap: 2px;
}
.statusToolbar strong {
color: #222;
font-size: 14px;
}
.statusToolbar span {
color: #888;
font-size: 12px;
}
.summaryCard {
min-height: 148px;
padding: 26px 24px 20px;
border: 1px solid #eeeeeb;
border-radius: 16px;
background: #fff;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.02);
}
.summaryTitle {
margin-bottom: 4px;
color: #111;
font-size: 14px;
font-weight: 700;
}
.summaryValue {
color: #ee3737;
font-size: 38px;
font-weight: 800;
line-height: 1.08;
font-variant-numeric: tabular-nums;
}
.summaryUnit {
margin-left: 5px;
color: #202020;
font-size: 16px;
font-weight: 600;
}
.summarySub {
margin: 8px 0 8px;
color: #969696;
font-size: 13px;
}
.rule {
width: fit-content;
padding: 4px 8px;
border: 0;
border-radius: 6px;
background: #f6f6f4;
color: #111;
cursor: pointer;
font-family: inherit;
font-size: 12px;
font-weight: 600;
transition: background 0.18s ease, box-shadow 0.18s ease;
}
.rule:hover,
.rule:focus-visible {
background: #fff3bf;
box-shadow: 0 0 0 2px rgba(255, 212, 0, 0.3);
outline: none;
}
.rule strong {
margin-left: 4px;
color: #df2727;
}
.ruleEditIcon {
margin-left: 7px;
color: #777;
font-size: 11px;
}
.ruleDialogIntro {
margin: 0 0 16px;
padding: 10px 12px;
border-radius: 8px;
background: #faf8ef;
color: #666;
font-size: 12px;
line-height: 1.7;
}
.ruleSettings {
border-top: 1px solid #f0f0ed;
}
.ruleSettingRow {
display: grid;
grid-template-columns: minmax(0, 1fr) 140px;
gap: 20px;
align-items: center;
padding: 16px 0;
border-bottom: 1px solid #f0f0ed;
}
.ruleSettingCopy {
display: flex;
flex-direction: column;
gap: 5px;
}
.ruleSettingCopy strong {
color: #222;
font-size: 14px;
}
.ruleSettingCopy span {
color: #888;
font-size: 12px;
line-height: 1.55;
}
.ruleValueEditor {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 8px;
color: #666;
}
.ruleValueEditor :global(.ant-input-number) {
width: 110px;
}
.section {
margin-top: 14px;
padding: 20px 20px 16px;
border: 1px solid #ecece8;
border-radius: 16px;
background: #fff;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.02);
}
.sectionTitle {
margin: 0 0 10px;
font-size: 15px;
font-weight: 700;
}
.deviceCell {
gap: 7px;
}
.mono {
max-width: 210px;
overflow: hidden;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 12px;
text-overflow: ellipsis;
white-space: nowrap;
}
.copyButton {
height: 25px !important;
padding: 0 7px !important;
color: #777 !important;
font-size: 12px !important;
}
.actionGroup {
justify-content: flex-end;
gap: 6px;
white-space: nowrap;
}
.expandButton {
border-color: #ffd400 !important;
background: #ffd400 !important;
color: #111 !important;
font-weight: 600;
}
.detailWrap {
padding: 12px 16px 6px;
border-radius: 10px;
background: #fafaf8;
}
.factRow {
gap: 8px;
margin-bottom: 12px;
}
.fact {
padding: 6px 10px;
border: 1px solid #ecece7;
border-radius: 8px;
background: #fff;
color: #666;
font-size: 12px;
}
.fact strong {
margin: 0 3px;
color: #111;
font-size: 14px;
}
.price {
white-space: nowrap;
font-variant-numeric: tabular-nums;
}
.na {
color: #aaa;
}
.footerNote {
margin-top: 16px;
padding: 16px 20px;
border: 1px dashed #dcdcd8;
border-radius: 14px;
background: rgba(255, 255, 255, 0.42);
color: #666;
font-size: 12px;
line-height: 1.8;
}
.footerNote strong {
color: #222;
}
@media (max-width: 900px) {
.summaryGrid {
grid-template-columns: 1fr;
}
.hero {
align-items: flex-start;
padding-top: 16px;
padding-bottom: 16px;
}
.updatedMeta {
display: none;
}
.statusToolbar {
align-items: flex-start;
flex-direction: column;
}
}
-902
View File
@@ -1,902 +0,0 @@
'use client';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
App,
Button,
Empty,
InputNumber,
Modal,
Segmented,
Skeleton,
Table,
Tag,
Tooltip,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import {
ClearOutlined,
CopyOutlined,
DownOutlined,
EditOutlined,
ReloadOutlined,
RightOutlined,
} from '@ant-design/icons';
import dayjs from 'dayjs';
import { api, errMsg } from '@/lib/api';
import { formatUtcTime, utcDayjs } from '@/lib/format';
import type {
RiskDetailItem,
RiskDetailPage,
RiskIncidentItem,
RiskIncidentPage,
RiskKind,
RiskMonitorSummary,
RiskResetResponse,
RiskRuleConfig,
RiskSummaryCard,
} from '@/lib/types';
import styles from './page.module.css';
const KIND_META: Record<
RiskKind,
{ title: string; summaryTitle: string; totalLabel: string; unit: string }
> = {
sms: {
title: '短信',
summaryTitle: '触发短信报警的设备',
totalLabel: '今日短信下发共',
unit: '台',
},
oneclick: {
title: '一键登录',
summaryTitle: '触发一键登录报警的设备',
totalLabel: '今日一键登录共',
unit: '台',
},
compare: {
title: '比价',
summaryTitle: '触发比价报警的账户',
totalLabel: '今日比价共',
unit: '个',
},
};
const integer = (value: number) => new Intl.NumberFormat('zh-CN').format(value);
const LIST_PAGE_SIZE = 20;
const RISK_KINDS: RiskKind[] = ['sms', 'oneclick', 'compare'];
type IncidentStatus = 'open' | 'blocked';
const RULE_LIMITS: Record<RiskKind, { min: number; max: number; help: string }> = {
sms: {
min: 1,
max: 5,
help: '统计成功下发;最高5次,与现有每设备每小时发送上限一致。',
},
oneclick: {
min: 1,
max: 100000,
help: '成功和失败均计入,同一设备按北京时间自然日累计。',
},
compare: {
min: 1,
max: 100,
help: '同一账户按北京时间自然日累计;最高100次,与比价每日上限一致。',
},
};
const utcTime = (value: string | null, withDate = true) =>
formatUtcTime(value, withDate ? 'MM-DD HH:mm' : 'HH:mm');
const eventMoment = (value: string, kind: RiskKind) =>
kind === 'compare' ? dayjs(value) : utcDayjs(value).tz('Asia/Shanghai');
const eventTime = (value: string | null, kind: RiskKind, withDate = true) =>
value ? eventMoment(value, kind).format(withDate ? 'MM-DD HH:mm' : 'HH:mm') : '-';
function period(item: RiskIncidentItem): string {
const start = eventMoment(item.first_event_at, item.kind);
const end = eventMoment(item.last_event_at, item.kind);
if (start.isSame(end, 'day')) {
return `${start.format('YYYY-MM-DD HH:mm')}${end.format('HH:mm')}`;
}
return `${start.format('YYYY-MM-DD HH:mm')}${end.format('YYYY-MM-DD HH:mm')}`;
}
function DeviceId({
value,
onCopy,
}: {
value: string | null;
onCopy: (value: string) => void;
}) {
if (!value) return <span className={styles.na}>-</span>;
return (
<span className={styles.deviceCell}>
<Tooltip title={value}>
<span className={styles.mono}>{value}</span>
</Tooltip>
<Button
className={styles.copyButton}
size="small"
icon={<CopyOutlined />}
onClick={() => onCopy(value)}
>
</Button>
</span>
);
}
function DetailTable({
detail,
loading,
page,
onPage,
}: {
detail?: RiskDetailPage;
loading: boolean;
page: number;
onPage: (page: number) => void;
}) {
if (loading || !detail) return <Skeleton active paragraph={{ rows: 4 }} />;
let columns: ColumnsType<RiskDetailItem>;
if (detail.kind === 'sms') {
columns = [
{
title: '发送时间',
dataIndex: 'occurred_at',
width: 150,
render: (v) => eventTime(v, detail.kind),
},
{ title: '手机号', dataIndex: 'phone', width: 140, render: (v) => v || '-' },
{
title: '完成验证',
dataIndex: 'verified',
width: 100,
render: (v) => (v ? <Tag color="success"></Tag> : <Tag></Tag>),
},
{
title: '登录账号',
key: 'account',
render: (_, row) => row.username || (row.user_id ? `U${row.user_id}` : '-'),
},
{
title: '账号注册时间',
dataIndex: 'account_registered_at',
width: 150,
render: (v) => utcTime(v),
},
];
} else if (detail.kind === 'oneclick') {
columns = [
{
title: '登录时间',
dataIndex: 'occurred_at',
width: 150,
render: (v) => eventTime(v, detail.kind),
},
{ title: '手机号', dataIndex: 'phone', width: 140, render: (v) => v || '-' },
{
title: '登录账号',
key: 'account',
render: (_, row) => row.username || (row.user_id ? `U${row.user_id}` : '-'),
},
{
title: '账号注册时间',
dataIndex: 'account_registered_at',
width: 150,
render: (v) => utcTime(v),
},
{
title: '结果',
dataIndex: 'outcome',
width: 100,
render: (v) =>
v === 'success' ? <Tag color="success"></Tag> : <Tag color="error"></Tag>,
},
{ title: '失败原因', dataIndex: 'reason', render: (v) => v || '-' },
];
} else {
const priceColumn = (platform: string) => ({
title: platform,
key: platform,
width: 100,
render: (_: unknown, row: RiskDetailItem) => {
const value = row.prices?.[platform];
return value == null ? (
<span className={styles.na}></span>
) : (
<span className={styles.price}>¥{value.toFixed(2)}</span>
);
},
});
columns = [
{
title: '触发时间',
dataIndex: 'occurred_at',
width: 150,
render: (v) => eventTime(v, detail.kind),
},
{
title: '店铺 / 菜品',
key: 'shop',
render: (_, row) => (
<span>{[row.store_name, row.product_names].filter(Boolean).join(' · ') || '-'}</span>
),
},
priceColumn('美团'),
priceColumn('淘宝'),
priceColumn('京东'),
{
title: '节省',
dataIndex: 'saved_amount_yuan',
width: 90,
render: (v) => (v == null ? '-' : <span className={styles.price}>{v.toFixed(2)} </span>),
},
{
title: '状态',
dataIndex: 'status',
width: 90,
render: (v) =>
v === 'success' ? <Tag color="success"></Tag> : <Tag color="error"></Tag>,
},
];
}
return (
<div className={styles.detailWrap}>
<div className={styles.factRow}>
<span className={styles.fact}>
{KIND_META[detail.kind].title}
<strong>{integer(detail.event_count)}</strong>
</span>
{detail.distinct_accounts != null && (
<span className={styles.fact}>
<strong>{integer(detail.distinct_accounts)}</strong>
</span>
)}
</div>
<Table
rowKey="id"
size="small"
columns={columns}
dataSource={detail.items}
scroll={{ x: detail.kind === 'compare' ? 1000 : 720 }}
pagination={{
current: page,
pageSize: 20,
total: detail.total,
showSizeChanger: false,
onChange: onPage,
}}
/>
</div>
);
}
export default function RiskMonitorPage() {
const { message, modal } = App.useApp();
const [summary, setSummary] = useState<RiskMonitorSummary | null>(null);
const [lists, setLists] = useState<Partial<Record<RiskKind, RiskIncidentPage>>>({});
const [listPage, setListPage] = useState<Record<RiskKind, number>>({
sms: 1,
oneclick: 1,
compare: 1,
});
const [incidentStatus, setIncidentStatus] = useState<IncidentStatus>('open');
const listPageRef = useRef(listPage);
const [loading, setLoading] = useState(true);
const [expanded, setExpanded] = useState<Set<number>>(new Set());
const [details, setDetails] = useState<Record<number, RiskDetailPage>>({});
const [detailLoading, setDetailLoading] = useState<Set<number>>(new Set());
const [detailPage, setDetailPage] = useState<Record<number, number>>({});
const [acting, setActing] = useState<number | null>(null);
const [ruleOpen, setRuleOpen] = useState(false);
const [ruleSaving, setRuleSaving] = useState(false);
const [resetting, setResetting] = useState(false);
const [ruleDraft, setRuleDraft] = useState<Record<RiskKind, number>>({
sms: 5,
oneclick: 20,
compare: 100,
});
const loadAll = useCallback(async (quiet = false) => {
if (!quiet) setLoading(true);
try {
const pages = listPageRef.current;
const [summaryRes, smsRes, oneclickRes, compareRes] = await Promise.all([
api.get<RiskMonitorSummary>('/admin/api/risk-monitor/summary'),
api.get<RiskIncidentPage>('/admin/api/risk-monitor/incidents/sms', {
params: {
status: incidentStatus,
cursor: (pages.sms - 1) * LIST_PAGE_SIZE,
limit: LIST_PAGE_SIZE,
},
}),
api.get<RiskIncidentPage>('/admin/api/risk-monitor/incidents/oneclick', {
params: {
status: incidentStatus,
cursor: (pages.oneclick - 1) * LIST_PAGE_SIZE,
limit: LIST_PAGE_SIZE,
},
}),
api.get<RiskIncidentPage>('/admin/api/risk-monitor/incidents/compare', {
params: {
status: incidentStatus,
cursor: (pages.compare - 1) * LIST_PAGE_SIZE,
limit: LIST_PAGE_SIZE,
},
}),
]);
setSummary(summaryRes.data);
setLists({
sms: smsRes.data,
oneclick: oneclickRes.data,
compare: compareRes.data,
});
} catch (error) {
void message.error(errMsg(error, '风控数据加载失败'));
} finally {
setLoading(false);
}
}, [incidentStatus, message]);
const changeListPage = useCallback(
async (kind: RiskKind, page: number) => {
const nextPages = { ...listPageRef.current, [kind]: page };
listPageRef.current = nextPages;
setListPage(nextPages);
try {
const { data } = await api.get<RiskIncidentPage>(
`/admin/api/risk-monitor/incidents/${kind}`,
{
params: {
status: incidentStatus,
cursor: (page - 1) * LIST_PAGE_SIZE,
limit: LIST_PAGE_SIZE,
},
},
);
setLists((current) => ({ ...current, [kind]: data }));
} catch (error) {
void message.error(errMsg(error, '风险列表加载失败'));
}
},
[incidentStatus, message],
);
const changeIncidentStatus = useCallback((status: IncidentStatus) => {
const firstPage = { sms: 1, oneclick: 1, compare: 1 };
listPageRef.current = firstPage;
setListPage(firstPage);
setLists({});
setExpanded(new Set());
setDetails({});
setDetailLoading(new Set());
setDetailPage({});
setIncidentStatus(status);
}, []);
useEffect(() => {
void loadAll();
const timer = window.setInterval(() => void loadAll(true), 60 * 60 * 1000);
const onFocus = () => void loadAll(true);
window.addEventListener('focus', onFocus);
return () => {
window.clearInterval(timer);
window.removeEventListener('focus', onFocus);
};
}, [loadAll]);
const copy = useCallback(
async (value: string) => {
await navigator.clipboard.writeText(value);
void message.success('设备 ID 已复制');
},
[message],
);
const openRuleSettings = useCallback(() => {
if (summary) {
const current = Object.fromEntries(
summary.cards.map((card) => [card.kind, card.threshold]),
) as Record<RiskKind, number>;
setRuleDraft(current);
}
setRuleOpen(true);
}, [summary]);
const saveRules = useCallback(async () => {
setRuleSaving(true);
try {
const payload: RiskRuleConfig = {
sms_hourly_threshold: ruleDraft.sms,
oneclick_daily_threshold: ruleDraft.oneclick,
compare_daily_threshold: ruleDraft.compare,
};
await api.patch<RiskRuleConfig>('/admin/api/risk-monitor/rules', payload);
setRuleOpen(false);
void message.success('规则已保存,并已重新核算当前时段');
await loadAll(true);
} catch (error) {
void message.error(errMsg(error, '规则保存失败'));
} finally {
setRuleSaving(false);
}
}, [loadAll, message, ruleDraft]);
const resetAlerts = useCallback(() => {
modal.confirm({
title: '确认重置全部报警?',
content:
'短信、一键登录、比价三类待处理报警将归零,并从确认时刻重新累计。历史流水会保留,已封禁的设备和账户不会解封。',
okText: '确认重置',
okButtonProps: { danger: true },
cancelText: '取消',
async onOk() {
setResetting(true);
try {
const { data } = await api.post<RiskResetResponse>(
'/admin/api/risk-monitor/reset',
);
listPageRef.current = { sms: 1, oneclick: 1, compare: 1 };
setListPage({ sms: 1, oneclick: 1, compare: 1 });
setExpanded(new Set());
setDetails({});
setDetailPage({});
if (data.reset_incident_count > 0) {
void message.success(
`已重置 ${integer(data.reset_incident_count)} 条报警,并从 0 重新累计`,
);
} else {
void message.success('当前无待处理报警,新的累计基线已生效');
}
await loadAll(true);
} catch (error) {
void message.error(errMsg(error, '报警重置失败'));
throw error;
} finally {
setResetting(false);
}
},
});
}, [loadAll, message, modal]);
const loadDetail = useCallback(
async (kind: RiskKind, incidentId: number, page = 1) => {
setDetailLoading((current) => new Set(current).add(incidentId));
try {
const { data } = await api.get<RiskDetailPage>(
`/admin/api/risk-monitor/incidents/${kind}/${incidentId}/details`,
{ params: { cursor: (page - 1) * 20, limit: 20 } },
);
setDetails((current) => ({ ...current, [incidentId]: data }));
setDetailPage((current) => ({ ...current, [incidentId]: page }));
} catch (error) {
void message.error(errMsg(error, '风险明细加载失败'));
} finally {
setDetailLoading((current) => {
const next = new Set(current);
next.delete(incidentId);
return next;
});
}
},
[message],
);
const toggle = useCallback(
(row: RiskIncidentItem) => {
const willOpen = !expanded.has(row.incident_id);
setExpanded((current) => {
const next = new Set(current);
if (willOpen) next.add(row.incident_id);
else next.delete(row.incident_id);
return next;
});
if (willOpen && !details[row.incident_id]) {
void loadDetail(row.kind, row.incident_id);
}
},
[details, expanded, loadDetail],
);
const runAction = useCallback(
(row: RiskIncidentItem, action: 'ignore' | 'block') => {
const verb = action === 'block' ? '封禁' : '忽略';
modal.confirm({
title: `确认${verb}${row.subject_type === 'device' ? '设备' : '账户'}`,
content:
action === 'block'
? row.subject_type === 'device'
? '封禁后,该设备发送短信和一键登录会被直接拒绝,不影响它登录过的账户。'
: '封禁后,该账户不能发起比价、领取任务奖励或提现,现有金币和现金不会清零。'
: '忽略后,本风险事件会移出待处理列表,事实流水仍会保留。',
okText: verb,
okButtonProps: { danger: action === 'block' },
cancelText: '取消',
async onOk() {
setActing(row.incident_id);
try {
await api.post(`/admin/api/risk-monitor/incidents/${row.incident_id}/${action}`, {
reason: `风控监控页人工${verb}`,
});
void message.success(`${verb}成功`);
setExpanded((current) => {
const next = new Set(current);
next.delete(row.incident_id);
return next;
});
if (
(lists[row.kind]?.items.length ?? 0) === 1
&& listPageRef.current[row.kind] > 1
) {
const nextPages = {
...listPageRef.current,
[row.kind]: listPageRef.current[row.kind] - 1,
};
listPageRef.current = nextPages;
setListPage(nextPages);
}
await loadAll(true);
} catch (error) {
void message.error(errMsg(error));
throw error;
} finally {
setActing(null);
}
},
});
},
[lists, loadAll, message, modal],
);
const revokeRestriction = useCallback(
(row: RiskIncidentItem) => {
if (!row.restriction_id) {
void message.error('未找到有效的封禁记录,请刷新后重试');
return;
}
modal.confirm({
title: `确认解除该${row.subject_type === 'device' ? '设备' : '账户'}的封禁?`,
content:
row.subject_type === 'device'
? '解除后,该设备可以重新发送短信验证码和使用一键登录。'
: '解除后,该账户可以重新发起比价、领取任务奖励和提现。',
okText: '解除封禁',
cancelText: '取消',
async onOk() {
setActing(row.incident_id);
try {
await api.post(
`/admin/api/risk-monitor/restrictions/${row.restriction_id}/revoke`,
);
void message.success('解除封禁成功');
setExpanded((current) => {
const next = new Set(current);
next.delete(row.incident_id);
return next;
});
if (
(lists[row.kind]?.items.length ?? 0) === 1
&& listPageRef.current[row.kind] > 1
) {
const nextPages = {
...listPageRef.current,
[row.kind]: listPageRef.current[row.kind] - 1,
};
listPageRef.current = nextPages;
setListPage(nextPages);
}
await loadAll(true);
} catch (error) {
void message.error(errMsg(error, '解除封禁失败'));
throw error;
} finally {
setActing(null);
}
},
});
},
[lists, loadAll, message, modal],
);
const columns = useCallback(
(kind: RiskKind): ColumnsType<RiskIncidentItem> => {
const actionColumn = {
title: '操作',
key: 'actions',
align: 'right' as const,
fixed: 'right' as const,
width: 180,
render: (_: unknown, row: RiskIncidentItem) => {
const open = expanded.has(row.incident_id);
return (
<span className={styles.actionGroup}>
<Button
className={styles.expandButton}
size="small"
loading={detailLoading.has(row.incident_id)}
icon={open ? <DownOutlined /> : <RightOutlined />}
onClick={() => toggle(row)}
>
{open ? '收起' : '展开'}
</Button>
{row.status === 'open' && (
<>
<Button
size="small"
danger
loading={acting === row.incident_id}
onClick={() => runAction(row, 'block')}
>
</Button>
<Button
size="small"
loading={acting === row.incident_id}
onClick={() => runAction(row, 'ignore')}
>
</Button>
</>
)}
{row.status === 'blocked' && (
<Button
size="small"
loading={acting === row.incident_id}
disabled={!row.restriction_id}
onClick={() => revokeRestriction(row)}
>
</Button>
)}
</span>
);
},
};
if (kind === 'compare') {
return [
{ title: '账户手机号', dataIndex: 'phone', width: 130, render: (v) => v || '-' },
{
title: '注册时间',
dataIndex: 'registered_at',
width: 105,
render: (v) => utcTime(v),
},
{
title: '常用设备',
dataIndex: 'common_device_id',
width: 180,
render: (v) => <DeviceId value={v} onCopy={copy} />,
},
{ title: '触发时段', key: 'period', width: 180, render: (_, row) => period(row) },
{
title: '首次触发',
dataIndex: 'triggered_at',
width: 125,
render: (v) => eventTime(v, kind),
},
actionColumn,
];
}
return [
{ title: '设备型号', dataIndex: 'device_model', width: 120, render: (v) => v || '-' },
{
title: '设备 ID',
dataIndex: 'subject_id',
width: 190,
render: (v) => <DeviceId value={v} onCopy={copy} />,
},
{
title: '首次使用',
dataIndex: 'first_used_at',
width: 110,
render: (v) => eventTime(v, kind),
},
{ title: '触发时段', key: 'period', width: 180, render: (_, row) => period(row) },
{
title: '首次触发',
dataIndex: 'triggered_at',
width: 110,
render: (v) => eventTime(v, kind),
},
actionColumn,
];
},
[acting, copy, detailLoading, expanded, revokeRestriction, runAction, toggle],
);
const cards = useMemo(() => {
if (!summary) return [];
const byKind = Object.fromEntries(summary.cards.map((card) => [card.kind, card]));
return RISK_KINDS
.map((kind) => byKind[kind])
.filter(Boolean) as RiskSummaryCard[];
}, [summary]);
return (
<main className={styles.page}>
<header className={styles.hero}>
<div className={styles.titleCluster}>
<span className={styles.back}> </span>
<span className={styles.brandMark}></span>
<div>
<h1 className={styles.title}></h1>
<div className={styles.subtitle}> / / </div>
</div>
</div>
<div className={styles.updated}>
<span className={styles.updatedMeta}>
<span>{summary ? dayjs(summary.date).format('YYYY-MM-DD') : '---- -- --'}</span>
<span></span>
<span className={styles.dot} />
<span></span>
</span>
<Button
type="text"
size="small"
icon={<ReloadOutlined />}
loading={loading}
aria-label="刷新风控数据"
onClick={() => void loadAll()}
/>
<Tooltip title="三类待处理报警归零,历史流水和封禁状态不变">
<Button
size="small"
icon={<ClearOutlined />}
loading={resetting}
onClick={resetAlerts}
>
</Button>
</Tooltip>
</div>
</header>
{loading && !summary ? (
<Skeleton active paragraph={{ rows: 10 }} />
) : (
<>
<section className={styles.summaryGrid}>
{cards.map((card) => {
const meta = KIND_META[card.kind];
return (
<article key={card.kind} className={styles.summaryCard}>
<div className={styles.summaryTitle}>{meta.summaryTitle}</div>
<div>
<span className={styles.summaryValue}>{card.alert_subject_count}</span>
<span className={styles.summaryUnit}>{meta.unit}</span>
</div>
<div className={styles.summarySub}>
{meta.totalLabel} {integer(card.today_total)}
</div>
<button
type="button"
className={styles.rule}
onClick={openRuleSettings}
aria-label={`编辑${meta.title}告警规则`}
>
<span>{card.rule_text.replace(/≥.*$/, '')}</span>
<strong> {card.threshold} </strong>
<EditOutlined className={styles.ruleEditIcon} />
</button>
</article>
);
})}
</section>
<div className={styles.statusToolbar}>
<div>
<strong></strong>
<span>
{incidentStatus === 'open'
? '查看待处理报警,可执行封禁或忽略'
: '查看当前已封禁主体,可恢复其业务权限'}
</span>
</div>
<Segmented
value={incidentStatus}
options={[
{ label: '待处理', value: 'open' },
{ label: '已封禁', value: 'blocked' },
]}
onChange={(value) => changeIncidentStatus(value as IncidentStatus)}
/>
</div>
{RISK_KINDS.map((kind) => {
const data = lists[kind]?.items ?? [];
return (
<section key={kind} className={styles.section}>
<h2 className={styles.sectionTitle}>{KIND_META[kind].title}</h2>
<Table
rowKey="incident_id"
size="middle"
columns={columns(kind)}
dataSource={data}
tableLayout="fixed"
scroll={{ x: kind === 'compare' ? 900 : 890 }}
locale={{
emptyText: (
<Empty
description={
incidentStatus === 'open'
? '当前没有待处理风险'
: '当前没有已封禁主体'
}
/>
),
}}
pagination={{
current: listPage[kind],
pageSize: LIST_PAGE_SIZE,
total: lists[kind]?.total ?? 0,
hideOnSinglePage: true,
showSizeChanger: false,
onChange: (page) => void changeListPage(kind, page),
}}
expandable={{
expandedRowKeys: [...expanded],
showExpandColumn: false,
expandedRowRender: (row) => (
<DetailTable
detail={details[row.incident_id]}
loading={detailLoading.has(row.incident_id)}
page={detailPage[row.incident_id] || 1}
onPage={(page) => void loadDetail(row.kind, row.incident_id, page)}
/>
),
}}
/>
</section>
);
})}
<footer className={styles.footerNote}>
<strong></strong>
线
</footer>
</>
)}
<Modal
title="风控规则设置"
open={ruleOpen}
okText="保存并立即生效"
cancelText="取消"
confirmLoading={ruleSaving}
onOk={() => void saveRules()}
onCancel={() => setRuleOpen(false)}
destroyOnHidden
>
<p className={styles.ruleDialogIntro}>
</p>
<div className={styles.ruleSettings}>
{RISK_KINDS.map((kind) => {
const meta = KIND_META[kind];
const limits = RULE_LIMITS[kind];
return (
<div key={kind} className={styles.ruleSettingRow}>
<div className={styles.ruleSettingCopy}>
<strong>{meta.summaryTitle}</strong>
<span>{limits.help}</span>
</div>
<div className={styles.ruleValueEditor}>
<InputNumber
min={limits.min}
max={limits.max}
precision={0}
value={ruleDraft[kind]}
onChange={(value) => {
if (value == null) return;
setRuleDraft((current) => ({ ...current, [kind]: value }));
}}
/>
<span></span>
</div>
</div>
);
})}
</div>
</Modal>
</main>
);
}
+10 -65
View File
@@ -13,11 +13,6 @@ import { formatUtcTime } from '@/lib/format';
import { usePagedList } from '@/lib/usePagedList';
import { AdjustCashModal, AdjustCoinModal } from '@/components/AdjustBalanceModals';
import { DeleteUserModal } from '@/components/DeleteUserModal';
import {
clearUserRisk,
UserRiskModal,
type RiskUser,
} from '@/components/UserRiskModal';
import type { UserListItem } from '@/lib/types';
const { RangePicker } = DatePicker;
@@ -54,7 +49,6 @@ export default function UsersPage() {
const [coinUser, setCoinUser] = useState<UserListItem | null>(null);
const [cashUser, setCashUser] = useState<UserListItem | null>(null);
const [delUser, setDelUser] = useState<UserListItem | null>(null);
const [riskUser, setRiskUser] = useState<RiskUser | null>(null);
const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([]);
// 筛选/排序变化后清空已选(避免选中项跨筛选错位)
@@ -140,22 +134,6 @@ export default function UsersPage() {
});
};
const markNormalRisk = (u: UserListItem) => {
modal.confirm({
title: `确认将用户 ${u.phone} 标记为非高风险?`,
content: '确认后将清空当前高风险备注。',
onOk: async () => {
try {
await clearUserRisk(u.id);
message.success('已标记为非高风险');
reload();
} catch (error) {
message.error(errMsg(error));
}
},
});
};
// 一次性操作:点一下把该用户标记为「未看过引导」,下次打开 App 重看一遍,看完后端自动恢复(只触发这一次)。
// 用户尚未重看前可「撤销」(把 force_onboarding 置回 false),纠正误点。
const setForceOnboarding = (u: UserListItem, enable: boolean) => {
@@ -235,38 +213,26 @@ export default function UsersPage() {
};
const columns: ColumnsType<UserListItem> = [
{ title: 'ID', dataIndex: 'id', width: 60, sorter: true, sortOrder: sortOrderOf('id') },
{ title: '手机号', dataIndex: 'phone', width: 115 },
{ title: 'ID', dataIndex: 'id', width: 80, sorter: true, sortOrder: sortOrderOf('id') },
{ title: '手机号', dataIndex: 'phone', width: 130 },
{
title: '昵称',
dataIndex: 'nickname',
width: 130,
width: 150,
ellipsis: true,
render: (v: string | null) => v || '-',
},
{
title: '用户标识',
dataIndex: 'is_high_risk',
width: 95,
render: (_: boolean, user: UserListItem) => (
<Tooltip title={user.is_high_risk ? user.high_risk_note || '暂无高风险备注' : undefined}>
<Tag color={user.is_high_risk ? 'red' : 'default'}>
{user.is_high_risk ? '高风险' : '非高风险'}
</Tag>
</Tooltip>
),
},
{ title: '渠道', dataIndex: 'register_channel', width: 70 },
{ title: '渠道', dataIndex: 'register_channel', width: 90 },
{
title: '状态',
dataIndex: 'status',
width: 80,
width: 90,
render: (s: string) => <Tag color={STATUS_COLOR[s]}>{s}</Tag>,
},
{
title: '注册时间',
dataIndex: 'created_at',
width: 140,
width: 160,
sorter: true,
sortOrder: sortOrderOf('created_at'),
render: (v: string) => formatUtcTime(v),
@@ -279,7 +245,7 @@ export default function UsersPage() {
</Tooltip>
),
dataIndex: 'last_active_at',
width: 140,
width: 160,
sorter: true,
// 关掉 antd 默认的「点击升序/降序」表头提示,否则与上面自定义口径 Tooltip 同时弹出互相遮挡
showSorterTooltip: false,
@@ -290,14 +256,9 @@ export default function UsersPage() {
title: '操作',
key: 'op',
fixed: 'right',
width: 540,
width: 340,
render: (_: unknown, u: UserListItem) => (
<Space
size={6}
wrap={false}
style={{ whiteSpace: 'nowrap' }}
onClick={(e) => e.stopPropagation()}
>
<Space wrap={false} onClick={(e) => e.stopPropagation()}>
<a onClick={() => router.push(`/users/${u.id}`)}></a>
{canCoins && <a onClick={() => setCoinUser(u)}></a>}
{canCoins && <a onClick={() => setCashUser(u)}></a>}
@@ -309,16 +270,6 @@ export default function UsersPage() {
{u.debug_trace_enabled ? '关调试链接' : '开调试链接'}
</a>
)}
{canStatus &&
u.status !== 'deleted' &&
(u.is_high_risk ? (
<>
<a onClick={() => setRiskUser(u)}></a>
<a onClick={() => markNormalRisk(u)}></a>
</>
) : (
<a onClick={() => setRiskUser(u)}></a>
))}
{canStatus &&
u.status !== 'deleted' &&
(u.force_onboarding ? (
@@ -441,7 +392,7 @@ export default function UsersPage() {
showTotal: (t) => `${t} 个用户`,
onChange: onPageChange,
}}
scroll={{ x: 1400 }}
scroll={{ x: 1200 }}
onChange={onTableChange}
/>
@@ -453,12 +404,6 @@ export default function UsersPage() {
onClose={() => setDelUser(null)}
onDone={reload}
/>
<UserRiskModal
user={riskUser}
open={!!riskUser}
onClose={() => setRiskUser(null)}
onDone={reload}
/>
</div>
);
}
+20 -51
View File
@@ -4,13 +4,11 @@ import { useCallback, useEffect, useState } from 'react';
import {
DatePicker,
Descriptions,
Input,
Radio,
Space,
Table,
Tag,
Typography,
Tooltip,
message,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
@@ -41,18 +39,12 @@ const PAGE_SIZE = 10; // 金币记录每页条数
interface Props {
userId: number;
user: WithdrawUserSnapshot | null;
withdrawSource?: 'coin_cash' | 'invite_cash';
// 统计区字段集:withdraw(默认,提现详情:含提现细分) / ad(广告收益详情:只看看广告观看统计,对齐参考图 6 项)
statsVariant?: 'withdraw' | 'ad';
}
/** 用户看广告/提现详情:基本信息 + 互斥时间筛选 + 统计区(按 statsVariant 取字段集)+ 金币发放记录表。 */
export default function UserRewardPanel({
userId,
user,
withdrawSource,
statsVariant = 'withdraw',
}: Props) {
export default function UserRewardPanel({ userId, user, statsVariant = 'withdraw' }: Props) {
const [mode, setMode] = useState<'all' | 'range'>('all'); // all=注册至今 / range=自定义区间
const [range, setRange] = useState<[Dayjs, Dayjs] | null>(null);
const [stats, setStats] = useState<UserRewardStats | null>(null);
@@ -77,10 +69,7 @@ export default function UserRewardPanel({
setStatsLoading(true);
try {
const { data } = await api.get<UserRewardStats>(`/admin/api/users/${userId}/reward-stats`, {
params: {
...JSON.parse(paramsKey),
...(withdrawSource ? { withdraw_source: withdrawSource } : {}),
},
params: JSON.parse(paramsKey),
});
setStats(data);
} catch (e) {
@@ -88,7 +77,7 @@ export default function UserRewardPanel({
} finally {
setStatsLoading(false);
}
}, [userId, paramsKey, withdrawSource]);
}, [userId, paramsKey]);
const loadRecords = useCallback(
async (p: number) => {
@@ -146,13 +135,6 @@ export default function UserRewardPanel({
<Space size="large" wrap>
<span>
<Text strong>{user?.phone || '-'}</Text>
{user && (
<Tooltip title={user.is_high_risk ? user.high_risk_note || '暂无高风险备注' : undefined}>
<Tag color={user.is_high_risk ? 'red' : 'default'} style={{ marginInlineStart: 8 }}>
{user.is_high_risk ? '高风险' : '非高风险'}
</Tag>
</Tooltip>
)}
</span>
<span>
<Text strong>{user?.nickname || '-'}</Text>
@@ -178,7 +160,6 @@ export default function UserRewardPanel({
<RangePicker
size="small"
disabled={mode !== 'range'}
allowEmpty={[true, true]}
value={range}
onChange={(v) => setRange(v as [Dayjs, Dayjs] | null)}
/>
@@ -187,7 +168,7 @@ export default function UserRewardPanel({
{/* 统计区(受时间筛选;现金余额为当前快照)。ad 视图只保留看广告观看统计(对齐参考图 6 项) */}
<Descriptions bordered size="small" column={2} style={{ marginBottom: 8 }}>
<Descriptions.Item label="累计成功提现">
<Descriptions.Item label="累计提现">
{stats ? yuan(stats.withdraw_success_cents) : '-'}
</Descriptions.Item>
<Descriptions.Item label="现金余额">
@@ -195,40 +176,40 @@ export default function UserRewardPanel({
</Descriptions.Item>
{statsVariant === 'ad' ? (
<>
<Descriptions.Item label="激励视频成功发奖次数">
<Descriptions.Item label="激励视频观看数">
{stats?.reward_video_count ?? '-'}
</Descriptions.Item>
{/* eCPM 均按元展示(reward_video / feed avg_ecpm 原始为分/千次,÷100 转元) */}
<Descriptions.Item label="预估平均激励视频ECPM">
<Descriptions.Item label="平均激励视频ECPM">
{stats ? `${(stats.reward_video_avg_ecpm / 100).toFixed(2)} 元/千` : '-'}
</Descriptions.Item>
<Descriptions.Item label="Draw信息流奖励份数">
<Descriptions.Item label="draw信息流视频观看数">
{stats?.feed_count ?? '-'}
</Descriptions.Item>
<Descriptions.Item label="预估平均Draw信息流ECPM">
<Descriptions.Item label="平均draw信息流ECPM">
{stats ? `${(stats.feed_avg_ecpm / 100).toFixed(2)} 元/千` : '-'}
</Descriptions.Item>
</>
) : (
<>
<Descriptions.Item label="提现申请总次数">{stats?.withdraw_total ?? '-'}</Descriptions.Item>
<Descriptions.Item label="传统任务累计收益">
<Descriptions.Item label="提现总次数">{stats?.withdraw_total ?? '-'}</Descriptions.Item>
<Descriptions.Item label="传统任务提现">
{stats ? yuan(stats.traditional_task_cash_cents) : '-'}
</Descriptions.Item>
<Descriptions.Item label="激励视频成功发奖次数">
<Descriptions.Item label="累计激励视频数">
{stats?.reward_video_count ?? '-'}
</Descriptions.Item>
<Descriptions.Item label="预估平均激励视频ECPM">
<Descriptions.Item label="平均激励视频ECPM">
{stats ? `${stats.reward_video_avg_ecpm} 分/千` : '-'}
</Descriptions.Item>
<Descriptions.Item label="激励视频累计收益">
<Descriptions.Item label="激励视频提现">
{stats ? yuan(stats.reward_video_cash_cents) : '-'}
</Descriptions.Item>
<Descriptions.Item label="信息流奖励份数">{stats?.feed_count ?? '-'}</Descriptions.Item>
<Descriptions.Item label="预估平均信息流广告ECPM">
<Descriptions.Item label="累计信息流广告数">{stats?.feed_count ?? '-'}</Descriptions.Item>
<Descriptions.Item label="平均信息流广告ECPM">
{stats ? `${stats.feed_avg_ecpm} 分/千` : '-'}
</Descriptions.Item>
<Descriptions.Item label="信息流广告累计收益">
<Descriptions.Item label="信息流广告提现">
{stats ? yuan(stats.feed_cash_cents) : '-'}
</Descriptions.Item>
</>
@@ -236,24 +217,12 @@ export default function UserRewardPanel({
</Descriptions>
<Text type="secondary" style={{ fontSize: 12 }}>
{statsVariant === 'ad'
? '统计随上方时间筛选(现金余额除外,为当前快照);次数仅统计成功发奖记录,信息流按奖励份数统计;eCPM 为预估值。'
: '统计随上方时间筛选(现金余额除外,为当前快照);提现按申请提交时间统计;累计收益为已发金币按当前汇率折算,不代表实际已提现金额;eCPM 为预估值。'}
? '统计随上方时间筛选(现金余额除外,为当前快照);eCPM 均按元展示(原始分/千次 ÷100)。'
: '统计随上方时间筛选(现金余额除外,为当前快照);eCPM 单位分/千次,同金币审计。'}
</Text>
{user?.is_high_risk && (
<div style={{ marginTop: 16 }}>
<Text strong></Text>
<Input.TextArea
readOnly
value={user.high_risk_note || ''}
rows={3}
style={{ marginTop: 8 }}
/>
</div>
)}
{/* 主要金币发放记录 */}
<h4 style={{ margin: '16px 0 8px' }}></h4>
{/* 金币记录 */}
<h4 style={{ margin: '16px 0 8px' }}></h4>
<Table
rowKey={(r) => `${r.source}-${r.created_at}-${r.coin}-${r.ecpm ?? ''}`}
size="small"
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+5 -18
View File
@@ -1,26 +1,13 @@
'use client';
import { useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { getToken } from '@/lib/auth';
export default function Home() {
const router = useRouter();
useEffect(() => {
window.location.replace(getToken() ? '/dashboard' : '/login');
}, []);
return (
<main
style={{
minHeight: '100vh',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
background: '#f0f2f5',
color: '#595959',
fontFamily: 'system-ui, sans-serif',
}}
>
</main>
);
router.replace(getToken() ? '/dashboard' : '/login');
}, [router]);
return null;
}
-81
View File
@@ -1,81 +0,0 @@
'use client';
import { useEffect, useState } from 'react';
import { App, Input, Modal } from 'antd';
import { api, errMsg } from '@/lib/api';
export type RiskUser = {
id: number;
phone: string;
is_high_risk: boolean;
high_risk_note: string | null;
};
type Props = {
user: RiskUser | null;
open: boolean;
onClose: () => void;
onDone: () => void | Promise<void>;
};
export function UserRiskModal({ user, open, onClose, onDone }: Props) {
const { message } = App.useApp();
const [note, setNote] = useState('');
const [saving, setSaving] = useState(false);
useEffect(() => {
if (open) setNote(user?.high_risk_note ?? '');
}, [open, user]);
const save = async () => {
if (!user) return;
const trimmed = note.trim();
if (!trimmed) {
message.warning('请输入标记为高风险的原因');
return;
}
setSaving(true);
try {
await api.post(`/admin/api/users/${user.id}/risk`, {
is_high_risk: true,
note: trimmed,
});
message.success(user.is_high_risk ? '高风险备注已更新' : '已标记为高风险');
await onDone();
onClose();
} catch (error) {
message.error(errMsg(error));
} finally {
setSaving(false);
}
};
return (
<Modal
title="高风险备注"
open={open}
okText="保存"
confirmLoading={saving}
onOk={save}
onCancel={onClose}
destroyOnHidden
>
<Input.TextArea
autoFocus
rows={5}
maxLength={500}
showCount
value={note}
placeholder="请输入标记为高风险的原因"
onChange={(event) => setNote(event.target.value)}
/>
</Modal>
);
}
export async function clearUserRisk(userId: number) {
await api.post(`/admin/api/users/${userId}/risk`, {
is_high_risk: false,
note: null,
});
}
-33
View File
@@ -1,33 +0,0 @@
export interface BulkReviewItemResult {
id: number;
ok: boolean;
status: string | null;
error: string | null;
}
export interface BulkReviewResult {
total: number;
success: number;
failed: number;
items: BulkReviewItemResult[];
}
export const BULK_REVIEW_MAX = 50;
export function failedReviewIds(result: BulkReviewResult): number[] {
return result.items.filter((item) => !item.ok).map((item) => item.id);
}
export function bulkFailureReasonText(result: BulkReviewResult): string {
const reasons = Array.from(
new Set(
result.items
.filter((item) => !item.ok)
.map((item) => item.error?.trim())
.filter((reason): reason is string => Boolean(reason)),
),
);
if (!reasons.length) return '';
const visible = reasons.slice(0, 3);
return `;原因:${visible.join('')}${reasons.length > visible.length ? ';…' : ''}`;
}
-14
View File
@@ -1,14 +0,0 @@
export type ReviewBadgeKey =
| '/invite-withdraws'
| '/withdraws'
| '/price-reports'
| '/feedbacks';
export const REVIEW_BADGE_REFRESH_EVENT = 'review-badge-refresh';
export function refreshReviewBadge(key: ReviewBadgeKey) {
if (typeof window === 'undefined') return;
window.dispatchEvent(
new CustomEvent<ReviewBadgeKey>(REVIEW_BADGE_REFRESH_EVENT, { detail: key }),
);
}
+22 -144
View File
@@ -52,8 +52,6 @@ export interface UserListItem {
status: string;
// 调试链接权限:开了的用户在 App 比价结果页/记录页可复制 price.shaguabijia.com 的 trace 调试链接
debug_trace_enabled: boolean;
is_high_risk: boolean;
high_risk_note: string | null;
// 运营「一键开启新手引导」:true = 该用户下次打开 App 会被强制重走新手引导,走完自动取消
force_onboarding: boolean;
wechat_openid: string | null;
@@ -145,6 +143,7 @@ export interface WithdrawOrder {
amount_cents: number;
// 提现类型:coin_cash(福利页提现,金币兑换现金) / invite_cash(邀请提现,邀请奖励金)
source: string;
user_name: string | null;
status: string; // reviewing / pending / success / failed / rejected
wechat_state: string | null;
transfer_bill_no: string | null;
@@ -158,8 +157,6 @@ export interface WithdrawOrder {
export interface WithdrawListItem extends WithdrawOrder {
phone: string | null;
nickname: string | null;
is_high_risk: boolean;
high_risk_note: string | null;
cumulative_success_cents: number; // 累计成功提现(分)
}
@@ -177,8 +174,6 @@ export interface WithdrawUserSnapshot {
id: number;
phone: string;
nickname: string | null;
is_high_risk: boolean;
high_risk_note: string | null;
status: string;
wechat_nickname: string | null;
wechat_avatar_url: string | null;
@@ -189,34 +184,14 @@ export interface WithdrawUserSnapshot {
withdraw_success_cents: number;
}
export interface InviteeDetail {
user_id: number;
phone: string;
registered_at: string;
invite_success: boolean;
first_compare_store: string | null;
first_compare_products: string | null;
first_order_store: string | null;
first_order_products: string | null;
first_order_amount_cents: number | null;
}
export interface InviteOverview {
invite_total: number;
invite_success_total: number;
items: InviteeDetail[];
}
export interface WithdrawDetail {
order: WithdrawOrder;
user: WithdrawUserSnapshot | null;
cumulative_success_cents: number;
risk_flags: string[];
risk_score: number;
recent_withdraws: WithdrawOrder[];
recent_cash_transactions: CashTxn[];
audit_logs: AuditLog[];
invite_overview: InviteOverview | null;
}
// 提现详情抽屉「用户统计区」:按时间窗口算的提现 + 看广告行为统计。
@@ -243,92 +218,6 @@ export interface UserCoinRecord {
coin: number;
}
// ===== 风控监控 =====
export type RiskKind = 'sms' | 'oneclick' | 'compare';
export interface RiskSummaryCard {
kind: RiskKind;
alert_subject_count: number;
today_total: number;
threshold: number;
rule_text: string;
}
export interface RiskMonitorSummary {
date: string;
updated_at: string;
cards: RiskSummaryCard[];
}
export interface RiskRuleConfig {
sms_hourly_threshold: number;
oneclick_daily_threshold: number;
compare_daily_threshold: number;
}
export interface RiskResetResponse {
ok: boolean;
reset_at: string;
reset_incident_count: number;
reset_counts: Record<RiskKind, number>;
}
export interface RiskIncidentItem {
incident_id: number;
kind: RiskKind;
subject_type: 'device' | 'user';
subject_id: string;
device_model: string | null;
first_used_at: string | null;
phone: string | null;
user_id: number | null;
registered_at: string | null;
common_device_id: string | null;
window_start: string;
window_end: string;
first_event_at: string;
triggered_at: string;
last_event_at: string;
event_count: number;
status: 'open' | 'ignored' | 'blocked' | 'resolved';
restricted: boolean;
restriction_id: number | null;
}
export interface RiskIncidentPage {
items: RiskIncidentItem[];
next_cursor: number | null;
total: number;
}
export interface RiskDetailItem {
id: number;
occurred_at: string;
outcome: string;
phone: string | null;
user_id: number | null;
username: string | null;
account_registered_at: string | null;
verified: boolean | null;
reason: string | null;
store_name: string | null;
product_names: string | null;
prices: Record<string, number | null> | null;
saved_amount_yuan: number | null;
status: string | null;
}
export interface RiskDetailPage {
kind: RiskKind;
incident_id: number;
event_count: number;
distinct_accounts: number | null;
items: RiskDetailItem[];
next_cursor: number | null;
total: number;
}
export interface WithdrawBulkItemResult {
out_bill_no: string;
ok: boolean;
@@ -343,6 +232,26 @@ export interface WithdrawBulkResult {
items: WithdrawBulkItemResult[];
}
export interface WithdrawLedgerCheck {
ok: boolean;
// 普通现金账(coin_cash)
cash_balance_total_cents: number;
cash_transaction_total_cents: number;
balance_diff_cents: number;
missing_withdraw_txn_count: number;
missing_refund_txn_count: number;
duplicate_refund_txn_count: number;
refund_txn_on_non_terminal_count: number;
// 邀请奖励金账(invite_cash:与普通现金物理隔离,各自对账)
invite_cash_balance_total_cents: number;
invite_cash_transaction_total_cents: number;
invite_balance_diff_cents: number;
invite_missing_withdraw_txn_count: number;
invite_missing_refund_txn_count: number;
invite_duplicate_refund_txn_count: number;
invite_refund_txn_on_non_terminal_count: number;
}
export interface WxpayHealthCheck {
ok: boolean;
wxpay_configured: boolean;
@@ -408,18 +317,6 @@ export interface FeedbackQrConfig {
updated_at: string | null;
}
/** ( 3 广, 120 )
* enabled + ;, */
export interface GuideVideoConfig {
enabled: boolean;
video_url: string | null; // /media/guide_video/xxx.mp4;null = 未配片(浮层照旧只放广告)
max_plays: number; // 每个账号前 N 次浮层放引导视频(服务端默认 3,后台不开放调整)
reward_coin: number; // 每次固定金币(服务端默认 120,播完 / 中途关闭都发)
updated_at: string | null;
total_plays: number; // 只读统计:全站已播次数(后台不再展示)
granted_plays: number; // 只读统计:其中已发币次数(后台不再展示)
}
export interface AuditLog {
id: number;
admin_id: number;
@@ -467,25 +364,6 @@ export interface ComparisonRecordListItem {
created_at: string;
}
export interface ComparisonRecordsSummary {
started: number;
completed: number;
success: number;
success_rate: number | null;
avg_token_cost: number | null;
lower_price_rate: number | null;
avg_duration_ms: number | null;
p5_duration_ms: number | null;
p50_duration_ms: number | null;
p95_duration_ms: number | null;
p99_duration_ms: number | null;
cancelled: number;
cancelled_rate: number | null;
cancelled_p5_ms: number | null;
cancelled_p50_ms: number | null;
cancelled_p95_ms: number | null;
}
// 单次 LLM 调用明细(pricebot chat() 收口落盘,server 按 trace 拉来)
export interface LlmCall {
ts?: number;
@@ -591,7 +469,7 @@ export interface AdRevenueRow {
has_impression: boolean; // 是否有广告展示(信息流逐条展示=true,纯发奖行=false)
impressions: number; // 本行展示条数 1/0(供日汇总、趋势图复用)
ecpm: string | null; // 分/千次;展示行取展示值,纯发奖行取发奖采用值
revenue_yuan: number; // 本次有效展示预估收益(元);纯发奖、激励视频提前关闭/时长不足=0
revenue_yuan: number; // 本次展示预估收益(元);纯发奖=0
row_revenue_yuan?: number | null; // 主表逐行显示用:一次比价/领券聚合行=该次发奖广告 eCPM 折算之和;其它行空(回退 revenue_yuan)
adn: string | null; // 实际填充 ADN;纯发奖行为空
slot_id: string | null; // 底层 mediation rit;纯发奖行为空