i
This commit is contained in:
gr
2026-10-22 11:12:29 +08:00
480 changed files with 9840 additions and 953 deletions
+34 -2
View File
@@ -26,15 +26,19 @@ const render = moduleFrom(template.code).render
const passthrough = { setup: (_, { slots }) => () => vue.h('div', [slots.default?.(), slots.headerToolbar?.()]) }
const picker = text => ({ setup: () => () => vue.h('button', text) })
function chat(policy = {}) {
function chat(policy = {}, migrationBlocked = vue.ref(false)) {
const requests = [], warnings = [], sdkCalls = []
const guard = moduleFrom(read('utils/appointment-call-guard.ts'))
const server = Object.fromEntries(['calls', 'call', 'groupCall'].map(name => [name, async params => { sdkCalls.push({ name, params }) }]))
const server = Object.fromEntries(['calls', 'call', 'groupCall', 'accept'].map(name => [name, async params => { sdkCalls.push({ name, params }) }]))
const api = { getCallSignature: async params => { requests.push(params); return policy } }
const result = moduleFrom(script.content, name => {
if (name === 'vue') return { ...vue, onMounted() {}, onUnmounted() {} }
if (name === '@/utils/appointment-type') return types
if (name === '@/utils/appointment-call-guard') return guard
if (name === '@/hooks/useDoctorWebConsultation') return {
useDoctorWebConsultation: () => ({ webConsultationBlocked: migrationBlocked, webConsultationMessage: vue.ref('网页端面诊已停用,请医生使用桌面应用进行面诊。'), ensureWebConsultationAllowed: () => !migrationBlocked.value })
}
if (name === '@/utils/doctor-web-consultation') return moduleFrom(read('utils/doctor-web-consultation.ts'))
if (name === '@/utils/im-chat-archive-trigger') return moduleFrom(read('utils/im-chat-archive-trigger.ts'))
if (name === '@/api/tcm') return api
if (name === '@/utils/feedback') return { default: { msgWarning: text => warnings.push(text) } }
@@ -144,3 +148,31 @@ test('singleton call guard switches to current chat and cancels a pending old co
releaseNew()
await assert.rejects(guard.checkAppointmentOutgoingCall({ type: 2 }), /先打开/)
})
test('a cached video session stops every outgoing SDK path and incoming accept after migration', async () => {
const blocked = vue.ref(false)
const { state, server, sdkCalls, requests } = chat(policy('video'), blocked)
state.installTUICallKitRoomHooks()
assert.equal(state.canVideoCall.value, true)
blocked.value = true
assert.equal(state.canVideoCall.value, false)
assert.equal(state.canAudioCall.value, false)
for (const method of ['call', 'calls', 'groupCall', 'accept']) {
await assert.rejects(server[method]({ type: 2 }), /桌面应用/)
}
await state.startGroupVideoCall()
assert.deepEqual(sdkCalls, [])
assert.deepEqual(requests, [])
})
test('a signature request spanning the deadline never reaches the calling SDK', async () => {
const blocked = vue.ref(false)
const { state, server, sdkCalls, api } = chat(policy('video'), blocked)
state.installTUICallKitRoomHooks()
api.getCallSignature = async () => {
blocked.value = true
return policy('video')
}
await assert.rejects(server.calls({ type: 2 }), /桌面应用/)
assert.deepEqual(sdkCalls, [])
})
@@ -0,0 +1,214 @@
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 { parse, compileScript, compileTemplate } = require('@vue/compiler-sfc')
const { renderToString } = require('@vue/server-renderer')
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 util = moduleFrom(read('utils/consultation-transcripts.ts'))
const row = (id, diagnosis = 101, text = `医生:记录${id}的问题\n患者:记录${id}的回答`) => ({
id, diagnosis_id: diagnosis, call_type: 2, status: 2, start_time: 1792444800,
start_time_text: '2026-10-20 09:20:00', end_time_text: '2026-10-20 09:30:00',
duration_text: '10分钟', transcript_text: text, transcription_status: 'completed', transcription_segment_count: 2
})
const drain = () => new Promise(resolve => setImmediate(resolve))
test('each call keeps its own transcript even when multiple visits have the same date', () => {
const rows = util.normalizeConsultationRecords([row(10), row(11), row(12, 202, '串诊单文字'), row(10), null, { id: 0 }], 101)
assert.deepEqual(rows.map(item => item.id), [11, 10])
assert.equal(rows[0].transcript_text, row(11).transcript_text)
assert.equal(rows[1].transcript_text, row(10).transcript_text)
assert.throws(() => util.normalizeConsultationRecords({ lists: [] }, 101), /格式异常/)
const legacy = util.normalizeConsultationRecords([{ id: '13', transcript_text: '医生:你好\r\n患者:你好' }], 101)[0]
assert.equal(legacy.diagnosis_id, 101)
assert.equal(legacy.transcript_text, '医生:你好\n患者:你好')
})
test('running, partial and failed calls retain their saved words without pretending they are complete', () => {
for (const [status, label] of [['running', '录音转写中'], ['partial', '文字部分保存'], ['failed', '文字生成失败']]) {
const record = { ...row(1), transcription_status: status }
assert.equal(util.consultationTranscriptStatus(record).label, label)
assert.equal(util.consultationTranscriptText(record), row(1).transcript_text)
}
assert.match(util.consultationTranscriptEmptyText({ ...row(1), transcription_status: 'running', transcript_text: '' }), /正在转写/)
assert.match(util.consultationTranscriptEmptyText({ status: 3 }), /未接听/)
assert.match(util.consultationTranscriptEmptyText({ status: 4 }), /已取消/)
assert.equal(util.consultationTranscriptStatus({ transcript_text: '历史已保存文字' }).label, '文字已保存')
})
function hookFixture(initial = 101) {
const id = vue.ref(initial), requests = [], cleanup = []
const hook = moduleFrom(read('hooks/useConsultationTranscripts.ts'), name => {
if (name === 'vue') return { ...vue, onBeforeUnmount: fn => cleanup.push(fn) }
if (name === '@/api/tcm') return { getConsultationTranscripts: (params, signal) => new Promise((resolve, reject) => requests.push({ params, signal, resolve, reject })) }
if (name === '@/utils/consultation-transcripts') return util
throw new Error(name)
})
const scope = vue.effectScope()
const state = scope.run(() => hook.useConsultationTranscripts(() => id.value))
return { id, requests, state, dispose() { cleanup.forEach(fn => fn()); scope.stop() } }
}
test('changing diagnosis clears the old words immediately and ignores late responses and failures', async () => {
const f = hookFixture()
assert.deepEqual(f.requests[0].params, { diagnosis_id: 101 })
f.id.value = 202
assert.equal(f.requests[0].signal.aborted, true)
assert.deepEqual(f.state.records.value, [])
f.requests[1].resolve([row(20, 202), row(99, 101, '不属于该诊单')])
await drain()
assert.deepEqual(f.state.records.value.map(item => item.id), [20])
f.requests[0].reject(new Error('旧诊单请求失败'))
await drain()
assert.deepEqual(f.state.records.value.map(item => item.id), [20])
assert.equal(f.state.error.value, '')
f.id.value = 303
assert.deepEqual(f.state.records.value, [])
f.dispose()
assert.equal(f.requests[2].signal.aborted, true)
f.requests[2].resolve([row(30, 303)])
await drain()
assert.deepEqual(f.state.records.value, [])
})
test('manual refresh preserves current records on failure and recovers on retry without writes', async () => {
const f = hookFixture()
f.requests[0].resolve([row(10)])
await drain()
const failed = f.state.refresh()
f.requests[1].reject(new Error('网络连接失败'))
await failed
assert.equal(f.state.records.value[0].id, 10)
assert.equal(f.state.error.value, '网络连接失败')
assert.equal(f.state.loading.value, false)
const retried = f.state.refresh()
f.requests[2].resolve([row(11)])
await retried
assert.equal(f.state.error.value, '')
assert.equal(f.state.records.value[0].id, 11)
f.id.value = 0
assert.equal(f.requests.length, 3)
assert.deepEqual(f.state.records.value, [])
f.dispose()
})
const filename = 'views/tcm/diagnosis/components/ConsultationTranscriptPanel.vue'
const { descriptor, errors } = parse(read(filename), { filename })
assert.deepEqual(errors, [])
const script = compileScript(descriptor, { id: 'consultation-transcript-panel' })
const template = compileTemplate({ source: descriptor.template.content, filename, id: 'consultation-transcript-panel', compilerOptions: { bindingMetadata: script.bindings } })
assert.deepEqual(template.errors, [])
const render = moduleFrom(template.code).render
function panelFixture(records, extra = {}) {
const props = vue.reactive({ diagnosisId: 101 })
const data = { records: vue.ref(records), loading: vue.ref(false), error: vue.ref(''), refresh() {}, ...extra }
const copied = [], notices = []
const scope = vue.effectScope()
const component = moduleFrom(script.content, name => {
if (name === 'vue') return vue
if (name === '@/hooks/useConsultationTranscripts') return { useConsultationTranscripts: () => data }
if (name === '@/utils/consultation-transcripts') return util
if (name === '@/utils/feedback') return { default: { msgWarning: text => notices.push(text), msgSuccess: text => notices.push(text) } }
if (name === '@element-plus/icons-vue') return { Refresh: { render: () => vue.h('svg') }, Search: {} }
throw new Error(name)
}, { navigator: { clipboard: { writeText: async text => { copied.push(text) } } } })
const state = scope.run(() => component.default.setup(props, { expose() {} }))
async function html() {
const app = vue.createSSRApp({ render: () => render({}, [], props, vue.proxyRefs(state)) })
app.directive('loading', { getSSRProps: () => ({}) })
for (const name of ['el-button', 'el-icon', 'el-pagination']) app.component(name, { setup: (_, { slots }) => () => vue.h('span', slots.default?.()) })
app.component('el-tag', { props: ['type'], setup: (props, { slots }) => () => vue.h('span', { 'data-type': props.type }, slots.default?.()) })
app.component('el-empty', { props: ['description'], setup: props => () => vue.h('p', { class: 'empty-description' }, props.description) })
app.component('el-alert', { props: ['title'], setup: props => () => vue.h('p', { role: 'alert' }, props.title) })
app.component('el-input', { setup: () => () => vue.h('input') })
return renderToString(app)
}
return { props, state, data, copied, notices, html, dispose: () => scope.stop() }
}
test('the real panel selects one call, copies only its complete text, and escapes transcript HTML', async () => {
const f = panelFixture([row(12, 101, ''), row(11, 101, '医生:<img src=x onerror=alert(1)>\n患者:本次回答'), row(10), row(99, 202, '串诊单文字')])
assert.equal(f.state.selectedId.value, 11)
let html = await f.html()
assert.match(html, /&lt;img src=x onerror=alert\(1\)&gt;/)
assert.doesNotMatch(html, /<img src=x|串诊单文字/)
assert.doesNotMatch(html.match(/<pre[^>]*>([\s\S]*?)<\/pre>/)[1], /记录10/)
await f.state.copyTranscript()
assert.deepEqual(f.copied, ['医生:<img src=x onerror=alert(1)>\n患者:本次回答'])
f.state.selectedId.value = 10
assert.equal(f.state.selectedText.value, row(10).transcript_text)
f.data.records.value = [row(13), row(11), row(10)]
assert.equal(f.state.selectedId.value, 10)
f.state.search.value = '记录13'
assert.equal(f.state.selectedId.value, 13)
assert.equal(f.state.filteredRecords.value.length, 1)
f.props.diagnosisId = 202
assert.equal(f.state.selectedText.value, '')
assert.doesNotMatch(await f.html(), /记录13的问题|本次回答/)
f.dispose()
})
test('empty, failed and partial transcription states remain explicit in the rendered panel', async () => {
for (const status of ['running', 'partial', 'failed']) {
const f = panelFixture([{ ...row(1), transcription_status: status }])
const html = await f.html()
assert.match(html, /已保存|刷新查看最新/)
assert.match(html, /记录1的问题/)
f.dispose()
}
const missing = panelFixture([row(1, 101, '')])
assert.match(await missing.html(), /本次面诊暂无已保存的文字对话/)
missing.dispose()
const none = panelFixture([])
assert.match(await none.html(), /该诊单暂无面诊通话记录/)
none.dispose()
const failed = panelFixture([], { error: vue.ref('无权访问该诊单') })
assert.match(await failed.html(), /无权访问该诊单/)
assert.doesNotMatch(await failed.html(), /该诊单暂无面诊通话记录/)
failed.dispose()
})
test('the new tab is permission gated, lazy and absent when the drawer is closed', async () => {
const { descriptor } = parse(read('views/tcm/diagnosis/edit.vue'))
const editScript = compileScript(descriptor, { id: 'diagnosis-edit-transcript' })
const pane = descriptor.template.content.match(/<el-tab-pane\s+v-if="hasCallTranscriptPermission"[\s\S]*?<\/el-tab-pane>/)[0]
const compiled = compileTemplate({ source: pane, filename: 'edit-transcript-tab.vue', id: 'edit-transcript', compilerOptions: { bindingMetadata: editScript.bindings } })
assert.deepEqual(compiled.errors, [])
const renderPane = moduleFrom(compiled.code).render
async function html(allowed, active, visible, id) {
const state = { hasCallTranscriptPermission: allowed, activeTab: active, visible, formData: { id }, ConsultationTranscriptPanel: { props: ['diagnosisId'], setup: props => () => vue.h('div', { 'data-diagnosis': props.diagnosisId }, '真实转写面板入口') } }
const app = vue.createSSRApp({ render: () => renderPane({}, [], {}, state) })
app.component('el-tab-pane', { props: ['disabled', 'label'], setup: (props, { slots }) => () => vue.h('section', { 'data-disabled': String(props.disabled) }, [props.label, slots.default?.()]) })
app.component('el-empty', { props: ['description'], setup: props => () => vue.h('p', props.description) })
return renderToString(app)
}
assert.doesNotMatch(await html(false, 'callTranscript', true, 101), /面诊文字对话/)
assert.doesNotMatch(await html(true, 'basic', true, 101), /真实转写面板入口/)
assert.doesNotMatch(await html(true, 'callTranscript', false, 101), /真实转写面板入口/)
assert.match(await html(true, 'callTranscript', true, 101), /data-diagnosis="101"/)
assert.match(await html(true, 'callTranscript', true, ''), /data-disabled="true"/)
})
test('the read helper sends the exact diagnosis and abort signal without canceling replay requests', async () => {
let request
const api = moduleFrom(read('api/tcm.ts'), name => {
if (name === '@/utils/request') return { default: { get: (...args) => { request = args; return Promise.resolve([]) } } }
throw new Error(name)
})
const controller = new AbortController()
await api.getConsultationTranscripts({ diagnosis_id: 101 }, controller.signal)
assert.equal(request[0].url, '/tcm.diagnosis/getCallRecords')
assert.deepEqual(request[0].params, { diagnosis_id: 101 })
assert.equal(request[0].signal, controller.signal)
assert.equal(request[1].ignoreCancelToken, true)
})
@@ -0,0 +1,344 @@
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('the actual reception, diagnosis and both appointment list entries compile with the shared notice', () => {
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, 'setup-const')
assert.deepEqual(compileTemplate({ source: descriptor.template.content, filename: name, id: name, compilerOptions: { bindingMetadata: script.bindings } }).errors, [])
}
})