Compare commits

..

1 Commits

Author SHA1 Message Date
zzhyyyyy c6a8cb2cf0 feat: 反馈加反馈类型/运营回复 + 提现加提现类型筛选
用户反馈后台 + 提现审核后台的运营字段与筛选。

- 反馈页:新增「反馈类型」列(比价反馈/普通反馈 + 场景)、顶部「反馈类型」筛选;审核抽屉采纳/拒绝
  都能填「给用户的回复」(用户端可见),并回显反馈类型/场景/运营回复。
- 提现页:新增「提现类型」列(福利页提现/邀请提现)、顶部「提现类型」筛选,详情抽屉展示提现类型。
- types.ts:Feedback 加 source/scene/admin_reply,WithdrawOrder 加 source。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-02 16:43:17 +08:00
6 changed files with 110 additions and 533 deletions
+84 -368
View File
@@ -1,262 +1,81 @@
'use client';
import { useEffect, useMemo, useState } from 'react';
import { useEffect, useState } from 'react';
import type { ColumnsType } from 'antd/es/table';
import {
App, Button, Card, Checkbox, Input, Select, Space, Table, Tag,
} 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 { getAdmin } from '@/lib/auth';
import type { AdminInfo, AdminRole, PermissionGroup } from '@/lib/types';
import type { AdminInfo } from '@/lib/types';
const ROLES = [
{ value: 'super_admin', label: 'super_admin' },
{ value: 'finance', label: 'finance' },
{ value: 'operator', label: 'operator' },
];
// last_login_at 为 UTC 口径(datetime.now(utc)),按北京显示(勿用 new Date().toLocaleString)
const dt = (v: string | null) => (v ? formatUtcTime(v, 'YYYY-MM-DD HH:mm:ss') : '从未');
// 随机初始密码(排除易混字符 0O1lI),客户端生成、转交本人,后端只存 hash
function genPassword(len = 10): string {
const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789';
let s = '';
for (let i = 0; i < len; i += 1) s += chars[Math.floor(Math.random() * chars.length)];
return s;
}
type View = 'list' | 'person' | 'roles' | 'roleForm';
// ===== 只读权限矩阵:角色详情 / 人员「可见页面」预览共用(深色=有,灰色=无)=====
function PermMatrix({ catalog, pages }: { catalog: PermissionGroup[]; pages: string[] }) {
const has = useMemo(() => new Set(pages), [pages]);
return (
<div style={{ border: '1px solid #f0f0f0', borderRadius: 8, overflow: 'hidden' }}>
{catalog.map((g) => (
<div key={g.group} style={{ display: 'flex', borderBottom: '1px solid #f0f2f5' }}>
<div style={{ width: 150, flexShrink: 0, padding: '14px', fontWeight: 500, color: 'rgba(0,0,0,.85)' }}>
{g.group}
</div>
<div style={{ flex: 1, padding: '12px 16px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px 28px' }}>
{g.pages.map((p) => (
// 深色=可见,灰色(--ink-3)=不可见
<span key={p.key} style={{ fontSize: 13.5, color: has.has(p.key) ? 'rgba(0,0,0,.85)' : '#94a0b1' }}>
{p.label}
</span>
))}
</div>
</div>
))}
</div>
);
}
// ===== 可编辑权限矩阵:角色表单用(勾选框 + 分类全选/半选)=====
function PermEditor({
catalog, value, onChange,
}: { catalog: PermissionGroup[]; value: string[]; onChange: (next: string[]) => void }) {
const has = useMemo(() => new Set(value), [value]);
const setPages = (s: Set<string>) => onChange(Array.from(s));
const togglePage = (key: string) => {
const n = new Set(has);
if (n.has(key)) n.delete(key); else n.add(key);
setPages(n);
};
const toggleGroup = (g: PermissionGroup, on: boolean) => {
const n = new Set(has);
g.pages.forEach((p) => (on ? n.add(p.key) : n.delete(p.key)));
setPages(n);
};
return (
<div style={{ border: '1px solid #f0f0f0', borderRadius: 8, overflow: 'hidden' }}>
{catalog.map((g) => {
const cnt = g.pages.filter((p) => has.has(p.key)).length;
const all = cnt === g.pages.length && cnt > 0;
return (
<div key={g.group} style={{ display: 'flex', borderBottom: '1px solid #fafafa' }}>
<div style={{ width: 140, flexShrink: 0, padding: '14px', background: '#fafbfd' }}>
<Checkbox
checked={all}
indeterminate={cnt > 0 && !all}
onChange={(e) => toggleGroup(g, e.target.checked)}
>
{g.group}
</Checkbox>
</div>
<div style={{ flex: 1, padding: '12px 16px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px 24px' }}>
{g.pages.map((p) => (
<Checkbox key={p.key} checked={has.has(p.key)} onChange={() => togglePage(p.key)}>
{p.label}
</Checkbox>
))}
</div>
</div>
);
})}
</div>
);
}
export default function AdminsPage() {
const { message, modal } = App.useApp();
const me = getAdmin();
const isSuper = me?.role === 'super_admin';
const [view, setView] = useState<View>('list');
const [admins, setAdmins] = useState<AdminInfo[]>([]);
const [roles, setRoles] = useState<AdminRole[]>([]);
const [catalog, setCatalog] = useState<PermissionGroup[]>([]);
const [loading, setLoading] = useState(false);
const [createOpen, setCreateOpen] = useState(false);
const [form] = Form.useForm();
const roleByName = useMemo(() => {
const m: Record<string, AdminRole> = {};
roles.forEach((r) => { m[r.name] = r; });
return m;
}, [roles]);
const roleOptions = roles.map((r) => ({ value: r.name, label: r.label }));
const loadAll = async () => {
const load = async () => {
setLoading(true);
try {
const [a, r, c] = await Promise.all([
api.get<AdminInfo[]>('/admin/api/admins'),
api.get<AdminRole[]>('/admin/api/roles'),
api.get<PermissionGroup[]>('/admin/api/roles/catalog'),
]);
setAdmins(a.data);
setRoles(r.data);
setCatalog(c.data);
} catch (e) {
message.error(errMsg(e));
const { data } = await api.get<AdminInfo[]>('/admin/api/admins');
setAdmins(data);
} finally {
setLoading(false);
}
};
useEffect(() => { loadAll(); }, []); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
load();
}, []);
// ===== 人员表单(新增 / 编辑)状态 =====
const [personEditing, setPersonEditing] = useState<AdminInfo | null>(null);
const [personName, setPersonName] = useState('');
const [personRole, setPersonRole] = useState('');
const [initPw, setInitPw] = useState('');
const openCreatePerson = () => {
setPersonEditing(null);
setPersonName('');
setPersonRole(roles.find((r) => !r.is_builtin)?.name ?? roles[0]?.name ?? 'operator');
setInitPw(genPassword());
setView('person');
};
const openEditPerson = (a: AdminInfo) => {
setPersonEditing(a);
setPersonName(a.username);
setPersonRole(a.role);
setInitPw(''); // 编辑态密码只读展示 a.password(已确定的登录密码),不用 initPw
setView('person');
};
const copyText = (v: string) => {
navigator.clipboard?.writeText(v);
message.success('已复制到剪贴板');
};
// 密码展示框(对齐原型 .pw-show:虚线灰框 + 大号等宽 + 复制)
const pwBox = (value: string) => (
<div style={{ display: 'flex', alignItems: 'center', gap: 12, background: '#f4f6fa', border: '1px dashed #cbd5e1', borderRadius: 8, padding: '12px 14px' }}>
<code style={{ flex: 1, fontFamily: '"DIN Alternate", "SF Mono", Consolas, monospace', fontSize: 22, fontWeight: 700, letterSpacing: 1, color: 'rgba(0,0,0,.85)' }}>{value}</code>
<Button onClick={() => copyText(value)}></Button>
</div>
);
const submitPerson = async () => {
const create = async () => {
const v = await form.validateFields();
try {
if (personEditing) {
// 密码只读、不改;只提交变更的角色
if (personRole !== personEditing.role) {
await api.patch(`/admin/api/admins/${personEditing.id}`, { role: personRole });
}
message.success('已保存');
} else {
if (personName.trim().length < 3) { message.error('用户名至少 3 位'); return; }
await api.post('/admin/api/admins', {
username: personName.trim(), password: initPw, role: personRole,
});
message.success('已创建,请把初始密码转交本人');
}
setView('list');
loadAll();
await api.post('/admin/api/admins', v);
message.success('已创建');
setCreateOpen(false);
form.resetFields();
load();
} catch (e) {
message.error(errMsg(e));
}
};
// ===== 列表操作 =====
const changeRole = (a: AdminInfo, role: string) => {
if (role === a.role) return;
modal.confirm({
title: `${a.username} 的角色改为 ${role}?`,
onOk: async () => {
try { await api.patch(`/admin/api/admins/${a.id}`, { role }); message.success('已更新'); loadAll(); }
catch (e) { message.error(errMsg(e)); }
try {
await api.patch(`/admin/api/admins/${a.id}`, { role });
message.success('已更新');
load();
} catch (e) {
message.error(errMsg(e));
}
},
});
};
const toggleStatus = (a: AdminInfo) => {
const toggle = (a: AdminInfo) => {
const next = a.status === 'active' ? 'disabled' : 'active';
modal.confirm({
title: `${next === 'disabled' ? '禁用' : '启用'}管理员 ${a.username}?`,
onOk: async () => {
try { await api.patch(`/admin/api/admins/${a.id}`, { status: next }); message.success('已更新'); loadAll(); }
catch (e) { message.error(errMsg(e)); }
},
});
};
const deletePerson = (a: AdminInfo) => {
modal.confirm({
title: '确认删除',
content: `确定删除管理员「${a.username}」吗?删除后该账号将无法登录,不可恢复。`,
okText: '确认删除', okButtonProps: { danger: true },
onOk: async () => {
try { await api.delete(`/admin/api/admins/${a.id}`); message.success('已删除'); loadAll(); }
catch (e) { message.error(errMsg(e)); }
},
});
};
// ===== 角色设置状态 =====
const [selRoleId, setSelRoleId] = useState<number | null>(null);
const selRole = roles.find((r) => r.id === selRoleId) ?? roles[0] ?? null;
const openRoles = () => {
setSelRoleId((prev) => prev ?? roles[0]?.id ?? null);
setView('roles');
};
// 角色表单(新增 / 编辑)
const [roleEditing, setRoleEditing] = useState<AdminRole | null>(null);
const [roleName, setRoleName] = useState('');
const [rolePages, setRolePages] = useState<string[]>([]);
const openCreateRole = () => {
setRoleEditing(null); setRoleName(''); setRolePages([]); setView('roleForm');
};
const openEditRole = (r: AdminRole) => {
setRoleEditing(r); setRoleName(r.label); setRolePages(r.pages); setView('roleForm');
};
const submitRole = async () => {
if (!roleName.trim()) { message.error('请输入角色名称'); return; }
try {
if (roleEditing) {
// 只改展示名 + 可见页(key 不可变)
await api.patch(`/admin/api/roles/${roleEditing.id}`, { label: roleName.trim(), pages: rolePages });
message.success('角色已保存');
} else {
await api.post('/admin/api/roles', { name: roleName.trim(), pages: rolePages });
message.success('角色已创建');
}
await loadAll();
setView('roles');
} catch (e) {
message.error(errMsg(e));
}
};
const deleteRole = (r: AdminRole) => {
modal.confirm({
title: '确认删除角色',
content: `确定删除角色「${r.label}」吗?${r.in_use > 0 ? `当前有 ${r.in_use} 名成员在用,需先改派。` : '此操作不可恢复。'}`,
okText: '确认删除', okButtonProps: { danger: true },
onOk: async () => {
try { await api.delete(`/admin/api/roles/${r.id}`); message.success('已删除角色'); await loadAll(); setSelRoleId(null); }
catch (e) { message.error(errMsg(e)); }
try {
await api.patch(`/admin/api/admins/${a.id}`, { status: next });
message.success('已更新');
load();
} catch (e) {
message.error(errMsg(e));
}
},
});
};
@@ -265,163 +84,60 @@ export default function AdminsPage() {
{ title: 'ID', dataIndex: 'id', width: 70 },
{ title: '用户名', dataIndex: 'username' },
{
title: '角色', dataIndex: 'role', width: 170,
title: '角色',
dataIndex: 'role',
render: (r: string, a: AdminInfo) => (
<Select size="small" value={r} style={{ width: 150 }} options={roleOptions} onChange={(v) => changeRole(a, v)} />
<Select
size="small"
value={r}
style={{ width: 140 }}
options={ROLES}
onChange={(v) => changeRole(a, v)}
/>
),
},
{ title: '状态', dataIndex: 'status', width: 90, render: (s: string) => <Tag color={s === 'active' ? 'green' : 'default'}>{s === 'active' ? 'active' : '已禁用'}</Tag> },
{ title: '最后登录', dataIndex: 'last_login_at', width: 180, render: dt },
{
title: '操作', key: 'op', width: 200,
title: '状态',
dataIndex: 'status',
render: (s: string) => <Tag color={s === 'active' ? 'green' : 'red'}>{s}</Tag>,
},
{ title: '最后登录', dataIndex: 'last_login_at', render: dt },
{
title: '操作',
key: 'op',
render: (_: unknown, a: AdminInfo) => (
<Space size="middle">
<a onClick={() => openEditPerson(a)}></a>
<a onClick={() => toggleStatus(a)}>{a.status === 'active' ? '禁用' : '启用'}</a>
<a style={{ color: '#cf1322' }} onClick={() => deletePerson(a)}></a>
</Space>
<a onClick={() => toggle(a)}>{a.status === 'active' ? '禁用' : '启用'}</a>
),
},
];
// ============ 视图 1:管理员账号列表 ============
if (view === 'list') {
return (
<div>
<h2></h2>
<Space style={{ marginBottom: 16 }}>
<Button type="primary" onClick={openCreatePerson}>+ </Button>
<Button onClick={openRoles}></Button>
</Space>
<Table rowKey="id" columns={columns} dataSource={admins} loading={loading} pagination={false} />
</div>
);
}
// ============ 视图 2:新增 / 编辑人员 ============
if (view === 'person') {
const rolePagesPreview = roleByName[personRole]?.pages ?? [];
return (
<div>
<Space style={{ marginBottom: 16 }}><a onClick={() => setView('list')}> </a></Space>
<Card style={{ maxWidth: 720, margin: '0 auto' }}>
<h2 style={{ fontSize: 19, fontWeight: 600, marginBottom: 22 }}>{personEditing ? '编辑人员' : '新增人员'}</h2>
<div style={{ marginBottom: 20 }}>
<div style={{ marginBottom: 8 }}><span style={{ color: '#cf1322' }}> *</span></div>
<Input value={personName} disabled={!!personEditing} onChange={(e) => setPersonName(e.target.value)} placeholder="至少 3 位" />
{personEditing && <div style={{ color: '#999', fontSize: 12, marginTop: 6 }}></div>}
</div>
{!personEditing ? (
// 新增:系统生成初始密码(可换)
<div style={{ marginBottom: 20 }}>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
<span></span>
<a onClick={() => setInitPw(genPassword())}> </a>
</div>
{pwBox(initPw)}
</div>
) : personEditing.password ? (
// 编辑:显示该成员已确定的登录密码(只读、不可换)
<div style={{ marginBottom: 20 }}>
<div style={{ marginBottom: 8 }}></div>
{pwBox(personEditing.password)}
<div style={{ color: '#999', fontSize: 12, marginTop: 6 }}>,</div>
</div>
) : (
// 编辑:无留存明文(脚本/起后台建的超管)→ 不显示密码
<div style={{ marginBottom: 20 }}>
<div style={{ marginBottom: 8 }}></div>
<div style={{ color: '#999', fontSize: 13, padding: '6px 0' }}>,</div>
</div>
)}
<div style={{ marginBottom: 20 }}>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
<span><span style={{ color: '#cf1322' }}> *</span></span>
{isSuper && <a onClick={openRoles}> </a>}
</div>
<Select value={personRole} options={roleOptions} onChange={setPersonRole} style={{ width: '100%' }} />
<div style={{ color: '#999', fontSize: 12, marginTop: 6 }}>;</div>
</div>
<div>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
<span></span>
<span style={{ color: '#999', fontSize: 12 }}>,(=)</span>
</div>
<PermMatrix catalog={catalog} pages={personRole === 'super_admin' ? catalog.flatMap((g) => g.pages.map((p) => p.key)) : rolePagesPreview} />
</div>
<div style={{ marginTop: 24, textAlign: 'right' }}>
<Space><Button onClick={() => setView('list')}></Button><Button type="primary" onClick={submitPerson}></Button></Space>
</div>
</Card>
</div>
);
}
// ============ 视图 3:角色设置(角色列表 + 只读权限详情)============
if (view === 'roles') {
return (
<div>
<Space style={{ marginBottom: 16 }}><a onClick={() => setView('list')}> </a><b></b></Space>
<div>
<Button type="primary" style={{ marginBottom: 16 }} onClick={openCreateRole}>+ </Button>
<div style={{ display: 'flex', background: '#fff', border: '1px solid #e8ebf1', borderRadius: 10, boxShadow: '0 1px 3px rgba(16,24,40,.06)', overflow: 'hidden' }}>
<div style={{ width: 176, flexShrink: 0, borderRight: '1px solid #eff1f6', padding: 8 }}>
{roles.map((r) => (
<div
key={r.id}
onClick={() => setSelRoleId(r.id)}
style={{
padding: '10px 14px', borderRadius: 8, cursor: 'pointer', marginBottom: 2,
background: selRole?.id === r.id ? '#e6f0ff' : undefined,
color: selRole?.id === r.id ? '#1677ff' : undefined,
fontWeight: selRole?.id === r.id ? 600 : undefined,
}}
>
{r.label}{r.is_builtin && <Tag style={{ marginLeft: 6 }}></Tag>}
</div>
))}
</div>
<div style={{ flex: 1, minWidth: 0, padding: '18px 22px' }}>
{selRole && (
<>
<Space style={{ marginBottom: 16 }} size="middle">
<b style={{ fontSize: 16 }}>{selRole.label}</b>
{!selRole.is_builtin && <a onClick={() => openEditRole(selRole)}></a>}
{!selRole.is_builtin && <a style={{ color: '#cf1322' }} onClick={() => deleteRole(selRole)}></a>}
{selRole.in_use > 0 && <span style={{ color: '#999', fontSize: 12 }}>{selRole.in_use} </span>}
</Space>
<PermMatrix catalog={catalog} pages={selRole.pages} />
</>
)}
</div>
</div>
</div>
</div>
);
}
// ============ 视图 4:新增 / 编辑角色权限 ============
return (
<div>
<Space style={{ marginBottom: 16 }}><a onClick={() => setView('roles')}> </a></Space>
<Card style={{ maxWidth: 920, margin: '0 auto' }}>
<h2 style={{ fontSize: 19, fontWeight: 600, marginBottom: 22 }}>{roleEditing ? '编辑角色权限' : '新增角色权限'}</h2>
<div style={{ marginBottom: 20 }}>
<div style={{ marginBottom: 8 }}><span style={{ color: '#cf1322' }}> *</span></div>
<Input value={roleName} onChange={(e) => setRoleName(e.target.value)} placeholder="如:运营专员 / 财务 / 审核" maxLength={32} />
</div>
<div>
<div style={{ marginBottom: 8 }}>()<span style={{ color: '#cf1322' }}> *</span></div>
<PermEditor catalog={catalog} value={rolePages} onChange={setRolePages} />
</div>
<div style={{ marginTop: 24, textAlign: 'right' }}>
<Space><Button onClick={() => setView('roles')}></Button><Button type="primary" onClick={submitRole}></Button></Space>
</div>
</Card>
<h2></h2>
<Button type="primary" style={{ marginBottom: 16 }} onClick={() => setCreateOpen(true)}>
</Button>
<Table rowKey="id" columns={columns} dataSource={admins} loading={loading} pagination={false} />
<Modal
title="新建管理员"
open={createOpen}
onOk={create}
onCancel={() => setCreateOpen(false)}
destroyOnClose
>
<Form form={form} layout="vertical" initialValues={{ role: 'operator' }}>
<Form.Item name="username" label="用户名" rules={[{ required: true, min: 3 }]}>
<Input />
</Form.Item>
<Form.Item name="password" label="密码(≥8 位)" rules={[{ required: true, min: 8 }]}>
<Input.Password />
</Form.Item>
<Form.Item name="role" label="角色" rules={[{ required: true }]}>
<Select options={ROLES} />
</Form.Item>
</Form>
</Modal>
</div>
);
}
+5 -72
View File
@@ -1,7 +1,7 @@
'use client';
import { useState } from 'react';
import type { CSSProperties, ReactNode } from 'react';
import type { CSSProperties } from 'react';
import {
App, Button, Card, Collapse, Descriptions, Drawer, Input, InputNumber,
Select, Space, Spin, Table, Tag, Typography,
@@ -48,33 +48,6 @@ function pretty(s: string | null): string {
}
}
// 搜索命中高亮:把 text 里匹配 keyword 的子串套黄底荧光,方便审计快速定位。
// 大小写不敏感;用 indexOf 逐段切(非正则,keyword 含特殊字符也安全)。keyword 取「已应用」
// 的搜索词(applied.store / applied.product),不是输入框实时值——只高亮真正搜过的词。
function highlightMatch(text: string | null, keyword: unknown): ReactNode {
if (!text) return '-';
const kw = (typeof keyword === 'string' ? keyword : '').trim();
if (!kw) return text;
const parts: ReactNode[] = [];
const hay = text.toLowerCase();
const needle = kw.toLowerCase();
let from = 0;
let hit = hay.indexOf(needle);
let k = 0;
while (hit !== -1) {
if (hit > from) parts.push(text.slice(from, hit));
parts.push(
<mark key={k++} style={{ background: '#fff566', padding: 0 }}>
{text.slice(hit, hit + kw.length)}
</mark>,
);
from = hit + kw.length;
hit = hay.indexOf(needle, from);
}
if (from < text.length) parts.push(text.slice(from));
return parts;
}
const preStyle: CSSProperties = {
background: '#f6f8fa', padding: 8, borderRadius: 6, fontSize: 12,
maxHeight: 340, overflow: 'auto', whiteSpace: 'pre-wrap', wordBreak: 'break-word', margin: 0,
@@ -86,8 +59,6 @@ export default function ComparisonRecordsPage() {
const [userId, setUserId] = useState<number | null>(null);
const [phone, setPhone] = useState('');
const [status, setStatus] = useState<string | undefined>();
const [store, setStore] = useState('');
const [product, setProduct] = useState('');
const [applied, setApplied] = useState<Record<string, unknown>>({});
// LLM 单价(元/百万 token),本地持久化;仅用于前端估算成本,不入库、不影响其它页面
const [pricePerMTok, setPricePerMTok] = useState<number | null>(() => {
@@ -109,20 +80,12 @@ export default function ComparisonRecordsPage() {
const [detailLoading, setDetailLoading] = useState(false);
const search = () =>
setApplied({
user_id: userId ?? undefined,
phone: phone || undefined,
status,
store: store.trim() || undefined,
product: product.trim() || undefined,
});
setApplied({ user_id: userId ?? undefined, phone: phone || undefined, status });
const reset = () => {
setUserId(null);
setPhone('');
setStatus(undefined);
setStore('');
setProduct('');
setApplied({});
};
@@ -159,21 +122,7 @@ export default function ComparisonRecordsPage() {
},
{ title: '状态', dataIndex: 'status', width: 72, render: (s: string) => <Tag color={STATUS_COLOR[s]}>{STATUS_LABEL[s] || s}</Tag> },
{ title: '源平台', dataIndex: 'source_platform_name', width: 90, render: (v) => v || '-' },
{
title: '店',
dataIndex: 'store_name',
width: 170,
// 审计要一眼看全:不截断、整格自动换行(去 ellipsis),而非靠 hover tooltip
onCell: () => ({ style: { whiteSpace: 'normal', wordBreak: 'break-word', verticalAlign: 'top' } }),
render: (v: string | null) => highlightMatch(v, applied.store),
},
{
title: '商品',
dataIndex: 'product_names',
width: 280,
onCell: () => ({ style: { whiteSpace: 'normal', wordBreak: 'break-word', verticalAlign: 'top' } }),
render: (v: string | null) => highlightMatch(v, applied.product),
},
{ title: '店/商品', dataIndex: 'store_name', width: 150, ellipsis: true, render: (v) => v || '-' },
{ title: '最优', dataIndex: 'best_platform_name', width: 80, render: (v) => v || '-' },
{
title: '省',
@@ -243,22 +192,6 @@ export default function ComparisonRecordsPage() {
allowClear
style={{ width: 150 }}
/>
<Input
placeholder="搜索店名"
value={store}
onChange={(e) => setStore(e.target.value)}
onPressEnter={search}
allowClear
style={{ width: 150 }}
/>
<Input
placeholder="搜索商品"
value={product}
onChange={(e) => setProduct(e.target.value)}
onPressEnter={search}
allowClear
style={{ width: 150 }}
/>
<Select
placeholder="状态"
value={status}
@@ -297,7 +230,7 @@ export default function ComparisonRecordsPage() {
showTotal: (t) => `${t}`,
onChange,
}}
scroll={{ x: 1820 }}
scroll={{ x: 1520 }}
onRow={(r) => ({ onClick: () => openDetail(r.id), style: { cursor: 'pointer' } })}
/>
@@ -328,7 +261,7 @@ export default function ComparisonRecordsPage() {
<Descriptions.Item label="源平台">{detail.source_platform_name || '-'}{cents(detail.source_price_cents)}</Descriptions.Item>
<Descriptions.Item label="最优">{detail.best_platform_name || '-'}{cents(detail.best_price_cents)}</Descriptions.Item>
<Descriptions.Item label="省" span={2}>{cents(detail.saved_amount_cents)}{detail.is_source_best ? '(源平台最便宜)' : ''}</Descriptions.Item>
<Descriptions.Item label="店" span={2}>{detail.store_name || '-'}</Descriptions.Item>
<Descriptions.Item label="店/商品" span={2}>{detail.store_name || '-'}</Descriptions.Item>
<Descriptions.Item label="结论文案" span={2}>{detail.information || '-'}</Descriptions.Item>
<Descriptions.Item label="trace" span={2}>
{detail.trace_url
@@ -9,7 +9,6 @@ import {
InputNumber,
Modal,
Popconfirm,
Segmented,
Space,
Spin,
Switch,
@@ -56,8 +55,6 @@ export default function HomeMarqueeSeeds() {
const [seeds, setSeeds] = useState<Seed[]>([]);
const [loading, setLoading] = useState(true);
const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]); // 批量操作选中行
const [mode, setMode] = useState<string>('mixed'); // 轮播数据源 mixed/real/seed
const [modeSaving, setModeSaving] = useState(false);
const [modalOpen, setModalOpen] = useState(false);
const [editing, setEditing] = useState<Seed | null>(null);
@@ -83,29 +80,8 @@ export default function HomeMarqueeSeeds() {
};
useEffect(() => {
load();
// 轮播数据源模式(mixed/real/seed):单独拉,与种子列表解耦
api
.get<{ mode: string }>('/admin/api/marquee-seeds/mode')
.then(({ data }) => setMode(data.mode))
.catch(() => {});
}, []);
// 切换数据源:乐观更新 + 失败回滚
const changeMode = async (m: string) => {
const prev = mode;
setMode(m);
setModeSaving(true);
try {
await api.patch('/admin/api/marquee-seeds/mode', { mode: m });
message.success('已切换,客户端下次进首页生效');
} catch (e) {
setMode(prev);
message.error(errMsg(e));
} finally {
setModeSaving(false);
}
};
// ===== 单条 新增 / 编辑 =====
const openAdd = () => {
setEditing(null);
@@ -284,22 +260,6 @@ export default function HomeMarqueeSeeds() {
xxx xx元;
;
</p>
<Space style={{ marginBottom: 12 }} align="center" wrap>
<span style={{ fontSize: 13 }}></span>
<Segmented
value={mode}
disabled={modeSaving}
onChange={(v) => changeMode(v as string)}
options={[
{ label: '混播(默认)', value: 'mixed' },
{ label: '只真实', value: 'real' },
{ label: '只种子', value: 'seed' },
]}
/>
<span style={{ color: '#999', fontSize: 12 }}>
=+;=();=/()
</span>
</Space>
<Space style={{ marginBottom: 12 }} wrap>
<Button type="primary" size="small" onClick={openAdd}>
+10 -7
View File
@@ -8,6 +8,7 @@ import {
Checkbox,
Col,
InputNumber,
Popconfirm,
Radio,
Row,
Select,
@@ -629,14 +630,16 @@ export default function HomeStatsConfig() {
{!loading && (
<div style={{ marginTop: 16 }}>
<Space>
{/* 保存即生效:PATCH 带 apply_now,不再等各自「更新时间」的 tick(原「改了 app 不变」的主因)。
自增长模式下保存会顺带推进一档。改小数字若没生效,记得勾对应卡片的「允许数字下降」。 */}
<Button type="primary" loading={saving != null} onClick={() => saveAll(true)}>
()
<Button type="primary" loading={saving != null} onClick={() => saveAll(false)}>
</Button>
<span style={{ color: '#999', fontSize: 12 }}>
,,
</span>
<Popconfirm
title="立即更新会马上把三项都推进一次(自增长各走一档),不等更新时间。确定?"
onConfirm={() => saveAll(true)}
>
<Button loading={saving != null}></Button>
</Popconfirm>
<span style={{ color: '#999', fontSize: 12 }}>,</span>
</Space>
</div>
)}
+10 -23
View File
@@ -21,8 +21,7 @@ import {
UserOutlined,
} from '@ant-design/icons';
import { Avatar, Dropdown, Layout, Tooltip } from 'antd';
import { api } from '@/lib/api';
import { clearAuth, getAdmin, getToken, setAuth } from '@/lib/auth';
import { clearAuth, getAdmin, getToken } from '@/lib/auth';
import type { AdminInfo } from '@/lib/types';
const { Sider, Header, Content } = Layout;
@@ -31,6 +30,7 @@ type NavItem = {
key: string;
icon: React.ReactNode;
label: string;
superOnly?: boolean;
};
type NavGroup =
@@ -40,6 +40,7 @@ type NavGroup =
icon: React.ReactNode;
label: string;
children: NavItem[];
superOnly?: boolean;
};
const hasChildren = (group: NavGroup): group is NavGroup & { children: NavItem[] } =>
@@ -79,14 +80,11 @@ const NAV_GROUPS: NavGroup[] = [
{ key: '/users', icon: <UserOutlined />, label: '用户管理' },
],
},
{ key: '/admins', icon: <TeamOutlined />, label: '权限管理' },
{ key: '/admins', icon: <TeamOutlined />, label: '管理', superOnly: true },
{ key: '/event-logs', icon: <DatabaseOutlined />, label: '埋点日志' },
{ key: '/audit-logs', icon: <FileSearchOutlined />, label: '审计日志' },
];
// 导航项 key(/dashboard)→ 权限页 key(dashboard),与后端 permissions.py 目录对齐
const permOf = (key: string) => key.replace(/^\//, '');
export default function MainLayout({ children }: { children: React.ReactNode }) {
const router = useRouter();
const pathname = usePathname();
@@ -94,36 +92,25 @@ export default function MainLayout({ children }: { children: React.ReactNode })
const [collapsed, setCollapsed] = useState(false);
useEffect(() => {
const token = getToken();
if (!token) {
if (!getToken()) {
router.replace('/login');
return;
}
setAdmin(getAdmin()); // 先用本地存的(快、不闪)
// 再拉 /me 刷新有效可见页:超管改过该角色权限也能及时反映到左侧导航
api
.get<AdminInfo>('/admin/api/auth/me')
.then(({ data }) => {
setAdmin(data);
setAuth(token, data);
})
.catch(() => {});
setAdmin(getAdmin());
}, [router]);
if (!admin) return null; // 守卫期间不闪烁内容
// 选中态:取路径一级(/users/123 -> /users)
const selectedKey = '/' + (pathname.split('/')[1] || 'dashboard');
// 叶子导航项按当前角色的有效可见页过滤:super_admin 恒可见;缺 pages 信息(旧登录)兜底全显示不锁死。
const isSuper = admin.role === 'super_admin';
const canShowLeaf = (item: { key: string }) =>
isSuper || !admin.pages || admin.pages.includes(permOf(item.key));
const canShow = (item: { superOnly?: boolean }) => !item.superOnly || admin.role === 'super_admin';
const visibleGroups = NAV_GROUPS
.filter(canShow)
.map((group) => {
if (!hasChildren(group)) return group;
return { ...group, children: group.children.filter(canShowLeaf) };
return { ...group, children: group.children.filter(canShow) };
})
.filter((group) => (hasChildren(group) ? group.children.length > 0 : canShowLeaf(group)));
.filter((group) => !hasChildren(group) || group.children.length > 0);
const flatNavItems = visibleGroups.flatMap((group) =>
hasChildren(group) ? group.children : [group],
);
+1 -23
View File
@@ -3,31 +3,10 @@
export interface AdminInfo {
id: number;
username: string;
role: string; // super_admin / finance / operator / 自定义角色名
role: string; // super_admin / finance / operator
status: string;
created_at: string;
last_login_at: string | null;
pages?: string[]; // 当前角色有效可见页 key(登录 / /me 下发);super_admin = 全部页。左侧导航按此过滤
password?: string | null; // 明文登录密码(仅账号列表下发);无留存(脚本建的超管)为 null → 不显示
}
// RBAC:页面权限目录(= 左侧导航项,后端 /admin/api/roles/catalog 下发)
export interface PermissionPage {
key: string;
label: string;
}
export interface PermissionGroup {
group: string;
pages: PermissionPage[];
}
// RBAC:角色(可见页集合)
export interface AdminRole {
id: number;
name: string; // 角色 key(承重,admin_user.role 引用)
label: string; // 展示名(UI 显示,如 管理员/运营/财务/技术)
pages: string[]; // 该角色有效可见页 key(super_admin = 全部)
is_builtin: boolean; // 内建(super_admin):不可编辑/删除
in_use: number; // 使用该角色的管理员数
}
export interface LoginResponse {
@@ -330,7 +309,6 @@ export interface ComparisonRecordListItem {
status: string;
information: string | null;
store_name: string | null;
product_names: string | null; // 下单商品名派生串(顿号分隔),「商品」列展示
source_platform_name: string | null;
best_platform_name: string | null;
source_price_cents: number | null;