refactor(web-antd): 超管账户与公司菜单/权限页改为两栏布局,并统一左侧列表托盘与卡片样式

This commit is contained in:
小蟑螂
2026-05-25 17:35:02 +08:00
parent 4fe8fb5846
commit 2f44eaa9d2
9 changed files with 830 additions and 525 deletions
@@ -0,0 +1,20 @@
/**
* 左侧两栏页:列表滚动区容器(灰底托盘,与 Card 白底、列表项卡片分层)
*/
export const SIDEBAR_LIST_SHELL_CLASS =
'flex min-h-0 flex-1 flex-col gap-1.5 overflow-y-auto rounded-lg border border-border bg-slate-100 p-2 dark:border-border dark:bg-slate-900/55';
/**
* 左侧两栏页:列表项选中 / 未选中样式(每项为独立白卡片)
*/
export function sidebarListRowClass(active: boolean, extraClasses = '') {
return [
'rounded-lg border px-3 py-2.5 text-sm font-semibold transition-all',
extraClasses,
active
? 'border-2 border-primary bg-card text-foreground shadow-md ring-2 ring-primary/30 dark:bg-primary/20 dark:ring-primary/40'
: 'border-border bg-card text-foreground shadow-sm hover:border-primary/50 hover:shadow-md dark:border-border/80',
]
.filter(Boolean)
.join(' ');
}
@@ -22,7 +22,7 @@ const goWorkbench = () => {
}; };
const goImportTask = () => { const goImportTask = () => {
router.push('/import'); router.push('/import/order');
}; };
</script> </script>
@@ -33,6 +33,10 @@ import { getProductPageApi } from '#/api/ecommerce/product';
import { getShopPageApi } from '#/api/ecommerce/shop/apis'; import { getShopPageApi } from '#/api/ecommerce/shop/apis';
import BrushOrderFormModal from './components/BrushOrderFormModal.vue'; import BrushOrderFormModal from './components/BrushOrderFormModal.vue';
import {
SIDEBAR_LIST_SHELL_CLASS,
sidebarListRowClass,
} from '#/utils/sidebar-list-styles';
defineOptions({ name: 'BrushOrderManagement' }); defineOptions({ name: 'BrushOrderManagement' });
@@ -289,12 +293,11 @@ function shopRowClass(id: number | 'all') {
id === 'all' id === 'all'
? selectedShopId.value === undefined ? selectedShopId.value === undefined
: selectedShopId.value === id; : selectedShopId.value === id;
return [ const layout =
'flex cursor-pointer items-center gap-2 rounded-lg border px-3 py-2.5 text-sm font-semibold transition-colors', id === 'all'
active ? 'mb-1.5 flex w-full cursor-pointer items-center gap-2 text-left'
? 'border-primary bg-primary/8 text-primary' : 'group flex w-full cursor-pointer items-center gap-2';
: 'border-transparent bg-muted/30 text-foreground hover:bg-muted/60', return sidebarListRowClass(active, layout);
].join(' ');
} }
const handleAdd = () => { const handleAdd = () => {
@@ -375,11 +378,10 @@ const formatAmount = (amount: number) => `¥${amount.toFixed(2)}`;
</span> </span>
</template> </template>
<Spin :spinning="shopsLoading" class="flex min-h-0 flex-1 flex-col"> <Spin :spinning="shopsLoading" class="flex min-h-0 flex-1 flex-col">
<div class="flex min-h-0 flex-1 flex-col overflow-y-auto"> <div :class="SIDEBAR_LIST_SHELL_CLASS">
<button <button
type="button" type="button"
:class="shopRowClass('all')" :class="shopRowClass('all')"
class="mb-1 w-full text-left"
@click="selectShopAll" @click="selectShopAll"
> >
<span class="min-w-0 flex-1 truncate">全部店铺</span> <span class="min-w-0 flex-1 truncate">全部店铺</span>
@@ -34,6 +34,10 @@ import { getShopPageApi } from '#/api/ecommerce/shop/apis';
import { getAllPromotionFeeTypeListApi } from '#/api/ecommerce/promotion-fee-type/apis'; import { getAllPromotionFeeTypeListApi } from '#/api/ecommerce/promotion-fee-type/apis';
import PromotionFeeFormModal from './components/PromotionFeeFormModal.vue'; import PromotionFeeFormModal from './components/PromotionFeeFormModal.vue';
import {
SIDEBAR_LIST_SHELL_CLASS,
sidebarListRowClass,
} from '#/utils/sidebar-list-styles';
defineOptions({ name: 'PromotionFeeManagement' }); defineOptions({ name: 'PromotionFeeManagement' });
@@ -295,12 +299,11 @@ function shopRowClass(id: number | 'all') {
id === 'all' id === 'all'
? selectedShopId.value === undefined ? selectedShopId.value === undefined
: selectedShopId.value === id; : selectedShopId.value === id;
return [ const layout =
'flex cursor-pointer items-center gap-2 rounded-lg border px-3 py-2.5 text-sm font-semibold transition-colors', id === 'all'
active ? 'mb-1.5 flex w-full cursor-pointer items-center gap-2 text-left'
? 'border-primary bg-primary/8 text-primary' : 'group flex w-full cursor-pointer items-center gap-2';
: 'border-transparent bg-muted/30 text-foreground hover:bg-muted/60', return sidebarListRowClass(active, layout);
].join(' ');
} }
</script> </script>
@@ -341,11 +344,10 @@ function shopRowClass(id: number | 'all') {
</span> </span>
</template> </template>
<Spin :spinning="shopsLoading" class="flex min-h-0 flex-1 flex-col"> <Spin :spinning="shopsLoading" class="flex min-h-0 flex-1 flex-col">
<div class="flex min-h-0 flex-1 flex-col overflow-y-auto"> <div :class="SIDEBAR_LIST_SHELL_CLASS">
<button <button
type="button" type="button"
:class="shopRowClass('all')" :class="shopRowClass('all')"
class="mb-1 w-full text-left"
@click="selectShopAll" @click="selectShopAll"
> >
<span class="min-w-0 flex-1 truncate">全部店铺</span> <span class="min-w-0 flex-1 truncate">全部店铺</span>
@@ -32,6 +32,10 @@ import {
} from '#/api/ecommerce/shop-monthly-target'; } from '#/api/ecommerce/shop-monthly-target';
import ShopMonthlyTargetFormModal from './components/ShopMonthlyTargetFormModal.vue'; import ShopMonthlyTargetFormModal from './components/ShopMonthlyTargetFormModal.vue';
import {
SIDEBAR_LIST_SHELL_CLASS,
sidebarListRowClass,
} from '#/utils/sidebar-list-styles';
defineOptions({ name: 'ShopMonthlyTargetManagement' }); defineOptions({ name: 'ShopMonthlyTargetManagement' });
@@ -259,12 +263,11 @@ function shopRowClass(id: number | 'all') {
id === 'all' id === 'all'
? selectedShopId.value === undefined ? selectedShopId.value === undefined
: selectedShopId.value === id; : selectedShopId.value === id;
return [ const layout =
'flex cursor-pointer items-center gap-2 rounded-lg border px-3 py-2.5 text-sm font-semibold transition-colors', id === 'all'
active ? 'mb-1.5 flex w-full cursor-pointer items-center gap-2 text-left'
? 'border-primary bg-primary/8 text-primary' : 'group flex w-full cursor-pointer items-center gap-2';
: 'border-transparent bg-muted/30 text-foreground hover:bg-muted/60', return sidebarListRowClass(active, layout);
].join(' ');
} }
</script> </script>
@@ -305,11 +308,10 @@ function shopRowClass(id: number | 'all') {
</span> </span>
</template> </template>
<Spin :spinning="shopsLoading" class="flex min-h-0 flex-1 flex-col"> <Spin :spinning="shopsLoading" class="flex min-h-0 flex-1 flex-col">
<div class="flex min-h-0 flex-1 flex-col overflow-y-auto"> <div :class="SIDEBAR_LIST_SHELL_CLASS">
<button <button
type="button" type="button"
:class="shopRowClass('all')" :class="shopRowClass('all')"
class="mb-1 w-full text-left"
@click="selectShopAll" @click="selectShopAll"
> >
<span class="min-w-0 flex-1 truncate">全部店铺</span> <span class="min-w-0 flex-1 truncate">全部店铺</span>
@@ -1,4 +1,5 @@
<script lang="ts" setup> <script lang="ts" setup>
import type { CompanyVO } from '#/api/organization/company/types';
import type { import type {
SuperAccountDTO, SuperAccountDTO,
SuperAccountVO, SuperAccountVO,
@@ -23,7 +24,6 @@ defineOptions({ name: 'SuperAccountFormModal' });
const emit = defineEmits<Emits>(); const emit = defineEmits<Emits>();
// 创建 vben modal
const [Modal, modalApi] = useVbenModal({ const [Modal, modalApi] = useVbenModal({
draggable: true, draggable: true,
class: 'w-[500px]', class: 'w-[500px]',
@@ -35,13 +35,12 @@ const [Modal, modalApi] = useVbenModal({
}, },
}); });
// 响应式数据
const formRef = ref(); const formRef = ref();
const loading = ref(false); const loading = ref(false);
const isEdit = ref(false); const isEdit = ref(false);
const currentAccountData = ref<null | SuperAccountVO.AccountInfoVO>(null); const currentAccountData = ref<null | SuperAccountVO.AccountInfoVO>(null);
const presetCompany = ref<CompanyVO.CompanyInfoVO | null>(null);
// 表单数据
const formData = ref< const formData = ref<
SuperAccountDTO.SuperCreateAccountDTO & { status?: number } SuperAccountDTO.SuperCreateAccountDTO & { status?: number }
>({ >({
@@ -55,70 +54,68 @@ const formData = ref<
role: '', role: '',
avatarImageId: undefined, avatarImageId: undefined,
remark: '', remark: '',
status: 0, status: 1,
}); });
// 模态框标题
const modalTitle = computed(() => (isEdit.value ? '编辑账户' : '添加账户')); const modalTitle = computed(() => (isEdit.value ? '编辑账户' : '添加账户'));
// 状态选项
const statusOptions = [ const statusOptions = [
{ label: '正常', value: 0 }, { label: '正常', value: 1 },
{ label: '删除', value: 1 }, { label: '停用', value: 0 },
{ label: '停用', value: 2 },
{ label: '冻结', value: 3 },
]; ];
// 重置表单
function resetForm() { function resetForm() {
formData.value = { formData.value = {
loginCode: '', loginCode: '',
password: '', password: '',
realName: '', realName: '',
phone: '', phone: '',
companyId: 0, companyId: presetCompany.value?.id ?? 0,
departmentId: undefined, departmentId: undefined,
positionId: undefined, positionId: undefined,
role: '', role: '',
avatarImageId: undefined, avatarImageId: undefined,
remark: '', remark: '',
status: 0, status: 1,
}; };
formRef.value?.resetFields(); formRef.value?.resetFields();
} }
// 处理模态框关闭
function handleCancel() { function handleCancel() {
modalApi.close(); modalApi.close();
} }
// 暴露给父组件的方法 function open(
function open(accountData?: null | SuperAccountVO.AccountInfoVO) { accountData?: null | SuperAccountVO.AccountInfoVO,
company?: CompanyVO.CompanyInfoVO | null,
) {
isEdit.value = !!accountData; isEdit.value = !!accountData;
currentAccountData.value = accountData || null; currentAccountData.value = accountData || null;
presetCompany.value = company || null;
resetForm(); resetForm();
if (accountData) { if (accountData) {
formData.value = { formData.value = {
loginCode: accountData.loginCode, loginCode: accountData.loginCode,
password: '', // 编辑时密码为空 password: '',
realName: accountData.realName, realName: accountData.realName,
phone: accountData.phone || '', phone: accountData.phone || '',
companyId: accountData.companyId || 0, companyId: accountData.companyId || presetCompany.value?.id || 0,
departmentId: accountData.departmentId, departmentId: accountData.departmentId,
positionId: accountData.positionId, positionId: accountData.positionId,
role: accountData.role || '', role: accountData.role || '',
avatarImageId: accountData.avatarImageId, avatarImageId: accountData.avatarImageId,
remark: accountData.remark || '', remark: accountData.remark || '',
status: accountData.status, status: accountData.status ?? 1,
}; };
} else if (presetCompany.value) {
formData.value.companyId = presetCompany.value.id;
} }
modalApi.open(); modalApi.open();
} }
// 处理表单提交
async function handleSubmit() { async function handleSubmit() {
try { try {
await formRef.value?.validate(); await formRef.value?.validate();
@@ -137,25 +134,24 @@ async function handleSubmit() {
modalApi.close(); modalApi.close();
} catch (error: any) { } catch (error: any) {
console.error('保存账户失败:', error); console.error('保存账户失败:', error);
const errorMessage = message.error(
error?.response?.data?.message || error?.message || '保存账户失败'; error?.response?.data?.message || error?.message || '保存账户失败',
message.error(errorMessage); );
} finally { } finally {
loading.value = false; loading.value = false;
} }
} }
// 监听 modal 关闭状态
watch( watch(
() => modalApi.useStore()?.value?.isOpen, () => modalApi.useStore()?.value?.isOpen,
(newVal) => { (newVal) => {
if (!newVal) { if (!newVal) {
presetCompany.value = null;
resetForm(); resetForm();
} }
}, },
); );
// 暴露方法给父组件
defineExpose({ defineExpose({
open, open,
}); });
@@ -169,6 +165,10 @@ defineExpose({
:label-col="{ span: 6 }" :label-col="{ span: 6 }"
:wrapper-col="{ span: 18 }" :wrapper-col="{ span: 18 }"
> >
<Form.Item v-if="presetCompany" label="所属公司">
<Input :value="presetCompany.name" disabled />
</Form.Item>
<Form.Item <Form.Item
label="登录账号" label="登录账号"
name="loginCode" name="loginCode"
@@ -224,6 +224,7 @@ defineExpose({
</Form.Item> </Form.Item>
<Form.Item <Form.Item
v-if="!presetCompany"
label="公司ID" label="公司ID"
name="companyId" name="companyId"
:rules="[{ required: true, message: '请输入公司ID' }]" :rules="[{ required: true, message: '请输入公司ID' }]"
@@ -1,144 +1,131 @@
<script lang="ts" setup> <script lang="ts" setup>
import type { VxeGridProps } from '#/adapter/vxe-table'; import type { VxeGridProps } from '#/adapter/vxe-table';
import type { CompanyVO } from '#/api/organization/company/types';
import type { import type {
SuperAccountDTO, SuperAccountDTO,
SuperAccountVO, SuperAccountVO,
} from '#/api/organization/account-super'; } from '#/api/organization/account-super';
import type { PageQueryDTO } from '#/types/common'; import type { PageQueryDTO } from '#/types/common';
import { computed, ref } from 'vue'; import { computed, onMounted, ref, watch } from 'vue';
import { Page } from '@vben/common-ui'; import { Page } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons'; import { createIconifyIcon } from '@vben/icons';
import { Button, message, Popconfirm, Space, Tag } from 'ant-design-vue'; import {
Button,
Card,
Empty,
Flex,
Input,
message,
Pagination,
Popconfirm,
Select,
Space,
Spin,
Tag,
} from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table'; import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getCompanyPageApi } from '#/api/organization/company';
import { import {
super_deleteAccountApi, super_deleteAccountApi,
super_getAccountPageApi, super_getAccountPageApi,
} from '#/api/organization/account-super'; } from '#/api/organization/account-super';
import SuperAccountFormModal from './components/SuperAccountFormModal.vue'; import SuperAccountFormModal from './components/SuperAccountFormModal.vue';
import {
SIDEBAR_LIST_SHELL_CLASS,
sidebarListRowClass,
} from '#/utils/sidebar-list-styles';
defineOptions({ name: 'SuperAccountManagement' }); defineOptions({ name: 'SuperAccountManagement' });
// 创建图标组件
const PlusIcon = createIconifyIcon('lucide:plus'); const PlusIcon = createIconifyIcon('lucide:plus');
const BuildingIcon = createIconifyIcon('lucide:building-2');
// 响应式数据
const loading = ref(false); const loading = ref(false);
const accountFormModalRef = ref(); const accountFormModalRef = ref();
// 搜索表单 const companySearchForm = ref({
name: '',
status: undefined as number | undefined,
});
const companyList = ref<CompanyVO.CompanyInfoVO[]>([]);
const companyLoading = ref(false);
const companyPagination = ref({
current: 1,
pageSize: 20,
total: 0,
});
const currentCompany = ref<CompanyVO.CompanyInfoVO | null>(null);
const searchForm = ref({ const searchForm = ref({
loginCode: undefined as string | undefined, loginCode: undefined as string | undefined,
realName: undefined as string | undefined, realName: undefined as string | undefined,
phone: undefined as string | undefined, phone: undefined as string | undefined,
companyId: undefined as number | undefined,
departmentId: undefined as number | undefined,
positionId: undefined as number | undefined,
role: undefined as string | undefined,
status: undefined as number | undefined, status: undefined as number | undefined,
}); });
// 状态选项
const statusOptions = [ const statusOptions = [
{ label: '正常', value: 0 }, { label: '正常', value: 1 },
{ label: '删除', value: 1 }, { label: '停用', value: 0 },
{ label: '停用', value: 2 },
{ label: '冻结', value: 3 },
]; ];
// 搜索表单配置 const selectedCompanyLabel = computed(() => {
const gridReloadRef = ref<(() => void) | null>(null); if (!currentCompany.value) {
const formOptions = computed(() => ({ return '全部账户';
schemas: [ }
{ return currentCompany.value.name;
fieldName: 'loginCode', });
label: '登录账号',
component: 'Input',
componentProps: {
placeholder: '请输入登录账号(回车搜索)',
onPressEnter: () => gridReloadRef.value?.(),
},
},
{
fieldName: 'realName',
label: '真实姓名',
component: 'Input',
componentProps: {
placeholder: '请输入真实姓名(回车搜索)',
onPressEnter: () => gridReloadRef.value?.(),
},
},
{
fieldName: 'phone',
label: '手机号',
component: 'Input',
componentProps: {
placeholder: '请输入手机号(回车搜索)',
onPressEnter: () => gridReloadRef.value?.(),
},
},
{
fieldName: 'status',
label: '状态',
component: 'Select',
componentProps: {
options: statusOptions,
placeholder: '请选择状态',
onChange: () => gridReloadRef.value?.(),
},
},
],
showDefaultActions: true,
collapsed: true,
collapsedRows: 1,
}));
// VbenVxeGrid 表格配置 const gridOptions: VxeGridProps<SuperAccountVO.AccountInfoVO> = {
const gridOptions: VxeGridProps<any> = {
columns: [ columns: [
{ { type: 'seq' as const, minWidth: 56, title: '序号' },
type: 'seq' as const,
minWidth: 'auto',
title: '序号',
},
{ {
field: 'loginCode', field: 'loginCode',
title: '登录账号', title: '登录账号',
minWidth: 120, minWidth: 120,
showOverflow: 'tooltip' as const,
}, },
{ {
field: 'realName', field: 'realName',
title: '真实姓名', title: '真实姓名',
minWidth: 120, minWidth: 120,
showOverflow: 'tooltip' as const,
}, },
{ {
field: 'phone', field: 'phone',
title: '手机号', title: '手机号',
minWidth: 120, minWidth: 120,
showOverflow: 'tooltip' as const,
}, },
{ {
field: 'companyName', field: 'companyName',
title: '公司', title: '公司',
minWidth: 150, minWidth: 140,
showOverflow: 'tooltip' as const,
}, },
{ {
field: 'departmentName', field: 'departmentName',
title: '部门', title: '部门',
minWidth: 120, minWidth: 120,
showOverflow: 'tooltip' as const,
}, },
{ {
field: 'positionName', field: 'positionName',
title: '职位', title: '职位',
minWidth: 120, minWidth: 120,
showOverflow: 'tooltip' as const,
}, },
{ {
field: 'role', field: 'role',
title: '角色', title: '角色',
minWidth: 100, minWidth: 100,
showOverflow: 'tooltip' as const,
}, },
{ {
field: 'status', field: 'status',
@@ -150,15 +137,16 @@ const gridOptions: VxeGridProps<any> = {
field: 'createTime', field: 'createTime',
title: '创建时间', title: '创建时间',
minWidth: 160, minWidth: 160,
showOverflow: 'tooltip' as const,
}, },
{ {
title: '操作', title: '操作',
width: 120, minWidth: 140,
fixed: 'right' as const, fixed: 'right' as const,
slots: { default: 'action' }, slots: { default: 'action' },
}, },
], ],
height: 'auto', height: '100%',
border: true, border: true,
stripe: true, stripe: true,
rowConfig: { isHover: true }, rowConfig: { isHover: true },
@@ -193,7 +181,6 @@ const gridOptions: VxeGridProps<any> = {
| 'Total' | 'Total'
)[], )[],
}, },
// 配置远程加载
proxyConfig: { proxyConfig: {
ajax: { ajax: {
query: async ({ page }) => { query: async ({ page }) => {
@@ -202,7 +189,13 @@ const gridOptions: VxeGridProps<any> = {
const params: PageQueryDTO<SuperAccountDTO.AccountFilterDTO> = { const params: PageQueryDTO<SuperAccountDTO.AccountFilterDTO> = {
page: page.currentPage, page: page.currentPage,
pageSize: page.pageSize, pageSize: page.pageSize,
...searchForm.value, filters: {
loginCode: searchForm.value.loginCode || undefined,
realName: searchForm.value.realName || undefined,
phone: searchForm.value.phone || undefined,
status: searchForm.value.status,
companyId: currentCompany.value?.id,
},
}; };
const response = await super_getAccountPageApi(params); const response = await super_getAccountPageApi(params);
return { return {
@@ -210,14 +203,10 @@ const gridOptions: VxeGridProps<any> = {
total: response.total, total: response.total,
}; };
} catch (error: any) { } catch (error: any) {
console.error('查询数据失败:', error); message.error(
const errorMessage = error?.response?.data?.message || error?.message || '查询数据失败',
error?.response?.data?.message || error?.message || '查询数据失败'; );
message.error(errorMessage); return { items: [], total: 0 };
return {
items: [],
total: 0,
};
} finally { } finally {
loading.value = false; loading.value = false;
} }
@@ -226,145 +215,344 @@ const gridOptions: VxeGridProps<any> = {
}, },
}; };
// 表格实例
const [Grid, gridApi] = useVbenVxeGrid({ const [Grid, gridApi] = useVbenVxeGrid({
gridOptions, gridOptions,
formOptions: formOptions.value, showSearchForm: false,
showSearchForm: true, tableTitle: '账户列表',
tableTitle: '超级账户管理',
});
gridReloadRef.value = () => gridApi.reload();
// 计算属性
const hasSelected = computed(() => {
const vxeTable = (gridApi as any).grid;
return vxeTable?.getCheckboxRecords?.()?.length > 0;
}); });
// 刷新表格数据 async function searchCompanies() {
function refreshTable() { companyLoading.value = true;
if (gridApi) { try {
gridApi.reload(); const result = await getCompanyPageApi({
page: companyPagination.value.current,
pageSize: companyPagination.value.pageSize,
filters: {
name: companySearchForm.value.name || undefined,
status: companySearchForm.value.status,
},
});
companyList.value = result.records;
companyPagination.value.total = result.total;
} catch (error: any) {
message.error(error?.message || '获取公司列表失败');
} finally {
companyLoading.value = false;
} }
} }
const handleAdd = () => { function resetCompanySearch() {
accountFormModalRef.value?.open(); companySearchForm.value = { name: '', status: undefined };
}; companyPagination.value.current = 1;
searchCompanies();
}
const handleEdit = (row: SuperAccountVO.AccountInfoVO) => { function handleCompanyPageChange(page: number, pageSize: number) {
accountFormModalRef.value?.open(row); companyPagination.value.current = page;
}; companyPagination.value.pageSize = pageSize;
searchCompanies();
}
const handleDelete = async (row: SuperAccountVO.AccountInfoVO) => { function selectCompanyAll() {
currentCompany.value = null;
}
function selectCompany(company: CompanyVO.CompanyInfoVO) {
currentCompany.value = company;
}
function refreshTable() {
gridApi?.reload();
}
function handleAdd() {
if (!currentCompany.value) {
message.warning('请先选择具体公司,或在公司行点击「添加」');
return;
}
accountFormModalRef.value?.open(undefined, currentCompany.value);
}
function handleAddForCompany(company: CompanyVO.CompanyInfoVO) {
selectCompany(company);
accountFormModalRef.value?.open(undefined, company);
}
function handleEdit(row: SuperAccountVO.AccountInfoVO) {
accountFormModalRef.value?.open(row, currentCompany.value);
}
async function handleDelete(row: SuperAccountVO.AccountInfoVO) {
try { try {
await super_deleteAccountApi(row.id); await super_deleteAccountApi(row.id);
message.success('删除成功'); message.success('删除成功');
refreshTable(); refreshTable();
} catch (error: any) { } catch (error: any) {
console.error('删除失败:', error); message.error(
const errorMessage = error?.response?.data?.message || error?.message || '删除失败',
error?.response?.data?.message || error?.message || '删除失败';
message.error(errorMessage);
}
};
const handleBatchDelete = async () => {
const vxeTable = (gridApi as any).grid;
const selectedRows = vxeTable?.getCheckboxRecords?.();
if (!selectedRows?.length) {
message.warning('请选择要删除的数据');
return;
}
try {
const deletePromises = selectedRows.map(
(row: SuperAccountVO.AccountInfoVO) => super_deleteAccountApi(row.id),
); );
await Promise.all(deletePromises);
message.success(`成功删除 ${selectedRows.length} 条记录`);
refreshTable();
} catch (error: any) {
console.error('批量删除失败:', error);
const errorMessage =
error?.response?.data?.message || error?.message || '批量删除失败';
message.error(errorMessage);
} }
}; }
// 处理模态框成功回调
function handleModalSuccess() { function handleModalSuccess() {
refreshTable(); refreshTable();
} }
// 获取状态文本 function getStatusText(status: number) {
const getStatusText = (status: number) => { const statusMap: Record<number, string> = {
const statusMap = { 0: '停用',
0: '正常', 1: '正常',
1: '删除',
2: '停用',
3: '冻结',
}; };
return statusMap[status as keyof typeof statusMap] || '未知'; return statusMap[status] || '未知';
}; }
// 获取状态颜色 function getStatusColor(status: number) {
const getStatusColor = (status: number) => { const colorMap: Record<number, string> = {
const colorMap = { 0: 'orange',
0: 'green', 1: 'green',
1: 'red',
2: 'orange',
3: 'purple',
}; };
return colorMap[status as keyof typeof colorMap] || 'default'; return colorMap[status] || 'default';
}; }
function companyRowClass(id: number | 'all') {
const active =
id === 'all'
? currentCompany.value === null
: currentCompany.value?.id === id;
const layout =
id === 'all'
? 'mb-1.5 flex w-full cursor-pointer items-center gap-2 text-left'
: 'group flex w-full cursor-pointer items-center gap-2';
return sidebarListRowClass(active, layout);
}
watch(currentCompany, () => {
gridApi.reload();
});
onMounted(() => {
searchCompanies();
});
</script> </script>
<template> <template>
<Page title="超级账户管理" auto-content-height> <Page title="超级账户管理" :auto-content-height="true">
<template #description> <template #description>
<div class="text-foreground/80 mt-2"> <div class="text-foreground/80 mt-2">
管理超级管理员账户信息,支持账户的增删改查操作 左侧选择公司筛选右侧账户;首项「全部账户」展示所有账户,可在公司行快捷新增。
</div> </div>
</template> </template>
<!-- VbenVxeGrid 表格 --> <template #extra>
<Grid :loading="loading"> <Space>
<!-- 工具栏工具 --> <Button type="primary" @click="handleAdd">
<template #toolbar-tools> <PlusIcon class="mr-2 h-4 w-4" />
<Space> 新增账户
<Button type="primary" @click="handleAdd"> </Button>
<PlusIcon /> </Space>
添加账户 </template>
<Flex gap="middle" class="h-full min-h-0">
<!-- 左:公司 -->
<Card
class="flex h-full w-[420px] shrink-0 flex-col"
:body-style="{
height: '100%',
display: 'flex',
flexDirection: 'column',
gap: '8px',
minHeight: 0,
padding: '12px',
}"
>
<template #title>
<span class="flex items-center gap-2 text-base font-semibold">
<BuildingIcon class="h-4 w-4" />
公司
</span>
</template>
<Flex wrap="wrap" align="center" class="shrink-0 gap-2">
<Input
v-model:value="companySearchForm.name"
placeholder="公司名称"
allow-clear
class="min-w-[140px] flex-1"
@press-enter="searchCompanies"
/>
<Select
v-model:value="companySearchForm.status"
placeholder="状态"
allow-clear
class="w-[88px]"
:options="[
{ label: '启用', value: 1 },
{ label: '禁用', value: 0 },
]"
/>
<Button type="primary" size="small" @click="searchCompanies">
搜索
</Button> </Button>
<Button v-if="hasSelected" danger @click="handleBatchDelete"> <Button size="small" @click="resetCompanySearch">重置</Button>
批量删除 </Flex>
</Button>
</Space>
</template>
<!-- 状态列 --> <Spin :spinning="companyLoading" class="flex min-h-0 flex-1 flex-col">
<template #status="{ row }"> <div :class="SIDEBAR_LIST_SHELL_CLASS">
<Tag :color="getStatusColor(row.status)"> <button
{{ getStatusText(row.status) }} type="button"
</Tag> :class="companyRowClass('all')"
</template> @click="selectCompanyAll"
>
<span class="min-w-0 flex-1 truncate">全部账户</span>
<span class="shrink-0 text-xs font-normal text-muted-foreground">
全部记录
</span>
</button>
<Empty
v-if="!companyLoading && companyList.length === 0"
class="py-8"
description="暂无公司"
/>
<div v-else class="space-y-1">
<div
v-for="company in companyList"
:key="company.id"
:class="companyRowClass(company.id)"
>
<button
type="button"
class="min-w-0 flex-1 truncate text-left"
@click="selectCompany(company)"
>
<span class="block truncate">{{ company.name }}</span>
<span
class="mt-0.5 block truncate text-xs font-normal text-muted-foreground"
>
{{ company.status === 1 ? '启用' : '禁用' }}
</span>
</button>
<Button
type="link"
size="small"
class="!h-7 shrink-0 !px-1 !text-xs font-semibold opacity-80 group-hover:opacity-100"
@click.stop="handleAddForCompany(company)"
>
<PlusIcon class="mr-0.5 inline h-3.5 w-3.5" />
添加
</Button>
</div>
</div>
</div>
<!-- 操作列 --> <Flex justify="center" class="mt-2 shrink-0 pt-1">
<template #action="{ row }"> <Pagination
<Space> v-model:current="companyPagination.current"
<Button size="small" @click="handleEdit(row)"> 编辑 </Button> v-model:page-size="companyPagination.pageSize"
<Popconfirm :total="companyPagination.total"
title="确定要删除这个账户吗?" size="small"
@confirm="handleDelete(row)" :show-size-changer="true"
> :show-quick-jumper="true"
<Button size="small" danger> 删除 </Button> @change="handleCompanyPageChange"
</Popconfirm> />
</Space> </Flex>
</template> </Spin>
</Grid> </Card>
<!-- 右:账户列表 -->
<Card
class="flex h-full min-h-0 min-w-0 flex-1 flex-col"
:body-style="{
height: '100%',
minHeight: 0,
padding: 0,
display: 'flex',
flexDirection: 'column',
}"
>
<template #title>
<span class="text-base font-semibold">账户列表</span>
</template>
<template #extra>
<Space wrap size="small" class="max-w-[min(100%,42rem)]">
<Input
v-model:value="searchForm.loginCode"
allow-clear
placeholder="登录账号"
class="w-[120px]"
@press-enter="refreshTable"
/>
<Input
v-model:value="searchForm.realName"
allow-clear
placeholder="姓名"
class="w-[100px]"
@press-enter="refreshTable"
/>
<Input
v-model:value="searchForm.phone"
allow-clear
placeholder="手机号"
class="w-[120px]"
@press-enter="refreshTable"
/>
<Select
v-model:value="searchForm.status"
allow-clear
placeholder="状态"
class="min-w-[88px]"
:options="statusOptions"
@change="refreshTable"
/>
<Button size="small" @click="refreshTable">查询</Button>
</Space>
</template>
<div
class="shrink-0 border-t border-border px-4 py-2 text-xs text-muted-foreground"
>
当前:{{ selectedCompanyLabel }}
<template v-if="currentCompany">
<Tag
class="ml-2"
:color="currentCompany.status === 1 ? 'green' : 'red'"
>
{{ currentCompany.status === 1 ? '启用' : '禁用' }}
</Tag>
</template>
</div>
<div
class="min-h-0 flex-1 overflow-hidden px-2 pb-2 pt-0 sm:px-3 sm:pb-3"
>
<Grid :loading="loading" class="h-full min-h-0">
<template #toolbar-tools>
<span class="text-xs text-muted-foreground">
使用上方筛选条件查询;表格在区域内滚动
</span>
</template>
<template #status="{ row }">
<Tag :color="getStatusColor(row.status)">
{{ getStatusText(row.status) }}
</Tag>
</template>
<template #action="{ row }">
<Space>
<Button size="small" @click="handleEdit(row)">编辑</Button>
<Popconfirm
title="确定要删除这个账户吗?"
@confirm="handleDelete(row)"
>
<Button size="small" danger>删除</Button>
</Popconfirm>
</Space>
</template>
</Grid>
</div>
</Card>
</Flex>
<!-- 账户表单弹窗 -->
<SuperAccountFormModal <SuperAccountFormModal
ref="accountFormModalRef" ref="accountFormModalRef"
@success="handleModalSuccess" @success="handleModalSuccess"
@@ -4,15 +4,18 @@ import type { CompanyVO } from '#/api/organization/company/types';
import { computed, onMounted, ref } from 'vue'; import { computed, onMounted, ref } from 'vue';
import { Page } from '@vben/common-ui'; import { Page } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons';
import { import {
Button, Button,
Card, Card,
Empty,
Flex, Flex,
Input, Input,
message, message,
Pagination, Pagination,
Select, Select,
Space,
Spin, Spin,
Tag, Tag,
Tree, Tree,
@@ -24,40 +27,44 @@ import {
getCompanyMenuIdsApi, getCompanyMenuIdsApi,
} from '#/api/organization/company-menu/apis'; } from '#/api/organization/company-menu/apis';
import { getCompanyPageApi } from '#/api/organization/company'; import { getCompanyPageApi } from '#/api/organization/company';
import {
SIDEBAR_LIST_SHELL_CLASS,
sidebarListRowClass,
} from '#/utils/sidebar-list-styles';
defineOptions({ defineOptions({
name: 'CompanyMenuManagePage', name: 'CompanyMenuManagePage',
}); });
// 搜索表单 const BuildingIcon = createIconifyIcon('lucide:building-2');
const searchForm = ref({
const companySearchForm = ref({
name: '', name: '',
status: undefined as number | undefined, status: undefined as number | undefined,
}); });
// 公司列表
const companyList = ref<CompanyVO.CompanyInfoVO[]>([]); const companyList = ref<CompanyVO.CompanyInfoVO[]>([]);
const companyLoading = ref(false); const companyLoading = ref(false);
const companyPagination = ref({ const companyPagination = ref({
current: 1, current: 1,
pageSize: 10, pageSize: 20,
total: 0, total: 0,
}); });
// 当前选中的公司 const currentCompany = ref<CompanyVO.CompanyInfoVO | null>(null);
const currentCompany = ref<null | CompanyVO.CompanyInfoVO>(null);
// 所有菜单列表(扁平)
const systemMenuList = ref<any[]>([]); const systemMenuList = ref<any[]>([]);
// 当前公司的菜单ID列表
const companyMenuIds = ref<number[]>([]); const companyMenuIds = ref<number[]>([]);
const selectedMenuIds = ref<number[]>([]); const selectedMenuIds = ref<number[]>([]);
// 菜单加载状态
const menuLoading = ref(false); const menuLoading = ref(false);
// 树形数据 const selectedCompanyLabel = computed(() => {
if (!currentCompany.value) {
return '请先选择公司';
}
return currentCompany.value.name;
});
const menuTreeData = computed(() => { const menuTreeData = computed(() => {
const list = systemMenuList.value; const list = systemMenuList.value;
const map = new Map<number, any>(); const map = new Map<number, any>();
@@ -79,7 +86,6 @@ const menuTreeData = computed(() => {
return roots; return roots;
}); });
// 统计
const stats = computed(() => ({ const stats = computed(() => ({
total: systemMenuList.value.filter((m) => m.type === 'menu').length, total: systemMenuList.value.filter((m) => m.type === 'menu').length,
company: companyMenuIds.value.length, company: companyMenuIds.value.length,
@@ -87,7 +93,6 @@ const stats = computed(() => ({
changed: selectedMenuIds.value.length !== companyMenuIds.value.length, changed: selectedMenuIds.value.length !== companyMenuIds.value.length,
})); }));
// 搜索公司列表
async function searchCompanies() { async function searchCompanies() {
companyLoading.value = true; companyLoading.value = true;
try { try {
@@ -95,8 +100,8 @@ async function searchCompanies() {
page: companyPagination.value.current, page: companyPagination.value.current,
pageSize: companyPagination.value.pageSize, pageSize: companyPagination.value.pageSize,
filters: { filters: {
name: searchForm.value.name || undefined, name: companySearchForm.value.name || undefined,
status: searchForm.value.status, status: companySearchForm.value.status,
}, },
}); });
companyList.value = result.records; companyList.value = result.records;
@@ -108,13 +113,11 @@ async function searchCompanies() {
} }
} }
// 选择公司
async function selectCompany(company: CompanyVO.CompanyInfoVO) { async function selectCompany(company: CompanyVO.CompanyInfoVO) {
currentCompany.value = company; currentCompany.value = company;
await loadCompanyMenus(); await loadCompanyMenus();
} }
// 加载当前公司的菜单
async function loadCompanyMenus() { async function loadCompanyMenus() {
if (!currentCompany.value?.id) return; if (!currentCompany.value?.id) return;
menuLoading.value = true; menuLoading.value = true;
@@ -133,19 +136,16 @@ async function loadCompanyMenus() {
} }
} }
// Tree勾选变化
function handleTreeCheckChange( function handleTreeCheckChange(
checked: (number | string)[] | { checked: (number | string)[]; halfChecked: (number | string)[] }, checked: (number | string)[] | { checked: (number | string)[]; halfChecked: (number | string)[] },
) { ) {
const checkedKeys = Array.isArray(checked) ? checked : checked.checked; const checkedKeys = Array.isArray(checked) ? checked : checked.checked;
// 对比新旧值,找出被取消勾选的节点
const oldKeys = new Set<number>(selectedMenuIds.value); const oldKeys = new Set<number>(selectedMenuIds.value);
const newKeys = new Set<number>(checkedKeys as number[]); const newKeys = new Set<number>(checkedKeys as number[]);
const removedKeys = [...oldKeys].filter((k) => !newKeys.has(k)); const removedKeys = [...oldKeys].filter((k) => !newKeys.has(k));
const addedKeys = [...newKeys].filter((k) => !oldKeys.has(k)); const addedKeys = [...newKeys].filter((k) => !oldKeys.has(k));
// 如果是取消勾选,移除子节点
if (removedKeys.length > 0) { if (removedKeys.length > 0) {
const parentToChildren = new Map<number, number[]>(); const parentToChildren = new Map<number, number[]>();
for (const menu of systemMenuList.value) { for (const menu of systemMenuList.value) {
@@ -169,7 +169,6 @@ function handleTreeCheckChange(
} }
} }
// 如果是新增勾选,自动勾选所有祖先节点
if (addedKeys.length > 0) { if (addedKeys.length > 0) {
const menuMap = new Map<number, any>(); const menuMap = new Map<number, any>();
for (const menu of systemMenuList.value) { for (const menu of systemMenuList.value) {
@@ -192,7 +191,6 @@ function handleTreeCheckChange(
selectedMenuIds.value = [...newKeys]; selectedMenuIds.value = [...newKeys];
} }
// 全选/取消全选
function selectAll() { function selectAll() {
selectedMenuIds.value = systemMenuList.value selectedMenuIds.value = systemMenuList.value
.filter((m) => m.type === 'menu') .filter((m) => m.type === 'menu')
@@ -203,7 +201,6 @@ function selectNone() {
selectedMenuIds.value = []; selectedMenuIds.value = [];
} }
// 保存
async function handleSave() { async function handleSave() {
if (!currentCompany.value?.id) return; if (!currentCompany.value?.id) return;
try { try {
@@ -215,171 +212,197 @@ async function handleSave() {
} }
} }
// 重置搜索 function resetCompanySearch() {
function resetSearch() { companySearchForm.value = { name: '', status: undefined };
searchForm.value = { name: '', status: undefined };
companyPagination.value.current = 1; companyPagination.value.current = 1;
searchCompanies(); searchCompanies();
} }
// 分页 function handleCompanyPageChange(page: number, pageSize: number) {
function handlePageChange(page: number, pageSize: number) {
companyPagination.value.current = page; companyPagination.value.current = page;
companyPagination.value.pageSize = pageSize; companyPagination.value.pageSize = pageSize;
searchCompanies(); searchCompanies();
} }
// 初始化 function companyRowClass(companyId: number) {
const active = currentCompany.value?.id === companyId;
return sidebarListRowClass(active, 'w-full cursor-pointer text-left');
}
onMounted(() => { onMounted(() => {
searchCompanies(); searchCompanies();
}); });
</script> </script>
<template> <template>
<Page :auto-content-height="true"> <Page title="公司菜单管理" :auto-content-height="true">
<Flex gap="middle" class="h-full"> <template #description>
<!-- 左栏:公司列表 --> <div class="text-foreground/80 mt-2">
左侧选择公司,右侧勾选并保存该公司可访问的菜单。
</div>
</template>
<template #extra>
<Space>
<Button :disabled="!currentCompany" @click="selectNone">取消全选</Button>
<Button type="primary" :disabled="!currentCompany" @click="selectAll">
一键全选
</Button>
<Button
type="primary"
:disabled="!currentCompany || !stats.changed"
@click="handleSave"
>
保存配置
</Button>
</Space>
</template>
<Flex gap="middle" class="h-full min-h-0">
<!-- 左:公司 -->
<Card <Card
title="公司列表" class="flex h-full w-[420px] shrink-0 flex-col"
class="flex h-full max-w-[400px] flex-col"
:body-style="{ :body-style="{
height: '100%', height: '100%',
display: 'flex', display: 'flex',
flexDirection: 'column', flexDirection: 'column',
gap: '10px', gap: '8px',
minHeight: 0,
padding: '12px',
}" }"
> >
<!-- 搜索区域 --> <template #title>
<Flex class="flex-wrap gap-2"> <span class="flex items-center gap-2 text-base font-semibold">
<BuildingIcon class="h-4 w-4" />
公司
</span>
</template>
<Flex wrap="wrap" align="center" class="shrink-0 gap-2">
<Input <Input
v-model:value="searchForm.name" v-model:value="companySearchForm.name"
placeholder="请输入公司名称" placeholder="公司名称"
allow-clear allow-clear
style="width: 180px; margin-right: 8px" class="min-w-[140px] flex-1"
@press-enter="searchCompanies"
/> />
<Select <Select
v-model:value="searchForm.status" v-model:value="companySearchForm.status"
placeholder="状态" placeholder="状态"
allow-clear allow-clear
style="width: 100px; margin-right: 8px" class="w-[88px]"
> :options="[
<Select.Option :value="1">启用</Select.Option> { label: '启用', value: 1 },
<Select.Option :value="0">禁用</Select.Option> { label: '禁用', value: 0 },
</Select> ]"
<Button type="primary" @click="searchCompanies">搜索</Button> />
<Button @click="resetSearch">重置</Button> <Button type="primary" size="small" @click="searchCompanies">
搜索
</Button>
<Button size="small" @click="resetCompanySearch">重置</Button>
</Flex> </Flex>
<!-- 公司列表 --> <Spin :spinning="companyLoading" class="flex min-h-0 flex-1 flex-col">
<Flex vertical class="flex-1 overflow-y-auto"> <div :class="SIDEBAR_LIST_SHELL_CLASS">
<Spin :spinning="companyLoading"> <Empty
<Card v-if="!companyLoading && companyList.length === 0"
v-for="company in companyList" class="py-8"
:key="company.id" description="暂无公司"
hoverable />
size="small" <div v-else class="space-y-1">
:body-style="{ padding: '10px 12px' }" <button
class="mb-2 cursor-pointer transition-all duration-200" v-for="company in companyList"
:class="[ :key="company.id"
currentCompany?.id === company.id && type="button"
'ring-primary shadow ring-1', :class="companyRowClass(company.id)"
]" @click="selectCompany(company)"
@click="selectCompany(company)" >
> <span class="block truncate">{{ company.name }}</span>
<div class="flex items-start justify-between gap-2"> <span
<div class="min-w-0"> class="mt-0.5 block truncate text-xs font-normal text-muted-foreground"
<div class="mb-1 flex items-center gap-2"> >
<span
class="inline-block h-2 w-2 rounded-full"
:class="company.status === 1 ? 'bg-green-500' : 'bg-red-500'"
></span>
<span class="truncate text-sm font-semibold">{{ company.name }}</span>
</div>
<div class="text-xs text-gray-400">ID: {{ company.id }}</div>
</div>
<Tag :color="company.status === 1 ? 'green' : 'red'">
{{ company.status === 1 ? '启用' : '禁用' }} {{ company.status === 1 ? '启用' : '禁用' }}
</Tag> </span>
</div> </button>
</Card> </div>
</Spin> </div>
<Flex justify="center" class="mt-2"> <Flex justify="center" class="mt-2 shrink-0 pt-1">
<Pagination <Pagination
v-model:current="companyPagination.current" v-model:current="companyPagination.current"
v-model:page-size="companyPagination.pageSize" v-model:page-size="companyPagination.pageSize"
:total="companyPagination.total" :total="companyPagination.total"
size="small"
:show-size-changer="true" :show-size-changer="true"
:show-quick-jumper="true" :show-quick-jumper="true"
@change="handlePageChange" @change="handleCompanyPageChange"
/> />
</Flex> </Flex>
</Flex> </Spin>
</Card> </Card>
<!-- 右栏:公司菜单分配 --> <!-- 右:菜单分配 -->
<Card <Card
title="公司菜单分配" class="flex h-full min-h-0 min-w-0 flex-1 flex-col"
class="flex h-full flex-1 flex-col" :body-style="{
:body-style="{ height: '100%' }" height: '100%',
minHeight: 0,
padding: 0,
display: 'flex',
flexDirection: 'column',
}"
> >
<template v-if="currentCompany"> <template #title>
<!-- 头部 --> <span class="text-base font-semibold">菜单分配</span>
<div class="mb-4 rounded bg-gray-50 p-4">
<div class="mb-3 flex items-center justify-between gap-2">
<div class="flex items-center gap-2">
<span class="text-base font-semibold">{{ currentCompany.name }}</span>
<Tag :color="currentCompany.status === 1 ? 'green' : 'red'">
{{ currentCompany.status === 1 ? '启用' : '禁用' }}
</Tag>
</div>
<div class="flex items-center gap-2">
<Button @click="selectNone">取消全选</Button>
<Button type="primary" @click="selectAll">一键全选</Button>
<Button
type="primary"
:disabled="!stats.changed"
@click="handleSave"
>
保存配置
</Button>
</div>
</div>
<div class="flex gap-6 text-xs text-gray-500">
<span>系统菜单:<strong>{{ stats.total }}</strong></span>
<span>已配置:<strong class="text-green-600">{{ stats.company }}</strong></span>
<span>当前选择:<strong class="text-blue-600">{{ stats.selected }}</strong></span>
<span v-if="stats.changed" class="text-orange-500">(有未保存的更改)</span>
</div>
</div>
<!-- 菜单树 -->
<div class="flex-1 overflow-y-auto">
<Spin :spinning="menuLoading">
<Tree
v-model:checked-keys="selectedMenuIds"
:tree-data="menuTreeData"
checkable
:default-expand-all="true"
class="company-menu-tree"
@check="handleTreeCheckChange"
>
<template #title="{ title, status }">
<span>
{{ title }}
<span v-if="status === 0" class="ml-2 text-xs text-gray-400">(已禁用)</span>
</span>
</template>
</Tree>
</Spin>
</div>
</template> </template>
<div v-else class="flex h-full flex-1 items-center justify-center text-gray-400"> <div
<div class="text-center"> class="shrink-0 border-t border-border px-4 py-2 text-xs text-muted-foreground"
<div class="mb-2 text-5xl">👈</div> >
<div>请先选择一家公司</div> 当前:{{ selectedCompanyLabel }}
</div> <template v-if="currentCompany">
<Tag
class="ml-2"
:color="currentCompany.status === 1 ? 'green' : 'red'"
>
{{ currentCompany.status === 1 ? '启用' : '禁用' }}
</Tag>
<span class="ml-3">
系统菜单 {{ stats.total }} · 已配置
<strong class="text-green-600">{{ stats.company }}</strong> · 当前选择
<strong class="text-blue-600">{{ stats.selected }}</strong>
<span v-if="stats.changed" class="text-orange-500">(有未保存更改)</span>
</span>
</template>
</div>
<div
v-if="!currentCompany"
class="flex min-h-0 flex-1 items-center justify-center"
>
<Empty description="请从左侧选择公司以配置菜单" />
</div>
<div v-else class="min-h-0 flex-1 overflow-y-auto px-4 py-3 sm:px-5">
<Spin :spinning="menuLoading">
<Tree
v-model:checked-keys="selectedMenuIds"
:tree-data="menuTreeData"
checkable
:default-expand-all="true"
class="company-menu-tree"
@check="handleTreeCheckChange"
>
<template #title="{ title, status }">
<span>
{{ title }}
<span v-if="status === 0" class="ml-2 text-xs text-gray-400">
(已禁用)
</span>
</span>
</template>
</Tree>
</Spin>
</div> </div>
</Card> </Card>
</Flex> </Flex>
@@ -5,41 +5,63 @@ import type { PermissionVO } from '#/api/system/permission/types';
import { computed, onMounted, ref } from 'vue'; import { computed, onMounted, ref } from 'vue';
import { Page } from '@vben/common-ui'; import { Page } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons';
import { Button, Card, Flex, Input, message, Pagination, Select, Spin, Tag } from 'ant-design-vue'; import {
Button,
Card,
Empty,
Flex,
Input,
message,
Pagination,
Select,
Space,
Spin,
Tag,
} from 'ant-design-vue';
import { batchUpdateCompanyPermissionsApi, getCompanyPermissionIdsApi } from '#/api/organization/company-permission/apis'; import {
batchUpdateCompanyPermissionsApi,
getCompanyPermissionIdsApi,
} from '#/api/organization/company-permission/apis';
import { getCompanyPageApi } from '#/api/organization/company'; import { getCompanyPageApi } from '#/api/organization/company';
import { getPermissionTreeApi } from '#/api/system/permission'; import { getPermissionTreeApi } from '#/api/system/permission';
import TreeNodeContent from './components/TreeNodeContent.vue'; import TreeNodeContent from './components/TreeNodeContent.vue';
import {
SIDEBAR_LIST_SHELL_CLASS,
sidebarListRowClass,
} from '#/utils/sidebar-list-styles';
defineOptions({ name: 'CompanyPermissionManagePage' }); defineOptions({ name: 'CompanyPermissionManagePage' });
// 搜索表单 const BuildingIcon = createIconifyIcon('lucide:building-2');
const searchForm = ref({ name: '', status: undefined as number | undefined });
const companySearchForm = ref({
name: '',
status: undefined as number | undefined,
});
// 公司列表
const companyList = ref<CompanyVO.CompanyInfoVO[]>([]); const companyList = ref<CompanyVO.CompanyInfoVO[]>([]);
const companyLoading = ref(false); const companyLoading = ref(false);
const companyPagination = ref({ current: 1, pageSize: 10, total: 0 }); const companyPagination = ref({ current: 1, pageSize: 20, total: 0 });
// 当前选中的公司 const currentCompany = ref<CompanyVO.CompanyInfoVO | null>(null);
const currentCompany = ref<null | CompanyVO.CompanyInfoVO>(null);
// 权限树数据
const permissionTree = ref<PermissionVO.PermissionInfoVO[]>([]); const permissionTree = ref<PermissionVO.PermissionInfoVO[]>([]);
const permissionLoading = ref(false); const permissionLoading = ref(false);
// 公司原始已分配权限ID
const companyPermissionIds = ref<number[]>([]); const companyPermissionIds = ref<number[]>([]);
// 用户当前选中的权限ID(唯一真实数据源)
const selectedPermissionIds = ref<number[]>([]); const selectedPermissionIds = ref<number[]>([]);
// 展开状态
const expandedIds = ref<Set<number>>(new Set()); const expandedIds = ref<Set<number>>(new Set());
// 统计 const selectedCompanyLabel = computed(() => {
if (!currentCompany.value) {
return '请先选择公司';
}
return currentCompany.value.name;
});
const stats = computed(() => ({ const stats = computed(() => ({
total: countLeafPermissions(permissionTree.value), total: countLeafPermissions(permissionTree.value),
company: companyPermissionIds.value.length, company: companyPermissionIds.value.length,
@@ -53,14 +75,16 @@ function sameArray(a: number[], b: number[]): boolean {
return b.every((id) => sa.has(id)); return b.every((id) => sa.has(id));
} }
// 搜索公司
async function searchCompanies() { async function searchCompanies() {
companyLoading.value = true; companyLoading.value = true;
try { try {
const result = await getCompanyPageApi({ const result = await getCompanyPageApi({
page: companyPagination.value.current, page: companyPagination.value.current,
pageSize: companyPagination.value.pageSize, pageSize: companyPagination.value.pageSize,
filters: { name: searchForm.value.name || undefined, status: searchForm.value.status }, filters: {
name: companySearchForm.value.name || undefined,
status: companySearchForm.value.status,
},
}); });
companyList.value = result.records; companyList.value = result.records;
companyPagination.value.total = result.total; companyPagination.value.total = result.total;
@@ -71,13 +95,11 @@ async function searchCompanies() {
} }
} }
// 选择公司
async function selectCompany(company: CompanyVO.CompanyInfoVO) { async function selectCompany(company: CompanyVO.CompanyInfoVO) {
currentCompany.value = company; currentCompany.value = company;
await loadCompanyPermissions(); await loadCompanyPermissions();
} }
// 加载公司已有权限
async function loadCompanyPermissions() { async function loadCompanyPermissions() {
if (!currentCompany.value?.id) return; if (!currentCompany.value?.id) return;
permissionLoading.value = true; permissionLoading.value = true;
@@ -92,22 +114,20 @@ async function loadCompanyPermissions() {
} }
} }
// 加载权限树(全量树,用于分配)
async function loadPermissionTree() { async function loadPermissionTree() {
try { try {
const result = await getPermissionTreeApi(); const result = await getPermissionTreeApi();
permissionTree.value = result || []; permissionTree.value = result || [];
// 默认全部展开 expandedIds.value = new Set(
expandedIds.value = new Set(result?.map((n: PermissionVO.PermissionInfoVO) => n.id) || []); result?.map((n: PermissionVO.PermissionInfoVO) => n.id) || [],
);
} catch (error: any) { } catch (error: any) {
message.error(error?.message || '获取权限树失败'); message.error(error?.message || '获取权限树失败');
} }
} }
// 保存(只保存叶子权限节点,模块节点仅作视觉分组)
async function handleSave() { async function handleSave() {
if (!currentCompany.value?.id) return; if (!currentCompany.value?.id) return;
// 过滤掉模块节点,只保留叶子权限
const leafIds = selectedPermissionIds.value.filter((id) => { const leafIds = selectedPermissionIds.value.filter((id) => {
const node = findNode(permissionTree.value, id); const node = findNode(permissionTree.value, id);
return node && (!node.children || node.children.length === 0); return node && (!node.children || node.children.length === 0);
@@ -122,29 +142,30 @@ async function handleSave() {
} }
} }
function resetSearch() { function resetCompanySearch() {
searchForm.value = { name: '', status: undefined }; companySearchForm.value = { name: '', status: undefined };
companyPagination.value.current = 1; companyPagination.value.current = 1;
searchCompanies(); searchCompanies();
} }
function handlePageChange(page: number, pageSize: number) { function handleCompanyPageChange(page: number, pageSize: number) {
companyPagination.value.current = page; companyPagination.value.current = page;
companyPagination.value.pageSize = pageSize; companyPagination.value.pageSize = pageSize;
searchCompanies(); searchCompanies();
} }
// 统计叶子权限数
function countLeafPermissions(nodes: PermissionVO.PermissionInfoVO[]): number { function countLeafPermissions(nodes: PermissionVO.PermissionInfoVO[]): number {
let count = 0; let count = 0;
for (const node of nodes) { for (const node of nodes) {
if (node.children && node.children.length > 0) count += countLeafPermissions(node.children); if (node.children && node.children.length > 0) {
else count++; count += countLeafPermissions(node.children);
} else {
count++;
}
} }
return count; return count;
} }
// 获取所有叶子权限ID
function getAllLeafIds(nodes: PermissionVO.PermissionInfoVO[]): number[] { function getAllLeafIds(nodes: PermissionVO.PermissionInfoVO[]): number[] {
const result: number[] = []; const result: number[] = [];
for (const node of nodes) { for (const node of nodes) {
@@ -154,33 +175,40 @@ function getAllLeafIds(nodes: PermissionVO.PermissionInfoVO[]): number[] {
return result; return result;
} }
// 全选(只选叶子节点)
function selectAll() { function selectAll() {
selectedPermissionIds.value = getAllLeafIds(permissionTree.value); selectedPermissionIds.value = getAllLeafIds(permissionTree.value);
} }
// 取消全选
function selectNone() { function selectNone() {
selectedPermissionIds.value = []; selectedPermissionIds.value = [];
} }
// 单个 checkbox 变化
function onCheck(permissionId: number, checked: boolean) { function onCheck(permissionId: number, checked: boolean) {
if (checked) { if (checked) {
const toAdd = new Set<number>([permissionId]); const toAdd = new Set<number>([permissionId]);
getParentChain(permissionTree.value, permissionId).forEach((id) => toAdd.add(id)); getParentChain(permissionTree.value, permissionId).forEach((id) =>
toAdd.add(id),
);
getDescendantIds(permissionId).forEach((id) => toAdd.add(id)); getDescendantIds(permissionId).forEach((id) => toAdd.add(id));
const newSet = new Set(selectedPermissionIds.value); const newSet = new Set(selectedPermissionIds.value);
toAdd.forEach((id) => newSet.add(id)); toAdd.forEach((id) => newSet.add(id));
selectedPermissionIds.value = Array.from(newSet); selectedPermissionIds.value = Array.from(newSet);
} else { } else {
const toRemove = new Set<number>([permissionId, ...getDescendantIds(permissionId)]); const toRemove = new Set<number>([
selectedPermissionIds.value = selectedPermissionIds.value.filter((id) => !toRemove.has(id)); permissionId,
...getDescendantIds(permissionId),
]);
selectedPermissionIds.value = selectedPermissionIds.value.filter(
(id) => !toRemove.has(id),
);
} }
} }
// 递归获取父节点链 function getParentChain(
function getParentChain(nodes: PermissionVO.PermissionInfoVO[], targetId: number, path: number[] = []): number[] { nodes: PermissionVO.PermissionInfoVO[],
targetId: number,
path: number[] = [],
): number[] {
for (const node of nodes) { for (const node of nodes) {
if (node.id === targetId) return [...path, node.id]; if (node.id === targetId) return [...path, node.id];
if (node.children) { if (node.children) {
@@ -191,7 +219,6 @@ function getParentChain(nodes: PermissionVO.PermissionInfoVO[], targetId: number
return []; return [];
} }
// 递归获取某节点下所有子孙ID
function getDescendantIds(permissionId: number): number[] { function getDescendantIds(permissionId: number): number[] {
const node = findNode(permissionTree.value, permissionId); const node = findNode(permissionTree.value, permissionId);
if (!node || !node.children) return []; if (!node || !node.children) return [];
@@ -211,8 +238,10 @@ function getDescendantIds(permissionId: number): number[] {
return result; return result;
} }
// 递归查找节点 function findNode(
function findNode(nodes: PermissionVO.PermissionInfoVO[], id: number): PermissionVO.PermissionInfoVO | null { nodes: PermissionVO.PermissionInfoVO[],
id: number,
): PermissionVO.PermissionInfoVO | null {
for (const node of nodes) { for (const node of nodes) {
if (node.id === id) return node; if (node.id === id) return node;
if (node.children) { if (node.children) {
@@ -223,7 +252,6 @@ function findNode(nodes: PermissionVO.PermissionInfoVO[], id: number): Permissio
return null; return null;
} }
// 展开/收起
function toggleExpand(nodeId: number) { function toggleExpand(nodeId: number) {
const newSet = new Set(expandedIds.value); const newSet = new Set(expandedIds.value);
if (newSet.has(nodeId)) newSet.delete(nodeId); if (newSet.has(nodeId)) newSet.delete(nodeId);
@@ -231,6 +259,11 @@ function toggleExpand(nodeId: number) {
expandedIds.value = newSet; expandedIds.value = newSet;
} }
function companyRowClass(companyId: number) {
const active = currentCompany.value?.id === companyId;
return sidebarListRowClass(active, 'w-full cursor-pointer text-left');
}
onMounted(() => { onMounted(() => {
searchCompanies(); searchCompanies();
loadPermissionTree(); loadPermissionTree();
@@ -238,140 +271,174 @@ onMounted(() => {
</script> </script>
<template> <template>
<Page :auto-content-height="true"> <Page title="公司权限管理" :auto-content-height="true">
<Flex gap="middle" class="h-full"> <template #description>
<!-- 左栏:公司列表 --> <div class="text-foreground/80 mt-2">
左侧选择公司,右侧勾选并保存该公司可分配的权限。
</div>
</template>
<template #extra>
<Space>
<Button :disabled="!currentCompany" @click="selectNone">取消全选</Button>
<Button type="primary" :disabled="!currentCompany" @click="selectAll">
一键全选
</Button>
<Button
type="primary"
:disabled="!currentCompany || !stats.changed"
@click="handleSave"
>
保存配置
</Button>
</Space>
</template>
<Flex gap="middle" class="h-full min-h-0">
<!-- 左:公司 -->
<Card <Card
title="公司列表" class="flex h-full w-[420px] shrink-0 flex-col"
class="flex h-full max-w-[400px] flex-col" :body-style="{
:body-style="{ height: '100%', display: 'flex', flexDirection: 'column', gap: '10px' }" height: '100%',
display: 'flex',
flexDirection: 'column',
gap: '8px',
minHeight: 0,
padding: '12px',
}"
> >
<Flex class="flex-wrap gap-2"> <template #title>
<span class="flex items-center gap-2 text-base font-semibold">
<BuildingIcon class="h-4 w-4" />
公司
</span>
</template>
<Flex wrap="wrap" align="center" class="shrink-0 gap-2">
<Input <Input
v-model:value="searchForm.name" v-model:value="companySearchForm.name"
placeholder="请输入公司名称" placeholder="公司名称"
allow-clear allow-clear
style="width: 180px; margin-right: 8px" class="min-w-[140px] flex-1"
@press-enter="searchCompanies"
/> />
<Select <Select
v-model:value="searchForm.status" v-model:value="companySearchForm.status"
placeholder="状态" placeholder="状态"
allow-clear allow-clear
style="width: 100px; margin-right: 8px" class="w-[88px]"
> :options="[
<Select.Option :value="1">启用</Select.Option> { label: '启用', value: 1 },
<Select.Option :value="0">禁用</Select.Option> { label: '禁用', value: 0 },
</Select> ]"
<Button type="primary" @click="searchCompanies">搜索</Button> />
<Button @click="resetSearch">重置</Button> <Button type="primary" size="small" @click="searchCompanies">
搜索
</Button>
<Button size="small" @click="resetCompanySearch">重置</Button>
</Flex> </Flex>
<Flex vertical class="flex-1 overflow-y-auto"> <Spin :spinning="companyLoading" class="flex min-h-0 flex-1 flex-col">
<Spin :spinning="companyLoading"> <div :class="SIDEBAR_LIST_SHELL_CLASS">
<Card <Empty
v-for="company in companyList" v-if="!companyLoading && companyList.length === 0"
:key="company.id" class="py-8"
hoverable description="暂无公司"
size="small" />
:body-style="{ padding: '10px 12px' }" <div v-else class="space-y-1">
class="mb-2 cursor-pointer transition-all duration-200" <button
:class="[currentCompany?.id === company.id && 'ring-primary shadow ring-1']" v-for="company in companyList"
@click="selectCompany(company)" :key="company.id"
> type="button"
<div class="flex items-start justify-between gap-2"> :class="companyRowClass(company.id)"
<div class="min-w-0"> @click="selectCompany(company)"
<div class="mb-1 flex items-center gap-2"> >
<span <span class="block truncate">{{ company.name }}</span>
class="inline-block h-2 w-2 rounded-full" <span
:class="company.status === 1 ? 'bg-green-500' : 'bg-red-500'" class="mt-0.5 block truncate text-xs font-normal text-muted-foreground"
></span> >
<span class="truncate text-sm font-semibold">{{ company.name }}</span>
</div>
<div class="text-xs text-gray-400">ID: {{ company.id }}</div>
</div>
<Tag :color="company.status === 1 ? 'green' : 'red'">
{{ company.status === 1 ? '启用' : '禁用' }} {{ company.status === 1 ? '启用' : '禁用' }}
</Tag> </span>
</div> </button>
</Card> </div>
</Spin> </div>
<Flex justify="center" class="mt-2"> <Flex justify="center" class="mt-2 shrink-0 pt-1">
<Pagination <Pagination
v-model:current="companyPagination.current" v-model:current="companyPagination.current"
v-model:page-size="companyPagination.pageSize" v-model:page-size="companyPagination.pageSize"
:total="companyPagination.total" :total="companyPagination.total"
size="small"
:show-size-changer="true" :show-size-changer="true"
:show-quick-jumper="true" :show-quick-jumper="true"
@change="handlePageChange" @change="handleCompanyPageChange"
/> />
</Flex> </Flex>
</Flex> </Spin>
</Card> </Card>
<!-- 右栏:公司权限分配 --> <!-- 右:权限分配 -->
<Card <Card
title="公司权限分配" class="flex h-full min-h-0 min-w-0 flex-1 flex-col"
class="flex h-full flex-1 flex-col" :body-style="{
:body-style="{ height: '100%' }" height: '100%',
minHeight: 0,
padding: 0,
display: 'flex',
flexDirection: 'column',
}"
> >
<template v-if="currentCompany"> <template #title>
<!-- 头部 --> <span class="text-base font-semibold">权限分配</span>
<div class="mb-4 rounded bg-gray-50 p-4">
<div class="mb-3 flex items-center justify-between gap-2">
<div class="flex items-center gap-2">
<span class="text-base font-semibold">{{ currentCompany.name }}</span>
<Tag :color="currentCompany.status === 1 ? 'green' : 'red'">
{{ currentCompany.status === 1 ? '启用' : '禁用' }}
</Tag>
</div>
<div class="flex items-center gap-2">
<Button @click="selectNone">取消全选</Button>
<Button type="primary" @click="selectAll">一键全选</Button>
<Button type="primary" :disabled="!stats.changed" @click="handleSave">
保存配置
</Button>
</div>
</div>
<div class="flex gap-6 text-xs text-gray-500">
<span>全部叶子权限:<strong>{{ stats.total }}</strong></span>
<span>已配置:<strong class="text-green-600">{{ stats.company }}</strong></span>
<span>当前选择:<strong class="text-blue-600">{{ stats.selected }}</strong></span>
<span v-if="stats.changed" class="text-orange-500">(有未保存的更改)</span>
</div>
</div>
<!-- 权限树(完全自己控制,不用 antd checkable) -->
<div class="flex-1 overflow-y-auto">
<Spin :spinning="permissionLoading">
<div v-if="permissionTree.length > 0" class="py-2">
<!-- 递归渲染树节点 -->
<template v-for="node in permissionTree" :key="node.id">
<TreeNodeContent
:node="node"
:level="0"
:expanded-ids="expandedIds"
:selected-ids="selectedPermissionIds"
@toggle="toggleExpand"
@check="onCheck"
/>
</template>
</div>
<div v-else-if="!permissionLoading" class="py-8 text-center text-gray-400">
暂无可分配的权限
</div>
</Spin>
</div>
</template> </template>
<div <div
v-else class="shrink-0 border-t border-border px-4 py-2 text-xs text-muted-foreground"
class="flex h-full flex-1 items-center justify-center text-gray-400"
> >
<div class="text-center"> 当前:{{ selectedCompanyLabel }}
<div class="mb-2 text-5xl">👈</div> <template v-if="currentCompany">
<div>请先选择一家公司</div> <Tag
</div> class="ml-2"
:color="currentCompany.status === 1 ? 'green' : 'red'"
>
{{ currentCompany.status === 1 ? '启用' : '禁用' }}
</Tag>
<span class="ml-3">
全部叶子权限 {{ stats.total }} · 已配置
<strong class="text-green-600">{{ stats.company }}</strong> · 当前选择
<strong class="text-blue-600">{{ stats.selected }}</strong>
<span v-if="stats.changed" class="text-orange-500">(有未保存更改)</span>
</span>
</template>
</div>
<div
v-if="!currentCompany"
class="flex min-h-0 flex-1 items-center justify-center"
>
<Empty description="请从左侧选择公司以配置权限" />
</div>
<div v-else class="min-h-0 flex-1 overflow-y-auto px-4 py-3 sm:px-5">
<Spin :spinning="permissionLoading">
<div v-if="permissionTree.length > 0" class="py-2">
<template v-for="node in permissionTree" :key="node.id">
<TreeNodeContent
:node="node"
:level="0"
:expanded-ids="expandedIds"
:selected-ids="selectedPermissionIds"
@toggle="toggleExpand"
@check="onCheck"
/>
</template>
</div>
<Empty
v-else-if="!permissionLoading"
class="py-8"
description="暂无可分配的权限"
/>
</Spin>
</div> </div>
</Card> </Card>
</Flex> </Flex>