Compare commits

..

13 Commits

Author SHA1 Message Date
zhuzihao 36d00a9d68 feat(force-onboarding): 用户列表加「开启新手引导」一次性操作 (#13)
Co-authored-by: zzhyyyyy <2685922758@qq.com>
Reviewed-on: #13
Co-authored-by: zhuzihao <zhuzihao@wonderable.ai>
Co-committed-by: zhuzihao <zhuzihao@wonderable.ai>
2026-06-21 00:15:17 +08:00
marco 98417ff8c6 feat(ad): 「广告数据」改「广告管理」,加穿山甲配置面板
- 顶部广告配置面板:app_id / 3 场景广告位ID / 激励验签密钥(Password) / 3 场景开关,
  读写 /admin/api/ad-config
- 原报表保留为下方「收益报表」;左侧菜单更名「广告管理」

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-20 01:35:19 +08:00
marco b7957e58c0 feat(cps): 群详情页加「群内微信用户」区块(头像/昵称/领券次数)
微信落地页授权来的用户列表:头像+昵称+领券次数(点复制)+点击次数+首次进入。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-19 11:44:14 +08:00
marco 5ae87fc11e feat(cps): 群详情页加按天明细大表格(退款佣金/净佣金/转化)
- 天级范围(3/7/14/30天)显示每日明细表;今日小时模式隐藏(看上面折线)
- 列:点击/独立/复制/点击→下单/有效单/取消风控/成交额/预估佣金/退款佣金/净佣金/结算佣金
- 净佣金=预估-退款(前端算);非美团群订单列显示 "-"

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-18 17:32:20 +08:00
marco f4043f2abf fix(admin-web): 比价记录页时区/cancelled/详情展示位修复
- 列表时间改 formatWallTime(created_at 北京 wall-clock 口径, 原 formatUtcTime 快 8h)
- cancelled 加颜色/中文(成功/失败/已终止) + 筛选选项
- 详情补 下单商品(items+跳过菜)/最优深链/device_id 展示位
- comparison_results 空值兜底

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-17 23:32:36 +08:00
marco 472912560c fix(cps): 详情页折线点大小用 style.r(sizeField 是字段映射不能给常量)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-17 23:06:06 +08:00
marco 9afb213b50 feat(admin): 比价记录 debug 页
按 user_id/手机号查任意用户的全部比价记录:列表(平台/店菜/省/耗时/步数/LLM次数/重试/机型ROM/状态)
+ 详情抽屉(逐平台对比、卡在哪一步=platform_results 细分原因、设备环境、每次 LLM 调用 input/output
JSON 结构化展开、trace 可点链接、raw_payload 全量)。侧栏新增「比价记录」入口。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-17 22:33:37 +08:00
marco 1a6e590a42 feat(cps): 群对账详情页折线图(点击/独立/复制趋势,3/7/14/30天+小时)
- 对账统计页群名可点进群详情页 /cps/groups/[id]
- @ant-design/plots 折线图,4 指标多线,Segmented 切时间范围,y 轴 0 基线
- 数据稀疏靠后端补零保证折线连续/x 轴铺满

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-17 22:31:37 +08:00
marco cef5ea0140 feat(cps): 活动表单支持编辑 + 列表加编辑按钮
- ActivityFormModal 改 create+edit 双模式(回填字段, 编辑走 PATCH, 加状态切换)
- 活动列表操作列加「编辑」

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-17 22:13:36 +08:00
marco b1923c3133 feat(cps): 群/活动列表加删除按钮(Popconfirm 二次确认)
- 群操作列 + 删除;活动列表新增操作列含删除
- 确认弹窗说明影响(已发链接仍可用 / 淘宝活动删后落地页用默认图)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-17 21:43:35 +08:00
marco ecbce54e70 feat(cps): 新建淘宝活动支持上传/选择落地页图 + 列表缩略图
- ActivityFormModal 淘宝分支加 ImagePicker(上传新图 / 选已有 / 预览),必填
- 活动列表加落地页图缩略图列
- types: CpsActivity.image_url

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-17 21:32:12 +08:00
marco 654aca4c40 feat(cps): 分发后台从仅美团扩展到美团/淘宝/京东多平台
- 群/活动支持平台多选,sid 仅美团群保留
- 活动按平台切换录入(美团 actId/pvs、淘宝淘口令、京东链接)
- 生成发群链接改批量勾选多活动(/cps/referral-links)
- 统计表加平台/复制列,淘宝/京东无对账字段显示 "-"

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-17 19:15:27 +08:00
ouzhou a393b5c0e3 feat(config): 配置页 bool 开关控件 + 全站 antd App.useApp 迁移 (#12)
- 系统配置页支持 bool 类型(Switch 控件),供「提现自动对账」「比价期广告」等运营开关使用
- message / Modal.confirm 静态调用迁移到 App.useApp() 的 message / modal,消除 React 19
  "Static function can not consume context" 告警;providers 用 <App> 容器包裹全站

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

---------

Co-authored-by: OuYingJun1024 <1034284404@qq.com>
Reviewed-on: #12
Co-authored-by: ouzhou <ouzhou@wonderable.ai>
Co-committed-by: ouzhou <ouzhou@wonderable.ai>
2026-06-17 10:38:40 +08:00
27 changed files with 2825 additions and 411 deletions
+4
View File
@@ -1,3 +1,7 @@
# 生产:前端与 admin API 同域(admin.shaguabijia.com),nginx 把 /admin/api 反代到后端 8771。
# 留空 = axios 用相对路径,请求落到当前域名,由 nginx 转发。
NEXT_PUBLIC_API_BASE=
# 媒体(反馈二维码 / 上报截图)的公开地址。媒体由 App 后端的 /media 托管,默认不在 admin 域。
# 设为可公开访问媒体的源(如 https://api.shaguabijia.com),或在 admin nginx 增加 /media 反代后留空走同域。
NEXT_PUBLIC_MEDIA_BASE=
+12 -4
View File
@@ -5,10 +5,12 @@ Next.js 15 + Ant Design 5,对接 `shaguabijia-app-server` 的 admin API(`app/adm
鉴权用独立 JWT)。本仓只是前端。
## 功能(P0)
数据大盘 / 用户管理(列表+360详情+封禁+调金币) / 提现管理(列表+重试+对账) /
反馈工单 / 管理员账号(super) / 审计日志。按角色显示操作:finance=钱、operator=用户+反馈、super=全部。
## 本地开发
```bash
# 1. 起 admin 后端(在 shaguabijia-app-server 目录)
conda activate price && uvicorn app.admin.main:admin_app --port 8771
@@ -17,11 +19,13 @@ python scripts/create_admin.py --username admin --role super_admin
# 3. 起前端
npm install && npm run dev # → http://localhost:3001
```
`.env.local` 已指向 `http://localhost:8771`
## 生产部署(阿里云,域名 admin.shaguabijia.com)
### ① 后端 admin(在 app-server 机器,复用同一 codebase)
```bash
scp deploy/shaguabijia-admin.service server:/etc/systemd/system/ # 文件在 app-server/deploy/
ssh server "systemctl daemon-reload && systemctl enable --now shaguabijia-admin"
@@ -29,6 +33,7 @@ ssh server "cd /opt/shaguabijia-app-server && .venv/bin/python scripts/create_ad
```
### ② 前端
```bash
npm run build
rsync -avz --exclude node_modules --exclude .next/cache ./ server:/opt/shaguabijia-admin-web/
@@ -36,13 +41,16 @@ ssh server "cd /opt/shaguabijia-admin-web && npm install --omit=dev && npm run b
```
### ③ nginx
```bash
scp deploy/nginx/admin.shaguabijia.com.conf server:/etc/nginx/conf.d/
ssh server "nginx -t && systemctl reload nginx"
```
## ⚠️ 上线必查
- [ ] app-server 的 `.env``ADMIN_JWT_SECRET` 改成 ≥32 字节强随机串(默认 `change-me-admin` 可伪造 token)
- [ ] nginx 打开 IP 白名单(运营出口 IP)+ HTTPS 证书就位
- [ ] `.env.production``NEXT_PUBLIC_API_BASE` 留空(同域,nginx 反代 /admin/api)
- [ ] 首个 super_admin 已建、能登录
- app-server 的 `.env``ADMIN_JWT_SECRET` 改成 ≥32 字节强随机串(默认 `change-me-admin` 可伪造 token)
- nginx 打开 IP 白名单(运营出口 IP)+ HTTPS 证书就位
- `.env.production``NEXT_PUBLIC_API_BASE` 留空(同域,nginx 反代 /admin/api)
- 首个 super_admin 已建、能登录
+12
View File
@@ -32,6 +32,18 @@ server {
proxy_read_timeout 60s;
}
# 用户上传媒体(上报截图 / 反馈截图 / 反馈二维码)由 App 后端(:8770)的 /media 托管。
# admin 页面要展示这些图,经此同域反代过去(免跨域 + 免 https 页面引 http 图被拦)。
# 前提:App 后端与本 admin 同机;若分机,把 127.0.0.1:8770 换成 App 后端可达地址。
# 配好此段后,前端 .env.production 的 NEXT_PUBLIC_MEDIA_BASE 留空即走同域。
location /media/ {
proxy_pass http://127.0.0.1:8770;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 60s;
}
# 其余 → Next.js 前端
location / {
proxy_pass http://127.0.0.1:3001;
+873 -60
View File
File diff suppressed because it is too large Load Diff
+1
View File
@@ -12,6 +12,7 @@
"@ant-design/cssinjs": "^1.24.0",
"@ant-design/icons": "^5.5.2",
"@ant-design/nextjs-registry": "^1.0.2",
"@ant-design/plots": "^2.6.8",
"@ant-design/v5-patch-for-react-19": "^1.0.3",
"antd": "^5.22.0",
"axios": "^1.7.7",
+96 -2
View File
@@ -3,12 +3,15 @@
import { useCallback, useEffect, useState } from 'react';
import type { ColumnsType } from 'antd/es/table';
import {
App,
Alert,
Button,
Card,
Col,
DatePicker,
Divider,
Form,
Input,
InputNumber,
Modal,
Popover,
@@ -16,10 +19,10 @@ import {
Select,
Space,
Statistic,
Switch,
Table,
Tag,
Typography,
message,
} from 'antd';
import {
FallOutlined,
@@ -268,7 +271,97 @@ function TrendChart({ points }: { points: TrendPoint[] }) {
// 广告数据页:单表 —— 按 用户×类型×应用×代码位 聚合,一行同时给出
// 展示条数 / 收益 / 应发金币 / 实发金币 / 是否一致(发奖对账下沉到聚合级)。
// 广告配置面板:穿山甲 app_id / 各场景广告位ID / 验签密钥 / 各场景开关。
// 客户端(发版后)从 /api/v1/platform/ad-config 拉取;此处经 admin /ad-config 读写。
interface AdCfg {
app_id: string;
reward_code_id: string;
compare_feed_code_id: string;
coupon_feed_code_id: string;
reward_mkey: string;
reward_enabled: boolean;
compare_ad_enabled: boolean;
coupon_ad_enabled: boolean;
}
function AdConfigPanel() {
const { message } = App.useApp();
const [form] = Form.useForm();
const [saving, setSaving] = useState(false);
const load = useCallback(async () => {
try {
const r = await api.get<AdCfg>('/admin/api/ad-config');
form.setFieldsValue(r.data);
} catch (e) {
message.error(errMsg(e, '广告配置加载失败'));
}
}, [form, message]);
useEffect(() => {
load();
}, [load]);
const save = async () => {
const v = await form.validateFields();
setSaving(true);
try {
await api.patch('/admin/api/ad-config', v);
message.success('已保存。客户端下次拉取生效(应用ID需冷启,广告位ID即时)');
load();
} catch (e) {
message.error(errMsg(e, '保存失败'));
} finally {
setSaving(false);
}
};
return (
<Card
title="广告配置(穿山甲)"
style={{ marginBottom: 16 }}
extra={
<Button type="primary" loading={saving} onClick={save}>
</Button>
}
>
<Alert
type="info"
style={{ marginBottom: 16 }}
message="应用ID改了客户端需冷启生效,广告位ID即时;换激励位必须同步换验签密钥(m-key),否则发不出金币。这些配置需客户端发版接入后才会读取。"
/>
<Form form={form} layout="vertical">
<Form.Item name="app_id" label="穿山甲应用ID (APP_ID)" rules={[{ required: true }]}>
<Input placeholder="如 5830519" />
</Form.Item>
<Form.Item name="reward_code_id" label="福利页 · 激励视频 广告位ID" rules={[{ required: true }]}>
<Input placeholder="如 104099389" />
</Form.Item>
<Form.Item
name="reward_mkey"
label="福利激励 · 验签密钥 m-key(机密,不下发客户端;换激励位必须同步换;留空回退 .env)"
>
<Input.Password placeholder="GroMore S2S 回调验签密钥" autoComplete="off" />
</Form.Item>
<Form.Item name="compare_feed_code_id" label="比价 · 信息流 广告位ID" rules={[{ required: true }]}>
<Input placeholder="如 104090333" />
</Form.Item>
<Form.Item name="coupon_feed_code_id" label="领券 · 信息流 广告位ID" rules={[{ required: true }]}>
<Input placeholder="如 104090333" />
</Form.Item>
<Form.Item name="reward_enabled" label="福利激励视频开关" valuePropName="checked">
<Switch />
</Form.Item>
<Form.Item name="compare_ad_enabled" label="比价广告开关" valuePropName="checked">
<Switch />
</Form.Item>
<Form.Item name="coupon_ad_enabled" label="领券广告开关" valuePropName="checked">
<Switch />
</Form.Item>
</Form>
</Card>
);
}
export default function AdRevenuePage() {
const { message } = App.useApp();
const [range, setRange] = useState<[Dayjs, Dayjs]>([dayjs(), dayjs()]);
const [userId, setUserId] = useState<number | null>(null);
const [adType, setAdType] = useState<string | undefined>();
@@ -411,8 +504,9 @@ export default function AdRevenuePage() {
return (
<div>
<AdConfigPanel />
<Space align="center" style={{ display: 'flex', marginBottom: 16 }}>
<h2 style={{ margin: 0 }}>广</h2>
<h2 style={{ margin: 0 }}></h2>
<Button
type="link"
size="small"
+4 -3
View File
@@ -2,7 +2,7 @@
import { useEffect, useState } from 'react';
import type { ColumnsType } from 'antd/es/table';
import { Button, Form, Input, Modal, Select, Table, Tag, message } from 'antd';
import { App, Button, Form, Input, Modal, Select, Table, Tag } from 'antd';
import { api, errMsg } from '@/lib/api';
import { formatUtcTime } from '@/lib/format';
import type { AdminInfo } from '@/lib/types';
@@ -16,6 +16,7 @@ const ROLES = [
const dt = (v: string | null) => (v ? formatUtcTime(v, 'YYYY-MM-DD HH:mm:ss') : '从未');
export default function AdminsPage() {
const { message, modal } = App.useApp();
const [admins, setAdmins] = useState<AdminInfo[]>([]);
const [loading, setLoading] = useState(false);
const [createOpen, setCreateOpen] = useState(false);
@@ -49,7 +50,7 @@ export default function AdminsPage() {
const changeRole = (a: AdminInfo, role: string) => {
if (role === a.role) return;
Modal.confirm({
modal.confirm({
title: `${a.username} 的角色改为 ${role}?`,
onOk: async () => {
try {
@@ -65,7 +66,7 @@ export default function AdminsPage() {
const toggle = (a: AdminInfo) => {
const next = a.status === 'active' ? 'disabled' : 'active';
Modal.confirm({
modal.confirm({
title: `${next === 'disabled' ? '禁用' : '启用'}管理员 ${a.username}?`,
onOk: async () => {
try {
+334
View File
@@ -0,0 +1,334 @@
'use client';
import { useState } from 'react';
import type { CSSProperties } from 'react';
import {
App, Button, Card, Collapse, Descriptions, Drawer, Input, InputNumber,
Select, Space, Spin, Table, Tag, Typography,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { api, errMsg } from '@/lib/api';
import { formatWallTime, yuan } from '@/lib/format';
import { usePagedList } from '@/lib/usePagedList';
import type { ComparisonRecordDetail, ComparisonRecordListItem } from '@/lib/types';
const STATUS_COLOR: Record<string, string> = { success: 'green', failed: 'red', cancelled: 'default' };
const STATUS_LABEL: Record<string, string> = { success: '成功', failed: '失败', cancelled: '已终止' };
// 「卡在哪一步」: platform_results[*].status 翻成人话(找店/加菜/起送/读价)
const STUCK_LABEL: Record<string, string> = {
success: '成功',
store_not_found: '没找到店',
items_not_found: '菜没匹配上',
below_minimum: '未达起送',
unsupported: '平台不支持',
failed: '失败',
};
const fmtMs = (ms: number | null) => (ms == null ? '-' : `${(ms / 1000).toFixed(1)}s`);
const cents = (c: number | null) => (c == null ? '-' : yuan(c));
// LLM message content 常是 json.dumps 的卡片列表;能 parse 成 JSON 就缩进展开,否则原样。
function pretty(s: string | null): string {
if (!s) return '';
try {
return JSON.stringify(JSON.parse(s), null, 2);
} catch {
return s;
}
}
const preStyle: CSSProperties = {
background: '#f6f8fa', padding: 8, borderRadius: 6, fontSize: 12,
maxHeight: 340, overflow: 'auto', whiteSpace: 'pre-wrap', wordBreak: 'break-word', margin: 0,
};
export default function ComparisonRecordsPage() {
const { message } = App.useApp();
const [userId, setUserId] = useState<number | null>(null);
const [phone, setPhone] = useState('');
const [status, setStatus] = useState<string | undefined>();
const [applied, setApplied] = useState<Record<string, unknown>>({});
const { items, total, page, pageSize, loading, onChange } =
usePagedList<ComparisonRecordListItem>('/admin/api/comparison-records', applied);
const [detail, setDetail] = useState<ComparisonRecordDetail | null>(null);
const [detailLoading, setDetailLoading] = useState(false);
const search = () =>
setApplied({ user_id: userId ?? undefined, phone: phone || undefined, status });
const reset = () => {
setUserId(null);
setPhone('');
setStatus(undefined);
setApplied({});
};
const openDetail = async (id: number) => {
setDetailLoading(true);
setDetail(null);
try {
const { data } = await api.get<ComparisonRecordDetail>(`/admin/api/comparison-records/${id}`);
setDetail(data);
} catch (e) {
message.error(errMsg(e));
} finally {
setDetailLoading(false);
}
};
const closeDetail = () => {
setDetail(null);
setDetailLoading(false);
};
const columns: ColumnsType<ComparisonRecordListItem> = [
{ title: 'ID', dataIndex: 'id', width: 64 },
{
title: '用户',
key: 'user',
width: 140,
render: (_, r) => (
<div>
<div>{r.phone || `#${r.user_id}`}</div>
{r.nickname && <div style={{ color: '#999', fontSize: 12 }}>{r.nickname}</div>}
</div>
),
},
{ title: '状态', dataIndex: 'status', width: 72, render: (s: string) => <Tag color={STATUS_COLOR[s]}>{STATUS_LABEL[s] || s}</Tag> },
{ title: '源平台', dataIndex: 'source_platform_name', width: 90, render: (v) => v || '-' },
{ title: '店/商品', dataIndex: 'store_name', width: 150, ellipsis: true, render: (v) => v || '-' },
{ title: '最优', dataIndex: 'best_platform_name', width: 80, render: (v) => v || '-' },
{
title: '省',
key: 'saved',
width: 84,
render: (_, r) =>
r.saved_amount_cents == null ? '-' : (
<b style={{ color: r.saved_amount_cents > 0 ? '#3f8600' : '#999' }}>{yuan(r.saved_amount_cents)}</b>
),
},
{ title: '耗时', dataIndex: 'total_ms', width: 64, render: fmtMs },
{ title: '步', dataIndex: 'step_count', width: 48, render: (v) => v ?? '-' },
{ title: 'LLM', dataIndex: 'llm_call_count', width: 56, render: (v) => v ?? '-' },
{
title: '重试',
dataIndex: 'retry_count',
width: 50,
render: (v: number | null) => (v ? <span style={{ color: '#cf1322' }}>{v}</span> : v ?? '-'),
},
{
title: '机型/ROM',
key: 'device',
width: 150,
ellipsis: true,
render: (_, r) => [r.device_model, r.rom_name].filter(Boolean).join(' / ') || '-',
},
{ title: '时间', dataIndex: 'created_at', width: 150, render: (v: string) => formatWallTime(v) },
{
title: '操作',
key: 'op',
fixed: 'right',
width: 80,
render: (_, r) =>
r.trace_url ? (
<a href={r.trace_url} target="_blank" rel="noreferrer" onClick={(e) => e.stopPropagation()}>trace</a>
) : (
<span style={{ color: '#ccc' }}>-</span>
),
},
];
const platformResults =
(detail?.raw_payload?.platform_results as Record<string, unknown>[] | undefined) || [];
return (
<div>
<h2>(debug)</h2>
<Space style={{ marginBottom: 16 }} wrap>
<InputNumber placeholder="user_id" value={userId} onChange={setUserId} style={{ width: 110 }} />
<Input
placeholder="手机号前缀"
value={phone}
onChange={(e) => setPhone(e.target.value)}
onPressEnter={search}
allowClear
style={{ width: 150 }}
/>
<Select
placeholder="状态"
value={status}
onChange={setStatus}
allowClear
style={{ width: 110 }}
options={[
{ value: 'success', label: '成功' },
{ value: 'failed', label: '失败' },
{ value: 'cancelled', label: '已终止' },
]}
/>
<Button type="primary" onClick={search}></Button>
<Button onClick={reset}></Button>
</Space>
<Table
rowKey="id"
columns={columns}
dataSource={items}
loading={loading}
pagination={{
current: page,
pageSize,
total,
showSizeChanger: true,
showTotal: (t) => `${t}`,
onChange,
}}
scroll={{ x: 1320 }}
onRow={(r) => ({ onClick: () => openDetail(r.id), style: { cursor: 'pointer' } })}
/>
<Drawer title={detail ? `比价记录 #${detail.id}` : '详情'} width={780} open={detailLoading || !!detail} onClose={closeDetail}>
{detailLoading && <Spin />}
{detail && (
<Space direction="vertical" size="middle" style={{ width: '100%' }}>
<Descriptions size="small" column={2} bordered>
<Descriptions.Item label="用户">
{detail.phone || `#${detail.user_id}`}{detail.nickname ? `(${detail.nickname})` : ''}
</Descriptions.Item>
<Descriptions.Item label="状态"><Tag color={STATUS_COLOR[detail.status]}>{STATUS_LABEL[detail.status] || detail.status}</Tag></Descriptions.Item>
<Descriptions.Item label="业务">{detail.business_type}</Descriptions.Item>
<Descriptions.Item label="耗时">{fmtMs(detail.total_ms)}</Descriptions.Item>
<Descriptions.Item label="步数">{detail.step_count ?? '-'}</Descriptions.Item>
<Descriptions.Item label="LLM 次数/重试">{detail.llm_call_count ?? '-'} / {detail.retry_count ?? '-'}</Descriptions.Item>
<Descriptions.Item label="源平台">{detail.source_platform_name || '-'}{cents(detail.source_price_cents)}</Descriptions.Item>
<Descriptions.Item label="最优">{detail.best_platform_name || '-'}{cents(detail.best_price_cents)}</Descriptions.Item>
<Descriptions.Item label="省" span={2}>{cents(detail.saved_amount_cents)}{detail.is_source_best ? '(源平台最便宜)' : ''}</Descriptions.Item>
<Descriptions.Item label="店/商品" span={2}>{detail.store_name || '-'}</Descriptions.Item>
<Descriptions.Item label="结论文案" span={2}>{detail.information || '-'}</Descriptions.Item>
<Descriptions.Item label="trace" span={2}>
{detail.trace_url
? <a href={detail.trace_url} target="_blank" rel="noreferrer">{detail.trace_url}</a>
: <span style={{ color: '#999' }}>{detail.trace_id} trace_url</span>}
</Descriptions.Item>
<Descriptions.Item label="定位" span={2}>
{detail.longitude != null ? `${detail.longitude}, ${detail.latitude}` : '-'}
</Descriptions.Item>
<Descriptions.Item label="最优深链" span={2}>
{detail.best_deeplink
? <Typography.Text copyable={{ text: detail.best_deeplink }} style={{ fontSize: 12, wordBreak: 'break-all' }}>{detail.best_deeplink}</Typography.Text>
: '-'}
</Descriptions.Item>
</Descriptions>
<Card size="small" title="设备环境">
<Descriptions size="small" column={2}>
<Descriptions.Item label="机型">{detail.device_model || '-'}{detail.device_manufacturer || '-'}</Descriptions.Item>
<Descriptions.Item label="ROM">{[detail.rom_vendor, detail.rom_name, detail.rom_version].filter(Boolean).join(' ') || '-'}</Descriptions.Item>
<Descriptions.Item label="Android">{detail.android_version || '-'}SDK {detail.android_sdk ?? '-'}</Descriptions.Item>
<Descriptions.Item label="App 版本">{detail.app_version || '-'}{detail.app_version_code ?? '-'}</Descriptions.Item>
<Descriptions.Item label="源 App 版本" span={2}>{detail.source_app_version || '-'}</Descriptions.Item>
<Descriptions.Item label="device_id" span={2}>{detail.device_id || '-'}</Descriptions.Item>
</Descriptions>
</Card>
{((detail.items?.length ?? 0) > 0 || (detail.skipped_dish_names?.length ?? 0) > 0) && (
<Card size="small" title={`下单商品${detail.total_dish_count != null ? `(共 ${detail.total_dish_count}` : ''}`}>
{(detail.items?.length ?? 0) > 0 ? (
<ul style={{ margin: 0, paddingLeft: 18 }}>
{detail.items.map((it, i) => (
<li key={i}>
{it.name}{it.qty != null ? ` ×${it.qty}` : ''}
{it.specs?.length ? <span style={{ color: '#999' }}>{it.specs.join('/')}</span> : null}
</li>
))}
</ul>
) : <Typography.Text type="secondary"></Typography.Text>}
{(detail.skipped_dish_names?.length ?? 0) > 0 && (
<div style={{ marginTop: 8, color: '#cf1322' }}>
{detail.skipped_dish_count != null ? ` ${detail.skipped_dish_count} ` : ''}{detail.skipped_dish_names.join('、')}
</div>
)}
</Card>
)}
{platformResults.length > 0 && (
<Card size="small" title="逐平台结局(卡在哪一步)">
<Table
size="small"
rowKey={(_, i) => String(i)}
pagination={false}
dataSource={platformResults}
columns={[
{ title: '平台', dataIndex: 'platform_name', render: (v, r: Record<string, unknown>) => (v as string) || (r.platform_id as string) || '-' },
{ title: '结局', dataIndex: 'status', render: (s: string) => <Tag color={s === 'success' ? 'green' : 'orange'}>{STUCK_LABEL[s] || s || '-'}</Tag> },
{ title: '说明', dataIndex: 'reason', render: (v) => (v as string) || '-' },
]}
/>
</Card>
)}
{(detail.comparison_results?.length ?? 0) > 0 && (
<Collapse
size="small"
items={[{
key: 'cmp',
label: `逐平台对比(${detail.comparison_results.length}`,
children: <pre style={preStyle}>{JSON.stringify(detail.comparison_results, null, 2)}</pre>,
}]}
/>
)}
<Card size="small" title={`LLM 调用明细(${detail.llm_calls?.length ?? 0} 次)`}>
{detail.llm_calls && detail.llm_calls.length > 0 ? (
<Collapse
size="small"
items={detail.llm_calls.map((c, i) => ({
key: String(i),
label: (
<Space size={6} wrap>
<Tag color="blue">{c.scene || 'llm'}</Tag>
<span style={{ color: '#999', fontSize: 12 }}>{c.model}</span>
<span style={{ color: '#999', fontSize: 12 }}>{c.latency_ms ?? '-'}ms</span>
{c.usage?.total_tokens ? <span style={{ color: '#999', fontSize: 12 }}>{c.usage.total_tokens} tok</span> : null}
{c.error ? <Tag color="red">error</Tag> : null}
</Space>
),
children: (
<div>
{c.input_messages.map((m, j) => (
<div key={j} style={{ marginBottom: 8 }}>
<Tag>{m.role}</Tag>
<pre style={preStyle}>{pretty(m.content)}</pre>
</div>
))}
<div style={{ marginTop: 8 }}>
<Tag color="green">output</Tag>
<pre style={preStyle}>{c.error ? `【error】${c.error}` : pretty(c.output)}</pre>
</div>
</div>
),
}))}
/>
) : (
<Typography.Text type="secondary"> LLM / pricebot / LLM</Typography.Text>
)}
</Card>
<Collapse
size="small"
items={[{
key: 'raw',
label: '原始上报 raw_payload',
children: <pre style={preStyle}>{JSON.stringify(detail.raw_payload, null, 2)}</pre>,
}]}
/>
</Space>
)}
</Drawer>
</div>
);
}
+10 -3
View File
@@ -1,14 +1,14 @@
'use client';
import { useEffect, useState } from 'react';
import { Button, Card, Input, InputNumber, Space, Spin, Tag, Tooltip, message } from 'antd';
import { App, Button, Card, Input, InputNumber, Space, Spin, Switch, Tag, Tooltip } from 'antd';
import { api, errMsg } from '@/lib/api';
interface ConfigItem {
key: string;
label: string;
group: string;
type: string; // int / int_list / dict_str_int
type: string; // int / int_list / dict_str_int / bool
help: string | null;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
default: any;
@@ -28,6 +28,7 @@ function toEdit(item: ConfigItem): any {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function fromEdit(type: string, raw: any): any {
if (type === 'int') return Number(raw);
if (type === 'bool') return Boolean(raw);
if (type === 'int_list') {
return String(raw)
.split(',')
@@ -38,6 +39,7 @@ function fromEdit(type: string, raw: any): any {
}
export default function ConfigPage() {
const { message } = App.useApp();
const [items, setItems] = useState<ConfigItem[]>([]);
const [loading, setLoading] = useState(true);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -109,7 +111,12 @@ export default function ConfigPage() {
)}
</div>
<Space wrap>
{item.type === 'int' ? (
{item.type === 'bool' ? (
<Switch
checked={!!edits[item.key]}
onChange={(v) => setEdits({ ...edits, [item.key]: v })}
/>
) : item.type === 'int' ? (
<InputNumber
value={edits[item.key]}
onChange={(v) => setEdits({ ...edits, [item.key]: v })}
+331
View File
@@ -0,0 +1,331 @@
'use client';
// CPS 群对账详情:该群点击量/独立点击/复制/独立复制的天级 or 小时级变化折线图。
// 时间范围: 近 3/7/14/30 天(天级) 或 今日(小时级)。数据由后端补零成连续桶,折线不断裂。
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import dynamic from 'next/dynamic';
import type { ColumnsType } from 'antd/es/table';
import { Button, Card, Col, Empty, Row, Segmented, Space, Spin, Statistic, Table, message } from 'antd';
import { api, errMsg } from '@/lib/api';
import { formatUtcTime, yuan } from '@/lib/format';
// @ant-design/plots 依赖 DOM,关掉 SSR 仅在客户端渲染(否则 Next 预渲染报 document undefined)。
const Line = dynamic(() => import('@ant-design/plots').then((m) => m.Line), { ssr: false });
interface TsPoint {
label: string;
click_pv: number;
click_uv: number;
copy_pv: number;
copy_uv: number;
}
interface TsResp {
group_id: number;
group_name: string;
granularity: string;
points: TsPoint[];
}
// 按天大表格一行(订单侧字段对淘宝/京东群为 null → 显示 "-")
interface DailyRow {
date: string;
click_pv: number;
click_uv: number;
copy_pv: number;
order_count: number | null;
canceled_count: number | null;
gmv_cents: number | null;
est_commission_cents: number | null;
refund_profit_cents: number | null;
settled_commission_cents: number | null;
}
interface DailyResp {
group_name: string;
is_meituan: boolean;
days: number;
rows: DailyRow[];
}
// 群内微信用户(落地页授权拿到;nickname/headimgurl 仅 userinfo 授权后有)
interface WxUser {
openid: string;
nickname: string | null;
headimgurl: string | null;
first_seen: string;
visit_count: number;
copy_count: number;
}
const RANGES = [
{ label: '近 3 天', value: 'd3' },
{ label: '近 7 天', value: 'd7' },
{ label: '近 14 天', value: 'd14' },
{ label: '近 30 天', value: 'd30' },
{ label: '今日(按小时)', value: 'h' },
];
const METRICS: { key: keyof Omit<TsPoint, 'label'>; name: string }[] = [
{ key: 'click_pv', name: '点击量' },
{ key: 'click_uv', name: '独立点击' },
{ key: 'copy_pv', name: '复制次数' },
{ key: 'copy_uv', name: '独立复制' },
];
function rangeToQuery(r: string): string {
if (r === 'h') return 'granularity=hour';
const days: Record<string, number> = { d3: 3, d7: 7, d14: 14, d30: 30 };
return `granularity=day&days=${days[r] ?? 7}`;
}
// 大表格只按天:天级范围 → 天数;今日小时(h) → null(此时隐藏表格,小时维度看上面折线)
function rangeToDays(r: string): number | null {
return ({ d3: 3, d7: 7, d14: 14, d30: 30 } as Record<string, number>)[r] ?? null;
}
export default function GroupDetailPage() {
const params = useParams();
const router = useRouter();
const id = params.id as string;
const [range, setRange] = useState('d7');
const [data, setData] = useState<TsResp | null>(null);
const [loading, setLoading] = useState(false);
const load = useCallback(async () => {
setLoading(true);
try {
const r = await api.get<TsResp>(
`/admin/api/cps/groups/${id}/timeseries?${rangeToQuery(range)}`,
);
setData(r.data);
} catch (e) {
message.error(errMsg(e, '加载失败'));
} finally {
setLoading(false);
}
}, [id, range]);
useEffect(() => {
load();
}, [load]);
// 按天大表格(独立于折线;今日小时模式 tableDays=null 时不取、不显示)
const [daily, setDaily] = useState<DailyResp | null>(null);
const tableDays = rangeToDays(range);
const loadDaily = useCallback(async () => {
if (tableDays == null) return;
try {
const r = await api.get<DailyResp>(`/admin/api/cps/groups/${id}/daily?days=${tableDays}`);
setDaily(r.data);
} catch (e) {
message.error(errMsg(e, '明细加载失败'));
}
}, [id, tableDays]);
useEffect(() => {
loadDaily();
}, [loadDaily]);
// 群内微信用户(独立于时间范围,累计画像)
const [wxUsers, setWxUsers] = useState<WxUser[]>([]);
const loadWxUsers = useCallback(async () => {
try {
const r = await api.get<{ users: WxUser[] }>(`/admin/api/cps/groups/${id}/wx-users`);
setWxUsers(r.data.users || []);
} catch (e) {
message.error(errMsg(e, '用户列表加载失败'));
}
}, [id]);
useEffect(() => {
loadWxUsers();
}, [loadWxUsers]);
const points = useMemo(() => data?.points ?? [], [data]);
// 展平成「长表」给折线图:每个 (时间桶 × 指标) 一行,colorField 按指标分 4 条线。
const chartData = useMemo(
() =>
points.flatMap((p) =>
METRICS.map((m) => ({ label: p.label, 指标: m.name, value: Number(p[m.key]) })),
),
[points],
);
const totals = useMemo(
() => METRICS.map((m) => ({ name: m.name, sum: points.reduce((s, p) => s + Number(p[m.key]), 0) })),
[points],
);
const hasData = points.some((p) => p.click_pv || p.click_uv || p.copy_pv || p.copy_uv);
const config = {
data: chartData,
xField: 'label',
yField: 'value',
colorField: '指标',
height: 420,
legend: { color: { position: 'top' as const } },
// 折线带数据点(每桶一个);大小用 style.r 固定 —— sizeField/shapeField 是数据字段映射,
// 给常量会被 G2 当字段名找而失效。
point: { style: { r: 3 } },
// y 轴恒从 0 起、上限自适应取整;CPS 数据量小,固定 0 基线对比更直观。
scale: { y: { domainMin: 0, nice: true } },
axis: { x: { title: range === 'h' ? '小时' : '日期' }, y: { title: '次数' } },
interaction: { tooltip: { shared: true } },
};
const dailyColumns: ColumnsType<DailyRow> = [
{ title: '日期', dataIndex: 'date', width: 64, fixed: 'left' },
{ title: '点击', dataIndex: 'click_pv', width: 56 },
{ title: '独立', dataIndex: 'click_uv', width: 56 },
{ title: '复制', dataIndex: 'copy_pv', width: 56, render: (v: number) => v || '-' },
{
title: '点击→下单',
key: 'rate',
width: 86,
render: (_, r) =>
r.order_count == null
? '-'
: r.click_uv
? `${((r.order_count / r.click_uv) * 100).toFixed(0)}%`
: '-',
},
{ title: '有效单', dataIndex: 'order_count', width: 64, render: (v: number | null) => (v == null ? '-' : v) },
{
title: '取消/风控',
dataIndex: 'canceled_count',
width: 78,
render: (v: number | null) => (v == null ? '-' : v ? <span style={{ color: '#cf1322' }}>{v}</span> : 0),
},
{ title: '成交额', dataIndex: 'gmv_cents', width: 84, render: (v: number | null) => (v == null ? '-' : yuan(v)) },
{
title: '预估佣金',
dataIndex: 'est_commission_cents',
width: 84,
render: (v: number | null) => (v == null ? '-' : yuan(v)),
},
{
title: '退款佣金',
dataIndex: 'refund_profit_cents',
width: 84,
render: (v: number | null) =>
v == null ? '-' : v ? <span style={{ color: '#cf1322' }}>{yuan(v)}</span> : yuan(0),
},
{
title: '净佣金',
key: 'net',
width: 84,
render: (_, r) =>
r.est_commission_cents == null ? (
'-'
) : (
<b>{yuan(r.est_commission_cents - (r.refund_profit_cents || 0))}</b>
),
},
{
title: '结算佣金',
dataIndex: 'settled_commission_cents',
width: 84,
render: (v: number | null) => (v == null ? '-' : <span style={{ color: '#3f8600' }}>{yuan(v)}</span>),
},
];
const wxColumns: ColumnsType<WxUser> = [
{
title: '用户',
key: 'user',
render: (_, u) => (
<Space>
{u.headimgurl ? (
<img
src={u.headimgurl}
alt=""
style={{ width: 32, height: 32, borderRadius: '50%', objectFit: 'cover' }}
/>
) : (
<span
style={{ width: 32, height: 32, borderRadius: '50%', background: '#f0f0f0', display: 'inline-block' }}
/>
)}
<span>{u.nickname || '(未授权昵称)'}</span>
</Space>
),
},
{
title: '领券次数',
dataIndex: 'copy_count',
width: 90,
sorter: (a, b) => a.copy_count - b.copy_count,
render: (v: number) => (v ? <b style={{ color: '#ff4d4f' }}>{v}</b> : 0),
},
{ title: '点击次数', dataIndex: 'visit_count', width: 90 },
{ title: '首次进入', dataIndex: 'first_seen', width: 160, render: (v: string) => formatUtcTime(v) },
];
return (
<div>
<Space style={{ marginBottom: 16 }} align="center" wrap>
<Button onClick={() => router.push('/cps')}> </Button>
<span style={{ fontSize: 18, fontWeight: 600 }}>
{data?.group_name ?? ''}
</span>
</Space>
<Card style={{ marginBottom: 16 }}>
<Segmented options={RANGES} value={range} onChange={(v) => setRange(v as string)} />
</Card>
<Row gutter={16} style={{ marginBottom: 16 }}>
{totals.map((t) => (
<Col key={t.name} xs={12} sm={6}>
<Card size="small">
<Statistic title={`${t.name}(合计)`} value={t.sum} />
</Card>
</Col>
))}
</Row>
<Card>
<Spin spinning={loading}>
{hasData ? (
<Line {...config} />
) : (
<Empty
style={{ padding: '80px 0' }}
description={loading ? '加载中…' : '该时间范围内暂无点击数据'}
/>
)}
</Spin>
</Card>
{tableDays != null && (
<Card title={`每日明细(近 ${tableDays} 天)`} style={{ marginTop: 16 }}>
{daily && !daily.is_meituan && (
<div style={{ fontSize: 12, color: '#999', marginBottom: 8 }}>
,/,-
</div>
)}
<Table<DailyRow>
rowKey="date"
size="small"
columns={dailyColumns}
dataSource={daily?.rows ?? []}
pagination={false}
scroll={{ x: 900 }}
/>
</Card>
)}
<Card title={`群内微信用户(${wxUsers.length})`} style={{ marginTop: 16 }}>
<div style={{ fontSize: 12, color: '#999', marginBottom: 8 }}>
= ;/
</div>
<Table<WxUser>
rowKey="openid"
size="small"
columns={wxColumns}
dataSource={wxUsers}
pagination={false}
scroll={{ x: 560 }}
locale={{ emptyText: '暂无授权用户' }}
/>
</Card>
</div>
);
}
+400 -156
View File
@@ -1,16 +1,19 @@
'use client';
// CPS 优惠券分发与对账(当前仅美团)。单页 Tabs:对账统计 / 群管理 / 活动管理 / 订单明细
// 群管理生成带 sid 的券链接 → 发群 → 对账按 sid 拉回订单/佣金归群统计
// CPS 优惠券分发与对账。平台:美团(actId+sid,完整对账) / 淘宝(淘口令) / 京东(链接)
// 淘宝/京东无 API → 只统计点击,对账字段显示 "-"。单页 Tabs:对账统计/群管理/活动管理/订单明细
import { useCallback, useEffect, useState } from 'react';
import Link from 'next/link';
import type { ColumnsType } from 'antd/es/table';
import {
Button,
Card,
Checkbox,
Form,
Input,
InputNumber,
Modal,
Popconfirm,
Select,
Space,
Statistic,
@@ -18,6 +21,7 @@ import {
Tabs,
Tag,
Typography,
Upload,
message,
} from 'antd';
import { api, errMsg } from '@/lib/api';
@@ -30,7 +34,7 @@ import type {
CpsGroupStat,
CpsOrder,
CpsReconcileResult,
CpsReferralLink,
CpsReferralLinks,
CpsStats,
} from '@/lib/types';
@@ -42,21 +46,30 @@ const MT_STATUS: Record<string, { text: string; color: string }> = {
'6': { text: '已结算', color: 'green' },
};
const LINK_TYPE_NAME: Record<string, string> = {
'1': 'H5 长链',
'2': '短链(微信可发)',
'3': 'deeplink(唤起 App)',
};
const PLATFORM_LABEL: Record<string, string> = { meituan: '美团', taobao: '淘宝', jd: '京东' };
const PLATFORM_COLOR: Record<string, string> = { meituan: 'gold', taobao: 'volcano', jd: 'red' };
const PLATFORM_OPTIONS = [
{ label: '美团', value: 'meituan' },
{ label: '淘宝', value: 'taobao' },
{ label: '京东', value: 'jd' },
];
const fmtRate = (r: string | null) => (r ? `${Number(r) / 100}%` : '-');
const DASH = <span style={{ color: '#bbb' }}>-</span>;
const platformTags = (ps: string[] | undefined) =>
(ps || []).map((p) => (
<Tag key={p} color={PLATFORM_COLOR[p]} style={{ marginInlineEnd: 4 }}>
{PLATFORM_LABEL[p] || p}
</Tag>
));
export default function CpsPage() {
return (
<div>
<h2>CPS </h2>
<Typography.Paragraph type="secondary" style={{ marginTop: -8 }}>
sid: sid , sid
()
(actId + sid,/) / () / () API,
<b></b>,- /c/xxx
</Typography.Paragraph>
<Tabs
defaultActiveKey="stats"
@@ -113,43 +126,62 @@ function StatsTab() {
};
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: 'name',
width: 140,
ellipsis: true,
fixed: 'left',
render: (v: string, r) =>
r.group_id ? <Link href={`/cps/groups/${r.group_id}`}>{v}</Link> : v,
},
{ title: '平台', key: 'platforms', width: 130, render: (_, r) => platformTags(r.platforms) },
{ title: '人数', dataIndex: 'member_count', width: 64, render: (v) => v ?? '-' },
{ title: '点击', dataIndex: 'click_pv', width: 64 },
{ title: '独立', dataIndex: 'click_uv', width: 64 },
{
title: '复制',
dataIndex: 'copy_pv',
width: 64,
render: (v: number) => (v ? v : DASH),
},
{
title: '有效单',
dataIndex: 'order_count',
width: 70,
render: (v: number | null) => (v == null ? DASH : v),
},
{ 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),
width: 80,
render: (v: number | null) => (v == null ? DASH : v ? <span style={{ color: '#cf1322' }}>{v}</span> : 0),
},
{
title: '点击→下单',
key: 'rate',
width: 90,
width: 88,
render: (_, r) =>
r.click_uv ? `${((r.order_count / r.click_uv) * 100).toFixed(0)}%` : '-',
r.order_count == null ? DASH : r.click_uv ? `${((r.order_count / r.click_uv) * 100).toFixed(0)}%` : '-',
},
{
title: '成交额',
dataIndex: 'gmv_cents',
width: 96,
render: (v: number | null) => (v == null ? DASH : yuan(v)),
},
{ 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>,
width: 100,
sorter: (a, b) => (a.est_commission_cents || 0) - (b.est_commission_cents || 0),
render: (v: number | null) => (v == null ? DASH : <b>{yuan(v)}</b>),
},
{
title: '已结算佣金',
dataIndex: 'settled_commission_cents',
width: 110,
render: (v: number) => <span style={{ color: '#3f8600' }}>{yuan(v)}</span>,
width: 100,
render: (v: number | null) => (v == null ? DASH : <span style={{ color: '#3f8600' }}>{yuan(v)}</span>),
},
];
@@ -172,14 +204,12 @@ function StatsTab() {
()
</Button>
)}
<Typography.Text type="secondary">
,
</Typography.Text>
<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} />
<Statistic title="有效订单数(美团)" value={data?.total_order_count ?? 0} />
</Card>
<Card size="small">
<Statistic
@@ -206,7 +236,7 @@ function StatsTab() {
dataSource={data?.groups ?? []}
loading={loading}
pagination={false}
scroll={{ x: 1120 }}
scroll={{ x: 1200 }}
/>
</div>
);
@@ -222,37 +252,58 @@ function GroupsTab() {
);
const canManage = canDo(['operator']);
const [editing, setEditing] = useState<CpsGroup | null>(null); // null=不开,{} 新建用单独标志
const [editing, setEditing] = useState<CpsGroup | null>(null);
const [createOpen, setCreateOpen] = useState(false);
const [linkGroup, setLinkGroup] = useState<CpsGroup | null>(null);
const delGroup = async (g: CpsGroup) => {
try {
await api.delete(`/admin/api/cps/groups/${g.id}`);
message.success('已删除群');
reload();
} catch (e) {
message.error(errMsg(e));
}
};
const columns: ColumnsType<CpsGroup> = [
{ title: 'ID', dataIndex: 'id', width: 70 },
{ title: '群名', dataIndex: 'name', width: 180, ellipsis: true },
{ title: 'ID', dataIndex: 'id', width: 60 },
{ title: '群名', dataIndex: 'name', width: 160, ellipsis: true },
{ title: '平台', key: 'platforms', width: 140, render: (_, g) => platformTags(g.platforms) },
{
title: 'sid',
dataIndex: 'sid',
width: 150,
render: (v: string) => <Typography.Text copyable>{v}</Typography.Text>,
width: 130,
render: (v: string | null) => (v ? <Typography.Text copyable>{v}</Typography.Text> : DASH),
},
{ title: '人数', dataIndex: 'member_count', width: 80, render: (v) => v ?? '-' },
{ title: '人数', dataIndex: 'member_count', width: 70, render: (v) => v ?? '-' },
{
title: '状态',
dataIndex: 'status',
width: 90,
width: 80,
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,
width: 200,
render: (_, g) => (
<Space onClick={(e) => e.stopPropagation()}>
{canManage && <a onClick={() => setLinkGroup(g)}></a>}
{canManage && <a onClick={() => setEditing(g)}></a>}
{canManage && (
<Popconfirm
title="删除这个群?"
description="已发出的链接仍可用,但该群不再计入统计。"
okText="删除"
okButtonProps={{ danger: true }}
onConfirm={() => delGroup(g)}
>
<a style={{ color: '#cf1322' }}></a>
</Popconfirm>
)}
</Space>
),
},
@@ -272,9 +323,7 @@ function GroupsTab() {
<Button type="primary" onClick={() => setApplied({ keyword: keyword || undefined })}>
</Button>
{canManage && (
<Button onClick={() => setCreateOpen(true)}></Button>
)}
{canManage && <Button onClick={() => setCreateOpen(true)}></Button>}
</Space>
<Table
@@ -290,21 +339,11 @@ function GroupsTab() {
showTotal: (t) => `${t} 个群`,
onChange,
}}
scroll={{ x: 1050 }}
scroll={{ x: 1090 }}
/>
<GroupFormModal
open={createOpen}
group={null}
onClose={() => setCreateOpen(false)}
onDone={reload}
/>
<GroupFormModal
open={!!editing}
group={editing}
onClose={() => setEditing(null)}
onDone={reload}
/>
<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>
);
@@ -323,18 +362,22 @@ function GroupFormModal({
}) {
const [form] = Form.useForm();
const isEdit = !!group;
const watchPlatforms = (Form.useWatch('platforms', form) as string[] | undefined) || [];
const hasMeituan = watchPlatforms.includes('meituan');
useEffect(() => {
if (open) {
if (group) {
form.setFieldsValue({
name: group.name,
platforms: group.platforms,
member_count: group.member_count,
remark: group.remark,
status: group.status,
});
} else {
form.resetFields();
form.setFieldsValue({ platforms: ['meituan'] });
}
}
}, [open, group, form]);
@@ -357,26 +400,32 @@ function GroupFormModal({
};
return (
<Modal
title={isEdit ? '编辑群' : '新建群'}
open={open}
onOk={submit}
onCancel={onClose}
destroyOnHidden
>
<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="platforms"
label="这个群发哪些平台的券(可多选)"
rules={[{ required: true, message: '至少选一个平台' }]}
>
<Checkbox.Group options={PLATFORM_OPTIONS} />
</Form.Item>
{hasMeituan && !isEdit && (
<Form.Item
name="sid"
label="sid(渠道标识,留空自动生成 g+ID)"
label="美团 sid(渠道标识,留空自动生成 g+ID)"
rules={[{ pattern: /^[A-Za-z0-9]+$/, message: '仅字母和数字' }]}
>
<Input placeholder="留空自动生成;或自定义如 baoma1" maxLength={64} />
</Form.Item>
)}
{hasMeituan && isEdit && (
<Typography.Text type="secondary" style={{ fontSize: 12, display: 'block', marginBottom: 12 }}>
sid:{group?.sid || '(无,保存后如缺会在生成美团链接时报错)'}
</Typography.Text>
)}
<Form.Item name="member_count" label="群人数(用于估算转化率)">
<InputNumber style={{ width: '100%' }} min={0} placeholder="如 200" />
</Form.Item>
@@ -400,13 +449,13 @@ function GroupFormModal({
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 [activityIds, setActivityIds] = useState<number[]>([]);
const [result, setResult] = useState<CpsReferralLinks | null>(null);
const [loading, setLoading] = useState(false);
useEffect(() => {
if (!group) {
setActivityId(undefined);
setActivityIds([]);
setResult(null);
return;
}
@@ -416,16 +465,19 @@ function ReferralLinkModal({ group, onClose }: { group: CpsGroup | null; onClose
.catch((e) => message.error(errMsg(e)));
}, [group]);
// 只列群平台范围内的活动
const groupActivities = activities.filter((a) => (group?.platforms || []).includes(a.platform));
const generate = async () => {
if (!group || !activityId) {
message.warning('请选择活动');
if (!group || !activityIds.length) {
message.warning('请勾选要生成的活动');
return;
}
setLoading(true);
try {
const resp = await api.post<CpsReferralLink>('/admin/api/cps/referral-link', {
const resp = await api.post<CpsReferralLinks>('/admin/api/cps/referral-links', {
group_id: group.id,
activity_id: activityId,
activity_ids: activityIds,
});
setResult(resp.data);
} catch (e) {
@@ -437,68 +489,68 @@ function ReferralLinkModal({ group, onClose }: { group: CpsGroup | null; onClose
return (
<Modal
title={`生成链接 - ${group?.name ?? ''}(sid=${group?.sid ?? ''})`}
title={`生成发群链接 - ${group?.name ?? ''}`}
open={!!group}
onCancel={onClose}
onOk={generate}
okText="生成"
confirmLoading={loading}
destroyOnHidden
width={640}
width={660}
>
<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>
<Typography.Paragraph type="secondary" style={{ fontSize: 12 }}>
,;
</Typography.Paragraph>
{groupActivities.length === 0 ? (
<Typography.Text type="warning">
({(group?.platforms || []).map((p) => PLATFORM_LABEL[p]).join('/')}),
</Typography.Text>
) : (
<Checkbox.Group
value={activityIds}
onChange={(v) => setActivityIds(v as number[])}
style={{ width: '100%' }}
>
<Space direction="vertical" style={{ width: '100%' }}>
{groupActivities.map((a) => (
<Checkbox key={a.id} value={a.id}>
<Tag color={PLATFORM_COLOR[a.platform]}>{PLATFORM_LABEL[a.platform]}</Tag>
{a.name}
{a.act_id ? <span style={{ color: '#999' }}> (actId={a.act_id})</span> : null}
</Checkbox>
))}
</Space>
</Checkbox.Group>
)}
{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' }}
<div style={{ marginTop: 16 }}>
<Typography.Text strong>👇 ():</Typography.Text>
{result.results.map((item) => (
<div
key={item.code}
style={{
marginTop: 8,
padding: 10,
background: '#f6ffed',
border: '1px solid #b7eb8f',
borderRadius: 6,
}}
>
{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}
<div style={{ marginBottom: 4 }}>
<Tag color={PLATFORM_COLOR[item.platform]}>{PLATFORM_LABEL[item.platform]}</Tag>
<span style={{ fontSize: 13 }}>{item.activity_name}</span>
</div>
<Typography.Text copyable={{ text: item.redirect_url }} style={{ fontSize: 14, wordBreak: 'break-all' }}>
{item.redirect_url}
</Typography.Text>
</div>
))}
{result.results.some((i) => !i.redirect_url.startsWith('http')) && (
<Typography.Text type="warning" style={{ fontSize: 12 }}>
部分为相对路径:后端未配 CPS_REDIRECT_BASE,
</Typography.Text>
)}
</div>
)}
</Modal>
@@ -513,31 +565,82 @@ function ActivitiesTab() {
);
const canManage = canDo(['operator']);
const [createOpen, setCreateOpen] = useState(false);
const [editing, setEditing] = useState<CpsActivity | null>(null);
const delActivity = async (a: CpsActivity) => {
try {
await api.delete(`/admin/api/cps/activities/${a.id}`);
message.success('已删除活动');
reload();
} catch (e) {
message.error(errMsg(e));
}
};
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: 'ID', dataIndex: 'id', width: 60 },
{
title: 'actId',
title: '平台',
dataIndex: 'platform',
width: 80,
render: (v: string) => <Tag color={PLATFORM_COLOR[v]}>{PLATFORM_LABEL[v] || v}</Tag>,
},
{ title: '活动名', dataIndex: 'name', width: 180, ellipsis: true },
{
title: 'actId(美团)',
dataIndex: 'act_id',
width: 120,
width: 110,
render: (v: string | null) => v || '-',
},
{
title: 'productViewSign',
dataIndex: 'product_view_sign',
width: 160,
title: '淘口令/链接',
dataIndex: 'payload',
width: 240,
ellipsis: true,
render: (v: string | null) => v || '-',
},
{
title: '落地页图',
dataIndex: 'image_url',
width: 80,
render: (v: string | null) =>
v ? (
<img src={v} alt="" style={{ width: 36, height: 46, objectFit: 'cover', borderRadius: 4 }} />
) : (
'-'
),
},
{
title: '状态',
dataIndex: 'status',
width: 90,
width: 80,
render: (s: string) => <Tag color={s === 'active' ? 'green' : 'default'}>{s}</Tag>,
},
{ title: '创建时间', dataIndex: 'created_at', width: 150, render: (v: string) => formatUtcTime(v) },
...(canManage
? ([
{
title: '操作',
key: 'op',
fixed: 'right' as const,
width: 120,
render: (_: unknown, a: CpsActivity) => (
<Space>
<a onClick={() => setEditing(a)}></a>
<Popconfirm
title="删除这个活动?"
description="已生成的链接仍可用;淘宝活动删除后其落地页改用默认图。"
okText="删除"
okButtonProps={{ danger: true }}
onConfirm={() => delActivity(a)}
>
<a style={{ color: '#cf1322' }}></a>
</Popconfirm>
</Space>
),
},
] as ColumnsType<CpsActivity>)
: []),
];
return (
@@ -562,37 +665,141 @@ function ActivitiesTab() {
showTotal: (t) => `${t} 个活动`,
onChange,
}}
scroll={{ x: 1000 }}
scroll={{ x: 1200 }}
/>
<ActivityFormModal open={createOpen} onClose={() => setCreateOpen(false)} onDone={reload} />
<ActivityFormModal open={createOpen} activity={null} onClose={() => setCreateOpen(false)} onDone={reload} />
<ActivityFormModal open={!!editing} activity={editing} onClose={() => setEditing(null)} onDone={reload} />
</div>
);
}
// 淘宝活动落地页图选择器:上传新图 或 点选已有图。受控组件(value = image_url 绝对 URL)。
function ImagePicker({ value, onChange }: { value?: string | null; onChange?: (v: string) => void }) {
const [existing, setExisting] = useState<string[]>([]);
const [uploading, setUploading] = useState(false);
useEffect(() => {
api
.get<{ images: string[] }>('/admin/api/cps/activity-images')
.then((r) => setExisting(r.data.images || []))
.catch(() => {});
}, []);
const upload = async (file: File) => {
setUploading(true);
try {
const fd = new FormData();
fd.append('file', file);
const r = await api.post<{ url: string }>('/admin/api/cps/upload-image', fd);
onChange?.(r.data.url);
setExisting((prev) => (prev.includes(r.data.url) ? prev : [r.data.url, ...prev]));
message.success('图片已上传');
} catch (e) {
message.error(errMsg(e, '上传失败'));
} finally {
setUploading(false);
}
};
const thumb = (u: string, w: number, selected: boolean) => (
<img
key={u}
src={u}
alt="落地页图"
onClick={() => onChange?.(u)}
style={{
width: w,
height: Math.round(w * 1.27),
objectFit: 'cover',
borderRadius: 6,
cursor: 'pointer',
border: selected ? '2px solid #ff4d4f' : '2px solid #f0f0f0',
}}
/>
);
return (
<div>
<Upload
accept="image/*"
showUploadList={false}
beforeUpload={(file) => {
upload(file);
return false; // 阻止 antd 默认上传,走我们自己的端点
}}
>
<Button loading={uploading}></Button>
</Upload>
{value && (
<div style={{ marginTop: 8, display: 'flex', alignItems: 'center', gap: 8 }}>
<span style={{ fontSize: 12, color: '#999' }}>:</span>
{thumb(value, 90, true)}
</div>
)}
{existing.length > 0 && (
<div style={{ marginTop: 10 }}>
<div style={{ fontSize: 12, color: '#999', marginBottom: 6 }}>:</div>
<Space wrap>{existing.map((u) => thumb(u, 56, u === value))}</Space>
</div>
)}
</div>
);
}
function ActivityFormModal({
open,
activity,
onClose,
onDone,
}: {
open: boolean;
activity: CpsActivity | null;
onClose: () => void;
onDone: () => void;
}) {
const [form] = Form.useForm();
const isEdit = !!activity;
const platform = (Form.useWatch('platform', form) as string | undefined) || 'meituan';
useEffect(() => {
if (open) form.resetFields();
}, [open, form]);
if (open) {
if (activity) {
form.setFieldsValue({
name: activity.name,
platform: activity.platform,
act_id: activity.act_id,
product_view_sign: activity.product_view_sign,
payload: activity.payload,
image_url: activity.image_url,
remark: activity.remark,
status: activity.status,
});
} else {
form.resetFields();
form.setFieldsValue({ platform: 'meituan' });
}
}
}, [open, activity, form]);
const submit = async () => {
const v = await form.validateFields();
if (!v.act_id && !v.product_view_sign) {
message.warning('actId 与 productViewSign 至少填一个');
if (v.platform === 'meituan') {
if (!v.act_id && !v.product_view_sign) {
message.warning('美团活动:actId 与 productViewSign 至少填一个');
return;
}
} else if (!v.payload) {
message.warning(v.platform === 'taobao' ? '请填淘口令' : '请填京东链接');
return;
}
try {
await api.post('/admin/api/cps/activities', v);
message.success('已新建活动');
if (isEdit && activity) {
await api.patch(`/admin/api/cps/activities/${activity.id}`, v);
message.success('已更新活动');
} else {
await api.post('/admin/api/cps/activities', v);
message.success('已新建活动');
}
onClose();
onDone();
} catch (e) {
@@ -601,29 +808,66 @@ function ActivityFormModal({
};
return (
<Modal title="新建活动" open={open} onOk={submit} onCancel={onClose} destroyOnHidden>
<Modal title={isEdit ? '编辑活动' : '新建活动'} 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 name="platform" label="平台" rules={[{ required: true }]}>
<Select options={PLATFORM_OPTIONS} />
</Form.Item>
{platform === 'meituan' && (
<>
<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>
</>
)}
{platform === 'taobao' && (
<>
<Form.Item
name="payload"
label="淘口令(整段,运营从淘宝联盟复制,落地页原样复制给用户)"
rules={[{ required: true, message: '请填淘口令' }]}
>
<Input.TextArea rows={4} placeholder="如:8¥abcXYZ¥ https://m.tb.cn/h.xxx 长按复制本条..." maxLength={4096} />
</Form.Item>
<Form.Item
name="image_url"
label="落地页图(用户点链接后看到的页面主图,上传新图或选已有)"
rules={[{ required: true, message: '请上传或选择落地页图' }]}
>
<ImagePicker />
</Form.Item>
</>
)}
{platform === 'jd' && (
<Form.Item
name="payload"
label="京东推广链接(落地页 302 跳到它)"
rules={[{ required: true, message: '请填京东链接' }]}
>
<Input placeholder="如:https://u.jd.com/xxxxxx" maxLength={1024} />
</Form.Item>
)}
<Form.Item name="remark" label="备注">
<Input.TextArea rows={2} maxLength={256} />
</Form.Item>
{isEdit && (
<Form.Item name="status" label="状态">
<Select
options={[
{ value: 'active', label: '启用(active)' },
{ value: 'archived', label: '归档(archived)' },
]}
/>
</Form.Item>
)}
</Form>
</Modal>
);
@@ -2,6 +2,7 @@
import { useEffect, useState } from 'react';
import {
App,
Button,
Form,
Input,
@@ -12,7 +13,6 @@ import {
Spin,
Switch,
Table,
message,
} from 'antd';
import { api, errMsg } from '@/lib/api';
@@ -51,6 +51,7 @@ const yuan = (cents: number) => (cents / 100).toFixed(2);
/** 首页轮播「种子」管理(真实记录不足时的兜底假数据,现为「生成规则」)。「数据大盘」页的一个区块。 */
export default function HomeMarqueeSeeds() {
const { message } = App.useApp();
const [seeds, setSeeds] = useState<Seed[]>([]);
const [loading, setLoading] = useState(true);
const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]); // 批量操作选中行
+3 -3
View File
@@ -2,12 +2,12 @@
import { useEffect, useState } from 'react';
import {
App,
Button,
Card,
Checkbox,
Col,
InputNumber,
Modal,
Popconfirm,
Radio,
Row,
@@ -16,7 +16,6 @@ import {
Spin,
Tag,
Tooltip,
message,
} from 'antd';
import { api, errMsg } from '@/lib/api';
import { formatUtcTime } from '@/lib/format';
@@ -249,6 +248,7 @@ function buildBody(metric: string, e: Edit, immediate: boolean): Record<string,
/** 首页三门面数字(帮助用户/完成比价/累计节省)的展示模式配置。作为「数据大盘」页的一个区块。 */
export default function HomeStatsConfig() {
const { message, modal } = App.useApp();
const [items, setItems] = useState<StatItem[]>([]);
const [loading, setLoading] = useState(true);
const [edits, setEdits] = useState<Record<string, Edit>>({});
@@ -321,7 +321,7 @@ export default function HomeStatsConfig() {
// 智能校验:按下后三者大概会呈现的关系是否合理,不合理则弹窗劝阻、确认才提交。
const rel = checkRelations(items, edits);
if (rel && rel.warnings.length > 0) {
Modal.confirm({
modal.confirm({
title: '数据关系校验',
width: 480,
okText: '仍要这样设置',
+3 -2
View File
@@ -1,7 +1,7 @@
'use client';
import type { ColumnsType } from 'antd/es/table';
import { Button, Modal, Popconfirm, Space, Table, message } from 'antd';
import { App, Button, Popconfirm, Space, Table } from 'antd';
import { api, errMsg } from '@/lib/api';
import { canDo } from '@/lib/auth';
import { formatUtcTime } from '@/lib/format';
@@ -13,6 +13,7 @@ const dt = (v: string) => formatUtcTime(v);
const EMPTY: Record<string, unknown> = {};
export default function DevicesPage() {
const { message, modal } = App.useApp();
// 后端按设备聚合、全量返回(next_cursor 恒 null),故无筛选/加载更多。
const { items, loading, reload } = useCursorList<DeviceOnboardingItem>(
'/admin/api/onboarding/devices',
@@ -31,7 +32,7 @@ export default function DevicesPage() {
};
const resetAll = () => {
Modal.confirm({
modal.confirm({
title: '确认全部重设新手引导?',
content:
'清空所有设备的引导完成记录,库里所有用户下次打开 App 都会重走一遍新手引导。此操作不可逆。',
@@ -0,0 +1,273 @@
'use client';
import { useEffect, useState } from 'react';
import { Button, Card, Image, Input, 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 { FeedbackQrConfig as QrConfig } from '@/lib/types';
const { Text } = Typography;
const ACCEPT = ['image/jpeg', 'image/png', 'image/webp'];
/** 反馈页「加群二维码」卡配置。改完 App 意见反馈页下次进入即同步。「反馈工单」页的一个区块。 */
export default function FeedbackQrConfig() {
const [cfg, setCfg] = useState<QrConfig | null>(null);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [uploading, setUploading] = useState(false);
// 本地编辑态(文案 + 开关),保存时一次性 PATCH
const [enabled, setEnabled] = useState(true);
const [title, setTitle] = useState('');
const [groupName, setGroupName] = useState('');
const [subtitle, setSubtitle] = useState('');
const canEdit = canDo(['operator']);
const sync = (c: QrConfig) => {
setCfg(c);
setEnabled(c.enabled);
setTitle(c.title);
setGroupName(c.group_name);
setSubtitle(c.subtitle);
};
const load = async () => {
setLoading(true);
try {
const { data } = await api.get<QrConfig>('/admin/api/feedback-config');
sync(data);
} finally {
setLoading(false);
}
};
useEffect(() => {
load();
}, []);
const save = async () => {
if (!title.trim() || !groupName.trim() || !subtitle.trim()) {
message.warning('三行文案都需填写');
return;
}
setSaving(true);
try {
const { data } = await api.patch<QrConfig>('/admin/api/feedback-config', {
enabled,
title: title.trim(),
group_name: groupName.trim(),
subtitle: subtitle.trim(),
});
sync(data);
message.success('已保存,App 反馈页下次进入即可见');
} catch (e) {
message.error(errMsg(e));
} finally {
setSaving(false);
}
};
// antd Upload:beforeUpload 里自行 POST(multipart),返回 false 阻止其默认上传。
const beforeUpload = (file: File) => {
if (!ACCEPT.includes(file.type)) {
message.error('仅支持 JPEG / PNG / WebP 图片');
return Upload.LIST_IGNORE;
}
if (file.size > 5 * 1024 * 1024) {
message.error('图片不能超过 5MB');
return Upload.LIST_IGNORE;
}
void uploadImage(file);
return false;
};
const uploadImage = async (file: File) => {
const form = new FormData();
form.append('file', file);
setUploading(true);
try {
const { data } = await api.post<QrConfig>('/admin/api/feedback-config/image', form);
sync(data);
message.success('二维码已更新,App 反馈页下次进入即可见');
} catch (e) {
message.error(errMsg(e));
} finally {
setUploading(false);
}
};
const removeImage = async () => {
setUploading(true);
try {
const { data } = await api.delete<QrConfig>('/admin/api/feedback-config/image');
sync(data);
message.success('已移除二维码,App 将显示本地兜底图');
} catch (e) {
message.error(errMsg(e));
} finally {
setUploading(false);
}
};
return (
<Card
size="small"
title="反馈页二维码卡(App 意见反馈页底部)"
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 }}>
App
</p>
{loading || !cfg ? (
<Spin style={{ display: 'block', margin: '24px 0' }} />
) : (
<Space align="start" size={32} wrap>
{/* 左:所见即所得预览(对齐 App 卡片布局) */}
<div>
<Text type="secondary" style={{ fontSize: 12 }}>
App
</Text>
<div
style={{
marginTop: 8,
width: 320,
display: 'flex',
gap: 14,
alignItems: 'center',
padding: 14,
border: '1px solid #f0f0f0',
borderRadius: 14,
boxShadow: '0 1px 4px rgba(0,0,0,0.06)',
opacity: enabled ? 1 : 0.4,
}}
>
{cfg.image_url ? (
<Image
src={mediaUrl(cfg.image_url)}
width={88}
height={88}
style={{ objectFit: 'cover', borderRadius: 8, border: '1px solid #f0f0f0' }}
/>
) : (
<div
style={{
width: 88,
height: 88,
borderRadius: 8,
border: '1px dashed #d9d9d9',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
color: '#bbb',
fontSize: 12,
textAlign: 'center',
flexShrink: 0,
}}
>
</div>
)}
<div style={{ fontSize: 13, color: '#1a1a1a', lineHeight: '21px' }}>
<div>{title || '(标题)'}</div>
<div>
<b>{groupName || '群名'}</b>
</div>
<div>{subtitle || '(标语)'}</div>
</div>
</div>
{!enabled && (
<div style={{ color: '#fa8c16', fontSize: 12, marginTop: 6 }}>
App
</div>
)}
</div>
{/* 右:编辑控件 */}
<Space direction="vertical" size="middle" style={{ minWidth: 320 }}>
<Space>
<span></span>
<Switch checked={enabled} disabled={!canEdit} onChange={setEnabled} />
{!enabled && <Tag color="orange"></Tag>}
</Space>
<Space wrap>
<Upload accept="image/*" showUploadList={false} beforeUpload={beforeUpload} disabled={!canEdit}>
<Button icon={<UploadOutlined />} loading={uploading} disabled={!canEdit}>
{cfg.image_url ? '更换二维码' : '上传二维码'}
</Button>
</Upload>
{cfg.image_url && (
<Button
icon={<DeleteOutlined />}
danger
loading={uploading}
disabled={!canEdit}
onClick={removeImage}
>
</Button>
)}
<Text type="secondary" style={{ fontSize: 12 }}>
JPEG/PNG/WebP5MB
</Text>
</Space>
<div>
<Text type="secondary" style={{ fontSize: 12 }}>
</Text>
<Input
value={title}
maxLength={40}
disabled={!canEdit}
onChange={(e) => setTitle(e.target.value)}
placeholder="如:长按图片保存二维码"
/>
</div>
<div>
<Text type="secondary" style={{ fontSize: 12 }}>
App
</Text>
<Input
value={groupName}
maxLength={40}
disabled={!canEdit}
onChange={(e) => setGroupName(e.target.value)}
placeholder="如:傻瓜比价官方群"
/>
</div>
<div>
<Text type="secondary" style={{ fontSize: 12 }}>
</Text>
<Input
value={subtitle}
maxLength={60}
disabled={!canEdit}
onChange={(e) => setSubtitle(e.target.value)}
placeholder="如:一起唠嗑共创、解锁新玩法"
/>
</div>
<Button type="primary" loading={saving} disabled={!canEdit} onClick={save}>
/
</Button>
{!canEdit && <Text type="secondary"> operator / super_admin </Text>}
</Space>
</Space>
)}
</Card>
);
}
+5 -3
View File
@@ -5,17 +5,16 @@ import type { Key } from 'react';
import type { ColumnsType } from 'antd/es/table';
import type { SorterResult } from 'antd/es/table/interface';
import {
App,
Button,
DatePicker,
Image,
Input,
Modal,
Select,
Space,
Table,
Tag,
Typography,
message,
} from 'antd';
import type { Dayjs } from 'dayjs';
import { api, errMsg } from '@/lib/api';
@@ -23,6 +22,7 @@ import { canDo } from '@/lib/auth';
import { formatUtcTime } from '@/lib/format';
import { usePagedList } from '@/lib/usePagedList';
import type { Feedback } from '@/lib/types';
import FeedbackQrConfig from './FeedbackQrConfig';
const { Text, Paragraph } = Typography;
const { RangePicker } = DatePicker;
@@ -34,6 +34,7 @@ const mediaUrl = (p: string) => (p.startsWith('http') ? p : MEDIA_BASE + p);
type SortField = 'id' | 'created_at';
export default function FeedbacksPage() {
const { message, modal } = App.useApp();
// 筛选草稿:点「查询」才应用(避免输入即刷新)
const [status, setStatus] = useState<string | undefined>();
const [userId, setUserId] = useState('');
@@ -114,7 +115,7 @@ export default function FeedbacksPage() {
message.warning('没有可处理的选中项(仅待处理 new 态生效)');
return;
}
Modal.confirm({
modal.confirm({
title: `确认批量标记处理 ${selectedNew.length} 条反馈?`,
content: '仅对选中的待处理(new)反馈生效',
onOk: async () => {
@@ -204,6 +205,7 @@ export default function FeedbacksPage() {
return (
<div>
<h2></h2>
<FeedbackQrConfig />
<Space style={{ marginBottom: 16 }} wrap>
<Select
placeholder="状态"
+3 -1
View File
@@ -11,6 +11,7 @@ import {
MessageOutlined,
MobileOutlined,
MoneyCollectOutlined,
ProfileOutlined,
SettingOutlined,
ShareAltOutlined,
TeamOutlined,
@@ -28,8 +29,9 @@ const MENU = [
{ key: '/devices', icon: <MobileOutlined />, label: '设备管理' },
{ key: '/withdraws', icon: <MoneyCollectOutlined />, label: '提现管理' },
{ key: '/price-reports', icon: <FlagOutlined />, label: '上报审核' },
{ key: '/comparison-records', icon: <ProfileOutlined />, label: '比价记录' },
{ key: '/feedbacks', icon: <MessageOutlined />, label: '反馈工单' },
{ key: '/ad-revenue', icon: <BarChartOutlined />, label: '广告数据' },
{ key: '/ad-revenue', icon: <BarChartOutlined />, label: '广告管理' },
{ key: '/cps', icon: <ShareAltOutlined />, label: 'CPS 分发' },
{ key: '/config', icon: <SettingOutlined />, label: '系统配置' },
{ key: '/admins', icon: <TeamOutlined />, label: '管理员', superOnly: true },
+5 -5
View File
@@ -2,6 +2,7 @@
import { useEffect, useState } from 'react';
import {
App,
Button,
Card,
Image,
@@ -13,13 +14,13 @@ import {
Tabs,
Tag,
Typography,
message,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import { api, errMsg } from '@/lib/api';
import { canDo } from '@/lib/auth';
import { mediaUrl } from '@/lib/media';
import { usePagedList } from '@/lib/usePagedList';
import type { PriceReport, PriceReportSummary } from '@/lib/types';
@@ -30,9 +31,7 @@ const { Text } = Typography;
const dt = (v: string | null) => (v ? dayjs(v).format('YYYY-MM-DD HH:mm') : '-');
const yuan = (c: number | null) => (c == null ? '-' : `¥${(c / 100).toFixed(2)}`);
// 截图是 app-server 的 /media 相对路径,本地由 :8770 提供(NEXT_PUBLIC_MEDIA_BASE);生产同域走 nginx 代理
const MEDIA_BASE = process.env.NEXT_PUBLIC_MEDIA_BASE || '';
const mediaUrl = (p: string) => (p.startsWith('http') ? p : MEDIA_BASE + p);
// 截图 URL 解析见 @/lib/media(dev 指向 :8770,生产走 nginx /media 同域反代)
const STATUS_COLOR: Record<string, string> = {
pending: 'gold',
@@ -57,6 +56,7 @@ function statusTag(status: string) {
}
export default function PriceReportsPage() {
const { message, modal } = App.useApp();
const [activeStatus, setActiveStatus] = useState('pending');
const [summary, setSummary] = useState<PriceReportSummary | null>(null);
const [rejecting, setRejecting] = useState<PriceReport | null>(null);
@@ -88,7 +88,7 @@ export default function PriceReportsPage() {
};
const approve = (r: PriceReport) => {
Modal.confirm({
modal.confirm({
title: '确认通过该上报?',
icon: <CheckCircleOutlined style={{ color: '#52c41a' }} />,
content: (
+3 -3
View File
@@ -4,11 +4,11 @@ import { useCallback, useEffect, useState } from 'react';
import { useParams } from 'next/navigation';
import type { ColumnsType } from 'antd/es/table';
import {
App,
Button,
Card,
Col,
Descriptions,
Modal,
Result,
Row,
Space,
@@ -17,7 +17,6 @@ import {
Table,
Tabs,
Tag,
message,
} from 'antd';
import { api, errMsg } from '@/lib/api';
import { canDo } from '@/lib/auth';
@@ -27,6 +26,7 @@ import { AdjustCashModal, AdjustCoinModal } from '@/components/AdjustBalanceModa
import type { CashTxn, CoinTxn, UserOverview, WithdrawOrder } from '@/lib/types';
export default function UserDetailPage() {
const { message, modal } = App.useApp();
const params = useParams<{ id: string }>();
const uid = Number(params.id);
const [data, setData] = useState<UserOverview | null>(null);
@@ -56,7 +56,7 @@ export default function UserDetailPage() {
const toggleStatus = () => {
if (!data) return;
const next = data.user.status === 'active' ? 'disabled' : 'active';
Modal.confirm({
modal.confirm({
title: `确认${next === 'disabled' ? '封禁' : '解封'}用户 ${data.user.phone}?`,
onOk: async () => {
try {
+37 -5
View File
@@ -5,7 +5,7 @@ import type { Key } from 'react';
import { useRouter } from 'next/navigation';
import type { ColumnsType } from 'antd/es/table';
import type { SorterResult } from 'antd/es/table/interface';
import { Button, DatePicker, Input, Modal, Select, Space, Table, Tag, message } from 'antd';
import { App, Button, DatePicker, Input, Select, Space, Table, Tag } from 'antd';
import dayjs, { type Dayjs } from 'dayjs';
import { api, errMsg } from '@/lib/api';
import { canDo } from '@/lib/auth';
@@ -22,6 +22,7 @@ type SortField = 'id' | 'created_at' | 'last_login_at';
export default function UsersPage() {
const router = useRouter();
const { message, modal } = App.useApp();
// 筛选草稿:点「查询」才应用(避免输入即刷新);状态/渠道/日期一并随查询提交
const [phone, setPhone] = useState('');
@@ -97,7 +98,7 @@ export default function UsersPage() {
const toggleStatus = (u: UserListItem) => {
const next = u.status === 'active' ? 'disabled' : 'active';
Modal.confirm({
modal.confirm({
title: `确认${next === 'disabled' ? '封禁' : '解封'}用户 ${u.phone}?`,
onOk: async () => {
try {
@@ -113,7 +114,7 @@ export default function UsersPage() {
const toggleDebugTrace = (u: UserListItem) => {
const next = !u.debug_trace_enabled;
Modal.confirm({
modal.confirm({
title: `确认${next ? '开启' : '关闭'}用户 ${u.phone} 的调试链接权限?`,
content: next
? '开启后,该用户在 App 比价结果页/记录页可复制 trace 调试链接发给开发排障'
@@ -130,6 +131,28 @@ export default function UsersPage() {
});
};
// 一次性操作:点一下把该用户标记为「未看过引导」,下次打开 App 重看一遍,看完后端自动恢复(只触发这一次)。
// 用户尚未重看前可「撤销」(把 force_onboarding 置回 false),纠正误点。
const setForceOnboarding = (u: UserListItem, enable: boolean) => {
modal.confirm({
title: enable
? `确认让用户 ${u.phone} 重看一次新手引导?`
: `撤销用户 ${u.phone} 的「重看新手引导」?`,
content: enable
? '点一下即把该用户标记为「未看过引导」:Ta 下次打开 App 会重走一遍新手引导,看完自动恢复——只触发这一次。仅对已支持该功能的 App 版本生效。'
: '该用户尚未重看,撤销后下次打开 App 不再触发。',
onOk: async () => {
try {
await api.post(`/admin/api/users/${u.id}/force-onboarding`, { enabled: enable });
message.success(enable ? '已开启:该用户下次打开 App 会重看一次' : '已撤销');
reload();
} catch (e) {
message.error(errMsg(e));
}
},
});
};
const selectedUsers = items.filter((u) => selectedRowKeys.includes(u.id));
const selectedActive = selectedUsers.filter((u) => u.status === 'active');
const selectedDisabled = selectedUsers.filter((u) => u.status === 'disabled');
@@ -156,7 +179,7 @@ export default function UsersPage() {
message.warning(`没有可${target === 'disabled' ? '封禁(active)' : '解封(disabled)'}的选中用户`);
return;
}
Modal.confirm({
modal.confirm({
title: `确认${label} ${targets.length} 个用户?`,
content: target === 'disabled' ? '仅对选中的 active 用户生效' : '仅对选中的 disabled 用户生效',
okButtonProps: { danger: target === 'disabled' },
@@ -177,7 +200,7 @@ export default function UsersPage() {
message.warning('没有需要变更的选中用户');
return;
}
Modal.confirm({
modal.confirm({
title: `确认${label} ${targets.length} 个用户?`,
onOk: () =>
runBulk(targets, label, (u) =>
@@ -237,6 +260,15 @@ export default function UsersPage() {
{u.debug_trace_enabled ? '关调试链接' : '开调试链接'}
</a>
)}
{canStatus &&
u.status !== 'deleted' &&
(u.force_onboarding ? (
<span style={{ color: '#fa8c16' }}>
<a onClick={() => setForceOnboarding(u, false)}></a>
</span>
) : (
<a onClick={() => setForceOnboarding(u, true)}></a>
))}
</Space>
),
},
@@ -0,0 +1,220 @@
'use client';
import { useCallback, useEffect, useState } from 'react';
import {
Button,
DatePicker,
Descriptions,
Radio,
Space,
Table,
Tag,
Typography,
message,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import dayjs, { type Dayjs } from 'dayjs';
import type { CursorPage, UserCoinRecord, UserRewardStats, WithdrawUserSnapshot } from '@/lib/types';
import { api, errMsg } from '@/lib/api';
const { Text } = Typography;
const { RangePicker } = DatePicker;
const yuan = (c: number) => `¥${(c / 100).toFixed(2)}`;
// 后端时间为 UTC(无时区串补 Z),按北京时区展示(与提现列表口径一致)
const apiTime = (v: string) => {
const hasTz = /(?:Z|[+-]\d{2}:?\d{2})$/i.test(v);
return dayjs(hasTz ? v : `${v}Z`);
};
const dt = (v: string) => apiTime(v).format('YYYY-MM-DD HH:mm');
const SOURCE_COLOR: Record<string, string> = {
reward_video: 'blue',
signin_boost: 'cyan',
feed: 'purple',
signin: 'green',
};
interface Props {
userId: number;
user: WithdrawUserSnapshot | null;
}
/** 提现详情抽屉:用户基本信息 + 互斥时间筛选 + 看广告/提现统计区 + 金币发放记录表。 */
export default function UserRewardPanel({ userId, user }: Props) {
const [mode, setMode] = useState<'all' | 'range'>('all'); // all=注册至今 / range=自定义区间
const [range, setRange] = useState<[Dayjs, Dayjs] | null>(null);
const [stats, setStats] = useState<UserRewardStats | null>(null);
const [statsLoading, setStatsLoading] = useState(false);
const [records, setRecords] = useState<UserCoinRecord[]>([]);
const [nextCursor, setNextCursor] = useState<number | null>(null);
const [recordsLoading, setRecordsLoading] = useState(false);
// 时间窗口参数:注册至今=不传;自定义区间(选齐两端)=date_from/date_to。
const params =
mode === 'range' && range?.[0] && range?.[1]
? {
date_from: range[0].startOf('day').toISOString(),
date_to: range[1].endOf('day').toISOString(),
}
: {};
const paramsKey = JSON.stringify(params);
const loadStats = useCallback(async () => {
setStatsLoading(true);
try {
const { data } = await api.get<UserRewardStats>(`/admin/api/users/${userId}/reward-stats`, {
params: JSON.parse(paramsKey),
});
setStats(data);
} catch (e) {
message.error(errMsg(e));
} finally {
setStatsLoading(false);
}
}, [userId, paramsKey]);
const loadRecords = useCallback(
async (cursor: number | null) => {
setRecordsLoading(true);
try {
const reqParams: Record<string, unknown> = { ...JSON.parse(paramsKey), limit: 20 };
if (cursor != null) reqParams.cursor = cursor;
const { data } = await api.get<CursorPage<UserCoinRecord>>(
`/admin/api/users/${userId}/coin-records`,
{ params: reqParams },
);
setRecords((prev) => (cursor == null ? data.items : [...prev, ...data.items]));
setNextCursor(data.next_cursor);
} catch (e) {
message.error(errMsg(e));
} finally {
setRecordsLoading(false);
}
},
[userId, paramsKey],
);
useEffect(() => {
loadStats();
loadRecords(null);
}, [loadStats, loadRecords]);
const regDays = user?.created_at ? dayjs().diff(apiTime(user.created_at), 'day') : null;
const columns: ColumnsType<UserCoinRecord> = [
{ title: '日期时间', dataIndex: 'created_at', width: 150, render: dt },
{
title: '赚取途径',
dataIndex: 'source_label',
width: 120,
render: (label: string, r) => <Tag color={SOURCE_COLOR[r.source] ?? 'default'}>{label}</Tag>,
},
{
title: 'ECPM',
dataIndex: 'ecpm',
width: 100,
render: (v: string | null) => v ?? <Text type="secondary">-</Text>,
},
{ title: '发放金币数', dataIndex: 'coin', width: 100, render: (v: number) => <b>{v}</b> },
];
return (
<div>
{/* 用户基本信息 + 互斥时间筛选(同一行) */}
<Space
wrap
align="center"
style={{ width: '100%', justifyContent: 'space-between', marginBottom: 12 }}
>
<Space size="large" wrap>
<span>
<Text strong>{user?.phone || '-'}</Text>
</span>
<span>
<Text strong>{user?.nickname || '-'}</Text>
</span>
<span>
<Text strong>{user?.wechat_nickname || '-'}</Text>
</span>
<span>
<Text strong>{regDays != null ? `${regDays}` : '-'}</Text>
</span>
</Space>
<Space wrap>
<Radio.Group
size="small"
value={mode}
onChange={(e) => setMode(e.target.value)}
optionType="button"
buttonStyle="solid"
>
<Radio.Button value="all"></Radio.Button>
<Radio.Button value="range"></Radio.Button>
</Radio.Group>
<RangePicker
size="small"
disabled={mode !== 'range'}
value={range}
onChange={(v) => setRange(v as [Dayjs, Dayjs] | null)}
/>
</Space>
</Space>
{/* 统计区(受时间筛选;现金余额为当前快照) */}
<Descriptions bordered size="small" column={2} style={{ marginBottom: 8 }}>
<Descriptions.Item label="累计提现">
{stats ? yuan(stats.withdraw_success_cents) : '-'}
</Descriptions.Item>
<Descriptions.Item label="现金余额">
{stats ? yuan(stats.cash_balance_cents) : '-'}
</Descriptions.Item>
<Descriptions.Item label="提现总次数">{stats?.withdraw_total ?? '-'}</Descriptions.Item>
<Descriptions.Item label="传统任务提现">
{stats ? yuan(stats.traditional_task_cash_cents) : '-'}
</Descriptions.Item>
<Descriptions.Item label="累计激励视频数">
{stats?.reward_video_count ?? '-'}
</Descriptions.Item>
<Descriptions.Item label="平均激励视频ECPM">
{stats ? `${stats.reward_video_avg_ecpm} 分/千` : '-'}
</Descriptions.Item>
<Descriptions.Item label="激励视频提现">
{stats ? yuan(stats.reward_video_cash_cents) : '-'}
</Descriptions.Item>
<Descriptions.Item label="累计信息流广告数">{stats?.feed_count ?? '-'}</Descriptions.Item>
<Descriptions.Item label="平均信息流广告ECPM">
{stats ? `${stats.feed_avg_ecpm} 分/千` : '-'}
</Descriptions.Item>
<Descriptions.Item label="信息流广告提现">
{stats ? yuan(stats.feed_cash_cents) : '-'}
</Descriptions.Item>
</Descriptions>
<Text type="secondary" style={{ fontSize: 12 }}>
(,);eCPM /,
</Text>
{/* 金币记录 */}
<h4 style={{ margin: '16px 0 8px' }}></h4>
<Table
rowKey={(r) => `${r.source}-${r.created_at}-${r.coin}-${r.ecpm ?? ''}`}
size="small"
columns={columns}
dataSource={records}
loading={recordsLoading || statsLoading}
pagination={false}
/>
<div style={{ marginTop: 12, textAlign: 'center' }}>
<Button
size="small"
onClick={() => loadRecords(nextCursor)}
disabled={!nextCursor}
loading={recordsLoading}
>
{nextCursor ? '加载更多' : '没有更多了'}
</Button>
</div>
</div>
);
}
+38 -139
View File
@@ -3,6 +3,7 @@
import { useCallback, useEffect, useState } from 'react';
import type { Key } from 'react';
import {
App,
Alert,
Button,
Card,
@@ -22,7 +23,6 @@ import {
Tag,
Timeline,
Typography,
message,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import {
@@ -38,18 +38,19 @@ import {
import dayjs, { type Dayjs } from 'dayjs';
import { api, errMsg } from '@/lib/api';
import { canDo } from '@/lib/auth';
import { formatUtcTime, formatWallTime, utcDayjs, utcFromNow, yuan } from '@/lib/format';
import { formatUtcTime, utcDayjs, utcFromNow, yuan } from '@/lib/format';
import { usePagedList } from '@/lib/usePagedList';
import type {
AuditLog,
CashTxn,
WithdrawBulkResult,
WithdrawDetail,
WithdrawLedgerCheck,
WithdrawListItem,
WithdrawOrder,
WithdrawSummary,
WxpayHealthCheck,
} from '@/lib/types';
import UserRewardPanel from './UserRewardPanel';
const { Text } = Typography;
const { RangePicker } = DatePicker;
@@ -101,19 +102,12 @@ const QUICK_FILTER_STATUS: Record<string, string> = {
};
const SORT_OPTIONS = [
{ value: 'created_at', label: '申请时间' },
{ value: 'updated_at', label: '更新时间' },
{ value: 'amount_cents', label: '提现金额' },
{ value: 'id', label: '记录 ID' },
];
const DATE_FIELD_OPTIONS = [
{ value: 'created_at', label: '申请时间' },
{ value: 'updated_at', label: '更新时间' },
];
const CASH_BIZ_LABEL: Record<string, string> = {
exchange_in: '金币兑入',
withdraw: '提现扣款',
withdraw_refund: '提现退款',
};
function statusTag(status: string) {
return <Tag color={STATUS_COLOR[status]}>{STATUS_LABEL[status] || status}</Tag>;
@@ -169,6 +163,7 @@ function bulkResultText(action: string, result: WithdrawBulkResult) {
}
export default function WithdrawsPage() {
const { message, modal } = App.useApp();
const [activeStatus, setActiveStatus] = useState('reviewing');
const [summary, setSummary] = useState<WithdrawSummary | null>(null);
const [health, setHealth] = useState<WxpayHealthCheck | null>(null);
@@ -185,9 +180,7 @@ export default function WithdrawsPage() {
const [keyword, setKeyword] = useState('');
const [dateRange, setDateRange] = useState<[Dayjs, Dayjs] | null>(null);
const [dateField, setDateField] = useState<'created_at' | 'updated_at'>('created_at');
const [sortBy, setSortBy] = useState<'created_at' | 'updated_at' | 'amount_cents' | 'id'>(
'created_at',
);
const [sortBy, setSortBy] = useState<'created_at' | 'amount_cents'>('created_at');
const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc');
const [quickFilter, setQuickFilter] = useState<string | undefined>(undefined);
@@ -202,7 +195,7 @@ export default function WithdrawsPage() {
filters.sort_order = sortOrder;
const filterKey = JSON.stringify(filters);
const { items, total, page, pageSize, loading, onChange: onPageChange, reload } =
usePagedList<WithdrawOrder>('/admin/api/withdraws', filters, 20);
usePagedList<WithdrawListItem>('/admin/api/withdraws', filters, 20);
const canManage = canDo(['finance']);
const selectedOrders = items.filter((item) => selectedRowKeys.includes(item.id));
const selectedReviewing = selectedOrders.filter((item) => item.status === 'reviewing');
@@ -305,7 +298,7 @@ export default function WithdrawsPage() {
};
const approve = (o: WithdrawOrder) => {
Modal.confirm({
modal.confirm({
title: `确认通过并打款 ${yuan(o.amount_cents)}?`,
content: (
<div>
@@ -368,7 +361,7 @@ export default function WithdrawsPage() {
}
const amount = selectedReviewing.reduce((sum, item) => sum + item.amount_cents, 0);
let confirmText = '';
Modal.confirm({
modal.confirm({
title: `确认批量通过 ${selectedReviewing.length} 笔提现?`,
content: (
<Space direction="vertical" style={{ width: '100%' }}>
@@ -406,7 +399,7 @@ export default function WithdrawsPage() {
message.warning('请选择打款中的提现单');
return;
}
Modal.confirm({
modal.confirm({
title: `确认批量刷新 ${selectedPending.length} 笔打款状态?`,
content: '会逐笔向微信查单,并按最新状态归一化。',
okText: '批量刷新查单',
@@ -428,7 +421,7 @@ export default function WithdrawsPage() {
};
const retry = (o: WithdrawOrder) => {
Modal.confirm({
modal.confirm({
title: `重新查询 ${o.out_bill_no} 的微信状态?`,
content: '会按微信最新状态归一化为成功、失败退款或撤销未确认。',
okText: '刷新查单',
@@ -450,7 +443,7 @@ export default function WithdrawsPage() {
};
const reconcile = () => {
Modal.confirm({
modal.confirm({
title: '批量对账?',
content: '扫描超过 15 分钟仍处于打款中的提现单,逐单向微信查实并归一化。',
okText: '开始对账',
@@ -468,37 +461,37 @@ export default function WithdrawsPage() {
});
};
const columns: ColumnsType<WithdrawOrder> = [
const columns: ColumnsType<WithdrawListItem> = [
{
title: '用户',
dataIndex: 'user_id',
width: 110,
render: (v: number) => <Text strong>#{v}</Text>,
},
{
title: '提现实名',
dataIndex: 'user_name',
title: '手机号',
dataIndex: 'phone',
width: 130,
render: (v: string | null) => v || <Text type="secondary"></Text>,
render: (v: string | null) => v || <Text type="secondary">-</Text>,
},
{
title: '金额',
title: '用户昵称',
dataIndex: 'nickname',
width: 130,
render: (v: string | null) => v || <Text type="secondary">-</Text>,
},
{
title: '提现金额',
dataIndex: 'amount_cents',
width: 120,
render: (v: number) => <Text strong>{yuan(v)}</Text>,
},
{
title: '累计提现',
dataIndex: 'cumulative_success_cents',
width: 120,
render: (v: number) => yuan(v ?? 0),
},
{
title: '状态',
dataIndex: 'status',
width: 110,
render: statusTag,
},
{
title: '微信状态',
dataIndex: 'wechat_state',
width: 150,
render: (v: string | null) => v || <Text type="secondary">-</Text>,
},
{
title: '提交时间',
dataIndex: 'created_at',
@@ -511,7 +504,7 @@ export default function WithdrawsPage() {
),
},
{
title: '提单号',
title: '提单号',
dataIndex: 'out_bill_no',
ellipsis: true,
},
@@ -526,7 +519,7 @@ export default function WithdrawsPage() {
key: 'op',
fixed: 'right',
width: 210,
render: (_: unknown, o: WithdrawOrder) => {
render: (_: unknown, o: WithdrawListItem) => {
if (!canManage) return <Text type="secondary">-</Text>;
if (o.status === 'reviewing') {
return (
@@ -575,37 +568,6 @@ export default function WithdrawsPage() {
},
];
const cashColumns: ColumnsType<CashTxn> = [
{
title: '类型',
dataIndex: 'biz_type',
width: 130,
render: (v: string) => CASH_BIZ_LABEL[v] || v,
},
{
title: '金额',
dataIndex: 'amount_cents',
width: 100,
render: (v: number) => (
<Text style={{ color: v < 0 ? '#cf1322' : '#389e0d' }}>
{v > 0 ? '+' : ''}
{yuan(v)}
</Text>
),
},
{ title: '余额', dataIndex: 'balance_after_cents', width: 100, render: yuan },
{ title: '备注', dataIndex: 'remark', render: (v: string | null) => v || '-' },
// 现金流水是北京 wall-clock 口径,原样显示,不能当 UTC 再 +8
{ title: '时间', dataIndex: 'created_at', width: 150, render: (v: string) => formatWallTime(v) },
];
const recentWithdrawColumns: ColumnsType<WithdrawOrder> = [
{ title: '单号', dataIndex: 'out_bill_no', ellipsis: true },
{ title: '金额', dataIndex: 'amount_cents', width: 90, render: yuan },
{ title: '状态', dataIndex: 'status', width: 90, render: statusTag },
{ title: '时间', dataIndex: 'created_at', width: 150, render: dt },
];
const auditTimeline = detail
? [
{
@@ -703,34 +665,14 @@ export default function WithdrawsPage() {
)}
<Row gutter={12} style={{ marginBottom: 16 }}>
<Col xs={24} sm={12} xl={5}>
<Col xs={24} sm={12}>
<Card size="small">
<Statistic title="待审核" value={summary?.reviewing_count || 0} suffix="笔" />
<Text type="secondary"> {yuan(summary?.reviewing_amount_cents || 0)}</Text>
</Card>
</Col>
<Col xs={24} sm={12} xl={5}>
<Col xs={24} sm={12}>
<Card size="small">
<Statistic title="今日拒绝" value={summary?.today_rejected_count || 0} suffix="笔" />
<Text type="secondary"></Text>
</Card>
</Col>
<Col xs={24} sm={12} xl={5}>
<Card size="small">
<Statistic title="打款中" value={summary?.pending_count || 0} suffix="笔" />
<Text type="secondary"></Text>
</Card>
</Col>
<Col xs={24} sm={12} xl={4}>
<Card size="small">
<Statistic title="失败待处理" value={summary?.failed_count || 0} suffix="笔" />
<Text type="secondary">退</Text>
</Card>
</Col>
<Col xs={24} sm={12} xl={5}>
<Card size="small">
<Statistic title="今日到账" value={summary?.today_success_count || 0} suffix="笔" />
<Text type="secondary"> {yuan(summary?.today_success_amount_cents || 0)}</Text>
<Statistic title="待审核金额" value={yuan(summary?.reviewing_amount_cents || 0)} />
</Card>
</Col>
</Row>
@@ -771,9 +713,9 @@ export default function WithdrawsPage() {
allowClear
enterButton="搜索"
prefix={<SearchOutlined />}
placeholder="用户ID / 手机号 / 单号 / 原因"
placeholder="用户手机号"
value={searchDraft}
style={{ width: 320 }}
style={{ width: 240 }}
onChange={(e) => {
const value = e.target.value;
setSearchDraft(value);
@@ -820,9 +762,7 @@ export default function WithdrawsPage() {
style={{ width: 130 }}
suffixIcon={<SortAscendingOutlined />}
options={SORT_OPTIONS}
onChange={(value: 'created_at' | 'updated_at' | 'amount_cents' | 'id') =>
setSortBy(value)
}
onChange={(value: 'created_at' | 'amount_cents') => setSortBy(value)}
/>
<Select
value={sortOrder}
@@ -957,26 +897,7 @@ export default function WithdrawsPage() {
</Descriptions.Item>
</Descriptions>
<Descriptions bordered size="small" column={2} title="用户与钱包">
<Descriptions.Item label="用户 ID">#{detail.order.user_id}</Descriptions.Item>
<Descriptions.Item label="账号状态">
{detail.user ? <Tag>{detail.user.status}</Tag> : '-'}
</Descriptions.Item>
<Descriptions.Item label="手机号">{detail.user?.phone || '-'}</Descriptions.Item>
<Descriptions.Item label="昵称">{detail.user?.nickname || '-'}</Descriptions.Item>
<Descriptions.Item label="微信昵称">
{detail.user?.wechat_nickname || '-'}
</Descriptions.Item>
<Descriptions.Item label="现金余额">
{yuan(detail.user?.cash_balance_cents || 0)}
</Descriptions.Item>
<Descriptions.Item label="提现总次数">
{detail.user?.withdraw_total ?? '-'}
</Descriptions.Item>
<Descriptions.Item label="成功提现">
{yuan(detail.user?.withdraw_success_cents || 0)}
</Descriptions.Item>
</Descriptions>
<UserRewardPanel userId={detail.order.user_id} user={detail.user} />
<div>
<h3> {detail.risk_score ? <Tag color="red">{detail.risk_score}</Tag> : null}</h3>
@@ -997,28 +918,6 @@ export default function WithdrawsPage() {
<h3>线</h3>
<Timeline items={auditTimeline} />
</div>
<div>
<h3></h3>
<Table
rowKey="id"
size="small"
columns={recentWithdrawColumns}
dataSource={detail.recent_withdraws}
pagination={false}
/>
</div>
<div>
<h3></h3>
<Table
rowKey="id"
size="small"
columns={cashColumns}
dataSource={detail.recent_cash_transactions}
pagination={false}
/>
</div>
</Space>
)}
</Spin>
+2 -1
View File
@@ -2,13 +2,14 @@
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { Button, Card, Form, Input, message } from 'antd';
import { App, Button, Card, Form, Input } from 'antd';
import { api, errMsg } from '@/lib/api';
import { setAuth } from '@/lib/auth';
import type { LoginResponse } from '@/lib/types';
export default function LoginPage() {
const router = useRouter();
const { message } = App.useApp();
const [loading, setLoading] = useState(false);
const onFinish = async (values: { username: string; password: string }) => {
+4 -2
View File
@@ -5,7 +5,7 @@
// 必须在引入 antd 之前 import。
import '@ant-design/v5-patch-for-react-19';
import { AntdRegistry } from '@ant-design/nextjs-registry';
import { ConfigProvider } from 'antd';
import { App, ConfigProvider } from 'antd';
import zhCN from 'antd/locale/zh_CN';
export function Providers({ children }: { children: React.ReactNode }) {
@@ -23,7 +23,9 @@ export function Providers({ children }: { children: React.ReactNode }) {
},
}}
>
{children}
{/* antd <App> 容器:让 message/notification/Modal 能通过 App.useApp() 读到 ConfigProvider
的动态主题/locale,消除 "Static function can not consume context" 告警(全站生效) */}
<App>{children}</App>
</ConfigProvider>
</AntdRegistry>
);
+3 -1
View File
@@ -3,7 +3,7 @@
// 调金币 / 调现金弹窗(受控)。列表页与用户详情页共用,避免两处各写一套。
// 每个弹窗自带「增减 / 设为指定值」两种模式;打开时拉一次 360 概览展示当前余额。
import { useEffect, useState } from 'react';
import { Form, Input, InputNumber, Modal, Segmented, message } from 'antd';
import { App, Form, Input, InputNumber, Modal, Segmented } from 'antd';
import { api, errMsg } from '@/lib/api';
import { yuan } from '@/lib/format';
import type { UserOverview } from '@/lib/types';
@@ -47,6 +47,7 @@ function useBalances(userId: number | undefined, open: boolean) {
}
export function AdjustCoinModal({ user, open, onClose, onDone }: ModalProps) {
const { message } = App.useApp();
const [form] = Form.useForm();
const [mode, setMode] = useState<'delta' | 'set'>('delta');
const balances = useBalances(user?.id, open);
@@ -110,6 +111,7 @@ export function AdjustCoinModal({ user, open, onClose, onDone }: ModalProps) {
}
export function AdjustCashModal({ user, open, onClose, onDone }: ModalProps) {
const { message } = App.useApp();
const [form] = Form.useForm();
const [mode, setMode] = useState<'delta' | 'set'>('delta');
const balances = useBalances(user?.id, open);
+11
View File
@@ -0,0 +1,11 @@
// 媒体(上报截图 / 反馈截图 / 反馈二维码等)由 App 后端的 /media 静态服务托管,admin 域不一定同源:
// - dev:NEXT_PUBLIC_MEDIA_BASE 指向 App 后端(http://localhost:8770)。
// - 生产:留空 = 走同域相对路径,由 admin nginx 的 /media 反代到后端(见 deploy/nginx/*.conf),
// 避免跨域 / 混合内容(https 页面引 http 图会被浏览器拦)。
const MEDIA_BASE = process.env.NEXT_PUBLIC_MEDIA_BASE || '';
/** 把后端返回的相对媒体路径(/media/...)拼成可加载的 URL;已是 http(s) 绝对地址的原样返回。 */
export function mediaUrl(p: string): string {
if (!p) return p;
return p.startsWith('http') ? p : MEDIA_BASE + p;
}
+136 -17
View File
@@ -30,6 +30,8 @@ export interface UserListItem {
status: string;
// 调试链接权限:开了的用户在 App 比价结果页/记录页可复制 price.shaguabijia.com 的 trace 调试链接
debug_trace_enabled: boolean;
// 运营「一键开启新手引导」:true = 该用户下次打开 App 会被强制重走新手引导,走完自动取消
force_onboarding: boolean;
wechat_openid: string | null;
created_at: string;
last_login_at: string;
@@ -90,6 +92,14 @@ export interface WithdrawOrder {
updated_at: string;
}
// 提现列表项:WithdrawOrder + 列表接口联表带出的用户字段。
// 详情抽屉的 recent_withdraws 仍是裸 WithdrawOrder(无这些字段)。
export interface WithdrawListItem extends WithdrawOrder {
phone: string | null;
nickname: string | null;
cumulative_success_cents: number; // 累计成功提现(分)
}
export interface WithdrawSummary {
reviewing_count: number;
reviewing_amount_cents: number;
@@ -124,6 +134,30 @@ export interface WithdrawDetail {
audit_logs: AuditLog[];
}
// 提现详情抽屉「用户统计区」:按时间窗口算的提现 + 看广告行为统计。
// *_cash_cents = 该来源累计金币折算成可提现现金(分);现金余额是当前快照不随窗口。
export interface UserRewardStats {
withdraw_success_cents: number; // 累计提现
cash_balance_cents: number; // 现金余额(快照)
withdraw_total: number; // 提现总次数(全部状态)
traditional_task_cash_cents: number; // 传统任务提现
reward_video_count: number; // 累计激励视频数
reward_video_avg_ecpm: number; // 平均激励视频 eCPM(分/千次)
reward_video_cash_cents: number; // 激励视频提现
feed_count: number; // 累计信息流广告数(份)
feed_avg_ecpm: number; // 平均信息流广告 eCPM(分/千次)
feed_cash_cents: number; // 信息流广告提现
}
// 金币发放记录(提现详情底部表)。ecpm 为原始分/千次,非广告来源为 null。
export interface UserCoinRecord {
source: string; // reward_video / signin_boost / feed / signin
source_label: string; // 激励视频 / 签到膨胀 / 信息流广告 / 签到
created_at: string;
ecpm: string | null;
coin: number;
}
export interface WithdrawBulkItemResult {
out_bill_no: string;
ok: boolean;
@@ -176,6 +210,17 @@ export interface Feedback {
created_at: string;
}
// 反馈页「加群二维码」卡配置(运营后台改 → App 意见反馈页同步)。
// image_url 为后端 /media 相对路径(留空=App 走本地兜底图);其余为卡片三行文案与显隐开关。
export interface FeedbackQrConfig {
enabled: boolean;
image_url: string | null;
title: string; // 第一行(操作提示),如「长按图片保存二维码」
group_name: string; // 第二行加粗群名,App 渲染为 直通「{group_name}」
subtitle: string; // 第三行(标语)
updated_at: string | null;
}
export interface AuditLog {
id: number;
admin_id: number;
@@ -189,6 +234,70 @@ export interface AuditLog {
}
// 广告收益报表聚合行下钻的单条展示明细
// ===== 比价记录(admin debug 页)=====
export interface ComparisonRecordListItem {
id: number;
user_id: number;
phone: string | null;
nickname: string | null;
business_type: string;
trace_id: string;
trace_url: string | null;
status: string;
information: string | null;
store_name: string | null;
source_platform_name: string | null;
best_platform_name: string | null;
source_price_cents: number | null;
best_price_cents: number | null;
saved_amount_cents: number | null;
total_ms: number | null;
step_count: number | null;
llm_call_count: number | null;
retry_count: number | null;
device_model: string | null;
rom_vendor: string | null;
rom_name: string | null;
android_version: string | null;
app_version: string | null;
created_at: string;
}
// 单次 LLM 调用明细(pricebot chat() 收口落盘,server 按 trace 拉来)
export interface LlmCall {
ts?: number;
scene: string;
model: string;
input_messages: { role: string; content: string }[];
output: string | null;
usage: { prompt_tokens?: number; completion_tokens?: number; total_tokens?: number } | null;
latency_ms: number | null;
error: string | null;
}
export interface ComparisonRecordDetail extends ComparisonRecordListItem {
source_platform_id: string | null;
source_package: string | null;
best_platform_id: string | null;
best_deeplink: string | null;
is_source_best: boolean | null;
total_dish_count: number | null;
skipped_dish_count: number | null;
device_id: string | null;
items: { name: string; qty?: number; specs?: string[] }[];
comparison_results: Record<string, unknown>[];
skipped_dish_names: string[];
device_manufacturer: string | null;
rom_version: number | null;
android_sdk: number | null;
app_version_code: number | null;
source_app_version: string | null;
longitude: number | null;
latitude: number | null;
llm_calls: LlmCall[] | null;
raw_payload: Record<string, unknown> | null;
}
export interface AdRevenueImpression {
id: number;
created_at: string;
@@ -307,8 +416,9 @@ export interface PriceReportSummary {
// ===== CPS 分发与对账 =====
export interface CpsGroup {
id: number;
sid: string; // 美团二级渠道追踪位,每群唯一
sid: string | null; // 美团群有(渠道追踪位)
name: string;
platforms: string[]; // meituan/taobao/jd 多选
member_count: number | null;
status: string; // active / archived
remark: string | null;
@@ -321,6 +431,8 @@ export interface CpsActivity {
name: string;
act_id: string | null; // 美团活动物料 ID
product_view_sign: string | null;
payload: string | null; // 淘宝整段淘口令 / 京东链接
image_url: string | null; // 淘宝落地页主视觉图(绝对 URL)
status: string;
remark: string | null;
created_at: string;
@@ -340,14 +452,17 @@ export interface CpsOrder {
pay_time: string | null;
}
export interface CpsReferralLink {
redirect_url: string; // ★ 我们的群发短链(/c/{code}),发群用这个,点击经我们统计
code: string;
sid: string;
group_name: string;
export interface CpsReferralLinkItem {
activity_id: number;
activity_name: string;
target_url: string; // 实际 302 跳转的美团短链
link_map: Record<string, string>; // 美团原始 1长链/2短链/3deeplink(参考)
platform: string;
redirect_url: string; // 我们的落地页 /c/{code}(发群用)
code: string;
}
export interface CpsReferralLinks {
group_name: string;
results: CpsReferralLinkItem[];
}
export interface CpsReconcileResult {
@@ -358,18 +473,22 @@ export interface CpsReconcileResult {
}
export interface CpsGroupStat {
group_id: number | null; // null = 未归群的 sid
group_id: number | null;
sid: string | null;
name: string;
platforms: 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;
click_pv: number;
click_uv: number;
copy_pv: number; // 淘宝"复制口令"次数
copy_uv: number;
// 对账类:淘宝/京东无法对账 → null(前端显示 "-")
order_count: number | null;
settled_count: number | null;
canceled_count: number | null;
gmv_cents: number | null;
est_commission_cents: number | null;
settled_commission_cents: number | null;
}
export interface CpsStats {