Files
admin-web/src/modules/iam/pages/InternalUsersView.test.ts
T

317 lines
14 KiB
TypeScript
Raw Normal View History

2026-08-03 14:58:17 +08:00
import ElementPlus from 'element-plus'
2026-08-12 17:29:35 +08:00
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
2026-08-03 14:58:17 +08:00
import { createPinia, setActivePinia } from 'pinia'
import { enableAutoUnmount, flushPromises, mount } from '@vue/test-utils'
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
2026-08-25 09:52:45 +08:00
createPlatformManagedUser,
2026-08-03 14:58:17 +08:00
getPlatformUserOptions,
2026-08-25 09:52:45 +08:00
listSharedReceivingOverseasWarehouseOptions,
2026-08-03 14:58:17 +08:00
listPlatformManagedUsers,
2026-08-25 09:52:45 +08:00
updatePlatformManagedUser,
2026-08-03 14:58:17 +08:00
type PlatformManagedUser,
2026-08-03 18:49:18 +08:00
} from '@/modules/iam/api/platformIam'
import { useAccessPreviewStore } from '@/core/access/accessPreview'
import { useAuthStore } from '@/core/auth/auth'
2026-08-03 14:58:17 +08:00
import InternalUsersView from './InternalUsersView.vue'
2026-08-12 17:29:35 +08:00
const internalUsersSource = readFileSync(resolve(process.cwd(), 'src/modules/iam/pages/InternalUsersView.vue'), 'utf8')
2026-08-03 18:49:18 +08:00
vi.mock('@/modules/iam/api/platformIam', () => ({
2026-08-03 14:58:17 +08:00
listPlatformManagedUsers: vi.fn(),
getPlatformUserOptions: vi.fn(),
2026-08-25 09:52:45 +08:00
listSharedReceivingOverseasWarehouseOptions: vi.fn(),
2026-08-03 14:58:17 +08:00
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: '张伟',
2026-08-04 13:32:08 +08:00
phone: '13800138000', email: 'zhangwei@example.com', tenantId: '0', tenantName: '平台',
memberType: 'INTERNAL', memberNo: 'PLATFORM-30', status: 'ACTIVE', roleIds: ['40'],
roleNames: ['运营管理员'], lastLoginAt: '2026-06-01T10:30:00',
2026-08-03 14:58:17 +08:00
protectedAccount: false,
2026-08-25 09:52:45 +08:00
overseasWarehouseId: null,
2026-08-03 14:58:17 +08:00
}
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())
2026-08-04 13:32:08 +08:00
describe('InternalUsersView platform internal user management', () => {
2026-09-15 09:58:15 +08:00
it('renders row business actions as shared outlined text buttons', () => {
expect(internalUsersSource).toContain('size="small" data-tone="neutral" @click="openEdit')
expect(internalUsersSource).toContain('size="small" :data-tone="(row as PlatformManagedUser).status')
expect(internalUsersSource).toMatch(/>\s*编辑\s*<\/el-button>/)
expect(internalUsersSource).toContain(':data-tone=')
2026-08-12 17:45:49 +08:00
expect(internalUsersSource).not.toContain('v-if="canChangeStatus" link')
})
2026-08-12 17:29:35 +08:00
it('uses the prototype-sized centered editor with a scrollable body and mobile single column', () => {
expect(internalUsersSource).toContain('width="min(650px, calc(100vw - 28px))"')
expect(internalUsersSource).toContain('fullscreenable destroy-on-close')
expect(internalUsersSource).toContain(':global(.internal-user-editor-dialog.app-dialog.admin-density-dialog.el-dialog:not(.is-fullscreen)) { max-height: min(760px, calc(100vh - 32px)); }')
expect(internalUsersSource).not.toContain(':global(.internal-user-editor-dialog .el-dialog__body)')
2026-08-12 17:29:35 +08:00
expect(internalUsersSource).toContain('@media (max-width: 720px)')
expect(internalUsersSource).toContain('.user-editor-table tr { display: grid; }')
2026-08-12 17:29:35 +08:00
})
2026-08-03 14:58:17 +08:00
beforeEach(() => {
vi.stubGlobal('ResizeObserver', ResizeObserverStub)
document.body.innerHTML = ''
2026-08-04 13:32:08 +08:00
vi.mocked(listPlatformManagedUsers).mockReset().mockResolvedValue({
records: [user], page: 1, size: 10, total: 21, pages: 3,
})
2026-08-03 14:58:17 +08:00
vi.mocked(getPlatformUserOptions).mockReset().mockResolvedValue({
tenants: [
{ id: '0', name: '平台', status: 'ACTIVE' },
{ id: '10001', name: '华远贸易', status: 'ACTIVE' },
],
2026-08-04 13:32:08 +08:00
roles: [
2026-08-25 09:52:45 +08:00
{ id: '40', tenantId: '0', roleCode: 'PLATFORM_OPERATOR', name: '运营管理员', status: 'ACTIVE' },
{ id: '41', tenantId: '10001', roleCode: 'CUSTOMER_ADMIN', name: '客户管理员', status: 'ACTIVE' },
2026-08-04 13:32:08 +08:00
],
2026-08-03 14:58:17 +08:00
})
2026-08-25 09:52:45 +08:00
vi.mocked(listSharedReceivingOverseasWarehouseOptions).mockReset().mockResolvedValue([
{ id: '90071992547409931', warehouseCode: 'LAX-01', warehouseName: '洛杉矶收货仓', countryCode: 'US' },
])
vi.mocked(createPlatformManagedUser).mockReset().mockResolvedValue(user)
vi.mocked(updatePlatformManagedUser).mockReset().mockResolvedValue(user)
2026-08-03 14:58:17 +08:00
})
2026-08-04 13:32:08 +08:00
it('loads a server page and only renders internal-user fields', async () => {
2026-08-03 14:58:17 +08:00
const wrapper = await mountView()
expect(listPlatformManagedUsers).toHaveBeenCalledOnce()
2026-08-04 13:32:08 +08:00
expect(listPlatformManagedUsers).toHaveBeenCalledWith({ page: 1, size: 10 })
2026-08-03 14:58:17 +08:00
expect(getPlatformUserOptions).toHaveBeenCalledOnce()
expect(wrapper.text()).toContain('zhangwei')
expect(wrapper.text()).toContain('张伟')
2026-08-04 13:32:08 +08:00
expect(wrapper.text()).toContain('运营管理员')
2026-08-03 14:58:17 +08:00
expect(wrapper.text()).toContain('2026-06-01 10:30')
2026-08-03 19:05:40 +08:00
expect(wrapper.find('[aria-label="用户筛选"]').exists()).toBe(true)
2026-08-04 13:32:08 +08:00
expect(wrapper.find('[aria-label="内部用户列表"]').exists()).toBe(true)
expect(wrapper.text()).toContain('共 21 条')
2026-08-03 19:05:40 +08:00
expect(wrapper.text()).toContain('查询')
expect(wrapper.text()).toContain('重置')
2026-08-03 14:58:17 +08:00
expect(wrapper.text()).not.toContain('认证用户 ID')
expect(wrapper.text()).not.toContain('成员编号')
2026-08-04 13:32:08 +08:00
expect(wrapper.text()).not.toContain('所属租户')
expect(wrapper.text()).not.toContain('华远贸易')
2026-08-03 14:58:17 +08:00
})
2026-08-04 13:32:08 +08:00
it('opens an internal-user form without a tenant selector', async () => {
2026-08-03 14:58:17 +08:00
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()
2026-08-04 13:32:08 +08:00
expect(document.body.textContent).not.toContain('所属租户')
2026-08-03 14:58:17 +08:00
expect(document.body.textContent).toContain('初始密码')
expect(document.body.textContent).toContain('确认添加')
})
2026-08-28 13:54:44 +08:00
it('requires a shared receiving warehouse for OVERSEAS_WAREHOUSE_PDA_OPERATOR', async () => {
2026-08-25 09:52:45 +08:00
vi.mocked(getPlatformUserOptions).mockResolvedValueOnce({
tenants: [{ id: '0', name: '平台', status: 'ACTIVE' }],
roles: [
{ id: '40', tenantId: '0', roleCode: 'PLATFORM_OPERATOR', name: '运营管理员', status: 'ACTIVE' },
2026-08-28 13:54:44 +08:00
{ id: '4000005', tenantId: '0', roleCode: 'OVERSEAS_WAREHOUSE_PDA_OPERATOR', name: '海外仓 PDA 作业员', status: 'ACTIVE' },
2026-08-25 09:52:45 +08:00
],
})
const wrapper = await mountView()
await wrapper.findAll('button').find((button) => button.text().trim() === '新增用户')?.trigger('click')
await flushPromises()
expect(document.body.textContent).not.toContain('实际海外收货仓')
const roleSelect = wrapper.findAllComponents({ name: 'ElSelect' })
.find((component) => component.props('placeholder') === '选择角色')
expect(roleSelect).toBeDefined()
roleSelect?.vm.$emit('update:modelValue', ['4000005'])
await flushPromises()
expect(listSharedReceivingOverseasWarehouseOptions).toHaveBeenCalledOnce()
expect(document.body.textContent).toContain('实际海外收货仓')
const warehouseSelect = wrapper.findAllComponents({ name: 'ElSelect' })
.find((component) => component.props('placeholder') === '请选择平台共享海外收货仓')
expect(warehouseSelect).toBeDefined()
})
it('uses the stable role code instead of localized role names to activate the warehouse binding', () => {
2026-08-28 13:54:44 +08:00
expect(internalUsersSource).toContain("role.roleCode === 'OVERSEAS_WAREHOUSE_PDA_OPERATOR'")
expect(internalUsersSource).toContain('overseasWarehouseId: hasOverseasPdaRole.value ? form.overseasWarehouseId : null')
expect(internalUsersSource).not.toContain("role.name === '海外仓 PDA 作业员'")
2026-08-25 09:52:45 +08:00
})
2026-08-28 13:54:44 +08:00
it('preserves the picker warehouse binding when editing a OVERSEAS_WAREHOUSE_PDA_OPERATOR user', async () => {
2026-08-25 09:52:45 +08:00
const pickerUser: PlatformManagedUser = {
...user,
roleIds: ['4000005'],
2026-08-28 13:54:44 +08:00
roleNames: ['海外仓 PDA 作业员'],
2026-08-25 09:52:45 +08:00
overseasWarehouseId: '90071992547409931',
}
vi.mocked(listPlatformManagedUsers).mockResolvedValueOnce({
records: [pickerUser], page: 1, size: 10, total: 1, pages: 1,
})
vi.mocked(getPlatformUserOptions).mockResolvedValueOnce({
tenants: [{ id: '0', name: '平台', status: 'ACTIVE' }],
2026-08-28 13:54:44 +08:00
roles: [{ id: '4000005', tenantId: '0', roleCode: 'OVERSEAS_WAREHOUSE_PDA_OPERATOR', name: '海外仓 PDA 作业员', status: 'ACTIVE' }],
2026-08-25 09:52:45 +08:00
})
vi.mocked(updatePlatformManagedUser).mockResolvedValueOnce(pickerUser)
const wrapper = await mountView()
const setupState = (wrapper.vm.$ as unknown as {
setupState: { openEdit: (row: PlatformManagedUser) => void }
}).setupState
setupState.openEdit(pickerUser)
await flushPromises()
await wrapper.findAll('button').find((button) => button.text().trim() === '保存修改')?.trigger('click')
await flushPromises()
expect(updatePlatformManagedUser).toHaveBeenCalledWith('30', {
displayName: '张伟',
phone: '13800138000',
email: 'zhangwei@example.com',
tenantId: '0',
roleIds: ['4000005'],
overseasWarehouseId: '90071992547409931',
})
})
2026-08-28 13:54:44 +08:00
it('clears a warehouse binding after switching away from OVERSEAS_WAREHOUSE_PDA_OPERATOR', async () => {
vi.mocked(getPlatformUserOptions).mockResolvedValueOnce({
tenants: [{ id: '0', name: '平台', status: 'ACTIVE' }],
roles: [
{ id: '40', tenantId: '0', roleCode: 'PLATFORM_OPERATOR', name: '运营管理员', status: 'ACTIVE' },
2026-08-28 13:54:44 +08:00
{ id: '4000005', tenantId: '0', roleCode: 'OVERSEAS_WAREHOUSE_PDA_OPERATOR', name: '海外仓 PDA 作业员', status: 'ACTIVE' },
],
})
const wrapper = await mountView()
const setupState = (wrapper.vm.$ as unknown as {
setupState: {
openCreate: () => void
form: { roleIds: string[]; overseasWarehouseId: string }
}
}).setupState
setupState.openCreate()
setupState.form.roleIds = ['4000005']
await flushPromises()
setupState.form.overseasWarehouseId = '90071992547409931'
setupState.form.roleIds = ['40']
await flushPromises()
expect(setupState.form.overseasWarehouseId).toBe('')
expect(document.body.textContent).not.toContain('实际海外收货仓')
})
it('submits the selected picker warehouse as an unchanged long-id string', async () => {
vi.mocked(getPlatformUserOptions).mockResolvedValueOnce({
tenants: [{ id: '0', name: '平台', status: 'ACTIVE' }],
2026-08-28 13:54:44 +08:00
roles: [{ id: '4000005', tenantId: '0', roleCode: 'OVERSEAS_WAREHOUSE_PDA_OPERATOR', name: '海外仓 PDA 作业员', status: 'ACTIVE' }],
})
const wrapper = await mountView()
const setupState = (wrapper.vm.$ as unknown as {
setupState: {
openCreate: () => void
saveUser: () => Promise<void>
form: Record<string, unknown>
}
}).setupState
setupState.openCreate()
Object.assign(setupState.form, {
username: 'overseas_picker_dev',
displayName: '海外仓操作员',
phone: '17512095155',
email: 'overseas_picker_dev@qq.com',
roleIds: ['4000005'],
overseasWarehouseId: '90071992547409931',
password: 'ChangeMe123!',
confirmPassword: 'ChangeMe123!',
status: 'ACTIVE',
})
await flushPromises()
await setupState.saveUser()
expect(createPlatformManagedUser).toHaveBeenCalledWith({
username: 'overseas_picker_dev',
displayName: '海外仓操作员',
phone: '17512095155',
email: 'overseas_picker_dev@qq.com',
tenantId: '0',
roleIds: ['4000005'],
overseasWarehouseId: '90071992547409931',
password: 'ChangeMe123!',
status: 'ACTIVE',
})
})
2026-08-04 13:32:08 +08:00
it('requests server-side pages and filters instead of slicing locally', async () => {
const wrapper = await mountView()
await wrapper.find('button[aria-label="第 2 页"]').trigger('click')
await flushPromises()
expect(listPlatformManagedUsers).toHaveBeenLastCalledWith({ page: 2, size: 10 })
await wrapper.find('input[aria-label="用户关键词"]').setValue(' 张伟 ')
const searchButton = wrapper.findAll('button').find((button) => button.text().trim() === '查询')
await searchButton?.trigger('click')
await flushPromises()
expect(listPlatformManagedUsers).toHaveBeenLastCalledWith({ page: 1, size: 10, keyword: '张伟' })
})
2026-08-03 14:58:17 +08:00
it('shows a recoverable API error without fake users', async () => {
vi.mocked(listPlatformManagedUsers).mockRejectedValueOnce(new Error('Gateway unavailable'))
const wrapper = await mountView()
2026-08-12 12:35:32 +08:00
expect(wrapper.text()).toContain('内部用户列表加载失败,请稍后重试')
expect(wrapper.text()).not.toContain('Gateway unavailable')
2026-08-03 14:58:17 +08:00
expect(wrapper.text()).toContain('重新加载')
expect(wrapper.text()).not.toContain('zhangwei')
})
})