Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ffad461d67 | |||
| f950bcd841 | |||
| b1bdb66a76 | |||
| c905e15ec9 | |||
| dd84d771f9 | |||
| b620948a71 | |||
| 281cfdb0e4 | |||
| 2727eaa929 | |||
| af74ecf9d3 | |||
| 3102a96bd3 |
@@ -0,0 +1,84 @@
|
||||
'use client';
|
||||
|
||||
// 点收益报表里的用户手机号 → 半屏抽屉展示该用户的广告收益详情(统计卡 + 金币记录)。
|
||||
// 复用「提现详情」里的 UserRewardPanel(数据走 /users/{id}/reward-stats + /coin-records);
|
||||
// 用户基本信息(昵称/注册时间/钱包)取自 /users/{id} 概览。抽屉样式(width 50% 半屏)与提现详情一致。
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Drawer } from 'antd';
|
||||
import { api } from '@/lib/api';
|
||||
import type { WithdrawUserSnapshot } from '@/lib/types';
|
||||
import UserRewardPanel from '../withdraws/UserRewardPanel';
|
||||
|
||||
// GET /admin/api/users/{id} 概览里我们要用到的子集(前端未单独定义 AdminUserOverview 类型)。
|
||||
interface UserOverviewResp {
|
||||
user: {
|
||||
id: number;
|
||||
phone: string;
|
||||
nickname: string | null;
|
||||
status: string;
|
||||
wechat_nickname: string | null;
|
||||
created_at: string;
|
||||
last_login_at: string;
|
||||
};
|
||||
cash_balance_cents: number;
|
||||
withdraw_total: number;
|
||||
withdraw_success_cents: number;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
userId: number | null;
|
||||
phone: string | null; // 报表行已有的手机号:概览拉取失败时兜底展示
|
||||
}
|
||||
|
||||
export default function UserAdRevenueDrawer({ open, onClose, userId, phone }: Props) {
|
||||
// UserRewardPanel 的 user 快照:它只读 phone/nickname/wechat_nickname/created_at,其余按 snapshot 形状补齐。
|
||||
const [user, setUser] = useState<WithdrawUserSnapshot | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || userId == null) return;
|
||||
let alive = true;
|
||||
setUser(null);
|
||||
api
|
||||
.get<UserOverviewResp>(`/admin/api/users/${userId}`)
|
||||
.then((r) => {
|
||||
if (!alive) return;
|
||||
const o = r.data;
|
||||
setUser({
|
||||
id: o.user.id,
|
||||
phone: o.user.phone,
|
||||
nickname: o.user.nickname,
|
||||
status: o.user.status,
|
||||
wechat_nickname: o.user.wechat_nickname, // 概览接口已返回微信昵称
|
||||
wechat_avatar_url: null,
|
||||
created_at: o.user.created_at,
|
||||
last_login_at: o.user.last_login_at,
|
||||
cash_balance_cents: o.cash_balance_cents,
|
||||
withdraw_total: o.withdraw_total,
|
||||
withdraw_success_cents: o.withdraw_success_cents,
|
||||
});
|
||||
})
|
||||
.catch(() => {
|
||||
// 概览失败:退回只带手机号,昵称/注册天数显示「-」,不阻塞统计/金币记录(它们由 userId 独立拉)
|
||||
if (alive) setUser(phone ? ({ phone } as WithdrawUserSnapshot) : null);
|
||||
});
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [open, userId, phone]);
|
||||
|
||||
return (
|
||||
<Drawer
|
||||
title={`用户广告收益详情${phone ? ` · ${phone}` : ''}`}
|
||||
width="50%"
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
destroyOnHidden
|
||||
>
|
||||
{/* userId 就绪即渲染;UserRewardPanel 内部按 userId 自行拉统计与金币记录,user 基本信息随后补上。
|
||||
statsVariant="ad":统计区只显示 6 项看广告统计(累计提现/现金余额/激励视频观看数+eCPM/draw观看数+eCPM) */}
|
||||
{userId != null && <UserRewardPanel userId={userId} user={user} statsVariant="ad" />}
|
||||
</Drawer>
|
||||
);
|
||||
}
|
||||
@@ -40,13 +40,15 @@ import type {
|
||||
AdRevenueRow,
|
||||
AdRevenueTypeStat,
|
||||
} from '@/lib/types';
|
||||
import UserAdRevenueDrawer from './UserAdRevenueDrawer';
|
||||
|
||||
const { RangePicker } = DatePicker;
|
||||
|
||||
// 广告类型标签
|
||||
const TYPE_TAG: Record<string, { color: string; label: string }> = {
|
||||
reward_video: { color: 'blue', label: '激励视频' },
|
||||
feed: { color: 'purple', label: '信息流' },
|
||||
// 历史误标 feed(领券/比价广告修 adType 之前上报)一律按 Draw 信息流显示——业务已全切 Draw
|
||||
feed: { color: 'geekblue', label: 'Draw 信息流' },
|
||||
draw: { color: 'geekblue', label: 'Draw 信息流' },
|
||||
withdrawal_video: { color: 'gold', label: '提现激励视频' },
|
||||
};
|
||||
@@ -131,12 +133,6 @@ const DETAIL_COLUMNS: ColumnsType<AdRevenueRecord> = [
|
||||
},
|
||||
{ title: '应发金币', dataIndex: 'expected_coin', width: 100, render: (v: number) => <b>{v}</b> },
|
||||
{ title: '实发金币', dataIndex: 'actual_coin', width: 100 },
|
||||
{
|
||||
title: '一致',
|
||||
dataIndex: 'matched',
|
||||
width: 80,
|
||||
render: (m: boolean) => (m ? <Tag color="green">✓</Tag> : <Tag color="red">✗ 不符</Tag>),
|
||||
},
|
||||
];
|
||||
|
||||
// 趋势图(纯 SVG,零依赖):柱=展示条数(左轴),橙线=客户端预估收益元(右轴),
|
||||
@@ -309,6 +305,8 @@ export default function AdRevenueReportPage() {
|
||||
const [queriedLimit, setQueriedLimit] = useState<number>(500);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [formulaOpen, setFormulaOpen] = useState(false);
|
||||
// 点用户手机号弹出的「用户广告收益详情」半屏抽屉(userId + 手机号;null=关闭)
|
||||
const [userDrawer, setUserDrawer] = useState<{ userId: number; phone: string | null } | null>(null);
|
||||
|
||||
// 当前选择是否跨多天:跨多天时「按小时」无意义,粒度强制按天
|
||||
const rangeMultiDay = range[0].format('YYYY-MM-DD') !== range[1].format('YYYY-MM-DD');
|
||||
@@ -364,25 +362,39 @@ export default function AdRevenueReportPage() {
|
||||
title: '用户',
|
||||
dataIndex: 'user_phone',
|
||||
width: 150,
|
||||
render: (phone: string | null, r: AdRevenueRow) =>
|
||||
phone ? (
|
||||
<span>
|
||||
{phone}
|
||||
<Typography.Text type="secondary" style={{ fontSize: 11, marginLeft: 6 }}>
|
||||
#{r.user_id}
|
||||
</Typography.Text>
|
||||
</span>
|
||||
) : (
|
||||
<Typography.Text type="secondary">#{r.user_id}(无手机号)</Typography.Text>
|
||||
),
|
||||
render: (phone: string | null, r: AdRevenueRow) => (
|
||||
// 点手机号/用户 → 打开该用户「广告收益详情」半屏抽屉(统计卡 + 金币记录)
|
||||
<a onClick={() => setUserDrawer({ userId: r.user_id, phone })}>
|
||||
{phone ? (
|
||||
<span>
|
||||
{phone}
|
||||
<Typography.Text type="secondary" style={{ fontSize: 11, marginLeft: 6 }}>
|
||||
#{r.user_id}
|
||||
</Typography.Text>
|
||||
</span>
|
||||
) : (
|
||||
<span>#{r.user_id}(无手机号)</span>
|
||||
)}
|
||||
</a>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '广告类型',
|
||||
dataIndex: 'ad_type',
|
||||
width: 110,
|
||||
render: (s: string) => {
|
||||
width: 130,
|
||||
render: (s: string, r: AdRevenueRow) => {
|
||||
const t = TYPE_TAG[s] ?? { color: 'default', label: s };
|
||||
return <Tag color={t.color}>{t.label}</Tag>;
|
||||
return (
|
||||
<span>
|
||||
<Tag color={t.color}>{t.label}</Tag>
|
||||
{/* 一次比价/领券聚合了多条广告时标出条数,点「+」展开看逐条 */}
|
||||
{r.sub_count && r.sub_count > 1 ? (
|
||||
<Typography.Text type="secondary" style={{ fontSize: 11 }}>
|
||||
{r.sub_count} 条
|
||||
</Typography.Text>
|
||||
) : null}
|
||||
</span>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -428,7 +440,11 @@ export default function AdRevenueReportPage() {
|
||||
dataIndex: 'revenue_yuan',
|
||||
width: 110,
|
||||
align: 'right',
|
||||
render: (v: number, r: AdRevenueRow) => (r.has_impression ? v.toFixed(4) : '-'),
|
||||
// 一次比价/领券聚合行用 row_revenue_yuan(该次发奖广告 eCPM 折算之和),其它行用展示侧 revenue_yuan
|
||||
render: (v: number, r: AdRevenueRow) => {
|
||||
const rev = r.row_revenue_yuan ?? v;
|
||||
return r.has_impression || rev > 0 ? rev.toFixed(4) : '-';
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '发奖状态',
|
||||
@@ -456,18 +472,6 @@ export default function AdRevenueReportPage() {
|
||||
render: (v: number, r: AdRevenueRow) =>
|
||||
r.has_reward ? v : <Typography.Text type="secondary">-</Typography.Text>,
|
||||
},
|
||||
{
|
||||
title: '一致',
|
||||
dataIndex: 'matched',
|
||||
width: 70,
|
||||
align: 'center',
|
||||
render: (m: boolean, r: AdRevenueRow) =>
|
||||
r.has_reward ? (
|
||||
m ? <Tag color="green">✓</Tag> : <Tag color="red">✗ 不符</Tag>
|
||||
) : (
|
||||
<Typography.Text type="secondary">-</Typography.Text>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '广告位ID',
|
||||
dataIndex: 'our_code_id',
|
||||
@@ -486,7 +490,7 @@ export default function AdRevenueReportPage() {
|
||||
|
||||
// 派生指标(全部基于全量 total_* 字段,不受分页影响,准):
|
||||
// 发奖成本(元)= 实发金币÷汇率;预估毛利 = 收益−发奖成本;发奖占收益比 = 发奖成本÷收益;
|
||||
// 应发实发差额(金币)= 应发−实发(正=少发/负=多发);ARPU = 预估收益÷今日DAU(仅今日)。
|
||||
// 应发实发差额(金币)= 应发−实发(正=少发/负=多发);ARPU = 区间预估收益÷区间活跃用户(见 dau)。
|
||||
const derived = data
|
||||
? {
|
||||
payoutYuan: data.total_actual_coin / COIN_PER_YUAN,
|
||||
@@ -496,11 +500,23 @@ export default function AdRevenueReportPage() {
|
||||
? (data.total_actual_coin / COIN_PER_YUAN / data.total_revenue_yuan) * 100
|
||||
: null,
|
||||
coinGap: data.total_expected_coin - data.total_actual_coin,
|
||||
// ARPU(今日)= 预估广告收益 ÷ 今日 DAU;dau 为 null(历史/多天)或 0 时不可算 → null,前端显示「-」。
|
||||
// ARPU = 区间预估广告收益 ÷ 区间去重活跃用户(dau,口径同数据大盘);dau 为 0 时不可算 → null,显示「-」。
|
||||
arpu: data.dau && data.dau > 0 ? data.total_revenue_yuan / data.dau : null,
|
||||
}
|
||||
: null;
|
||||
|
||||
// DAU / ARPU 的统计区间 = 本次查询的 date_from~date_to(后端 period_active_dau 同口径按此区间算);
|
||||
// 今日单天特殊标注「今日」,便于「今日 / 近 7 天 / 近 30 天」三个时段分别看 ARPU。
|
||||
const dauRangeIsToday =
|
||||
!!data && data.date_from === data.date_to && data.date_to === dayjs().format('YYYY-MM-DD');
|
||||
const dauRangeLabel = !data
|
||||
? ''
|
||||
: data.date_from === data.date_to
|
||||
? dauRangeIsToday
|
||||
? '今日'
|
||||
: data.date_from
|
||||
: `${data.date_from} ~ ${data.date_to}`;
|
||||
|
||||
// 第二行大盘「分广告类型」:draw / 激励视频 各自 收益 / eCPM / 展示条数;eCPM = 收益÷展示×1000。
|
||||
const drawStat = data?.type_stats?.draw;
|
||||
const rvStat = data?.type_stats?.reward_video;
|
||||
@@ -527,6 +543,10 @@ export default function AdRevenueReportPage() {
|
||||
title="收益口径说明"
|
||||
content={
|
||||
<div style={{ maxWidth: 360, fontSize: 13, lineHeight: 1.7 }}>
|
||||
<b>主表每行 = 一次广告行为</b>(激励视频一次观看 / 一次比价 / 一次领券);比价·领券的 Draw
|
||||
逐条展示不单独占行(其展示数 / eCPM / 预估收益已计入上方合计与大盘),点行左侧「+」展开看该次金币复算。
|
||||
<br />
|
||||
<br />
|
||||
「预估收益」为客户端在广告展示(onAdShow)时上报 eCPM 折算的预估值(每千次展示 ÷1000
|
||||
累加),<b>只要广告展示就计入、不论是否看完发奖</b>;穿山甲会过滤无效/过短曝光,故预估值可能偏高,
|
||||
<b>实际收益一律以穿山甲后台结算为准</b>。测试应用多为 0。「广告位ID / 来源应用」为本期新增,历史记录留空。
|
||||
@@ -578,7 +598,6 @@ export default function AdRevenueReportPage() {
|
||||
style={{ width: 150 }}
|
||||
options={[
|
||||
{ value: 'reward_video', label: '激励视频' },
|
||||
{ value: 'feed', label: '信息流' },
|
||||
{ value: 'draw', label: 'Draw 信息流' },
|
||||
{ value: 'withdrawal_video', label: '提现激励视频' },
|
||||
]}
|
||||
@@ -650,7 +669,7 @@ export default function AdRevenueReportPage() {
|
||||
<Card size="small" style={{ marginBottom: 16 }}>
|
||||
<Divider orientation="left" plain style={{ marginTop: 0, marginBottom: 16 }}>
|
||||
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
|
||||
核心指标
|
||||
核心指标{dauRangeLabel ? ` · 统计区间 ${dauRangeLabel}` : ''}
|
||||
</Typography.Text>
|
||||
</Divider>
|
||||
<Row gutter={[16, 12]}>
|
||||
@@ -660,9 +679,11 @@ export default function AdRevenueReportPage() {
|
||||
<Col flex="1 1 0">
|
||||
<Statistic
|
||||
title={
|
||||
<Tooltip title="每活跃用户广告预估收入 = 预估收益 ÷ 今日 DAU;DAU 仅今日口径,历史/多天显示 -">
|
||||
<Tooltip
|
||||
title={`每活跃用户广告预估收入 = 区间预估收益 ÷ 区间去重活跃用户(口径同数据大盘)。统计区间:${dauRangeLabel || '—'}`}
|
||||
>
|
||||
<span>
|
||||
ARPU(今日)
|
||||
{dauRangeIsToday ? 'ARPU(今日)' : 'ARPU'}
|
||||
<InfoCircleOutlined style={{ marginLeft: 4 }} />
|
||||
</span>
|
||||
</Tooltip>
|
||||
@@ -674,9 +695,11 @@ export default function AdRevenueReportPage() {
|
||||
<Col flex="1 1 0">
|
||||
<Statistic
|
||||
title={
|
||||
<Tooltip title="今日活跃用户(复用大盘口径 last_login_at = 今日登录过);仅查询=今日时有值,历史/多天显示 -">
|
||||
<Tooltip
|
||||
title={`区间去重活跃用户,口径同数据大盘:登录 + 开始比价 + 开始领券,按用户去重。全局口径,不随用户/类型/场景/应用筛选变化。统计区间:${dauRangeLabel || '—'}`}
|
||||
>
|
||||
<span>
|
||||
今日活跃 DAU
|
||||
{dauRangeIsToday ? '今日活跃 DAU' : '活跃用户'}
|
||||
<InfoCircleOutlined style={{ marginLeft: 4 }} />
|
||||
</span>
|
||||
</Tooltip>
|
||||
@@ -792,22 +815,6 @@ export default function AdRevenueReportPage() {
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{data && (
|
||||
<Space direction="vertical" style={{ width: '100%', marginBottom: 12 }}>
|
||||
{data.mismatch_count > 0 ? (
|
||||
<Alert
|
||||
type="error"
|
||||
showIcon
|
||||
message={`共 ${data.total} 条广告事件,其中 ${data.mismatch_count} 条应发≠实发(✗);应发−实发 合计 ${
|
||||
derived && derived.coinGap >= 0 ? '+' : ''
|
||||
}${derived?.coinGap ?? 0} 金币(正=少发/负=多发)——公式可能未生效或发奖有问题。定位到具体记录可用后端逐条审计接口。`}
|
||||
/>
|
||||
) : (
|
||||
<Alert type="success" showIcon message={`共 ${data.total} 条广告事件,应发与实发全部一致。`} />
|
||||
)}
|
||||
</Space>
|
||||
)}
|
||||
|
||||
{data &&
|
||||
(queriedMultiDay
|
||||
? (data.daily?.length ?? 0) > 0
|
||||
@@ -884,12 +891,27 @@ export default function AdRevenueReportPage() {
|
||||
}}
|
||||
size="small"
|
||||
scroll={{ x: 1380 }}
|
||||
rowClassName={(r) => (r.has_reward && !r.matched ? 'row-mismatch' : '')}
|
||||
expandable={{
|
||||
// 每行都可展开(左侧恒有 + 号):有发奖看「金币复算因子」;纯展示看「展示明细」。
|
||||
rowExpandable: () => true,
|
||||
expandedRowRender: (r) =>
|
||||
r.reward_detail ? (
|
||||
r.sub_rewards && r.sub_rewards.length > 0 ? (
|
||||
<div>
|
||||
<Typography.Text strong>本次广告逐条明细</Typography.Text>{' '}
|
||||
<Typography.Text type="secondary">
|
||||
(共 {r.sub_count ?? r.sub_rewards.length} 条 · 应发 {r.expected_coin} / 实发 {r.actual_coin})
|
||||
</Typography.Text>
|
||||
<Table<AdRevenueRecord>
|
||||
style={{ marginTop: 8 }}
|
||||
rowKey="record_id"
|
||||
columns={DETAIL_COLUMNS}
|
||||
dataSource={r.sub_rewards}
|
||||
pagination={false}
|
||||
size="small"
|
||||
scroll={{ x: 900 }}
|
||||
/>
|
||||
</div>
|
||||
) : r.reward_detail ? (
|
||||
<div>
|
||||
<Typography.Text strong>金币复算明细</Typography.Text>{' '}
|
||||
<Typography.Text type="secondary">
|
||||
@@ -903,7 +925,6 @@ export default function AdRevenueReportPage() {
|
||||
pagination={false}
|
||||
size="small"
|
||||
scroll={{ x: 900 }}
|
||||
rowClassName={(d) => (d.matched ? '' : 'row-mismatch')}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
@@ -979,11 +1000,12 @@ export default function AdRevenueReportPage() {
|
||||
</Typography.Paragraph>
|
||||
</Modal>
|
||||
|
||||
<style jsx global>{`
|
||||
.row-mismatch > td {
|
||||
background: #fff1f0 !important;
|
||||
}
|
||||
`}</style>
|
||||
<UserAdRevenueDrawer
|
||||
open={!!userDrawer}
|
||||
userId={userDrawer?.userId ?? null}
|
||||
phone={userDrawer?.phone ?? null}
|
||||
onClose={() => setUserDrawer(null)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
+370
-86
@@ -1,81 +1,262 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import { App, Button, Form, Input, Modal, Select, Table, Tag } from 'antd';
|
||||
import {
|
||||
App, Button, Card, Checkbox, Input, Select, Space, Table, Tag,
|
||||
} from 'antd';
|
||||
import { api, errMsg } from '@/lib/api';
|
||||
import { formatUtcTime } from '@/lib/format';
|
||||
import type { AdminInfo } from '@/lib/types';
|
||||
import { getAdmin } from '@/lib/auth';
|
||||
import type { AdminInfo, AdminRole, PermissionGroup } from '@/lib/types';
|
||||
|
||||
const ROLES = [
|
||||
{ value: 'super_admin', label: 'super_admin' },
|
||||
{ value: 'finance', label: 'finance' },
|
||||
{ value: 'operator', label: 'operator' },
|
||||
];
|
||||
// last_login_at 为 UTC 口径(datetime.now(utc)),按北京显示(勿用 new Date().toLocaleString)
|
||||
const dt = (v: string | null) => (v ? formatUtcTime(v, 'YYYY-MM-DD HH:mm:ss') : '从未');
|
||||
|
||||
// 随机初始密码(排除易混字符 0O1lI),客户端生成、转交本人,后端只存 hash
|
||||
function genPassword(len = 10): string {
|
||||
const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789';
|
||||
let s = '';
|
||||
for (let i = 0; i < len; i += 1) s += chars[Math.floor(Math.random() * chars.length)];
|
||||
return s;
|
||||
}
|
||||
|
||||
type View = 'list' | 'person' | 'roles' | 'roleForm';
|
||||
|
||||
// ===== 只读权限矩阵:角色详情 / 人员「可见页面」预览共用(深色=有,灰色=无)=====
|
||||
function PermMatrix({ catalog, pages }: { catalog: PermissionGroup[]; pages: string[] }) {
|
||||
const has = useMemo(() => new Set(pages), [pages]);
|
||||
return (
|
||||
<div style={{ border: '1px solid #f0f0f0', borderRadius: 8, overflow: 'hidden' }}>
|
||||
{catalog.map((g) => (
|
||||
<div key={g.group} style={{ display: 'flex', borderBottom: '1px solid #f0f2f5' }}>
|
||||
<div style={{ width: 150, flexShrink: 0, padding: '14px', fontWeight: 500, color: 'rgba(0,0,0,.85)' }}>
|
||||
{g.group}
|
||||
</div>
|
||||
<div style={{ flex: 1, padding: '12px 16px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px 28px' }}>
|
||||
{g.pages.map((p) => (
|
||||
// 深色=可见,灰色(--ink-3)=不可见
|
||||
<span key={p.key} style={{ fontSize: 13.5, color: has.has(p.key) ? 'rgba(0,0,0,.85)' : '#94a0b1' }}>
|
||||
{p.label}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ===== 可编辑权限矩阵:角色表单用(勾选框 + 分类全选/半选)=====
|
||||
function PermEditor({
|
||||
catalog, value, onChange,
|
||||
}: { catalog: PermissionGroup[]; value: string[]; onChange: (next: string[]) => void }) {
|
||||
const has = useMemo(() => new Set(value), [value]);
|
||||
const setPages = (s: Set<string>) => onChange(Array.from(s));
|
||||
const togglePage = (key: string) => {
|
||||
const n = new Set(has);
|
||||
if (n.has(key)) n.delete(key); else n.add(key);
|
||||
setPages(n);
|
||||
};
|
||||
const toggleGroup = (g: PermissionGroup, on: boolean) => {
|
||||
const n = new Set(has);
|
||||
g.pages.forEach((p) => (on ? n.add(p.key) : n.delete(p.key)));
|
||||
setPages(n);
|
||||
};
|
||||
return (
|
||||
<div style={{ border: '1px solid #f0f0f0', borderRadius: 8, overflow: 'hidden' }}>
|
||||
{catalog.map((g) => {
|
||||
const cnt = g.pages.filter((p) => has.has(p.key)).length;
|
||||
const all = cnt === g.pages.length && cnt > 0;
|
||||
return (
|
||||
<div key={g.group} style={{ display: 'flex', borderBottom: '1px solid #fafafa' }}>
|
||||
<div style={{ width: 140, flexShrink: 0, padding: '14px', background: '#fafbfd' }}>
|
||||
<Checkbox
|
||||
checked={all}
|
||||
indeterminate={cnt > 0 && !all}
|
||||
onChange={(e) => toggleGroup(g, e.target.checked)}
|
||||
>
|
||||
{g.group}
|
||||
</Checkbox>
|
||||
</div>
|
||||
<div style={{ flex: 1, padding: '12px 16px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px 24px' }}>
|
||||
{g.pages.map((p) => (
|
||||
<Checkbox key={p.key} checked={has.has(p.key)} onChange={() => togglePage(p.key)}>
|
||||
{p.label}
|
||||
</Checkbox>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function AdminsPage() {
|
||||
const { message, modal } = App.useApp();
|
||||
const [admins, setAdmins] = useState<AdminInfo[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [createOpen, setCreateOpen] = useState(false);
|
||||
const [form] = Form.useForm();
|
||||
const me = getAdmin();
|
||||
const isSuper = me?.role === 'super_admin';
|
||||
|
||||
const load = async () => {
|
||||
const [view, setView] = useState<View>('list');
|
||||
const [admins, setAdmins] = useState<AdminInfo[]>([]);
|
||||
const [roles, setRoles] = useState<AdminRole[]>([]);
|
||||
const [catalog, setCatalog] = useState<PermissionGroup[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const roleByName = useMemo(() => {
|
||||
const m: Record<string, AdminRole> = {};
|
||||
roles.forEach((r) => { m[r.name] = r; });
|
||||
return m;
|
||||
}, [roles]);
|
||||
const roleOptions = roles.map((r) => ({ value: r.name, label: r.label }));
|
||||
|
||||
const loadAll = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const { data } = await api.get<AdminInfo[]>('/admin/api/admins');
|
||||
setAdmins(data);
|
||||
const [a, r, c] = await Promise.all([
|
||||
api.get<AdminInfo[]>('/admin/api/admins'),
|
||||
api.get<AdminRole[]>('/admin/api/roles'),
|
||||
api.get<PermissionGroup[]>('/admin/api/roles/catalog'),
|
||||
]);
|
||||
setAdmins(a.data);
|
||||
setRoles(r.data);
|
||||
setCatalog(c.data);
|
||||
} catch (e) {
|
||||
message.error(errMsg(e));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, []);
|
||||
useEffect(() => { loadAll(); }, []); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const create = async () => {
|
||||
const v = await form.validateFields();
|
||||
// ===== 人员表单(新增 / 编辑)状态 =====
|
||||
const [personEditing, setPersonEditing] = useState<AdminInfo | null>(null);
|
||||
const [personName, setPersonName] = useState('');
|
||||
const [personRole, setPersonRole] = useState('');
|
||||
const [initPw, setInitPw] = useState('');
|
||||
|
||||
const openCreatePerson = () => {
|
||||
setPersonEditing(null);
|
||||
setPersonName('');
|
||||
setPersonRole(roles.find((r) => !r.is_builtin)?.name ?? roles[0]?.name ?? 'operator');
|
||||
setInitPw(genPassword());
|
||||
setView('person');
|
||||
};
|
||||
const openEditPerson = (a: AdminInfo) => {
|
||||
setPersonEditing(a);
|
||||
setPersonName(a.username);
|
||||
setPersonRole(a.role);
|
||||
setInitPw(''); // 编辑态密码只读展示 a.password(已确定的登录密码),不用 initPw
|
||||
setView('person');
|
||||
};
|
||||
const copyText = (v: string) => {
|
||||
navigator.clipboard?.writeText(v);
|
||||
message.success('已复制到剪贴板');
|
||||
};
|
||||
// 密码展示框(对齐原型 .pw-show:虚线灰框 + 大号等宽 + 复制)
|
||||
const pwBox = (value: string) => (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 12, background: '#f4f6fa', border: '1px dashed #cbd5e1', borderRadius: 8, padding: '12px 14px' }}>
|
||||
<code style={{ flex: 1, fontFamily: '"DIN Alternate", "SF Mono", Consolas, monospace', fontSize: 22, fontWeight: 700, letterSpacing: 1, color: 'rgba(0,0,0,.85)' }}>{value}</code>
|
||||
<Button onClick={() => copyText(value)}>复制</Button>
|
||||
</div>
|
||||
);
|
||||
const submitPerson = async () => {
|
||||
try {
|
||||
await api.post('/admin/api/admins', v);
|
||||
message.success('已创建');
|
||||
setCreateOpen(false);
|
||||
form.resetFields();
|
||||
load();
|
||||
if (personEditing) {
|
||||
// 密码只读、不改;只提交变更的角色
|
||||
if (personRole !== personEditing.role) {
|
||||
await api.patch(`/admin/api/admins/${personEditing.id}`, { role: personRole });
|
||||
}
|
||||
message.success('已保存');
|
||||
} else {
|
||||
if (personName.trim().length < 3) { message.error('用户名至少 3 位'); return; }
|
||||
await api.post('/admin/api/admins', {
|
||||
username: personName.trim(), password: initPw, role: personRole,
|
||||
});
|
||||
message.success('已创建,请把初始密码转交本人');
|
||||
}
|
||||
setView('list');
|
||||
loadAll();
|
||||
} catch (e) {
|
||||
message.error(errMsg(e));
|
||||
}
|
||||
};
|
||||
|
||||
// ===== 列表操作 =====
|
||||
const changeRole = (a: AdminInfo, role: string) => {
|
||||
if (role === a.role) return;
|
||||
modal.confirm({
|
||||
title: `把 ${a.username} 的角色改为 ${role}?`,
|
||||
onOk: async () => {
|
||||
try {
|
||||
await api.patch(`/admin/api/admins/${a.id}`, { role });
|
||||
message.success('已更新');
|
||||
load();
|
||||
} catch (e) {
|
||||
message.error(errMsg(e));
|
||||
}
|
||||
try { await api.patch(`/admin/api/admins/${a.id}`, { role }); message.success('已更新'); loadAll(); }
|
||||
catch (e) { message.error(errMsg(e)); }
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const toggle = (a: AdminInfo) => {
|
||||
const toggleStatus = (a: AdminInfo) => {
|
||||
const next = a.status === 'active' ? 'disabled' : 'active';
|
||||
modal.confirm({
|
||||
title: `${next === 'disabled' ? '禁用' : '启用'}管理员 ${a.username}?`,
|
||||
onOk: async () => {
|
||||
try {
|
||||
await api.patch(`/admin/api/admins/${a.id}`, { status: next });
|
||||
message.success('已更新');
|
||||
load();
|
||||
} catch (e) {
|
||||
message.error(errMsg(e));
|
||||
}
|
||||
try { await api.patch(`/admin/api/admins/${a.id}`, { status: next }); message.success('已更新'); loadAll(); }
|
||||
catch (e) { message.error(errMsg(e)); }
|
||||
},
|
||||
});
|
||||
};
|
||||
const deletePerson = (a: AdminInfo) => {
|
||||
modal.confirm({
|
||||
title: '确认删除',
|
||||
content: `确定删除管理员「${a.username}」吗?删除后该账号将无法登录,不可恢复。`,
|
||||
okText: '确认删除', okButtonProps: { danger: true },
|
||||
onOk: async () => {
|
||||
try { await api.delete(`/admin/api/admins/${a.id}`); message.success('已删除'); loadAll(); }
|
||||
catch (e) { message.error(errMsg(e)); }
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
// ===== 角色设置状态 =====
|
||||
const [selRoleId, setSelRoleId] = useState<number | null>(null);
|
||||
const selRole = roles.find((r) => r.id === selRoleId) ?? roles[0] ?? null;
|
||||
const openRoles = () => {
|
||||
setSelRoleId((prev) => prev ?? roles[0]?.id ?? null);
|
||||
setView('roles');
|
||||
};
|
||||
|
||||
// 角色表单(新增 / 编辑)
|
||||
const [roleEditing, setRoleEditing] = useState<AdminRole | null>(null);
|
||||
const [roleName, setRoleName] = useState('');
|
||||
const [rolePages, setRolePages] = useState<string[]>([]);
|
||||
const openCreateRole = () => {
|
||||
setRoleEditing(null); setRoleName(''); setRolePages([]); setView('roleForm');
|
||||
};
|
||||
const openEditRole = (r: AdminRole) => {
|
||||
setRoleEditing(r); setRoleName(r.label); setRolePages(r.pages); setView('roleForm');
|
||||
};
|
||||
const submitRole = async () => {
|
||||
if (!roleName.trim()) { message.error('请输入角色名称'); return; }
|
||||
try {
|
||||
if (roleEditing) {
|
||||
// 只改展示名 + 可见页(key 不可变)
|
||||
await api.patch(`/admin/api/roles/${roleEditing.id}`, { label: roleName.trim(), pages: rolePages });
|
||||
message.success('角色已保存');
|
||||
} else {
|
||||
await api.post('/admin/api/roles', { name: roleName.trim(), pages: rolePages });
|
||||
message.success('角色已创建');
|
||||
}
|
||||
await loadAll();
|
||||
setView('roles');
|
||||
} catch (e) {
|
||||
message.error(errMsg(e));
|
||||
}
|
||||
};
|
||||
const deleteRole = (r: AdminRole) => {
|
||||
modal.confirm({
|
||||
title: '确认删除角色',
|
||||
content: `确定删除角色「${r.label}」吗?${r.in_use > 0 ? `当前有 ${r.in_use} 名成员在用,需先改派。` : '此操作不可恢复。'}`,
|
||||
okText: '确认删除', okButtonProps: { danger: true },
|
||||
onOk: async () => {
|
||||
try { await api.delete(`/admin/api/roles/${r.id}`); message.success('已删除角色'); await loadAll(); setSelRoleId(null); }
|
||||
catch (e) { message.error(errMsg(e)); }
|
||||
},
|
||||
});
|
||||
};
|
||||
@@ -84,60 +265,163 @@ export default function AdminsPage() {
|
||||
{ title: 'ID', dataIndex: 'id', width: 70 },
|
||||
{ title: '用户名', dataIndex: 'username' },
|
||||
{
|
||||
title: '角色',
|
||||
dataIndex: 'role',
|
||||
title: '角色', dataIndex: 'role', width: 170,
|
||||
render: (r: string, a: AdminInfo) => (
|
||||
<Select
|
||||
size="small"
|
||||
value={r}
|
||||
style={{ width: 140 }}
|
||||
options={ROLES}
|
||||
onChange={(v) => changeRole(a, v)}
|
||||
/>
|
||||
<Select size="small" value={r} style={{ width: 150 }} options={roleOptions} onChange={(v) => changeRole(a, v)} />
|
||||
),
|
||||
},
|
||||
{ title: '状态', dataIndex: 'status', width: 90, render: (s: string) => <Tag color={s === 'active' ? 'green' : 'default'}>{s === 'active' ? 'active' : '已禁用'}</Tag> },
|
||||
{ title: '最后登录', dataIndex: 'last_login_at', width: 180, render: dt },
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
render: (s: string) => <Tag color={s === 'active' ? 'green' : 'red'}>{s}</Tag>,
|
||||
},
|
||||
{ title: '最后登录', dataIndex: 'last_login_at', render: dt },
|
||||
{
|
||||
title: '操作',
|
||||
key: 'op',
|
||||
title: '操作', key: 'op', width: 200,
|
||||
render: (_: unknown, a: AdminInfo) => (
|
||||
<a onClick={() => toggle(a)}>{a.status === 'active' ? '禁用' : '启用'}</a>
|
||||
<Space size="middle">
|
||||
<a onClick={() => openEditPerson(a)}>编辑</a>
|
||||
<a onClick={() => toggleStatus(a)}>{a.status === 'active' ? '禁用' : '启用'}</a>
|
||||
<a style={{ color: '#cf1322' }} onClick={() => deletePerson(a)}>删除</a>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
// ============ 视图 1:管理员账号列表 ============
|
||||
if (view === 'list') {
|
||||
return (
|
||||
<div>
|
||||
<h2>权限管理</h2>
|
||||
<Space style={{ marginBottom: 16 }}>
|
||||
<Button type="primary" onClick={openCreatePerson}>+ 新增人员</Button>
|
||||
<Button onClick={openRoles}>角色设置</Button>
|
||||
</Space>
|
||||
<Table rowKey="id" columns={columns} dataSource={admins} loading={loading} pagination={false} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ============ 视图 2:新增 / 编辑人员 ============
|
||||
if (view === 'person') {
|
||||
const rolePagesPreview = roleByName[personRole]?.pages ?? [];
|
||||
return (
|
||||
<div>
|
||||
<Space style={{ marginBottom: 16 }}><a onClick={() => setView('list')}>‹ 返回</a></Space>
|
||||
<Card style={{ maxWidth: 720, margin: '0 auto' }}>
|
||||
<h2 style={{ fontSize: 19, fontWeight: 600, marginBottom: 22 }}>{personEditing ? '编辑人员' : '新增人员'}</h2>
|
||||
<div style={{ marginBottom: 20 }}>
|
||||
<div style={{ marginBottom: 8 }}>用户名<span style={{ color: '#cf1322' }}> *</span></div>
|
||||
<Input value={personName} disabled={!!personEditing} onChange={(e) => setPersonName(e.target.value)} placeholder="至少 3 位" />
|
||||
{personEditing && <div style={{ color: '#999', fontSize: 12, marginTop: 6 }}>用户名不可修改</div>}
|
||||
</div>
|
||||
|
||||
{!personEditing ? (
|
||||
// 新增:系统生成初始密码(可换)
|
||||
<div style={{ marginBottom: 20 }}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
|
||||
<span>初始密码</span>
|
||||
<a onClick={() => setInitPw(genPassword())}>换一个 ↻</a>
|
||||
</div>
|
||||
{pwBox(initPw)}
|
||||
</div>
|
||||
) : personEditing.password ? (
|
||||
// 编辑:显示该成员已确定的登录密码(只读、不可换)
|
||||
<div style={{ marginBottom: 20 }}>
|
||||
<div style={{ marginBottom: 8 }}>登录密码</div>
|
||||
{pwBox(personEditing.password)}
|
||||
<div style={{ color: '#999', fontSize: 12, marginTop: 6 }}>该成员已确定的登录密码,可复制转交本人</div>
|
||||
</div>
|
||||
) : (
|
||||
// 编辑:无留存明文(脚本/起后台建的超管)→ 不显示密码
|
||||
<div style={{ marginBottom: 20 }}>
|
||||
<div style={{ marginBottom: 8 }}>登录密码</div>
|
||||
<div style={{ color: '#999', fontSize: 13, padding: '6px 0' }}>该账号密码仅在后台创建时设定、系统未留存,不可查看。</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div style={{ marginBottom: 20 }}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
|
||||
<span>选择角色<span style={{ color: '#cf1322' }}> *</span></span>
|
||||
{isSuper && <a onClick={openRoles}>设置角色权限 ›</a>}
|
||||
</div>
|
||||
<Select value={personRole} options={roleOptions} onChange={setPersonRole} style={{ width: '100%' }} />
|
||||
<div style={{ color: '#999', fontSize: 12, marginTop: 6 }}>可见页面完全由所选角色决定;如需调整请到「角色设置」修改该角色</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
|
||||
<span>可见页面</span>
|
||||
<span style={{ color: '#999', fontSize: 12 }}>跟随所选角色,此处只读(深色=可见)</span>
|
||||
</div>
|
||||
<PermMatrix catalog={catalog} pages={personRole === 'super_admin' ? catalog.flatMap((g) => g.pages.map((p) => p.key)) : rolePagesPreview} />
|
||||
</div>
|
||||
|
||||
<div style={{ marginTop: 24, textAlign: 'right' }}>
|
||||
<Space><Button onClick={() => setView('list')}>取消</Button><Button type="primary" onClick={submitPerson}>确定</Button></Space>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ============ 视图 3:角色设置(角色列表 + 只读权限详情)============
|
||||
if (view === 'roles') {
|
||||
return (
|
||||
<div>
|
||||
<Space style={{ marginBottom: 16 }}><a onClick={() => setView('list')}>‹ 返回</a><b>角色设置</b></Space>
|
||||
<div>
|
||||
<Button type="primary" style={{ marginBottom: 16 }} onClick={openCreateRole}>+ 新增角色权限</Button>
|
||||
<div style={{ display: 'flex', background: '#fff', border: '1px solid #e8ebf1', borderRadius: 10, boxShadow: '0 1px 3px rgba(16,24,40,.06)', overflow: 'hidden' }}>
|
||||
<div style={{ width: 176, flexShrink: 0, borderRight: '1px solid #eff1f6', padding: 8 }}>
|
||||
{roles.map((r) => (
|
||||
<div
|
||||
key={r.id}
|
||||
onClick={() => setSelRoleId(r.id)}
|
||||
style={{
|
||||
padding: '10px 14px', borderRadius: 8, cursor: 'pointer', marginBottom: 2,
|
||||
background: selRole?.id === r.id ? '#e6f0ff' : undefined,
|
||||
color: selRole?.id === r.id ? '#1677ff' : undefined,
|
||||
fontWeight: selRole?.id === r.id ? 600 : undefined,
|
||||
}}
|
||||
>
|
||||
{r.label}{r.is_builtin && <Tag style={{ marginLeft: 6 }}>内建</Tag>}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div style={{ flex: 1, minWidth: 0, padding: '18px 22px' }}>
|
||||
{selRole && (
|
||||
<>
|
||||
<Space style={{ marginBottom: 16 }} size="middle">
|
||||
<b style={{ fontSize: 16 }}>{selRole.label}</b>
|
||||
{!selRole.is_builtin && <a onClick={() => openEditRole(selRole)}>编辑角色权限</a>}
|
||||
{!selRole.is_builtin && <a style={{ color: '#cf1322' }} onClick={() => deleteRole(selRole)}>删除角色权限</a>}
|
||||
{selRole.in_use > 0 && <span style={{ color: '#999', fontSize: 12 }}>{selRole.in_use} 名成员在用</span>}
|
||||
</Space>
|
||||
<PermMatrix catalog={catalog} pages={selRole.pages} />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ============ 视图 4:新增 / 编辑角色权限 ============
|
||||
return (
|
||||
<div>
|
||||
<h2>管理员账号</h2>
|
||||
<Button type="primary" style={{ marginBottom: 16 }} onClick={() => setCreateOpen(true)}>
|
||||
新建管理员
|
||||
</Button>
|
||||
<Table rowKey="id" columns={columns} dataSource={admins} loading={loading} pagination={false} />
|
||||
|
||||
<Modal
|
||||
title="新建管理员"
|
||||
open={createOpen}
|
||||
onOk={create}
|
||||
onCancel={() => setCreateOpen(false)}
|
||||
destroyOnClose
|
||||
>
|
||||
<Form form={form} layout="vertical" initialValues={{ role: 'operator' }}>
|
||||
<Form.Item name="username" label="用户名" rules={[{ required: true, min: 3 }]}>
|
||||
<Input />
|
||||
</Form.Item>
|
||||
<Form.Item name="password" label="密码(≥8 位)" rules={[{ required: true, min: 8 }]}>
|
||||
<Input.Password />
|
||||
</Form.Item>
|
||||
<Form.Item name="role" label="角色" rules={[{ required: true }]}>
|
||||
<Select options={ROLES} />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
<Space style={{ marginBottom: 16 }}><a onClick={() => setView('roles')}>‹ 返回</a></Space>
|
||||
<Card style={{ maxWidth: 920, margin: '0 auto' }}>
|
||||
<h2 style={{ fontSize: 19, fontWeight: 600, marginBottom: 22 }}>{roleEditing ? '编辑角色权限' : '新增角色权限'}</h2>
|
||||
<div style={{ marginBottom: 20 }}>
|
||||
<div style={{ marginBottom: 8 }}>角色名称<span style={{ color: '#cf1322' }}> *</span></div>
|
||||
<Input value={roleName} onChange={(e) => setRoleName(e.target.value)} placeholder="如:运营专员 / 财务 / 审核" maxLength={32} />
|
||||
</div>
|
||||
<div>
|
||||
<div style={{ marginBottom: 8 }}>角色权限(可见页面)<span style={{ color: '#cf1322' }}> *</span></div>
|
||||
<PermEditor catalog={catalog} value={rolePages} onChange={setRolePages} />
|
||||
</div>
|
||||
<div style={{ marginTop: 24, textAlign: 'right' }}>
|
||||
<Space><Button onClick={() => setView('roles')}>取消</Button><Button type="primary" onClick={submitRole}>确定</Button></Space>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import type { CSSProperties } from 'react';
|
||||
import type { CSSProperties, ReactNode } from 'react';
|
||||
import {
|
||||
App, Button, Card, Collapse, Descriptions, Drawer, Input, InputNumber,
|
||||
Select, Space, Spin, Table, Tag, Typography,
|
||||
@@ -48,6 +48,33 @@ function pretty(s: string | null): string {
|
||||
}
|
||||
}
|
||||
|
||||
// 搜索命中高亮:把 text 里匹配 keyword 的子串套黄底荧光,方便审计快速定位。
|
||||
// 大小写不敏感;用 indexOf 逐段切(非正则,keyword 含特殊字符也安全)。keyword 取「已应用」
|
||||
// 的搜索词(applied.store / applied.product),不是输入框实时值——只高亮真正搜过的词。
|
||||
function highlightMatch(text: string | null, keyword: unknown): ReactNode {
|
||||
if (!text) return '-';
|
||||
const kw = (typeof keyword === 'string' ? keyword : '').trim();
|
||||
if (!kw) return text;
|
||||
const parts: ReactNode[] = [];
|
||||
const hay = text.toLowerCase();
|
||||
const needle = kw.toLowerCase();
|
||||
let from = 0;
|
||||
let hit = hay.indexOf(needle);
|
||||
let k = 0;
|
||||
while (hit !== -1) {
|
||||
if (hit > from) parts.push(text.slice(from, hit));
|
||||
parts.push(
|
||||
<mark key={k++} style={{ background: '#fff566', padding: 0 }}>
|
||||
{text.slice(hit, hit + kw.length)}
|
||||
</mark>,
|
||||
);
|
||||
from = hit + kw.length;
|
||||
hit = hay.indexOf(needle, from);
|
||||
}
|
||||
if (from < text.length) parts.push(text.slice(from));
|
||||
return parts;
|
||||
}
|
||||
|
||||
const preStyle: CSSProperties = {
|
||||
background: '#f6f8fa', padding: 8, borderRadius: 6, fontSize: 12,
|
||||
maxHeight: 340, overflow: 'auto', whiteSpace: 'pre-wrap', wordBreak: 'break-word', margin: 0,
|
||||
@@ -59,6 +86,8 @@ export default function ComparisonRecordsPage() {
|
||||
const [userId, setUserId] = useState<number | null>(null);
|
||||
const [phone, setPhone] = useState('');
|
||||
const [status, setStatus] = useState<string | undefined>();
|
||||
const [store, setStore] = useState('');
|
||||
const [product, setProduct] = useState('');
|
||||
const [applied, setApplied] = useState<Record<string, unknown>>({});
|
||||
// LLM 单价(元/百万 token),本地持久化;仅用于前端估算成本,不入库、不影响其它页面
|
||||
const [pricePerMTok, setPricePerMTok] = useState<number | null>(() => {
|
||||
@@ -80,12 +109,20 @@ export default function ComparisonRecordsPage() {
|
||||
const [detailLoading, setDetailLoading] = useState(false);
|
||||
|
||||
const search = () =>
|
||||
setApplied({ user_id: userId ?? undefined, phone: phone || undefined, status });
|
||||
setApplied({
|
||||
user_id: userId ?? undefined,
|
||||
phone: phone || undefined,
|
||||
status,
|
||||
store: store.trim() || undefined,
|
||||
product: product.trim() || undefined,
|
||||
});
|
||||
|
||||
const reset = () => {
|
||||
setUserId(null);
|
||||
setPhone('');
|
||||
setStatus(undefined);
|
||||
setStore('');
|
||||
setProduct('');
|
||||
setApplied({});
|
||||
};
|
||||
|
||||
@@ -122,7 +159,21 @@ export default function ComparisonRecordsPage() {
|
||||
},
|
||||
{ title: '状态', dataIndex: 'status', width: 72, render: (s: string) => <Tag color={STATUS_COLOR[s]}>{STATUS_LABEL[s] || s}</Tag> },
|
||||
{ title: '源平台', dataIndex: 'source_platform_name', width: 90, render: (v) => v || '-' },
|
||||
{ title: '店/商品', dataIndex: 'store_name', width: 150, ellipsis: true, render: (v) => v || '-' },
|
||||
{
|
||||
title: '店',
|
||||
dataIndex: 'store_name',
|
||||
width: 170,
|
||||
// 审计要一眼看全:不截断、整格自动换行(去 ellipsis),而非靠 hover tooltip
|
||||
onCell: () => ({ style: { whiteSpace: 'normal', wordBreak: 'break-word', verticalAlign: 'top' } }),
|
||||
render: (v: string | null) => highlightMatch(v, applied.store),
|
||||
},
|
||||
{
|
||||
title: '商品',
|
||||
dataIndex: 'product_names',
|
||||
width: 280,
|
||||
onCell: () => ({ style: { whiteSpace: 'normal', wordBreak: 'break-word', verticalAlign: 'top' } }),
|
||||
render: (v: string | null) => highlightMatch(v, applied.product),
|
||||
},
|
||||
{ title: '最优', dataIndex: 'best_platform_name', width: 80, render: (v) => v || '-' },
|
||||
{
|
||||
title: '省',
|
||||
@@ -192,6 +243,22 @@ export default function ComparisonRecordsPage() {
|
||||
allowClear
|
||||
style={{ width: 150 }}
|
||||
/>
|
||||
<Input
|
||||
placeholder="搜索店名"
|
||||
value={store}
|
||||
onChange={(e) => setStore(e.target.value)}
|
||||
onPressEnter={search}
|
||||
allowClear
|
||||
style={{ width: 150 }}
|
||||
/>
|
||||
<Input
|
||||
placeholder="搜索商品"
|
||||
value={product}
|
||||
onChange={(e) => setProduct(e.target.value)}
|
||||
onPressEnter={search}
|
||||
allowClear
|
||||
style={{ width: 150 }}
|
||||
/>
|
||||
<Select
|
||||
placeholder="状态"
|
||||
value={status}
|
||||
@@ -230,7 +297,7 @@ export default function ComparisonRecordsPage() {
|
||||
showTotal: (t) => `共 ${t} 条`,
|
||||
onChange,
|
||||
}}
|
||||
scroll={{ x: 1520 }}
|
||||
scroll={{ x: 1820 }}
|
||||
onRow={(r) => ({ onClick: () => openDetail(r.id), style: { cursor: 'pointer' } })}
|
||||
/>
|
||||
|
||||
@@ -261,7 +328,7 @@ export default function ComparisonRecordsPage() {
|
||||
<Descriptions.Item label="源平台">{detail.source_platform_name || '-'}({cents(detail.source_price_cents)})</Descriptions.Item>
|
||||
<Descriptions.Item label="最优">{detail.best_platform_name || '-'}({cents(detail.best_price_cents)})</Descriptions.Item>
|
||||
<Descriptions.Item label="省" span={2}>{cents(detail.saved_amount_cents)}{detail.is_source_best ? '(源平台最便宜)' : ''}</Descriptions.Item>
|
||||
<Descriptions.Item label="店/商品" span={2}>{detail.store_name || '-'}</Descriptions.Item>
|
||||
<Descriptions.Item label="店" span={2}>{detail.store_name || '-'}</Descriptions.Item>
|
||||
<Descriptions.Item label="结论文案" span={2}>{detail.information || '-'}</Descriptions.Item>
|
||||
<Descriptions.Item label="trace" span={2}>
|
||||
{detail.trace_url
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
InputNumber,
|
||||
Modal,
|
||||
Popconfirm,
|
||||
Segmented,
|
||||
Space,
|
||||
Spin,
|
||||
Switch,
|
||||
@@ -41,13 +42,15 @@ interface BulkVals {
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
interface PreviewItem {
|
||||
interface RealRecord {
|
||||
masked_user: string;
|
||||
saved_amount_cents: number;
|
||||
time: string;
|
||||
created_at: string;
|
||||
user_id: number;
|
||||
}
|
||||
|
||||
const yuan = (cents: number) => (cents / 100).toFixed(2);
|
||||
const MODE_LABEL: Record<string, string> = { mixed: '混播', real: '只真实', seed: '只种子' };
|
||||
|
||||
/** 首页轮播「种子」管理(真实记录不足时的兜底假数据,现为「生成规则」)。「系统配置 / 首页」里的一个区块。 */
|
||||
export default function HomeMarqueeSeeds() {
|
||||
@@ -55,6 +58,8 @@ export default function HomeMarqueeSeeds() {
|
||||
const [seeds, setSeeds] = useState<Seed[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]); // 批量操作选中行
|
||||
const [mode, setMode] = useState<string>('mixed'); // 轮播数据源 mixed/real/seed
|
||||
const [modeSaving, setModeSaving] = useState(false);
|
||||
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [editing, setEditing] = useState<Seed | null>(null);
|
||||
@@ -63,9 +68,12 @@ export default function HomeMarqueeSeeds() {
|
||||
const [bulkOpen, setBulkOpen] = useState(false);
|
||||
const [bulkForm] = Form.useForm<BulkVals>();
|
||||
|
||||
const [previewOpen, setPreviewOpen] = useState(false);
|
||||
const [previewItems, setPreviewItems] = useState<PreviewItem[]>([]);
|
||||
const [previewLoading, setPreviewLoading] = useState(false);
|
||||
// 「可展示的真实记录」分页浏览(替代原随机预览):翻遍所有 success+省>0 的真实记录
|
||||
const REC_PAGE_SIZE = 8;
|
||||
const [recItems, setRecItems] = useState<RealRecord[]>([]);
|
||||
const [recTotal, setRecTotal] = useState(0);
|
||||
const [recPage, setRecPage] = useState(0); // 0-based
|
||||
const [recLoading, setRecLoading] = useState(false);
|
||||
|
||||
const load = async () => {
|
||||
setLoading(true);
|
||||
@@ -80,8 +88,30 @@ export default function HomeMarqueeSeeds() {
|
||||
};
|
||||
useEffect(() => {
|
||||
load();
|
||||
// 轮播数据源模式(mixed/real/seed):单独拉,与种子列表解耦
|
||||
api
|
||||
.get<{ mode: string }>('/admin/api/marquee-seeds/mode')
|
||||
.then(({ data }) => setMode(data.mode))
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
|
||||
// 切换数据源:乐观更新 + 失败回滚
|
||||
const changeMode = async (m: string) => {
|
||||
const prev = mode;
|
||||
setMode(m);
|
||||
setRecPage(0); // 切模式回第 1 页(不同模式条数不同,避免停在越界页)
|
||||
setModeSaving(true);
|
||||
try {
|
||||
await api.patch('/admin/api/marquee-seeds/mode', { mode: m });
|
||||
message.success('已切换,客户端下次进首页生效');
|
||||
} catch (e) {
|
||||
setMode(prev);
|
||||
message.error(errMsg(e));
|
||||
} finally {
|
||||
setModeSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
// ===== 单条 新增 / 编辑 =====
|
||||
const openAdd = () => {
|
||||
setEditing(null);
|
||||
@@ -144,22 +174,29 @@ export default function HomeMarqueeSeeds() {
|
||||
}
|
||||
};
|
||||
|
||||
// ===== 预览实际 feed =====
|
||||
const fetchPreview = async () => {
|
||||
setPreviewLoading(true);
|
||||
// ===== 可展示的记录:按「当前模式」分页浏览全部(不去重)=====
|
||||
// 只真实=真实记录;只种子=各启用种子按生成逻辑各出一行;混播=真实+种子。与 app 同口径洗牌+去连簇,
|
||||
// 后端固定种子 → 翻页稳定、能翻遍全部。
|
||||
const fetchRecords = async (page: number, m: string) => {
|
||||
setRecLoading(true);
|
||||
try {
|
||||
const { data } = await api.get<{ items: PreviewItem[] }>('/admin/api/marquee-seeds/preview?limit=8');
|
||||
setPreviewItems(data.items);
|
||||
const { data } = await api.get<{ items: RealRecord[]; total: number }>(
|
||||
'/admin/api/marquee-seeds/real-records',
|
||||
{ params: { offset: page * REC_PAGE_SIZE, limit: REC_PAGE_SIZE, mode: m } },
|
||||
);
|
||||
setRecItems(data.items);
|
||||
setRecTotal(data.total);
|
||||
} catch (e) {
|
||||
message.error(errMsg(e));
|
||||
} finally {
|
||||
setPreviewLoading(false);
|
||||
setRecLoading(false);
|
||||
}
|
||||
};
|
||||
const openPreview = () => {
|
||||
setPreviewOpen(true);
|
||||
fetchPreview();
|
||||
};
|
||||
// 页码或模式变化都重拉(切模式时 changeMode 会把页码重置到 0)。
|
||||
useEffect(() => {
|
||||
fetchRecords(recPage, mode);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [recPage, mode]);
|
||||
|
||||
const toggle = async (s: Seed, enabled: boolean) => {
|
||||
try {
|
||||
@@ -260,6 +297,100 @@ export default function HomeMarqueeSeeds() {
|
||||
首页「用户xxx 比价后节省xx元」轮播的兜底假数据。真实比价记录不足时随机抽取这些补齐;停用的不参与混播。
|
||||
用户名留空则每次展示随机合成;金额为区间则每次随机取值。
|
||||
</p>
|
||||
<Space style={{ marginBottom: 12 }} align="center" wrap>
|
||||
<span style={{ fontSize: 13 }}>数据源</span>
|
||||
<Segmented
|
||||
value={mode}
|
||||
disabled={modeSaving}
|
||||
onChange={(v) => changeMode(v as string)}
|
||||
options={[
|
||||
{ label: '混播(默认)', value: 'mixed' },
|
||||
{ label: '只真实', value: 'real' },
|
||||
{ label: '只种子', value: 'seed' },
|
||||
]}
|
||||
/>
|
||||
<span style={{ color: '#999', fontSize: 12 }}>
|
||||
混播=真实优先+种子补位;只真实=不掺假数据(真实不足则少显示);只种子=只用下方种子/合成(演示用)
|
||||
</span>
|
||||
</Space>
|
||||
|
||||
{/* 可展示的真实记录:分页浏览全部(success+省>0,不去重、稳定倒序);app 轮播即从这些记录
|
||||
随机打乱、同一用户去连簇后展示。翻页可看全所有真实用户的展示信息。 */}
|
||||
<div
|
||||
style={{
|
||||
marginBottom: 16,
|
||||
border: '1px solid #f0f0f0',
|
||||
borderRadius: 8,
|
||||
padding: '10px 12px',
|
||||
background: '#fafafa',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
marginBottom: 6,
|
||||
flexWrap: 'wrap',
|
||||
gap: 8,
|
||||
}}
|
||||
>
|
||||
<span style={{ fontSize: 13, fontWeight: 500 }}>
|
||||
可展示的记录 · {MODE_LABEL[mode] ?? mode} · 共 {recTotal} 条
|
||||
<span style={{ color: '#999', fontWeight: 400, fontSize: 12, marginLeft: 8 }}>
|
||||
当前模式下 app 轮播能露出的全部记录(不去重):只真实=真实、只种子=各种子生成、混播=真实+种子;
|
||||
已按 app 口径洗牌+去连簇,顺序固定便于翻页看全
|
||||
</span>
|
||||
</span>
|
||||
<Space size="small">
|
||||
<Button size="small" disabled={recPage <= 0} onClick={() => setRecPage((p) => Math.max(0, p - 1))}>
|
||||
上一页
|
||||
</Button>
|
||||
<span style={{ fontSize: 12, color: '#666' }}>
|
||||
第 {recTotal === 0 ? 0 : recPage + 1}/{Math.max(1, Math.ceil(recTotal / REC_PAGE_SIZE))} 页
|
||||
</span>
|
||||
<Button
|
||||
size="small"
|
||||
disabled={(recPage + 1) * REC_PAGE_SIZE >= recTotal}
|
||||
onClick={() => setRecPage((p) => p + 1)}
|
||||
>
|
||||
下一页
|
||||
</Button>
|
||||
</Space>
|
||||
</div>
|
||||
<Spin spinning={recLoading}>
|
||||
<div style={{ minHeight: 120 }}>
|
||||
{recItems.length === 0 && !recLoading ? (
|
||||
<div style={{ color: '#bbb', textAlign: 'center', padding: '36px 0', fontSize: 13 }}>
|
||||
当前模式暂无可展示的记录
|
||||
</div>
|
||||
) : (
|
||||
recItems.map((it, i) => (
|
||||
<div
|
||||
key={i}
|
||||
style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
padding: '6px 4px',
|
||||
borderBottom: '1px solid #f0f0f0',
|
||||
}}
|
||||
>
|
||||
<span>
|
||||
{it.masked_user} 比价后节省{' '}
|
||||
<b style={{ color: '#fa541c' }}>{yuan(it.saved_amount_cents)} 元</b>
|
||||
<span style={{ color: '#ccc', fontSize: 12, marginLeft: 8 }}>
|
||||
{it.user_id > 0 ? `u${it.user_id}` : '种子'}
|
||||
</span>
|
||||
</span>
|
||||
<span style={{ color: '#999', fontSize: 12 }}>{it.created_at}</span>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</Spin>
|
||||
</div>
|
||||
|
||||
<Space style={{ marginBottom: 12 }} wrap>
|
||||
<Button type="primary" size="small" onClick={openAdd}>
|
||||
新增种子
|
||||
@@ -267,9 +398,6 @@ export default function HomeMarqueeSeeds() {
|
||||
<Button size="small" onClick={openBulk}>
|
||||
批量生成
|
||||
</Button>
|
||||
<Button size="small" onClick={openPreview}>
|
||||
预览效果
|
||||
</Button>
|
||||
<span style={{ borderLeft: '1px solid #eee', height: 18 }} />
|
||||
<Button size="small" disabled={!selectedRowKeys.length} onClick={() => batchSetEnabled(true)}>
|
||||
批量启用
|
||||
@@ -373,48 +501,6 @@ export default function HomeMarqueeSeeds() {
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
|
||||
{/* 预览实际 feed */}
|
||||
<Modal
|
||||
title="预览轮播效果"
|
||||
open={previewOpen}
|
||||
onCancel={() => setPreviewOpen(false)}
|
||||
footer={
|
||||
<Space>
|
||||
<Button size="small" onClick={fetchPreview}>
|
||||
换一批
|
||||
</Button>
|
||||
<Button size="small" type="primary" onClick={() => setPreviewOpen(false)}>
|
||||
关闭
|
||||
</Button>
|
||||
</Space>
|
||||
}
|
||||
>
|
||||
<p style={{ color: '#999', marginTop: 0 }}>
|
||||
客户端实际会看到的混播结果:真实记录会插队,种子随机抽取、金额/用户名每次都不同。点「换一批」可重新随机。
|
||||
</p>
|
||||
<Spin spinning={previewLoading}>
|
||||
<div style={{ minHeight: 120 }}>
|
||||
{previewItems.map((it, i) => (
|
||||
<div
|
||||
key={i}
|
||||
style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
padding: '7px 4px',
|
||||
borderBottom: '1px solid #f0f0f0',
|
||||
}}
|
||||
>
|
||||
<span>
|
||||
{it.masked_user} 比价后节省{' '}
|
||||
<b style={{ color: '#fa541c' }}>{yuan(it.saved_amount_cents)} 元</b>
|
||||
</span>
|
||||
<span style={{ color: '#999' }}>{it.time}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Spin>
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
Checkbox,
|
||||
Col,
|
||||
InputNumber,
|
||||
Popconfirm,
|
||||
Radio,
|
||||
Row,
|
||||
Select,
|
||||
@@ -630,16 +629,14 @@ export default function HomeStatsConfig() {
|
||||
{!loading && (
|
||||
<div style={{ marginTop: 16 }}>
|
||||
<Space>
|
||||
<Button type="primary" loading={saving != null} onClick={() => saveAll(false)}>
|
||||
保存
|
||||
{/* 保存即生效:PATCH 带 apply_now,不再等各自「更新时间」的 tick(原「改了 app 不变」的主因)。
|
||||
自增长模式下保存会顺带推进一档。改小数字若没生效,记得勾对应卡片的「允许数字下降」。 */}
|
||||
<Button type="primary" loading={saving != null} onClick={() => saveAll(true)}>
|
||||
保存(立即生效)
|
||||
</Button>
|
||||
<Popconfirm
|
||||
title="立即更新会马上把三项都推进一次(自增长各走一档),不等更新时间。确定?"
|
||||
onConfirm={() => saveAll(true)}
|
||||
>
|
||||
<Button loading={saving != null}>立即更新</Button>
|
||||
</Popconfirm>
|
||||
<span style={{ color: '#999', fontSize: 12 }}>三项配置共用,一次保存全部生效</span>
|
||||
<span style={{ color: '#999', fontSize: 12 }}>
|
||||
三项共用,一次保存全部立即生效,客户端下次进首页即可见
|
||||
</span>
|
||||
</Space>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,677 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import {
|
||||
App,
|
||||
Button,
|
||||
Card,
|
||||
Col,
|
||||
DatePicker,
|
||||
Divider,
|
||||
Input,
|
||||
Row,
|
||||
Select,
|
||||
Space,
|
||||
Statistic,
|
||||
Table,
|
||||
Tag,
|
||||
Typography,
|
||||
} from 'antd';
|
||||
import dayjs, { type Dayjs } from 'dayjs';
|
||||
import { api, errMsg } from '@/lib/api';
|
||||
import { formatUtcTime } from '@/lib/format';
|
||||
import UserRecordsDrawer from '@/components/UserRecordsDrawer';
|
||||
|
||||
const { RangePicker } = DatePicker;
|
||||
|
||||
// ── 领券数据看板类型(仅本页用,内联定义)──
|
||||
interface CouponDataSummary {
|
||||
started_count: number;
|
||||
completed_count: number;
|
||||
avg_elapsed_ms: number | null;
|
||||
p5_ms: number | null;
|
||||
p50_ms: number | null;
|
||||
p95_ms: number | null;
|
||||
p99_ms: number | null;
|
||||
}
|
||||
interface CouponDataDaily {
|
||||
date: string;
|
||||
started_count: number;
|
||||
completed_count: number;
|
||||
avg_elapsed_ms: number | null;
|
||||
}
|
||||
interface CouponDataHourly {
|
||||
hour: number;
|
||||
started_count: number;
|
||||
completed_count: number;
|
||||
avg_elapsed_ms: number | null;
|
||||
}
|
||||
interface CouponDataRow {
|
||||
id: number;
|
||||
trace_id: string;
|
||||
user_id: number | null;
|
||||
user_phone: string | null;
|
||||
user_nickname: string | null;
|
||||
status: string;
|
||||
platforms: string[] | null;
|
||||
origin_package: string | null;
|
||||
elapsed_ms: number | null;
|
||||
platform_elapsed: Record<string, number> | null;
|
||||
device_model: string | null;
|
||||
rom: string | null;
|
||||
app_env: string | null;
|
||||
started_at: string;
|
||||
claimed_count: number | null;
|
||||
trace_url: string | null;
|
||||
}
|
||||
interface CouponDataReport {
|
||||
date_from: string;
|
||||
date_to: string;
|
||||
summary: CouponDataSummary;
|
||||
daily: CouponDataDaily[];
|
||||
hourly: CouponDataHourly[];
|
||||
total: number;
|
||||
items: CouponDataRow[];
|
||||
}
|
||||
|
||||
// 发起来源 App 包名 → 中文(「发起平台」列):空=傻瓜比价首页发起,外卖 App 包名→对应平台。
|
||||
function originLabel(pkg: string | null): string {
|
||||
if (!pkg) return '傻瓜比价';
|
||||
if (pkg.includes('meituan') || pkg.includes('sankuai')) return '美团';
|
||||
if (pkg.includes('taobao') || pkg.includes('ele')) return '淘宝';
|
||||
if (pkg.includes('jingdong') || pkg.includes('jd')) return '京东';
|
||||
return pkg;
|
||||
}
|
||||
|
||||
// 领券状态 → 颜色 + 中文(started 无终态 = 中途流失)
|
||||
const STATUS_TAG: Record<string, { color: string; label: string }> = {
|
||||
started: { color: 'default', label: '未完成' },
|
||||
completed: { color: 'green', label: '完成' },
|
||||
failed: { color: 'red', label: '失败' },
|
||||
abandoned: { color: 'orange', label: '中途退出' },
|
||||
};
|
||||
|
||||
// ms → "1.5s"(空值显示 -)
|
||||
const fmtSec = (ms: number | null | undefined): string =>
|
||||
ms == null ? '-' : `${(ms / 1000).toFixed(1)}s`;
|
||||
|
||||
// 点手机号弹出的「该用户全部领券」抽屉列(精简版:单用户,不含用户/手机号列)。
|
||||
const RECORD_COLUMNS: ColumnsType<CouponDataRow> = [
|
||||
{ title: '时间', dataIndex: 'started_at', width: 160, render: (v: string) => formatUtcTime(v) },
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
width: 80,
|
||||
render: (s: string) => {
|
||||
const t = STATUS_TAG[s] ?? { color: 'default', label: s };
|
||||
return <Tag color={t.color}>{t.label}</Tag>;
|
||||
},
|
||||
},
|
||||
{ title: '发起平台', dataIndex: 'origin_package', width: 90, render: (pkg: string | null) => originLabel(pkg) },
|
||||
{ title: '耗时', dataIndex: 'elapsed_ms', width: 80, align: 'right', render: (v: number | null) => fmtSec(v) },
|
||||
{ title: '美团', key: 'mt', width: 70, align: 'right', render: (_: unknown, r: CouponDataRow) => fmtSec(r.platform_elapsed?.['meituan-waimai']) },
|
||||
{ title: '淘宝', key: 'tb', width: 70, align: 'right', render: (_: unknown, r: CouponDataRow) => fmtSec(r.platform_elapsed?.['taobao-shanguang']) },
|
||||
{ title: '京东', key: 'jd', width: 70, align: 'right', render: (_: unknown, r: CouponDataRow) => fmtSec(r.platform_elapsed?.['jd-waimai']) },
|
||||
{
|
||||
title: 'trace',
|
||||
dataIndex: 'trace_id',
|
||||
width: 90,
|
||||
render: (v: string, r: CouponDataRow) =>
|
||||
r.trace_url ? (
|
||||
<a href={r.trace_url} target="_blank" rel="noreferrer" title={v}>trace</a>
|
||||
) : (
|
||||
<Typography.Text type="secondary" style={{ fontSize: 12 }}>{v.slice(0, 6)}…</Typography.Text>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
// ── 趋势图(纯 SVG,零依赖,复用广告报表同款):浅蓝柱=发起数、深蓝柱=完成数(左轴 次数),橙线=平均耗时(右轴 秒)──
|
||||
const CHART_BAR_STARTED = '#bae0ff';
|
||||
const CHART_BAR_COMPLETED = '#1677ff';
|
||||
const CHART_LINE = '#fa8c16';
|
||||
|
||||
interface TrendPoint {
|
||||
label: string; // x 轴刻度(小时数 / MM-DD)
|
||||
tip: string; // hover 原生 tooltip
|
||||
started: number;
|
||||
completed: number;
|
||||
avgSec: number | null; // 平均耗时(秒);该桶无完成为 null(不画线点)
|
||||
}
|
||||
|
||||
// 按天聚合:用 from..to 补齐空缺日为 0,轴连续。
|
||||
function aggregateDaily(dateFrom: string, dateTo: string, daily: CouponDataDaily[]): TrendPoint[] {
|
||||
const map = new Map(daily.map((d) => [d.date, d]));
|
||||
const out: TrendPoint[] = [];
|
||||
let cur = dayjs(dateFrom);
|
||||
let guard = 0;
|
||||
while (cur.format('YYYY-MM-DD') <= dateTo && guard < 400) {
|
||||
const ds = cur.format('YYYY-MM-DD');
|
||||
const d = map.get(ds);
|
||||
const started = d?.started_count ?? 0;
|
||||
const completed = d?.completed_count ?? 0;
|
||||
const avgSec = d?.avg_elapsed_ms != null ? d.avg_elapsed_ms / 1000 : null;
|
||||
out.push({
|
||||
label: ds.slice(5),
|
||||
tip: `${ds} 发起 ${started} · 完成 ${completed} · 平均耗时 ${avgSec == null ? '-' : avgSec.toFixed(1) + 's'}`,
|
||||
started,
|
||||
completed,
|
||||
avgSec,
|
||||
});
|
||||
cur = cur.add(1, 'day');
|
||||
guard += 1;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// 按小时聚合(0–23)。
|
||||
function aggregateHourly(rows: CouponDataHourly[]): TrendPoint[] {
|
||||
const byHour = new Map(rows.map((r) => [r.hour, r]));
|
||||
return Array.from({ length: 24 }, (_, h) => {
|
||||
const r = byHour.get(h);
|
||||
const started = r?.started_count ?? 0;
|
||||
const completed = r?.completed_count ?? 0;
|
||||
const avgSec = r?.avg_elapsed_ms != null ? r.avg_elapsed_ms / 1000 : null;
|
||||
return {
|
||||
label: String(h),
|
||||
tip: `${String(h).padStart(2, '0')}:00 发起 ${started} · 完成 ${completed} · 平均耗时 ${avgSec == null ? '-' : avgSec.toFixed(1) + 's'}`,
|
||||
started,
|
||||
completed,
|
||||
avgSec,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function TrendChart({ points }: { points: TrendPoint[] }) {
|
||||
const n = points.length;
|
||||
const maxBar = Math.max(1, ...points.map((p) => p.started));
|
||||
const maxSec = Math.max(1e-9, ...points.map((p) => p.avgSec ?? 0));
|
||||
|
||||
const W = 960;
|
||||
const H = 280;
|
||||
const padL = 48;
|
||||
const padR = 56;
|
||||
const padT = 16;
|
||||
const padB = 32;
|
||||
const plotW = W - padL - padR;
|
||||
const plotH = H - padT - padB;
|
||||
const step = plotW / Math.max(1, n);
|
||||
const barW = Math.min(24, step * 0.5);
|
||||
const yBase = padT + plotH;
|
||||
|
||||
const barX = (i: number) => padL + i * step + (step - barW) / 2;
|
||||
const cx = (i: number) => padL + i * step + step / 2;
|
||||
const barH = (v: number) => (v / maxBar) * plotH;
|
||||
const secY = (v: number) => yBase - (v / maxSec) * plotH;
|
||||
// X 轴刻度按天/按小时尽量每格都标(≤31 个点每个都标,超出才抽稀),避免跨度稍大就隔天显示。
|
||||
const labelEvery = Math.max(1, Math.ceil(n / 31));
|
||||
|
||||
// 平均耗时线:仅 avgSec 非 null 的点连线(无完成的桶断开)。
|
||||
const linePts = points
|
||||
.map((p, i) => (p.avgSec == null ? null : `${cx(i)},${secY(p.avgSec)}`))
|
||||
.filter((x): x is string => x !== null)
|
||||
.join(' ');
|
||||
|
||||
return (
|
||||
<svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ display: 'block' }} role="img" aria-label="趋势图">
|
||||
{[0, 0.25, 0.5, 0.75, 1].map((t) => {
|
||||
const y = yBase - t * plotH;
|
||||
return (
|
||||
<g key={t}>
|
||||
<line x1={padL} y1={y} x2={W - padR} y2={y} stroke="#f0f0f0" />
|
||||
<text x={padL - 8} y={y + 4} textAnchor="end" fontSize={11} fill={CHART_BAR_COMPLETED}>
|
||||
{Math.round(maxBar * t)}
|
||||
</text>
|
||||
<text x={W - padR + 8} y={y + 4} textAnchor="start" fontSize={11} fill={CHART_LINE}>
|
||||
{(maxSec * t).toFixed(1)}
|
||||
</text>
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
{/* 发起数柱(浅) */}
|
||||
{points.map((p, i) => (
|
||||
<rect
|
||||
key={`s-${i}`}
|
||||
x={barX(i)}
|
||||
y={yBase - barH(p.started)}
|
||||
width={barW}
|
||||
height={barH(p.started)}
|
||||
fill={CHART_BAR_STARTED}
|
||||
rx={2}
|
||||
>
|
||||
<title>{p.tip}</title>
|
||||
</rect>
|
||||
))}
|
||||
{/* 完成数柱(深,窄,叠中间) */}
|
||||
{points.map((p, i) => {
|
||||
const cw = barW * 0.55;
|
||||
return (
|
||||
<rect
|
||||
key={`c-${i}`}
|
||||
x={cx(i) - cw / 2}
|
||||
y={yBase - barH(p.completed)}
|
||||
width={cw}
|
||||
height={barH(p.completed)}
|
||||
fill={CHART_BAR_COMPLETED}
|
||||
rx={1}
|
||||
>
|
||||
<title>{p.tip}</title>
|
||||
</rect>
|
||||
);
|
||||
})}
|
||||
{/* 平均耗时线(橙,右轴) */}
|
||||
<polyline points={linePts} fill="none" stroke={CHART_LINE} strokeWidth={2} />
|
||||
{points.map((p, i) =>
|
||||
p.avgSec == null ? null : (
|
||||
<circle key={`p-${i}`} cx={cx(i)} cy={secY(p.avgSec)} r={2.5} fill={CHART_LINE}>
|
||||
<title>{p.tip}</title>
|
||||
</circle>
|
||||
),
|
||||
)}
|
||||
{points.map((p, i) =>
|
||||
i % labelEvery === 0 || i === n - 1 ? (
|
||||
<text key={`x-${i}`} x={cx(i)} y={H - 14} textAnchor="middle" fontSize={11} fill="#999">
|
||||
{p.label}
|
||||
</text>
|
||||
) : null,
|
||||
)}
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
// 领券数据看板:上半汇总卡 + 按天/小时趋势(参考广告收益大盘),下半逐条领券明细。
|
||||
// 数据源 coupon_session(客户端 /api/v1/coupon/session 两段上报);耗时统计只算 completed。
|
||||
export default function CouponDataPage() {
|
||||
const { message } = App.useApp();
|
||||
const [range, setRange] = useState<[Dayjs, Dayjs]>([dayjs().subtract(6, 'day'), dayjs()]);
|
||||
const [user, setUser] = useState<string>('');
|
||||
const [appEnv, setAppEnv] = useState<string>('prod');
|
||||
const [granularity, setGranularity] = useState<'day' | 'hour'>('day');
|
||||
const [sortBy, setSortBy] = useState<'time' | 'elapsed'>('time');
|
||||
const [limit, setLimit] = useState<number>(100);
|
||||
const [page, setPage] = useState<number>(1);
|
||||
const [queriedGranularity, setQueriedGranularity] = useState<'day' | 'hour'>('day');
|
||||
const [queriedMultiDay, setQueriedMultiDay] = useState(false);
|
||||
const [queriedLimit, setQueriedLimit] = useState<number>(100);
|
||||
const [data, setData] = useState<CouponDataReport | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
// 点手机号:抽屉看该用户全部领券(总次数 + 记录)
|
||||
const [recordsUser, setRecordsUser] = useState<{ userId: number; phone: string | null } | null>(null);
|
||||
const openUserRecords = (r: CouponDataRow) => {
|
||||
if (r.user_id != null) setRecordsUser({ userId: r.user_id, phone: r.user_phone });
|
||||
};
|
||||
|
||||
// 跨多天时「按小时」无意义,粒度强制按天(同广告报表)。
|
||||
const rangeMultiDay = range[0].format('YYYY-MM-DD') !== range[1].format('YYYY-MM-DD');
|
||||
|
||||
const load = useCallback(
|
||||
async (targetPage = 1, targetLimit = limit, targetSort = sortBy) => {
|
||||
const from = range[0].format('YYYY-MM-DD');
|
||||
const to = range[1].format('YYYY-MM-DD');
|
||||
const multiDay = from !== to;
|
||||
const gran = multiDay ? 'day' : granularity;
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await api.get<CouponDataReport>('/admin/api/coupon-data', {
|
||||
params: {
|
||||
date_from: from,
|
||||
date_to: to,
|
||||
user: user.trim() || undefined,
|
||||
app_env: appEnv,
|
||||
granularity: gran,
|
||||
limit: targetLimit,
|
||||
offset: (targetPage - 1) * targetLimit,
|
||||
sort: targetSort,
|
||||
},
|
||||
});
|
||||
setData(res.data);
|
||||
setPage(targetPage);
|
||||
setQueriedLimit(targetLimit);
|
||||
setQueriedGranularity(gran);
|
||||
setQueriedMultiDay(multiDay);
|
||||
} catch (e) {
|
||||
message.error(errMsg(e));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
[range, user, appEnv, granularity, limit, sortBy, message],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
// 仅首次自动拉近 7 天;之后由「查询」按钮触发
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
const columns: ColumnsType<CouponDataRow> = [
|
||||
{
|
||||
title: '用户',
|
||||
dataIndex: 'user_nickname',
|
||||
width: 140,
|
||||
render: (_: unknown, r: CouponDataRow) => {
|
||||
if (r.user_nickname) {
|
||||
return (
|
||||
<span>
|
||||
{r.user_nickname}
|
||||
{r.user_id != null && (
|
||||
<Typography.Text type="secondary" style={{ fontSize: 11, marginLeft: 6 }}>
|
||||
#{r.user_id}
|
||||
</Typography.Text>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
if (r.user_id != null) return <Typography.Text type="secondary">#{r.user_id}</Typography.Text>;
|
||||
return <Typography.Text type="secondary">游客</Typography.Text>;
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '手机号',
|
||||
dataIndex: 'user_phone',
|
||||
width: 130,
|
||||
// 点手机号 → 抽屉看该用户全部领券(参考低价审核/反馈页)。游客(无 user_id)不可点。
|
||||
render: (phone: string | null, r: CouponDataRow) =>
|
||||
r.user_id != null ? (
|
||||
<a onClick={() => openUserRecords(r)}>{phone || `#${r.user_id}`}</a>
|
||||
) : (
|
||||
<Typography.Text type="secondary">游客</Typography.Text>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
width: 90,
|
||||
render: (s: string) => {
|
||||
const t = STATUS_TAG[s] ?? { color: 'default', label: s };
|
||||
return <Tag color={t.color}>{t.label}</Tag>;
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '发起平台',
|
||||
dataIndex: 'origin_package',
|
||||
width: 110,
|
||||
render: (pkg: string | null) => originLabel(pkg),
|
||||
},
|
||||
{
|
||||
title: '耗时',
|
||||
dataIndex: 'elapsed_ms',
|
||||
width: 90,
|
||||
align: 'right',
|
||||
render: (v: number | null) => fmtSec(v),
|
||||
},
|
||||
{
|
||||
title: '美团耗时',
|
||||
key: 'mt_elapsed',
|
||||
width: 90,
|
||||
align: 'right',
|
||||
render: (_: unknown, r: CouponDataRow) => fmtSec(r.platform_elapsed?.['meituan-waimai']),
|
||||
},
|
||||
{
|
||||
title: '淘宝耗时',
|
||||
key: 'tb_elapsed',
|
||||
width: 90,
|
||||
align: 'right',
|
||||
render: (_: unknown, r: CouponDataRow) => fmtSec(r.platform_elapsed?.['taobao-shanguang']),
|
||||
},
|
||||
{
|
||||
title: '京东耗时',
|
||||
key: 'jd_elapsed',
|
||||
width: 90,
|
||||
align: 'right',
|
||||
render: (_: unknown, r: CouponDataRow) => fmtSec(r.platform_elapsed?.['jd-waimai']),
|
||||
},
|
||||
{
|
||||
title: '机型/ROM',
|
||||
key: 'device',
|
||||
width: 200,
|
||||
render: (_: unknown, r: CouponDataRow) => {
|
||||
const parts = [r.device_model, r.rom].filter(Boolean);
|
||||
return parts.length ? parts.join(' / ') : <Typography.Text type="secondary">-</Typography.Text>;
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '时间',
|
||||
dataIndex: 'started_at',
|
||||
width: 165,
|
||||
render: (v: string) => formatUtcTime(v),
|
||||
},
|
||||
{
|
||||
title: '领券 trace',
|
||||
dataIndex: 'trace_id',
|
||||
width: 150,
|
||||
// 有 trace_url(pricebot 上云,仅 completed)→ 可点链接打开完整现场;否则降级为可复制 trace_id。
|
||||
render: (v: string, r: CouponDataRow) =>
|
||||
r.trace_url ? (
|
||||
<a href={r.trace_url} target="_blank" rel="noreferrer" title={v}>
|
||||
trace({v.slice(0, 8)}…)
|
||||
</a>
|
||||
) : (
|
||||
<Typography.Text copyable={{ text: v }} style={{ fontSize: 12 }}>
|
||||
{v.slice(0, 8)}…
|
||||
</Typography.Text>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
const summary = data?.summary;
|
||||
const items = data?.items ?? [];
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Space align="center" style={{ display: 'flex', marginBottom: 16 }}>
|
||||
<h2 style={{ margin: 0 }}>领券数据</h2>
|
||||
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
|
||||
发起→完成耗时口径为客户端全程计时;均值/分位仅统计「完成」的领券
|
||||
</Typography.Text>
|
||||
</Space>
|
||||
|
||||
<Card size="small" style={{ marginBottom: 16 }}>
|
||||
<Space wrap size="middle" align="center">
|
||||
<Space size={6}>
|
||||
<Typography.Text type="secondary">日期</Typography.Text>
|
||||
<RangePicker
|
||||
value={range}
|
||||
onChange={(v) => v && v[0] && v[1] && setRange([v[0], v[1]])}
|
||||
allowClear={false}
|
||||
presets={[
|
||||
{ label: '今天', value: [dayjs(), dayjs()] },
|
||||
{ label: '近 7 天', value: [dayjs().subtract(6, 'day'), dayjs()] },
|
||||
{ label: '近 30 天', value: [dayjs().subtract(29, 'day'), dayjs()] },
|
||||
]}
|
||||
/>
|
||||
</Space>
|
||||
<Space size={6}>
|
||||
<Typography.Text type="secondary">用户</Typography.Text>
|
||||
<Input
|
||||
placeholder="手机号/昵称"
|
||||
value={user}
|
||||
onChange={(e) => setUser(e.target.value)}
|
||||
onPressEnter={() => load(1)}
|
||||
allowClear
|
||||
style={{ width: 150 }}
|
||||
/>
|
||||
</Space>
|
||||
<Space size={6}>
|
||||
<Typography.Text type="secondary">环境</Typography.Text>
|
||||
<Select
|
||||
value={appEnv}
|
||||
onChange={setAppEnv}
|
||||
style={{ width: 120 }}
|
||||
options={[
|
||||
{ value: 'prod', label: '正式(prod)' },
|
||||
{ value: 'dev', label: '测试(dev)' },
|
||||
{ value: 'all', label: '全部' },
|
||||
]}
|
||||
/>
|
||||
</Space>
|
||||
<Space size={6}>
|
||||
<Typography.Text type="secondary">粒度</Typography.Text>
|
||||
<Select
|
||||
value={rangeMultiDay ? 'day' : granularity}
|
||||
onChange={setGranularity}
|
||||
disabled={rangeMultiDay}
|
||||
style={{ width: 110 }}
|
||||
title={rangeMultiDay ? '跨多天仅支持按天' : undefined}
|
||||
options={[
|
||||
{ value: 'day', label: '按天' },
|
||||
{ value: 'hour', label: '按小时' },
|
||||
]}
|
||||
/>
|
||||
</Space>
|
||||
<Space size={6}>
|
||||
<Typography.Text type="secondary">排序</Typography.Text>
|
||||
<Select
|
||||
value={sortBy}
|
||||
onChange={(v) => {
|
||||
setSortBy(v);
|
||||
load(1, limit, v);
|
||||
}}
|
||||
style={{ width: 130 }}
|
||||
options={[
|
||||
{ value: 'time', label: '时间倒序' },
|
||||
{ value: 'elapsed', label: '耗时倒序' },
|
||||
]}
|
||||
/>
|
||||
</Space>
|
||||
<Space size={6}>
|
||||
<Typography.Text type="secondary">每页</Typography.Text>
|
||||
<Select
|
||||
value={limit}
|
||||
onChange={(v) => {
|
||||
setLimit(v);
|
||||
load(1, v);
|
||||
}}
|
||||
style={{ width: 120 }}
|
||||
options={[20, 50, 100, 200, 500].map((nn) => ({ value: nn, label: `${nn} 条/页` }))}
|
||||
/>
|
||||
</Space>
|
||||
<Button type="primary" onClick={() => load(1)} loading={loading}>
|
||||
查询
|
||||
</Button>
|
||||
</Space>
|
||||
</Card>
|
||||
|
||||
{summary && (
|
||||
<Card size="small" style={{ marginBottom: 16 }}>
|
||||
<Row gutter={[16, 12]}>
|
||||
<Col flex="1 1 0">
|
||||
<Statistic title="领券发起数" value={summary.started_count} />
|
||||
</Col>
|
||||
<Col flex="1 1 0">
|
||||
<Statistic title="领券完成数" value={summary.completed_count} />
|
||||
</Col>
|
||||
<Col flex="1 1 0">
|
||||
<Statistic title="平均耗时" value={fmtSec(summary.avg_elapsed_ms)} />
|
||||
</Col>
|
||||
</Row>
|
||||
<Divider style={{ marginTop: 16, marginBottom: 16 }} />
|
||||
<Row gutter={[16, 12]}>
|
||||
<Col flex="1 1 0">
|
||||
<Statistic title="耗时 5 分位" value={fmtSec(summary.p5_ms)} />
|
||||
</Col>
|
||||
<Col flex="1 1 0">
|
||||
<Statistic title="耗时 50 分位" value={fmtSec(summary.p50_ms)} />
|
||||
</Col>
|
||||
<Col flex="1 1 0">
|
||||
<Statistic title="耗时 95 分位" value={fmtSec(summary.p95_ms)} />
|
||||
</Col>
|
||||
<Col flex="1 1 0">
|
||||
<Statistic title="耗时 99 分位" value={fmtSec(summary.p99_ms)} />
|
||||
</Col>
|
||||
</Row>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{data &&
|
||||
(queriedMultiDay
|
||||
? (data.daily?.length ?? 0) > 0
|
||||
: queriedGranularity === 'hour' && (data.hourly?.length ?? 0) > 0) && (
|
||||
<Card
|
||||
size="small"
|
||||
title={queriedMultiDay ? '按天趋势' : '按小时趋势'}
|
||||
style={{ marginBottom: 16 }}
|
||||
extra={
|
||||
<Space size={16}>
|
||||
<span style={{ fontSize: 12, color: '#666' }}>
|
||||
<span
|
||||
style={{
|
||||
display: 'inline-block',
|
||||
width: 10,
|
||||
height: 10,
|
||||
background: CHART_BAR_STARTED,
|
||||
borderRadius: 2,
|
||||
marginRight: 4,
|
||||
}}
|
||||
/>
|
||||
发起数
|
||||
</span>
|
||||
<span style={{ fontSize: 12, color: '#666' }}>
|
||||
<span
|
||||
style={{
|
||||
display: 'inline-block',
|
||||
width: 10,
|
||||
height: 10,
|
||||
background: CHART_BAR_COMPLETED,
|
||||
borderRadius: 2,
|
||||
marginRight: 4,
|
||||
}}
|
||||
/>
|
||||
完成数
|
||||
</span>
|
||||
<span style={{ fontSize: 12, color: '#666' }}>
|
||||
<span
|
||||
style={{
|
||||
display: 'inline-block',
|
||||
width: 14,
|
||||
borderTop: `2px solid ${CHART_LINE}`,
|
||||
marginRight: 4,
|
||||
verticalAlign: 'middle',
|
||||
}}
|
||||
/>
|
||||
平均耗时(秒)
|
||||
</span>
|
||||
</Space>
|
||||
}
|
||||
>
|
||||
{queriedMultiDay ? (
|
||||
<TrendChart points={aggregateDaily(data.date_from, data.date_to, data.daily)} />
|
||||
) : (
|
||||
<TrendChart points={aggregateHourly(data.hourly)} />
|
||||
)}
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<Table
|
||||
rowKey="trace_id"
|
||||
columns={columns}
|
||||
dataSource={items}
|
||||
loading={loading}
|
||||
pagination={{
|
||||
current: page,
|
||||
pageSize: queriedLimit,
|
||||
total: data?.total ?? 0,
|
||||
showSizeChanger: false,
|
||||
showTotal: (t) => `共 ${t} 条`,
|
||||
onChange: (p) => load(p, queriedLimit),
|
||||
}}
|
||||
size="small"
|
||||
scroll={{ x: 1450 }}
|
||||
/>
|
||||
|
||||
<UserRecordsDrawer<CouponDataRow>
|
||||
open={recordsUser != null}
|
||||
onClose={() => setRecordsUser(null)}
|
||||
userId={recordsUser?.userId ?? null}
|
||||
phone={recordsUser?.phone ?? null}
|
||||
endpoint="/admin/api/coupon-data/user-records"
|
||||
columns={RECORD_COLUMNS}
|
||||
recordLabel="领券"
|
||||
countLabel="领券次数"
|
||||
rewardLabel="领到券张数"
|
||||
rewardSuffix="张"
|
||||
rewardOf={(r) => r.claimed_count ?? 0}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -118,9 +118,10 @@ function previousPeriodRange(range: ReturnType<typeof periodRange>) {
|
||||
}
|
||||
|
||||
function retentionTitle(period: PeriodKey) {
|
||||
if (period === '7d') return '近 7 日新增留存';
|
||||
if (period === '30d') return '近 30 日新增留存';
|
||||
return '昨日新增留存';
|
||||
// 次日留存口径(2026-07-05):每天取前一日新增用户,统计其当日活跃比例;单日窗口即「前日新增的昨日留存」。
|
||||
if (period === '7d') return '近 7 日新增次日留存';
|
||||
if (period === '30d') return '近 30 日新增次日留存';
|
||||
return '前日用户新增留存';
|
||||
}
|
||||
|
||||
function avgEcpm(report: AdRevenueReport | null) {
|
||||
@@ -131,19 +132,23 @@ function avgEcpm(report: AdRevenueReport | null) {
|
||||
function adTypeSummary(report: AdRevenueReport | null, adType: string) {
|
||||
if (!report) return null;
|
||||
if (report.by_ad_type?.[adType]) return report.by_ad_type[adType];
|
||||
// 优先用后端全量小计 type_stats(items 受 limit 分页截断,>1000 行的区间按 items 现算会漏旧数据)
|
||||
const stat = report.type_stats?.[adType];
|
||||
if (stat) return { impressions: stat.impressions, revenue_yuan: stat.revenue_yuan };
|
||||
const matched = report.items.filter((it) => it.ad_type === adType);
|
||||
if (matched.length === 0) return null;
|
||||
return {
|
||||
ad_type: adType,
|
||||
impressions: matched.reduce((sum, it) => sum + it.impressions, 0),
|
||||
revenue_yuan: matched.reduce((sum, it) => sum + it.revenue_yuan, 0),
|
||||
expected_coin: matched.reduce((sum, it) => sum + it.expected_coin, 0),
|
||||
actual_coin: matched.reduce((sum, it) => sum + it.actual_coin, 0),
|
||||
};
|
||||
}
|
||||
|
||||
function adSceneSummary(report: AdRevenueReport | null, feedScene: 'coupon' | 'comparison') {
|
||||
if (!report) return null;
|
||||
// 优先用后端全量小计 scene_stats:2026-07-02 起 items 不再含信息流逐条展示行(唯一带收益+场景的行),
|
||||
// 按 items 现算恒为 0;scene_stats 在全量 events 上聚合且不受分页截断。旧后端无此字段时回退 items 现算。
|
||||
const stat = report.scene_stats?.[feedScene];
|
||||
if (stat) return { impressions: stat.impressions, revenue_yuan: stat.revenue_yuan };
|
||||
const matched = report.items.filter((it) => it.feed_scene === feedScene);
|
||||
if (matched.length === 0) return null;
|
||||
return {
|
||||
@@ -521,6 +526,23 @@ export default function DashboardPage() {
|
||||
periodData?.comparison.average_duration_ms,
|
||||
previousPeriodData?.comparison.average_duration_ms,
|
||||
);
|
||||
// 领券核心数据(period.coupon;旧后端无此字段时整节显示 '--')
|
||||
const couponPeriod = periodData?.coupon ?? null;
|
||||
const previousCouponPeriod = previousPeriodData?.coupon ?? null;
|
||||
const couponStartedDelta = percentDelta(couponPeriod?.started, previousCouponPeriod?.started);
|
||||
const couponSuccessRateValue =
|
||||
couponPeriod?.success_rate == null ? '--' : (couponPeriod.success_rate * 100).toFixed(1);
|
||||
const couponSuccessRateDelta = pointDelta(couponPeriod?.success_rate, previousCouponPeriod?.success_rate);
|
||||
const couponPointRateValue =
|
||||
couponPeriod?.point_success_rate == null ? '--' : (couponPeriod.point_success_rate * 100).toFixed(1);
|
||||
const couponPointRateDelta = pointDelta(
|
||||
couponPeriod?.point_success_rate,
|
||||
previousCouponPeriod?.point_success_rate,
|
||||
);
|
||||
const couponMedianDelta = durationDelta(
|
||||
couponPeriod?.median_elapsed_ms,
|
||||
previousCouponPeriod?.median_elapsed_ms,
|
||||
);
|
||||
const averageSavedDelta = moneyDeltaCents(
|
||||
periodData?.comparison.average_saved_cents,
|
||||
previousPeriodData?.comparison.average_saved_cents,
|
||||
@@ -761,6 +783,51 @@ export default function DashboardPage() {
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="section">
|
||||
<div className="section-head">
|
||||
<span className="bar" />
|
||||
<h3>领券核心数据</h3>
|
||||
<span>发起、整场成功、点位成功与效率</span>
|
||||
</div>
|
||||
<div className="grid g4">
|
||||
<StatCard
|
||||
title="领券发起数"
|
||||
value={fmtInt(couponPeriod?.started)}
|
||||
unit="次"
|
||||
delta={couponStartedDelta.value}
|
||||
deltaTone={couponStartedDelta.tone}
|
||||
/>
|
||||
<StatCard
|
||||
title="领券成功率"
|
||||
value={couponSuccessRateValue}
|
||||
unit="%"
|
||||
delta={couponSuccessRateDelta.value}
|
||||
deltaTone={couponSuccessRateDelta.tone}
|
||||
hint={`全部点位领成功的次数 / 领券发起数;本期 ${fmtInt(couponPeriod?.all_success)} / ${fmtInt(
|
||||
couponPeriod?.started,
|
||||
)} 次。点位成功口径含「今日已领过」。`}
|
||||
/>
|
||||
<StatCard
|
||||
title="点位成功率"
|
||||
value={couponPointRateValue}
|
||||
unit="%"
|
||||
delta={couponPointRateDelta.value}
|
||||
deltaTone={couponPointRateDelta.tone}
|
||||
hint={`成功点位数 / (领券发起数 × 每次应领点位数);中途退出未跑到的点位计入分母视为失败。本期成功点位 ${fmtInt(
|
||||
couponPeriod?.point_success,
|
||||
)} 个,每次应领 ${fmtInt(couponPeriod?.points_per_session)} 个(按本期完成场自动校准)。`}
|
||||
/>
|
||||
<StatCard
|
||||
title="耗时中位数"
|
||||
value={fmtMsAsSeconds(couponPeriod?.median_elapsed_ms)}
|
||||
unit="秒"
|
||||
delta={couponMedianDelta.value}
|
||||
deltaTone={couponMedianDelta.tone}
|
||||
hint="仅统计「完成」的领券(同领券数据页口径),中位数比均值更抗中途暂停等待的长尾。"
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="section">
|
||||
<div className="section-head">
|
||||
<span className="bar" />
|
||||
@@ -932,7 +999,7 @@ export default function DashboardPage() {
|
||||
value={fmtInt(periodData?.coins.reward_video_coin_total)}
|
||||
delta={rewardVideoCoinRatio.value}
|
||||
deltaTone={rewardVideoCoinRatio.tone}
|
||||
hint="激励视频金币已按产品口径计入领券奖励金币,这里单独展示来源占比。"
|
||||
hint="独立统计激励视频发放,不再重复计入领券奖励。"
|
||||
/>
|
||||
<StatCard
|
||||
title="常规任务金币"
|
||||
@@ -955,7 +1022,7 @@ export default function DashboardPage() {
|
||||
实际提现兑付 <b>{fmtCents(periodData?.cash.withdraw_success_cents)}</b>。
|
||||
累计已发放 <b>{fmtCoinAmount(data.coins.granted_total)}</b> 金币但累计真实提现仅
|
||||
<b>{fmtCents(data.cash.withdraw_success_cents)}</b>,发放与现金兑付背离属正常(金币沉淀/过期);
|
||||
需盯紧各来源占比突变与异常领取,防薅羊毛。
|
||||
邀请奖励、后台手动加金币、福利页/老版本未打标签信息流不进入这 4 项,需盯紧各来源占比突变与异常领取。
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -49,6 +49,17 @@ const statusTag = (s: string) => {
|
||||
return <Tag color={m.color}>{m.label}</Tag>;
|
||||
};
|
||||
|
||||
// 反馈类型:comparison=比价反馈 / profile(及旧数据)=普通反馈
|
||||
const SOURCE_META: Record<string, { label: string; color: string }> = {
|
||||
comparison: { label: '比价反馈', color: 'geekblue' },
|
||||
profile: { label: '普通反馈', color: 'default' },
|
||||
};
|
||||
|
||||
const sourceTag = (s: string) => {
|
||||
const m = SOURCE_META[s] ?? { label: '普通反馈', color: 'default' };
|
||||
return <Tag color={m.color}>{m.label}</Tag>;
|
||||
};
|
||||
|
||||
function FeedbackImages({ images }: { images: string[] | null }) {
|
||||
if (!images || !images.length) return <Text type="secondary">无截图</Text>;
|
||||
return (
|
||||
@@ -113,12 +124,14 @@ export default function FeedbackHandleDrawer({ feedback, open, onClose, onDone }
|
||||
await api.post(`/admin/api/feedbacks/${feedback.id}/approve`, {
|
||||
reward_coins: v.reward_coins,
|
||||
note: v.note?.trim() || null,
|
||||
reply: v.reply?.trim() || null,
|
||||
});
|
||||
message.success(`已采纳,发放 ${v.reward_coins} 金币`);
|
||||
} else {
|
||||
await api.post(`/admin/api/feedbacks/${feedback.id}/reject`, {
|
||||
reason: v.reason.trim(),
|
||||
note: v.note?.trim() || null,
|
||||
reply: v.reply?.trim() || null,
|
||||
});
|
||||
message.success('已拒绝');
|
||||
}
|
||||
@@ -155,6 +168,14 @@ export default function FeedbackHandleDrawer({ feedback, open, onClose, onDone }
|
||||
<Text type="secondary">
|
||||
用户 {feedback.user_id} · {formatWallTime(feedback.created_at)}
|
||||
</Text>
|
||||
<div style={{ marginTop: 6 }}>
|
||||
{sourceTag(feedback.source)}
|
||||
{feedback.scene ? (
|
||||
<Text type="secondary" style={{ marginLeft: 6 }}>
|
||||
场景:{feedback.scene}
|
||||
</Text>
|
||||
) : null}
|
||||
</div>
|
||||
<Paragraph style={{ whiteSpace: 'pre-wrap', marginTop: 8, marginBottom: 8 }}>
|
||||
{feedback.content || '-'}
|
||||
</Paragraph>
|
||||
@@ -200,7 +221,11 @@ export default function FeedbackHandleDrawer({ feedback, open, onClose, onDone }
|
||||
</div>
|
||||
)}
|
||||
<div style={{ marginTop: 6 }}>
|
||||
审核备注:{feedback.review_note || <Text type="secondary">(无)</Text>}
|
||||
审核备注(内部):{feedback.review_note || <Text type="secondary">(无)</Text>}
|
||||
</div>
|
||||
<div style={{ marginTop: 6 }}>
|
||||
给用户的回复(用户可见):
|
||||
{feedback.admin_reply || <Text type="secondary">(无)</Text>}
|
||||
</div>
|
||||
{isPending(feedback.status) && (
|
||||
<div style={{ marginTop: 6 }}>
|
||||
@@ -243,11 +268,23 @@ export default function FeedbackHandleDrawer({ feedback, open, onClose, onDone }
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="note"
|
||||
label="采纳要点 / 审核备注(选填)"
|
||||
label="采纳要点 / 审核备注(选填,内部)"
|
||||
rules={[{ max: 256, message: '最多 256 字' }]}
|
||||
>
|
||||
<Input.TextArea rows={3} maxLength={256} showCount placeholder="如:建议已采纳,将在下个版本上线" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="reply"
|
||||
label="给用户的回复(选填,用户端可见)"
|
||||
rules={[{ max: 256, message: '最多 256 字' }]}
|
||||
>
|
||||
<Input.TextArea
|
||||
rows={2}
|
||||
maxLength={256}
|
||||
showCount
|
||||
placeholder="将展示在用户的「我的反馈」里,如:感谢反馈,已收到~"
|
||||
/>
|
||||
</Form.Item>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
@@ -268,6 +305,18 @@ export default function FeedbackHandleDrawer({ feedback, open, onClose, onDone }
|
||||
>
|
||||
<Input.TextArea rows={2} maxLength={256} showCount placeholder="运营内部备注" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="reply"
|
||||
label="给用户的回复(选填,用户端可见)"
|
||||
rules={[{ max: 256, message: '最多 256 字' }]}
|
||||
>
|
||||
<Input.TextArea
|
||||
rows={2}
|
||||
maxLength={256}
|
||||
showCount
|
||||
placeholder="除未采纳原因外,想额外对用户说的话(选填)"
|
||||
/>
|
||||
</Form.Item>
|
||||
</>
|
||||
)}
|
||||
</Form>
|
||||
@@ -294,7 +343,10 @@ export default function FeedbackHandleDrawer({ feedback, open, onClose, onDone }
|
||||
<Text type="secondary">
|
||||
#{h.id} · {formatWallTime(h.created_at)}
|
||||
</Text>
|
||||
{statusTag(h.status)}
|
||||
<Space size={4}>
|
||||
{sourceTag(h.source)}
|
||||
{statusTag(h.status)}
|
||||
</Space>
|
||||
</div>
|
||||
<Paragraph
|
||||
style={{ whiteSpace: 'pre-wrap', margin: '6px 0 0' }}
|
||||
@@ -313,6 +365,9 @@ export default function FeedbackHandleDrawer({ feedback, open, onClose, onDone }
|
||||
未采纳:{h.reject_reason || '-'}
|
||||
</Text>
|
||||
)}
|
||||
{h.admin_reply ? (
|
||||
<div style={{ fontSize: 12, marginTop: 2 }}>回复:{h.admin_reply}</div>
|
||||
) : null}
|
||||
</div>
|
||||
))}
|
||||
</Space>
|
||||
|
||||
@@ -49,7 +49,42 @@ const statusTag = (s: string) => {
|
||||
return <Tag color={m.color}>{m.label}</Tag>;
|
||||
};
|
||||
|
||||
// 审核结果展示(采纳=金币+批注 / 未采纳=原因 / 待审核=-),主表与「该用户全部反馈」抽屉共用
|
||||
// 反馈类型:comparison=比价反馈(比价结果页入口) / profile=普通反馈(「我的」页入口)。
|
||||
// 旧数据与未识别来源按普通反馈展示。
|
||||
const SOURCE_META: Record<string, { label: string; color: string }> = {
|
||||
comparison: { label: '比价反馈', color: 'geekblue' },
|
||||
profile: { label: '普通反馈', color: 'default' },
|
||||
};
|
||||
|
||||
const SOURCE_OPTIONS = [
|
||||
{ value: 'comparison', label: '比价反馈' },
|
||||
{ value: 'profile', label: '普通反馈' },
|
||||
];
|
||||
|
||||
// 反馈类型标签 +(比价反馈时)问题场景副标题
|
||||
const renderSource = (f: Feedback) => {
|
||||
const m = SOURCE_META[f.source] ?? { label: '普通反馈', color: 'default' };
|
||||
return (
|
||||
<Space direction="vertical" size={0}>
|
||||
<Tag color={m.color}>{m.label}</Tag>
|
||||
{f.scene ? (
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>
|
||||
{f.scene}
|
||||
</Text>
|
||||
) : null}
|
||||
</Space>
|
||||
);
|
||||
};
|
||||
|
||||
// 用户可见的运营回复留言(采纳/未采纳都可能有)
|
||||
const replyLine = (f: Feedback) =>
|
||||
f.admin_reply ? (
|
||||
<Text style={{ fontSize: 12 }} ellipsis>
|
||||
回复:{f.admin_reply}
|
||||
</Text>
|
||||
) : null;
|
||||
|
||||
// 审核结果展示(采纳=金币+批注 / 未采纳=原因 / 回复留言 / 待审核=-),主表与「该用户全部反馈」抽屉共用
|
||||
const renderReview = (f: Feedback) => {
|
||||
if (f.status === 'adopted') {
|
||||
return (
|
||||
@@ -60,14 +95,18 @@ const renderReview = (f: Feedback) => {
|
||||
{f.review_note}
|
||||
</Text>
|
||||
) : null}
|
||||
{replyLine(f)}
|
||||
</Space>
|
||||
);
|
||||
}
|
||||
if (f.status === 'rejected') {
|
||||
return (
|
||||
<Text type="secondary" style={{ fontSize: 12 }} ellipsis>
|
||||
未采纳:{f.reject_reason || '-'}
|
||||
</Text>
|
||||
<Space direction="vertical" size={0}>
|
||||
<Text type="secondary" style={{ fontSize: 12 }} ellipsis>
|
||||
未采纳:{f.reject_reason || '-'}
|
||||
</Text>
|
||||
{replyLine(f)}
|
||||
</Space>
|
||||
);
|
||||
}
|
||||
return <Text type="secondary">-</Text>;
|
||||
@@ -95,6 +134,7 @@ const renderDeviceOs = (f: Feedback) => {
|
||||
const RECORD_COLUMNS: ColumnsType<Feedback> = [
|
||||
{ title: '提交时间', dataIndex: 'created_at', width: 150, render: (v: string) => formatWallTime(v) },
|
||||
{ title: '状态', dataIndex: 'status', width: 80, render: statusTag },
|
||||
{ title: '反馈类型', key: 'source', width: 100, render: (_: unknown, f: Feedback) => renderSource(f) },
|
||||
{
|
||||
title: '内容',
|
||||
dataIndex: 'content',
|
||||
@@ -116,6 +156,7 @@ const RECORD_COLUMNS: ColumnsType<Feedback> = [
|
||||
export default function FeedbacksPage() {
|
||||
// 筛选草稿:点「查询」才应用(避免输入即刷新)
|
||||
const [status, setStatus] = useState<string | undefined>();
|
||||
const [source, setSource] = useState<string | undefined>();
|
||||
const [userId, setUserId] = useState('');
|
||||
const [content, setContent] = useState('');
|
||||
const [createdRange, setCreatedRange] = useState<[Dayjs, Dayjs] | null>(null);
|
||||
@@ -158,6 +199,7 @@ export default function FeedbacksPage() {
|
||||
const search = () =>
|
||||
setApplied({
|
||||
status,
|
||||
source,
|
||||
user_id: userId.trim() ? Number(userId.trim()) : undefined,
|
||||
content: content.trim() || undefined,
|
||||
created_from: createdRange?.[0] ? createdRange[0].startOf('day').toISOString() : undefined,
|
||||
@@ -166,6 +208,7 @@ export default function FeedbacksPage() {
|
||||
|
||||
const resetFilters = () => {
|
||||
setStatus(undefined);
|
||||
setSource(undefined);
|
||||
setUserId('');
|
||||
setContent('');
|
||||
setCreatedRange(null);
|
||||
@@ -216,6 +259,12 @@ export default function FeedbacksPage() {
|
||||
width: 120,
|
||||
render: (v: string | null) => v || <Text type="secondary">无昵称</Text>,
|
||||
},
|
||||
{
|
||||
title: '反馈类型',
|
||||
key: 'source',
|
||||
width: 110,
|
||||
render: (_: unknown, f: Feedback) => renderSource(f),
|
||||
},
|
||||
{
|
||||
title: '提交版本号',
|
||||
dataIndex: 'app_version',
|
||||
@@ -325,6 +374,14 @@ export default function FeedbacksPage() {
|
||||
{ value: 'rejected', label: '未采纳' },
|
||||
]}
|
||||
/>
|
||||
<Select
|
||||
placeholder="反馈类型"
|
||||
value={source}
|
||||
onChange={setSource}
|
||||
allowClear
|
||||
style={{ width: 130 }}
|
||||
options={SOURCE_OPTIONS}
|
||||
/>
|
||||
<Input
|
||||
placeholder="用户ID"
|
||||
value={userId}
|
||||
@@ -367,7 +424,7 @@ export default function FeedbacksPage() {
|
||||
onChange: onPageChange,
|
||||
}}
|
||||
onChange={onTableChange}
|
||||
scroll={{ x: 1610 }}
|
||||
scroll={{ x: 1720 }}
|
||||
/>
|
||||
|
||||
<FeedbackHandleDrawer
|
||||
|
||||
+263
-34
@@ -8,10 +8,10 @@ import {
|
||||
DatabaseOutlined,
|
||||
FileSearchOutlined,
|
||||
FlagOutlined,
|
||||
GiftOutlined,
|
||||
HeartOutlined,
|
||||
LogoutOutlined,
|
||||
MessageOutlined,
|
||||
MobileOutlined,
|
||||
MoneyCollectOutlined,
|
||||
NotificationOutlined,
|
||||
ProfileOutlined,
|
||||
@@ -20,53 +20,113 @@ import {
|
||||
TeamOutlined,
|
||||
UserOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import { Avatar, Dropdown, Layout, Menu } from 'antd';
|
||||
import { clearAuth, getAdmin, getToken } from '@/lib/auth';
|
||||
import { Avatar, Dropdown, Layout, Tooltip } from 'antd';
|
||||
import { api } from '@/lib/api';
|
||||
import { clearAuth, getAdmin, getToken, setAuth } from '@/lib/auth';
|
||||
import type { AdminInfo } from '@/lib/types';
|
||||
|
||||
const { Sider, Header, Content } = Layout;
|
||||
|
||||
const MENU = [
|
||||
{ key: '/dashboard', icon: <DashboardOutlined />, label: '数据大盘' },
|
||||
{ key: '/users', icon: <UserOutlined />, label: '用户管理' },
|
||||
{ key: '/devices', icon: <MobileOutlined />, label: '设备管理' },
|
||||
{ key: '/device-liveness', icon: <HeartOutlined />, label: '设备存活' },
|
||||
{ key: '/withdraws', icon: <MoneyCollectOutlined />, label: '提现管理' },
|
||||
{ key: '/price-reports', icon: <FlagOutlined />, label: '低价审核' },
|
||||
{ key: '/comparison-records', icon: <ProfileOutlined />, label: '比价记录' },
|
||||
{ key: '/feedbacks', icon: <MessageOutlined />, label: '用户反馈' },
|
||||
{ key: '/ad-revenue', icon: <NotificationOutlined />, label: '广告配置' },
|
||||
{ key: '/ad-revenue-report', icon: <BarChartOutlined />, label: '广告收益' },
|
||||
{ key: '/cps', icon: <ShareAltOutlined />, label: 'CPS 分发' },
|
||||
{ key: '/config', icon: <SettingOutlined />, label: '系统配置' },
|
||||
{ key: '/admins', icon: <TeamOutlined />, label: '管理员', superOnly: true },
|
||||
type NavItem = {
|
||||
key: string;
|
||||
icon: React.ReactNode;
|
||||
label: string;
|
||||
};
|
||||
|
||||
type NavGroup =
|
||||
| (NavItem & { children?: never })
|
||||
| {
|
||||
key: string;
|
||||
icon: React.ReactNode;
|
||||
label: string;
|
||||
children: NavItem[];
|
||||
};
|
||||
|
||||
const hasChildren = (group: NavGroup): group is NavGroup & { children: NavItem[] } =>
|
||||
Array.isArray(group.children);
|
||||
|
||||
const NAV_GROUPS: NavGroup[] = [
|
||||
{
|
||||
key: 'dashboard',
|
||||
icon: <DashboardOutlined />,
|
||||
label: '看板',
|
||||
children: [
|
||||
{ key: '/dashboard', icon: <DashboardOutlined />, label: '数据大盘' },
|
||||
{ key: '/coupon-data', icon: <GiftOutlined />, label: '领券数据' },
|
||||
{ key: '/ad-revenue-report', icon: <BarChartOutlined />, label: '广告收益' },
|
||||
{ key: '/comparison-records', icon: <ProfileOutlined />, label: '比价记录' },
|
||||
{ key: '/cps', icon: <ShareAltOutlined />, label: 'CPS收益' },
|
||||
{ key: '/device-liveness', icon: <HeartOutlined />, label: '设备存活' },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: 'reward-review',
|
||||
icon: <MoneyCollectOutlined />,
|
||||
label: '奖励审核',
|
||||
children: [
|
||||
{ key: '/withdraws', icon: <MoneyCollectOutlined />, label: '提现审核' },
|
||||
{ key: '/price-reports', icon: <FlagOutlined />, label: '低价审核' },
|
||||
{ key: '/feedbacks', icon: <MessageOutlined />, label: '用户反馈' },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: 'data-config',
|
||||
icon: <SettingOutlined />,
|
||||
label: '数据配置',
|
||||
children: [
|
||||
{ key: '/config', icon: <SettingOutlined />, label: '系统配置' },
|
||||
{ key: '/ad-revenue', icon: <NotificationOutlined />, label: '广告配置' },
|
||||
{ key: '/users', icon: <UserOutlined />, label: '用户管理' },
|
||||
],
|
||||
},
|
||||
{ key: '/admins', icon: <TeamOutlined />, label: '权限管理' },
|
||||
{ key: '/event-logs', icon: <DatabaseOutlined />, label: '埋点日志' },
|
||||
{ key: '/audit-logs', icon: <FileSearchOutlined />, label: '审计日志' },
|
||||
];
|
||||
|
||||
// 导航项 key(/dashboard)→ 权限页 key(dashboard),与后端 permissions.py 目录对齐
|
||||
const permOf = (key: string) => key.replace(/^\//, '');
|
||||
|
||||
export default function MainLayout({ children }: { children: React.ReactNode }) {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const [admin, setAdmin] = useState<AdminInfo | null>(null);
|
||||
const [collapsed, setCollapsed] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!getToken()) {
|
||||
const token = getToken();
|
||||
if (!token) {
|
||||
router.replace('/login');
|
||||
return;
|
||||
}
|
||||
setAdmin(getAdmin());
|
||||
setAdmin(getAdmin()); // 先用本地存的(快、不闪)
|
||||
// 再拉 /me 刷新有效可见页:超管改过该角色权限也能及时反映到左侧导航
|
||||
api
|
||||
.get<AdminInfo>('/admin/api/auth/me')
|
||||
.then(({ data }) => {
|
||||
setAdmin(data);
|
||||
setAuth(token, data);
|
||||
})
|
||||
.catch(() => {});
|
||||
}, [router]);
|
||||
|
||||
if (!admin) return null; // 守卫期间不闪烁内容
|
||||
|
||||
const items = MENU.filter((m) => !m.superOnly || admin.role === 'super_admin').map((m) => ({
|
||||
key: m.key,
|
||||
icon: m.icon,
|
||||
label: m.label,
|
||||
}));
|
||||
|
||||
// 选中态:取路径一级(/users/123 → /users)
|
||||
// 选中态:取路径一级(/users/123 -> /users)
|
||||
const selectedKey = '/' + (pathname.split('/')[1] || 'dashboard');
|
||||
// 叶子导航项按当前角色的有效可见页过滤:super_admin 恒可见;缺 pages 信息(旧登录)兜底全显示不锁死。
|
||||
const isSuper = admin.role === 'super_admin';
|
||||
const canShowLeaf = (item: { key: string }) =>
|
||||
isSuper || !admin.pages || admin.pages.includes(permOf(item.key));
|
||||
const visibleGroups = NAV_GROUPS
|
||||
.map((group) => {
|
||||
if (!hasChildren(group)) return group;
|
||||
return { ...group, children: group.children.filter(canShowLeaf) };
|
||||
})
|
||||
.filter((group) => (hasChildren(group) ? group.children.length > 0 : canShowLeaf(group)));
|
||||
const flatNavItems = visibleGroups.flatMap((group) =>
|
||||
hasChildren(group) ? group.children : [group],
|
||||
);
|
||||
|
||||
const logout = () => {
|
||||
clearAuth();
|
||||
@@ -75,7 +135,15 @@ export default function MainLayout({ children }: { children: React.ReactNode })
|
||||
|
||||
return (
|
||||
<Layout style={{ minHeight: '100vh' }}>
|
||||
<Sider theme="dark" breakpoint="lg" collapsible>
|
||||
<Sider
|
||||
theme="dark"
|
||||
breakpoint="lg"
|
||||
collapsible
|
||||
collapsed={collapsed}
|
||||
collapsedWidth={72}
|
||||
width={220}
|
||||
onCollapse={setCollapsed}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
height: 48,
|
||||
@@ -88,13 +156,61 @@ export default function MainLayout({ children }: { children: React.ReactNode })
|
||||
>
|
||||
运营后台
|
||||
</div>
|
||||
<Menu
|
||||
theme="dark"
|
||||
mode="inline"
|
||||
selectedKeys={[selectedKey]}
|
||||
items={items}
|
||||
onClick={({ key }) => router.push(key)}
|
||||
/>
|
||||
<nav className={`side-nav${collapsed ? ' side-nav-collapsed' : ''}`} aria-label="后台导航">
|
||||
{collapsed
|
||||
? flatNavItems.map((item) => (
|
||||
<Tooltip key={item.key} title={item.label} placement="right">
|
||||
<button
|
||||
type="button"
|
||||
className={`nav-icon-button${selectedKey === item.key ? ' is-selected' : ''}`}
|
||||
onClick={() => router.push(item.key)}
|
||||
aria-label={item.label}
|
||||
>
|
||||
{item.icon}
|
||||
</button>
|
||||
</Tooltip>
|
||||
))
|
||||
: visibleGroups.map((group) => {
|
||||
const isGroup = hasChildren(group);
|
||||
const groupSelected = isGroup
|
||||
? group.children.some((child) => child.key === selectedKey)
|
||||
: selectedKey === group.key;
|
||||
if (!isGroup) {
|
||||
return (
|
||||
<button
|
||||
key={group.key}
|
||||
type="button"
|
||||
className={`nav-primary nav-direct${groupSelected ? ' is-selected' : ''}`}
|
||||
onClick={() => router.push(group.key)}
|
||||
>
|
||||
<span className="nav-primary-icon">{group.icon}</span>
|
||||
<span>{group.label}</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<section key={group.key} className={`nav-group${groupSelected ? ' is-active' : ''}`}>
|
||||
<div className="nav-primary">
|
||||
<span className="nav-primary-icon">{group.icon}</span>
|
||||
<span>{group.label}</span>
|
||||
</div>
|
||||
<div className="nav-children">
|
||||
{group.children.map((child) => (
|
||||
<button
|
||||
key={child.key}
|
||||
type="button"
|
||||
className={`nav-child${selectedKey === child.key ? ' is-selected' : ''}`}
|
||||
onClick={() => router.push(child.key)}
|
||||
>
|
||||
<span className="nav-child-icon">{child.icon}</span>
|
||||
<span>{child.label}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
</Sider>
|
||||
<Layout>
|
||||
<Header
|
||||
@@ -120,6 +236,119 @@ export default function MainLayout({ children }: { children: React.ReactNode })
|
||||
</Header>
|
||||
<Content style={{ margin: 24 }}>{children}</Content>
|
||||
</Layout>
|
||||
<style jsx global>{`
|
||||
.side-nav {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
padding: 0 10px 14px;
|
||||
}
|
||||
.nav-group {
|
||||
padding: 6px 0 8px;
|
||||
}
|
||||
.nav-group + .nav-group,
|
||||
.nav-group + .nav-direct,
|
||||
.nav-direct + .nav-direct {
|
||||
margin-top: 4px;
|
||||
}
|
||||
.nav-primary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
min-height: 36px;
|
||||
padding: 0 12px;
|
||||
color: rgba(255, 255, 255, 0.88);
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
.nav-primary-icon,
|
||||
.nav-child-icon {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: rgba(255, 255, 255, 0.72);
|
||||
font-size: 16px;
|
||||
}
|
||||
.nav-direct,
|
||||
.nav-child,
|
||||
.nav-icon-button {
|
||||
border: 0;
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
}
|
||||
.nav-direct {
|
||||
width: 100%;
|
||||
border-radius: 8px;
|
||||
background: transparent;
|
||||
}
|
||||
.nav-direct:hover,
|
||||
.nav-direct.is-selected {
|
||||
background: #1677ff;
|
||||
color: #fff;
|
||||
}
|
||||
.nav-direct:hover .nav-primary-icon,
|
||||
.nav-direct.is-selected .nav-primary-icon {
|
||||
color: #fff;
|
||||
}
|
||||
.nav-children {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
margin-left: 34px;
|
||||
margin-top: -2px;
|
||||
padding-right: 2px;
|
||||
}
|
||||
.nav-child {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
min-height: 34px;
|
||||
border-radius: 8px;
|
||||
background: transparent;
|
||||
color: rgba(255, 255, 255, 0.72);
|
||||
font-size: 13px;
|
||||
padding: 0 10px;
|
||||
}
|
||||
.nav-child:hover {
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
color: #fff;
|
||||
}
|
||||
.nav-child.is-selected {
|
||||
background: #1677ff;
|
||||
color: #fff;
|
||||
font-weight: 600;
|
||||
}
|
||||
.nav-child.is-selected .nav-child-icon {
|
||||
color: #fff;
|
||||
}
|
||||
.nav-group.is-active .nav-primary {
|
||||
color: #fff;
|
||||
}
|
||||
.side-nav-collapsed {
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 0 8px 14px;
|
||||
}
|
||||
.nav-icon-button {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: 8px;
|
||||
background: transparent;
|
||||
color: rgba(255, 255, 255, 0.72);
|
||||
font-size: 17px;
|
||||
}
|
||||
.nav-icon-button:hover,
|
||||
.nav-icon-button.is-selected {
|
||||
background: #1677ff;
|
||||
color: #fff;
|
||||
}
|
||||
`}</style>
|
||||
</Layout>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ import { canDo } from '@/lib/auth';
|
||||
import { formatUtcTime, formatWallTime, yuan } from '@/lib/format';
|
||||
import { useCursorList } from '@/lib/useCursorList';
|
||||
import { AdjustCashModal, AdjustCoinModal } from '@/components/AdjustBalanceModals';
|
||||
import { DeleteUserModal } from '@/components/DeleteUserModal';
|
||||
import type { CashTxn, CoinTxn, UserOverview, WithdrawOrder } from '@/lib/types';
|
||||
|
||||
export default function UserDetailPage() {
|
||||
@@ -33,6 +34,7 @@ export default function UserDetailPage() {
|
||||
const [err, setErr] = useState<string | null>(null);
|
||||
const [coinOpen, setCoinOpen] = useState(false);
|
||||
const [cashOpen, setCashOpen] = useState(false);
|
||||
const [delOpen, setDelOpen] = useState(false);
|
||||
|
||||
const loadData = useCallback(() => {
|
||||
setErr(null);
|
||||
@@ -52,6 +54,7 @@ export default function UserDetailPage() {
|
||||
|
||||
const canCoins = canDo(['finance']);
|
||||
const canStatus = canDo(['operator']);
|
||||
const canDelete = canDo(['super_admin']); // 注销账号最高危,仅 super_admin(与后端 require_role 对齐)
|
||||
|
||||
const toggleStatus = () => {
|
||||
if (!data) return;
|
||||
@@ -154,6 +157,11 @@ export default function UserDetailPage() {
|
||||
{data.user.status === 'active' ? '封禁' : '解封'}
|
||||
</Button>
|
||||
)}
|
||||
{canDelete && data.user.status !== 'deleted' && (
|
||||
<Button danger onClick={() => setDelOpen(true)}>
|
||||
注销账号
|
||||
</Button>
|
||||
)}
|
||||
</Space>
|
||||
</Space>
|
||||
<Card style={{ marginBottom: 16 }}>
|
||||
@@ -272,6 +280,12 @@ export default function UserDetailPage() {
|
||||
cash.reload();
|
||||
}}
|
||||
/>
|
||||
<DeleteUserModal
|
||||
user={data.user}
|
||||
open={delOpen}
|
||||
onClose={() => setDelOpen(false)}
|
||||
onDone={loadData}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -5,20 +5,21 @@ import type { Key } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import type { SorterResult } from 'antd/es/table/interface';
|
||||
import { App, Button, DatePicker, Input, Select, Space, Table, Tag } from 'antd';
|
||||
import { App, Button, DatePicker, Input, Select, Space, Table, Tag, Tooltip } from 'antd';
|
||||
import dayjs, { type Dayjs } from 'dayjs';
|
||||
import { api, errMsg } from '@/lib/api';
|
||||
import { canDo } from '@/lib/auth';
|
||||
import { formatUtcTime } from '@/lib/format';
|
||||
import { usePagedList } from '@/lib/usePagedList';
|
||||
import { AdjustCashModal, AdjustCoinModal } from '@/components/AdjustBalanceModals';
|
||||
import { DeleteUserModal } from '@/components/DeleteUserModal';
|
||||
import type { UserListItem } from '@/lib/types';
|
||||
|
||||
const { RangePicker } = DatePicker;
|
||||
|
||||
const STATUS_COLOR: Record<string, string> = { active: 'green', disabled: 'red', deleted: 'default' };
|
||||
|
||||
type SortField = 'id' | 'created_at' | 'last_login_at';
|
||||
type SortField = 'id' | 'created_at' | 'last_active_at';
|
||||
|
||||
export default function UsersPage() {
|
||||
const router = useRouter();
|
||||
@@ -43,9 +44,11 @@ export default function UsersPage() {
|
||||
|
||||
const canCoins = canDo(['finance']);
|
||||
const canStatus = canDo(['operator']);
|
||||
const canDelete = canDo(['super_admin']); // 注销账号最高危,仅 super_admin(与后端 require_role 对齐)
|
||||
|
||||
const [coinUser, setCoinUser] = useState<UserListItem | null>(null);
|
||||
const [cashUser, setCashUser] = useState<UserListItem | null>(null);
|
||||
const [delUser, setDelUser] = useState<UserListItem | null>(null);
|
||||
const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([]);
|
||||
|
||||
// 筛选/排序变化后清空已选(避免选中项跨筛选错位)
|
||||
@@ -61,8 +64,8 @@ export default function UsersPage() {
|
||||
register_channel: channel || undefined,
|
||||
created_from: regRange?.[0] ? regRange[0].startOf('day').toISOString() : undefined,
|
||||
created_to: regRange?.[1] ? regRange[1].endOf('day').toISOString() : undefined,
|
||||
last_login_from: loginRange?.[0] ? loginRange[0].startOf('day').toISOString() : undefined,
|
||||
last_login_to: loginRange?.[1] ? loginRange[1].endOf('day').toISOString() : undefined,
|
||||
last_active_from: loginRange?.[0] ? loginRange[0].startOf('day').toISOString() : undefined,
|
||||
last_active_to: loginRange?.[1] ? loginRange[1].endOf('day').toISOString() : undefined,
|
||||
});
|
||||
|
||||
const resetFilters = () => {
|
||||
@@ -235,18 +238,25 @@ export default function UsersPage() {
|
||||
render: (v: string) => formatUtcTime(v),
|
||||
},
|
||||
{
|
||||
title: '最近登录',
|
||||
dataIndex: 'last_login_at',
|
||||
// 最近活跃 = max(最近登录, 最近发起比价, 最近发起领券),与大盘 DAU/留存活跃口径一致(2026-07-05)
|
||||
title: (
|
||||
<Tooltip title="进入 App(登录)/ 发起比价 / 发起领券,取最近一次">
|
||||
最近活跃
|
||||
</Tooltip>
|
||||
),
|
||||
dataIndex: 'last_active_at',
|
||||
width: 160,
|
||||
sorter: true,
|
||||
sortOrder: sortOrderOf('last_login_at'),
|
||||
render: (v: string) => formatUtcTime(v),
|
||||
// 关掉 antd 默认的「点击升序/降序」表头提示,否则与上面自定义口径 Tooltip 同时弹出互相遮挡
|
||||
showSorterTooltip: false,
|
||||
sortOrder: sortOrderOf('last_active_at'),
|
||||
render: (v: string | null, u: UserListItem) => formatUtcTime(v ?? u.last_login_at),
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
key: 'op',
|
||||
fixed: 'right',
|
||||
width: 300,
|
||||
width: 340,
|
||||
render: (_: unknown, u: UserListItem) => (
|
||||
<Space wrap={false} onClick={(e) => e.stopPropagation()}>
|
||||
<a onClick={() => router.push(`/users/${u.id}`)}>详情</a>
|
||||
@@ -269,6 +279,11 @@ export default function UsersPage() {
|
||||
) : (
|
||||
<a onClick={() => setForceOnboarding(u, true)}>开启新手引导</a>
|
||||
))}
|
||||
{canDelete && u.status !== 'deleted' && (
|
||||
<a style={{ color: '#cf1322' }} onClick={() => setDelUser(u)}>
|
||||
注销
|
||||
</a>
|
||||
)}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
@@ -324,7 +339,7 @@ export default function UsersPage() {
|
||||
allowClear
|
||||
/>
|
||||
<RangePicker
|
||||
placeholder={['最近登录起', '最近登录止']}
|
||||
placeholder={['最近活跃起', '最近活跃止']}
|
||||
value={loginRange}
|
||||
onChange={(v) => setLoginRange(v as [Dayjs, Dayjs] | null)}
|
||||
allowClear
|
||||
@@ -377,12 +392,18 @@ export default function UsersPage() {
|
||||
showTotal: (t) => `共 ${t} 个用户`,
|
||||
onChange: onPageChange,
|
||||
}}
|
||||
scroll={{ x: 1160 }}
|
||||
scroll={{ x: 1200 }}
|
||||
onChange={onTableChange}
|
||||
/>
|
||||
|
||||
<AdjustCoinModal user={coinUser} open={!!coinUser} onClose={() => setCoinUser(null)} />
|
||||
<AdjustCashModal user={cashUser} open={!!cashUser} onClose={() => setCashUser(null)} />
|
||||
<DeleteUserModal
|
||||
user={delUser}
|
||||
open={!!delUser}
|
||||
onClose={() => setDelUser(null)}
|
||||
onDone={reload}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -39,10 +39,12 @@ const PAGE_SIZE = 10; // 金币记录每页条数
|
||||
interface Props {
|
||||
userId: number;
|
||||
user: WithdrawUserSnapshot | null;
|
||||
// 统计区字段集:withdraw(默认,提现详情:含提现细分) / ad(广告收益详情:只看看广告观看统计,对齐参考图 6 项)
|
||||
statsVariant?: 'withdraw' | 'ad';
|
||||
}
|
||||
|
||||
/** 提现详情抽屉:用户基本信息 + 互斥时间筛选 + 看广告/提现统计区 + 金币发放记录表。 */
|
||||
export default function UserRewardPanel({ userId, user }: Props) {
|
||||
/** 用户看广告/提现详情:基本信息 + 互斥时间筛选 + 统计区(按 statsVariant 取字段集)+ 金币发放记录表。 */
|
||||
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);
|
||||
@@ -164,7 +166,7 @@ export default function UserRewardPanel({ userId, user }: Props) {
|
||||
</Space>
|
||||
</Space>
|
||||
|
||||
{/* 统计区(受时间筛选;现金余额为当前快照) */}
|
||||
{/* 统计区(受时间筛选;现金余额为当前快照)。ad 视图只保留看广告观看统计(对齐参考图 6 项) */}
|
||||
<Descriptions bordered size="small" column={2} style={{ marginBottom: 8 }}>
|
||||
<Descriptions.Item label="累计提现">
|
||||
{stats ? yuan(stats.withdraw_success_cents) : '-'}
|
||||
@@ -172,29 +174,51 @@ export default function UserRewardPanel({ userId, user }: Props) {
|
||||
<Descriptions.Item label="现金余额">
|
||||
{stats ? yuan(stats.cash_balance_cents) : '-'}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="提现总次数">{stats?.withdraw_total ?? '-'}</Descriptions.Item>
|
||||
<Descriptions.Item label="传统任务提现">
|
||||
{stats ? yuan(stats.traditional_task_cash_cents) : '-'}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="累计激励视频数">
|
||||
{stats?.reward_video_count ?? '-'}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="平均激励视频ECPM">
|
||||
{stats ? `${stats.reward_video_avg_ecpm} 分/千` : '-'}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="激励视频提现">
|
||||
{stats ? yuan(stats.reward_video_cash_cents) : '-'}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="累计信息流广告数">{stats?.feed_count ?? '-'}</Descriptions.Item>
|
||||
<Descriptions.Item label="平均信息流广告ECPM">
|
||||
{stats ? `${stats.feed_avg_ecpm} 分/千` : '-'}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="信息流广告提现">
|
||||
{stats ? yuan(stats.feed_cash_cents) : '-'}
|
||||
</Descriptions.Item>
|
||||
{statsVariant === 'ad' ? (
|
||||
<>
|
||||
<Descriptions.Item label="激励视频观看数">
|
||||
{stats?.reward_video_count ?? '-'}
|
||||
</Descriptions.Item>
|
||||
{/* eCPM 均按元展示(reward_video / feed avg_ecpm 原始为分/千次,÷100 转元) */}
|
||||
<Descriptions.Item label="平均激励视频ECPM">
|
||||
{stats ? `${(stats.reward_video_avg_ecpm / 100).toFixed(2)} 元/千` : '-'}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="draw信息流视频观看数">
|
||||
{stats?.feed_count ?? '-'}
|
||||
</Descriptions.Item>
|
||||
<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="传统任务提现">
|
||||
{stats ? yuan(stats.traditional_task_cash_cents) : '-'}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="累计激励视频数">
|
||||
{stats?.reward_video_count ?? '-'}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="平均激励视频ECPM">
|
||||
{stats ? `${stats.reward_video_avg_ecpm} 分/千` : '-'}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="激励视频提现">
|
||||
{stats ? yuan(stats.reward_video_cash_cents) : '-'}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="累计信息流广告数">{stats?.feed_count ?? '-'}</Descriptions.Item>
|
||||
<Descriptions.Item label="平均信息流广告ECPM">
|
||||
{stats ? `${stats.feed_avg_ecpm} 分/千` : '-'}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="信息流广告提现">
|
||||
{stats ? yuan(stats.feed_cash_cents) : '-'}
|
||||
</Descriptions.Item>
|
||||
</>
|
||||
)}
|
||||
</Descriptions>
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>
|
||||
统计随上方时间筛选(现金余额除外,为当前快照);eCPM 单位分/千次,同金币审计。
|
||||
{statsVariant === 'ad'
|
||||
? '统计随上方时间筛选(现金余额除外,为当前快照);eCPM 均按元展示(原始分/千次 ÷100)。'
|
||||
: '统计随上方时间筛选(现金余额除外,为当前快照);eCPM 单位分/千次,同金币审计。'}
|
||||
</Text>
|
||||
|
||||
{/* 金币记录 */}
|
||||
|
||||
@@ -104,6 +104,19 @@ const SORT_OPTIONS = [
|
||||
{ value: 'created_at', label: '申请时间' },
|
||||
{ value: 'amount_cents', label: '提现金额' },
|
||||
];
|
||||
// 提现类型:coin_cash=福利页提现(金币兑换现金) / invite_cash=邀请提现(邀请奖励金)
|
||||
const SOURCE_LABEL: Record<string, string> = {
|
||||
coin_cash: '福利页提现',
|
||||
invite_cash: '邀请提现',
|
||||
};
|
||||
const SOURCE_COLOR: Record<string, string> = {
|
||||
coin_cash: 'blue',
|
||||
invite_cash: 'purple',
|
||||
};
|
||||
const SOURCE_OPTIONS = [
|
||||
{ value: 'coin_cash', label: '福利页提现' },
|
||||
{ value: 'invite_cash', label: '邀请提现' },
|
||||
];
|
||||
const DATE_FIELD_OPTIONS = [
|
||||
{ value: 'created_at', label: '申请时间' },
|
||||
{ value: 'updated_at', label: '更新时间' },
|
||||
@@ -184,9 +197,11 @@ export default function WithdrawsPage() {
|
||||
const [sortBy, setSortBy] = useState<'created_at' | 'amount_cents'>('created_at');
|
||||
const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc');
|
||||
const [quickFilter, setQuickFilter] = useState<string | undefined>(undefined);
|
||||
const [source, setSource] = useState<string | undefined>(undefined);
|
||||
|
||||
const filters: Record<string, unknown> = {};
|
||||
if (activeStatus !== 'all') filters.status = activeStatus;
|
||||
if (source) filters.source = source;
|
||||
if (keyword.trim()) filters.keyword = keyword.trim();
|
||||
if (dateRange?.[0]) filters.date_from = dateRange[0].startOf('day').toISOString();
|
||||
if (dateRange?.[1]) filters.date_to = dateRange[1].endOf('day').toISOString();
|
||||
@@ -211,6 +226,7 @@ export default function WithdrawsPage() {
|
||||
setSortBy('created_at');
|
||||
setSortOrder('desc');
|
||||
setQuickFilter(undefined);
|
||||
setSource(undefined);
|
||||
};
|
||||
|
||||
const applyQuickFilter = (value?: string) => {
|
||||
@@ -481,6 +497,12 @@ export default function WithdrawsPage() {
|
||||
width: 120,
|
||||
render: (v: number) => <Text strong>{yuan(v)}</Text>,
|
||||
},
|
||||
{
|
||||
title: '提现类型',
|
||||
dataIndex: 'source',
|
||||
width: 110,
|
||||
render: (v: string) => <Tag color={SOURCE_COLOR[v] || 'default'}>{SOURCE_LABEL[v] || v}</Tag>,
|
||||
},
|
||||
{
|
||||
title: '累计提现',
|
||||
dataIndex: 'cumulative_success_cents',
|
||||
@@ -724,6 +746,14 @@ export default function WithdrawsPage() {
|
||||
}}
|
||||
onSearch={(value) => setKeyword(value.trim())}
|
||||
/>
|
||||
<Select
|
||||
value={source}
|
||||
allowClear
|
||||
placeholder="提现类型"
|
||||
style={{ width: 140 }}
|
||||
options={SOURCE_OPTIONS}
|
||||
onChange={(value?: string) => setSource(value)}
|
||||
/>
|
||||
<Select
|
||||
value={quickFilter}
|
||||
allowClear
|
||||
@@ -849,7 +879,7 @@ export default function WithdrawsPage() {
|
||||
showTotal: (t) => `共 ${t} 条`,
|
||||
onChange: onPageChange,
|
||||
}}
|
||||
scroll={{ x: 1350 }}
|
||||
scroll={{ x: 1460 }}
|
||||
onRow={(record) => ({
|
||||
onClick: () => openDetail(record),
|
||||
style: { cursor: 'pointer' },
|
||||
@@ -881,6 +911,11 @@ export default function WithdrawsPage() {
|
||||
<Descriptions.Item label="金额">
|
||||
<Text strong>{yuan(detail.order.amount_cents)}</Text>
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="提现类型">
|
||||
<Tag color={SOURCE_COLOR[detail.order.source] || 'default'}>
|
||||
{SOURCE_LABEL[detail.order.source] || detail.order.source}
|
||||
</Tag>
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="提现实名">
|
||||
{detail.order.user_name || '-'}
|
||||
</Descriptions.Item>
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
'use client';
|
||||
|
||||
// 注销/删除账号弹窗(受控)。列表页与用户详情页共用,避免两处各写一套(同 AdjustBalanceModals)。
|
||||
// 复用 C 端自助注销同一套后端清理:物理删除个人内容/行为/PII 表 + 清零余额 + 匿名化 user 行,
|
||||
// 保留资金流水/邀请关系/广告幂等+对账表。仅 super_admin 可见入口;后端亦 require_role("super_admin") 兜底。
|
||||
// 后端资金前置闸(有未提现现金/邀请金 / 在审提现单 → 409)带明确 detail,errMsg 原样透出。
|
||||
import { App, Form, Input, Modal } from 'antd';
|
||||
import { api, errMsg } from '@/lib/api';
|
||||
|
||||
export type DeleteTargetUser = { id: number; phone: string };
|
||||
|
||||
interface Props {
|
||||
user: DeleteTargetUser | null;
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
onDone?: () => void; // 删除成功后回调(刷新详情/列表)
|
||||
}
|
||||
|
||||
export function DeleteUserModal({ user, open, onClose, onDone }: Props) {
|
||||
const { message } = App.useApp();
|
||||
const [form] = Form.useForm();
|
||||
|
||||
const submit = async () => {
|
||||
if (!user) return;
|
||||
const v = await form.validateFields(); // 原因必填,缺失即红字阻断
|
||||
try {
|
||||
// axios 的 DELETE 带 body 要放在 config.data 里
|
||||
await api.delete(`/admin/api/users/${user.id}`, { data: { reason: v.reason } });
|
||||
message.success('账号已注销');
|
||||
onClose();
|
||||
onDone?.();
|
||||
} catch (e) {
|
||||
message.error(errMsg(e));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
title={`注销账号 - ${user?.phone ?? ''}`}
|
||||
open={open}
|
||||
onOk={submit}
|
||||
onCancel={onClose}
|
||||
okText="确认注销"
|
||||
okButtonProps={{ danger: true }}
|
||||
afterOpenChange={(o) => {
|
||||
if (o) form.resetFields();
|
||||
}}
|
||||
destroyOnHidden
|
||||
>
|
||||
<p style={{ color: '#cf1322', marginBottom: 12 }}>
|
||||
将永久删除该账号的个人数据(比价/省钱/签到/领券/埋点/设备/邀请指纹等)并清零余额、匿名化手机号,
|
||||
<strong>不可恢复</strong>。资金流水/邀请关系/广告对账记录按合规保留。
|
||||
</p>
|
||||
<Form form={form} layout="vertical">
|
||||
<Form.Item name="reason" label="注销原因(入审计)" rules={[{ required: true, message: '请填写注销原因' }]}>
|
||||
<Input.TextArea rows={2} />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -21,6 +21,7 @@ interface Props<T> {
|
||||
countLabel: string; // 顶部计数卡标题,如「提交总计」/「上报总计」
|
||||
rewardLabel: string; // 顶部奖励卡标题,如「提交奖励总计」/「上报奖励总计」
|
||||
rewardOf: (item: T) => number; // 单条已发奖励金币(未采纳/未通过返回 0)
|
||||
rewardSuffix?: string; // 第二个汇总卡单位,默认「金币」;领券场景可传「张」(领到券张数)等
|
||||
}
|
||||
|
||||
export default function UserRecordsDrawer<T extends { id: number }>({
|
||||
@@ -34,6 +35,7 @@ export default function UserRecordsDrawer<T extends { id: number }>({
|
||||
countLabel,
|
||||
rewardLabel,
|
||||
rewardOf,
|
||||
rewardSuffix = '金币',
|
||||
}: Props<T>) {
|
||||
const [items, setItems] = useState<T[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
@@ -91,7 +93,7 @@ export default function UserRecordsDrawer<T extends { id: number }>({
|
||||
<>
|
||||
<Space size={48} style={{ marginBottom: 20 }}>
|
||||
<Statistic title={countLabel} value={total} />
|
||||
<Statistic title={rewardLabel} value={rewardTotal} suffix="金币" />
|
||||
<Statistic title={rewardLabel} value={rewardTotal} suffix={rewardSuffix} />
|
||||
</Space>
|
||||
{items.length === 0 ? (
|
||||
<Empty description={`该用户暂无${recordLabel}`} style={{ marginTop: 24 }} />
|
||||
|
||||
+54
-3
@@ -3,10 +3,31 @@
|
||||
export interface AdminInfo {
|
||||
id: number;
|
||||
username: string;
|
||||
role: string; // super_admin / finance / operator
|
||||
role: string; // super_admin / finance / operator / 自定义角色名
|
||||
status: string;
|
||||
created_at: string;
|
||||
last_login_at: string | null;
|
||||
pages?: string[]; // 当前角色有效可见页 key(登录 / /me 下发);super_admin = 全部页。左侧导航按此过滤
|
||||
password?: string | null; // 明文登录密码(仅账号列表下发);无留存(脚本建的超管)为 null → 不显示
|
||||
}
|
||||
|
||||
// RBAC:页面权限目录(= 左侧导航项,后端 /admin/api/roles/catalog 下发)
|
||||
export interface PermissionPage {
|
||||
key: string;
|
||||
label: string;
|
||||
}
|
||||
export interface PermissionGroup {
|
||||
group: string;
|
||||
pages: PermissionPage[];
|
||||
}
|
||||
// RBAC:角色(可见页集合)
|
||||
export interface AdminRole {
|
||||
id: number;
|
||||
name: string; // 角色 key(承重,admin_user.role 引用)
|
||||
label: string; // 展示名(UI 显示,如 管理员/运营/财务/技术)
|
||||
pages: string[]; // 该角色有效可见页 key(super_admin = 全部)
|
||||
is_builtin: boolean; // 内建(super_admin):不可编辑/删除
|
||||
in_use: number; // 使用该角色的管理员数
|
||||
}
|
||||
|
||||
export interface LoginResponse {
|
||||
@@ -35,6 +56,8 @@ export interface UserListItem {
|
||||
wechat_openid: string | null;
|
||||
created_at: string;
|
||||
last_login_at: string;
|
||||
// 最近活跃 = max(最近登录, 最近发起比价, 最近发起领券);与大盘 DAU/留存活跃口径一致
|
||||
last_active_at: string | null;
|
||||
}
|
||||
|
||||
// 设备维度新手引导:一台设备(ANDROID_ID)聚合,走过引导的账号数 + 最近完成时间。
|
||||
@@ -117,6 +140,8 @@ export interface WithdrawOrder {
|
||||
user_id: number;
|
||||
out_bill_no: string;
|
||||
amount_cents: number;
|
||||
// 提现类型:coin_cash(福利页提现,金币兑换现金) / invite_cash(邀请提现,邀请奖励金)
|
||||
source: string;
|
||||
user_name: string | null;
|
||||
status: string; // reviewing / pending / success / failed / rejected
|
||||
wechat_state: string | null;
|
||||
@@ -239,12 +264,17 @@ export interface Feedback {
|
||||
user_id: number;
|
||||
content: string;
|
||||
contact: string;
|
||||
// 反馈来源入口:profile(「我的」页=普通反馈) / comparison(比价结果页=比价反馈)
|
||||
source: string;
|
||||
// 比价反馈的问题场景(找错商品/优惠不对…);普通反馈为 null
|
||||
scene: string | null;
|
||||
images: string[] | null;
|
||||
// pending(审核中) / adopted(已采纳) / rejected(未采纳);历史数据可能为 new
|
||||
status: string;
|
||||
reject_reason: string | null; // 未采纳原因(用户端可见)
|
||||
reward_coins: number | null; // 采纳后发放金币
|
||||
review_note: string | null; // 审核批注(采纳要点 / 内部备注)
|
||||
review_note: string | null; // 审核批注(采纳要点 / 内部备注,用户不可见)
|
||||
admin_reply: string | null; // 运营给用户的回复留言(用户端可见)
|
||||
reviewed_by_admin_id: number | null;
|
||||
reviewed_at: string | null;
|
||||
created_at: string;
|
||||
@@ -302,6 +332,7 @@ export interface ComparisonRecordListItem {
|
||||
status: string;
|
||||
information: string | null;
|
||||
store_name: string | null;
|
||||
product_names: string | null; // 下单商品名派生串(顿号分隔),「商品」列展示
|
||||
source_platform_name: string | null;
|
||||
best_platform_name: string | null;
|
||||
source_price_cents: number | null;
|
||||
@@ -425,6 +456,7 @@ export interface AdRevenueRow {
|
||||
impressions: number; // 本行展示条数 1/0(供日汇总、趋势图复用)
|
||||
ecpm: string | null; // 分/千次;展示行取展示值,纯发奖行取发奖采用值
|
||||
revenue_yuan: number; // 本次展示预估收益(元);纯发奖行=0
|
||||
row_revenue_yuan?: number | null; // 主表逐行显示用:一次比价/领券聚合行=该次发奖广告 eCPM 折算之和;其它行空(回退 revenue_yuan)
|
||||
adn: string | null; // 实际填充 ADN;纯发奖行为空
|
||||
slot_id: string | null; // 底层 mediation rit;纯发奖行为空
|
||||
// ── 发奖侧 ──
|
||||
@@ -434,6 +466,8 @@ export interface AdRevenueRow {
|
||||
actual_coin: number; // 实发金币;纯展示=0
|
||||
matched: boolean; // 本条应发==实发;纯展示恒 true(不计对账)
|
||||
reward_detail: AdRevenueRecord | null; // 发奖复算明细(点行展开下钻);纯展示为空
|
||||
sub_rewards?: AdRevenueRecord[]; // 一次比价/领券聚合行的组内逐条明细(同整场 ad_session_id 的多条广告);展开渲染多行
|
||||
sub_count?: number; // 本行聚合的发奖条数:一次比价/领券=该次广告条数(≥1);激励视频/纯展示=1
|
||||
}
|
||||
|
||||
export interface AdRevenueReport {
|
||||
@@ -442,13 +476,17 @@ export interface AdRevenueReport {
|
||||
daily: AdRevenueDaily[]; // 按日期汇总序列(全量,供按天趋势图)
|
||||
hourly: AdRevenueHourly[]; // 按小时汇总序列(全量,供按小时趋势图;按天查询时为空)
|
||||
type_stats: Record<string, AdRevenueTypeStat>; // 按广告类型小计;前端取 draw / reward_video
|
||||
// 按信息流场景小计(comparison/coupon/welfare;全量,不受分页截断)。数据大盘「领券广告/比价广告」卡
|
||||
// 优先读它:2026-07-02 后端起 items 不再含信息流逐条展示行(唯一带收益+场景的行),按 items 现算恒 0。
|
||||
// 可选(`?.` 探测)以兼容未升级后端,缺失时回退 items 现算。
|
||||
scene_stats?: Record<string, AdRevenueTypeStat>;
|
||||
// 可选:后端预聚合的「按广告类型」富小计(含发放金币明细)。当前后端未下发 → 数据大盘页
|
||||
// (dashboard adTypeSummary)用 `?.` 探测、缺失时按 items 现算兜底;后端补上即自动启用。
|
||||
by_ad_type?: Record<
|
||||
string,
|
||||
{ ad_type: string; impressions: number; revenue_yuan: number; expected_coin: number; actual_coin: number }
|
||||
>;
|
||||
dau: number | null; // 今日活跃(复用大盘 last_login_at);仅查询=今日时有值,否则 null
|
||||
dau: number | null; // 区间去重活跃用户(口径同数据大盘 period.users.active:登录+开始比价+开始领券);按查询区间统计、含今日,全局口径不随筛选变化
|
||||
total: number; // 当前筛选下的分页总条数(全量,不受分页影响)
|
||||
truncated: boolean; // 当前页之后是否还有更多事件(分页后前端不再据此报警)
|
||||
total_impressions: number;
|
||||
@@ -497,6 +535,8 @@ export interface DashboardOverview {
|
||||
new: number;
|
||||
active: number;
|
||||
retained_new_users: number;
|
||||
// 次日留存基数:窗口内逐日「前一日新增用户数」之和(retention_rate 的分母;旧后端无此字段)
|
||||
retention_cohort?: number;
|
||||
retention_rate: number | null;
|
||||
retention_note: string;
|
||||
};
|
||||
@@ -508,6 +548,17 @@ export interface DashboardOverview {
|
||||
average_duration_ms: number | null;
|
||||
average_saved_cents: number | null;
|
||||
};
|
||||
// 领券核心数据(2026-07-05 新增;旧后端无此字段,前端 `?.` 探测)。
|
||||
// 点位=一张券;成功口径 success+already_claimed;点位成功率分母=发起数×应领点位数(未跑到视为失败)。
|
||||
coupon?: {
|
||||
started: number;
|
||||
all_success: number; // 全部点位领成功的完成场次数
|
||||
success_rate: number | null;
|
||||
point_success: number;
|
||||
points_per_session: number | null; // 应领点位数(本期完成场点位数众数)
|
||||
point_success_rate: number | null;
|
||||
median_elapsed_ms: number | null; // 仅 completed,同「领券数据」页口径
|
||||
};
|
||||
coins: {
|
||||
granted_total: number;
|
||||
reward_video_coin_total: number;
|
||||
|
||||
Reference in New Issue
Block a user