Compare commits

..

13 Commits

Author SHA1 Message Date
linkeyu 5c4af0d5fa 功能:新增风控监控后台页面 2026-07-25 10:21:15 +08:00
linkeyu 7ca55d0dcb 优化:明确提现审核状态与超时订单处理 (#71)
## 改动说明

- 将支付配置阻断问题改为明确、可操作的提示,技术详情默认折叠。
- 为支付配置检测和现金账本校验增加加载状态、精确时间与完成反馈。
- 账本正常时使用紧凑状态展示,异常时才显示醒目提示。
- 将“批量对账”改为“处理超时订单”,在确认弹窗中说明查单、更新状态、撤销和退款行为。
- 移除自动查单关闭提示,避免把非阻断运维状态展示成业务问题。
- 审计记录中的操作名称同步调整为“处理超时订单”。

## 验证

- `npx tsc --noEmit`
- Next.js 本地页面编译通过。
- 实际验证重新检测、重新校验和超时订单确认弹窗,浏览器控制台无错误。

## 后端配套

- WonderableAI/shaguabijia-app-server#170

---------

Co-authored-by: guke <guke@wonderable.ai>
Co-authored-by: linkeyu <798648091@qq.com>
Reviewed-on: #71
Co-authored-by: linkeyu <linkeyu@wonderable.ai>
Co-committed-by: linkeyu <linkeyu@wonderable.ai>
2026-07-24 14:51:26 +08:00
zuochenyong d29dce91fa 后台前端:新增新手引导视频配置 (#69)
配置页增加「新手引导视频」分区(GuideVideoConfig.tsx):上传 MP4、设置
生效次数、开关启停。types.ts 补齐对应类型。nginx 配置放宽该上传接口的
client_max_body_size,否则大视频在网关就被 413 挡下、到不了后端。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: guke <guke@wonderable.ai>
Co-authored-by: 左辰勇 <exinglang@gmail.com>
Reviewed-on: #69
Co-authored-by: zuochenyong <zuochenyong@wonderable.ai>
Co-committed-by: zuochenyong <zuochenyong@wonderable.ai>
2026-07-24 14:47:57 +08:00
linkeyu 2dfdc721b3 后台审核改用后端批量接口 (#67)
依赖 app-server PR #164。

## 改动
- 低价审核、用户反馈仅勾选待审核记录
- 批量操作改为单次请求后端 `/bulk/approve` 或 `/bulk/reject`
- 按后端逐条结果展示成功/失败;失败项保留勾选,方便重试
- 采纳/拒绝所需的统一金币、原因、内部备注和用户回复保持原有校验与二次确认

## 验证
- `npm run build`
- `git diff --check`

---------

Co-authored-by: linkeyu <798648091@qq.com>
Reviewed-on: #67
Co-authored-by: linkeyu <linkeyu@wonderable.ai>
Co-committed-by: linkeyu <linkeyu@wonderable.ai>
2026-07-24 12:04:37 +08:00
linkeyu bce720df9e 修复:更新金币经济分类说明 (#70)
## 修改内容

- “看视频金币”提示增加历史签到膨胀奖励。
- “常规任务金币”提示移除历史签到膨胀奖励。
- 页面数值继续使用后端统一分类结果。

## 本地验证

- Next.js 生产构建通过。
- `git diff --check` 通过。

---------

Co-authored-by: linkeyu <798648091@qq.com>
Reviewed-on: #70
Co-authored-by: linkeyu <linkeyu@wonderable.ai>
Co-committed-by: linkeyu <linkeyu@wonderable.ai>
2026-07-24 11:16:44 +08:00
linkeyu 17ddf7ff1e 修复:明确领券单券成功率展示 (#68)
## 修改内容

- 将含义模糊的“百分比”列改名为“单券成功率”。
- 同时显示成功数量、有效尝试数量和百分比,例如 `7/8(87.5%)`。
- 保留点击数字查看逐张券结果明细的能力。

## 验证结果

- Next.js 生产构建通过。

---------

Co-authored-by: linkeyu <798648091@qq.com>
Reviewed-on: #68
Co-authored-by: linkeyu <linkeyu@wonderable.ai>
Co-committed-by: linkeyu <linkeyu@wonderable.ai>
2026-07-24 11:15:13 +08:00
linkeyu ecf8150cfc 修复:优化广告播放状态文案 (#65)
## 修改内容
- 广告播放状态“未满10秒”调整为“观看时长不足”
- 聚合播放状态“混合状态”调整为“部分完成”
- 保持后端状态码、接口结构和判定逻辑不变

## 影响范围
- 仅修改后台广告收益页的前端展示文案

## 验证
- npm run build

---------

Co-authored-by: linkeyu <798648091@qq.com>
Reviewed-on: #65
Co-authored-by: linkeyu <linkeyu@wonderable.ai>
Co-committed-by: linkeyu <linkeyu@wonderable.ai>
2026-07-22 18:21:39 +08:00
linkeyu 1559d4faf0 修复:激励视频未完成时预估收益显示为零 (#64)
## 问题
后台明细需要与后端有效收益口径一致:激励视频提前关闭或播放时长不足时显示 0,不能继续展示原始 eCPM 折算金额。

## 修改
- 对 reward_video + closed_early/too_short 做防御性归零显示
- 更新收益口径说明和类型注释
- 顶部合计、趋势和分类统计使用后端修正后的有效收益

## 关联后端
WonderableAI/shaguabijia-app-server#160

## 验证
- npm ci --legacy-peer-deps
- npm run build:通过(包含 TypeScript 与页面构建检查)

---------

Co-authored-by: linkeyu <798648091@qq.com>
Reviewed-on: #64
Co-authored-by: linkeyu <linkeyu@wonderable.ai>
Co-committed-by: linkeyu <linkeyu@wonderable.ai>
2026-07-22 17:38:47 +08:00
linkeyu 9d32234015 后台前端:新增“监控审计”一级目录 (#63)
## 变更
- 左侧导航新增一级目录“监控审计”。
- 将设备存活、埋点成功率、埋点日志和审计日志统一迁入该目录。
- 从“看板”移除技术监控项,并取消埋点日志、审计日志的独立一级入口。
- 保留现有页面权限过滤逻辑:无可见子项时不会展示该目录。

## 验证
- `npm run build` 通过,Next.js 编译、lint 和 TypeScript 检查均成功。

## 后端配套
- WonderableAI/shaguabijia-app-server#159

---------

Co-authored-by: linkeyu <798648091@qq.com>
Reviewed-on: #63
Co-authored-by: linkeyu <linkeyu@wonderable.ai>
Co-committed-by: linkeyu <linkeyu@wonderable.ai>
2026-07-22 17:22:23 +08:00
linkeyu a2a8451aec 修复:领券记录百分比状态配色 (#61)
## 改动
- 将领券记录表格的「点位成功率」列改名为「百分比」
- 全部点位成功的 x/x 使用与「完成」相同的绿色
- 未全部成功的 x/x 使用与「中途退出」相同的警示色
- 保留点击 x/x 查看点位明细的交互

## 验证
- 提交前已执行 git pull --rebase --autostash origin main
- npm run build

---------

Co-authored-by: linkeyu <798648091@qq.com>
Reviewed-on: #61
Co-authored-by: linkeyu <linkeyu@wonderable.ai>
Co-committed-by: linkeyu <linkeyu@wonderable.ai>
2026-07-22 13:56:22 +08:00
linkeyu 578819a284 fix(admin): 使用后端常规任务金币汇总 (#60)
## 修改

- 大盘“常规任务金币”直接使用后端 `regular_task_coin_total`
- 移除前端自行将签到、签到膨胀和任务金币相加的兜底逻辑
- 补充卡片口径说明:每日签到、历史签到膨胀、通知/其他任务、上报更低价、反馈采纳

## 验证

- `npx tsc --noEmit`:通过
- `npm run build`:通过

配套后端 PR 会将 `regular_task_coin_total` 改为明确白名单聚合。

---------

Co-authored-by: linkeyu <798648091@qq.com>
Reviewed-on: #60
Co-authored-by: linkeyu <linkeyu@wonderable.ai>
Co-committed-by: linkeyu <linkeyu@wonderable.ai>
2026-07-22 13:56:13 +08:00
linkeyu efa443ea8a 修复:拆分广告发奖状态与播放状态 (#59)
## 改动
- 将广告收益列表中的混合状态拆为「发奖状态」和「广告播放状态」两列
- 聚合行按全部子记录展示「已发 / 部分已发 / 未发」及「已完成 / 混合状态」
- 保留次数超限、缺 eCPM、未满 10 秒、提前关闭等原因的悬停说明
- 未知后端状态明确显示为「未知」,避免误判为已完成

## 验证
- npm run build

---------

Co-authored-by: linkeyu <798648091@qq.com>
Reviewed-on: #59
Co-authored-by: linkeyu <linkeyu@wonderable.ai>
Co-committed-by: linkeyu <linkeyu@wonderable.ai>
2026-07-22 12:09:54 +08:00
linkeyu f3cfd622a7 feat(admin): 领券点位分数支持查看明细 (#56)
## 变更内容
- 领券记录列表的点位成功率展示为成功数/尝试数,例如 8/8
- 点击分数弹出点位明细
- 逐条展示点位名称、ID、成功、已领、失败或跳过状态
- 失败点位额外展示失败原因
- 无逐券埋点的旧记录显示 -

## 依赖
- 依赖 app-server #153 提供 point_success_count、point_total_count 和 point_details

## 验证
- npx tsc --noEmit
- npm run build
- 本地实际验证 8/8 全部成功和 7/8 含失败原因两种状态

---------

Co-authored-by: guke <guke@wonderable.ai>
Co-authored-by: linkeyu <798648091@qq.com>
Reviewed-on: #56
Co-authored-by: linkeyu <linkeyu@wonderable.ai>
Co-committed-by: linkeyu <linkeyu@wonderable.ai>
2026-07-22 11:46:47 +08:00
14 changed files with 2153 additions and 84 deletions
+14
View File
@@ -32,6 +32,20 @@ server {
proxy_read_timeout 60s;
}
# 新手引导视频上传:视频比图片大一个量级,单独放宽到 100MB(对齐后端
# settings.GUIDE_VIDEO_MAX_BYTES)。不放宽全站上限,避免其它接口被大 body 打。
# 上传大文件耗时长,读超时同步放宽到 300s。
location = /admin/api/guide-video/video {
client_max_body_size 100m;
proxy_pass http://127.0.0.1:8771;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 300s;
proxy_send_timeout 300s;
proxy_request_buffering off;
}
# 用户上传媒体(上报截图 / 反馈截图 / 反馈二维码)由 App 后端(:8770)的 /media 托管。
# admin 页面要展示这些图,经此同域反代过去(免跨域 + 免 https 页面引 http 图被拦)。
# 前提:App 后端与本 admin 同机;若分机,把 127.0.0.1:8770 换成 App 后端可达地址。
+111 -24
View File
@@ -66,21 +66,101 @@ const APP_TAG: Record<string, { color: string; label: string }> = {
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秒' },
const REWARD_STATUS_HINT: Record<string, string> = {
granted: '已完成金币发放',
capped: '次数超限,未发金币',
ecpm_missing: '缺少有效 eCPM,未发金币',
too_short: '播放时长未达到发奖条件,未发金币',
closed_early: '用户提前关闭广告,未发金币',
};
const PLAYBACK_STATUS_TAG: Record<string, { color: string; label: string }> = {
completed: { color: 'green', label: '已完成' },
too_short: { color: 'gold', label: '观看时长不足' },
closed_early: { color: 'default', label: '提前关闭' },
unknown: { color: 'default', label: '未知' },
};
const STATUS_HINT: Record<string, string> = {
granted: '已满足当前客户端发奖条件并完成金币发放。',
too_short: '旧版 Draw 信息流观看不足 10 秒,不发金币;新版按观看比例发放时会记为已发。',
closed_early: '用户在达到发奖条件前主动关闭,不发金币。',
capped: '已达到次数上限,不再发金币。',
ecpm_missing: '缺少有效 eCPM,无法计算金币。',
};
const ZERO_REVENUE_REWARD_VIDEO_STATUSES = new Set(['closed_early', 'too_short']);
function rewardStatuses(row: AdRevenueRow): string[] {
if (row.sub_rewards?.length) return row.sub_rewards.map((reward) => reward.status);
return row.status ? [row.status] : [];
}
function effectiveRevenueYuan(row: AdRevenueRow): number {
if (
row.ad_type === 'reward_video'
&& rewardStatuses(row).some((status) => ZERO_REVENUE_REWARD_VIDEO_STATUSES.has(status))
) {
return 0;
}
return row.row_revenue_yuan ?? row.revenue_yuan;
}
function rewardStatusTag(row: AdRevenueRow) {
const statuses = rewardStatuses(row);
if (!row.has_reward || statuses.length === 0) {
return { color: 'default', label: '无记录', hint: '仅记录到广告展示,没有对应发奖记录。' };
}
const grantedCount = statuses.filter((status) => status === 'granted').length;
const reasonSummary = Object.entries(
statuses
.filter((status) => status !== 'granted')
.reduce<Record<string, number>>((counts, status) => {
counts[status] = (counts[status] ?? 0) + 1;
return counts;
}, {}),
)
.map(([status, count]) => `${REWARD_STATUS_HINT[status] ?? status} ${count}`)
.join('');
if (grantedCount === statuses.length) {
return { color: 'green', label: '已发', hint: `已完成金币发放${statuses.length > 1 ? ` ${statuses.length}` : ''}` };
}
if (grantedCount > 0) {
return {
color: 'blue',
label: '部分已发',
hint: `已发 ${grantedCount} 条,未发 ${statuses.length - grantedCount}${reasonSummary ? `${reasonSummary}` : ''}`,
};
}
return { color: 'default', label: '未发', hint: reasonSummary ? `${reasonSummary}` : '未发放金币。' };
}
function playbackStatusTag(row: AdRevenueRow) {
const statuses = rewardStatuses(row);
if (statuses.length === 0) {
return row.has_impression
? { color: 'blue', label: '仅展示', hint: '记录到广告展示,但没有对应的播放结果。' }
: { color: 'default', label: '无记录', hint: '没有可用的广告播放记录。' };
}
const playbackCounts = statuses.reduce<Record<string, number>>((counts, status) => {
const playbackStatus =
status === 'too_short' || status === 'closed_early'
? status
: status === 'granted' || status === 'capped' || status === 'ecpm_missing'
? 'completed'
: 'unknown';
counts[playbackStatus] = (counts[playbackStatus] ?? 0) + 1;
return counts;
}, {});
const entries = Object.entries(playbackCounts);
if (entries.length === 1) {
const [status, count] = entries[0];
const tag = PLAYBACK_STATUS_TAG[status];
return {
...tag,
hint: `${tag.label}${count > 1 ? ` ${count}` : ''}`,
};
}
const hint = entries
.map(([status, count]) => `${PLAYBACK_STATUS_TAG[status].label} ${count}`)
.join('');
return { color: 'purple', label: '部分完成', hint: `${hint}` };
}
const fmtFactorRange = (a: number | null, b: number | null) => {
if (a == null) return '-';
@@ -478,19 +558,25 @@ export default function AdRevenueReportPage() {
width: 110,
align: 'right',
// 一次比价/领券聚合行用 row_revenue_yuan(该次发奖广告 eCPM 折算之和),其它行用展示侧 revenue_yuan
render: (v: number, r: AdRevenueRow) => {
const rev = r.row_revenue_yuan ?? v;
return rev.toFixed(4);
},
// 激励视频提前关闭/时长不足时防御性显示 0,与后端有效收益口径一致。
render: (_v: number, r: AdRevenueRow) => effectiveRevenueYuan(r).toFixed(4),
},
{
title: '发奖状态',
dataIndex: 'status',
key: 'reward_status',
width: 100,
render: (s: string | null) => {
if (!s) return <Tooltip title="仅记录广告展示,没有对应发奖事件。"><Tag></Tag></Tooltip>;
const t = STATUS_TAG[s] ?? { color: 'default', label: s };
return <Tooltip title={STATUS_HINT[s]}><Tag color={t.color}>{t.label}</Tag></Tooltip>;
render: (_: unknown, row: AdRevenueRow) => {
const tag = rewardStatusTag(row);
return <Tooltip title={tag.hint}><Tag color={tag.color}>{tag.label}</Tag></Tooltip>;
},
},
{
title: '广告播放状态',
key: 'playback_status',
width: 120,
render: (_: unknown, row: AdRevenueRow) => {
const tag = playbackStatusTag(row);
return <Tooltip title={tag.hint}><Tag color={tag.color}>{tag.label}</Tag></Tooltip>;
},
},
{
@@ -532,7 +618,8 @@ export default function AdRevenueReportPage() {
'ecpm_yuan',
'revenue_yuan',
'actual_coin',
'status',
'reward_status',
'playback_status',
'ad_type',
'app_env',
'our_code_id',
@@ -618,7 +705,7 @@ export default function AdRevenueReportPage() {
<br />
<br />
广(onAdShow) eCPM ( ÷1000
),<b>广</b>;穿/,,
);<b> 0 </b>, eCPM 穿,
<b>穿</b> 0广ID / ,
<br />
<br />
+222
View File
@@ -0,0 +1,222 @@
'use client';
import { useEffect, useState } from 'react';
import { Button, Card, Space, Spin, Switch, Tag, Typography, Upload, message } from 'antd';
import { DeleteOutlined, UploadOutlined } from '@ant-design/icons';
import { api, errMsg } from '@/lib/api';
import { canDo } from '@/lib/auth';
import { mediaUrl } from '@/lib/media';
import type { GuideVideoConfig as GuideCfg } from '@/lib/types';
const { Text } = Typography;
/** 后端 media.save_guide_video 只认 MP4 魔数;这里先在浏览器挡一道,省得白传 100MB。 */
const MAX_BYTES = 100 * 1024 * 1024;
/**
* 领券等候浮层的「新手引导视频」配置。
*
* 用户点首页「一键自动领取」→ 出等候浮层,浮层下方那块位置**前 3 次**放这支引导视频
* (而不是广告),每次固定发 120 金币;播完若浮层还开着,自动接着放广告(原逻辑)。
* 「系统配置 → 领券引导视频」tab 的一个区块。
*
* 后台只管两件事:**开关** 和 **换片**。次数(3)/ 金币(120)走服务端默认值,产品已拍板不再
* 开放配置,所以这里不渲染输入框、PATCH 也不带这两个字段(后端仍保留字段与默认值)。
*/
export default function GuideVideoConfig() {
const [cfg, setCfg] = useState<GuideCfg | null>(null);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [uploading, setUploading] = useState(false);
// 本地编辑态,保存时一次性 PATCH
const [enabled, setEnabled] = useState(true);
const canEdit = canDo(['operator']);
const sync = (c: GuideCfg) => {
setCfg(c);
setEnabled(c.enabled);
};
const load = async () => {
setLoading(true);
try {
const { data } = await api.get<GuideCfg>('/admin/api/guide-video');
sync(data);
} finally {
setLoading(false);
}
};
useEffect(() => {
load();
}, []);
const save = async () => {
setSaving(true);
try {
const { data } = await api.patch<GuideCfg>('/admin/api/guide-video', { enabled });
sync(data);
message.success('已保存,用户下一次进入领券浮层即生效');
} catch (e) {
message.error(errMsg(e));
} finally {
setSaving(false);
}
};
// antd Upload:beforeUpload 里自行 POST(multipart),返回 false 阻止其默认上传。
const beforeUpload = (file: File) => {
// 有些系统给 .mp4 的 type 是空串,不能只看 type,再兜一层扩展名。
const looksMp4 = file.type === 'video/mp4' || /\.mp4$/i.test(file.name);
if (!looksMp4) {
message.error('仅支持 MP4 视频(H.264 编码)');
return Upload.LIST_IGNORE;
}
if (file.size > MAX_BYTES) {
message.error('视频不能超过 100MB');
return Upload.LIST_IGNORE;
}
void uploadVideo(file);
return false;
};
const uploadVideo = async (file: File) => {
const form = new FormData();
form.append('file', file);
setUploading(true);
try {
const { data } = await api.post<GuideCfg>('/admin/api/guide-video/video', form);
sync(data);
message.success('引导视频已更新,用户下一次进入领券浮层即生效');
} catch (e) {
message.error(errMsg(e));
} finally {
setUploading(false);
}
};
const removeVideo = async () => {
setUploading(true);
try {
const { data } = await api.delete<GuideCfg>('/admin/api/guide-video/video');
sync(data);
message.success('已移除引导视频,领券浮层恢复为只放广告');
} catch (e) {
message.error(errMsg(e));
} finally {
setUploading(false);
}
};
return (
<Card
size="small"
title="领券引导视频(App 领券等候浮层,前 3 次替代广告)"
style={{ marginBottom: 16 }}
extra={
cfg?.updated_at ? (
<Text type="secondary" style={{ fontSize: 12 }}>
{new Date(cfg.updated_at).toLocaleString('zh-CN')}
</Text>
) : null
}
>
<p style={{ color: '#999', marginTop: 0 }}>
广<b> 3 </b>
<b></b> <b>120 </b>广
<b></b><b></b>
<b></b><b></b>
</p>
{loading || !cfg ? (
<Spin style={{ display: 'block', margin: '24px 0' }} />
) : (
<Space align="start" size={32} wrap>
{/* 左:视频预览 */}
<div>
<Text type="secondary" style={{ fontSize: 12 }}>
</Text>
<div style={{ marginTop: 8, width: 240 }}>
{cfg.video_url ? (
// eslint-disable-next-line jsx-a11y/media-has-caption
<video
src={mediaUrl(cfg.video_url)}
controls
style={{
width: 240,
maxHeight: 420,
borderRadius: 12,
background: '#000',
border: '1px solid #f0f0f0',
}}
/>
) : (
<div
style={{
width: 240,
height: 320,
borderRadius: 12,
border: '1px dashed #d9d9d9',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
color: '#bbb',
fontSize: 13,
textAlign: 'center',
padding: 16,
}}
>
<br />
广
</div>
)}
</div>
{!enabled && cfg.video_url && (
<div style={{ color: '#fa8c16', fontSize: 12, marginTop: 6 }}>
广
</div>
)}
</div>
{/* 右:编辑控件 */}
<Space direction="vertical" size="middle" style={{ minWidth: 360 }}>
<Space>
<span></span>
<Switch checked={enabled} disabled={!canEdit} onChange={setEnabled} />
{!enabled && <Tag color="orange"></Tag>}
</Space>
<Space wrap>
<Upload accept="video/mp4,.mp4" showUploadList={false} beforeUpload={beforeUpload} disabled={!canEdit}>
<Button icon={<UploadOutlined />} loading={uploading} disabled={!canEdit}>
{cfg.video_url ? '更换视频' : '上传视频'}
</Button>
</Upload>
{cfg.video_url && (
<Button
icon={<DeleteOutlined />}
danger
loading={uploading}
disabled={!canEdit}
onClick={removeVideo}
>
</Button>
)}
<Text type="secondary" style={{ fontSize: 12 }}>
MP4H.264100MB
</Text>
</Space>
<Button type="primary" loading={saving} disabled={!canEdit} onClick={save}>
</Button>
{!canEdit && <Text type="secondary"> operator / super_admin </Text>}
</Space>
</Space>
)}
</Card>
);
}
+2
View File
@@ -6,6 +6,7 @@ import { api, errMsg } from '@/lib/api';
import HomeMarqueeSeeds from './HomeMarqueeSeeds';
import HomeStatsConfig from './HomeStatsConfig';
import FeedbackQrConfig from './FeedbackQrConfig';
import GuideVideoConfig from './GuideVideoConfig';
interface ConfigItem {
key: string;
@@ -164,6 +165,7 @@ export default function ConfigPage() {
},
{ key: 'welfare', label: '福利页', children: welfareConfig },
{ key: 'feedback-qr', label: '反馈二维码', children: <FeedbackQrConfig /> },
{ key: 'guide-video', label: '领券引导视频', children: <GuideVideoConfig /> },
]}
/>
</div>
+116 -13
View File
@@ -10,9 +10,11 @@ import {
DatePicker,
Divider,
Input,
Popover,
Row,
Select,
Space,
Spin,
Statistic,
Table,
Tag,
@@ -72,9 +74,23 @@ interface CouponDataRow {
app_env: string | null;
started_at: string;
claimed_count: number | null;
point_success_count: number | null;
point_total_count: number | null;
// 兼容旧后端的内嵌明细;新后端不再返回,改为点击后按 trace 加载。
point_details?: CouponPointDetail[];
trace_url: string | null;
ad_revenue_yuan: number | null; // 本次领券看的信息流广告预估收益(元);未填充为 null
}
interface CouponPointDetail {
coupon_id: string;
coupon_name: string | null;
status: string;
reason: string | null;
}
interface CouponPointDetailsOut {
trace_id: string;
items: CouponPointDetail[];
}
interface CouponDataReport {
date_from: string;
date_to: string;
@@ -116,6 +132,103 @@ const STATUS_TAG: Record<string, { color: string; label: string }> = {
abandoned: { color: 'orange', label: '中途退出' },
};
const POINT_STATUS_TAG: Record<string, { color: string; label: string }> = {
success: { color: 'success', label: '成功' },
already_claimed: { color: 'processing', label: '已领' },
failed: { color: 'error', label: '失败' },
skipped: { color: 'default', label: '跳过' },
};
function PointScorePopover({ row }: { row: CouponDataRow }) {
const { message } = App.useApp();
const [details, setDetails] = useState<CouponPointDetail[] | null>(row.point_details ?? null);
const [loading, setLoading] = useState(false);
const [loadError, setLoadError] = useState<string | null>(null);
if (row.point_success_count == null || row.point_total_count == null || row.point_total_count <= 0) {
return <Typography.Text type="secondary">-</Typography.Text>;
}
const score = `${row.point_success_count}/${row.point_total_count}`;
const scoreWithRate = `${score}${(
row.point_success_count / row.point_total_count * 100
).toFixed(1)}%`;
const scoreColor =
row.point_success_count === row.point_total_count
? STATUS_TAG.completed.color
: STATUS_TAG.abandoned.color;
const loadDetails = async () => {
if (details !== null || loading) return;
setLoading(true);
setLoadError(null);
try {
const response = await api.get<CouponPointDetailsOut>('/admin/api/coupon-data/point-details', {
params: { trace_id: row.trace_id },
});
setDetails(response.data.items);
} catch (error) {
const errorMessage = errMsg(error);
setLoadError(errorMessage);
message.error(errorMessage);
} finally {
setLoading(false);
}
};
return (
<Popover
trigger="click"
placement="bottomLeft"
title={`点位明细(${score}`}
onOpenChange={(open) => {
if (open) void loadDetails();
}}
content={(
<div style={{ width: 380, maxHeight: 360, overflowY: 'auto' }}>
{loading || (details === null && loadError === null) ? (
<Spin size="small" style={{ display: 'block', margin: '24px auto' }} />
) : loadError ? (
<Typography.Text type="danger"></Typography.Text>
) : details && details.length > 0 ? details.map((point, index) => {
const status = POINT_STATUS_TAG[point.status] ?? {
color: 'default', label: point.status,
};
return (
<div
key={`${point.coupon_id}-${index}`}
style={{
padding: '8px 0',
borderBottom: index < details.length - 1 ? '1px solid #f0f0f0' : undefined,
}}
>
<div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
<div style={{ flex: 1, minWidth: 0 }}>
<Typography.Text>{point.coupon_name || point.coupon_id}</Typography.Text>
{point.coupon_name ? (
<div><Typography.Text type="secondary">{point.coupon_id}</Typography.Text></div>
) : null}
</div>
<Tag color={status.color} style={{ marginInlineEnd: 0 }}>{status.label}</Tag>
</div>
{point.reason ? (
<div style={{ marginTop: 4 }}>
<Typography.Text type="danger">{point.reason}</Typography.Text>
</div>
) : null}
</div>
);
}) : (
<Typography.Text type="secondary"></Typography.Text>
)}
</div>
)}
>
<Button type="link" size="small" style={{ height: 'auto', padding: 0, color: scoreColor }}>
{scoreWithRate}
</Button>
</Popover>
);
}
// ms → "1.5s"(空值显示 -)
const fmtSec = (ms: number | null | undefined): string =>
ms == null ? '-' : `${(ms / 1000).toFixed(1)}s`;
@@ -492,20 +605,10 @@ export default function CouponDataPage() {
render: (v: number | null) => fmtSec(v),
},
{
title: '点位成功率',
title: '单券成功率',
key: 'point_success_rate',
width: 110,
render: (_: unknown, r: CouponDataRow) => (
<Tooltip title="当前接口未返回本场应领点位及逐点结果,前端不使用全局均值冒充本场成功率。">
{r.trace_url ? (
<a href={r.trace_url} target="_blank" rel="noreferrer">
</a>
) : (
<Typography.Text type="secondary"></Typography.Text>
)}
</Tooltip>
),
width: 150,
render: (_: unknown, r: CouponDataRow) => <PointScorePopover row={r} />,
},
{
title: '广告收益',
+2 -2
View File
@@ -1065,14 +1065,14 @@ export default function DashboardPage() {
value={fmtInt(periodData?.coins.reward_video_coin_total)}
delta={rewardVideoCoinRatio.value}
deltaTone={rewardVideoCoinRatio.tone}
hint="独立统计看视频发放,不再重复计入领券奖励。"
hint="普通看视频与历史签到膨胀的实发金币之和,不再重复计入领券奖励或常规任务。"
/>
<StatCard
title="常规任务金币"
value={fmtInt(regularTaskCoinTotal)}
delta={regularTaskCoinRatio.value}
deltaTone={regularTaskCoinRatio.tone}
hint="每日签到、历史签到膨胀、通知/其他任务、上报更低价和反馈采纳的实发金币之和。"
hint="每日签到、通知/其他任务、上报更低价和反馈采纳的实发金币之和。"
/>
<StatCard
title="本期提现金额"
+202 -1
View File
@@ -4,11 +4,15 @@ import { useEffect, useState } from 'react';
import type { ColumnsType } from 'antd/es/table';
import type { SorterResult } from 'antd/es/table/interface';
import {
App,
Button,
Card,
DatePicker,
Form,
Image,
Input,
InputNumber,
Modal,
Select,
Space,
Statistic,
@@ -17,10 +21,12 @@ import {
Typography,
} from 'antd';
import type { Dayjs } from 'dayjs';
import { api } from '@/lib/api';
import { api, errMsg } from '@/lib/api';
import { canDo } from '@/lib/auth';
import { formatWallTime } from '@/lib/format';
import { refreshReviewBadge } from '@/lib/reviewBadge';
import { BULK_REVIEW_MAX, bulkFailureReasonText, failedReviewIds } from '@/lib/bulkAction';
import type { BulkReviewResult } from '@/lib/bulkAction';
import { usePagedList } from '@/lib/usePagedList';
import type { Feedback, FeedbackSummary } from '@/lib/types';
import FeedbackHandleDrawer from './FeedbackHandleDrawer';
@@ -28,6 +34,7 @@ import UserRecordsDrawer from '@/components/UserRecordsDrawer';
const { Text, Paragraph } = Typography;
const { RangePicker } = DatePicker;
const REWARD_MAX = 10000;
// 截图是 app-server 的 /media 相对路径,本地由 :8770 提供(NEXT_PUBLIC_MEDIA_BASE);生产同域走 nginx 代理。
const MEDIA_BASE = process.env.NEXT_PUBLIC_MEDIA_BASE || '';
@@ -155,6 +162,8 @@ const RECORD_COLUMNS: ColumnsType<Feedback> = [
];
export default function FeedbacksPage() {
const { message } = App.useApp();
const [bulkForm] = Form.useForm();
// 筛选草稿:点「查询」才应用(避免输入即刷新)
const [status, setStatus] = useState<string | undefined>();
const [source, setSource] = useState<string | undefined>();
@@ -171,6 +180,19 @@ export default function FeedbacksPage() {
usePagedList<Feedback>('/admin/api/feedbacks', filters);
const canReview = canDo(['operator']);
const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
const [bulkAction, setBulkAction] = useState<'approve' | 'reject' | null>(null);
const [bulkSubmitting, setBulkSubmitting] = useState(false);
const selectedFeedbacks = items.filter(
(item) => selectedRowKeys.includes(item.id) && isPending(item.status),
);
useEffect(() => {
const visiblePendingIds = new Set(
items.filter((item) => isPending(item.status)).map((item) => item.id),
);
setSelectedRowKeys((keys) => keys.filter((id) => visiblePendingIds.has(id)));
}, [items]);
const [summary, setSummary] = useState<FeedbackSummary | null>(null);
const loadSummary = async () => {
@@ -236,6 +258,61 @@ export default function FeedbacksPage() {
const sortOrderOf = (field: SortField) =>
sortBy === field ? (sortOrder === 'asc' ? 'ascend' : 'descend') : null;
const openBulkModal = (action: 'approve' | 'reject') => {
if (!selectedFeedbacks.length) return;
if (selectedFeedbacks.length > BULK_REVIEW_MAX) {
message.warning(`单次最多审核 ${BULK_REVIEW_MAX} 条反馈`);
return;
}
bulkForm.resetFields();
setBulkAction(action);
};
const submitBulkReview = async () => {
if (!bulkAction || !selectedFeedbacks.length) return;
const values = await bulkForm.validateFields();
const targets = selectedFeedbacks;
setBulkSubmitting(true);
try {
const { data } = await api.post<BulkReviewResult>(
`/admin/api/feedbacks/bulk/${bulkAction}`,
bulkAction === 'approve'
? {
ids: targets.map((item) => item.id),
reward_coins: values.reward_coins,
note: values.note?.trim() || null,
reply: values.reply?.trim() || null,
}
: {
ids: targets.map((item) => item.id),
reason: values.reason.trim(),
note: values.note?.trim() || null,
reply: values.reply?.trim() || null,
},
);
const failedIds = failedReviewIds(data);
setSelectedRowKeys(failedIds);
setBulkAction(null);
bulkForm.resetFields();
if (failedIds.length) reload();
else onPageChange(1, pageSize);
loadSummary();
refreshReviewBadge('/feedbacks');
const label = bulkAction === 'approve' ? '批量采纳' : '批量拒绝';
if (failedIds.length) {
message.warning(
`${label}完成:成功 ${data.success} 条,失败 ${failedIds.length} 条;失败项已保留勾选${bulkFailureReasonText(data)}`,
);
} else {
message.success(`${label}完成:成功 ${data.success}`);
}
} catch (e) {
message.error(errMsg(e));
} finally {
setBulkSubmitting(false);
}
};
const columns: ColumnsType<Feedback> = [
{
title: '用户ID',
@@ -411,16 +488,58 @@ export default function FeedbacksPage() {
<Button onClick={resetFilters}></Button>
</Space>
{canReview && (
<Space wrap style={{ display: 'flex', marginBottom: 12 }}>
<Text> <Text strong>{selectedFeedbacks.length}</Text> </Text>
<Button
type="primary"
disabled={!selectedFeedbacks.length || selectedFeedbacks.length > BULK_REVIEW_MAX}
onClick={() => openBulkModal('approve')}
>
</Button>
<Button
danger
disabled={!selectedFeedbacks.length || selectedFeedbacks.length > BULK_REVIEW_MAX}
onClick={() => openBulkModal('reject')}
>
</Button>
{!!selectedFeedbacks.length && (
<Button onClick={() => setSelectedRowKeys([])}></Button>
)}
</Space>
)}
<Table
rowKey="id"
columns={columns}
dataSource={items}
rowSelection={
canReview
? {
selectedRowKeys,
onChange: (keys) => {
const ids = keys as number[];
if (ids.length > BULK_REVIEW_MAX) {
message.warning(`单次最多选择 ${BULK_REVIEW_MAX} 条待审核反馈`);
}
setSelectedRowKeys(ids.slice(0, BULK_REVIEW_MAX));
},
getCheckboxProps: (record) => ({
disabled: !isPending(record.status),
name: `选择反馈 #${record.id}`,
}),
}
: undefined
}
loading={loading}
pagination={{
current: page,
pageSize,
total,
showSizeChanger: true,
pageSizeOptions: [10, 20, 50],
showTotal: (t) => `${t} 条反馈`,
onChange: onPageChange,
}}
@@ -428,6 +547,88 @@ export default function FeedbacksPage() {
scroll={{ x: 1720 }}
/>
<Modal
title={
bulkAction === 'approve'
? `批量采纳 ${selectedFeedbacks.length} 条反馈`
: `批量拒绝 ${selectedFeedbacks.length} 条反馈`
}
open={bulkAction != null}
okText={bulkAction === 'approve' ? '批量采纳并发金币' : '确认批量拒绝'}
okButtonProps={{ danger: bulkAction === 'reject' }}
confirmLoading={bulkSubmitting}
onOk={submitBulkReview}
onCancel={() => {
if (bulkSubmitting) return;
setBulkAction(null);
bulkForm.resetFields();
}}
destroyOnHidden
>
<Text type="secondary">
{selectedFeedbacks.length}
</Text>
<Form form={bulkForm} layout="vertical" preserve={false} style={{ marginTop: 16 }}>
{bulkAction === 'approve' ? (
<Form.Item
name="reward_coins"
label={`每条奖励金币(必填,1 ~ ${REWARD_MAX}`}
rules={[
{ required: true, message: '请输入每条反馈的奖励金币' },
{ type: 'number', min: 1, max: REWARD_MAX, message: `请输入 1 ~ ${REWARD_MAX}` },
]}
>
<InputNumber
min={1}
max={REWARD_MAX}
style={{ width: '100%' }}
placeholder="每条反馈发放相同金币"
/>
</Form.Item>
) : (
<Form.Item
name="reason"
label="未采纳原因(必填,用户可见)"
rules={[
{ required: true, whitespace: true, message: '请填写未采纳原因' },
{ max: 256, message: '最多 256 字' },
]}
>
<Input.TextArea
rows={3}
maxLength={256}
showCount
placeholder="同一原因将发送给全部已选用户"
/>
</Form.Item>
)}
<Form.Item
name="note"
label={
bulkAction === 'approve'
? '采纳要点 / 审核备注(选填,内部)'
: '内部备注(选填)'
}
rules={[{ max: 256, message: '最多 256 字' }]}
>
<Input.TextArea rows={2} maxLength={256} showCount />
</Form.Item>
<Form.Item
name="reply"
label="给用户的回复(选填,用户可见)"
rules={[{ max: 256, message: '最多 256 字' }]}
>
<Input.TextArea
rows={2}
maxLength={256}
showCount
placeholder="同一回复将发送给全部已选用户"
/>
</Form.Item>
</Form>
</Modal>
<FeedbackHandleDrawer
feedback={drawerFb}
open={drawerOpen}
+13 -4
View File
@@ -17,6 +17,7 @@ import {
NotificationOutlined,
ProfileOutlined,
SafetyCertificateOutlined,
SecurityScanOutlined,
SettingOutlined,
ShareAltOutlined,
TeamOutlined,
@@ -67,8 +68,6 @@ const NAV_GROUPS: NavGroup[] = [
{ key: '/comparison-records', icon: <ProfileOutlined />, label: '比价记录' },
{ key: '/coupon-data', icon: <GiftOutlined />, label: '领券记录' },
{ key: '/cps', icon: <ShareAltOutlined />, label: 'CPS收益' },
{ key: '/device-liveness', icon: <HeartOutlined />, label: '设备存活' },
{ key: '/analytics-health', icon: <LineChartOutlined />, label: '埋点成功率' },
],
},
{
@@ -92,9 +91,19 @@ const NAV_GROUPS: NavGroup[] = [
{ key: '/users', icon: <UserOutlined />, label: '用户管理' },
],
},
{
key: 'monitoring-audit',
icon: <FileSearchOutlined />,
label: '监控审计',
children: [
{ key: '/risk-monitor', icon: <SecurityScanOutlined />, label: '风控监控' },
{ key: '/device-liveness', icon: <HeartOutlined />, label: '设备存活' },
{ key: '/analytics-health', icon: <LineChartOutlined />, label: '埋点成功率' },
{ key: '/event-logs', icon: <DatabaseOutlined />, label: '埋点日志' },
{ key: '/audit-logs', icon: <FileSearchOutlined />, label: '审计日志' },
],
},
{ key: '/admins', icon: <TeamOutlined />, label: '权限管理' },
{ key: '/event-logs', icon: <DatabaseOutlined />, label: '埋点日志' },
{ key: '/audit-logs', icon: <FileSearchOutlined />, label: '审计日志' },
];
// 导航项 key(/dashboard)→ 权限页 key(dashboard),与后端 permissions.py 目录对齐
+137 -11
View File
@@ -23,6 +23,8 @@ import { api, errMsg } from '@/lib/api';
import { canDo } from '@/lib/auth';
import { mediaUrl } from '@/lib/media';
import { refreshReviewBadge } from '@/lib/reviewBadge';
import { BULK_REVIEW_MAX, bulkFailureReasonText, failedReviewIds } from '@/lib/bulkAction';
import type { BulkReviewResult } from '@/lib/bulkAction';
import { usePagedList } from '@/lib/usePagedList';
import type { PriceReport, PriceReportSummary } from '@/lib/types';
import UserRecordsDrawer from '@/components/UserRecordsDrawer';
@@ -132,7 +134,10 @@ export default function PriceReportsPage() {
const [activeStatus, setActiveStatus] = useState('pending');
const [summary, setSummary] = useState<PriceReportSummary | null>(null);
const [rejecting, setRejecting] = useState<PriceReport | null>(null);
const [bulkRejecting, setBulkRejecting] = useState<PriceReport[]>([]);
const [rejectReason, setRejectReason] = useState('');
const [rejectSubmitting, setRejectSubmitting] = useState(false);
const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
// 提交时间列服务端排序(默认按提交时间倒序,最新在前)
const [sortBy, setSortBy] = useState<SortField>('created_at');
const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc');
@@ -165,6 +170,16 @@ export default function PriceReportsPage() {
};
const canReview = canDo(['operator']);
const selectedReports = items.filter(
(item) => selectedRowKeys.includes(item.id) && item.status === 'pending',
);
useEffect(() => {
const visiblePendingIds = new Set(
items.filter((item) => item.status === 'pending').map((item) => item.id),
);
setSelectedRowKeys((keys) => keys.filter((id) => visiblePendingIds.has(id)));
}, [items]);
const loadSummary = async () => {
try {
@@ -183,6 +198,49 @@ export default function PriceReportsPage() {
loadSummary();
};
const reportBulkResult = (label: string, result: BulkReviewResult) => {
const failedIds = failedReviewIds(result);
setSelectedRowKeys(failedIds);
refreshReviewBadge('/price-reports');
loadSummary();
if (failedIds.length) reload();
else onPageChange(1, pageSize);
if (failedIds.length) {
message.warning(
`${label}完成:成功 ${result.success} 条,失败 ${failedIds.length} 条;失败项已保留勾选${bulkFailureReasonText(result)}`,
);
} else {
message.success(`${label}完成:成功 ${result.success}`);
}
};
const bulkApprove = () => {
const targets = selectedReports;
if (!targets.length) return;
if (targets.length > BULK_REVIEW_MAX) {
message.warning(`单次最多审核 ${BULK_REVIEW_MAX} 条记录`);
return;
}
modal.confirm({
title: `确认批量通过 ${targets.length} 条低价上报?`,
icon: <CheckCircleOutlined style={{ color: '#52c41a' }} />,
content: `通过后将向每位用户发放 1000 金币,共发放 ${targets.length * 1000} 金币。请确认已逐条核实截图。`,
okText: '批量通过并发金币',
onOk: async () => {
try {
const { data } = await api.post<BulkReviewResult>(
'/admin/api/price-reports/bulk/approve',
{ ids: targets.map((item) => item.id) },
);
reportBulkResult('批量通过', data);
} catch (e) {
message.error(errMsg(e));
throw e;
}
},
});
};
const approve = (r: PriceReport) => {
modal.confirm({
title: '确认通过该上报?',
@@ -214,21 +272,38 @@ export default function PriceReportsPage() {
};
const confirmReject = async () => {
if (!rejecting) return;
const targets = bulkRejecting.length ? bulkRejecting : rejecting ? [rejecting] : [];
if (!targets.length) return;
if (targets.length > BULK_REVIEW_MAX) {
message.warning(`单次最多审核 ${BULK_REVIEW_MAX} 条记录`);
return;
}
const reason = rejectReason.trim();
if (!reason) {
message.warning('请填写拒绝理由');
return;
}
setRejectSubmitting(true);
try {
await api.post(`/admin/api/price-reports/${rejecting.id}/reject`, { reason });
refreshReviewBadge('/price-reports');
message.success('已拒绝');
if (bulkRejecting.length) {
const { data } = await api.post<BulkReviewResult>(
'/admin/api/price-reports/bulk/reject',
{ ids: targets.map((item) => item.id), reason },
);
reportBulkResult('批量拒绝', data);
} else {
await api.post(`/admin/api/price-reports/${targets[0].id}/reject`, { reason });
refreshReviewBadge('/price-reports');
message.success('已拒绝');
refreshAfterChange();
}
setRejecting(null);
setBulkRejecting([]);
setRejectReason('');
refreshAfterChange();
} catch (e) {
message.error(errMsg(e));
} finally {
setRejectSubmitting(false);
}
};
@@ -393,10 +468,56 @@ export default function PriceReportsPage() {
onChange={setActiveStatus}
items={STATUS_TABS.map((t) => ({ key: t.key, label: t.label }))}
/>
{canReview && (
<Space wrap style={{ marginBottom: 16 }}>
<Text> <Text strong>{selectedReports.length}</Text> </Text>
<Button
type="primary"
icon={<CheckCircleOutlined />}
disabled={!selectedReports.length || selectedReports.length > BULK_REVIEW_MAX}
onClick={bulkApprove}
>
</Button>
<Button
danger
icon={<CloseCircleOutlined />}
disabled={!selectedReports.length || selectedReports.length > BULK_REVIEW_MAX}
onClick={() => {
setRejecting(null);
setBulkRejecting(selectedReports);
setRejectReason('');
}}
>
</Button>
{!!selectedReports.length && (
<Button onClick={() => setSelectedRowKeys([])}></Button>
)}
</Space>
)}
<Table
rowKey="id"
columns={columns}
dataSource={items}
rowSelection={
canReview
? {
selectedRowKeys,
onChange: (keys) => {
const ids = keys as number[];
if (ids.length > BULK_REVIEW_MAX) {
message.warning(`单次最多选择 ${BULK_REVIEW_MAX} 条待审核记录`);
}
setSelectedRowKeys(ids.slice(0, BULK_REVIEW_MAX));
},
getCheckboxProps: (record) => ({
disabled: record.status !== 'pending',
name: `选择低价上报 #${record.id}`,
}),
}
: undefined
}
loading={loading}
onChange={onTableChange}
pagination={{
@@ -404,6 +525,7 @@ export default function PriceReportsPage() {
pageSize,
total,
showSizeChanger: true,
pageSizeOptions: [10, 20, 50],
showTotal: (t) => `${t}`,
onChange: onPageChange,
}}
@@ -412,21 +534,25 @@ export default function PriceReportsPage() {
</Card>
<Modal
title="拒绝上报"
open={!!rejecting}
title={bulkRejecting.length ? `批量拒绝 ${bulkRejecting.length} 条低价上报` : '拒绝上报'}
open={!!(rejecting || bulkRejecting.length)}
okText="确认拒绝"
confirmLoading={rejectSubmitting}
okButtonProps={{ danger: true, icon: <CloseCircleOutlined /> }}
onOk={confirmReject}
onCancel={() => {
setRejecting(null);
setBulkRejecting([]);
setRejectReason('');
}}
>
{rejecting && (
{(rejecting || bulkRejecting.length > 0) && (
<Space direction="vertical" style={{ width: '100%' }}>
<Text>
#{rejecting.user_id} · {rejecting.store_name || '-'}
</Text>
{bulkRejecting.length ? (
<Text type="secondary"> {bulkRejecting.length} </Text>
) : rejecting ? (
<Text> #{rejecting.user_id} · {rejecting.store_name || '-'}</Text>
) : null}
<Space wrap>
{REJECT_TEMPLATES.map((tpl) => (
<Button size="small" key={tpl} onClick={() => setRejectReason(tpl)}>
+323
View File
@@ -0,0 +1,323 @@
.page {
min-height: calc(100vh - 112px);
margin: -24px;
padding: 0 16px 28px;
background: #f5f5f3;
color: #171717;
}
.hero {
display: flex;
align-items: center;
justify-content: space-between;
min-height: 72px;
margin: 0 -16px 18px;
padding: 0 24px;
border-bottom: 1px solid #e8e8e6;
background: #fff;
}
.titleCluster,
.brandLine,
.updated,
.rule,
.deviceCell,
.actionGroup,
.factRow {
display: flex;
align-items: center;
}
.back {
margin-right: 18px;
color: #555;
font-size: 13px;
}
.brandMark {
display: inline-flex;
align-items: center;
justify-content: center;
width: 34px;
height: 34px;
margin-right: 12px;
border-radius: 10px;
background: #ffd400;
color: #111;
font-size: 17px;
font-weight: 800;
}
.title {
margin: 0;
font-size: 18px;
font-weight: 700;
line-height: 1.2;
}
.subtitle {
margin-top: 3px;
color: #929292;
font-size: 12px;
}
.updated {
gap: 7px;
color: #898989;
font-size: 12px;
}
.updatedMeta {
display: flex;
align-items: center;
gap: 7px;
}
.dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: #9b9b9b;
}
.summaryGrid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 14px;
margin-bottom: 16px;
}
.summaryCard {
min-height: 148px;
padding: 26px 24px 20px;
border: 1px solid #eeeeeb;
border-radius: 16px;
background: #fff;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.02);
}
.summaryTitle {
margin-bottom: 4px;
color: #111;
font-size: 14px;
font-weight: 700;
}
.summaryValue {
color: #ee3737;
font-size: 38px;
font-weight: 800;
line-height: 1.08;
font-variant-numeric: tabular-nums;
}
.summaryUnit {
margin-left: 5px;
color: #202020;
font-size: 16px;
font-weight: 600;
}
.summarySub {
margin: 8px 0 8px;
color: #969696;
font-size: 13px;
}
.rule {
width: fit-content;
padding: 4px 8px;
border: 0;
border-radius: 6px;
background: #f6f6f4;
color: #111;
cursor: pointer;
font-family: inherit;
font-size: 12px;
font-weight: 600;
transition: background 0.18s ease, box-shadow 0.18s ease;
}
.rule:hover,
.rule:focus-visible {
background: #fff3bf;
box-shadow: 0 0 0 2px rgba(255, 212, 0, 0.3);
outline: none;
}
.rule strong {
margin-left: 4px;
color: #df2727;
}
.ruleEditIcon {
margin-left: 7px;
color: #777;
font-size: 11px;
}
.ruleDialogIntro {
margin: 0 0 16px;
padding: 10px 12px;
border-radius: 8px;
background: #faf8ef;
color: #666;
font-size: 12px;
line-height: 1.7;
}
.ruleSettings {
border-top: 1px solid #f0f0ed;
}
.ruleSettingRow {
display: grid;
grid-template-columns: minmax(0, 1fr) 140px;
gap: 20px;
align-items: center;
padding: 16px 0;
border-bottom: 1px solid #f0f0ed;
}
.ruleSettingCopy {
display: flex;
flex-direction: column;
gap: 5px;
}
.ruleSettingCopy strong {
color: #222;
font-size: 14px;
}
.ruleSettingCopy span {
color: #888;
font-size: 12px;
line-height: 1.55;
}
.ruleValueEditor {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 8px;
color: #666;
}
.ruleValueEditor :global(.ant-input-number) {
width: 110px;
}
.section {
margin-top: 14px;
padding: 20px 20px 16px;
border: 1px solid #ecece8;
border-radius: 16px;
background: #fff;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.02);
}
.sectionTitle {
margin: 0 0 10px;
font-size: 15px;
font-weight: 700;
}
.deviceCell {
gap: 7px;
}
.mono {
max-width: 210px;
overflow: hidden;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 12px;
text-overflow: ellipsis;
white-space: nowrap;
}
.copyButton {
height: 25px !important;
padding: 0 7px !important;
color: #777 !important;
font-size: 12px !important;
}
.actionGroup {
justify-content: flex-end;
gap: 6px;
white-space: nowrap;
}
.expandButton {
border-color: #ffd400 !important;
background: #ffd400 !important;
color: #111 !important;
font-weight: 600;
}
.detailWrap {
padding: 12px 16px 6px;
border-radius: 10px;
background: #fafaf8;
}
.factRow {
gap: 8px;
margin-bottom: 12px;
}
.fact {
padding: 6px 10px;
border: 1px solid #ecece7;
border-radius: 8px;
background: #fff;
color: #666;
font-size: 12px;
}
.fact strong {
margin: 0 3px;
color: #111;
font-size: 14px;
}
.price {
white-space: nowrap;
font-variant-numeric: tabular-nums;
}
.na {
color: #aaa;
}
.footerNote {
margin-top: 16px;
padding: 16px 20px;
border: 1px dashed #dcdcd8;
border-radius: 14px;
background: rgba(255, 255, 255, 0.42);
color: #666;
font-size: 12px;
line-height: 1.8;
}
.footerNote strong {
color: #222;
}
@media (max-width: 900px) {
.summaryGrid {
grid-template-columns: 1fr;
}
.hero {
align-items: flex-start;
padding-top: 16px;
padding-bottom: 16px;
}
.updatedMeta {
display: none;
}
}
+778
View File
@@ -0,0 +1,778 @@
'use client';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
App,
Button,
Empty,
InputNumber,
Modal,
Skeleton,
Table,
Tag,
Tooltip,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import {
ClearOutlined,
CopyOutlined,
DownOutlined,
EditOutlined,
ReloadOutlined,
RightOutlined,
} from '@ant-design/icons';
import dayjs from 'dayjs';
import { api, errMsg } from '@/lib/api';
import { formatUtcTime, utcDayjs } from '@/lib/format';
import type {
RiskDetailItem,
RiskDetailPage,
RiskIncidentItem,
RiskIncidentPage,
RiskKind,
RiskMonitorSummary,
RiskResetResponse,
RiskRuleConfig,
RiskSummaryCard,
} from '@/lib/types';
import styles from './page.module.css';
const KIND_META: Record<
RiskKind,
{ title: string; summaryTitle: string; totalLabel: string; unit: string }
> = {
sms: {
title: '短信',
summaryTitle: '触发短信报警的设备',
totalLabel: '今日短信下发共',
unit: '台',
},
oneclick: {
title: '一键登录',
summaryTitle: '触发一键登录报警的设备',
totalLabel: '今日一键登录共',
unit: '台',
},
compare: {
title: '比价',
summaryTitle: '触发比价报警的账户',
totalLabel: '今日比价共',
unit: '个',
},
};
const integer = (value: number) => new Intl.NumberFormat('zh-CN').format(value);
const LIST_PAGE_SIZE = 20;
const RISK_KINDS: RiskKind[] = ['sms', 'oneclick', 'compare'];
const RULE_LIMITS: Record<RiskKind, { min: number; max: number; help: string }> = {
sms: {
min: 1,
max: 5,
help: '统计成功下发;最高5次,与现有每设备每小时发送上限一致。',
},
oneclick: {
min: 1,
max: 100000,
help: '成功和失败均计入,同一设备按北京时间自然日累计。',
},
compare: {
min: 1,
max: 100,
help: '同一账户按北京时间自然日累计;最高100次,与比价每日上限一致。',
},
};
const utcTime = (value: string | null, withDate = true) =>
formatUtcTime(value, withDate ? 'MM-DD HH:mm' : 'HH:mm');
const eventMoment = (value: string, kind: RiskKind) =>
kind === 'compare' ? dayjs(value) : utcDayjs(value).tz('Asia/Shanghai');
const eventTime = (value: string | null, kind: RiskKind, withDate = true) =>
value ? eventMoment(value, kind).format(withDate ? 'MM-DD HH:mm' : 'HH:mm') : '-';
function period(item: RiskIncidentItem): string {
const start = eventMoment(item.first_event_at, item.kind);
const end = eventMoment(item.last_event_at, item.kind);
if (start.isSame(end, 'day')) {
return `${start.format('YYYY-MM-DD HH:mm')}${end.format('HH:mm')}`;
}
return `${start.format('YYYY-MM-DD HH:mm')}${end.format('YYYY-MM-DD HH:mm')}`;
}
function DeviceId({
value,
onCopy,
}: {
value: string | null;
onCopy: (value: string) => void;
}) {
if (!value) return <span className={styles.na}>-</span>;
return (
<span className={styles.deviceCell}>
<Tooltip title={value}>
<span className={styles.mono}>{value}</span>
</Tooltip>
<Button
className={styles.copyButton}
size="small"
icon={<CopyOutlined />}
onClick={() => onCopy(value)}
>
</Button>
</span>
);
}
function DetailTable({
detail,
loading,
page,
onPage,
}: {
detail?: RiskDetailPage;
loading: boolean;
page: number;
onPage: (page: number) => void;
}) {
if (loading || !detail) return <Skeleton active paragraph={{ rows: 4 }} />;
let columns: ColumnsType<RiskDetailItem>;
if (detail.kind === 'sms') {
columns = [
{
title: '发送时间',
dataIndex: 'occurred_at',
width: 150,
render: (v) => eventTime(v, detail.kind),
},
{ title: '手机号', dataIndex: 'phone', width: 140, render: (v) => v || '-' },
{
title: '完成验证',
dataIndex: 'verified',
width: 100,
render: (v) => (v ? <Tag color="success"></Tag> : <Tag></Tag>),
},
{
title: '登录账号',
key: 'account',
render: (_, row) => row.username || (row.user_id ? `U${row.user_id}` : '-'),
},
{
title: '账号注册时间',
dataIndex: 'account_registered_at',
width: 150,
render: (v) => utcTime(v),
},
];
} else if (detail.kind === 'oneclick') {
columns = [
{
title: '登录时间',
dataIndex: 'occurred_at',
width: 150,
render: (v) => eventTime(v, detail.kind),
},
{ title: '手机号', dataIndex: 'phone', width: 140, render: (v) => v || '-' },
{
title: '登录账号',
key: 'account',
render: (_, row) => row.username || (row.user_id ? `U${row.user_id}` : '-'),
},
{
title: '账号注册时间',
dataIndex: 'account_registered_at',
width: 150,
render: (v) => utcTime(v),
},
{
title: '结果',
dataIndex: 'outcome',
width: 100,
render: (v) =>
v === 'success' ? <Tag color="success"></Tag> : <Tag color="error"></Tag>,
},
{ title: '失败原因', dataIndex: 'reason', render: (v) => v || '-' },
];
} else {
const priceColumn = (platform: string) => ({
title: platform,
key: platform,
width: 100,
render: (_: unknown, row: RiskDetailItem) => {
const value = row.prices?.[platform];
return value == null ? (
<span className={styles.na}></span>
) : (
<span className={styles.price}>¥{value.toFixed(2)}</span>
);
},
});
columns = [
{
title: '触发时间',
dataIndex: 'occurred_at',
width: 150,
render: (v) => eventTime(v, detail.kind),
},
{
title: '店铺 / 菜品',
key: 'shop',
render: (_, row) => (
<span>{[row.store_name, row.product_names].filter(Boolean).join(' · ') || '-'}</span>
),
},
priceColumn('美团'),
priceColumn('淘宝'),
priceColumn('京东'),
{
title: '节省',
dataIndex: 'saved_amount_yuan',
width: 90,
render: (v) => (v == null ? '-' : <span className={styles.price}>{v.toFixed(2)} </span>),
},
{
title: '状态',
dataIndex: 'status',
width: 90,
render: (v) =>
v === 'success' ? <Tag color="success"></Tag> : <Tag color="error"></Tag>,
},
];
}
return (
<div className={styles.detailWrap}>
<div className={styles.factRow}>
<span className={styles.fact}>
{KIND_META[detail.kind].title}
<strong>{integer(detail.event_count)}</strong>
</span>
{detail.distinct_accounts != null && (
<span className={styles.fact}>
<strong>{integer(detail.distinct_accounts)}</strong>
</span>
)}
</div>
<Table
rowKey="id"
size="small"
columns={columns}
dataSource={detail.items}
scroll={{ x: detail.kind === 'compare' ? 1000 : 720 }}
pagination={{
current: page,
pageSize: 20,
total: detail.total,
showSizeChanger: false,
onChange: onPage,
}}
/>
</div>
);
}
export default function RiskMonitorPage() {
const { message, modal } = App.useApp();
const [summary, setSummary] = useState<RiskMonitorSummary | null>(null);
const [lists, setLists] = useState<Partial<Record<RiskKind, RiskIncidentPage>>>({});
const [listPage, setListPage] = useState<Record<RiskKind, number>>({
sms: 1,
oneclick: 1,
compare: 1,
});
const listPageRef = useRef(listPage);
const [loading, setLoading] = useState(true);
const [expanded, setExpanded] = useState<Set<number>>(new Set());
const [details, setDetails] = useState<Record<number, RiskDetailPage>>({});
const [detailLoading, setDetailLoading] = useState<Set<number>>(new Set());
const [detailPage, setDetailPage] = useState<Record<number, number>>({});
const [acting, setActing] = useState<number | null>(null);
const [ruleOpen, setRuleOpen] = useState(false);
const [ruleSaving, setRuleSaving] = useState(false);
const [resetting, setResetting] = useState(false);
const [ruleDraft, setRuleDraft] = useState<Record<RiskKind, number>>({
sms: 5,
oneclick: 20,
compare: 100,
});
const loadAll = useCallback(async (quiet = false) => {
if (!quiet) setLoading(true);
try {
const pages = listPageRef.current;
const [summaryRes, smsRes, oneclickRes, compareRes] = await Promise.all([
api.get<RiskMonitorSummary>('/admin/api/risk-monitor/summary'),
api.get<RiskIncidentPage>('/admin/api/risk-monitor/incidents/sms', {
params: { cursor: (pages.sms - 1) * LIST_PAGE_SIZE, limit: LIST_PAGE_SIZE },
}),
api.get<RiskIncidentPage>('/admin/api/risk-monitor/incidents/oneclick', {
params: { cursor: (pages.oneclick - 1) * LIST_PAGE_SIZE, limit: LIST_PAGE_SIZE },
}),
api.get<RiskIncidentPage>('/admin/api/risk-monitor/incidents/compare', {
params: { cursor: (pages.compare - 1) * LIST_PAGE_SIZE, limit: LIST_PAGE_SIZE },
}),
]);
setSummary(summaryRes.data);
setLists({
sms: smsRes.data,
oneclick: oneclickRes.data,
compare: compareRes.data,
});
} catch (error) {
void message.error(errMsg(error, '风控数据加载失败'));
} finally {
setLoading(false);
}
}, [message]);
const changeListPage = useCallback(
async (kind: RiskKind, page: number) => {
const nextPages = { ...listPageRef.current, [kind]: page };
listPageRef.current = nextPages;
setListPage(nextPages);
try {
const { data } = await api.get<RiskIncidentPage>(
`/admin/api/risk-monitor/incidents/${kind}`,
{
params: { cursor: (page - 1) * LIST_PAGE_SIZE, limit: LIST_PAGE_SIZE },
},
);
setLists((current) => ({ ...current, [kind]: data }));
} catch (error) {
void message.error(errMsg(error, '风险列表加载失败'));
}
},
[message],
);
useEffect(() => {
void loadAll();
const timer = window.setInterval(() => void loadAll(true), 60 * 60 * 1000);
const onFocus = () => void loadAll(true);
window.addEventListener('focus', onFocus);
return () => {
window.clearInterval(timer);
window.removeEventListener('focus', onFocus);
};
}, [loadAll]);
const copy = useCallback(
async (value: string) => {
await navigator.clipboard.writeText(value);
void message.success('设备 ID 已复制');
},
[message],
);
const openRuleSettings = useCallback(() => {
if (summary) {
const current = Object.fromEntries(
summary.cards.map((card) => [card.kind, card.threshold]),
) as Record<RiskKind, number>;
setRuleDraft(current);
}
setRuleOpen(true);
}, [summary]);
const saveRules = useCallback(async () => {
setRuleSaving(true);
try {
const payload: RiskRuleConfig = {
sms_hourly_threshold: ruleDraft.sms,
oneclick_daily_threshold: ruleDraft.oneclick,
compare_daily_threshold: ruleDraft.compare,
};
await api.patch<RiskRuleConfig>('/admin/api/risk-monitor/rules', payload);
setRuleOpen(false);
void message.success('规则已保存,并已重新核算当前时段');
await loadAll(true);
} catch (error) {
void message.error(errMsg(error, '规则保存失败'));
} finally {
setRuleSaving(false);
}
}, [loadAll, message, ruleDraft]);
const resetAlerts = useCallback(() => {
modal.confirm({
title: '确认重置全部报警?',
content:
'短信、一键登录、比价三类待处理报警将归零,并从确认时刻重新累计。历史流水会保留,已封禁的设备和账户不会解封。',
okText: '确认重置',
okButtonProps: { danger: true },
cancelText: '取消',
async onOk() {
setResetting(true);
try {
const { data } = await api.post<RiskResetResponse>(
'/admin/api/risk-monitor/reset',
);
listPageRef.current = { sms: 1, oneclick: 1, compare: 1 };
setListPage({ sms: 1, oneclick: 1, compare: 1 });
setExpanded(new Set());
setDetails({});
setDetailPage({});
if (data.reset_incident_count > 0) {
void message.success(
`已重置 ${integer(data.reset_incident_count)} 条报警,并从 0 重新累计`,
);
} else {
void message.success('当前无待处理报警,新的累计基线已生效');
}
await loadAll(true);
} catch (error) {
void message.error(errMsg(error, '报警重置失败'));
throw error;
} finally {
setResetting(false);
}
},
});
}, [loadAll, message, modal]);
const loadDetail = useCallback(
async (kind: RiskKind, incidentId: number, page = 1) => {
setDetailLoading((current) => new Set(current).add(incidentId));
try {
const { data } = await api.get<RiskDetailPage>(
`/admin/api/risk-monitor/incidents/${kind}/${incidentId}/details`,
{ params: { cursor: (page - 1) * 20, limit: 20 } },
);
setDetails((current) => ({ ...current, [incidentId]: data }));
setDetailPage((current) => ({ ...current, [incidentId]: page }));
} catch (error) {
void message.error(errMsg(error, '风险明细加载失败'));
} finally {
setDetailLoading((current) => {
const next = new Set(current);
next.delete(incidentId);
return next;
});
}
},
[message],
);
const toggle = useCallback(
(row: RiskIncidentItem) => {
const willOpen = !expanded.has(row.incident_id);
setExpanded((current) => {
const next = new Set(current);
if (willOpen) next.add(row.incident_id);
else next.delete(row.incident_id);
return next;
});
if (willOpen && !details[row.incident_id]) {
void loadDetail(row.kind, row.incident_id);
}
},
[details, expanded, loadDetail],
);
const runAction = useCallback(
(row: RiskIncidentItem, action: 'ignore' | 'block') => {
const verb = action === 'block' ? '封禁' : '忽略';
modal.confirm({
title: `确认${verb}${row.subject_type === 'device' ? '设备' : '账户'}`,
content:
action === 'block'
? row.subject_type === 'device'
? '封禁后,该设备发送短信和一键登录会被直接拒绝,不影响它登录过的账户。'
: '封禁后,该账户不能发起比价、领取任务奖励或提现,现有金币和现金不会清零。'
: '忽略后,本风险事件会移出待处理列表,事实流水仍会保留。',
okText: verb,
okButtonProps: { danger: action === 'block' },
cancelText: '取消',
async onOk() {
setActing(row.incident_id);
try {
await api.post(`/admin/api/risk-monitor/incidents/${row.incident_id}/${action}`, {
reason: `风控监控页人工${verb}`,
});
void message.success(`${verb}成功`);
setExpanded((current) => {
const next = new Set(current);
next.delete(row.incident_id);
return next;
});
if (
(lists[row.kind]?.items.length ?? 0) === 1
&& listPageRef.current[row.kind] > 1
) {
const nextPages = {
...listPageRef.current,
[row.kind]: listPageRef.current[row.kind] - 1,
};
listPageRef.current = nextPages;
setListPage(nextPages);
}
await loadAll(true);
} catch (error) {
void message.error(errMsg(error));
throw error;
} finally {
setActing(null);
}
},
});
},
[lists, loadAll, message, modal],
);
const columns = useCallback(
(kind: RiskKind): ColumnsType<RiskIncidentItem> => {
const actionColumn = {
title: '操作',
key: 'actions',
align: 'right' as const,
fixed: 'right' as const,
width: 180,
render: (_: unknown, row: RiskIncidentItem) => {
const open = expanded.has(row.incident_id);
return (
<span className={styles.actionGroup}>
<Button
className={styles.expandButton}
size="small"
loading={detailLoading.has(row.incident_id)}
icon={open ? <DownOutlined /> : <RightOutlined />}
onClick={() => toggle(row)}
>
{open ? '收起' : '展开'}
</Button>
<Button
size="small"
danger
loading={acting === row.incident_id}
onClick={() => runAction(row, 'block')}
>
</Button>
<Button
size="small"
loading={acting === row.incident_id}
onClick={() => runAction(row, 'ignore')}
>
</Button>
</span>
);
},
};
if (kind === 'compare') {
return [
{ title: '账户手机号', dataIndex: 'phone', width: 130, render: (v) => v || '-' },
{
title: '注册时间',
dataIndex: 'registered_at',
width: 105,
render: (v) => utcTime(v),
},
{
title: '常用设备',
dataIndex: 'common_device_id',
width: 180,
render: (v) => <DeviceId value={v} onCopy={copy} />,
},
{ title: '触发时段', key: 'period', width: 180, render: (_, row) => period(row) },
{
title: '首次触发',
dataIndex: 'triggered_at',
width: 125,
render: (v) => eventTime(v, kind),
},
actionColumn,
];
}
return [
{ title: '设备型号', dataIndex: 'device_model', width: 120, render: (v) => v || '-' },
{
title: '设备 ID',
dataIndex: 'subject_id',
width: 190,
render: (v) => <DeviceId value={v} onCopy={copy} />,
},
{
title: '首次使用',
dataIndex: 'first_used_at',
width: 110,
render: (v) => eventTime(v, kind),
},
{ title: '触发时段', key: 'period', width: 180, render: (_, row) => period(row) },
{
title: '首次触发',
dataIndex: 'triggered_at',
width: 110,
render: (v) => eventTime(v, kind),
},
actionColumn,
];
},
[acting, copy, detailLoading, expanded, runAction, toggle],
);
const cards = useMemo(() => {
if (!summary) return [];
const byKind = Object.fromEntries(summary.cards.map((card) => [card.kind, card]));
return RISK_KINDS
.map((kind) => byKind[kind])
.filter(Boolean) as RiskSummaryCard[];
}, [summary]);
return (
<main className={styles.page}>
<header className={styles.hero}>
<div className={styles.titleCluster}>
<span className={styles.back}> </span>
<span className={styles.brandMark}></span>
<div>
<h1 className={styles.title}></h1>
<div className={styles.subtitle}> / / </div>
</div>
</div>
<div className={styles.updated}>
<span className={styles.updatedMeta}>
<span>{summary ? dayjs(summary.date).format('YYYY-MM-DD') : '---- -- --'}</span>
<span></span>
<span className={styles.dot} />
<span></span>
</span>
<Button
type="text"
size="small"
icon={<ReloadOutlined />}
loading={loading}
aria-label="刷新风控数据"
onClick={() => void loadAll()}
/>
<Tooltip title="三类待处理报警归零,历史流水和封禁状态不变">
<Button
size="small"
icon={<ClearOutlined />}
loading={resetting}
onClick={resetAlerts}
>
</Button>
</Tooltip>
</div>
</header>
{loading && !summary ? (
<Skeleton active paragraph={{ rows: 10 }} />
) : (
<>
<section className={styles.summaryGrid}>
{cards.map((card) => {
const meta = KIND_META[card.kind];
return (
<article key={card.kind} className={styles.summaryCard}>
<div className={styles.summaryTitle}>{meta.summaryTitle}</div>
<div>
<span className={styles.summaryValue}>{card.alert_subject_count}</span>
<span className={styles.summaryUnit}>{meta.unit}</span>
</div>
<div className={styles.summarySub}>
{meta.totalLabel} {integer(card.today_total)}
</div>
<button
type="button"
className={styles.rule}
onClick={openRuleSettings}
aria-label={`编辑${meta.title}告警规则`}
>
<span>{card.rule_text.replace(/≥.*$/, '')}</span>
<strong> {card.threshold} </strong>
<EditOutlined className={styles.ruleEditIcon} />
</button>
</article>
);
})}
</section>
{RISK_KINDS.map((kind) => {
const data = lists[kind]?.items ?? [];
return (
<section key={kind} className={styles.section}>
<h2 className={styles.sectionTitle}>{KIND_META[kind].title}</h2>
<Table
rowKey="incident_id"
size="middle"
columns={columns(kind)}
dataSource={data}
tableLayout="fixed"
scroll={{ x: kind === 'compare' ? 900 : 890 }}
locale={{ emptyText: <Empty description="当前没有待处理风险" /> }}
pagination={{
current: listPage[kind],
pageSize: LIST_PAGE_SIZE,
total: lists[kind]?.total ?? 0,
hideOnSinglePage: true,
showSizeChanger: false,
onChange: (page) => void changeListPage(kind, page),
}}
expandable={{
expandedRowKeys: [...expanded],
showExpandColumn: false,
expandedRowRender: (row) => (
<DetailTable
detail={details[row.incident_id]}
loading={detailLoading.has(row.incident_id)}
page={detailPage[row.incident_id] || 1}
onPage={(page) => void loadDetail(row.kind, row.incident_id, page)}
/>
),
}}
/>
</section>
);
})}
<footer className={styles.footerNote}>
<strong></strong>
线
</footer>
</>
)}
<Modal
title="风控规则设置"
open={ruleOpen}
okText="保存并立即生效"
cancelText="取消"
confirmLoading={ruleSaving}
onOk={() => void saveRules()}
onCancel={() => setRuleOpen(false)}
destroyOnHidden
>
<p className={styles.ruleDialogIntro}>
</p>
<div className={styles.ruleSettings}>
{RISK_KINDS.map((kind) => {
const meta = KIND_META[kind];
const limits = RULE_LIMITS[kind];
return (
<div key={kind} className={styles.ruleSettingRow}>
<div className={styles.ruleSettingCopy}>
<strong>{meta.summaryTitle}</strong>
<span>{limits.help}</span>
</div>
<div className={styles.ruleValueEditor}>
<InputNumber
min={limits.min}
max={limits.max}
precision={0}
value={ruleDraft[kind]}
onChange={(value) => {
if (value == null) return;
setRuleDraft((current) => ({ ...current, [kind]: value }));
}}
/>
<span></span>
</div>
</div>
);
})}
</div>
</Modal>
</main>
);
}
+102 -28
View File
@@ -142,7 +142,7 @@ function actionLabel(action: string) {
'withdraw.approve': '审核通过',
'withdraw.reject': '审核拒绝',
'withdraw.refresh': '查单刷新',
'withdraw.reconcile': '批量对账',
'withdraw.reconcile': '处理超时订单',
};
return labels[action] || action;
}
@@ -182,8 +182,11 @@ export default function WithdrawsPage() {
const [activeStatus, setActiveStatus] = useState('reviewing');
const [summary, setSummary] = useState<WithdrawSummary | null>(null);
const [health, setHealth] = useState<WxpayHealthCheck | null>(null);
const [healthLoading, setHealthLoading] = useState(false);
const [healthCheckedAt, setHealthCheckedAt] = useState<number | null>(null);
const [ledger, setLedger] = useState<WithdrawLedgerCheck | null>(null);
const [ledgerLoading, setLedgerLoading] = useState(false);
const [ledgerCheckedAt, setLedgerCheckedAt] = useState<number | null>(null);
const [drawerOpen, setDrawerOpen] = useState(false);
const [detail, setDetail] = useState<WithdrawDetail | null>(null);
const [detailLoading, setDetailLoading] = useState(false);
@@ -255,21 +258,36 @@ export default function WithdrawsPage() {
}
}, []);
const loadHealth = useCallback(async () => {
const loadHealth = useCallback(async (showFeedback = false) => {
setHealthLoading(true);
try {
const { data } = await api.get<WxpayHealthCheck>('/admin/api/withdraws/health-check');
setHealth(data);
setHealthCheckedAt(Date.now());
if (showFeedback) {
message.success(data.ok ? '检测完成,微信提现配置正常' : '检测完成,仍有配置项需要处理');
}
} catch (e) {
message.error(errMsg(e));
} finally {
setHealthLoading(false);
}
}, []);
// 账本校验是全表对账、相对重,故只在进页时拉一次 + 提供手动按钮,不随每次写操作重算。
const loadLedger = useCallback(async () => {
const loadLedger = useCallback(async (showFeedback = false) => {
setLedgerLoading(true);
try {
const { data } = await api.get<WithdrawLedgerCheck>('/admin/api/withdraws/ledger-check');
setLedger(data);
setLedgerCheckedAt(Date.now());
if (showFeedback) {
if (data.ok) {
message.success('校验完成,现金账本正常');
} else {
message.warning('校验完成,发现现金账本异常');
}
}
} catch (e) {
message.error(errMsg(e));
} finally {
@@ -465,15 +483,16 @@ export default function WithdrawsPage() {
const reconcile = () => {
modal.confirm({
title: '批量对账?',
content: '扫描超过 15 分钟仍处于打款中的提现单,逐单向微信查实并归一化。',
okText: '开始对账',
title: '处理超时打款订单?',
content:
'将检查超过 15 分钟仍处于“打款中”的订单:微信已成功则更新为“已到账”;失败则退款;仍待用户确认的老单将撤销并退款;仍在处理中则保持不变。',
okText: '开始处理',
onOk: async () => {
try {
const { data } = await api.post<{ checked: number; resolved: number }>(
'/admin/api/withdraws/reconcile',
);
message.success(`对账完成: 检查 ${data.checked} 单,解决 ${data.resolved}`);
message.success(`处理完成:检查 ${data.checked} 单,更新 ${data.resolved}`);
await refreshAfterChange();
} catch (e) {
message.error(errMsg(e));
@@ -652,6 +671,10 @@ export default function WithdrawsPage() {
: '',
].filter(Boolean)
: [];
const payoutReady = Boolean(
health?.wxpay_configured && health.private_key_loadable && health.public_key_loadable,
);
const hasBlockingPayoutIssue = Boolean(health && !payoutReady);
return (
<div>
@@ -662,41 +685,62 @@ export default function WithdrawsPage() {
</div>
{canManage && (
<Button danger icon={<ReloadOutlined />} onClick={reconcile}>
</Button>
)}
</Space>
{(health || ledger) && (
{(hasBlockingPayoutIssue || (ledger && !ledger.ok)) && (
<Space direction="vertical" style={{ width: '100%', marginBottom: 16 }}>
{health && (
{health && hasBlockingPayoutIssue && (
<Alert
showIcon
type={health.ok ? 'success' : 'warning'}
message={health.ok ? '微信提现配置正常' : '微信提现配置需检查'}
type="warning"
message="当前环境无法执行微信打款"
description={
health.ok
? `自动对账已${health.auto_reconcile_enabled ? '开启' : '关闭'},每 ${health.auto_reconcile_interval_sec}s 扫描 ${health.auto_reconcile_older_than_minutes} 分钟前的打款中订单`
: health.issues.join('')
}
/>
)}
{ledger && (
<Alert
showIcon
type={ledger.ok ? 'success' : 'error'}
message={ledger.ok ? '现金账本校验正常' : '现金账本存在异常'}
description={
ledger.ok
? `现金 余额 ${yuan(ledger.cash_balance_total_cents)} / 流水 ${yuan(ledger.cash_transaction_total_cents)};邀请金 余额 ${yuan(ledger.invite_cash_balance_total_cents)} / 流水 ${yuan(ledger.invite_cash_transaction_total_cents)}`
: ledgerIssues.join('')
<Space direction="vertical" size={6}>
<Text></Text>
{healthCheckedAt && (
<Text type="secondary">
{dayjs(healthCheckedAt).format('HH:mm:ss')}
</Text>
)}
<details>
<summary style={{ color: '#1677ff', cursor: 'pointer' }}></summary>
<ul style={{ margin: '8px 0 0', paddingInlineStart: 20 }}>
{health.issues.map((issue) => (
<li key={issue} style={{ marginBottom: 4, overflowWrap: 'anywhere' }}>
{issue}
</li>
))}
</ul>
</details>
</Space>
}
action={
<Button
size="small"
icon={<ReloadOutlined />}
loading={healthLoading}
onClick={() => void loadHealth(true)}
>
</Button>
}
/>
)}
{ledger && !ledger.ok && (
<Alert
showIcon
type="error"
message="现金账本存在异常"
description={ledgerIssues.join('')}
action={
<Button
size="small"
icon={<ReloadOutlined />}
loading={ledgerLoading}
onClick={() => void loadLedger()}
onClick={() => void loadLedger(true)}
>
</Button>
@@ -706,6 +750,36 @@ export default function WithdrawsPage() {
</Space>
)}
{(health || ledger) && (
<Space
size={12}
wrap
style={{ width: '100%', justifyContent: 'flex-end', marginBottom: 12 }}
>
{health && payoutReady && <Tag color="success"></Tag>}
{ledger?.ok && (
<Space size={6}>
<CheckCircleOutlined style={{ color: '#52c41a' }} />
<Text strong></Text>
{ledgerCheckedAt && (
<Text type="secondary">
· {dayjs(ledgerCheckedAt).format('HH:mm:ss')}
</Text>
)}
<Button
type="link"
size="small"
icon={<ReloadOutlined />}
loading={ledgerLoading}
onClick={() => void loadLedger(true)}
>
</Button>
</Space>
)}
</Space>
)}
<Row gutter={12} style={{ marginBottom: 16 }}>
<Col xs={24} sm={12}>
<Card size="small">
+33
View File
@@ -0,0 +1,33 @@
export interface BulkReviewItemResult {
id: number;
ok: boolean;
status: string | null;
error: string | null;
}
export interface BulkReviewResult {
total: number;
success: number;
failed: number;
items: BulkReviewItemResult[];
}
export const BULK_REVIEW_MAX = 50;
export function failedReviewIds(result: BulkReviewResult): number[] {
return result.items.filter((item) => !item.ok).map((item) => item.id);
}
export function bulkFailureReasonText(result: BulkReviewResult): string {
const reasons = Array.from(
new Set(
result.items
.filter((item) => !item.ok)
.map((item) => item.error?.trim())
.filter((reason): reason is string => Boolean(reason)),
),
);
if (!reasons.length) return '';
const visible = reasons.slice(0, 3);
return `;原因:${visible.join('')}${reasons.length > visible.length ? ';…' : ''}`;
}
+98 -1
View File
@@ -218,6 +218,91 @@ export interface UserCoinRecord {
coin: number;
}
// ===== 风控监控 =====
export type RiskKind = 'sms' | 'oneclick' | 'compare';
export interface RiskSummaryCard {
kind: RiskKind;
alert_subject_count: number;
today_total: number;
threshold: number;
rule_text: string;
}
export interface RiskMonitorSummary {
date: string;
updated_at: string;
cards: RiskSummaryCard[];
}
export interface RiskRuleConfig {
sms_hourly_threshold: number;
oneclick_daily_threshold: number;
compare_daily_threshold: number;
}
export interface RiskResetResponse {
ok: boolean;
reset_at: string;
reset_incident_count: number;
reset_counts: Record<RiskKind, number>;
}
export interface RiskIncidentItem {
incident_id: number;
kind: RiskKind;
subject_type: 'device' | 'user';
subject_id: string;
device_model: string | null;
first_used_at: string | null;
phone: string | null;
user_id: number | null;
registered_at: string | null;
common_device_id: string | null;
window_start: string;
window_end: string;
first_event_at: string;
triggered_at: string;
last_event_at: string;
event_count: number;
status: 'open' | 'ignored' | 'blocked' | 'resolved';
restricted: boolean;
}
export interface RiskIncidentPage {
items: RiskIncidentItem[];
next_cursor: number | null;
total: number;
}
export interface RiskDetailItem {
id: number;
occurred_at: string;
outcome: string;
phone: string | null;
user_id: number | null;
username: string | null;
account_registered_at: string | null;
verified: boolean | null;
reason: string | null;
store_name: string | null;
product_names: string | null;
prices: Record<string, number | null> | null;
saved_amount_yuan: number | null;
status: string | null;
}
export interface RiskDetailPage {
kind: RiskKind;
incident_id: number;
event_count: number;
distinct_accounts: number | null;
items: RiskDetailItem[];
next_cursor: number | null;
total: number;
}
export interface WithdrawBulkItemResult {
out_bill_no: string;
ok: boolean;
@@ -317,6 +402,18 @@ export interface FeedbackQrConfig {
updated_at: string | null;
}
/** ( 3 广, 120 )
* enabled + ;, */
export interface GuideVideoConfig {
enabled: boolean;
video_url: string | null; // /media/guide_video/xxx.mp4;null = 未配片(浮层照旧只放广告)
max_plays: number; // 每个账号前 N 次浮层放引导视频(服务端默认 3,后台不开放调整)
reward_coin: number; // 每次固定金币(服务端默认 120,播完 / 中途关闭都发)
updated_at: string | null;
total_plays: number; // 只读统计:全站已播次数(后台不再展示)
granted_plays: number; // 只读统计:其中已发币次数(后台不再展示)
}
export interface AuditLog {
id: number;
admin_id: number;
@@ -488,7 +585,7 @@ export interface AdRevenueRow {
has_impression: boolean; // 是否有广告展示(信息流逐条展示=true,纯发奖行=false)
impressions: number; // 本行展示条数 1/0(供日汇总、趋势图复用)
ecpm: string | null; // 分/千次;展示行取展示值,纯发奖行取发奖采用值
revenue_yuan: number; // 本次展示预估收益(元);纯发奖=0
revenue_yuan: number; // 本次有效展示预估收益(元);纯发奖、激励视频提前关闭/时长不足=0
row_revenue_yuan?: number | null; // 主表逐行显示用:一次比价/领券聚合行=该次发奖广告 eCPM 折算之和;其它行空(回退 revenue_yuan)
adn: string | null; // 实际填充 ADN;纯发奖行为空
slot_id: string | null; // 底层 mediation rit;纯发奖行为空