This commit is contained in:
gr
2026-10-15 11:56:36 +08:00
35 changed files with 2289 additions and 72 deletions
+14
View File
@@ -75,6 +75,8 @@ export interface FollowupTaskSummary {
version: number
created_at: number | string
expires_at: number | string
can_delete?: boolean
delete_block_reason?: string
can_retry: boolean
audio_available: boolean
preview_only?: boolean
@@ -82,6 +84,16 @@ export interface FollowupTaskSummary {
pipeline_progress?: { transcribed: number; total: number }
}
export interface FollowupTaskDetail extends FollowupTaskSummary {
extraction_revision?: number
extraction_channel_roles?: FollowupChannelRoles
can_reextract?: boolean
reextract_block_reason?: string
role_check?: {
conflict: boolean
suggested_roles: FollowupChannelRoles
message: string
evidence: Array<{ channel: FollowupAudioChannel; start_ms: number; end_ms: number; text: string }>
}
summary: string
transcript: string
transcript_segments?: FollowupTranscriptSegment[]
@@ -130,6 +142,8 @@ export const followupAudioUploadComplete = (uploadId: string, signal?: AbortSign
export const followupAudioCreate = (data: { diagnosis_id: number; upload_id: string; recorded_at: string; model_key: string; channel_roles?: FollowupChannelRoles }, signal?: AbortSignal) => post<{ task_id: number; status: string; reused?: boolean; reuse_message?: string }>('create', data, signal)
export const followupAudioSaveDraft = (data: { id: number; version: number; items: FollowupReviewItem[]; channel_roles?: FollowupChannelRoles }, signal?: AbortSignal) => post<FollowupTaskDetail>('saveDraft', data, signal)
export const followupAudioApply = (data: { id: number; version: number; items: FollowupReviewItem[] }, signal?: AbortSignal) => post<{ id: number; status: 'applied'; applied_items: unknown[] }>('apply', data, signal)
export const followupAudioReextract = (data: { id: number; version: number; channel_roles: Exclude<FollowupChannelRoles, 'unconfirmed'> }, signal?: AbortSignal) => post<FollowupTaskDetail>('reextract', data, signal)
export const followupAudioDelete = (data: { id: number; version: number }, signal?: AbortSignal) => post<{ id: number; status: 'deleted'; version: number }>('delete', data, signal)
export const followupAudioRetry = (id: number, signal?: AbortSignal) => post<{ id: number; status: string }>('retry', { id }, signal)
/** The existing request interceptor puts the token in a header, never in the audio URL. */
export async function followupAudioBlob(id: number, signal?: AbortSignal): Promise<Blob> {
@@ -205,8 +205,8 @@
</header>
<dl class="daily-matrix__detail-fields">
<dt>运动</dt><dd>{{ record.exercise_type || '—' }}</dd>
<dt>时长</dt><dd>{{ record.duration ?? '—' }} 分钟</dd>
<dt>强度</dt><dd>{{ record.intensity_text || intensityLabel(record.intensity) }}</dd>
<dt>时长</dt><dd>{{ record.duration == null ? '未记录' : `${record.duration} 分钟` }}</dd>
<dt>强度</dt><dd>{{ intensityLabel(record.intensity) }}</dd>
<dt>备注</dt><dd>{{ record.note || '—' }}</dd>
</dl>
<div v-if="record.images?.length" class="daily-matrix__detail-images">
@@ -343,11 +343,13 @@
<el-option label="其他" value="其他" />
</el-select>
</el-form-item>
<el-form-item label="运动时长(分钟)" required>
<el-input-number v-model="exerciseForm.duration" :min="0" :max="300" />
<el-form-item label="运动时长(分钟)" :required="!exerciseForm.id">
<el-input-number v-model="exerciseForm.duration" :min="0" :max="300" placeholder="未记录" />
<span v-if="exerciseForm.id" class="ml-2 text-info">留空表示未记录</span>
</el-form-item>
<el-form-item label="运动强度" required>
<el-select v-model="exerciseForm.intensity" placeholder="请选择运动强度" class="w-full">
<el-form-item label="运动强度">
<el-select v-model="exerciseIntensity" placeholder="未记录" class="w-full">
<el-option label="未记录" value="" />
<el-option label="低强度" :value="1" />
<el-option label="中强度" :value="2" />
<el-option label="高强度" :value="3" />
@@ -492,8 +494,8 @@ interface ExerciseRecord {
patient_id?: number
record_date?: string
exercise_type?: string
duration?: number
intensity?: number
duration?: number | null
intensity?: number | null
intensity_text?: string
images?: string[]
note?: string
@@ -547,6 +549,11 @@ const trackingSubmitting = ref(false)
const bloodForm = ref<BloodRecord>(createBloodForm())
const dietForm = ref<DietRecord>(createDietForm())
const exerciseForm = ref<ExerciseRecord>(createExerciseForm())
// el-option uses a string sentinel; persisted unknowns remain SQL/JSON null.
const exerciseIntensity = computed<number | ''>({
get: () => exerciseForm.value.intensity ?? '',
set: (value) => { exerciseForm.value.intensity = value === '' ? null : value }
})
const trackingForm = ref({
note_date: '',
existing_content: '',
@@ -719,8 +726,8 @@ function recordTimePeriodLabel(record: BloodRecord) {
return labels[period] || period || '未提供时段'
}
function intensityLabel(value?: number) {
return ({ 1: '低强度', 2: '中强度', 3: '高强度' } as Record<number, string>)[Number(value)] || '—'
function intensityLabel(value?: number | null) {
return ({ 1: '低强度', 2: '中强度', 3: '高强度' } as Record<number, string>)[Number(value)] || '未记录'
}
function bloodDetailFields(record: BloodRecord) {
@@ -880,7 +887,7 @@ function getCell(metric: string, date: string): { value: string; isHigh: boolean
return { value: count ? '✓' : '', isHigh: false, hasRecord: count > 0 }
}
if (metric === 'exercise') {
return { value: exercise.map((record) => record.duration ? `${record.duration}min` : record.exercise_type || '已记录').join(' / '), isHigh: false, hasRecord: exercise.length > 0 }
return { value: exercise.map((record) => record.duration != null ? `${record.duration}min` : record.exercise_type || '已记录').join(' / '), isHigh: false, hasRecord: exercise.length > 0 }
}
if (metric === 'tracking') {
return { value: tracking?.content ? summarizeTracking(tracking.content) : '', isHigh: false, hasRecord: !!tracking?.content }
@@ -970,7 +977,12 @@ function openDietRecord(source: DietRecord | undefined, date: string) {
function openExerciseRecord(source: ExerciseRecord | undefined, date: string) {
if (!canEditDailyRecord.value) return
exerciseForm.value = { ...createExerciseForm(date), ...source, images: [...(source?.images || [])] }
exerciseForm.value = {
...createExerciseForm(date), ...source,
// Existing omissions must not inherit the defaults used only for manual new records.
...(source ? { duration: source.duration ?? null, intensity: source.intensity ?? null } : {}),
images: [...(source?.images || [])]
}
exerciseDialogVisible.value = true
}
@@ -1063,12 +1075,12 @@ async function submitExercise() {
feedback.msgWarning('请选择运动类型')
return
}
if (!exerciseForm.value.duration) {
if (!exerciseForm.value.id && !exerciseForm.value.duration) {
feedback.msgWarning('请输入运动时长')
return
}
const targetDiagnosisId = diagnosisId.value
const payload = { ...exerciseForm.value }
const payload = { ...exerciseForm.value, duration: exerciseForm.value.duration ?? null, intensity: exerciseForm.value.intensity ?? null }
exerciseSubmitting.value = true
try {
if (payload.id) {
@@ -34,8 +34,8 @@
<el-table-column label="状态" width="145">
<template #default="{ row }"><el-tag size="small" :type="statusType(row.status)">{{ followupTaskStatus(row) }}</el-tag><div v-if="row.transcript_available && (row.status === 'failed' || row.status === 'needs_reconciliation')" class="task-time">转写已保留</div></template>
</el-table-column>
<el-table-column label="操作" width="65" align="right">
<template #default="{ row }"><el-button link type="primary" :disabled="busy" @click="openTask(row.id)">查看</el-button></template>
<el-table-column label="操作" width="112" align="right">
<template #default="{ row }"><el-button link type="primary" :disabled="busy" @click="openTask(row.id)">查看</el-button><el-button v-if="!viewOnly && row.can_delete !== undefined" link type="danger" :disabled="busy || !canDeleteTask(row)" :title="row.delete_block_reason || '删除未入单录音任务'" @click="deleteRecording(row)">删除</el-button></template>
</el-table-column>
</el-table>
</div>
@@ -43,7 +43,7 @@
<section v-if="selectedId && detail" class="task-detail" aria-label="录音任务详情">
<div class="detail-heading">
<div class="recording-title"><h3>{{ detail.file_name }}</h3><span>通话时间 {{ detail.recorded_at }}</span></div>
<el-tag size="small" :type="statusType(detail.status)">{{ followupTaskStatus(detail) }}</el-tag>
<div class="detail-actions"><el-tag size="small" :type="statusType(detail.status)">{{ followupTaskStatus(detail) }}</el-tag><el-button v-if="!viewOnly && detail.can_delete !== undefined" link type="danger" :disabled="busy || !canDeleteTask(detail)" :title="detail.delete_block_reason || '删除未入单录音任务'" @click="deleteRecording(detail)">删除录音</el-button></div>
</div>
<p v-if="detail.status === 'running' || detail.status === 'queued'" class="processing-state" role="status">{{ followupProgressText(detail) }}</p>
<el-alert v-if="detail.error_message || detail.status === 'failed'" :type="detail.status === 'failed' ? 'error' : 'warning'" :closable="false" :title="detail.error_message || '任务处理失败,不能写入;请先核对失败原因。'" />
@@ -56,13 +56,25 @@
<p>{{ detail.summary || '暂无回访摘要' }}</p>
<div class="summary-counts"><span>{{ detail.status === 'applied' ? '已写入' : '已选' }} <strong>{{ selectedCount }}</strong> 项</span><span>待核实 <strong>{{ pendingCount }}</strong> 项</span></div>
</div>
<section v-if="hasStereo" class="channel-role-box" aria-label="声道角色人工标注">
<el-alert v-if="detail.status === 'review' && !reviewItems.length" type="warning" :closable="false" title="未生成可写入信息" :description="detail.uncertainties.length ? `本次提炼保留了 ${detail.uncertainties.length} 条待核实原因,已展示在下方。请结合原文回听核对,尤其注意声道角色是否相符。` : '请查看回访摘要并回听录音;本次没有可供确认写入的结构化候选。'" show-icon />
<section v-if="hasStereo && !['queued', 'running'].includes(detail.status)" class="channel-role-box" aria-label="声道角色人工标注">
<div v-if="savedChannelRoles !== 'unconfirmed' && !editingRoles && !roleDirty" class="role-summary"><span>{{ savedChannelRoles === 'left_service' ? '左客服端 / 右患者或家属端' : '右客服端 / 左患者或家属端' }} · 已确认</span><el-button v-if="canEditReview" link type="primary" @click="editingRoles = true">修改</el-button></div>
<label v-else>声道角色(人工确认)<el-select :model-value="channelRoles" :disabled="!canEditReview || (busy && mutation !== 'save')" @update:model-value="setChannelRoles"><el-option label="角色待确认" value="unconfirmed" /><el-option label="左客服端 / 右患者或家属端" value="left_service" /><el-option label="右客服端 / 左患者或家属端" value="right_service" /></el-select></label>
<p v-if="savedChannelRoles === 'unconfirmed' || editingRoles || roleDirty" class="muted">声道不等于已核实的说话人身份。角色标注不自动重新提炼;变更后保存草稿会取消全部采纳,须重新核对。</p>
<p v-if="savedChannelRoles !== 'unconfirmed' && !roleDirty" class="muted">当前角色已确认,无需再次选择;只有左右标错时才需修改。</p>
<p v-if="roleDirty" class="review-error" role="status">角色标注正在等待保存;保存后请逐项重新核对。</p>
</section>
<section v-if="detail.role_check?.conflict || (detail.can_reextract !== undefined && savedChannelRoles !== extractionRoles && savedChannelRoles !== 'unconfirmed')" class="role-reextract" aria-label="角色纠错与重新提炼">
<strong>{{ detail.role_check?.conflict ? '声道角色与转写内容可能不一致' : '审核角色已修改,原提炼结果尚未更新' }}</strong>
<p>{{ detail.role_check?.message || '修改角色标注不会自动改变已生成的建议,可按核实后的角色重新提炼。' }}</p>
<blockquote v-for="(evidence, index) in detail.role_check?.evidence || []" :key="index"><span>{{ evidence.channel === 0 ? '左声道' : '右声道' }} · {{ audioTimestamp(evidence.start_ms) }}:{{ evidence.text }}</span><el-button v-if="detail.audio_available" link type="primary" @click="loadDialogue(evidence.start_ms)">回听依据</el-button></blockquote>
<p>当前提炼依据:{{ extractionRoleLabel(extractionRoles) }}。{{ reextractTarget !== 'unconfirmed' ? `待确认的新角色:${extractionRoleLabel(reextractTarget)}。` : '请先回听并修改上方角色标注。' }}建议仅供核对,系统不会自动交换角色。</p>
<el-button type="primary" plain :disabled="!canReextract || busy || dirty || reextractTarget === 'unconfirmed' || reextractTarget === extractionRoles" @click="reextractWithRoles">确认角色并重新提炼</el-button>
<p v-if="dirty">请先完成当前单项核对或取消编辑,等待审核草稿保存后再重新提炼。</p>
<p v-else-if="detail.reextract_block_reason">{{ detail.reextract_block_reason }}</p>
<p class="muted">复用已完成的转写,不重复语音识别;旧结果保留,重新提炼不自动写入病例。</p>
</section>
<p v-if="(detail.extraction_revision || 0) > 0" class="muted">第 {{ (detail.extraction_revision || 0) + 1 }} 版提炼 · {{ extractionRoleLabel(extractionRoles) }} · 历史结果已保留</p>
<FollowupAudioReview :key="selectedId" ref="reviewRef" v-model:items="reviewItems" :fields="detail.fields || capabilities.fields" :disabled="!canEditReview || uploading || (mutation !== '' && mutation !== 'save')" :can-daily="capabilities.can_daily" :applied="detail.status === 'applied'" :uncertainties="detail.uncertainties" :snapshot-items="detail.items" :channel-roles="savedChannelRoles" :save-state="saveState" :persisted-revision="persistedRevision" @saved-next="saveDraft(true)" @seek="loadDialogue">
<template #player>
<div class="audio-player">
@@ -144,13 +156,13 @@
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
FollowupAudioError, followupAudioApply, followupAudioBlob, followupAudioCreate,
FollowupAudioError, followupAudioReextract, followupAudioDelete, followupAudioApply, followupAudioBlob, followupAudioCreate,
followupAudioDetail, followupAudioLists, followupAudioRetry, followupAudioSaveDraft,
followupAudioUploadChunk, followupAudioUploadComplete, followupAudioUploadSession,
type FollowupAudioChannel, type FollowupCapabilities, type FollowupChannelRoles, type FollowupReviewItem, type FollowupTaskDetail, type FollowupTaskSummary
} from '@/api/followupAudio'
import FollowupAudioReview from './FollowupAudioReview.vue'
import { channelPlaybackLabel, dialogueWindows, dialoguePlaybackStart, audioTimestamp, changedReviewTarget, cloneReviewItems, createFollowupScope, followupAudioReady, followupCanApply, followupCanReview, followupChannelLabel, followupError, followupFeatureEnabled, followupProgressText, followupTaskStatus, hasStereoTranscript, normalizedChannelRoles, rebaseReviewItems, retainedTranscriptNotice, reviewFieldIssue, reviewIssue, reviewPending, uploadChunks, uploadIssue } from './followupAudioState'
import { channelPlaybackLabel, dialogueWindows, dialoguePlaybackStart, audioTimestamp, changedReviewTarget, cloneReviewItems, createFollowupScope, followupAudioReady, followupCanApply, followupCanReview, followupChannelLabel, followupError, followupFeatureEnabled, followupProgressText, followupTaskStatus, hasStereoTranscript, normalizedChannelRoles, rebaseReviewItems, retainedTranscriptNotice, reviewBatchIssue, reviewFieldIssue, reviewIssue, reviewPending, uploadChunks, uploadIssue } from './followupAudioState'
import { createFollowupAudioPlayback, type FollowupPlaybackChannel } from './followupAudioPlayback'
const props = withDefaults(defineProps<{
diagnosisId: number; viewOnly?: boolean; active?: boolean; capabilities: FollowupCapabilities;
@@ -194,7 +206,7 @@ const uploading = ref(false)
const uploadProgress = ref(0)
const uploadStage = ref('')
const createUncertain = ref(false)
const mutation = ref<'save' | 'apply' | 'retry' | ''>('')
const mutation = ref<'save' | 'apply' | 'retry' | 'delete' | 'reextract' | ''>('')
const errorMessage = ref('')
const audioUrl = ref('')
const audioElement = ref<HTMLAudioElement | null>(null)
@@ -210,6 +222,12 @@ const audioReady = computed(() => followupAudioReady(props.capabilities))
const canUpload = computed(() => !props.viewOnly && featureEnabled.value && audioReady.value && props.capabilities.can_upload && props.capabilities.models.length > 0)
const canEditReview = computed(() => !props.viewOnly && followupCanReview(props.capabilities, !!detail.value?.preview_only) && detail.value?.status === 'review')
const canApplyReview = computed(() => !props.viewOnly && followupCanApply(props.capabilities, !!detail.value?.preview_only) && detail.value?.status === 'review')
const extractionRoles = computed(() => normalizedChannelRoles(detail.value?.extraction_channel_roles))
const reextractTarget = computed<FollowupChannelRoles>(() => {
if (savedChannelRoles.value !== 'unconfirmed' && savedChannelRoles.value !== extractionRoles.value) return savedChannelRoles.value
return normalizedChannelRoles(detail.value?.role_check?.suggested_roles)
})
const canReextract = computed(() => !props.viewOnly && featureEnabled.value && detail.value?.status === 'review' && detail.value?.can_reextract === true)
const selectedCount = computed(() => reviewItems.value.filter(item => item.selected).length)
const pendingCount = computed(() => reviewItems.value.filter(item => reviewPending(item, detail.value?.fields || props.capabilities.fields, props.capabilities.can_daily)).length + (detail.value?.uncertainties.length || 0))
const applyIssue = computed(() => previewOnly.value ? '测试预览仅保存审核草稿,不允许确认写入病历'
@@ -220,7 +238,7 @@ const applyIssue = computed(() => previewOnly.value ? '测试预览仅保存审
: hasStereo.value && savedChannelRoles.value === 'unconfirmed' ? '请先回听并确认声道角色,保存草稿后重新核对建议'
: changedReviewTarget(reviewItems.value, detail.value?.items || [])
? '写入目标或记录日期已更改,请先保存审核草稿取得新快照,再核对并采纳'
: reviewItems.value.map(item => reviewFieldIssue(item, detail.value?.fields || props.capabilities.fields) || reviewIssue(item, props.capabilities.can_daily)).find(Boolean) || '')
: reviewBatchIssue(reviewItems.value, detail.value?.fields || props.capabilities.fields) || reviewItems.value.map(item => reviewFieldIssue(item, detail.value?.fields || props.capabilities.fields) || reviewIssue(item, props.capabilities.can_daily)).find(Boolean) || '')
const effectiveActive = computed(() => props.active && featureEnabled.value && documentVisible.value)
const scope = createFollowupScope()
let timer: ReturnType<typeof setTimeout> | undefined
@@ -270,9 +288,25 @@ function setChannelRoles(value: unknown) {
if (!canEditReview.value || (busy.value && mutation.value !== 'save') || !hasStereo.value || !['unconfirmed', 'left_service', 'right_service'].includes(String(value))) return
channelRoles.value = value as FollowupChannelRoles
}
async function readDetail(id: number, preserve = false) {
function taskUnavailable(error: unknown): boolean {
return error instanceof FollowupAudioError && (error.code === 'FOLLOWUP_AUDIO_TASK_UNAVAILABLE' || error.message.includes('FOLLOWUP_AUDIO_TASK_UNAVAILABLE'))
}
function forgetUnavailableTask(id: number) {
if (selectedId.value !== id) return
stop(); resetRoles(); selectedId.value = 0; detail.value = null; reviewItems.value = []; snapshot.value = '[]'; detailSections.value = []
tasks.value = tasks.value.filter(row => row.id !== id)
errorMessage.value = '录音已删除或不再可访问,已关闭本页缓存与播放;未写入病例。'
void refresh()
}
async function readDetail(id: number, preserve = false, verifyOnly = false) {
const ticket = scope.capture()
const fresh = await followupAudioDetail(id, ticket.signal)
let fresh: FollowupTaskDetail
try { fresh = await followupAudioDetail(id, ticket.signal) }
catch (error) {
if (scope.current(ticket) && id === selectedId.value && taskUnavailable(error)) { forgetUnavailableTask(id); return }
throw error
}
if (verifyOnly && detail.value && fresh.version === detail.value.version && fresh.status === detail.value.status) return
if (!scope.current(ticket) || id !== selectedId.value || (detail.value && fresh.version < detail.value.version)) return
preserve = preserve || (!!detail.value && dirty.value)
const newlyApplied = detail.value?.status === 'review' && fresh.status === 'applied'
@@ -292,6 +326,9 @@ async function refresh() {
const updated = tasks.value.find(task => task.id === selectedId.value)
if (updated && (!detail.value || updated.version > detail.value.version || (updated.version >= detail.value.version && updated.status !== detail.value.status) || updated.status === 'running')) {
await readDetail(updated.id, dirty.value)
} else if (!updated && selectedId.value && detail.value) {
// A limited list can omit older tasks; only an authoritative detail denial revokes them.
await readDetail(selectedId.value, false, true)
}
} catch (error) { if (scope.current(ticket)) errorMessage.value = followupError(error) }
finally {
@@ -382,6 +419,7 @@ async function submitUpload() {
}
async function handleReviewError(error: unknown) {
const ticket = scope.capture()
if (taskUnavailable(error) && detail.value) { forgetUnavailableTask(detail.value.id); return }
errorMessage.value = followupError(error)
const stale = error instanceof FollowupAudioError && error.code === 'FOLLOWUP_AUDIO_STALE_REVIEW'
if (stale || /STALE_REVIEW|版本|快照|已变化/.test(errorMessage.value)) {
@@ -488,6 +526,57 @@ async function applySelected() {
} catch (error) { if (scope.current(ticket)) await handleReviewError(error) }
finally { if (scope.current(ticket)) { mutation.value = ''; await refresh() } }
}
function extractionRoleLabel(roles: FollowupChannelRoles): string {
return roles === 'left_service' ? '左客服 / 右患者或家属' : roles === 'right_service' ? '右客服 / 左患者或家属' : '角色未确认'
}
async function reextractWithRoles() {
const roles = reextractTarget.value
if (!canReextract.value || !detail.value || busy.value || roles === 'unconfirmed' || roles === extractionRoles.value) return
if (dirty.value) { ElMessage.warning('请先完成或取消当前审核修改,等待草稿保存后再重新提炼'); return }
const ticket = scope.capture(), id = detail.value.id, version = detail.value.version, diagnosisId = props.diagnosisId
const current = () => scope.current(ticket) && diagnosisId === props.diagnosisId && selectedId.value === id
clearAutosave(); clearTimer(); mutation.value = 'reextract'; errorMessage.value = ''
let confirmed = false
try {
await ElMessageBox.confirm(`确认已回听并核实角色为“${extractionRoleLabel(roles)}”?将保留旧版结果,复用已完成的转写重新提炼,不重复语音识别;新建议须重新审核,不自动写入病例。`, '确认角色并重新提炼', { type: 'warning', confirmButtonText: '角色正确,开始重新提炼', cancelButtonText: '返回回听' })
if (!current() || !canReextract.value || dirty.value) return
confirmed = true
const fresh = await followupAudioReextract({ id, version, channel_roles: roles }, ticket.signal)
if (!current()) return
installDetail(fresh, false); saveState.value = 'idle'; editingRoles.value = false
ElMessage.success('已提交重新提炼,将复用原转写;新结果仍需审核,不自动写入病例')
} catch (error) { if (confirmed && current()) await handleReviewError(error) }
finally { if (current()) { mutation.value = ''; scheduleAutosave(); await refresh() } }
}
function canDeleteTask(task: FollowupTaskSummary): boolean {
return !props.viewOnly && featureEnabled.value && task.can_delete === true && ['review', 'failed'].includes(task.status)
}
async function deleteRecording(task: FollowupTaskSummary) {
if (busy.value || !canDeleteTask(task)) return
const ticket = scope.capture(), diagnosisId = props.diagnosisId, id = task.id, version = task.version
const current = () => scope.current(ticket) && diagnosisId === props.diagnosisId
clearAutosave(); clearTimer(); mutation.value = 'delete'; errorMessage.value = ''
let confirmed = false
try {
await ElMessageBox.confirm('删除后,该录音任务及审核草稿将从列表移除,未保存修改会丢弃;不删除或回滚病例。原录音和转写仍按原保留期限清理。重新上传同一文件将创建新的分析任务。确认删除?', '删除录音任务', { type: 'warning', confirmButtonText: '确认删除', cancelButtonText: '保留录音' })
if (!current() || !canDeleteTask(task)) return
confirmed = true
await followupAudioDelete({ id, version }, ticket.signal)
if (!current()) return
// Fence pending playback, autosaves and reads; deletion never revives a stale draft.
if (selectedId.value === id) {
stop(); resetRoles(); selectedId.value = 0; detail.value = null; reviewItems.value = []; snapshot.value = '[]'; detailSections.value = []
}
tasks.value = tasks.value.filter(row => row.id !== id)
errorMessage.value = ''
ElMessage.success('录音任务已删除,未修改病例。原资料按保留策略清理。')
await refresh()
} catch (error) {
if (confirmed && current()) errorMessage.value = followupError(error)
} finally {
if (current()) { mutation.value = ''; scheduleAutosave(); await refresh() }
}
}
async function retryTask() {
if (!detail.value?.can_retry || detail.value.status !== 'failed' || !canUpload.value || busy.value) return
const ticket = scope.capture()
@@ -577,6 +666,11 @@ h3 { margin: 0; font-size: 14px; font-weight: 600; }
.detail-heading { align-items: flex-start; }
.recording-title { min-width: 0; }
.recording-title h3 { overflow-wrap: anywhere; line-height: 1.6; }
.role-reextract { padding: 12px; border: 1px solid var(--el-color-warning-light-5); background: var(--el-color-warning-light-9); border-radius: 6px; display: grid; gap: 8px; }
.role-reextract p { margin: 0; line-height: 1.6; }
.role-reextract blockquote { margin: 0; padding: 8px; background: var(--el-bg-color); white-space: pre-wrap; overflow-wrap: anywhere; }
.role-reextract :deep(.el-button) { justify-self: start; }
.detail-actions { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
.detail-heading :deep(.el-tag) { flex-shrink: 0; }
.detail-loading { padding: 32px; text-align: center; color: var(--el-text-color-secondary); }
.processing-state, .applied-note { margin: 0; color: var(--el-text-color-secondary); font-size: 13px; }
@@ -32,8 +32,8 @@
</el-table-column>
</el-table>
</div>
<section v-if="group === 'pending' && uncertainties?.length" class="uncertainty-list" aria-label="原文待核实信息">
<strong>原文中还需补充的信息</strong>
<section v-if="(group === 'pending' || !items.length) && uncertainties?.length" class="uncertainty-list" aria-label="原文待核实信息">
<strong>本次未能确认的信息与原因</strong>
<ul><li v-for="(value, index) in uncertainties" :key="index">{{ uncertaintyText(value) }}</li></ul>
</section>
<section ref="reviewWorkspace" class="review-workspace" tabindex="-1" aria-label="同页核对与回听">
@@ -70,6 +70,22 @@ export function fieldText(value: FollowupValue | undefined, field: FollowupField
export function hasEditableReviewFields(item: FollowupReviewItem, fields: FollowupFields): boolean {
return Object.keys(item.values).some(key => fields[item.kind]?.some(field => field.key === key && !field.readonly))
}
/** Prevent multiple selected writes to the same diagnosis field; never silently pick a last value. */
export function reviewBatchIssue(items: FollowupReviewItem[], fields: FollowupFields): string {
const touched = new Set<string>()
for (const item of items.filter(item => item.selected)) {
if (item.kind === 'diagnosis') {
for (const key of Object.keys(item.values)) {
if (touched.has(key)) {
const label = fields.diagnosis?.find(field => field.key === key)?.label || key
return `${label}存在多条选中建议,请合并内容到一项或仅保留一项后再确认写入`
}
touched.add(key)
}
}
}
return ''
}
export function reviewFieldIssue(item: FollowupReviewItem, fields: FollowupFields): string {
if (!item.selected) return ''
for (const key of Object.keys(item.values)) {
+60 -13
View File
@@ -671,9 +671,14 @@
<el-empty v-else description="请先保存诊单后查看" />
</el-tab-pane>
<el-tab-pane v-if="followupCapabilities?.enabled && formData.id" label="回访录音" name="followupAudio" lazy>
<el-tab-pane v-if="formData.id && hasFollowupAudioPermission" label="回访录音" name="followupAudio" lazy>
<el-alert v-if="followupCapabilitiesLoading" title="正在检查回访录音状态…" type="info" :closable="false" show-icon />
<div v-else-if="followupCapabilitiesError" role="alert">
<el-alert :title="followupCapabilitiesError" type="error" :closable="false" show-icon />
<el-button class="mt-3" @click="loadFollowupCapabilities">重新加载</el-button>
</div>
<FollowupAudioPanel
v-if="visible && formData.id && followupCapabilities"
v-else-if="visible && followupCapabilities?.enabled && followupCapabilitiesDiagnosisId === Number(formData.id)"
:key="Number(formData.id)"
ref="followupAudioRef"
:diagnosis-id="Number(formData.id)"
@@ -684,6 +689,13 @@
:before-apply="canApplyFollowup"
@applied="handleFollowupApplied"
/>
<el-alert
v-else
:title="followupCapabilities?.test_scope_allowed === false ? '当前诊单未开放回访录音' : '当前未启用回访录音,请联系管理员确认'"
type="info"
:closable="false"
show-icon
/>
</el-tab-pane>
<!-- 病历记录标签页(开方后自动显示) -->
@@ -833,6 +845,9 @@ const prescriptionRef = ref()
const dailyMatrixRef = ref<{ refresh?: () => Promise<void> | void } | null>(null)
const followupAudioRef = ref<{ confirmLeave: () => Promise<boolean> } | null>(null)
const followupCapabilities = ref<FollowupCapabilities | null>(null)
const followupCapabilitiesLoading = ref(false)
const followupCapabilitiesError = ref('')
const followupCapabilitiesDiagnosisId = ref<number | null>(null)
const basicSnapshot = ref('')
let diagnosisGeneration = 0
let capabilitiesRequest: AbortController | undefined
@@ -847,6 +862,7 @@ const submitting = ref(false)
/** 拥有后手机号可正常编辑,失焦不再强制脱敏 */
const hasPhonePlainPermission = computed(() => hasPermission(['tcm.diagnosis/phonePlain']))
const hasDailyRecordPermission = computed(() => hasPermission(['tcm.diagnosis/dailyRecord']))
const hasFollowupAudioPermission = computed(() => hasPermission(['tcm.diagnosis/followupAudio']))
const patientBasicLocked = ref(false)
const canEditPatientBasicFromApi = ref(true)
const latestPrescriptionOrder = ref<{
@@ -1021,18 +1037,50 @@ async function handleFollowupApplied(diagnosisId: number) {
if (generation === diagnosisGeneration) feedback.msgWarning('录音已采纳,但病历或日常记录刷新失败,请手动刷新查看')
}
}
watch([visible, () => formData.value.id], async ([isVisible, id]) => {
function resetFollowupCapabilities() {
capabilitiesRequest?.abort()
capabilitiesRequest = undefined
followupCapabilities.value = null
if (!isVisible || !id) return
followupCapabilitiesDiagnosisId.value = null
followupCapabilitiesLoading.value = false
followupCapabilitiesError.value = ''
}
async function loadFollowupCapabilities(): Promise<void> {
// A rapid second click must not create another request for the same context.
if (followupCapabilitiesLoading.value) return
resetFollowupCapabilities()
const id = Number(formData.value.id)
if (!visible.value || !id || !hasFollowupAudioPermission.value) return
const generation = diagnosisGeneration
const request = new AbortController()
capabilitiesRequest = request
followupCapabilitiesLoading.value = true
const isCurrent = () => capabilitiesRequest === request && !request.signal.aborted
&& generation === diagnosisGeneration && visible.value && Number(formData.value.id) === id
try {
const result = await followupAudioCapabilities(Number(id), request.signal)
if (!request.signal.aborted && visible.value && String(formData.value.id) === String(id)) followupCapabilities.value = result
} catch { /* Fail closed: an unavailable capability endpoint must not expose this feature. */ }
})
onBeforeUnmount(() => { diagnosisGeneration++; capabilitiesRequest?.abort() })
const result = await followupAudioCapabilities(id, request.signal)
if (!isCurrent()) return
if (typeof result?.enabled !== 'boolean') throw new Error('Invalid capability response')
followupCapabilities.value = result
followupCapabilitiesDiagnosisId.value = id
} catch {
if (!isCurrent()) return
// No endpoint failure (including permission denial) may mount the panel.
followupCapabilitiesError.value = '回访录音状态加载失败,请重新加载;若仍失败,请联系管理员检查权限或服务状态'
} finally {
if (isCurrent()) {
followupCapabilitiesLoading.value = false
capabilitiesRequest = undefined
}
}
}
watch([visible, () => formData.value.id, hasFollowupAudioPermission], () => {
// Invalidate synchronously on patient switches and permission changes.
if (!hasFollowupAudioPermission.value && activeTab.value === 'followupAudio') activeTab.value = 'basic'
resetFollowupCapabilities()
void loadFollowupCapabilities()
}, { flush: 'sync' })
onBeforeUnmount(() => { diagnosisGeneration++; resetFollowupCapabilities() })
/** 就诊卡创建来源(与 zyt_tcm_diagnosis.create_source 一致) */
const createSourceOptions = [
@@ -1360,7 +1408,7 @@ const open = async (type: string, id?: number) => {
const generation = ++diagnosisGeneration
submitting.value = false
basicSnapshot.value = ''
followupCapabilities.value = null
resetFollowupCapabilities()
formData.value.id = ''
viewOnly.value = false
mode.value = type
@@ -1390,7 +1438,7 @@ const openViewOnly = async (id: number) => {
const generation = ++diagnosisGeneration
submitting.value = false
basicSnapshot.value = ''
followupCapabilities.value = null
resetFollowupCapabilities()
formData.value.id = ''
viewOnly.value = true
mode.value = 'edit'
@@ -1490,8 +1538,7 @@ const handleOpenPrescription = () => {
const handleClose = async () => {
if (followupAudioRef.value && !await followupAudioRef.value.confirmLeave()) return
diagnosisGeneration++
capabilitiesRequest?.abort()
followupCapabilities.value = null
resetFollowupCapabilities()
basicSnapshot.value = ''
formRef.value?.resetFields()
formData.value = {
@@ -0,0 +1,47 @@
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 file = process.env.FOLLOWUP_EXERCISE_MATRIX_SOURCE || path.resolve(__dirname, '../src/views/tcm/diagnosis/components/DailyMatrix.vue')
const source = fs.readFileSync(file, 'utf8')
function setup() {
const descriptor = parse(source, {filename:file}).descriptor
const compiled = compileScript(descriptor, {id:'exercise-null'})
const output = ts.transpileModule(compiled.content, {compilerOptions:{target:ts.ScriptTarget.ES2022,module:ts.ModuleKind.CommonJS}}).outputText
const calls=[]; const warnings=[]; const module={exports:{}}
const api={diagnosisTrackingWindow:async()=>({}),diagnosisTrackingNotes:async()=>[],exerciseRecordEdit:async p=>calls.push(p),exerciseRecordAdd:async p=>calls.push(p)}
new Function('require','module','exports',output)(name=>name==='vue'?{...vue,onMounted(){},onUnmounted(){}}:name==='@/utils/perm'?{hasPermission:()=>true}:name==='@/api/tcm'?api:name==='@/utils/feedback'?{default:{msgWarning:m=>warnings.push(m)}}:{default:{}},module,module.exports)
const scope=vue.effectScope()
const matrix=scope.run(()=>module.exports.default.setup({diagnosisId:1,patientId:101,readOnly:false},{expose(){}}))
return {matrix,calls,warnings,dispose:()=>scope.stop()}
}
test('real DailyMatrix edit and submit preserve null duration/intensity',async()=>{
const f=setup(); f.matrix.openExerciseRecord({id:1,record_date:'2026-09-29',exercise_type:'散步',duration:null,intensity:null},'2026-09-29')
assert.equal(f.matrix.exerciseForm.value.duration,null);assert.equal(f.matrix.exerciseForm.value.intensity,null)
f.matrix.exerciseForm.value.note='仅改备注';await f.matrix.submitExercise()
assert.equal(f.calls.length,1);assert.equal(f.calls[0].duration,null);assert.equal(f.calls[0].intensity,null);assert.deepEqual(f.warnings,[]);f.dispose()
})
test('missing keys in existing row do not inherit manual-entry defaults',()=>{
const f=setup();f.matrix.openExerciseRecord({id:2,exercise_type:'散步'},'2026-09-29')
assert.equal(f.matrix.exerciseForm.value.duration,null);assert.equal(f.matrix.exerciseForm.value.intensity,null);f.dispose()
})
test('explicit known and zero values remain unchanged; cleared duration submits null',async()=>{
const f=setup();f.matrix.openExerciseRecord({id:2,exercise_type:'散步',duration:0,intensity:1},'2026-09-29')
await f.matrix.submitExercise();assert.equal(f.calls[0].duration,0);assert.equal(f.calls[0].intensity,1)
f.matrix.exerciseForm.value.duration=undefined;await f.matrix.submitExercise();assert.equal(f.calls[1].duration,null);f.dispose()
})
test('unknown intensity option maps to null without conflating known low intensity',()=>{
const f=setup();f.matrix.openExerciseRecord({id:1,exercise_type:'散步',duration:null,intensity:null},'2026-09-29')
assert.equal(f.matrix.exerciseIntensity.value,'');f.matrix.exerciseIntensity.value=1;assert.equal(f.matrix.exerciseForm.value.intensity,1)
f.matrix.exerciseIntensity.value='';assert.equal(f.matrix.exerciseForm.value.intensity,null)
assert.equal(f.matrix.intensityLabel(null),'未记录');assert.equal(f.matrix.intensityLabel(1),'低强度');f.dispose()
})
test('matrix compiles and detail rendering explicitly distinguishes unknown from zero',()=>{
const descriptor=parse(source,{filename:file}).descriptor;const script=compileScript(descriptor,{id:'exercise-compile'})
const render=compileTemplate({source:descriptor.template.content,filename:file,id:'exercise-compile',compilerOptions:{bindingMetadata:script.bindings}})
assert.deepEqual(render.errors,[]);assert.ok(/<el-option label="未记录" value=""/.test(source), "explicit unknown option exists")
assert.ok(/record\.duration == null \? '未记录'/.test(source), 'null duration renders unknown')
})
+333 -2
View File
@@ -38,6 +38,8 @@ function setupPanel(overrides = {}, propsPatch = {}, options = {}) {
followupAudioUploadChunk: async (id, index, blob) => { calls.push(['chunk', id, index, blob.size]); return { index, received: true } },
followupAudioUploadComplete: async id => { calls.push(['complete', id]); return { upload_id: id, duration_seconds: 10, sha256: 'test' } },
followupAudioCreate: async payload => { calls.push(['create', payload]); return { task_id: 2, status: 'queued' } },
followupAudioReextract: async payload => { calls.push(['reextract', payload]); return task(payload.id, { status: 'queued', version: payload.version + 1, items: [], extraction_revision: 1, extraction_channel_roles: payload.channel_roles }) },
followupAudioDelete: async payload => { calls.push(['delete', payload]); return { id: payload.id, status: 'deleted', version: payload.version + 1 } },
followupAudioRetry: async id => { calls.push(['retry', id]); return { id, status: 'queued' } },
...overrides
}
@@ -267,7 +269,7 @@ test('authenticated audio object URLs revoked on hide and stale blobs never crea
test('editor capability gate, dirty guard and successful apply hook wire diagnosis plus daily refresh', () => {
const source = fs.readFileSync(path.join(componentDir, '../edit.vue'), 'utf8')
assert.match(source, /v-if="followupCapabilities\?\.enabled && formData.id"/)
assert.match(source, /<el-tab-pane v-if="formData.id && hasFollowupAudioPermission" label="回访录音"/)
assert.match(source, /:before-leave="beforeTabLeave"/)
assert.match(source, /next === 'followupAudio' && basicDirty.value/)
assert.match(source, /await loadDiagnosisDetailIntoForm\(diagnosisId, true\)/)
@@ -1409,7 +1411,7 @@ test('actual patient editor outside preview allowlist still opens and edits its
await editor.handleSubmit()
assert.equal(edits.length, 1, 'ordinary diagnosis mock API remains usable; no real patient write')
assert.equal(edits[0].remark, '合成普通表单编辑')
assert.match(descriptor.template.content, /v-if="followupCapabilities\?\.enabled && formData.id"/)
assert.match(descriptor.template.content, /<el-tab-pane v-if="formData.id && hasFollowupAudioPermission" label="回访录音"/)
} finally { scope.stop() }
})
@@ -1793,3 +1795,332 @@ test('detail fetch begun before an edit preserves that edit when the new snapsho
assert.equal(f.calls.filter(x => x[0] === 'save').length, 0)
f.dispose()
})
test('delete requires actor-aware capability and blocks applied/running/unknown tasks', async () => {
const f=setupPanel();await settle()
for (const row of [task(), task(1,{can_delete:false}),task(1,{can_delete:true,status:'applied'}),task(1,{can_delete:true,status:'running'}),task(1,{can_delete:true,status:'needs_reconciliation'})]) await f.panel.deleteRecording(row)
assert.equal(f.calls.filter(c=>c[0]==='delete').length,0)
f.props.viewOnly=true;await f.panel.deleteRecording(task(1,{can_delete:true}));assert.equal(f.calls.filter(c=>c[0]==='delete').length,0);f.dispose()
})
test('confirmed deletion sends optimistic version once, clears selected editor and never applies', async () => {
let removed=false;const current=task(1,{can_delete:true})
const f=setupPanel({followupAudioDetail:async()=>current,followupAudioLists:async()=>({items:removed?[]:[current]}),followupAudioDelete:async p=>{f.calls.push(['delete',p]);removed=true;return {id:p.id,status:'deleted',version:p.version+1}}})
await settle();await f.panel.openTask(1);await f.panel.deleteRecording(current)
assert.deepEqual(f.calls.find(c=>c[0]==='delete')[1],{id:1,version:1});assert.equal(f.panel.selectedId.value,0);assert.equal(f.panel.detail.value,null);assert.deepEqual(f.panel.tasks.value,[]);assert.deepEqual(f.panel.reviewItems.value,[])
assert.equal(f.calls.some(c=>c[0]==='apply'),false);assert.equal(f.panel.mutation.value,'');f.dispose()
})
test('delete cancellation keeps recording and drafts, patient switch before confirm sends nothing', async () => {
const f=setupPanel({}, {}, {confirm:async()=>{throw new Error('cancel')}});await settle();await f.panel.openTask(1);await f.panel.deleteRecording(task(1,{can_delete:true}));assert.equal(f.panel.selectedId.value,1);assert.equal(f.calls.some(c=>c[0]==='delete'),false);assert.equal(f.panel.mutation.value,'');f.dispose()
const answer=deferred();const g=setupPanel({}, {}, {confirm:()=>answer.promise});await settle();const pending=g.panel.deleteRecording(task(1,{can_delete:true}));g.props.diagnosisId=20;await settle();answer.resolve();await pending;assert.equal(g.calls.some(c=>c[0]==='delete'),false);g.dispose()
})
test('late delete result cannot clear another patient and errors preserve current recording', async () => {
const response=deferred();const f=setupPanel({followupAudioDelete:async p=>{f.calls.push(['delete',p]);return response.promise}});await settle();await f.panel.openTask(1)
const deleting=f.panel.deleteRecording(task(1,{can_delete:true}));await settle();const duplicate=f.panel.deleteRecording(task(1,{can_delete:true}));await duplicate;assert.equal(f.calls.filter(c=>c[0]==='delete').length,1)
f.props.diagnosisId=20;await settle();await f.panel.openTask(2);response.resolve({id:1,status:'deleted',version:2});await deleting;assert.equal(f.panel.selectedId.value,2);assert.equal(f.panel.detail.value.id,2);f.dispose()
const g=setupPanel({followupAudioDelete:async()=>{throw new apiModule.FollowupAudioError('版本已变化')}});await settle();await g.panel.openTask(1);await g.panel.deleteRecording(task(1,{can_delete:true}));assert.equal(g.panel.selectedId.value,1);assert.match(g.panel.errorMessage.value,/版本已变化/);g.dispose()
})
test('delete API has no automatic retry and empty results expose uncertainty reasons without tab switching', async () => {
const requests=[];const api=loadTs(path.join(root,'src/api/followupAudio.ts'),()=>({default:{post:async(config,options)=>{requests.push({config,options});return {code:1,data:{id:1,status:'deleted',version:2}}}}}))
await api.followupAudioDelete({id:1,version:1});assert.equal(requests[0].config.url,'/tcm.followupAudio/delete');assert.equal(requests[0].options.isOpenRetry,false)
const source=fs.readFileSync(path.join(componentDir,'FollowupAudioReview.vue'),'utf8');assert.match(source,/\(group === 'pending' \|\| !items.length\) && uncertainties\?\.length/)
const panelSource=fs.readFileSync(path.join(componentDir,'FollowupAudioPanel.vue'),'utf8');assert.match(panelSource,/未生成可写入信息/);assert.match(panelSource,/不删除或回滚病例/)
})
test('remote deletion revalidates missing detail and releases cached audio/editor', async () => {
let deleted=false;const f=setupPanel({followupAudioLists:async()=>({items:deleted?[]:[task()]}),followupAudioDetail:async id=>{if(deleted)throw new apiModule.FollowupAudioError('FOLLOWUP_AUDIO_TASK_UNAVAILABLE');return task(id)}})
await settle();await f.panel.openTask(1);await f.panel.loadAudio();assert.equal(f.panel.audioUrl.value,'blob:private-0')
deleted=true;await f.panel.refresh();await settle()
assert.equal(f.panel.selectedId.value,0);assert.equal(f.panel.detail.value,null);assert.equal(f.panel.audioUrl.value,'');assert.deepEqual(f.revoked,['blob:private-0']);assert.deepEqual(f.panel.reviewItems.value,[]);assert.match(f.panel.errorMessage.value,/录音已删除/);f.dispose()
})
test('list pagination omission alone never discards current unsaved edits', async () => {
let omit=false;const f=setupPanel({followupAudioLists:async()=>({items:omit?[]:[task()]})});await settle();await f.panel.openTask(1)
f.panel.reviewItems.value[0].values.fasting_blood_sugar=6.9;omit=true;await f.panel.refresh()
assert.equal(f.panel.selectedId.value,1);assert.equal(f.panel.reviewItems.value[0].values.fasting_blood_sugar,6.9);assert.notEqual(f.panel.saveState.value,'conflict');f.dispose()
})
test('deleting another row resumes current task autosave without clearing its draft', async () => {
const f=setupPanel();await settle();await f.panel.openTask(1);f.panel.reviewItems.value[0].values.fasting_blood_sugar=6.9
await f.panel.deleteRecording(task(2,{can_delete:true}));assert.equal(f.panel.selectedId.value,1);assert.equal(f.panel.reviewItems.value[0].values.fasting_blood_sugar,6.9)
f.tick();await settle();assert.ok(f.calls.some(c=>c[0]==='save'&&c[1].id===1&&c[1].items[0].values.fasting_blood_sugar===6.9));f.dispose()
})
test('autosave denial for remotely deleted task clears local playback without another save', async () => {
let deleted=false;const f=setupPanel({followupAudioLists:async()=>({items:deleted?[]:[task()]}),followupAudioSaveDraft:async()=>{deleted=true;throw new apiModule.FollowupAudioError('FOLLOWUP_AUDIO_TASK_UNAVAILABLE')}})
await settle();await f.panel.openTask(1);await f.panel.loadAudio();f.panel.reviewItems.value[0].values.fasting_blood_sugar=6.9;await f.panel.saveDraft(true);await settle()
assert.equal(f.panel.selectedId.value,0);assert.equal(f.panel.audioUrl.value,'');assert.match(f.panel.errorMessage.value,/录音已删除/);f.dispose()
})
// Execute the real editor script and its actual tab template, with deferred network I/O.
function setupAudioEntry(permissions = ['*']) {
const userStore = vue.reactive({ perms: [...permissions], userInfo: { id: 1 } })
const permissionModule = loadTs(path.join(root, 'src/utils/perm.ts'), () => ({ default: () => userStore }))
const requests = [], warnings = [], hooks = {}, exposed = {}
const filename = path.join(componentDir, '../edit.vue')
const descriptor = parse(fs.readFileSync(filename, 'utf8'), { filename }).descriptor
const script = compileScript(descriptor, { id: 'entry-runtime' })
const panelComponent = { name: 'FollowupAudioPanel' }
const module = execute(script.content, name => {
if (name === 'vue') return { ...vue, onBeforeUnmount: callback => { hooks.unmount = callback } }
if (name === '@/api/tcm') return { tcmDiagnosisDetail: async ({ id }) => ({ id: String(id), patient_id: String(id + 100), phone: '', id_card: '', remark: '原始备注' }) }
if (name === '@/api/app') return { getDictData: async () => ({}) }
if (name === '@/api/followupAudio') return { followupAudioCapabilities: (id, signal) => { const pending = deferred(); requests.push({ id, signal, ...pending }); return pending.promise } }
if (name === '@/utils/feedback') return { default: { msgWarning: message => warnings.push(message) } }
if (name === '@/utils/perm') return permissionModule
if (name === '@/stores/modules/user') return { default: () => userStore }
if (name === '@/stores/modules/app') return { default: () => ({ getImageUrl: value => value }) }
if (name === 'element-plus') return { ElMessage: { warning() {} } }
if (name === '@element-plus/icons-vue' || name === '@/api/patient') return {}
if (name.endsWith('FollowupAudioPanel.vue')) return { default: panelComponent }
if (name.endsWith('.vue')) return { default: {} }
throw new Error(`Unexpected entry import: ${name}`)
})
const tab = descriptor.template.content.match(/<el-tab-pane[^>]+name="followupAudio"[\s\S]*?<\/el-tab-pane>/)[0]
const compiled = compileTemplate({ source: tab, filename, id: 'entry-tab', compilerOptions: { bindingMetadata: script.bindings } })
assert.deepEqual(compiled.errors, [])
const render = execute(compiled.code, () => ({ ...vue, resolveComponent: name => name })).render
const scope = vue.effectScope()
const editor = scope.run(() => module.default.setup({}, { expose: value => Object.assign(exposed, value), emit() {} }))
const dailyTab = descriptor.template.content.match(/<el-tab-pane\s+v-if="hasDailyRecordPermission"[\s\S]*?<\/el-tab-pane>/)[0]
const dailyCompiled = compileTemplate({ source: dailyTab, filename, id: 'daily-tab', compilerOptions: { bindingMetadata: script.bindings } })
assert.deepEqual(dailyCompiled.errors, [])
const renderDaily = execute(dailyCompiled.code, () => ({ ...vue, resolveComponent: name => name })).render
const nodes = (renderTab = render) => {
const collected = []
const visit = node => {
if (!node || typeof node !== 'object') return
if (Array.isArray(node)) { node.forEach(visit); return }
collected.push(node)
visit(node.children)
if (node.children?.default) visit(node.children.default())
}
visit(renderTab({}, [], {}, vue.proxyRefs(editor)))
return collected
}
return { editor, exposed, requests, warnings, nodes, userStore, hasDailyTab: () => nodes(renderDaily).some(node => node.type === 'el-tab-pane'), hasTab: () => nodes().some(node => node.type === 'el-tab-pane'), hasPanel: () => nodes().some(node => node.type === panelComponent), dispose: () => { hooks.unmount(); scope.stop() } }
}
test('saved diagnosis keeps audio entry during pending/error; manual retry recovers without losing dirty input', async () => {
const f = setupAudioEntry()
try {
await f.editor.open('edit', 10)
assert.equal(f.hasTab(), true)
assert.equal(f.hasPanel(), false)
assert.equal(f.editor.followupCapabilitiesLoading.value, true)
assert.ok(f.nodes().some(node => node.props?.title === '正在检查回访录音状态…'))
f.requests[0].reject(new Error('network offline')); await settle()
assert.equal(f.hasTab(), true)
assert.equal(f.hasPanel(), false)
assert.equal(f.editor.followupCapabilitiesLoading.value, false)
assert.match(f.editor.followupCapabilitiesError.value, /加载失败/)
assert.equal(f.requests.length, 1, 'no automatic retry')
f.editor.formData.value.remark = '保留未保存输入'
assert.equal(await f.editor.beforeTabLeave('followupAudio', 'basic'), false)
const retryButton = f.nodes().find(node => node.type === 'el-button')
const retry = retryButton.props.onClick()
const duplicate = f.editor.loadFollowupCapabilities()
assert.equal(f.requests.length, 2, 'rapid retries share the in-flight context')
assert.equal(f.editor.followupCapabilitiesError.value, '')
assert.equal(f.hasPanel(), false)
f.requests[1].resolve(caps()); await retry; await duplicate
assert.equal(f.hasTab(), true)
assert.equal(f.hasPanel(), true)
assert.equal(f.editor.formData.value.remark, '保留未保存输入')
assert.equal(f.editor.basicDirty.value, true)
assert.equal(f.editor.canApplyFollowup(), false)
assert.equal(await f.editor.beforeTabLeave('followupAudio', 'basic'), false)
} finally { f.dispose() }
})
test('disabled/scope-denied and permission-denied capability responses preserve entry without a panel', async () => {
for (const response of [{ ...caps(), enabled: false }, { ...caps(), enabled: false, test_scope_allowed: false }, new Error('403 permission denied'), null]) {
const f = setupAudioEntry()
try {
await f.editor.open('edit', 10)
if (response instanceof Error) f.requests[0].reject(response)
else f.requests[0].resolve(response)
await settle()
assert.equal(f.hasTab(), true)
assert.equal(f.hasPanel(), false)
assert.equal(f.editor.followupCapabilitiesLoading.value, false)
const title = f.nodes().find(node => node.type === 'el-alert').props.title
assert.match(title, response instanceof Error || response === null ? /加载失败/ : /未启用|未开放/)
assert.equal(f.requests.length, 1)
} finally { f.dispose() }
}
})
test('old capability success/error/finally cannot affect a new patient or same-ID reopened context', async () => {
for (const oldFails of [false, true]) for (const id of [10, 20]) {
const f = setupAudioEntry()
try {
await f.editor.open('edit', 10)
const old = f.requests[0]
const opening = f.editor.open('edit', id)
assert.equal(old.signal.aborted, true, 'open resets before awaiting dictionaries')
assert.equal(f.editor.followupCapabilities.value, null)
await opening
assert.equal(f.requests.length, 2)
if (oldFails) old.reject(new Error('late old error'))
else old.resolve(caps())
await settle()
assert.equal(f.editor.followupCapabilities.value, null)
assert.equal(f.editor.followupCapabilitiesError.value, '')
assert.equal(f.editor.followupCapabilitiesLoading.value, true, 'old finally cannot end new loading')
assert.equal(f.hasPanel(), false)
f.requests[1].resolve({ ...caps(), enabled: false }); await settle()
assert.equal(f.editor.followupCapabilitiesDiagnosisId.value, id)
assert.equal(f.editor.followupCapabilities.value.enabled, false)
assert.equal(f.hasPanel(), false)
} finally { f.dispose() }
}
})
test('successful capabilities are immediately invalidated on patient switch; late retry completion stays isolated', async () => {
const f = setupAudioEntry()
try {
await f.editor.open('edit', 10); f.requests[0].resolve(caps()); await settle()
assert.equal(f.hasPanel(), true)
f.editor.formData.value.id = '20'
assert.equal(f.hasPanel(), false)
assert.equal(f.editor.followupCapabilities.value, null)
f.requests[1].reject(new Error('second patient error')); await settle()
const retry = f.editor.loadFollowupCapabilities()
await f.editor.openViewOnly(30)
assert.equal(f.requests[2].signal.aborted, true)
f.requests[3].resolve(caps()); await settle()
f.requests[2].reject(new Error('old retry error')); await retry
assert.equal(f.hasPanel(), true)
assert.equal(f.editor.followupCapabilitiesDiagnosisId.value, 30)
assert.equal(f.editor.followupCapabilitiesError.value, '')
assert.equal(f.editor.viewOnly.value, true)
} finally { f.dispose() }
})
test('close and unmount abort pending capabilities and prevent any late state resurrection', async () => {
for (const unmount of [false, true]) for (const fails of [false, true]) {
const f = setupAudioEntry()
try {
await f.editor.open('edit', 10)
if (unmount) f.dispose()
else await f.editor.handleClose()
assert.equal(f.requests[0].signal.aborted, true)
if (fails) f.requests[0].reject(new Error('late close failure'))
else f.requests[0].resolve(caps())
await settle()
assert.equal(f.editor.followupCapabilities.value, null)
assert.equal(f.editor.followupCapabilitiesLoading.value, false)
assert.equal(f.editor.followupCapabilitiesError.value, '')
assert.equal(f.hasPanel(), false)
if (!unmount) assert.equal(f.hasTab(), false)
} finally { f.dispose() }
}
})
const roleConflictTask = (extra={}) => stereoTask({items:[], channel_roles:'left_service',extraction_channel_roles:'left_service',extraction_revision:0,can_reextract:true,reextract_block_reason:'',role_check:{conflict:true,suggested_roles:'right_service',message:'合成角色冲突',evidence:[{channel:1,start_ms:0,end_ms:15000,text:'我是测试医院的医疗助理'}]},...extra})
test('role correction requires explicit confirmation and submits versioned roles without uploading or applying',async()=>{
let current=roleConflictTask();const confirmations=[]
const f=setupPanel({followupAudioDetail:async()=>current,followupAudioLists:async()=>({items:[current]}),followupAudioReextract:async p=>{f.calls.push(['reextract',p]);current=roleConflictTask({status:'queued',version:2,extraction_revision:1,extraction_channel_roles:p.channel_roles,channel_roles:p.channel_roles,can_reextract:false,role_check:{conflict:false,suggested_roles:'unconfirmed',message:'',evidence:[]}});return current}}, {}, {confirm:async(message)=>{confirmations.push(message)}})
await settle();await f.panel.openTask(1);assert.equal(f.panel.reextractTarget.value,'right_service');await f.panel.reextractWithRoles()
assert.deepEqual(f.calls.find(c=>c[0]==='reextract')[1],{id:1,version:1,channel_roles:'right_service'});assert.match(confirmations[0],/右客服/);assert.match(confirmations[0],/不重复语音识别/)
assert.equal(f.panel.detail.value.status,'queued');assert.equal(f.panel.detail.value.extraction_revision,1);assert.equal(f.calls.some(c=>['apply','create','session','chunk'].includes(c[0])),false);f.dispose()
})
test('role proposal never mutates manual roles or sends re-extraction until confirmed',async()=>{
const f=setupPanel({followupAudioDetail:async()=>roleConflictTask()}, {}, {confirm:async()=>{throw new Error('cancel')}});await settle();await f.panel.openTask(1)
assert.equal(f.panel.savedChannelRoles.value,'left_service');assert.equal(f.panel.channelRoles.value,'left_service');assert.equal(f.calls.some(c=>c[0]==='reextract'),false)
await f.panel.reextractWithRoles();assert.equal(f.calls.some(c=>c[0]==='reextract'),false);assert.equal(f.panel.detail.value.status,'review');assert.equal(f.panel.mutation.value,'');f.dispose()
})
test('re-extraction blocks dirty, readonly, unavailable, same-role and processing contexts',async()=>{
const f=setupPanel({followupAudioDetail:async()=>roleConflictTask()});await settle();await f.panel.openTask(1)
f.panel.reviewRef.value={hasUnsavedChanges:()=>true};await f.panel.reextractWithRoles();assert.equal(f.calls.some(c=>c[0]==='reextract'),false)
f.panel.reviewRef.value=null;f.props.viewOnly=true;await f.panel.reextractWithRoles();f.props.viewOnly=false
for(const patch of [{can_reextract:false},{status:'running'},{status:'applied'},{role_check:{conflict:false,suggested_roles:'left_service',evidence:[],message:''}}]){f.panel.installDetail(roleConflictTask(patch),false);await f.panel.reextractWithRoles()}
assert.equal(f.calls.some(c=>c[0]==='reextract'),false);f.dispose()
})
test('re-extraction confirmation and late results are fenced across patient changes',async()=>{
const answer=deferred();const f=setupPanel({followupAudioDetail:async()=>roleConflictTask()}, {}, {confirm:()=>answer.promise});await settle();await f.panel.openTask(1)
const pending=f.panel.reextractWithRoles();f.props.diagnosisId=20;await settle();answer.resolve();await pending;assert.equal(f.calls.some(c=>c[0]==='reextract'),false);f.dispose()
const response=deferred();const g=setupPanel({followupAudioDetail:async id=>roleConflictTask({id}),followupAudioReextract:async p=>{g.calls.push(['reextract',p]);return response.promise}});await settle();await g.panel.openTask(1)
const work=g.panel.reextractWithRoles();await settle();await g.panel.reextractWithRoles();assert.equal(g.calls.filter(c=>c[0]==='reextract').length,1);g.props.diagnosisId=30;await settle();await g.panel.openTask(2);response.resolve(roleConflictTask({status:'queued',version:2}));await work;assert.equal(g.panel.selectedId.value,2);assert.equal(g.panel.detail.value.id,2);g.dispose()
})
test('explicitly corrected review roles take priority over the advisory suggestion',async()=>{
const f=setupPanel({followupAudioDetail:async()=>roleConflictTask({channel_roles:'right_service',role_check:{conflict:false,suggested_roles:'unconfirmed',message:'',evidence:[]}})});await settle();await f.panel.openTask(1);assert.equal(f.panel.reextractTarget.value,'right_service');f.dispose()
const calls=[];const api=loadTs(path.join(root,'src/api/followupAudio.ts'),()=>({default:{post:async(config,options)=>{calls.push({config,options});return {code:1,data:roleConflictTask({status:'queued'})}}}}));await api.followupAudioReextract({id:1,version:1,channel_roles:'right_service'});assert.equal(calls[0].config.url,'/tcm.followupAudio/reextract');assert.equal(calls[0].options.isOpenRetry,false)
})
test('duplicate diagnosis suggestions are blocked clearly without losing distinct daily measurements',()=>{
const fields={diagnosis:[{key:'symptoms',label:'症状',type:'text'},{key:'remark',label:'备注',type:'text'}]}
const a=item({id:'a',kind:'diagnosis',values:{symptoms:'口干'}}),b=item({id:'b',kind:'diagnosis',values:{symptoms:'睡眠中断'}})
assert.match(state.reviewBatchIssue([a,b],fields),/症状存在多条选中建议/)
assert.equal(state.reviewBatchIssue([a,{...b,selected:false}],fields),'')
assert.equal(state.reviewBatchIssue([item(),item({id:'another',record_time:'12:00'})],fields),'')
assert.equal(a.values.symptoms,'口干');assert.equal(b.values.symptoms,'睡眠中断')
})
test('grouped audio permission independently gates saved diagnosis entry and capabilities requests', async () => {
for (const permissions of [[], ['tcm.diagnosis/dailyRecord'], ['tcm.diagnosis/detail', 'tcm.diagnosis/edit'], ['tcm.diagnosis/followupaudio']]) {
const f = setupAudioEntry(permissions)
try {
await f.editor.open('edit', 10)
assert.equal(f.hasTab(), false)
assert.equal(f.hasPanel(), false)
assert.equal(f.hasDailyTab(), permissions.includes('tcm.diagnosis/dailyRecord'))
await f.editor.loadFollowupCapabilities()
assert.equal(f.requests.length, 0, 'denied entry makes no capabilities request, including direct reload')
assert.equal(f.editor.followupCapabilitiesLoading.value, false)
assert.equal(f.editor.followupCapabilitiesError.value, '')
} finally { f.dispose() }
}
for (const permissions of [['tcm.diagnosis/followupAudio'], ['tcm.diagnosis/followupAudio', 'tcm.diagnosis/dailyRecord'], ['*']]) {
const f = setupAudioEntry(permissions)
try {
await f.editor.open('add')
assert.equal(f.hasTab(), false, 'unsaved diagnoses have no audio entry even with permission')
assert.equal(f.requests.length, 0)
await f.editor.open('edit', 10)
assert.equal(f.hasTab(), true)
assert.equal(f.hasDailyTab(), permissions.includes('*') || permissions.includes('tcm.diagnosis/dailyRecord'))
assert.equal(f.requests.length, 1)
f.requests[0].reject(new Error('transient network failure')); await settle()
assert.equal(f.hasTab(), true, 'granted entry never depends on capabilities success')
assert.equal(f.hasPanel(), false)
assert.match(f.editor.followupCapabilitiesError.value, /加载失败/)
assert.equal(f.requests.length, 1)
const retry = f.editor.loadFollowupCapabilities()
f.requests[1].resolve({ ...caps(), can_upload: false, can_apply: false, can_daily: false })
await retry
assert.equal(f.hasPanel(), true)
const panel = f.nodes().find(node => node.props?.capabilities)
assert.equal(panel.props.capabilities.can_apply, false, 'entry grant never overrides server write capability')
assert.equal(panel.props.capabilities.can_upload, false)
} finally { f.dispose() }
}
})
test('permission revocation aborts pending capabilities and grant refreshes current saved diagnosis only', async () => {
const f = setupAudioEntry(['tcm.diagnosis/followupAudio'])
try {
await f.editor.open('edit', 10)
f.editor.activeTab.value = 'followupAudio'
const old = f.requests[0]
f.userStore.perms = ['tcm.diagnosis/dailyRecord']
assert.equal(old.signal.aborted, true)
assert.equal(f.hasTab(), false)
assert.equal(f.hasDailyTab(), true)
assert.equal(f.editor.activeTab.value, 'basic')
old.resolve(caps()); await settle()
assert.equal(f.editor.followupCapabilities.value, null)
assert.equal(f.requests.length, 1)
f.userStore.perms.push('tcm.diagnosis/followupAudio')
assert.equal(f.hasTab(), true)
assert.equal(f.requests.length, 2)
f.requests[1].resolve(caps()); await settle()
assert.equal(f.hasPanel(), true)
f.userStore.perms = []
assert.equal(f.hasPanel(), false)
assert.equal(f.editor.followupCapabilities.value, null)
assert.equal(f.requests.length, 2)
} finally { f.dispose() }
})