front/src/views/system/permission/role/index.vue
zzh 57d506ee89
All checks were successful
Build and Deploy Front / deploy (push) Successful in 4m4s
feat: 优化 AI Skill/MCP、仓作业与数据权限等交互体验
统一装袋/打板扫描布局,完善主从页脏数据与顶栏操作;语言收进用户菜单,艾迪浮窗精简为胶囊顶栏。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-15 00:07:55 +08:00

823 lines
24 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<template>
<div class="rbac-split-layout">
<CustomLeftMenu
class="left-sidebar"
:tree-data="roleTreeData"
:selected-keys="selectedKeys"
v-model:expanded-keys="expandedKeys"
v-model:search-keyword="searchKeyword"
:loading="loading"
:search-placeholder="t('system.role.search.placeholder.roleNameOrCode')"
:refresh-title="t('system.user.actions.refresh')"
:add-title="t('system.role.actions.add')"
:delete-label="t('system.role.actions.delete')"
:loading-text="t('system.role.loading')"
:show-add="hasPermission('Rbac.Roles.Create')"
:show-node-actions="hasPermission('Rbac.Roles.Delete')"
:show-method="false"
:show-map-count="false"
:show-node-code="true"
:show-pagination="true"
:page-size="20"
@search="handleSearch"
@refresh="loadData"
@add="handleAdd"
@select="handleRoleSelect"
@node-click="handleRoleNodeClick"
@delete-node="(node) => handleDelete(node?.id)"
/>
<div class="right-panel">
<RbacDetailShell
:empty="!selectedRole"
:empty-title="t('system.role.emptySelect')"
:empty-desc="t('system.role.emptyDesc')"
:title="headerTitle"
:subtitle="headerSubtitle"
:tags="roleTags"
:tabs="roleTabs"
v-model:active-tab="activeTab"
:loading="permissionLoading && activeTab === 'permissions'"
>
<template #actions>
<a-button
v-if="hasPermission('Rbac.Roles.Update') || isCreating"
type="primary"
:loading="modalLoading || permissionSaving"
@click="handleSaveAll"
>
{{ dirty ? t('system.role.actions.saveDirty') : t('system.role.actions.save') }}
</a-button>
</template>
<div v-show="activeTab === 'basic'" class="role-pane">
<section class="role-card">
<div class="role-card__head">
<h3 class="role-card__title">{{ t('system.role.section.identity') }}</h3>
<p class="role-card__hint">{{ t('system.role.section.identityHint') }}</p>
</div>
<div class="role-card__body">
<a-form
ref="formRef"
:model="formState"
:rules="formRules"
layout="vertical"
class="role-basic-form"
>
<a-row :gutter="16">
<a-col :span="12">
<a-form-item :label="t('system.role.form.name')" field="name" required>
<a-input
v-model="formState.name"
:placeholder="t('system.role.form.namePlaceholder')"
allow-clear
/>
</a-form-item>
</a-col>
<a-col :span="12">
<a-form-item :label="t('system.role.form.code')" field="code" required>
<a-input
v-model="formState.code"
:placeholder="t('system.role.form.codePlaceholder')"
:disabled="!isCreating"
allow-clear
/>
</a-form-item>
</a-col>
<a-col :span="12">
<a-form-item :label="t('system.role.form.boundWarehouse')" field="boundWarehouseId">
<a-select
v-model="formState.boundWarehouseId"
:placeholder="t('system.role.form.boundWarehousePlaceholder')"
allow-clear
:options="warehouseOptions"
/>
</a-form-item>
</a-col>
<a-col v-if="!isCreating" :span="12">
<a-form-item :label="t('system.role.table.createTime')">
<span class="role-create-time">{{ formatTime(selectedRole?.createdAt) }}</span>
</a-form-item>
</a-col>
</a-row>
</a-form>
</div>
</section>
<section v-if="canAssignPermissions" class="role-next-card">
<div class="role-next-card__main">
<p class="role-next-card__title">{{ t('system.role.flow.goPermTitle') }}</p>
<p class="role-next-card__desc">{{ t('system.role.flow.goPermDesc') }}</p>
</div>
<a-button type="primary" @click="activeTab = 'permissions'">
{{ t('system.role.flow.goPermBtn') }}
<template v-if="!isSelectedAdminRole && totalPermissionCount">
({{ selectedPermissionCount }}/{{ totalPermissionCount }})
</template>
</a-button>
</section>
</div>
<div v-show="activeTab === 'permissions'" class="permission-body">
<a-alert
v-if="isSelectedAdminRole"
type="info"
show-icon
:title="t('system.role.permission.adminAllHint')"
/>
<template v-else-if="canAssignPermissions">
<div class="permission-toolbar">
<a-input
v-model="permissionKeyword"
:placeholder="t('system.role.permission.search')"
allow-clear
class="permission-toolbar__search"
/>
<a-button class="app-btn-toolbar" @click="checkAllPermissions">
{{ t('system.role.permission.checkAll') }}
</a-button>
<a-button class="app-btn-toolbar" @click="uncheckAllPermissions">
{{ t('system.role.permission.uncheckAll') }}
</a-button>
</div>
<a-table
v-if="filteredPermissionRows.length > 0"
class="permission-table"
:data="filteredPermissionRows"
:pagination="false"
:bordered="{ cell: true }"
:span-method="permissionSpanMethod"
row-key="rowKey"
size="small"
:scroll="{ y: permissionTableScrollY }"
>
<template #columns>
<a-table-column
:title="t('system.role.permission.col.level1')"
data-index="level1Name"
:width="180"
>
<template #cell="{ record }">
<a-checkbox
:model-value="isPermissionChecked(record.level1Code)"
@change="(checked) => togglePermission(record.level1Code, checked)"
>
{{ record.level1Name }}
</a-checkbox>
</template>
</a-table-column>
<a-table-column
:title="t('system.role.permission.col.level2')"
data-index="level2Name"
:width="200"
>
<template #cell="{ record }">
<a-checkbox
:model-value="isPermissionChecked(record.level2Code)"
@change="(checked) => togglePermission(record.level2Code, checked)"
>
{{ record.level2Name }}
</a-checkbox>
</template>
</a-table-column>
<a-table-column :title="t('system.role.permission.col.level3')">
<template #cell="{ record }">
<div v-if="record.level2HasChildren" class="permission-button-group">
<a-checkbox
v-for="btn in record.buttons"
:key="btn.code"
:model-value="isPermissionChecked(btn.code)"
@change="(checked) => togglePermission(btn.code, checked)"
>
{{ btn.name }}
</a-checkbox>
</div>
<span v-else class="permission-no-buttons">—</span>
</template>
</a-table-column>
</template>
</a-table>
<div v-else class="permission-empty">
{{
permissionKeyword
? t('system.role.permission.noMatch')
: t('system.role.permission.loading')
}}
</div>
</template>
<a-empty v-else :description="t('system.role.permission.noAssignRight')" />
</div>
</RbacDetailShell>
</div>
</div>
</template>
<script setup lang="ts">
defineOptions({ name: 'SystemRoles' })
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { Message, Modal } from '@arco-design/web-vue'
import CustomLeftMenu from '@/components/CustomLeftMenu/index.vue'
import RbacDetailShell from '@/components/RbacSplit/RbacDetailShell.vue'
import type { RbacDetailTag } from '@/components/RbacSplit/RbacDetailShell.vue'
import { RoleService, PermissionService } from '@/api/rbac'
import type {
RoleDto,
RoleCreateDto,
RoleUpdateDto,
PermissionGroupDto,
} from '@/api/rbac'
import { useWarehouseList } from '@/composables/useWarehouseList'
import { hasPermission } from '@/utils/rbac-permission'
import { handleApiError } from '@/utils/rbac-error-handler'
import { useRbacUserStore } from '@/store/modules/rbac-user'
import { buildFlatLeftMenuTree, findLeftMenuItemByKey } from '@/utils/rbacLeftMenuTree'
import {
buildPermissionAssignRows,
buildPermissionCascadeContext,
collectPermissionCodesFromRows,
computeLevel1RowSpans,
countSelectedAssignablePermissions,
filterPermissionAssignRows,
normalizeSelectedPermissions,
togglePermissionWithCascade,
} from '@/utils/rbacPermissionAssignRows'
import dayjs from 'dayjs'
const { t } = useI18n()
const loading = ref(false)
const dataSource = ref<RoleDto[]>([])
const searchKeyword = ref('')
const selectedRole = ref<RoleDto | null>(null)
const isCreating = ref(false)
const expandedKeys = ref(['category-roles'])
const activeTab = ref('basic')
const formRef = ref()
const permissionKeyword = ref('')
const dirty = ref(false)
let baselineJson = ''
let dirtyWatchReady = false
const pagination = reactive({ current: 1, pageSize: 100 })
const { warehouseOptions } = useWarehouseList()
const roleWarehouseMap = ref<Record<string, string>>({})
const formState = reactive<RoleCreateDto & { boundWarehouseId?: string }>({
name: '',
code: '',
boundWarehouseId: undefined,
})
const formRules = computed(() => ({
name: [{ required: true, message: t('system.role.rules.name.required') }],
code: [{ required: true, message: t('system.role.rules.code.required') }],
}))
const modalLoading = ref(false)
const permissionLoading = ref(false)
const permissionSaving = ref(false)
const permissionTree = ref<PermissionGroupDto[]>([])
const selectedPermissions = ref<string[]>([])
const permissionTableScrollY = 'calc(100vh - 280px)'
const canAssignPermissions = computed(() => hasPermission('Rbac.Roles.AssignPermissions'))
const roleTreeData = computed(() =>
buildFlatLeftMenuTree('category-roles', t('system.role.pageTitle'), dataSource.value, {
titleKey: 'name',
codeKey: 'code',
})
)
const selectedKeys = computed(() =>
selectedRole.value?.id ? [`item-${selectedRole.value.id}`] : []
)
const permissionRows = computed(() => buildPermissionAssignRows(permissionTree.value))
const permissionCascadeContext = computed(() =>
buildPermissionCascadeContext(permissionRows.value)
)
const filteredPermissionRows = computed(() =>
filterPermissionAssignRows(permissionRows.value, permissionKeyword.value)
)
const level1RowSpans = computed(() => computeLevel1RowSpans(filteredPermissionRows.value))
const selectedPermissionCount = computed(() =>
countSelectedAssignablePermissions(selectedPermissions.value, permissionRows.value)
)
const totalPermissionCount = computed(() =>
collectPermissionCodesFromRows(permissionRows.value).length
)
const normalizedSelectedPermissions = computed(() =>
normalizeSelectedPermissions(selectedPermissions.value, permissionRows.value)
)
function isCustomerRole(role?: RoleDto | null) {
const code = role?.code || ''
return code === 'Customer' || code.startsWith('CustomerSub_')
}
function isAdminRole(role?: RoleDto | null) {
return (role?.code || '').toLowerCase() === 'admin'
}
const isSelectedAdminRole = computed(() => isAdminRole(selectedRole.value))
const headerTitle = computed(() => {
if (isCreating.value) return t('system.role.actions.add')
return formState.name || selectedRole.value?.name || ''
})
const headerSubtitle = computed(() => {
if (isCreating.value) return formState.code || ''
return formState.code || selectedRole.value?.code || ''
})
const roleTags = computed((): RbacDetailTag[] => {
if (!selectedRole.value && !isCreating.value) return []
const tags: RbacDetailTag[] = []
if (isCreating.value) {
tags.push({ label: t('system.role.tag.creating'), color: 'orangered' })
}
if (dirty.value) {
tags.push({ label: t('system.role.tag.dirty'), color: 'orangered' })
}
if (isAdminRole(selectedRole.value)) {
tags.push({ label: t('system.role.tag.admin'), color: 'purple' })
}
if (isCustomerRole(selectedRole.value)) {
tags.push({ label: t('system.role.category.system'), color: 'arcoblue' })
}
if (formState.boundWarehouseId) {
tags.push({ label: t('system.role.tag.boundWarehouse'), color: 'green' })
}
return tags
})
const roleTabs = computed(() => {
const tabs: { key: string; label: string; badge?: string | number }[] = [
{ key: 'basic', label: t('system.role.tab.info') },
]
if (!canAssignPermissions.value) return tabs
if (isSelectedAdminRole.value) {
tabs.push({ key: 'permissions', label: t('system.role.modal.assignPermissions') })
return tabs
}
const selected = selectedPermissionCount.value
const total = totalPermissionCount.value
tabs.push({
key: 'permissions',
label: t('system.role.modal.assignPermissions'),
badge: total ? `${selected}/${total}` : undefined,
})
return tabs
})
function snapshotState() {
return JSON.stringify({
name: formState.name || '',
code: formState.code || '',
boundWarehouseId: formState.boundWarehouseId || '',
permissions: [...selectedPermissions.value].sort(),
})
}
function captureBaseline() {
baselineJson = snapshotState()
dirty.value = false
}
function refreshDirty() {
if (!dirtyWatchReady || loading.value || modalLoading.value || permissionSaving.value) return
dirty.value = snapshotState() !== baselineJson
}
function permissionSpanMethod({
rowIndex,
columnIndex,
}: {
rowIndex: number
columnIndex: number
}) {
if (columnIndex !== 0) return { rowspan: 1, colspan: 1 }
const rowspan = level1RowSpans.value[rowIndex] ?? 1
if (rowspan === 0) return { rowspan: 0, colspan: 0 }
return { rowspan, colspan: 1 }
}
function isPermissionChecked(code: string) {
return selectedPermissions.value.includes(code)
}
function isChangeChecked(checked: boolean | (string | number | boolean)) {
if (Array.isArray(checked)) return checked.length > 0
return checked === true
}
function togglePermission(code: string, checked: boolean | (string | number | boolean)) {
if (!code) return
selectedPermissions.value = togglePermissionWithCascade(
selectedPermissions.value,
permissionCascadeContext.value,
code,
isChangeChecked(checked)
)
}
function formatTime(value?: string | null) {
if (!value) return '—'
const d = dayjs(value)
if (!d.isValid() || d.year() < 1970) return '—'
return d.format('YYYY-MM-DD HH:mm:ss')
}
function selectRoleFromKey(key: string) {
const role = findLeftMenuItemByKey(key, dataSource.value)
if (role) {
dirty.value = false
isCreating.value = false
selectedRole.value = role
}
}
function handleRoleSelect(keys: string[]) {
const key = keys[0]
if (key) selectRoleFromKey(key)
}
function handleRoleNodeClick(key: string) {
selectRoleFromKey(key)
}
function syncFormFromRole(role: RoleDto) {
Object.assign(formState, {
name: role.name || '',
code: role.code || '',
boundWarehouseId: roleWarehouseMap.value[role.id || ''] || undefined,
})
}
async function loadData() {
loading.value = true
try {
const response = await RoleService.getRbacRoleGetList(
searchKeyword.value || undefined,
pagination.current,
pagination.pageSize
)
dataSource.value = response?.items || []
if (selectedRole.value?.id) {
const stillExists = dataSource.value.find((r) => r.id === selectedRole.value?.id)
selectedRole.value = stillExists || dataSource.value[0] || null
} else if (!isCreating.value && dataSource.value.length > 0) {
selectedRole.value = dataSource.value[0]
}
} catch (error) {
handleApiError(error)
} finally {
loading.value = false
}
}
async function loadPermissionTree() {
if (permissionTree.value.length > 0) return
try {
permissionTree.value = (await PermissionService.getRbacPermissionGetPermissionTree()) || []
} catch (error) {
handleApiError(error)
}
}
async function loadRolePermissions(roleId: string) {
permissionLoading.value = true
dirtyWatchReady = false
try {
await loadPermissionTree()
const loaded = (await RoleService.getRbacRoleGetRolePermissions(roleId)) || []
selectedPermissions.value = normalizeSelectedPermissions(loaded, permissionRows.value)
captureBaseline()
} catch (error) {
handleApiError(error)
captureBaseline()
} finally {
permissionLoading.value = false
dirtyWatchReady = true
}
}
function checkAllPermissions() {
selectedPermissions.value = collectPermissionCodesFromRows(permissionRows.value)
}
function uncheckAllPermissions() {
selectedPermissions.value = []
}
function handleSearch() {
pagination.current = 1
loadData()
}
function handleAdd() {
dirtyWatchReady = false
isCreating.value = true
selectedRole.value = { name: '', code: '' }
Object.assign(formState, { name: '', code: '', boundWarehouseId: undefined })
activeTab.value = 'basic'
selectedPermissions.value = []
captureBaseline()
dirtyWatchReady = true
}
async function handleDelete(id?: string) {
if (!id) return
const role = dataSource.value.find((r) => r.id === id)
if (isCustomerRole(role)) {
Message.warning(t('system.role.message.cannotDeleteSystemRole'))
return
}
Modal.confirm({
content: t('system.role.modal.deleteConfirmContent', { count: 1 }),
onOk: async () => {
try {
await RoleService.deleteRbacRoleDelete(id)
Message.success(t('system.role.message.deleteSuccess'))
if (selectedRole.value?.id === id) {
selectedRole.value = null
isCreating.value = false
}
await loadData()
} catch (error) {
handleApiError(error)
}
},
})
}
async function handleSaveRole() {
try {
await formRef.value?.validate()
modalLoading.value = true
if (isCreating.value) {
const createData: RoleCreateDto = {
name: formState.name,
code: formState.code,
}
const res = await RoleService.postRbacRoleCreate(createData)
const newRoleId = res?.id
if (newRoleId && formState.boundWarehouseId) {
roleWarehouseMap.value[newRoleId] = formState.boundWarehouseId
}
Message.success(t('system.role.message.createSuccess'))
isCreating.value = false
await loadData()
if (newRoleId) {
selectedRole.value = dataSource.value.find((r) => r.id === newRoleId) || null
}
return newRoleId || null
}
if (selectedRole.value?.id) {
const updateData: RoleUpdateDto = { name: formState.name }
await RoleService.putRbacRoleUpdate(selectedRole.value.id, updateData)
if (formState.boundWarehouseId !== undefined) {
roleWarehouseMap.value[selectedRole.value.id] = formState.boundWarehouseId || ''
}
await loadData()
return selectedRole.value.id
}
return null
} catch (error: any) {
if (error?.fields) {
activeTab.value = 'basic'
return null
}
handleApiError(error)
return null
} finally {
modalLoading.value = false
}
}
async function handleSavePermissions(roleId?: string) {
const id = roleId || selectedRole.value?.id
if (!id || isCreating.value) return false
if (isAdminRole(selectedRole.value)) return true
if (!canAssignPermissions.value) return true
permissionSaving.value = true
try {
await RoleService.postRbacRoleAssignPermissions(id, normalizedSelectedPermissions.value)
const rbacUserStore = useRbacUserStore()
const currentHasRole = rbacUserStore.userInfo?.roles?.some((r) => r.id === id)
if (currentHasRole) {
try {
await rbacUserStore.refreshUserInfo()
} catch {
Message.warning(t('system.role.permission.refreshHint'))
}
}
return true
} catch (error) {
handleApiError(error)
return false
} finally {
permissionSaving.value = false
}
}
async function handleSaveAll() {
const wasCreating = isCreating.value
const roleId = await handleSaveRole()
if (!roleId) return
if (wasCreating || isAdminRole(selectedRole.value)) {
if (!wasCreating) {
Message.success(t('system.role.message.updateSuccess'))
}
captureBaseline()
if (wasCreating && canAssignPermissions.value) {
activeTab.value = 'permissions'
}
return
}
const ok = await handleSavePermissions(roleId)
if (ok) {
Message.success(t('system.role.message.updateSuccess'))
captureBaseline()
}
}
watch(
() => selectedRole.value?.id,
async (roleId) => {
if (!roleId || isCreating.value) return
dirtyWatchReady = false
syncFormFromRole(selectedRole.value!)
activeTab.value = canAssignPermissions.value ? 'permissions' : 'basic'
permissionKeyword.value = ''
await loadRolePermissions(roleId)
}
)
watch(
[() => formState.name, () => formState.code, () => formState.boundWarehouseId, selectedPermissions],
() => refreshDirty(),
{ deep: true }
)
onMounted(async () => {
await loadData()
await loadPermissionTree()
})
</script>
<style scoped lang="less">
@import '@/components/RbacSplit/rbac-split-layout.less';
.role-pane {
display: flex;
flex-direction: column;
gap: 14px;
max-width: 880px;
}
.role-card {
border: 1px solid var(--color-border-2);
border-radius: 10px;
background: #fff;
overflow: hidden;
}
.role-card__head {
padding: 14px 18px 0;
}
.role-card__title {
margin: 0;
font-size: 14px;
font-weight: 600;
color: var(--color-text-1);
}
.role-card__hint {
margin: 4px 0 0;
font-size: 12px;
color: var(--color-text-3);
line-height: 1.4;
}
.role-card__body {
padding: 12px 18px 16px;
}
.role-basic-form {
:deep(.arco-form-item) {
margin-bottom: 12px;
}
}
.role-create-time {
display: inline-block;
font-size: 13px;
color: var(--color-text-2);
line-height: 32px;
}
.role-next-card {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
flex-wrap: wrap;
padding: 14px 16px;
border-radius: 10px;
border: 1px solid color-mix(in srgb, var(--app-primary-color, #1d7281) 28%, #fff);
background: color-mix(in srgb, var(--app-primary-color, #1d7281) 8%, #fff);
}
.role-next-card__title {
margin: 0;
font-size: 14px;
font-weight: 600;
color: var(--color-text-1);
}
.role-next-card__desc {
margin: 4px 0 0;
font-size: 12px;
color: var(--color-text-3);
line-height: 1.4;
}
.permission-body {
display: flex;
flex-direction: column;
min-height: 0;
height: 100%;
}
.permission-toolbar {
display: flex;
align-items: center;
justify-content: center;
flex-wrap: wrap;
gap: 8px;
margin-bottom: 12px;
}
.permission-toolbar__search {
width: 220px;
}
.permission-table {
width: 100%;
:deep(.arco-table-th) {
background: var(--color-fill-1);
}
:deep(.arco-table-td) {
vertical-align: middle;
}
:deep(.arco-table-td .arco-checkbox) {
display: inline-flex;
align-items: center;
}
:deep(.arco-table-td .arco-checkbox .arco-checkbox-label) {
line-height: 1.4;
}
}
.permission-button-group {
display: flex;
flex-wrap: wrap;
gap: 8px 16px;
padding: 4px 0;
}
.permission-no-buttons {
color: var(--color-text-4);
}
.permission-empty {
padding: 64px 24px;
text-align: center;
color: var(--color-text-3);
}
</style>