管理后台左侧列表调整

This commit is contained in:
2026-07-07 18:49:47 +08:00
parent 98e9652865
commit 1ac72e9a69
14 changed files with 780 additions and 40 deletions
+2
View File
@@ -30,6 +30,7 @@ import ThirdPartyLogsPage from './pages/ThirdPartyLogsPage';
import StoreLogsPage from './pages/StoreLogsPage'; import StoreLogsPage from './pages/StoreLogsPage';
import PartnerLogsPage from './pages/PartnerLogsPage'; import PartnerLogsPage from './pages/PartnerLogsPage';
import WechatBindingsPage from './pages/WechatBindingsPage'; import WechatBindingsPage from './pages/WechatBindingsPage';
import HqPermissionsPage from './pages/HqPermissionsPage';
function RequireAuth({ children }: { children: React.ReactNode }) { function RequireAuth({ children }: { children: React.ReactNode }) {
if (!getToken()) return <Navigate to="/login" replace />; if (!getToken()) return <Navigate to="/login" replace />;
@@ -75,6 +76,7 @@ export default function App() {
<Route path="/logs/third-party" element={<ThirdPartyLogsPage />} /> <Route path="/logs/third-party" element={<ThirdPartyLogsPage />} />
<Route path="/deliveries" element={<DeliveriesPage />} /> <Route path="/deliveries" element={<DeliveriesPage />} />
<Route path="/deliveries/xiaofeixia" element={<XiaofeixiaTestPage />} /> <Route path="/deliveries/xiaofeixia" element={<XiaofeixiaTestPage />} />
<Route path="/hq-permissions" element={<HqPermissionsPage />} />
<Route path="/hq-accounts" element={<HqAccountsPage />} /> <Route path="/hq-accounts" element={<HqAccountsPage />} />
</Route> </Route>
<Route path="*" element={<Navigate to="/" replace />} /> <Route path="*" element={<Navigate to="/" replace />} />
+13 -11
View File
@@ -14,6 +14,7 @@ import {
LogoutOutlined, LogoutOutlined,
CloudUploadOutlined, CloudUploadOutlined,
FileTextOutlined, FileTextOutlined,
LockOutlined,
} from '@ant-design/icons'; } from '@ant-design/icons';
import { clearAuth, request, type HqProfile } from '../lib/api'; import { clearAuth, request, type HqProfile } from '../lib/api';
import { bindAdminEllipsisTitle } from '../lib/ellipsis-title'; import { bindAdminEllipsisTitle } from '../lib/ellipsis-title';
@@ -34,7 +35,6 @@ const MENU_ITEMS: MenuProps['items'] = [
], ],
}, },
{ key: '/orders', icon: <ShoppingOutlined />, label: '订单' }, { key: '/orders', icon: <ShoppingOutlined />, label: '订单' },
{ key: '/resources', icon: <CloudUploadOutlined />, label: 'OSS 资源库' },
{ {
key: 'stores-group', key: 'stores-group',
icon: <ShopOutlined />, icon: <ShopOutlined />,
@@ -54,6 +54,7 @@ const MENU_ITEMS: MenuProps['items'] = [
{ key: '/partners', label: '开城合伙人' }, { key: '/partners', label: '开城合伙人' },
{ key: '/cities', label: '开城城市' }, { key: '/cities', label: '开城城市' },
{ key: '/partner-accounts', label: '开城合伙人账户' }, { key: '/partner-accounts', label: '开城合伙人账户' },
{ key: '/partner-bills', label: '合伙人结算' },
], ],
}, },
{ {
@@ -67,8 +68,17 @@ const MENU_ITEMS: MenuProps['items'] = [
{ key: '/redeem/debug', label: '核销调试' }, { key: '/redeem/debug', label: '核销调试' },
], ],
}, },
{ key: '/partner-bills', icon: <TeamOutlined />, label: '合伙人结算' }, {
key: 'deliveries-group',
icon: <CarOutlined />,
label: '配送单',
children: [
{ key: '/deliveries', label: '配送单列表' },
{ key: '/deliveries/xiaofeixia', label: '小飞侠联调' },
],
},
{ key: '/tickets', icon: <CarOutlined />, label: '工单中心' }, { key: '/tickets', icon: <CarOutlined />, label: '工单中心' },
{ key: '/resources', icon: <CloudUploadOutlined />, label: 'OSS 资源库' },
{ {
key: 'logs-group', key: 'logs-group',
icon: <FileTextOutlined />, icon: <FileTextOutlined />,
@@ -81,15 +91,7 @@ const MENU_ITEMS: MenuProps['items'] = [
{ key: '/logs/third-party', label: '第三方日志' }, { key: '/logs/third-party', label: '第三方日志' },
], ],
}, },
{ { key: '/hq-permissions', icon: <LockOutlined />, label: '权限分配' },
key: 'deliveries-group',
icon: <CarOutlined />,
label: '配送单',
children: [
{ key: '/deliveries', label: '配送单列表' },
{ key: '/deliveries/xiaofeixia', label: '小飞侠联调' },
],
},
{ key: '/hq-accounts', icon: <SafetyOutlined />, label: 'HQ账户' }, { key: '/hq-accounts', icon: <SafetyOutlined />, label: 'HQ账户' },
]; ];
+2 -1
View File
@@ -6,7 +6,8 @@ export const HQ_OPERATION_ACTION_OPTIONS = [
{ value: 'PARTNER_ACCOUNT_CREATE', label: '新增合伙人账户' }, { value: 'PARTNER_ACCOUNT_CREATE', label: '新增合伙人账户' },
{ value: 'PARTNER_ACCOUNT_UPDATE', label: '编辑合伙人账户' }, { value: 'PARTNER_ACCOUNT_UPDATE', label: '编辑合伙人账户' },
{ value: 'HQ_ACCOUNT_CREATE', label: '新增 HQ 管理员' }, { value: 'HQ_ACCOUNT_CREATE', label: '新增 HQ 管理员' },
{ value: 'HQ_ACCOUNT_UPDATE', label: '编辑 HQ 管理员/权限' }, { value: 'HQ_ACCOUNT_UPDATE', label: '编辑 HQ 管理员' },
{ value: 'HQ_PERMISSION_UPDATE', label: '配置 HQ 权限' },
{ value: 'USER_DELETE', label: '删除用户' }, { value: 'USER_DELETE', label: '删除用户' },
{ value: 'USER_BATCH_DELETE', label: '批量删除用户' }, { value: 'USER_BATCH_DELETE', label: '批量删除用户' },
{ value: 'ORDER_SHIP', label: '订单发货' }, { value: 'ORDER_SHIP', label: '订单发货' },
+85 -16
View File
@@ -1,6 +1,6 @@
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import { import {
Button, Drawer, Form, Input, Modal, Select, Space, Table, Tag, Typography, message, Button, Drawer, Form, Input, Modal, Radio, Select, Space, Table, Tag, Typography, message,
} from 'antd'; } from 'antd';
import type { ColumnsType } from 'antd/es/table'; import type { ColumnsType } from 'antd/es/table';
import { request, type HqProfile } from '../lib/api'; import { request, type HqProfile } from '../lib/api';
@@ -8,7 +8,15 @@ import { ACCOUNT_STATUS_LABELS, fmtTime } from '../lib/constants';
import { useAdminList } from '../lib/useAdminList'; import { useAdminList } from '../lib/useAdminList';
type Row = { type Row = {
id: string; phone: string; name: string; adminRole: string; status: string; lastLoginAt: string | null; createdAt: string; id: string;
phone: string;
loginName: string | null;
hasPassword: boolean;
name: string;
adminRole: string;
status: string;
lastLoginAt: string | null;
createdAt: string;
}; };
const ROLE_LABELS: Record<string, string> = { const ROLE_LABELS: Record<string, string> = {
@@ -38,6 +46,7 @@ export default function HqAccountsPage() {
const [detail, setDetail] = useState<Row | null>(null); const [detail, setDetail] = useState<Row | null>(null);
const [drawerOpen, setDrawerOpen] = useState(false); const [drawerOpen, setDrawerOpen] = useState(false);
const [createOpen, setCreateOpen] = useState(false); const [createOpen, setCreateOpen] = useState(false);
const credentialType = Form.useWatch('credentialType', createForm) ?? 'phone';
const isSuperAdmin = profile?.adminRole === 'SUPER_ADMIN'; const isSuperAdmin = profile?.adminRole === 'SUPER_ADMIN';
useEffect(() => { useEffect(() => {
@@ -46,7 +55,18 @@ export default function HqAccountsPage() {
const columns: ColumnsType<Row> = [ const columns: ColumnsType<Row> = [
{ title: '姓名', dataIndex: 'name' }, { title: '姓名', dataIndex: 'name' },
{ title: '用户名', dataIndex: 'loginName', width: 120, render: (v) => v || '—' },
{ title: '手机', dataIndex: 'phone', width: 130 }, { title: '手机', dataIndex: 'phone', width: 130 },
{
title: '登录方式',
width: 110,
render: (_, r) => (
<Space size={4}>
{r.hasPassword ? <Tag color="blue"></Tag> : null}
<Tag></Tag>
</Space>
),
},
{ title: '角色', dataIndex: 'adminRole', width: 110, render: (r) => ROLE_LABELS[r] || r }, { title: '角色', dataIndex: 'adminRole', width: 110, render: (r) => ROLE_LABELS[r] || r },
{ title: '状态', dataIndex: 'status', width: 90, render: (s) => <Tag>{ACCOUNT_STATUS_LABELS[s] || s}</Tag> }, { title: '状态', dataIndex: 'status', width: 90, render: (s) => <Tag>{ACCOUNT_STATUS_LABELS[s] || s}</Tag> },
{ title: '最后登录', dataIndex: 'lastLoginAt', width: 160, render: fmtTime }, { title: '最后登录', dataIndex: 'lastLoginAt', width: 160, render: fmtTime },
@@ -55,7 +75,12 @@ export default function HqAccountsPage() {
render: (_, row) => ( render: (_, row) => (
<Button type="link" size="small" disabled={!isSuperAdmin} onClick={() => { <Button type="link" size="small" disabled={!isSuperAdmin} onClick={() => {
setDetail(row); setDetail(row);
editForm.setFieldsValue(row); editForm.setFieldsValue({
name: row.name,
loginName: row.loginName,
adminRole: row.adminRole,
status: row.status,
});
setDrawerOpen(true); setDrawerOpen(true);
}}></Button> }}></Button>
), ),
@@ -66,7 +91,18 @@ export default function HqAccountsPage() {
<div> <div>
<Space style={{ marginBottom: 16, width: '100%', justifyContent: 'space-between' }}> <Space style={{ marginBottom: 16, width: '100%', justifyContent: 'space-between' }}>
<Typography.Title level={4} style={{ margin: 0 }}>HQ </Typography.Title> <Typography.Title level={4} style={{ margin: 0 }}>HQ </Typography.Title>
{isSuperAdmin && <Button type="primary" onClick={() => setCreateOpen(true)}></Button>} {isSuperAdmin && (
<Button
type="primary"
onClick={() => {
createForm.resetFields();
createForm.setFieldsValue({ credentialType: 'phone', adminRole: 'OPS' });
setCreateOpen(true);
}}
>
</Button>
)}
</Space> </Space>
<Form form={form} layout="inline" style={{ marginBottom: 16 }} onFinish={(v) => { setFilters(v); setPage(1); }}> <Form form={form} layout="inline" style={{ marginBottom: 16 }} onFinish={(v) => { setFilters(v); setPage(1); }}>
<Form.Item name="phone" label="手机"><Input allowClear /></Form.Item> <Form.Item name="phone" label="手机"><Input allowClear /></Form.Item>
@@ -82,7 +118,9 @@ export default function HqAccountsPage() {
<Button type="primary" onClick={async () => { <Button type="primary" onClick={async () => {
if (!detail) return; if (!detail) return;
const v = await editForm.validateFields(); const v = await editForm.validateFields();
await request(`/admin/hq-accounts/${detail.id}`, { method: 'PUT', body: JSON.stringify(v) }); const payload = { ...v };
if (!payload.password) delete payload.password;
await request(`/admin/hq-accounts/${detail.id}`, { method: 'PUT', body: JSON.stringify(payload) });
message.success('已保存'); message.success('已保存');
setDrawerOpen(false); setDrawerOpen(false);
void reload(); void reload();
@@ -90,6 +128,10 @@ export default function HqAccountsPage() {
}> }>
<Form form={editForm} layout="vertical"> <Form form={editForm} layout="vertical">
<Form.Item name="name" label="姓名" rules={[{ required: true }]}><Input /></Form.Item> <Form.Item name="name" label="姓名" rules={[{ required: true }]}><Input /></Form.Item>
<Form.Item name="loginName" label="用户名"><Input placeholder="用于密码登录" /></Form.Item>
<Form.Item name="password" label="新密码" extra="留空则不修改">
<Input.Password placeholder="至少 6 位" />
</Form.Item>
<Form.Item name="adminRole" label="角色"> <Form.Item name="adminRole" label="角色">
<Select options={Object.entries(ROLE_LABELS).map(([value, label]) => ({ value, label }))} /> <Select options={Object.entries(ROLE_LABELS).map(([value, label]) => ({ value, label }))} />
</Form.Item> </Form.Item>
@@ -98,20 +140,47 @@ export default function HqAccountsPage() {
</Form.Item> </Form.Item>
</Form> </Form>
</Drawer> </Drawer>
<Modal title="新建 HQ 账户" open={createOpen} onCancel={() => setCreateOpen(false)} onOk={async () => { <Modal
const v = await createForm.validateFields(); title="新建 HQ 账户"
await request('/admin/hq-accounts', { method: 'POST', body: JSON.stringify(v) }); open={createOpen}
message.success('已创建'); onCancel={() => setCreateOpen(false)}
setCreateOpen(false); onOk={async () => {
createForm.resetFields(); const v = await createForm.validateFields();
void reload(); await request('/admin/hq-accounts', { method: 'POST', body: JSON.stringify(v) });
}}> message.success('已创建');
<Form form={createForm} layout="vertical"> setCreateOpen(false);
<Form.Item name="phone" label="手机" rules={[{ required: true }]}><Input /></Form.Item> createForm.resetFields();
void reload();
}}
>
<Form form={createForm} layout="vertical" initialValues={{ credentialType: 'phone', adminRole: 'OPS' }}>
<Form.Item name="credentialType" label="创建方式">
<Radio.Group>
<Radio value="phone"></Radio>
<Radio value="password"></Radio>
</Radio.Group>
</Form.Item>
<Form.Item name="name" label="姓名" rules={[{ required: true }]}><Input /></Form.Item> <Form.Item name="name" label="姓名" rules={[{ required: true }]}><Input /></Form.Item>
<Form.Item name="adminRole" label="角色" initialValue="OPS"> <Form.Item name="adminRole" label="角色">
<Select options={Object.entries(ROLE_LABELS).map(([value, label]) => ({ value, label }))} /> <Select options={Object.entries(ROLE_LABELS).map(([value, label]) => ({ value, label }))} />
</Form.Item> </Form.Item>
{credentialType === 'phone' ? (
<Form.Item name="phone" label="手机号" rules={[{ required: true, message: '请输入手机号' }]}>
<Input maxLength={11} />
</Form.Item>
) : (
<>
<Form.Item name="loginName" label="用户名" rules={[{ required: true, message: '请输入用户名' }]}>
<Input autoComplete="off" />
</Form.Item>
<Form.Item name="password" label="密码" rules={[{ required: true, message: '请输入密码' }, { min: 6, message: '至少 6 位' }]}>
<Input.Password autoComplete="new-password" />
</Form.Item>
<Form.Item name="phone" label="手机号(可选)" extra="不填则自动生成占位手机号,用于满足账号唯一约束">
<Input maxLength={11} />
</Form.Item>
</>
)}
</Form> </Form>
</Modal> </Modal>
</div> </div>
@@ -0,0 +1,264 @@
import { useEffect, useMemo, useState } from 'react';
import {
Alert,
Button,
Card,
Checkbox,
Col,
Form,
Row,
Select,
Space,
Tabs,
Tag,
Typography,
message,
} from 'antd';
import {
HQ_ADMIN_ROLES,
HQ_PERMISSION_CATALOG,
type HqPermissionKey,
} from '@dukang/shared-types';
import { request, type HqProfile } from '../lib/api';
type RolePermRes = { role: string; permissionKeys: string[] };
type AccountOption = { id: string; name: string; phone: string; loginName: string | null; adminRole: string };
type AccountPermRes = {
account: AccountOption;
permissionKeys: string[];
rolePermissionKeys: string[];
userPermissionKeys: string[];
effectivePermissionKeys: string[];
};
const ROLE_LABELS = Object.fromEntries(HQ_ADMIN_ROLES.map((r) => [r.value, r.label]));
function PermissionChecklist({
value,
onChange,
disabled,
}: {
value: string[];
onChange: (keys: string[]) => void;
disabled?: boolean;
}) {
return (
<Checkbox.Group
style={{ width: '100%' }}
value={value}
disabled={disabled}
onChange={(checked) => onChange(checked as string[])}
>
<Row gutter={[8, 8]}>
{HQ_PERMISSION_CATALOG.map((item) => (
<Col key={item.key} span={8}>
<Checkbox value={item.key}>{item.label}</Checkbox>
</Col>
))}
</Row>
</Checkbox.Group>
);
}
export default function HqPermissionsPage() {
const [profile, setProfile] = useState<HqProfile | null>(null);
const [role, setRole] = useState<string>('OPS');
const [roleKeys, setRoleKeys] = useState<string[]>([]);
const [roleLoading, setRoleLoading] = useState(false);
const [roleSaving, setRoleSaving] = useState(false);
const [accounts, setAccounts] = useState<AccountOption[]>([]);
const [accountId, setAccountId] = useState<string>();
const [accountKeys, setAccountKeys] = useState<string[]>([]);
const [roleInheritedKeys, setRoleInheritedKeys] = useState<string[]>([]);
const [accountLoading, setAccountLoading] = useState(false);
const [accountSaving, setAccountSaving] = useState(false);
const previewEffectiveKeys = useMemo(
() => [...new Set([...roleInheritedKeys, ...accountKeys])],
[roleInheritedKeys, accountKeys],
);
const isSuperAdmin = profile?.adminRole === 'SUPER_ADMIN';
useEffect(() => {
request<HqProfile>('/admin/auth/me').then(setProfile).catch(() => {});
}, []);
useEffect(() => {
if (!isSuperAdmin) return;
request<{ items: AccountOption[] }>('/admin/hq-accounts?page=1&pageSize=100')
.then((res) => setAccounts(res.items))
.catch(() => {});
}, [isSuperAdmin]);
useEffect(() => {
if (!isSuperAdmin || !role) return;
setRoleLoading(true);
request<RolePermRes>(`/admin/hq-permissions/roles/${role}`)
.then((res) => setRoleKeys(res.permissionKeys))
.finally(() => setRoleLoading(false));
}, [isSuperAdmin, role]);
useEffect(() => {
if (!isSuperAdmin || !accountId) return;
setAccountLoading(true);
request<AccountPermRes>(`/admin/hq-permissions/accounts/${accountId}`)
.then((res) => {
setAccountKeys(res.userPermissionKeys);
setRoleInheritedKeys(res.rolePermissionKeys);
})
.finally(() => setAccountLoading(false));
}, [isSuperAdmin, accountId]);
async function saveRolePermissions() {
setRoleSaving(true);
try {
const res = await request<RolePermRes>(`/admin/hq-permissions/roles/${role}`, {
method: 'PUT',
body: JSON.stringify({ permissionKeys: roleKeys }),
});
setRoleKeys(res.permissionKeys);
message.success('角色权限已保存');
} catch (e) {
message.error(e instanceof Error ? e.message : '保存失败');
} finally {
setRoleSaving(false);
}
}
async function saveAccountPermissions() {
if (!accountId) return;
setAccountSaving(true);
try {
const res = await request<AccountPermRes>(`/admin/hq-permissions/accounts/${accountId}`, {
method: 'PUT',
body: JSON.stringify({ permissionKeys: accountKeys }),
});
setAccountKeys(res.userPermissionKeys);
setRoleInheritedKeys(res.rolePermissionKeys);
message.success('用户权限已保存');
} catch (e) {
message.error(e instanceof Error ? e.message : '保存失败');
} finally {
setAccountSaving(false);
}
}
if (!isSuperAdmin) {
return (
<div>
<Typography.Title level={4}></Typography.Title>
<Alert type="warning" showIcon message="仅超级管理员可配置权限" />
</div>
);
}
return (
<div>
<Typography.Title level={4}></Typography.Title>
<Typography.Paragraph type="secondary">
=
</Typography.Paragraph>
<Tabs
items={[
{
key: 'role',
label: '按角色分配',
children: (
<Card loading={roleLoading}>
<Form layout="inline" style={{ marginBottom: 16 }}>
<Form.Item label="角色">
<Select
style={{ width: 180 }}
value={role}
onChange={setRole}
options={HQ_ADMIN_ROLES.map((r) => ({
value: r.value,
label: r.label,
disabled: r.value === 'SUPER_ADMIN',
}))}
/>
</Form.Item>
</Form>
{role === 'SUPER_ADMIN' ? (
<Alert type="info" showIcon message="超级管理员拥有全部权限,无需配置" />
) : (
<>
<PermissionChecklist value={roleKeys} onChange={setRoleKeys} />
<div style={{ marginTop: 16 }}>
<Button type="primary" loading={roleSaving} onClick={() => void saveRolePermissions()}>
</Button>
</div>
</>
)}
</Card>
),
},
{
key: 'user',
label: '按用户分配',
children: (
<Card loading={accountLoading}>
<Form layout="inline" style={{ marginBottom: 16 }}>
<Form.Item label="HQ 账户">
<Select
showSearch
allowClear
placeholder="选择账户"
style={{ width: 320 }}
value={accountId}
onChange={setAccountId}
optionFilterProp="label"
options={accounts
.filter((a) => a.adminRole !== 'SUPER_ADMIN')
.map((a) => ({
value: a.id,
label: `${a.name} · ${a.loginName || a.phone} · ${ROLE_LABELS[a.adminRole] || a.adminRole}`,
}))}
/>
</Form.Item>
</Form>
{!accountId ? (
<Alert type="info" showIcon message="请先选择要配置的 HQ 账户" />
) : (
<>
<Space wrap style={{ marginBottom: 12 }}>
<span></span>
{roleInheritedKeys.map((key) => {
const item = HQ_PERMISSION_CATALOG.find((p) => p.key === key);
return (
<Tag key={key} color="blue">
{item?.label || key}
</Tag>
);
})}
</Space>
<Typography.Paragraph type="secondary">
</Typography.Paragraph>
<PermissionChecklist value={accountKeys} onChange={setAccountKeys} />
<Space wrap style={{ marginTop: 12 }}>
<span></span>
{previewEffectiveKeys.map((key) => {
const item = HQ_PERMISSION_CATALOG.find((p) => p.key === (key as HqPermissionKey));
return <Tag key={key}>{item?.label || key}</Tag>;
})}
</Space>
<div style={{ marginTop: 16 }}>
<Button type="primary" loading={accountSaving} onClick={() => void saveAccountPermissions()}>
</Button>
</div>
</>
)}
</Card>
),
},
]}
/>
</div>
);
}
@@ -0,0 +1,45 @@
export const HQ_PERMISSION_CATALOG = [
{ key: 'dashboard', label: '概览' },
{ key: 'users', label: '用户管理' },
{ key: 'wechat_bindings', label: '微信绑定' },
{ key: 'products', label: '商品管理' },
{ key: 'orders', label: '订单管理' },
{ key: 'stores', label: '门店管理' },
{ key: 'partners', label: '开城管理' },
{ key: 'benefit', label: '好客权益' },
{ key: 'deliveries', label: '配送单' },
{ key: 'tickets', label: '工单中心' },
{ key: 'resources', label: 'OSS 资源库' },
{ key: 'logs', label: '日志' },
{ key: 'hq_permissions', label: '权限分配' },
{ key: 'hq_accounts', label: 'HQ 账户' },
] as const;
export type HqPermissionKey = (typeof HQ_PERMISSION_CATALOG)[number]['key'];
export const HQ_ADMIN_ROLES = [
{ value: 'SUPER_ADMIN', label: '超级管理员' },
{ value: 'OPS', label: '运营' },
{ value: 'FINANCE', label: '财务' },
{ value: 'CUSTOMER_SERVICE', label: '客服' },
] as const;
export const HQ_ROLE_DEFAULT_PERMISSIONS: Record<string, HqPermissionKey[]> = {
SUPER_ADMIN: HQ_PERMISSION_CATALOG.map((p) => p.key),
OPS: [
'dashboard',
'users',
'wechat_bindings',
'products',
'orders',
'stores',
'partners',
'benefit',
'deliveries',
'tickets',
'resources',
'logs',
],
FINANCE: ['dashboard', 'orders', 'stores', 'partners', 'benefit', 'logs'],
CUSTOMER_SERVICE: ['dashboard', 'users', 'orders', 'tickets', 'logs'],
};
+1
View File
@@ -13,3 +13,4 @@ export * from './user-log';
export * from './store-log'; export * from './store-log';
export * from './partner-log'; export * from './partner-log';
export * from './promo'; export * from './promo';
export * from './hq-permissions';
+22
View File
@@ -506,9 +506,31 @@ model HqAccount {
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3) createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
updatedAt DateTime @updatedAt @map("updated_at") @db.DateTime(3) updatedAt DateTime @updatedAt @map("updated_at") @db.DateTime(3)
permissions HqAccountPermission[]
@@map("hq_account") @@map("hq_account")
} }
model HqRolePermission {
adminRole HqAdminRole @map("admin_role")
permissionKey String @map("permission_key") @db.VarChar(64)
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
@@id([adminRole, permissionKey])
@@map("hq_role_permission")
}
model HqAccountPermission {
hqAccountId BigInt @map("hq_account_id") @db.UnsignedBigInt
permissionKey String @map("permission_key") @db.VarChar(64)
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
hqAccount HqAccount @relation(fields: [hqAccountId], references: [id], onDelete: Cascade)
@@id([hqAccountId, permissionKey])
@@map("hq_account_permission")
}
// ─── USER ───────────────────────────────────────────── // ─── USER ─────────────────────────────────────────────
model User { model User {
@@ -8,6 +8,7 @@ export const HqOperationAction = {
PARTNER_ACCOUNT_UPDATE: 'PARTNER_ACCOUNT_UPDATE', PARTNER_ACCOUNT_UPDATE: 'PARTNER_ACCOUNT_UPDATE',
HQ_ACCOUNT_CREATE: 'HQ_ACCOUNT_CREATE', HQ_ACCOUNT_CREATE: 'HQ_ACCOUNT_CREATE',
HQ_ACCOUNT_UPDATE: 'HQ_ACCOUNT_UPDATE', HQ_ACCOUNT_UPDATE: 'HQ_ACCOUNT_UPDATE',
HQ_PERMISSION_UPDATE: 'HQ_PERMISSION_UPDATE',
USER_DELETE: 'USER_DELETE', USER_DELETE: 'USER_DELETE',
USER_BATCH_DELETE: 'USER_BATCH_DELETE', USER_BATCH_DELETE: 'USER_BATCH_DELETE',
ORDER_SHIP: 'ORDER_SHIP', ORDER_SHIP: 'ORDER_SHIP',
@@ -50,7 +51,8 @@ export const HQ_OPERATION_ACTION_LABELS: Record<string, string> = {
[HqOperationAction.PARTNER_ACCOUNT_CREATE]: '新增合伙人账户', [HqOperationAction.PARTNER_ACCOUNT_CREATE]: '新增合伙人账户',
[HqOperationAction.PARTNER_ACCOUNT_UPDATE]: '编辑合伙人账户', [HqOperationAction.PARTNER_ACCOUNT_UPDATE]: '编辑合伙人账户',
[HqOperationAction.HQ_ACCOUNT_CREATE]: '新增 HQ 管理员', [HqOperationAction.HQ_ACCOUNT_CREATE]: '新增 HQ 管理员',
[HqOperationAction.HQ_ACCOUNT_UPDATE]: '编辑 HQ 管理员/权限', [HqOperationAction.HQ_ACCOUNT_UPDATE]: '编辑 HQ 管理员',
[HqOperationAction.HQ_PERMISSION_UPDATE]: '配置 HQ 权限',
[HqOperationAction.USER_DELETE]: '删除用户', [HqOperationAction.USER_DELETE]: '删除用户',
[HqOperationAction.USER_BATCH_DELETE]: '批量删除用户', [HqOperationAction.USER_BATCH_DELETE]: '批量删除用户',
[HqOperationAction.ORDER_SHIP]: '订单发货', [HqOperationAction.ORDER_SHIP]: '订单发货',
@@ -4,6 +4,31 @@ import { PrismaService } from '../../common/prisma/prisma.module';
import { serializeBigInt } from '../../common/decorators/current-user.decorator'; import { serializeBigInt } from '../../common/decorators/current-user.decorator';
import type { AdminHqAccountsQueryDto } from './dto/admin-query.dto'; import type { AdminHqAccountsQueryDto } from './dto/admin-query.dto';
import type { CreateHqAccountDto, UpdateHqAccountDto } from './dto/admin-mutate.dto'; import type { CreateHqAccountDto, UpdateHqAccountDto } from './dto/admin-mutate.dto';
import { hashPassword } from '../../common/crypto/password.util';
function mapHqAccountRow(account: {
id: bigint;
phone: string;
loginName: string | null;
passwordHash: string | null;
name: string;
adminRole: string;
status: string;
lastLoginAt: Date | null;
createdAt: Date;
}) {
return {
id: account.id,
phone: account.phone,
loginName: account.loginName,
hasPassword: !!account.passwordHash,
name: account.name,
adminRole: account.adminRole,
status: account.status,
lastLoginAt: account.lastLoginAt,
createdAt: account.createdAt,
};
}
@Injectable() @Injectable()
export class AdminHqAccountsService { export class AdminHqAccountsService {
@@ -23,42 +48,130 @@ export class AdminHqAccountsService {
orderBy: { createdAt: 'desc' }, orderBy: { createdAt: 'desc' },
skip: (page - 1) * pageSize, skip: (page - 1) * pageSize,
take: pageSize, take: pageSize,
select: {
id: true,
phone: true,
loginName: true,
passwordHash: true,
name: true,
adminRole: true,
status: true,
lastLoginAt: true,
createdAt: true,
},
}), }),
this.prisma.hqAccount.count({ where }), this.prisma.hqAccount.count({ where }),
]); ]);
return serializeBigInt({ items, total, page, pageSize }); return serializeBigInt({
items: items.map(mapHqAccountRow),
total,
page,
pageSize,
});
} }
async detail(id: bigint) { async detail(id: bigint) {
const account = await this.prisma.hqAccount.findUnique({ where: { id } }); const account = await this.prisma.hqAccount.findUnique({
where: { id },
select: {
id: true,
phone: true,
loginName: true,
passwordHash: true,
name: true,
adminRole: true,
status: true,
lastLoginAt: true,
createdAt: true,
},
});
if (!account) throw new NotFoundException('HQ 账号不存在'); if (!account) throw new NotFoundException('HQ 账号不存在');
return serializeBigInt(account); return serializeBigInt(mapHqAccountRow(account));
} }
async create(dto: CreateHqAccountDto) { async create(dto: CreateHqAccountDto) {
const exists = await this.prisma.hqAccount.findUnique({ where: { phone: dto.phone } }); const adminRole = (dto.adminRole ?? 'OPS') as 'SUPER_ADMIN' | 'OPS' | 'FINANCE' | 'CUSTOMER_SERVICE';
if (exists) throw new BadRequestException('手机号已存在');
if (dto.credentialType === 'phone') {
if (!dto.phone?.trim()) throw new BadRequestException('请填写手机号');
const phone = dto.phone.trim();
const exists = await this.prisma.hqAccount.findUnique({ where: { phone } });
if (exists) throw new BadRequestException('手机号已存在');
const account = await this.prisma.hqAccount.create({
data: { phone, name: dto.name, adminRole },
});
return serializeBigInt(mapHqAccountRow({ ...account, passwordHash: null }));
}
if (!dto.loginName?.trim() || !dto.password) {
throw new BadRequestException('账号密码模式需填写用户名和密码');
}
const loginName = dto.loginName.trim();
const loginTaken = await this.prisma.hqAccount.findUnique({ where: { loginName } });
if (loginTaken) throw new BadRequestException('用户名已存在');
const phone = dto.phone?.trim() || (await this.generatePlaceholderPhone());
const phoneTaken = await this.prisma.hqAccount.findUnique({ where: { phone } });
if (phoneTaken) throw new BadRequestException('手机号已存在');
const account = await this.prisma.hqAccount.create({ const account = await this.prisma.hqAccount.create({
data: { data: {
phone: dto.phone, phone,
loginName,
passwordHash: hashPassword(dto.password),
name: dto.name, name: dto.name,
adminRole: (dto.adminRole ?? 'OPS') as 'SUPER_ADMIN' | 'OPS' | 'FINANCE' | 'CUSTOMER_SERVICE', adminRole,
}, },
}); });
return serializeBigInt(account); return serializeBigInt(mapHqAccountRow(account));
} }
async update(id: bigint, dto: UpdateHqAccountDto) { async update(id: bigint, dto: UpdateHqAccountDto) {
const current = await this.prisma.hqAccount.findUnique({ where: { id } });
if (!current) throw new NotFoundException('HQ 账号不存在');
if (dto.loginName !== undefined) {
const loginName = dto.loginName.trim();
if (!loginName) throw new BadRequestException('用户名不能为空');
const conflict = await this.prisma.hqAccount.findFirst({
where: { loginName, id: { not: id } },
});
if (conflict) throw new BadRequestException('用户名已存在');
}
const account = await this.prisma.hqAccount.update({ const account = await this.prisma.hqAccount.update({
where: { id }, where: { id },
data: { data: {
...(dto.name !== undefined ? { name: dto.name } : {}), ...(dto.name !== undefined ? { name: dto.name } : {}),
...(dto.loginName !== undefined ? { loginName: dto.loginName.trim() } : {}),
...(dto.password ? { passwordHash: hashPassword(dto.password) } : {}),
...(dto.adminRole !== undefined ...(dto.adminRole !== undefined
? { adminRole: dto.adminRole as 'SUPER_ADMIN' | 'OPS' | 'FINANCE' | 'CUSTOMER_SERVICE' } ? { adminRole: dto.adminRole as 'SUPER_ADMIN' | 'OPS' | 'FINANCE' | 'CUSTOMER_SERVICE' }
: {}), : {}),
...(dto.status !== undefined ? { status: dto.status as 'ACTIVE' | 'DISABLED' } : {}), ...(dto.status !== undefined ? { status: dto.status as 'ACTIVE' | 'DISABLED' } : {}),
}, },
select: {
id: true,
phone: true,
loginName: true,
passwordHash: true,
name: true,
adminRole: true,
status: true,
lastLoginAt: true,
createdAt: true,
},
}); });
return serializeBigInt(account); return serializeBigInt(mapHqAccountRow(account));
}
private async generatePlaceholderPhone(): Promise<string> {
for (let i = 0; i < 8; i += 1) {
const suffix = `${Date.now()}${Math.floor(Math.random() * 1000)}`.slice(-8);
const phone = `199${suffix}`;
const exists = await this.prisma.hqAccount.findUnique({ where: { phone } });
if (!exists) return phone;
}
throw new BadRequestException('无法生成占位手机号,请手动填写');
} }
} }
@@ -0,0 +1,50 @@
import { Body, Controller, Get, Param, Put, UseGuards } from '@nestjs/common';
import { HqAuthGuard } from '../../common/guards/hq-auth.guard';
import { SuperAdminGuard } from '../../common/guards/super-admin.guard';
import { HqOperation } from '../../common/hq-operation/hq-operation.decorator';
import { HqOperationAction } from '../../common/hq-operation/hq-operation.constants';
import { AdminHqPermissionsService } from './admin-hq-permissions.service';
import { SaveHqAccountPermissionsDto, SaveHqRolePermissionsDto } from './dto/admin-mutate.dto';
@Controller('admin/hq-permissions')
@UseGuards(HqAuthGuard, SuperAdminGuard)
export class AdminHqPermissionsController {
constructor(private readonly service: AdminHqPermissionsService) {}
@Get('catalog')
catalog() {
return this.service.catalog();
}
@Get('roles/:role')
getRolePermissions(@Param('role') role: string) {
return this.service.getRolePermissions(role);
}
@Put('roles/:role')
@HqOperation({
action: HqOperationAction.HQ_PERMISSION_UPDATE,
refType: 'HQ_ROLE',
refIdParam: 'role',
includeBody: true,
})
saveRolePermissions(@Param('role') role: string, @Body() dto: SaveHqRolePermissionsDto) {
return this.service.saveRolePermissions(role, dto.permissionKeys);
}
@Get('accounts/:id')
getAccountPermissions(@Param('id') id: string) {
return this.service.getAccountPermissions(BigInt(id));
}
@Put('accounts/:id')
@HqOperation({
action: HqOperationAction.HQ_PERMISSION_UPDATE,
refType: 'HQ_ACCOUNT',
refIdParam: 'id',
includeBody: true,
})
saveAccountPermissions(@Param('id') id: string, @Body() dto: SaveHqAccountPermissionsDto) {
return this.service.saveAccountPermissions(BigInt(id), dto.permissionKeys);
}
}
@@ -0,0 +1,120 @@
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import {
HQ_PERMISSION_CATALOG,
HQ_ROLE_DEFAULT_PERMISSIONS,
type HqPermissionKey,
} from '@dukang/shared-types';
import { PrismaService } from '../../common/prisma/prisma.module';
import { serializeBigInt } from '../../common/decorators/current-user.decorator';
const VALID_PERMISSION_KEYS = new Set<string>(HQ_PERMISSION_CATALOG.map((p) => p.key));
function assertPermissionKeys(keys: string[]) {
const invalid = keys.filter((key) => !VALID_PERMISSION_KEYS.has(key));
if (invalid.length) {
throw new BadRequestException(`无效权限项: ${invalid.join(', ')}`);
}
}
@Injectable()
export class AdminHqPermissionsService {
constructor(private readonly prisma: PrismaService) {}
catalog() {
return {
permissions: HQ_PERMISSION_CATALOG,
roles: Object.entries(HQ_ROLE_DEFAULT_PERMISSIONS).map(([role, permissionKeys]) => ({
role,
permissionKeys,
})),
};
}
async getRolePermissions(role: string) {
const rows = await this.prisma.hqRolePermission.findMany({
where: { adminRole: role as 'SUPER_ADMIN' | 'OPS' | 'FINANCE' | 'CUSTOMER_SERVICE' },
select: { permissionKey: true },
});
const permissionKeys =
rows.length > 0
? rows.map((r) => r.permissionKey)
: [...(HQ_ROLE_DEFAULT_PERMISSIONS[role] ?? [])];
return { role, permissionKeys };
}
async saveRolePermissions(role: string, permissionKeys: string[]) {
if (role === 'SUPER_ADMIN') {
throw new BadRequestException('超级管理员拥有全部权限,无需配置');
}
assertPermissionKeys(permissionKeys);
const adminRole = role as 'OPS' | 'FINANCE' | 'CUSTOMER_SERVICE';
await this.prisma.$transaction([
this.prisma.hqRolePermission.deleteMany({ where: { adminRole } }),
...(permissionKeys.length
? [
this.prisma.hqRolePermission.createMany({
data: permissionKeys.map((permissionKey) => ({ adminRole, permissionKey })),
}),
]
: []),
]);
return this.getRolePermissions(role);
}
async getAccountPermissions(accountId: bigint) {
const account = await this.prisma.hqAccount.findUnique({
where: { id: accountId },
select: { id: true, name: true, phone: true, loginName: true, adminRole: true, status: true },
});
if (!account) throw new NotFoundException('HQ 账号不存在');
if (account.adminRole === 'SUPER_ADMIN') {
return serializeBigInt({
account,
permissionKeys: HQ_PERMISSION_CATALOG.map((p) => p.key),
rolePermissionKeys: HQ_PERMISSION_CATALOG.map((p) => p.key),
userPermissionKeys: [],
effectivePermissionKeys: HQ_PERMISSION_CATALOG.map((p) => p.key),
});
}
const [rolePerms, userPerms] = await Promise.all([
this.getRolePermissions(account.adminRole),
this.prisma.hqAccountPermission.findMany({
where: { hqAccountId: accountId },
select: { permissionKey: true },
}),
]);
const userPermissionKeys = userPerms.map((p) => p.permissionKey);
const effectivePermissionKeys = [
...new Set([...rolePerms.permissionKeys, ...userPermissionKeys]),
] as HqPermissionKey[];
return serializeBigInt({
account,
permissionKeys: userPermissionKeys,
rolePermissionKeys: rolePerms.permissionKeys,
userPermissionKeys,
effectivePermissionKeys,
});
}
async saveAccountPermissions(accountId: bigint, permissionKeys: string[]) {
const account = await this.prisma.hqAccount.findUnique({ where: { id: accountId } });
if (!account) throw new NotFoundException('HQ 账号不存在');
if (account.adminRole === 'SUPER_ADMIN') {
throw new BadRequestException('超级管理员拥有全部权限,无需配置');
}
assertPermissionKeys(permissionKeys);
await this.prisma.$transaction([
this.prisma.hqAccountPermission.deleteMany({ where: { hqAccountId: accountId } }),
...(permissionKeys.length
? [
this.prisma.hqAccountPermission.createMany({
data: permissionKeys.map((permissionKey) => ({ hqAccountId: accountId, permissionKey })),
}),
]
: []),
]);
return this.getAccountPermissions(accountId);
}
}
@@ -1,5 +1,17 @@
import { Type } from 'class-transformer'; import { Type } from 'class-transformer';
import { IsArray, IsBoolean, IsIn, IsNotEmpty, IsNumber, IsObject, IsOptional, IsString, Min } from 'class-validator'; import {
IsArray,
IsBoolean,
IsIn,
IsNotEmpty,
IsNumber,
IsObject,
IsOptional,
IsString,
Min,
MinLength,
ValidateIf,
} from 'class-validator';
export class UpdateStoreStatusDto { export class UpdateStoreStatusDto {
@IsString() @IsString()
@@ -413,9 +425,22 @@ export class UpdateDeliveryDto {
} }
export class CreateHqAccountDto { export class CreateHqAccountDto {
@IsIn(['phone', 'password'])
credentialType: 'phone' | 'password';
@IsOptional()
@IsString()
phone?: string;
@ValidateIf((o: CreateHqAccountDto) => o.credentialType === 'password')
@IsString() @IsString()
@IsNotEmpty() @IsNotEmpty()
phone: string; loginName?: string;
@ValidateIf((o: CreateHqAccountDto) => o.credentialType === 'password')
@IsString()
@MinLength(6)
password?: string;
@IsString() @IsString()
@IsNotEmpty() @IsNotEmpty()
@@ -427,6 +452,14 @@ export class CreateHqAccountDto {
} }
export class UpdateHqAccountDto { export class UpdateHqAccountDto {
@IsOptional()
@IsString()
loginName?: string;
@IsOptional()
@IsString()
@MinLength(6)
password?: string;
@IsOptional() @IsOptional()
@IsString() @IsString()
name?: string; name?: string;
@@ -440,6 +473,18 @@ export class UpdateHqAccountDto {
status?: string; status?: string;
} }
export class SaveHqRolePermissionsDto {
@IsArray()
@IsString({ each: true })
permissionKeys: string[];
}
export class SaveHqAccountPermissionsDto {
@IsArray()
@IsString({ each: true })
permissionKeys: string[];
}
export class CreateProductDto { export class CreateProductDto {
@IsString() @IsString()
@IsNotEmpty() @IsNotEmpty()
@@ -46,6 +46,8 @@ import { AdminRedeemDebugController } from './admin-redeem-debug.controller';
import { AdminRedeemDebugService } from './admin-redeem-debug.service'; import { AdminRedeemDebugService } from './admin-redeem-debug.service';
import { AdminWechatBindingsController } from './admin-wechat-bindings.controller'; import { AdminWechatBindingsController } from './admin-wechat-bindings.controller';
import { AdminWechatBindingsService } from './admin-wechat-bindings.service'; import { AdminWechatBindingsService } from './admin-wechat-bindings.service';
import { AdminHqPermissionsController } from './admin-hq-permissions.controller';
import { AdminHqPermissionsService } from './admin-hq-permissions.service';
@Module({ @Module({
imports: [IamModule, TradeModule, BenefitModule, CommonModule, IntegrationsModule, RedeemModule], imports: [IamModule, TradeModule, BenefitModule, CommonModule, IntegrationsModule, RedeemModule],
@@ -75,6 +77,7 @@ import { AdminWechatBindingsService } from './admin-wechat-bindings.service';
AdminRedeemDebugController, AdminRedeemDebugController,
AdminPromoCodesController, AdminPromoCodesController,
AdminWechatBindingsController, AdminWechatBindingsController,
AdminHqPermissionsController,
], ],
providers: [ providers: [
AdminDashboardService, AdminDashboardService,
@@ -98,6 +101,7 @@ import { AdminWechatBindingsService } from './admin-wechat-bindings.service';
AdminRedeemDebugService, AdminRedeemDebugService,
AdminPromoCodesService, AdminPromoCodesService,
AdminWechatBindingsService, AdminWechatBindingsService,
AdminHqPermissionsService,
SuperAdminGuard, SuperAdminGuard,
], ],
}) })