优化构架
This commit is contained in:
@@ -0,0 +1,326 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { http } from '@/shared/api/http'
|
||||
import {
|
||||
assignPlatformInternalUserRoles,
|
||||
changePlatformManagedUserStatus,
|
||||
changePlatformInternalUserStatus,
|
||||
changePlatformTenantStatus,
|
||||
changePlatformPermissionStatus,
|
||||
changePlatformRoleStatus,
|
||||
createPlatformPermission,
|
||||
createPlatformManagedUser,
|
||||
createPlatformRole,
|
||||
createPlatformTenant,
|
||||
deletePlatformPermission,
|
||||
deletePlatformRole,
|
||||
downloadTenantQualification,
|
||||
listPlatformTenants,
|
||||
listPlatformTenantOrderCounts,
|
||||
listTenantQualifications,
|
||||
listPlatformPermissions,
|
||||
listPlatformRoles,
|
||||
listPlatformInternalUsers,
|
||||
listPlatformManagedUsers,
|
||||
getPlatformUserOptions,
|
||||
qualificationFileName,
|
||||
replacePlatformRolePermissions,
|
||||
resetPlatformInternalUserPassword,
|
||||
resetPlatformManagedUserPassword,
|
||||
submitPlatformTenantReview,
|
||||
updatePlatformInternalUser,
|
||||
updatePlatformManagedUser,
|
||||
updatePlatformPermission,
|
||||
updatePlatformRole,
|
||||
updatePlatformTenant,
|
||||
uploadPlatformTenantQualification,
|
||||
type PlatformPermissionResource,
|
||||
type PlatformInternalUser,
|
||||
type PlatformManagedUser,
|
||||
type PlatformRoleResource,
|
||||
} from './platformIam'
|
||||
|
||||
vi.mock('@/shared/api/http', () => ({
|
||||
http: { get: vi.fn(), post: vi.fn(), put: vi.fn(), delete: vi.fn() },
|
||||
unwrapApiResponse: <T>(response: { data: T }) => response.data,
|
||||
}))
|
||||
|
||||
const role: PlatformRoleResource = {
|
||||
id: 4000002,
|
||||
tenantId: 0,
|
||||
appCode: 'PLATFORM',
|
||||
roleCode: 'CUSTOMER_REVIEWER',
|
||||
roleName: '企业审核员',
|
||||
roleType: 'SYSTEM',
|
||||
status: 'ACTIVE',
|
||||
description: '企业资料与入驻审核',
|
||||
permissionIds: ['5100010'],
|
||||
}
|
||||
|
||||
const permission: PlatformPermissionResource = {
|
||||
id: 5100010,
|
||||
tenantId: 0,
|
||||
appCode: 'PLATFORM',
|
||||
permissionType: 'MENU',
|
||||
parentId: 5100000,
|
||||
permissionCode: 'platform:customer:list',
|
||||
permissionName: '企业客户',
|
||||
routePath: '/customers',
|
||||
httpMethod: null,
|
||||
sortNo: 10,
|
||||
status: 'ACTIVE',
|
||||
builtIn: false,
|
||||
}
|
||||
|
||||
const internalUser: PlatformInternalUser = {
|
||||
membershipId: 3000001,
|
||||
userId: 2000001,
|
||||
authUserId: 2000001,
|
||||
username: 'platform_admin',
|
||||
displayName: '平台管理员',
|
||||
phone: '13800138000',
|
||||
email: 'admin@example.com',
|
||||
memberType: 'INTERNAL',
|
||||
memberNo: 'PLATFORM-0001',
|
||||
status: 'ACTIVE',
|
||||
roleIds: [4000001],
|
||||
}
|
||||
|
||||
const managedUser: PlatformManagedUser = {
|
||||
membershipId: '3000002',
|
||||
userId: '2000002',
|
||||
authUserId: '1000002',
|
||||
username: 'zhangwei',
|
||||
displayName: '张伟',
|
||||
phone: '13800138000',
|
||||
email: 'zhangwei@example.com',
|
||||
tenantId: '10001',
|
||||
tenantName: '华远贸易',
|
||||
memberType: 'EMPLOYEE',
|
||||
memberNo: 'MEMBER-3000002',
|
||||
status: 'ACTIVE',
|
||||
roleIds: ['40001'],
|
||||
roleNames: ['租户管理员'],
|
||||
lastLoginAt: '2026-06-01T10:30:00',
|
||||
protectedAccount: false,
|
||||
}
|
||||
|
||||
describe('platform IAM roles', () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(http.get).mockReset()
|
||||
vi.mocked(http.post).mockReset()
|
||||
vi.mocked(http.put).mockReset()
|
||||
vi.mocked(http.delete).mockReset()
|
||||
})
|
||||
|
||||
it('loads roles from the platform IAM prefix', async () => {
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', message: 'success', data: [role] })
|
||||
|
||||
await expect(listPlatformRoles()).resolves.toEqual([role])
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/iam/roles')
|
||||
})
|
||||
|
||||
it('creates a platform role with the documented payload', async () => {
|
||||
const payload = {
|
||||
roleCode: 'CUSTOMER_REVIEWER',
|
||||
roleName: '企业审核员',
|
||||
description: '企业资料与入驻审核',
|
||||
}
|
||||
vi.mocked(http.post).mockResolvedValue({ code: '200', message: 'success', data: role })
|
||||
|
||||
await expect(createPlatformRole(payload)).resolves.toEqual(role)
|
||||
expect(http.post).toHaveBeenCalledWith('/platform/v1/iam/roles', payload)
|
||||
})
|
||||
|
||||
it('updates status, permissions, and deletes roles with the implemented IAM routes', async () => {
|
||||
vi.mocked(http.put).mockResolvedValue({ code: '200', message: 'success', data: role })
|
||||
vi.mocked(http.delete).mockResolvedValue({ code: '200', message: 'success', data: null })
|
||||
|
||||
await expect(updatePlatformRole(role.id, { roleName: '审核主管', description: '负责企业审核' })).resolves.toEqual(role)
|
||||
await expect(changePlatformRoleStatus(role.id, 'DISABLED')).resolves.toEqual(role)
|
||||
await expect(replacePlatformRolePermissions(role.id, ['5100010'])).resolves.toEqual(role)
|
||||
await expect(deletePlatformRole(role.id)).resolves.toBeNull()
|
||||
|
||||
expect(http.put).toHaveBeenNthCalledWith(1, `/platform/v1/iam/roles/${role.id}`, { roleName: '审核主管', description: '负责企业审核' })
|
||||
expect(http.put).toHaveBeenNthCalledWith(2, `/platform/v1/iam/roles/${role.id}/status`, { status: 'DISABLED' })
|
||||
expect(http.put).toHaveBeenNthCalledWith(3, '/platform/v1/iam/roles/permissions', { roleId: role.id, permissionIds: ['5100010'] })
|
||||
expect(http.delete).toHaveBeenCalledWith(`/platform/v1/iam/roles/${role.id}`)
|
||||
})
|
||||
|
||||
it('loads and creates permission resources under the platform IAM prefix', async () => {
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', message: 'success', data: [permission] })
|
||||
vi.mocked(http.post).mockResolvedValue({ code: '200', message: 'success', data: permission })
|
||||
const payload = {
|
||||
type: 'MENU' as const,
|
||||
code: permission.permissionCode,
|
||||
name: permission.permissionName,
|
||||
parentId: permission.parentId,
|
||||
routePath: permission.routePath,
|
||||
httpMethod: null,
|
||||
sortNo: permission.sortNo,
|
||||
}
|
||||
|
||||
await expect(listPlatformPermissions()).resolves.toEqual([permission])
|
||||
await expect(createPlatformPermission(payload)).resolves.toEqual(permission)
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/iam/permissions')
|
||||
expect(http.post).toHaveBeenCalledWith('/platform/v1/iam/permissions', payload)
|
||||
})
|
||||
|
||||
it('updates, changes status, and deletes custom permission resources with IAM routes', async () => {
|
||||
vi.mocked(http.put).mockResolvedValue({ code: '200', message: 'success', data: permission })
|
||||
vi.mocked(http.delete).mockResolvedValue({ code: '200', message: 'success', data: null })
|
||||
const payload = { name: '企业客户', parentId: permission.parentId, routePath: '/customers', httpMethod: null, sortNo: 10 }
|
||||
|
||||
await expect(updatePlatformPermission(permission.id, payload)).resolves.toEqual(permission)
|
||||
await expect(changePlatformPermissionStatus(permission.id, 'DISABLED')).resolves.toEqual(permission)
|
||||
await expect(deletePlatformPermission(permission.id)).resolves.toBeNull()
|
||||
|
||||
expect(http.put).toHaveBeenNthCalledWith(1, `/platform/v1/iam/permissions/${permission.id}`, payload)
|
||||
expect(http.put).toHaveBeenNthCalledWith(2, `/platform/v1/iam/permissions/${permission.id}/status`, { status: 'DISABLED' })
|
||||
expect(http.delete).toHaveBeenCalledWith(`/platform/v1/iam/permissions/${permission.id}`)
|
||||
})
|
||||
|
||||
it('maintains internal users through their public membership ID', async () => {
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', message: 'success', data: [internalUser] })
|
||||
vi.mocked(http.put).mockResolvedValue({ code: '200', message: 'success', data: internalUser })
|
||||
const update = {
|
||||
displayName: '平台管理员',
|
||||
phone: '13800138000',
|
||||
email: 'admin@example.com',
|
||||
memberNo: 'PLATFORM-0001',
|
||||
roleIds: [4000001],
|
||||
}
|
||||
|
||||
await expect(listPlatformInternalUsers()).resolves.toEqual([internalUser])
|
||||
await expect(updatePlatformInternalUser(internalUser.membershipId, update)).resolves.toEqual(internalUser)
|
||||
await expect(changePlatformInternalUserStatus(internalUser.membershipId, 'DISABLED')).resolves.toEqual(internalUser)
|
||||
await expect(resetPlatformInternalUserPassword(internalUser.membershipId, 'ChangeMe123')).resolves.toEqual(internalUser)
|
||||
await expect(assignPlatformInternalUserRoles(internalUser.membershipId, [4000001])).resolves.toEqual(internalUser)
|
||||
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/iam/internal-users')
|
||||
expect(http.put).toHaveBeenNthCalledWith(1, `/platform/v1/iam/internal-users/${internalUser.membershipId}`, update)
|
||||
expect(http.put).toHaveBeenNthCalledWith(2, `/platform/v1/iam/internal-users/${internalUser.membershipId}/status`, { status: 'DISABLED' })
|
||||
expect(http.put).toHaveBeenNthCalledWith(3, `/platform/v1/iam/internal-users/${internalUser.membershipId}/password`, { newPassword: 'ChangeMe123' })
|
||||
expect(http.put).toHaveBeenNthCalledWith(4, `/platform/v1/iam/internal-users/${internalUser.membershipId}/roles`, { roleIds: [4000001] })
|
||||
})
|
||||
|
||||
it('maintains platform and tenant users through the unified user contract', async () => {
|
||||
const userOptions = {
|
||||
tenants: [{ id: '10001', name: '华远贸易', status: 'ACTIVE' }],
|
||||
roles: [{ id: '40001', tenantId: '10001', name: '租户管理员', status: 'ACTIVE' }],
|
||||
}
|
||||
const create = {
|
||||
username: 'zhangwei', displayName: '张伟', phone: '13800138000', email: 'zhangwei@example.com',
|
||||
tenantId: '10001', roleIds: ['40001'], password: 'Password1', status: 'ACTIVE' as const,
|
||||
}
|
||||
const update = {
|
||||
displayName: '张伟', phone: '13800138000', email: 'zhangwei@example.com',
|
||||
tenantId: '10001', roleIds: ['40001'],
|
||||
}
|
||||
vi.mocked(http.get).mockResolvedValueOnce({ code: '200', message: 'success', data: [managedUser] })
|
||||
.mockResolvedValueOnce({ code: '200', message: 'success', data: userOptions })
|
||||
vi.mocked(http.post).mockResolvedValue({ code: '200', message: 'success', data: managedUser })
|
||||
vi.mocked(http.put).mockResolvedValue({ code: '200', message: 'success', data: managedUser })
|
||||
|
||||
await expect(listPlatformManagedUsers()).resolves.toEqual([managedUser])
|
||||
await expect(getPlatformUserOptions()).resolves.toEqual(userOptions)
|
||||
await expect(createPlatformManagedUser(create)).resolves.toEqual(managedUser)
|
||||
await expect(updatePlatformManagedUser(managedUser.membershipId, update)).resolves.toEqual(managedUser)
|
||||
await expect(changePlatformManagedUserStatus(managedUser.membershipId, 'DISABLED')).resolves.toEqual(managedUser)
|
||||
await expect(resetPlatformManagedUserPassword(managedUser.membershipId, 'ChangeMe123')).resolves.toEqual(managedUser)
|
||||
|
||||
expect(http.get).toHaveBeenNthCalledWith(1, '/platform/v1/iam/users')
|
||||
expect(http.get).toHaveBeenNthCalledWith(2, '/platform/v1/iam/users/options')
|
||||
expect(http.post).toHaveBeenCalledWith('/platform/v1/iam/users', create)
|
||||
expect(http.put).toHaveBeenNthCalledWith(1, `/platform/v1/iam/users/${managedUser.membershipId}`, update)
|
||||
expect(http.put).toHaveBeenNthCalledWith(2, `/platform/v1/iam/users/${managedUser.membershipId}/status`, { status: 'DISABLED' })
|
||||
expect(http.put).toHaveBeenNthCalledWith(3, `/platform/v1/iam/users/${managedUser.membershipId}/password`, { newPassword: 'ChangeMe123' })
|
||||
})
|
||||
|
||||
it('loads qualifications for the selected tenant', async () => {
|
||||
const qualification = {
|
||||
id: 12,
|
||||
tenantId: 8,
|
||||
qualificationType: 'BUSINESS_LICENSE',
|
||||
certificateNo: '91440300XXXXXXXXXX',
|
||||
documentUrl: '/api/merchant/v1/files/qualifications/license.png',
|
||||
status: 'PENDING' as const,
|
||||
reviewComment: null,
|
||||
}
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', message: 'success', data: [qualification] })
|
||||
|
||||
await expect(listTenantQualifications(8)).resolves.toEqual([qualification])
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/iam/tenants/8/qualifications')
|
||||
})
|
||||
|
||||
it('loads paginated tenants with the documented filters', async () => {
|
||||
const page = { records: [], page: 2, size: 10, total: 11, pages: 2 }
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', message: 'success', data: { ...page, page: '2', size: '10', total: '11', pages: '2' } })
|
||||
|
||||
await expect(listPlatformTenants({ page: 2, size: 10, keyword: '柏悦', status: 'ACTIVE' })).resolves.toEqual(page)
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/iam/tenants', {
|
||||
params: { page: 2, size: 10, keyword: '柏悦', status: 'ACTIVE' },
|
||||
})
|
||||
})
|
||||
|
||||
it('creates, updates, and changes customer status with the platform tenant contract', async () => {
|
||||
const tenant = { id: '8', tenantCode: 'TEN8', tenantName: '柏悦物流', status: 'ACTIVE' }
|
||||
const create = {
|
||||
tenantName: '柏悦物流', legalName: '柏悦物流有限公司', unifiedSocialCreditCode: '91440300MA5ABCDE12',
|
||||
contactName: '张三', contactPhone: '13800138000', contactEmail: 'ops@example.com', servicePackage: '标准版',
|
||||
contactWechat: 'baiyue-ops', salesOwnerName: '李四', paymentTermDays: 30, enterpriseType: '有限责任公司',
|
||||
establishedDate: '2020-01-01', registeredCapital: 1000, registeredCapitalCurrency: 'CNY',
|
||||
registeredAddress: '深圳市宝安区', internalRemark: '重点客户',
|
||||
}
|
||||
vi.mocked(http.post).mockResolvedValue({ code: '200', message: 'success', data: tenant })
|
||||
vi.mocked(http.put).mockResolvedValue({ code: '200', message: 'success', data: tenant })
|
||||
|
||||
await expect(createPlatformTenant(create)).resolves.toEqual(tenant)
|
||||
const { unifiedSocialCreditCode: _creditCode, ...update } = create
|
||||
await expect(updatePlatformTenant('8', update)).resolves.toEqual(tenant)
|
||||
await expect(changePlatformTenantStatus('8', 'DISABLED')).resolves.toEqual(tenant)
|
||||
|
||||
expect(http.post).toHaveBeenCalledWith('/platform/v1/iam/tenants', create)
|
||||
expect(http.put).toHaveBeenNthCalledWith(1, '/platform/v1/iam/tenants/8', update)
|
||||
expect(http.put).toHaveBeenNthCalledWith(2, '/platform/v1/iam/tenants/8/status', { status: 'DISABLED' })
|
||||
})
|
||||
|
||||
it('loads real order totals for the visible customer tenants', async () => {
|
||||
const counts = [{ tenantId: '8', orderCount: 12 }, { tenantId: '9', orderCount: 0 }]
|
||||
vi.mocked(http.get).mockResolvedValue({ code: '200', message: 'success', data: counts })
|
||||
await expect(listPlatformTenantOrderCounts(['8', '9'])).resolves.toEqual(counts)
|
||||
expect(http.get).toHaveBeenCalledWith('/platform/v1/orders/first-leg/tenant-counts?tenantIds=8,9')
|
||||
})
|
||||
|
||||
it('uploads qualification metadata before explicitly submitting the customer review', async () => {
|
||||
const uploadResult = { qualificationId: '91', reviewId: null, tenantStatus: 'PROFILE_REQUIRED', documentUrl: '/file.pdf' }
|
||||
const tenant = { id: '8', tenantCode: 'TEN8', tenantName: '柏悦物流', status: 'PENDING' }
|
||||
vi.mocked(http.post).mockResolvedValueOnce({ code: '200', message: 'success', data: uploadResult })
|
||||
.mockResolvedValueOnce({ code: '200', message: 'success', data: tenant })
|
||||
const file = new File(['%PDF-1.4'], '营业执照.pdf', { type: 'application/pdf' })
|
||||
|
||||
await expect(uploadPlatformTenantQualification('8', 'BUSINESS_LICENSE', file, '2030-12-31', '91440300MA5ABCDE12', true)).resolves.toEqual(uploadResult)
|
||||
await expect(submitPlatformTenantReview('8')).resolves.toEqual(tenant)
|
||||
|
||||
const form = vi.mocked(http.post).mock.calls[0]?.[1] as FormData
|
||||
expect(http.post).toHaveBeenNthCalledWith(1, '/platform/v1/files/qualifications/8', expect.any(FormData))
|
||||
expect(form.get('file')).toBe(file)
|
||||
expect(form.get('qualificationType')).toBe('BUSINESS_LICENSE')
|
||||
expect(form.get('validTo')).toBe('2030-12-31')
|
||||
expect(form.get('certificateNo')).toBe('91440300MA5ABCDE12')
|
||||
expect(form.get('replace')).toBe('true')
|
||||
expect(http.post).toHaveBeenNthCalledWith(2, '/platform/v1/iam/tenants/8/submit-review', {})
|
||||
})
|
||||
|
||||
it('downloads a qualification with the platform file endpoint and a safe filename', async () => {
|
||||
const blob = new Blob(['image'], { type: 'image/png' })
|
||||
vi.mocked(http.get).mockResolvedValue(blob)
|
||||
|
||||
expect(qualificationFileName('/api/merchant/v1/files/qualifications/%E8%90%A5%E4%B8%9A%E6%89%A7%E7%85%A7.png?token=ignored')).toBe('营业执照.png')
|
||||
await expect(downloadTenantQualification(8, '/api/merchant/v1/files/qualifications/%E8%90%A5%E4%B8%9A%E6%89%A7%E7%85%A7.png')).resolves.toBe(blob)
|
||||
expect(http.get).toHaveBeenCalledWith(
|
||||
'/platform/v1/files/qualifications/8/%E8%90%A5%E4%B8%9A%E6%89%A7%E7%85%A7.png',
|
||||
{ responseType: 'blob' },
|
||||
)
|
||||
expect(() => qualificationFileName('/api/merchant/v1/files/qualifications/%2Fetc%2Fpasswd')).toThrow('资质文件地址无效')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,446 @@
|
||||
import { http, unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
|
||||
import type { PlatformPermissionResource } from '@/shared/types/platformPermission'
|
||||
|
||||
export type { PlatformPermissionResource } from '@/shared/types/platformPermission'
|
||||
|
||||
export interface EnterpriseReview {
|
||||
id: number
|
||||
tenantId: number
|
||||
status: 'PENDING' | 'APPROVED' | 'REJECTED'
|
||||
tenantName?: string | null
|
||||
tenantCode?: string | null
|
||||
qualificationId?: number | null
|
||||
qualificationType?: string | null
|
||||
certificateNo?: string | null
|
||||
documentUrl?: string | null
|
||||
contactName?: string | null
|
||||
contactPhone?: string | null
|
||||
contactEmail?: string | null
|
||||
submittedAt?: string | null
|
||||
createdAt?: string | null
|
||||
reviewComment?: string | null
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
export type PlatformTenantStatus = 'PENDING' | 'ACTIVE' | 'REJECTED' | 'INACTIVE' | string
|
||||
|
||||
export interface PlatformTenantResource {
|
||||
id: number | string
|
||||
tenantCode: string
|
||||
tenantName: string
|
||||
status: PlatformTenantStatus
|
||||
legalName: string | null
|
||||
unifiedSocialCreditCode: string | null
|
||||
contactName: string | null
|
||||
contactPhone: string | null
|
||||
contactEmail: string | null
|
||||
servicePackage: string | null
|
||||
contactWechat: string | null
|
||||
salesOwnerName: string | null
|
||||
paymentTermDays: number | null
|
||||
enterpriseType: string | null
|
||||
establishedDate: string | null
|
||||
registeredCapital: number | string | null
|
||||
registeredCapitalCurrency: string | null
|
||||
registeredAddress: string | null
|
||||
internalRemark: string | null
|
||||
createdAt: string | null
|
||||
approvedAt: string | null
|
||||
}
|
||||
|
||||
export interface CreatePlatformTenantRequest {
|
||||
tenantName: string
|
||||
legalName: string
|
||||
unifiedSocialCreditCode: string
|
||||
contactName: string
|
||||
contactPhone: string
|
||||
contactEmail: string
|
||||
servicePackage: string
|
||||
contactWechat: string
|
||||
salesOwnerName: string
|
||||
paymentTermDays: number
|
||||
enterpriseType: string
|
||||
establishedDate: string | null
|
||||
registeredCapital: number | null
|
||||
registeredCapitalCurrency: string
|
||||
registeredAddress: string
|
||||
internalRemark: string
|
||||
}
|
||||
|
||||
export type UpdatePlatformTenantRequest = Omit<CreatePlatformTenantRequest, 'unifiedSocialCreditCode'>
|
||||
|
||||
export interface PlatformTenantOrderCount {
|
||||
tenantId: number | string
|
||||
orderCount: number
|
||||
}
|
||||
|
||||
export interface PlatformTenantPage {
|
||||
records: PlatformTenantResource[]
|
||||
page: number
|
||||
size: number
|
||||
total: number
|
||||
pages: number
|
||||
}
|
||||
|
||||
export interface PlatformTenantQuery {
|
||||
page: number
|
||||
size: number
|
||||
keyword?: string
|
||||
status?: PlatformTenantStatus
|
||||
}
|
||||
|
||||
export interface PlatformTenantQualification {
|
||||
id: number | string
|
||||
tenantId: number | string
|
||||
qualificationType: 'BUSINESS_LICENSE' | string
|
||||
certificateNo: string | null
|
||||
documentUrl: string
|
||||
status: 'PENDING' | 'APPROVED' | 'REJECTED'
|
||||
reviewComment: string | null
|
||||
validTo?: string | null
|
||||
}
|
||||
|
||||
export type PlatformQualificationType = 'BUSINESS_LICENSE' | 'LEGAL_PERSON_ID' | 'FREIGHT_FORWARDER_CERTIFICATE' | 'BANK_ACCOUNT_LICENSE'
|
||||
|
||||
export interface PlatformQualificationUploadResponse {
|
||||
qualificationId: number | string
|
||||
reviewId: number | string | null
|
||||
tenantStatus: PlatformTenantStatus
|
||||
documentUrl: string
|
||||
replacedDocumentUrl?: string | null
|
||||
}
|
||||
|
||||
export interface PlatformRoleResource {
|
||||
id: number | string
|
||||
tenantId: number | string
|
||||
appCode: 'PLATFORM'
|
||||
roleCode: string
|
||||
roleName: string
|
||||
roleType: 'SYSTEM' | 'CUSTOM' | string
|
||||
status: 'ACTIVE' | 'INACTIVE' | string
|
||||
description: string | null
|
||||
permissionIds?: Array<number | string>
|
||||
}
|
||||
|
||||
export interface CreatePlatformRoleRequest {
|
||||
roleCode: string
|
||||
roleName: string
|
||||
description: string
|
||||
}
|
||||
|
||||
export interface UpdatePlatformRoleRequest {
|
||||
roleName: string
|
||||
description: string
|
||||
}
|
||||
|
||||
export interface CreatePlatformPermissionRequest {
|
||||
type: 'MENU' | 'BUTTON'
|
||||
code: string
|
||||
name: string
|
||||
parentId: number | string
|
||||
routePath: string | null
|
||||
httpMethod: null
|
||||
sortNo: number
|
||||
}
|
||||
|
||||
export interface UpdatePlatformPermissionRequest {
|
||||
name: string
|
||||
parentId: number | string | null
|
||||
routePath: string | null
|
||||
httpMethod: string | null
|
||||
sortNo: number
|
||||
}
|
||||
|
||||
export interface PlatformInternalUser {
|
||||
membershipId: number | string
|
||||
userId: number | string
|
||||
authUserId: number | string
|
||||
username: string
|
||||
displayName: string
|
||||
phone: string | null
|
||||
email: string | null
|
||||
memberType: string
|
||||
memberNo: string | null
|
||||
status: 'ACTIVE' | 'DISABLED' | string
|
||||
roleIds: Array<number | string>
|
||||
}
|
||||
|
||||
export interface CreatePlatformInternalUserRequest {
|
||||
authUserId: number | string
|
||||
userType: string
|
||||
displayName: string
|
||||
phone: string
|
||||
email: string
|
||||
memberNo?: string
|
||||
roleIds?: Array<number | string>
|
||||
}
|
||||
|
||||
export interface UpdatePlatformInternalUserRequest {
|
||||
displayName: string
|
||||
phone: string
|
||||
email: string
|
||||
memberNo: string
|
||||
roleIds: Array<number | string>
|
||||
}
|
||||
|
||||
export interface PlatformManagedUser {
|
||||
membershipId: number | string
|
||||
userId: number | string
|
||||
authUserId: number | string
|
||||
username: string
|
||||
displayName: string
|
||||
phone: string | null
|
||||
email: string | null
|
||||
tenantId: number | string
|
||||
tenantName: string
|
||||
memberType: string
|
||||
memberNo: string | null
|
||||
status: 'ACTIVE' | 'DISABLED'
|
||||
roleIds: Array<number | string>
|
||||
roleNames: string[]
|
||||
lastLoginAt: string | null
|
||||
protectedAccount: boolean
|
||||
}
|
||||
|
||||
export interface PlatformUserOptions {
|
||||
tenants: Array<{ id: number | string; name: string; status: string }>
|
||||
roles: Array<{ id: number | string; tenantId: number | string; name: string; status: string }>
|
||||
}
|
||||
|
||||
export interface CreatePlatformManagedUserRequest {
|
||||
username: string
|
||||
displayName: string
|
||||
phone: string
|
||||
email: string
|
||||
tenantId: number | string
|
||||
roleIds: Array<number | string>
|
||||
password: string
|
||||
status: 'ACTIVE' | 'DISABLED'
|
||||
}
|
||||
|
||||
export interface UpdatePlatformManagedUserRequest {
|
||||
displayName: string
|
||||
phone: string
|
||||
email: string
|
||||
tenantId: number | string
|
||||
roleIds: Array<number | string>
|
||||
}
|
||||
|
||||
async function getData<T>(path: string): Promise<T> {
|
||||
const response = await http.get<ApiEnvelope<T>, ApiEnvelope<T>>(path)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
async function postData<T>(path: string, body: unknown): Promise<T> {
|
||||
const response = await http.post<ApiEnvelope<T>, ApiEnvelope<T>>(path, body)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
async function putData<T>(path: string, body: unknown): Promise<T> {
|
||||
const response = await http.put<ApiEnvelope<T>, ApiEnvelope<T>>(path, body)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
async function deleteData<T>(path: string): Promise<T> {
|
||||
const response = await http.delete<ApiEnvelope<T>, ApiEnvelope<T>>(path)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
export function listPlatformPermissions() {
|
||||
return getData<PlatformPermissionResource[]>('/platform/v1/iam/permissions')
|
||||
}
|
||||
|
||||
export function listEnterpriseReviews() {
|
||||
return getData<EnterpriseReview[]>('/platform/v1/iam/reviews')
|
||||
}
|
||||
|
||||
export async function listPlatformTenants(query: PlatformTenantQuery) {
|
||||
const response = await http.get<ApiEnvelope<PlatformTenantPage>, ApiEnvelope<PlatformTenantPage>>(
|
||||
'/platform/v1/iam/tenants',
|
||||
{
|
||||
params: {
|
||||
page: query.page,
|
||||
size: query.size,
|
||||
...(query.keyword ? { keyword: query.keyword } : {}),
|
||||
...(query.status ? { status: query.status } : {}),
|
||||
},
|
||||
},
|
||||
)
|
||||
const data = unwrapApiResponse(response)
|
||||
return {
|
||||
...data,
|
||||
page: Number(data.page),
|
||||
size: Number(data.size),
|
||||
total: Number(data.total),
|
||||
pages: Number(data.pages),
|
||||
}
|
||||
}
|
||||
|
||||
export function getPlatformTenant(tenantId: number | string) {
|
||||
return getData<PlatformTenantResource>(`/platform/v1/iam/tenants/${tenantId}`)
|
||||
}
|
||||
|
||||
export function createPlatformTenant(payload: CreatePlatformTenantRequest) {
|
||||
return postData<PlatformTenantResource>('/platform/v1/iam/tenants', payload)
|
||||
}
|
||||
|
||||
export function updatePlatformTenant(tenantId: number | string, payload: UpdatePlatformTenantRequest) {
|
||||
return putData<PlatformTenantResource>(`/platform/v1/iam/tenants/${tenantId}`, payload)
|
||||
}
|
||||
|
||||
export function changePlatformTenantStatus(tenantId: number | string, status: 'ACTIVE' | 'DISABLED') {
|
||||
return putData<PlatformTenantResource>(`/platform/v1/iam/tenants/${tenantId}/status`, { status })
|
||||
}
|
||||
|
||||
export function submitPlatformTenantReview(tenantId: number | string) {
|
||||
return postData<PlatformTenantResource>(`/platform/v1/iam/tenants/${tenantId}/submit-review`, {})
|
||||
}
|
||||
|
||||
export async function uploadPlatformTenantQualification(
|
||||
tenantId: number | string,
|
||||
qualificationType: PlatformQualificationType,
|
||||
file: File,
|
||||
validTo?: string,
|
||||
certificateNo?: string,
|
||||
replace = false,
|
||||
) {
|
||||
const form = new FormData()
|
||||
form.append('file', file)
|
||||
form.append('qualificationType', qualificationType)
|
||||
if (validTo) form.append('validTo', validTo)
|
||||
if (certificateNo) form.append('certificateNo', certificateNo)
|
||||
if (replace) form.append('replace', 'true')
|
||||
const response = await http.post<ApiEnvelope<PlatformQualificationUploadResponse>, ApiEnvelope<PlatformQualificationUploadResponse>>(
|
||||
`/platform/v1/files/qualifications/${tenantId}`,
|
||||
form,
|
||||
)
|
||||
return unwrapApiResponse(response)
|
||||
}
|
||||
|
||||
export function listPlatformTenantOrderCounts(tenantIds: Array<number | string>) {
|
||||
const ids = tenantIds.map((id) => encodeURIComponent(String(id))).join(',')
|
||||
return getData<PlatformTenantOrderCount[]>(`/platform/v1/orders/first-leg/tenant-counts?tenantIds=${ids}`)
|
||||
}
|
||||
|
||||
export function listTenantQualifications(tenantId: number | string) {
|
||||
return getData<PlatformTenantQualification[]>(`/platform/v1/iam/tenants/${tenantId}/qualifications`)
|
||||
}
|
||||
|
||||
export function qualificationFileName(documentUrl: string) {
|
||||
const path = documentUrl.split(/[?#]/, 1)[0]
|
||||
const encodedName = path.split('/').filter(Boolean).at(-1)
|
||||
if (!encodedName) throw new Error('资质文件地址无效')
|
||||
let fileName: string
|
||||
try {
|
||||
fileName = decodeURIComponent(encodedName)
|
||||
} catch {
|
||||
throw new Error('资质文件地址无效')
|
||||
}
|
||||
if (!fileName || fileName === '.' || fileName === '..' || /[\\/]/.test(fileName)) {
|
||||
throw new Error('资质文件地址无效')
|
||||
}
|
||||
return fileName
|
||||
}
|
||||
|
||||
export function downloadTenantQualification(tenantId: number | string, documentUrl: string) {
|
||||
const fileName = qualificationFileName(documentUrl)
|
||||
return http.get<Blob, Blob>(`/platform/v1/files/qualifications/${tenantId}/${encodeURIComponent(fileName)}`, {
|
||||
responseType: 'blob',
|
||||
})
|
||||
}
|
||||
|
||||
export function listPlatformRoles() {
|
||||
return getData<PlatformRoleResource[]>('/platform/v1/iam/roles')
|
||||
}
|
||||
|
||||
export function createPlatformRole(payload: CreatePlatformRoleRequest) {
|
||||
return postData<PlatformRoleResource>('/platform/v1/iam/roles', payload)
|
||||
}
|
||||
|
||||
export function updatePlatformRole(roleId: number | string, payload: UpdatePlatformRoleRequest) {
|
||||
return putData<PlatformRoleResource>(`/platform/v1/iam/roles/${roleId}`, payload)
|
||||
}
|
||||
|
||||
export function changePlatformRoleStatus(roleId: number | string, status: 'ACTIVE' | 'DISABLED') {
|
||||
return putData<PlatformRoleResource>(`/platform/v1/iam/roles/${roleId}/status`, { status })
|
||||
}
|
||||
|
||||
export function deletePlatformRole(roleId: number | string) {
|
||||
return deleteData<void>(`/platform/v1/iam/roles/${roleId}`)
|
||||
}
|
||||
|
||||
export function replacePlatformRolePermissions(roleId: number | string, permissionIds: Array<number | string>) {
|
||||
return putData<void>('/platform/v1/iam/roles/permissions', { roleId, permissionIds })
|
||||
}
|
||||
|
||||
export function createPlatformPermission(payload: CreatePlatformPermissionRequest) {
|
||||
return postData<PlatformPermissionResource>('/platform/v1/iam/permissions', payload)
|
||||
}
|
||||
|
||||
export function updatePlatformPermission(permissionId: number | string, payload: UpdatePlatformPermissionRequest) {
|
||||
return putData<PlatformPermissionResource>(`/platform/v1/iam/permissions/${permissionId}`, payload)
|
||||
}
|
||||
|
||||
export function changePlatformPermissionStatus(permissionId: number | string, status: 'ACTIVE' | 'DISABLED') {
|
||||
return putData<PlatformPermissionResource>(`/platform/v1/iam/permissions/${permissionId}/status`, { status })
|
||||
}
|
||||
|
||||
export function deletePlatformPermission(permissionId: number | string) {
|
||||
return deleteData<void>(`/platform/v1/iam/permissions/${permissionId}`)
|
||||
}
|
||||
|
||||
export function listPlatformInternalUsers() {
|
||||
return getData<PlatformInternalUser[]>('/platform/v1/iam/internal-users')
|
||||
}
|
||||
|
||||
export function createPlatformInternalUser(payload: CreatePlatformInternalUserRequest) {
|
||||
return postData<PlatformInternalUser>('/platform/v1/iam/internal-users', payload)
|
||||
}
|
||||
|
||||
export function updatePlatformInternalUser(membershipId: number | string, payload: UpdatePlatformInternalUserRequest) {
|
||||
return putData<PlatformInternalUser>(`/platform/v1/iam/internal-users/${membershipId}`, payload)
|
||||
}
|
||||
|
||||
export function changePlatformInternalUserStatus(membershipId: number | string, status: 'ACTIVE' | 'DISABLED') {
|
||||
return putData<PlatformInternalUser>(`/platform/v1/iam/internal-users/${membershipId}/status`, { status })
|
||||
}
|
||||
|
||||
export function resetPlatformInternalUserPassword(membershipId: number | string, newPassword: string) {
|
||||
return putData<void>(`/platform/v1/iam/internal-users/${membershipId}/password`, { newPassword })
|
||||
}
|
||||
|
||||
export function assignPlatformInternalUserRoles(membershipId: number | string, roleIds: Array<number | string>) {
|
||||
return putData<PlatformInternalUser>(`/platform/v1/iam/internal-users/${membershipId}/roles`, { roleIds })
|
||||
}
|
||||
|
||||
export function listPlatformManagedUsers() {
|
||||
return getData<PlatformManagedUser[]>('/platform/v1/iam/users')
|
||||
}
|
||||
|
||||
export function getPlatformUserOptions() {
|
||||
return getData<PlatformUserOptions>('/platform/v1/iam/users/options')
|
||||
}
|
||||
|
||||
export function createPlatformManagedUser(payload: CreatePlatformManagedUserRequest) {
|
||||
return postData<PlatformManagedUser>('/platform/v1/iam/users', payload)
|
||||
}
|
||||
|
||||
export function updatePlatformManagedUser(membershipId: number | string, payload: UpdatePlatformManagedUserRequest) {
|
||||
return putData<PlatformManagedUser>(`/platform/v1/iam/users/${membershipId}`, payload)
|
||||
}
|
||||
|
||||
export function changePlatformManagedUserStatus(membershipId: number | string, status: 'ACTIVE' | 'DISABLED') {
|
||||
return putData<PlatformManagedUser>(`/platform/v1/iam/users/${membershipId}/status`, { status })
|
||||
}
|
||||
|
||||
export function resetPlatformManagedUserPassword(membershipId: number | string, newPassword: string) {
|
||||
return putData<void>(`/platform/v1/iam/users/${membershipId}/password`, { newPassword })
|
||||
}
|
||||
|
||||
export function approveEnterpriseReview(reviewId: number, comment: string) {
|
||||
return postData<unknown>(`/platform/v1/iam/reviews/${reviewId}/approve`, { comment })
|
||||
}
|
||||
|
||||
export function rejectEnterpriseReview(reviewId: number, comment: string) {
|
||||
return postData<unknown>(`/platform/v1/iam/reviews/${reviewId}/reject`, { comment })
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from './api/platformIam'
|
||||
@@ -0,0 +1,123 @@
|
||||
import ElementPlus from 'element-plus'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import { enableAutoUnmount, flushPromises, mount } from '@vue/test-utils'
|
||||
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
getPlatformUserOptions,
|
||||
listPlatformManagedUsers,
|
||||
type PlatformManagedUser,
|
||||
} from '@/modules/iam/api/platformIam'
|
||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
||||
import { useAuthStore } from '@/core/auth/auth'
|
||||
import InternalUsersView from './InternalUsersView.vue'
|
||||
|
||||
vi.mock('@/modules/iam/api/platformIam', () => ({
|
||||
listPlatformManagedUsers: vi.fn(),
|
||||
getPlatformUserOptions: vi.fn(),
|
||||
createPlatformManagedUser: vi.fn(),
|
||||
updatePlatformManagedUser: vi.fn(),
|
||||
changePlatformManagedUserStatus: vi.fn(),
|
||||
resetPlatformManagedUserPassword: vi.fn(),
|
||||
}))
|
||||
|
||||
class ResizeObserverStub implements ResizeObserver {
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
}
|
||||
|
||||
function createMemoryStorage(): Storage {
|
||||
const values = new Map<string, string>()
|
||||
return {
|
||||
get length() { return values.size },
|
||||
clear: () => values.clear(),
|
||||
getItem: (key) => values.get(key) ?? null,
|
||||
key: (index) => [...values.keys()][index] ?? null,
|
||||
removeItem: (key) => values.delete(key),
|
||||
setItem: (key, value) => values.set(key, value),
|
||||
}
|
||||
}
|
||||
|
||||
const user: PlatformManagedUser = {
|
||||
membershipId: '30', userId: '20', authUserId: '10', username: 'zhangwei', displayName: '张伟',
|
||||
phone: '13800138000', email: 'zhangwei@example.com', tenantId: '10001', tenantName: '华远贸易',
|
||||
memberType: 'EMPLOYEE', memberNo: 'MEMBER-30', status: 'ACTIVE', roleIds: ['40'],
|
||||
roleNames: ['租户管理员'], lastLoginAt: '2026-06-01T10:30:00',
|
||||
protectedAccount: false,
|
||||
}
|
||||
|
||||
async function mountView() {
|
||||
vi.stubGlobal('localStorage', createMemoryStorage())
|
||||
vi.stubGlobal('sessionStorage', createMemoryStorage())
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const auth = useAuthStore()
|
||||
auth.token = 'token'
|
||||
auth.permissions = [
|
||||
'platform:user:list', 'platform:user:create', 'platform:user:edit',
|
||||
'platform:user:status', 'platform:user:reset-password', 'platform:user:grant-role',
|
||||
]
|
||||
useAccessPreviewStore().initializeAfterLogin()
|
||||
const wrapper = mount(InternalUsersView, {
|
||||
attachTo: document.body,
|
||||
global: { plugins: [pinia, ElementPlus] },
|
||||
})
|
||||
await flushPromises()
|
||||
return wrapper
|
||||
}
|
||||
|
||||
enableAutoUnmount(afterEach)
|
||||
afterAll(() => vi.unstubAllGlobals())
|
||||
|
||||
describe('InternalUsersView unified platform user management', () => {
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('ResizeObserver', ResizeObserverStub)
|
||||
document.body.innerHTML = ''
|
||||
vi.mocked(listPlatformManagedUsers).mockReset().mockResolvedValue([user])
|
||||
vi.mocked(getPlatformUserOptions).mockReset().mockResolvedValue({
|
||||
tenants: [
|
||||
{ id: '0', name: '平台', status: 'ACTIVE' },
|
||||
{ id: '10001', name: '华远贸易', status: 'ACTIVE' },
|
||||
],
|
||||
roles: [{ id: '40', tenantId: '10001', name: '租户管理员', status: 'ACTIVE' }],
|
||||
})
|
||||
})
|
||||
|
||||
it('loads and renders prototype fields from the unified API', async () => {
|
||||
const wrapper = await mountView()
|
||||
|
||||
expect(listPlatformManagedUsers).toHaveBeenCalledOnce()
|
||||
expect(getPlatformUserOptions).toHaveBeenCalledOnce()
|
||||
expect(wrapper.text()).toContain('zhangwei')
|
||||
expect(wrapper.text()).toContain('张伟')
|
||||
expect(wrapper.text()).toContain('华远贸易')
|
||||
expect(wrapper.text()).toContain('租户管理员')
|
||||
expect(wrapper.text()).toContain('2026-06-01 10:30')
|
||||
expect(wrapper.text()).not.toContain('认证用户 ID')
|
||||
expect(wrapper.text()).not.toContain('成员编号')
|
||||
})
|
||||
|
||||
it('opens the complete prototype create form', async () => {
|
||||
const wrapper = await mountView()
|
||||
const createButton = wrapper.findAll('button').find((button) => button.text().trim() === '新增用户')
|
||||
await createButton?.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(document.querySelector('input[placeholder="登录用户名"]')).not.toBeNull()
|
||||
expect(document.querySelector('input[placeholder="真实姓名"]')).not.toBeNull()
|
||||
expect(document.querySelector('input[placeholder="手机号码"]')).not.toBeNull()
|
||||
expect(document.querySelector('input[placeholder="邮箱地址"]')).not.toBeNull()
|
||||
expect(document.body.textContent).toContain('所属租户')
|
||||
expect(document.body.textContent).toContain('初始密码')
|
||||
expect(document.body.textContent).toContain('确认添加')
|
||||
})
|
||||
|
||||
it('shows a recoverable API error without fake users', async () => {
|
||||
vi.mocked(listPlatformManagedUsers).mockRejectedValueOnce(new Error('Gateway unavailable'))
|
||||
const wrapper = await mountView()
|
||||
|
||||
expect(wrapper.text()).toContain('Gateway unavailable')
|
||||
expect(wrapper.text()).toContain('重新加载')
|
||||
expect(wrapper.text()).not.toContain('zhangwei')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,377 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onMounted, reactive, ref } from 'vue'
|
||||
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
|
||||
import { Pencil, Plus } from '@lucide/vue'
|
||||
import {
|
||||
changePlatformManagedUserStatus,
|
||||
createPlatformManagedUser,
|
||||
getPlatformUserOptions,
|
||||
listPlatformManagedUsers,
|
||||
resetPlatformManagedUserPassword,
|
||||
updatePlatformManagedUser,
|
||||
type PlatformManagedUser,
|
||||
type PlatformUserOptions,
|
||||
} from '@/modules/iam/api/platformIam'
|
||||
import { getApiErrorDetails, getApiErrorMessage, type ApiErrorDetails } from '@/shared/api/http'
|
||||
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
|
||||
import StatusBadge from '@/shared/components/StatusBadge.vue'
|
||||
import DataTable, { type DataTableColumn } from '@/shared/components/DataTable.vue'
|
||||
import { useUnsavedWorkRegistration } from '@/core/unsaved-work/useUnsavedWorkRegistration'
|
||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
||||
import { useAuthStore } from '@/core/auth/auth'
|
||||
|
||||
const access = useAccessPreviewStore()
|
||||
const auth = useAuthStore()
|
||||
const users = ref<PlatformManagedUser[]>([])
|
||||
const options = ref<PlatformUserOptions>({ tenants: [], roles: [] })
|
||||
const loading = ref(false)
|
||||
const saving = ref(false)
|
||||
const loadError = ref<ApiErrorDetails | null>(null)
|
||||
const editorOpen = ref(false)
|
||||
const formRef = ref<FormInstance>()
|
||||
const editingUser = ref<PlatformManagedUser | null>(null)
|
||||
const rowActionId = ref('')
|
||||
const page = ref(1)
|
||||
const pageSize = ref(10)
|
||||
const filters = reactive({ keyword: '', tenantId: '', status: '' })
|
||||
|
||||
const emptyForm = () => ({
|
||||
username: '',
|
||||
displayName: '',
|
||||
phone: '',
|
||||
email: '',
|
||||
tenantId: '' as string,
|
||||
roleIds: [] as string[],
|
||||
password: '',
|
||||
confirmPassword: '',
|
||||
status: 'ACTIVE' as 'ACTIVE' | 'DISABLED',
|
||||
resetPassword: false,
|
||||
})
|
||||
const form = reactive(emptyForm())
|
||||
|
||||
const canCreate = computed(() => access.can('platform:user:create') && access.can('platform:user:grant-role'))
|
||||
const canEdit = computed(() => access.can('platform:user:edit'))
|
||||
const canGrantRoles = computed(() => access.can('platform:user:grant-role'))
|
||||
const canChangeStatus = computed(() => access.can('platform:user:status'))
|
||||
const canResetPassword = computed(() => access.can('platform:user:reset-password'))
|
||||
const editorLabel = computed(() => editingUser.value ? `编辑用户 - ${editingUser.value.displayName}` : '新增用户')
|
||||
|
||||
useUnsavedWorkRegistration({
|
||||
key: 'platform-user-editor',
|
||||
label: editorLabel,
|
||||
isOpen: editorOpen,
|
||||
model: form,
|
||||
requiredPermission: computed(() => editingUser.value ? 'platform:user:edit' : 'platform:user:create'),
|
||||
})
|
||||
|
||||
const enabledTenants = computed(() => options.value.tenants.filter((tenant) =>
|
||||
tenant.status === 'ACTIVE' || String(tenant.id) === form.tenantId,
|
||||
))
|
||||
const availableRoles = computed(() => options.value.roles.filter((role) =>
|
||||
String(role.tenantId) === form.tenantId
|
||||
&& (role.status === 'ACTIVE' || form.roleIds.includes(String(role.id))),
|
||||
))
|
||||
|
||||
const formRules = computed<FormRules>(() => ({
|
||||
username: editingUser.value ? [] : [
|
||||
{ required: true, whitespace: true, message: '请输入用户名', trigger: 'blur' },
|
||||
{ pattern: /^[A-Za-z0-9_.@-]{4,64}$/, message: '用户名为 4-64 位字母、数字或 _ . @ -', trigger: 'blur' },
|
||||
],
|
||||
displayName: editingUser.value && !canEdit.value ? [] : [{ required: true, whitespace: true, message: '请输入姓名', trigger: 'blur' }],
|
||||
phone: editingUser.value && !canEdit.value ? [] : [
|
||||
{ required: true, message: '请输入手机号', trigger: 'blur' },
|
||||
{ pattern: /^1\d{10}$/, message: '请输入正确的 11 位手机号', trigger: 'blur' },
|
||||
],
|
||||
email: editingUser.value && !canEdit.value ? [] : [{ type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }],
|
||||
tenantId: editingUser.value && !canEdit.value ? [] : [{ required: true, message: '请选择所属租户', trigger: 'change' }],
|
||||
roleIds: editingUser.value && !canEdit.value ? [] : [{ type: 'array', required: true, min: 1, message: '请选择角色', trigger: 'change' }],
|
||||
password: editingUser.value && !form.resetPassword ? [] : [
|
||||
{ required: true, message: '请输入密码', trigger: 'blur' },
|
||||
{ pattern: /^(?=.*[A-Za-z])(?=.*\d).{8,64}$/, message: '密码为 8-64 位,且必须包含字母和数字', trigger: 'blur' },
|
||||
],
|
||||
confirmPassword: editingUser.value && !form.resetPassword ? [] : [
|
||||
{ required: true, message: '请再次输入密码', trigger: 'blur' },
|
||||
{ validator: (_rule, value, callback) => value === form.password ? callback() : callback(new Error('两次输入的密码不一致')), trigger: 'blur' },
|
||||
],
|
||||
}))
|
||||
|
||||
const filteredRows = computed(() => {
|
||||
const keyword = filters.keyword.trim().toLowerCase()
|
||||
return users.value.filter((item) => {
|
||||
const matchesKeyword = !keyword || [item.username, item.displayName, item.phone ?? '', item.email ?? '', item.tenantName, ...item.roleNames]
|
||||
.some((value) => value.toLowerCase().includes(keyword))
|
||||
return matchesKeyword
|
||||
&& (!filters.tenantId || String(item.tenantId) === filters.tenantId)
|
||||
&& (!filters.status || item.status === filters.status)
|
||||
})
|
||||
})
|
||||
const pagedRows = computed(() => filteredRows.value.slice((page.value - 1) * pageSize.value, page.value * pageSize.value))
|
||||
|
||||
const userColumns: DataTableColumn[] = [
|
||||
{ key: 'actions', label: '操作', width: 170, fixed: 'left', slotName: 'actions' },
|
||||
{ prop: 'username', label: '用户名', minWidth: 145 },
|
||||
{ prop: 'displayName', label: '姓名', minWidth: 130 },
|
||||
{ prop: 'tenantName', label: '所属租户', minWidth: 190 },
|
||||
{ key: 'roles', label: '角色', minWidth: 180, slotName: 'roles' },
|
||||
{ key: 'status', label: '状态', width: 100, slotName: 'status' },
|
||||
{ key: 'lastLoginAt', label: '最后登录', minWidth: 170, slotName: 'lastLoginAt' },
|
||||
]
|
||||
|
||||
async function loadUsers() {
|
||||
loading.value = true
|
||||
loadError.value = null
|
||||
try {
|
||||
const [userRecords, optionRecords] = await Promise.all([
|
||||
listPlatformManagedUsers(),
|
||||
getPlatformUserOptions(),
|
||||
])
|
||||
users.value = userRecords
|
||||
options.value = optionRecords
|
||||
} catch (error) {
|
||||
users.value = []
|
||||
loadError.value = getApiErrorDetails(error, '用户列表加载失败,请稍后重试')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function openCreate() {
|
||||
Object.assign(form, emptyForm())
|
||||
const defaultTenant = options.value.tenants.find((tenant) => tenant.status === 'ACTIVE')
|
||||
form.tenantId = defaultTenant ? String(defaultTenant.id) : ''
|
||||
editingUser.value = null
|
||||
editorOpen.value = true
|
||||
nextTick(() => formRef.value?.clearValidate())
|
||||
}
|
||||
|
||||
function openEdit(row: PlatformManagedUser) {
|
||||
editingUser.value = row
|
||||
Object.assign(form, {
|
||||
username: row.username,
|
||||
displayName: row.displayName,
|
||||
phone: row.phone ?? '',
|
||||
email: row.email ?? '',
|
||||
tenantId: String(row.tenantId),
|
||||
roleIds: row.roleIds.map(String),
|
||||
password: '',
|
||||
confirmPassword: '',
|
||||
status: row.status,
|
||||
resetPassword: false,
|
||||
})
|
||||
editorOpen.value = true
|
||||
nextTick(() => formRef.value?.clearValidate())
|
||||
}
|
||||
|
||||
function handleTenantChange() {
|
||||
const validRoleIds = new Set(availableRoles.value.map((role) => String(role.id)))
|
||||
form.roleIds = form.roleIds.filter((roleId) => validRoleIds.has(roleId))
|
||||
}
|
||||
|
||||
function isCurrentUser(row: PlatformManagedUser | null) {
|
||||
if (!row) return false
|
||||
return String(row.userId) === auth.user?.id || String(row.authUserId) === auth.user?.id
|
||||
}
|
||||
|
||||
function cannotDisable(row: PlatformManagedUser | null) {
|
||||
return Boolean(row?.protectedAccount) || isCurrentUser(row)
|
||||
}
|
||||
|
||||
async function saveUser() {
|
||||
const valid = await formRef.value?.validate().catch(() => false)
|
||||
if (!valid) return
|
||||
saving.value = true
|
||||
try {
|
||||
if (!editingUser.value) {
|
||||
await createPlatformManagedUser({
|
||||
username: form.username.trim(),
|
||||
displayName: form.displayName.trim(),
|
||||
phone: form.phone.trim(),
|
||||
email: form.email.trim(),
|
||||
tenantId: form.tenantId,
|
||||
roleIds: form.roleIds,
|
||||
password: form.password,
|
||||
status: form.status,
|
||||
})
|
||||
ElMessage.success('用户添加成功')
|
||||
} else {
|
||||
const row = editingUser.value
|
||||
if (canEdit.value) {
|
||||
await updatePlatformManagedUser(row.membershipId, {
|
||||
displayName: form.displayName.trim(),
|
||||
phone: form.phone.trim(),
|
||||
email: form.email.trim(),
|
||||
tenantId: form.tenantId,
|
||||
roleIds: form.roleIds,
|
||||
})
|
||||
}
|
||||
if (canChangeStatus.value && form.status !== row.status) {
|
||||
await changePlatformManagedUserStatus(row.membershipId, form.status)
|
||||
}
|
||||
if (canResetPassword.value && form.resetPassword) {
|
||||
await resetPlatformManagedUserPassword(row.membershipId, form.password)
|
||||
}
|
||||
ElMessage.success(form.resetPassword ? '用户信息已更新,密码已重置' : '用户信息已更新')
|
||||
}
|
||||
editorOpen.value = false
|
||||
await loadUsers()
|
||||
} catch (error) {
|
||||
ElMessage.error(getApiErrorMessage(error, editingUser.value ? '用户更新失败,请稍后重试' : '用户添加失败,请稍后重试'))
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleStatus(row: PlatformManagedUser) {
|
||||
const targetStatus = row.status === 'ACTIVE' ? 'DISABLED' : 'ACTIVE'
|
||||
const targetLabel = targetStatus === 'ACTIVE' ? '启用' : '禁用'
|
||||
try {
|
||||
await ElMessageBox.confirm(`确认${targetLabel}用户“${row.displayName}”吗?`, `${targetLabel}用户`, {
|
||||
confirmButtonText: `确认${targetLabel}`,
|
||||
cancelButtonText: '取消',
|
||||
type: targetStatus === 'DISABLED' ? 'warning' : 'info',
|
||||
})
|
||||
rowActionId.value = String(row.membershipId)
|
||||
const updated = await changePlatformManagedUserStatus(row.membershipId, targetStatus)
|
||||
Object.assign(row, updated)
|
||||
ElMessage.success(`用户已${targetLabel}`)
|
||||
} catch (error) {
|
||||
if (error === 'cancel' || error === 'close') return
|
||||
ElMessage.error(getApiErrorMessage(error, `用户${targetLabel}失败,请稍后重试`))
|
||||
} finally {
|
||||
rowActionId.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
function formatLogin(value: string | null) {
|
||||
if (!value) return '—'
|
||||
return value.replace('T', ' ').slice(0, 16)
|
||||
}
|
||||
|
||||
function resetFilters() {
|
||||
filters.keyword = ''
|
||||
filters.tenantId = ''
|
||||
filters.status = ''
|
||||
page.value = 1
|
||||
}
|
||||
|
||||
onMounted(loadUsers)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="business-page">
|
||||
<el-alert v-if="loadError" type="error" :closable="false" show-icon role="alert">
|
||||
<template #title>
|
||||
<div class="api-error-alert-title"><span>{{ loadError.message }}</span><ApiErrorMeta :details="loadError" /></div>
|
||||
<el-button link type="danger" @click="loadUsers">重新加载</el-button>
|
||||
</template>
|
||||
</el-alert>
|
||||
|
||||
<section class="surface-panel table-panel">
|
||||
<header class="panel-heading">
|
||||
<div><h2>用户管理 <span class="secondary-text">共 {{ filteredRows.length }} 条</span></h2></div>
|
||||
<el-button v-if="canCreate" type="primary" @click="openCreate"><Plus :size="16" />新增用户</el-button>
|
||||
</header>
|
||||
|
||||
<div class="query-toolbar">
|
||||
<el-input v-model="filters.keyword" clearable placeholder="用户名、姓名、手机号、租户或角色" @keyup.enter="page = 1" />
|
||||
<el-select v-model="filters.tenantId" clearable placeholder="全部租户" @change="page = 1">
|
||||
<el-option v-for="tenant in options.tenants" :key="tenant.id" :label="tenant.name" :value="String(tenant.id)" />
|
||||
</el-select>
|
||||
<el-select v-model="filters.status" clearable placeholder="全部状态" @change="page = 1">
|
||||
<el-option label="正常" value="ACTIVE" />
|
||||
<el-option label="禁用" value="DISABLED" />
|
||||
</el-select>
|
||||
<el-button @click="resetFilters">重置</el-button>
|
||||
</div>
|
||||
|
||||
<DataTable v-model:page="page" v-model:page-size="pageSize" :data="pagedRows" :columns="userColumns"
|
||||
:loading="loading" :total="filteredRows.length" row-key="membershipId" empty-text="暂无用户数据">
|
||||
<template #actions="{ row }">
|
||||
<div class="table-actions">
|
||||
<el-button v-if="canEdit || canChangeStatus || canResetPassword" link type="primary" @click="openEdit(row as PlatformManagedUser)">
|
||||
<Pencil :size="15" />编辑
|
||||
</el-button>
|
||||
<el-button v-if="canChangeStatus" link :type="(row as PlatformManagedUser).status === 'ACTIVE' ? 'danger' : 'success'"
|
||||
:loading="rowActionId === String((row as PlatformManagedUser).membershipId)"
|
||||
:disabled="cannotDisable(row as PlatformManagedUser)"
|
||||
:title="(row as PlatformManagedUser).protectedAccount ? '系统管理员不能被禁用' : isCurrentUser(row as PlatformManagedUser) ? '不能禁用当前登录用户' : undefined"
|
||||
@click="toggleStatus(row as PlatformManagedUser)">
|
||||
{{ (row as PlatformManagedUser).status === 'ACTIVE' ? '禁用' : '启用' }}
|
||||
</el-button>
|
||||
</div>
|
||||
</template>
|
||||
<template #roles="{ row }">
|
||||
<div class="tag-list">
|
||||
<el-tag v-for="role in (row as PlatformManagedUser).roleNames" :key="role" effect="plain" size="small">{{ role }}</el-tag>
|
||||
<span v-if="!(row as PlatformManagedUser).roleNames.length" class="secondary-text">未分配</span>
|
||||
</div>
|
||||
</template>
|
||||
<template #status="{ row }"><StatusBadge :status="(row as PlatformManagedUser).status === 'ACTIVE' ? '正常' : '禁用'" /></template>
|
||||
<template #lastLoginAt="{ row }">{{ formatLogin((row as PlatformManagedUser).lastLoginAt) }}</template>
|
||||
</DataTable>
|
||||
</section>
|
||||
|
||||
<el-dialog v-model="editorOpen" :title="editorLabel" width="min(760px, calc(100vw - 32px))" :close-on-click-modal="false" destroy-on-close>
|
||||
<el-form ref="formRef" :model="form" :rules="formRules" label-position="top">
|
||||
<div class="form-grid two-cols">
|
||||
<el-form-item label="用户名" prop="username" required>
|
||||
<el-input v-model="form.username" :disabled="Boolean(editingUser)" placeholder="登录用户名" maxlength="64" />
|
||||
</el-form-item>
|
||||
<el-form-item label="姓名" prop="displayName" required>
|
||||
<el-input v-model="form.displayName" :disabled="Boolean(editingUser) && !canEdit" placeholder="真实姓名" maxlength="64" />
|
||||
</el-form-item>
|
||||
<el-form-item label="手机号" prop="phone" required>
|
||||
<el-input v-model="form.phone" :disabled="Boolean(editingUser) && !canEdit" placeholder="手机号码" inputmode="tel" maxlength="11" />
|
||||
</el-form-item>
|
||||
<el-form-item label="邮箱" prop="email">
|
||||
<el-input v-model="form.email" :disabled="Boolean(editingUser) && !canEdit" placeholder="邮箱地址" inputmode="email" maxlength="128" />
|
||||
</el-form-item>
|
||||
<el-form-item label="所属租户" prop="tenantId" required>
|
||||
<el-select v-model="form.tenantId" :disabled="Boolean(editingUser) && (!canEdit || !canGrantRoles || editingUser?.protectedAccount)" placeholder="选择所属租户" @change="handleTenantChange">
|
||||
<el-option v-for="tenant in enabledTenants" :key="tenant.id" :label="tenant.name" :value="String(tenant.id)" :disabled="tenant.status !== 'ACTIVE'" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="角色" prop="roleIds" required>
|
||||
<el-select v-model="form.roleIds" multiple collapse-tags collapse-tags-tooltip
|
||||
:disabled="Boolean(editingUser) && (!canEdit || !canGrantRoles || editingUser?.protectedAccount)" placeholder="选择角色">
|
||||
<el-option v-for="role in availableRoles" :key="role.id" :label="role.name" :value="String(role.id)" :disabled="role.status !== 'ACTIVE'" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="状态" prop="status">
|
||||
<el-select v-model="form.status" :disabled="Boolean(editingUser) && (!canChangeStatus || cannotDisable(editingUser))">
|
||||
<el-option label="正常" value="ACTIVE" />
|
||||
<el-option label="禁用" value="DISABLED" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item v-if="editingUser" label="最后登录">
|
||||
<el-input :model-value="formatLogin(editingUser.lastLoginAt)" disabled />
|
||||
</el-form-item>
|
||||
</div>
|
||||
|
||||
<template v-if="!editingUser || canResetPassword">
|
||||
<el-checkbox v-if="editingUser" v-model="form.resetPassword">同时重置密码</el-checkbox>
|
||||
<div v-if="!editingUser || form.resetPassword" class="form-grid two-cols password-fields">
|
||||
<el-form-item :label="editingUser ? '新密码' : '初始密码'" prop="password" required>
|
||||
<el-input v-model="form.password" type="password" show-password autocomplete="new-password" placeholder="8-64 位,包含字母和数字" />
|
||||
</el-form-item>
|
||||
<el-form-item label="确认密码" prop="confirmPassword" required>
|
||||
<el-input v-model="form.confirmPassword" type="password" show-password autocomplete="new-password" placeholder="再次输入密码" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
</template>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button :disabled="saving" @click="editorOpen = false">取消</el-button>
|
||||
<el-button type="primary" :loading="saving" @click="saveUser">{{ editingUser ? '保存修改' : '确认添加' }}</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.query-toolbar { display: grid; grid-template-columns: minmax(240px, 1fr) 220px 160px auto; gap: 12px; padding: 0 20px 16px; }
|
||||
.password-fields { margin-top: 16px; }
|
||||
@media (max-width: 720px) {
|
||||
.query-toolbar, .form-grid.two-cols { grid-template-columns: 1fr; }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,83 @@
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import { flushPromises, shallowMount } from '@vue/test-utils'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { listPlatformPermissions, type PlatformPermissionResource } from '@/modules/iam/api/platformIam'
|
||||
import { useAuthStore } from '@/core/auth/auth'
|
||||
import PermissionsView from './PermissionsView.vue'
|
||||
|
||||
vi.mock('@/modules/iam/api/platformIam', () => ({
|
||||
changePlatformPermissionStatus: vi.fn(),
|
||||
createPlatformPermission: vi.fn(),
|
||||
deletePlatformPermission: vi.fn(),
|
||||
listPlatformPermissions: vi.fn(),
|
||||
updatePlatformPermission: vi.fn(),
|
||||
}))
|
||||
|
||||
const permission: PlatformPermissionResource = {
|
||||
id: 5100010,
|
||||
tenantId: 0,
|
||||
appCode: 'PLATFORM',
|
||||
permissionType: 'MENU',
|
||||
parentId: 5100000,
|
||||
permissionCode: 'platform:customer:list',
|
||||
permissionName: '企业客户',
|
||||
routePath: '/customers',
|
||||
httpMethod: null,
|
||||
sortNo: 10,
|
||||
status: 'ACTIVE',
|
||||
}
|
||||
|
||||
function mountServerView() {
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const auth = useAuthStore()
|
||||
auth.isServerSession = true
|
||||
auth.permissions = ['platform:permission:list', 'platform:permission:create']
|
||||
return shallowMount(PermissionsView, {
|
||||
global: {
|
||||
plugins: [pinia],
|
||||
directives: { loading: () => undefined },
|
||||
stubs: {
|
||||
'el-alert': { props: ['title'], template: '<div role="alert">{{ title }}<slot name="title" /></div>' },
|
||||
'el-input': true,
|
||||
'el-option': true,
|
||||
'el-select': true,
|
||||
'el-button': true,
|
||||
'el-table': true,
|
||||
'el-table-column': true,
|
||||
'el-input-number': true,
|
||||
'el-radio-group': true,
|
||||
'el-radio-button': true,
|
||||
'el-drawer': { template: '<section><slot /><slot name="footer" /></section>' },
|
||||
'el-form': { template: '<form><slot /></form>' },
|
||||
'el-form-item': { template: '<label><slot /></label>' },
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
describe('PermissionsView IAM mode', () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(listPlatformPermissions).mockReset()
|
||||
})
|
||||
|
||||
it('loads the platform permission resource tree from IAM', async () => {
|
||||
vi.mocked(listPlatformPermissions).mockResolvedValue([permission])
|
||||
|
||||
const wrapper = mountServerView()
|
||||
await flushPromises()
|
||||
|
||||
expect(listPlatformPermissions).toHaveBeenCalledTimes(1)
|
||||
expect(wrapper.text()).toContain('权限资源树')
|
||||
expect(wrapper.text()).toContain('共 1 项')
|
||||
})
|
||||
|
||||
it('shows a recoverable state when the permission list fails', async () => {
|
||||
vi.mocked(listPlatformPermissions).mockRejectedValue(new Error('IAM unavailable'))
|
||||
|
||||
const wrapper = mountServerView()
|
||||
await flushPromises()
|
||||
|
||||
expect(wrapper.findAll('[role="alert"]').map((item) => item.text()).join(' ')).toContain('IAM unavailable')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,285 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onMounted, reactive, ref } from 'vue'
|
||||
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
|
||||
import { Braces, FolderTree, Pencil, Plus, ShieldCheck, Trash2 } from '@lucide/vue'
|
||||
import StatusBadge from '@/shared/components/StatusBadge.vue'
|
||||
import DataTable, { type DataTableColumn } from '@/shared/components/DataTable.vue'
|
||||
import QueryToolbar, { type QueryField, type QueryModel } from '@/shared/components/QueryToolbar.vue'
|
||||
import {
|
||||
changePlatformPermissionStatus,
|
||||
createPlatformPermission,
|
||||
deletePlatformPermission,
|
||||
listPlatformPermissions,
|
||||
updatePlatformPermission,
|
||||
} from '@/modules/iam/api/platformIam'
|
||||
import { getApiErrorDetails, getApiErrorMessage, type ApiErrorDetails } from '@/shared/api/http'
|
||||
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
|
||||
import { useUnsavedWorkRegistration } from '@/core/unsaved-work/useUnsavedWorkRegistration'
|
||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
||||
import type { Permission, PermissionType } from '@/modules/iam/types'
|
||||
import { buildPermissionTree, getDescendantIds, type PermissionTreeNode } from '@/modules/iam/utils/permissionTree'
|
||||
import { mapPlatformPermission } from '@/modules/iam/utils/platformPermission'
|
||||
|
||||
const access = useAccessPreviewStore()
|
||||
const editorOpen = ref(false)
|
||||
const formRef = ref<FormInstance>()
|
||||
const serverPermissions = ref<Permission[]>([])
|
||||
const loading = ref(false)
|
||||
const saving = ref(false)
|
||||
const rowActionId = ref('')
|
||||
const loadError = ref<ApiErrorDetails | null>(null)
|
||||
const page = ref(1)
|
||||
const pageSize = ref(10)
|
||||
type PermissionFilters = QueryModel & { keyword: string; type: string; status: string }
|
||||
const filters = ref<PermissionFilters>({ keyword: '', type: '', status: '' })
|
||||
const appliedFilters = ref<PermissionFilters>({ ...filters.value })
|
||||
const queryFields: QueryField[] = [
|
||||
{ key: 'keyword', type: 'input', placeholder: '权限名称、编码或路径' },
|
||||
{ key: 'type', type: 'select', placeholder: '全部类型', options: [{ label: '菜单', value: '菜单' }, { label: '按钮', value: '按钮' }] },
|
||||
{ key: 'status', type: 'select', placeholder: '全部状态', options: [{ label: '启用', value: '启用' }, { label: '停用', value: '停用' }] },
|
||||
]
|
||||
const expandedRowKeys = ref<string[]>([])
|
||||
const tableRenderKey = ref(0)
|
||||
const emptyForm = (): Permission => ({ id: '', parentId: null, name: '', code: '', type: '菜单', path: '', method: '-', status: '启用', sort: 10 })
|
||||
const form = reactive(emptyForm())
|
||||
const formRules = computed<FormRules>(() => ({
|
||||
name: [{ required: true, whitespace: true, message: '请输入权限名称', trigger: 'blur' }],
|
||||
code: [{ required: true, whitespace: true, message: '请输入权限编码', trigger: 'blur' }],
|
||||
type: [{ required: true, message: '请选择资源类型', trigger: 'change' }],
|
||||
parentId: form.type === '按钮' ? [{ required: true, message: '请选择上级菜单', trigger: 'change' }] : [],
|
||||
path: form.type === '菜单' ? [{ required: true, whitespace: true, message: '请输入菜单路由', trigger: 'blur' }] : [],
|
||||
sort: [{ required: true, type: 'number', message: '请输入显示排序', trigger: 'change' }],
|
||||
}))
|
||||
const editorLabel = computed(() => form.id ? '编辑权限' : '新增权限')
|
||||
const requiredPermission = computed(() => form.id ? 'platform:permission:edit' : 'platform:permission:create')
|
||||
const { captureBaseline } = useUnsavedWorkRegistration({
|
||||
key: 'permission-editor',
|
||||
label: editorLabel,
|
||||
isOpen: editorOpen,
|
||||
model: form,
|
||||
requiredPermission,
|
||||
})
|
||||
const availablePermissionTypes: PermissionType[] = ['菜单', '按钮']
|
||||
const permissions = computed(() => serverPermissions.value)
|
||||
const canCreate = computed(() => access.can('platform:permission:create'))
|
||||
const canEdit = computed(() => access.can('platform:permission:edit'))
|
||||
const canChangeStatus = computed(() => access.can('platform:permission:status'))
|
||||
const canDelete = computed(() => access.can('platform:permission:delete'))
|
||||
|
||||
function matches(item: Permission) {
|
||||
const keyword = appliedFilters.value.keyword.trim().toLowerCase()
|
||||
return (!keyword || [item.name, item.code, item.path].some((value) => value.toLowerCase().includes(keyword))) && (!appliedFilters.value.type || item.type === appliedFilters.value.type) && (!appliedFilters.value.status || item.status === appliedFilters.value.status)
|
||||
}
|
||||
const treeRows = computed(() => buildPermissionTree(permissions.value, matches))
|
||||
const pagedTreeRows = computed(() => treeRows.value.slice((page.value - 1) * pageSize.value, page.value * pageSize.value))
|
||||
const rootRowKeys = computed(() => treeRows.value.map((item) => item.id))
|
||||
const blockedParentIds = computed(() => new Set(
|
||||
form.id ? [form.id, ...getDescendantIds(permissions.value, form.id)] : [],
|
||||
))
|
||||
const parentOptions = computed(() => permissions.value.filter((item) => (
|
||||
item.type === '菜单' && !blockedParentIds.value.has(item.id)
|
||||
)))
|
||||
const permissionColumns: DataTableColumn[] = [
|
||||
{ key: 'actions', label: '操作', width: 280, fixed: 'left', slotName: 'actions' },
|
||||
{ key: 'name', label: '权限名称', minWidth: 260, slotName: 'name' },
|
||||
{ key: 'code', label: '权限编码', minWidth: 220, slotName: 'code' },
|
||||
{ prop: 'type', label: '类型', width: 80 },
|
||||
{ key: 'endpoint', label: '路由 / 接口', minWidth: 260, slotName: 'endpoint' },
|
||||
{ prop: 'sort', label: '排序', width: 72, align: 'right' },
|
||||
{ key: 'status', label: '状态', width: 88, slotName: 'status' },
|
||||
]
|
||||
|
||||
async function loadPermissions() {
|
||||
loading.value = true
|
||||
loadError.value = null
|
||||
serverPermissions.value = []
|
||||
try {
|
||||
serverPermissions.value = (await listPlatformPermissions()).map(mapPlatformPermission)
|
||||
expandedRowKeys.value = rootRowKeys.value
|
||||
tableRenderKey.value += 1
|
||||
} catch (error) {
|
||||
loadError.value = getApiErrorDetails(error, '权限资源加载失败,请稍后重试')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function applyFilters() {
|
||||
appliedFilters.value = { ...filters.value }
|
||||
page.value = 1
|
||||
void loadPermissions()
|
||||
}
|
||||
|
||||
function collectDescendantIds(nodes: PermissionTreeNode[], ids: string[] = []) {
|
||||
nodes.forEach((node) => {
|
||||
ids.push(node.id)
|
||||
if (node.children) collectDescendantIds(node.children, ids)
|
||||
})
|
||||
return ids
|
||||
}
|
||||
|
||||
function permissionSummary(row: PermissionTreeNode) {
|
||||
const descendants = collectDescendantIds(row.children ?? [])
|
||||
.map((id) => permissions.value.find((item) => item.id === id))
|
||||
.filter((item): item is Permission => Boolean(item))
|
||||
const menuCount = descendants.filter((item) => item.type === '菜单').length
|
||||
const actionCount = descendants.filter((item) => ['按钮', '接口'].includes(item.type)).length
|
||||
if (menuCount === 0 && actionCount === 0) return '无下级权限'
|
||||
return [menuCount ? `${menuCount} 个菜单` : '', actionCount ? `${actionCount} 项操作` : ''].filter(Boolean).join(' · ')
|
||||
}
|
||||
|
||||
function expandAllRows() {
|
||||
expandedRowKeys.value = collectDescendantIds(treeRows.value)
|
||||
tableRenderKey.value += 1
|
||||
}
|
||||
|
||||
function collapseActionRows() {
|
||||
expandedRowKeys.value = rootRowKeys.value
|
||||
tableRenderKey.value += 1
|
||||
}
|
||||
|
||||
function openCreate(parentId: string | null = null) {
|
||||
Object.assign(form, emptyForm(), { parentId })
|
||||
captureBaseline()
|
||||
editorOpen.value = true
|
||||
nextTick(() => formRef.value?.clearValidate())
|
||||
}
|
||||
function openEdit(row: Permission) {
|
||||
if (!canEdit.value || row.builtIn) return
|
||||
Object.assign(form, { ...row })
|
||||
captureBaseline()
|
||||
editorOpen.value = true
|
||||
nextTick(() => formRef.value?.clearValidate())
|
||||
}
|
||||
function handleTypeChange() {
|
||||
if (form.type === '按钮') form.path = ''
|
||||
nextTick(() => formRef.value?.clearValidate(['parentId', 'path']))
|
||||
}
|
||||
async function savePermission() {
|
||||
const valid = await formRef.value?.validate().catch(() => false)
|
||||
if (!valid) return
|
||||
if (permissions.value.some((item) => item.code.toLowerCase() === form.code.toLowerCase() && item.id !== form.id)) { ElMessage.error('权限编码已经存在'); return }
|
||||
saving.value = true
|
||||
try {
|
||||
if (form.id) {
|
||||
const updated = await updatePlatformPermission(form.id, {
|
||||
name: form.name.trim(),
|
||||
parentId: form.parentId,
|
||||
routePath: form.type === '菜单' ? form.path.trim() : null,
|
||||
httpMethod: form.method === '-' ? null : form.method,
|
||||
sortNo: form.sort,
|
||||
})
|
||||
const index = serverPermissions.value.findIndex((item) => item.id === form.id)
|
||||
if (index >= 0) serverPermissions.value[index] = mapPlatformPermission(updated)
|
||||
ElMessage.success('权限资源已更新')
|
||||
} else {
|
||||
const created = await createPlatformPermission({
|
||||
type: form.type === '按钮' ? 'BUTTON' : 'MENU',
|
||||
code: form.code.trim(),
|
||||
name: form.name.trim(),
|
||||
parentId: form.parentId || '0',
|
||||
routePath: form.type === '菜单' ? form.path.trim() : null,
|
||||
httpMethod: null,
|
||||
sortNo: form.sort,
|
||||
})
|
||||
serverPermissions.value.push(mapPlatformPermission(created))
|
||||
ElMessage.success('权限资源已创建')
|
||||
}
|
||||
editorOpen.value = false
|
||||
} catch (error) {
|
||||
ElMessage.error(getApiErrorMessage(error, form.id ? '权限资源更新失败,请稍后重试' : '权限资源创建失败,请稍后重试'))
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
async function toggleStatus(row: Permission) {
|
||||
if (row.builtIn) return
|
||||
const target = row.status === '启用' ? '停用' : '启用'
|
||||
try {
|
||||
await ElMessageBox.confirm(`确认${target}权限“${row.name}”吗?`, '权限状态', { confirmButtonText: '确认', cancelButtonText: '取消' })
|
||||
rowActionId.value = row.id
|
||||
const updated = await changePlatformPermissionStatus(row.id, target === '启用' ? 'ACTIVE' : 'DISABLED')
|
||||
Object.assign(row, mapPlatformPermission(updated))
|
||||
ElMessage.success(`权限已${target}`)
|
||||
} catch (error) {
|
||||
if (error === 'cancel' || error === 'close') return
|
||||
ElMessage.error(getApiErrorMessage(error, '权限状态更新失败,请稍后重试'))
|
||||
} finally {
|
||||
rowActionId.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
async function removePermission(row: Permission) {
|
||||
if (row.builtIn) return
|
||||
try {
|
||||
await ElMessageBox.confirm(`确认删除权限“${row.name}”吗?删除前需确保没有下级资源且未分配给角色。`, '删除权限', { confirmButtonText: '删除', cancelButtonText: '取消', type: 'warning' })
|
||||
rowActionId.value = row.id
|
||||
await deletePlatformPermission(row.id)
|
||||
await loadPermissions()
|
||||
ElMessage.success('权限资源已删除')
|
||||
} catch (error) {
|
||||
if (error === 'cancel' || error === 'close') return
|
||||
ElMessage.error(getApiErrorMessage(error, '权限资源删除失败,请稍后重试'))
|
||||
} finally {
|
||||
rowActionId.value = ''
|
||||
}
|
||||
}
|
||||
function typeClass(type: PermissionType) { return { '目录': 'directory', '菜单': 'menu', '按钮': 'action', '接口': 'api' }[type] }
|
||||
|
||||
onMounted(loadPermissions)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="business-page">
|
||||
<el-alert v-if="loadError" type="error" :closable="false" show-icon role="alert"><template #title><div class="api-error-alert-title"><span>{{ loadError.message }}</span><ApiErrorMeta :details="loadError" /></div><el-button link type="danger" @click="loadPermissions">重新加载</el-button></template></el-alert>
|
||||
<QueryToolbar v-model="filters" class="surface-panel" ariaLabel="权限筛选" :fields="queryFields" @search="applyFilters" />
|
||||
|
||||
<section class="surface-panel table-panel">
|
||||
<header class="panel-heading"><div><h2>权限资源树 <span class="secondary-text">共 {{ permissions.length }} 项</span></h2><p>默认展示目录与菜单,展开菜单后查看按钮权限;接口权限将在服务端契约确定后补充。</p></div><div class="permission-tree-heading-actions"><div class="permission-tree-tools"><div class="legend-list"><span><i class="is-menu" />目录 / 菜单</span><span><i class="is-action" />操作</span><span><i class="is-api" />接口预留</span></div><div class="tree-view-actions"><el-button link type="primary" @click="expandAllRows">展开全部</el-button><el-button link @click="collapseActionRows">收起操作权限</el-button></div></div><el-button v-if="canCreate" type="primary" @click="openCreate(null)"><Plus :size="16" />新增权限</el-button></div></header>
|
||||
<DataTable :key="tableRenderKey" v-model:page="page" v-model:page-size="pageSize" :data="pagedTreeRows" :columns="permissionColumns" :loading="loading" :total="treeRows.length" row-key="id" :expand-row-keys="expandedRowKeys" :tree-props="{ children: 'children' }" empty-text="没有符合条件的权限资源">
|
||||
<template #actions="{ row }"><div v-if="canCreate || canEdit || canChangeStatus || canDelete" class="table-actions"><el-button v-if="canCreate && (row as Permission).type === '菜单'" link type="primary" @click="openCreate((row as Permission).id)"><Plus :size="15" />添加下级</el-button><el-button v-if="canEdit" link type="primary" :disabled="(row as Permission).builtIn || rowActionId === (row as Permission).id" @click="openEdit(row as Permission)"><Pencil :size="15" />编辑</el-button><el-button v-if="canChangeStatus" link :type="(row as Permission).status === '启用' ? 'danger' : 'success'" :loading="rowActionId === (row as Permission).id" :disabled="(row as Permission).builtIn" @click="toggleStatus(row as Permission)">{{ (row as Permission).status === '启用' ? '停用' : '启用' }}</el-button><el-button v-if="canDelete" link type="danger" :disabled="(row as Permission).builtIn || rowActionId === (row as Permission).id" @click="removePermission(row as Permission)"><Trash2 :size="15" />删除</el-button><span v-if="(row as Permission).builtIn" class="secondary-text">系统内置</span></div><span v-else class="secondary-text">仅查看</span></template>
|
||||
<template #name="{ row }"><div class="permission-name"><span :class="`is-${typeClass((row as Permission).type)}`"><FolderTree v-if="(row as Permission).type === '目录' || (row as Permission).type === '菜单'" :size="16" /><ShieldCheck v-else-if="(row as Permission).type === '按钮'" :size="16" /><Braces v-else :size="16" /></span><div><strong>{{ (row as Permission).name }}</strong><small v-if="(row as PermissionTreeNode).children?.length">{{ permissionSummary(row as PermissionTreeNode) }}</small></div></div></template>
|
||||
<template #code="{ row }"><code class="code-value">{{ (row as Permission).code }}</code></template>
|
||||
<template #endpoint="{ row }"><div class="endpoint-cell"><span v-if="(row as Permission).method !== '-'">{{ (row as Permission).method }}</span><code>{{ (row as Permission).path || '-' }}</code></div></template>
|
||||
<template #status="{ row }"><StatusBadge :status="(row as Permission).status" /></template>
|
||||
</DataTable>
|
||||
</section>
|
||||
|
||||
<el-drawer v-model="editorOpen" :title="form.id ? '编辑权限资源' : '新增权限资源'" size="600px" class="business-drawer editor-drawer" :modal="false" :close-on-click-modal="false">
|
||||
<el-form ref="formRef" :model="form" :rules="formRules" label-position="top" class="drawer-form">
|
||||
<div class="form-section">
|
||||
<h3>资源定义</h3>
|
||||
<div class="form-grid two-cols">
|
||||
<el-form-item label="权限名称" prop="name" required><el-input v-model="form.name" placeholder="用户可理解的中文名称" maxlength="64" /></el-form-item>
|
||||
<el-form-item label="权限编码" prop="code" required><el-input v-model="form.code" :disabled="Boolean(form.id)" placeholder="如:platform:customer:list" maxlength="128" /></el-form-item>
|
||||
<el-form-item label="资源类型" prop="type" required><el-select v-model="form.type" :disabled="Boolean(form.id)" @change="handleTypeChange"><el-option v-for="item in availablePermissionTypes" :key="item" :label="item" :value="item" /></el-select></el-form-item>
|
||||
<el-form-item label="上级资源" prop="parentId" :required="form.type === '按钮'"><el-select v-model="form.parentId" clearable placeholder="作为一级资源"><el-option v-for="item in parentOptions" :key="item.id" :label="`${item.name} (${item.code})`" :value="item.id" /></el-select></el-form-item>
|
||||
<el-form-item v-if="form.type === '菜单'" label="路由路径" prop="path" required><el-input v-model="form.path" placeholder="如:/customers" /></el-form-item>
|
||||
<el-form-item label="显示排序" prop="sort" required><el-input-number v-model="form.sort" :min="0" :max="999" controls-position="right" /></el-form-item>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-callout"><Braces :size="18" /><div><strong>权限编码约定</strong><p>使用稳定的“业务域:资源:动作”编码;一期真实资源只创建菜单和按钮,接口鉴权由服务端实现。</p></div></div>
|
||||
</el-form>
|
||||
<template #footer><div class="drawer-footer"><el-button :disabled="saving" @click="editorOpen = false">取消</el-button><el-button v-if="form.id ? canEdit : canCreate" type="primary" :loading="saving" @click="savePermission">{{ form.id ? '保存修改' : '保存权限' }}</el-button></div></template>
|
||||
</el-drawer>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.permission-tree-tools { display: flex; align-items: center; gap: 16px; }
|
||||
.permission-tree-heading-actions { display: flex; align-items: center; gap: 12px; }
|
||||
.tree-view-actions { display: flex; align-items: center; gap: 4px; white-space: nowrap; }
|
||||
.tree-view-actions .el-button + .el-button { margin-left: 0; }
|
||||
.permission-name > div { display: flex; min-width: 0; flex-direction: column; gap: 2px; }
|
||||
.permission-name small { color: var(--cc-muted); font-size: 11px; line-height: 1.35; }
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.permission-tree-heading-actions { width: 100%; align-items: flex-start; flex-direction: column; gap: 8px; }
|
||||
.permission-tree-tools { width: 100%; align-items: flex-start; flex-direction: column; gap: 8px; }
|
||||
.permission-tree-heading-actions > .el-button { min-height: 40px; }
|
||||
}
|
||||
|
||||
@media (max-width: 420px) {
|
||||
.tree-view-actions { width: 100%; justify-content: flex-start; }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,111 @@
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import { flushPromises, shallowMount } from '@vue/test-utils'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createPlatformRole, listPlatformInternalUsers, listPlatformPermissions, listPlatformRoles, type PlatformRoleResource } from '@/modules/iam/api/platformIam'
|
||||
import { useAuthStore } from '@/core/auth/auth'
|
||||
import RolesView from './RolesView.vue'
|
||||
|
||||
vi.mock('@/modules/iam/api/platformIam', () => ({
|
||||
createPlatformRole: vi.fn(),
|
||||
listPlatformInternalUsers: vi.fn(),
|
||||
listPlatformPermissions: vi.fn(),
|
||||
listPlatformRoles: vi.fn(),
|
||||
updatePlatformRole: vi.fn(),
|
||||
changePlatformRoleStatus: vi.fn(),
|
||||
deletePlatformRole: vi.fn(),
|
||||
replacePlatformRolePermissions: vi.fn(),
|
||||
}))
|
||||
|
||||
const platformRole: PlatformRoleResource = {
|
||||
id: 4000002,
|
||||
tenantId: 0,
|
||||
appCode: 'PLATFORM',
|
||||
roleCode: 'CUSTOMER_REVIEWER',
|
||||
roleName: '企业审核员',
|
||||
roleType: 'SYSTEM',
|
||||
status: 'ACTIVE',
|
||||
description: '企业资料与入驻审核',
|
||||
}
|
||||
|
||||
function mountView(pinia = createPinia()) {
|
||||
setActivePinia(pinia)
|
||||
const auth = useAuthStore()
|
||||
if (auth.permissions.length === 0) auth.permissions = ['platform:role:list', 'platform:role:create', 'platform:role:grant']
|
||||
return shallowMount(RolesView, {
|
||||
global: {
|
||||
plugins: [pinia],
|
||||
directives: { loading: () => undefined },
|
||||
stubs: {
|
||||
'el-alert': { props: ['title'], template: '<div role="alert">{{ title }}<slot name="title" /></div>' },
|
||||
'el-input': true,
|
||||
'el-option': true,
|
||||
'el-select': true,
|
||||
'el-button': true,
|
||||
'el-table': true,
|
||||
'el-table-column': true,
|
||||
'el-tag': true,
|
||||
'el-radio-group': true,
|
||||
'el-radio-button': true,
|
||||
'el-drawer': {
|
||||
props: ['modelValue'],
|
||||
template: '<section><slot /><slot name="footer" /></section>',
|
||||
},
|
||||
'el-form': { template: '<form><slot /></form>' },
|
||||
'el-form-item': { template: '<label><slot /></label>' },
|
||||
'el-tree': {
|
||||
props: { checkStrictly: Boolean },
|
||||
template: '<div data-testid="permission-tree" :data-check-strictly="String(checkStrictly)" />',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
describe('RolesView', () => {
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia())
|
||||
vi.mocked(listPlatformRoles).mockReset()
|
||||
vi.mocked(listPlatformPermissions).mockReset()
|
||||
vi.mocked(listPlatformInternalUsers).mockReset()
|
||||
vi.mocked(listPlatformPermissions).mockResolvedValue([])
|
||||
vi.mocked(listPlatformInternalUsers).mockResolvedValue([])
|
||||
vi.mocked(createPlatformRole).mockReset()
|
||||
})
|
||||
|
||||
it('keeps directory, menu, and action permissions independently checkable', () => {
|
||||
const wrapper = mountView()
|
||||
|
||||
expect(wrapper.get('[data-testid="permission-tree"]').attributes('data-check-strictly')).toBe('true')
|
||||
})
|
||||
|
||||
it('loads platform roles from IAM for a server session', async () => {
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const auth = useAuthStore()
|
||||
auth.isServerSession = true
|
||||
auth.permissions = ['platform:role:list', 'platform:role:create']
|
||||
vi.mocked(listPlatformRoles).mockResolvedValue([platformRole])
|
||||
|
||||
const wrapper = mountView(pinia)
|
||||
await flushPromises()
|
||||
|
||||
expect(listPlatformRoles).toHaveBeenCalledTimes(1)
|
||||
expect(listPlatformInternalUsers).toHaveBeenCalledTimes(1)
|
||||
expect(wrapper.text()).toContain('角色负责聚合菜单、操作和数据范围,内部用户可分配多个角色')
|
||||
expect(wrapper.find('[data-testid="permission-tree"]').exists()).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps a failed IAM role list recoverable', async () => {
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const auth = useAuthStore()
|
||||
auth.isServerSession = true
|
||||
auth.permissions = ['platform:role:list']
|
||||
vi.mocked(listPlatformRoles).mockRejectedValue(new Error('IAM unavailable'))
|
||||
|
||||
const wrapper = mountView(pinia)
|
||||
await flushPromises()
|
||||
|
||||
expect(wrapper.findAll('[role="alert"]').map((item) => item.text()).join(' ')).toContain('IAM unavailable')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,257 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onMounted, reactive, ref } from 'vue'
|
||||
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
|
||||
import { Pencil, Plus, ShieldCheck, Trash2 } from '@lucide/vue'
|
||||
import {
|
||||
changePlatformRoleStatus,
|
||||
createPlatformRole,
|
||||
deletePlatformRole,
|
||||
listPlatformInternalUsers,
|
||||
listPlatformPermissions,
|
||||
listPlatformRoles,
|
||||
replacePlatformRolePermissions,
|
||||
updatePlatformRole,
|
||||
type PlatformRoleResource,
|
||||
} from '@/modules/iam/api/platformIam'
|
||||
import { getApiErrorDetails, getApiErrorMessage, type ApiErrorDetails } from '@/shared/api/http'
|
||||
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
|
||||
import StatusBadge from '@/shared/components/StatusBadge.vue'
|
||||
import DataTable, { type DataTableColumn } from '@/shared/components/DataTable.vue'
|
||||
import QueryToolbar, { type QueryField, type QueryModel } from '@/shared/components/QueryToolbar.vue'
|
||||
import { useUnsavedWorkRegistration } from '@/core/unsaved-work/useUnsavedWorkRegistration'
|
||||
import { useAccessPreviewStore } from '@/core/access/accessPreview'
|
||||
import type { Permission, Role } from '@/modules/iam/types'
|
||||
import { buildPermissionTree, summarizePermissionSelection } from '@/modules/iam/utils/permissionTree'
|
||||
import { mapPlatformPermission } from '@/modules/iam/utils/platformPermission'
|
||||
|
||||
interface TreeController {
|
||||
getCheckedKeys: (leafOnly?: boolean) => Array<string | number>
|
||||
getHalfCheckedKeys: () => Array<string | number>
|
||||
setCheckedKeys: (keys: string[]) => void
|
||||
}
|
||||
|
||||
const access = useAccessPreviewStore()
|
||||
const editorOpen = ref(false)
|
||||
const formRef = ref<FormInstance>()
|
||||
const treeRef = ref<TreeController | null>(null)
|
||||
const serverRoles = ref<Role[]>([])
|
||||
const serverPermissions = ref<Permission[]>([])
|
||||
const loading = ref(false)
|
||||
const saving = ref(false)
|
||||
const rowActionId = ref('')
|
||||
const loadError = ref<ApiErrorDetails | null>(null)
|
||||
const page = ref(1)
|
||||
const pageSize = ref(10)
|
||||
type RoleFilters = QueryModel & { keyword: string; status: string }
|
||||
const filters = ref<RoleFilters>({ keyword: '', status: '' })
|
||||
const appliedFilters = ref<RoleFilters>({ ...filters.value })
|
||||
const queryFields: QueryField[] = [
|
||||
{ key: 'keyword', type: 'input', placeholder: '角色名称、编码或描述' },
|
||||
{ key: 'status', type: 'select', placeholder: '全部状态', options: [{ label: '启用', value: '启用' }, { label: '停用', value: '停用' }] },
|
||||
]
|
||||
const emptyForm = (): Omit<Role, 'userCount'> => ({ id: '', name: '', code: '', description: '', dataScope: '本部门数据', status: '启用', permissionIds: [], builtIn: false })
|
||||
const form = reactive(emptyForm())
|
||||
const formRules: FormRules = {
|
||||
name: [{ required: true, whitespace: true, message: '请输入角色名称', trigger: 'blur' }],
|
||||
code: [{ required: true, whitespace: true, message: '请输入角色编码', trigger: 'blur' }],
|
||||
}
|
||||
const editorLabel = computed(() => form.id ? '配置角色' : '新增角色')
|
||||
const canEdit = computed(() => access.can('platform:role:edit'))
|
||||
const canGrant = computed(() => access.can('platform:role:grant'))
|
||||
const requiredPermission = computed(() => form.id && canEdit.value ? 'platform:role:edit' : form.id ? 'platform:role:grant' : 'platform:role:create')
|
||||
const { captureBaseline } = useUnsavedWorkRegistration({
|
||||
key: 'role-editor',
|
||||
label: editorLabel,
|
||||
isOpen: editorOpen,
|
||||
model: form,
|
||||
requiredPermission,
|
||||
})
|
||||
const roles = computed(() => serverRoles.value)
|
||||
const canCreate = computed(() => access.can('platform:role:create'))
|
||||
const filteredRows = computed(() => roles.value.filter((item) => {
|
||||
const keyword = appliedFilters.value.keyword.trim().toLowerCase()
|
||||
return (!keyword || [item.name, item.code, item.description].some((value) => value.toLowerCase().includes(keyword))) && (!appliedFilters.value.status || item.status === appliedFilters.value.status)
|
||||
}))
|
||||
const pagedRows = computed(() => filteredRows.value.slice((page.value - 1) * pageSize.value, page.value * pageSize.value))
|
||||
const roleColumns: DataTableColumn[] = [
|
||||
{ key: 'actions', label: '操作', width: 235, fixed: 'left', slotName: 'actions' },
|
||||
{ key: 'role', label: '角色', minWidth: 210, slotName: 'role' },
|
||||
{ prop: 'description', label: '说明', minWidth: 240, showOverflowTooltip: true },
|
||||
{ key: 'permissionSummary', label: '授权范围', minWidth: 170, slotName: 'permissionSummary' },
|
||||
{ prop: 'userCount', label: '用户数', width: 86, align: 'right' },
|
||||
{ key: 'roleType', label: '类型', width: 95, slotName: 'roleType' },
|
||||
{ key: 'status', label: '状态', width: 88, slotName: 'status' },
|
||||
]
|
||||
const availablePermissions = computed(() => serverPermissions.value)
|
||||
const permissionTree = computed(() => buildPermissionTree(availablePermissions.value))
|
||||
|
||||
function applyFilters() {
|
||||
appliedFilters.value = { ...filters.value }
|
||||
page.value = 1
|
||||
void loadRoles()
|
||||
}
|
||||
|
||||
function mapPlatformRole(role: PlatformRoleResource, userCount = 0): Role {
|
||||
return {
|
||||
id: String(role.id),
|
||||
name: role.roleName,
|
||||
code: role.roleCode,
|
||||
description: role.description ?? '暂无角色说明',
|
||||
userCount,
|
||||
dataScope: '全部数据',
|
||||
status: role.status === 'ACTIVE' ? '启用' : '停用',
|
||||
permissionIds: (role.permissionIds ?? []).map(String),
|
||||
builtIn: role.roleType === 'SYSTEM',
|
||||
}
|
||||
}
|
||||
|
||||
async function loadRoles() {
|
||||
loading.value = true
|
||||
loadError.value = null
|
||||
serverRoles.value = []
|
||||
serverPermissions.value = []
|
||||
try {
|
||||
const [roleRecords, permissionRecords, memberRecords] = await Promise.all([
|
||||
listPlatformRoles(),
|
||||
listPlatformPermissions(),
|
||||
listPlatformInternalUsers(),
|
||||
])
|
||||
const roleMemberCounts = new Map<string, number>()
|
||||
for (const member of memberRecords) {
|
||||
for (const roleId of member.roleIds) {
|
||||
const key = String(roleId)
|
||||
roleMemberCounts.set(key, (roleMemberCounts.get(key) ?? 0) + 1)
|
||||
}
|
||||
}
|
||||
serverPermissions.value = permissionRecords.map(mapPlatformPermission)
|
||||
serverRoles.value = roleRecords.map((role) => mapPlatformRole(role, roleMemberCounts.get(String(role.id)) ?? 0))
|
||||
} catch (error) {
|
||||
loadError.value = getApiErrorDetails(error, '平台角色列表加载失败,请稍后重试')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function openCreate() {
|
||||
Object.assign(form, emptyForm())
|
||||
captureBaseline()
|
||||
editorOpen.value = true
|
||||
nextTick(() => { formRef.value?.clearValidate(); treeRef.value?.setCheckedKeys([]) })
|
||||
}
|
||||
function openEdit(row: Role) {
|
||||
if (!canEdit.value && !canGrant.value) return
|
||||
Object.assign(form, { ...row, permissionIds: [...row.permissionIds] })
|
||||
captureBaseline()
|
||||
editorOpen.value = true
|
||||
nextTick(() => { formRef.value?.clearValidate(); treeRef.value?.setCheckedKeys([...row.permissionIds]) })
|
||||
}
|
||||
|
||||
function selectedPermissionIds() {
|
||||
const checked = treeRef.value?.getCheckedKeys(false).map(String) || []
|
||||
const halfChecked = treeRef.value?.getHalfCheckedKeys().map(String) || []
|
||||
return [...new Set([...checked, ...halfChecked])]
|
||||
}
|
||||
|
||||
function syncPermissionIds() {
|
||||
form.permissionIds = selectedPermissionIds()
|
||||
}
|
||||
|
||||
async function saveRole() {
|
||||
const valid = await formRef.value?.validate().catch(() => false)
|
||||
if (!valid) return
|
||||
const normalizedCode = form.code.trim().toUpperCase()
|
||||
const duplicate = roles.value.some((item) => item.code.toLowerCase() === normalizedCode.toLowerCase() && item.id !== form.id)
|
||||
if (duplicate) { ElMessage.error('角色编码已经存在'); return }
|
||||
saving.value = true
|
||||
try {
|
||||
const permissionIds = selectedPermissionIds()
|
||||
if (form.id) {
|
||||
if (canEdit.value) {
|
||||
await updatePlatformRole(form.id, { roleName: form.name.trim(), description: form.description.trim() })
|
||||
}
|
||||
if (canGrant.value) await replacePlatformRolePermissions(form.id, permissionIds)
|
||||
} else {
|
||||
const created = await createPlatformRole({
|
||||
roleCode: normalizedCode,
|
||||
roleName: form.name.trim(),
|
||||
description: form.description.trim(),
|
||||
})
|
||||
if (canGrant.value && permissionIds.length > 0) await replacePlatformRolePermissions(created.id, permissionIds)
|
||||
}
|
||||
await loadRoles()
|
||||
editorOpen.value = false
|
||||
ElMessage.success(form.id ? '角色已更新' : '角色已创建')
|
||||
} catch (error) {
|
||||
ElMessage.error(getApiErrorMessage(error, '角色保存失败,请稍后重试'))
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function removeRole(row: Role) {
|
||||
if (row.builtIn) { ElMessage.warning('系统内置角色不能删除'); return }
|
||||
if (row.userCount > 0) { ElMessage.warning('请先移除该角色下的用户'); return }
|
||||
try {
|
||||
await ElMessageBox.confirm(`确认删除角色“${row.name}”吗?`, '删除角色', { confirmButtonText: '删除', cancelButtonText: '取消', type: 'warning' })
|
||||
rowActionId.value = row.id
|
||||
await deletePlatformRole(row.id)
|
||||
serverRoles.value = serverRoles.value.filter((item) => item.id !== row.id)
|
||||
ElMessage.success('角色已删除')
|
||||
} catch (error) {
|
||||
if (error === 'cancel' || error === 'close') return
|
||||
ElMessage.error(getApiErrorMessage(error, '角色删除失败,请稍后重试'))
|
||||
} finally {
|
||||
rowActionId.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleStatus(row: Role) {
|
||||
if (row.builtIn) { ElMessage.warning('系统内置角色不能停用'); return }
|
||||
const target = row.status === '启用' ? '停用' : '启用'
|
||||
try {
|
||||
await ElMessageBox.confirm(`确认${target}角色“${row.name}”吗?`, '角色状态', { confirmButtonText: '确认', cancelButtonText: '取消' })
|
||||
rowActionId.value = row.id
|
||||
const updated = await changePlatformRoleStatus(row.id, target === '启用' ? 'ACTIVE' : 'DISABLED')
|
||||
Object.assign(row, mapPlatformRole(updated))
|
||||
ElMessage.success(`角色已${target}`)
|
||||
} catch (error) {
|
||||
if (error === 'cancel' || error === 'close') return
|
||||
ElMessage.error(getApiErrorMessage(error, '角色状态更新失败,请稍后重试'))
|
||||
} finally {
|
||||
rowActionId.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
function permissionSummary(row: Role) {
|
||||
const { menuCount, actionCount } = summarizePermissionSelection(availablePermissions.value, row.permissionIds)
|
||||
return `${menuCount} 菜单 · ${actionCount} 操作`
|
||||
}
|
||||
|
||||
onMounted(loadRoles)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="business-page">
|
||||
<el-alert v-if="loadError" type="error" :closable="false" show-icon role="alert"><template #title><div class="api-error-alert-title"><span>{{ loadError.message }}</span><ApiErrorMeta :details="loadError" /></div><el-button link type="danger" @click="loadRoles">重新加载</el-button></template></el-alert>
|
||||
<QueryToolbar v-model="filters" class="surface-panel" ariaLabel="角色筛选" :fields="queryFields" @search="applyFilters" />
|
||||
|
||||
<section class="surface-panel table-panel">
|
||||
<header class="panel-heading"><div><h2>角色与授权 <span class="secondary-text">共 {{ filteredRows.length }} 条</span></h2><p>角色负责聚合菜单、操作和数据范围,内部用户可分配多个角色。</p></div><el-button v-if="canCreate" type="primary" @click="openCreate"><Plus :size="16" />新增角色</el-button></header>
|
||||
<DataTable v-model:page="page" v-model:page-size="pageSize" :data="pagedRows" :columns="roleColumns" :loading="loading" :total="filteredRows.length" row-key="id" empty-text="没有符合条件的角色">
|
||||
<template #actions="{ row }"><div v-if="canEdit || canGrant || access.can('platform:role:status') || access.can('platform:role:delete')" class="table-actions"><el-button v-if="canEdit || canGrant" link type="primary" :disabled="rowActionId === (row as Role).id || (row as Role).builtIn" @click="openEdit(row as Role)"><Pencil :size="15" />配置</el-button><el-button v-if="access.can('platform:role:status')" link :type="(row as Role).status === '启用' ? 'danger' : 'success'" :loading="rowActionId === (row as Role).id" :disabled="(row as Role).builtIn" @click="toggleStatus(row as Role)">{{ (row as Role).status === '启用' ? '停用' : '启用' }}</el-button><el-button v-if="access.can('platform:role:delete')" link type="danger" :disabled="(row as Role).builtIn || (row as Role).userCount > 0 || rowActionId === (row as Role).id" @click="removeRole(row as Role)"><Trash2 :size="15" />删除</el-button></div><span v-else class="secondary-text">仅查看</span></template>
|
||||
<template #role="{ row }"><div class="role-cell"><span><ShieldCheck :size="18" /></span><div><strong>{{ (row as Role).name }}</strong><small>{{ (row as Role).code }}</small></div></div></template>
|
||||
<template #permissionSummary="{ row }"><div class="primary-cell"><strong>{{ permissionSummary(row as Role) }}</strong><span>平台 IAM 权限</span></div></template>
|
||||
<template #roleType="{ row }"><el-tag :type="(row as Role).builtIn ? 'warning' : 'info'" effect="plain" size="small">{{ (row as Role).builtIn ? '系统内置' : '自定义' }}</el-tag></template>
|
||||
<template #status="{ row }"><StatusBadge :status="(row as Role).status" /></template>
|
||||
</DataTable>
|
||||
</section>
|
||||
|
||||
<el-drawer v-model="editorOpen" :title="form.id ? '配置角色' : '新增角色'" size="760px" class="business-drawer editor-drawer" :modal="false" :close-on-click-modal="false">
|
||||
<el-form ref="formRef" :model="form" :rules="formRules" label-position="top" class="drawer-form">
|
||||
<div class="form-section"><h3>基本信息</h3><div class="form-grid two-cols"><el-form-item label="角色名称" prop="name" required><el-input v-model="form.name" :disabled="Boolean(form.id) && !canEdit" placeholder="如:订单运营专员" maxlength="64" /></el-form-item><el-form-item label="角色编码" prop="code" required><el-input v-model="form.code" :disabled="Boolean(form.id)" placeholder="如:ORDER_OPERATOR" maxlength="64" /></el-form-item></div><el-form-item label="角色说明"><el-input v-model="form.description" :disabled="Boolean(form.id) && !canEdit" type="textarea" :rows="2" placeholder="说明该角色的工作范围" maxlength="200" show-word-limit /></el-form-item></div>
|
||||
<div v-if="canGrant" class="form-section permission-section"><div class="section-heading-row"><div><h3>菜单与操作权限</h3><p>保存时按后端契约全量替换当前角色权限;未勾选表示清空授权。</p></div><span>{{ form.permissionIds.length }} 项原有授权</span></div><el-tree ref="treeRef" class="permission-tree" :data="permissionTree" node-key="id" show-checkbox check-strictly default-expand-all :props="{ label: 'name', children: 'children' }" @check="syncPermissionIds"><template #default="{ data }"><div class="permission-node"><span>{{ data.name }}</span><code>{{ data.code }}</code></div></template></el-tree></div>
|
||||
</el-form>
|
||||
<template #footer><div class="drawer-footer"><el-button :disabled="saving" @click="editorOpen = false">取消</el-button><el-button v-if="form.id ? canEdit || canGrant : canCreate" type="primary" :loading="saving" @click="saveRole">保存角色</el-button></div></template>
|
||||
</el-drawer>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { RouteRecordRaw } from 'vue-router'
|
||||
|
||||
export const iamRoutes = [
|
||||
{
|
||||
path: 'system/users',
|
||||
name: 'users',
|
||||
component: () => import('@/modules/iam/pages/InternalUsersView.vue'),
|
||||
meta: { title: '用户管理', description: '统一管理平台和企业租户用户、状态及角色', permission: 'platform:user:list' },
|
||||
},
|
||||
{
|
||||
path: 'system/roles',
|
||||
name: 'roles',
|
||||
component: () => import('@/modules/iam/pages/RolesView.vue'),
|
||||
meta: { title: '角色管理', description: '维护平台角色并配置菜单及操作权限', permission: 'platform:role:list' },
|
||||
},
|
||||
{
|
||||
path: 'system/permissions',
|
||||
name: 'permissions',
|
||||
component: () => import('@/modules/iam/pages/PermissionsView.vue'),
|
||||
meta: { title: '菜单权限', description: '维护菜单、页面、按钮和接口权限编码', permission: 'platform:permission:list' },
|
||||
},
|
||||
] satisfies RouteRecordRaw[]
|
||||
@@ -0,0 +1,42 @@
|
||||
export type RecordStatus = '正常' | '停用'
|
||||
export type RoleStatus = '启用' | '停用'
|
||||
export type PermissionType = '目录' | '菜单' | '按钮' | '接口'
|
||||
export type DataScope = '全部数据' | '本部门数据' | '本人数据' | '自定义'
|
||||
|
||||
export interface InternalUser {
|
||||
id: string
|
||||
account: string
|
||||
name: string
|
||||
department: string
|
||||
phone: string
|
||||
email: string
|
||||
roleIds: string[]
|
||||
status: RecordStatus
|
||||
lastLogin: string
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
export interface Role {
|
||||
id: string
|
||||
name: string
|
||||
code: string
|
||||
description: string
|
||||
userCount: number
|
||||
dataScope: DataScope
|
||||
status: RoleStatus
|
||||
permissionIds: string[]
|
||||
builtIn?: boolean
|
||||
}
|
||||
|
||||
export interface Permission {
|
||||
id: string
|
||||
parentId: string | null
|
||||
name: string
|
||||
code: string
|
||||
type: PermissionType
|
||||
path: string
|
||||
method: string
|
||||
status: RoleStatus
|
||||
sort: number
|
||||
builtIn?: boolean
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { Permission } from '@/modules/iam/types'
|
||||
import { buildPermissionTree, getDescendantIds, summarizePermissionSelection } from '@/modules/iam/utils/permissionTree'
|
||||
|
||||
const permissions: Permission[] = [
|
||||
{ id: 'action-b', parentId: 'menu', name: '操作 B', code: 'demo:b', type: '按钮', path: '', method: '-', status: '启用', sort: 20 },
|
||||
{ id: 'menu', parentId: 'directory', name: '页面', code: 'demo:list', type: '菜单', path: '/demo', method: '-', status: '启用', sort: 10 },
|
||||
{ id: 'directory', parentId: null, name: '目录', code: 'demo', type: '目录', path: '', method: '-', status: '启用', sort: 10 },
|
||||
{ id: 'action-a', parentId: 'menu', name: '操作 A', code: 'demo:a', type: '按钮', path: '', method: '-', status: '启用', sort: 10 },
|
||||
]
|
||||
|
||||
describe('permissionTree', () => {
|
||||
it('builds arbitrary-depth trees and sorts siblings', () => {
|
||||
const tree = buildPermissionTree(permissions)
|
||||
|
||||
expect(tree[0]?.children?.[0]?.children?.map((node) => node.id)).toEqual(['action-a', 'action-b'])
|
||||
})
|
||||
|
||||
it('keeps the ancestor chain when a deep descendant matches', () => {
|
||||
const tree = buildPermissionTree(permissions, (item) => item.code === 'demo:a')
|
||||
|
||||
expect(tree.map((node) => node.id)).toEqual(['directory'])
|
||||
expect(tree[0]?.children?.map((node) => node.id)).toEqual(['menu'])
|
||||
expect(tree[0]?.children?.[0]?.children?.map((node) => node.id)).toEqual(['action-a'])
|
||||
})
|
||||
|
||||
it('stops building a branch when malformed data repeats an ancestor id', () => {
|
||||
const malformed = [
|
||||
...permissions,
|
||||
{ id: 'loop', parentId: null, name: '循环目录', code: 'loop', type: '目录', path: '', method: '-', status: '启用', sort: 20 },
|
||||
{ id: 'loop', parentId: 'loop', name: '循环下级', code: 'loop:child', type: '目录', path: '', method: '-', status: '启用', sort: 10 },
|
||||
] satisfies Permission[]
|
||||
|
||||
const tree = buildPermissionTree(malformed)
|
||||
|
||||
expect(tree.find((node) => node.code === 'loop')).not.toHaveProperty('children')
|
||||
})
|
||||
|
||||
it('collects descendants once when malformed data contains a cycle', () => {
|
||||
const malformed = [
|
||||
...permissions,
|
||||
{ id: 'cycle-a', parentId: 'cycle-b', name: 'A', code: 'cycle:a', type: '目录', path: '', method: '-', status: '启用', sort: 1 },
|
||||
{ id: 'cycle-b', parentId: 'cycle-a', name: 'B', code: 'cycle:b', type: '目录', path: '', method: '-', status: '启用', sort: 2 },
|
||||
] satisfies Permission[]
|
||||
|
||||
expect(getDescendantIds(malformed, 'cycle-a')).toEqual(['cycle-b'])
|
||||
})
|
||||
|
||||
it('counts page menus and operations without treating directories as menus', () => {
|
||||
expect(summarizePermissionSelection(permissions, ['directory', 'menu', 'action-a'])).toEqual({
|
||||
menuCount: 1,
|
||||
actionCount: 1,
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,75 @@
|
||||
import type { Permission } from '@/modules/iam/types'
|
||||
|
||||
export type PermissionTreeNode = Permission & { children?: PermissionTreeNode[] }
|
||||
export type PermissionMatcher = (permission: Permission) => boolean
|
||||
|
||||
function groupByParent(permissions: Permission[]) {
|
||||
const childrenByParent = new Map<string | null, Permission[]>()
|
||||
|
||||
permissions.forEach((permission) => {
|
||||
const siblings = childrenByParent.get(permission.parentId) ?? []
|
||||
siblings.push(permission)
|
||||
childrenByParent.set(permission.parentId, siblings)
|
||||
})
|
||||
|
||||
childrenByParent.forEach((siblings) => {
|
||||
siblings.sort((left, right) => left.sort - right.sort)
|
||||
})
|
||||
|
||||
return childrenByParent
|
||||
}
|
||||
|
||||
export function buildPermissionTree(
|
||||
permissions: Permission[],
|
||||
matches: PermissionMatcher = () => true,
|
||||
): PermissionTreeNode[] {
|
||||
const childrenByParent = groupByParent(permissions)
|
||||
|
||||
function buildNode(permission: Permission, ancestors: Set<string>): PermissionTreeNode | null {
|
||||
if (ancestors.has(permission.id)) return null
|
||||
|
||||
const nextAncestors = new Set(ancestors).add(permission.id)
|
||||
const children = (childrenByParent.get(permission.id) ?? [])
|
||||
.map((child) => buildNode(child, nextAncestors))
|
||||
.filter((child): child is PermissionTreeNode => child !== null)
|
||||
|
||||
if (!matches(permission) && children.length === 0) return null
|
||||
|
||||
return {
|
||||
...permission,
|
||||
...(children.length ? { children } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
return (childrenByParent.get(null) ?? [])
|
||||
.map((permission) => buildNode(permission, new Set()))
|
||||
.filter((node): node is PermissionTreeNode => node !== null)
|
||||
}
|
||||
|
||||
export function getDescendantIds(permissions: Permission[], permissionId: string): string[] {
|
||||
const childrenByParent = groupByParent(permissions)
|
||||
const visited = new Set([permissionId])
|
||||
const descendants: string[] = []
|
||||
const queue = [...(childrenByParent.get(permissionId) ?? [])]
|
||||
|
||||
while (queue.length) {
|
||||
const current = queue.shift()
|
||||
if (!current || visited.has(current.id)) continue
|
||||
|
||||
visited.add(current.id)
|
||||
descendants.push(current.id)
|
||||
queue.push(...(childrenByParent.get(current.id) ?? []))
|
||||
}
|
||||
|
||||
return descendants
|
||||
}
|
||||
|
||||
export function summarizePermissionSelection(permissions: Permission[], selectedIds: string[]) {
|
||||
const selected = new Set(selectedIds)
|
||||
const selectedPermissions = permissions.filter((permission) => selected.has(permission.id))
|
||||
|
||||
return {
|
||||
menuCount: selectedPermissions.filter((permission) => permission.type === '菜单').length,
|
||||
actionCount: selectedPermissions.filter((permission) => ['按钮', '接口'].includes(permission.type)).length,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { mapPlatformPermission } from '@/modules/iam/utils/platformPermission'
|
||||
|
||||
describe('mapPlatformPermission', () => {
|
||||
it('treats the string root parent as a root node and preserves long ids', () => {
|
||||
expect(mapPlatformPermission({
|
||||
id: '2082813911786024961',
|
||||
tenantId: '0',
|
||||
appCode: 'PLATFORM',
|
||||
permissionType: 'MENU',
|
||||
parentId: '0',
|
||||
permissionCode: 'platform:audit',
|
||||
permissionName: '审计管理',
|
||||
routePath: '/audit',
|
||||
httpMethod: null,
|
||||
sortNo: 50,
|
||||
status: 'ACTIVE',
|
||||
})).toMatchObject({ id: '2082813911786024961', parentId: null, code: 'platform:audit' })
|
||||
})
|
||||
|
||||
it('preserves a long string parent id for child resources', () => {
|
||||
expect(mapPlatformPermission({
|
||||
id: '2082813911786024962',
|
||||
tenantId: '0',
|
||||
appCode: 'PLATFORM',
|
||||
permissionType: 'BUTTON',
|
||||
parentId: '2082813911786024961',
|
||||
permissionCode: 'platform:audit:list',
|
||||
permissionName: '操作日志',
|
||||
routePath: null,
|
||||
httpMethod: null,
|
||||
sortNo: 10,
|
||||
status: 'ACTIVE',
|
||||
})).toMatchObject({ id: '2082813911786024962', parentId: '2082813911786024961', type: '按钮' })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { PlatformPermissionResource } from '@/modules/iam/api/platformIam'
|
||||
import type { Permission } from '@/modules/iam/types'
|
||||
|
||||
export function mapPlatformPermission(item: PlatformPermissionResource): Permission {
|
||||
const parentId = String(item.parentId)
|
||||
return {
|
||||
id: String(item.id),
|
||||
parentId: parentId === '0' ? null : parentId,
|
||||
name: item.permissionName,
|
||||
code: item.permissionCode,
|
||||
type: item.permissionType === 'BUTTON' ? '按钮' : '菜单',
|
||||
path: item.routePath ?? '',
|
||||
method: item.httpMethod ?? '-',
|
||||
status: item.status === 'ACTIVE' ? '启用' : '停用',
|
||||
sort: item.sortNo,
|
||||
builtIn: Boolean(item.builtIn),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user