Files
zyt/admin/tests/doctor-web-consultation.test.cjs
T
2026-10-27 16:46:50 +08:00

420 lines
24 KiB
JavaScript

const assert = require('node:assert/strict')
const fs = require('node:fs')
const path = require('node:path')
const test = require('node:test')
const ts = require('typescript')
const vue = require('vue')
const { renderToString } = require('@vue/server-renderer')
const { parse, compileScript, compileTemplate } = require('@vue/compiler-sfc')
const read = name => fs.readFileSync(path.join(__dirname, '../src', name), 'utf8')
function moduleFrom(source, dependencies = require, globals = {}) {
const code = ts.transpileModule(source, {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 }
}).outputText
const module = { exports: {} }
new Function('require', 'module', 'exports', ...Object.keys(globals), code)(dependencies, module, module.exports, ...Object.values(globals))
return module.exports
}
const policy = moduleFrom(read('utils/doctor-web-consultation.ts'))
const cutoff = Date.parse('2026-10-24T00:00:00+08:00')
const schedule = {
cutoff_at: '2026-10-24T00:00:00+08:00',
approaching_at: '2026-10-22T00:00:00+08:00',
urgent_at: '2026-10-23T00:00:00+08:00',
server_time: cutoff / 1000
}
const doctor = { root: 0, role_ids: [1] }
const installer = {
platform: 'windows_x64', label: 'Windows 64位',
url: 'https://cdn.example.test/doctor-setup.exe',
filename: 'doctor-setup.exe', sha256: 'a'.repeat(64), size: 171474334, type: 'inno_setup'
}
test('doctors can use the web throughout October 23, and stop exactly at Shanghai midnight', () => {
assert.equal(Date.parse(schedule.cutoff_at), Date.parse('2026-10-23T16:00:00Z'))
assert.equal(policy.isDoctorWebConsultationBlocked(doctor, schedule, cutoff - 1), false)
assert.equal(policy.isDoctorWebConsultationBlocked(doctor, schedule, cutoff), true)
assert.equal(policy.isDoctorWebConsultationBlocked(doctor, schedule, cutoff + 1), true)
for (const user of [{ root: 1, role_ids: [1] }, { role_ids: [2] }, { role_ids: [3, 7, 8] }, {}]) {
assert.equal(policy.isDoctorWebConsultationBlocked(user, schedule, cutoff), false)
}
assert.equal(policy.isDoctorWebConsultationBlocked({ role_ids: ['2', '1'] }, schedule, cutoff), true)
})
test('the mounted page changes at midnight, rechecks clicks and keeps a previously synchronized clock', () => {
let clock = cutoff - 10000
const mounted = [], unmounted = [], warnings = []
let tick
const listeners = new Map()
const surface = { addEventListener: (name, callback) => listeners.set(name, callback), removeEventListener: name => listeners.delete(name) }
// The profile was fetched earlier; opening a new page must not reset to that old server timestamp.
const store = vue.reactive({ userInfo: { ...doctor, web_consultation_policy: schedule }, serverTimeOffsetMs: 5000 })
const hook = moduleFrom(read('hooks/useDoctorWebConsultation.ts'), name => {
if (name === 'vue') return { ...vue, onMounted: fn => mounted.push(fn), onUnmounted: fn => unmounted.push(fn) }
if (name === '@/stores/modules/user') return { default: () => store }
if (name === '@/api/app') return { getDoctorWebConsultationPolicy: () => new Promise(() => {}) }
if (name === '@/utils/feedback') return { default: { msgWarning: text => warnings.push(text) } }
if (name === '@/utils/doctor-web-consultation') return policy
throw new Error(`Unexpected import: ${name}`)
}, { Date: { now: () => clock }, window: surface, document: surface, setInterval: fn => { tick = fn; return 1 }, clearInterval: () => { tick = undefined } })
const state = hook.useDoctorWebConsultation()
mounted.forEach(fn => fn())
assert.equal(state.webConsultationBlocked.value, false)
clock = cutoff - 5000
tick()
assert.equal(state.webConsultationBlocked.value, true)
assert.equal(state.ensureWebConsultationAllowed(), false)
assert.match(warnings[0], /桌面应用/)
clock = cutoff - 5001
listeners.get('focus')()
assert.equal(state.webConsultationBlocked.value, false)
clock = cutoff - 5000
// Even if a suspended tab's timer has not fired, the click itself checks the clock.
assert.equal(state.ensureWebConsultationAllowed(), false)
const laterPage = hook.useDoctorWebConsultation()
assert.equal(laterPage.webConsultationBlocked.value, true)
unmounted.forEach(fn => fn())
assert.equal(listeners.size, 0)
assert.equal(tick, undefined)
})
test('the shared system notice keeps installer downloads available throughout all reminder phases', async () => {
const { descriptor } = parse(read('components/doctor-web-consultation-notice/index.vue'))
const script = compileScript(descriptor, { id: 'doctor-web-notice' })
const template = compileTemplate({ source: descriptor.template.content, filename: 'notice.vue', id: 'doctor-web-notice', compilerOptions: { bindingMetadata: script.bindings } })
assert.deepEqual(template.errors, [])
const render = moduleFrom(template.code).render
async function markup(date, packages = [installer], failed = false, loading = false) {
const component = moduleFrom(script.content, name => {
if (name === 'vue') return vue
if (name === '@/hooks/useDoctorWebConsultation') return { useDoctorWebConsultation: () => ({ consultationReminder: vue.ref(policy.doctorWebConsultationReminder(schedule, Date.parse(date))), policyLoadFailed: vue.ref(false), refreshConsultationPolicy() {} }) }
if (name === '@/hooks/useDesktopWorkstationDownloads') return {
useDesktopWorkstationDownloads: () => ({ downloads: vue.ref({ version: '1.4.8', packages }), downloadsLoading: vue.ref(loading), downloadsFailed: vue.ref(failed), loadDownloads() {} })
}
if (name === '@element-plus/icons-vue') return { Download: { render: () => vue.h('svg') } }
throw new Error(name)
})
const state = component.default.setup({}, { expose() {} })
const app = vue.createSSRApp({ render: () => render({}, [], {}, vue.proxyRefs(state)) })
app.component('el-alert', { props: ['title', 'type', 'closable'], setup: (props, { slots }) => () => vue.h('section', { role: 'alert', 'data-type': props.type, 'data-closable': String(props.closable) }, [vue.h('strong', props.title), slots.default?.()]) })
app.component('el-icon', { setup: (_, { slots }) => () => vue.h('span', slots.default?.()) })
app.component('el-button', { setup: (_, { slots }) => () => vue.h('button', slots.default?.()) })
return renderToString(app)
}
const before = await markup('2026-10-20T10:00:00+08:00')
assert.match(before, /2026年10月24日00:00(北京时间)/)
assert.match(before, /接诊台、问诊列表/)
assert.match(before, /data-closable="false"/)
assert.match(before, /data-type="info"/)
assert.match(before, /href="https:\/\/cdn.example.test\/doctor-setup.exe"/)
assert.match(before, /下载 Windows 64位安装包/)
assert.match(before, /当前版本 v1.4.8/)
assert.match(before, /Windows 10 1809/)
const approaching = await markup('2026-10-22T12:00:00+08:00')
assert.match(approaching, /data-type="warning"/)
assert.match(approaching, /距网页端面诊停用还有 1天12小时/)
const lastDay = await markup('2026-10-23T23:59:59+08:00')
assert.match(lastDay, /最后提醒/)
assert.match(lastDay, /不足1分钟/)
assert.match(lastDay, /data-type="error"/)
const after = await markup('2026-10-24T00:00:00+08:00')
assert.match(after, /网页端面诊已停用/)
assert.match(after, /桌面应用/)
assert.match(after, /data-type="error"/)
assert.match(after, /href="https:\/\/cdn.example.test\/doctor-setup.exe"/)
assert.doesNotMatch(after, /距网页端面诊停用还有/)
const missing = await markup('2026-10-20T10:00:00+08:00', [])
assert.match(missing, /安装包暂未发布/)
assert.match(missing, /重新获取/)
assert.doesNotMatch(missing, /href=/)
assert.match(await markup('2026-10-20T10:00:00+08:00', [], true), /安装包加载失败/)
assert.match(await markup('2026-10-20T10:00:00+08:00', [], false, true), /正在获取安装包/)
})
test('reminders switch exactly at Beijing midnight on October 22, 23 and 24', () => {
for (const [boundary, previous, current] of [
['2026-10-22T00:00:00+08:00', 'prepare', 'approaching'],
['2026-10-23T00:00:00+08:00', 'approaching', 'last_day'],
['2026-10-24T00:00:00+08:00', 'last_day', 'expired']
]) {
const time = Date.parse(boundary)
assert.equal(policy.doctorWebConsultationReminder(schedule, time - 1).phase, previous)
assert.equal(policy.doctorWebConsultationReminder(schedule, time).phase, current)
}
assert.equal(policy.doctorWebConsultationReminder(schedule, Date.parse('2026-10-23T15:59:59Z')).phase, 'last_day')
assert.equal(policy.doctorWebConsultationReminder(schedule, Date.parse('2026-10-23T16:00:00Z')).phase, 'expired')
})
test('an open page advances through each reminder stage without refreshing or changing the cutoff', () => {
let clock = Date.parse('2026-10-21T23:59:59+08:00')
let tick
const mounted = [], unmounted = []
const surface = { addEventListener() {}, removeEventListener() {} }
const hook = moduleFrom(read('hooks/useDoctorWebConsultation.ts'), name => {
if (name === 'vue') return { ...vue, onMounted: fn => mounted.push(fn), onUnmounted: fn => unmounted.push(fn) }
if (name === '@/stores/modules/user') return { default: () => ({ userInfo: { ...doctor, web_consultation_policy: schedule }, serverTimeOffsetMs: 0 }) }
if (name === '@/api/app') return { getDoctorWebConsultationPolicy: () => new Promise(() => {}) }
if (name === '@/utils/feedback') return { default: { msgWarning() {} } }
if (name === '@/utils/doctor-web-consultation') return policy
throw new Error(name)
}, { Date: { now: () => clock }, window: surface, document: surface, setInterval: fn => { tick = fn; return 1 }, clearInterval() {} })
const state = hook.useDoctorWebConsultation()
mounted.forEach(fn => fn())
assert.equal(state.consultationReminder.value.phase, 'prepare')
for (const [day, phase] of [[22, 'approaching'], [23, 'last_day'], [24, 'expired']]) {
clock = Date.parse(`2026-10-${day}T00:00:00+08:00`)
tick()
assert.equal(state.consultationReminder.value.phase, phase)
assert.equal(state.webConsultationBlocked.value, day === 24)
}
unmounted.forEach(fn => fn())
})
function shiftedSchedule(cutoffAt, serverTime, approachingHours = 48, urgentHours = 24) {
const time = Date.parse(cutoffAt)
return {
cutoff_at: cutoffAt,
approaching_at: new Date(time - approachingHours * 3600000).toISOString(),
urgent_at: new Date(time - urgentHours * 3600000).toISOString(),
server_time: serverTime / 1000
}
}
test('arbitrary configured dates and hours drive announcements, reminders and enforcement to the second', () => {
const custom = shiftedSchedule('2027-06-15T14:35:12+08:00', cutoff, 10, 2)
const end = Date.parse(custom.cutoff_at)
const approaching = Date.parse(custom.approaching_at)
const urgent = Date.parse(custom.urgent_at)
assert.deepEqual(policy.normalizeDoctorWebConsultationPolicy(custom), custom)
for (const [time, phase] of [[approaching - 1, 'prepare'], [approaching, 'approaching'], [urgent - 1, 'approaching'], [urgent, 'last_day'], [end - 1, 'last_day'], [end, 'expired']]) {
const reminder = policy.doctorWebConsultationReminder(custom, time)
assert.equal(reminder.phase, phase)
assert.match(reminder.description, /2027年06月15日14:35:12(北京时间)/)
assert.doesNotMatch(reminder.description, /2026年|今天结束|最后一天/)
assert.equal(policy.isDoctorWebConsultationBlocked(doctor, custom, time), time >= end)
}
assert.equal(policy.doctorWebConsultationDate({ ...custom, cutoff_at: '2027-06-15T06:35:12Z' }), '2027年06月15日14:35:12(北京时间)')
assert.equal(policy.isDoctorWebConsultationBlocked(doctor, undefined, end), false)
assert.equal(policy.doctorWebConsultationReminder().countdown, '')
for (const invalid of [null, {}, { ...custom, cutoff_at: 'invalid' }, { ...custom, approaching_at: '2027-06-16T00:00:00+08:00' }, { ...custom, server_time: 0 }, { ...custom, urgent_at: '2027-06-15 13:00:00' }]) {
assert.equal(policy.normalizeDoctorWebConsultationPolicy(invalid), undefined)
}
})
test('open notices share live configuration, poll every minute and refresh on focus with failure recovery', async () => {
let clock = Date.parse('2027-06-15T14:00:00+08:00')
let requests = 0, resolveRequest, rejectRequest
const mounted = [], unmounted = [], ticks = new Set(), listeners = new Map()
const surface = {
visibilityState: 'visible',
addEventListener(name, callback) {
if (!listeners.has(name)) listeners.set(name, new Set())
listeners.get(name).add(callback)
},
removeEventListener(name, callback) { listeners.get(name)?.delete(callback) }
}
const store = vue.reactive({ userInfo: { ...doctor, web_consultation_policy: schedule }, serverTimeOffsetMs: 0 })
const hook = moduleFrom(read('hooks/useDoctorWebConsultation.ts'), name => {
if (name === 'vue') return { ...vue, onMounted: fn => mounted.push(fn), onUnmounted: fn => unmounted.push(fn) }
if (name === '@/stores/modules/user') return { default: () => store }
if (name === '@/api/app') return {
getDoctorWebConsultationPolicy: () => {
requests++
return new Promise((resolve, reject) => { resolveRequest = resolve; rejectRequest = reject })
}
}
if (name === '@/utils/feedback') return { default: { msgWarning() {} } }
if (name === '@/utils/doctor-web-consultation') return policy
throw new Error(name)
}, {
Date: { now: () => clock }, window: surface, document: surface,
setInterval: fn => { ticks.add(fn); return fn }, clearInterval: fn => ticks.delete(fn)
})
const first = hook.useDoctorWebConsultation()
const second = hook.useDoctorWebConsultation()
assert.equal(first.webConsultationBlocked.value, true)
mounted.forEach(fn => fn())
assert.equal(requests, 1)
const initial = first.refreshConsultationPolicy()
assert.equal(second.refreshConsultationPolicy(), initial)
resolveRequest(shiftedSchedule('2027-06-15T14:35:12+08:00', clock, 10, 2))
await initial
assert.equal(first.webConsultationBlocked.value, false)
assert.equal(second.webConsultationBlocked.value, false)
assert.match(first.consultationReminder.value.description, /2027年06月15日14:35:12/)
clock += 59000
ticks.forEach(fn => fn())
assert.equal(requests, 1)
clock += 1000
ticks.forEach(fn => fn())
assert.equal(requests, 2)
const polled = first.refreshConsultationPolicy()
resolveRequest(shiftedSchedule('2027-06-15T13:59:00+08:00', clock))
await polled
assert.equal(second.webConsultationBlocked.value, true)
assert.match(second.webConsultationMessage.value, /2027年06月15日13:59/)
listeners.get('focus').forEach(fn => fn())
assert.equal(requests, 3)
const failed = first.refreshConsultationPolicy()
rejectRequest(new Error('offline'))
await failed
assert.equal(first.policyLoadFailed.value, true)
assert.equal(second.webConsultationBlocked.value, true)
listeners.get('visibilitychange').forEach(fn => fn())
assert.equal(requests, 4)
const retry = second.refreshConsultationPolicy()
resolveRequest(shiftedSchedule('2028-01-01T12:30:00+08:00', clock))
await retry
assert.equal(first.policyLoadFailed.value, false)
assert.equal(second.webConsultationBlocked.value, false)
assert.match(first.consultationReminder.value.description, /2028年01月01日12:30/)
const invalid = first.refreshConsultationPolicy()
resolveRequest({ cutoff_at: 'invalid' })
await invalid
assert.equal(first.policyLoadFailed.value, true)
assert.match(first.consultationReminder.value.description, /2028年01月01日12:30/)
unmounted.forEach(fn => fn())
assert.equal(ticks.size, 0)
assert.ok([...listeners.values()].every(callbacks => callbacks.size === 0))
})
test('the runtime policy endpoint is public and requests a fresh response', async () => {
let transport
const api = moduleFrom(read('api/app.ts'), name => {
if (name === '@/utils/request') return { default: { get: (...args) => { transport = args; return Promise.resolve(schedule) } } }
throw new Error(name)
})
assert.deepEqual(await api.getDoctorWebConsultationPolicy(), schedule)
assert.equal(transport[0].url, '/config/doctorWebConsultation')
assert.ok(transport[0].params._t > 0)
assert.equal(transport[1].withToken, false)
})
test('installer requests are public, deduplicated across notices, cached, and recover after failure', async () => {
let requests = 0, resolve
const mounted = [], unmounted = []
const api = { getDesktopWorkstationDownloads: () => { requests++; return new Promise(done => { resolve = done }) } }
const mod = moduleFrom(read('hooks/useDesktopWorkstationDownloads.ts'), name => {
if (name === 'vue') return { ...vue, onMounted: fn => mounted.push(fn), onUnmounted: fn => unmounted.push(fn) }
if (name === '@/api/setting/desktop_workstation') return api
throw new Error(name)
}, { window: { addEventListener() {}, removeEventListener() {} } })
const first = mod.useDesktopWorkstationDownloads()
const second = mod.useDesktopWorkstationDownloads()
const pending = first.loadDownloads()
assert.equal(second.loadDownloads(), pending)
assert.equal(requests, 1)
resolve({ version: '1.4.8', packages: [installer] })
await pending
await second.loadDownloads()
assert.equal(requests, 1)
assert.equal(second.downloads.value.packages.length, 1)
api.getDesktopWorkstationDownloads = async () => { throw new Error('offline') }
await first.loadDownloads(true)
assert.equal(first.downloadsFailed.value, true)
assert.equal(first.downloads.value.packages.length, 1)
api.getDesktopWorkstationDownloads = async () => ({ version: '1.4.9', packages: [installer] })
await second.loadDownloads(true)
assert.equal(first.downloadsFailed.value, false)
assert.equal(first.downloads.value.version, '1.4.9')
assert.deepEqual(mod.normalizeDesktopDownloads({ version: '1', packages: [null, { ...installer, url: 'javascript:alert(1)' }, { ...installer, url: 'https://user:pass@example.test/setup.exe' }, { ...installer, sha256: '' }] }).packages, [])
assert.equal(mod.normalizeDesktopDownloads({ version: '1', packages: [installer, installer] }).packages.length, 1)
unmounted.forEach(fn => fn())
let transport
const apiModule = moduleFrom(read('api/setting/desktop_workstation.ts'), name => {
if (name === '@/utils/request') return { default: { get: (...args) => { transport = args; return Promise.resolve({}) } } }
throw new Error(name)
})
await apiModule.getDesktopWorkstationDownloads()
assert.equal(transport[0].url, '/setting.desktop_workstation/downloads')
assert.equal(transport[1].withToken, false)
})
test('consultation entries retain the shared notice while the patient list compiles without it', () => {
for (const name of ['views/patient/reception/index.vue', 'views/tcm/diagnosis/index.vue', 'views/tcm/appointment/list.vue', 'views/tcm/appointment/list_h5.vue']) {
const { descriptor, errors } = parse(read(name), { filename: name })
assert.deepEqual(errors, [])
const script = compileScript(descriptor, { id: name })
assert.equal(script.bindings.DoctorWebConsultationNotice, name === 'views/tcm/diagnosis/index.vue' ? undefined : 'setup-const')
assert.deepEqual(compileTemplate({ source: descriptor.template.content, filename: name, id: name, compilerOptions: { bindingMetadata: script.bindings } }).errors, [])
}
})
test('reception makes doctor cutoff visible and blocks calls while preserving administrator and assistant access', async () => {
const { descriptor } = parse(read('views/patient/reception/index.vue'))
const script = compileScript(descriptor, { id: 'reception-cutoff' })
const template = compileTemplate({ source: descriptor.template.content, filename: 'reception.vue', id: 'reception-cutoff', compilerOptions: { bindingMetadata: script.bindings } })
assert.deepEqual(template.errors, [])
const render = moduleFrom(template.code).render
const passthrough = { setup: (_, { slots }) => () => vue.h('div', slots.default?.()) }
const lifecycle = { ...vue, onMounted() {}, onUnmounted() {}, defineAsyncComponent: () => passthrough }
let clock = cutoff - 1
const store = vue.reactive({ userInfo: { ...doctor, web_consultation_policy: schedule }, serverTimeOffsetMs: 0 })
const warnings = [], requests = [], opened = []
const feedback = { msgWarning: message => warnings.push(message) }
const hook = moduleFrom(read('hooks/useDoctorWebConsultation.ts'), name => {
if (name === 'vue') return lifecycle
if (name === '@/stores/modules/user') return { default: () => store }
if (name === '@/api/app') return {}
if (name === '@/utils/feedback') return { default: feedback }
if (name === '@/utils/doctor-web-consultation') return policy
throw new Error(name)
}, { Date: { now: () => clock } })
let onSignature = () => ({})
const state = moduleFrom(script.content, name => {
if (name === 'vue') return lifecycle
if (name === '@/hooks/useDoctorWebConsultation') return hook
if (name === '@/api/patient' || name === '@/api/doctor') return {}
if (name === '@/api/tcm') return { getCallSignature: async params => { requests.push(params); return onSignature() } }
if (name === '@/utils/feedback') return { default: feedback }
if (name === '@/utils/diag-display') return { formatGender: () => '男' }
if (name === '@/utils/diabetes-discovery-display') return {}
if (name === '@element-plus/icons-vue') return Object.fromEntries(['Phone', 'Search', 'ChatDotRound', 'Loading'].map(key => [key, passthrough]))
if (name.endsWith('.vue')) return { default: passthrough }
throw new Error(name)
}, { ref: vue.ref, computed: vue.computed, watch: vue.watch }).default.setup({}, { expose() {} })
const row = { id: 90, patient_id: 50, source_patient_id: 50, diagnosis_id: 70, patient_name: '测试患者', appointment_type: 'video' }
state.queue.value = [row]
state.chatDialogRef.value = { open: value => opened.push(value) }
async function markup() {
const app = vue.createSSRApp({ render: () => render({}, [], {}, vue.proxyRefs(state)) })
app.config.warnHandler = () => {}
for (const name of ['el-input', 'el-icon', 'el-tag', 'el-empty', 'el-dialog', 'el-button']) app.component(name, passthrough)
app.component('el-tooltip', { props: ['content'], setup: (props, { slots }) => () => vue.h('div', { 'data-tooltip': props.content }, slots.default?.()) })
for (const name of ['loading', 'perms']) app.directive(name, { getSSRProps: () => ({}) })
return renderToString(app)
}
assert.match(await markup(), /class="row-icon-btn call" aria-label="发起通话"/)
await state.handleCall(row)
assert.equal(requests.length, 1)
assert.equal(opened.length, 1)
// A signature that returns after the deadline must never open the calling window.
onSignature = () => { clock = cutoff; return {} }
await state.handleCall(row)
assert.equal(requests.length, 2)
assert.equal(opened.length, 1)
const expired = await markup()
assert.match(expired, /class="row-icon-btn call" disabled aria-label="[^"]*桌面应用/)
assert.match(expired, /<span>已停用<\/span>/)
assert.match(expired, /data-tooltip="[^"]*桌面应用/)
assert.doesNotMatch(expired, /class="row-icon-btn notify" disabled/)
await state.handleCall(row)
assert.equal(requests.length, 2)
assert.equal(opened.length, 1)
assert.equal(warnings.length, 2)
for (const identity of [{ root: 1, role_ids: [1] }, { root: 0, role_ids: [2] }]) {
Object.assign(store.userInfo, identity)
assert.match(await markup(), /class="row-icon-btn call" aria-label="发起通话"/)
assert.doesNotMatch(await markup(), /<span>已停用<\/span>/)
await state.handleCall(row)
}
assert.equal(requests.length, 4)
assert.equal(opened.length, 3)
})