392 lines
19 KiB
JavaScript
392 lines
19 KiB
JavaScript
import assert from 'node:assert/strict'
|
|
import { readFile } from 'node:fs/promises'
|
|
import test from 'node:test'
|
|
import ts from '../node_modules/typescript/lib/typescript.js'
|
|
import compiler from '../node_modules/@vue/compiler-sfc/dist/compiler-sfc.cjs.js'
|
|
import { createSSRApp, h, inject, provide, reactive } from '../node_modules/vue/index.mjs'
|
|
import { renderToString } from '../node_modules/@vue/server-renderer/index.js'
|
|
import { createPinia, setActivePinia } from '../node_modules/pinia/dist/pinia.mjs'
|
|
|
|
// 实际 store、SFC 脚本与编译后的模板;网络、确认框和 Element Plus 仅使用隔离替身。
|
|
const fixtures = {}
|
|
globalThis[Symbol.for('native-company-ui')] = fixtures
|
|
let sequence = 0
|
|
const dataModule = source => `data:text/javascript;base64,${Buffer.from(source).toString('base64')}`
|
|
const vueUrl = new URL('../node_modules/vue/index.mjs', import.meta.url).href
|
|
const piniaUrl = new URL('../node_modules/pinia/dist/pinia.mjs', import.meta.url).href
|
|
const compile = source => ts.transpileModule(source, {
|
|
compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022 }
|
|
}).outputText
|
|
const deferred = () => {
|
|
let resolve
|
|
const promise = new Promise(done => { resolve = done })
|
|
return { promise, resolve }
|
|
}
|
|
const company = (id, overrides = {}) => ({
|
|
id, code: `fixture${id}`, name: `测试公司${id}`, parent_id: 0, disable: 0, effective_disable: 0,
|
|
is_directory_company: false, structure_mode: 'group', can_manage_structure: true,
|
|
permission_prefix: `company.fixture${id}`, member_status: 0, can_login: 0, ...overrides
|
|
})
|
|
const menu = (overrides = {}) => ({
|
|
id: 1000000001, pid: 0, name: '订单目录', type: 'M', paths: '', component: '', perms: '', icon: '',
|
|
sort: 0, is_show: 1, disable: 0, ...overrides
|
|
})
|
|
const department = { id: 1000000001, pid: 0, name: '运营中心', sort: 0, disable: 0 }
|
|
|
|
async function fixtureStore(overrides = {}) {
|
|
setActivePinia(createPinia())
|
|
const key = `fixture-${++sequence}`
|
|
const fixture = fixtures[key] = {
|
|
calls: [], reads: [], events: [], headers: [], refreshes: 0, confirms: 0, rows: [],
|
|
context: {
|
|
group: { name: '隔离集团' }, identity: { gid: 'isolated-owner', source_admin_id: 1 },
|
|
default_company_id: 2, is_group_admin: true,
|
|
companies: [company(1, { code: 'hospital', is_directory_company: true, structure_mode: 'hospital', member_status: 1, can_login: 1 }), company(2), company(3)],
|
|
applications: [], ...overrides
|
|
},
|
|
auth: reactive({ isShared: true, can: () => false })
|
|
}
|
|
const stub = source => dataModule(`const fixture = globalThis[Symbol.for('native-company-ui')][${JSON.stringify(key)}]; ${source}`)
|
|
const http = stub(`
|
|
export const get = async url => {
|
|
if (url === '/group/context') return fixture.context;
|
|
fixture.reads.push({ url, company: fixture.group.currentCompanyId });
|
|
return fixture.onGet ? fixture.onGet(url) : structuredClone(fixture.rows);
|
|
};
|
|
export const post = async (url, payload) => {
|
|
fixture.calls.push({ url, payload: structuredClone(payload), company: fixture.group.currentCompanyId });
|
|
await fixture.onPost?.(url, payload);
|
|
};
|
|
export const setCompanyContext = id => fixture.headers.push(id);
|
|
export const reportError = error => fixture.events.push({ type: 'error', message: error.message });
|
|
`)
|
|
const source = await readFile(new URL('../src/stores/group.ts', import.meta.url), 'utf8')
|
|
const access = dataModule(compile(await readFile(new URL('../src/services/access.ts', import.meta.url), 'utf8')))
|
|
const auth = stub('export const useAuthStore = () => fixture.auth;')
|
|
const storeUrl = dataModule(compile(source)
|
|
.replace(/from ['"]vue['"]/, `from '${vueUrl}'`)
|
|
.replace(/from ['"]pinia['"]/, `from '${piniaUrl}'`)
|
|
.replace(/from ['"]\.\.\/services\/http['"]/, `from '${http}'`)
|
|
.replace(/from ['"]\.\.\/services\/access['"]/, `from '${access}'`)
|
|
.replace(/from ['"]\.\/auth['"]/, `from '${auth}'`))
|
|
const { useGroupStore } = await import(storeUrl)
|
|
fixture.group = useGroupStore()
|
|
fixture.group.configure(true)
|
|
await fixture.group.load()
|
|
return { fixture, stub, http }
|
|
}
|
|
|
|
async function loadView(view, overrides) {
|
|
const { fixture, stub, http } = await fixtureStore(overrides)
|
|
const ui = stub(`
|
|
export const ElMessage = Object.fromEntries(['success', 'warning', 'error', 'info'].map(type => [type, message => fixture.events.push({ type, message })]));
|
|
export const ElMessageBox = { confirm: async () => { fixture.confirms++; await fixture.onConfirm?.(); } };
|
|
`)
|
|
const component = dataModule(`import { h } from '${vueUrl}'; export default { setup: (_, { slots }) => () => h('section', slots.default?.()) };`)
|
|
const imports = {
|
|
vue: vueUrl, 'element-plus': ui,
|
|
'@element-plus/icons-vue': dataModule('export const Plus = {}; export const Refresh = {};'),
|
|
'../stores/auth': stub('export const useAuthStore = () => fixture.auth;'),
|
|
'../stores/group': stub('export const useGroupStore = () => fixture.group;'),
|
|
'../services/http': http,
|
|
'../router': stub('export const refreshAccess = async () => { fixture.refreshes++; return fixture.onRefresh ? fixture.onRefresh() : true; };'),
|
|
'../components/PageHeader.vue': component, '../components/CompanyScope.vue': component,
|
|
'../components/CompanyDirectoryEmpty.vue': component
|
|
}
|
|
const sfc = await readFile(new URL(`../src/views/${view}.vue`, import.meta.url), 'utf8')
|
|
const { descriptor } = compiler.parse(sfc)
|
|
const script = compiler.compileScript(descriptor, { id: `native-${sequence}` })
|
|
const exports = Object.keys(script.bindings)
|
|
let source = descriptor.scriptSetup.content.replace(
|
|
"import { computed, onMounted, reactive, ref } from 'vue'",
|
|
"import { computed, reactive, ref } from 'vue'\nconst onMounted = () => {}"
|
|
)
|
|
const replaceImports = content => content.replace(/from (['"])([^'"]+)\1/g, (_match, _quote, name) => {
|
|
assert.ok(imports[name], `未隔离依赖:${name}`)
|
|
return `from '${imports[name]}'`
|
|
})
|
|
source = replaceImports(compile(`${source}\nexport { ${exports.join(', ')} };`))
|
|
const module = await import(dataModule(source))
|
|
module.formRef.value = { validate: async () => true, clearValidate() {} }
|
|
const template = compiler.compileTemplate({
|
|
source: descriptor.template.content, filename: `${view}.vue`, id: `native-${sequence}`,
|
|
compilerOptions: { bindingMetadata: script.bindings, expressionPlugins: ['typescript'] }
|
|
})
|
|
assert.deepEqual(template.errors, [])
|
|
const { render } = await import(dataModule(replaceImports(compile(template.code))))
|
|
return { fixture, module, render }
|
|
}
|
|
|
|
async function html(view) {
|
|
const app = createSSRApp({ setup: () => ({ ...view.module }), render: view.render })
|
|
app.directive('loading', {})
|
|
const generic = { setup: (_, { slots }) => () => h('div', slots.default?.()) }
|
|
for (const name of ['ElForm', 'ElFormItem', 'ElRadioGroup', 'ElRadioButton', 'ElTreeSelect', 'ElSelect', 'ElOption', 'ElInputNumber', 'ElSwitch', 'ElTag']) app.component(name, generic)
|
|
app.component('ElButton', { props: ['disabled'], setup: (props, { slots }) => () => h('button', { disabled: props.disabled }, slots.default?.()) })
|
|
app.component('ElAlert', { props: ['title'], setup: props => () => h('aside', props.title) })
|
|
app.component('ElEmpty', { props: ['description'], setup: props => () => h('p', props.description) })
|
|
app.component('ElInput', { props: ['placeholder', 'maxlength'], setup: props => () => h('input', { placeholder: props.placeholder, maxlength: props.maxlength }) })
|
|
app.component('ElDialog', { props: ['modelValue'], setup: (props, { slots }) => () => props.modelValue ? h('dialog', [slots.default?.(), slots.footer?.()]) : null })
|
|
app.component('ElTable', { props: ['data'], setup: (props, { slots }) => { provide('testRows', props.data); return () => h('main', props.data?.length ? slots.default?.() : slots.empty?.()) } })
|
|
app.component('ElTableColumn', { setup: (_, { slots }) => { const rows = inject('testRows', []); return () => h('div', rows.map(row => slots.default?.({ row }))) } })
|
|
app.config.warnHandler = () => {}
|
|
return renderToString(app)
|
|
}
|
|
|
|
test('显式 native owner 不依赖应用、成员资格、源权限;旧能力字段不决定授权,停用祖先阻断操作', async () => {
|
|
const { fixture } = await fixtureStore()
|
|
const group = fixture.group
|
|
assert.equal(group.directoryAvailable, false)
|
|
assert.equal(group.isNativeStructure, true)
|
|
assert.equal(group.structureAvailable, true)
|
|
assert.deepEqual(group.applications, [])
|
|
group.context.is_group_admin = false
|
|
assert.equal(group.structureAvailable, false)
|
|
group.context.is_group_admin = true
|
|
group.currentCompany.can_manage_structure = false
|
|
assert.equal(group.structureAvailable, true)
|
|
group.currentCompany.can_manage_structure = true
|
|
delete group.currentCompany.structure_mode
|
|
assert.equal(group.structureAvailable, false)
|
|
group.currentCompany.structure_mode = 'group'
|
|
group.currentCompany.parent_id = 3
|
|
group.context.companies[2].disable = 1
|
|
assert.equal(group.structureAvailable, false)
|
|
group.context.companies[2].disable = 0
|
|
group.context.companies[2].effective_disable = 0
|
|
assert.equal(group.structureAvailable, true)
|
|
const version = group.companyRevision
|
|
group.selectCompany(3)
|
|
group.selectCompany(2)
|
|
assert.equal(group.companyRevision, version + 2)
|
|
group.selectCompany(1)
|
|
assert.equal(group.directoryAvailable, true)
|
|
assert.equal(group.isNativeStructure, false)
|
|
})
|
|
|
|
test('空 native 公司显示新增部门,owner 可创建、编辑并删除空顶级部门且不刷新医院资料', async () => {
|
|
const view = await loadView('Departments')
|
|
const { fixture, module } = view
|
|
await module.load()
|
|
assert.deepEqual(module.rows.value, [])
|
|
assert.match(await html(view), /新增部门/)
|
|
assert.equal(fixture.auth.can('auth.dept/add'), false)
|
|
module.open()
|
|
module.form.name = ' 运营中心 '
|
|
assert.equal(module.form.pid, 0)
|
|
await module.save()
|
|
module.open(department)
|
|
assert.equal(module.protectedParent.value, false)
|
|
module.form.name = '运营部'
|
|
await module.save()
|
|
await module.remove(department)
|
|
assert.deepEqual(fixture.calls.map(call => call.url), ['/auth.dept/add', '/auth.dept/edit', '/auth.dept/delete'])
|
|
assert.equal(fixture.calls[0].payload.name, '运营中心')
|
|
assert.equal(fixture.calls[0].company, 2)
|
|
assert.equal(fixture.calls[2].payload.id, department.id)
|
|
assert.equal(fixture.refreshes, 0)
|
|
assert.equal(fixture.reads.length, 4)
|
|
})
|
|
|
|
test('native 菜单正常加载,M/C/A CRUD 使用公司权限前缀,配置不暗示导航已同步', async () => {
|
|
const view = await loadView('Menus')
|
|
const { fixture, module } = view
|
|
fixture.rows = [menu()]
|
|
await module.load()
|
|
assert.equal(module.rows.value[0].name, '订单目录')
|
|
assert.match(await html(view), /新增菜单/)
|
|
assert.match(await html(view), /组件和外链不会直接执行/)
|
|
for (const type of ['M', 'C', 'A']) {
|
|
module.open(undefined, type === 'A' ? menu({ type: 'C' }) : undefined)
|
|
Object.assign(module.form, { type, name: `${type}配置`, paths: 'orders/index', component: 'orders/index', perms: type === 'M' ? '' : `company.fixture2.orders.${type}` })
|
|
await module.save()
|
|
}
|
|
module.open(menu({ type: 'C', perms: 'company.fixture2.orders.read', paths: 'legacy/orders', component: 'orders/list' }))
|
|
module.form.name = '订单页面'
|
|
await module.save()
|
|
await module.remove(menu())
|
|
assert.equal(fixture.calls.length, 5)
|
|
assert.deepEqual(fixture.calls.slice(0, 3).map(call => call.payload.type), ['M', 'C', 'A'])
|
|
assert.equal(fixture.calls[3].payload.paths, 'legacy/orders')
|
|
assert.equal(fixture.calls[3].payload.component, 'orders/list')
|
|
assert.equal(fixture.refreshes, 0)
|
|
assert.equal(fixture.events.some(event => event.message.includes('导航已同步')), false)
|
|
})
|
|
|
|
test('native 前缀校验拒绝跨公司、裸前缀、空页面权限,目录可留空', async () => {
|
|
const { fixture, module } = await loadView('Menus')
|
|
module.open()
|
|
Object.assign(module.form, { type: 'C', name: '订单页' })
|
|
for (const permission of ['', 'company.fixture2.', 'company.fixture3.orders.list', 'auth.admin/lists', 'company.fixture2.orders list', 'company.fixture2.orders#read', `company.fixture2.${'x'.repeat(200)}`]) {
|
|
module.form.perms = permission
|
|
let validation
|
|
module.permissionRules.value[0].validator({}, permission, error => { validation = error })
|
|
assert.ok(validation instanceof Error)
|
|
await module.save()
|
|
}
|
|
assert.equal(fixture.calls.length, 0)
|
|
module.form.type = 'M'
|
|
module.form.perms = ''
|
|
await module.save()
|
|
assert.equal(fixture.calls.length, 1)
|
|
})
|
|
|
|
test('native 文案、占位和 64/200 长度规则使用本公司约定,与医院 data_mode 无关', async () => {
|
|
const view = await loadView('Menus')
|
|
const { fixture, module } = view
|
|
fixture.auth.isShared = false
|
|
module.open()
|
|
assert.equal(module.canManage('add'), true)
|
|
const output = await html(view)
|
|
assert.match(output, /company\.fixture2\.orders\.list/)
|
|
assert.match(output, /不会加载或执行该组件/)
|
|
assert.equal(module.nameRules.value[1].max, 64)
|
|
for (const [rules, value, expected] of [
|
|
[module.pathRules, 'orders/index', false], [module.pathRules, 'x'.repeat(201), true],
|
|
[module.componentRules.value, 'orders/index', false], [module.componentRules.value, 'x'.repeat(201), true],
|
|
[module.componentRules.value, 'orders\nindex', true]
|
|
]) {
|
|
let result
|
|
rules[0].validator({}, value, error => { result = error })
|
|
assert.equal(result instanceof Error, expected)
|
|
}
|
|
})
|
|
|
|
for (const viewName of ['Departments', 'Menus']) {
|
|
test(`${viewName} 普通成员与停用公司没有写入口或读取,源星号也不授予 native 管理`, async () => {
|
|
for (const unavailable of ['member', 'disabled', 'legacy-capability']) {
|
|
const view = await loadView(viewName)
|
|
const { fixture, module } = view
|
|
fixture.auth.can = () => true
|
|
if (unavailable === 'member') fixture.group.context.is_group_admin = false
|
|
if (unavailable === 'disabled') fixture.group.currentCompany.effective_disable = 1
|
|
if (unavailable === 'legacy-capability') {
|
|
fixture.group.context.is_group_admin = false
|
|
fixture.group.currentCompany.can_manage_structure = true
|
|
}
|
|
await module.load()
|
|
module.open()
|
|
await module.save()
|
|
await module.remove(viewName === 'Departments' ? department : menu())
|
|
assert.equal(module.visible.value, false)
|
|
assert.equal(fixture.calls.length, 0)
|
|
assert.equal(fixture.reads.length, 0)
|
|
assert.doesNotMatch(await html(view), viewName === 'Departments' ? /新增部门/ : /新增菜单/)
|
|
}
|
|
})
|
|
|
|
test(`${viewName} 表单异步验证期间切公司再切回不提交旧数据,原对话框关闭`, async () => {
|
|
const { fixture, module } = await loadView(viewName)
|
|
const blocked = deferred()
|
|
module.open()
|
|
module.formRef.value.validate = () => blocked.promise
|
|
Object.assign(module.form, { name: '旧公司样例', ...(viewName === 'Menus' ? { perms: 'company.fixture2.orders.list' } : {}) })
|
|
const saving = module.save()
|
|
fixture.group.selectCompany(3)
|
|
fixture.group.selectCompany(2)
|
|
blocked.resolve(true)
|
|
await saving
|
|
assert.equal(fixture.calls.length, 0)
|
|
assert.equal(module.visible.value, false)
|
|
assert.equal(module.saving.value, false)
|
|
})
|
|
|
|
test(`${viewName} 删除确认期间切公司再切回不提交;旧列表响应不能覆盖新公司`, async () => {
|
|
const { fixture, module } = await loadView(viewName)
|
|
const confirm = deferred()
|
|
fixture.onConfirm = () => confirm.promise
|
|
const deleting = module.remove(viewName === 'Departments' ? department : menu())
|
|
fixture.group.selectCompany(3)
|
|
fixture.group.selectCompany(2)
|
|
confirm.resolve()
|
|
await deleting
|
|
assert.equal(fixture.calls.length, 0)
|
|
const stale = deferred()
|
|
fixture.onGet = () => stale.promise
|
|
const oldLoad = module.load()
|
|
fixture.onGet = () => []
|
|
fixture.group.selectCompany(3)
|
|
await module.load()
|
|
stale.resolve([{ id: 991, name: '旧公司列表' }])
|
|
await oldLoad
|
|
assert.deepEqual(module.rows.value, [])
|
|
})
|
|
|
|
test(`${viewName} 保存成功后列表失败明确提示已保存,写失败保持表单`, async () => {
|
|
const { fixture, module } = await loadView(viewName)
|
|
module.open()
|
|
Object.assign(module.form, { name: '测试配置', ...(viewName === 'Menus' ? { perms: 'company.fixture2.orders.list' } : {}) })
|
|
fixture.onGet = () => { throw new Error('隔离读取失败') }
|
|
await module.save()
|
|
assert.deepEqual(fixture.events.map(event => event.type), ['success', 'warning'])
|
|
assert.match(fixture.events[1].message, /^变更已保存/)
|
|
module.open()
|
|
Object.assign(module.form, { name: '保留输入', ...(viewName === 'Menus' ? { perms: 'company.fixture2.orders.list' } : {}) })
|
|
fixture.onPost = () => { throw new Error('隔离写入失败') }
|
|
await module.save()
|
|
assert.equal(module.visible.value, true)
|
|
assert.equal(module.form.name, '保留输入')
|
|
assert.equal(fixture.events.at(-1).type, 'error')
|
|
})
|
|
|
|
test(`${viewName} 已发出的写入始终属于原公司,切换后不刷新旧结果;重复点击不多写`, async () => {
|
|
const { fixture, module } = await loadView(viewName)
|
|
const blocked = deferred()
|
|
const started = deferred()
|
|
fixture.onPost = () => { started.resolve(); return blocked.promise }
|
|
module.open()
|
|
Object.assign(module.form, { name: '原公司配置', ...(viewName === 'Menus' ? { perms: 'company.fixture2.orders.list' } : {}) })
|
|
const saving = module.save()
|
|
await started.promise
|
|
await module.save()
|
|
module.open(viewName === 'Menus' ? menu() : department)
|
|
assert.equal(module.form.id, 0)
|
|
fixture.group.selectCompany(3)
|
|
blocked.resolve()
|
|
await saving
|
|
assert.equal(fixture.calls.length, 1)
|
|
assert.equal(fixture.calls[0].company, 2)
|
|
assert.equal(fixture.events.length, 0)
|
|
assert.equal(fixture.refreshes, 0)
|
|
assert.equal(module.visible.value, false)
|
|
assert.equal(module.saving.value, false)
|
|
})
|
|
}
|
|
|
|
test('医院部门保留顶级保护和原按钮授权,普通新增不获得集团能力', async () => {
|
|
const view = await loadView('Departments', { default_company_id: 1 })
|
|
const { fixture, module } = view
|
|
module.open(department)
|
|
assert.equal(module.visible.value, false)
|
|
assert.doesNotMatch(await html(view), /新增部门/)
|
|
fixture.auth.can = () => true
|
|
module.open(department)
|
|
assert.equal(module.protectedParent.value, true)
|
|
await module.remove(department)
|
|
assert.equal(fixture.confirms, 0)
|
|
await module.save()
|
|
assert.equal(fixture.calls[0].url, '/auth.dept/edit')
|
|
assert.equal(fixture.refreshes, 1)
|
|
})
|
|
|
|
test('医院菜单原路径、组件和权限原样保存;standalone路径限制保持不变', async () => {
|
|
const { fixture, module } = await loadView('Menus', { default_company_id: 1 })
|
|
fixture.auth.can = () => true
|
|
const original = menu({ paths: 'legacy/group', component: 'legacy/layout', perms: 'legacy/entry', source_secret: 'omit' })
|
|
module.open(original)
|
|
await module.save()
|
|
const payload = fixture.calls[0].payload
|
|
assert.equal(payload.paths, original.paths)
|
|
assert.equal(payload.component, original.component)
|
|
assert.equal(payload.perms, original.perms)
|
|
assert.equal('source_secret' in payload, false)
|
|
fixture.auth.isShared = false
|
|
fixture.group.configure(false)
|
|
module.form.type = 'C'
|
|
let error
|
|
module.pathRules[0].validator({}, 'legacy/group', result => { error = result })
|
|
assert.ok(error instanceof Error)
|
|
module.pathRules[0].validator({}, '/orders', result => { error = result })
|
|
assert.equal(error, undefined)
|
|
})
|