Compare commits

..

4 Commits

Author SHA1 Message Date
OuYingJun1024 de58e69933 feat(admin-web): 主列表页改页码分页(usePagedList + antd pagination)
用户/提现/上报/审计日志四页从「加载更多」改为页码分页:
- 新增 usePagedList hook:页码→offset、暴露 total,配 antd Table pagination;
  与 useCursorList(加载更多)并存,详情子表/反馈页仍用后者
- CursorPage 类型加 total?
- 四页接入 pagination(页码/跳页/共 N 条/showSizeChanger);提现页移除自定义
  「每次加载」选择器,统一用 showSizeChanger(20/50/100)
- 反馈页本轮不动(后端反馈接口在 feat/feedback-iteration 迭代中)

tsc --noEmit 通过。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-14 15:37:38 +08:00
OuYingJun1024 a84c4570ba fix(admin-web): 用户列表列宽——手机号/昵称定宽,操作列加宽防换行
手机号/昵称原无 width,宽屏下吃满剩余空间显得失衡;操作列 fixed 230px
装不下 super_admin 的 5 个链接(详情/调金币/调现金/封禁/关调试链接)→ 换行。
- 手机号 width 130、昵称 width 150 + ellipsis(超长省略)
- 操作列 230→300 + Space wrap={false},5 链接稳定一行
- scroll.x 1100→1160 同步

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-14 15:02:56 +08:00
OuYingJun1024 b1270481aa feat(admin-web): 反馈工单页加截图列 + 排序/筛选/批量标记处理
- 截图列:缩略图 + Image.PreviewGroup 预览,URL 走 NEXT_PUBLIC_MEDIA_BASE(本地 :8770)
- 排序:ID/时间 列头服务端排序
- 筛选:状态 + 用户ID + 内容模糊 + 提交时间范围(草稿态 + 查询/重置)
- 批量:勾选 new 态 → 批量标记处理(循环 /handle + Promise.allSettled)
- 对齐用户页交互模式;依赖 app-server list_feedbacks 新增的 sort/filter 参数

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-14 14:37:22 +08:00
OuYingJun1024 8ec2e99366 fix(admin-web): 时间渲染收口到 formatUtcTime,消灭 new Date().toLocaleString
review 发现 4 处仍用 new Date(v).toLocaleString 渲染后端 UTC 口径时间戳——
正是 lib/format.ts 头注释明令消灭的反模式(SQLite 本地/非中国浏览器会差 8h,
生产靠 +00:00 偏移侥幸正确)。统一改用 formatUtcTime 按北京显示:
- admins: last_login_at
- audit-logs: created_at
- devices: completed_at
- dashboard/HomeStatsConfig: ops_stat_config.updated_at
均为 server_default now()/datetime.now(utc) 的 UTC 口径字段。
HomeStatsConfig 的「下个更新时刻」用 epoch ms + 强制 Asia/Shanghai,正确,不动。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-14 14:21:47 +08:00
8 changed files with 285 additions and 1637 deletions
+1 -1
View File
@@ -2438,7 +2438,7 @@
},
"node_modules/@next/swc-win32-x64-msvc": {
"version": "15.5.19",
"resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-15.5.19.tgz",
"resolved": "https://registry.npmmirror.com/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-15.5.19.tgz",
"integrity": "sha512-PhmojAHyqMne56HBLGu9dhDnHPuFmEjrXSQMM/nW0J6j849lk3ESrVtqNJcCk8CKOV7brpTTbaYAjwKPzKM69w==",
"cpu": [
"x64"
+247
View File
@@ -0,0 +1,247 @@
'use client';
import { useCallback, useEffect, useState } from 'react';
import type { ColumnsType } from 'antd/es/table';
import {
Alert,
Button,
Card,
Checkbox,
DatePicker,
InputNumber,
Select,
Space,
Table,
Tag,
Typography,
message,
} from 'antd';
import dayjs, { type Dayjs } from 'dayjs';
import { api, errMsg } from '@/lib/api';
import { formatUtcTime } from '@/lib/format';
import type { AdCoinAudit, AdCoinAuditRow } from '@/lib/types';
const SCENE_TAG: Record<string, { color: string; label: string }> = {
reward_video: { color: 'blue', label: '看视频' },
feed: { color: 'purple', label: '信息流' },
};
const STATUS_TAG: Record<string, string> = {
granted: 'green',
capped: 'orange',
ecpm_missing: 'red',
};
const fmtFactorRange = (a: number | null, b: number | null) => {
if (a == null) return '-';
return a === b || b == null ? String(a) : `${a}${b}`;
};
const fmtIndexRange = (a: number | null, b: number | null) => {
if (a == null) return '-';
return a === b ? String(a) : `${a}${b}`;
};
export default function AdAuditPage() {
const [date, setDate] = useState<Dayjs>(dayjs());
const [userId, setUserId] = useState<number | null>(null);
const [scene, setScene] = useState<string | undefined>();
const [limit, setLimit] = useState<number>(100);
const [data, setData] = useState<AdCoinAudit | null>(null);
const [queriedLimit, setQueriedLimit] = useState<number>(100); // 本次结果对应的 limit,截断提示里展示
const [onlyMismatch, setOnlyMismatch] = useState(false); // 只看不一致(✗)行
const [loading, setLoading] = useState(false);
const load = useCallback(async () => {
setLoading(true);
try {
const res = await api.get<AdCoinAudit>('/admin/api/ad-coin-audit', {
params: {
date: date.format('YYYY-MM-DD'),
user_id: userId ?? undefined,
scene: scene ?? undefined,
limit,
only_mismatch: onlyMismatch || undefined,
},
});
setData(res.data);
setQueriedLimit(limit);
} catch (e) {
message.error(errMsg(e));
} finally {
setLoading(false);
}
}, [date, userId, scene, limit, onlyMismatch]);
useEffect(() => {
load();
// 仅首次自动拉今天;之后由「查询」按钮触发
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const columns: ColumnsType<AdCoinAuditRow> = [
{
title: '场景',
dataIndex: 'scene',
width: 90,
render: (s: string) => {
const t = SCENE_TAG[s] ?? { color: 'default', label: s };
return <Tag color={t.color}>{t.label}</Tag>;
},
},
{ title: '时间', dataIndex: 'created_at', render: (v: string) => formatUtcTime(v), width: 175 },
{ title: '用户', dataIndex: 'user_id', width: 70 },
{
title: '状态',
dataIndex: 'status',
width: 110,
render: (s: string) => <Tag color={STATUS_TAG[s] ?? 'default'}>{s}</Tag>,
},
{ title: 'eCPM', dataIndex: 'ecpm', width: 90, render: (v: string | null) => v ?? '-' },
{
title: '因子1',
dataIndex: 'ecpm_factor',
width: 70,
render: (v: number | null) => v ?? '-',
},
{ title: '份数', dataIndex: 'units', width: 60 },
{
title: 'LT累计条数',
key: 'lt_index',
width: 100,
render: (_: unknown, r: AdCoinAuditRow) => fmtIndexRange(r.lt_index_start, r.lt_index_end),
},
{
title: '因子2',
key: 'lt_factor',
width: 90,
render: (_: unknown, r: AdCoinAuditRow) => fmtFactorRange(r.lt_factor_start, r.lt_factor_end),
},
{
title: '应发金币',
dataIndex: 'expected_coin',
width: 100,
render: (v: number) => <b>{v}</b>,
},
{ title: '实发金币', dataIndex: 'actual_coin', width: 100 },
{
title: '一致',
dataIndex: 'matched',
width: 70,
render: (m: boolean) =>
m ? <Tag color="green"></Tag> : <Tag color="red"> </Tag>,
},
];
return (
<div>
<h2>广</h2>
<Typography.Paragraph type="secondary" style={{ marginBottom: 16 }}>
广,,
</Typography.Paragraph>
{data && (
<Card size="small" style={{ marginBottom: 16 }}>
<Typography.Text strong>:</Typography.Text>{' '}
<Typography.Text code>{data.formula.description}</Typography.Text>
<div style={{ marginTop: 8, color: '#666', fontSize: 13 }}>
<div>
eCPM :{data.formula.ecpm_unit}, ÷100 ;金币: ={' '}
{data.formula.coin_per_yuan}:1; {data.formula.feed_unit_seconds} 1 LT累计条数
</div>
<div style={{ marginTop: 4 }}>
1( eCPM ,阈值单位:):
{data.formula.ecpm_factor_tiers
.map(([f, lo, hi]) => `${lo}~${hi ?? '∞'}元→${f}`)
.join(' | ')}
</div>
<div style={{ marginTop: 4 }}>
2(LT ):
{data.formula.lt_factor_tiers
.map(([f, lo, hi]) => `${lo}${hi != null && hi !== lo ? `~${hi}` : ''}${f}`)
.join(' | ')}
</div>
</div>
</Card>
)}
<Space style={{ marginBottom: 16 }} wrap>
<DatePicker value={date} onChange={(d) => d && setDate(d)} allowClear={false} />
<InputNumber
placeholder="用户 ID(可空)"
value={userId ?? undefined}
onChange={(v) => setUserId(v ?? null)}
style={{ width: 140 }}
/>
<Select
placeholder="场景(全部)"
value={scene}
onChange={setScene}
allowClear
style={{ width: 140 }}
options={[
{ value: 'reward_video', label: '看视频' },
{ value: 'feed', label: '信息流' },
]}
/>
<Select
value={limit}
onChange={setLimit}
style={{ width: 120 }}
options={[50, 100, 200, 500].map((n) => ({ value: n, label: `${n}` }))}
/>
<Checkbox checked={onlyMismatch} onChange={(e) => setOnlyMismatch(e.target.checked)}>
()
</Checkbox>
<Button type="primary" onClick={load} loading={loading}>
</Button>
</Space>
{data && (
<div style={{ marginBottom: 12 }}>
<Space direction="vertical" style={{ width: '100%' }}>
{data.mismatch_count > 0 ? (
<Alert
type="error"
message={`${data.total} 条,其中 ${data.mismatch_count} 条复算与实发不一致(✗)——公式可能未生效或发奖有问题`}
/>
) : (
<Alert type="success" message={`${data.total} 条,全部按公式发放(无不一致)`} />
)}
{onlyMismatch && (
<Alert
type="info"
showIcon
message={`当前只展示不一致(✗)行;上方统计仍为全量(共 ${data.total} 条)。`}
/>
)}
{data.truncated && (
<Alert
type="warning"
showIcon
message={`展示明细已截断到 ${queriedLimit} 条,还有更多未显示——请按用户/场景/日期缩小范围,或调大「条数」。统计数字不受影响。`}
/>
)}
</Space>
</div>
)}
<Table
rowKey={(r) => `${r.scene}-${r.record_id}`}
columns={columns}
dataSource={data?.items ?? []}
loading={loading}
pagination={false}
size="small"
scroll={{ x: 1100 }}
rowClassName={(r) => (r.matched ? '' : 'row-mismatch')}
/>
<style jsx global>{`
.row-mismatch > td {
background: #fff1f0 !important;
}
`}</style>
</div>
);
}
-746
View File
@@ -1,746 +0,0 @@
'use client';
import { useCallback, useEffect, useState } from 'react';
import type { ColumnsType } from 'antd/es/table';
import {
Alert,
Button,
Card,
Col,
DatePicker,
Divider,
InputNumber,
Modal,
Popover,
Row,
Select,
Space,
Statistic,
Table,
Tag,
Typography,
message,
} from 'antd';
import {
FallOutlined,
InfoCircleOutlined,
QuestionCircleOutlined,
RiseOutlined,
} from '@ant-design/icons';
import dayjs, { type Dayjs } from 'dayjs';
import { api, errMsg } from '@/lib/api';
import { formatUtcTime } from '@/lib/format';
import type {
AdRevenueDaily,
AdRevenueImpression,
AdRevenueRecord,
AdRevenueReport,
AdRevenueRow,
} from '@/lib/types';
const { RangePicker } = DatePicker;
// 广告类型标签
const TYPE_TAG: Record<string, { color: string; label: string }> = {
reward_video: { color: 'blue', label: '激励视频' },
feed: { color: 'purple', label: '信息流' },
draw: { color: 'geekblue', label: 'Draw 信息流' },
};
// 我们的应用环境标签
const APP_TAG: Record<string, { color: string; label: string }> = {
prod: { color: 'green', label: '傻瓜比价(正式)' },
test: { color: 'default', label: '测试应用' },
};
// 发奖状态 → 颜色 + 中文(含「不发金币的原因」:提前关闭/未满10秒/缺eCPM/次数超限)
const STATUS_TAG: Record<string, { color: string; label: string }> = {
granted: { color: 'green', label: '已发' },
capped: { color: 'orange', label: '次数超限' },
ecpm_missing: { color: 'red', label: '缺 eCPM' },
too_short: { color: 'gold', label: '未满10秒' },
closed_early: { color: 'default', label: '提前关闭' },
};
const fmtFactorRange = (a: number | null, b: number | null) => {
if (a == null) return '-';
return a === b || b == null ? String(a) : `${a}${b}`;
};
const fmtIndexRange = (a: number | null, b: number | null) => {
if (a == null) return '-';
return a === b ? String(a) : `${a}${b}`;
};
// 金币计算公式(写死,展示用)——与后端 app/core/rewards.py 同源,改动以后端常量为准。
// 单次奖励(元) = (eCPM元 ÷ 1000) × 因子1(eCPM 元档) × 因子2(LT 累计条数);1 元 = 10000 金币,四舍五入取整。
const COIN_PER_YUAN = 10000;
// 因子1:按 eCPM(元/千次)判档,对应 AD_ECPM_FACTOR_TABLE
const ECPM_FACTOR_ROWS = [
{ key: '4', range: '> 400', factor: 0.6 },
{ key: '3', range: '201 400', factor: 0.4 },
{ key: '2', range: '101 200', factor: 0.3 },
{ key: '1', range: '0 100', factor: 0.1 },
];
// 因子2:按该账号累计第几条/份(不按天重置),对应 AD_LT_FACTOR_TABLE
const LT_FACTOR_ROWS = [
{ key: '1', lt: '第 1 条', factor: 2.0 },
{ key: '2', lt: '第 2 条', factor: 1.5 },
{ key: '3', lt: '第 3 条', factor: 1.3 },
{ key: '4', lt: '4 10 条', factor: 1.1 },
{ key: '5', lt: '第 11 条及以后', factor: 1.0 },
];
// 展开行 - 展示明细:每条广告展示一行(时间/eCPM/收益/adn/底层位)
const IMPRESSION_COLUMNS: ColumnsType<AdRevenueImpression> = [
{ title: '时间', dataIndex: 'created_at', render: (v: string) => formatUtcTime(v), width: 165 },
{ title: 'eCPM(分)', dataIndex: 'ecpm', width: 100 },
{ title: '预估收益(元)', dataIndex: 'revenue_yuan', width: 120, render: (v: number) => v.toFixed(4) },
{
title: 'adn',
dataIndex: 'adn',
width: 90,
render: (v: string | null) => v ?? '-',
},
{
title: '底层代码位ID',
dataIndex: 'slot_id',
render: (v: string | null) => v ?? '-',
},
];
// 展开行 - 发奖明细:该组的逐条发奖复算明细(还原原金币审计的 eCPM/因子1/份数/LT/因子2 等列)
const DETAIL_COLUMNS: ColumnsType<AdRevenueRecord> = [
{ title: '时间', dataIndex: 'created_at', render: (v: string) => formatUtcTime(v), width: 165 },
{
title: '状态',
dataIndex: 'status',
width: 110,
render: (s: string) => {
const t = STATUS_TAG[s] ?? { color: 'default', label: s };
return <Tag color={t.color}>{t.label}</Tag>;
},
},
{ title: 'eCPM(分)', dataIndex: 'ecpm', width: 90, render: (v: string | null) => v ?? '-' },
{ title: '因子1', dataIndex: 'ecpm_factor', width: 70, render: (v: number | null) => v ?? '-' },
{ title: '份数', dataIndex: 'units', width: 60 },
{
title: 'LT累计条数',
key: 'lt_index',
width: 100,
render: (_: unknown, r: AdRevenueRecord) => fmtIndexRange(r.lt_index_start, r.lt_index_end),
},
{
title: '因子2',
key: 'lt_factor',
width: 90,
render: (_: unknown, r: AdRevenueRecord) => fmtFactorRange(r.lt_factor_start, r.lt_factor_end),
},
{ 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,零依赖):柱=展示条数(左轴),线=预估收益元(右轴)。x 轴按传入点序。
const CHART_BAR = '#69b1ff';
const CHART_LINE = '#fa8c16';
interface TrendPoint {
label: string; // x 轴刻度文案(小时数 / MM-DD)
tip: string; // hover 原生 tooltip 全文
impressions: number;
revenue: number;
}
// 按小时聚合(023),数据源是 items(被 limit 截断时会偏少,调用处给警告)
function aggregateHourly(rows: AdRevenueRow[]): TrendPoint[] {
const byHour = Array.from({ length: 24 }, (_, h) => ({ hour: h, impressions: 0, revenue: 0 }));
for (const r of rows) {
if (r.hour == null || r.hour < 0 || r.hour > 23) continue;
byHour[r.hour].impressions += r.impressions;
byHour[r.hour].revenue += r.revenue_yuan;
}
return byHour.map((b) => ({
label: String(b.hour),
tip: `${String(b.hour).padStart(2, '0')}:00 展示 ${b.impressions} 条 · 预估收益 ${b.revenue.toFixed(4)}`,
impressions: b.impressions,
revenue: b.revenue,
}));
}
// 按天聚合,数据源是 daily(全量,不受 limit 影响);用 from..to 补齐空缺日为 0,轴连续
function aggregateDaily(dateFrom: string, dateTo: string, daily: AdRevenueDaily[]): 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 impressions = d?.impressions ?? 0;
const revenue = d?.revenue_yuan ?? 0;
out.push({
label: ds.slice(5),
tip: `${ds} 展示 ${impressions} 条 · 预估收益 ${revenue.toFixed(4)}`,
impressions,
revenue,
});
cur = cur.add(1, 'day');
guard += 1;
}
return out;
}
function TrendChart({ points }: { points: TrendPoint[] }) {
const n = points.length;
const maxImp = Math.max(1, ...points.map((p) => p.impressions));
const maxRev = Math.max(1e-9, ...points.map((p) => p.revenue));
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(28, step * 0.55);
const yBase = padT + plotH;
const barX = (i: number) => padL + i * step + (step - barW) / 2;
const cx = (i: number) => padL + i * step + step / 2;
const impH = (v: number) => (v / maxImp) * plotH;
const revY = (v: number) => yBase - (v / maxRev) * plotH;
const linePts = points.map((p, i) => `${cx(i)},${revY(p.revenue)}`).join(' ');
const labelEvery = Math.max(1, Math.ceil(n / 12)); // 至多 ~12 个 x 标签,避免拥挤
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}>
{Math.round(maxImp * t)}
</text>
<text x={W - padR + 8} y={y + 4} textAnchor="start" fontSize={11} fill={CHART_LINE}>
{(maxRev * t).toFixed(2)}
</text>
</g>
);
})}
{points.map((p, i) => (
<rect
key={i}
x={barX(i)}
y={yBase - impH(p.impressions)}
width={barW}
height={impH(p.impressions)}
fill={CHART_BAR}
rx={2}
>
<title>{p.tip}</title>
</rect>
))}
<polyline points={linePts} fill="none" stroke={CHART_LINE} strokeWidth={2} />
{points.map((p, i) => (
<circle key={i} cx={cx(i)} cy={revY(p.revenue)} r={2.5} fill={CHART_LINE}>
<title>{p.tip}</title>
</circle>
))}
{points.map((p, i) =>
i % labelEvery === 0 || i === n - 1 ? (
<text key={i} x={cx(i)} y={H - 14} textAnchor="middle" fontSize={11} fill="#999">
{p.label}
</text>
) : null,
)}
</svg>
);
}
// 广告数据页:单表 —— 按 用户×类型×应用×代码位 聚合,一行同时给出
// 展示条数 / 收益 / 应发金币 / 实发金币 / 是否一致(发奖对账下沉到聚合级)。
export default function AdRevenuePage() {
const [range, setRange] = useState<[Dayjs, Dayjs]>([dayjs(), dayjs()]);
const [userId, setUserId] = useState<number | null>(null);
const [adType, setAdType] = useState<string | undefined>();
const [granularity, setGranularity] = useState<'day' | 'hour'>('day');
const [limit, setLimit] = useState<number>(500);
const [queriedGranularity, setQueriedGranularity] = useState<'day' | 'hour'>('day'); // 本次结果对应的粒度,决定是否显示「小时」列
const [queriedMultiDay, setQueriedMultiDay] = useState(false); // 本次结果是否跨多天,决定显示「日期」列 + 按天/按小时图
const [data, setData] = useState<AdRevenueReport | null>(null);
const [queriedLimit, setQueriedLimit] = useState<number>(500);
const [loading, setLoading] = useState(false);
const [formulaOpen, setFormulaOpen] = useState(false);
// 当前选择是否跨多天:跨多天时「按小时」无意义,粒度强制按天
const rangeMultiDay = range[0].format('YYYY-MM-DD') !== range[1].format('YYYY-MM-DD');
const load = useCallback(async () => {
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<AdRevenueReport>('/admin/api/ad-revenue-report', {
params: {
date_from: from,
date_to: to,
user_id: userId ?? undefined,
ad_type: adType ?? undefined,
granularity: gran,
limit,
},
});
setData(res.data);
setQueriedLimit(limit);
setQueriedGranularity(gran);
setQueriedMultiDay(multiDay);
} catch (e) {
message.error(errMsg(e));
} finally {
setLoading(false);
}
}, [range, userId, adType, granularity, limit]);
useEffect(() => {
load();
// 仅首次自动拉今天;之后由「查询」按钮触发
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const columns: ColumnsType<AdRevenueRow> = [
...(queriedMultiDay
? [{ title: '日期', dataIndex: 'report_date', width: 110, fixed: 'left' } as ColumnsType<AdRevenueRow>[number]]
: []),
{ title: '用户', dataIndex: 'user_id', width: 80 },
...(queriedGranularity === 'hour'
? [
{
title: '小时',
dataIndex: 'hour',
width: 90,
render: (h: number | null) =>
h == null ? '-' : `${String(h).padStart(2, '0')}:00`,
} as ColumnsType<AdRevenueRow>[number],
]
: []),
{
title: '广告类型',
dataIndex: 'ad_type',
width: 120,
render: (s: string) => {
const t = TYPE_TAG[s] ?? { color: 'default', label: s };
return <Tag color={t.color}>{t.label}</Tag>;
},
},
{
title: '来源应用',
dataIndex: 'app_env',
width: 150,
render: (v: string | null) => {
if (!v) return <Typography.Text type="secondary"></Typography.Text>;
const t = APP_TAG[v] ?? { color: 'default', label: v };
return <Tag color={t.color}>{t.label}</Tag>;
},
},
{
title: '广告位ID',
dataIndex: 'our_code_id',
width: 120,
render: (v: string | null) =>
v ? <Typography.Text code>{v}</Typography.Text> : <Typography.Text type="secondary">-</Typography.Text>,
},
{ title: '展示条数', dataIndex: 'impressions', width: 90, align: 'right' },
{
title: '预估收益(元)',
dataIndex: 'revenue_yuan',
width: 120,
align: 'right',
render: (v: number) => v.toFixed(4),
},
{
title: '应发金币',
dataIndex: 'expected_coin',
width: 100,
align: 'right',
render: (v: number) => <b>{v}</b>,
},
{ title: '实发金币', dataIndex: 'actual_coin', width: 100, align: 'right' },
{
title: '一致',
dataIndex: 'matched',
width: 80,
align: 'center',
render: (m: boolean) => (m ? <Tag color="green"></Tag> : <Tag color="red"> </Tag>),
},
{
title: '底层 ADN',
dataIndex: 'adns',
render: (v: string[]) =>
v.length ? v.map((a) => <Tag key={a}>{a}</Tag>) : <Typography.Text type="secondary">-</Typography.Text>,
},
];
// 派生指标(全部基于全量 total_* 字段,不受 limit 截断影响,准):
// 平均 eCPM = 收益÷展示×1000;发奖成本(元)= 实发金币÷汇率;预估毛利 = 收益−发奖成本;
// 发奖占收益比 = 发奖成本÷收益;应发实发差额(金币)= 应发−实发(正=少发/负=多发)。
const derived = data
? {
avgEcpm: data.total_impressions
? (data.total_revenue_yuan / data.total_impressions) * 1000
: 0,
payoutYuan: data.total_actual_coin / COIN_PER_YUAN,
grossProfit: data.total_revenue_yuan - data.total_actual_coin / COIN_PER_YUAN,
payoutRatioPct:
data.total_revenue_yuan > 0
? (data.total_actual_coin / COIN_PER_YUAN / data.total_revenue_yuan) * 100
: null,
coinGap: data.total_expected_coin - data.total_actual_coin,
}
: null;
return (
<div>
<Space align="center" style={{ display: 'flex', marginBottom: 16 }}>
<h2 style={{ margin: 0 }}>广</h2>
<Button
type="link"
size="small"
icon={<QuestionCircleOutlined />}
onClick={() => setFormulaOpen(true)}
>
</Button>
<Popover
placement="bottomLeft"
title="收益口径说明"
content={
<div style={{ maxWidth: 360, fontSize: 13, lineHeight: 1.7 }}>
广(onAdShow) eCPM ( ÷1000
),<b>广</b>;穿/,,
<b>穿</b> 0广ID / ,
</div>
}
>
<Button type="link" size="small" icon={<InfoCircleOutlined />}>
</Button>
</Popover>
</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>
<InputNumber
placeholder="可空"
value={userId ?? undefined}
onChange={(v) => setUserId(v ?? null)}
style={{ width: 130 }}
/>
</Space>
<Space size={6}>
<Typography.Text type="secondary"></Typography.Text>
<Select
placeholder="全部"
value={adType}
onChange={setAdType}
allowClear
style={{ width: 150 }}
options={[
{ value: 'reward_video', label: '激励视频' },
{ value: 'feed', label: '信息流' },
{ value: 'draw', label: 'Draw 信息流' },
]}
/>
</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={limit}
onChange={setLimit}
style={{ width: 110 }}
options={[100, 200, 500, 1000].map((n) => ({ value: n, label: `${n}` }))}
/>
</Space>
<Button type="primary" onClick={load} loading={loading}>
</Button>
</Space>
</Card>
{data && derived && (
<Card size="small" style={{ marginBottom: 16 }}>
<Divider orientation="left" plain style={{ marginTop: 0, marginBottom: 16 }}>
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
广
</Typography.Text>
</Divider>
<Row gutter={[16, 12]}>
<Col span={6}>
<Statistic title="展示条数合计" value={data.total_impressions} />
</Col>
<Col span={6}>
<Statistic title="平均 eCPM(元/千次)" value={derived.avgEcpm} precision={2} />
</Col>
<Col span={6}>
<Statistic title="预估收益合计(元)" value={data.total_revenue_yuan} precision={4} />
</Col>
<Col span={6}>
<Statistic title="聚合组数" value={data.total} />
</Col>
</Row>
<Divider orientation="left" plain style={{ marginTop: 20, marginBottom: 16 }}>
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
</Typography.Text>
</Divider>
<Row gutter={[16, 12]}>
<Col span={6}>
<Statistic title="应发金币合计" value={data.total_expected_coin} />
</Col>
<Col span={6}>
<Statistic title="实发金币合计" value={data.total_actual_coin} />
</Col>
<Col span={6}>
<Statistic title="发奖成本(元)" value={derived.payoutYuan} precision={4} />
</Col>
<Col span={6}>
<Statistic
title="预估毛利(元)"
value={derived.grossProfit}
precision={4}
prefix={derived.grossProfit >= 0 ? <RiseOutlined /> : <FallOutlined />}
valueStyle={{ color: derived.grossProfit >= 0 ? '#3f8600' : '#cf1322' }}
/>
<Typography.Text type="secondary" style={{ fontSize: 12 }}>
{' '}
{derived.payoutRatioPct == null ? '—' : `${derived.payoutRatioPct.toFixed(0)}%`}
</Typography.Text>
</Col>
</Row>
</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} 组,应发与实发全部一致。`} />
)}
{data.truncated && (
<Alert
type="warning"
showIcon
message={`聚合明细已截断到 ${queriedLimit} 组,还有更多未显示——请按用户/类型/日期缩小范围,或调大「组数」。合计数字不受影响。`}
/>
)}
</Space>
)}
{data &&
(queriedMultiDay
? (data.daily?.length ?? 0) > 0
: queriedGranularity === 'hour' && (data.items?.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,
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>
}
>
{/* 按小时图由 items 聚合,会被 limit 截断;按天图用 daily(全量)不受影响,故只在按小时时警告 */}
{!queriedMultiDay && data.truncated && (
<Alert
type="warning"
showIcon
style={{ marginBottom: 12 }}
message={`图表按小时聚合的是已截断到 ${queriedLimit} 组的明细,可能少算——调大「条数」或缩小筛选可还原真实趋势。`}
/>
)}
{queriedMultiDay ? (
<TrendChart points={aggregateDaily(data.date_from, data.date_to, data.daily)} />
) : (
<TrendChart points={aggregateHourly(data.items)} />
)}
</Card>
)}
<Table
rowKey={(r) => `${r.report_date}-${r.user_id}-${r.ad_type}-${r.app_env ?? ''}-${r.our_code_id ?? ''}-${r.hour ?? ''}`}
columns={columns}
dataSource={data?.items ?? []}
loading={loading}
pagination={false}
size="small"
scroll={{ x: 1100 }}
rowClassName={(r) => (r.matched ? '' : 'row-mismatch')}
expandable={{
rowExpandable: (r) =>
(r.impression_records?.length ?? 0) > 0 || (r.records?.length ?? 0) > 0,
expandedRowRender: (r) => {
const imps = r.impression_records ?? [];
const recs = r.records ?? [];
return (
<Space direction="vertical" size="middle" style={{ width: '100%' }}>
<div>
<Typography.Text strong></Typography.Text>{' '}
<Typography.Text type="secondary">({imps.length} )</Typography.Text>
<Table<AdRevenueImpression>
style={{ marginTop: 8 }}
rowKey="id"
columns={IMPRESSION_COLUMNS}
dataSource={imps}
pagination={false}
size="small"
scroll={{ x: 700 }}
/>
</div>
<div>
<Typography.Text strong></Typography.Text>{' '}
<Typography.Text type="secondary">({recs.length} )</Typography.Text>
<Table<AdRevenueRecord>
style={{ marginTop: 8 }}
rowKey="record_id"
columns={DETAIL_COLUMNS}
dataSource={recs}
pagination={false}
size="small"
scroll={{ x: 900 }}
rowClassName={(d) => (d.matched ? '' : 'row-mismatch')}
locale={{ emptyText: '该组无发奖记录(只有展示,未发奖)' }}
/>
</div>
</Space>
);
},
}}
/>
<Modal
title="金币计算规则"
open={formulaOpen}
onCancel={() => setFormulaOpen(false)}
footer={null}
width={680}
>
<Typography.Paragraph>
<b>()</b> eCPM<sub></sub> ÷ 1000)× <b>1</b>(eCPM )× <b>2</b>(LT )
</Typography.Paragraph>
<Typography.Paragraph type="secondary" style={{ fontSize: 13 }}>
· eCPM 穿 SDK <Typography.Text code>getEcpm()</Typography.Text> ,/, ÷100 ; ÷1000
<br />· :<b>1 {COIN_PER_YUAN.toLocaleString()} </b>,
<br />· 2LT (); 1 , 10 1
<br />· ,
</Typography.Paragraph>
<Row gutter={16}>
<Col span={12}>
<Typography.Text strong>1 · eCPM(/)</Typography.Text>
<Table
style={{ marginTop: 8 }}
size="small"
pagination={false}
dataSource={ECPM_FACTOR_ROWS}
columns={[
{ title: 'eCPM 范围(元)', dataIndex: 'range' },
{ title: '因子1', dataIndex: 'factor', width: 80 },
]}
/>
</Col>
<Col span={12}>
<Typography.Text strong>2 · LT </Typography.Text>
<Table
style={{ marginTop: 8 }}
size="small"
pagination={false}
dataSource={LT_FACTOR_ROWS}
columns={[
{ title: 'LT 累计条数', dataIndex: 'lt' },
{ title: '因子2', dataIndex: 'factor', width: 80 },
]}
/>
</Col>
</Row>
<Typography.Paragraph type="secondary" style={{ fontSize: 13, marginTop: 12, marginBottom: 0 }}>
示例:eCPM 300 / 1 0.3 × 0.4 × 2.0 0.24 2,400
</Typography.Paragraph>
</Modal>
<style jsx global>{`
.row-mismatch > td {
background: #fff1f0 !important;
}
`}</style>
</div>
);
}
-719
View File
@@ -1,719 +0,0 @@
'use client';
// CPS 优惠券分发与对账(当前仅美团)。单页 Tabs:对账统计 / 群管理 / 活动管理 / 订单明细。
// 群管理生成带 sid 的券链接 → 发群 → 对账按 sid 拉回订单/佣金归群统计。
import { useCallback, useEffect, useState } from 'react';
import type { ColumnsType } from 'antd/es/table';
import {
Button,
Card,
Form,
Input,
InputNumber,
Modal,
Select,
Space,
Statistic,
Table,
Tabs,
Tag,
Typography,
message,
} from 'antd';
import { api, errMsg } from '@/lib/api';
import { canDo } from '@/lib/auth';
import { formatUtcTime, yuan } from '@/lib/format';
import { usePagedList } from '@/lib/usePagedList';
import type {
CpsActivity,
CpsGroup,
CpsGroupStat,
CpsOrder,
CpsReconcileResult,
CpsReferralLink,
CpsStats,
} from '@/lib/types';
const MT_STATUS: Record<string, { text: string; color: string }> = {
'2': { text: '已付款', color: 'blue' },
'3': { text: '已完成', color: 'cyan' },
'4': { text: '已取消', color: 'red' },
'5': { text: '风控', color: 'orange' },
'6': { text: '已结算', color: 'green' },
};
const LINK_TYPE_NAME: Record<string, string> = {
'1': 'H5 长链',
'2': '短链(微信可发)',
'3': 'deeplink(唤起 App)',
};
const fmtRate = (r: string | null) => (r ? `${Number(r) / 100}%` : '-');
export default function CpsPage() {
return (
<div>
<h2>CPS </h2>
<Typography.Paragraph type="secondary" style={{ marginTop: -8 }}>
sid: sid , sid
()
</Typography.Paragraph>
<Tabs
defaultActiveKey="stats"
destroyInactiveTabPane
items={[
{ key: 'stats', label: '对账统计', children: <StatsTab /> },
{ key: 'groups', label: '群管理', children: <GroupsTab /> },
{ key: 'activities', label: '活动管理', children: <ActivitiesTab /> },
{ key: 'orders', label: '订单明细', children: <OrdersTab /> },
]}
/>
</div>
);
}
// ───────────── 对账统计 ─────────────
function StatsTab() {
const [days, setDays] = useState(30);
const [data, setData] = useState<CpsStats | null>(null);
const [loading, setLoading] = useState(false);
const [reconciling, setReconciling] = useState(false);
const canReconcile = canDo(['finance']);
const load = useCallback(async (d: number) => {
setLoading(true);
try {
const resp = await api.get<CpsStats>('/admin/api/cps/stats', { params: { days: d } });
setData(resp.data);
} catch (e) {
message.error(errMsg(e));
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
load(days);
}, [days, load]);
const reconcile = async () => {
setReconciling(true);
try {
const resp = await api.post<CpsReconcileResult>('/admin/api/cps/orders/reconcile', null, {
params: { days },
});
const r = resp.data;
message.success(`对账完成:拉取 ${r.fetched} 单(新增 ${r.inserted}、更新 ${r.updated})`);
load(days);
} catch (e) {
message.error(errMsg(e));
} finally {
setReconciling(false);
}
};
const columns: ColumnsType<CpsGroupStat> = [
{ title: '群', dataIndex: 'name', width: 160, ellipsis: true },
{
title: 'sid',
dataIndex: 'sid',
width: 130,
render: (v: string | null) => (v ? <Typography.Text copyable>{v}</Typography.Text> : '-'),
},
{ title: '人数', dataIndex: 'member_count', width: 70, render: (v) => v ?? '-' },
{ title: '点击', dataIndex: 'click_pv', width: 70 },
{ title: '独立访客', dataIndex: 'click_uv', width: 80 },
{ title: '有效单', dataIndex: 'order_count', width: 70 },
{
title: '取消/风控',
dataIndex: 'canceled_count',
width: 85,
render: (v: number) => (v ? <span style={{ color: '#cf1322' }}>{v}</span> : 0),
},
{
title: '点击→下单',
key: 'rate',
width: 90,
render: (_, r) =>
r.click_uv ? `${((r.order_count / r.click_uv) * 100).toFixed(0)}%` : '-',
},
{ title: '成交额', dataIndex: 'gmv_cents', width: 110, render: (v: number) => yuan(v) },
{
title: '预估佣金',
dataIndex: 'est_commission_cents',
width: 110,
sorter: (a, b) => a.est_commission_cents - b.est_commission_cents,
render: (v: number) => <b>{yuan(v)}</b>,
},
{
title: '已结算佣金',
dataIndex: 'settled_commission_cents',
width: 110,
render: (v: number) => <span style={{ color: '#3f8600' }}>{yuan(v)}</span>,
},
];
return (
<div>
<Space style={{ marginBottom: 16 }} wrap>
<span></span>
<Select
value={days}
onChange={setDays}
style={{ width: 120 }}
options={[
{ value: 7, label: '近 7 天' },
{ value: 30, label: '近 30 天' },
{ value: 90, label: '近 90 天' },
]}
/>
{canReconcile && (
<Button type="primary" loading={reconciling} onClick={reconcile}>
()
</Button>
)}
<Typography.Text type="secondary">
,
</Typography.Text>
</Space>
<Space size="large" style={{ marginBottom: 16 }} wrap>
<Card size="small">
<Statistic title="有效订单数" value={data?.total_order_count ?? 0} />
</Card>
<Card size="small">
<Statistic
title="预估佣金"
value={(data?.total_est_commission_cents ?? 0) / 100}
precision={2}
prefix="¥"
/>
</Card>
<Card size="small">
<Statistic
title="已结算佣金"
value={(data?.total_settled_commission_cents ?? 0) / 100}
precision={2}
prefix="¥"
valueStyle={{ color: '#3f8600' }}
/>
</Card>
</Space>
<Table
rowKey={(r) => r.sid ?? `gid-${r.group_id ?? 'none'}`}
columns={columns}
dataSource={data?.groups ?? []}
loading={loading}
pagination={false}
scroll={{ x: 1120 }}
/>
</div>
);
}
// ───────────── 群管理 ─────────────
function GroupsTab() {
const [keyword, setKeyword] = useState('');
const [applied, setApplied] = useState<Record<string, unknown>>({});
const { items, total, page, pageSize, loading, onChange, reload } = usePagedList<CpsGroup>(
'/admin/api/cps/groups',
applied,
);
const canManage = canDo(['operator']);
const [editing, setEditing] = useState<CpsGroup | null>(null); // null=不开,{} 新建用单独标志
const [createOpen, setCreateOpen] = useState(false);
const [linkGroup, setLinkGroup] = useState<CpsGroup | null>(null);
const columns: ColumnsType<CpsGroup> = [
{ title: 'ID', dataIndex: 'id', width: 70 },
{ title: '群名', dataIndex: 'name', width: 180, ellipsis: true },
{
title: 'sid',
dataIndex: 'sid',
width: 150,
render: (v: string) => <Typography.Text copyable>{v}</Typography.Text>,
},
{ title: '人数', dataIndex: 'member_count', width: 80, render: (v) => v ?? '-' },
{
title: '状态',
dataIndex: 'status',
width: 90,
render: (s: string) => <Tag color={s === 'active' ? 'green' : 'default'}>{s}</Tag>,
},
{ title: '备注', dataIndex: 'remark', width: 160, ellipsis: true, render: (v) => v || '-' },
{ title: '创建时间', dataIndex: 'created_at', width: 150, render: (v: string) => formatUtcTime(v) },
{
title: '操作',
key: 'op',
fixed: 'right',
width: 170,
render: (_, g) => (
<Space onClick={(e) => e.stopPropagation()}>
{canManage && <a onClick={() => setLinkGroup(g)}></a>}
{canManage && <a onClick={() => setEditing(g)}></a>}
</Space>
),
},
];
return (
<div>
<Space style={{ marginBottom: 16 }} wrap>
<Input
placeholder="群名/sid"
value={keyword}
onChange={(e) => setKeyword(e.target.value)}
onPressEnter={() => setApplied({ keyword: keyword || undefined })}
allowClear
style={{ width: 180 }}
/>
<Button type="primary" onClick={() => setApplied({ keyword: keyword || undefined })}>
</Button>
{canManage && (
<Button onClick={() => setCreateOpen(true)}></Button>
)}
</Space>
<Table
rowKey="id"
columns={columns}
dataSource={items}
loading={loading}
pagination={{
current: page,
pageSize,
total,
showSizeChanger: true,
showTotal: (t) => `${t} 个群`,
onChange,
}}
scroll={{ x: 1050 }}
/>
<GroupFormModal
open={createOpen}
group={null}
onClose={() => setCreateOpen(false)}
onDone={reload}
/>
<GroupFormModal
open={!!editing}
group={editing}
onClose={() => setEditing(null)}
onDone={reload}
/>
<ReferralLinkModal group={linkGroup} onClose={() => setLinkGroup(null)} />
</div>
);
}
function GroupFormModal({
open,
group,
onClose,
onDone,
}: {
open: boolean;
group: CpsGroup | null;
onClose: () => void;
onDone: () => void;
}) {
const [form] = Form.useForm();
const isEdit = !!group;
useEffect(() => {
if (open) {
if (group) {
form.setFieldsValue({
name: group.name,
member_count: group.member_count,
remark: group.remark,
status: group.status,
});
} else {
form.resetFields();
}
}
}, [open, group, form]);
const submit = async () => {
const v = await form.validateFields();
try {
if (isEdit && group) {
await api.patch(`/admin/api/cps/groups/${group.id}`, v);
message.success('已更新群');
} else {
await api.post('/admin/api/cps/groups', v);
message.success('已新建群');
}
onClose();
onDone();
} catch (e) {
message.error(errMsg(e));
}
};
return (
<Modal
title={isEdit ? '编辑群' : '新建群'}
open={open}
onOk={submit}
onCancel={onClose}
destroyOnHidden
>
<Form form={form} layout="vertical">
<Form.Item name="name" label="群名" rules={[{ required: true, message: '请输入群名' }]}>
<Input placeholder="如:宝妈优惠群1" />
</Form.Item>
{!isEdit && (
<Form.Item
name="sid"
label="sid(渠道标识,留空自动生成 g+ID)"
rules={[{ pattern: /^[A-Za-z0-9]+$/, message: '仅字母和数字' }]}
>
<Input placeholder="留空自动生成;或自定义如 baoma1" maxLength={64} />
</Form.Item>
)}
<Form.Item name="member_count" label="群人数(用于估算转化率)">
<InputNumber style={{ width: '100%' }} min={0} placeholder="如 200" />
</Form.Item>
{isEdit && (
<Form.Item name="status" label="状态">
<Select
options={[
{ value: 'active', label: 'active(启用)' },
{ value: 'archived', label: 'archived(归档)' },
]}
/>
</Form.Item>
)}
<Form.Item name="remark" label="备注">
<Input.TextArea rows={2} maxLength={256} />
</Form.Item>
</Form>
</Modal>
);
}
function ReferralLinkModal({ group, onClose }: { group: CpsGroup | null; onClose: () => void }) {
const [activities, setActivities] = useState<CpsActivity[]>([]);
const [activityId, setActivityId] = useState<number | undefined>();
const [result, setResult] = useState<CpsReferralLink | null>(null);
const [loading, setLoading] = useState(false);
useEffect(() => {
if (!group) {
setActivityId(undefined);
setResult(null);
return;
}
api
.get('/admin/api/cps/activities', { params: { status: 'active', limit: 100 } })
.then((r) => setActivities(r.data.items as CpsActivity[]))
.catch((e) => message.error(errMsg(e)));
}, [group]);
const generate = async () => {
if (!group || !activityId) {
message.warning('请选择活动');
return;
}
setLoading(true);
try {
const resp = await api.post<CpsReferralLink>('/admin/api/cps/referral-link', {
group_id: group.id,
activity_id: activityId,
});
setResult(resp.data);
} catch (e) {
message.error(errMsg(e));
} finally {
setLoading(false);
}
};
return (
<Modal
title={`生成券链接 - ${group?.name ?? ''}(sid=${group?.sid ?? ''})`}
open={!!group}
onCancel={onClose}
onOk={generate}
okText="生成"
confirmLoading={loading}
destroyOnHidden
width={640}
>
<Form layout="vertical">
<Form.Item label="选择活动" required>
<Select
placeholder="选要推广的活动"
value={activityId}
onChange={setActivityId}
options={activities.map((a) => ({
value: a.id,
label: `${a.name}${a.act_id ? ` (actId=${a.act_id})` : ''}`,
}))}
notFoundContent="无活动,请先到「活动管理」新建"
/>
</Form.Item>
</Form>
{result && (
<div style={{ marginTop: 8 }}>
<Typography.Text strong>👇 ( sid={result.sid},):</Typography.Text>
<div
style={{
marginTop: 8,
padding: 12,
background: '#f6ffed',
border: '1px solid #b7eb8f',
borderRadius: 6,
}}
>
<Typography.Text
copyable={{ text: result.redirect_url }}
style={{ fontSize: 15, wordBreak: 'break-all' }}
>
{result.redirect_url}
</Typography.Text>
</div>
{!result.redirect_url.startsWith('http') && (
<Typography.Text type="warning" style={{ fontSize: 12 }}>
CPS_REDIRECT_BASE,; .env
</Typography.Text>
)}
<Typography.Paragraph type="secondary" style={{ marginTop: 14, marginBottom: 4, fontSize: 12 }}>
(/,):
</Typography.Paragraph>
{Object.entries(result.link_map).map(([type, url]) => (
<div key={type} style={{ marginBottom: 4 }}>
<Tag>{LINK_TYPE_NAME[type] ?? type}</Tag>
<Typography.Text
copyable={{ text: url }}
style={{ fontSize: 12, color: '#999', wordBreak: 'break-all' }}
>
{url.length > 56 ? `${url.slice(0, 56)}` : url}
</Typography.Text>
</div>
))}
</div>
)}
</Modal>
);
}
// ───────────── 活动管理 ─────────────
function ActivitiesTab() {
const { items, total, page, pageSize, loading, onChange, reload } = usePagedList<CpsActivity>(
'/admin/api/cps/activities',
{},
);
const canManage = canDo(['operator']);
const [createOpen, setCreateOpen] = useState(false);
const columns: ColumnsType<CpsActivity> = [
{ title: 'ID', dataIndex: 'id', width: 70 },
{ title: '平台', dataIndex: 'platform', width: 90, render: (v: string) => <Tag>{v}</Tag> },
{ title: '活动名', dataIndex: 'name', width: 220, ellipsis: true },
{
title: 'actId',
dataIndex: 'act_id',
width: 120,
render: (v: string | null) => v || '-',
},
{
title: 'productViewSign',
dataIndex: 'product_view_sign',
width: 160,
ellipsis: true,
render: (v: string | null) => v || '-',
},
{
title: '状态',
dataIndex: 'status',
width: 90,
render: (s: string) => <Tag color={s === 'active' ? 'green' : 'default'}>{s}</Tag>,
},
{ title: '创建时间', dataIndex: 'created_at', width: 150, render: (v: string) => formatUtcTime(v) },
];
return (
<div>
{canManage && (
<Space style={{ marginBottom: 16 }}>
<Button type="primary" onClick={() => setCreateOpen(true)}>
</Button>
</Space>
)}
<Table
rowKey="id"
columns={columns}
dataSource={items}
loading={loading}
pagination={{
current: page,
pageSize,
total,
showSizeChanger: true,
showTotal: (t) => `${t} 个活动`,
onChange,
}}
scroll={{ x: 1000 }}
/>
<ActivityFormModal open={createOpen} onClose={() => setCreateOpen(false)} onDone={reload} />
</div>
);
}
function ActivityFormModal({
open,
onClose,
onDone,
}: {
open: boolean;
onClose: () => void;
onDone: () => void;
}) {
const [form] = Form.useForm();
useEffect(() => {
if (open) form.resetFields();
}, [open, form]);
const submit = async () => {
const v = await form.validateFields();
if (!v.act_id && !v.product_view_sign) {
message.warning('actId 与 productViewSign 至少填一个');
return;
}
try {
await api.post('/admin/api/cps/activities', v);
message.success('已新建活动');
onClose();
onDone();
} catch (e) {
message.error(errMsg(e));
}
};
return (
<Modal title="新建活动" open={open} onOk={submit} onCancel={onClose} destroyOnHidden>
<Form form={form} layout="vertical" initialValues={{ platform: 'meituan' }}>
<Form.Item name="name" label="活动名" rules={[{ required: true }]}>
<Input placeholder="如:点我领取大额红包" />
</Form.Item>
<Form.Item name="platform" label="平台">
<Select
options={[
{ value: 'meituan', label: '美团(已支持)' },
{ value: 'taobao', label: '淘宝(待接入)', disabled: true },
{ value: 'jd', label: '京东(待接入)', disabled: true },
]}
/>
</Form.Item>
<Form.Item name="act_id" label="actId(美团活动物料 ID,推荐)">
<Input placeholder="美团联盟「我要推广-活动推广」第一列 ID,如 792" maxLength={64} />
</Form.Item>
<Form.Item name="product_view_sign" label="productViewSign(商品券,与 actId 二选一)">
<Input maxLength={128} />
</Form.Item>
<Form.Item name="remark" label="备注">
<Input.TextArea rows={2} maxLength={256} />
</Form.Item>
</Form>
</Modal>
);
}
// ───────────── 订单明细 ─────────────
function OrdersTab() {
const [sid, setSid] = useState('');
const [status, setStatus] = useState<string | undefined>();
const [applied, setApplied] = useState<Record<string, unknown>>({});
const { items, total, page, pageSize, loading, onChange } = usePagedList<CpsOrder>(
'/admin/api/cps/orders',
applied,
);
const columns: ColumnsType<CpsOrder> = [
{
title: '订单号',
dataIndex: 'order_id',
width: 200,
ellipsis: true,
render: (v: string) => <Typography.Text copyable>{v}</Typography.Text>,
},
{ title: 'sid', dataIndex: 'sid', width: 120, render: (v) => v || '-' },
{ title: '商品', dataIndex: 'product_name', width: 200, ellipsis: true, render: (v) => v || '-' },
{
title: '成交额',
dataIndex: 'pay_price_cents',
width: 100,
render: (v: number | null) => (v != null ? yuan(v) : '-'),
},
{
title: '佣金',
dataIndex: 'commission_cents',
width: 90,
render: (v: number | null) => (v != null ? yuan(v) : '-'),
},
{ title: '佣金率', dataIndex: 'commission_rate', width: 80, render: fmtRate },
{
title: '状态',
dataIndex: 'mt_status',
width: 90,
render: (s: string | null) => {
const m = s ? MT_STATUS[s] : null;
return m ? <Tag color={m.color}>{m.text}</Tag> : s || '-';
},
},
{ title: '支付时间', dataIndex: 'pay_time', width: 150, render: (v) => formatUtcTime(v) },
];
const search = () => setApplied({ sid: sid || undefined, mt_status: status });
return (
<div>
<Space style={{ marginBottom: 16 }} wrap>
<Input
placeholder="sid"
value={sid}
onChange={(e) => setSid(e.target.value)}
onPressEnter={search}
allowClear
style={{ width: 150 }}
/>
<Select
placeholder="状态"
value={status}
onChange={setStatus}
allowClear
style={{ width: 120 }}
options={Object.entries(MT_STATUS).map(([v, m]) => ({ value: v, label: m.text }))}
/>
<Button type="primary" onClick={search}>
</Button>
</Space>
<Table
rowKey="id"
columns={columns}
dataSource={items}
loading={loading}
pagination={{
current: page,
pageSize,
total,
showSizeChanger: true,
showTotal: (t) => `${t}`,
onChange,
}}
scroll={{ x: 1030 }}
/>
</div>
);
}
+13 -28
View File
@@ -21,10 +21,10 @@ import 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 { useCursorList } from '@/lib/useCursorList';
import type { Feedback } from '@/lib/types';
const { Text, Paragraph } = Typography;
const { Text } = Typography;
const { RangePicker } = DatePicker;
// 截图是 app-server 的 /media 相对路径,本地由 :8770 提供(NEXT_PUBLIC_MEDIA_BASE);生产同域走 nginx 代理。
@@ -46,8 +46,10 @@ export default function FeedbacksPage() {
const filters: Record<string, unknown> = { ...applied, sort_by: sortBy, sort_order: sortOrder };
const filterKey = JSON.stringify(filters);
const { items, total, page, pageSize, loading, onChange: onPageChange, reload } =
usePagedList<Feedback>('/admin/api/feedbacks', filters);
const { items, nextCursor, loading, loadMore, reload } = useCursorList<Feedback>(
'/admin/api/feedbacks',
filters,
);
const canHandle = canDo(['operator']);
const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([]);
@@ -134,22 +136,7 @@ export default function FeedbacksPage() {
const columns: ColumnsType<Feedback> = [
{ title: 'ID', dataIndex: 'id', width: 70, sorter: true, sortOrder: sortOrderOf('id') },
{ title: '用户', dataIndex: 'user_id', width: 80 },
{
title: '内容',
dataIndex: 'content',
width: 360,
render: (v: string) =>
v ? (
<Paragraph
style={{ marginBottom: 0, whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}
ellipsis={{ rows: 3, expandable: true, symbol: '展开', tooltip: true }}
>
{v}
</Paragraph>
) : (
<Text type="secondary">-</Text>
),
},
{ title: '内容', dataIndex: 'content' },
{
title: '截图',
dataIndex: 'images',
@@ -270,16 +257,14 @@ export default function FeedbacksPage() {
columns={columns}
dataSource={items}
loading={loading}
pagination={{
current: page,
pageSize,
total,
showSizeChanger: true,
showTotal: (t) => `${t} 条反馈`,
onChange: onPageChange,
}}
pagination={false}
onChange={onTableChange}
/>
<div style={{ marginTop: 16, textAlign: 'center' }}>
<Button onClick={loadMore} disabled={!nextCursor} loading={loading}>
{nextCursor ? '加载更多' : '没有更多了'}
</Button>
</div>
</div>
);
}
+2 -4
View File
@@ -3,16 +3,15 @@
import { useEffect, useState } from 'react';
import { usePathname, useRouter } from 'next/navigation';
import {
BarChartOutlined,
DashboardOutlined,
FileSearchOutlined,
FlagOutlined,
FundProjectionScreenOutlined,
LogoutOutlined,
MessageOutlined,
MobileOutlined,
MoneyCollectOutlined,
SettingOutlined,
ShareAltOutlined,
TeamOutlined,
UserOutlined,
} from '@ant-design/icons';
@@ -29,8 +28,7 @@ const MENU = [
{ key: '/withdraws', icon: <MoneyCollectOutlined />, label: '提现管理' },
{ key: '/price-reports', icon: <FlagOutlined />, label: '上报审核' },
{ key: '/feedbacks', icon: <MessageOutlined />, label: '反馈工单' },
{ key: '/ad-revenue', icon: <BarChartOutlined />, label: '广告数据' },
{ key: '/cps', icon: <ShareAltOutlined />, label: 'CPS 分发' },
{ key: '/ad-audit', icon: <FundProjectionScreenOutlined />, label: '金币审计' },
{ key: '/config', icon: <SettingOutlined />, label: '系统配置' },
{ key: '/admins', icon: <TeamOutlined />, label: '管理员', superOnly: true },
{ key: '/audit-logs', icon: <FileSearchOutlined />, label: '审计日志' },
+1 -11
View File
@@ -12,17 +12,7 @@ export function Providers({ children }: { children: React.ReactNode }) {
return (
<AntdRegistry>
{/* wave 禁用:消除 antd 5 波纹在 Next15 dev 下的 React 版本兼容误报(纯噪音,后台不需要波纹) */}
{/* 全局主题:统一圆角到 8、页面底色用偏冷的浅灰,让白色卡片更有层次(全站生效) */}
<ConfigProvider
locale={zhCN}
wave={{ disabled: true }}
theme={{
token: {
borderRadius: 8,
colorBgLayout: '#f0f2f5',
},
}}
>
<ConfigProvider locale={zhCN} wave={{ disabled: true }}>
{children}
</ConfigProvider>
</AntdRegistry>
+21 -128
View File
@@ -188,72 +188,40 @@ export interface AuditLog {
created_at: string;
}
// 广告收益报表聚合行下钻的单条展示明细
export interface AdRevenueImpression {
id: number;
created_at: string;
ecpm: string; // 分/千次展示
revenue_yuan: number; // 本次展示预估收益(元)
adn: string | null;
slot_id: string | null; // 底层 mediation rit
}
// 广告收益报表聚合行下钻的单条发奖复算明细
export interface AdRevenueRecord {
export interface AdCoinAuditRow {
scene: string; // reward_video / feed
record_id: number;
user_id: number;
created_at: string;
status: string; // granted / capped / ecpm_missing / too_short / closed_early
status: string; // granted / capped / ecpm_missing
ecpm: string | null;
ecpm_factor: number | null; // 因子1
units: number; // 份数
ecpm_factor: number | null;
units: number;
lt_index_start: number | null;
lt_index_end: number | null;
lt_factor_start: number | null; // 因子2
lt_factor_start: number | null;
lt_factor_end: number | null;
expected_coin: number;
actual_coin: number;
matched: boolean;
}
// 广告收益报表:按日期汇总的一天(按天趋势图用;全量,不受 limit 影响)
export interface AdRevenueDaily {
date: string; // 北京时间 YYYY-MM-DD
impressions: number;
revenue_yuan: number;
expected_coin: number;
actual_coin: number;
export interface AdCoinFormula {
description: string;
coin_per_yuan: number;
ecpm_unit: string;
feed_unit_seconds: number;
ecpm_factor_tiers: [number, number, number | null][];
lt_factor_tiers: [number, number, number | null][];
}
// 广告收益报表:按 日期 × 用户 × 广告类型 × 应用 × 代码位 聚合
export interface AdRevenueRow {
report_date: string; // 该组所属日期 北京时间 YYYY-MM-DD
user_id: number;
ad_type: string; // reward_video / feed / draw
app_env: string | null; // prod(傻瓜比价) / test(测试);旧数据为空
our_code_id: string | null; // 我们配置的代码位 104xxx;旧数据为空
hour: number | null; // 北京时间小时 0–23(按小时粒度时有值;按天为 null)
impressions: number; // 展示条数(轮播每条各计一次)
revenue_yuan: number; // 收益(元),预估口径
expected_coin: number; // 应发金币(公式复算,与金币审计同源)
actual_coin: number; // 实发金币(实际入账)
matched: boolean; // 该组应发==实发
adns: string[]; // 底层填充 ADN 子渠道集合
impression_records: AdRevenueImpression[]; // 该组逐条展示明细(展开下钻)
records: AdRevenueRecord[]; // 该组逐条发奖复算明细(展开下钻)
}
export interface AdRevenueReport {
date_from: string; // 起始日 北京时间 YYYY-MM-DD
date_to: string; // 结束日 北京时间 YYYY-MM-DD(闭区间;单日时与 date_from 相同)
daily: AdRevenueDaily[]; // 按日期汇总序列(全量,供按天趋势图)
total: number; // 聚合组总数(全量,不受 limit 影响)
truncated: boolean;
total_impressions: number;
total_revenue_yuan: number;
total_expected_coin: number;
total_actual_coin: number;
mismatch_count: number; // 应发≠实发的组数
items: AdRevenueRow[];
export interface AdCoinAudit {
date: string;
formula: AdCoinFormula;
total: number; // 全量条数(不受 limit/only_mismatch 影响)
mismatch_count: number; // 全量不一致条数
truncated: boolean; // 展示集是否被 limit 截断
items: AdCoinAuditRow[];
}
export interface DashboardOverview {
@@ -303,78 +271,3 @@ export interface PriceReportSummary {
rejected: number;
total: number;
}
// ===== CPS 分发与对账 =====
export interface CpsGroup {
id: number;
sid: string; // 美团二级渠道追踪位,每群唯一
name: string;
member_count: number | null;
status: string; // active / archived
remark: string | null;
created_at: string;
}
export interface CpsActivity {
id: number;
platform: string; // meituan / taobao / jd
name: string;
act_id: string | null; // 美团活动物料 ID
product_view_sign: string | null;
status: string;
remark: string | null;
created_at: string;
}
export interface CpsOrder {
id: number;
order_id: string;
sid: string | null;
act_id: string | null;
pay_price_cents: number | null;
commission_cents: number | null;
commission_rate: string | null; // "300"=3% "10"=0.1%
mt_status: string | null; // 2付款 3完成 4取消 5风控 6结算
invalid_reason: string | null;
product_name: string | null;
pay_time: string | null;
}
export interface CpsReferralLink {
redirect_url: string; // ★ 我们的群发短链(/c/{code}),发群用这个,点击经我们统计
code: string;
sid: string;
group_name: string;
activity_name: string;
target_url: string; // 实际 302 跳转的美团短链
link_map: Record<string, string>; // 美团原始 1长链/2短链/3deeplink(参考)
}
export interface CpsReconcileResult {
fetched: number;
inserted: number;
updated: number;
pages: number;
}
export interface CpsGroupStat {
group_id: number | null; // null = 未归群的 sid
sid: string | null;
name: string;
member_count: number | null;
click_pv: number; // 点击总次数
click_uv: number; // 独立点击(ip+ua 近似去重)
order_count: number; // 有效单(不含取消/风控)
settled_count: number;
canceled_count: number;
gmv_cents: number;
est_commission_cents: number;
settled_commission_cents: number;
}
export interface CpsStats {
groups: CpsGroupStat[];
total_order_count: number;
total_est_commission_cents: number;
total_settled_commission_cents: number;
}