@@ -5,6 +5,14 @@ export function getConfig() {
|
||||
return request.get({ url: '/config/getConfig' })
|
||||
}
|
||||
|
||||
// 运行时读取医生网页面诊切换时间,与服务端拦截规则共用配置。
|
||||
export function getDoctorWebConsultationPolicy() {
|
||||
return request.get(
|
||||
{ url: '/config/doctorWebConsultation', params: { _t: Date.now() } },
|
||||
{ withToken: false, isOpenRetry: false }
|
||||
)
|
||||
}
|
||||
|
||||
// 工作台主页
|
||||
export function getWorkbench() {
|
||||
return request.get({ url: '/workbench/index' })
|
||||
|
||||
@@ -24,6 +24,24 @@ export type DesktopWorkstationConfig = {
|
||||
}
|
||||
}
|
||||
|
||||
export type DesktopWorkstationDownload = DesktopPackage & {
|
||||
platform: 'windows_x64' | 'macos_arm64' | 'macos_x64'
|
||||
label: string
|
||||
}
|
||||
|
||||
export type DesktopWorkstationDownloads = {
|
||||
version: string
|
||||
packages: DesktopWorkstationDownload[]
|
||||
}
|
||||
|
||||
// 仅返回已发布的安装包,不要求医生拥有系统设置权限。
|
||||
export function getDesktopWorkstationDownloads() {
|
||||
return request.get(
|
||||
{ url: '/setting.desktop_workstation/downloads' },
|
||||
{ withToken: false }
|
||||
) as Promise<DesktopWorkstationDownloads>
|
||||
}
|
||||
|
||||
export function getDesktopWorkstationConfig() {
|
||||
return request.get({
|
||||
url: '/setting.desktop_workstation/getConfig'
|
||||
|
||||
@@ -227,6 +227,29 @@ export function getCallRecords(params: any) {
|
||||
return request.get({ url: '/tcm.diagnosis/getCallRecords', params })
|
||||
}
|
||||
|
||||
export interface ConsultationCallRecord {
|
||||
id: number
|
||||
diagnosis_id: number
|
||||
call_type?: number
|
||||
status?: number
|
||||
start_time?: number
|
||||
start_time_text?: string
|
||||
end_time_text?: string
|
||||
duration_text?: string
|
||||
transcript_text?: string | null
|
||||
transcription_status?: string
|
||||
transcription_status_text?: string
|
||||
transcription_segment_count?: number
|
||||
}
|
||||
|
||||
/** 按诊单读取每次面诊已保存的文字;不触发语音识别或转写写入。 */
|
||||
export function getConsultationTranscripts(params: { diagnosis_id: number }, signal?: AbortSignal) {
|
||||
return request.get<ConsultationCallRecord[]>(
|
||||
{ url: '/tcm.diagnosis/getCallRecords', params, signal },
|
||||
{ ignoreCancelToken: true }
|
||||
)
|
||||
}
|
||||
|
||||
// 将 TRTC 房间号写入通话记录(与云端录制回调 room 关联)
|
||||
export function bindCallRoom(params: { diagnosis_id: number; room_id: string }) {
|
||||
return request.post({ url: '/tcm.diagnosis/bindCallRoom', params })
|
||||
|
||||
@@ -34,6 +34,7 @@
|
||||
|
||||
</div>
|
||||
</div>
|
||||
<DoctorWebConsultationNotice v-if="!isMinimized" />
|
||||
<div v-show="!isMinimized" class="chat-container">
|
||||
<div v-if="!isReady" class="loading-container">
|
||||
<el-icon class="is-loading"><Loading /></el-icon>
|
||||
@@ -131,6 +132,8 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, nextTick, watch, computed, onMounted, onUnmounted } from 'vue'
|
||||
import DoctorWebConsultationNotice from '@/components/doctor-web-consultation-notice/index.vue'
|
||||
import { useDoctorWebConsultation } from '@/hooks/useDoctorWebConsultation'
|
||||
import { Loading, Close, Rank, Camera, Fold, Expand } from '@element-plus/icons-vue'
|
||||
import { uploadImageBlob, uploadVideoBlob } from '@/api/file'
|
||||
import { addDoctorNote } from '@/api/patient'
|
||||
@@ -195,8 +198,9 @@ const appointmentTypeLabel = computed(() => confirmedTypeLabel.value || appointm
|
||||
const serverAllowsVideo = ref(false)
|
||||
const serverAllowsAudio = ref(false)
|
||||
const callDisabledReason = ref('正在确认挂号类型')
|
||||
const canVideoCall = computed(() => serverAllowsVideo.value && canAppointmentVideoCall(appointmentType.value))
|
||||
const canAudioCall = computed(() => serverAllowsAudio.value && (canAppointmentVideoCall(appointmentType.value) || appointmentType.value === 'phone'))
|
||||
const { webConsultationBlocked, webConsultationMessage, ensureWebConsultationAllowed } = useDoctorWebConsultation()
|
||||
const canVideoCall = computed(() => !webConsultationBlocked.value && serverAllowsVideo.value && canAppointmentVideoCall(appointmentType.value))
|
||||
const canAudioCall = computed(() => !webConsultationBlocked.value && serverAllowsAudio.value && (canAppointmentVideoCall(appointmentType.value) || appointmentType.value === 'phone'))
|
||||
let releaseAppointmentCallGuard: (() => void) | undefined
|
||||
let chatContextVersion = 0
|
||||
let outgoingCallType = 2
|
||||
@@ -253,6 +257,7 @@ function syncAppointmentCallPolicy(res: {
|
||||
}
|
||||
|
||||
async function prepareAppointmentCall(callType: number) {
|
||||
if (!ensureWebConsultationAllowed()) throw new Error(webConsultationMessage.value)
|
||||
const contextVersion = chatContextVersion
|
||||
const allowed = () => callType === 1 ? canAudioCall.value : canVideoCall.value
|
||||
if (!visible.value || !allowed()) {
|
||||
@@ -266,6 +271,7 @@ async function prepareAppointmentCall(callType: number) {
|
||||
})
|
||||
if (!visible.value || chatContextVersion !== contextVersion) throw new Error('当前问诊已切换,请重新发起通话')
|
||||
syncAppointmentCallPolicy(res)
|
||||
if (!ensureWebConsultationAllowed()) throw new Error(webConsultationMessage.value)
|
||||
if (!allowed()) {
|
||||
feedback.msgWarning(callDisabledReason.value)
|
||||
throw new Error(callDisabledReason.value)
|
||||
@@ -713,6 +719,14 @@ function installTUICallKitRoomHooks() {
|
||||
wrap('calls')
|
||||
wrap('call')
|
||||
wrap('groupCall')
|
||||
// 已登录 SDK 的旧聊天窗口也不能在截止后接起新面诊。
|
||||
const originalAccept = server.accept
|
||||
if (typeof originalAccept === 'function') {
|
||||
server.accept = async function patchedAccept(...args: unknown[]) {
|
||||
if (!ensureWebConsultationAllowed()) throw new Error(webConsultationMessage.value)
|
||||
return originalAccept.apply(server, args)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function doBindCallRoom(rid: string) {
|
||||
@@ -1099,6 +1113,7 @@ watch(() => activeConversation.value, async (newConversation) => {
|
||||
})
|
||||
|
||||
const open = async (data: { patientId: number; patientName: string; diagnosisId?: number; appointmentId?: number; appointmentType?: string | null }) => {
|
||||
if (!ensureWebConsultationAllowed()) return
|
||||
stopChatArchiveWatch(true)
|
||||
const contextVersion = ++chatContextVersion
|
||||
releaseAppointmentCallGuard?.()
|
||||
@@ -1260,6 +1275,7 @@ const open = async (data: { patientId: number; patientName: string; diagnosisId?
|
||||
|
||||
// 群组视频通话(多人通话):当前医生作为发起方,默认先邀请当前会话患者
|
||||
const startGroupVideoCall = async () => {
|
||||
if (!ensureWebConsultationAllowed()) return
|
||||
if (!canVideoCall.value) {
|
||||
feedback.msgWarning(appointmentType.value === 'text' ? '图文问诊不支持视频通话' : callDisabledReason.value)
|
||||
return
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
<template>
|
||||
<el-alert
|
||||
class="doctor-web-consultation-notice"
|
||||
:type="consultationReminder.type"
|
||||
:closable="false"
|
||||
show-icon
|
||||
:title="consultationReminder.title"
|
||||
>
|
||||
<p>{{ consultationReminder.description }}</p>
|
||||
<p v-if="policyLoadFailed">
|
||||
面诊切换时间更新失败,请重新获取最新设置。
|
||||
<el-button link type="primary" @click="refreshConsultationPolicy()">刷新切换时间</el-button>
|
||||
</p>
|
||||
<p v-if="consultationReminder.countdown" class="notice-countdown">
|
||||
距网页端面诊停用还有 {{ consultationReminder.countdown }}(北京时间)
|
||||
</p>
|
||||
<div class="notice-downloads">
|
||||
<a
|
||||
v-for="item in downloads.packages"
|
||||
:key="item.platform"
|
||||
class="installer-link"
|
||||
:href="item.url"
|
||||
:download="item.filename || undefined"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<el-icon><Download /></el-icon>
|
||||
下载 {{ item.label }}安装包
|
||||
</a>
|
||||
<span v-if="downloadsLoading && !downloads.packages.length">正在获取安装包…</span>
|
||||
<template v-else-if="!downloads.packages.length">
|
||||
<span>{{ downloadsFailed ? '安装包加载失败,请重试。' : '安装包暂未发布,请联系管理员获取。' }}</span>
|
||||
<el-button link type="primary" @click="loadDownloads(true)">重新获取</el-button>
|
||||
</template>
|
||||
<el-button v-else-if="downloadsFailed" link type="primary" @click="loadDownloads(true)">刷新安装包</el-button>
|
||||
</div>
|
||||
<p v-if="downloads.packages.length" class="install-instructions">
|
||||
<span v-if="downloads.version">当前版本 v{{ downloads.version }} · </span>
|
||||
安装完成后,使用当前医生账号登录桌面应用。
|
||||
</p>
|
||||
<p v-if="hasWindowsInstaller" class="install-instructions">
|
||||
Windows 安装包适用于 Windows 10 1809 及以上版本、Windows 11(64位)。
|
||||
</p>
|
||||
</el-alert>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { useDoctorWebConsultation } from '@/hooks/useDoctorWebConsultation'
|
||||
import { useDesktopWorkstationDownloads } from '@/hooks/useDesktopWorkstationDownloads'
|
||||
import { Download } from '@element-plus/icons-vue'
|
||||
import { computed, watch } from 'vue'
|
||||
|
||||
const { consultationReminder, policyLoadFailed, refreshConsultationPolicy } = useDoctorWebConsultation()
|
||||
const { downloads, downloadsLoading, downloadsFailed, loadDownloads } = useDesktopWorkstationDownloads()
|
||||
const hasWindowsInstaller = computed(() => downloads.value.packages.some(item => item.platform === 'windows_x64'))
|
||||
watch(() => consultationReminder.value.phase, () => { void loadDownloads(true) })
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.doctor-web-consultation-notice {
|
||||
flex-shrink: 0;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.doctor-web-consultation-notice p {
|
||||
margin: 4px 0 0;
|
||||
font-size: 14px;
|
||||
line-height: 1.7;
|
||||
}
|
||||
.notice-countdown {
|
||||
font-weight: 600;
|
||||
}
|
||||
.notice-downloads {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px 12px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
.installer-link {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 7px 12px;
|
||||
border-radius: 6px;
|
||||
color: #fff;
|
||||
background: #2563eb;
|
||||
font-size: 14px;
|
||||
line-height: 1.5;
|
||||
text-decoration: none;
|
||||
}
|
||||
.installer-link:hover {
|
||||
background: #1d4ed8;
|
||||
}
|
||||
.installer-link:focus-visible {
|
||||
outline: 2px solid #1d4ed8;
|
||||
outline-offset: 3px;
|
||||
}
|
||||
.doctor-web-consultation-notice .install-instructions {
|
||||
margin-top: 8px;
|
||||
font-size: 13px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,47 @@
|
||||
import { onBeforeUnmount, ref, watch } from 'vue'
|
||||
import { getConsultationTranscripts, type ConsultationCallRecord } from '@/api/tcm'
|
||||
import { normalizeConsultationRecords } from '@/utils/consultation-transcripts'
|
||||
|
||||
export function useConsultationTranscripts(diagnosisId: () => number) {
|
||||
const records = ref<ConsultationCallRecord[]>([])
|
||||
const loading = ref(false)
|
||||
const error = ref('')
|
||||
let sequence = 0
|
||||
let controller: AbortController | undefined
|
||||
|
||||
const refresh = async () => {
|
||||
const id = Number(diagnosisId())
|
||||
const request = ++sequence
|
||||
controller?.abort()
|
||||
error.value = ''
|
||||
if (!Number.isSafeInteger(id) || id <= 0) {
|
||||
records.value = []
|
||||
loading.value = false
|
||||
return
|
||||
}
|
||||
controller = new AbortController()
|
||||
loading.value = true
|
||||
try {
|
||||
const result = await getConsultationTranscripts({ diagnosis_id: id }, controller.signal)
|
||||
if (request !== sequence || Number(diagnosisId()) !== id) return
|
||||
records.value = normalizeConsultationRecords(result, id)
|
||||
} catch (reason: any) {
|
||||
if (request !== sequence || Number(diagnosisId()) !== id) return
|
||||
error.value = String(reason?.msg || reason?.message || '面诊文字对话加载失败,请重试')
|
||||
} finally {
|
||||
if (request === sequence) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(diagnosisId, () => {
|
||||
records.value = []
|
||||
void refresh()
|
||||
}, { immediate: true, flush: 'sync' })
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
sequence++
|
||||
controller?.abort()
|
||||
records.value = []
|
||||
})
|
||||
return { records, loading, error, refresh }
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { onMounted, onUnmounted, ref, shallowRef } from 'vue'
|
||||
import {
|
||||
getDesktopWorkstationDownloads,
|
||||
type DesktopWorkstationDownload,
|
||||
type DesktopWorkstationDownloads
|
||||
} from '@/api/setting/desktop_workstation'
|
||||
|
||||
// 接诊台、列表和聊天窗口共用一个请求与短缓存。
|
||||
const downloads = shallowRef<DesktopWorkstationDownloads>({ version: '', packages: [] })
|
||||
const downloadsLoading = ref(false)
|
||||
const downloadsFailed = ref(false)
|
||||
let pending: Promise<void> | undefined
|
||||
let loadedAt = 0
|
||||
const CACHE_MS = 5 * 60 * 1000
|
||||
|
||||
export function normalizeDesktopDownloads(value: DesktopWorkstationDownloads): DesktopWorkstationDownloads {
|
||||
const platforms = ['windows_x64', 'macos_arm64', 'macos_x64']
|
||||
const packages: DesktopWorkstationDownload[] = []
|
||||
const seen = new Set<string>()
|
||||
for (const item of Array.isArray(value?.packages) ? value.packages : []) {
|
||||
if (!item || typeof item !== 'object') continue
|
||||
if (!platforms.includes(item.platform) || seen.has(item.platform)) continue
|
||||
try {
|
||||
const url = new URL(item.url)
|
||||
if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password) continue
|
||||
if (!/^[a-f\d]{64}$/i.test(item.sha256)) continue
|
||||
packages.push({ ...item, url: url.href })
|
||||
seen.add(item.platform)
|
||||
} catch { /* 配置异常时不生成无效下载链接。 */ }
|
||||
}
|
||||
return { version: String(value?.version || ''), packages }
|
||||
}
|
||||
|
||||
export function useDesktopWorkstationDownloads() {
|
||||
const loadDownloads = (force = false): Promise<void> => {
|
||||
if (pending) return pending
|
||||
if (!force && loadedAt > 0 && Date.now() - loadedAt < CACHE_MS) return Promise.resolve()
|
||||
downloadsLoading.value = true
|
||||
downloadsFailed.value = false
|
||||
pending = getDesktopWorkstationDownloads().then(data => {
|
||||
downloads.value = normalizeDesktopDownloads(data)
|
||||
loadedAt = Date.now()
|
||||
}).catch(() => {
|
||||
downloadsFailed.value = true
|
||||
}).finally(() => {
|
||||
downloadsLoading.value = false
|
||||
pending = undefined
|
||||
})
|
||||
return pending
|
||||
}
|
||||
const refreshOnFocus = () => { void loadDownloads() }
|
||||
onMounted(() => {
|
||||
void loadDownloads()
|
||||
window.addEventListener('focus', refreshOnFocus)
|
||||
})
|
||||
onUnmounted(() => window.removeEventListener('focus', refreshOnFocus))
|
||||
|
||||
return { downloads, downloadsLoading, downloadsFailed, loadDownloads }
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
|
||||
import { getDoctorWebConsultationPolicy } from '@/api/app'
|
||||
import useUserStore from '@/stores/modules/user'
|
||||
import feedback from '@/utils/feedback'
|
||||
import {
|
||||
doctorWebConsultationMessage,
|
||||
doctorWebConsultationReminder,
|
||||
hasDoctorWebConsultationExpired,
|
||||
isConsultationDoctor,
|
||||
isDoctorWebConsultationBlocked,
|
||||
normalizeDoctorWebConsultationPolicy
|
||||
} from '@/utils/doctor-web-consultation'
|
||||
|
||||
// 多个列表、公告及聊天窗口共用请求;配置更新无需重新构建前端。
|
||||
let pending: Promise<void> | undefined
|
||||
let lastAttemptAt = 0
|
||||
const REFRESH_MS = 60 * 1000
|
||||
const policyLoadFailed = ref(false)
|
||||
|
||||
export function useDoctorWebConsultation() {
|
||||
const userStore = useUserStore()
|
||||
const now = ref(Date.now())
|
||||
let timer: ReturnType<typeof setInterval> | undefined
|
||||
const updateClock = () => { now.value = Date.now() + (userStore.serverTimeOffsetMs || 0) }
|
||||
const policy = computed(() => normalizeDoctorWebConsultationPolicy(userStore.userInfo.web_consultation_policy))
|
||||
|
||||
const loadPolicy = (force = false): Promise<void> => {
|
||||
if (pending) return pending
|
||||
if (!force && lastAttemptAt > 0 && Date.now() - lastAttemptAt < REFRESH_MS) return Promise.resolve()
|
||||
lastAttemptAt = Date.now()
|
||||
pending = getDoctorWebConsultationPolicy().then(data => {
|
||||
const next = normalizeDoctorWebConsultationPolicy(data)
|
||||
if (!next) throw new Error('网页面诊时间配置无效')
|
||||
userStore.userInfo.web_consultation_policy = next
|
||||
userStore.serverTimeOffsetMs = next.server_time * 1000 - Date.now()
|
||||
policyLoadFailed.value = false
|
||||
updateClock()
|
||||
}).catch(() => {
|
||||
// 保留最近一次有效配置,后端仍逐次校验实际截止时间。
|
||||
policyLoadFailed.value = true
|
||||
}).finally(() => { pending = undefined })
|
||||
return pending
|
||||
}
|
||||
const refreshConsultationPolicy = () => loadPolicy(true)
|
||||
const refreshOnFocus = () => {
|
||||
updateClock()
|
||||
void refreshConsultationPolicy()
|
||||
}
|
||||
const refreshOnVisible = () => {
|
||||
if (document.visibilityState !== 'hidden') refreshOnFocus()
|
||||
}
|
||||
|
||||
// 登录响应和配置刷新响应均提供服务器时刻,避免本机时区/时钟影响规则。
|
||||
watch(() => userStore.serverTimeOffsetMs, updateClock, { immediate: true })
|
||||
|
||||
onMounted(() => {
|
||||
updateClock()
|
||||
void refreshConsultationPolicy()
|
||||
timer = setInterval(() => {
|
||||
updateClock()
|
||||
void loadPolicy()
|
||||
}, 1000)
|
||||
window.addEventListener('focus', refreshOnFocus)
|
||||
document.addEventListener('visibilitychange', refreshOnVisible)
|
||||
})
|
||||
onUnmounted(() => {
|
||||
clearInterval(timer)
|
||||
window.removeEventListener('focus', refreshOnFocus)
|
||||
document.removeEventListener('visibilitychange', refreshOnVisible)
|
||||
})
|
||||
|
||||
const isDoctor = computed(() => isConsultationDoctor(userStore.userInfo))
|
||||
const webConsultationExpired = computed(() => hasDoctorWebConsultationExpired(policy.value, now.value))
|
||||
const consultationReminder = computed(() => doctorWebConsultationReminder(policy.value, now.value))
|
||||
const webConsultationMessage = computed(() => doctorWebConsultationMessage(policy.value))
|
||||
const webConsultationBlocked = computed(() => isDoctorWebConsultationBlocked(userStore.userInfo, policy.value, now.value))
|
||||
const ensureWebConsultationAllowed = () => {
|
||||
updateClock()
|
||||
if (!webConsultationBlocked.value) return true
|
||||
feedback.msgWarning(webConsultationMessage.value)
|
||||
return false
|
||||
}
|
||||
|
||||
return {
|
||||
isDoctor, consultationReminder, webConsultationExpired, webConsultationBlocked,
|
||||
webConsultationMessage, ensureWebConsultationAllowed, policyLoadFailed, refreshConsultationPolicy
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ export interface UserState {
|
||||
routes: RouteRecordRaw[]
|
||||
perms: string[]
|
||||
isPaw: number // 0=需要修改密码,1=正常
|
||||
serverTimeOffsetMs: number
|
||||
}
|
||||
|
||||
const useUserStore = defineStore({
|
||||
@@ -27,7 +28,8 @@ const useUserStore = defineStore({
|
||||
// 权限
|
||||
perms: [],
|
||||
// 是否需要修改密码
|
||||
isPaw: 1
|
||||
isPaw: 1,
|
||||
serverTimeOffsetMs: 0
|
||||
}),
|
||||
getters: {},
|
||||
actions: {
|
||||
@@ -36,6 +38,7 @@ const useUserStore = defineStore({
|
||||
this.userInfo = {}
|
||||
this.perms = []
|
||||
this.isPaw = 1
|
||||
this.serverTimeOffsetMs = 0
|
||||
},
|
||||
login(playload: any) {
|
||||
const { account, password } = playload
|
||||
@@ -95,6 +98,8 @@ const useUserStore = defineStore({
|
||||
getUserInfo()
|
||||
.then((data) => {
|
||||
this.userInfo = data.user
|
||||
const serverTime = Number(data.user?.web_consultation_policy?.server_time)
|
||||
this.serverTimeOffsetMs = serverTime > 0 ? serverTime * 1000 - Date.now() : 0
|
||||
this.perms = data.permissions
|
||||
this.routes = filterAsyncRoutes(data.menu)
|
||||
// 更新 isPaw 状态
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { ConsultationCallRecord } from '@/api/tcm'
|
||||
|
||||
export function normalizeConsultationRecords(value: unknown, diagnosisId: number): ConsultationCallRecord[] {
|
||||
if (!Array.isArray(value)) throw new Error('面诊记录返回格式异常,请重试')
|
||||
const seen = new Set<number>()
|
||||
return value.filter(row => {
|
||||
if (!row || !Number.isSafeInteger(Number(row.id)) || Number(row.id) <= 0 || seen.has(Number(row.id))) return false
|
||||
if (row.diagnosis_id != null && Number(row.diagnosis_id) !== diagnosisId) return false
|
||||
seen.add(Number(row.id))
|
||||
return true
|
||||
}).map(row => ({
|
||||
...row,
|
||||
id: Number(row.id),
|
||||
diagnosis_id: diagnosisId,
|
||||
transcript_text: typeof row.transcript_text === 'string' ? row.transcript_text.replace(/\r\n/g, '\n').trim() : ''
|
||||
})).sort((a, b) => b.id - a.id)
|
||||
}
|
||||
|
||||
export function consultationTranscriptText(row?: ConsultationCallRecord | null): string {
|
||||
return typeof row?.transcript_text === 'string' ? row.transcript_text.trim() : ''
|
||||
}
|
||||
|
||||
export function consultationTranscriptStatus(row: ConsultationCallRecord) {
|
||||
switch (row.transcription_status) {
|
||||
case 'running': return { label: '录音转写中', type: 'info' as const }
|
||||
case 'completed': return { label: '文字已生成', type: 'success' as const }
|
||||
case 'partial': return { label: '文字部分保存', type: 'warning' as const }
|
||||
case 'failed': return { label: '文字生成失败', type: 'danger' as const }
|
||||
default: return consultationTranscriptText(row)
|
||||
? { label: '文字已保存', type: 'success' as const }
|
||||
: { label: '未生成文字', type: 'info' as const }
|
||||
}
|
||||
}
|
||||
|
||||
export function consultationTranscriptEmptyText(row: ConsultationCallRecord): string {
|
||||
if (row.transcription_status === 'running') return '正在转写,可点击刷新查看最新保存的文字。'
|
||||
if (row.transcription_status === 'failed') return '本次面诊文字生成失败,暂无已保存的对话。'
|
||||
if (Number(row.status) === 3) return '本次通话未接听,暂无文字对话。'
|
||||
if (Number(row.status) === 4) return '本次通话已取消,暂无文字对话。'
|
||||
return '本次面诊暂无已保存的文字对话。'
|
||||
}
|
||||
|
||||
export function consultationCallLabel(row: ConsultationCallRecord): string {
|
||||
return Number(row.call_type) === 1 ? '语音面诊' : Number(row.call_type) === 2 ? '视频面诊' : '面诊记录'
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
// 所有时间由服务端配置提供,浏览器不保留独立的截止日期。
|
||||
export type DoctorWebConsultationPolicy = {
|
||||
cutoff_at: string
|
||||
approaching_at: string
|
||||
urgent_at: string
|
||||
server_time: number
|
||||
}
|
||||
|
||||
export type DoctorWebConsultationPhase = 'prepare' | 'approaching' | 'last_day' | 'expired'
|
||||
|
||||
export function normalizeDoctorWebConsultationPolicy(value: unknown): DoctorWebConsultationPolicy | undefined {
|
||||
if (!value || typeof value !== 'object') return undefined
|
||||
const policy = value as DoctorWebConsultationPolicy
|
||||
const timestamps = [policy.approaching_at, policy.urgent_at, policy.cutoff_at].map(date =>
|
||||
typeof date === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/.test(date) ? Date.parse(date) : NaN
|
||||
)
|
||||
if (timestamps.some(time => !Number.isFinite(time)) || timestamps[0] > timestamps[1] || timestamps[1] > timestamps[2]) return undefined
|
||||
if (!Number.isFinite(policy.server_time) || policy.server_time <= 0) return undefined
|
||||
return { cutoff_at: policy.cutoff_at, approaching_at: policy.approaching_at, urgent_at: policy.urgent_at, server_time: policy.server_time }
|
||||
}
|
||||
|
||||
export function doctorWebConsultationDate(policy: DoctorWebConsultationPolicy): string {
|
||||
// 无论医生电脑所在时区为何,公告始终显示北京时间。
|
||||
const parts = new Intl.DateTimeFormat('en-GB', {
|
||||
timeZone: 'Asia/Shanghai', year: 'numeric', month: '2-digit', day: '2-digit',
|
||||
hour: '2-digit', minute: '2-digit', second: '2-digit', hourCycle: 'h23'
|
||||
}).formatToParts(new Date(policy.cutoff_at))
|
||||
const part = (type: string) => parts.find(item => item.type === type)?.value || ''
|
||||
const seconds = part('second') === '00' ? '' : `:${part('second')}`
|
||||
return `${part('year')}年${part('month')}月${part('day')}日${part('hour')}:${part('minute')}${seconds}(北京时间)`
|
||||
}
|
||||
|
||||
export function doctorWebConsultationMessage(policy?: DoctorWebConsultationPolicy): string {
|
||||
return `网页端面诊已${policy ? `于${doctorWebConsultationDate(policy)}` : ''}停用,请医生使用桌面应用进行面诊。`
|
||||
}
|
||||
|
||||
export function doctorWebConsultationReminder(policy?: DoctorWebConsultationPolicy, now = Date.now()) {
|
||||
if (!policy) return {
|
||||
phase: 'prepare' as DoctorWebConsultationPhase,
|
||||
type: 'info' as const,
|
||||
title: '系统公告:医生桌面应用安装指引',
|
||||
description: '请各位医生提前下载并安装桌面应用,使用当前医生账号登录。',
|
||||
countdown: ''
|
||||
}
|
||||
const cutoffDate = doctorWebConsultationDate(policy)
|
||||
const remaining = Date.parse(policy.cutoff_at) - now
|
||||
const days = Math.floor(remaining / 86400000)
|
||||
const hours = Math.floor(remaining / 3600000) % 24
|
||||
const minutes = Math.floor(remaining / 60000) % 60
|
||||
const countdown = remaining <= 0 ? '' : remaining < 60000 ? '不足1分钟' :
|
||||
`${days > 0 ? `${days}天` : ''}${hours > 0 ? `${hours}小时` : ''}${minutes > 0 ? `${minutes}分钟` : ''}`
|
||||
|
||||
if (remaining <= 0) return {
|
||||
phase: 'expired' as DoctorWebConsultationPhase,
|
||||
type: 'error' as const,
|
||||
title: '系统公告:医生网页端面诊已停用',
|
||||
description: doctorWebConsultationMessage(policy),
|
||||
countdown: ''
|
||||
}
|
||||
if (now >= Date.parse(policy.urgent_at)) return {
|
||||
phase: 'last_day' as DoctorWebConsultationPhase,
|
||||
type: 'error' as const,
|
||||
title: '系统公告:医生网页端面诊停用最后提醒',
|
||||
description: `请各位医生在${cutoffDate}前完成桌面应用的安装与登录。届时接诊台、问诊列表的网页端面诊功能将同步停用,请使用桌面应用进行面诊。`,
|
||||
countdown
|
||||
}
|
||||
if (now >= Date.parse(policy.approaching_at)) return {
|
||||
phase: 'approaching' as DoctorWebConsultationPhase,
|
||||
type: 'warning' as const,
|
||||
title: '系统公告:医生网页端面诊即将停用',
|
||||
description: `网页端面诊将于${cutoffDate}停用。请各位医生尽快下载桌面应用,完成安装并使用当前医生账号登录,接诊台、问诊列表将同步执行此规则。`,
|
||||
countdown
|
||||
}
|
||||
return {
|
||||
phase: 'prepare' as DoctorWebConsultationPhase,
|
||||
type: 'info' as const,
|
||||
title: '系统公告:请提前安装医生桌面应用',
|
||||
description: `请各位医生提前下载并安装桌面应用,使用当前医生账号登录试用。自${cutoffDate}起,接诊台、问诊列表的网页端面诊功能将停用,请提前做好准备。`,
|
||||
countdown: ''
|
||||
}
|
||||
}
|
||||
|
||||
export function isConsultationDoctor(user: Record<string, any>): boolean {
|
||||
return Number(user.root) !== 1 && Array.isArray(user.role_ids) && user.role_ids.some(role => Number(role) === 1)
|
||||
}
|
||||
|
||||
export function hasDoctorWebConsultationExpired(policy?: DoctorWebConsultationPolicy, now = Date.now()): boolean {
|
||||
return !!policy && now >= Date.parse(policy.cutoff_at)
|
||||
}
|
||||
|
||||
export function isDoctorWebConsultationBlocked(
|
||||
user: Record<string, any>,
|
||||
policy?: DoctorWebConsultationPolicy,
|
||||
now = Date.now()
|
||||
): boolean {
|
||||
return isConsultationDoctor(user) && hasDoctorWebConsultationExpired(policy, now)
|
||||
}
|
||||
@@ -144,6 +144,17 @@
|
||||
>
|
||||
<el-table-column type="selection" width="48" />
|
||||
<el-table-column label="订单号" prop="order_no" min-width="150" />
|
||||
|
||||
<el-table-column label="处方业务订单号" min-width="210">
|
||||
<template #default="{ row }">
|
||||
<div v-if="row.prescription_orders?.length" class="flex flex-col gap-1">
|
||||
<span v-for="order in row.prescription_orders" :key="order.id" class="break-all">
|
||||
{{ order.order_no }}
|
||||
</span>
|
||||
</div>
|
||||
<span v-else class="text-gray-400">未关联</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
|
||||
<el-table-column label="患者信息" min-width="150">
|
||||
<template #default="{ row }">
|
||||
@@ -302,6 +313,14 @@
|
||||
<el-tag :type="getStatusTag(detailData.status)">
|
||||
{{ getStatusText(detailData.status) }}
|
||||
</el-tag>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="处方业务订单号" :span="2">
|
||||
<div v-if="detailData.prescription_orders?.length" class="flex flex-col gap-1">
|
||||
<span v-for="order in detailData.prescription_orders" :key="order.id" class="break-all">
|
||||
{{ order.order_no }}
|
||||
</span>
|
||||
</div>
|
||||
<span v-else class="text-gray-400">未关联</span>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="患者姓名">
|
||||
{{ detailData.patient?.patient_name || '待关联' }}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<template>
|
||||
<div class="reception-page">
|
||||
<DoctorWebConsultationNotice />
|
||||
<!-- 页头 -->
|
||||
<div class="reception-header">
|
||||
<div class="header-left">
|
||||
@@ -84,7 +85,7 @@
|
||||
</button>
|
||||
</el-tooltip>
|
||||
<el-tooltip content="发起通话" placement="top">
|
||||
<button class="row-icon-btn call" @click="handleCall(row)">
|
||||
<button class="row-icon-btn call" :disabled="webConsultationBlocked" @click="handleCall(row)">
|
||||
<el-icon><Phone /></el-icon>
|
||||
</button>
|
||||
</el-tooltip>
|
||||
@@ -189,6 +190,8 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { defineAsyncComponent, onMounted, onUnmounted } from 'vue'
|
||||
import DoctorWebConsultationNotice from '@/components/doctor-web-consultation-notice/index.vue'
|
||||
import { useDoctorWebConsultation } from '@/hooks/useDoctorWebConsultation'
|
||||
import { receptionQueue, receptionDetail, notifyAssistant, addDoctorNote } from '@/api/patient'
|
||||
import NoteTimeline from './components/NoteTimeline.vue'
|
||||
import PatientInfoCard from '@/views/tcm/diagnosis/components/PatientInfoCard.vue'
|
||||
@@ -211,6 +214,7 @@ const DiagnosisEdit = defineAsyncComponent(() => import('@/views/tcm/diagnosis/e
|
||||
|
||||
const POLL_MS = 5_000
|
||||
const PAGE_SIZE = 15
|
||||
const { webConsultationBlocked, ensureWebConsultationAllowed } = useDoctorWebConsultation()
|
||||
|
||||
interface QueueRow {
|
||||
id: number
|
||||
@@ -438,6 +442,7 @@ const handleSearch = async () => {
|
||||
}
|
||||
|
||||
const handleCall = async (row: QueueRow) => {
|
||||
if (!ensureWebConsultationAllowed()) return
|
||||
const sourcePatientId = Number(row.source_patient_id || 0)
|
||||
const diagnosisId = Number(row.diagnosis_id || 0)
|
||||
if (!sourcePatientId) {
|
||||
@@ -454,6 +459,7 @@ const handleCall = async (row: QueueRow) => {
|
||||
appointment_id: Number(row.id),
|
||||
diagnosis_id: diagnosisId
|
||||
})
|
||||
if (!ensureWebConsultationAllowed()) return
|
||||
chatDialogRef.value?.open({
|
||||
patientId: sourcePatientId,
|
||||
patientName: row.patient_name,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<template>
|
||||
<div class="appointment-list">
|
||||
<DoctorWebConsultationNotice />
|
||||
<el-card class="list-card !border-none" shadow="never">
|
||||
<!-- 单行工具栏:Tab(主) + 搜索(辅) -->
|
||||
<div class="list-toolbar">
|
||||
@@ -559,6 +560,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import DoctorWebConsultationNotice from '@/components/doctor-web-consultation-notice/index.vue'
|
||||
import { appointmentTypeDescription, canAppointmentVideoCall } from '@/utils/appointment-type'
|
||||
import { usePaging } from '@/hooks/usePaging'
|
||||
import { defineAsyncComponent, onMounted, onUnmounted, watch } from 'vue'
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<template>
|
||||
<div class="apt-h5">
|
||||
<DoctorWebConsultationNotice />
|
||||
<template v-if="currentView === 'list'">
|
||||
<header class="apt-h5-topbar">
|
||||
<div class="apt-h5-search">
|
||||
@@ -412,6 +413,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts" name="tcmAppointmentH5">
|
||||
import DoctorWebConsultationNotice from '@/components/doctor-web-consultation-notice/index.vue'
|
||||
import { appointmentTypeDescription, canAppointmentVideoCall } from '@/utils/appointment-type'
|
||||
import { appointmentDetail, appointmentLists, cancelAppointment, completeAppointment } from '@/api/doctor'
|
||||
import { getWeappConfig } from '@/api/channel/weapp'
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
<template>
|
||||
<section class="consultation-transcripts">
|
||||
<header class="transcript-toolbar">
|
||||
<div>
|
||||
<h3>面诊文字对话</h3>
|
||||
<p>按每次通话分别查看已保存的文字记录。</p>
|
||||
</div>
|
||||
<el-button :loading="loading" @click="refresh"><el-icon><Refresh /></el-icon>刷新</el-button>
|
||||
</header>
|
||||
|
||||
<el-alert v-if="error" :title="error" type="error" :closable="false" show-icon class="transcript-error" />
|
||||
<div v-loading="loading" class="transcript-body">
|
||||
<template v-if="records.length">
|
||||
<aside class="transcript-sessions" aria-label="历次面诊记录">
|
||||
<el-input v-model="search" clearable placeholder="搜索面诊时间或对话内容" :prefix-icon="Search" />
|
||||
<p class="session-count">{{ filteredRecords.length }} 条面诊记录</p>
|
||||
<div class="session-list">
|
||||
<button
|
||||
v-for="row in pageRecords"
|
||||
:key="row.id"
|
||||
type="button"
|
||||
class="session-item"
|
||||
:class="{ selected: selectedId === row.id }"
|
||||
:aria-pressed="selectedId === row.id"
|
||||
@click="selectedId = row.id"
|
||||
>
|
||||
<span class="session-time">{{ row.start_time_text || '开始时间未记录' }}</span>
|
||||
<span class="session-meta">{{ consultationCallLabel(row) }} · 记录 #{{ row.id }}</span>
|
||||
<el-tag size="small" :type="consultationTranscriptStatus(row).type">{{ consultationTranscriptStatus(row).label }}</el-tag>
|
||||
<span class="session-preview">{{ preview(row) }}</span>
|
||||
</button>
|
||||
</div>
|
||||
<el-pagination
|
||||
v-if="filteredRecords.length > PAGE_SIZE"
|
||||
v-model:current-page="page"
|
||||
:page-size="PAGE_SIZE"
|
||||
:total="filteredRecords.length"
|
||||
layout="prev, pager, next"
|
||||
small
|
||||
/>
|
||||
</aside>
|
||||
|
||||
<article v-if="selectedRecord" class="transcript-detail" :key="`${diagnosisId}-${selectedRecord.id}`">
|
||||
<header class="transcript-detail-header">
|
||||
<div>
|
||||
<h4>{{ selectedRecord.start_time_text || '开始时间未记录' }} · {{ consultationCallLabel(selectedRecord) }}</h4>
|
||||
<p>
|
||||
通话记录 #{{ selectedRecord.id }}
|
||||
<span v-if="selectedRecord.duration_text"> · 时长 {{ selectedRecord.duration_text }}</span>
|
||||
<span v-if="selectedRecord.end_time_text"> · 结束 {{ selectedRecord.end_time_text }}</span>
|
||||
</p>
|
||||
</div>
|
||||
<el-button v-if="selectedText" :loading="copying" @click="copyTranscript">复制全文</el-button>
|
||||
</header>
|
||||
<div class="transcript-status">
|
||||
<el-tag :type="consultationTranscriptStatus(selectedRecord).type">{{ consultationTranscriptStatus(selectedRecord).label }}</el-tag>
|
||||
<span>{{ callStatusText(selectedRecord.status) }}</span>
|
||||
<span v-if="selectedRecord.transcription_segment_count">{{ selectedRecord.transcription_segment_count }} 段对话</span>
|
||||
</div>
|
||||
<p v-if="selectedRecord.transcription_status === 'partial'" class="transcript-note">本次文字记录不完整,以下展示已保存的内容。</p>
|
||||
<p v-else-if="selectedRecord.transcription_status === 'failed' && selectedText" class="transcript-note">本次转写未完成,以下展示已保存的内容。</p>
|
||||
<p v-else-if="selectedRecord.transcription_status === 'running' && selectedText" class="transcript-note">转写仍在进行,可刷新查看最新保存的文字。</p>
|
||||
<pre v-if="selectedText" class="transcript-text">{{ selectedText }}</pre>
|
||||
<el-empty v-else :description="consultationTranscriptEmptyText(selectedRecord)" :image-size="72" />
|
||||
</article>
|
||||
<el-empty v-else description="没有匹配的面诊记录,请调整搜索内容" class="transcript-detail" :image-size="72" />
|
||||
</template>
|
||||
<el-empty v-else-if="!loading && !error" description="该诊单暂无面诊通话记录" :image-size="80" class="transcript-empty" />
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { Refresh, Search } from '@element-plus/icons-vue'
|
||||
import type { ConsultationCallRecord } from '@/api/tcm'
|
||||
import { useConsultationTranscripts } from '@/hooks/useConsultationTranscripts'
|
||||
import {
|
||||
consultationCallLabel,
|
||||
consultationTranscriptEmptyText,
|
||||
consultationTranscriptStatus,
|
||||
consultationTranscriptText
|
||||
} from '@/utils/consultation-transcripts'
|
||||
import feedback from '@/utils/feedback'
|
||||
|
||||
const props = defineProps<{ diagnosisId: number }>()
|
||||
const { records, loading, error, refresh } = useConsultationTranscripts(() => props.diagnosisId)
|
||||
const search = ref('')
|
||||
const selectedId = ref<number | null>(null)
|
||||
const page = ref(1)
|
||||
const copying = ref(false)
|
||||
const PAGE_SIZE = 10
|
||||
const filteredRecords = computed(() => {
|
||||
const term = search.value.trim().toLocaleLowerCase()
|
||||
return records.value.filter(row => row.diagnosis_id === props.diagnosisId &&
|
||||
(!term || `${row.start_time_text || ''} ${row.id} ${consultationTranscriptText(row)}`.toLocaleLowerCase().includes(term)))
|
||||
})
|
||||
const pageRecords = computed(() => filteredRecords.value.slice((page.value - 1) * PAGE_SIZE, page.value * PAGE_SIZE))
|
||||
const selectedRecord = computed(() => filteredRecords.value.find(row => row.id === selectedId.value))
|
||||
const selectedText = computed(() => consultationTranscriptText(selectedRecord.value))
|
||||
watch(filteredRecords, rows => {
|
||||
if (!rows.some(row => row.id === selectedId.value)) {
|
||||
const selected = rows.find(row => consultationTranscriptText(row)) || rows[0]
|
||||
selectedId.value = selected?.id ?? null
|
||||
page.value = selected ? Math.floor(rows.indexOf(selected) / PAGE_SIZE) + 1 : 1
|
||||
}
|
||||
page.value = Math.min(page.value, Math.max(1, Math.ceil(rows.length / PAGE_SIZE)))
|
||||
}, { immediate: true, flush: 'sync' })
|
||||
watch(search, () => { page.value = 1 }, { flush: 'sync' })
|
||||
|
||||
function preview(row: ConsultationCallRecord): string {
|
||||
const text = consultationTranscriptText(row).replace(/\s+/g, ' ')
|
||||
return text ? text.slice(0, 90) + (text.length > 90 ? '…' : '') : consultationTranscriptEmptyText(row)
|
||||
}
|
||||
function callStatusText(value?: number): string {
|
||||
return ({ 1: '进行中', 2: '已结束', 3: '未接听', 4: '已取消' } as Record<number, string>)[Number(value)] || '状态未记录'
|
||||
}
|
||||
async function copyTranscript() {
|
||||
const text = selectedText.value
|
||||
if (!text || copying.value) return
|
||||
if (!navigator.clipboard?.writeText) {
|
||||
feedback.msgWarning('当前浏览器不支持自动复制,请选中文字复制')
|
||||
return
|
||||
}
|
||||
copying.value = true
|
||||
try {
|
||||
await navigator.clipboard.writeText(text)
|
||||
feedback.msgSuccess('已复制本次面诊文字对话')
|
||||
} catch {
|
||||
feedback.msgWarning('复制失败,请选中文字复制')
|
||||
} finally {
|
||||
copying.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.consultation-transcripts { padding: 4px 0 16px; }
|
||||
.transcript-toolbar, .transcript-detail-header { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; }
|
||||
.transcript-toolbar { margin-bottom: 20px; }
|
||||
.transcript-toolbar h3, .transcript-detail h4 { margin: 0; color: var(--el-text-color-primary); font-weight: 600; }
|
||||
.transcript-toolbar h3 { font-size: 18px; }
|
||||
.transcript-toolbar p, .transcript-detail-header p { margin: 7px 0 0; color: var(--el-text-color-secondary); line-height: 1.7; font-size: 13px; }
|
||||
.transcript-error { margin-bottom: 16px; }
|
||||
.transcript-body { display: flex; min-height: 360px; border-top: 1px solid var(--el-border-color-lighter); }
|
||||
.transcript-sessions { flex: 0 0 282px; min-width: 0; padding: 18px 18px 0 0; border-right: 1px solid var(--el-border-color-lighter); }
|
||||
.session-count { margin: 12px 0 8px; color: var(--el-text-color-secondary); font-size: 12px; }
|
||||
.session-list { display: flex; flex-direction: column; gap: 8px; max-height: 580px; overflow-y: auto; margin-bottom: 12px; }
|
||||
.session-item { display: flex; flex-direction: column; align-items: flex-start; gap: 8px; width: 100%; padding: 13px 12px; border: 1px solid var(--el-border-color-lighter); border-radius: 7px; background: var(--el-bg-color); text-align: left; cursor: pointer; font: inherit; }
|
||||
.session-item:hover, .session-item.selected { border-color: var(--el-color-primary); background: var(--el-color-primary-light-9); }
|
||||
.session-item:focus-visible { outline: 2px solid var(--el-color-primary); outline-offset: -2px; }
|
||||
.session-time { color: var(--el-text-color-primary); font-size: 14px; font-weight: 600; }
|
||||
.session-meta, .session-preview { color: var(--el-text-color-secondary); font-size: 12px; line-height: 1.6; }
|
||||
.session-preview { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; overflow-wrap: anywhere; }
|
||||
.transcript-detail { flex: 1; min-width: 0; padding: 20px 0 0 24px; }
|
||||
.transcript-detail h4 { font-size: 16px; line-height: 1.7; }
|
||||
.transcript-status { display: flex; align-items: center; flex-wrap: wrap; gap: 12px; margin: 16px 0; color: var(--el-text-color-secondary); font-size: 13px; }
|
||||
.transcript-note { padding: 10px 12px; background: var(--el-color-warning-light-9); color: var(--el-color-warning-dark-2); font-size: 13px; line-height: 1.7; }
|
||||
.transcript-text { margin: 0; padding: 20px 0; color: var(--el-text-color-primary); white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; font-size: 15px; line-height: 2; user-select: text; }
|
||||
.transcript-empty { flex: 1; }
|
||||
@media (max-width: 900px) {
|
||||
.transcript-body { flex-direction: column; }
|
||||
.transcript-sessions { flex-basis: auto; padding: 16px 0; border-right: 0; border-bottom: 1px solid var(--el-border-color-lighter); }
|
||||
.session-list { max-height: 300px; }
|
||||
.transcript-detail { padding: 20px 0 0; }
|
||||
.transcript-detail-header { flex-wrap: wrap; }
|
||||
}
|
||||
</style>
|
||||
@@ -744,6 +744,20 @@
|
||||
<el-empty v-else description="请先保存诊单后再查看视频录制回放记录" />
|
||||
</el-tab-pane>
|
||||
<el-tab-pane
|
||||
v-if="hasCallTranscriptPermission"
|
||||
label="面诊文字对话"
|
||||
name="callTranscript"
|
||||
:disabled="!formData.id"
|
||||
lazy
|
||||
>
|
||||
<consultation-transcript-panel
|
||||
v-if="visible && activeTab === 'callTranscript' && formData.id"
|
||||
:key="Number(formData.id)"
|
||||
:diagnosis-id="Number(formData.id)"
|
||||
/>
|
||||
<el-empty v-else-if="!formData.id" description="请先保存诊单后再查看面诊文字对话" />
|
||||
</el-tab-pane>
|
||||
<el-tab-pane
|
||||
v-if="hasPermission(['tcm.diagnosis/chat'])"
|
||||
label="聊天记录"
|
||||
name="chat"
|
||||
@@ -827,6 +841,7 @@ import FollowupAudioPanel from './components/FollowupAudioPanel.vue'
|
||||
import { followupAudioCapabilities, type FollowupCapabilities } from '@/api/followupAudio'
|
||||
import CaseRecordList from './components/CaseRecordList.vue'
|
||||
import CallRecordPanel from './components/CallRecordPanel.vue'
|
||||
import ConsultationTranscriptPanel from './components/ConsultationTranscriptPanel.vue'
|
||||
import ImChatRecordPanel from './components/ImChatRecordPanel.vue'
|
||||
import AssignLogPanel from './components/AssignLogPanel.vue'
|
||||
import AppointmentRecordPanel from './components/AppointmentRecordPanel.vue'
|
||||
@@ -862,6 +877,7 @@ const submitting = ref(false)
|
||||
/** 拥有后手机号可正常编辑,失焦不再强制脱敏 */
|
||||
const hasPhonePlainPermission = computed(() => hasPermission(['tcm.diagnosis/phonePlain']))
|
||||
const hasDailyRecordPermission = computed(() => hasPermission(['tcm.diagnosis/dailyRecord']))
|
||||
const hasCallTranscriptPermission = computed(() => hasPermission(['tcm.diagnosis/huifang']) || hasPermission(['tcm.diagnosis/getCallRecords']))
|
||||
const hasFollowupAudioPermission = computed(() => hasPermission(['tcm.diagnosis/followupAudio']))
|
||||
const patientBasicLocked = ref(false)
|
||||
const canEditPatientBasicFromApi = ref(true)
|
||||
@@ -930,12 +946,15 @@ watch(() => activeTab.value, async (tab) => {
|
||||
}
|
||||
})
|
||||
|
||||
watch([visible, activeTab], () => {
|
||||
watch([visible, activeTab, hasCallTranscriptPermission], () => {
|
||||
if (!visible.value) return
|
||||
if (activeTab.value === 'chat' && !hasPermission(['tcm.diagnosis/chat'])) {
|
||||
activeTab.value = 'basic'
|
||||
}
|
||||
if (activeTab.value === 'visit' && !hasPermission(['tcm.diagnosis/huifang'])) {
|
||||
activeTab.value = 'basic'
|
||||
}
|
||||
if (activeTab.value === 'callTranscript' && !hasCallTranscriptPermission.value) {
|
||||
activeTab.value = 'basic'
|
||||
}
|
||||
if (
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<template>
|
||||
<div class="tcm-diagnosis">
|
||||
<DoctorWebConsultationNotice />
|
||||
<el-card class="filter-card !border-none" shadow="never">
|
||||
<!-- 第一行:日期 + 患者搜索 -->
|
||||
<div class="filter-main">
|
||||
@@ -767,6 +768,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts" name="tcmDiagnosis">
|
||||
import DoctorWebConsultationNotice from '@/components/doctor-web-consultation-notice/index.vue'
|
||||
import { tcmDiagnosisLists, tcmDiagnosisDelete, tcmDiagnosisAssign, tcmDiagnosisGuahaoLogList, getAssistants, generateMiniProgramQrcode, generateOrderQrcode, getWechatChatRecords, addWechatChatRecord, deleteWechatChatRecord, getWechatExternalContact, fillIdCard, diagnosisReadonlyDetail } from '@/api/tcm'
|
||||
import { orderCreate } from '@/api/order'
|
||||
import { cancelAppointment } from '@/api/doctor'
|
||||
|
||||
@@ -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, /<img src=x onerror=alert\(1\)>/)
|
||||
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, [])
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user