Compare commits

..

4 Commits

Author SHA1 Message Date
linkeyu ea483ce281 fix(admin): 领券广告收益未填充时显示明确文案 (#52)
## 修改内容
- 广告收益字段支持 null
- null 显示未填充
- 真实零收益仍显示 ¥0.0000

## 验证
- TypeScript 类型检查通过
- Next.js 生产构建通过

---------

Co-authored-by: linkeyu <798648091@qq.com>
Reviewed-on: #52
Co-authored-by: linkeyu <linkeyu@wonderable.ai>
Co-committed-by: linkeyu <linkeyu@wonderable.ai>
2026-07-21 10:14:12 +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
10 changed files with 141 additions and 592 deletions
+20 -127
View File
@@ -66,89 +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: '已完成' },
// 发奖状态 → 颜色 + 中文(含「不发金币的原因」:提前关闭/未满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: '未知' },
};
function rewardStatuses(row: AdRevenueRow): string[] {
if (row.sub_rewards?.length) return row.sub_rewards.map((reward) => reward.status);
return row.status ? [row.status] : [];
}
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 '-';
@@ -368,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>();
@@ -403,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,
@@ -446,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(() => {
@@ -553,20 +481,12 @@ export default function AdRevenueReportPage() {
},
{
title: '发奖状态',
key: 'reward_status',
dataIndex: 'status',
width: 100,
render: (_: unknown, row: AdRevenueRow) => {
const tag = rewardStatusTag(row);
return <Tooltip title={tag.hint}><Tag color={tag.color}>{tag.label}</Tag></Tooltip>;
},
},
{
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>;
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>;
},
},
{
@@ -608,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',
@@ -701,8 +620,7 @@ export default function AdRevenueReportPage() {
<br />
<b>穿(T+1)</b>穿 GroMore API(,):
<b>穿</b>= revenue<b>API</b>= ADN 穿//,
<b></b>(//);穿
+ ;广
<b></b>(//);,
</div>
}
>
@@ -737,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,
+21 -152
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,100 +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 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 }}>
{score}
</Button>
</Popover>
);
}
// ms → "1.5s"(空值显示 -)
const fmtSec = (ms: number | null | undefined): string =>
ms == null ? '-' : `${(ms / 1000).toFixed(1)}s`;
@@ -247,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': '美团',
@@ -602,10 +497,20 @@ export default function CouponDataPage() {
render: (v: number | null) => fmtSec(v),
},
{
title: '百分比',
title: '点位成功率',
key: 'point_success_rate',
width: 110,
render: (_: unknown, r: CouponDataRow) => <PointScorePopover row={r} />,
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: '广告收益',
@@ -692,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 (
@@ -813,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>
@@ -838,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">
+1 -6
View File
@@ -20,7 +20,6 @@ import type { Dayjs } from 'dayjs';
import { api } from '@/lib/api';
import { canDo } from '@/lib/auth';
import { formatWallTime } from '@/lib/format';
import { refreshReviewBadge } from '@/lib/reviewBadge';
import { usePagedList } from '@/lib/usePagedList';
import type { Feedback, FeedbackSummary } from '@/lib/types';
import FeedbackHandleDrawer from './FeedbackHandleDrawer';
@@ -432,11 +431,7 @@ export default function FeedbacksPage() {
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>
);
}
+4 -101
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,7 +16,6 @@ import {
MoneyCollectOutlined,
NotificationOutlined,
ProfileOutlined,
SafetyCertificateOutlined,
SettingOutlined,
ShareAltOutlined,
TeamOutlined,
@@ -25,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;
@@ -88,7 +78,6 @@ 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: '用户管理' },
],
},
@@ -105,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();
@@ -125,44 +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') {
count = (await api.get<WithdrawSummary>('/admin/api/withdraws/summary')).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('/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)
@@ -181,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');
@@ -229,7 +164,6 @@ export default function MainLayout({ children }: { children: React.ReactNode })
aria-label={item.label}
>
{item.icon}
{reviewBadge(item.key)}
</button>
</Tooltip>
))
@@ -247,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>
);
}
@@ -267,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>
@@ -335,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 {
@@ -421,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;
@@ -432,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;
-3
View File
@@ -22,7 +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 { usePagedList } from '@/lib/usePagedList';
import type { PriceReport, PriceReportSummary } from '@/lib/types';
import UserRecordsDrawer from '@/components/UserRecordsDrawer';
@@ -203,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) {
@@ -222,7 +220,6 @@ export default function PriceReportsPage() {
}
try {
await api.post(`/admin/api/price-reports/${rejecting.id}/reject`, { reason });
refreshReviewBadge('/price-reports');
message.success('已拒绝');
setRejecting(null);
setRejectReason('');
-4
View File
@@ -39,7 +39,6 @@ import dayjs, { type Dayjs } from 'dayjs';
import { api, errMsg } from '@/lib/api';
import { canDo } from '@/lib/auth';
import { formatUtcTime, utcDayjs, utcFromNow, yuan } from '@/lib/format';
import { refreshReviewBadge } from '@/lib/reviewBadge';
import { usePagedList } from '@/lib/usePagedList';
import type {
AuditLog,
@@ -333,7 +332,6 @@ export default function WithdrawsPage() {
onOk: async () => {
try {
await api.post(`/admin/api/withdraws/${o.out_bill_no}/approve`);
refreshReviewBadge('/withdraws');
message.success('已通过审核并发起打款');
await refreshAfterChange(o.out_bill_no);
} catch (e) {
@@ -364,7 +362,6 @@ export default function WithdrawsPage() {
await api.post(`/admin/api/withdraws/${targets[0].out_bill_no}/reject`, { reason: trimmed });
message.success('已拒绝并退回余额');
}
refreshReviewBadge('/withdraws');
setRejecting(null);
setBulkRejecting([]);
setRejectReason('');
@@ -403,7 +400,6 @@ export default function WithdrawsPage() {
const { data } = await api.post<WithdrawBulkResult>('/admin/api/withdraws/bulk/approve', {
out_bill_nos: selectedReviewing.map((item) => item.out_bill_no),
});
refreshReviewBadge('/withdraws');
const text = bulkResultText('批量通过完成', data);
if (data.failed) message.warning(text);
else message.success(text);
-10
View File
@@ -1,10 +0,0 @@
export type ReviewBadgeKey = '/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 }),
);
}
-19
View File
@@ -364,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;