Files
zyt/admin/src/views/assistant_service/components/CaseDetail.vue
T
2026-11-12 09:07:07 +08:00

731 lines
26 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<template>
<div class="case-detail">
<el-button class="mb-4" @click="emit('back')">返回医助详情</el-button>
<p class="muted">关联沟通核查 · 医助 #{{ assistantId }} · 患者信息仅用于定位服务证据</p>
<el-card shadow="never" class="patient-header">
<div class="patient-summary">
<div>
<h2>{{ selected.patient_name || '未命名患者' }}</h2>
<span
>诊单 #{{ selected.diagnosis_id }} ·
{{ selected.phone_masked || '当前授权患者' }}</span
>
</div>
<div class="patient-controls">
<span class="muted">最近 {{ days }} 天</span>
<el-button :loading="contextLoading" @click="reloadContext">刷新来源</el-button
><el-button
v-if="can('record') && assistantId === actorId"
:disabled="contextLoading || !!contextError"
type="primary"
plain
@click="recordOpened = true"
>录入服务记录</el-button
>
</div>
</div>
</el-card>
<el-alert
v-if="contextError"
:title="contextError"
type="error"
:closable="false"
show-icon
class="mb-4"
/>
<el-card shadow="never" v-loading="contextLoading" class="content-card">
<el-tabs v-model="activeTab">
<el-tab-pane label="来源时间线" name="sources"
><SourceTimeline
v-if="context"
:sources="context.sources"
:coverage="context.coverage" /><el-empty
v-else-if="!contextLoading"
description="来源尚未加载,请刷新来源"
/></el-tab-pane>
<el-tab-pane label="医助服务分析" name="analysis">
<div v-if="!automatic" class="generation-toolbar">
<el-select v-model="scenario" aria-label="分析场景" style="width: 170px"
><el-option
v-for="item in capabilities.scenarios"
:key="item.value"
:label="item.label"
:value="item.value" /></el-select
><el-button
v-if="can('analyze')"
type="primary"
:loading="submitting.analysis"
:disabled="
!canGenerate || busy('analysis') || unknownSubmission.analysis
"
@click="generate('analysis')"
>生成服务分析</el-button
>
</div>
<p v-if="!context?.sources.length" class="muted">
当前医助在此范围无可用来源,可由医助补录本人服务记录。
</p>
<p v-else-if="automatic" class="muted">
系统自动分析更新后的沟通记录,结果仍需结合原文核查。
</p>
<el-alert
v-if="newAnalysisAvailable"
title="已有更新的分析结果。完成当前核查后可查看最新结果。"
type="info"
:closable="false"
class="mb-4"
><el-button link type="primary" @click="showLatestAnalysis"
>查看最新结果</el-button
></el-alert
>
<el-alert
v-if="submitErrors.analysis"
:title="submitErrors.analysis"
type="error"
:closable="false"
class="mb-4"
/>
<el-button v-if="unknownSubmission.analysis" class="mb-4" @click="reloadContext"
>查询已提交任务</el-button
>
<JobResult
v-if="analysisState.job"
:key="analysisState.job.id"
:job="analysisState.job"
:permissions="capabilities.permissions"
:error="analysisState.error"
:checking="analysisState.checking"
:disabled="contextLoading || !!contextError"
@refresh="refreshAnalysis"
@adopted="handleAdopted"
@evidence="showEvidence"
/>
<el-empty
v-else-if="!contextLoading"
:description="
automatic
? '尚无分析结果,系统会自动分析可用沟通记录'
: '尚无服务分析,选择场景后生成'
"
:image-size="90"
/>
</el-tab-pane>
<el-tab-pane label="回复草稿" name="reply">
<el-form label-position="top"
><el-form-item label="需要回复的服务问题"
><el-input
v-model="question"
type="textarea"
:rows="3"
:maxlength="1000"
show-word-limit
placeholder="例如:患者询问复诊预约流程。请录入实际问题,答复将依据已发布的服务知识。" /></el-form-item
></el-form>
<div class="generation-toolbar">
<el-select v-model="scenario" aria-label="回复场景" style="width: 170px"
><el-option
v-for="item in capabilities.scenarios"
:key="item.value"
:label="item.label"
:value="item.value" /></el-select
><el-button
v-if="can('draftReply')"
type="primary"
:loading="submitting.reply"
:disabled="
!canGenerate ||
!question.trim() ||
busy('reply') ||
unknownSubmission.reply
"
@click="generate('reply')"
>生成回复草稿</el-button
><span class="muted">人工核对与编辑后复制</span>
</div>
<el-alert
v-if="submitErrors.reply"
:title="submitErrors.reply"
type="error"
:closable="false"
class="mb-4"
/>
<el-button v-if="unknownSubmission.reply" class="mb-4" @click="reloadContext"
>查询已提交任务</el-button
>
<JobResult
v-if="replyState.job"
:key="replyState.job.id"
:job="replyState.job"
:permissions="capabilities.permissions"
:error="replyState.error"
:checking="replyState.checking"
:disabled="contextLoading || !!contextError"
@refresh="replyTracker.refresh"
@adopted="handleAdopted"
@evidence="showEvidence"
/>
<el-empty
v-else-if="!contextLoading"
description="输入实际服务问题,生成有知识依据的回复草稿"
:image-size="90"
/>
</el-tab-pane>
<el-tab-pane label="服务待办" name="actions"
><ServiceActions
v-if="context"
:key="selected.diagnosis_id"
:diagnosis-id="selected.diagnosis_id"
:assistant-id="assistantId"
:actor-id="actorId"
:can-complete="can('completeAction')"
:can-review="can('reviewQuality')"
:refresh-key="actionsRefresh"
@changed="emit('changed')"
/></el-tab-pane>
<el-tab-pane label="分析与复核记录" name="history">
<el-alert
v-if="historyError"
:title="historyError"
type="error"
:closable="false"
class="mb-4"
/>
<el-table
v-loading="historyLoading"
:data="history"
empty-text="该医助在此诊单暂无分析记录"
><el-table-column prop="id" label="任务" width="90" /><el-table-column
label="类型"
width="110"
><template #default="{ row }">{{
row.type === 'reply' ? '回复草稿' : '服务分析'
}}</template></el-table-column
><el-table-column label="创建时间" min-width="170"
><template #default="{ row }">{{
formatTime(row.created_at)
}}</template></el-table-column
><el-table-column label="状态" min-width="170"
><template #default="{ row }">{{
jobLabels[row.status as JobStatus]
}}</template></el-table-column
><el-table-column label="操作" width="90"
><template #default="{ row }"
><el-button link type="primary" @click="openHistory(row)"
>查看</el-button
></template
></el-table-column
></el-table
>
<el-pagination
v-if="historyTotal"
v-model:current-page="historyPage"
class="mt-4"
:total="historyTotal"
:page-size="10"
layout="total, prev, pager, next"
@current-change="loadHistory"
/>
</el-tab-pane>
</el-tabs>
</el-card>
<RecordDialog
v-if="assistantId === actorId"
:key="selected.diagnosis_id"
v-model="recordOpened"
:diagnosis-id="selected.diagnosis_id"
:max-chars="capabilities.limits.max_manual_chars"
@saved="reloadContext"
/>
<el-drawer
v-model="evidenceOpened"
title="原文依据 · 生成时的来源快照"
size="min(620px, 96vw)"
append-to-body
>
<SourceTimeline :sources="evidenceSources" :coverage="[]" />
</el-drawer>
</div>
</template>
<script setup lang="ts">
import {
computed,
onActivated,
onBeforeUnmount,
onDeactivated,
onMounted,
reactive,
ref,
watch
} from 'vue'
import {
assistantAnalyze,
assistantContext,
assistantDraftReply,
assistantJob,
assistantJobs,
type Capabilities,
type Context,
type Days,
type Job,
type JobStatus,
type Patient,
type Permission,
type Scenario,
type Source
} from '@/api/assistantService'
import useUserStore from '@/stores/modules/user'
import SourceTimeline from './SourceTimeline.vue'
import RecordDialog from './RecordDialog.vue'
import JobResult from './JobResult.vue'
import ServiceActions from './ServiceActions.vue'
import { createJobTracker } from '../workbench/jobTracker'
import { errorText, formatTime, isCancelled, jobLabels } from '../shared'
const props = defineProps<{
patient: Patient
assistantId: number
days: Days
capabilities: Capabilities
initialJobId?: number
automatic?: boolean
refreshKey?: number
}>()
const emit = defineEmits<{ (event: 'back'): void; (event: 'changed'): void }>()
const capabilities = computed(() => props.capabilities)
const selected = ref<Patient>(props.patient),
context = ref<Context | null>(null),
days = computed(() => props.days),
scenario = ref<Scenario>('followup'),
question = ref(''),
activeTab = ref('analysis')
const contextLoading = ref(false),
contextError = ref(''),
recordOpened = ref(false),
actionsRefresh = ref(0)
const user = useUserStore(),
actorId = computed(() => Number(user.userInfo.id || user.userInfo.admin_id || 0))
const can = (permission: Permission) =>
capabilities.value?.permissions.includes(permission) || false
const canGenerate = computed(
() =>
!!capabilities.value?.ready &&
!!context.value?.sources.length &&
!contextLoading.value &&
!contextError.value
)
const analysisTracker = createJobTracker({ read: assistantJob }),
replyTracker = createJobTracker({ read: assistantJob })
const analysisState = analysisTracker.state,
replyState = replyTracker.state
const trackers = { analysis: analysisTracker, reply: replyTracker }
const submitting = reactive({ analysis: false, reply: false }),
unknownSubmission = reactive({ analysis: false, reply: false }),
submitErrors = reactive({ analysis: '', reply: '' })
const busy = (type: 'analysis' | 'reply') =>
['queued', 'running', 'needs_reconciliation'].includes(trackers[type].state.job?.status || '')
const inFlight = new Set<string>()
const history = ref<Job[]>([]),
historyPage = ref(1),
historyTotal = ref(0),
historyLoading = ref(false),
historyError = ref('')
const evidenceOpened = ref(false),
evidenceSources = ref<Source[]>([])
const newAnalysisAvailable = computed(
() =>
!!context.value?.latest_analysis_job &&
!!analysisState.job &&
context.value.latest_analysis_job.id > analysisState.job.id
)
let revision = 0,
historyRevision = 0,
disposed = false,
activated = true
let contextRequest: AbortController | undefined,
historyRequest: AbortController | undefined,
automaticRequest: AbortController | undefined
let automaticRevision = 0
function clearPatient() {
revision++
historyRevision++
contextRequest?.abort()
historyRequest?.abort()
automaticRequest?.abort()
automaticRevision++
context.value = null
history.value = []
historyTotal.value = 0
analysisTracker.setJob(null)
replyTracker.setJob(null)
evidenceOpened.value = false
evidenceSources.value = []
recordOpened.value = false
}
function selectPatient(patient: Patient) {
clearPatient()
selected.value = patient
activeTab.value = 'analysis'
question.value = ''
historyPage.value = 1
submitting.analysis = false
submitting.reply = false
submitErrors.analysis = ''
submitErrors.reply = ''
unknownSubmission.analysis = false
unknownSubmission.reply = false
void reloadContext()
}
async function reloadContext(preferLatest: unknown = false) {
if (!selected.value) return
const token = ++revision,
id = selected.value.diagnosis_id
contextRequest?.abort()
automaticRequest?.abort()
automaticRevision++
contextRequest = new AbortController()
contextLoading.value = true
contextError.value = ''
context.value = null
history.value = []
historyTotal.value = 0
analysisTracker.setJob(null)
replyTracker.setJob(null)
evidenceOpened.value = false
evidenceSources.value = []
try {
const data = await assistantContext(
{ diagnosis_id: id, days: days.value, assistant_id: props.assistantId },
contextRequest.signal
)
if (disposed || token !== revision) return
assertContext(data, id)
context.value = data
analysisTracker.setJob(data.latest_analysis_job)
if (data.latest_job?.type === 'reply') replyTracker.setJob(data.latest_job)
await loadHistory(true)
if (disposed || token !== revision) return
for (const tracker of Object.values(trackers)) if (tracker.state.job) void tracker.refresh()
if (!historyError.value) {
unknownSubmission.analysis = false
unknownSubmission.reply = false
submitErrors.analysis = ''
submitErrors.reply = ''
}
if (props.initialJobId && preferLatest !== true) {
const target = await assistantJob(props.initialJobId, contextRequest.signal)
if (disposed || token !== revision) return
if (target.diagnosis_id !== id || target.subject_admin_id !== props.assistantId)
throw new Error('质检问题与当前医助或诊单不一致')
trackers[target.type].setJob(target)
activeTab.value = target.type
}
if (preferLatest === true) activeTab.value = 'analysis'
actionsRefresh.value++
} catch (cause) {
if (!disposed && token === revision && !isCancelled(cause))
contextError.value = errorText(cause)
} finally {
if (!disposed && token === revision) contextLoading.value = false
}
}
function showLatestAnalysis() {
void reloadContext(true)
}
function assertContext(data: Context, diagnosisId: number) {
if (
data.patient.diagnosis_id !== diagnosisId ||
data.subject_admin_id !== props.assistantId ||
[data.latest_job, data.latest_analysis_job].some(
(job) =>
job &&
(job.subject_admin_id !== props.assistantId || job.diagnosis_id !== diagnosisId)
) ||
(data.latest_analysis_job && data.latest_analysis_job.type !== 'analysis')
)
throw new Error('返回的来源与当前医助或关联诊单不一致')
}
async function loadHistory(restore: unknown = false) {
if (!selected.value) return
// el-pagination 传入页码;只有显式 true 才恢复回复,最新分析由 context 独立提供。
const shouldRestore = restore === true
if (shouldRestore) historyPage.value = 1
const token = ++historyRevision,
patientToken = revision,
id = selected.value.diagnosis_id
historyRequest?.abort()
historyRequest = new AbortController()
historyLoading.value = true
historyError.value = ''
try {
const data = await assistantJobs(
{
diagnosis_id: id,
assistant_id: props.assistantId,
page_no: historyPage.value,
page_size: 10
},
historyRequest.signal
)
if (disposed || token !== historyRevision || patientToken !== revision) return
if (
data.lists.some(
(job) => job.subject_admin_id !== props.assistantId || job.diagnosis_id !== id
)
)
throw new Error('历史记录与当前医助或诊单不一致')
history.value = data.lists
historyTotal.value = data.count
if (shouldRestore && !replyState.job) {
const job = data.lists.find((item) => item.type === 'reply')
if (job) replyTracker.setJob(job)
}
} catch (cause) {
if (
!disposed &&
token === historyRevision &&
patientToken === revision &&
!isCancelled(cause)
) {
historyError.value = errorText(cause)
history.value = []
historyTotal.value = 0
}
} finally {
if (!disposed && token === historyRevision) historyLoading.value = false
}
}
async function generate(type: 'analysis' | 'reply') {
if (props.automatic && type === 'analysis') return
if (
!selected.value ||
!canGenerate.value ||
submitting[type] ||
busy(type) ||
unknownSubmission[type]
)
return
if (!can(type === 'analysis' ? 'analyze' : 'draftReply')) return
if (type === 'reply' && !question.value.trim()) return
const token = revision,
diagnosis_id = selected.value.diagnosis_id,
key = `${props.assistantId}:${days.value}:${diagnosis_id}:${type}`
if (inFlight.has(key)) return
inFlight.add(key)
submitting[type] = true
submitErrors[type] = ''
const data = {
diagnosis_id,
assistant_id: props.assistantId,
days: days.value,
scenario: scenario.value
}
try {
const job = await (type === 'analysis'
? assistantAnalyze(data)
: assistantDraftReply({ ...data, question: question.value.trim() }))
if (disposed || token !== revision) return
if (
job.diagnosis_id !== diagnosis_id ||
job.type !== type ||
job.subject_admin_id !== props.assistantId
)
throw new Error('任务与当前医助或关联诊单不一致')
trackers[type].setJob(job)
void loadHistory()
} catch (cause) {
if (!disposed && token === revision) {
submitErrors[type] = `${errorText(cause)}。请先查询已提交任务,确认状态后再操作。`
unknownSubmission[type] = true
}
} finally {
inFlight.delete(key)
if (!disposed && token === revision) submitting[type] = false
}
}
function handleAdopted() {
actionsRefresh.value++
emit('changed')
}
async function refreshAnalysis() {
await analysisTracker.refresh()
if (!disposed) emit('changed')
}
watch(
() => [props.patient.diagnosis_id, props.assistantId, props.days],
() => selectPatient(props.patient),
{ flush: 'sync' }
)
function openHistory(job: Job) {
trackers[job.type].setJob({ ...job, result: null })
activeTab.value = job.type
void trackers[job.type].refresh()
}
function showEvidence(sources: Source[]) {
evidenceSources.value = sources
evidenceOpened.value = true
}
async function refreshAutomatic() {
if (
!props.automatic ||
disposed ||
!activated ||
document.visibilityState === 'hidden' ||
contextLoading.value
)
return
const token = revision,
readToken = ++automaticRevision,
id = selected.value.diagnosis_id
automaticRequest?.abort()
automaticRequest = new AbortController()
try {
const data = await assistantContext(
{ diagnosis_id: id, days: days.value, assistant_id: props.assistantId },
automaticRequest.signal
)
if (disposed || token !== revision || readToken !== automaticRevision) return
assertContext(data, id)
context.value = data
contextError.value = ''
if (!analysisState.job && data.latest_analysis_job)
analysisTracker.setJob(data.latest_analysis_job)
// 保持当前核查和输入;仅更新当前结果的有效性,不自动切换到另一份分析。
if (analysisState.job) void analysisTracker.refresh()
if (replyState.job) void replyTracker.refresh()
void loadHistory()
actionsRefresh.value++
} catch (cause) {
if (
!disposed &&
token === revision &&
readToken === automaticRevision &&
!isCancelled(cause)
) {
contextError.value = errorText(cause)
context.value = null
analysisTracker.setJob(null)
replyTracker.setJob(null)
evidenceOpened.value = false
evidenceSources.value = []
}
}
}
watch(
() => props.refreshKey,
() => void refreshAutomatic()
)
function updateVisibility() {
const visible = activated && document.visibilityState !== 'hidden'
analysisTracker.setActive(visible)
replyTracker.setActive(visible)
if (!visible) {
automaticRequest?.abort()
automaticRevision++
}
}
onMounted(() => {
document.addEventListener('visibilitychange', updateVisibility)
updateVisibility()
selectPatient(props.patient)
})
onActivated(() => {
activated = true
updateVisibility()
})
onDeactivated(() => {
activated = false
updateVisibility()
})
onBeforeUnmount(() => {
disposed = true
revision++
historyRevision++
contextRequest?.abort()
historyRequest?.abort()
automaticRequest?.abort()
automaticRevision++
analysisTracker.dispose()
replyTracker.dispose()
document.removeEventListener('visibilitychange', updateVisibility)
})
</script>
<style scoped>
.assistant-workbench {
padding: 4px;
}
.page-heading {
display: flex;
justify-content: space-between;
align-items: center;
gap: 16px;
margin-bottom: 20px;
flex-wrap: wrap;
}
h1 {
font-size: 22px;
font-weight: 600;
margin: 0 0 8px;
}
.page-heading p,
.patient-summary span,
.muted {
font-size: 13px;
color: var(--el-text-color-secondary);
line-height: 1.6;
}
.page-heading p {
margin: 0;
}
.workspace-grid {
display: grid;
grid-template-columns: 260px minmax(0, 1fr);
gap: 16px;
align-items: start;
}
.workspace-main {
min-width: 0;
}
.patient-header {
margin-bottom: 16px;
}
.patient-summary,
.patient-controls,
.generation-toolbar {
display: flex;
align-items: center;
gap: 12px;
flex-wrap: wrap;
}
.patient-summary {
justify-content: space-between;
}
h2 {
margin: 0 0 5px;
font-size: 18px;
font-weight: 600;
}
.generation-toolbar {
margin: 0 0 18px;
}
.content-card {
min-height: 380px;
}
@media (max-width: 1100px) {
.workspace-grid {
grid-template-columns: 220px minmax(0, 1fr);
}
}
@media (max-width: 760px) {
.workspace-grid {
grid-template-columns: minmax(0, 1fr);
}
.patient-controls {
width: 100%;
}
.content-card :deep(.el-card__body) {
padding: 14px;
}
}
</style>