Compare commits

..
1324 changed files with 10538 additions and 129571 deletions
-3
View File
@@ -9,7 +9,6 @@ import useAppStore from './stores/modules/app'
import useSettingStore from './stores/modules/setting'
import useUserStore from './stores/modules/user'
import ChatNotifyToast from './components/chat-notify-toast/index.vue'
import RevisitDueToast from './components/revisit-due-toast/index.vue'
const appStore = useAppStore()
const settingStore = useSettingStore()
@@ -59,8 +58,6 @@ watch(
<el-config-provider :locale="elConfig.locale" :z-index="elConfig.zIndex">
<router-view />
<ChatNotifyToast v-if="showChatNotifyToast" />
<!-- 复诊到期弹窗(右下角):与会话通知并列挂载,复用同一条件避免未绑企微时无意义轮询 -->
<RevisitDueToast v-if="showChatNotifyToast" />
</el-config-provider>
</template>
-8
View File
@@ -5,14 +5,6 @@ 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' })
+37
View File
@@ -0,0 +1,37 @@
import request from '@/utils/request'
export type IdentityOperation = {
kind: 'bind' | 'create_and_bind' | 'unbind' | 'rebind' | 'reconcile'
user_id: number
employee_id?: string
expected_version?: number
new_employee?: { username: string; display_name: string; email?: string }
reason: string
}
const prefix = '/iam/v2'
const opts = { isOpenRetry: false, ignoreCancelToken: true }
export const iamGet = (path: string, params?: Record<string, unknown>): Promise<any> =>
request.get({ url: prefix + path, params, withCredentials: true }, opts)
export const iamPost = (
path: string,
params: Record<string, unknown> = {},
key = crypto.randomUUID()
): Promise<any> =>
request.post(
{ url: prefix + path, params, headers: { 'Idempotency-Key': key }, withCredentials: true },
opts
)
export const identityError = (e: any): string =>
({
REAUTH_REQUIRED: '请先验证当前账号密码,或通过企业微信重新登录。',
ACCOUNT_MISMATCH: '两端账号不一致,请确认身份后重新发起。',
NOT_LINKED: '当前账号还未关联 IAM。',
NOT_AUTHORIZED: 'IAM 尚未授予目标应用访问权限。',
BINDING_CONFLICT: '关联已变更,请刷新后重新确认。',
PROTECTED_ACCOUNT_REVIEW_REQUIRED: '敏感账号需要双侧近期管理员核验,请由统一身份平台审核。',
SERVICE_UNAVAILABLE: '统一身份服务暂时不可用,状态未确认,请稍后重试。',
FEATURE_DISABLED: 'IAM 关联管理尚未启用。',
FORBIDDEN: '没有当前操作权限或目标超出数据范围。',
TRANSACTION_EXPIRED: '验证已过期或已经使用,请重新发起。'
})[e?.error?.code as string] ||
e?.error?.code ||
'操作未完成,请刷新状态后重试。'
-195
View File
@@ -1,195 +0,0 @@
import request from '@/utils/request'
/**
* 复诊到期弹窗(需求 4)接口:/adminapi/tcm.revisitDue/<action>
* 契约见 docs/plans/assistant-revisit-reach-reminder-2026-10-12.md §3.3。
* 写接口后端 show=1,成功提示由 utils/request 统一弹出,调用方不要重复 ElMessage。
*/
/** 弹窗条目(RevisitDueLogic::formatItem) */
export interface RevisitDueToastItem {
id: number
diagnosis_id: number
assistant_id: number
patient_name: string
current_slot: number
next_slot: number
medication_days: number
/** 'YYYY-MM-DD' 或 '' */
due_date: string
overdue_days: number | null
/** overdue | missed(弹窗只含这两态) */
state: string
state_text: string
severe: 0 | 1
missed_count: number
snooze_count: number
/** 0~3,3 = 居中模态 */
escalation_level: number
contact_count: number
promised_date: string
next_remind_at: number
next_remind_at_text: string
/** 下一次点「延迟」会顺延的秒数(按钮文案用) */
next_snooze_seconds: number
appointment_date: string
closed_state: number
}
/** 汇总计数(RevisitDueLogic::buildSummary) */
export interface RevisitDueToastSummary {
enabled: boolean
due_total: number
max_overdue_days: number
warning_total: number
promise_max_days: number
contact_max_per_cycle: number
work_hours: [string, string]
}
export interface RevisitDuePendingResult {
items: RevisitDueToastItem[]
summary: RevisitDueToastSummary
}
/** 写接口返回处理后的当前行(幂等:被他人处理时也返回当前行) */
export type RevisitDueWriteResult = RevisitDueToastItem
export interface RevisitDueSnoozeAllResult {
items: RevisitDueToastItem[]
snoozed: number
skipped: number
message: string
}
/** 轮询接口不走统一 code 处理:权限不足 / 开关关闭时不要每分钟弹一次错误提示 */
const POLL_OPTIONS = {
isTransformResponse: false,
ignoreCancelToken: true,
isOpenRetry: false,
retryCount: 0
}
/**
* 弹窗待办(60s 轮询):本人到期未挂号 / 过号且已到提醒时刻的项,每次返回全集。
* 非 code=1 一律 reject(调用方静默处理),避免轮询刷错误提示。
*/
export async function revisitDuePending(): Promise<RevisitDuePendingResult> {
const res = await request.get({ url: '/tcm.revisitDue/pending' }, POLL_OPTIONS)
if (res && typeof res === 'object' && Number(res.code) === 1) {
return res.data as RevisitDuePendingResult
}
return Promise.reject(res?.msg ?? 'revisit due pending failed')
}
/** 仅计数,不更新弹出时间 */
export function revisitDueSummary(): Promise<RevisitDueToastSummary> {
return request.get({ url: '/tcm.revisitDue/summary' })
}
/** 延迟一次(幂等) */
export function revisitDueSnooze(params: { id: number }): Promise<RevisitDueWriteResult> {
return request.post({ url: '/tcm.revisitDue/snooze', params })
}
/** 批量延迟(仅 escalation_level<=1 的项) */
export function revisitDueSnoozeAll(params: {
ids: number[]
}): Promise<RevisitDueSnoozeAllResult> {
return request.post({ url: '/tcm.revisitDue/snoozeAll', params })
}
/** 已联系:记录患者承诺复诊日 */
export function revisitDueContact(params: {
id: number
promised_date: string
remark?: string
}): Promise<RevisitDueWriteResult> {
return request.post({ url: '/tcm.revisitDue/contact', params })
}
/** 人工关闭(reason lost|other,remark 必填 ≤200) */
export function revisitDueClose(params: {
id: number
reason: 'lost' | 'other'
remark: string
}): Promise<RevisitDueWriteResult> {
return request.post({ url: '/tcm.revisitDue/close', params })
}
/** 主管视图列表行(RevisitDueLists,按角色 data_scope 收窄) */
export interface RevisitDueListRow {
id: number
diagnosis_id: number
patient_name: string
assistant_id: number
assistant_name: string
dept_name: string
current_slot: number
next_slot: number
medication_days: number
/** 14/21/28/30 或 0=其它 */
rule_days: number
anchor_date: string
due_date: string
overdue_days: number | null
days_left: number | null
state: string
state_text: string
severe: 0 | 1
appointment_state: number
appointment_date: string
snooze_count: number
escalation_level: number
contact_count: number
promised_date: string
missed_count: number
closed_state: number
closed_state_text: string
handle_reason: string
handle_remark: string
first_shown_at_text: string
last_snoozed_at_text: string
computed_at_text: string
}
/** 主管视图筛选参数(state:due|warning|booked|visited|contacted|no_days|pending|closed;days_bucket:14|21|28|30|other) */
export interface RevisitDueListsParams {
assistant_id?: number | ''
dept_id?: number | ''
state?: string
days_bucket?: string
min_snooze?: number | ''
keyword?: string
page_no?: number
page_size?: number
/** 1 = 导出(export-data 组件追加) */
export?: number
[key: string]: any
}
/** 主管视图:复诊到期跟进分页列表(lists/count/page_no/page_size/extend 包络,供 usePaging / export-data 消费) */
export function revisitDueLists(params: RevisitDueListsParams) {
return request.get({ url: '/tcm.revisitDue/lists', params })
}
/** 事件流水行(RevisitDueLogic::logs) */
export interface RevisitDueLogRow {
id: number
/** 1 延迟 2 已联系 3 人工关闭 4 自动关闭-已挂号 5 自动关闭-已面诊 6 周期重置 7 重新打开 8 企微推送 9 医助变更 10 形态升级 11 首次弹出 */
event: number
event_text: string
snooze_count_after: number
level_after: number
overdue_days: number
/** payload JSON 解析后的对象(next_remind_at / promised_date / appointment_id / order_id / remark / from_assistant 等) */
payload_arr: Record<string, any>
operator_id: number
operator_name: string
create_time_text: string
}
/** 主管视图:某条提醒的事件流水(按 due_id,时间倒序由后端决定) */
export function revisitDueLogs(params: { due_id: number }) {
return request.get({ url: '/tcm.revisitDue/logs', params })
}
@@ -24,24 +24,6 @@ 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'
@@ -1,49 +0,0 @@
import request from '@/utils/request'
export interface PrescriptionAiVisibilityConfig {
role_ids: number[]
admin_ids: number[]
}
export interface PrescriptionAiVisibilityOptions {
roles: { id: number; name: string }[]
admins: { id: number; name: string; account: string }[]
}
export interface PrescriptionAiCapabilities {
agreement_visible: boolean
can_manage_visibility: boolean
}
// A failed or malformed read must never become an empty policy that can be saved.
function readVisibilityConfig(value: unknown): PrescriptionAiVisibilityConfig {
const config = value as Partial<PrescriptionAiVisibilityConfig> | null
const validIds = (ids: unknown): ids is number[] =>
Array.isArray(ids) && ids.every((id) => Number.isSafeInteger(id) && id > 0)
if (!config || !validIds(config.role_ids) || !validIds(config.admin_ids)) {
throw new Error('可见范围配置响应格式不正确')
}
return { role_ids: [...config.role_ids], admin_ids: [...config.admin_ids] }
}
export async function getPrescriptionAiVisibilityConfig() {
const data = await request.get({ url: '/tcm.prescriptionAi/getVisibilityConfig' })
return readVisibilityConfig(data)
}
export async function setPrescriptionAiVisibilityConfig(params: PrescriptionAiVisibilityConfig) {
const data = await request.post({ url: '/tcm.prescriptionAi/setVisibilityConfig', params })
return readVisibilityConfig(data)
}
export function getPrescriptionAiVisibilityOptions() {
return request.get({
url: '/tcm.prescriptionAi/visibilityOptions'
}) as Promise<PrescriptionAiVisibilityOptions>
}
export function getPrescriptionAiCapabilities() {
return request.get({
url: '/tcm.prescriptionAi/capabilities'
}) as Promise<PrescriptionAiCapabilities>
}
+4 -88
View File
@@ -204,26 +204,8 @@ export function commissionSettlementConfirmRevoke(params: Record<string, any>) {
return request.post({ url: '/stats.commissionSettlement/confirmRevoke', params })
}
/**
* 复诊接诊率口径:
* - slot(默认,后端 config project.revisit_rate.default_inherit_mode):继承按继承时诊次计入每列独立分母(visit{N}_den = 新指派数 + 起算诊次 ≤ N 的继承数)
* - exclude:继承不计分母(旧口径,assigned_count / visit{N}_count / visit{N}_rate 与 2026-10 前一致)
*/
export type RevisitRateInheritMode = 'exclude' | 'slot'
/** 被指派明细行类型:new 新指派 / inherit 继承 / all 两者(默认) */
export type RevisitRateAssignKind = 'new' | 'inherit' | 'all'
/**
* 复诊接诊率(按月):部门 → 医助分组 + 合计。
* 返回 inherit_mode、slots,行含 assigned_count(新指派)、inherit_count、assigned_total_count、
* visit{N}_count/_den/_rate、visit_all_count/_den/_rate、visit2_rate_new_assign(旧口径二诊率)
*/
export function revisitRateOverview(params: {
month?: string
dept_ids?: string
inherit_mode?: RevisitRateInheritMode
}) {
/** 复诊接诊率(按月):当月 N 诊接诊率,部门 → 医助分组 + 合计;剔除「继承」指派 */
export function revisitRateOverview(params: { month?: string; dept_ids?: string }) {
return request.get({ url: '/stats.revisitRate/overview', params })
}
@@ -232,29 +214,23 @@ export function revisitRateDeptOptions() {
return request.get({ url: '/stats.revisitRate/deptOptions' })
}
/**
* 复诊接诊率:「新指派数 / 继承数 / 被指派合计」点击下钻(按诊单聚合明细)。
* 行含 assign_type(new|inherit)、inherit_visit_slot(继承时诊次 k)、entry_slot(起算诊次)
*/
/** 复诊接诊率:「被指派数」点击下钻(按诊单聚合明细) */
export function revisitRateAssignLines(params: {
month?: string
dept_ids?: string
assistant_id?: number
dept_id?: number
inherit_mode?: RevisitRateInheritMode
kind?: RevisitRateAssignKind
}) {
return request.get({ url: '/stats.revisitRate/assignLines', params })
}
/** 复诊接诊率:「N 诊单数」点击下钻(具体订单明细);slot=0 为全部 N≥2(复诊合计单数),行含 visit_slot */
/** 复诊接诊率:「N 诊单数」点击下钻(具体订单明细) */
export function revisitRateVisitOrderLines(params: {
month?: string
slot: number
dept_ids?: string
assistant_id?: number
dept_id?: number
inherit_mode?: RevisitRateInheritMode
}) {
return request.get({ url: '/stats.revisitRate/visitOrderLines', params })
}
@@ -277,63 +253,3 @@ export function assistantPerformanceOverview(params: {
}) {
return request.get({ url: '/stats.assistantPerformance/overview', params })
}
/** 「我的复诊接诊率」卡片返回(RevisitRateLogic::assistantOverview,仅本人行) */
export interface AssistantRevisitRateResult {
month: string
inherit_mode: RevisitRateInheritMode
/** 诊次列范围(2~N) */
slots: number[]
/** false = 本人不属于二中心子树(复诊接诊率仅统计二中心医助) */
in_scope: boolean
/** 本人行:assigned_count / inherit_count / assigned_total_count / visit{N}_count|_den|_rate / visit_all_*;无数据为 null */
row: Record<string, any> | null
}
/**
* 医助个人业绩:我的复诊接诊率(按月,仅本人行;口径与复诊接诊率页一致,
* 继承患者按继承时诊次从第 k+1 诊起计入分母)
*/
export function assistantPerformanceRevisitRate(params: {
month?: string
}): Promise<AssistantRevisitRateResult> {
return request.get({ url: '/stats.assistantPerformance/revisitRate', params })
}
/** 独立指派周期统计,与原 revisitRate 按月报表分别调用。 */
export type RevisitRateCohortType = 'new' | 'inherit'
export interface RevisitRateQuery {
start_date: string
end_date: string
dept_ids?: string
assistant_id?: number
}
export interface RevisitRateDetailQuery extends RevisitRateQuery {
scope_assistant_id?: number
dept_id?: number
}
const revisitCohortPrefix = (cohortType: RevisitRateCohortType) =>
cohortType === 'inherit' ? '/stats.revisitInheritRate' : '/stats.revisitAssignRate'
export function revisitCohortOverview(params: RevisitRateQuery, cohortType: RevisitRateCohortType) {
return request.get({ url: `${revisitCohortPrefix(cohortType)}/overview`, params })
}
export function revisitCohortDeptOptions(cohortType: RevisitRateCohortType) {
return request.get({ url: `${revisitCohortPrefix(cohortType)}/deptOptions` })
}
export function revisitCohortAssignLines(params: RevisitRateDetailQuery, cohortType: RevisitRateCohortType) {
return request.get({ url: `${revisitCohortPrefix(cohortType)}/assignLines`, params })
}
export function revisitCohortVisitOrderLines(
params: RevisitRateDetailQuery & { slot: number },
cohortType: RevisitRateCohortType
) {
return request.get({ url: `${revisitCohortPrefix(cohortType)}/visitOrderLines`, params })
}
-25
View File
@@ -227,29 +227,6 @@ 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 })
@@ -513,10 +490,8 @@ export function prescriptionOrderPatchPrescriptionUsage(params: {
times_per_day: number
usage_days: number
medication_days: number
dosage_bag_count?: number
aux_times_per_day?: number
aux_usage_days?: number
aux_dosage_bag_count?: number
}) {
return request.post({ url: '/tcm.prescriptionOrder/patchPrescriptionUsage', params })
}
+2 -18
View File
@@ -34,7 +34,6 @@
</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>
@@ -132,8 +131,6 @@
<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'
@@ -198,9 +195,8 @@ const appointmentTypeLabel = computed(() => confirmedTypeLabel.value || appointm
const serverAllowsVideo = ref(false)
const serverAllowsAudio = ref(false)
const callDisabledReason = ref('正在确认挂号类型')
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'))
const canVideoCall = computed(() => serverAllowsVideo.value && canAppointmentVideoCall(appointmentType.value))
const canAudioCall = computed(() => serverAllowsAudio.value && (canAppointmentVideoCall(appointmentType.value) || appointmentType.value === 'phone'))
let releaseAppointmentCallGuard: (() => void) | undefined
let chatContextVersion = 0
let outgoingCallType = 2
@@ -257,7 +253,6 @@ 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()) {
@@ -271,7 +266,6 @@ 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)
@@ -719,14 +713,6 @@ 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) {
@@ -1113,7 +1099,6 @@ 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?.()
@@ -1275,7 +1260,6 @@ 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
@@ -1,102 +0,0 @@
<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>
+33
View File
@@ -0,0 +1,33 @@
<template>
<el-button v-if="enabled" text :loading="busy" @click="launch">进入甄美 ERP ↗</el-button>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { iamGet, iamPost, identityError } from '@/api/iam-v2'
const enabled = ref(false),
busy = ref(false)
onMounted(async () => {
try {
const status = await iamGet('/status')
enabled.value = !!status.enabled && status.launch_enabled === true
} catch {
enabled.value = false
}
})
async function launch() {
const tab = window.open('about:blank', '_blank')
if (tab) tab.opener = null
busy.value = true
try {
const r = await iamPost('/launch/start')
if (tab) tab.location.href = r.url
else ElMessage.warning('请允许新标签页后再试。')
} catch (e) {
tab?.close()
ElMessage.warning(identityError(e))
} finally {
busy.value = false
}
}
</script>
+137
View File
@@ -0,0 +1,137 @@
<template>
<el-card v-if="status?.enabled || error" class="mt-4" shadow="never">
<template #header
><strong>统一身份 IAM</strong
><el-button class="float-right" text @click="refresh">刷新状态</el-button></template
>
<el-alert v-if="error" :title="error" type="warning" :closable="false" class="mb-4" />
<p>
关联状态:<el-tag :type="linked ? 'success' : 'info'">{{
linked ? '已关联' : status.binding?.state === 'revoked' ? '关联已撤销' : '未关联'
}}</el-tag>
</p>
<p v-if="status.employee" class="my-3">
IAM 员工:{{ status.employee.displayName }}({{ status.employee.username }})
</p>
<p class="my-3 text-gray-500">
关联只确认同一人的身份,不会复制业务角色或自动授予其他平台权限。
</p>
<el-alert
v-if="!linked && status.protected_account"
class="mb-4"
type="warning"
:closable="false"
title="此账号属于敏感账号,请由本地管理员在 IAM 关联管理发起单人中央复核,不使用个人自助绑定。"
/>
<div class="flex flex-wrap gap-3">
<el-button @click="reauthVisible = true">验证当前身份</el-button>
<el-button @click="wecomRelogin">企业微信重新登录</el-button>
<el-button
v-if="!linked && !status.protected_account && status.management_enabled"
type="primary"
:loading="busy"
@click="navigate('/self-link/start')"
>关联已有 IAM 账号</el-button
>
<el-button
v-if="linked && status.management_enabled && status.employee?.passwordSetupPending"
type="primary"
:loading="busy"
@click="navigate('/password-setup')"
>设置 IAM 登录密码</el-button
>
<el-button v-if="linked && status.launch_enabled" :loading="busy" @click="launch">进入甄美 ERP ↗</el-button>
</div>
<el-dialog
v-model="reauthVisible"
title="验证当前 ZYT 身份"
width="420px"
:close-on-click-modal="false"
>
<el-form @submit.prevent="reauth"
><el-form-item label="当前密码"
><el-input
v-model="password"
type="password"
show-password
autocomplete="current-password"
@keyup.enter="reauth" /></el-form-item
></el-form>
<p class="text-gray-500">
仅验证当前账号,验证有效期 5 分钟。密码不会被保存或传给 IAM。
</p>
<template #footer
><el-button @click="cancelReauth">取消</el-button
><el-button type="primary" :loading="busy" @click="reauth"
>验证</el-button
></template
>
</el-dialog>
</el-card>
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { iamGet, iamPost, identityError } from '@/api/iam-v2'
import useUserStore from '@/stores/modules/user'
const status = ref<any>({ enabled: false }),
error = ref(''),
busy = ref(false),
reauthVisible = ref(false),
password = ref('')
const linked = computed(() => status.value?.binding?.state === 'verified')
async function refresh() {
try {
status.value = await iamGet('/status')
error.value = ''
} catch (e) {
error.value = identityError(e)
}
}
function cancelReauth() {
reauthVisible.value = false
password.value = ''
}
async function reauth() {
busy.value = true
try {
await iamPost('/reauth', { password: password.value })
reauthVisible.value = false
await refresh()
} catch (e) {
error.value = identityError(e)
} finally {
password.value = ''
busy.value = false
}
}
async function navigate(path: string) {
busy.value = true
try {
const r = await iamPost(path)
window.location.assign(r.url)
} catch (e) {
error.value = identityError(e)
} finally {
busy.value = false
}
}
async function launch() {
const tab = window.open('about:blank', '_blank')
if (tab) tab.opener = null
busy.value = true
try {
const r = await iamPost('/launch/start')
if (tab) tab.location.href = r.url
else error.value = '请允许浏览器打开新标签页后再试。'
} catch (e) {
tab?.close()
error.value = identityError(e)
} finally {
busy.value = false
}
}
async function wecomRelogin() {
await useUserStore().logout()
}
onMounted(refresh)
</script>
File diff suppressed because it is too large Load Diff
@@ -1,47 +0,0 @@
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 }
}
@@ -1,59 +0,0 @@
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 }
}
@@ -1,88 +0,0 @@
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
}
}
@@ -22,6 +22,7 @@
</div>
</div>
<div class="flex">
<iam-launch />
<div class="navbar-item" v-if="!isMobile">
<el-tooltip
class="box-item"
@@ -52,6 +53,7 @@
</template>
<script setup lang="ts">
import IamLaunch from '@/components/iam-v2/launch.vue'
import { useFullscreen } from '@vueuse/core'
import useAppStore from '@/stores/modules/app'
+1 -1
View File
@@ -81,7 +81,7 @@ const defaultPath = PageEnum.INDEX
const changePasswordPath = '/change-password'
const bindWorkWechatPath = '/bind-work-wechat'
// 免登录白名单
const whiteList: string[] = [PageEnum.LOGIN, PageEnum.ERROR_403]
const whiteList: string[] = [PageEnum.LOGIN, PageEnum.ERROR_403, '/iam/launch']
router.beforeEach(async (to, from, next) => {
document.title = to.meta.title ?? config.title
const userStore = useUserStore()
+5
View File
@@ -23,6 +23,11 @@ export const LAYOUT = () => Promise.resolve(Layout)
export const INDEX_ROUTE_NAME = Symbol()
export const constantRoutes: Array<RouteRecordRaw> = [
{
path: '/iam/launch',
component: () => import('@/views/account/iam-launch.vue'),
meta: { title: '统一身份进入甄养堂', hideTab: true }
},
{
path: '/:pathMatch(.*)*',
component: () => import('@/views/error/404.vue')
+9
View File
@@ -2,6 +2,7 @@ import { defineStore } from 'pinia'
import type { RouteRecordRaw } from 'vue-router'
import { getUserInfo, iamLogin, login, logout, workWechatLogin } from '@/api/user'
import { iamPost } from '@/api/iam-v2'
import { TOKEN_KEY } from '@/enums/cacheEnums'
import { PageEnum } from '@/enums/pageEnum'
import router, { filterAsyncRoutes } from '@/router'
@@ -86,6 +87,14 @@ const useUserStore = defineStore({
})
})
},
async iamLaunchLogin(ticket: string) {
const data = await iamPost('/launch/exchange', { ticket })
this.resetState()
this.token = data.token
this.isPaw = data.is_paw ?? 1
cache.set(TOKEN_KEY, data.token)
return data
},
async iamLogin(ticket: string) {
const data = await iamLogin(ticket)
this.token = data.token
@@ -1,45 +0,0 @@
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 ? '视频面诊' : '面诊记录'
}
@@ -1,97 +0,0 @@
// 所有时间由服务端配置提供,浏览器不保留独立的截止日期。
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)
}
-403
View File
@@ -1,403 +0,0 @@
/**
* 复诊节点(revisit_due)前端纯函数集合
*
* 数据契约与后端 `RevisitDueService::buildListPayload` 输出一致(方案 docs/plans/assistant-revisit-reach-reminder-2026-10-12.md 契约 C):
* 所有日期为 'Y-m-d' 字符串或 '';无快照且无法计算时后端返回 state='none' 的对象,前端显示「—」。
*
* 本文件只做 state → 文案 / 颜色 class / el-tag type 的映射与日期、天数文案拼装,不含任何请求或响应式逻辑,
* 供 PC 列表、H5 卡片、只读页三处共用(RevisitNodeCell.vue + readonly.vue)。
*/
export type RevisitDueState =
| 'visited'
| 'booked'
| 'missed'
| 'contacted'
| 'overdue'
| 'warning'
| 'pending'
| 'no_days'
| 'none'
/** 列表行 `revisit_due` 对象(契约 C) */
export interface RevisitDue {
current_slot: number
next_slot: number
valid_order_count: number
medication_days: number
/** 0=缺失 1=订单 2=处方 */
days_src: 0 | 1 | 2
/** 14/21/28/30 或 0=其它 */
rule_days: number
/** 0=无 1=签收 2=发货 3=下单 */
anchor_src: 0 | 1 | 2 | 3
anchor_date: string
order_date: string
due_date: string
days_left: number | null
overdue_days: number | null
state: RevisitDueState | string
state_text: string
severe: 0 | 1
/** 0=无 1=已约 3=已面诊 4=过号 */
appointment_state: number
appointment_date: string
snooze_count: number
escalation_level: number
promised_date: string
missed_count: number
first_touch_date: string
in_care_days: number | null
total_medication_days: number
closed_state: number
}
/** 「复诊状态」筛选下拉选项(请求参数 revisit_state;due = overdue ∪ missed) */
export const REVISIT_STATE_FILTER_OPTIONS: Array<{ label: string; value: string }> = [
{ label: '到期未挂号 / 过号', value: 'due' },
{ label: '即将到期', value: 'warning' },
{ label: '已约待面诊', value: 'booked' },
{ label: '已面诊', value: 'visited' },
{ label: '已联系', value: 'contacted' },
{ label: '缺开药天数', value: 'no_days' },
{ label: '未到期', value: 'pending' }
]
/** 「开药天数档」筛选下拉选项(请求参数 revisit_days_bucket) */
export const REVISIT_DAYS_BUCKET_OPTIONS: Array<{ label: string; value: string }> = [
{ label: '14 天', value: '14' },
{ label: '21 天', value: '21' },
{ label: '28 天', value: '28' },
{ label: '30 天', value: '30' },
{ label: '其它天数', value: 'other' }
]
/** state → 默认文案(后端 state_text 缺失时兜底) */
const STATE_LABEL: Record<string, string> = {
visited: '已面诊',
booked: '已约',
missed: '过号',
contacted: '已联系',
overdue: '超期',
warning: '即将到期',
pending: '未到期',
no_days: '缺开药天数',
none: '—'
}
const toInt = (v: unknown, fallback = 0): number => {
if (v === null || v === undefined || v === '') return fallback
const n = Number(v)
return Number.isFinite(n) ? Math.trunc(n) : fallback
}
const toNullableInt = (v: unknown): number | null => {
if (v === null || v === undefined || v === '') return null
const n = Number(v)
return Number.isFinite(n) ? Math.trunc(n) : null
}
const toDateStr = (v: unknown): string => {
if (v === null || v === undefined) return ''
const s = String(v).trim()
if (s === '' || s === '0000-00-00') return ''
return s
}
/**
* 把列表行 / 详情里的 `revisit_due` 原始值规整为 RevisitDue;
* 字段缺失(旧接口)或非对象时返回 null,调用方据此不渲染。
*/
export function normalizeRevisitDue(raw: unknown): RevisitDue | null {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null
const r = raw as Record<string, unknown>
const state = String(r.state ?? 'none').trim() || 'none'
const daysSrc = toInt(r.days_src)
const anchorSrc = toInt(r.anchor_src)
return {
current_slot: toInt(r.current_slot),
next_slot: toInt(r.next_slot),
valid_order_count: toInt(r.valid_order_count),
medication_days: toInt(r.medication_days),
days_src: (daysSrc === 1 || daysSrc === 2 ? daysSrc : 0) as 0 | 1 | 2,
rule_days: toInt(r.rule_days),
anchor_src: (anchorSrc >= 1 && anchorSrc <= 3 ? anchorSrc : 0) as 0 | 1 | 2 | 3,
anchor_date: toDateStr(r.anchor_date),
order_date: toDateStr(r.order_date),
due_date: toDateStr(r.due_date),
days_left: toNullableInt(r.days_left),
overdue_days: toNullableInt(r.overdue_days),
state,
state_text: String(r.state_text ?? '').trim(),
severe: toInt(r.severe) === 1 ? 1 : 0,
appointment_state: toInt(r.appointment_state),
appointment_date: toDateStr(r.appointment_date),
snooze_count: toInt(r.snooze_count),
escalation_level: toInt(r.escalation_level),
promised_date: toDateStr(r.promised_date),
missed_count: toInt(r.missed_count),
first_touch_date: toDateStr(r.first_touch_date),
in_care_days: toNullableInt(r.in_care_days),
total_medication_days: toInt(r.total_medication_days),
closed_state: toInt(r.closed_state)
}
}
/** 是否有可展示的复诊节点(state !== 'none') */
export function hasRevisitDue(due: RevisitDue | null | undefined): due is RevisitDue {
return !!due && due.state !== 'none' && due.state !== ''
}
/** 行级标红:到期未挂号 / 过号未面诊;人工关闭或已自动关闭(closed_state!==0)的行不标红,与「复诊到期」chip / 筛选口径一致 */
export function isRevisitDueHighlight(due: RevisitDue | null | undefined): boolean {
return (
hasRevisitDue(due) &&
toInt(due.closed_state) === 0 &&
(due.state === 'overdue' || due.state === 'missed')
)
}
/** 深红:超期达到 severe_overdue_days(后端已算好 severe=1) */
export function isRevisitDueSevere(due: RevisitDue | null | undefined): boolean {
return isRevisitDueHighlight(due) && Number(due?.severe) === 1
}
/**
* el-table :row-class-name 片段:
* '' | 'row-revisit-overdue' | 'row-revisit-overdue row-revisit-overdue-deep'
*/
export function revisitRowClassName(due: RevisitDue | null | undefined): string {
if (!isRevisitDueHighlight(due)) return ''
return isRevisitDueSevere(due) ? 'row-revisit-overdue row-revisit-overdue-deep' : 'row-revisit-overdue'
}
/** 'YYYY-MM-DD' → 'MM-DD';非法/空值返回 '' */
export function formatRevisitMonthDay(date: string | null | undefined): string {
const s = toDateStr(date)
if (!s) return ''
const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(s)
if (m) return `${m[2]}-${m[3]}`
return s
}
/** 用药起算锚点来源文案(行 2 末尾) */
export function revisitAnchorSrcText(src: number | null | undefined): string {
const n = toInt(src)
if (n === 1) return '签收起'
if (n === 2) return '发货起'
if (n === 3) return '下单起'
return ''
}
/** 开药天数来源文案(tooltip 用) */
export function revisitDaysSrcText(src: number | null | undefined): string {
const n = toInt(src)
if (n === 1) return '订单'
if (n === 2) return '处方'
return '缺失'
}
/** 是否缺开药天数(days_src=0 或 medication_days<=0) */
export function isRevisitDaysMissing(due: RevisitDue | null | undefined): boolean {
if (!hasRevisitDue(due)) return false
return toInt(due.days_src) === 0 || toInt(due.medication_days) <= 0
}
/** 「第 N 诊」文案 */
export function revisitSlotText(due: RevisitDue | null | undefined): string {
if (!hasRevisitDue(due)) return ''
const slot = toInt(due.current_slot)
return slot > 0 ? `第 ${slot} 诊` : '未成交'
}
/** 「开药 X 天」或「缺开药天数」 */
export function revisitMedicationDaysText(due: RevisitDue | null | undefined): string {
if (!hasRevisitDue(due)) return ''
if (isRevisitDaysMissing(due)) return '缺开药天数'
return `开药 ${toInt(due.medication_days)} 天`
}
/** 「药尽 MM-DD」;缺天数无 due_date 时返回 '' */
export function revisitDueDateText(due: RevisitDue | null | undefined): string {
if (!hasRevisitDue(due)) return ''
const md = formatRevisitMonthDay(due.due_date)
return md ? `药尽 ${md}` : ''
}
/** state 兜底文案(后端 state_text 为空时使用) */
export function revisitStateLabel(state: string | null | undefined): string {
const key = String(state ?? '').trim()
return STATE_LABEL[key] ?? (key || '—')
}
/**
* 状态 chip 文案:优先后端 state_text;为空时按 state + 数字自行拼装,
* 保证旧接口 / 字段缺失时也可读。
*/
export function revisitStateChipText(due: RevisitDue | null | undefined): string {
if (!hasRevisitDue(due)) return ''
if (due.state_text) return due.state_text
const state = String(due.state)
switch (state) {
case 'overdue': {
const n = toInt(due.overdue_days)
return n <= 0 ? '今日应挂号' : `超期 ${n} 天`
}
case 'missed': {
const md = formatRevisitMonthDay(due.appointment_date)
return md ? `过号 ${md}` : '过号'
}
case 'booked': {
const md = formatRevisitMonthDay(due.appointment_date)
return md ? `已约 ${md}` : '已约'
}
case 'visited': {
const md = formatRevisitMonthDay(due.appointment_date)
return md ? `已面诊 ${md}` : '已面诊'
}
case 'contacted': {
const md = formatRevisitMonthDay(due.promised_date)
return md ? `已联系·约 ${md}` : '已联系'
}
case 'warning':
case 'pending': {
const n = due.days_left
return n === null ? revisitStateLabel(state) : `剩 ${n} 天`
}
default:
return revisitStateLabel(state)
}
}
/** 状态 chip 的 el-tag type */
export function revisitStateTagType(
state: string | null | undefined
): 'danger' | 'warning' | 'primary' | 'success' | 'info' {
switch (String(state ?? '')) {
case 'overdue':
case 'missed':
return 'danger'
case 'warning':
case 'no_days':
return 'warning'
case 'booked':
case 'contacted':
return 'primary'
case 'visited':
return 'success'
default:
return 'info'
}
}
/** 状态 chip 的 el-tag effect:红为 dark;描边态(已联系 / 缺天数)为 plain;其余 light */
export function revisitStateTagEffect(state: string | null | undefined): 'dark' | 'light' | 'plain' {
switch (String(state ?? '')) {
case 'overdue':
case 'missed':
return 'dark'
case 'contacted':
case 'no_days':
return 'plain'
default:
return 'light'
}
}
/**
* 状态 → 徽标颜色 class(复用列表 / 只读页既有的 unserved-* 色板):
* overdue/missed → unserved-red;warning/no_days → unserved-orange;
* visited → unserved-green;booked/contacted → unserved-blue;其余 → unserved-muted
*/
export function revisitStateColorClass(
state: string | null | undefined
): 'unserved-red' | 'unserved-orange' | 'unserved-green' | 'unserved-blue' | 'unserved-muted' {
switch (String(state ?? '')) {
case 'overdue':
case 'missed':
return 'unserved-red'
case 'warning':
case 'no_days':
return 'unserved-orange'
case 'visited':
return 'unserved-green'
case 'booked':
case 'contacted':
return 'unserved-blue'
default:
return 'unserved-muted'
}
}
/** 状态 chip 附加 class(组件内样式钩子):rv-chip rv-chip--<state> [rv-chip--severe] */
export function revisitStateChipClass(due: RevisitDue | null | undefined): string {
if (!hasRevisitDue(due)) return 'rv-chip'
const cls = ['rv-chip', `rv-chip--${String(due.state)}`]
if (isRevisitDueSevere(due)) cls.push('rv-chip--severe')
return cls.join(' ')
}
/** 行 4:「已延迟 N 次」 */
export function revisitSnoozeText(due: RevisitDue | null | undefined): string {
if (!hasRevisitDue(due)) return ''
const n = toInt(due.snooze_count)
return n > 0 ? `已延迟 ${n} 次` : ''
}
/** 行 4:「已联系 约 MM-DD」 */
export function revisitContactText(due: RevisitDue | null | undefined): string {
if (!hasRevisitDue(due)) return ''
const md = formatRevisitMonthDay(due.promised_date)
return md ? `已联系 约 ${md}` : ''
}
/** 行 4 合并文案:仅 snooze_count>0 或 promised_date 有值时非空 */
export function revisitFollowLineText(due: RevisitDue | null | undefined): string {
const parts = [revisitSnoozeText(due), revisitContactText(due)].filter((s) => s !== '')
return parts.join(' · ')
}
/** 行 2:「MM-DD 开药 · 开药 X 天 · 签收起」 */
export function revisitOrderLineText(due: RevisitDue | null | undefined): string {
if (!hasRevisitDue(due)) return ''
const parts: string[] = []
const md = formatRevisitMonthDay(due.order_date)
if (md) parts.push(`${md} 开药`)
parts.push(revisitMedicationDaysText(due))
if (!isRevisitDaysMissing(due)) {
const anchor = revisitAnchorSrcText(due.anchor_src)
if (anchor) parts.push(anchor)
}
return parts.filter((s) => s !== '').join(' · ')
}
/** 诊次 tag tooltip 行 */
export function revisitTooltipLines(due: RevisitDue | null | undefined): string[] {
if (!hasRevisitDue(due)) return []
const lines: string[] = []
const offset = Math.max(0, toInt(due.current_slot) - toInt(due.valid_order_count))
lines.push(`有效订单 ${toInt(due.valid_order_count)} 笔 · 诊次偏移 +${offset}`)
if (toInt(due.next_slot) > 0) lines.push(`待复诊:第 ${toInt(due.next_slot)} 诊`)
const first = formatRevisitMonthDay(due.first_touch_date)
if (first) {
const care = due.in_care_days
lines.push(care === null ? `首次触达 ${first}` : `首次触达 ${first} · 在管 ${care} 天`)
}
if (toInt(due.total_medication_days) > 0) lines.push(`累计开药 ${toInt(due.total_medication_days)} 天`)
const anchorMd = formatRevisitMonthDay(due.anchor_date)
const anchorSrc = revisitAnchorSrcText(due.anchor_src)
if (anchorMd && anchorSrc) lines.push(`用药起算 ${anchorMd}(${anchorSrc.replace(/起$/, '')})`)
if (!isRevisitDaysMissing(due)) lines.push(`开药天数来源:${revisitDaysSrcText(due.days_src)}`)
if (toInt(due.missed_count) > 0) lines.push(`曾过号 ${toInt(due.missed_count)} 次`)
return lines
}
/**
* 只读页徽标文案:「第 N 诊 · 药尽 MM-DD · 超期 N 天」
* 无 due_date 时省略中段;尾段为状态 chip 文案。
*/
export function revisitBadgeText(due: RevisitDue | null | undefined): string {
if (!hasRevisitDue(due)) return ''
const parts = [revisitSlotText(due), revisitDueDateText(due), revisitStateChipText(due)]
return parts.filter((s) => s !== '').join(' · ')
}
+93
View File
@@ -0,0 +1,93 @@
<template>
<main class="min-h-screen flex items-center justify-center bg-page p-6">
<el-card class="w-full max-w-xl" shadow="never">
<h1 class="text-xl font-semibold mb-4">统一身份进入甄养堂</h1>
<p v-if="busy" class="text-gray-500">正在核验同一身份,请稍候…</p>
<el-alert v-if="error" :title="error" type="warning" :closable="false" show-icon />
<p class="text-gray-500 my-4">
已有 ZYT 账号将进行一致性检查。系统不会自动替换当前已登录的人。
</p>
<div v-if="error" class="flex flex-wrap gap-3">
<el-button v-if="restartUrl" type="primary" @click="back"
>返回 IAM 重新发起</el-button
>
<el-button v-if="restartUrl" :loading="busy" @click="switchAccount"
>退出当前 ZYT 身份并返回 IAM</el-button
>
<router-link to="/login"><el-button>使用原登录方式</el-button></router-link>
</div>
</el-card>
</main>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { iamGet, iamPost, identityError } from '@/api/iam-v2'
import useUserStore from '@/stores/modules/user'
import { clearAuthInfo } from '@/utils/auth'
import feedback from '@/utils/feedback'
const route = useRoute(),
router = useRouter(),
store = useUserStore()
const busy = ref(true),
error = ref(''),
restartUrl = ref('')
let handled = false
const text = (v: unknown) => (typeof v === 'string' ? v : '')
function back() {
if (restartUrl.value) window.location.assign(restartUrl.value)
}
async function switchAccount() {
await feedback.confirm(
'确认退出当前浏览器的 ZYT 身份?其他平台和其他浏览器不受影响。请回 IAM 重新发起。'
)
busy.value = true
try {
await iamPost('/launch/reset')
clearAuthInfo()
back()
} catch (e) {
error.value = identityError(e)
} finally {
busy.value = false
}
}
onMounted(async () => {
if (handled) return
handled = true
const ticket = text(route.query.ticket),
source = text(route.query.source),
intent = text(route.query.intent),
issue = text(route.query.iam_error)
// Strip one-use material before any network/async work; never retain it in history.
window.history.replaceState(window.history.state, '', window.location.pathname)
try {
const config = await iamGet('/launch/config', { source })
restartUrl.value = config.restart_url || ''
if (!config.enabled) throw { error: { code: 'FEATURE_DISABLED' } }
if (issue) throw { error: { code: issue } }
if (ticket) {
const result = await store.iamLaunchLogin(ticket)
await router.replace(
result.is_paw === 0
? '/change-password'
: result.need_bind_work_wechat
? '/bind-work-wechat'
: '/'
)
} else {
if (
!['iam-admin', 'iam-portal'].includes(source) ||
!/^[A-Za-z0-9_-]{32,256}$/.test(intent)
)
throw { error: { code: 'INVALID_REQUEST' } }
const result = await iamPost('/launch/prepare', { source, intent })
window.location.assign(result.url)
}
} catch (e) {
error.value = identityError(e)
} finally {
busy.value = false
}
})
</script>
@@ -312,17 +312,6 @@
{{ detailPrescription.dosage_amount }}{{ detailPrescription.dosage_unit || 'g' }}
<template v-if="detailPrescription.prescription_type === '浓缩水丸'">
· {{ Number(detailPrescription.dosage_bag_count) > 0 ? Number(detailPrescription.dosage_bag_count) : 1 }}袋
<el-button
v-if="!readonly && detailData.prescription_id && !String(detailData.prescription_detail_error || '').trim()"
v-perms="['tcm.prescriptionOrder/patchPrescriptionUsage']"
type="primary"
size="small"
link
class="ml-2"
@click="openPatchUsageDialog"
>
修改
</el-button>
</template>
<span v-if="detailPrescription.prescription_type === '饮片' && detailPrescription.need_decoction !== null" class="ml-2 text-gray-500">
({{ detailPrescription.need_decoction ? '代煎' : '不代煎' }})
@@ -336,17 +325,6 @@
{{ detailAuxUsage.dosage_amount }}{{ detailPrescription.dosage_unit || 'g' }}
<template v-if="detailPrescription.prescription_type === '浓缩水丸'">
· {{ Number(detailAuxUsage.dosage_bag_count) > 0 ? Number(detailAuxUsage.dosage_bag_count) : 1 }}袋
<el-button
v-if="!readonly && detailData.prescription_id && !String(detailData.prescription_detail_error || '').trim()"
v-perms="['tcm.prescriptionOrder/patchPrescriptionUsage']"
type="primary"
size="small"
link
class="ml-2"
@click="openPatchUsageDialog"
>
修改
</el-button>
</template>
<span v-if="detailPrescription.prescription_type === '饮片'" class="ml-2 text-gray-500">
({{ detailAuxUsage.need_decoction ? '代煎' : '不代煎' }})
@@ -965,15 +943,6 @@
label-width="108px"
>
<div v-if="detailHasAuxHerbs" class="text-xs font-medium text-gray-500 mb-3">主方</div>
<el-form-item
v-if="detailPrescription?.prescription_type === '浓缩水丸'"
label="每次袋数"
prop="dosage_bag_count"
>
<el-select v-model="patchUsageForm.dosage_bag_count" class="w-full">
<el-option v-for="count in 5" :key="count" :label="`${count}袋`" :value="count" />
</el-select>
</el-form-item>
<el-form-item label="每天次数" prop="times_per_day">
<el-input-number
v-model="patchUsageForm.times_per_day"
@@ -999,15 +968,6 @@
</el-form-item>
<template v-if="detailHasAuxHerbs">
<div class="text-xs font-medium text-gray-500 mb-3 mt-2 pt-2 border-t border-gray-100">辅方</div>
<el-form-item
v-if="detailPrescription?.prescription_type === '浓缩水丸'"
label="每次袋数"
prop="aux_dosage_bag_count"
>
<el-select v-model="patchUsageForm.aux_dosage_bag_count" class="w-full">
<el-option v-for="count in 5" :key="count" :label="`${count}袋`" :value="count" />
</el-select>
</el-form-item>
<el-form-item label="每天次数" prop="aux_times_per_day">
<el-input-number
v-model="patchUsageForm.aux_times_per_day"
@@ -1472,12 +1432,10 @@ const patchUsageVisible = ref(false)
const patchUsageSaving = ref(false)
const patchUsageFormRef = ref<FormInstance>()
const patchUsageForm = reactive({
dosage_bag_count: 1 as number | undefined,
times_per_day: 3 as number | undefined,
usage_days: 7 as number | undefined,
aux_times_per_day: 3 as number | undefined,
aux_usage_days: 7 as number | undefined,
aux_dosage_bag_count: 1 as number | undefined,
medication_days: undefined as number | undefined
})
const patchUsageRules = computed<FormRules>(() => {
@@ -1486,15 +1444,9 @@ const patchUsageRules = computed<FormRules>(() => {
usage_days: [{ required: true, message: '请填写主方开立天数', trigger: 'change' }],
medication_days: [{ required: true, message: '请填写订单服用天数', trigger: 'change' }]
}
if (detailPrescription.value?.prescription_type === '浓缩水丸') {
rules.dosage_bag_count = [{ required: true, message: '请选择主方每次袋数', trigger: 'change' }]
}
if (detailHasAuxHerbs.value) {
rules.aux_times_per_day = [{ required: true, message: '请填写辅方每天次数', trigger: 'change' }]
rules.aux_usage_days = [{ required: true, message: '请填写辅方开立天数', trigger: 'change' }]
if (detailPrescription.value?.prescription_type === '浓缩水丸') {
rules.aux_dosage_bag_count = [{ required: true, message: '请选择辅方每次袋数', trigger: 'change' }]
}
}
return rules
})
@@ -1507,7 +1459,6 @@ function openPatchUsageDialog() {
return
}
const aux = detailAuxUsage.value
patchUsageForm.dosage_bag_count = Number(rx.dosage_bag_count) > 0 ? Number(rx.dosage_bag_count) : 1
patchUsageForm.times_per_day =
Number(rx.times_per_day) > 0 ? Number(rx.times_per_day) : 3
patchUsageForm.usage_days =
@@ -1517,20 +1468,16 @@ function openPatchUsageDialog() {
patchUsageForm.aux_usage_days =
aux && Number(aux.usage_days) > 0 ? Number(aux.usage_days) : 7
const md = Number(ord.medication_days)
patchUsageForm.aux_dosage_bag_count =
aux && Number(aux.dosage_bag_count) > 0 ? Number(aux.dosage_bag_count) : 1
patchUsageForm.medication_days = md > 0 ? md : Number(rx.usage_days) > 0 ? Number(rx.usage_days) : 7
patchUsageVisible.value = true
nextTick(() => patchUsageFormRef.value?.clearValidate())
}
function resetPatchUsageForm() {
patchUsageForm.dosage_bag_count = 1
patchUsageForm.times_per_day = 3
patchUsageForm.usage_days = 7
patchUsageForm.aux_times_per_day = 3
patchUsageForm.aux_usage_days = 7
patchUsageForm.aux_dosage_bag_count = 1
patchUsageForm.medication_days = undefined
}
@@ -1551,25 +1498,17 @@ async function submitPatchUsage() {
times_per_day: number
usage_days: number
medication_days: number
dosage_bag_count?: number
aux_times_per_day?: number
aux_usage_days?: number
aux_dosage_bag_count?: number
} = {
id: ordId,
times_per_day: Number(patchUsageForm.times_per_day),
usage_days: Number(patchUsageForm.usage_days),
medication_days: Number(patchUsageForm.medication_days)
}
if (detailPrescription.value?.prescription_type === '浓缩水丸') {
payload.dosage_bag_count = Number(patchUsageForm.dosage_bag_count)
}
if (detailHasAuxHerbs.value) {
payload.aux_times_per_day = Number(patchUsageForm.aux_times_per_day)
payload.aux_usage_days = Number(patchUsageForm.aux_usage_days)
if (detailPrescription.value?.prescription_type === '浓缩水丸') {
payload.aux_dosage_bag_count = Number(patchUsageForm.aux_dosage_bag_count)
}
}
await prescriptionOrderPatchPrescriptionUsage(payload)
feedback.msgSuccess('保存成功')
@@ -1824,7 +1763,7 @@ async function refresh() {
detailLogisticsExpress.value = String(d.express_company || 'auto') || 'auto'
void fetchLogisticsTrace()
}
if (props.loadRelatedData) await fetchLogs(id)
if (props.loadRelatedData) void fetchLogs(id)
const diagId = d.diagnosis_id
if (props.loadRelatedData && diagId) {
void loadDetailUnlinkedPayOrders(diagId, id, d.pay_order_ids || [])
@@ -883,17 +883,6 @@
{{ detailPrescription.dosage_amount }}{{ detailPrescription.dosage_unit || 'g' }}
<template v-if="detailPrescription.prescription_type === '浓缩水丸'">
· {{ Number(detailPrescription.dosage_bag_count) > 0 ? Number(detailPrescription.dosage_bag_count) : 1 }}袋
<el-button
v-if="detailData.prescription_id && !String(detailData.prescription_detail_error || '').trim()"
v-perms="['tcm.prescriptionOrder/patchPrescriptionUsage']"
type="primary"
size="small"
link
class="ml-2"
@click="openPatchUsageDialog"
>
修改
</el-button>
</template>
<span v-if="detailPrescription.prescription_type === '饮片' && detailPrescription.need_decoction !== null" class="ml-2 text-gray-500">
({{ detailPrescription.need_decoction ? '代煎' : '不代煎' }})
@@ -907,17 +896,6 @@
{{ detailAuxUsage.dosage_amount }}{{ detailPrescription.dosage_unit || 'g' }}
<template v-if="detailPrescription.prescription_type === '浓缩水丸'">
· {{ Number(detailAuxUsage.dosage_bag_count) > 0 ? Number(detailAuxUsage.dosage_bag_count) : 1 }}袋
<el-button
v-if="detailData.prescription_id && !String(detailData.prescription_detail_error || '').trim()"
v-perms="['tcm.prescriptionOrder/patchPrescriptionUsage']"
type="primary"
size="small"
link
class="ml-2"
@click="openPatchUsageDialog"
>
修改
</el-button>
</template>
<span v-if="detailPrescription.prescription_type === '饮片'" class="ml-2 text-gray-500">
({{ detailAuxUsage.need_decoction ? '代煎' : '不代煎' }})
@@ -2283,15 +2261,6 @@
label-width="96px"
>
<div v-if="detailHasAuxHerbs" class="text-xs font-medium text-gray-500 mb-3">主方</div>
<el-form-item
v-if="detailPrescription?.prescription_type === '浓缩水丸'"
label="每次袋数"
prop="dosage_bag_count"
>
<el-select v-model="patchUsageForm.dosage_bag_count" class="w-full">
<el-option v-for="count in 5" :key="count" :label="`${count}袋`" :value="count" />
</el-select>
</el-form-item>
<el-form-item label="每天次数" prop="times_per_day">
<el-input-number
v-model="patchUsageForm.times_per_day"
@@ -2317,15 +2286,6 @@
</el-form-item>
<template v-if="detailHasAuxHerbs">
<div class="text-xs font-medium text-gray-500 mb-3 mt-2 pt-2 border-t border-gray-100">辅方</div>
<el-form-item
v-if="detailPrescription?.prescription_type === '浓缩水丸'"
label="每次袋数"
prop="aux_dosage_bag_count"
>
<el-select v-model="patchUsageForm.aux_dosage_bag_count" class="w-full">
<el-option v-for="count in 5" :key="count" :label="`${count}袋`" :value="count" />
</el-select>
</el-form-item>
<el-form-item label="每天次数" prop="aux_times_per_day">
<el-input-number
v-model="patchUsageForm.aux_times_per_day"
@@ -3994,12 +3954,10 @@ const patchUsageVisible = ref(false)
const patchUsageSaving = ref(false)
const patchUsageFormRef = ref<FormInstance>()
const patchUsageForm = reactive({
dosage_bag_count: 1 as number | undefined,
times_per_day: 3 as number | undefined,
usage_days: 7 as number | undefined,
aux_times_per_day: 3 as number | undefined,
aux_usage_days: 7 as number | undefined,
aux_dosage_bag_count: 1 as number | undefined,
medication_days: undefined as number | undefined
})
const patchUsageRules = computed<FormRules>(() => {
@@ -4008,15 +3966,9 @@ const patchUsageRules = computed<FormRules>(() => {
usage_days: [{ required: true, message: '请填写主方开立天数', trigger: 'change' }],
medication_days: [{ required: true, message: '请填写订单服用天数', trigger: 'change' }]
}
if (detailPrescription.value?.prescription_type === '浓缩水丸') {
rules.dosage_bag_count = [{ required: true, message: '请选择主方每次袋数', trigger: 'change' }]
}
if (detailHasAuxHerbs.value) {
rules.aux_times_per_day = [{ required: true, message: '请填写辅方每天次数', trigger: 'change' }]
rules.aux_usage_days = [{ required: true, message: '请填写辅方开立天数', trigger: 'change' }]
if (detailPrescription.value?.prescription_type === '浓缩水丸') {
rules.aux_dosage_bag_count = [{ required: true, message: '请选择辅方每次袋数', trigger: 'change' }]
}
}
return rules
})
@@ -4029,7 +3981,6 @@ function openPatchUsageDialog() {
return
}
const aux = detailAuxUsage.value
patchUsageForm.dosage_bag_count = Number(rx.dosage_bag_count) > 0 ? Number(rx.dosage_bag_count) : 1
patchUsageForm.times_per_day =
Number(rx.times_per_day) > 0 ? Number(rx.times_per_day) : 3
patchUsageForm.usage_days =
@@ -4039,20 +3990,16 @@ function openPatchUsageDialog() {
patchUsageForm.aux_usage_days =
aux && Number(aux.usage_days) > 0 ? Number(aux.usage_days) : 7
const md = Number(ord.medication_days)
patchUsageForm.aux_dosage_bag_count =
aux && Number(aux.dosage_bag_count) > 0 ? Number(aux.dosage_bag_count) : 1
patchUsageForm.medication_days = md > 0 ? md : Number(rx.usage_days) > 0 ? Number(rx.usage_days) : 7
patchUsageVisible.value = true
nextTick(() => patchUsageFormRef.value?.clearValidate())
}
function resetPatchUsageForm() {
patchUsageForm.dosage_bag_count = 1
patchUsageForm.times_per_day = 3
patchUsageForm.usage_days = 7
patchUsageForm.aux_times_per_day = 3
patchUsageForm.aux_usage_days = 7
patchUsageForm.aux_dosage_bag_count = 1
patchUsageForm.medication_days = undefined
}
@@ -4073,25 +4020,17 @@ async function submitPatchUsage() {
times_per_day: number
usage_days: number
medication_days: number
dosage_bag_count?: number
aux_times_per_day?: number
aux_usage_days?: number
aux_dosage_bag_count?: number
} = {
id: ordId,
times_per_day: Number(patchUsageForm.times_per_day),
usage_days: Number(patchUsageForm.usage_days),
medication_days: Number(patchUsageForm.medication_days)
}
if (detailPrescription.value?.prescription_type === '浓缩水丸') {
payload.dosage_bag_count = Number(patchUsageForm.dosage_bag_count)
}
if (detailHasAuxHerbs.value) {
payload.aux_times_per_day = Number(patchUsageForm.aux_times_per_day)
payload.aux_usage_days = Number(patchUsageForm.aux_usage_days)
if (detailPrescription.value?.prescription_type === '浓缩水丸') {
payload.aux_dosage_bag_count = Number(patchUsageForm.aux_dosage_bag_count)
}
}
await prescriptionOrderPatchPrescriptionUsage(payload)
feedback.msgSuccess('保存成功')
-19
View File
@@ -144,17 +144,6 @@
>
<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 }">
@@ -313,14 +302,6 @@
<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 || '待关联' }}
+7 -30
View File
@@ -1,6 +1,5 @@
<template>
<div class="reception-page">
<DoctorWebConsultationNotice />
<!-- 页头 -->
<div class="reception-header">
<div class="header-left">
@@ -84,18 +83,10 @@
<el-icon v-else><ChatDotRound /></el-icon>
</button>
</el-tooltip>
<el-tooltip :content="webConsultationBlocked ? webConsultationMessage : '发起通话'" placement="top">
<span class="row-call-action">
<button
class="row-icon-btn call"
:disabled="webConsultationBlocked"
:aria-label="webConsultationBlocked ? webConsultationMessage : '发起通话'"
@click="handleCall(row)"
>
<el-icon><Phone /></el-icon>
<span v-if="webConsultationBlocked">已停用</span>
</button>
</span>
<el-tooltip content="发起通话" placement="top">
<button class="row-icon-btn call" @click="handleCall(row)">
<el-icon><Phone /></el-icon>
</button>
</el-tooltip>
</div>
</div>
@@ -198,8 +189,6 @@
<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'
@@ -222,7 +211,6 @@ const DiagnosisEdit = defineAsyncComponent(() => import('@/views/tcm/diagnosis/e
const POLL_MS = 5_000
const PAGE_SIZE = 15
const { webConsultationBlocked, webConsultationMessage, ensureWebConsultationAllowed } = useDoctorWebConsultation()
interface QueueRow {
id: number
@@ -450,7 +438,6 @@ 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) {
@@ -467,7 +454,6 @@ 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,
@@ -1018,25 +1004,16 @@ onUnmounted(() => {
font-size: 15px;
padding: 0;
}
.row-call-action {
display: inline-flex;
}
.row-icon-btn.call:disabled {
width: auto;
gap: 4px;
padding: 0 6px;
font-size: 12px;
}
.row-icon-btn:hover:not(:disabled) {
.row-icon-btn:hover {
background: var(--rx-accent-soft);
color: var(--rx-accent-strong);
border-color: var(--rx-accent);
transform: translateY(-1px);
}
.row-icon-btn:active:not(:disabled) {
.row-icon-btn:active {
transform: scale(0.92);
}
.row-icon-btn.notify:hover:not(:disabled) {
.row-icon-btn.notify:hover {
background: #fff7e6;
color: var(--rx-warning);
border-color: var(--rx-warning);
@@ -0,0 +1,636 @@
<template>
<div class="identity-management">
<el-card shadow="never">
<div class="flex items-center justify-between mb-4">
<div>
<h2 class="text-xl font-semibold">IAM 关联管理</h2>
<p class="text-gray-500 mt-2">
保留历史本地账号、业务角色与数据;只管理统一身份关联。
</p>
</div>
<el-button @click="reauthVisible = true">验证管理员身份</el-button>
</div>
<el-alert
v-if="error"
:title="error"
type="warning"
show-icon
:closable="false"
class="mb-4"
/>
<el-alert
v-if="!enabled"
title="IAM v2 尚未启用,原有业务与登录方式保持不变。"
type="info"
:closable="false"
/>
<el-form v-if="enabled" inline class="mt-4" @submit.prevent="reload">
<el-form-item label="本地账号"
><el-input
v-model="query.q"
placeholder="账号或姓名"
clearable
@keyup.enter="reload"
/></el-form-item>
<el-form-item label="关联状态"
><el-select v-model="query.state" clearable class="!w-40"
><el-option
v-for="(label, key) in states"
:key="key"
:label="label"
:value="key" /></el-select
></el-form-item>
<el-form-item
><el-button type="primary" @click="reload">查询</el-button
><el-button :disabled="!can('batch')" @click="batchVisible = true"
>批量预检</el-button
></el-form-item
>
</el-form>
<el-table v-if="enabled" v-loading="loading" :data="rows" row-key="id">
<el-table-column prop="id" label="ID" width="70" />
<el-table-column prop="account" label="本地账号" min-width="140" />
<el-table-column prop="name" label="姓名" min-width="120" />
<el-table-column label="本地状态" width="110"
><template #default="{ row }"
><el-tag :type="row.disable ? 'danger' : 'success'">{{
row.disable ? '停用' : row.root ? '敏感账号' : '正常'
}}</el-tag></template
></el-table-column
>
<el-table-column label="IAM 员工" min-width="180"
><template #default="{ row }"
>{{ row.iam.employee?.displayName || '—' }}
<div class="text-xs text-gray-500">
{{ row.iam.employee?.username }}
</div></template
></el-table-column
>
<el-table-column label="关联状态" width="130"
><template #default="{ row }"
><el-tag :type="row.iam.state === 'verified' ? 'success' : 'info'">{{
states[row.iam.state] || row.iam.state
}}</el-tag>
<div class="text-xs">
版本 {{ row.iam.binding?.version ?? '—' }}
</div></template
></el-table-column
>
<el-table-column label="操作" min-width="210"
><template #default="{ row }">
<el-button
link
type="primary"
:disabled="
(!!row.root && !reviewAllowed) ||
row.iam.state === 'verified' ||
!can(row.iam.state === 'revoked' ? 'rebind' : 'bind')
"
@click="open(row, 'bind')"
>关联</el-button
>
<el-button
link
type="primary"
:disabled="
(!!row.root && !reviewAllowed) ||
row.iam.state === 'verified' ||
!can('create') ||
(row.iam.state === 'revoked' && !can('rebind'))
"
@click="open(row, 'create_and_bind')"
>创建并关联</el-button
>
<el-dropdown @command="(kind: string) => more(row, kind)"
><el-button link>更多</el-button
><template #dropdown
><el-dropdown-menu>
<el-dropdown-item
command="rebind"
:disabled="(!!row.root && !reviewAllowed) || !can('rebind')"
>换绑</el-dropdown-item
>
<el-dropdown-item
command="unbind"
:disabled="(!!row.root && !reviewAllowed) || !can('unbind')"
>解绑</el-dropdown-item
>
<el-dropdown-item command="audit">审计记录</el-dropdown-item>
</el-dropdown-menu></template
></el-dropdown
>
</template></el-table-column
>
</el-table>
<el-pagination
v-if="enabled"
class="mt-4 justify-end"
layout="total, prev, pager, next"
:total="total"
v-model:current-page="query.page"
:page-size="20"
@current-change="load"
/>
</el-card>
<el-drawer
v-model="drawer"
:title="titles[operation.kind]"
size="min(680px, 94vw)"
:close-on-click-modal="false"
>
<el-steps :active="step" finish-status="success" align-center
><el-step title="核对本地账号" /><el-step title="核对 IAM 身份" /><el-step
title="确认变更"
/></el-steps>
<section class="mt-8">
<template v-if="step === 0"
><h3 class="text-lg mb-4">{{ selected?.name }} · {{ selected?.account }}</h3>
<p>本地 ID:{{ selected?.id }}</p>
<p class="my-3">
当前关联:{{ selected?.iam.employee?.displayName || '未关联' }}(版本
{{ selected?.iam.binding?.version ?? '无' }})
</p>
<el-alert
title="本次操作不改变本地密码、角色、部门或历史数据;人员同名不代表同一身份。"
type="info"
:closable="false"
/></template>
<template v-if="step === 1">
<el-form v-if="operation.kind === 'create_and_bind'" label-position="top"
><el-form-item label="IAM 登录名"
><el-input
v-model="newEmployee.username"
maxlength="64" /></el-form-item
><el-form-item label="姓名"
><el-input
v-model="newEmployee.display_name"
maxlength="100" /></el-form-item
><el-form-item label="邮箱(可选)"
><el-input v-model="newEmployee.email" /></el-form-item
><el-alert
title="使用正常员工开户流程,默认应用授权遵循 IAM 当前策略。不会生成共享初始密码;本人首次使用需设置 IAM 密码。"
type="info"
:closable="false"
/></el-form>
<template v-else-if="operation.kind !== 'unbind'"
><el-input
v-model="identityQuery"
placeholder="搜索 IAM 登录名或姓名"
@keyup.enter="searchIdentities"
><template #append
><el-button @click="searchIdentities">搜索</el-button></template
></el-input
><el-table
class="mt-4"
:data="identities"
highlight-current-row
@current-change="choose"
><el-table-column label="选择" width="70"
><template #default="{ row }"
><el-radio
:model-value="operation.employee_id"
:value="row.id"
@change="choose(row)"
><span /></el-radio></template></el-table-column
><el-table-column prop="username" label="IAM 登录名" /><el-table-column
prop="displayName"
label="姓名" /><el-table-column
prop="status"
label="状态" /></el-table
></template>
<el-alert
v-else
title="解绑后跨平台快捷登录停止,相关来源/业务会话撤销,历史数据和本地账号保留。自动开户不会恢复已撤销关联。"
type="warning"
:closable="false"
/>
</template>
<template v-if="step === 2"
><el-descriptions :column="1" border
><el-descriptions-item label="本地账号"
>{{ selected?.account }} #{{ selected?.id }}</el-descriptions-item
><el-descriptions-item label="变更类型">{{
titles[operation.kind]
}}</el-descriptions-item
><el-descriptions-item label="原 IAM 员工">{{
selected?.iam.employee?.username || '无'
}}</el-descriptions-item
><el-descriptions-item label="目标 IAM 员工">{{
operation.kind === 'unbind'
? '解除关联'
: operation.kind === 'create_and_bind'
? newEmployee.username
: chosenIdentity?.username
}}</el-descriptions-item
><el-descriptions-item label="预期版本">{{
operation.expected_version ?? '首次关联'
}}</el-descriptions-item></el-descriptions
><el-input
class="mt-4"
v-model="operation.reason"
:disabled="!!submittedPayload"
type="textarea"
:rows="3"
maxlength="500"
placeholder="必填:核对方式和变更原因,将写入审计记录"
/><el-checkbox class="mt-4" v-model="confirmed"
>我已核对本地账号与 IAM 员工为同一人,理解会话撤销影响</el-checkbox
></template
>
<el-alert
v-if="drawerError"
class="mt-4"
:title="drawerError"
type="error"
:closable="false"
/>
<el-alert
v-if="result"
class="mt-4"
:title="`操作 ${result.id}:${result.status}${result.error?.code ? ' · ' + identityError(result) : ''}`"
:type="result.status === 'succeeded' ? 'success' : 'warning'"
:closable="false"
/>
<div v-if="result?.reviewUrl" class="mt-4">
<a
:href="result.reviewUrl"
target="_blank"
rel="noopener noreferrer"
class="text-primary"
>中央复核 ↗</a
>
<p class="text-gray-500 mt-2">
由中央管理员完成近期验证并批准后,重试原操作;原目标、版本和原因保持不变。
</p>
</div>
<el-button
v-if="result && result.status !== 'succeeded'"
class="mt-4"
@click="refreshOperation"
>查询同一操作状态</el-button
>
</section>
<template #footer
><el-button @click="drawer = false">关闭</el-button
><el-button v-if="step > 0" :disabled="!!submittedPayload" @click="step--"
>上一步</el-button
><el-button
v-if="step < 2"
type="primary"
:disabled="step === 1 && !validIdentity"
@click="step++"
>下一步</el-button
><el-button
v-else
type="primary"
:loading="busy"
:disabled="
!confirmed || !operation.reason.trim() || result?.status === 'succeeded'
"
@click="submit"
>{{
result?.reviewUrl
? '完成中央复核后重试原操作'
: '确认' + titles[operation.kind]
}}</el-button
></template
>
</el-drawer>
<el-dialog v-model="reauthVisible" title="近期管理员身份验证" width="420px"
><el-input
v-model="password"
type="password"
show-password
placeholder="当前 ZYT 账号密码"
autocomplete="current-password"
@keyup.enter="reauth"
/>
<p class="mt-4 text-gray-500">
有效期 5 分钟。敏感目标还需中央管理员审核,此处不会越过审核。
</p>
<template #footer
><el-button type="primary" :loading="busy" @click="reauth"
>验证</el-button
></template
></el-dialog
>
<el-drawer v-model="auditVisible" title="关联审计" size="min(760px, 94vw)"
><el-table :data="audits"
><el-table-column prop="occurredAt" label="时间" min-width="170" /><el-table-column
prop="action"
label="操作" /><el-table-column label="操作人"
><template #default="{ row }">{{
typeof row.actor === 'string' ? row.actor : JSON.stringify(row.actor)
}}</template></el-table-column
><el-table-column prop="reason" label="原因" /></el-table
></el-drawer>
<el-dialog
v-model="batchVisible"
title="批量预检与确认"
width="min(920px, 94vw)"
:close-on-click-modal="false"
>
<el-alert
title="先预检,不会创建账号或修改绑定。仅选择 ready 项后显式确认;敏感账号与冲突项跳过。每批最多 100 条。"
type="info"
:closable="false"
/>
<el-input
v-model="batchText"
class="mt-4"
type="textarea"
:rows="7"
placeholder='[{"kind":"bind","user_id":42,"employee_id":"员工ID","reason":"核对后历史关联"}]'
/>
<el-button class="mt-4" :loading="busy" @click="preflight">只读预检</el-button>
<el-table
v-if="preview"
class="mt-4"
:data="preview.items"
@selection-change="(items: any[]) => (selectedIndexes = items.map((x) => x.index))"
><el-table-column
type="selection"
:selectable="(row: any) => row.status === 'ready'" /><el-table-column
prop="externalAccountId"
label="本地 ID" /><el-table-column prop="status" label="状态" /><el-table-column
prop="message"
label="结果"
/></el-table>
<el-checkbox v-if="preview" v-model="batchConfirmed" class="mt-4"
>确认仅执行已选择项目({{ selectedIndexes.length }} 条)</el-checkbox
>
<section v-if="job" class="mt-4">
<h3>任务 {{ job.id }} · {{ job.status }}</h3>
<el-table :data="job.items"
><el-table-column prop="externalAccountId" label="本地账号" /><el-table-column
prop="status"
label="状态"
/><el-table-column label="结果"
><template #default="{ row }">{{
row.error?.message || row.error?.code || '—'
}}</template></el-table-column
></el-table
><el-button @click="refreshJob">刷新任务</el-button
><el-button
:disabled="
!job.items?.some((x: any) => ['failed', 'pending'].includes(x.status))
"
@click="retryJob"
>只重试失败/待处理项</el-button
>
</section>
<template #footer
><el-button @click="batchVisible = false">关闭</el-button
><el-button
type="primary"
:loading="busy"
:disabled="
!preview?.previewId || !batchConfirmed || !selectedIndexes.length || !!job
"
@click="submitBatch"
>确认执行</el-button
></template
>
</el-dialog>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { iamGet, iamPost, identityError, type IdentityOperation } from '@/api/iam-v2'
const states: Record<string, string> = {
verified: '已关联',
unlinked: '未关联',
revoked: '已撤销',
pending: '待确认',
conflict: '冲突',
unknown: '待核验'
}
const titles: Record<string, string> = {
bind: '关联',
create_and_bind: '创建并关联',
rebind: '换绑',
unbind: '解绑',
reconcile: '对账'
}
const enabled = ref(false),
reviewAllowed = ref(false),
managementEnabled = ref(false),
caps = ref<string[]>([]),
rows = ref<any[]>([]),
total = ref(0),
loading = ref(false),
busy = ref(false),
error = ref('')
const query = reactive({ q: '', state: '', page: 1, pageSize: 20 })
const drawer = ref(false),
step = ref(0),
selected = ref<any>(null),
identities = ref<any[]>([]),
identityQuery = ref(''),
chosenIdentity = ref<any>(null),
confirmed = ref(false),
drawerError = ref(''),
result = ref<any>(null)
const submittedPayload = ref<Record<string, unknown> | null>(null)
const operation = reactive<IdentityOperation>({ kind: 'bind', user_id: 0, reason: '' }),
newEmployee = reactive({ username: '', display_name: '', email: '' })
let operationKey = crypto.randomUUID(),
batchKey = crypto.randomUUID()
const reauthVisible = ref(false),
password = ref(''),
auditVisible = ref(false),
audits = ref<any[]>([])
const batchVisible = ref(false),
batchText = ref(''),
preview = ref<any>(null),
selectedIndexes = ref<number[]>([]),
batchConfirmed = ref(false),
job = ref<any>(null)
const can = (c: string) => caps.value.includes(c) && (c === 'read' || managementEnabled.value)
const validIdentity = computed(
() =>
operation.kind === 'unbind' ||
(operation.kind === 'create_and_bind'
? !!newEmployee.username.trim() && !!newEmployee.display_name.trim()
: !!operation.employee_id)
)
async function load() {
loading.value = true
try {
const r = await iamGet('/accounts', query)
rows.value = r.items
total.value = r.total
error.value = ''
} catch (e) {
error.value = identityError(e)
} finally {
loading.value = false
}
}
function reload() {
query.page = 1
void load()
}
function open(row: any, kind: IdentityOperation['kind']) {
if (kind === 'bind' && row.iam.state === 'revoked') kind = 'rebind'
selected.value = row
Object.assign(operation, {
kind,
user_id: row.id,
employee_id: undefined,
expected_version: row.iam.binding?.version,
reason: ''
})
Object.assign(newEmployee, { username: '', display_name: row.name, email: '' })
drawer.value = true
step.value = 0
confirmed.value = false
drawerError.value = ''
result.value = null
submittedPayload.value = null
chosenIdentity.value = null
identities.value = []
operationKey = crypto.randomUUID()
}
async function more(row: any, kind: string) {
if (kind === 'audit') {
try {
audits.value = (await iamGet(`/accounts/${row.id}/audit`)).items
auditVisible.value = true
} catch (e) {
error.value = identityError(e)
}
} else open(row, kind as IdentityOperation['kind'])
}
async function searchIdentities() {
try {
identities.value = (
await iamGet('/identities', { q: identityQuery.value, page: 1, pageSize: 20 })
).items
} catch (e) {
drawerError.value = identityError(e)
}
}
function choose(row: any) {
if (row?.status === 'active') {
chosenIdentity.value = row
operation.employee_id = row.id
}
}
async function submit() {
busy.value = true
try {
if (!submittedPayload.value) {
submittedPayload.value = JSON.parse(
JSON.stringify({
...operation,
...(operation.kind === 'create_and_bind'
? { new_employee: { ...newEmployee } }
: {})
})
)
}
result.value = await iamPost('/operations', submittedPayload.value!, operationKey)
drawerError.value = ''
await load()
} catch (e) {
drawerError.value = identityError(e)
} finally {
busy.value = false
}
}
async function refreshOperation() {
try {
result.value = await iamGet(`/operations/${result.value.id}`)
await load()
} catch (e) {
drawerError.value = identityError(e)
}
}
async function reauth() {
busy.value = true
try {
await iamPost('/reauth', { password: password.value })
reauthVisible.value = false
ElMessage.success('身份已验证,有效期 5 分钟')
await load()
} catch (e) {
error.value = identityError(e)
} finally {
password.value = ''
busy.value = false
}
}
async function preflight() {
busy.value = true
preview.value = null
job.value = null
batchConfirmed.value = false
selectedIndexes.value = []
try {
const items = JSON.parse(batchText.value)
if (!Array.isArray(items) || items.length < 1 || items.length > 100) throw Error('input')
preview.value = await iamPost('/batch/preflight', { items })
batchKey = crypto.randomUUID()
} catch (e) {
error.value = e instanceof SyntaxError ? '批量输入必须是 JSON 数组。' : identityError(e)
} finally {
busy.value = false
}
}
async function submitBatch() {
busy.value = true
try {
job.value = await iamPost(
'/batch',
{ preview_id: preview.value.previewId, indexes: selectedIndexes.value },
batchKey
)
await load()
} catch (e) {
error.value = identityError(e)
} finally {
busy.value = false
}
}
async function refreshJob() {
try {
job.value = await iamGet(`/jobs/${job.value.id}`)
await load()
} catch (e) {
error.value = identityError(e)
}
}
async function retryJob() {
busy.value = true
try {
job.value = await iamPost(`/jobs/${job.value.id}/retry`)
await load()
} catch (e) {
error.value = identityError(e)
} finally {
busy.value = false
}
}
onMounted(async () => {
try {
const s = await iamGet('/status')
enabled.value = s.enabled
caps.value = s.management_capabilities || []
reviewAllowed.value = s.protected_review_operator === true
managementEnabled.value = s.management_enabled === true
if (enabled.value && can('read')) await load()
} catch (e) {
error.value = identityError(e)
}
})
</script>
<style scoped>
.identity-management p {
line-height: 1.7;
}
.identity-management :deep(.el-steps) {
margin-bottom: 24px;
}
</style>
@@ -1,227 +0,0 @@
<template>
<div class="prescription-ai-visibility">
<el-card v-loading="loading" shadow="never" class="!border-none">
<div class="text-xl font-medium mb-[20px]">处方 AI 一致度可见范围</div>
<el-alert type="info" :closable="false" show-icon class="mb-5">
<template #title>指定用户组或用户可查看一致度</template>
<div class="leading-6">
用户命中任一指定系统角色,或被单独指定,即可查看桌面端“与 AI
一致度”、逐味对照和一致度统计。AI
报告继续按原有权限开放,已有报告不受影响,患者与处方的数据范围保持原有规则。
</div>
</el-alert>
<el-alert
v-if="loadError"
:title="loadError"
type="error"
:closable="false"
show-icon
class="mb-5"
/>
<div v-if="loading" role="status" class="mb-5">正在读取当前可见范围…</div>
<el-form
v-if="hasLoaded"
class="ls-form"
:model="formData"
:disabled="!ready || loading || saving"
label-width="140px"
>
<el-form-item label="指定用户组" prop="role_ids">
<div class="w-full max-w-[640px]">
<el-select
v-model="formData.role_ids"
class="w-full"
multiple
filterable
clearable
placeholder="请选择系统角色,可搜索角色名称"
>
<el-option
v-for="role in roleOptions"
:key="role.id"
:label="role.name"
:value="role.id"
/>
</el-select>
<div class="form-tips">账号拥有任一指定角色即可命中。</div>
</div>
</el-form-item>
<el-form-item label="指定用户" prop="admin_ids">
<div class="w-full max-w-[640px]">
<el-select
v-model="formData.admin_ids"
class="w-full"
multiple
filterable
clearable
placeholder="请选择用户,可搜索姓名或账号"
>
<el-option
v-for="admin in adminOptions"
:key="admin.id"
:label="admin.label"
:value="admin.id"
/>
</el-select>
<div class="form-tips">
单独指定的用户无需同时命中用户组。当前不在可选列表中的已配置 ID
会保留,移除后保存才会取消该项授权。
</div>
</div>
</el-form-item>
<el-form-item label="生效规则">
<div>
<div class="leading-6">指定用户组与指定用户按“或”生效。</div>
<div class="form-tips">
两项均为空时,所有账号(包括超级管理员)均隐藏一致度、对照与统计。
拥有本页管理权限不自动获得一致度查看权,超级管理员也需命中上述名单。
</div>
</div>
</el-form-item>
</el-form>
<el-alert
v-if="ready && !formData.role_ids.length && !formData.admin_ids.length"
title="当前选择为空:保存后所有账号将隐藏一致度、对照与统计,AI 报告仍保留。"
type="warning"
:closable="false"
show-icon
class="mb-5"
/>
<el-alert
v-if="saveError"
:title="saveError"
type="error"
:closable="false"
show-icon
class="mb-5"
/>
<el-button :disabled="loading || saving" @click="loadConfig">
{{ loadError ? '重试加载' : '重新加载' }}
</el-button>
</el-card>
<footer-btns v-if="canManage">
<el-button
type="primary"
:loading="saving"
:disabled="!ready || loading || saving"
@click="handleSubmit"
>
{{ saving ? '正在保存' : '保存' }}
</el-button>
</footer-btns>
</div>
</template>
<script setup lang="ts" name="prescriptionAiVisibility">
import { computed, reactive, ref } from 'vue'
import type {
PrescriptionAiVisibilityConfig,
PrescriptionAiVisibilityOptions
} from '@/api/setting/prescription_ai_visibility'
import {
getPrescriptionAiCapabilities,
getPrescriptionAiVisibilityConfig,
getPrescriptionAiVisibilityOptions,
setPrescriptionAiVisibilityConfig
} from '@/api/setting/prescription_ai_visibility'
import feedback from '@/utils/feedback'
const loading = ref(false)
const saving = ref(false)
const ready = ref(false)
const hasLoaded = ref(false)
const canManage = ref(false)
const loadError = ref('')
const saveError = ref('')
const formData = reactive<PrescriptionAiVisibilityConfig>({ role_ids: [], admin_ids: [] })
const optionsData = reactive<PrescriptionAiVisibilityOptions>({ roles: [], admins: [] })
const roleOptions = computed(() => {
const options = new Map(optionsData.roles.map((role) => [role.id, role]))
for (const id of formData.role_ids) {
if (!options.has(id)) {
options.set(id, { id, name: `已配置角色 #${id}(当前不在可选列表)` })
}
}
return [...options.values()]
})
const adminOptions = computed(() => {
const options = new Map(
optionsData.admins.map((admin) => [
admin.id,
{ id: admin.id, label: `${admin.name || `用户 #${admin.id}`}(${admin.account})` }
])
)
for (const id of formData.admin_ids) {
if (!options.has(id)) {
options.set(id, { id, label: `已配置用户 #${id}(当前不在可选列表)` })
}
}
return [...options.values()]
})
const assignConfig = (config: PrescriptionAiVisibilityConfig) => {
formData.role_ids = [...config.role_ids]
formData.admin_ids = [...config.admin_ids]
}
const loadConfig = async () => {
if (loading.value || saving.value) return
loading.value = true
ready.value = false
canManage.value = false
loadError.value = ''
saveError.value = ''
try {
const capabilities = await getPrescriptionAiCapabilities()
if (capabilities.can_manage_visibility !== true) {
loadError.value = '当前账号无权管理处方 AI 一致度可见范围。'
return
}
canManage.value = true
const [config, options] = await Promise.all([
getPrescriptionAiVisibilityConfig(),
getPrescriptionAiVisibilityOptions()
])
if (!Array.isArray(options?.roles) || !Array.isArray(options?.admins)) {
throw new Error('可选用户组或用户响应格式不正确')
}
// Apply both responses together; an incomplete load cannot overwrite the current policy.
assignConfig(config)
optionsData.roles = options.roles
optionsData.admins = options.admins
hasLoaded.value = true
ready.value = true
} catch {
loadError.value = '可见范围加载失败,尚未读取完整配置。请重试加载后再保存。'
} finally {
loading.value = false
}
}
const handleSubmit = async () => {
if (!ready.value || !canManage.value || loading.value || saving.value) return
saving.value = true
saveError.value = ''
try {
const config = await setPrescriptionAiVisibilityConfig({
role_ids: [...formData.role_ids],
admin_ids: [...formData.admin_ids]
})
assignConfig(config)
feedback.msgSuccess('可见范围已保存')
} catch {
saveError.value = '保存结果未确认,当前选择已保留。请重试保存,或重新加载以确认服务端策略。'
} finally {
saving.value = false
}
}
void loadConfig()
</script>
@@ -56,70 +56,6 @@
/>
<el-empty v-else description="暂无数据" />
</el-card>
<!-- 我的复诊接诊率(方案 §10 D1-h):仅本人行,口径与「复诊接诊率」报表一致 -->
<el-card v-if="canViewRevisitRate" class="!border-none mt-4" shadow="never">
<template #header>
<div class="card-header">
<div class="card-header-left">
<span class="card-title">我的复诊接诊率</span>
<el-date-picker
v-model="revisitMonth"
type="month"
value-format="YYYY-MM"
placeholder="选择月份"
:clearable="false"
:disabled-date="disableFutureMonth"
size="small"
style="width: 130px"
@change="fetchRevisitRate"
/>
</div>
<span class="card-hint">{{ revisitMonthText }} · 与「复诊接诊率」报表同口径</span>
</div>
</template>
<div v-loading="revisitLoading" class="revisit-rate-body">
<template v-if="revisitRow">
<div class="revisit-kpi-grid">
<div class="revisit-kpi-card">
<div class="stats-kpi-label">新指派数</div>
<div class="revisit-kpi-value">
{{ Number(revisitRow.assigned_count ?? 0) }}
</div>
<div class="revisit-kpi-sub">当月新指派给我的患者</div>
</div>
<div class="revisit-kpi-card">
<div class="stats-kpi-label">继承数</div>
<div class="revisit-kpi-value">
{{ Number(revisitRow.inherit_count ?? 0) }}
</div>
<div class="revisit-kpi-sub">当月继承给我的患者</div>
</div>
<div class="revisit-kpi-card is-primary">
<div class="stats-kpi-label">复诊合计接诊率</div>
<div class="revisit-kpi-value">
{{ formatRate(revisitRow.visit_all_rate) }}
</div>
<div class="revisit-kpi-sub">{{ visitAllFractionText }}</div>
</div>
<div v-for="slot in revisitSlots" :key="slot" class="revisit-kpi-card">
<div class="stats-kpi-label">{{ slotLabel(slot) }}接诊率</div>
<div class="revisit-kpi-value">
{{ formatRate(slotMetric(slot, 'rate')) }}
</div>
<div class="revisit-kpi-sub">{{ slotFractionText(slot) }}</div>
</div>
</div>
</template>
<el-empty v-else :description="revisitEmptyText" :image-size="72" />
<div class="revisit-caliber">
口径:N 诊接诊率 = 当月 N 诊成交单数 ÷ N 诊分母(新指派数 + 起算诊次 ≤ N 的继承数),分母为 0 显示「—」;
<template v-if="revisitInheritMode === 'exclude'">当前为旧口径,继承患者不计入分母;</template>
<template v-else>继承患者按继承时诊次从第 k+1 诊起计入;</template>
复诊合计 = 各诊次成交单数之和 ÷ 被指派合计(新指派 ∪ 继承),可超过 100%。
</div>
</div>
</el-card>
</div>
</template>
@@ -127,12 +63,7 @@
import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import vCharts from 'vue-echarts'
import {
assistantPerformanceOverview,
assistantPerformanceRevisitRate,
type AssistantRevisitRateResult
} from '@/api/stats'
import { hasPermission } from '@/utils/perm'
import { assistantPerformanceOverview } from '@/api/stats'
const loading = ref(false)
const dateRange = ref<string[]>([])
@@ -260,78 +191,8 @@ const handleReset = () => {
fetchData()
}
// ── 我的复诊接诊率(方案 §10 D1-h)────────────────────────
/** 权限点由 server/sql/1.9.20261012/10_add_assistant_revisit_rate_menu.sql 登记并自动授予已有个人业绩页的角色 */
const canViewRevisitRate = hasPermission(['stats.assistantPerformance/revisitRate'])
const initNow = new Date()
const currentMonth = `${initNow.getFullYear()}-${String(initNow.getMonth() + 1).padStart(2, '0')}`
const revisitMonth = ref<string>(currentMonth)
const revisitLoading = ref(false)
const revisitResult = ref<AssistantRevisitRateResult | null>(null)
const revisitRow = computed(() => revisitResult.value?.row ?? null)
const revisitInheritMode = computed(() => revisitResult.value?.inherit_mode ?? 'slot')
const revisitSlots = computed(() =>
(revisitResult.value?.slots ?? []).map((s) => Number(s)).filter((s) => s >= 2)
)
const revisitMonthText = computed(() => {
const [y, m] = (revisitResult.value?.month || revisitMonth.value).split('-')
return y && m ? `${y} 年 ${Number(m)} 月` : revisitMonth.value
})
/** row=null:非二中心医助(in_scope=false)与「当月无被指派患者」文案区分 */
const revisitEmptyText = computed(() => {
if (revisitResult.value && revisitResult.value.in_scope === false) {
return '暂无数据(仅二中心医助统计)'
}
return revisitMonth.value === currentMonth ? '本月暂无被指派患者' : '该月暂无被指派患者'
})
const disableFutureMonth = (date: Date) => {
const now = new Date()
return date.getFullYear() * 12 + date.getMonth() > now.getFullYear() * 12 + now.getMonth()
}
const cnDigits = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十']
const slotLabel = (slot: number) => {
if (slot >= 2 && slot <= 10) return `${cnDigits[slot]}诊`
if (slot > 10 && slot < 20) return `十${cnDigits[slot - 10]}诊`
return `${slot}诊`
}
const formatRate = (rate: unknown) =>
rate === null || rate === undefined || rate === '' ? '—' : `${Number(rate)}%`
/** 读取本人行的 visit{N}_count / visit{N}_den / visit{N}_rate */
const slotMetric = (slot: number, kind: 'count' | 'den' | 'rate') =>
revisitRow.value?.[`visit${slot}_${kind}`]
/** 「成交 N 单 / 分母 M」 */
const fractionText = (count: unknown, den: unknown) =>
`成交 ${Number(count ?? 0)} 单 / 分母 ${Number(den ?? 0)}`
const slotFractionText = (slot: number) =>
fractionText(slotMetric(slot, 'count'), slotMetric(slot, 'den'))
const visitAllFractionText = computed(() =>
fractionText(revisitRow.value?.visit_all_count, revisitRow.value?.visit_all_den)
)
const fetchRevisitRate = async () => {
if (!canViewRevisitRate) return
revisitLoading.value = true
try {
revisitResult.value = await assistantPerformanceRevisitRate({ month: revisitMonth.value })
} catch {
// 错误提示由 utils/request 统一弹出;失败时保留上一次结果
} finally {
revisitLoading.value = false
}
}
onMounted(() => {
fetchData()
fetchRevisitRate()
})
</script>
@@ -409,57 +270,4 @@ onMounted(() => {
.stats-chart {
height: 360px;
}
.card-header-left {
display: flex;
align-items: center;
gap: 12px;
}
.revisit-rate-body {
min-height: 120px;
}
.revisit-kpi-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
gap: 12px;
}
.revisit-kpi-card {
background: linear-gradient(145deg, #ffffff, #f7f9ff);
border: 1px solid #ebf1ff;
border-radius: 12px;
padding: 14px 16px;
}
.revisit-kpi-card.is-primary {
background: linear-gradient(145deg, #ffffff, #eef3ff);
border-color: #d9e4ff;
}
.revisit-kpi-value {
margin-top: 8px;
font-size: 24px;
line-height: 1.1;
font-weight: 700;
color: #1f2937;
}
.revisit-kpi-card.is-primary .revisit-kpi-value {
color: #4a78ff;
}
.revisit-kpi-sub {
margin-top: 6px;
font-size: 12px;
color: #909399;
}
.revisit-caliber {
margin-top: 12px;
font-size: 12px;
line-height: 1.6;
color: #909399;
}
</style>
@@ -67,10 +67,7 @@
</el-form>
<div class="log-hint">
由每日定时任务「待分配诊单自动指派」写入:按上月二诊复诊接诊率分档轮询分配(&gt;70% 每人3条/日,60%~70%
每人2条/日,50%~60% 每人1条/日,&lt;50% 不分)。「回退」可将已分配医助撤回到自动分配前的原医助(通常为一中心),并写入指派日志(原医助重新接手按「继承」记录)。
<br />
口径版本:<b>v1 旧口径</b> = 分母仅新指派(visit2_rate_new_assign);<b>v2 新口径</b> = 每列独立分母,继承按继承时诊次计入(visit2_rate)。
每条日志同时记录两套率并标注本批次分档所用口径(配置 project.revisit_rate.auto_assign_tier_field);2026-10 前的历史行仅有旧口径率。
每人2条/日,50%~60% 每人1条/日,&lt;50% 不分)。「回退」可将已分配医助撤回到自动分配前的原医助(通常为一中心),并写入指派日志。
</div>
</el-card>
@@ -140,7 +137,7 @@
<template #default="{ row }">
<template v-if="Number(row.assistant_id) > 0">
<div>{{ row.assistant_name || '#' + row.assistant_id }}</div>
<div class="cell-sub">上月二诊接诊率 {{ formatRate(tierRate(row)) }}</div>
<div class="cell-sub">上月二诊接诊率 {{ formatRate(row.visit2_rate) }}</div>
</template>
<span v-else>—</span>
</template>
@@ -148,29 +145,6 @@
<el-table-column label="档位" width="100" align="center">
<template #default="{ row }">{{ row.tier_text || '—' }}</template>
</el-table-column>
<el-table-column label="分档口径" min-width="150">
<template #header>
<span>分档口径</span>
<el-tooltip
placement="top"
effect="dark"
content="本批次分档所用口径;下方为两套口径的上月二诊接诊率(新口径 = 每列独立分母 / 旧口径 = 分母仅新指派)"
>
<el-icon class="col-hint"><InfoFilled /></el-icon>
</el-tooltip>
</template>
<template #default="{ row }">
<template v-if="Number(row.action) === 1">
<el-tag :type="row.rate_version === 'v2' ? 'primary' : 'info'" size="small">
{{ row.rate_version_text || row.rate_version || 'v1' }}
</el-tag>
<div class="cell-sub">
新口径 {{ formatRate(row.visit2_rate) }} · 旧口径 {{ formatRate(row.visit2_rate_new_assign) }}
</div>
</template>
<span v-else class="cell-sub">—</span>
</template>
</el-table-column>
<el-table-column label="轮次" width="70" align="center">
<template #default="{ row }">
{{ Number(row.round_no) > 0 ? '第' + row.round_no + '轮' : '—' }}
@@ -212,7 +186,6 @@
import { autoAssignLogLists, autoAssignLogRollback } from '@/api/stats'
import { usePaging } from '@/hooks/usePaging'
import feedback from '@/utils/feedback'
import { InfoFilled } from '@element-plus/icons-vue'
import { onMounted, reactive, ref, watch } from 'vue'
const dateRange = ref<[string, string] | null>(null)
@@ -268,14 +241,6 @@ const handleReset = () => {
const formatRate = (rate: number | null | undefined) =>
rate === null || rate === undefined ? '—' : `${rate}%`
/** 「医助」列显示的接诊率 = 本批次分档所用口径的率(v1 旧口径取 visit2_rate_new_assign,历史行无该列时回落 visit2_rate) */
const tierRate = (row: any): number | null | undefined => {
if (row?.rate_version === 'v1' && row?.visit2_rate_new_assign !== null && row?.visit2_rate_new_assign !== undefined) {
return row.visit2_rate_new_assign
}
return row?.visit2_rate
}
const rowSelectable = (row: any) => Number(row.can_rollback) === 1
const onSelectionChange = (rows: any[]) => {
@@ -350,12 +315,5 @@ onMounted(() => getLists())
font-size: 12px;
color: var(--el-text-color-secondary);
}
.col-hint {
margin-left: 2px;
vertical-align: -2px;
color: var(--el-text-color-secondary);
cursor: help;
}
}
</style>
@@ -1,901 +0,0 @@
<template>
<div class="revisit-rate-page">
<el-card class="!border-none" shadow="never">
<el-form :inline="true" class="rate-filter-form">
<el-form-item :label="dateLabel">
<el-date-picker
v-model="dateRange"
type="daterange"
value-format="YYYY-MM-DD"
start-placeholder="开始日期"
end-placeholder="结束日期"
range-separator="至"
:clearable="false"
style="width: 280px"
@change="loadData"
/>
</el-form-item>
<el-form-item label="部门">
<el-tree-select
v-model="deptId"
:data="deptTreeOptions"
placeholder="二中心(全部)"
clearable
filterable
check-strictly
node-key="id"
:default-expand-all="true"
:props="deptTreeProps"
style="width: 210px"
@change="handleDeptChange"
/>
</el-form-item>
<el-form-item label="医助">
<el-select
v-model="assistantId"
placeholder="全部医助"
filterable
clearable
:loading="optionsLoading"
style="width: 180px"
@change="loadData"
>
<el-option
v-for="assistant in assistantOptions"
:key="assistant.id"
:label="assistant.name"
:value="assistant.id"
/>
</el-select>
</el-form-item>
<el-form-item>
<el-button type="primary" :loading="loading" @click="loadData">查询</el-button>
<el-button :disabled="loading" @click="handleReset">重置</el-button>
</el-form-item>
<el-form-item>
<el-popover placement="bottom-start" :width="540" trigger="hover">
<template #reference>
<span class="rate-caliber-trigger"
><el-icon><InfoFilled /></el-icon>统计口径</span
>
</template>
<div class="rate-caliber">
<p>
<b>{{ cohortLabel }}</b
>:按所选{{
dateLabel
}}范围确定患者,订单从对应指派后累计至查询当天;结束日期允许选择未来日期,但未来订单不会提前计入。
</p>
<p v-if="isInherit">
<b>继承诊次重新起算</b>:继承后的第 1 笔有效订单算二诊,第 2
笔算三诊,依次递增;不使用继承前的全局诊次,也不叠加诊次偏移。只统计继承患者,不混入新指派患者。
</p>
<p v-else>
只统计新指派患者,不混入继承患者。继承患者在独立的「继承复诊接诊率」页面统计。
</p>
<p>
<b>N 诊接诊率</b> = N 诊单数 ÷ 本页{{ cohortLabel }};分母为 0
显示「—」。<b>复诊合计接诊率</b> = 复诊合计单数 ÷ 本页{{
cohortLabel
}},表示人均复诊成交单数,可超过 100%。
</p>
<p>
订单仅计入有效业务订单,剔除已取消 / 拒收 /
退款;归属按服务端的患者持有记录计算。医助按人事部门归组;仅统计「二中心」及其组织下级,选定部门时包含其下级。
</p>
<p>
部门行和合计行按诊单去重,不能直接将医助行相加。灰字为「单数 /
分母」。
</p>
</div>
</el-popover>
</el-form-item>
</el-form>
<el-alert class="mt-3" type="info" :closable="false" show-icon :title="reportHint" />
<el-alert
v-if="optionsError"
class="mt-3"
type="warning"
:title="optionsError"
:closable="false"
/>
<el-alert
v-if="queryError"
class="mt-3"
type="error"
:title="queryError"
:closable="false"
/>
</el-card>
<div class="rate-kpi-grid">
<div
v-for="card in summaryCards"
:key="card.key"
class="rate-kpi-card"
:class="{ 'is-clickable': card.clickable }"
@click="card.clickable && card.onClick()"
>
<div class="rate-kpi-label">{{ card.label }}</div>
<div class="rate-kpi-value">{{ card.value }}</div>
<div v-if="card.sub" class="rate-kpi-sub">{{ card.sub }}</div>
</div>
</div>
<el-card class="!border-none mt-4" shadow="never">
<template #header>
<div class="rate-card-header">
<span>{{ reportTitle }} · 部门 / 医助明细</span>
<span class="rate-card-hint">{{ dateLabel }}:{{ rangeText }}</span>
<span v-if="observedUntil" class="rate-card-hint"
>订单统计截至:{{ observedUntil }}</span
>
</div>
<div class="rate-card-hint mt-2">
点击{{ cohortLabel }}、各诊次单数可查看患者与订单;底栏合计按诊单去重。
</div>
</template>
<el-table
v-loading="loading"
:data="rows"
size="small"
border
row-key="row_key"
:tree-props="{ children: 'children' }"
:default-expand-all="true"
show-summary
:summary-method="getSummaries"
>
<el-table-column label="部门 / 医助" min-width="200" fixed>
<template #default="{ row }">
<span v-if="row.is_dept" class="rate-dept-cell"
>{{ row.dept_name
}}<span class="rate-dept-count"
>{{ row.assistant_count }} 人</span
></span
>
<span v-else>{{ row.assistant_name }}</span>
</template>
</el-table-column>
<el-table-column
:prop="cohortCountKey"
:label="cohortLabel"
min-width="100"
align="right"
>
<template #header>
<span>{{ cohortLabel }}</span>
<el-tooltip
effect="dark"
placement="top"
:content="`所选${dateLabel}范围内的${cohortLabel},部门和合计按诊单去重`"
><el-icon class="rate-th-hint"><InfoFilled /></el-icon
></el-tooltip>
</template>
<template #default="{ row }">
<el-link
v-if="canViewAssignLines && row[cohortCountKey] > 0"
type="primary"
:underline="false"
@click="openAssignDetail(row)"
>{{ row[cohortCountKey] }}</el-link
>
<span v-else>{{ row[cohortCountKey] ?? 0 }}</span>
</template>
</el-table-column>
<template v-for="slot in visitSlots" :key="slot">
<el-table-column
:prop="`visit${slot}_count`"
:label="`${slotLabel(slot)}单数`"
min-width="96"
align="right"
>
<template #header>
<span>{{ slotLabel(slot) }}单数</span>
<el-tooltip effect="dark" placement="top" :content="slotCountTip(slot)"
><el-icon class="rate-th-hint"><InfoFilled /></el-icon
></el-tooltip>
</template>
<template #default="{ row }">
<el-link
v-if="canViewOrderLines && row[`visit${slot}_count`] > 0"
type="primary"
:underline="false"
@click="openOrderDetail(slot, row)"
>{{ row[`visit${slot}_count`] }}</el-link
>
<span v-else>{{ row[`visit${slot}_count`] ?? 0 }}</span>
</template>
</el-table-column>
<el-table-column
:prop="`visit${slot}_rate`"
:label="`${slotLabel(slot)}接诊率`"
min-width="110"
align="right"
>
<template #header>
<span>{{ slotLabel(slot) }}接诊率</span>
<el-tooltip
effect="dark"
placement="top"
:content="`${slotLabel(slot)}单数 ÷ ${cohortLabel};分母为 0 显示「—」`"
><el-icon class="rate-th-hint"><InfoFilled /></el-icon
></el-tooltip>
</template>
<template #default="{ row }">
<div class="rate-cell">
<span class="rate-cell-main">{{
formatRate(row[`visit${slot}_rate`])
}}</span
><span class="rate-cell-sub">{{
denText(row, `visit${slot}`)
}}</span>
</div>
</template>
</el-table-column>
</template>
<el-table-column
prop="visit_all_count"
label="复诊合计单数"
min-width="110"
align="right"
>
<template #header>
<span>复诊合计单数</span>
<el-tooltip
effect="dark"
placement="top"
content="所选患者从对应指派后累计至查询当天的全部复诊订单数"
><el-icon class="rate-th-hint"><InfoFilled /></el-icon
></el-tooltip>
</template>
<template #default="{ row }">
<el-link
v-if="canViewOrderLines && row.visit_all_count > 0"
type="primary"
:underline="false"
@click="openOrderDetail(0, row)"
>{{ row.visit_all_count }}</el-link
>
<span v-else>{{ row.visit_all_count ?? 0 }}</span>
</template>
</el-table-column>
<el-table-column
prop="visit_all_rate"
label="复诊合计接诊率"
min-width="128"
align="right"
>
<template #header>
<span>复诊合计接诊率</span>
<el-tooltip
effect="dark"
placement="top"
:content="`复诊合计单数 ÷ ${cohortLabel};表示人均复诊成交单数,可超过 100%`"
><el-icon class="rate-th-hint"><InfoFilled /></el-icon
></el-tooltip>
</template>
<template #default="{ row }">
<div class="rate-cell">
<span class="rate-cell-main">{{ formatRate(row.visit_all_rate) }}</span
><span class="rate-cell-sub">{{ denText(row, 'visit_all') }}</span>
</div>
</template>
</el-table-column>
</el-table>
</el-card>
<el-dialog
v-model="detailVisible"
:title="detailTitle"
width="1080px"
top="6vh"
destroy-on-close
@close="invalidateDetail"
>
<p class="rate-detail-hint">{{ detailHint }}</p>
<el-alert
v-if="detailError"
class="mb-3"
type="error"
:title="detailError"
:closable="false"
/>
<el-table
v-loading="detailLoading"
:data="detailRows"
size="small"
border
stripe
max-height="60vh"
>
<template v-if="detailType === 'assign'">
<el-table-column prop="diagnosis_id" label="诊单ID" width="90" />
<el-table-column prop="patient_name" label="患者" min-width="100">
<template #default="{ row }">
<el-link
v-if="canViewPatientDetail && row.diagnosis_id"
type="primary"
:underline="false"
@click="openPatientDetail(row.diagnosis_id)"
>{{ row.patient_name || `诊单#${row.diagnosis_id}` }}</el-link
>
<span v-else>{{ row.patient_name || '—' }}</span>
</template>
</el-table-column>
<el-table-column prop="patient_phone" label="联系电话" min-width="120"
><template #default="{ row }">{{
row.patient_phone || '—'
}}</template></el-table-column
>
<el-table-column
prop="assistant_names"
:label="isInherit ? '继承医助' : '被指派医助'"
min-width="140"
show-overflow-tooltip
/>
<el-table-column
prop="assign_count"
:label="isInherit ? '范围内继承次数' : '范围内指派次数'"
width="120"
align="right"
/>
<el-table-column
prop="first_assign_time_text"
:label="isInherit ? '首次继承时间' : '首次指派时间'"
min-width="160"
/>
<el-table-column
prop="last_assign_time_text"
:label="isInherit ? '最近继承时间' : '最近指派时间'"
min-width="160"
/>
</template>
<template v-else>
<el-table-column
prop="order_no"
label="订单号"
min-width="180"
show-overflow-tooltip
>
<template #default="{ row }">
<el-link
v-if="canViewOrderDetail && row.order_id"
type="primary"
:underline="false"
@click="openOrderInfo(row.order_id)"
>{{ row.order_no || `#${row.order_id}` }}</el-link
>
<span v-else>{{ row.order_no || `#${row.order_id}` }}</span>
</template>
</el-table-column>
<el-table-column
v-if="detailSlot === 0 || isInherit"
prop="visit_slot"
:label="isInherit ? '继承后诊次' : '诊次'"
width="100"
align="center"
><template #default="{ row }">{{
slotLabel(Number(row.visit_slot))
}}</template></el-table-column
>
<el-table-column
v-if="isInherit"
prop="global_visit_slot"
label="全局诊次(参考)"
width="130"
align="center"
><template #default="{ row }">{{
row.global_visit_slot ? slotLabel(Number(row.global_visit_slot)) : '—'
}}</template></el-table-column
>
<el-table-column prop="diagnosis_id" label="诊单ID" width="90" />
<el-table-column prop="patient_name" label="患者" min-width="100">
<template #default="{ row }">
<el-link
v-if="canViewPatientDetail && row.diagnosis_id"
type="primary"
:underline="false"
@click="openPatientDetail(row.diagnosis_id)"
>{{ row.patient_name || `诊单#${row.diagnosis_id}` }}</el-link
>
<span v-else>{{ row.patient_name || '—' }}</span>
</template>
</el-table-column>
<el-table-column prop="patient_phone" label="联系电话" min-width="120"
><template #default="{ row }">{{
row.patient_phone || '—'
}}</template></el-table-column
>
<el-table-column prop="amount" label="金额" width="100" align="right"
><template #default="{ row }">¥ {{ row.amount }}</template></el-table-column
>
<el-table-column
prop="cohort_assign_time_text"
:label="isInherit ? '继承时间' : '指派时间'"
min-width="160"
/>
<el-table-column prop="create_time_text" label="下单时间" min-width="160" />
<el-table-column prop="assistant_name" label="持有医助" min-width="100" />
<el-table-column prop="creator_name" label="订单创建人" min-width="100" />
</template>
</el-table>
<div class="rate-detail-footer">共 {{ detailCount }} 条</div>
</el-dialog>
<order-detail-drawer ref="orderDetailRef" readonly append-to-body />
<diagnosis-edit-popup ref="diagnosisEditRef" />
</div>
</template>
<script setup lang="ts">
import { computed, defineAsyncComponent, onBeforeUnmount, onMounted, ref } from 'vue'
import { InfoFilled } from '@element-plus/icons-vue'
import {
revisitCohortAssignLines,
revisitCohortDeptOptions,
revisitCohortOverview,
revisitCohortVisitOrderLines,
type RevisitRateCohortType,
type RevisitRateDetailQuery,
type RevisitRateQuery
} from '@/api/stats'
import { hasPermission } from '@/utils/perm'
const props = defineProps<{ cohortType: RevisitRateCohortType }>()
const OrderDetailDrawer = defineAsyncComponent(
() => import('@/views/consumer/prescription/components/PrescriptionOrderDetailDrawer.vue')
)
const DiagnosisEditPopup = defineAsyncComponent(() => import('@/views/tcm/diagnosis/edit.vue'))
interface MetricPack extends Record<string, any> {
assigned_count: number
inherit_count: number
assigned_total_count: number
visit_all_count: number
visit_all_den: number
visit_all_rate: number | null
}
interface StatsRow extends MetricPack {
row_key: string
is_dept: 0 | 1
dept_id: number
dept_name: string
assistant_id?: number
assistant_name?: string
assistant_count?: number
children?: StatsRow[]
}
interface DeptOption {
id: number
pid: number
name: string
}
interface DeptTreeNode extends DeptOption {
children?: DeptTreeNode[]
}
interface AssistantOption {
id: number
name: string
dept_id: number
}
interface SummaryCard {
key: string
label: string
value: string
sub: string
clickable: boolean
onClick: () => void
}
const isInherit = computed(() => props.cohortType === 'inherit')
const cohortLabel = computed(() => (isInherit.value ? '继承数' : '新指派数'))
const cohortCountKey = computed(() => (isInherit.value ? 'inherit_count' : 'assigned_count'))
const dateLabel = computed(() => (isInherit.value ? '继承日期' : '指派日期'))
const reportTitle = computed(() => (isInherit.value ? '继承复诊接诊率' : '按指派周期复诊率'))
const reportHint = computed(() =>
isInherit.value
? '按继承日期范围选择患者,订单累计至查询当天。继承后第 1 笔有效订单算二诊,第 2 笔算三诊;忽略继承前全局诊次及偏移,新指派患者另页统计。'
: '按新指派日期范围选择患者,订单累计至查询当天,跨月继续累计。继承患者在独立的「继承复诊接诊率」页面统计。'
)
const permissionPrefix = computed(() =>
isInherit.value ? 'stats.revisitInheritRate' : 'stats.revisitAssignRate'
)
const canViewAssignLines = computed(() => hasPermission([`${permissionPrefix.value}/assignLines`]))
const canViewOrderLines = computed(() =>
hasPermission([`${permissionPrefix.value}/visitOrderLines`])
)
const canViewOrderDetail = hasPermission(['tcm.prescriptionOrder/detail'])
const canViewPatientDetail = hasPermission(['tcm.diagnosis/detail'])
const formatDate = (date: Date) =>
`${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
const defaultDateRange = (): [string, string] => {
const now = new Date()
return [formatDate(new Date(now.getFullYear(), now.getMonth(), 1)), formatDate(now)]
}
const dateRange = ref<[string, string]>(defaultDateRange())
const deptId = ref<number | undefined>()
const assistantId = ref<number | undefined>()
const loading = ref(false)
const queryError = ref('')
const rows = ref<StatsRow[]>([])
const total = ref<MetricPack | null>(null)
const visitSlots = ref<number[]>([2, 3, 4])
const observedUntil = ref('')
/** 下钻只复用已展示报表的查询快照,避免读取正在编辑的筛选。 */
const loadedQuery = ref<RevisitRateQuery | null>(null)
let overviewRequestId = 0
let disposed = false
const rangeText = computed(() =>
loadedQuery.value
? `${loadedQuery.value.start_date} 至 ${loadedQuery.value.end_date}`
: `${dateRange.value[0]} 至 ${dateRange.value[1]}`
)
const currentQuery = (): RevisitRateQuery => ({
start_date: dateRange.value[0],
end_date: dateRange.value[1],
dept_ids: deptId.value ? String(deptId.value) : '',
assistant_id: assistantId.value || undefined
})
const deptOptions = ref<DeptOption[]>([])
const allAssistants = ref<AssistantOption[]>([])
const optionsLoading = ref(false)
const optionsError = ref('')
const deptTreeProps = { value: 'id', label: 'name', children: 'children' }
const deptTreeOptions = computed<DeptTreeNode[]>(() => {
const nodes = new Map<number, DeptTreeNode>()
deptOptions.value.forEach((item) => nodes.set(item.id, { ...item, children: [] }))
const roots: DeptTreeNode[] = []
nodes.forEach((node) => {
const parent = nodes.get(node.pid)
if (parent && parent !== node) parent.children!.push(node)
else roots.push(node)
})
const stripEmptyChildren = (node: DeptTreeNode) => {
if (node.children?.length) node.children.forEach(stripEmptyChildren)
else delete node.children
}
roots.forEach(stripEmptyChildren)
return roots
})
const selectedDeptIds = computed(() => {
if (!deptId.value) return null
const ids = new Set<number>([Number(deptId.value)])
let expanded = true
while (expanded) {
expanded = false
deptOptions.value.forEach((item) => {
if (ids.has(item.pid) && !ids.has(item.id)) {
ids.add(item.id)
expanded = true
}
})
}
return ids
})
const assistantOptions = computed(() =>
allAssistants.value.filter(
(item) => !selectedDeptIds.value || selectedDeptIds.value.has(item.dept_id)
)
)
const handleDeptChange = () => {
if (assistantId.value && !assistantOptions.value.some((item) => item.id === assistantId.value))
assistantId.value = undefined
void loadData()
}
const loadDeptOptions = async () => {
optionsLoading.value = true
optionsError.value = ''
try {
const res = await revisitCohortDeptOptions(props.cohortType)
if (disposed) return
deptOptions.value = (res?.rows ?? []).map((item: DeptOption) => ({
...item,
id: Number(item.id),
pid: Number(item.pid)
}))
allAssistants.value = (res?.assistants ?? []).map((item: AssistantOption) => ({
...item,
id: Number(item.id),
dept_id: Number(item.dept_id)
}))
} catch {
if (!disposed) optionsError.value = '部门及医助选项加载失败,请刷新页面重试。'
} finally {
if (!disposed) optionsLoading.value = false
}
}
const cnDigits = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十']
const slotLabel = (slot: number) => {
if (slot === 0) return '复诊合计'
if (slot >= 1 && slot <= 10) return `${cnDigits[slot]}诊`
if (slot > 10 && slot < 20) return `十${cnDigits[slot - 10]}诊`
return `${slot}诊`
}
const slotCountTip = (slot: number) =>
isInherit.value
? `所选继承患者在继承后的第 ${slot - 1} 笔有效订单数,累计至查询当天;不使用继承前全局诊次和偏移`
: `所选新指派患者的${slotLabel(slot)}有效订单数,从对应指派后累计至查询当天`
const formatRate = (rate: number | null | undefined) =>
rate === null || rate === undefined ? '—' : `${rate}%`
const denText = (row: Record<string, any>, prefix: string) =>
`${Number(row[`${prefix}_count`] ?? 0)} / ${row[`${prefix}_den`] ?? '—'}`
const summaryCards = computed<SummaryCard[]>(() => {
const t = total.value
const cards: SummaryCard[] = [
{
key: 'cohort',
label: cohortLabel.value,
value: t ? String(t[cohortCountKey.value] ?? 0) : '—',
sub: `按${dateLabel.value}范围选择患者`,
clickable: !!(canViewAssignLines.value && t && t[cohortCountKey.value] > 0),
onClick: () => void openAssignDetail(null)
}
]
visitSlots.value.forEach((slot) =>
cards.push({
key: `visit${slot}`,
label: `${slotLabel(slot)}接诊率`,
value: t ? formatRate(t[`visit${slot}_rate`]) : '—',
sub: t
? `${slotLabel(slot)}下单 ${t[`visit${slot}_count`] ?? 0} 单 / 分母 ${t[`visit${slot}_den`] ?? '—'}`
: '',
clickable: !!(canViewOrderLines.value && t && t[`visit${slot}_count`] > 0),
onClick: () => void openOrderDetail(slot, null)
})
)
cards.push({
key: 'visit_all',
label: '复诊合计接诊率',
value: t ? formatRate(t.visit_all_rate) : '—',
sub: t ? `复诊下单 ${t.visit_all_count ?? 0} 单 / 分母 ${t.visit_all_den ?? '—'}` : '',
clickable: !!(canViewOrderLines.value && t && t.visit_all_count > 0),
onClick: () => void openOrderDetail(0, null)
})
return cards
})
/** 服务端已按诊单去重,合计不能由各医助行相加。 */
const getSummaries = ({ columns }: { columns: Array<{ property?: string }> }) =>
columns.map((column, index) => {
if (index === 0) return '合计'
const t = total.value
if (!t) return ''
const prop = column.property || ''
if (prop === cohortCountKey.value) return String(t[prop] ?? 0)
const match = /^visit(\d+|_all)_(count|rate)$/.exec(prop)
if (!match) return ''
return match[2] === 'rate'
? `${formatRate(t[prop])}(${denText(t, `visit${match[1]}`)})`
: String(t[prop] ?? 0)
})
const loadData = async () => {
const requestId = ++overviewRequestId
invalidateDetail()
detailVisible.value = false
loadedQuery.value = null
rows.value = []
total.value = null
observedUntil.value = ''
queryError.value = ''
loading.value = true
const query = currentQuery()
try {
const res = await revisitCohortOverview(query, props.cohortType)
if (disposed || requestId !== overviewRequestId) return
rows.value = res?.rows ?? []
total.value = res?.total ?? null
observedUntil.value = res?.observed_until ?? ''
const slots: number[] = Array.isArray(res?.slots) ? res.slots.map(Number) : []
visitSlots.value = slots.length
? [
...new Set(
slots.filter((slot) => Number.isInteger(slot) && slot >= 2 && slot <= 50)
)
].sort((a, b) => a - b)
: [2, 3, 4]
loadedQuery.value = { ...query }
} catch {
if (!disposed && requestId === overviewRequestId)
queryError.value = '报表加载失败,请重新查询。'
} finally {
if (!disposed && requestId === overviewRequestId) loading.value = false
}
}
const detailVisible = ref(false)
const detailType = ref<'assign' | 'orders'>('assign')
const detailTitle = ref('')
const detailHint = ref('')
const detailLoading = ref(false)
const detailError = ref('')
const detailRows = ref<any[]>([])
const detailCount = ref(0)
const detailSlot = ref(2)
let detailRequestId = 0
const invalidateDetail = () => {
++detailRequestId
detailLoading.value = false
detailRows.value = []
detailCount.value = 0
detailError.value = ''
}
const rowScope = (
row: StatsRow | null
): Pick<RevisitRateDetailQuery, 'scope_assistant_id' | 'dept_id'> & { label: string } => {
if (!row) return { label: '合计' }
return row.is_dept
? { dept_id: row.dept_id, label: row.dept_name }
: { scope_assistant_id: row.assistant_id, label: row.assistant_name || '' }
}
const openDetail = async (type: 'assign' | 'orders', slot: number, row: StatsRow | null) => {
if (loading.value || !loadedQuery.value) return
if (type === 'assign' ? !canViewAssignLines.value : !canViewOrderLines.value) return
const query = { ...loadedQuery.value }
const { label, ...scope } = rowScope(row)
const requestId = ++detailRequestId
detailType.value = type
detailSlot.value = slot
detailTitle.value = `${label} · ${type === 'assign' ? `${cohortLabel.value}明细` : `${slotLabel(slot)}订单明细`}(${query.start_date} 至 ${query.end_date})`
detailHint.value = `${dateLabel.value}:${query.start_date} 至 ${query.end_date};订单统计截至:${observedUntil.value || '查询当天'}${isInherit.value && type === 'orders' ? '。继承后首笔有效订单算二诊,全局诊次仅供参考。' : '。'}`
detailRows.value = []
detailCount.value = 0
detailError.value = ''
detailLoading.value = true
detailVisible.value = true
try {
// assistant_id 保留顶层筛选,scope_assistant_id 独立约束医助行。
const params: RevisitRateDetailQuery = { ...query, ...scope }
const res =
type === 'assign'
? await revisitCohortAssignLines(params, props.cohortType)
: await revisitCohortVisitOrderLines({ ...params, slot }, props.cohortType)
if (disposed || requestId !== detailRequestId || !detailVisible.value) return
detailRows.value = res?.rows ?? []
detailCount.value = Number(res?.count ?? detailRows.value.length)
} catch {
if (!disposed && requestId === detailRequestId)
detailError.value = '明细加载失败,请关闭后重试。'
} finally {
if (!disposed && requestId === detailRequestId) detailLoading.value = false
}
}
const openAssignDetail = (row: StatsRow | null) => openDetail('assign', 0, row)
const openOrderDetail = (slot: number, row: StatsRow | null) => openDetail('orders', slot, row)
const orderDetailRef = ref<{ open: (id: number) => void } | null>(null)
const openOrderInfo = (orderId: number) => {
if (canViewOrderDetail && orderId) orderDetailRef.value?.open(orderId)
}
const diagnosisEditRef = ref<{ openViewOnly: (id: number) => void } | null>(null)
const openPatientDetail = (diagnosisId: number) => {
if (canViewPatientDetail && diagnosisId) diagnosisEditRef.value?.openViewOnly(diagnosisId)
}
const handleReset = () => {
dateRange.value = defaultDateRange()
deptId.value = undefined
assistantId.value = undefined
void loadData()
}
onMounted(() => {
void loadDeptOptions()
void loadData()
})
onBeforeUnmount(() => {
disposed = true
++overviewRequestId
++detailRequestId
})
</script>
<style lang="scss" scoped>
.revisit-rate-page {
.rate-filter-form {
display: flex;
flex-wrap: wrap;
gap: 12px 0;
:deep(.el-form-item) {
margin-bottom: 0;
}
}
.rate-caliber-trigger {
display: inline-flex;
align-items: center;
gap: 4px;
color: var(--el-text-color-secondary);
font-size: 13px;
cursor: help;
}
.rate-kpi-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 12px;
margin-top: 16px;
}
.rate-kpi-card {
background: var(--el-bg-color);
border-radius: 8px;
padding: 16px 20px;
&.is-clickable {
cursor: pointer;
transition: box-shadow 0.15s ease;
&:hover {
box-shadow: var(--el-box-shadow-light);
}
}
.rate-kpi-label {
color: var(--el-text-color-secondary);
font-size: 13px;
}
.rate-kpi-value {
margin-top: 6px;
font-size: 26px;
font-weight: 600;
color: var(--el-text-color-primary);
}
.rate-kpi-sub {
margin-top: 2px;
font-size: 12px;
color: var(--el-text-color-secondary);
}
}
.rate-card-header {
display: flex;
flex-wrap: wrap;
align-items: baseline;
gap: 10px;
}
.rate-card-hint {
font-size: 12px;
color: var(--el-text-color-secondary);
}
.rate-dept-cell {
font-weight: 600;
.rate-dept-count {
margin-left: 6px;
font-weight: 400;
font-size: 12px;
color: var(--el-text-color-secondary);
}
}
.rate-th-hint {
margin-left: 2px;
vertical-align: -2px;
color: var(--el-text-color-secondary);
cursor: help;
}
.rate-cell {
display: flex;
flex-direction: column;
align-items: flex-end;
line-height: 1.3;
.rate-cell-main {
font-weight: 500;
}
.rate-cell-sub {
font-size: 11px;
color: var(--el-text-color-placeholder);
}
}
}
.rate-detail-hint {
margin: 0 0 12px;
font-size: 12px;
color: var(--el-text-color-secondary);
}
.rate-detail-footer {
margin-top: 10px;
text-align: right;
font-size: 12px;
color: var(--el-text-color-secondary);
}
.rate-caliber {
font-size: 13px;
line-height: 1.7;
color: var(--el-text-color-regular);
p + p {
margin-top: 6px;
}
}
</style>
@@ -1,7 +0,0 @@
<template>
<cohort-report cohort-type="new" />
</template>
<script setup lang="ts" name="revisitAssignRateStatsPage">
import CohortReport from './components/CohortReport.vue'
</script>
-863
View File
@@ -1,863 +0,0 @@
<template>
<div class="revisit-due-page">
<el-card class="!border-none" shadow="never">
<el-form :inline="true" class="due-filter-form">
<el-form-item label="医助">
<el-select
v-model="queryParams.assistant_id"
clearable
filterable
placeholder="全部"
class="w-[160px]"
@change="doSearch"
>
<el-option
v-for="item in assistantOptions"
:key="item.id"
:label="item.name"
:value="Number(item.id)"
/>
</el-select>
</el-form-item>
<el-form-item label="部门">
<el-tree-select
v-model="queryParams.dept_id"
:data="deptTreeOptions"
placeholder="全部(二中心)"
clearable
filterable
check-strictly
node-key="id"
:default-expand-all="true"
:props="deptTreeProps"
class="w-[200px]"
@change="doSearch"
/>
</el-form-item>
<el-form-item label="状态">
<el-select
v-model="queryParams.state"
clearable
placeholder="全部"
class="w-[170px]"
@change="doSearch"
>
<el-option
v-for="opt in stateOptions"
:key="opt.value"
:label="opt.label"
:value="opt.value"
/>
</el-select>
</el-form-item>
<el-form-item label="开药天数">
<el-select
v-model="queryParams.days_bucket"
clearable
placeholder="全部"
class="w-[120px]"
@change="doSearch"
>
<el-option
v-for="opt in REVISIT_DAYS_BUCKET_OPTIONS"
:key="opt.value"
:label="opt.label"
:value="opt.value"
/>
</el-select>
</el-form-item>
<el-form-item label="延迟次数 ≥">
<el-input-number
v-model="minSnooze"
:min="0"
:max="999"
:step="1"
step-strictly
controls-position="right"
placeholder="不限"
class="!w-[120px]"
@change="onMinSnoozeChange"
/>
</el-form-item>
<el-form-item label="患者">
<el-input
v-model="queryParams.keyword"
placeholder="患者姓名"
clearable
class="w-[160px]"
@keyup.enter="doSearch"
@clear="doSearch"
/>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="doSearch">查询</el-button>
<el-button @click="handleReset">重置</el-button>
<export-data
class="ml-2.5"
:fetch-fun="revisitDueLists"
:params="queryParams"
:page-size="pager.size"
export-hint="导出范围与当前筛选一致(医助 / 部门 / 状态 / 开药天数 / 延迟次数 / 患者)"
/>
</el-form-item>
</el-form>
<div class="due-hint">
每位患者(诊单)一行,取最新有效业务订单为本轮周期:预计复诊日 = 用药起算日(签收 → 发货 → 下单)+ 开药天数;
到期仍无有效挂号 / 过号未面诊的行标红,持有医助登录后台会收到右下角弹窗。
「延迟次数」为医助在弹窗上点「延迟」的累计次数(越多说明越未跟进),「已联系」为填写患者承诺复诊日的次数,
「人工关闭」由医助填原因关闭、在此标记供主管复核。数据范围按角色数据权限收窄;状态按今天实时推导。
</div>
</el-card>
<el-card class="!border-none mt-3" shadow="never">
<el-table
:data="pager.lists"
v-loading="pager.loading"
size="default"
stripe
row-key="id"
:row-class-name="rowClassName"
>
<el-table-column label="患者" min-width="120" fixed="left">
<template #default="{ row }">
<div class="cell-main">{{ row.patient_name || '—' }}</div>
<div class="cell-sub">诊单 #{{ row.diagnosis_id }}</div>
</template>
</el-table-column>
<el-table-column label="医助" min-width="100">
<template #default="{ row }">{{ assistantText(row) }}</template>
</el-table-column>
<el-table-column label="部门" min-width="110" show-overflow-tooltip>
<template #default="{ row }">{{ row.dept_name || '—' }}</template>
</el-table-column>
<el-table-column label="诊次" width="110" align="center">
<template #header>
<span>诊次</span>
<el-tooltip
placement="top"
effect="dark"
content="患者当前已完成诊次 = 有效业务订单数 + 诊单诊次偏移,与复诊接诊率同口径;下一行为待复诊诊次"
>
<el-icon class="col-hint"><InfoFilled /></el-icon>
</el-tooltip>
</template>
<template #default="{ row }">
<div class="cell-main">{{ slotText(row) }}</div>
<div v-if="Number(row.next_slot) > 0" class="cell-sub">
待复诊第 {{ row.next_slot }} 诊
</div>
</template>
</el-table-column>
<el-table-column label="开药天数" width="110" align="center">
<template #default="{ row }">
<template v-if="Number(row.medication_days) > 0">
<span>{{ row.medication_days }} 天</span>
<el-tag
v-if="Number(row.rule_days) > 0"
size="small"
type="info"
effect="plain"
class="ml-1"
>
{{ row.rule_days }} 档
</el-tag>
</template>
<span v-else class="text-missing">缺开药天数</span>
</template>
</el-table-column>
<el-table-column label="预计复诊" width="110">
<template #default="{ row }">
<div class="cell-main">{{ row.due_date || '—' }}</div>
<div v-if="row.anchor_date" class="cell-sub">
起算 {{ formatRevisitMonthDay(row.anchor_date) }}
</div>
</template>
</el-table-column>
<el-table-column label="超期天数" width="100" align="center">
<template #default="{ row }">
<span :class="['overdue-cell', overdueCell(row).cls]">
{{ overdueCell(row).text }}
</span>
</template>
</el-table-column>
<el-table-column label="状态" min-width="150">
<template #default="{ row }">
<el-tag
:type="revisitStateTagType(row.state)"
:effect="revisitStateTagEffect(row.state)"
size="small"
:class="revisitStateChipClass(dueOf(row))"
>
{{ chipText(row) }}
</el-tag>
<el-tag
v-if="Number(row.closed_state) === 4"
size="small"
type="info"
effect="plain"
class="ml-1"
>
人工关闭
</el-tag>
</template>
</el-table-column>
<el-table-column label="延迟次数" width="100" align="center">
<template #header>
<span>延迟次数</span>
<el-tooltip
placement="top"
effect="dark"
content="医助在到期弹窗上点「延迟」的累计次数;1~2 次 L1、3~4 次 L2、≥5 次 L3(居中强制模态)。换医助后清零"
>
<el-icon class="col-hint"><InfoFilled /></el-icon>
</el-tooltip>
</template>
<template #default="{ row }">
<span :class="['snooze-cell', snoozeClass(row)]">
{{ Number(row.snooze_count ?? 0) }}
</span>
<div v-if="Number(row.escalation_level) > 0" class="cell-sub">
等级 L{{ row.escalation_level }}
</div>
</template>
</el-table-column>
<el-table-column label="已联系" width="80" align="center">
<template #default="{ row }">{{ Number(row.contact_count ?? 0) }}</template>
</el-table-column>
<el-table-column label="承诺日" width="100">
<template #default="{ row }">{{ row.promised_date || '—' }}</template>
</el-table-column>
<el-table-column label="过号" width="70" align="center">
<template #default="{ row }">{{ Number(row.missed_count ?? 0) }}</template>
</el-table-column>
<el-table-column label="关闭原因" min-width="170" show-overflow-tooltip>
<template #default="{ row }">
<template v-if="Number(row.closed_state) === 4">
<span>{{ handleReasonText(row.handle_reason) }}</span>
<span v-if="row.handle_remark" class="cell-sub">
:{{ row.handle_remark }}
</span>
</template>
<span v-else-if="Number(row.closed_state) > 0" class="cell-sub">
{{ row.closed_state_text || '—' }}
</span>
<span v-else>—</span>
</template>
</el-table-column>
<el-table-column label="操作" width="130" fixed="right" align="center">
<template #default="{ row }">
<el-button
v-perms="['tcm.revisitDue/logs']"
link
type="primary"
@click="openLogs(row)"
>
流水
</el-button>
<el-button link type="primary" @click="goDiagnosis(row)">去诊单</el-button>
</template>
</el-table-column>
</el-table>
<div class="flex justify-end mt-4">
<pagination v-model="pager" @change="getLists" />
</div>
</el-card>
<el-drawer
v-model="logVisible"
:title="logTitle"
direction="rtl"
size="540px"
destroy-on-close
>
<div v-loading="logLoading" class="log-drawer-body">
<div v-if="logRow" class="log-summary">
<div class="log-summary-row">
<span>医助:{{ assistantText(logRow) }}</span>
<span>{{ slotText(logRow) }}</span>
<span v-if="logRow.due_date">预计复诊 {{ logRow.due_date }}</span>
</div>
<div class="log-summary-row">
<el-tag
:type="revisitStateTagType(logRow.state)"
:effect="revisitStateTagEffect(logRow.state)"
size="small"
:class="revisitStateChipClass(dueOf(logRow))"
>
{{ chipText(logRow) }}
</el-tag>
<span class="cell-sub">{{ followCountText(logRow) }}</span>
</div>
<div v-if="hasShownMeta(logRow)" class="log-summary-row cell-sub">
<span v-if="logRow.first_shown_at_text">
首次弹出 {{ logRow.first_shown_at_text }}
</span>
<span v-if="logRow.last_snoozed_at_text">
最近延迟 {{ logRow.last_snoozed_at_text }}
</span>
<span v-if="logRow.computed_at_text">
重算于 {{ logRow.computed_at_text }}
</span>
</div>
</div>
<el-timeline v-if="logRows.length" class="mt-3">
<el-timeline-item
v-for="item in logRows"
:key="item.id"
:timestamp="item.create_time_text"
placement="top"
:type="eventTimelineType(item.event)"
:hollow="!isUserEvent(item.event)"
>
<div class="log-event">
<span class="log-event-title">
{{ item.event_text || eventLabel(item.event) }}
</span>
<span class="log-event-operator">{{ operatorText(item) }}</span>
</div>
<div class="log-event-meta">
<span>延迟 {{ Number(item.snooze_count_after ?? 0) }} 次</span>
<span>等级 L{{ Number(item.level_after ?? 0) }}</span>
<span>{{ logOverdueText(item.overdue_days) }}</span>
</div>
<div v-if="payloadEntries(item).length" class="log-event-payload">
<span
v-for="p in payloadEntries(item)"
:key="p.key"
class="log-payload-chip"
>
{{ p.label }}:{{ p.value }}
</span>
</div>
</el-timeline-item>
</el-timeline>
<el-empty v-else-if="!logLoading" description="暂无流水" :image-size="80" />
</div>
</el-drawer>
</div>
</template>
<script setup lang="ts" name="statsRevisitDue">
import { InfoFilled } from '@element-plus/icons-vue'
import { computed, onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import {
revisitDueLists,
revisitDueLogs,
type RevisitDueListRow,
type RevisitDueListsParams,
type RevisitDueLogRow
} from '@/api/revisitDue'
import { revisitRateDeptOptions } from '@/api/stats'
import { getAssistants } from '@/api/tcm'
import { usePaging } from '@/hooks/usePaging'
import {
REVISIT_DAYS_BUCKET_OPTIONS,
REVISIT_STATE_FILTER_OPTIONS,
formatRevisitMonthDay,
normalizeRevisitDue,
revisitRowClassName,
revisitStateChipClass,
revisitStateChipText,
revisitStateTagEffect,
revisitStateTagType,
type RevisitDue
} from '@/utils/revisitDue'
interface DeptTreeNode {
id: number
name: string
pid: number
children?: DeptTreeNode[]
}
const router = useRouter()
/** 状态筛选:诊单列表的 7 个状态 + 主管视图专有「人工关闭」 */
const stateOptions = [...REVISIT_STATE_FILTER_OPTIONS, { label: '人工关闭', value: 'closed' }]
const assistantOptions = ref<Array<{ id: number; name: string }>>([])
const deptTreeOptions = ref<DeptTreeNode[]>([])
const deptTreeProps = { value: 'id', label: 'name', children: 'children' }
const queryParams = reactive<RevisitDueListsParams>({
assistant_id: '',
dept_id: '',
state: '',
days_bucket: '',
min_snooze: '',
keyword: ''
})
/** el-input-number 清空时为 null/undefined,单独持有后再写回 queryParams 的 '' */
const minSnooze = ref<number | undefined>(undefined)
const { pager, getLists, resetPage } = usePaging({
fetchFun: revisitDueLists,
params: queryParams
})
const doSearch = () => resetPage()
const onMinSnoozeChange = (val: number | undefined | null) => {
queryParams.min_snooze = val === null || val === undefined ? '' : Number(val)
doSearch()
}
const handleReset = () => {
queryParams.assistant_id = ''
queryParams.dept_id = ''
queryParams.state = ''
queryParams.days_bucket = ''
queryParams.min_snooze = ''
queryParams.keyword = ''
minSnooze.value = undefined
doSearch()
}
// ── 单元格 ──────────────────────────────────────────
/** 列表行 → 复诊节点对象(复用 utils/revisitDue 的 chip 映射;缺失字段按默认值补齐) */
const dueOf = (row: RevisitDueListRow | Record<string, any>): RevisitDue | null =>
normalizeRevisitDue(row)
const rowClassName = ({ row }: { row: RevisitDueListRow }) => revisitRowClassName(dueOf(row))
const assistantText = (row: RevisitDueListRow) =>
row.assistant_name || (Number(row.assistant_id) > 0 ? `#${row.assistant_id}` : '—')
const slotText = (row: RevisitDueListRow) => {
const slot = Number(row.current_slot ?? 0)
return slot > 0 ? `第 ${slot} 诊` : '未成交'
}
const chipText = (row: RevisitDueListRow) =>
revisitStateChipText(dueOf(row)) || row.state_text || '—'
/** 抽屉摘要:「延迟 N 次 · 已联系 N 次 · 过号 N 次」 */
const followCountText = (row: RevisitDueListRow) => {
const snooze = Number(row.snooze_count ?? 0)
const contact = Number(row.contact_count ?? 0)
const missed = Number(row.missed_count ?? 0)
return `延迟 ${snooze} 次 · 已联系 ${contact} 次 · 过号 ${missed} 次`
}
const hasShownMeta = (row: RevisitDueListRow) =>
!!(row.first_shown_at_text || row.last_snoozed_at_text || row.computed_at_text)
const toNullableNumber = (v: unknown): number | null => {
if (v === null || v === undefined || v === '') return null
const n = Number(v)
return Number.isFinite(n) ? n : null
}
/** 超期天数列:到期/过号红字(深红 = severe),其它状态显示剩余天数或历史超期 */
const overdueCell = (row: RevisitDueListRow): { text: string; cls: string } => {
const od = toNullableNumber(row.overdue_days)
const dl = toNullableNumber(row.days_left)
const isDue = row.state === 'overdue' || row.state === 'missed'
if (isDue && od !== null && od >= 0) {
return {
text: od === 0 ? '今日到期' : `${od} 天`,
cls: Number(row.severe) === 1 ? 'is-severe' : 'is-overdue'
}
}
if (od !== null && od > 0) {
return { text: `${od} 天`, cls: 'is-muted' }
}
if (dl !== null && dl >= 0) {
return { text: `剩 ${dl} 天`, cls: 'is-muted' }
}
return { text: '—', cls: '' }
}
const snoozeClass = (row: RevisitDueListRow) => {
const level = Number(row.escalation_level ?? 0)
if (level >= 3) return 'is-level-3'
if (level === 2) return 'is-level-2'
if (level === 1) return 'is-level-1'
return ''
}
const handleReasonText = (reason: string | null | undefined) => {
const key = String(reason ?? '').trim()
if (key === 'lost') return '患者流失'
if (key === 'other') return '其它'
return key || '人工关闭'
}
// ── 流水抽屉 ──────────────────────────────────────────
const logVisible = ref(false)
const logLoading = ref(false)
const logRow = ref<RevisitDueListRow | null>(null)
const logRows = ref<RevisitDueLogRow[]>([])
const logTitle = computed(() =>
logRow.value ? `${logRow.value.patient_name || '患者'} · 复诊到期流水` : '复诊到期流水'
)
const EVENT_LABEL: Record<number, string> = {
1: '延迟',
2: '已联系',
3: '人工关闭',
4: '自动关闭 · 已挂号',
5: '自动关闭 · 已面诊',
6: '周期重置(新订单)',
7: '重新打开(挂号取消 / 过号)',
8: '企微推送',
9: '医助变更',
10: '形态升级',
11: '首次弹出'
}
const eventLabel = (event: number) => EVENT_LABEL[Number(event)] ?? `事件 ${event}`
/** 1 延迟 / 2 已联系 / 3 人工关闭 由医助操作,实心节点;其余系统事件空心 */
const isUserEvent = (event: number) => [1, 2, 3].includes(Number(event))
type TimelineType = 'primary' | 'success' | 'warning' | 'danger' | 'info'
const eventTimelineType = (event: number): TimelineType => {
switch (Number(event)) {
case 1:
return 'warning'
case 2:
case 6:
return 'primary'
case 4:
case 5:
return 'success'
case 7:
case 10:
return 'danger'
default:
return 'info'
}
}
const operatorText = (item: RevisitDueLogRow) => {
if (item.operator_name) return item.operator_name
return Number(item.operator_id) > 0 ? `#${item.operator_id}` : '系统'
}
const logOverdueText = (days: number | null | undefined) => {
const n = toNullableNumber(days)
if (n === null) return ''
if (n > 0) return `超期 ${n} 天`
if (n === 0) return '到期当天'
return `未到期(剩 ${-n} 天)`
}
const PAYLOAD_LABEL: Record<string, string> = {
next_remind_at: '下次提醒',
next_remind_at_text: '下次提醒',
promised_date: '承诺日',
appointment_id: '挂号单',
appointment_date: '预约日',
order_id: '订单',
source_order_id: '周期订单',
remark: '备注',
reason: '原因',
from_assistant: '原医助',
from_assistant_id: '原医助',
to_assistant: '新医助',
to_assistant_id: '新医助',
interval: '间隔(秒)',
level: '等级',
channel: '渠道',
message: '说明'
}
const formatPayloadValue = (key: string, value: unknown): string => {
if (value === null || value === undefined || value === '') return ''
if (typeof value === 'object') return JSON.stringify(value)
// 秒级时间戳(next_remind_at 等)转本地时间
if (/_at$/.test(key) && typeof value === 'number' && value > 1e9) {
const d = new Date(value * 1000)
const pad = (n: number) => String(n).padStart(2, '0')
const date = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
return `${date} ${pad(d.getHours())}:${pad(d.getMinutes())}`
}
return String(value)
}
interface PayloadEntry {
key: string
label: string
value: string
}
/** payload_arr → [{key,label,value}],有 *_text 版本时隐藏对应原始时间戳 */
const payloadEntries = (item: RevisitDueLogRow): PayloadEntry[] => {
const payload = item.payload_arr
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return []
const out: PayloadEntry[] = []
for (const [key, raw] of Object.entries(payload)) {
if (`${key}_text` in payload) continue
const value = formatPayloadValue(key, raw)
if (value === '') continue
out.push({ key, label: PAYLOAD_LABEL[key] ?? key, value })
}
return out
}
const openLogs = async (row: RevisitDueListRow) => {
logRow.value = row
logVisible.value = true
logLoading.value = true
logRows.value = []
try {
// 契约「返回 list」:兼容直接返回数组或 { list } / { lists } 包络
const res: any = await revisitDueLogs({ due_id: Number(row.id) })
const list = Array.isArray(res) ? res : (res?.list ?? res?.lists ?? [])
logRows.value = Array.isArray(list) ? list : []
} finally {
logLoading.value = false
}
}
const goDiagnosis = (row: RevisitDueListRow) => {
const id = Number(row.diagnosis_id ?? 0)
if (id <= 0) return
router.push({ path: '/tcm/diagnosis', query: { id: String(id) } })
}
// ── 下拉数据 ──────────────────────────────────────────
const buildDeptTree = (flat: Array<{ id: number; pid: number; name: string }>): DeptTreeNode[] => {
const map = new Map<number, DeptTreeNode>()
for (const d of flat) {
map.set(Number(d.id), { id: Number(d.id), pid: Number(d.pid), name: d.name, children: [] })
}
const roots: DeptTreeNode[] = []
for (const d of flat) {
const node = map.get(Number(d.id))!
if (Number(d.pid) > 0 && map.has(Number(d.pid))) {
map.get(Number(d.pid))!.children!.push(node)
} else {
roots.push(node)
}
}
const strip = (n: DeptTreeNode) => {
if (n.children?.length) {
n.children.forEach(strip)
} else {
delete n.children
}
}
roots.forEach(strip)
return roots
}
const loadOptions = async () => {
const [assistants, depts] = await Promise.allSettled([
getAssistants(),
revisitRateDeptOptions()
])
if (assistants.status === 'fulfilled') {
assistantOptions.value = Array.isArray(assistants.value) ? assistants.value : []
}
if (depts.status === 'fulfilled') {
deptTreeOptions.value = buildDeptTree(depts.value?.rows ?? [])
}
}
onMounted(() => {
// 下拉与列表并行加载,不阻塞首屏
void loadOptions()
getLists()
})
</script>
<style lang="scss" scoped>
.revisit-due-page {
.due-filter-form {
:deep(.el-form-item) {
margin-bottom: 8px;
}
}
.due-hint {
font-size: 12px;
color: var(--el-text-color-secondary);
line-height: 1.6;
}
.cell-main {
line-height: 1.4;
}
.cell-sub {
font-size: 12px;
color: var(--el-text-color-secondary);
line-height: 1.4;
}
.col-hint {
margin-left: 2px;
vertical-align: -2px;
color: var(--el-text-color-secondary);
cursor: help;
}
.text-missing {
color: #ea580c;
font-size: 12px;
}
.overdue-cell.is-overdue {
color: var(--el-color-danger);
font-weight: 600;
}
.overdue-cell.is-severe {
color: #b91c1c;
font-weight: 700;
}
.overdue-cell.is-muted {
color: var(--el-text-color-secondary);
font-size: 12px;
}
.snooze-cell {
font-weight: 600;
}
.snooze-cell.is-level-1 {
color: #ea580c;
}
.snooze-cell.is-level-2 {
color: var(--el-color-danger);
}
.snooze-cell.is-level-3 {
color: #b91c1c;
font-weight: 700;
}
/* 行级标红:与诊单列表一致(utils/revisitDue.ts revisitRowClassName) */
:deep(.el-table__row.row-revisit-overdue) {
border-left: 3px solid var(--el-color-danger);
background: linear-gradient(90deg, rgba(var(--el-color-danger-rgb), 0.06) 0%, transparent 100%) !important;
}
:deep(.el-table__row.row-revisit-overdue:hover > td) {
background: linear-gradient(90deg, rgba(var(--el-color-danger-rgb), 0.1) 0%, transparent 100%) !important;
}
:deep(.el-table__row.row-revisit-overdue.row-revisit-overdue-deep) {
border-left-color: #b91c1c;
background: linear-gradient(90deg, rgba(var(--el-color-danger-rgb), 0.1) 0%, transparent 100%) !important;
}
:deep(.el-table__row.row-revisit-overdue.row-revisit-overdue-deep:hover > td) {
background: linear-gradient(90deg, rgba(var(--el-color-danger-rgb), 0.14) 0%, transparent 100%) !important;
}
/* 状态 chip 配色:与 RevisitNodeCell 一致 */
:deep(.rv-chip) {
font-weight: 500;
}
:deep(.rv-chip--overdue),
:deep(.rv-chip--missed) {
--el-tag-bg-color: #dc2626;
--el-tag-border-color: #dc2626;
}
:deep(.rv-chip--severe) {
font-weight: 700;
--el-tag-bg-color: #b91c1c;
--el-tag-border-color: #b91c1c;
}
:deep(.rv-chip--warning) {
--el-tag-text-color: #ea580c;
--el-tag-bg-color: rgba(234, 88, 12, 0.1);
--el-tag-border-color: rgba(234, 88, 12, 0.3);
}
:deep(.rv-chip--no_days) {
--el-tag-text-color: #ea580c;
--el-tag-border-color: #ea580c;
}
:deep(.rv-chip--visited) {
--el-tag-text-color: #16a34a;
--el-tag-bg-color: rgba(22, 163, 74, 0.1);
--el-tag-border-color: rgba(22, 163, 74, 0.3);
}
:deep(.rv-chip--booked) {
--el-tag-text-color: #4a5dff;
--el-tag-bg-color: rgba(74, 93, 255, 0.1);
--el-tag-border-color: rgba(74, 93, 255, 0.3);
}
}
.log-drawer-body {
min-height: 200px;
}
.log-summary {
padding: 12px 14px;
border-radius: 8px;
background: var(--el-fill-color-light);
display: flex;
flex-direction: column;
gap: 6px;
font-size: 13px;
}
.log-summary-row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px 14px;
}
.log-event {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
}
.log-event-title {
font-size: 14px;
font-weight: 600;
color: var(--el-text-color-primary);
}
.log-event-operator {
font-size: 12px;
color: var(--el-text-color-secondary);
white-space: nowrap;
}
.log-event-meta {
margin-top: 4px;
display: flex;
flex-wrap: wrap;
gap: 4px 12px;
font-size: 12px;
color: var(--el-text-color-secondary);
}
.log-event-payload {
margin-top: 6px;
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.log-payload-chip {
font-size: 12px;
line-height: 20px;
padding: 0 8px;
border-radius: 4px;
background: var(--el-fill-color);
color: var(--el-text-color-regular);
word-break: break-all;
}
</style>
@@ -1,7 +0,0 @@
<template>
<cohort-report cohort-type="inherit" />
</template>
<script setup lang="ts" name="revisitInheritRateStatsPage">
import CohortReport from '../revisit_assign_rate/components/CohortReport.vue'
</script>
+31 -285
View File
@@ -29,18 +29,12 @@
@change="loadData"
/>
</el-form-item>
<el-form-item label="口径">
<el-radio-group v-model="inheritMode" size="small" @change="loadData">
<el-radio-button value="exclude">原口径(继承不计分母)</el-radio-button>
<el-radio-button value="slot">新口径(继承按继承时诊次计入)</el-radio-button>
</el-radio-group>
</el-form-item>
<el-form-item>
<el-button type="primary" :loading="loading" @click="loadData">查询</el-button>
<el-button :disabled="loading" @click="handleReset">重置</el-button>
</el-form-item>
<el-form-item>
<el-popover placement="bottom-start" :width="560" trigger="hover">
<el-popover placement="bottom-start" :width="500" trigger="hover">
<template #reference>
<span class="rate-caliber-trigger">
<el-icon><InfoFilled /></el-icon>
@@ -49,29 +43,16 @@
</template>
<div class="rate-caliber">
<p>
<b>{{ isSlotMode ? '新指派数' : '当月被指派数' }}</b>:当月内诊单被指派给医助(按指派操作时间落月,<b>不含勾选「继承」的指派</b>)的诊单数,按「医助 × 诊单」去重;部门行 / 合计行按诊单去重;<b>再剔除</b>名下存在履约「拒收 / 退款」业务订单的诊单。与业绩看板「被指派数」同口径。
</p>
<template v-if="isSlotMode">
<p>
<b>继承数</b>:当月勾选「继承」转接给该医助的诊单数(同一诊单多次继承取最早;同月既新指派又继承给同一医助只算新指派;历史「回退自动分配」行按继承处理;指派给自己的记录忽略)。<b>继承时诊次 k</b> = 继承时刻之前患者已完成的诊次(有效实单数 + 偏移),<b>起算诊次 = max(2, k+1)</b>:继承者只对第 k+1 诊及以后负责。
</p>
<p>
<b>N 诊分母</b> = 新指派数 + 起算诊次 ≤ N 的继承数(每列独立);<b>N 诊接诊率</b> = N 诊单数 ÷ N 诊分母,分母为 0 显示「—」。<b>复诊合计</b>:单数 = 各诊次单数之和,分母 = 新指派 ∪ 继承(被指派合计),比率可超过 100%(人均复诊成交单数)。
</p>
<p class="rate-caliber-note">
继承分母依赖指派记录的「继承」标记(2026-06 起写入),之前的转接无法回溯;切换为「旧口径」可对照上线前数字。
</p>
</template>
<template v-else>
<p>
<b>旧口径</b>:继承指派不计入分母,N 诊分母 = 新指派数(对所有 N 相同),新指派数 / N 诊单数 / N 诊接诊率与 2026-10 之前完全一致;继承数恒为 0。切换为「新口径」后继承按继承时诊次计入每列独立分母。
</p>
</template>
<p>
<b>诊次(第 N 次下单)</b>:患者(诊单)名下计入业绩的业务订单(剔除已取消 / 拒收 / 退款)按下单时间升序编号为「实单序号」,<b>统计诊次 = 实单序号 + 诊单偏移</b>(默认偏移 0 → 第 1 笔实单为一诊)。诊次<b>跨月累计不重置</b>。诊单可在「业务订单」tab 配置偏移量。
<b>当月被指派总数</b>:当月内诊单被指派给医助(按指派操作时间落月,<b>剔除勾选「继承」的指派</b>)的诊单数,按「医助 × 诊单」去重;部门行 / 合计行按诊单去重;<b>再剔除</b>名下存在履约「拒收 / 退款」业务订单的诊单。
</p>
<p>
<b>当月 N 诊单数</b>:当月内下单且诊次为 N 的订单数,归属下单时点<b>持有该患者的医助</b>(指派可在往月;释放后不再归属;继承会转移持有人)。往月指派、当月成交会推高分子,比率可能超过 100%。
<b>诊次(第 N 次下单)</b>:患者(诊单)名下计入业绩的业务订单(剔除已取消 / 拒收 / 退款)按下单时间升序编号为「实单序号」,<b>统计诊次 = 实单序号 + 诊单偏移</b>(默认偏移 0 → 第 1 笔实单为一诊;偏移 1 → 第 1 笔实单为二诊;偏移 2 → 第 1 笔实单为三诊,5 笔实单等价七诊)。诊次<b>跨月累计不重置</b>。诊单可在「业务订单」tab 配置偏移量。
</p>
<p>
<b>当月 N 诊单数</b>:当月内下单且诊次为 N 的订单数,归属下单时点<b>持有该患者的医助</b>(指派可在往月;释放后不再归属;「继承」指派会转移持有人但不计被指派数)。
</p>
<p>
<b>当月 N 诊接诊率</b> = 当月 N 诊单数 ÷ 当月被指派总数。往月指派、当月成交会推高分子,比率可能超过 100%;医助当月无新指派但旗下有成交时,被指派数为 0、比率显示「—」。
</p>
<p>
医助按人事部门归组;<b>仅统计「二中心」及其组织下级</b>;部门下拉与未选时的默认范围均限定在该子树,选定部门时含其组织下级。
@@ -100,9 +81,7 @@
<template #header>
<div class="rate-card-header">
<span>部门 · 医助明细({{ monthText }})</span>
<span class="rate-card-hint">
点击「新指派数 / 继承数 / 被指派合计 / N诊单数 / 复诊合计单数」可查看具体诊单与订单;接诊率下方灰字为「单数 / 分母」;底栏合计按诊单去重
</span>
<span class="rate-card-hint">点击「被指派数 / N诊单数」可查看具体诊单与订单;底栏合计的被指派数按诊单去重</span>
</div>
</template>
<el-table
@@ -125,88 +104,19 @@
<span v-else>{{ row.assistant_name }}</span>
</template>
</el-table-column>
<el-table-column
prop="assigned_count"
:label="isSlotMode ? '新指派数' : '当月被指派数'"
min-width="96"
align="right"
>
<template #header>
<span>{{ isSlotMode ? '新指派数' : '当月被指派数' }}</span>
<el-tooltip
effect="dark"
placement="top"
content="当月非继承指派的「医助 × 诊单」去重数(剔除名下有拒收/退款订单的诊单),与业绩看板「被指派数」同口径"
>
<el-icon class="rate-th-hint"><InfoFilled /></el-icon>
</el-tooltip>
</template>
<el-table-column prop="assigned_count" label="当月被指派数" min-width="110" align="right">
<template #default="{ row }">
<el-link
v-if="canViewAssignLines && row.assigned_count > 0"
type="primary"
:underline="false"
@click="openAssignDetail(row, 'new')"
@click="openAssignDetail(row)"
>
{{ row.assigned_count }}
</el-link>
<span v-else>{{ row.assigned_count }}</span>
</template>
</el-table-column>
<el-table-column
v-if="isSlotMode"
prop="inherit_count"
label="继承数"
min-width="88"
align="right"
>
<template #header>
<span>继承数</span>
<el-tooltip
effect="dark"
placement="top"
content="当月勾选「继承」转接给该医助的诊单数(按继承时诊次 k 从第 k+1 诊起计入分母;点击查看每条的继承时诊次与起算诊次)"
>
<el-icon class="rate-th-hint"><InfoFilled /></el-icon>
</el-tooltip>
</template>
<template #default="{ row }">
<el-link
v-if="canViewAssignLines && row.inherit_count > 0"
type="primary"
:underline="false"
@click="openAssignDetail(row, 'inherit')"
>
{{ row.inherit_count }}
</el-link>
<span v-else>{{ row.inherit_count ?? 0 }}</span>
</template>
</el-table-column>
<el-table-column
v-if="isSlotMode"
prop="assigned_total_count"
label="被指派合计"
min-width="100"
align="right"
>
<template #header>
<span>被指派合计</span>
<el-tooltip effect="dark" placement="top" content="新指派 ∪ 继承(按诊单去重),即「复诊合计接诊率」的分母">
<el-icon class="rate-th-hint"><InfoFilled /></el-icon>
</el-tooltip>
</template>
<template #default="{ row }">
<el-link
v-if="canViewAssignLines && row.assigned_total_count > 0"
type="primary"
:underline="false"
@click="openAssignDetail(row, 'all')"
>
{{ row.assigned_total_count }}
</el-link>
<span v-else>{{ row.assigned_total_count ?? 0 }}</span>
</template>
</el-table-column>
<template v-for="slot in visitSlots" :key="slot">
<el-table-column
:prop="`visit${slot}_count`"
@@ -239,64 +149,12 @@
<el-table-column
:prop="`visit${slot}_rate`"
:label="`${slotLabel(slot)}接诊率`"
min-width="104"
min-width="96"
align="right"
>
<template #header>
<span>{{ slotLabel(slot) }}接诊率</span>
<el-tooltip effect="dark" placement="top" :content="rateHeaderTip(slot)">
<el-icon class="rate-th-hint"><InfoFilled /></el-icon>
</el-tooltip>
</template>
<template #default="{ row }">
<div class="rate-cell">
<span class="rate-cell-main">{{ formatRate(row[`visit${slot}_rate`]) }}</span>
<span v-if="isSlotMode" class="rate-cell-sub">{{ denText(row, `visit${slot}`) }}</span>
</div>
</template>
<template #default="{ row }">{{ formatRate(row[`visit${slot}_rate`]) }}</template>
</el-table-column>
</template>
<el-table-column prop="visit_all_count" label="复诊合计单数" min-width="110" align="right">
<template #header>
<span>复诊合计单数</span>
<el-tooltip effect="dark" placement="top" content="当月内下单、诊次 ≥ 2 的订单数之和(= 各 N 诊单数之和)">
<el-icon class="rate-th-hint"><InfoFilled /></el-icon>
</el-tooltip>
</template>
<template #default="{ row }">
<el-link
v-if="canViewOrderLines && row.visit_all_count > 0"
type="primary"
:underline="false"
@click="openOrderDetail(0, row)"
>
{{ row.visit_all_count }}
</el-link>
<span v-else>{{ row.visit_all_count ?? 0 }}</span>
</template>
</el-table-column>
<el-table-column prop="visit_all_rate" label="复诊合计接诊率" min-width="118" align="right">
<template #header>
<span>复诊合计接诊率</span>
<el-tooltip
effect="dark"
placement="top"
:content="
isSlotMode
? '复诊合计单数 ÷ 被指派合计(新指派 ∪ 继承);可超过 100%,语义为人均复诊成交单数'
: '复诊合计单数 ÷ 新指派数(旧口径继承不计分母);可超过 100%'
"
>
<el-icon class="rate-th-hint"><InfoFilled /></el-icon>
</el-tooltip>
</template>
<template #default="{ row }">
<div class="rate-cell">
<span class="rate-cell-main">{{ formatRate(row.visit_all_rate) }}</span>
<span v-if="isSlotMode" class="rate-cell-sub">{{ denText(row, 'visit_all') }}</span>
</div>
</template>
</el-table-column>
</el-table>
</el-card>
@@ -304,7 +162,7 @@
<el-dialog
v-model="detailVisible"
:title="detailTitle"
width="1080px"
width="980px"
top="6vh"
destroy-on-close
>
@@ -335,33 +193,6 @@
<template #default="{ row }">{{ row.patient_phone || '—' }}</template>
</el-table-column>
<el-table-column prop="assistant_names" label="被指派医助" min-width="140" show-overflow-tooltip />
<el-table-column v-if="isSlotMode" prop="assign_type" label="指派类型" width="110" align="center">
<template #default="{ row }">
<el-tag :type="row.assign_type === 'inherit' ? 'warning' : 'success'" size="small">
{{ row.assign_type_text || (row.assign_type === 'inherit' ? '继承' : '新指派') }}
</el-tag>
</template>
</el-table-column>
<el-table-column v-if="isSlotMode" prop="inherit_visit_slot" label="继承时诊次" width="100" align="center">
<template #header>
<span>继承时诊次</span>
<el-tooltip effect="dark" placement="top" content="k:继承时刻之前患者已完成的诊次(有效实单数 + 偏移);新指派无此值">
<el-icon class="rate-th-hint"><InfoFilled /></el-icon>
</el-tooltip>
</template>
<template #default="{ row }">
{{ row.assign_type === 'inherit' ? `第 ${Number(row.inherit_visit_slot ?? 0)} 诊` : '—' }}
</template>
</el-table-column>
<el-table-column prop="entry_slot" label="起算诊次" width="96" align="center">
<template #header>
<span>起算诊次</span>
<el-tooltip effect="dark" placement="top" content="从该诊次列起计入分母:继承 = max(2, k+1);新指派 = 2(二诊)">
<el-icon class="rate-th-hint"><InfoFilled /></el-icon>
</el-tooltip>
</template>
<template #default="{ row }">{{ entrySlotText(row.entry_slot) }}</template>
</el-table-column>
<el-table-column prop="assign_count" label="当月指派次数" width="110" align="right" />
<el-table-column prop="last_assign_time_text" label="最近指派时间" min-width="160" />
</template>
@@ -379,9 +210,6 @@
<span v-else>{{ row.order_no || `#${row.order_id}` }}</span>
</template>
</el-table-column>
<el-table-column v-if="detailSlot === 0" prop="visit_slot" label="诊次" width="80" align="center">
<template #default="{ row }">{{ slotLabel(Number(row.visit_slot)) }}</template>
</el-table-column>
<el-table-column prop="diagnosis_id" label="诊单ID" width="90" />
<el-table-column prop="patient_name" label="患者" min-width="100">
<template #default="{ row }">
@@ -423,9 +251,7 @@ import {
revisitRateAssignLines,
revisitRateDeptOptions,
revisitRateOverview,
revisitRateVisitOrderLines,
type RevisitRateAssignKind,
type RevisitRateInheritMode
revisitRateVisitOrderLines
} from '@/api/stats'
import { hasPermission } from '@/utils/perm'
@@ -437,14 +263,7 @@ const OrderDetailDrawer = defineAsyncComponent(
const DiagnosisEditPopup = defineAsyncComponent(() => import('@/views/tcm/diagnosis/edit.vue'))
interface MetricPack extends Record<string, any> {
/** 新指派数(语义不变) */
assigned_count: number
inherit_count?: number
assigned_total_count?: number
visit_all_count?: number
visit_all_den?: number
visit_all_rate?: number | null
visit2_rate_new_assign?: number | null
}
interface StatsRow extends MetricPack {
@@ -470,14 +289,11 @@ const canViewOrderLines = hasPermission(['stats.revisitRate/visitOrderLines'])
const canViewOrderDetail = hasPermission(['tcm.prescriptionOrder/detail'])
const canViewPatientDetail = hasPermission(['tcm.diagnosis/detail'])
/** 接口动态返回的诊次分档(最少 2~4,按分子最大诊次 / 最大起算诊次扩展到五诊、六诊…) */
/** 接口动态返回的诊次分档(最少 2~4,按数据扩展到五诊、六诊…) */
const visitSlots = ref<number[]>([2, 3, 4])
const cnDigits = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十']
const slotLabel = (slot: number) => {
if (slot === 0) {
return '复诊合计'
}
if (slot >= 2 && slot <= 10) {
return `${cnDigits[slot]}诊`
}
@@ -491,8 +307,6 @@ const initNow = new Date()
const currentMonth = `${initNow.getFullYear()}-${String(initNow.getMonth() + 1).padStart(2, '0')}`
const month = ref<string>(currentMonth)
const deptId = ref<number | undefined>(undefined)
/** 口径:首次加载不传、取后端默认(config default_inherit_mode),之后以用户选择为准 */
const inheritMode = ref<RevisitRateInheritMode | ''>('')
const loading = ref(false)
const rows = ref<StatsRow[]>([])
const total = ref<MetricPack | null>(null)
@@ -500,8 +314,6 @@ const total = ref<MetricPack | null>(null)
const deptTreeOptions = ref<DeptTreeNode[]>([])
const deptTreeProps = { value: 'id', label: 'name', children: 'children' }
const isSlotMode = computed(() => inheritMode.value !== 'exclude')
const monthText = computed(() => {
const [y, m] = month.value.split('-')
return y && m ? `${y}年${Number(m)}月` : month.value
@@ -510,30 +322,9 @@ const monthText = computed(() => {
const formatRate = (rate: number | null | undefined) =>
rate === null || rate === undefined ? '—' : `${rate}%`
/** 接诊率单元格下方灰字:单数 / 分母 */
const denText = (row: Record<string, any>, prefix: string) => {
const cnt = Number(row[`${prefix}_count`] ?? 0)
const den = row[`${prefix}_den`]
return `${cnt} / ${den === null || den === undefined ? '—' : den}`
}
const rateHeaderTip = (slot: number) =>
isSlotMode.value
? `${slotLabel(slot)}单数 ÷ ${slotLabel(slot)}分母;分母 = 当月新指派数 + 起算诊次 ≤ ${slot} 的继承数;分母为 0 显示「—」`
: `${slotLabel(slot)}单数 ÷ 当月新指派数(旧口径:继承不计分母);分母为 0 显示「—」`
const entrySlotText = (entry: unknown) => {
const n = Number(entry ?? 0)
if (n <= 0) {
return '—'
}
return n > 50 ? `${n}(仅计合计)` : slotLabel(n)
}
const baseQuery = () => ({
month: month.value,
dept_ids: deptId.value ? String(deptId.value) : '',
inherit_mode: (inheritMode.value || undefined) as RevisitRateInheritMode | undefined
dept_ids: deptId.value ? String(deptId.value) : ''
})
interface SummaryCard {
@@ -550,11 +341,11 @@ const summaryCards = computed<SummaryCard[]>(() => {
const cards: SummaryCard[] = [
{
key: 'assigned',
label: isSlotMode.value ? '当月新指派数' : '当月被指派数',
label: '当月被指派总数',
value: t ? String(t.assigned_count) : '—',
sub: t && isSlotMode.value ? `继承 ${t.inherit_count ?? 0} · 被指派合计 ${t.assigned_total_count ?? 0}` : '',
sub: '',
clickable: !!(canViewAssignLines && t && t.assigned_count > 0),
onClick: () => openAssignDetail(null, 'new')
onClick: () => openAssignDetail(null)
}
]
for (const slot of visitSlots.value) {
@@ -564,19 +355,11 @@ const summaryCards = computed<SummaryCard[]>(() => {
key: `visit${slot}`,
label: `当月${slotLabel(slot)}接诊率`,
value: t ? formatRate(rate) : '—',
sub: t ? `${slotLabel(slot)}下单 ${cnt} 单 / 分母 ${t[`visit${slot}_den`] ?? '—'}` : '',
sub: t ? `${slotLabel(slot)}下单 ${cnt} 单` : '',
clickable: !!(canViewOrderLines && cnt > 0),
onClick: () => openOrderDetail(slot, null)
})
}
cards.push({
key: 'visit_all',
label: '当月复诊合计接诊率',
value: t ? formatRate(t.visit_all_rate) : '—',
sub: t ? `复诊下单 ${t.visit_all_count ?? 0} 单 / 被指派合计 ${t.visit_all_den ?? '—'}` : '',
clickable: !!(canViewOrderLines && t && Number(t.visit_all_count) > 0),
onClick: () => openOrderDetail(0, null)
})
return cards
})
@@ -591,16 +374,15 @@ const getSummaries = ({ columns }: { columns: any[] }) => {
return ''
}
const prop = String(col.property || '')
if (prop === 'assigned_count' || prop === 'inherit_count' || prop === 'assigned_total_count') {
return String(t[prop] ?? 0)
if (prop === 'assigned_count') {
return String(t.assigned_count)
}
const m = /^visit(\d+|all)_(count|den|rate)$/.exec(prop)
if (m) {
if (m[2] === 'rate') {
return `${formatRate(t[prop])}(${denText(t, `visit${m[1]}`)})`
}
if (/^visit\d+_count$/.test(prop)) {
return String(t[prop] ?? '')
}
if (/^visit\d+_rate$/.test(prop)) {
return formatRate(t[prop])
}
return ''
})
}
@@ -622,9 +404,6 @@ const loadData = async () => {
if (res?.month) {
month.value = res.month
}
if (res?.inherit_mode === 'slot' || res?.inherit_mode === 'exclude') {
inheritMode.value = res.inherit_mode
}
} finally {
loading.value = false
}
@@ -670,8 +449,6 @@ const detailType = ref<'assign' | 'orders'>('assign')
const detailTitle = ref('')
const detailLoading = ref(false)
const detailRows = ref<any[]>([])
/** 订单明细的诊次(0 = 复诊合计,表格多显示「诊次」列) */
const detailSlot = ref(2)
/** row 为 null 时表示合计(当前部门筛选范围) */
const rowScope = (row: StatsRow | null): { assistant_id?: number; dept_id?: number; label: string } => {
@@ -684,19 +461,13 @@ const rowScope = (row: StatsRow | null): { assistant_id?: number; dept_id?: numb
return { assistant_id: row.assistant_id, label: row.assistant_name || '' }
}
const assignKindLabel: Record<RevisitRateAssignKind, string> = {
new: '新指派明细',
inherit: '继承明细',
all: '被指派合计明细'
}
const openAssignDetail = async (row: StatsRow | null, kind: RevisitRateAssignKind = 'all') => {
const openAssignDetail = async (row: StatsRow | null) => {
if (!canViewAssignLines) {
return
}
const scope = rowScope(row)
detailType.value = 'assign'
detailTitle.value = `${scope.label} · ${assignKindLabel[kind]}(${monthText.value})`
detailTitle.value = `${scope.label} · 被指派明细(${monthText.value})`
detailVisible.value = true
detailLoading.value = true
detailRows.value = []
@@ -704,8 +475,7 @@ const openAssignDetail = async (row: StatsRow | null, kind: RevisitRateAssignKin
const res = await revisitRateAssignLines({
...baseQuery(),
assistant_id: scope.assistant_id,
dept_id: scope.dept_id,
kind
dept_id: scope.dept_id
})
detailRows.value = res?.rows ?? []
} finally {
@@ -713,14 +483,12 @@ const openAssignDetail = async (row: StatsRow | null, kind: RevisitRateAssignKin
}
}
/** slot=0 表示全部诊次 ≥ 2(复诊合计单数) */
const openOrderDetail = async (slot: number, row: StatsRow | null) => {
if (!canViewOrderLines) {
return
}
const scope = rowScope(row)
detailType.value = 'orders'
detailSlot.value = slot
detailTitle.value = `${scope.label} · ${slotLabel(slot)}订单明细(${monthText.value})`
detailVisible.value = true
detailLoading.value = true
@@ -761,7 +529,6 @@ const openPatientDetail = (diagnosisId: number) => {
const handleReset = () => {
month.value = currentMonth
deptId.value = undefined
inheritMode.value = ''
loadData()
}
@@ -856,22 +623,6 @@ onMounted(() => {
color: var(--el-text-color-secondary);
cursor: help;
}
.rate-cell {
display: flex;
flex-direction: column;
align-items: flex-end;
line-height: 1.3;
.rate-cell-main {
font-weight: 500;
}
.rate-cell-sub {
font-size: 11px;
color: var(--el-text-color-placeholder);
}
}
}
.rate-detail-footer {
@@ -889,10 +640,5 @@ onMounted(() => {
p + p {
margin-top: 6px;
}
.rate-caliber-note {
color: var(--el-text-color-secondary);
font-size: 12px;
}
}
</style>
-2
View File
@@ -1,6 +1,5 @@
<template>
<div class="appointment-list">
<DoctorWebConsultationNotice />
<el-card class="list-card !border-none" shadow="never">
<!-- 单行工具栏:Tab(主) + 搜索(辅) -->
<div class="list-toolbar">
@@ -560,7 +559,6 @@
</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,6 +1,5 @@
<template>
<div class="apt-h5">
<DoctorWebConsultationNotice />
<template v-if="currentView === 'list'">
<header class="apt-h5-topbar">
<div class="apt-h5-search">
@@ -413,7 +412,6 @@
</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'
@@ -12,21 +12,9 @@
{{ assistantLogCellText(row, 'to') }}
</template>
</el-table-column>
<el-table-column label="继承" width="118" align="center">
<template #header>
<span>继承</span>
<el-tooltip
placement="top"
content="继承时第 k 诊:继承时刻之前患者已完成的诊次(有效实单数 + 偏移),复诊接诊率从第 k+1 诊起计入新医助分母;2026-10 前的继承记录无此快照"
>
<el-icon class="assign-log-col-hint"><QuestionFilled /></el-icon>
</el-tooltip>
</template>
<el-table-column label="继承" width="72" align="center">
<template #default="{ row }">
<template v-if="Number(row.is_inherit) === 1">
<el-tag type="success" size="small">是</el-tag>
<div v-if="inheritSlotText(row)" class="assign-log-inherit-slot">{{ inheritSlotText(row) }}</div>
</template>
<el-tag v-if="Number(row.is_inherit) === 1" type="success" size="small">是</el-tag>
<span v-else class="text-gray-400">否</span>
</template>
</el-table-column>
@@ -97,20 +85,6 @@ function relatedPoCreateTimeCell(row: Record<string, unknown>): string {
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
}
/** 对应日志表 inherit_visit_slot / inherit_visit_slot_calc_time:后端已拼好「继承时第 k 诊」文案,缺失时按快照列兜底 */
function inheritSlotText(row: Record<string, unknown>): string {
const text = row.inherit_visit_slot_text
if (text != null && String(text).trim() !== '') {
return String(text)
}
const calcTime = Number(row.inherit_visit_slot_calc_time)
if (!Number.isFinite(calcTime) || calcTime <= 0) {
return ''
}
const k = Number(row.inherit_visit_slot)
return Number.isFinite(k) && k > 0 ? `继承时第 ${k} 诊` : '继承时未成交'
}
function assistantLogCellText(row: Record<string, unknown>, side: 'from' | 'to'): string {
const nameKey = side === 'from' ? 'from_assistant_name' : 'to_assistant_name'
const idKey = side === 'from' ? 'from_assistant_id' : 'to_assistant_id'
@@ -158,11 +132,4 @@ defineExpose({ refresh: load })
color: var(--el-text-color-secondary);
cursor: help;
}
.assign-log-inherit-slot {
margin-top: 2px;
font-size: 12px;
line-height: 1.3;
color: var(--el-text-color-secondary);
}
</style>
@@ -1,168 +0,0 @@
<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>
@@ -1,303 +0,0 @@
<template>
<div :class="['rv-cell', { 'rv-cell--compact': compact }]">
<!-- 行 1:[第 N 诊] tag + 已开方/未开方 + 复诊医生 -->
<div class="rv-line rv-line--head">
<el-tooltip
v-if="showDue && tooltipLines.length"
placement="top"
:show-after="300"
:hide-after="0"
>
<template #content>
<div class="rv-tooltip">
<div v-for="line in tooltipLines" :key="line">{{ line }}</div>
</div>
</template>
<el-tag size="small" :type="slotTagType" effect="light" class="rv-slot-tag">
{{ slotText }}
</el-tag>
</el-tooltip>
<el-tag
v-else-if="showDue"
size="small"
:type="slotTagType"
effect="light"
class="rv-slot-tag"
>
{{ slotText }}
</el-tag>
<span
v-if="prescribedLabel"
:class="['rv-prescribed', hasPrescription ? 'rv-prescribed--yes' : 'rv-prescribed--no']"
>
{{ prescribedLabel }}
</span>
<span v-if="followupDoctorName" class="rv-doctor">
<span v-if="prescribedLabel" class="rv-dot">·</span>{{ followupDoctorName }}
</span>
</div>
<template v-if="showDue">
<!-- 行 2:最新开药日 · 开药 X 天 · 锚点来源;缺天数时橙色 -->
<div class="rv-line rv-line--order">
<span v-if="orderDateText" class="rv-order-date">{{ orderDateText }} 开药</span>
<span v-if="orderDateText" class="rv-dot">·</span>
<span :class="['rv-days', { 'rv-days--missing': daysMissing }]">{{ medicationText }}</span>
<template v-if="!daysMissing && anchorText">
<span class="rv-dot">·</span>
<span class="rv-anchor">{{ anchorText }}</span>
</template>
</div>
<!-- 行 3:药尽 MM-DD + 状态 chip -->
<div class="rv-line rv-line--due">
<span v-if="dueDateText" class="rv-due-date">{{ dueDateText }}</span>
<el-tag
v-if="chipText"
size="small"
:type="chipType"
:effect="chipEffect"
:class="chipClass"
>
{{ chipText }}
</el-tag>
</div>
<!-- 行 4:已延迟 N 次 · 已联系 约 MM-DD(有值才显示) -->
<div v-if="followLineText" class="rv-line rv-line--follow">{{ followLineText }}</div>
</template>
<span v-else class="rv-none">—</span>
</div>
</template>
<script setup lang="ts">
/**
* 复诊节点单元格(PC 列表 / H5 卡片紧凑 / 只读页 三处共用)
*
* 只负责展示,不发请求;数据来自列表行 `revisit_due`(契约 C),由父组件用
* `normalizeRevisitDue` 规整后传入。state='none' 或 due 为 null 时仅显示行 1 + 「—」。
*/
import { computed } from 'vue'
import {
formatRevisitMonthDay,
hasRevisitDue,
isRevisitDaysMissing,
revisitAnchorSrcText,
revisitDueDateText,
revisitFollowLineText,
revisitMedicationDaysText,
revisitSlotText,
revisitStateChipClass,
revisitStateChipText,
revisitStateTagEffect,
revisitStateTagType,
revisitTooltipLines,
type RevisitDue
} from '@/utils/revisitDue'
const props = withDefaults(
defineProps<{
/** 规整后的复诊节点对象;null / state='none' 显示「—」 */
due: RevisitDue | null
/** H5 紧凑模式:更小字号、更紧行距 */
compact?: boolean
/** 是否已开方(决定「已开方/未开方」默认文案与颜色) */
hasPrescription?: boolean
/** 复诊医生(原列表 followup_doctor_name) */
followupDoctorName?: string
/** 自定义「已开方/未开方」文案;传 '' 隐藏该段(H5 卡片头已有标签时用) */
prescribedText?: string
}>(),
{
compact: false,
hasPrescription: false,
followupDoctorName: ''
}
)
const showDue = computed(() => hasRevisitDue(props.due))
const prescribedLabel = computed(() => {
if (props.prescribedText !== undefined) return props.prescribedText
return props.hasPrescription ? '已开方' : '未开方'
})
const slotText = computed(() => revisitSlotText(props.due))
const slotTagType = computed<'primary' | 'info'>(() =>
showDue.value && Number(props.due?.current_slot) > 0 ? 'primary' : 'info'
)
const tooltipLines = computed(() => revisitTooltipLines(props.due))
const orderDateText = computed(() => (showDue.value ? formatRevisitMonthDay(props.due?.order_date) : ''))
const daysMissing = computed(() => isRevisitDaysMissing(props.due))
const medicationText = computed(() => revisitMedicationDaysText(props.due))
const anchorText = computed(() => (showDue.value ? revisitAnchorSrcText(props.due?.anchor_src) : ''))
const dueDateText = computed(() => revisitDueDateText(props.due))
const chipText = computed(() => revisitStateChipText(props.due))
const chipType = computed(() => revisitStateTagType(props.due?.state))
const chipEffect = computed(() => revisitStateTagEffect(props.due?.state))
const chipClass = computed(() => revisitStateChipClass(props.due))
const followLineText = computed(() => revisitFollowLineText(props.due))
</script>
<style lang="scss" scoped>
.rv-cell {
display: flex;
flex-direction: column;
gap: 3px;
line-height: 1.35;
min-width: 0;
}
.rv-line {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 4px;
min-width: 0;
}
.rv-line--head {
font-size: 13px;
color: var(--el-text-color-primary);
}
.rv-slot-tag {
font-weight: 600;
cursor: default;
}
.rv-prescribed {
font-size: 13px;
font-weight: 500;
}
.rv-prescribed--yes {
color: #4a5dff;
}
.rv-prescribed--no {
color: var(--el-text-color-placeholder);
}
.rv-doctor {
font-size: 12px;
color: var(--el-text-color-secondary);
}
.rv-dot {
color: var(--el-text-color-placeholder);
font-size: 12px;
}
.rv-line--order {
font-size: 12px;
color: var(--el-text-color-secondary);
}
.rv-days--missing {
color: #ea580c;
font-weight: 600;
}
.rv-anchor {
color: var(--el-text-color-placeholder);
}
.rv-line--due {
font-size: 13px;
}
.rv-due-date {
font-weight: 500;
color: var(--el-text-color-primary);
font-variant-numeric: tabular-nums;
}
/* 状态 chip:el-tag 基础色由 type/effect 决定,这里只补深红加粗与描边细节。
前缀 .rv-cell 提高特异性,压过 Element 的 .el-tag--dark.el-tag--danger 变量定义 */
.rv-cell .rv-chip {
font-weight: 500;
}
.rv-cell .rv-chip--overdue,
.rv-cell .rv-chip--missed {
--el-tag-bg-color: #dc2626;
--el-tag-border-color: #dc2626;
}
.rv-cell .rv-chip--severe,
.rv-cell .rv-chip--overdue.rv-chip--severe,
.rv-cell .rv-chip--missed.rv-chip--severe {
font-weight: 700;
--el-tag-bg-color: #b91c1c;
--el-tag-border-color: #b91c1c;
}
.rv-cell .rv-chip--warning {
--el-tag-text-color: #ea580c;
--el-tag-bg-color: rgba(234, 88, 12, 0.1);
--el-tag-border-color: rgba(234, 88, 12, 0.3);
}
.rv-cell .rv-chip--no_days {
--el-tag-text-color: #ea580c;
--el-tag-border-color: #ea580c;
}
.rv-cell .rv-chip--visited {
--el-tag-text-color: #16a34a;
--el-tag-bg-color: rgba(22, 163, 74, 0.1);
--el-tag-border-color: rgba(22, 163, 74, 0.3);
}
.rv-cell .rv-chip--booked {
--el-tag-text-color: #4a5dff;
--el-tag-bg-color: rgba(74, 93, 255, 0.1);
--el-tag-border-color: rgba(74, 93, 255, 0.3);
}
.rv-cell .rv-chip--contacted {
--el-tag-text-color: #4a5dff;
--el-tag-border-color: #4a5dff;
}
.rv-line--follow {
font-size: 12px;
color: var(--el-text-color-secondary);
}
.rv-none {
font-size: 13px;
color: var(--el-text-color-placeholder);
}
.rv-tooltip {
line-height: 1.6;
font-size: 12px;
}
/* H5 紧凑模式 */
.rv-cell--compact {
gap: 2px;
.rv-line--head,
.rv-line--due,
.rv-prescribed {
font-size: 12px;
}
.rv-line--order,
.rv-line--follow,
.rv-doctor {
font-size: 11px;
}
.rv-none {
font-size: 12px;
}
}
</style>
+1 -20
View File
@@ -744,20 +744,6 @@
<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"
@@ -841,7 +827,6 @@ 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'
@@ -877,7 +862,6 @@ 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)
@@ -946,15 +930,12 @@ watch(() => activeTab.value, async (tab) => {
}
})
watch([visible, activeTab, hasCallTranscriptPermission], () => {
watch([visible, activeTab], () => {
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 (
+81 -286
View File
@@ -14,7 +14,6 @@
formData.pending_assign !== '1' &&
formData.pending_booking !== '1' &&
formData.completed_appointment !== '1' &&
formData.revisit_state === '' &&
!hasLatestAppointmentFilter() &&
formData.appointment_date === tab.value
}
@@ -31,14 +30,6 @@
待预约
<em v-if="pendingBookingCount !== undefined">{{ pendingBookingCount }}</em>
</span>
<!-- 复诊到期:到期未挂号 ∪ 过号未面诊(revisit_state=due),点击默认按药尽日升序 -->
<span
:class="['chip', 'chip-revisit-due', { active: formData.revisit_state === 'due' }]"
@click="handleRevisitDueTabClick"
>
复诊到期
<em v-if="revisitDueCount !== undefined">{{ revisitDueCount }}</em>
</span>
<span
:class="['chip', 'chip-completed-visit', { active: formData.completed_appointment === '1' }]"
@click="handleCompletedVisitTabClick"
@@ -156,36 +147,6 @@
:value="String(item.value)"
/>
</el-select>
<el-select
v-model="formData.revisit_state"
placeholder="复诊状态"
clearable
size="small"
class="revisit-state-select"
@change="handleRevisitFilterChange"
>
<el-option
v-for="item in revisitStateFilterOptions"
:key="item.value"
:label="item.label"
:value="item.value"
/>
</el-select>
<el-select
v-model="formData.revisit_days_bucket"
placeholder="开药天数档"
clearable
size="small"
class="revisit-days-bucket-select"
@change="doSearch"
>
<el-option
v-for="item in revisitDaysBucketOptions"
:key="item.value"
:label="item.label"
:value="item.value"
/>
</el-select>
<el-button size="small" @click="handleReset">重置</el-button>
</div>
</el-card>
@@ -317,20 +278,22 @@
<span v-else class="status-unconfirmed">未确认</span>
</template>
</el-table-column>
<!-- 复诊节点:吞掉原「复诊」「开方」两列;排序走后端 sort_revisit_due(药尽日,NULL 置后) -->
<el-table-column
label="复诊节点"
prop="revisit_due_date"
min-width="180"
sortable="custom"
>
<el-table-column label="复诊" min-width="120">
<template #default="{ row }">
<revisit-node-cell
:due="revisitDueOf(row)"
:has-prescription="!!row.has_prescription"
:followup-doctor-name="row.followup_doctor_name || ''"
:prescribed-text="prescribedTextOf(row)"
/>
<div v-if="row.has_prescription" class="followup-cell">
<div class="followup-time">{{ row.followup_time_text || '—' }}</div>
<div class="followup-doctor">{{ row.followup_doctor_name || '—' }}</div>
<el-tag
v-if="row.followup_rx_voided"
type="info"
size="small"
effect="plain"
class="followup-void-tag"
>
处方已作废
</el-tag>
</div>
<span v-else class="followup-none">无</span>
</template>
</el-table-column>
<el-table-column label="助理" width="100" show-overflow-tooltip>
@@ -338,6 +301,12 @@
<span class="assistant-cell">{{ getAssistantName(row.assistant_id || row.assistant) }}</span>
</template>
</el-table-column>
<el-table-column label="开方" width="72" align="center">
<template #default="{ row }">
<span v-if="row.has_prescription" class="status-prescribed">已开方</span>
<span v-else class="status-unprescribed">未开方</span>
</template>
</el-table-column>
<el-table-column
label="未服务天数"
prop="unserved_days"
@@ -550,6 +519,7 @@
</el-form-item>
<el-form-item label="继承">
<el-checkbox v-model="assignForm.is_inherit">继承</el-checkbox>
<span class="text-gray-400 text-xs ml-2">勾选后写入指派记录</span>
</el-form-item>
<el-form-item v-if="assignMode === 'batch'" label="已选择">
<div class="text-gray-500">{{ batchAssignIds.length }} 条诊单记录</div>
@@ -767,7 +737,7 @@
</template>
<script setup lang="ts" name="tcmDiagnosis">
import { tcmDiagnosisLists, tcmDiagnosisDelete, tcmDiagnosisAssign, tcmDiagnosisGuahaoLogList, getAssistants, generateMiniProgramQrcode, generateOrderQrcode, getWechatChatRecords, addWechatChatRecord, deleteWechatChatRecord, getWechatExternalContact, fillIdCard, diagnosisReadonlyDetail } from '@/api/tcm'
import { tcmDiagnosisLists, tcmDiagnosisDelete, tcmDiagnosisAssign, tcmDiagnosisGuahaoLogList, getAssistants, generateMiniProgramQrcode, generateOrderQrcode, getWechatChatRecords, addWechatChatRecord, deleteWechatChatRecord, getWechatExternalContact, fillIdCard } from '@/api/tcm'
import { orderCreate } from '@/api/order'
import { cancelAppointment } from '@/api/doctor'
import { usePaging } from '@/hooks/usePaging'
@@ -782,15 +752,6 @@ import { useRoute, useRouter } from 'vue-router'
import { computed, defineAsyncComponent, onMounted, onUnmounted, watch } from 'vue'
import dayjs from 'dayjs'
import DaterangePicker from '@/components/daterange-picker/index.vue'
import RevisitNodeCell from './components/RevisitNodeCell.vue'
import { formatGender } from '@/utils/diag-display'
import {
normalizeRevisitDue,
REVISIT_DAYS_BUCKET_OPTIONS,
REVISIT_STATE_FILTER_OPTIONS,
revisitRowClassName,
type RevisitDue
} from '@/utils/revisitDue'
const EditPopup = defineAsyncComponent(() => import('./edit.vue'))
const DetailPopup = defineAsyncComponent(() => import('./detail.vue'))
@@ -837,12 +798,6 @@ const formData = reactive({
latest_assign_end_date: '' as string,
/** 未服务天数排序:desc=天数多到少 asc=少到多 */
sort_unserved_days: '' as '' | 'asc' | 'desc',
/** 复诊状态筛选:due(到期未挂号∪过号)|warning|booked|visited|contacted|no_days|pending,空=不限 */
revisit_state: '' as string,
/** 开药天数档筛选:14|21|28|30|other,空=不限 */
revisit_days_bucket: '' as string,
/** 复诊节点(药尽日)排序:asc=最早到期在前(NULL 置后) desc 反之;与 sort_unserved_days 互斥 */
sort_revisit_due: '' as '' | 'asc' | 'desc',
diagnosis_confirmed: '' as '' | '0' | '1',
appointment_date: '' as string,
has_appointment: '' as '' | '0' | '1',
@@ -943,13 +898,11 @@ function buildSharedDiagnosisFilterPayload(): Record<string, unknown> {
latest_appointment_end_date: formData.latest_appointment_end_date,
latest_appointment_channel_source: formData.latest_appointment_channel_source,
latest_assign_start_date: formData.latest_assign_start_date,
latest_assign_end_date: formData.latest_assign_end_date,
revisit_state: formData.revisit_state,
revisit_days_bucket: formData.revisit_days_bucket
latest_assign_end_date: formData.latest_assign_end_date
}
}
/** 顶部 Tab 角标 count 请求:带上共用筛选,再叠加各 Tab 专属条件(revisit_state 视为 Tab 条件,角标间互不影响) */
/** 顶部 Tab 角标 count 请求:带上共用筛选,再叠加各 Tab 专属条件 */
function buildDateCountRequestPayload(overrides: Record<string, unknown> = {}): Record<string, unknown> {
return {
page_no: 1,
@@ -962,8 +915,6 @@ function buildDateCountRequestPayload(overrides: Record<string, unknown> = {}):
pending_assign_order_month: '',
pending_assign_keyword: '',
sort_unserved_days: '',
revisit_state: '',
sort_revisit_due: '',
...overrides
}
}
@@ -1009,9 +960,6 @@ function clearSecondaryFiltersWhenPendingAssignWideSearch() {
formData.latest_assign_start_date = ''
formData.latest_assign_end_date = ''
formData.sort_unserved_days = ''
formData.revisit_state = ''
formData.revisit_days_bucket = ''
formData.sort_revisit_due = ''
formData.pending_assign_order_month = ''
activeTab.value = 'all'
if (kw1 !== '') {
@@ -1048,7 +996,6 @@ const handleDateTabClick = async (value: string) => {
formData.pending_booking = ''
formData.completed_appointment = ''
formData.has_appointment = ''
clearRevisitTabFilters()
clearLatestAppointmentFilters()
formData.appointment_date = value
pager.page = 1
@@ -1065,7 +1012,6 @@ const handlePendingBookingTabClick = async () => {
formData.completed_appointment = ''
formData.appointment_date = ''
formData.has_appointment = '0'
clearRevisitTabFilters()
clearLatestAppointmentFilters()
pager.page = 1
await getLists()
@@ -1081,7 +1027,6 @@ const handleCompletedVisitTabClick = async () => {
formData.completed_appointment = '1'
formData.has_appointment = ''
formData.appointment_date = ''
clearRevisitTabFilters()
clearLatestAppointmentFilters()
pager.page = 1
await getLists()
@@ -1094,7 +1039,6 @@ const handlePendingAssignTabClick = async () => {
formData.completed_appointment = ''
formData.has_appointment = ''
formData.appointment_date = ''
clearRevisitTabFilters()
clearLatestAppointmentFilters()
if (!formData.pending_assign_order_month) {
formData.pending_assign_order_month = dayjs().format('YYYY-MM')
@@ -1113,66 +1057,10 @@ const onPendingAssignOrderMonthChange = async (val: string | null) => {
fetchDateCounts()
}
/** 复诊状态 / 开药天数档 下拉选项(文案与请求值映射在 utils/revisitDue.ts) */
const revisitStateFilterOptions = REVISIT_STATE_FILTER_OPTIONS
const revisitDaysBucketOptions = REVISIT_DAYS_BUCKET_OPTIONS
/** 顶部「复诊到期」角标:revisit_state=due 的 count */
const revisitDueCount = ref<number | undefined>(undefined)
/** 切换其它顶部 Tab 时清掉复诊 chip 状态与其排序(revisit_days_bucket 属「更多筛选」,保留) */
const clearRevisitTabFilters = () => {
formData.revisit_state = ''
formData.sort_revisit_due = ''
}
/** 顶部「复诊到期」chip:到期未挂号 ∪ 过号未面诊,默认按药尽日升序(超期最多在前) */
const handleRevisitDueTabClick = async () => {
formData.pending_assign = ''
formData.pending_assign_order_month = ''
formData.pending_assign_keyword = ''
formData.pending_booking = ''
formData.completed_appointment = ''
formData.appointment_date = ''
formData.has_appointment = ''
clearLatestAppointmentFilters()
formData.revisit_state = 'due'
formData.sort_revisit_due = 'asc'
formData.sort_unserved_days = ''
pager.page = 1
await getLists()
fetchDateCounts()
}
/** 「更多筛选 → 复诊状态」下拉:与顶部日期 Tab 互斥(同 chip 语义),选中后不再默认当天挂号 */
const handleRevisitFilterChange = () => {
if (formData.revisit_state !== '') {
formData.appointment_date = ''
formData.pending_booking = ''
formData.completed_appointment = ''
const noSortYet = formData.sort_revisit_due === '' && formData.sort_unserved_days === ''
if (formData.revisit_state === 'due' && noSortYet) {
formData.sort_revisit_due = 'asc'
}
} else {
formData.sort_revisit_due = ''
}
doSearch()
}
/** 列表行 revisit_due → 规整对象(旧接口无字段时为 null,单元格显示「—」) */
const revisitDueOf = (row: any): RevisitDue | null => normalizeRevisitDue(row?.revisit_due)
/** 「复诊节点」行 1 的开方文案:已开方 / 已开方(处方已作废) / 未开方 */
const prescribedTextOf = (row: any): string => {
if (!row?.has_prescription) return '未开方'
return row.followup_rx_voided ? '已开方(处方已作废)' : '已开方'
}
// 获取各日期挂号数量 + 全部 + 待预约 + 已完成 + 待分配医助数量 + 复诊到期数量
// 获取各日期挂号数量 + 全部 + 待预约 + 已完成 + 待分配医助数量
const fetchDateCounts = async () => {
try {
const [yesterday, dayBefore, today, tomorrow, dayAfter, all, noApt, doneVisit, pending, revisitDue] = await Promise.all([
const [yesterday, dayBefore, today, tomorrow, dayAfter, all, noApt, doneVisit, pending] = await Promise.all([
tcmDiagnosisLists(
buildDateCountRequestPayload({ appointment_date: yesterdayStr.value, has_appointment: '' }) as any
),
@@ -1193,10 +1081,7 @@ const fetchDateCounts = async () => {
tcmDiagnosisLists(
buildDateCountRequestPayload({ completed_appointment: 1, has_appointment: '' }) as any
),
tcmDiagnosisLists(buildPendingAssignCountPayload() as any),
tcmDiagnosisLists(
buildDateCountRequestPayload({ revisit_state: 'due', has_appointment: '' }) as any
)
tcmDiagnosisLists(buildPendingAssignCountPayload() as any)
])
dateCounts.value = {
[yesterdayStr.value]: yesterday?.count ?? 0,
@@ -1209,7 +1094,6 @@ const fetchDateCounts = async () => {
pendingBookingCount.value = noApt?.count ?? 0
completedVisitCount.value = doneVisit?.count ?? 0
pendingAssignCount.value = pending?.count ?? 0
revisitDueCount.value = revisitDue?.count ?? 0
} catch (e) {
console.error('获取日期数量失败', e)
}
@@ -1368,11 +1252,12 @@ const handleTableSortChange = ({
prop: string
order: 'ascending' | 'descending' | null
}) => {
const dir: '' | 'asc' | 'desc' =
order === 'ascending' ? 'asc' : order === 'descending' ? 'desc' : ''
// 按列 prop 分派;两种排序后端互斥,切换列时清掉另一列
formData.sort_unserved_days = prop === 'unserved_days' ? dir : ''
formData.sort_revisit_due = prop === 'revisit_due_date' ? dir : ''
if (prop === 'unserved_days') {
formData.sort_unserved_days =
order === 'ascending' ? 'asc' : order === 'descending' ? 'desc' : ''
} else {
formData.sort_unserved_days = ''
}
pager.page = 1
getLists()
}
@@ -1426,9 +1311,6 @@ const handleReset = () => {
formData.latest_assign_start_date = ''
formData.latest_assign_end_date = ''
formData.sort_unserved_days = ''
formData.revisit_state = ''
formData.revisit_days_bucket = ''
formData.sort_revisit_due = ''
formData.diagnosis_confirmed = ''
formData.appointment_date = ''
formData.has_appointment = ''
@@ -1461,10 +1343,8 @@ const unservedDaysClass = (n: unknown) => {
return 'unserved-green'
}
// 行高亮优先级(方案 D3-c 默认 overdue_first):复诊超期/过号 > 未确认 > 未挂号
// 行高亮:未确认诊单优先,其次未挂号
const getRowClassName = ({ row }: { row: any }) => {
const revisitCls = revisitRowClassName(revisitDueOf(row))
if (revisitCls) return revisitCls
if (!isDiagnosisConfirmed(row)) return 'row-unconfirmed'
if (!row.has_appointment) return 'row-no-appointment'
return ''
@@ -1476,8 +1356,6 @@ const prescriptionRef = ref()
const appointmentRef = ref()
/** 从路由带 id 进入时,诊单弹窗为异步组件,需在 ref 就绪后再 open */
const pendingRouteDiagnosisId = ref<number | null>(null)
/** 路由 ?id=&action=appointment 深链(复诊到期弹窗「去挂号」):挂号弹窗同为异步组件,先暂存行再 open */
const pendingRouteAppointmentRow = ref<Record<string, any> | null>(null)
const userStore = useUserStore()
watch(
@@ -1492,53 +1370,6 @@ watch(
{ flush: 'post' }
)
watch(
[appointmentRef, pendingRouteAppointmentRow],
() => {
const row = pendingRouteAppointmentRow.value
const opener = appointmentRef.value as { open?: (row: any) => void } | undefined
if (!row || !opener?.open) return
pendingRouteAppointmentRow.value = null
handleAppointment(row)
},
{ flush: 'post' }
)
/**
* 深链打开挂号弹窗:优先用当前列表里的行(字段最全);不在本页时回退只读详情接口拼最小行
* (appointment.vue open() 只读 patient_id / patient_name / gender_desc / age)。
*/
const openAppointmentFromRoute = async (diagnosisId: number) => {
// 深链打开挂号弹窗前先校验挂号权限(与行内「预约」按钮 v-perms 同口径)
if (!hasPermission(['tcm.diagnosis/guahao'])) {
feedback.msgWarning('无挂号权限')
return
}
const inList = (pager.lists as any[]).find((r) => Number(r?.id) === diagnosisId)
if (inList) {
pendingRouteAppointmentRow.value = inList
return
}
try {
const res: any = await diagnosisReadonlyDetail({ id: diagnosisId })
const diag = res?.diagnosis
if (!diag || !diag.patient_id) {
feedback.msgWarning('未找到该诊单或患者信息不完整,无法打开挂号')
return
}
pendingRouteAppointmentRow.value = {
...diag,
id: diagnosisId,
patient_id: diag.patient_id,
patient_name: diag.patient_name || '',
gender_desc: formatGender(diag.gender),
age: diag.age ?? 0
}
} catch (e: any) {
feedback.msgWarning(e?.msg || e?.message || '加载诊单失败,无法打开挂号')
}
}
const watchCallVisible = ref(false)
const watchCallDiagnosisId = ref(0)
@@ -1783,13 +1614,13 @@ const handleConfirmAssign = async () => {
feedback.msgWarning('请选择医助')
return
}
assignLoading.value = true
try {
if (assignMode.value === 'single') {
// 单独指派
await tcmDiagnosisAssign({
id: currentRow.value.id,
await tcmDiagnosisAssign({
id: currentRow.value.id,
assistant_id: assignForm.value.assistant_id,
is_inherit: assignForm.value.is_inherit ? 1 : 0
})
@@ -2389,57 +2220,22 @@ const goReadonly = (row: any) => {
}
onMounted(() => {
// 默认展示当天挂号,突出重点
formData.appointment_date = todayStr.value
// 字典与列表并行,避免 await 字典阻塞首屏列表(LCP)
getDictOptions()
if (String(route.query.revisit_state ?? '') === 'due') {
// 复诊到期弹窗「查看全部」深链:直接激活「复诊到期」chip(内部会 getLists + fetchDateCounts)
void handleRevisitDueTabClick()
} else {
// 默认展示当天挂号,突出重点
formData.appointment_date = todayStr.value
getLists()
scheduleDeferredDateCounts()
}
getLists()
scheduleDeferredDateCounts()
silentListPollTimer = setInterval(silentRefreshListsAndDateCounts, SILENT_LIST_POLL_MS)
const raw = route.query.id
if (raw != null && raw !== '') {
const num = Number(raw)
if (!Number.isNaN(num) && num > 0) {
if (String(route.query.action ?? '') === 'appointment') {
// 复诊到期弹窗「去挂号」深链:等首屏列表回来后再找行,找不到走详情接口
void getListsPromiseForRoute().then(() => openAppointmentFromRoute(num))
} else {
pendingRouteDiagnosisId.value = num
}
}
if (!Number.isNaN(num)) pendingRouteDiagnosisId.value = num
}
})
/** onMounted 里 getLists() 已发起;等待首屏列表 loading 结束(最多 8s)再找行,失败/超时不阻断 */
const getListsPromiseForRoute = () =>
new Promise<void>((resolve) => {
if (!pager.loading) {
resolve()
return
}
let settled = false
const finish = () => {
if (settled) return
settled = true
stop()
resolve()
}
const stop = watch(
() => pager.loading,
(loading) => {
if (!loading) finish()
}
)
setTimeout(finish, 8000)
})
onUnmounted(() => {
if (silentListPollTimer != null) {
clearInterval(silentListPollTimer)
@@ -2517,21 +2313,6 @@ onUnmounted(() => {
}
}
.chip-revisit-due {
margin-left: 8px;
color: var(--el-color-danger);
background: var(--el-color-danger-light-9);
&:hover {
background: var(--el-color-danger-light-8);
}
&.active {
color: #fff;
background: var(--el-color-danger);
}
}
.chip-completed-visit {
margin-left: 8px;
color: var(--el-color-success);
@@ -2670,14 +2451,6 @@ onUnmounted(() => {
.latest-appointment-channel {
width: 170px;
}
.revisit-state-select {
width: 170px;
}
.revisit-days-bucket-select {
width: 130px;
}
}
.list-card {
@@ -2868,6 +2641,17 @@ onUnmounted(() => {
font-weight: 600;
}
.status-prescribed {
font-size: 13px;
color: #4A5DFF;
font-weight: 500;
}
.status-unprescribed {
font-size: 13px;
color: var(--el-text-color-placeholder);
}
/* 未服务天数(T3):null=灰;>=7=红;3-6=橙;<=2=绿 */
.unserved-days {
display: inline-block;
@@ -2912,6 +2696,33 @@ onUnmounted(() => {
}
}
.followup-cell {
display: flex;
flex-direction: column;
gap: 4px;
line-height: 1.35;
.followup-time {
font-size: 13px;
font-weight: 500;
color: var(--el-text-color-primary);
}
.followup-doctor {
font-size: 12px;
color: var(--el-text-color-secondary);
}
.followup-void-tag {
align-self: flex-start;
}
}
.followup-none {
font-size: 13px;
color: var(--el-text-color-placeholder);
}
.assistant-cell {
font-size: 13px;
color: var(--el-text-color-secondary);
@@ -2971,22 +2782,6 @@ onUnmounted(() => {
:deep(.el-table__row.row-no-appointment:hover > td) {
background: linear-gradient(90deg, rgba(var(--el-color-info-rgb), 0.08) 0%, transparent 100%) !important;
}
/* 复诊到期未挂号 / 过号未面诊:红色左边条(同 row-unconfirmed 结构,warning → danger) */
:deep(.el-table__row.row-revisit-overdue) {
border-left: 3px solid var(--el-color-danger);
background: linear-gradient(90deg, rgba(var(--el-color-danger-rgb), 0.06) 0%, transparent 100%) !important;
}
:deep(.el-table__row.row-revisit-overdue:hover > td) {
background: linear-gradient(90deg, rgba(var(--el-color-danger-rgb), 0.1) 0%, transparent 100%) !important;
}
/* 超期 ≥ severe_overdue_days:底色加深到 10%,悬停 14% */
:deep(.el-table__row.row-revisit-overdue.row-revisit-overdue-deep) {
border-left-color: #b91c1c;
background: linear-gradient(90deg, rgba(var(--el-color-danger-rgb), 0.1) 0%, transparent 100%) !important;
}
:deep(.el-table__row.row-revisit-overdue.row-revisit-overdue-deep:hover > td) {
background: linear-gradient(90deg, rgba(var(--el-color-danger-rgb), 0.14) 0%, transparent 100%) !important;
}
}
.record-list {
+9 -70
View File
@@ -25,7 +25,6 @@
formData.pending_assign !== '1' &&
formData.pending_booking !== '1' &&
formData.completed_appointment !== '1' &&
formData.revisit_state === '' &&
formData.appointment_date === tab.value
}
]"
@@ -41,13 +40,6 @@
待预约
<em v-if="pendingBookingCount !== undefined">{{ pendingBookingCount }}</em>
</span>
<span
:class="['dh5-chip', 'dh5-chip--revisit', { active: formData.revisit_state === 'due' }]"
@click="handleRevisitDueTabClick"
>
复诊到期
<em v-if="revisitDueCount !== undefined">{{ revisitDueCount }}</em>
</span>
<span
:class="['dh5-chip', 'dh5-chip--done', { active: formData.completed_appointment === '1' }]"
@click="handleCompletedVisitTabClick"
@@ -178,17 +170,13 @@
</div>
</div>
<!-- 复诊节点块(已开方或有复诊节点数据时显示;卡片头已有「已开方」标签,此处隐藏开方文案) -->
<div v-if="row.has_prescription || hasRevisitDue(revisitDueOf(row))" class="dh5-row dh5-row--followup">
<!-- 复诊块(仅已开方时显示) -->
<div v-if="row.has_prescription" class="dh5-row dh5-row--followup">
<span class="dh5-row-key">复诊</span>
<div class="dh5-row-val dh5-row-val--revisit">
<revisit-node-cell
compact
:due="revisitDueOf(row)"
:has-prescription="!!row.has_prescription"
:followup-doctor-name="row.followup_doctor_name || ''"
:prescribed-text="row.followup_rx_voided ? '处方作废' : ''"
/>
<div class="dh5-row-val">
<span>{{ row.followup_time_text || '—' }}</span>
<span class="dh5-meta-doctor">{{ row.followup_doctor_name || '—' }}</span>
<span v-if="row.followup_rx_voided" class="dh5-tag dh5-tag--gray">处方作废</span>
</div>
</div>
@@ -637,13 +625,6 @@ import {
import useUserStore from '@/stores/modules/user'
import { defineAsyncComponent, computed, reactive, ref, onMounted, onUnmounted } from 'vue'
import dayjs from 'dayjs'
import RevisitNodeCell from './components/RevisitNodeCell.vue'
import {
hasRevisitDue,
isRevisitDueHighlight,
normalizeRevisitDue,
type RevisitDue
} from '@/utils/revisitDue'
const EditPopup = defineAsyncComponent(() => import('./edit.vue'))
const DetailPopup = defineAsyncComponent(() => import('./detail.vue'))
@@ -704,9 +685,7 @@ const formData = reactive({
has_appointment: '' as '' | '0' | '1',
pending_assign: '' as '' | '1',
pending_booking: '' as '' | '1',
completed_appointment: '' as '' | '1',
/** 顶部「复诊到期」chip:due = 到期未挂号 ∪ 过号未面诊(后端 revisit_state) */
revisit_state: '' as '' | 'due'
completed_appointment: '' as '' | '1'
})
const showMoreFilter = ref(false)
@@ -761,7 +740,6 @@ const handleReset = () => {
formData.pending_assign = ''
formData.pending_booking = ''
formData.completed_appointment = ''
formData.revisit_state = ''
pager.page = 1
getLists()
fetchDateCounts()
@@ -789,7 +767,6 @@ const handleDateTabClick = async (value: string) => {
formData.pending_assign = ''
formData.pending_booking = ''
formData.completed_appointment = ''
formData.revisit_state = ''
formData.has_appointment = ''
formData.appointment_date = value
pager.page = 1
@@ -801,7 +778,6 @@ const handlePendingBookingTabClick = async () => {
formData.pending_assign = ''
formData.pending_booking = '1'
formData.completed_appointment = ''
formData.revisit_state = ''
formData.appointment_date = ''
formData.has_appointment = '0'
pager.page = 1
@@ -813,7 +789,6 @@ const handleCompletedVisitTabClick = async () => {
formData.pending_assign = ''
formData.pending_booking = ''
formData.completed_appointment = '1'
formData.revisit_state = ''
formData.has_appointment = ''
formData.appointment_date = ''
pager.page = 1
@@ -825,7 +800,6 @@ const handlePendingAssignTabClick = async () => {
formData.pending_assign = '1'
formData.pending_booking = ''
formData.completed_appointment = ''
formData.revisit_state = ''
formData.has_appointment = ''
formData.appointment_date = ''
pager.page = 1
@@ -833,27 +807,9 @@ const handlePendingAssignTabClick = async () => {
fetchDateCounts()
}
/** 顶部「复诊到期」chip:到期未挂号 ∪ 过号未面诊;后端按 revisit_state=due 过滤,排序默认药尽日升序 */
const handleRevisitDueTabClick = async () => {
formData.pending_assign = ''
formData.pending_booking = ''
formData.completed_appointment = ''
formData.has_appointment = ''
formData.appointment_date = ''
formData.revisit_state = 'due'
pager.page = 1
await getLists()
fetchDateCounts()
}
const revisitDueCount = ref<number | undefined>(undefined)
/** 列表行 revisit_due → 规整对象(旧接口无字段时为 null,不渲染复诊块) */
const revisitDueOf = (row: any): RevisitDue | null => normalizeRevisitDue(row?.revisit_due)
const fetchDateCounts = async () => {
try {
const [yesterday, dayBefore, today, tomorrow, dayAfter, all, noApt, doneVisit, pending, revisitDue] = await Promise.all([
const [yesterday, dayBefore, today, tomorrow, dayAfter, all, noApt, doneVisit, pending] = await Promise.all([
tcmDiagnosisLists({ appointment_date: yesterdayStr.value, page_no: 1, page_size: 1 }),
tcmDiagnosisLists({ appointment_date: dayBeforeStr.value, page_no: 1, page_size: 1 }),
tcmDiagnosisLists({ appointment_date: todayStr.value, page_no: 1, page_size: 1 }),
@@ -862,8 +818,7 @@ const fetchDateCounts = async () => {
tcmDiagnosisLists({ page_no: 1, page_size: 1 }),
tcmDiagnosisLists({ has_appointment: 0, page_no: 1, page_size: 1 }),
tcmDiagnosisLists({ completed_appointment: 1, page_no: 1, page_size: 1 }),
tcmDiagnosisLists({ pending_assign: 1, page_no: 1, page_size: 1 }),
tcmDiagnosisLists({ revisit_state: 'due', page_no: 1, page_size: 1 })
tcmDiagnosisLists({ pending_assign: 1, page_no: 1, page_size: 1 })
])
dateCounts.value = {
[yesterdayStr.value]: yesterday?.count ?? 0,
@@ -876,7 +831,6 @@ const fetchDateCounts = async () => {
pendingBookingCount.value = noApt?.count ?? 0
completedVisitCount.value = doneVisit?.count ?? 0
pendingAssignCount.value = pending?.count ?? 0
revisitDueCount.value = revisitDue?.count ?? 0
} catch (e) {
console.error('获取日期数量失败', e)
}
@@ -944,9 +898,7 @@ const isDiagnosisConfirmed = (row: any) => {
return records.length > 0 && records.some((r: any) => r.is_confirmed == 1)
}
// 卡片左边条优先级(同 PC 行高亮):复诊超期/过号 > 未确认 > 未挂号
const getCardClass = (row: any) => {
if (isRevisitDueHighlight(revisitDueOf(row))) return 'dh5-card--overdue'
if (!isDiagnosisConfirmed(row)) return 'dh5-card--unconfirmed'
if (!row.has_appointment) return 'dh5-card--noapt'
return ''
@@ -1630,8 +1582,6 @@ $dh5-card-bg: #ffffff;
.dh5-chip--booking.active { background: $dh5-warn; }
.dh5-chip--done.active { background: $dh5-success; }
.dh5-chip--pending.active { background: $dh5-danger; }
.dh5-chip--revisit { color: #b91c1c; background: rgba(239, 68, 68, 0.10); }
.dh5-chip--revisit.active { color: #fff; background: $dh5-danger; }
.dh5-quick {
display: flex;
@@ -1725,12 +1675,6 @@ $dh5-card-bg: #ffffff;
.dh5-card--unconfirmed::before { background: $dh5-danger; }
.dh5-card--noapt::before { background: $dh5-warn; }
/* 复诊到期未挂号 / 过号未面诊:左边条同 danger,外框与底色轻微染红以区分「未确认」 */
.dh5-card--overdue::before { background: $dh5-danger; }
.dh5-card--overdue {
border-color: rgba(239, 68, 68, 0.35);
background: linear-gradient(90deg, rgba(239, 68, 68, 0.05) 0%, $dh5-card-bg 60%);
}
.dh5-card-head {
display: flex;
@@ -1856,11 +1800,6 @@ $dh5-card-bg: #ffffff;
font-size: 12px;
}
/* 复诊节点块:单元格组件自带多行布局,取消外层 flex 换行间距 */
.dh5-row-val--revisit {
display: block;
}
/* 挂号块 - 状态色 */
.dh5-row--apt {
background: #fafbfc;
@@ -25,17 +25,6 @@
</span>
</el-tooltip>
<span v-else class="unserved-badge unserved-muted">从未打卡</span>
<!-- 复诊节点徽标:第 N 诊 · 药尽 MM-DD · 超期 N 天(接口无 revisit_due 字段时不渲染) -->
<el-tooltip
v-if="revisitBadgeLabel"
placement="bottom"
:disabled="!revisitTooltipText"
:content="revisitTooltipText"
>
<span :class="['unserved-badge', 'revisit-badge', revisitBadgeColorClass]">
{{ revisitBadgeLabel }}
</span>
</el-tooltip>
</div>
</div>
@@ -167,12 +156,6 @@ import { diagnosisReadonlyDetail } from '@/api/tcm'
import { getDoctorNotes } from '@/api/patient'
import { formatGender } from '@/utils/diag-display'
import { hasPermission } from '@/utils/perm'
import {
normalizeRevisitDue,
revisitBadgeText,
revisitStateColorClass,
revisitTooltipLines
} from '@/utils/revisitDue'
import PatientInfoCard from './components/PatientInfoCard.vue'
import PatientCaseCard from './components/PatientCaseCard.vue'
import DailyMatrix from './components/DailyMatrix.vue'
@@ -210,17 +193,6 @@ const unservedDays = computed<number | null>(() => {
})
const lastBloodAt = computed<string>(() => detail.value?.last_blood_record_at || '')
/** 复诊节点:readonlyDetail 顶层 revisit_due(兼容挂在 diagnosis 下);字段不存在 → null → 不渲染徽标 */
const revisitDue = computed(() =>
normalizeRevisitDue(detail.value?.revisit_due ?? detail.value?.diagnosis?.revisit_due)
)
const revisitBadgeLabel = computed(() => revisitBadgeText(revisitDue.value))
const revisitBadgeColorClass = computed(() => {
const due = revisitDue.value
return due ? revisitStateColorClass(due.state) : 'unserved-muted'
})
const revisitTooltipText = computed(() => revisitTooltipLines(revisitDue.value).join(';'))
/**
* 「未服务天数」着色规则(与 T3 列表一致):
* null/undefined → 灰;>=7 → 红;3-6 → 橙;<=2 → 绿
@@ -380,13 +352,6 @@ onMounted(fetchDetail)
border-color: #fecaca;
background: rgba(220, 38, 38, 0.08);
}
/* 复诊节点徽标专用:已约 / 已联系 */
&.unserved-blue {
color: #4a5dff;
border-color: #c7d2fe;
background: rgba(74, 93, 255, 0.08);
}
}
.empty-state {
+2
View File
@@ -79,6 +79,7 @@
</el-form-item>
</el-form>
</el-card>
<iam-personal />
<footer-btns>
<el-button type="primary" @click="handleSubmit">保存</el-button>
</footer-btns>
@@ -108,6 +109,7 @@
</template>
<script setup lang="ts" name="userSetting">
import IamPersonal from '@/components/iam-v2/personal.vue'
import type { FormInstance } from 'element-plus'
import { nextTick, onMounted, onUnmounted, ref, reactive } from 'vue'
import { Loading, CircleCheck, Connection } from '@element-plus/icons-vue'
+2 -34
View File
@@ -26,19 +26,15 @@ 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 = {}, migrationBlocked = vue.ref(false)) {
function chat(policy = {}) {
const requests = [], warnings = [], sdkCalls = []
const guard = moduleFrom(read('utils/appointment-call-guard.ts'))
const server = Object.fromEntries(['calls', 'call', 'groupCall', 'accept'].map(name => [name, async params => { sdkCalls.push({ name, params }) }]))
const server = Object.fromEntries(['calls', 'call', 'groupCall'].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) } }
@@ -148,31 +144,3 @@ 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, [])
})
@@ -1,214 +0,0 @@
const assert = require('node:assert/strict')
const fs = require('node:fs')
const path = require('node:path')
const test = require('node:test')
const ts = require('typescript')
const vue = require('vue')
const { parse, compileScript, compileTemplate } = require('@vue/compiler-sfc')
const { renderToString } = require('@vue/server-renderer')
const read = name => fs.readFileSync(path.join(__dirname, '../src', name), 'utf8')
function moduleFrom(source, dependencies = require, globals = {}) {
const code = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText
const module = { exports: {} }
new Function('require', 'module', 'exports', ...Object.keys(globals), code)(dependencies, module, module.exports, ...Object.values(globals))
return module.exports
}
const util = moduleFrom(read('utils/consultation-transcripts.ts'))
const row = (id, diagnosis = 101, text = `医生:记录${id}的问题\n患者:记录${id}的回答`) => ({
id, diagnosis_id: diagnosis, call_type: 2, status: 2, start_time: 1792444800,
start_time_text: '2026-10-20 09:20:00', end_time_text: '2026-10-20 09:30:00',
duration_text: '10分钟', transcript_text: text, transcription_status: 'completed', transcription_segment_count: 2
})
const drain = () => new Promise(resolve => setImmediate(resolve))
test('each call keeps its own transcript even when multiple visits have the same date', () => {
const rows = util.normalizeConsultationRecords([row(10), row(11), row(12, 202, '串诊单文字'), row(10), null, { id: 0 }], 101)
assert.deepEqual(rows.map(item => item.id), [11, 10])
assert.equal(rows[0].transcript_text, row(11).transcript_text)
assert.equal(rows[1].transcript_text, row(10).transcript_text)
assert.throws(() => util.normalizeConsultationRecords({ lists: [] }, 101), /格式异常/)
const legacy = util.normalizeConsultationRecords([{ id: '13', transcript_text: '医生:你好\r\n患者:你好' }], 101)[0]
assert.equal(legacy.diagnosis_id, 101)
assert.equal(legacy.transcript_text, '医生:你好\n患者:你好')
})
test('running, partial and failed calls retain their saved words without pretending they are complete', () => {
for (const [status, label] of [['running', '录音转写中'], ['partial', '文字部分保存'], ['failed', '文字生成失败']]) {
const record = { ...row(1), transcription_status: status }
assert.equal(util.consultationTranscriptStatus(record).label, label)
assert.equal(util.consultationTranscriptText(record), row(1).transcript_text)
}
assert.match(util.consultationTranscriptEmptyText({ ...row(1), transcription_status: 'running', transcript_text: '' }), /正在转写/)
assert.match(util.consultationTranscriptEmptyText({ status: 3 }), /未接听/)
assert.match(util.consultationTranscriptEmptyText({ status: 4 }), /已取消/)
assert.equal(util.consultationTranscriptStatus({ transcript_text: '历史已保存文字' }).label, '文字已保存')
})
function hookFixture(initial = 101) {
const id = vue.ref(initial), requests = [], cleanup = []
const hook = moduleFrom(read('hooks/useConsultationTranscripts.ts'), name => {
if (name === 'vue') return { ...vue, onBeforeUnmount: fn => cleanup.push(fn) }
if (name === '@/api/tcm') return { getConsultationTranscripts: (params, signal) => new Promise((resolve, reject) => requests.push({ params, signal, resolve, reject })) }
if (name === '@/utils/consultation-transcripts') return util
throw new Error(name)
})
const scope = vue.effectScope()
const state = scope.run(() => hook.useConsultationTranscripts(() => id.value))
return { id, requests, state, dispose() { cleanup.forEach(fn => fn()); scope.stop() } }
}
test('changing diagnosis clears the old words immediately and ignores late responses and failures', async () => {
const f = hookFixture()
assert.deepEqual(f.requests[0].params, { diagnosis_id: 101 })
f.id.value = 202
assert.equal(f.requests[0].signal.aborted, true)
assert.deepEqual(f.state.records.value, [])
f.requests[1].resolve([row(20, 202), row(99, 101, '不属于该诊单')])
await drain()
assert.deepEqual(f.state.records.value.map(item => item.id), [20])
f.requests[0].reject(new Error('旧诊单请求失败'))
await drain()
assert.deepEqual(f.state.records.value.map(item => item.id), [20])
assert.equal(f.state.error.value, '')
f.id.value = 303
assert.deepEqual(f.state.records.value, [])
f.dispose()
assert.equal(f.requests[2].signal.aborted, true)
f.requests[2].resolve([row(30, 303)])
await drain()
assert.deepEqual(f.state.records.value, [])
})
test('manual refresh preserves current records on failure and recovers on retry without writes', async () => {
const f = hookFixture()
f.requests[0].resolve([row(10)])
await drain()
const failed = f.state.refresh()
f.requests[1].reject(new Error('网络连接失败'))
await failed
assert.equal(f.state.records.value[0].id, 10)
assert.equal(f.state.error.value, '网络连接失败')
assert.equal(f.state.loading.value, false)
const retried = f.state.refresh()
f.requests[2].resolve([row(11)])
await retried
assert.equal(f.state.error.value, '')
assert.equal(f.state.records.value[0].id, 11)
f.id.value = 0
assert.equal(f.requests.length, 3)
assert.deepEqual(f.state.records.value, [])
f.dispose()
})
const filename = 'views/tcm/diagnosis/components/ConsultationTranscriptPanel.vue'
const { descriptor, errors } = parse(read(filename), { filename })
assert.deepEqual(errors, [])
const script = compileScript(descriptor, { id: 'consultation-transcript-panel' })
const template = compileTemplate({ source: descriptor.template.content, filename, id: 'consultation-transcript-panel', compilerOptions: { bindingMetadata: script.bindings } })
assert.deepEqual(template.errors, [])
const render = moduleFrom(template.code).render
function panelFixture(records, extra = {}) {
const props = vue.reactive({ diagnosisId: 101 })
const data = { records: vue.ref(records), loading: vue.ref(false), error: vue.ref(''), refresh() {}, ...extra }
const copied = [], notices = []
const scope = vue.effectScope()
const component = moduleFrom(script.content, name => {
if (name === 'vue') return vue
if (name === '@/hooks/useConsultationTranscripts') return { useConsultationTranscripts: () => data }
if (name === '@/utils/consultation-transcripts') return util
if (name === '@/utils/feedback') return { default: { msgWarning: text => notices.push(text), msgSuccess: text => notices.push(text) } }
if (name === '@element-plus/icons-vue') return { Refresh: { render: () => vue.h('svg') }, Search: {} }
throw new Error(name)
}, { navigator: { clipboard: { writeText: async text => { copied.push(text) } } } })
const state = scope.run(() => component.default.setup(props, { expose() {} }))
async function html() {
const app = vue.createSSRApp({ render: () => render({}, [], props, vue.proxyRefs(state)) })
app.directive('loading', { getSSRProps: () => ({}) })
for (const name of ['el-button', 'el-icon', 'el-pagination']) app.component(name, { setup: (_, { slots }) => () => vue.h('span', slots.default?.()) })
app.component('el-tag', { props: ['type'], setup: (props, { slots }) => () => vue.h('span', { 'data-type': props.type }, slots.default?.()) })
app.component('el-empty', { props: ['description'], setup: props => () => vue.h('p', { class: 'empty-description' }, props.description) })
app.component('el-alert', { props: ['title'], setup: props => () => vue.h('p', { role: 'alert' }, props.title) })
app.component('el-input', { setup: () => () => vue.h('input') })
return renderToString(app)
}
return { props, state, data, copied, notices, html, dispose: () => scope.stop() }
}
test('the real panel selects one call, copies only its complete text, and escapes transcript HTML', async () => {
const f = panelFixture([row(12, 101, ''), row(11, 101, '医生:<img src=x onerror=alert(1)>\n患者:本次回答'), row(10), row(99, 202, '串诊单文字')])
assert.equal(f.state.selectedId.value, 11)
let html = await f.html()
assert.match(html, /&lt;img src=x onerror=alert\(1\)&gt;/)
assert.doesNotMatch(html, /<img src=x|串诊单文字/)
assert.doesNotMatch(html.match(/<pre[^>]*>([\s\S]*?)<\/pre>/)[1], /记录10/)
await f.state.copyTranscript()
assert.deepEqual(f.copied, ['医生:<img src=x onerror=alert(1)>\n患者:本次回答'])
f.state.selectedId.value = 10
assert.equal(f.state.selectedText.value, row(10).transcript_text)
f.data.records.value = [row(13), row(11), row(10)]
assert.equal(f.state.selectedId.value, 10)
f.state.search.value = '记录13'
assert.equal(f.state.selectedId.value, 13)
assert.equal(f.state.filteredRecords.value.length, 1)
f.props.diagnosisId = 202
assert.equal(f.state.selectedText.value, '')
assert.doesNotMatch(await f.html(), /记录13的问题|本次回答/)
f.dispose()
})
test('empty, failed and partial transcription states remain explicit in the rendered panel', async () => {
for (const status of ['running', 'partial', 'failed']) {
const f = panelFixture([{ ...row(1), transcription_status: status }])
const html = await f.html()
assert.match(html, /已保存|刷新查看最新/)
assert.match(html, /记录1的问题/)
f.dispose()
}
const missing = panelFixture([row(1, 101, '')])
assert.match(await missing.html(), /本次面诊暂无已保存的文字对话/)
missing.dispose()
const none = panelFixture([])
assert.match(await none.html(), /该诊单暂无面诊通话记录/)
none.dispose()
const failed = panelFixture([], { error: vue.ref('无权访问该诊单') })
assert.match(await failed.html(), /无权访问该诊单/)
assert.doesNotMatch(await failed.html(), /该诊单暂无面诊通话记录/)
failed.dispose()
})
test('the new tab is permission gated, lazy and absent when the drawer is closed', async () => {
const { descriptor } = parse(read('views/tcm/diagnosis/edit.vue'))
const editScript = compileScript(descriptor, { id: 'diagnosis-edit-transcript' })
const pane = descriptor.template.content.match(/<el-tab-pane\s+v-if="hasCallTranscriptPermission"[\s\S]*?<\/el-tab-pane>/)[0]
const compiled = compileTemplate({ source: pane, filename: 'edit-transcript-tab.vue', id: 'edit-transcript', compilerOptions: { bindingMetadata: editScript.bindings } })
assert.deepEqual(compiled.errors, [])
const renderPane = moduleFrom(compiled.code).render
async function html(allowed, active, visible, id) {
const state = { hasCallTranscriptPermission: allowed, activeTab: active, visible, formData: { id }, ConsultationTranscriptPanel: { props: ['diagnosisId'], setup: props => () => vue.h('div', { 'data-diagnosis': props.diagnosisId }, '真实转写面板入口') } }
const app = vue.createSSRApp({ render: () => renderPane({}, [], {}, state) })
app.component('el-tab-pane', { props: ['disabled', 'label'], setup: (props, { slots }) => () => vue.h('section', { 'data-disabled': String(props.disabled) }, [props.label, slots.default?.()]) })
app.component('el-empty', { props: ['description'], setup: props => () => vue.h('p', props.description) })
return renderToString(app)
}
assert.doesNotMatch(await html(false, 'callTranscript', true, 101), /面诊文字对话/)
assert.doesNotMatch(await html(true, 'basic', true, 101), /真实转写面板入口/)
assert.doesNotMatch(await html(true, 'callTranscript', false, 101), /真实转写面板入口/)
assert.match(await html(true, 'callTranscript', true, 101), /data-diagnosis="101"/)
assert.match(await html(true, 'callTranscript', true, ''), /data-disabled="true"/)
})
test('the read helper sends the exact diagnosis and abort signal without canceling replay requests', async () => {
let request
const api = moduleFrom(read('api/tcm.ts'), name => {
if (name === '@/utils/request') return { default: { get: (...args) => { request = args; return Promise.resolve([]) } } }
throw new Error(name)
})
const controller = new AbortController()
await api.getConsultationTranscripts({ diagnosis_id: 101 }, controller.signal)
assert.equal(request[0].url, '/tcm.diagnosis/getCallRecords')
assert.deepEqual(request[0].params, { diagnosis_id: 101 })
assert.equal(request[0].signal, controller.signal)
assert.equal(request[1].ignoreCancelToken, true)
})
@@ -1,419 +0,0 @@
const assert = require('node:assert/strict')
const fs = require('node:fs')
const path = require('node:path')
const test = require('node:test')
const ts = require('typescript')
const vue = require('vue')
const { renderToString } = require('@vue/server-renderer')
const { parse, compileScript, compileTemplate } = require('@vue/compiler-sfc')
const read = name => fs.readFileSync(path.join(__dirname, '../src', name), 'utf8')
function moduleFrom(source, dependencies = require, globals = {}) {
const code = ts.transpileModule(source, {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 }
}).outputText
const module = { exports: {} }
new Function('require', 'module', 'exports', ...Object.keys(globals), code)(dependencies, module, module.exports, ...Object.values(globals))
return module.exports
}
const policy = moduleFrom(read('utils/doctor-web-consultation.ts'))
const cutoff = Date.parse('2026-10-24T00:00:00+08:00')
const schedule = {
cutoff_at: '2026-10-24T00:00:00+08:00',
approaching_at: '2026-10-22T00:00:00+08:00',
urgent_at: '2026-10-23T00:00:00+08:00',
server_time: cutoff / 1000
}
const doctor = { root: 0, role_ids: [1] }
const installer = {
platform: 'windows_x64', label: 'Windows 64位',
url: 'https://cdn.example.test/doctor-setup.exe',
filename: 'doctor-setup.exe', sha256: 'a'.repeat(64), size: 171474334, type: 'inno_setup'
}
test('doctors can use the web throughout October 23, and stop exactly at Shanghai midnight', () => {
assert.equal(Date.parse(schedule.cutoff_at), Date.parse('2026-10-23T16:00:00Z'))
assert.equal(policy.isDoctorWebConsultationBlocked(doctor, schedule, cutoff - 1), false)
assert.equal(policy.isDoctorWebConsultationBlocked(doctor, schedule, cutoff), true)
assert.equal(policy.isDoctorWebConsultationBlocked(doctor, schedule, cutoff + 1), true)
for (const user of [{ root: 1, role_ids: [1] }, { role_ids: [2] }, { role_ids: [3, 7, 8] }, {}]) {
assert.equal(policy.isDoctorWebConsultationBlocked(user, schedule, cutoff), false)
}
assert.equal(policy.isDoctorWebConsultationBlocked({ role_ids: ['2', '1'] }, schedule, cutoff), true)
})
test('the mounted page changes at midnight, rechecks clicks and keeps a previously synchronized clock', () => {
let clock = cutoff - 10000
const mounted = [], unmounted = [], warnings = []
let tick
const listeners = new Map()
const surface = { addEventListener: (name, callback) => listeners.set(name, callback), removeEventListener: name => listeners.delete(name) }
// The profile was fetched earlier; opening a new page must not reset to that old server timestamp.
const store = vue.reactive({ userInfo: { ...doctor, web_consultation_policy: schedule }, serverTimeOffsetMs: 5000 })
const hook = moduleFrom(read('hooks/useDoctorWebConsultation.ts'), name => {
if (name === 'vue') return { ...vue, onMounted: fn => mounted.push(fn), onUnmounted: fn => unmounted.push(fn) }
if (name === '@/stores/modules/user') return { default: () => store }
if (name === '@/api/app') return { getDoctorWebConsultationPolicy: () => new Promise(() => {}) }
if (name === '@/utils/feedback') return { default: { msgWarning: text => warnings.push(text) } }
if (name === '@/utils/doctor-web-consultation') return policy
throw new Error(`Unexpected import: ${name}`)
}, { Date: { now: () => clock }, window: surface, document: surface, setInterval: fn => { tick = fn; return 1 }, clearInterval: () => { tick = undefined } })
const state = hook.useDoctorWebConsultation()
mounted.forEach(fn => fn())
assert.equal(state.webConsultationBlocked.value, false)
clock = cutoff - 5000
tick()
assert.equal(state.webConsultationBlocked.value, true)
assert.equal(state.ensureWebConsultationAllowed(), false)
assert.match(warnings[0], /桌面应用/)
clock = cutoff - 5001
listeners.get('focus')()
assert.equal(state.webConsultationBlocked.value, false)
clock = cutoff - 5000
// Even if a suspended tab's timer has not fired, the click itself checks the clock.
assert.equal(state.ensureWebConsultationAllowed(), false)
const laterPage = hook.useDoctorWebConsultation()
assert.equal(laterPage.webConsultationBlocked.value, true)
unmounted.forEach(fn => fn())
assert.equal(listeners.size, 0)
assert.equal(tick, undefined)
})
test('the shared system notice keeps installer downloads available throughout all reminder phases', async () => {
const { descriptor } = parse(read('components/doctor-web-consultation-notice/index.vue'))
const script = compileScript(descriptor, { id: 'doctor-web-notice' })
const template = compileTemplate({ source: descriptor.template.content, filename: 'notice.vue', id: 'doctor-web-notice', compilerOptions: { bindingMetadata: script.bindings } })
assert.deepEqual(template.errors, [])
const render = moduleFrom(template.code).render
async function markup(date, packages = [installer], failed = false, loading = false) {
const component = moduleFrom(script.content, name => {
if (name === 'vue') return vue
if (name === '@/hooks/useDoctorWebConsultation') return { useDoctorWebConsultation: () => ({ consultationReminder: vue.ref(policy.doctorWebConsultationReminder(schedule, Date.parse(date))), policyLoadFailed: vue.ref(false), refreshConsultationPolicy() {} }) }
if (name === '@/hooks/useDesktopWorkstationDownloads') return {
useDesktopWorkstationDownloads: () => ({ downloads: vue.ref({ version: '1.4.8', packages }), downloadsLoading: vue.ref(loading), downloadsFailed: vue.ref(failed), loadDownloads() {} })
}
if (name === '@element-plus/icons-vue') return { Download: { render: () => vue.h('svg') } }
throw new Error(name)
})
const state = component.default.setup({}, { expose() {} })
const app = vue.createSSRApp({ render: () => render({}, [], {}, vue.proxyRefs(state)) })
app.component('el-alert', { props: ['title', 'type', 'closable'], setup: (props, { slots }) => () => vue.h('section', { role: 'alert', 'data-type': props.type, 'data-closable': String(props.closable) }, [vue.h('strong', props.title), slots.default?.()]) })
app.component('el-icon', { setup: (_, { slots }) => () => vue.h('span', slots.default?.()) })
app.component('el-button', { setup: (_, { slots }) => () => vue.h('button', slots.default?.()) })
return renderToString(app)
}
const before = await markup('2026-10-20T10:00:00+08:00')
assert.match(before, /2026年10月24日00:00(北京时间)/)
assert.match(before, /接诊台、问诊列表/)
assert.match(before, /data-closable="false"/)
assert.match(before, /data-type="info"/)
assert.match(before, /href="https:\/\/cdn.example.test\/doctor-setup.exe"/)
assert.match(before, /下载 Windows 64位安装包/)
assert.match(before, /当前版本 v1.4.8/)
assert.match(before, /Windows 10 1809/)
const approaching = await markup('2026-10-22T12:00:00+08:00')
assert.match(approaching, /data-type="warning"/)
assert.match(approaching, /距网页端面诊停用还有 1天12小时/)
const lastDay = await markup('2026-10-23T23:59:59+08:00')
assert.match(lastDay, /最后提醒/)
assert.match(lastDay, /不足1分钟/)
assert.match(lastDay, /data-type="error"/)
const after = await markup('2026-10-24T00:00:00+08:00')
assert.match(after, /网页端面诊已停用/)
assert.match(after, /桌面应用/)
assert.match(after, /data-type="error"/)
assert.match(after, /href="https:\/\/cdn.example.test\/doctor-setup.exe"/)
assert.doesNotMatch(after, /距网页端面诊停用还有/)
const missing = await markup('2026-10-20T10:00:00+08:00', [])
assert.match(missing, /安装包暂未发布/)
assert.match(missing, /重新获取/)
assert.doesNotMatch(missing, /href=/)
assert.match(await markup('2026-10-20T10:00:00+08:00', [], true), /安装包加载失败/)
assert.match(await markup('2026-10-20T10:00:00+08:00', [], false, true), /正在获取安装包/)
})
test('reminders switch exactly at Beijing midnight on October 22, 23 and 24', () => {
for (const [boundary, previous, current] of [
['2026-10-22T00:00:00+08:00', 'prepare', 'approaching'],
['2026-10-23T00:00:00+08:00', 'approaching', 'last_day'],
['2026-10-24T00:00:00+08:00', 'last_day', 'expired']
]) {
const time = Date.parse(boundary)
assert.equal(policy.doctorWebConsultationReminder(schedule, time - 1).phase, previous)
assert.equal(policy.doctorWebConsultationReminder(schedule, time).phase, current)
}
assert.equal(policy.doctorWebConsultationReminder(schedule, Date.parse('2026-10-23T15:59:59Z')).phase, 'last_day')
assert.equal(policy.doctorWebConsultationReminder(schedule, Date.parse('2026-10-23T16:00:00Z')).phase, 'expired')
})
test('an open page advances through each reminder stage without refreshing or changing the cutoff', () => {
let clock = Date.parse('2026-10-21T23:59:59+08:00')
let tick
const mounted = [], unmounted = []
const surface = { addEventListener() {}, removeEventListener() {} }
const hook = moduleFrom(read('hooks/useDoctorWebConsultation.ts'), name => {
if (name === 'vue') return { ...vue, onMounted: fn => mounted.push(fn), onUnmounted: fn => unmounted.push(fn) }
if (name === '@/stores/modules/user') return { default: () => ({ userInfo: { ...doctor, web_consultation_policy: schedule }, serverTimeOffsetMs: 0 }) }
if (name === '@/api/app') return { getDoctorWebConsultationPolicy: () => new Promise(() => {}) }
if (name === '@/utils/feedback') return { default: { msgWarning() {} } }
if (name === '@/utils/doctor-web-consultation') return policy
throw new Error(name)
}, { Date: { now: () => clock }, window: surface, document: surface, setInterval: fn => { tick = fn; return 1 }, clearInterval() {} })
const state = hook.useDoctorWebConsultation()
mounted.forEach(fn => fn())
assert.equal(state.consultationReminder.value.phase, 'prepare')
for (const [day, phase] of [[22, 'approaching'], [23, 'last_day'], [24, 'expired']]) {
clock = Date.parse(`2026-10-${day}T00:00:00+08:00`)
tick()
assert.equal(state.consultationReminder.value.phase, phase)
assert.equal(state.webConsultationBlocked.value, day === 24)
}
unmounted.forEach(fn => fn())
})
function shiftedSchedule(cutoffAt, serverTime, approachingHours = 48, urgentHours = 24) {
const time = Date.parse(cutoffAt)
return {
cutoff_at: cutoffAt,
approaching_at: new Date(time - approachingHours * 3600000).toISOString(),
urgent_at: new Date(time - urgentHours * 3600000).toISOString(),
server_time: serverTime / 1000
}
}
test('arbitrary configured dates and hours drive announcements, reminders and enforcement to the second', () => {
const custom = shiftedSchedule('2027-06-15T14:35:12+08:00', cutoff, 10, 2)
const end = Date.parse(custom.cutoff_at)
const approaching = Date.parse(custom.approaching_at)
const urgent = Date.parse(custom.urgent_at)
assert.deepEqual(policy.normalizeDoctorWebConsultationPolicy(custom), custom)
for (const [time, phase] of [[approaching - 1, 'prepare'], [approaching, 'approaching'], [urgent - 1, 'approaching'], [urgent, 'last_day'], [end - 1, 'last_day'], [end, 'expired']]) {
const reminder = policy.doctorWebConsultationReminder(custom, time)
assert.equal(reminder.phase, phase)
assert.match(reminder.description, /2027年06月15日14:35:12(北京时间)/)
assert.doesNotMatch(reminder.description, /2026年|今天结束|最后一天/)
assert.equal(policy.isDoctorWebConsultationBlocked(doctor, custom, time), time >= end)
}
assert.equal(policy.doctorWebConsultationDate({ ...custom, cutoff_at: '2027-06-15T06:35:12Z' }), '2027年06月15日14:35:12(北京时间)')
assert.equal(policy.isDoctorWebConsultationBlocked(doctor, undefined, end), false)
assert.equal(policy.doctorWebConsultationReminder().countdown, '')
for (const invalid of [null, {}, { ...custom, cutoff_at: 'invalid' }, { ...custom, approaching_at: '2027-06-16T00:00:00+08:00' }, { ...custom, server_time: 0 }, { ...custom, urgent_at: '2027-06-15 13:00:00' }]) {
assert.equal(policy.normalizeDoctorWebConsultationPolicy(invalid), undefined)
}
})
test('open notices share live configuration, poll every minute and refresh on focus with failure recovery', async () => {
let clock = Date.parse('2027-06-15T14:00:00+08:00')
let requests = 0, resolveRequest, rejectRequest
const mounted = [], unmounted = [], ticks = new Set(), listeners = new Map()
const surface = {
visibilityState: 'visible',
addEventListener(name, callback) {
if (!listeners.has(name)) listeners.set(name, new Set())
listeners.get(name).add(callback)
},
removeEventListener(name, callback) { listeners.get(name)?.delete(callback) }
}
const store = vue.reactive({ userInfo: { ...doctor, web_consultation_policy: schedule }, serverTimeOffsetMs: 0 })
const hook = moduleFrom(read('hooks/useDoctorWebConsultation.ts'), name => {
if (name === 'vue') return { ...vue, onMounted: fn => mounted.push(fn), onUnmounted: fn => unmounted.push(fn) }
if (name === '@/stores/modules/user') return { default: () => store }
if (name === '@/api/app') return {
getDoctorWebConsultationPolicy: () => {
requests++
return new Promise((resolve, reject) => { resolveRequest = resolve; rejectRequest = reject })
}
}
if (name === '@/utils/feedback') return { default: { msgWarning() {} } }
if (name === '@/utils/doctor-web-consultation') return policy
throw new Error(name)
}, {
Date: { now: () => clock }, window: surface, document: surface,
setInterval: fn => { ticks.add(fn); return fn }, clearInterval: fn => ticks.delete(fn)
})
const first = hook.useDoctorWebConsultation()
const second = hook.useDoctorWebConsultation()
assert.equal(first.webConsultationBlocked.value, true)
mounted.forEach(fn => fn())
assert.equal(requests, 1)
const initial = first.refreshConsultationPolicy()
assert.equal(second.refreshConsultationPolicy(), initial)
resolveRequest(shiftedSchedule('2027-06-15T14:35:12+08:00', clock, 10, 2))
await initial
assert.equal(first.webConsultationBlocked.value, false)
assert.equal(second.webConsultationBlocked.value, false)
assert.match(first.consultationReminder.value.description, /2027年06月15日14:35:12/)
clock += 59000
ticks.forEach(fn => fn())
assert.equal(requests, 1)
clock += 1000
ticks.forEach(fn => fn())
assert.equal(requests, 2)
const polled = first.refreshConsultationPolicy()
resolveRequest(shiftedSchedule('2027-06-15T13:59:00+08:00', clock))
await polled
assert.equal(second.webConsultationBlocked.value, true)
assert.match(second.webConsultationMessage.value, /2027年06月15日13:59/)
listeners.get('focus').forEach(fn => fn())
assert.equal(requests, 3)
const failed = first.refreshConsultationPolicy()
rejectRequest(new Error('offline'))
await failed
assert.equal(first.policyLoadFailed.value, true)
assert.equal(second.webConsultationBlocked.value, true)
listeners.get('visibilitychange').forEach(fn => fn())
assert.equal(requests, 4)
const retry = second.refreshConsultationPolicy()
resolveRequest(shiftedSchedule('2028-01-01T12:30:00+08:00', clock))
await retry
assert.equal(first.policyLoadFailed.value, false)
assert.equal(second.webConsultationBlocked.value, false)
assert.match(first.consultationReminder.value.description, /2028年01月01日12:30/)
const invalid = first.refreshConsultationPolicy()
resolveRequest({ cutoff_at: 'invalid' })
await invalid
assert.equal(first.policyLoadFailed.value, true)
assert.match(first.consultationReminder.value.description, /2028年01月01日12:30/)
unmounted.forEach(fn => fn())
assert.equal(ticks.size, 0)
assert.ok([...listeners.values()].every(callbacks => callbacks.size === 0))
})
test('the runtime policy endpoint is public and requests a fresh response', async () => {
let transport
const api = moduleFrom(read('api/app.ts'), name => {
if (name === '@/utils/request') return { default: { get: (...args) => { transport = args; return Promise.resolve(schedule) } } }
throw new Error(name)
})
assert.deepEqual(await api.getDoctorWebConsultationPolicy(), schedule)
assert.equal(transport[0].url, '/config/doctorWebConsultation')
assert.ok(transport[0].params._t > 0)
assert.equal(transport[1].withToken, false)
})
test('installer requests are public, deduplicated across notices, cached, and recover after failure', async () => {
let requests = 0, resolve
const mounted = [], unmounted = []
const api = { getDesktopWorkstationDownloads: () => { requests++; return new Promise(done => { resolve = done }) } }
const mod = moduleFrom(read('hooks/useDesktopWorkstationDownloads.ts'), name => {
if (name === 'vue') return { ...vue, onMounted: fn => mounted.push(fn), onUnmounted: fn => unmounted.push(fn) }
if (name === '@/api/setting/desktop_workstation') return api
throw new Error(name)
}, { window: { addEventListener() {}, removeEventListener() {} } })
const first = mod.useDesktopWorkstationDownloads()
const second = mod.useDesktopWorkstationDownloads()
const pending = first.loadDownloads()
assert.equal(second.loadDownloads(), pending)
assert.equal(requests, 1)
resolve({ version: '1.4.8', packages: [installer] })
await pending
await second.loadDownloads()
assert.equal(requests, 1)
assert.equal(second.downloads.value.packages.length, 1)
api.getDesktopWorkstationDownloads = async () => { throw new Error('offline') }
await first.loadDownloads(true)
assert.equal(first.downloadsFailed.value, true)
assert.equal(first.downloads.value.packages.length, 1)
api.getDesktopWorkstationDownloads = async () => ({ version: '1.4.9', packages: [installer] })
await second.loadDownloads(true)
assert.equal(first.downloadsFailed.value, false)
assert.equal(first.downloads.value.version, '1.4.9')
assert.deepEqual(mod.normalizeDesktopDownloads({ version: '1', packages: [null, { ...installer, url: 'javascript:alert(1)' }, { ...installer, url: 'https://user:pass@example.test/setup.exe' }, { ...installer, sha256: '' }] }).packages, [])
assert.equal(mod.normalizeDesktopDownloads({ version: '1', packages: [installer, installer] }).packages.length, 1)
unmounted.forEach(fn => fn())
let transport
const apiModule = moduleFrom(read('api/setting/desktop_workstation.ts'), name => {
if (name === '@/utils/request') return { default: { get: (...args) => { transport = args; return Promise.resolve({}) } } }
throw new Error(name)
})
await apiModule.getDesktopWorkstationDownloads()
assert.equal(transport[0].url, '/setting.desktop_workstation/downloads')
assert.equal(transport[1].withToken, false)
})
test('consultation entries retain the shared notice while the patient list compiles without it', () => {
for (const name of ['views/patient/reception/index.vue', 'views/tcm/diagnosis/index.vue', 'views/tcm/appointment/list.vue', 'views/tcm/appointment/list_h5.vue']) {
const { descriptor, errors } = parse(read(name), { filename: name })
assert.deepEqual(errors, [])
const script = compileScript(descriptor, { id: name })
assert.equal(script.bindings.DoctorWebConsultationNotice, name === 'views/tcm/diagnosis/index.vue' ? undefined : 'setup-const')
assert.deepEqual(compileTemplate({ source: descriptor.template.content, filename: name, id: name, compilerOptions: { bindingMetadata: script.bindings } }).errors, [])
}
})
test('reception makes doctor cutoff visible and blocks calls while preserving administrator and assistant access', async () => {
const { descriptor } = parse(read('views/patient/reception/index.vue'))
const script = compileScript(descriptor, { id: 'reception-cutoff' })
const template = compileTemplate({ source: descriptor.template.content, filename: 'reception.vue', id: 'reception-cutoff', compilerOptions: { bindingMetadata: script.bindings } })
assert.deepEqual(template.errors, [])
const render = moduleFrom(template.code).render
const passthrough = { setup: (_, { slots }) => () => vue.h('div', slots.default?.()) }
const lifecycle = { ...vue, onMounted() {}, onUnmounted() {}, defineAsyncComponent: () => passthrough }
let clock = cutoff - 1
const store = vue.reactive({ userInfo: { ...doctor, web_consultation_policy: schedule }, serverTimeOffsetMs: 0 })
const warnings = [], requests = [], opened = []
const feedback = { msgWarning: message => warnings.push(message) }
const hook = moduleFrom(read('hooks/useDoctorWebConsultation.ts'), name => {
if (name === 'vue') return lifecycle
if (name === '@/stores/modules/user') return { default: () => store }
if (name === '@/api/app') return {}
if (name === '@/utils/feedback') return { default: feedback }
if (name === '@/utils/doctor-web-consultation') return policy
throw new Error(name)
}, { Date: { now: () => clock } })
let onSignature = () => ({})
const state = moduleFrom(script.content, name => {
if (name === 'vue') return lifecycle
if (name === '@/hooks/useDoctorWebConsultation') return hook
if (name === '@/api/patient' || name === '@/api/doctor') return {}
if (name === '@/api/tcm') return { getCallSignature: async params => { requests.push(params); return onSignature() } }
if (name === '@/utils/feedback') return { default: feedback }
if (name === '@/utils/diag-display') return { formatGender: () => '男' }
if (name === '@/utils/diabetes-discovery-display') return {}
if (name === '@element-plus/icons-vue') return Object.fromEntries(['Phone', 'Search', 'ChatDotRound', 'Loading'].map(key => [key, passthrough]))
if (name.endsWith('.vue')) return { default: passthrough }
throw new Error(name)
}, { ref: vue.ref, computed: vue.computed, watch: vue.watch }).default.setup({}, { expose() {} })
const row = { id: 90, patient_id: 50, source_patient_id: 50, diagnosis_id: 70, patient_name: '测试患者', appointment_type: 'video' }
state.queue.value = [row]
state.chatDialogRef.value = { open: value => opened.push(value) }
async function markup() {
const app = vue.createSSRApp({ render: () => render({}, [], {}, vue.proxyRefs(state)) })
app.config.warnHandler = () => {}
for (const name of ['el-input', 'el-icon', 'el-tag', 'el-empty', 'el-dialog', 'el-button']) app.component(name, passthrough)
app.component('el-tooltip', { props: ['content'], setup: (props, { slots }) => () => vue.h('div', { 'data-tooltip': props.content }, slots.default?.()) })
for (const name of ['loading', 'perms']) app.directive(name, { getSSRProps: () => ({}) })
return renderToString(app)
}
assert.match(await markup(), /class="row-icon-btn call" aria-label="发起通话"/)
await state.handleCall(row)
assert.equal(requests.length, 1)
assert.equal(opened.length, 1)
// A signature that returns after the deadline must never open the calling window.
onSignature = () => { clock = cutoff; return {} }
await state.handleCall(row)
assert.equal(requests.length, 2)
assert.equal(opened.length, 1)
const expired = await markup()
assert.match(expired, /class="row-icon-btn call" disabled aria-label="[^"]*桌面应用/)
assert.match(expired, /<span>已停用<\/span>/)
assert.match(expired, /data-tooltip="[^"]*桌面应用/)
assert.doesNotMatch(expired, /class="row-icon-btn notify" disabled/)
await state.handleCall(row)
assert.equal(requests.length, 2)
assert.equal(opened.length, 1)
assert.equal(warnings.length, 2)
for (const identity of [{ root: 1, role_ids: [1] }, { root: 0, role_ids: [2] }]) {
Object.assign(store.userInfo, identity)
assert.match(await markup(), /class="row-icon-btn call" aria-label="发起通话"/)
assert.doesNotMatch(await markup(), /<span>已停用<\/span>/)
await state.handleCall(row)
}
assert.equal(requests.length, 4)
assert.equal(opened.length, 3)
})
@@ -1,253 +0,0 @@
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 root = path.resolve(__dirname, '..')
const apiPath = path.join(root, 'src/api/setting/prescription_ai_visibility.ts')
const pagePath = path.join(root, 'src/views/setting/prescription_ai_visibility/index.vue')
const { descriptor, errors } = parse(fs.readFileSync(pagePath, 'utf8'), { filename: pagePath })
assert.deepEqual(errors, [])
const script = compileScript(descriptor, { id: 'prescription-ai-visibility' })
function moduleFrom(source, dependencies) {
const compiled = ts.transpileModule(source, {
compilerOptions: {
target: ts.ScriptTarget.ES2022,
module: ts.ModuleKind.CommonJS,
esModuleInterop: true
}
}).outputText
const module = { exports: {} }
new Function('require', 'module', 'exports', compiled)(dependencies, module, module.exports)
return module.exports
}
const makeApi = (request) =>
moduleFrom(fs.readFileSync(apiPath, 'utf8'), (name) => {
assert.equal(name, '@/utils/request')
return request
})
const tick = () => new Promise((resolve) => setImmediate(resolve))
const deferred = () => {
let resolve
let reject
const promise = new Promise((yes, no) => {
resolve = yes
reject = no
})
return { promise, resolve, reject }
}
function makePage(overrides = {}) {
const saved = []
const messages = []
const calls = []
const api = {
getPrescriptionAiCapabilities: async () => {
calls.push('capabilities')
return { agreement_visible: false, can_manage_visibility: true }
},
getPrescriptionAiVisibilityConfig: async () => {
calls.push('config')
return { role_ids: [2, 90], admin_ids: [3, 91] }
},
getPrescriptionAiVisibilityOptions: async () => {
calls.push('options')
return {
roles: [{ id: 2, name: '医生' }],
admins: [{ id: 3, name: '张医生', account: 'zhang.doctor' }]
}
},
setPrescriptionAiVisibilityConfig: async (params) => {
saved.push(params)
return params
},
...overrides
}
const component = moduleFrom(script.content, (name) => {
if (name === 'vue') return vue
if (name === '@/api/setting/prescription_ai_visibility') return api
if (name === '@/utils/feedback') {
return { msgSuccess: (message) => messages.push(message) }
}
throw new Error(`Unexpected import: ${name}`)
}).default
const page = component.setup({}, { expose() {} })
return { page, api, saved, messages, calls }
}
test('API uses the dedicated routes and rejects malformed policy responses', async () => {
const calls = []
let response = { role_ids: [2], admin_ids: [3] }
const api = makeApi({
get: async (params) => {
calls.push(['get', params])
return response
},
post: async (params) => {
calls.push(['post', params])
return response
}
})
const data = await api.getPrescriptionAiVisibilityConfig()
data.role_ids.push(5)
assert.deepEqual(response.role_ids, [2])
await api.setPrescriptionAiVisibilityConfig({ role_ids: [], admin_ids: [] })
await api.getPrescriptionAiVisibilityOptions()
await api.getPrescriptionAiCapabilities()
assert.deepEqual(calls, [
['get', { url: '/tcm.prescriptionAi/getVisibilityConfig' }],
[
'post',
{
url: '/tcm.prescriptionAi/setVisibilityConfig',
params: { role_ids: [], admin_ids: [] }
}
],
['get', { url: '/tcm.prescriptionAi/visibilityOptions' }],
['get', { url: '/tcm.prescriptionAi/capabilities' }]
])
for (response of [
null,
{},
{ role_ids: [], admin_ids: ['3'] },
{ role_ids: [-1], admin_ids: [] }
]) {
await assert.rejects(api.getPrescriptionAiVisibilityConfig(), /响应格式不正确/)
await assert.rejects(
api.setPrescriptionAiVisibilityConfig({ role_ids: [], admin_ids: [] }),
/响应格式不正确/
)
}
})
test('initial loading is pending and cannot submit before the real policy is read', async () => {
const pending = deferred()
const { page, saved } = makePage({ getPrescriptionAiVisibilityConfig: () => pending.promise })
assert.equal(page.loading.value, true)
assert.equal(page.ready.value, false)
assert.equal(page.hasLoaded.value, false)
await page.handleSubmit()
assert.deepEqual(saved, [])
pending.reject(new Error('offline'))
await tick()
assert.equal(page.loading.value, false)
assert.equal(page.ready.value, false)
assert.match(page.loadError.value, /加载失败/)
await page.handleSubmit()
assert.deepEqual(saved, [])
})
test('a failed reload cannot apply a partial policy or overwrite saved selections', async () => {
const { page, api, saved } = makePage()
await tick()
api.getPrescriptionAiVisibilityConfig = async () => ({ role_ids: [], admin_ids: [] })
api.getPrescriptionAiVisibilityOptions = async () => {
throw new Error('options failed')
}
await page.loadConfig()
assert.deepEqual(page.formData.role_ids, [2, 90])
assert.deepEqual(page.formData.admin_ids, [3, 91])
assert.equal(page.hasLoaded.value, true)
assert.equal(page.ready.value, false)
await page.handleSubmit()
assert.deepEqual(saved, [])
api.getPrescriptionAiVisibilityOptions = async () => ({ roles: [], admins: [] })
await page.loadConfig()
assert.equal(page.ready.value, true)
assert.equal(page.loadError.value, '')
assert.deepEqual(page.formData.role_ids, [])
})
test('missing selected IDs stay visible and user labels support both name and account search', async () => {
const { page, saved } = makePage()
await tick()
assert.equal(page.canManage.value, true)
assert.equal(page.ready.value, true)
assert.deepEqual(
page.roleOptions.value.map((row) => row.id),
[2, 90]
)
assert.match(page.roleOptions.value[1].name, /#90.*当前不在可选列表/)
assert.deepEqual(
page.adminOptions.value.map((row) => row.id),
[3, 91]
)
assert.match(page.adminOptions.value[0].label, /张医生.*zhang\.doctor/)
assert.match(page.adminOptions.value[1].label, /#91.*当前不在可选列表/)
await page.handleSubmit()
assert.deepEqual(saved, [{ role_ids: [2, 90], admin_ids: [3, 91] }])
})
test('explicitly clearing both selectors saves the empty policy and applies normalized response', async () => {
const { page, saved, messages, api } = makePage()
await tick()
page.formData.role_ids = []
page.formData.admin_ids = []
await page.handleSubmit()
assert.deepEqual(saved, [{ role_ids: [], admin_ids: [] }])
assert.equal(messages.length, 1)
page.formData.role_ids = [90, 2, 90]
api.setPrescriptionAiVisibilityConfig = async () => ({ role_ids: [2, 90], admin_ids: [] })
await page.handleSubmit()
assert.deepEqual(page.formData.role_ids, [2, 90])
assert.equal(page.saving.value, false)
})
test('pending save blocks duplicate writes and reload; failed write keeps the user selection', async () => {
const pending = deferred()
const saved = []
const { page, calls } = makePage({
setPrescriptionAiVisibilityConfig: (params) => {
saved.push(params)
return pending.promise
}
})
await tick()
page.formData.role_ids = [90]
const first = page.handleSubmit()
assert.equal(page.saving.value, true)
await page.handleSubmit()
await page.loadConfig()
assert.equal(saved.length, 1)
assert.equal(calls.filter((name) => name === 'capabilities').length, 1)
pending.reject(new Error('offline'))
await first
assert.equal(page.saving.value, false)
assert.equal(page.ready.value, true)
assert.deepEqual(page.formData.role_ids, [90])
assert.deepEqual(page.formData.admin_ids, [3, 91])
assert.match(page.saveError.value, /当前选择已保留/)
})
test('management capability is independent from viewing and denies policy reads when absent', async () => {
const { page, calls, saved } = makePage({
getPrescriptionAiCapabilities: async () => ({
agreement_visible: true,
can_manage_visibility: false
})
})
await tick()
assert.deepEqual(calls, [])
assert.equal(page.canManage.value, false)
assert.equal(page.hasLoaded.value, false)
assert.equal(page.ready.value, false)
assert.match(page.loadError.value, /无权管理/)
await page.handleSubmit()
assert.deepEqual(saved, [])
})
test('actual settings template compiles with its script bindings', () => {
const compiled = compileTemplate({
source: descriptor.template.content,
filename: pagePath,
id: 'prescription-ai-visibility',
compilerOptions: { bindingMetadata: script.bindings }
})
assert.deepEqual(compiled.errors, [])
})
@@ -1,167 +0,0 @@
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 selected = [
'patchUsageVisible', 'patchUsageSaving', 'patchUsageFormRef', 'patchUsageForm',
'patchUsageRules', 'openPatchUsageDialog', 'resetPatchUsageForm', 'submitPatchUsage'
]
for (const page of ['components/PrescriptionOrderDetailDrawer.vue', 'order_list_h5.vue']) {
const filename = path.join(__dirname, '../src/views/consumer/prescription', page)
const { descriptor, errors } = parse(fs.readFileSync(filename, 'utf8'), { filename })
assert.deepEqual(errors, [])
const script = compileScript(descriptor, { id: page })
const template = compileTemplate({
source: descriptor.template.content, filename, id: page,
compilerOptions: { bindingMetadata: script.bindings }
})
assert.deepEqual(template.errors, [])
// Run the real handlers; replace the network and the rest of the order page.
const ast = ts.createSourceFile(filename + '.ts', descriptor.scriptSetup.content, ts.ScriptTarget.Latest, true)
const declarations = new Map()
for (const node of ast.statements) {
if (ts.isFunctionDeclaration(node) && node.name) declarations.set(node.name.text, node.getText(ast))
if (ts.isVariableStatement(node)) {
for (const declaration of node.declarationList.declarations) {
declarations.set(declaration.name.getText(ast), `const ${declaration.getText(ast)}`)
}
}
}
const executed = page.startsWith('components/') ? [...selected, 'refresh'] : selected
for (const name of executed) assert.ok(declarations.has(name), `${page}: missing ${name}`)
const compiled = ts.transpileModule(executed.map(name => declarations.get(name)).join('\n'), {
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS }
}).outputText
function instance({ hasAux = true, prescriptionType = '浓缩水丸', bagCount = 2, mainBagCount = 2, status = 2, fail = false } = {}) {
const calls = []
const events = []
const aux = { times_per_day: 3, usage_days: 10, dosage_bag_count: bagCount }
const detailPrescription = vue.ref({ prescription_type: prescriptionType, times_per_day: 3, usage_days: 10, dosage_bag_count: mainBagCount })
const detailAuxUsage = vue.ref(hasAux ? aux : null)
const detailData = vue.ref({
id: 42, prescription_id: 17, medication_days: 10, fulfillment_status: status,
gancao_reciperl_order_no: 'TEST-SUBMITTED', ej_pharmacy_order_no: 'TEST-EJ-SUBMITTED'
})
const refresh = async () => {
if (calls[0]?.dosage_bag_count) detailPrescription.value.dosage_bag_count = calls[0].dosage_bag_count
if (calls[0]?.aux_dosage_bag_count) detailAuxUsage.value.dosage_bag_count = calls[0].aux_dosage_bag_count
events.push('refresh')
return { ...detailData.value }
}
const globals = {
ref: vue.ref, reactive: vue.reactive, computed: vue.computed, nextTick: vue.nextTick,
detailPrescription, detailAuxUsage, detailData, detailHasAuxHerbs: vue.ref(hasAux),
feedback: { msgWarning() {}, msgSuccess() {} },
prescriptionOrderPatchPrescriptionUsage: async payload => {
calls.push(payload)
if (fail) throw new Error('Save failed')
},
requestDetail: refresh, refreshCurrentPrescriptionOrderDetail: refresh,
props: { loadRelatedData: true },
emit: event => events.push(event),
fetchLogs: async () => {
events.push('logs:start')
await Promise.resolve()
events.push('logs:done')
},
getLists: () => events.push('lists')
}
const state = new Function(...Object.keys(globals), `${compiled}\nreturn { ${selected.join(', ')} }`)(...Object.values(globals))
state.patchUsageFormRef.value = { validate: async () => {}, clearValidate() {} }
return { state, calls, events, detailAuxUsage, detailPrescription }
}
test(`${page}: edits auxiliary bags and refreshes the persisted value without changing usage`, async () => {
const { state, calls, events, detailAuxUsage } = instance()
state.openPatchUsageDialog()
assert.equal(state.patchUsageForm.aux_dosage_bag_count, 2)
state.patchUsageForm.aux_dosage_bag_count = 4
await state.submitPatchUsage()
assert.deepEqual(calls, [{
id: 42, times_per_day: 3, usage_days: 10, medication_days: 10,
dosage_bag_count: 2,
aux_times_per_day: 3, aux_usage_days: 10, aux_dosage_bag_count: 4
}])
assert.equal(state.patchUsageVisible.value, false)
assert.equal(detailAuxUsage.value.dosage_bag_count, 4)
assert.ok(events.includes('refresh'))
assert.ok(events.indexOf('logs:done') > events.indexOf('refresh'))
const completedEvent = page.startsWith('components/') ? 'detail-changed' : 'lists'
assert.ok(events.indexOf(completedEvent) > events.indexOf('logs:done'))
state.openPatchUsageDialog()
assert.equal(state.patchUsageForm.aux_dosage_bag_count, 4)
})
test(`${page}: missing historical bag count defaults to one and resets on close`, () => {
const { state } = instance({ bagCount: null, mainBagCount: null })
state.openPatchUsageDialog()
assert.equal(state.patchUsageForm.aux_dosage_bag_count, 1)
assert.equal(state.patchUsageForm.dosage_bag_count, 1)
state.patchUsageForm.dosage_bag_count = 4
state.patchUsageForm.aux_dosage_bag_count = 5
state.resetPatchUsageForm()
assert.equal(state.patchUsageForm.aux_dosage_bag_count, 1)
assert.equal(state.patchUsageForm.dosage_bag_count, 1)
})
test(`${page}: only water pills with an auxiliary formula submit or require auxiliary bags`, async () => {
for (const options of [{ hasAux: false }, { prescriptionType: '饮片' }, { prescriptionType: '颗粒' }]) {
const { state, calls } = instance(options)
state.openPatchUsageDialog()
state.patchUsageForm.aux_dosage_bag_count = 5
assert.equal(state.patchUsageRules.value.aux_dosage_bag_count, undefined)
await state.submitPatchUsage()
assert.ok(!Object.hasOwn(calls[0], 'aux_dosage_bag_count'))
assert.equal(Object.hasOwn(calls[0], 'dosage_bag_count'), !options.prescriptionType)
}
const { state } = instance()
assert.equal(state.patchUsageRules.value.aux_dosage_bag_count[0].required, true)
assert.equal(state.patchUsageRules.value.dosage_bag_count[0].required, true)
})
test(`${page}: main and auxiliary bags can be edited independently in every submitted order status`, async () => {
for (let status = 1; status <= 12; status++) {
const { state, calls, detailPrescription, detailAuxUsage } = instance({ status })
state.openPatchUsageDialog()
assert.equal(state.patchUsageForm.dosage_bag_count, 2)
state.patchUsageForm.dosage_bag_count = 5
state.patchUsageForm.aux_dosage_bag_count = 1
await state.submitPatchUsage()
assert.equal(calls.length, 1, `status ${status}`)
assert.equal(calls[0].dosage_bag_count, 5)
assert.equal(calls[0].aux_dosage_bag_count, 1)
assert.equal(detailPrescription.value.dosage_bag_count, 5)
assert.equal(detailAuxUsage.value.dosage_bag_count, 1)
}
const { state, calls } = instance({ hasAux: false })
state.openPatchUsageDialog()
state.patchUsageForm.dosage_bag_count = 4
await state.submitPatchUsage()
assert.equal(calls[0].dosage_bag_count, 4)
assert.ok(!Object.hasOwn(calls[0], 'aux_dosage_bag_count'))
})
test(`${page}: validation blocks requests and a rejected save retains the selected bags`, async () => {
const { state, calls, events } = instance({ fail: true })
state.openPatchUsageDialog()
state.patchUsageForm.aux_dosage_bag_count = 3
state.patchUsageForm.dosage_bag_count = 4
state.patchUsageFormRef.value.validate = async () => { throw new Error('Required') }
await state.submitPatchUsage()
assert.equal(calls.length, 0)
state.patchUsageFormRef.value.validate = async () => {}
await state.submitPatchUsage()
assert.equal(state.patchUsageForm.aux_dosage_bag_count, 3)
assert.equal(state.patchUsageForm.dosage_bag_count, 4)
assert.equal(state.patchUsageVisible.value, true)
assert.equal(state.patchUsageSaving.value, false)
assert.deepEqual(events, [])
})
}
-2
View File
@@ -46,8 +46,6 @@ export default defineConfig(({ mode }) => {
return {
base: '/admin/',
// 临时 UI 预览可能共用 node_modules;主开发服务独立缓存,避免预构建互相覆盖。
cacheDir: path.resolve(__dirname, 'node_modules/.vite-admin'),
server: {
port: 5555,
host: '0.0.0.0',
-2
View File
@@ -1,6 +1,4 @@
.env
.local-workstation/
resources/local-asr/
.venv/
.venv-build/
.venv-win7-check/
-8
View File
@@ -35,14 +35,6 @@ Windows 打包机需预先安装 `uv` 与 Node.js 20+;脚本会自动处理项
- 腾讯视频:沿用现有项目的 `@trtc/calls-uikit-vue` 主链;UserSig 只从后端短时获取,客户端不包含 SDKSecretKey。当前仅支持隔离的 QtWebEngine 内嵌模式。
- PyInstaller Windows/macOS 构建脚本、macOS 摄像头/麦克风权限配置与自动化测试。
## 本地后端联调
本机 phpStudy 站点准备好后,双击 `Run_DoctorWorkstation_Local.bat`,使用当前源码连接 `https://css.zhenyangtang.com.cn`。此入口要求域名解析到本机,启用 TLS 校验,复用本机站点的公开证书;偏好、日志和登录凭据使用独立目录及凭据命名空间。正式启动入口及正式服务器配置保持原样。本地入口首次启动需要重新登录,不会借用正式环境的会话。
本地入口固定使用指定的本机地址和证书校验,会修正旧偏好中的线上地址,并隔离登录页保存的设置;登录时不能切换到其他服务器。普通的“一键运行”入口仍连接正式服务器,不能用来验证尚未部署的本地后端修改。
仅检查配置可执行 `Run_DoctorWorkstation_Local.bat --check`。其他本机 HTTPS 站点可通过 `DOCTOR_LOCAL_API_URL` 和 `DOCTOR_LOCAL_CA_FILE` 指定域名与公开证书路径,禁止传入私钥。配置保存在已忽略的 `.local-workstation/` 中;本地后端仍使用 `server/.env` 的现有配置。
## 手动运行
先安装 [uv](https://docs.astral.sh/uv/),然后在项目根目录执行:
-10
View File
@@ -1,10 +0,0 @@
@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "LOCAL_APP_ROOT=%~dp0"
if not exist "%LOCAL_APP_ROOT%.venv\Scripts\python.exe" (
echo Local Python environment is missing. Prepare the source environment first.
exit /b 1
)
"%LOCAL_APP_ROOT%.venv\Scripts\python.exe" "%LOCAL_APP_ROOT%scripts\run_local_workstation.py" %*
set "LOCAL_RESULT=%ERRORLEVEL%"
endlocal & exit /b %LOCAL_RESULT%
Binary file not shown.

Before

Width:  |  Height:  |  Size: 118 KiB

After

Width:  |  Height:  |  Size: 124 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 163 KiB

After

Width:  |  Height:  |  Size: 167 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 117 KiB

After

Width:  |  Height:  |  Size: 115 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 165 KiB

After

Width:  |  Height:  |  Size: 167 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 112 KiB

After

Width:  |  Height:  |  Size: 159 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 147 KiB

After

Width:  |  Height:  |  Size: 188 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 90 KiB

After

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 67 KiB

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 77 KiB

After

Width:  |  Height:  |  Size: 73 KiB

+4 -16
View File
@@ -10,14 +10,11 @@ modules, Qt6Multimedia shared libraries/frameworks, multimedia plugins, and
their platform media backends.
"""
import importlib.util
import os
import re
import sys
from pathlib import Path
from PyInstaller.utils.hooks import collect_all
PROJECT_ROOT = Path(SPEC).resolve().parent.parent
SOURCE_ROOT = PROJECT_ROOT / "src"
@@ -111,24 +108,15 @@ qt_multimedia_hiddenimports = [
"PySide6.QtMultimediaWidgets",
]
# Cloud transcription only needs offline character conversion on the client.
if importlib.util.find_spec("opencc") is None:
raise SystemExit("Install the project dependencies before packaging (missing opencc)")
transcript_datas, transcript_binaries, transcript_hiddenimports = collect_all("opencc")
client_resources = [
(str(entry), f"resources/{entry.name}" if entry.is_dir() else "resources")
for entry in RESOURCES.iterdir()
if entry.name != "local-asr"
]
analysis = Analysis(
[str(ENTRY_POINT)],
pathex=[str(SOURCE_ROOT)],
binaries=python_runtime_binaries + transcript_binaries,
binaries=python_runtime_binaries,
datas=[
(str(VIDEO_DIST), "video_companion_dist"),
] + client_resources + transcript_datas,
hiddenimports=qt_webengine_hiddenimports + qt_multimedia_hiddenimports + transcript_hiddenimports,
(str(RESOURCES), "resources"),
],
hiddenimports=qt_webengine_hiddenimports + qt_multimedia_hiddenimports,
hookspath=[],
hooksconfig={},
runtime_hooks=[str(MEDIA_SMOKE_HOOK)],
-4
View File
@@ -13,16 +13,12 @@ authors = [{ name = "Zhenyangtang" }]
dependencies = [
"httpx>=0.27.2,<1",
"keyring>=25.5,<26",
"opencc-python-reimplemented==0.1.7",
"platformdirs>=4.3,<5",
"PySide6>=6.8.2,<7",
"python-dotenv>=1.0.1,<2",
]
[project.optional-dependencies]
local-asr = [
"faster-whisper==1.2.1",
]
dev = [
"pytest>=8.3,<9",
"pytest-cov>=6,<7",
-72
View File
@@ -1,72 +0,0 @@
# 医生工作站客户端设计规范
本轮覆盖现有 PySide6 客户端与 Vue 视频伴随窗口。按 `redesign-existing-projects` 审查现有页面,结合 `minimalist-ui` 的扁平化原则实施;医疗工作台保留信息密度,不套用营销页面的大留白、装饰动效或布局模板。
## 审查结论
- 主框架与业务页面原先并存科技蓝、紫蓝及多套中性色;登录、AI、诊单的控件也各自定义配色。
- 页面内圆角、边框和层级不统一,部分阴影、悬浮位移和过渡使操作显得跳动。
- 小窗口的表格、诊单与视频操作需要分别验证,不能依靠整体缩小解决。
- 键盘焦点、禁用与选择状态应始终可识别,不通过改变控件几何位置表达状态。
## 视觉系统
设计变量以 `src/doctor_workstation/ui/design_system.py` 为准。旧页面通过 `clinical_stylesheet` 迁移已知的浅色主题颜色,新样式使用命名变量。医学数据曲线、模型标识色和深色主题不进行全局替色。
| 角色 | 值 | 使用场景 |
| --- | --- | --- |
| 主色 | `#4267B2` | 主操作、选中项、重要链接 |
| 主色浅底 | `#EAF0FB` | 选中背景、轻量状态 |
| 画布 | `#F5F7FA` | 主窗口背景 |
| 表面 | `#FFFFFF` | 内容区、对话框 |
| 次级表面 | `#F7F9FC` | 筛选栏、分组、只读区域 |
| 侧栏 | `#F0F3F8` | 导航区域 |
| 标题 / 正文 | `#223047` / `#344258` | 文字层级 |
| 次级文字 | `#647287` | 说明、辅助信息 |
| 边框 / 强边框 | `#E6EAF0` / `#D4DCE8` | 低对比结构线、输入边界 |
| 成功 / 警示 / 危险 | `#287B65` / `#96601D` / `#B54A59` | 保留明确语义,不只依赖颜色 |
- 圆角:标签 6 px、输入与按钮 10 px、内容面板 16 px、独立窗口 20 px。
- 间距:8 / 12 / 16 / 24 px,根据现有表格密度调整,不整体放大行高。
- 字体:继续使用打包的中文字体与现有可读字号;标题层级通过字重、字号和间距体现。
- 表面:纯色为主,轻边框划分区域,减少嵌套卡片与装饰阴影。
- 按钮:每个操作组主次清晰;次要操作使用浅底或边框;终止、删除等危险操作保留语义色。
## 交互规范
- 悬浮、按下和焦点反馈不移动布局、不改变控件尺寸。
- 动画短而克制;滚动可被键盘、拖动、程序定位与反向滚动即时打断;尊重减少动画设置。
- 切换页面保留原有路由、权限和数据加载机制。
- 登录表单保留密码存储、服务器设置与提交保护;组合密码框使用实际 Qt 焦点状态。
- 大小窗口都必须能找到主要操作,优先局部滚动而非把全部内容压小。
- 视频保留原有截图捕获、确认上传、大预览和小窗关闭返回大窗逻辑;视觉样式不改变媒体内容或尺寸计算。
## 覆盖范围
1. 登录与品牌区:扁平品牌面板、简洁功能说明、清晰表单与焦点。
2. 主框架:导航、顶部搜索、工具按钮、标签与 AI 入口。
3. 列表:挂号、接诊记录、患者、处方库、已开处方、业务订单及患者进度。
4. 诊疗:接诊台、预约抽屉、诊单编辑与只读、指标和保存状态。
5. 辅助窗口:AI 问诊、处方编辑、处方解读与报告控制台。
6. 视频:通话控制、聊天、录制提示与截图确认。
## 验收方式
`scripts/render_client_design.py` 使用演示仓库生成 1440 × 900、1024 × 640 的真实页面,以及 1280 × 800、860 × 640 的登录页;输出 `artifacts/client-design/index.html` 与原尺寸 PNG。诊疗和 AI 弹窗使用现有专用渲染脚本验证。
检查重点:小窗操作可达、中文可读、表格信息密度、长文本换行、键盘焦点、布局稳定、登录与页面路由契约、视频截图与窗口状态回归。生产服务与真实患者资料不用于视觉验收。
本轮共享组件还覆盖筛选展开按钮、列表加载状态、聊天通知、更新提示、本机录音队列、媒体预览和上传进度。860 × 640 登录表单完整显示,不需要为纯留白滚动。
## 验证记录与边界
- 主框架、登录、遮罩与动效首轮 100 项通过;新增组合密码框键盘焦点检查通过。
- 小窗登录与焦点补测 2 项、最终登录及主框架复查 68 项通过。
- 筛选、无限列表、通知、更新窗口与本机录音队列 37 项通过。
- 原生视频截图、截图预览尺寸、小窗关闭与视频契约 199 项通过。
- 视频前端 26 项检查通过,生产 dist 已重新构建。
- 当前视频 dist 在 1120 × 760、540 × 356、440 × 300 的合成画面中完成 27 项布局检查,截图与关闭事件正常,未访问外部服务。
- 临床页面、AI、处方及图表分别完成专项测试和真实控件渲染,详细记录位于 `artifacts/client-design/*-report.md`。
- 最终修改文件的 Ruff 与 `git diff --check` 均通过;AI 工作区及快捷操作权限最后复查 24 项通过。
此记录不表示整仓所有历史测试全部通过。扩展测试中存在已用原始 HEAD 复现的 AI 流式/延迟生命周期失败、共享 QApplication 样式引发的图表测试顺序依赖,以及 Windows Qt 网络模块异常;本轮没有改变相关业务行为。未连接真实面诊服务,也未重新打包或安装 Windows 客户端。
@@ -1,21 +0,0 @@
# 腾讯云实时转写恢复(2026-10-30)
用户明确选择“恢复腾讯云实时转写,保留简体中文”。本次仅替换识别通路,保留 IM AI、实时 AI 辅助、复盘、本机录音、视频录制、截图和窗口交互。
## 当前行为
- 使用当前固定 SDK 的 `getAITranscriberManager()` 和 `startRealtimeTranscriber({sourceLanguage: 'zh'})`。不再启动本地 PCM 识别或加载 Whisper/Nano 模型,本机语音录音保持独立。
- 最终转写片段先经过原生可信页面及会话校验,以宿主的医生/患者用户 ID 确定角色,再用本机 OpenCC 转为简体并保存。仅持久化成功的确认回传简体文字,字幕和本次 AI 引用使用同一保存原文;历史记录查看仍显示简体。
- 同一通话的云端重试复用原转写会话,保留已保存字幕和 AI 结果;云端中断不提前封存存储,真正挂断时才排空并归档。出错期间可能漏记的通话最终标记 partial。
- 云端启动成功通过 `transcription-ready` 更新原生状态,避免重试成功仍显示失败;旧页面、旧会话、旧监听器及本地 ASR 命令不能混入当前会话。
- 启动/打包脚本不再默认启用 `local-asr` 额外依赖;仍打包简体转换字典。`resources/local-asr` 从发布资源中排除。已有开发模型和独立测试模块保留,不默认使用。
## 验证及生效
仅用合成身份/文字与 SDK 替身验证启停、重试、尾段排空、成功保存后的六参数 ACK、简体转换、说话人归属、AI 更新和隔离边界。截图、大小窗及录音回归继续通过,前端类型检查和生产资源重建完成。
详细结果见 `app/artifacts/im-ai/cloud-transcription-restore-frontend.md`、`cloud-transcription-restore-native-tests.md`。没有发起真实患者通话或验证线上腾讯云识别效果,没有生成新的完整安装包。
最终整合验证:338 项 Python 回归、128 项前端测试通过,Vue 类型检查及生产构建通过。已核对真实 Qt 六参数转写信号,以及 PyInstaller 资源展开结果:图标、字体和简体词典保留,本地识别模型不进入发布资源。
源码客户端需要在结束当前通话后退出并重新启动整个客户端,原生 Python 代码与新前端资源才能一起生效。已冻结安装包需重新构建,不能只更换网页资源。
-75
View File
@@ -1,75 +0,0 @@
# IM 问诊 AI 辅助
用户确认范围:在现有 IM 问诊窗口内增加「总结病情」「建议追问」「起草回复」。结果供医生审阅,医生主动填入输入框后编辑并手动发送。
## 集成契约
- 复用 `stream_diagnosis_ai`:总结使用 `summary`,追问和回复使用 `custom`。不新增模型配置、不把凭据传到浏览器、不新增服务端路由。
- 每次生成前,通过 `sync_im_chat_messages(scope="current", sync_token=...)` 完成当前账号对话归档;响应 `completed=true` 且没有错误后才能调用 AI。准备失败明确报错,不静默降级为旧聊天。服务器按授权诊单聚合临床资料与归档 IM,提示词限定本次医生账号的近期对话。
- 三项提示词保持 500 字以内;不在提示词中挤入、截断完整聊天或未发送草稿。
- AI 独立后台 worker,不占用通话、录音和消息发送的队列。
原生配置 `DoctorCallConfig.imAi`:`{version:1, enabled:boolean, sessionId:string, reason?:string}`。宿主生成 sessionId,每个新窗口独立。上层将 AI 权限布尔值贯穿 launcher;默认拒绝。
浏览器到原生:
```json
{"source":"doctor-call","event":"im-ai-request","sessionId":"host-uuid","requestId":"uuid","contextKey":"frontend-context","diagnosisId":"501","appointmentId":101,"action":"summary"}
```
取消使用同一组身份字段及 `event="im-ai-cancel"`。只允许 `summary | followup | reply`。宿主核验可信文档、窗口未关闭、AI 权限、会话、诊单、挂号和请求格式;实际 repository 调用始终使用宿主绑定诊单。
原生通过 `window.doctorConsultation.imAiResult(payload)` 返回相同身份字段与:
```text
status: loading | streaming | success | error | cancelled
text?: 累积正文(流式及最终)
message?: 简短进度或错误
modelLabel?: 服务端模型标签
warnings?: string[]
```
所有数据使用 JSON 序列化,桥接正文仍为原始文本。页面通过受限 Markdown 渲染器显示标题、重点、列表和表格;原始 HTML 被转义,链接和图片只保留文字,不执行内容或加载外部资源。客户端截止时间 180 秒,超时发送取消;原生聊天同步有独立有界预算,AI 沿用现有 105 秒传输预算。取消请求由独立线程发送,GUI 不等待网络。停止只是停止本次接收,不冒称上游工作已确认停止。
## 界面与状态
- 宽屏右侧约 330 px 辅助区;窄屏可收起抽屉,独立滚动,操作和关闭可达。沿用现有蓝色、圆角和轻边框。
- AI loading 不阻塞 IM 输入、发送、加载更多和视频控制。
- 只有完整成功结果允许填入;追问与回复可填入,病情总结默认只读。非空草稿明确追加,超过 3000 字拒绝追加而不截断原文。
- 切换会话清空 AI 状态和草稿;迟到、重复、身份不匹配结果全部忽略。
- 异步手动发送成功仅清空当时提交且没有继续修改的草稿。
- 结果注明医生复核,展示服务端临床复核提示;不会自动发送、写病历或开处方。
## 验证要求
离线 fake repository 验证同步续拉、失败不生成、取消、终态、身份隔离、权限与关闭;Node 测试验证桥接状态/计时器、草稿追加和发送隔离;使用真实构建产物和合成消息验证宽屏与紧凑窗口。回归截图、录音收尾、通话权限与 IM 流程。验证不得访问真实患者、IM 或 AI 服务。
## 交付与验证结果(2026-10-29)
- `app.py` 在实际打开窗口时读取当前账号的 `tcm.diagnosis/aiAssistant` 权限,经 launcher 传入原生窗口;未配置权限时默认关闭,不采用聊天载荷中的权限标记。
- 三项功能已接入真实 Qt bridge 和现有流式服务;宽屏常驻侧栏,980 px 及以下窗口使用可收起抽屉。中文输入法选词时按 Enter 不发送,异步发送不会清除医生随后编辑的草稿。
- 合并后 Python 回归 **364 项通过**:包括新增 AI 服务/仓库/窗口、权限入口、IM、视频契约、截图、小窗关闭及大预览等。运行使用独立 `artifacts/im-ai/final-integration-tmp`,未访问外部服务。
- 前端 **45 项 Node 行为测试通过**,`vue-tsc` 与 Vite 构建通过;实际 dist 在 1120×760、980×640、540×356、440×300 下 **42 项界面检查通过**。离线夹具只使用合成消息和结果,外部请求尝试为 0。
- Ruff 与 `git diff --check` 通过。首次交付构建入口:`index-CnqWQu6O.js`、`index-BwArpbVK.css`。
- 截图、可复现夹具和详细报告存放在 `app/artifacts/im-ai/`。未验证真实账号的模型响应;未生成 Windows 安装包。源码运行需重启客户端,已安装版本需重新打包后安装。
停止接收后,原生端会独立请求取消;在旧请求实际退出前重试会提示稍后再试,避免重复模型请求。聊天同步失败时不使用旧归档静默生成,助手显示错误并允许重试。
## 结果排版与切换改进(2026-10-29)
- 模型输出的 Markdown 标题、加粗、列表、引用、代码和简单表格转换为安全的结构化展示;重点以加粗和浅蓝底色标记,结构标题使用蓝色引导线。不依据医学关键词自行推断重点。未闭合的流式片段保持可读原文。
- 三项操作在当前窗口会话内分别保留状态、正文、模型标签和复核提示。顶部按钮首次点击生成,之后只切换查看;底部“重新生成/重试”才会再发请求。生成中可以阅读其他已完成结果,后台更新不能覆盖当前阅读页。
- 每项保留独立滚动位置,换患者、关闭或重开会话时清空。结果仅保存在内存中,不增加本地患者内容持久化。
- 填入草稿前去除 Markdown 排版符号,保留原文、数值和列表含义,再执行 3000 字长度检查;仍不覆盖原稿、不自动发送。
- 本次前端 **61 项行为测试通过**,包含安全渲染、草稿转换、缓存、显式重生成、后台流式隔离及现有截图/通话守卫;TypeScript 与 Vite 构建通过。
- 真实 dist 配合生产 AI controller 源码和离线宿主替身,在四种窗口尺寸完成 **20 项可点击/布局检查**,以及切换不发请求、显式刷新、后台生成、独立阅读位置、原稿追加及注入防护断言。外部请求为 0。
- 证据:`artifacts/im-ai/refinements-visual-checks.json`、`render_im_ai_refinements.py` 与 `im-ai-styled-cached-*.png`。未打包安装程序。
## 可调宽度、首次总结与指标强调(2026-10-29)
- 聊天与助手之间增加可左右拖动的分隔线,宽屏保留至少 480 px 聊天区域;窄屏抽屉也可调整,最大宽度仍留出可操作的边缘。支持方向键、Home/End、Enter 或双击恢复默认,Escape 取消本次拖动。窗口变更、失焦与关闭释放指针捕获。宽屏和抽屉宽度分别记忆在当前窗口内。
- 进入有权限的 IM 会话后,首次总结等待当前登录、聊天、Qt 通道及原生 `imAiReady(sessionId)` 确认;准备等待最多 30 秒。每个会话只自动尝试一次,不因重连、标签切换、展开面板或失败自动重试。医生提前手动操作会取消待启动的自动总结。关闭和换会话清理计时器及旧结果。
- 普通文本中的血糖、血压、糖化血红蛋白、体重等指标名称及带单位的数值自动强调,支持范围、小数和血压组合。名称加深,数值加粗并显示浅蓝底色,不依赖模型输出 Markdown。原始数值、单位、否定和不确定表述保持不变;没有新增医学阈值判断或自动风险分级。
- **97 项前端测试、318 项客户端回归通过**,TypeScript、Vite 和 Ruff 检查通过,`git diff --check` 无问题。当前构建:`index-C_tMrPfb.js`、`index-CMN1CXTr.css`。
- 实际构建页面在 1634×1008、1120×760、980×640、540×356、440×300 下完成真实 Qt 鼠标拖动、键盘调整、取消、跨断点释放及指标样式检查,**15 项布局/点击检查通过**,自动选择与请求次数断言通过,外部请求为 0。
- 证据:`artifacts/im-ai/render_im_ai_resizing.py`、`resizing-visual-checks.json`、`im-ai-metrics-resizable-*.png`。本轮未生成安装包;原生就绪握手需重启使用最新源码的客户端。
@@ -1,72 +0,0 @@
# 实时问诊 AI:响应与建议质量改进
日期:2026-10-30。最新范围调整:仅视频接通后的实时 AI 使用本次通话文字;IM、病历分析与通话后复盘保持原范围。见末尾“纯对话实时模式”。
## 问题证据
从本机服务端当天运行日志中仅提取错误码和耗时,共发现 10 条 `LIVE_RESULT_INVALID` 记录:最短 12,833 ms,中位 15,002 ms,最长 29,465 ms。这说明部分等待最终消耗在无效结果上;原日志没有校验细项,不能断言具体是哪一种格式或引用错误。
代码另有两处可确认的问题:有结果后的新增对话要等待 8 秒才发起下一轮;“症状要点”允许放入医生的完整问句。模型还会重复询问已有年龄,且只有整份 JSON 通过后才显示结果。
## 已实现
- 首次已保存转写后等待约 0.8 秒发起分析,后续更新等待改为 2 秒。等待从第一段新增内容起算,持续说话不会无限推迟。每个窗口仍只有一个在途分析,期间新内容合并,已到期的下一轮不会在上一轮结束后再次等待。
- 服务端完整验证一条带合法分隔符的结果后,通过 `live_update` 提前交付累计内容,不再等待整个数组闭合。按实际可展示条目增加发送,实时最多 12 次、复盘最多 15 次,最终仍需 `done`。原始 JSON 片段不展示;客户端同样验证诊单、通话、转写会话、版本及所有引用。失败保留已经可核对的内容,并标明本轮尚未完成。
- 优先生成最多三条“下一步追问”,给出简短理由;实时辅助依据完整本次对话减少重复,通话后复盘仍结合授权病历。保留发病年龄、历史年龄和家属信息等必要的追问空间。
- 患者摘要由已校验的引用 ID 还原完整原话,不采用模型改写的事实。省略医生、未知说话人和单纯问题选段。合法 JSON 代码块包装可以解析;引用、数据范围和内容校验继续执行。
- 侧栏首问突出显示,再展示患者关键信息、待核实及复盘。显示实际已用时间、待处理分段和内容依据时间;区分连接、超时、格式、引用、权限等失败,不再统一提示升级服务端。
- 去除模型输入中当前转写和授权历史的重复副本,保留完整来源、资料权限、附件清单和现有超时预算。增加首条有效建议及整轮耗时的安全日志,不记录患者原文或模型正文。
- 沟通追问可帮助了解患者诉求、理解困难和执行顾虑,不预设需要新增治疗、检查或购买项目。腾讯云实时转写、简体中文及现有通话流程保持原配置。
## 验证与构建
- 客户端 Python 相关回归:277 项通过;Ruff 通过。
- 前端组件、通话和布局等测试:136 项通过;Vue 类型检查、生产构建通过。
- 服务端质量测试:421 个累计断言;流式集成:851 个累计断言;真实请求构造的响应契约测试:167 个累计检查。它们包含各自复用的基础断言,不能简单相加视为独立用例数。前一轮 SSE 协议、错误回执、心跳、计时、请求生命周期回归通过。
- `git diff --check` 通过;未提交或撤销其他开发中的功能。
- 构建产物:`app/video_companion/dist/index.html`,脚本 `index-DZWRwUZ-.js`,样式 `index-BbhpEZgS.css`。Vite 仍提示现有视频 SDK 主包体积较大;构建成功。
测试使用合成资料,未发送真实患者资料,未发起真实通话。第二轮另做了下述一次成功的纯文字在线合成验收。浏览器工具未完成本次视觉验收,组件与布局验证已完成。未重启医生客户端或部署远程服务端。
## 针对 16 秒反馈的第二轮定位与处理
11:13 的成功请求在客户端耗时 16,922 ms,首条有效内容 14,952 ms。对应服务端聚合仅 79 ms,未做历史压缩;附件处理 2,800 ms,其中 OCR 2,233 ms;Dify 传输 13,630 ms,其中模型节点开始到首正文约 8,098 ms。这些是相互包含的阶段,不能把嵌套指标重复相加。客户端与服务端按时间及状态关联,不是通过同一 trace ID 直接关联。
此次新增处理:
1. 修复公共 Dify 传输给实时任务附加长报告诊疗规则的冲突。仅服务端选定 `response_contract=live_consultation` 的问诊/复盘使用简短的实时结构化契约,普通诊疗报告保持原规则。当前完整资料、附件、否定/日期/角色及“不采脉”边界均保留。
2. 逐条交付第一条已校验内容,不等后续问题和整组输出。医生/未知来源不能被理由改写成“患者自述”,明确的无患者依据事实前提会省略。
3. 增加 300 秒 OCR 私有缓存,按凭据、应用端点、用户、原图内容、识别配置和运行环境绑定。每次仍重新校验当前来源;失败或识别预算耗尽不缓存。正常无文字图片可按原 unreadable 状态复用,原图仍发送,未减少医学资料。缓存上限 64 个槽位、32 MiB;实际图片内容及模型身份变化即失效。
4. 客户端分别显示首条有效结果和整轮完成时间,未知首条时间不显示为零。
OCR 新增 45 个离线断言通过;原桥接 25、预算 13、上传复用 62 项检查通过。两项外围测试仍失败,已用 Git HEAD 对应实现复现相同失败,未掩盖或计入通过:`DifyImageTextEvidenceTest.php:30` 的既有索引文案断言,以及 `DifyRequiredAttachmentUploadTest.php:519` 的既有“全缺失附件 + 无效配置”断言。后者在沙箱内先受回环测试服务器限制,在正常回环环境下才到达该断言。
在线合成验收使用现有 Qwen/Dify、无图片、无真实患者资料。一次成功请求的首条有效结果为 **1,306 ms**、整轮 **2,181 ms**,JSON 与引用校验通过。沙箱内两次连接立即失败,随后允许网络的同一合成脚本成功;不把失败连接算作模型速度样本。该结果只证明轻量文字请求可以快速且按契约返回,不能证明原来带图病例的 16.9 秒已降到 2.2 秒,也不是控制变量前后对比。实际带图问诊的缓存收益、首条和整轮耗时仍待部署后的相同场景验证。
## 生效与验收
客户端需要加载本次构建并重新启动;使用远程 PHP 服务时需同步服务端改动。旧服务端仍可通过最终 `done` 返回结果,但不能提前交付建议。
下一次实际使用应比较“已保存转写至首条有效建议”的耗时和校验失败率,同时由医生检查追问相关性、信息遗漏及患者理解情况。0.8 秒、2 秒仅为发起请求前的等待,不是模型响应承诺。本轮不声称已经验证诊断准确率或成单率提升。
## 纯对话实时模式
根据用户“仅限视频接通后的 AI 那一块”的明确限定,只有 `live_consultation` 改为 `current_call_only`。视频中的自动更新与重新生成只提交本次会话已保存的全部转写;不读取诊单详情、历史病历,不做病历压缩、OCR 或附件上传。权限、有效诊单、通话归属、会话身份与完整转写快照的校验仍在;原有 1 MiB 容量超限会明确拒绝,不截断早期文字。
`live_review` 保持 `authorized_case`,继续结合授权病历与图片;IM 总结、追问、起草回复及普通病历 AI 未改。实时提示词不再包含未提供的病历块,明确只依照本次对话、跳过已答问题。代价是没有在对话提及的历史过敏、用药、检查等资料不会纳入实时建议,不能将建议视作完整病历评估。
服务端在 start、live_update、done 返回可信分析范围。客户端只在结果校验通过后更新“当前内容仅依据本次通话文字,不含历史病历和图片”的说明;复盘等待或失败时不会把旧结果标成另一范围。旧服务端未提供范围时也不会误标为纯对话。同一请求中范围不一致会拒绝更新。
验证:纯对话服务端专测 328 个累计断言,包括 220 个完整分段、超过旧历史压缩阈值的长文本逐字一致、拒绝任何病历详情/历史读取、零附件,以及普通 summary 和完整复盘隔离。真实 Dify 构包测试 203 个累计检查;进度与质量回归仍为 851、421 个累计断言。客户端 277 项、前端 136 项均通过。服务端完整记录在 `app/artifacts/im-ai/dialogue-only-server.md`;其中两组普通临床策略测试的额外既有失败已隔离复现,没有将它们计入通过或改变其行为。
在线测速仅使用 6 段完全合成的对话,经真实请求构造器及 `streamPreparedAssistant` 的完整流式校验路径请求现有 Qwen/Dify。没有查询真实诊单、患者转写或图片。三轮结果:
| 轮次 | 首条已校验结果 | 整轮完成 | 结果 |
| --- | --- | --- | --- |
| 1 | 859 ms | 2,130 ms | 引用与结构校验通过 |
| 2 | 785 ms | 2,001 ms | 引用与结构校验通过 |
| 3 | 806 ms | 2,021 ms | 引用与结构校验通过 |
计时包括纯请求构造与真实流式模型处理,不含语音转写、保存分段、触发等待和客户端渲染。每轮 query 为 5,526 bytes、6 个分段、零附件,首轮与后续轮次均使用独立合成上游用户标识。这不是实际长通话延迟保证,也不是与原带图病例的控制变量对照。数据记录在 `app/artifacts/im-ai/live-dialogue-only-online-timing-20261030.json`。
尚未部署远程服务端或重启正在运行的医生客户端。需要服务端加载最新代码、客户端加载本次构建后才会生效;腾讯云实时转写与简体中文配置保持原样。
-92
View File
@@ -1,92 +0,0 @@
# 本地离线语音转写:安装、打包与验证
> 当前状态(2026-10-30):用户已明确要求恢复腾讯云实时转写、保留简体中文。客户端默认通路已经恢复腾讯云,启动/打包不再自动安装本地 ASR,也不把本地模型加入发布资源。本文后续内容保留为此前本地方案的开发、安装与评估记录,并非当前默认行为。当前通路见 `cloud-transcription-restore.md`。
运行时使用 faster-whisper 1.2.1,在医生电脑的 CPU 上以 int8 加载本地 Whisper 模型。音频为浏览器桥接传入的单声道、16 kHz、有符号 PCM16 小端字节流;不写临时音频、不发送至 ASR 服务。模型安装和下载只能通过下面的显式命令执行,视频通话不会触发安装、下载或腾讯云语音识别。
## 开发环境安装
在已安装医生工作站依赖的 `app` 目录运行:
```powershell
.venv\Scripts\python.exe scripts/setup_local_transcription.py --install-dependencies --download --model-size small --check
```
此命令明确允许联网安装 `faster-whisper==1.2.1` 及其传递依赖,并从官方 `Systran/faster-whisper-small` 仓库下载模型,然后禁用网络验证 CPU/int8 模型和 Silero VAD 的加载。`tiny`、`base`、`small`、`medium`、`large-v3` 均可选择;中文场景不要使用英文专用 `.en` 模型。开发默认选择 `small`,实际识别准确率和延迟仍需在目标电脑与实际通话音频上验收。
`--install-dependencies` 仅安装至执行命令的 Python 环境;`--download` 才下载模型。不传操作参数只显示帮助。可用 `--revision <官方仓库提交哈希>` 固定下载版本。
模型查找顺序为 `DOCTOR_ASR_MODEL_PATH`、开发目录或安装包内的 `resources/local-asr/model`、最后为 `platformdirs.user_data_path("ZhenyangDoctorWorkstation", appauthor="ZhenYangTang") / "local-asr" / "model"`。可以指定独立目录:
```powershell
$env:DOCTOR_ASR_MODEL_PATH = 'D:\DoctorModels\whisper-small'
.venv\Scripts\python.exe scripts/setup_local_transcription.py --download --model-size small --check
```
`--model-path` 只覆盖本次安装/检查命令;工作站仍按上述顺序查找。下载后会记录 `doctor-asr-install.json`,包含仓库、请求的版本、运行库版本和时间,不包含音频。运行时要求目录存在,且 `model.bin`、`config.json`、`tokenizer.json`、`vocabulary.txt` 或 `vocabulary.json` 非空。缺失时直接报错。`tokenizer.json` 必须随模型提供,以阻止上游缺失 tokenizer 时的自动获取回退。
离线电脑可通过离线安装包安装运行库,再复制完整模型目录;不要在通话过程中初始化下载。离线检查:
```powershell
.venv\Scripts\python.exe scripts/setup_local_transcription.py --check
```
## 桌面安装包
为应用配置 `local-asr` 可选依赖(`faster-whisper==1.2.1`),并在实际 PyInstaller 构建环境安装该额外依赖。运行库需要 NumPy、CTranslate2、tokenizers、ONNX Runtime、PyAV 等上游依赖。不能仅在开发 `.venv` 安装后假设 `.venv-build` 或已冻结的 exe 自动拥有这些依赖。
PyInstaller spec 已加入 `faster_whisper` 数据文件(包括 Silero VAD)及 `ctranslate2`、`onnxruntime`、`av`、`tokenizers` 的 `collect_all`,缺少运行库时构建会明确失败。Windows/macOS 运行环境准备与打包脚本已加入 `--extra local-asr`,依赖锁文件同步更新。构建前可把完整模型放在 `app/resources/local-asr/model`,随现有 resources 打入安装包;也可在目标电脑独立安装到应用数据目录或管理员指定目录。模型不纳入 Git。该模块导入依赖是延迟执行的,没有安装本地 ASR 运行库也不会阻止工作站、视频和录音模块启动。
本轮未生成新 exe 或安装包。发布前仍需验证运行库、模型和 VAD 在成品内真实可用,不能把开发环境通过的单元测试作为成品 ASR 可用性的证明。旧系统兼容性取决于这些原生依赖的官方 wheel 和操作系统支持,不自动沿用工作站其他部分的兼容性声明。
## 验证
```powershell
.venv\Scripts\python.exe -m pytest tests/test_local_transcription.py
.venv\Scripts\python.exe -m ruff check src/doctor_workstation/video/local_transcription.py tests/test_local_transcription.py scripts/setup_local_transcription.py
.venv\Scripts\python.exe scripts/setup_local_transcription.py --check --smoke-wav D:\ASR-Test\non-sensitive-16k-mono.wav
```
smoke WAV 必须是单声道 16 kHz PCM16,最长 12 秒。该命令阻止网络连接并输出识别结果;请使用无患者信息的人工测试音频。建议覆盖短回答“有”“不”、否定句、药物名称、0.5/5、剂量单位、静音、背景噪声,以及医生和患者同时说话。录音通道的角色来源于浏览器端音轨身份,模型不做声纹识别。
单元测试使用替代引擎,验证会话隔离、异步回调、队列上限、序号验证、排空停止、错误脱敏、静音和数字/否定词的原样输出。替代引擎测试不证明实际模型准确率。启动和推理只能在后台执行;Qt 接收方通过 signal 转交主线程。`close()` 立即取消回调,正在执行的原生推理可能在守护线程中完成,不能在 UI 线程等待它。
2026-10-29 已在本仓库 `.venv` 安装运行库,并在 `app/resources/local-asr/model` 安装官方 `Systran/faster-whisper-small`。CPU/int8 模型和 VAD 加载检查通过;使用 [FunASR 官方示例](https://github.com/modelscope/FunASR)提供的[公开中文音频](https://isv-data.oss-cn-hangzhou.aliyuncs.com/ics/MaaS/ASR/test_audio/asr_example_zh.wav)完成真实识别,检查及推理期间阻断网络。输出为“欢迎大家来体验打磨院推出的语音识别模型”,出现“达摩院”的同音误识;这验证了本机推理链路,不能代替医疗词汇、噪声、双向通话及目标电脑负载验收。没有发送真实患者资料,尚未测试真实 AI 服务响应。
## 视频 AI 接入与验收
现有腾讯音视频通信、IM 和云端录制继续使用;语音转写改由本地音轨 PCM 和本机模型完成。完成分段保存成功后才触发 AI,约八秒合并更新一次,无新增原文时不重复请求。使用现有 `tcm.diagnosis/aiAssistantStream` 的 `live_consultation`/`live_review` 任务;服务端按医生、诊单、通话及转写会话读取完整原文,再连同授权病历交给已授权的现有 Dify 服务。AI 不发送消息或自动写入病历。
客户端新增 AI 辅助、对话原文、患者资料标签、可调侧栏宽度和窄屏抽屉。挂断后在 IM 顶部打开“本次通话复盘”;点击复盘按钮请求复盘草稿。每条辅助结果可以查看完整引用原话,转写未完整保存时明确显示状态。模型缺失、AI 服务未更新或没有权限时显示具体状态,视频通话可继续。
生效需要部署本轮服务端代码,并重启使用新构建资源的客户端。开发验证只使用合成通话数据及公开音频,不连接真实患者。上线验收需在医生测试账号和合成患者下确认双方音轨归属、转写时延、挂断排空、服务端 AI JSON 格式、取消与复盘。
模型/存储准备阶段先采集到最多 12 个 PCM 分段的内存缓冲;超限明确标记转写不完整。挂断后等待原生识别线程排空才封存文字,15 秒仅提示等待,不提前关闭文字存储。关闭应用时沿用 190 秒异常收尾上限,强制退出会把未完成转写标记为 partial。同会话的存储启动临时失败可以显式重试,正在执行或已成功的启动请求仍复用。
音轨接入适配当前锁定的 CallEngine 3.5.9 / TRTCCloud 2.10.19:`getTRTCCloudInstance()` 返回包装对象,音轨 API 来自其 `_trtc`。`resolveTrtcAudioSource` 先验证实际能力,并保留方法所属实例;升级 SDK 时需重新运行真实包装对象的隔离验证。前端采集失败优先覆盖旧的 native running 状态,并保留独立错误文字和重试入口。持续声音或非零底噪的 PCM 提交窗口为约 4 秒,之后才排队识别,因此字幕按分段追加,不是逐字流式识别。无需提高音量来触发分段,轻声和短否定词不会因前端音量阈值被丢弃。
该音轨修复后,118 项前端测试和 63 项转写桥接/通话回归通过,生产资源已重建。公开语音在隔离 Qt 中贯通了实际 SDK 包装适配、生产音频采集、真实 WebChannel、本地 faster-whisper、Qt 信号及实际 App 字幕 DOM,双方共 8 段均显示;首段实测 6.494 秒。SDK 实例的媒体获取替换为公开音频双轨,存储使用内存,因此仍不代表真实 RTC 发布/订阅与在线持久化已验收。详细材料为 `app/artifacts/im-ai/asr-fixed-end-to-end.md`。已打开的通话页面不会自动载入新脚本,结束当前通话后需关闭并重新打开 IM/视频窗口。
本轮回归:384 项 Python 用例、113 项前端用例通过;PHP 新流式链路 440 项合成断言及 13 组既有回归通过。另有两个既有 PHP 套件在未修改的 HEAD 上同样失败,详见 `app/artifacts/im-ai/live-ai-server-implementation.md`,未将它们计入通过数。Vue 类型检查、前端生产构建、Python Ruff 和 diff 空白检查通过。隔离 QtWebEngine 加载本地合成页面,验证挂断入口、打开不重新生成、完整引用、弹窗 Tab 焦点循环、Escape 返回焦点和 440px 下按钮可见,截图位于 `app/artifacts/im-ai/video-ai-final-*.png`。未执行 macOS 真机构建或冻结安装包验收。
## 核对的官方来源(2026-10-29)
- [faster-whisper v1.2.1 模型和转写接口](https://github.com/SYSTRAN/faster-whisper/blob/v1.2.1/faster_whisper/transcribe.py):本地目录、`local_files_only`、CPU/int8 参数、数组音频输入、惰性 segments、tokenizer 回退。
- [faster-whisper v1.2.1 本地 VAD](https://github.com/SYSTRAN/faster-whisper/blob/v1.2.1/faster_whisper/vad.py):Silero ONNX 资产和 VAD 参数。保留 `min_speech_duration_ms=0`,避免额外丢弃短否定词。
- [faster-whisper 下载实现](https://github.com/SYSTRAN/faster-whisper/blob/master/faster_whisper/utils.py):官方模型映射与模型文件列表。
- [Systran/faster-whisper-small 文件清单](https://huggingface.co/Systran/faster-whisper-small/tree/main):本地模型、tokenizer 和词表文件。
## 简体输出与多方言边界(2026-10-30)
`opencc-python-reimplemented==0.1.7` 是客户端基础依赖。使用随包配置/词典进行本地 `t2s` 字形转换,在原生转写 controller 发出字幕/保存事件前统一为简体;实时字幕、存储和新通话 AI 引用使用同一份文字。已有通话记录打开“面诊对话文字”时以简体显示,不批量改写历史数据库。数字、剂量、否定词、标点和方言词语保留,不使用大模型改写原话。字形转换不能修复误听,也不把粤语词汇翻译成普通话。
安装工具已包含该依赖,PyInstaller 收集 `opencc` 配置和词典;模型启动时预加载转换资源,缺失则明确报错。不要同时安装同样提供 `opencc` 导入名的原生 `opencc` 分发。基础依赖与锁文件更新后,源码运行需要结束通话并重启客户端;单独重新打开网页不会重载原生 Python 代码。已冻结的安装包需要重新构建。
当前通用 Whisper small 不等于多方言专项模型。7 类方言/26 种地域口音的 Fun-ASR-Nano 是本地替代候选,具体能力范围、CPU 成本和离线测试方案见 `app/artifacts/im-ai/dialect-asr-research.md`;未通过目标电脑的双路时延及对应方言准确率验收前,不应声称“所有方言准确识别”。
本机已在隔离环境完成 Nano CPU float32 公开普通话/粤语测试,固定官方权重通过 SHA-256 校验,加载/推理均禁网。Nano 可以保留这条粤语样本词形,但普通话“开放时间”误成“开饭时间”,没有 VAD 的粤语尾段生成额外“对。”。4 秒双路负载预算也缺乏余量;这些结果不支持默认切换。详细输出、耗时和内存见 `app/artifacts/im-ai/dialect-asr-benchmark.md`。该评估没有修改应用运行环境,没有宣称四川/湖南已验收。
后续同机 VAD + 动态 int8 有界实测完成 24 个案例,15 次正常生成、9 次无语音输入被 VAD 跳过;短样本平均耗时下降,但量化期间峰值工作集约 5.7 GiB,且输出词形改变。未验证四川/湖南、医疗数字/否定语音和持续视频负载,因此保持默认引擎。完整结果为 `app/artifacts/im-ai/dialect-asr-quantized-benchmark.md`。评估环境、公开样本及权重保存在 `app/artifacts/im-ai/nano-*`,不会随客户端 resources 打包。
- [转换库发布者文档与固定版本](https://pypi.org/project/opencc-python-reimplemented/0.1.7/):纯 Python、离线词典、t2s 配置。
- [Fun-ASR-Nano 官方模型卡](https://huggingface.co/FunAudioLLM/Fun-ASR-Nano-2512):明确列出的多方言/地域口音范围。
-143
View File
@@ -1,143 +0,0 @@
"""Render the real native client with synthetic data for UI design review."""
from __future__ import annotations
import argparse
import html
import json
import os
from pathlib import Path
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
os.environ.setdefault("DOCTOR_MOTION", "off")
from PySide6.QtCore import QSettings, QThreadPool
from PySide6.QtGui import QImage
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication
from doctor_workstation.services import DemoDoctorRepository
from doctor_workstation.ui import ShellWindow, apply_theme
from doctor_workstation.ui.login import LoginWindow
ROUTES = {
"appointments": "挂号列表",
"consultations": "问诊列表",
"patients": "我的患者",
"prescription_library": "我的处方库",
"prescriptions": "已开处方",
"reception": "接诊台",
}
def settle(app: QApplication) -> None:
for _ in range(4):
QThreadPool.globalInstance().waitForDone(3000)
app.processEvents()
QTest.qWait(75)
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--output", type=Path, default=Path("artifacts/client-design"))
args = parser.parse_args()
output = args.output.resolve()
output.mkdir(parents=True, exist_ok=True)
app = QApplication.instance() or QApplication([])
apply_theme(app)
repo = DemoDoctorRepository()
records = []
def capture(window, name: str, title: str) -> None:
settle(app)
filename = f"{name}.png"
if not window.grab().save(str(output / filename)):
raise RuntimeError(f"Could not save {filename}")
records.append({
"title": title, "file": filename,
"width": window.width(), "height": window.height(),
})
# Isolate preview settings from the user's saved account and credentials.
settings = QSettings(str(output / "preview-login.ini"), QSettings.Format.IniFormat)
settings.clear()
login = LoginWindow(repo, settings=settings)
login.show()
for width, height in ((1280, 800), (860, 640)):
login.resize(width, height)
capture(login, f"login-{width}", "登录工作站")
login.close()
session = repo.login(repo.DEMO_ACCOUNT, repo.DEMO_PASSWORD)
shell = ShellWindow(
repo, {"session": session, "demo_mode": True}, permissions=session.permissions,
)
shell.show()
try:
for width, height in ((1440, 900), (1024, 640)):
shell.resize(width, height)
for route, title in ROUTES.items():
shell.navigate(route)
capture(shell, f"{route}-{width}", title)
finally:
settle(app)
shell.close()
# Include independently rendered dialog/media fixtures when available.
supplementary = [
("patient_orders_1366x768.png", "患者业务订单"),
("patient_progress_1366x768.png", "患者进度"),
("clinical-after/appointment_drawer_1440x900.png", "预约编辑"),
("clinical-after/diagnosis_edit_1440x900.png", "诊单编辑"),
("clinical-after/diagnosis_edit_1024x640.png", "诊单编辑 · 紧凑窗口"),
("clinical-after/diagnosis_index_1440x900.png", "诊单列表"),
("assistant-1440.png", "AI 问诊"),
("assistant-1080.png", "AI 问诊 · 紧凑窗口"),
("../subwindow_exact/prescription_editor_860x900.png", "处方编辑"),
("../subwindow_exact/prescription_ai_report_920x760.png", "处方报告"),
("video-call-1120x760.png", "视频面诊"),
("video-call-440x300.png", "视频面诊 · 小窗"),
("video-chat-440x300.png", "视频聊天 · 小窗"),
("video-preview-1120x760.png", "视频截图确认"),
]
for filename, title in supplementary:
preview = QImage(str(output / filename))
if not preview.isNull():
records.append({
"title": title, "file": filename,
"width": preview.width(), "height": preview.height(),
})
(output / "gallery.json").write_text(
json.dumps(records, ensure_ascii=False, indent=2), encoding="utf-8",
)
cards = []
for record in records:
filename = html.escape(record["file"])
title = html.escape(record["title"])
cards.append(
f'<section><h2>{title} <small>{record["width"]} × {record["height"]}</small>'
f'</h2><a href="{filename}"><img src="{filename}" alt="{title}" loading="lazy">'
'</a></section>'
)
(output / "index.html").write_text(
'<!doctype html><html lang="zh-CN"><meta charset="utf-8">'
'<meta name="viewport" content="width=device-width, initial-scale=1">'
'<title>医生工作站 · 客户端设计验收</title><style>'
'body{margin:0;padding:32px;background:#F5F7FA;color:#223047;'
'font-family:"Microsoft YaHei",sans-serif}main{max-width:1440px;margin:auto}'
'h1{font-size:28px}p,small{color:#647287}small{font-weight:400;font-size:14px}'
'section{margin:32px 0 48px}h2{font-size:20px;display:flex;gap:20px;align-items:baseline}'
'img{width:100%;display:block;border:1px solid #E6EAF0;border-radius:16px}'
'a:focus-visible{outline:3px solid #6D8CCB}footer{padding:24px 0}'
'</style><main><h1>医生工作站 · 客户端设计验收</h1>'
'<p>使用演示数据渲染的真实客户端。点击图片查看原始尺寸。</p>'
+ "".join(cards)
+ '<footer>主窗口与紧凑窗口均按实际控件排版生成。</footer></main></html>',
encoding="utf-8",
)
print(output / "index.html")
if __name__ == "__main__":
main()
+3 -6
View File
@@ -89,7 +89,7 @@ def example_batch() -> dict[str, Any]:
"algorithm_version": "prescription-soft-dice-v1.1.0",
"prompt_version": "manual-prescription-required-candidate-v4",
}
return {"id": 40, "prescription_id": 7556, "patient_id": 1391, "diagnosis_id": 1391, "agreement_visible": True,
return {"id": 40, "prescription_id": 7556, "patient_id": 1391, "diagnosis_id": 1391,
"prescription_revision": 1, "status": "success", "validity": "current",
"comparison_type": "non_independent", "models": models, "coverage_status": "partial",
"created_at": "2026-09-10 15:29:00", "cutoff_at": "2026-09-10 15:29:00",
@@ -143,11 +143,8 @@ class PreviewRepository:
def __init__(self) -> None:
self.batch = example_batch()
def get_prescription_ai_capabilities(self) -> dict[str, Any]:
return {"agreement_visible": True, "can_manage_visibility": False}
def list_prescription_ai_reports(self, **_params: Any) -> dict[str, Any]:
return {"agreement_visible": True, "enabled": True, "lists": deepcopy(self.history()), "count": len(self.history())}
return {"enabled": True, "lists": deepcopy(self.history()), "count": len(self.history())}
def history(self) -> list[dict[str, Any]]:
"""The current batch plus the earlier ones it supersedes, newest first."""
@@ -173,7 +170,7 @@ class PreviewRepository:
"algorithm_version": "prescription-soft-dice-v1.0.0"},
"openai": {"comparison": {"status": "not_comparable"}}}},
]
return [{**row, "agreement_visible": True} for row in [self.batch, *older]]
return [self.batch, *older]
def get_prescription_ai_report(self, _batch_id: int) -> dict[str, Any]:
return deepcopy(self.batch)
@@ -1,111 +0,0 @@
"""Capture agreement authorization states using synthetic data and no network."""
from __future__ import annotations
import os
from copy import deepcopy
from pathlib import Path
from typing import Any
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6.QtWidgets import QApplication
from render_issued_prescription_ai import PreviewRepository
from doctor_workstation.services import DemoDoctorRepository
from doctor_workstation.ui.dialogs import issued_prescription_ai as ai
from doctor_workstation.ui.pages import prescriptions
from doctor_workstation.ui.theme import apply_theme
class VisibilityPreviewRepository(DemoDoctorRepository, PreviewRepository):
def __init__(self) -> None:
DemoDoctorRepository.__init__(self)
PreviewRepository.__init__(self)
self.visible = True
def get_prescription_ai_capabilities(self) -> dict[str, Any]:
return {"agreement_visible": self.visible, "can_manage_visibility": True}
def list_prescription_ai_statuses(self, ids: list[int]) -> dict[str, Any]:
return {"enabled": True, "agreement_visible": self.visible, "items": [
{"prescription_id": value, "agreement_visible": self.visible, "status": "success",
"models": {"qwen": {"status": "success", "score": 68.5},
"openai": {"status": "success", "score": 55.2}}} for value in ids]}
def list_prescription_ai_reports(self, **_params: Any) -> dict[str, Any]:
rows = [{**row, "agreement_visible": self.visible} for row in self.history()]
return {"agreement_visible": self.visible, "enabled": True, "lists": deepcopy(rows), "count": len(rows)}
def get_prescription_ai_report(self, _batch_id: int) -> dict[str, Any]:
return {**deepcopy(self.batch), "agreement_visible": self.visible}
def main() -> None:
application = QApplication.instance() or QApplication([])
apply_theme(application)
output = Path(__file__).resolve().parents[2] / "artifacts" / "prescription-ai-visibility"
output.mkdir(parents=True, exist_ok=True)
def immediate(function: Any, **callbacks: Any) -> None:
try:
result = function()
except Exception as error:
if callbacks.get("on_error"):
callbacks["on_error"](error)
else:
raise
else:
if callbacks.get("on_success"):
callbacks["on_success"](result)
finally:
if callbacks.get("on_finished"):
callbacks["on_finished"]()
ai.run_async = immediate
prescriptions.run_async = immediate
repository = VisibilityPreviewRepository()
def capture(widget: Any, filename: str) -> None:
for _ in range(4):
application.processEvents()
assert widget.grab().save(str(output / filename))
page = prescriptions.PrescriptionsPage(repository, ["*"], {"name": "演示医生", "root": 1})
page.resize(1366, 800)
page.show()
capture(page, "list-authorized.png")
repository.visible = False
page.refresh()
capture(page, "list-restricted.png")
page.close()
repository.visible = True
dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=7556,
current_user={"name": "演示医生", "root": 1})
dialog.resize(1280, 860)
dialog.show()
capture(dialog, "report-authorized.png")
repository.visible = False
repository.batch["status"] = "partial"
repository.batch["models"]["openai"].update(
status="failed", report=None, candidate=None, comparison=None,
error_code="upstream_timeout", error_message="演示:模型连接超时,可重试。")
dialog.refresh()
dialog._goto("report")
capture(dialog, "report-restricted.png")
dialog._goto("overview")
capture(dialog, "review-restricted.png")
dialog._goto("per_herb")
capture(dialog, "candidate-restricted.png")
dialog.close()
statistics = ai.PrescriptionAiStatisticsDialog(repository, ["*"])
statistics.resize(1180, 860)
statistics.show()
capture(statistics, "statistics-restricted.png")
statistics.close()
print(output)
if __name__ == "__main__":
main()
-101
View File
@@ -1,101 +0,0 @@
"""Start the source workstation against a loopback backend with isolated login state."""
from __future__ import annotations
import functools
import os
import socket
import sys
from dataclasses import replace
from pathlib import Path
from urllib.parse import urlsplit
import certifi
def validate_local_url(api: str) -> None:
parsed = urlsplit(api)
if (parsed.scheme != "https" or not parsed.hostname or parsed.username or parsed.password
or parsed.query or parsed.fragment):
raise ValueError("本地入口需要不带凭据的 HTTPS 地址")
addresses = {row[4][0] for row in socket.getaddrinfo(parsed.hostname, parsed.port or 443)}
if not addresses or not addresses <= {"127.0.0.1", "::1"}:
raise ValueError("本地入口仅连接解析到本机的后端")
def validate_effective_config(config, requested_api: str) -> None:
from doctor_workstation.config import normalize_api_base_url
validate_local_url(config.api_base_url)
if config.api_base_url != normalize_api_base_url(requested_api) or not config.verify_ssl:
raise ValueError("本地独立配置已改动,请在 .local-workstation/config 中核对本地服务器设置")
def local_config_type(api: str):
"""Pin this explicit local entry, including later login/config updates."""
from doctor_workstation.config import AppConfig, normalize_api_base_url
validate_local_url(api)
local_api = normalize_api_base_url(api)
class LocalAppConfig(AppConfig):
def _merge_preferences(self):
config = super()._merge_preferences()
# Use the locked login behavior with the selected local endpoint.
# Shared Qt settings and stale local preferences must not send a
# local verification session back to the production backend.
return replace(config, api_base_url=local_api, debug_mode=False,
demo_mode=False, verify_ssl=True)
return LocalAppConfig
def main() -> int:
# Select the native backend before Qt creates network objects or scans TLS
# plugins. Selecting it later can load conflicting OpenSSL DLLs on Windows.
if sys.platform == "win32":
os.environ["QT_TLS_BACKEND"] = "schannel"
root = Path(__file__).resolve().parents[1]
api = os.environ.get("DOCTOR_LOCAL_API_URL", "https://css.zhenyangtang.com.cn")
validate_local_url(api)
certificate = Path(os.environ.get(
"DOCTOR_LOCAL_CA_FILE",
"D:/phpstudy_pro/Extensions/Nginx1.15.11/conf/ssl/css.zhenyangtang.com.cn.pem",
))
private_root = root / ".local-workstation"
private_root.mkdir(parents=True, exist_ok=True)
ca_bundle = private_root / "trusted-ca.pem"
ca_bundle.write_bytes(Path(certifi.where()).read_bytes() + b"\n" + certificate.read_bytes())
os.environ.update({
"DOCTOR_CONFIG_DIR": str(private_root / "config"),
"DOCTOR_LOG_DIR": str(private_root / "logs"),
"DOCTOR_API_BASE_URL": api,
"DOCTOR_DEMO_MODE": "false",
"DOCTOR_VERIFY_SSL": "true",
"SSL_CERT_FILE": str(ca_bundle),
})
sys.path.insert(0, str(root / "src"))
# This explicit source-only entry does not edit the formal build configuration.
LocalAppConfig = local_config_type(api)
config = LocalAppConfig.load()
validate_effective_config(config, api)
config.save_preferences()
if "--check" in sys.argv:
print("Local backend: loopback HTTPS; TLS verification enabled; isolated configuration and credential namespace")
return 0
from PySide6.QtCore import QSettings
from doctor_workstation import app as workstation_app
workstation_app.AppConfig = LocalAppConfig
workstation_app.LoginWindow = functools.partial(
workstation_app.LoginWindow,
settings=QSettings("ZhenYangTang", "DoctorWorkstationLocalSource"),
)
# The normal credential service remains untouched even after a local login.
workstation_app.TokenStore = functools.partial(
workstation_app.TokenStore, service_name="zyt-doctor-workstation-local-source"
)
return workstation_app.main()
if __name__ == "__main__":
raise SystemExit(main())
-193
View File
@@ -1,193 +0,0 @@
"""Explicit installation/download/check CLI; never invoked by a live call.
Run with --help for examples. With no action flags this only prints help.
"""
from __future__ import annotations
import argparse
import importlib.util
import json
import os
import shutil
import subprocess
import sys
import wave
from datetime import UTC, datetime
from pathlib import Path
from unittest.mock import patch
APP_ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(APP_ROOT / "src"))
MODEL_REPOS = {
size: f"Systran/faster-whisper-{size}"
for size in ("tiny", "base", "small", "medium", "large-v3")
}
RUNTIME_REQUIREMENT = "faster-whisper==1.2.1"
TEXT_REQUIREMENT = "opencc-python-reimplemented==0.1.7"
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Install or verify local CPU/int8 speech recognition before making calls.",
epilog=(
"Example: python scripts/setup_local_transcription.py "
"--install-dependencies --download --model-size small --check. "
"Offline check: python scripts/setup_local_transcription.py --check. "
"A packaged app must ship the runtime; installing into another Python "
"does not alter a frozen executable."
),
)
parser.add_argument(
"--install-dependencies",
action="store_true",
help="Explicitly run pip in this Python environment.",
)
parser.add_argument(
"--download",
action="store_true",
help="Explicitly download the selected official model from Hugging Face.",
)
parser.add_argument("--model-size", choices=tuple(MODEL_REPOS), default="small")
parser.add_argument(
"--model-path",
type=Path,
help="Override DOCTOR_ASR_MODEL_PATH or the app data model directory.",
)
parser.add_argument(
"--revision", default="main", help="Official repository revision/commit for model download."
)
parser.add_argument(
"--check",
action="store_true",
help="Load the local model and VAD on CPU with networking disabled.",
)
parser.add_argument(
"--smoke-wav",
type=Path,
help="Optional non-sensitive mono 16 kHz PCM16 WAV, at most 12 seconds; recognized text is printed.",
)
args = parser.parse_args(argv)
if not (args.install_dependencies or args.download or args.check or args.smoke_wav):
parser.print_help()
return args
def main(argv: list[str] | None = None) -> int:
args = parse_args(argv)
if not (args.install_dependencies or args.download or args.check or args.smoke_wav):
return 0
if args.install_dependencies:
installer = [sys.executable, "-m", "pip", "install"]
if importlib.util.find_spec("pip") is None:
uv = shutil.which("uv")
if not uv:
print(
"This environment has no pip. Install with uv pip install --python <python> "
f"{RUNTIME_REQUIREMENT} {TEXT_REQUIREMENT}",
file=sys.stderr,
)
return 1
installer = [uv, "pip", "install", "--python", sys.executable]
subprocess.run(
[*installer, RUNTIME_REQUIREMENT, TEXT_REQUIREMENT, "platformdirs>=4.3,<5"],
check=True,
)
from doctor_workstation.core.transcript_text import simplified_transcript
from doctor_workstation.video.local_transcription import (
MAX_PCM_BYTES,
SAMPLE_RATE,
FasterWhisperEngine,
LocalTranscriptionError,
default_model_path,
local_transcription_readiness,
)
path = args.model_path.expanduser().resolve() if args.model_path else default_model_path()
try:
if args.download:
from huggingface_hub import snapshot_download
path.mkdir(parents=True, exist_ok=True)
repo = MODEL_REPOS[args.model_size]
print(f"Downloading {repo} into {path}")
snapshot_download(
repo_id=repo,
revision=args.revision,
local_dir=str(path),
allow_patterns=[
"config.json",
"preprocessor_config.json",
"model.bin",
"tokenizer.json",
"vocabulary.*",
"README.md",
"LICENSE*",
],
token=False,
)
(path / "doctor-asr-install.json").write_text(
json.dumps(
{
"repository": repo,
"requestedRevision": args.revision,
"runtimeRequirement": RUNTIME_REQUIREMENT,
"textRequirement": TEXT_REQUIREMENT,
"installedAt": datetime.now(UTC).isoformat(),
},
indent=2,
)
+ "\n",
encoding="utf-8",
)
if args.check or args.smoke_wav or args.download:
# This affects only the explicit setup/check process. The runtime
# already requires complete local files and local_files_only=True.
os.environ["HF_HUB_OFFLINE"] = "1"
os.environ["HF_HUB_DISABLE_TELEMETRY"] = "1"
print(json.dumps(local_transcription_readiness(path), ensure_ascii=False, indent=2))
# The hub may already have been imported during --download, so its
# offline environment flag alone is not a sufficient verification.
# Block sockets in this standalone check process as well.
blocked = RuntimeError("Network access is disabled during local ASR verification")
with (
patch("socket.socket.connect", side_effect=blocked),
patch("socket.socket.connect_ex", side_effect=blocked),
patch("socket.getaddrinfo", side_effect=blocked),
):
engine = FasterWhisperEngine(path)
print("Local model and VAD loaded successfully (CPU/int8; network blocked).")
if args.smoke_wav:
with wave.open(str(args.smoke_wav), "rb") as audio:
if (
audio.getnchannels(),
audio.getsampwidth(),
audio.getframerate(),
audio.getcomptype(),
) != (1, 2, SAMPLE_RATE, "NONE"):
raise ValueError("Smoke WAV must be mono 16 kHz uncompressed PCM16.")
if not 0 < audio.getnframes() <= MAX_PCM_BYTES // 2:
raise ValueError(
"Smoke WAV must contain between one sample and 12 seconds."
)
pcm = audio.readframes(audio.getnframes())
print(f"Recognized text: {simplified_transcript(engine.transcribe(pcm))}")
return 0
except LocalTranscriptionError as error:
print(f"Local ASR setup failed ({error.code}): {error}", file=sys.stderr)
except ImportError:
print(
"Required packages are missing; run with --install-dependencies first.", file=sys.stderr
)
except (OSError, ValueError, RuntimeError) as error:
print(
f"Local ASR setup failed: {type(error).__name__}. Check model files, WAV format, and connectivity for explicit downloads.",
file=sys.stderr,
)
return 1
if __name__ == "__main__":
raise SystemExit(main())
+1 -1
View File
@@ -3,7 +3,7 @@
__all__ = ["DEBUG_MODE", "ONLINE_API_BASE_URL", "__version__"]
# Single source of truth for runtime, package, installer, and executable versions.
__version__ = "1.5.1"
__version__ = "1.4.5"
# 调试模式开启时,登录页显示“演示模式”和“服务器设置”。
# 正式发布请保持 False;此时程序只使用下面配置的线上域名。
+1 -16
View File
@@ -41,7 +41,6 @@ from doctor_workstation.ui.widgets import (
friendly_error,
gender_text,
get_value,
has_permission,
run_async,
set_authentication_expired_handler,
show_toast,
@@ -940,11 +939,6 @@ class ApplicationController(QObject):
open_im=open_im,
patient_name=patient_name,
patient_case=patient_case,
can_ai_assistant=has_permission(
getattr(self.shell_window, "permissions", None),
"tcm.diagnosis/aiAssistant",
default=False,
),
on_open_diagnosis=lambda current_id=diagnosis_id, current_key=call_key: (
self._open_video_diagnosis(current_id, call_key=current_key)
),
@@ -1030,14 +1024,11 @@ class ApplicationController(QObject):
lambda _result, expected=generation: self._restore_video_preview(expected)
)
try:
set_close_handler = getattr(video_window, "set_compact_close_handler", None)
if callable(set_close_handler):
set_close_handler(lambda expected=generation: self._restore_video_preview(expected))
video_window.raise_()
dialog.raise_()
dialog.activateWindow()
except RuntimeError:
self._restore_video_preview(generation, activate=False)
self._video_preview_state = None
def _restore_video_preview(
self,
@@ -1054,12 +1045,6 @@ class ApplicationController(QObject):
self._video_preview_generation += 1
window = state.get("window")
try:
set_close_handler = getattr(window, "set_compact_close_handler", None)
if callable(set_close_handler):
set_close_handler(None)
restore_screenshot = getattr(window, "restore_screenshot_preview", None)
if callable(restore_screenshot):
restore_screenshot()
window.setWindowFlag(
Qt.WindowType.WindowStaysOnTopHint,
bool(state.get("stays_on_top")),
@@ -1,23 +0,0 @@
"""Offline script conversion for speech transcripts, without paraphrasing."""
from __future__ import annotations
from threading import local
_converters = local()
def simplified_transcript(text: str) -> str:
"""Convert character forms only; retain dialect words, numbers and negations.
Each thread owns its converter. Cache dictionaries, never patient text.
The t2s configuration deliberately excludes regional vocabulary rewriting.
Missing package data is an error, rather than silently mixing scripts.
"""
converter = getattr(_converters, "simplified", None)
if converter is None:
from opencc import OpenCC
converter = OpenCC("t2s")
_converters.simplified = converter
return converter.convert(text)
@@ -2,19 +2,16 @@
from __future__ import annotations
import asyncio
import json
import time
from collections import deque
from collections.abc import Callable, Iterator, Mapping
from contextlib import contextmanager, suppress
from contextlib import contextmanager
from threading import Condition, RLock
from typing import Any
from urllib.parse import urljoin, urlsplit, urlunsplit
import httpx
from doctor_workstation import __version__
from doctor_workstation.core.errors import (
ApiBusinessError,
ApiHttpError,
@@ -231,29 +228,6 @@ class ApiClient:
headers=headers,
)
def post_independent(
self,
endpoint: str,
payload: Mapping[str, Any],
*,
timeout: float = 10.0,
) -> Any:
"""Send a short control request without waiting for the ordinary pool."""
try:
with httpx.Client(transport=self._stream_transport, verify=self._verify) as client:
response = client.post(
self._endpoint_url(endpoint),
json=dict(payload),
headers=self._headers(None),
timeout=timeout,
)
return self._unwrap(response)
except httpx.TimeoutException as exc:
raise ApiTimeoutError(f"POST {endpoint} timed out") from exc
except httpx.RequestError as exc:
raise ApiTransportError(f"POST {endpoint} failed") from exc
def post_event_stream(
self,
endpoint: str,
@@ -273,14 +247,6 @@ class ApiClient:
headers = self._headers({"Accept": "text/event-stream"})
request_timeout = self.timeout if timeout is None else timeout
try:
if cancelled is not None and (
self._stream_transport is None
or isinstance(self._stream_transport, httpx.AsyncBaseTransport)
):
yield from self._cancellable_event_stream(
url, payload, headers, request_timeout, cancelled
)
return
with httpx.Client(
transport=self._stream_transport,
verify=self._verify,
@@ -320,109 +286,6 @@ class ApiClient:
data={"method": "POST", "endpoint": endpoint},
) from exc
def _cancellable_event_stream(
self,
url: str,
payload: Mapping[str, Any],
headers: Mapping[str, str],
timeout: float | httpx.Timeout,
cancelled: Callable[[], bool],
) -> Iterator[dict[str, Any]]:
"""Own network reads and cancellation on the same worker-local event loop.
Closing a synchronous httpx response from another thread can wait on its
active read lock. Cancelling an async read interrupts idle headers/body
reads and closes their sockets on their owning loop instead.
"""
async def events():
async with httpx.AsyncClient(
transport=self._stream_transport, verify=self._verify
) as client, client.stream(
"POST", url, json=dict(payload), headers=headers, timeout=timeout
) as response:
if not 200 <= response.status_code < 300:
raise ApiHttpError(
f"API returned HTTP {response.status_code}",
status_code=response.status_code,
request_id=self._request_id(response),
)
content_type = response.headers.get("content-type", "").lower()
if "text/event-stream" not in content_type:
await response.aread()
if "json" in content_type:
self._unwrap(response)
raise ApiProtocolError("API response is not an event stream")
frame: list[str] = []
async for line in response.aiter_lines():
frame.append(line)
if not line:
for event in _iter_event_stream(frame):
yield event
frame.clear()
for event in _iter_event_stream(frame):
yield event
if cancelled():
return
loop = asyncio.new_event_loop()
iterator = events()
pending: deque[dict[str, Any]] = deque()
polling = False
wake_handle: asyncio.Handle | None = None
def wake_consumer() -> None:
nonlocal wake_handle
if polling and wake_handle is None:
wake_handle = loop.call_soon(loop.stop)
async def pump() -> None:
try:
async for event in iterator:
if cancelled():
return
pending.append(event)
wake_consumer()
# Bound buffered work and let the scheduled batch wake run,
# even when one HTTP chunk contains thousands of SSE frames.
if len(pending) >= 256:
await asyncio.sleep(0)
finally:
wake_consumer()
producer = loop.create_task(pump())
async def close_producer() -> None:
producer.cancel()
with suppress(asyncio.CancelledError, Exception):
await producer
await iterator.aclose()
try:
while not cancelled():
# Read buffered frames directly. There is one persistent async
# producer, not a new task/event-loop crossing for every delta.
if pending:
yield pending.popleft()
continue
if producer.done():
producer.result() # Propagate EOF errors after queued tails.
return
polling = True
wake_handle = None
timer = loop.call_later(0.03, loop.stop)
try:
loop.run_forever()
finally:
polling = False
timer.cancel()
if wake_handle is not None:
wake_handle.cancel()
finally:
loop.run_until_complete(close_producer())
loop.run_until_complete(loop.shutdown_asyncgens())
loop.close()
def get_bytes(self, url: str, *, max_bytes: int = 5 * 1024 * 1024) -> bytes:
"""Download a public binary asset without applying the JSON envelope contract."""
@@ -620,7 +483,6 @@ class ApiClient:
result = {
"Accept": "application/json",
"version": self.API_VERSION,
"User-Agent": f"ZytDoctorWorkstation/{__version__}",
}
if json_content_type:
result["Content-Type"] = "application/json;charset=UTF-8"
@@ -4,10 +4,9 @@ from __future__ import annotations
import hashlib
import json
import re
import struct
import zlib
from collections.abc import Callable, Mapping, Sequence
from collections.abc import Mapping, Sequence
from copy import deepcopy
from datetime import date, datetime, timedelta
from os import PathLike
@@ -2772,14 +2771,10 @@ class DemoDoctorRepository:
*,
call_record_id: int | None = None,
mime_type: str = "audio/webm",
on_progress: Callable[[int, int], None] | None = None,
) -> dict[str, Any]:
"""Upload then attach a demo local-audio file using the production sequence."""
source_path = Path(path)
size = source_path.stat().st_size if source_path.is_file() else 0
if on_progress is not None:
on_progress(0, size)
is_audio = source_path.suffix.lower() in {
".ogg",
".opus",
@@ -2816,8 +2811,6 @@ class DemoDoctorRepository:
record["local_audio_status_text"] = "已保存"
else:
self.attach_local_call_recording(diagnosis_id, file_url, call_record_id=target_id)
if on_progress is not None:
on_progress(size, size)
return {
"diagnosis_id": diagnosis_id,
"call_record_id": target_id,
@@ -2847,22 +2840,11 @@ class DemoDoctorRepository:
}
)
def sync_im_chat_messages(
self, diagnosis_id: int, *, scope: str = "", sync_token: str = ""
) -> dict[str, Any]:
"""Complete synthetic archive sync while retaining the legacy receipt."""
def sync_im_chat_messages(self, diagnosis_id: int) -> dict[str, Any]:
"""Acknowledge the same asynchronous sync contract in demo mode."""
self._find_consultation(diagnosis_id)
if scope not in {"", "current"}:
raise ValueError("IM sync scope must be empty or current")
if not isinstance(sync_token, str) or (
sync_token and re.fullmatch(r"[a-f0-9]{48}", sync_token) is None
):
raise ValueError("IM sync token is invalid")
return {
"queued": True, "diagnosis_id": diagnosis_id,
"completed": True, "phase": "completed", "errors": [],
}
return {"queued": True, "diagnosis_id": diagnosis_id}
def list_diagnosis_appointment_logs(self, diagnosis_id: int) -> list[dict[str, Any]]:
"""Build demo audit rows from the diagnosis appointments."""
+12 -115
View File
@@ -206,20 +206,9 @@ class DoctorRepository(Protocol):
prompt: str,
*,
task: str = "custom",
request_id: str | None = None,
cancelled: Callable[[], bool] | None = None,
) -> Iterator[dict[str, Any]]:
"""Yield normalized assistant content and preparation progress events."""
def cancel_diagnosis_ai(self, diagnosis_id: int, request_id: str) -> dict[str, Any]:
"""Request server/upstream cancellation of one correlated stream."""
def stream_video_ai(
self, diagnosis_id: int, *, call_record_id: int,
transcription_session_id: str, task: str = "live_consultation",
request_id: str, cancelled: Callable[[], bool] | None = None,
) -> Iterator[dict[str, Any]]:
"""Analyze the server-owned snapshot of this exact video call."""
"""Yield normalized ``start``/``delta``/``done`` assistant events."""
def generate_ai_prescription(self, diagnosis_id: int) -> dict[str, Any]:
"""Generate a server-validated prescription draft for doctor review."""
@@ -246,9 +235,6 @@ class DoctorRepository(Protocol):
def get_prescription(self, prescription_id: int) -> Prescription:
"""Return one issued prescription."""
def get_prescription_ai_capabilities(self) -> dict[str, Any]:
"""Read the server's current agreement visibility decision."""
def list_prescription_ai_statuses(self, ids: list[int]) -> dict[str, Any]:
"""Read cached dual-model states for up to 100 prescriptions."""
@@ -690,7 +676,6 @@ class DoctorRepository(Protocol):
*,
call_record_id: int | None = None,
mime_type: str = "audio/webm",
on_progress: Callable[[int, int], None] | None = None,
) -> dict[str, Any]:
"""Upload a locally captured call recording to a real call record."""
@@ -699,10 +684,8 @@ class DoctorRepository(Protocol):
) -> dict[str, Any]:
"""Return diagnosis IM messages, defaulting to the fast archive-only path."""
def sync_im_chat_messages(
self, diagnosis_id: int, *, scope: str = "", sync_token: str = ""
) -> Any:
"""Advance one server-side archive page; inspect completed before using it."""
def sync_im_chat_messages(self, diagnosis_id: int) -> Any:
"""Queue the server-side IM archive synchronisation job."""
def list_diagnosis_appointment_logs(self, diagnosis_id: int) -> list[dict[str, Any]]:
"""Return per-diagnosis registration / cancellation audit rows."""
@@ -1427,16 +1410,12 @@ class RemoteDoctorRepository:
prompt: str,
*,
task: str = "custom",
request_id: str | None = None,
cancelled: Callable[[], bool] | None = None,
) -> Iterator[dict[str, Any]]:
"""Stream a diagnosis answer; use the legacy route only when streaming is absent."""
clean_prompt, clean_task = _diagnosis_ai_request(diagnosis_id, prompt, task)
body = {
"id": diagnosis_id, "prompt": clean_prompt, "task": clean_task,
"request_id": request_id or str(uuid4()),
}
body = {"id": diagnosis_id, "prompt": clean_prompt, "task": clean_task}
received_event = False
received_done = False
try:
@@ -1485,54 +1464,6 @@ class RemoteDoctorRepository:
yield {"event": "delta", "text": answer, "fallback": True}
yield {**result, "event": "done", "fallback": True}
def stream_video_ai(
self, diagnosis_id: int, *, call_record_id: int,
transcription_session_id: str, task: str = "live_consultation",
request_id: str, cancelled: Callable[[], bool] | None = None,
) -> Iterator[dict[str, Any]]:
"""No legacy fallback: an older route cannot bind a live call safely."""
if (isinstance(diagnosis_id, bool) or not isinstance(diagnosis_id, int)
or diagnosis_id <= 0 or isinstance(call_record_id, bool)
or not isinstance(call_record_id, int) or call_record_id <= 0):
raise ValueError("diagnosis and call_record_id must be positive integers")
if (not isinstance(transcription_session_id, str)
or re.fullmatch(r"[A-Za-z0-9_-]{1,128}", transcription_session_id) is None):
raise ValueError("invalid transcription session")
if task not in {"live_consultation", "live_review"}:
raise ValueError("unsupported video AI task")
body = {
"id": diagnosis_id, "task": task,
"prompt": "请依据本次通话已保存的原文整理症状、追问和待核实信息,供医生复核。",
"call_record_id": call_record_id,
"transcription_session_id": transcription_session_id,
"request_id": request_id,
}
for raw in self.client.post_event_stream(
"tcm.diagnosis/aiAssistantStream", body, timeout=105.0, cancelled=cancelled,
):
if cancelled is not None and cancelled():
return
event = _normalise_diagnosis_ai_event(raw)
if event is not None:
yield event
if event["event"] == "done":
return
if cancelled is None or not cancelled():
raise ApiProtocolError("video AI stream ended before done")
def cancel_diagnosis_ai(self, diagnosis_id: int, request_id: str) -> dict[str, Any]:
"""Use an independent short request, even while the stream is idle."""
if diagnosis_id <= 0 or not request_id.strip():
raise ValueError("diagnosis_id and request_id are required")
method = "post_independent" if callable(getattr(self.client, "post_independent", None)) else "post"
payload = _client_request(
self.client, method, "tcm.diagnosis/cancelAiAssistant",
{"id": diagnosis_id, "request_id": request_id}, timeout=10.0,
)
return dict(_require_mapping(payload, "tcm.diagnosis/cancelAiAssistant"))
def generate_ai_prescription(self, diagnosis_id: int) -> dict[str, Any]:
"""Generate a structured draft using the server's full patient context."""
@@ -1680,9 +1611,6 @@ class RemoteDoctorRepository:
payload = _client_request(self.client, "post" if mutation else "get", endpoint, params, timeout=30.0)
return dict(_require_mapping(payload, endpoint))
def get_prescription_ai_capabilities(self) -> dict[str, Any]:
return self._prescription_ai_request("capabilities", {})
def list_prescription_ai_statuses(self, ids: list[int]) -> dict[str, Any]:
if len(ids) > 100 or any(int(value) <= 0 for value in ids):
raise ValueError("statuses requires at most 100 positive prescription IDs")
@@ -2558,13 +2486,8 @@ class RemoteDoctorRepository:
*,
call_record_id: int | None = None,
mime_type: str = "audio/webm",
on_progress: Callable[[int, int], None] | None = None,
) -> dict[str, Any]:
"""Chunk-upload one local audio recording and attach it atomically.
``on_progress(sent_bytes, total_bytes)`` runs on the calling thread after
every confirmed chunk; its failures never interrupt the upload.
"""
"""Chunk-upload one local audio recording and attach it atomically."""
if diagnosis_id <= 0:
raise ValueError("diagnosis_id must be positive")
@@ -2584,13 +2507,6 @@ class RemoteDoctorRepository:
clean_mime = str(mime_type or "audio/webm").strip()[:120] or "audio/webm"
final_result: Mapping[str, Any] | None = None
bound_call_record_id = call_record_id
def report(sent: int) -> None:
if on_progress is not None:
with suppress(Exception):
on_progress(min(sent, file_size), file_size)
report(0)
with recording_path.open("rb") as stream:
for chunk_index in range(chunk_total):
content = stream.read(chunk_size)
@@ -2625,7 +2541,6 @@ class RemoteDoctorRepository:
raise ApiProtocolError(
"uploadCallRecording returned a different call_record_id"
)
report((chunk_index + 1) * chunk_size)
if final_result is None or not bool(final_result.get("completed")):
raise ApiProtocolError("uploadCallRecording did not complete the local audio upload")
@@ -2647,27 +2562,12 @@ class RemoteDoctorRepository:
)
return dict(_require_mapping(payload, "tcm.diagnosis/getImChatMessages"))
def sync_im_chat_messages(
self, diagnosis_id: int, *, scope: str = "", sync_token: str = ""
) -> Any:
"""Advance a bounded archive page, preserving legacy no-option callers."""
def sync_im_chat_messages(self, diagnosis_id: int) -> Any:
"""Queue the confirmed shutdown-function archive sync endpoint."""
if diagnosis_id <= 0:
raise ValueError("diagnosis_id must be positive")
if scope not in {"", "current"}:
raise ValueError("IM sync scope must be empty or current")
if not isinstance(sync_token, str) or (
sync_token and re.fullmatch(r"[a-f0-9]{48}", sync_token) is None
):
raise ValueError("IM sync token is invalid")
payload: dict[str, Any] = {"diagnosis_id": diagnosis_id}
if scope:
payload["scope"] = scope
if sync_token:
payload["sync_token"] = sync_token
return _client_request(
self.client, "post", "tcm.diagnosis/triggerImChatSync", payload, timeout=15.0
)
return self.client.post("tcm.diagnosis/triggerImChatSync", {"diagnosis_id": diagnosis_id})
def list_diagnosis_appointment_logs(self, diagnosis_id: int) -> list[dict[str, Any]]:
"""Return registration/cancellation logs from ``guahaoLogList``."""
@@ -3064,9 +2964,6 @@ def _diagnosis_ai_request(diagnosis_id: int, prompt: str, task: str) -> tuple[st
raise ValueError("prompt must not exceed 500 characters")
clean_task = task.strip().lower() or "custom"
if clean_task not in {
"case_analysis",
"glucose_trend",
"lifestyle_advice",
"summary",
"tcm_pattern",
"prescription_review",
@@ -3087,10 +2984,10 @@ def _normalise_diagnosis_ai_event(raw: Mapping[str, Any]) -> dict[str, Any] | No
payload = dict(data) if isinstance(data, Mapping) else {}
if kind == "message":
kind = str(payload.get("event") or payload.get("type") or "message").lower()
if kind in {"start", "progress"}:
if kind == "start":
payload.pop("event", None)
payload.pop("type", None)
return {**payload, "event": kind}
return {**payload, "event": "start"}
if kind == "delta":
text = (
data
@@ -3103,10 +3000,10 @@ def _normalise_diagnosis_ai_event(raw: Mapping[str, Any]) -> dict[str, Any] | No
if not isinstance(text, str):
raise ApiProtocolError("AI assistant delta content must be text", data=data)
return {"event": "delta", "text": text}
if kind in {"live_update", "done"}:
if kind == "done":
payload.pop("event", None)
payload.pop("type", None)
return {**payload, "event": kind}
return {**payload, "event": "done"}
if kind == "error":
message = (
data
@@ -23,6 +23,7 @@ from PySide6.QtWidgets import (
QComboBox,
QDialog,
QFrame,
QGraphicsDropShadowEffect,
QGraphicsOpacityEffect,
QHBoxLayout,
QLabel,
@@ -42,7 +43,6 @@ from PySide6.QtWidgets import (
)
from ..core.appointment_modes import APPOINTMENT_MODES
from .design_system import clinical_stylesheet
from .theme import main_window_target_rect
from .widgets import (
display_text,
@@ -84,8 +84,8 @@ QDialog#AppointmentDrawerOverlay QToolButton#AppointmentDrawerClose {
min-height: 32px;
max-height: 32px;
padding: 0;
border: 1px solid transparent;
border-radius: $ds_radius_control;
border: 0;
border-radius: 4px;
background-color: transparent;
color: #606163;
font-size: 22px;
@@ -95,10 +95,6 @@ QDialog#AppointmentDrawerOverlay QToolButton#AppointmentDrawerClose {
QDialog#AppointmentDrawerOverlay QToolButton#AppointmentDrawerClose:hover {
color: #1A1C1F;
background-color: #F0F0F0;
}
QDialog#AppointmentDrawerOverlay QToolButton#AppointmentDrawerClose:focus {
border-color: $ds_focus;
background-color: $ds_accent_soft;
}
QDialog#AppointmentDrawerOverlay QScrollArea#AppointmentDrawerBody,
@@ -114,7 +110,7 @@ QDialog#AppointmentDrawerOverlay QWidget#AppointmentDrawerBodyContent {
}
QDialog#AppointmentDrawerOverlay QLabel[appointmentLabel="true"] {
color: $ds_muted;
color: #1A1C1F;
font-size: 14px;
font-weight: 500;
}
@@ -129,7 +125,7 @@ QDialog#AppointmentDrawerOverlay QPlainTextEdit {
min-height: 30px;
padding: 0 11px;
border: 1px solid #EDEDEE;
border-radius: 10px;
border-radius: 9px;
background-color: #FFFFFF;
color: #1A1C1F;
selection-background-color: #EEF1FA;
@@ -149,14 +145,7 @@ QDialog#AppointmentDrawerOverlay QPlainTextEdit:hover {
QDialog#AppointmentDrawerOverlay QComboBox:focus,
QDialog#AppointmentDrawerOverlay QLineEdit:focus,
QDialog#AppointmentDrawerOverlay QPlainTextEdit:focus {
border: 1px solid #8B9AD9;
}
QDialog#AppointmentDrawerOverlay QComboBox:disabled,
QDialog#AppointmentDrawerOverlay QLineEdit:disabled,
QDialog#AppointmentDrawerOverlay QPlainTextEdit:disabled {
color: $ds_disabled;
background-color: $ds_disabled_surface;
border-color: $ds_line;
border: 2px solid #8B9AD9;
}
QDialog#AppointmentDrawerOverlay QComboBox::drop-down {
@@ -208,7 +197,7 @@ QDialog#AppointmentDrawerOverlay QPushButton[appointmentDate="true"] {
max-height: 38px;
padding: 0;
border: 1px solid #EDEDEE;
border-radius: 10px;
border-radius: 8px;
background-color: #FFFFFF;
color: #1A1C1F;
font-size: 14px;
@@ -232,15 +221,15 @@ QDialog#AppointmentDrawerOverlay QPushButton[appointmentDate="true"]:checked {
}
QDialog#AppointmentDrawerOverlay QFrame#AppointmentSlotsPanel {
background-color: $ds_surface_alt;
background-color: #F7F7F7;
border: 0;
border-radius: $ds_radius_panel;
border-radius: 8px;
}
QDialog#AppointmentDrawerOverlay QLabel#AppointmentSlotsTitle {
color: #1A1C1F;
font-size: 15px;
font-weight: 600;
font-weight: 500;
}
QDialog#AppointmentDrawerOverlay QPushButton#AppointmentRefreshSlots {
@@ -258,17 +247,13 @@ QDialog#AppointmentDrawerOverlay QPushButton#AppointmentRefreshSlots {
QDialog#AppointmentDrawerOverlay QPushButton#AppointmentRefreshSlots:hover {
background-color: #EEF1FA;
}
QDialog#AppointmentDrawerOverlay QPushButton#AppointmentRefreshSlots:focus {
background-color: $ds_accent_soft;
border: 1px solid $ds_focus;
}
QDialog#AppointmentDrawerOverlay QPushButton[appointmentSlot="true"] {
min-width: 110px;
min-height: 70px;
padding: 0 8px;
border: 2px solid #EDEDEE;
border-radius: 10px;
border-radius: 8px;
background-color: #FFFFFF;
color: #1A1C1F;
}
@@ -345,25 +330,25 @@ QDialog#AppointmentDrawerOverlay QLabel#AppointmentEmptyText {
QDialog#AppointmentDrawerOverlay QFrame#AppointmentAlert[kind="info"] {
background-color: #EEF1FA;
border: 1px solid #EDEDEE;
border-radius: 10px;
border-radius: 9px;
}
QDialog#AppointmentDrawerOverlay QFrame#AppointmentAlert[kind="warning"] {
background-color: #FFF5E6;
border: 1px solid #F6E3C4;
border-radius: 10px;
border-radius: 9px;
}
QDialog#AppointmentDrawerOverlay QFrame#AppointmentAlert[kind="danger"] {
background-color: #FFF1F3;
border: 1px solid #F7D7DC;
border-radius: 10px;
border-radius: 9px;
}
QDialog#AppointmentDrawerOverlay QFrame#AppointmentAlert[kind="success"] {
background-color: #EAF9F3;
border: 1px solid #D4F0E5;
border-radius: 10px;
border-radius: 9px;
}
QDialog#AppointmentDrawerOverlay QFrame#AppointmentAlert[kind="info"] QLabel {
@@ -393,7 +378,7 @@ QDialog#AppointmentDrawerOverlay QFrame#AppointmentDrawerFooter QPushButton {
max-height: 30px;
padding: 0 15px;
border: 1px solid #EDEDEE;
border-radius: 10px;
border-radius: 9px;
background-color: #FFFFFF;
color: #1A1C1F;
font-size: 13px;
@@ -423,14 +408,9 @@ QDialog#AppointmentDrawerOverlay QFrame#AppointmentDrawerFooter QPushButton[prim
}
QDialog#AppointmentDrawerOverlay QFrame#AppointmentDrawerFooter QPushButton:disabled {
color: $ds_disabled;
border-color: $ds_line;
background-color: $ds_disabled_surface;
}
QDialog#AppointmentDrawerOverlay QFrame#AppointmentDrawerFooter QPushButton[primary="true"]:pressed {
color: $ds_surface;
background-color: $ds_accent_pressed;
border-color: $ds_accent_pressed;
color: #FFFFFF;
border-color: #EDEDEE;
background-color: #8E8F90;
}
QDialog#AppointmentDrawerOverlay QFrame#AppointmentLoadingOverlay {
@@ -507,7 +487,6 @@ _APPOINTMENT_DARK_REPLACEMENTS = (
)
# Light is the default application theme. Keep the replacement table available
# for a future explicit dark-mode switch, but do not mutate the light source QSS.
APPOINTMENT_DRAWER_QSS = clinical_stylesheet(APPOINTMENT_DRAWER_QSS)
def _as_int(value: Any, default: int = 0) -> int:
@@ -754,7 +733,35 @@ class _EmptyIllustration(QWidget):
painter.end()
class _SlotCard(QPushButton):
class _HoverLiftButton(QPushButton):
"""Button with a subtle two-pixel lift and blue-tinted shadow on hover."""
def __init__(self, text: str = "", parent: QWidget | None = None) -> None:
super().__init__(text, parent)
self._lifted = False
self._base_position = QPoint()
def enterEvent(self, event: QEvent) -> None: # noqa: N802 - Qt API
if self.isEnabled() and not self._lifted:
self._base_position = self.pos()
self.move(self.x(), self.y() - 2)
shadow = QGraphicsDropShadowEffect(self)
shadow.setBlurRadius(12)
shadow.setOffset(0, 4)
shadow.setColor(QColor(26, 28, 31, 72))
self.setGraphicsEffect(shadow)
self._lifted = True
super().enterEvent(event)
def leaveEvent(self, event: QEvent) -> None: # noqa: N802 - Qt API
if self._lifted:
self.move(self._base_position)
self.setGraphicsEffect(None)
self._lifted = False
super().leaveEvent(event)
class _SlotCard(_HoverLiftButton):
"""Two-line time card matching Element's independent time/status typography."""
def __init__(self, time_text: str, status_text: str) -> None:
@@ -812,8 +819,8 @@ class AppointmentDrawer(QDialog):
self._today_blocking = False
self._channel_names: dict[str, str] = {}
self._doctor_buttons: dict[int, QRadioButton] = {}
self._date_buttons: dict[str, QPushButton] = {}
self._slot_buttons: dict[str, QPushButton] = {}
self._date_buttons: dict[str, _HoverLiftButton] = {}
self._slot_buttons: dict[str, _HoverLiftButton] = {}
self._slot_available: dict[str, bool] = {}
self._slot_restore_selection = ""
self._active_loading = ""
@@ -1419,7 +1426,7 @@ class AppointmentDrawer(QDialog):
continue
label = f"{parsed.toString('MM月dd日')} ({week_days[parsed.dayOfWeek() % 7]})"
self.date_combo.addItem(label, value)
button = QPushButton(label)
button = _HoverLiftButton(label)
button.setProperty("appointmentDate", True)
button.setCheckable(True)
button.setFixedSize(130, 40)
@@ -2,155 +2,143 @@
from string import Template
from .design_system import clinical_stylesheet
from .reception_style import body_family, heading_family
def appointments_stylesheet() -> str:
return clinical_stylesheet(Template(_QSS).safe_substitute(body=body_family(), heading=heading_family()))
return Template(_QSS).substitute(body=body_family(), heading=heading_family())
_QSS = """
#AppointmentsPage { background: $ds_canvas; color: $ds_text; }
#AppointmentsPage { background: #F3F7FD; color: #273244; }
#AppointmentsPage QLabel, #AppointmentsPage QPushButton,
#AppointmentsPage QLineEdit, #AppointmentsPage QComboBox,
#AppointmentsPage QTabBar, #AppointmentsPage QTableWidget {
font-family: "$body"; font-size: 14px; font-weight: 400; color: $ds_text;
font-family: "$body"; font-size: 14px; font-weight: 400; color: #273244;
}
#AppointmentsPage QWidget#PageHeader QLabel[role="pageTitle"] {
font-family: "$heading"; font-size: 20px; font-weight: 600; color: $ds_heading;
font-family: "$heading"; font-size: 20px; font-weight: 600; color: #202C3F;
}
#AppointmentsPage QWidget#PageHeader QLabel[role="muted"],
#AppointmentsPage QWidget#PageHeader QLabel[role="breadcrumb"],
#AppointmentsPage QWidget#PageHeader QLabel[role="breadcrumbSeparator"],
#AppointmentsPage QWidget#PageHeader QLabel[role="breadcrumbCurrent"] {
color: $ds_muted; font-size: 13px; font-weight: 400;
color: #5D6B80; font-size: 13px; font-weight: 400;
}
#AppointmentsPage QFrame#AppointmentFilterPanel,
#AppointmentsPage QFrame#AppointmentMainCard {
background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_panel;
background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 8px;
}
#AppointmentsPage QPushButton {
min-height: 30px; padding: 0 12px; border: 1px solid transparent;
border-radius: $ds_radius_control; background: $ds_surface_alt;
min-height: 30px; padding: 0 12px; border: 1px solid #DBE5F2;
border-radius: 6px; background: #FFFFFF;
}
#AppointmentsPage QPushButton:hover { color: $ds_accent; background: $ds_surface_alt; border-color: $ds_line_strong; }
#AppointmentsPage QPushButton:pressed { background: $ds_accent_soft; }
#AppointmentsPage QPushButton:focus { border-color: $ds_focus; }
#AppointmentsPage QPushButton:hover { color: #1555B6; background: #F2F7FF; border-color: #B6CDEE; }
#AppointmentsPage QPushButton:pressed { background: #DCEAFF; }
#AppointmentsPage QPushButton:focus { border-color: #75A5F0; }
#AppointmentsPage QPushButton[variant="primary"] {
background: $ds_accent; color: $ds_surface; border-color: $ds_accent;
background: #1769E8; color: #FFFFFF; border-color: #1769E8;
}
#AppointmentsPage QPushButton[variant="primary"]:hover { background: $ds_accent_hover; }
#AppointmentsPage QPushButton[variant="primary"]:pressed { background: $ds_accent_pressed; }
#AppointmentsPage QPushButton[variant="primary"]:focus { border-color: $ds_focus; }
#AppointmentsPage QPushButton[variant="primary"]:hover { background: #155BCC; }
#AppointmentsPage QPushButton[variant="primary"]:pressed { background: #124EA9; }
#AppointmentsPage QPushButton[variant="danger"] {
color: $ds_danger; background: $ds_danger_soft; border-color: transparent;
color: #B84652; background: #FFFFFF; border-color: #EFC8CE;
}
#AppointmentsPage QPushButton[variant="danger"]:hover { background: $ds_danger_soft; }
#AppointmentsPage QPushButton[variant="danger"]:pressed { border-color: $ds_danger; }
#AppointmentsPage QPushButton[variant="danger"]:hover { background: #FFF0F2; }
#AppointmentsPage QPushButton[variant="ghost"] { background: transparent; border-color: transparent; }
#AppointmentsPage QPushButton[variant="ghost"]:hover { background: $ds_accent_soft; }
#AppointmentsPage QPushButton[variant="ghost"]:focus { border-color: $ds_focus; }
#AppointmentsPage QPushButton:disabled, #AppointmentsPage QPushButton[variant="primary"]:disabled,
#AppointmentsPage QPushButton[variant="danger"]:disabled {
color: $ds_disabled; background: $ds_disabled_surface; border-color: $ds_line;
#AppointmentsPage QPushButton:disabled {
color: #8A97A9; background: #F6F8FC; border-color: #E2E9F2;
}
#AppointmentsPage QLineEdit, #AppointmentsPage QComboBox {
min-height: 32px; padding: 0 10px; color: $ds_text; background: $ds_surface;
border: 1px solid $ds_line; border-radius: $ds_radius_control; selection-background-color: $ds_accent_soft;
min-height: 32px; padding: 0 10px; color: #273244; background: #FFFFFF;
border: 1px solid #DBE5F2; border-radius: 6px; selection-background-color: #DCEAFF;
}
#AppointmentsPage QLineEdit:focus, #AppointmentsPage QComboBox:focus { border-color: $ds_focus; }
#AppointmentsPage QLineEdit:focus, #AppointmentsPage QComboBox:focus { border-color: #75A5F0; }
#AppointmentsPage QLineEdit QToolButton {
min-width: 0; min-height: 0; padding: 0; border: 0; background: transparent;
}
#AppointmentsPage QLineEdit QToolButton:focus { background: $ds_accent_soft; }
#AppointmentsPage QLineEdit QToolButton:focus { background: #EAF2FF; }
#AppointmentsPage QPushButton#AppointmentSearchButton {
min-height: 39px; max-height: 39px; min-width: 52px;
}
#AppointmentsPage QLineEdit#AppointmentPatientSearch { min-height: 39px; max-height: 39px; }
#AppointmentsPage QPushButton[appointmentStat="true"] {
min-height: 34px; max-height: 34px; padding: 0 10px; background: $ds_canvas;
border-color: transparent; color: $ds_muted; font-size: 13px;
min-height: 34px; max-height: 34px; padding: 0 10px; background: #F4F7FC;
border-color: transparent; color: #5D6B80; font-size: 13px;
}
#AppointmentsPage QPushButton[appointmentStat="true"]:hover { color: $ds_accent; background: $ds_accent_soft; }
#AppointmentsPage QPushButton[appointmentStat="true"]:hover { color: #1555B6; background: #EAF2FF; }
#AppointmentsPage QPushButton[appointmentStat="true"]:checked {
color: $ds_accent; background: $ds_accent_soft; border-color: transparent; font-weight: 600;
color: #FFFFFF; background: #1769E8; border-color: #1769E8;
}
#AppointmentsPage QPushButton[appointmentStatKind="warning"][hasPending="true"]:!checked {
color: $ds_warning; background: $ds_warning_soft; border-color: $ds_warning_soft;
color: #9C681F; background: #FFF6E7; border-color: #EEDCBF;
}
#AppointmentsPage QLabel#FilterRowLabel { color: $ds_muted; font-size: 13px; }
#AppointmentsPage QLabel#FilterDivider { color: $ds_line; padding: 0 10px; }
#AppointmentsPage QLabel#FilterRowLabel { color: #5D6B80; font-size: 13px; }
#AppointmentsPage QLabel#FilterDivider { color: #DBE5F2; padding: 0 10px; }
#AppointmentsPage QTabBar#AppointmentStatusTabs::tab {
min-width: 52px; min-height: 32px; padding: 0 12px; color: $ds_muted;
min-width: 52px; min-height: 32px; padding: 0 12px; color: #5D6B80;
background: transparent; border: 0; border-bottom: 2px solid transparent; font-size: 13px;
}
#AppointmentsPage QTabBar#AppointmentStatusTabs::tab:hover { color: $ds_accent; background: $ds_surface_alt; }
#AppointmentsPage QTabBar#AppointmentStatusTabs::tab:hover { color: #1555B6; background: #F7FAFE; }
#AppointmentsPage QTabBar#AppointmentStatusTabs::tab:selected {
color: $ds_accent; background: transparent; border-bottom-color: $ds_accent;
color: #1769E8; background: transparent; border-bottom-color: #1769E8;
}
#AppointmentsPage QPushButton[filterChoice="true"] {
min-height: 30px; max-height: 30px; padding: 0 12px; color: $ds_muted;
min-height: 30px; max-height: 30px; padding: 0 12px; color: #5D6B80;
background: transparent; border-color: transparent; font-size: 13px;
}
#AppointmentsPage QPushButton[filterChoice="true"]:checked { color: $ds_accent; background: $ds_accent_soft; }
#AppointmentsPage QPushButton[filterChoice="true"]:focus,
#AppointmentsPage QPushButton[appointmentStat="true"]:focus { border-color: $ds_focus; }
#AppointmentsPage QPushButton[filterChoice="true"]:checked { color: #1555B6; background: #EAF2FF; }
#AppointmentsPage QFrame#AppointmentToolbar { background: transparent; border: 0; }
#AppointmentsPage QPushButton[compactAction="true"] {
min-height: 36px; max-height: 36px; padding: 0 17px; font-size: 13px;
}
#AppointmentsPage QFrame#AppointmentToolbar QPushButton[variant="secondary"]:enabled {
color: $ds_text; border-color: transparent;
color: #1769E8; border-color: #ADC8F0;
}
#AppointmentsPage QFrame#AppointmentToolbar QPushButton[variant="secondary"]:hover { color: $ds_accent; background: $ds_accent_soft; }
#AppointmentsPage QFrame#AppointmentToolbar QPushButton[variant="secondary"]:focus { border-color: $ds_focus; }
#AppointmentsPage QTableWidget#AppointmentTable {
background: $ds_surface; alternate-background-color: $ds_surface; border: 0; border-radius: 0;
gridline-color: $ds_line; selection-background-color: $ds_accent_soft; selection-color: $ds_text;
background: #FFFFFF; alternate-background-color: #FFFFFF; border: 0; border-radius: 0;
gridline-color: #E6EDF6; selection-background-color: #EAF2FF; selection-color: #273244;
}
#AppointmentsPage QTableWidget#AppointmentTable::item { padding: 0; border: 0; border-bottom: 1px solid $ds_line; }
#AppointmentsPage QTableWidget#AppointmentTable::item:selected { background: $ds_accent_soft; color: $ds_text; }
#AppointmentsPage QTableWidget#AppointmentTable::item { padding: 0; border: 0; border-bottom: 1px solid #E6EDF6; }
#AppointmentsPage QTableWidget#AppointmentTable::item:selected { background: #EAF2FF; color: #273244; }
#AppointmentsPage QTableWidget#AppointmentTable QHeaderView::section {
min-height: 40px; padding: 0; background: $ds_surface_alt; color: $ds_muted;
border: 0; border-top: 1px solid $ds_line; border-bottom: 1px solid $ds_line;
min-height: 40px; padding: 0; background: #F5F8FD; color: #5D6B80;
border: 0; border-top: 1px solid #E1E9F4; border-bottom: 1px solid #E1E9F4;
font-family: "$body"; font-size: 13px; font-weight: 400;
}
#AppointmentsPage QWidget[appointmentSelectionHost="true"] {
background: transparent; border-left: 3px solid transparent;
}
#AppointmentsPage QWidget[appointmentSelectionHost="true"][selected="true"] { border-left-color: $ds_accent; }
#AppointmentsPage QWidget[appointmentSelectionHost="true"][selected="true"] { border-left-color: #1769E8; }
#AppointmentsPage QCheckBox[appointmentSelector="true"]::indicator {
width: 16px; height: 16px; background: $ds_surface; border: 1px solid $ds_line_strong; border-radius: 3px;
width: 16px; height: 16px; background: #FFFFFF; border: 1px solid #C8D5E6; border-radius: 3px;
}
#AppointmentsPage QCheckBox[appointmentSelector="true"]::indicator:checked { background: $ds_accent; border-color: $ds_accent; }
#AppointmentsPage QCheckBox[appointmentSelector="true"]::indicator:checked { background: #1769E8; border-color: #1769E8; }
#AppointmentsPage QWidget[appointmentInfoHost="true"],
#AppointmentsPage QWidget[appointmentImHost="true"] { background: transparent; }
#AppointmentsPage QLabel[tableAppointmentStatus="true"] {
min-height: 20px; max-height: 20px; padding: 0 6px; color: $ds_accent;
background: $ds_accent_soft; border-radius: $ds_radius_small; font-size: 13px;
min-height: 20px; max-height: 20px; padding: 0 6px; color: #1555B6;
background: #EAF2FF; border-radius: 4px; font-size: 13px;
}
#AppointmentsPage QLabel[tableAppointmentStatusKind="warning"] { color: $ds_warning; background: $ds_warning_soft; }
#AppointmentsPage QLabel[tableAppointmentStatusKind="muted"] { color: $ds_muted; background: $ds_disabled_surface; }
#AppointmentsPage QLabel[tableAppointmentMeta="true"] { color: $ds_muted; font-size: 13px; }
#AppointmentsPage QLabel[tableAppointmentStatusKind="warning"] { color: #9C681F; background: #FFF3DD; }
#AppointmentsPage QLabel[tableAppointmentStatusKind="muted"] { color: #66758A; background: #EEF2F7; }
#AppointmentsPage QLabel[tableAppointmentMeta="true"] { color: #5D6B80; font-size: 13px; }
#AppointmentsPage QPushButton[tableCancelAction="true"] {
min-height: 20px; max-height: 20px; padding: 0 5px; color: $ds_danger;
background: $ds_danger_soft; border: 0; border-radius: $ds_radius_small; font-size: 13px;
min-height: 20px; max-height: 20px; padding: 0 5px; color: #B84652;
background: #FFF0F2; border: 0; border-radius: 4px; font-size: 13px;
}
#AppointmentsPage QPushButton[appointmentImAction="true"] {
min-width: 62px; min-height: 32px; max-height: 32px; padding: 0 10px;
color: $ds_accent; background: $ds_accent_soft; border-color: transparent; font-size: 13px;
color: #1555B6; background: #EAF2FF; border-color: #C9DCF7; font-size: 13px;
}
#AppointmentsPage QPushButton[appointmentImAction="true"]:hover { color: $ds_accent_hover; border-color: $ds_line_strong; }
#AppointmentsPage QPushButton[appointmentImAction="true"]:focus { border-color: $ds_focus; }
#AppointmentsPage QPushButton[appointmentImAction="true"]:disabled { color: $ds_disabled; background: $ds_disabled_surface; border-color: $ds_line; }
#AppointmentsPage QWidget#Pager { background: $ds_surface; border: 0; border-top: 1px solid $ds_line; }
#AppointmentsPage QWidget#Pager QLabel { color: $ds_muted; font-size: 13px; border: 0; }
#AppointmentsPage QPushButton[appointmentImAction="true"]:hover { color: #FFFFFF; background: #1769E8; }
#AppointmentsPage QPushButton[appointmentImAction="true"]:disabled { color: #8A97A9; background: #F3F6FB; border-color: #DFE7F2; }
#AppointmentsPage QWidget#Pager { background: #FFFFFF; border: 0; border-top: 1px solid #E1E9F4; }
#AppointmentsPage QWidget#Pager QLabel { color: #5D6B80; font-size: 13px; border: 0; }
#AppointmentsPage QWidget#Pager QPushButton {
min-width: 30px; max-width: 30px; min-height: 32px; max-height: 32px;
padding: 0; border: 1px solid $ds_line; background: $ds_surface; color: $ds_muted; font-size: 13px;
padding: 0; border: 1px solid #DBE5F2; background: #FFFFFF; color: #5D6B80; font-size: 13px;
}
#AppointmentsPage QWidget#Pager QPushButton[active="true"] { color: $ds_accent; background: $ds_accent_soft; border-color: transparent; font-weight: 600; }
#AppointmentsPage QWidget#Pager QPushButton:focus { border-color: $ds_focus; }
#AppointmentsPage QWidget#Pager QPushButton:disabled { color: $ds_disabled; background: $ds_surface_alt; }
#AppointmentsPage QWidget#Pager QPushButton[active="true"] { color: #FFFFFF; background: #1769E8; border-color: #1769E8; }
#AppointmentsPage QWidget#Pager QPushButton:disabled { color: #9AA6B7; background: #F7F9FC; }
"""
-376
View File
@@ -1,376 +0,0 @@
"""Shared, display-only normalization of archived chat messages and IM events."""
from __future__ import annotations
import json
import math
import re
from collections.abc import Mapping
from datetime import date, datetime
from typing import Any, NamedTuple
class ChatItem(NamedTuple):
variant: str
role: str
text: Any
title: str
detail: str
time_text: str
tone: str
marker: str
def _first_value(source: Any, *keys: str, default: Any = None) -> Any:
for key in keys:
if isinstance(source, Mapping):
value = source.get(key)
else:
value = getattr(source, key, None)
raw = getattr(source, "raw", None)
if value is None and isinstance(raw, Mapping):
value = raw.get(key)
if value is not None and value != "":
return value
return default
def _as_int(value: Any, default: int = 0) -> int:
try:
return int(value)
except (TypeError, ValueError, OverflowError):
return default
def _truthy(value: Any) -> bool:
if isinstance(value, bool):
return value
return str(value or "").strip().lower() in {"1", "true", "yes", "on", "是", "有"}
def format_chat_time(value: Any, *, include_date: bool = False) -> str:
"""Show actual archive times; accept Unix seconds/milliseconds and ISO dates."""
if value is None or value == "" or isinstance(value, bool):
return ""
pattern = "%Y-%m-%d %H:%M" if include_date else "%H:%M"
if isinstance(value, datetime):
return value.strftime(pattern)
if isinstance(value, date):
return value.isoformat()
text = str(value).strip()
if not text:
return ""
if isinstance(value, (int, float)) or re.fullmatch(r"[+-]?\d+(?:\.\d+)?", text):
numeric = float(value)
if not math.isfinite(numeric) or numeric <= 0:
return ""
if numeric >= 10_000_000_000:
numeric /= 1000
try:
return datetime.fromtimestamp(numeric).strftime(pattern)
except (OverflowError, OSError, ValueError):
return ""
try:
moment = datetime.fromisoformat(text.replace("Z", "+00:00"))
except ValueError:
# Legacy archive rows can already contain a display-only time.
return text if include_date else text.rsplit(" ", 1)[-1][:16]
return moment.strftime(pattern)
def _decode_json_value(value: Any) -> Any:
if isinstance(value, Mapping):
return dict(value)
if isinstance(value, (list, tuple)):
return list(value)
if not isinstance(value, str):
return None
text = value.strip()
if not text or text[0] not in "[{":
return None
try:
return json.loads(text)
except (TypeError, ValueError, json.JSONDecodeError):
return None
def _normalized_token(value: Any) -> str:
return re.sub(r"[^a-z0-9]", "", str(value or "").strip().lower())
def _format_call_duration(value: Any) -> str:
seconds = _as_int(value)
if seconds <= 0:
return ""
if seconds < 60:
return f"通话 {seconds} 秒"
minutes, remaining = divmod(seconds, 60)
return f"通话 {minutes} 分 {remaining} 秒" if remaining else f"通话 {minutes} 分钟"
def _event_time(
row: Mapping[str, Any], *payloads: Mapping[str, Any], include_date: bool = False
) -> str:
value = _first_value(
row, "time", "create_time", "created_at", "msg_time", "timestamp", default=None
)
if value in (None, ""):
for payload in payloads:
value = _first_value(payload, "time", "timestamp", "create_time", default=None)
if value not in (None, ""):
break
return format_chat_time(value, include_date=include_date)
def _event_item(
*,
title: str,
detail: str = "",
time_text: str = "",
tone: str = "neutral",
marker: str = "系",
) -> ChatItem:
return ChatItem("event", "system", "", title, detail, time_text, tone, marker)
def _system_event_from_payload(
payload: Mapping[str, Any],
row: Mapping[str, Any],
*,
include_date: bool = False,
) -> ChatItem | None:
business = _normalized_token(_first_value(payload, "businessID", "businessId", "business_id"))
time_text = _event_time(row, payload, include_date=include_date)
patient_name = str(
_first_value(payload, "patientName", "patient_name", default="患者") or "患者"
)
if business in {"patientopenedchat", "patientopenchat", "openchat"}:
return _event_item(
title="患者进入在线问诊",
detail=f"{patient_name}已进入当前会话",
time_text=time_text,
tone="success",
marker="入",
)
if business in {"patientclosedchat", "patientclosechat", "patientleftchat", "closechat"}:
return _event_item(
title="患者离开在线问诊",
detail=f"{patient_name}已离开当前会话",
time_text=time_text,
marker="离",
)
if business == "doctorenteredconsultroom":
return _event_item(
title="医生进入在线诊室",
detail="本次在线问诊已准备就绪",
time_text=time_text,
tone="success",
marker="医",
)
if business == "consultationcomplete":
return _event_item(
title="本次问诊已完成",
detail="会话内容已归档",
time_text=time_text,
tone="success",
marker="完",
)
nested = _decode_json_value(payload.get("data"))
rtc_payload: Mapping[str, Any] | None = None
if business in {"rtccall", "rtcvideo", "rtcaudio"}:
rtc_payload = payload
elif business in {"1", "avcall"}:
rtc_payload = {**payload, **nested} if isinstance(nested, Mapping) else payload
elif _first_value(payload, "cmd", "command", default="") not in (None, ""):
rtc_payload = payload
elif isinstance(nested, Mapping):
nested_business = _normalized_token(
_first_value(nested, "businessID", "businessId", "business_id")
)
if nested_business in {"rtccall", "rtcvideo", "rtcaudio"}:
rtc_payload = nested
else:
nested_event = _system_event_from_payload(nested, row, include_date=include_date)
if nested_event is not None:
return nested_event
if rtc_payload is None:
return None
call_data = _decode_json_value(rtc_payload.get("data"))
if not isinstance(call_data, Mapping):
call_data = rtc_payload
command = _normalized_token(_first_value(call_data, "cmd", "command", "action"))
action_type = _as_int(_first_value(rtc_payload, "actionType", "action_type"))
if not command:
command = {
1: "invite",
2: "cancel",
3: "accept",
4: "reject",
5: "timeout",
6: "hangup",
7: "linebusy",
}.get(action_type, "")
call_type = _as_int(_first_value(rtc_payload, "call_type", default=2), 2)
medium = (
"语音" if call_type == 1 or business == "rtcaudio" or command == "audiocall" else "视频"
)
marker = "音" if medium == "语音" else "视"
time_text = _event_time(row, payload, rtc_payload, call_data, include_date=include_date)
duration = _format_call_duration(
_first_value(
rtc_payload,
"call_end",
"duration",
"callDuration",
default=_first_value(call_data, "call_end", "duration", "callDuration", default=0),
)
)
if command in {"videocall", "audiocall", "call", "invite", "startcall"}:
return _event_item(
title=f"发起{medium}问诊",
detail=f"医生已向患者发起{medium}通话",
time_text=time_text,
tone="info",
marker=marker,
)
if command in {"accept", "answer", "answered", "connected", "join"}:
return _event_item(
title=f"{medium}问诊已接通",
detail="医生与患者已进入通话",
time_text=time_text,
tone="success",
marker=marker,
)
if command in {"hangup", "end", "endcall", "finish", "finished"}:
return _event_item(
title=f"{medium}问诊已结束",
detail=duration,
time_text=time_text,
marker=marker,
)
if command in {"reject", "refuse", "decline"}:
return _event_item(
title=f"{medium}问诊未接通",
detail="患者已拒绝本次通话邀请",
time_text=time_text,
tone="warning",
marker=marker,
)
if command in {"timeout", "busy", "linebusy", "cancel", "cancelled", "canceled"}:
reasons = {
"timeout": "呼叫超时,患者未接听",
"busy": "患者当前忙线",
"linebusy": "患者当前忙线",
"cancel": "通话邀请已取消",
"cancelled": "通话邀请已取消",
"canceled": "通话邀请已取消",
}
return _event_item(
title=f"{medium}问诊未接通",
detail=reasons[command],
time_text=time_text,
tone="warning",
marker=marker,
)
if command in {"switchtoaudio", "switchaudio"}:
return _event_item(
title="通话已切换为语音",
detail="视频画面已关闭",
time_text=time_text,
tone="info",
marker="音",
)
if command in {"switchtovideo", "switchvideo"}:
return _event_item(
title="通话已切换为视频",
time_text=time_text,
tone="info",
marker="视",
)
return _event_item(
title=f"{medium}问诊状态已更新",
detail="通话信令已归档",
time_text=time_text,
tone="info",
marker=marker,
)
def parse_chat_item(row: Mapping[str, Any], *, include_date: bool = False) -> ChatItem | None:
raw_text = _first_value(row, "text", "content", "message", default="")
payload = _decode_json_value(raw_text)
if isinstance(payload, Mapping):
business = _normalized_token(
_first_value(payload, "businessID", "businessId", "business_id")
)
if business == "usertypingstatus":
return None
event = _system_event_from_payload(payload, row, include_date=include_date)
if event is not None:
return event
kind = str(
_first_value(row, "msg_type", "message_type", "type", default="text") or "text"
).lower()
technical_keys = {
"businessID",
"businessId",
"business_id",
"actionType",
"inviteID",
"cmd",
"command",
}
if isinstance(payload, Mapping) and (
kind in {"custom", "other", "system"} or technical_keys.intersection(payload)
):
return _event_item(
title="系统状态已同步",
detail="技术消息已归档,不影响问诊内容",
time_text=_event_time(row, payload, include_date=include_date),
)
doctor_flag = _first_value(row, "is_from_doctor", "from_doctor", default=False)
sender_role = _normalized_token(_first_value(row, "role", "sender_type", default=""))
from_account = str(_first_value(row, "from_account", "sender", default="") or "").lower()
from_doctor = (
_truthy(doctor_flag)
or sender_role in {"doctor", "staff", "2"}
or from_account.startswith("doctor_")
)
from_ai = sender_role in {"ai", "assistant", "model"} or from_account.startswith(
("ai_", "assistant_")
)
role = "ai" if from_ai else "doctor" if from_doctor else "patient"
time_text = _event_time(row, include_date=include_date)
attachment_labels = {
"image": "图片消息",
"2": "图片消息",
"file": "附件",
"3": "附件",
"sound": "语音消息",
"audio": "语音消息",
"video": "视频消息",
"location": "位置消息",
"face": "表情消息",
}
if kind in attachment_labels:
file_name = str(_first_value(row, "file_name", default="") or "").strip()
detail = str(raw_text or "").strip()
if kind in {"file", "3"} and file_name:
text: Any = f"附件:{file_name}"
elif kind == "location" and detail:
text = f"位置:{detail}"
else:
text = attachment_labels[kind]
elif isinstance(payload, (Mapping, list)):
text = payload
else:
text = str(raw_text or _first_value(row, "file_name", default="") or "").strip()
if text in (None, "", {}, []):
return None
return ChatItem("message", role, text, "", "", time_text, "", "")
@@ -24,7 +24,6 @@ from PySide6.QtWidgets import (
QWidget,
)
from .design_system import clinical_stylesheet
from .widgets import display_text, first_value, run_async
# 后台 ChatNotifyLogic 写入的三种 type。
@@ -261,7 +260,7 @@ class ChatNotificationCenter(QWidget):
super().__init__(host)
self.repository = repository
self.setObjectName("ChatNotifyLayer")
self.setStyleSheet(clinical_stylesheet(CHAT_NOTIFICATION_QSS))
self.setStyleSheet(CHAT_NOTIFICATION_QSS)
self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents, False)
self._cards: dict[str, _NotificationCard] = {}
self._pending: list[ChatNotification] = []
@@ -2,67 +2,59 @@
from string import Template
from .design_system import clinical_stylesheet
from .reception_style import body_family, heading_family
def consultations_stylesheet() -> str:
return clinical_stylesheet(Template(_QSS).safe_substitute(body=body_family(), heading=heading_family()))
return Template(_QSS).substitute(body=body_family(), heading=heading_family())
_QSS = """
#DiagnosisIndex, #DiagnosisIndexContent, #DiagnosisPageScroll {
background: $ds_canvas; color: $ds_text; border: 0;
background: #F3F7FD; color: #273244; border: 0;
}
#DiagnosisIndex QLabel, #DiagnosisIndex QPushButton, #DiagnosisIndex QToolButton,
#DiagnosisIndex QLineEdit, #DiagnosisIndex QComboBox, #DiagnosisIndex QDateEdit,
#DiagnosisIndex QSpinBox, #DiagnosisIndex QTableView {
font-family: "$body"; font-size: 14px; font-weight: 400; color: $ds_text;
font-family: "$body"; font-size: 14px; font-weight: 400; color: #273244;
}
#DiagnosisIndex QWidget#PageHeader QLabel[role="pageTitle"] {
font-family: "$heading"; font-size: 20px; font-weight: 600; color: $ds_heading;
font-family: "$heading"; font-size: 20px; font-weight: 600; color: #202C3F;
}
#DiagnosisIndex QLabel[role="muted"], #DiagnosisIndex QLabel[role="breadcrumb"],
#DiagnosisIndex QLabel[role="breadcrumbCurrent"], #DiagnosisIndex QLabel[role="breadcrumbSeparator"],
#DiagnosisIndex QLabel[filterGroup="true"], #DiagnosisIndex QLabel[pagerMuted="true"] {
color: $ds_muted; font-size: 13px;
color: #5D6B80; font-size: 13px;
}
#DiagnosisIndex QFrame#DiagnosisFilterCard, #DiagnosisIndex QFrame#DiagnosisListCard {
background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_panel;
background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 8px;
}
#DiagnosisIndex QFrame#DiagnosisStatusCard, #DiagnosisIndex QFrame#DiagnosisQuickFilters,
#DiagnosisIndex QFrame#DiagnosisListToolbar { background: transparent; border: 0; }
#DiagnosisIndex QFrame#DiagnosisAdvancedFilters {
background: transparent; border: 0; border-top: 1px solid $ds_line; border-radius: 0;
background: transparent; border: 0; border-top: 1px solid #E6EDF6; border-radius: 0;
}
#DiagnosisIndex QPushButton {
min-height: 34px; padding: 0 13px; border: 1px solid transparent;
border-radius: $ds_radius_control; background: $ds_surface_alt;
min-height: 34px; padding: 0 13px; border: 1px solid #DBE5F2;
border-radius: 6px; background: #FFFFFF;
}
#DiagnosisIndex QPushButton:hover { color: $ds_accent; background: $ds_surface_alt; border-color: $ds_line_strong; }
#DiagnosisIndex QPushButton:pressed { background: $ds_accent_soft; }
#DiagnosisIndex QPushButton:focus { border-color: $ds_focus; }
#DiagnosisIndex QPushButton[variant="primary"] { color: $ds_surface; background: $ds_accent; border-color: $ds_accent; }
#DiagnosisIndex QPushButton[variant="primary"]:hover { background: $ds_accent_hover; }
#DiagnosisIndex QPushButton[variant="primary"]:pressed { background: $ds_accent_pressed; }
#DiagnosisIndex QPushButton[variant="primary"]:focus { border-color: $ds_focus; }
#DiagnosisIndex QPushButton[consultationTool="true"] { color: $ds_text; border-color: transparent; }
#DiagnosisIndex QPushButton[consultationTool="true"]:hover { color: $ds_accent; background: $ds_accent_soft; }
#DiagnosisIndex QPushButton[consultationDanger="true"] { color: $ds_danger; background: $ds_danger_soft; border-color: transparent; }
#DiagnosisIndex QPushButton[consultationDanger="true"]:hover { border-color: $ds_danger; }
#DiagnosisIndex QPushButton[consultationTool="true"]:focus,
#DiagnosisIndex QPushButton[consultationDanger="true"]:focus { border-color: $ds_focus; }
#DiagnosisIndex QPushButton:disabled, #DiagnosisIndex QPushButton[consultationDanger="true"]:disabled,
#DiagnosisIndex QPushButton[variant="primary"]:disabled, #DiagnosisIndex QPushButton[consultationTool="true"]:disabled {
color: $ds_disabled; background: $ds_disabled_surface; border-color: $ds_line;
#DiagnosisIndex QPushButton:hover { color: #1555B6; background: #F2F7FF; border-color: #B6CDEE; }
#DiagnosisIndex QPushButton:pressed { background: #DCEAFF; }
#DiagnosisIndex QPushButton:focus { border-color: #75A5F0; }
#DiagnosisIndex QPushButton[variant="primary"] { color: #FFFFFF; background: #1769E8; border-color: #1769E8; }
#DiagnosisIndex QPushButton[variant="primary"]:hover { background: #155BCC; }
#DiagnosisIndex QPushButton[consultationTool="true"] { color: #1555B6; border-color: #C2D5EF; }
#DiagnosisIndex QPushButton[consultationDanger="true"] { color: #BE4B58; border-color: #EBCDD2; }
#DiagnosisIndex QPushButton:disabled, #DiagnosisIndex QPushButton[consultationDanger="true"]:disabled {
color: #8A97A9; background: #F6F8FC; border-color: #E2E9F2;
}
#DiagnosisIndex QLineEdit, #DiagnosisIndex QComboBox, #DiagnosisIndex QDateEdit, #DiagnosisIndex QSpinBox {
min-height: 32px; padding: 0 10px; color: $ds_text; background: $ds_surface;
border: 1px solid $ds_line; border-radius: $ds_radius_control; selection-background-color: $ds_accent_soft;
min-height: 32px; padding: 0 10px; color: #273244; background: #FFFFFF;
border: 1px solid #DBE5F2; border-radius: 6px; selection-background-color: #DCEAFF;
font-size: 13px;
}
#DiagnosisIndex QLineEdit:focus, #DiagnosisIndex QComboBox:focus,
#DiagnosisIndex QDateEdit:focus, #DiagnosisIndex QSpinBox:focus { border-color: $ds_focus; }
#DiagnosisIndex QDateEdit:focus, #DiagnosisIndex QSpinBox:focus { border-color: #75A5F0; }
#DiagnosisIndex QLineEdit QToolButton {
min-width: 0; min-height: 0; padding: 0; border: 0; background: transparent;
}
@@ -70,77 +62,70 @@ _QSS = """
width: 22px; border: 0; background: transparent;
}
#DiagnosisIndex QComboBox QAbstractItemView {
color: $ds_text; background: $ds_surface; border: 1px solid $ds_line;
selection-background-color: $ds_accent_soft; selection-color: $ds_accent; outline: 0;
color: #273244; background: #FFFFFF; border: 1px solid #DBE5F2;
selection-background-color: #EAF2FF; selection-color: #1555B6; outline: 0;
}
#DiagnosisIndex QWidget#DiagnosisStatusSearch QLineEdit,
#DiagnosisIndex QWidget#DiagnosisStatusSearch QPushButton { min-height: 39px; max-height: 39px; }
#DiagnosisIndex QToolButton { min-width: 0; min-height: 0; border: 0; padding: 0; background: transparent; }
#DiagnosisIndex QToolButton[diagnosisChip="true"] {
min-height: 32px; max-height: 32px; padding: 0 14px; border: 1px solid transparent;
border-radius: $ds_radius_control; color: $ds_muted; background: transparent; font-size: 13px;
border-radius: 5px; color: #5D6B80; background: transparent; font-size: 13px;
}
#DiagnosisIndex QToolButton[diagnosisChip="true"]:hover { background: $ds_surface_alt; color: $ds_accent; }
#DiagnosisIndex QToolButton[diagnosisChip="true"]:checked { background: $ds_accent_soft; color: $ds_accent; font-weight: 600; }
#DiagnosisIndex QToolButton[dateChoice="true"] { padding: 0 17px; background: $ds_surface_alt; border-color: transparent; }
#DiagnosisIndex QToolButton[dateChoice="true"]:checked { background: $ds_accent_soft; border-color: transparent; }
#DiagnosisIndex QToolButton[diagnosisChip="true"]:focus { border-color: $ds_focus; }
#DiagnosisIndex QToolButton[diagnosisChip="true"]:hover { background: #F2F7FF; color: #1555B6; }
#DiagnosisIndex QToolButton[diagnosisChip="true"]:checked { background: #1769E8; color: #FFFFFF; }
#DiagnosisIndex QToolButton[dateChoice="true"] { padding: 0 17px; border-color: #E1E9F4; }
#DiagnosisIndex QToolButton[dateChoice="true"]:checked { border-color: #1769E8; }
#DiagnosisIndex QToolButton[statusTab="true"] {
min-height: 44px; max-height: 44px; padding: 0 20px; border: 0;
border-bottom: 2px solid transparent; border-radius: 0; background: transparent;
}
#DiagnosisIndex QToolButton[statusTab="true"]:checked {
color: $ds_accent; background: transparent; border-bottom-color: $ds_accent;
color: #1769E8; background: transparent; border-bottom-color: #1769E8;
}
#DiagnosisIndex QToolButton[statusTab="true"]:focus { background: $ds_accent_soft; }
#DiagnosisIndex QToolButton#DiagnosisMoreFilter {
min-height: 32px; padding: 0 6px; color: $ds_muted; font-size: 13px;
min-height: 32px; padding: 0 6px; color: #5D6B80; font-size: 13px;
}
#DiagnosisIndex QToolButton#DiagnosisMoreFilter:hover { color: $ds_accent; background: $ds_surface_alt; }
#DiagnosisIndex QFrame#DiagnosisFilterDivider { min-width: 1px; max-width: 1px; min-height: 20px; background: $ds_line; border: 0; }
#DiagnosisIndex QToolButton#DiagnosisMoreFilter:hover { color: #1769E8; background: #F2F7FF; }
#DiagnosisIndex QFrame#DiagnosisFilterDivider { min-width: 1px; max-width: 1px; min-height: 20px; background: #E1E9F4; border: 0; }
#DiagnosisIndex QFrame#DiagnosisDateRange {
background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_control;
background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 6px;
}
#DiagnosisIndex QDateEdit[diagnosisRangePart="true"] { min-height: 30px; padding: 0 4px; border: 0; }
#DiagnosisIndex QTableView {
background: $ds_surface; alternate-background-color: $ds_surface; border: 0; border-radius: 0;
gridline-color: $ds_line; selection-background-color: $ds_accent_soft; selection-color: $ds_text;
background: #FFFFFF; alternate-background-color: #FFFFFF; border: 0; border-radius: 0;
gridline-color: #E6EDF6; selection-background-color: #EAF2FF; selection-color: #273244;
}
#DiagnosisIndex QTableView QHeaderView::section {
min-height: 41px; padding: 0; background: $ds_surface_alt; color: $ds_muted;
border: 0; border-bottom: 1px solid $ds_line;
min-height: 41px; padding: 0; background: #F5F8FD; color: #5D6B80;
border: 0; border-bottom: 1px solid #E1E9F4;
font-family: "$body"; font-size: 13px; font-weight: 400;
}
#DiagnosisIndex QToolButton[rowLink], #DiagnosisIndex QToolButton[appointmentCancel="true"] {
color: $ds_accent; min-height: 26px; padding: 0 4px; border: 1px solid transparent;
border-radius: $ds_radius_small; background: transparent; font-size: 13px;
color: #1769E8; min-height: 26px; padding: 0 4px; border: 0; background: transparent; font-size: 13px;
}
#DiagnosisIndex QToolButton[appointmentCancel="true"] { color: $ds_danger; }
#DiagnosisIndex QToolButton[appointmentCancel="true"]:hover { background: $ds_danger_soft; }
#DiagnosisIndex QToolButton[rowLink]:hover { color: $ds_accent; background: $ds_accent_soft; border-radius: $ds_radius_small; }
#DiagnosisIndex QToolButton[rowLink]:focus,
#DiagnosisIndex QToolButton[appointmentCancel="true"]:focus { border-color: $ds_focus; }
#DiagnosisIndex QToolButton[appointmentCancel="true"] { color: #BE4B58; }
#DiagnosisIndex QToolButton[rowLink]:hover { color: #1555B6; background: #DCEAFF; border-radius: 4px; }
#DiagnosisIndex QToolButton[rowLink="muted"], #DiagnosisIndex QLabel[fixedMuted="true"] {
color: $ds_muted; font-size: 13px;
color: #5D6B80; font-size: 13px;
}
#DiagnosisIndex QToolButton#DiagnosisRowMore { padding-right: 18px; }
#DiagnosisIndex QWidget#DiagnosisFixedCell { background: transparent; }
#DiagnosisIndex QLabel#DiagnosisTableEmpty { color: $ds_muted; background: $ds_surface; }
#DiagnosisIndex QLabel#DiagnosisTableEmpty[stateKind="error"] { color: $ds_danger; }
#DiagnosisIndex QTableView#DiagnosisFixedTable { border-left: 1px solid $ds_line; }
#DiagnosisIndex QWidget#DiagnosisPager { background: $ds_surface; border-top: 1px solid $ds_line; }
#DiagnosisIndex QLabel#DiagnosisTableEmpty { color: #5D6B80; background: #FFFFFF; }
#DiagnosisIndex QLabel#DiagnosisTableEmpty[stateKind="error"] { color: #BE4B58; }
#DiagnosisIndex QTableView#DiagnosisFixedTable { border-left: 1px solid #E1E9F4; }
#DiagnosisIndex QWidget#DiagnosisPager { background: #FFFFFF; border-top: 1px solid #E6EDF6; }
#DiagnosisIndex QToolButton[pagerButton="true"] {
min-width: 30px; max-width: 30px; min-height: 30px; max-height: 30px;
border: 1px solid $ds_line; border-radius: $ds_radius_control; color: $ds_muted; background: $ds_surface;
border: 1px solid #DBE5F2; border-radius: 5px; color: #5D6B80; background: #FFFFFF;
}
#DiagnosisIndex QToolButton[pagerButton="true"][active="true"] { color: $ds_accent; background: $ds_accent_soft; border-color: transparent; font-weight: 600; }
#DiagnosisIndex QToolButton[pagerButton="true"]:focus { border-color: $ds_focus; }
#DiagnosisIndex QToolButton[pagerButton="true"]:disabled { color: $ds_disabled; background: $ds_disabled_surface; }
#DiagnosisIndex QToolButton[pagerButton="true"][active="true"] { color: #FFFFFF; background: #1769E8; border-color: #1769E8; }
#DiagnosisIndex QToolButton[pagerButton="true"]:disabled { color: #A4B0C0; background: #F6F8FC; }
#DiagnosisIndex QComboBox#DiagnosisPageSize { min-width: 95px; min-height: 30px; }
#DiagnosisIndex QSpinBox#DiagnosisPageJumper { min-height: 30px; padding: 0 8px; }
#DiagnosisIndex QScrollBar:vertical { background: $ds_canvas; width: 7px; margin: 0; }
#DiagnosisIndex QScrollBar:horizontal { background: $ds_canvas; height: 7px; margin: 0; }
#DiagnosisIndex QScrollBar::handle { background: $ds_line_strong; border-radius: 3px; min-width: 24px; min-height: 24px; }
#DiagnosisIndex QScrollBar:vertical { background: #F4F7FC; width: 7px; margin: 0; }
#DiagnosisIndex QScrollBar:horizontal { background: #F4F7FC; height: 7px; margin: 0; }
#DiagnosisIndex QScrollBar::handle { background: #C8D5E6; border-radius: 3px; min-width: 24px; min-height: 24px; }
#DiagnosisIndex QScrollBar::add-line, #DiagnosisIndex QScrollBar::sub-line { width: 0; height: 0; }
#DiagnosisIndex QScrollBar::add-page, #DiagnosisIndex QScrollBar::sub-page { background: transparent; }
"""
@@ -1,76 +0,0 @@
"""Clinical desktop design tokens, shared by native pages and dialog chrome.
Keep data-series colours and video pixels outside this palette. Existing scoped
QSS can adopt the system without changing selectors, layout or permissions.
New rules should use the named ``$ds_*`` tokens rather than legacy colours.
"""
from __future__ import annotations
import re
from string import Template
PALETTE = {
"canvas": "#F5F7FA",
"surface": "#FFFFFF",
"surface_alt": "#F7F9FC",
"sidebar": "#F0F3F8",
"line": "#E6EAF0",
"line_strong": "#D4DCE8",
"heading": "#223047",
"text": "#344258",
"muted": "#647287",
"disabled": "#8B96A6",
"disabled_surface": "#F0F2F5",
"accent": "#4267B2",
"accent_hover": "#355995",
"accent_pressed": "#2C4C82",
"accent_soft": "#EAF0FB",
"focus": "#6D8CCB",
"success": "#287B65",
"success_soft": "#EDF7F2",
"warning": "#96601D",
"warning_soft": "#FBF4E8",
"danger": "#B54A59",
"danger_soft": "#FCF0F2",
}
RADII = {"small": 6, "control": 10, "panel": 16, "window": 20}
SPACING = {"small": 8, "control": 12, "group": 16, "section": 24}
TOKENS = {f"ds_{name}": value for name, value in PALETTE.items()}
TOKENS.update({f"ds_radius_{name}": f"{value}px" for name, value in RADII.items()})
TOKENS.update({f"ds_space_{name}": f"{value}px" for name, value in SPACING.items()})
# Explicit migration of the two existing native palettes. This adapter only
# touches six-digit colour literals; selectors and metrics stay page-owned.
_LEGACY_ROLES = {
"accent": ("1769E8", "4F63D9", "5761F4", "5267DF"),
"accent_hover": ("155BCC", "1555B6", "4156C4", "4356C4", "4055CA"),
"accent_pressed": ("124EA9", "354BB4"),
"accent_soft": ("EAF2FF", "EEF1FA", "EEF0FF", "F0F2FF", "DCEAFF", "EDF0FC"),
"focus": ("75A5F0", "8B9AD9"),
"canvas": ("F3F7FD", "F4F6FA", "F6F6F6"),
"surface_alt": ("F7F7F7", "F7FAFE", "F5F8FD", "F7F9FE", "F2F7FF"),
"sidebar": ("EDF4FF",),
"line": ("DBE5F2", "EDEDEE", "E5ECF6", "E6EDF6", "E7EDF7", "EDF0F5", "E7EBF2", "E6EAF5"),
"line_strong": ("E4E4E5", "C8D5E6", "C9DCF7", "ADC8F0", "B6CDEE"),
"heading": ("1A1C1F", "202C3F", "111F46"),
"text": ("273244", "263551", "24334A", "233149", "3F4E75"),
"muted": ("606163", "6A6B6D", "5D6B80", "7886AA", "708097"),
"disabled": ("8E8F90", "8A97A9", "9AA6B7"),
"disabled_surface": ("F2F2F2", "F0F0F0"),
"success_soft": ("EEF7F3", "EAF9F3"),
"warning": ("A9691D", "9C681F"),
"warning_soft": ("FCF5E9", "FFF5E6", "FFF6E7"),
"danger": ("BE4B58", "B84652"),
"danger_soft": ("FFF0F2", "FFF1F3"),
}
_LEGACY = {colour.lower(): PALETTE[role] for role, colours in _LEGACY_ROLES.items() for colour in colours}
_HEX = re.compile(r"#([0-9a-fA-F]{6})(?![0-9a-fA-F])")
def clinical_stylesheet(source: str) -> str:
"""Resolve clinical tokens and migrate known legacy light-theme colours."""
resolved = Template(source).safe_substitute(TOKENS)
return _HEX.sub(lambda match: _LEGACY.get(match[1].lower(), match[0]), resolved)
+78 -150
View File
@@ -63,9 +63,7 @@ from PySide6.QtWidgets import (
QWidget,
)
from .chat_items import ChatItem, parse_chat_item
from .design_system import PALETTE, clinical_stylesheet
from .diagnosis_editors import FlowLayout
from .diagnosis_editors import FlowLayout
from .diagnosis_media import shared_image_manager
from .diagnosis_terms import FIELD_DICTIONARIES, format_timestamp, shared_terms
@@ -81,7 +79,10 @@ QFrame#DiagnosisDrawer {
border-left: 1px solid #EDEDEE;
}
QFrame#DiagnosisDrawerHeader {
background-color: #FFFFFF;
background-color: qlineargradient(
x1:0, y1:0, x2:0, y2:1,
stop:0 #FFFFFF, stop:1 #F7F7F7
);
border-bottom: 1px solid #EDEDEE;
}
QFrame#DiagnosisDrawerFooter {
@@ -103,7 +104,7 @@ QLabel#DiagnosisDrawerModeBadge,
QLabel#DiagnosisReadonlyStatus,
QLabel[diagnosisTag="true"] {
padding: 4px 9px;
border-radius: $ds_radius_small;
border-radius: 9px;
font-size: 12px;
font-weight: 500;
}
@@ -157,8 +158,8 @@ QDialog QPushButton:pressed {
border-color: #354BB4;
}
QDialog QPushButton:disabled {
color: $ds_disabled;
background-color: $ds_disabled_surface;
color: #E4E4E5;
background-color: #FFFFFF;
border-color: #EDEDEE;
}
QDialog QPushButton[variant="primary"] {
@@ -174,9 +175,9 @@ QDialog QPushButton[variant="primary"]:focus {
border-color: #4156C4;
}
QDialog QPushButton[variant="primary"]:disabled {
color: $ds_disabled;
background-color: $ds_disabled_surface;
border-color: $ds_line;
color: #FFFFFF;
background-color: #F0F0F0;
border-color: #F0F0F0;
}
QDialog QPushButton[variant="secondary"] {
color: #4F63D9;
@@ -265,9 +266,9 @@ QDialog#DiagnosisDialogRoot QPushButton#DiagnosisSaveButton:focus {
border-color: #4156C4;
}
QDialog#DiagnosisDialogRoot QPushButton#DiagnosisSaveButton:disabled {
color: $ds_disabled;
background-color: $ds_disabled_surface;
border-color: $ds_line;
color: #FFFFFF;
background-color: #F0F0F0;
border-color: #F0F0F0;
}
QDialog#DiagnosisDialogRoot QPushButton#DiagnosisFooterCloseButton {
color: #606163;
@@ -381,10 +382,10 @@ QFrame#DiagnosisFormHost {
QFrame[diagnosisSection="true"] {
background-color: #FFFFFF;
border: 1px solid #EDEDEE;
border-radius: 16px;
border-radius: 12px;
}
QLabel[diagnosisFieldLabel="true"] {
color: $ds_muted;
color: #1A1C1F;
font-size: 12px;
font-weight: 500;
}
@@ -424,7 +425,7 @@ QDoubleSpinBox[diagnosisField="true"]:focus,
QSpinBox[diagnosisField="true"]:focus,
QTimeEdit[diagnosisField="true"]:focus {
border: 1px solid #8B9AD9;
background-color: $ds_surface;
background-color: #F7F7F7;
}
QLineEdit[diagnosisField="true"][invalid="true"],
QComboBox[diagnosisField="true"][invalid="true"],
@@ -450,8 +451,8 @@ QLabel#DiagnosisSectionTitle {
background-color: transparent;
border: 0;
padding: 0;
font-size: 14px;
font-weight: 600;
font-size: 13px;
font-weight: 500;
letter-spacing: 0.02em;
}
QFrame#DiagnosisSectionAccent {
@@ -468,9 +469,9 @@ QFrame#DiagnosisReadonlyPage {
background-color: #F6F6F6;
}
QFrame#DiagnosisReadonlyHero {
background-color: $ds_surface;
border: 1px solid $ds_line;
border-radius: $ds_radius_panel;
background-color: #F7F7F7;
border: 1px solid #F0F0F0;
border-radius: 12px;
}
QLabel#DiagnosisReadonlyTitle {
color: #1A1C1F;
@@ -540,7 +541,7 @@ QFrame#DiagnosisReadonlyCaseCard,
QFrame[diagnosisReadonlyCard="true"] {
background-color: #FFFFFF;
border: 1px solid #EDEDEE;
border-radius: 16px;
border-radius: 14px;
}
QLabel#DiagnosisReadonlyCardTitle {
color: #1A1C1F;
@@ -719,25 +720,6 @@ QFrame#DiagnosisChatBubble[side="doctor"] {
border: 1px solid #F0F0F0;
border-radius: 8px;
}
QFrame#DiagnosisChatEvent {
background-color: #F7F8FA;
border: 1px solid #EDEDEE;
border-radius: 8px;
}
QLabel#DiagnosisChatEventMarker {
color: #697386;
font-size: 12px;
font-weight: 600;
}
QLabel#DiagnosisChatEventTitle {
color: #374151;
font-size: 13px;
font-weight: 600;
}
QLabel#DiagnosisChatEventDetail {
color: #697386;
font-size: 12px;
}
QLabel#DiagnosisChatMeta {
color: #606163;
font-size: 12px;
@@ -769,7 +751,7 @@ QWidget[diagnosisChoiceHost="true"] QPushButton {
color: #1A1C1F;
background-color: #FFFFFF;
border: 1px solid #EDEDEE;
border-radius: 10px;
border-radius: 999px;
font-size: 12px;
}
QWidget[diagnosisChoiceHost="true"] QPushButton:hover,
@@ -1066,7 +1048,6 @@ _DIAGNOSIS_BLUE_REPLACEMENTS = (
)
for _source_color, _theme_color in _DIAGNOSIS_BLUE_REPLACEMENTS:
DIAGNOSIS_QSS = DIAGNOSIS_QSS.replace(_source_color, _theme_color)
DIAGNOSIS_QSS = clinical_stylesheet(DIAGNOSIS_QSS)
def _text(value: Any, default: str = "—") -> str:
@@ -1146,19 +1127,12 @@ class DiagnosisSwitch(QAbstractButton):
track = QRectF(1, 3, self.width() - 2, self.height() - 6)
checked = self.isChecked()
painter.setPen(Qt.PenStyle.NoPen)
painter.setBrush(QColor(PALETTE["accent"] if checked else PALETTE["line_strong"]))
if not self.isEnabled():
painter.setOpacity(0.6)
painter.setBrush(QColor("#4F63D9" if checked else "#E4E4E5"))
painter.drawRoundedRect(track, track.height() / 2, track.height() / 2)
diameter = track.height() - 4
x = track.right() - diameter - 2 if checked else track.left() + 2
painter.setBrush(QColor("#FFFFFF"))
painter.drawEllipse(QRectF(x, track.top() + 2, diameter, diameter))
if self.hasFocus():
painter.setOpacity(1)
painter.setPen(QPen(QColor(PALETTE["focus"]), 1))
painter.setBrush(Qt.BrushStyle.NoBrush)
painter.drawRoundedRect(QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5), 11, 11)
painter.end()
@@ -1196,19 +1170,13 @@ class SaveStateButton(QPushButton):
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
enabled = self.isEnabled()
idle_color = PALETTE["accent_pressed"] if self.isDown() else PALETTE["accent"]
color = {
"success": PALETTE["success"],
"error": PALETTE["danger"],
"loading": PALETTE["accent"],
}.get(self._state, idle_color if enabled else PALETTE["disabled_surface"])
"success": "#287B65",
"error": "#BE4B58",
}.get(self._state, "#4F63D9" if enabled else "#8E8F90")
painter.setPen(Qt.PenStyle.NoPen)
painter.setBrush(QColor(color))
painter.drawRoundedRect(QRectF(self.rect()).adjusted(1, 1, -1, -1), 10, 10)
if self.hasFocus():
painter.setPen(QPen(QColor(PALETTE["focus"]), 1))
painter.setBrush(Qt.BrushStyle.NoBrush)
painter.drawRoundedRect(QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5), 10, 10)
label = {
"loading": "正在保存",
"success": "保存成功",
@@ -1232,9 +1200,7 @@ class SaveStateButton(QPushButton):
else:
painter.drawLine(x + 3, center_y - 5, x + 12, center_y + 5)
painter.drawLine(x + 12, center_y - 5, x + 3, center_y + 5)
painter.setPen(QColor(
PALETTE["disabled"] if not enabled and self._state == "idle" else PALETTE["surface"]
))
painter.setPen(QColor("#FFFFFF"))
painter.drawText(
QRect(x + icon_width, 0, metrics.horizontalAdvance(label), self.height()),
Qt.AlignmentFlag.AlignCenter,
@@ -1829,10 +1795,10 @@ class MessageStrip(QFrame):
self.glyph = QLabel("i")
self.glyph.setFixedWidth(18)
self.glyph.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.glyph.setStyleSheet(clinical_stylesheet("font-weight:700; color:$ds_accent;"))
self.glyph.setStyleSheet("font-weight:700; color:#4F63D9;")
self.label = QLabel()
self.label.setWordWrap(True)
self.label.setStyleSheet(clinical_stylesheet("color:$ds_text; font-size:13px;"))
self.label.setStyleSheet("color:#1A1C1F; font-size:13px;")
layout.addWidget(self.glyph)
layout.addWidget(self.label, 1)
self.action_button = QPushButton()
@@ -1908,7 +1874,7 @@ class LoadingOverlay(QFrame):
layout.setSpacing(8)
self.glyph = _LoadingSpinner(self)
label = QLabel(text)
label.setStyleSheet(clinical_stylesheet("color:$ds_muted; font-size:13px;"))
label.setStyleSheet("color:#606163; font-size:13px;")
layout.addWidget(self.glyph)
layout.addWidget(label)
self.hide()
@@ -1999,15 +1965,15 @@ class RecordTable(QTableWidget):
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter
)
if column_index in danger_columns:
item.setForeground(QColor(PALETTE["danger"]))
item.setForeground(QColor("#BE4B58"))
kind = semantic.get(column_index)
if kind:
palette = {
"success": (PALETTE["success"], PALETTE["success_soft"]),
"warning": (PALETTE["warning"], PALETTE["warning_soft"]),
"danger": (PALETTE["danger"], PALETTE["danger_soft"]),
"info": (PALETTE["accent"], PALETTE["accent_soft"]),
"neutral": (PALETTE["muted"], PALETTE["surface_alt"]),
"success": ("#287B65", "#EAF9F3"),
"warning": ("#A9691D", "#FFF5E6"),
"danger": ("#BE4B58", "#FFF1F3"),
"info": ("#4F63D9", "#EEF1FA"),
"neutral": ("#6A6B6D", "#F7F7F7"),
}
foreground, background = palette.get(kind, palette["neutral"])
item.setForeground(QColor(foreground))
@@ -2047,20 +2013,20 @@ class BloodTrendChart(QWidget):
plot = self.rect().adjusted(48, 24, -22, -38)
values = [value for value in (*self._fasting, *self._postprandial) if value is not None]
if not values or plot.width() <= 0 or plot.height() <= 0:
painter.setPen(QColor(PALETTE["muted"]))
painter.setPen(QColor("#606163"))
painter.drawText(self.rect(), Qt.AlignmentFlag.AlignCenter, "当前时间范围暂无血糖数据")
painter.end()
return
upper = max(12.0, max(values) * 1.15)
painter.setPen(QPen(QColor(PALETTE["line"]), 1))
painter.setPen(QPen(QColor("#EDEDEE"), 1))
for step in range(5):
y = plot.bottom() - round(plot.height() * step / 4)
painter.drawLine(plot.left(), y, plot.right(), y)
painter.setPen(QColor(PALETTE["muted"]))
painter.setPen(QColor("#606163"))
painter.drawText(
4, y - 8, 40, 16, Qt.AlignmentFlag.AlignRight, f"{upper * step / 4:.0f}"
)
painter.setPen(QPen(QColor(PALETTE["line"]), 1))
painter.setPen(QPen(QColor("#EDEDEE"), 1))
count = max(1, len(self._dates) - 1)
def point(index: int, value: float) -> QPointF:
@@ -2090,7 +2056,7 @@ class BloodTrendChart(QWidget):
painter.setPen(QColor("#A9691D"))
painter.drawText(plot.left() + 100, 4, 110, 18, Qt.AlignmentFlag.AlignLeft, "● 餐后血糖")
if self._dates:
painter.setPen(QColor(PALETTE["muted"]))
painter.setPen(QColor("#606163"))
painter.drawText(
plot.left(),
plot.bottom() + 8,
@@ -2293,7 +2259,7 @@ class DailyRecordPanel(QFrame):
self.todo_table.setMinimumHeight(180)
todo_layout.addWidget(self.todo_table)
self.todo_summary = QLabel("共 0 条")
self.todo_summary.setStyleSheet(clinical_stylesheet("color:$ds_muted; font-size:13px;"))
self.todo_summary.setStyleSheet("color:#606163; font-size:13px;")
todo_layout.addWidget(self.todo_summary, 0, Qt.AlignmentFlag.AlignRight)
root.addWidget(todo_card)
self.clear()
@@ -2451,8 +2417,8 @@ class DailyRecordPanel(QFrame):
for row_index, (metric, label) in enumerate(self.METRICS):
label_item = QTableWidgetItem(label)
label_item.setFont(label_font)
label_item.setForeground(QColor(PALETTE["muted"]))
label_item.setBackground(QColor(PALETTE["surface_alt"]))
label_item.setForeground(QColor("#606163"))
label_item.setBackground(QColor("#F7F7F7"))
self.matrix.setItem(row_index, 0, label_item)
for date_index, date in enumerate(dates, 1):
b = blood.get(date)
@@ -2505,11 +2471,11 @@ class DailyRecordPanel(QFrame):
item = QTableWidgetItem(value)
item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
if high:
item.setForeground(QColor(PALETTE["danger"]))
item.setBackground(QColor(PALETTE["danger_soft"]))
item.setForeground(QColor("#BE4B58"))
item.setBackground(QColor("#FFF1F3"))
elif value.endswith("· 自录"):
item.setForeground(QColor(PALETTE["text"]))
item.setBackground(QColor(PALETTE["surface_alt"]))
item.setForeground(QColor("#1A1C1F"))
item.setBackground(QColor("#F7F7F7"))
edit_kind = ""
edit_source: Any = None
if metric in {"fasting", "postprandial", "other", "bp", "western", "insulin"}:
@@ -3036,7 +3002,7 @@ class ChatPanel(QWidget):
toolbar_layout.setContentsMargins(0, 0, 0, 0)
toolbar_layout.setSpacing(8)
archive = QLabel("仅展示服务端已归档消息(only_archived=1)")
archive.setStyleSheet(clinical_stylesheet("color:$ds_muted;font-size:12px;"))
archive.setStyleSheet("color:#606163;font-size:12px;")
toolbar_layout.addWidget(archive)
toolbar_layout.addStretch(1)
self.sync_button = QPushButton("同步最新(后台异步)")
@@ -3068,16 +3034,25 @@ class ChatPanel(QWidget):
widget = item.widget()
if widget is not None and widget not in {self.empty, self.toolbar, self.info}:
widget.deleteLater()
visible_count = 0
self.empty.setVisible(not messages)
for message in messages:
item = parse_chat_item(message, include_date=True)
if item is None:
continue
visible_count += 1
if item.variant == "event":
self.root.insertWidget(max(2, self.root.count() - 1), self._event_row(item))
continue
side = "doctor" if item.role == "doctor" else "patient"
doctor_flag = _pick(message, "is_from_doctor", default=False)
is_doctor = (
doctor_flag.strip().lower() not in {"", "0", "false", "no"}
if isinstance(doctor_flag, str)
else bool(doctor_flag)
)
side = (
"doctor"
if is_doctor
or str(_pick(message, "role", "sender_type", default="")).lower()
in {
"doctor",
"staff",
"2",
}
else "patient"
)
row = QWidget()
row_layout = QHBoxLayout(row)
row_layout.setContentsMargins(0, 0, 0, 0)
@@ -3090,14 +3065,13 @@ class ChatPanel(QWidget):
bubble_layout.setSpacing(5)
meta = QLabel(
f"{_text(_pick(message, 'sender_name', 'from_staff_name', 'name'), '患者' if side == 'patient' else '医生')} "
f"{item.time_text}"
f"{_text(_pick(message, 'create_time', 'time'), '')}"
)
meta.setObjectName("DiagnosisChatMeta")
meta.setTextFormat(Qt.TextFormat.PlainText)
message_type = str(
_pick(message, "message_type", "msg_type", "type", default="text") or "text"
).lower()
body_text = _text(_pick(message, "text", "content", "message"), "不支持的消息")
body_text = _text(_pick(message, "content", "text", "message"), "不支持的消息")
body: QWidget
if message_type in {"image", "2"}:
target = str(
@@ -3137,11 +3111,9 @@ class ChatPanel(QWidget):
)
body = action
else:
text = QLabel(body_text)
text = QLabel(body_text)
text.setObjectName("DiagnosisChatText")
text.setTextFormat(Qt.TextFormat.PlainText)
text.setWordWrap(True)
text.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
body = text
bubble_layout.addWidget(meta)
bubble_layout.addWidget(body)
@@ -3152,50 +3124,6 @@ class ChatPanel(QWidget):
row_layout.addWidget(bubble)
row_layout.addStretch(1)
self.root.insertWidget(max(2, self.root.count() - 1), row)
self.empty.setVisible(visible_count == 0)
@staticmethod
def _event_row(item: ChatItem) -> QWidget:
row = QWidget()
layout = QHBoxLayout(row)
layout.setContentsMargins(0, 0, 0, 0)
layout.addStretch(1)
card = QFrame()
card.setObjectName("DiagnosisChatEvent")
card.setProperty("tone", item.tone)
card.setMaximumWidth(620)
card.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred)
content = QGridLayout(card)
content.setContentsMargins(12, 10, 12, 10)
content.setHorizontalSpacing(9)
content.setVerticalSpacing(4)
marker = QLabel(item.marker)
marker.setObjectName("DiagnosisChatEventMarker")
marker.setTextFormat(Qt.TextFormat.PlainText)
marker.setFixedWidth(22)
marker.setAlignment(Qt.AlignmentFlag.AlignCenter)
content.addWidget(marker, 0, 0)
title = QLabel(item.title)
title.setObjectName("DiagnosisChatEventTitle")
title.setTextFormat(Qt.TextFormat.PlainText)
title.setWordWrap(True)
content.addWidget(title, 0, 1)
content.setColumnStretch(1, 1)
if item.time_text:
time = QLabel(item.time_text)
time.setObjectName("DiagnosisChatMeta")
time.setTextFormat(Qt.TextFormat.PlainText)
content.addWidget(time, 0, 2, alignment=Qt.AlignmentFlag.AlignRight)
if item.detail:
detail = QLabel(item.detail)
detail.setObjectName("DiagnosisChatEventDetail")
detail.setTextFormat(Qt.TextFormat.PlainText)
detail.setWordWrap(True)
detail.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
content.addWidget(detail, 1, 1, 1, 2)
layout.addWidget(card, 4)
layout.addStretch(1)
return row
@dataclass(frozen=True)
@@ -3312,7 +3240,7 @@ class CaseGrid(QFrame):
if group_index:
divider = QFrame()
divider.setFrameShape(QFrame.Shape.HLine)
divider.setStyleSheet(clinical_stylesheet("border:0; border-top:1px solid $ds_line;"))
divider.setStyleSheet("border:0; border-top:1px dashed #E4E4E5;")
self.root.addWidget(divider)
group_title = QLabel(f"● {group_name}")
group_title.setProperty("diagnosisCaseGroup", True)
@@ -3470,11 +3398,11 @@ def readonly_card(title: str, object_name: str, body: QWidget) -> QFrame:
def set_tag_item(item: QTableWidgetItem, kind: str) -> None:
palette = {
"success": (PALETTE["success"], PALETTE["success_soft"]),
"warning": (PALETTE["warning"], PALETTE["warning_soft"]),
"danger": (PALETTE["danger"], PALETTE["danger_soft"]),
"info": (PALETTE["accent"], PALETTE["accent_soft"]),
"neutral": (PALETTE["muted"], PALETTE["surface_alt"]),
"success": ("#287B65", "#EAF9F3"),
"warning": ("#A9691D", "#FFF5E6"),
"danger": ("#BE4B58", "#FFF1F3"),
"info": ("#4F63D9", "#EEF1FA"),
"neutral": ("#6A6B6D", "#F7F7F7"),
}
foreground, background = palette.get(kind, palette["neutral"])
item.setForeground(QColor(foreground))
@@ -7,7 +7,7 @@ admin-table presentation cannot leak into another workstation page.
from __future__ import annotations
from collections.abc import Callable, Iterable, Mapping, Sequence
from collections.abc import Iterable, Mapping, Sequence
from math import ceil
from typing import Any
@@ -67,22 +67,24 @@ from ..core.appointment_modes import (
can_appointment_video,
)
from . import icons
from .design_system import PALETTE, clinical_stylesheet
from .reception_style import TECH_BLUE, body_family, heading_family
from .widgets import display_text, first_value, gender_text, get_value
PRIMARY = QColor(PALETTE["accent"])
TEXT = QColor(PALETTE["text"])
SECONDARY = QColor(PALETTE["muted"])
PLACEHOLDER = QColor(PALETTE["disabled"])
PRIMARY = QColor("#4F63D9")
TEXT = QColor("#1A1C1F")
SECONDARY = QColor("#606163")
PLACEHOLDER = QColor("#8E8F90")
_INVALID_INDEX = QModelIndex()
# The last two columns form the compact frozen pane. Video status and ending
# time occupy separate lines; actions keep two inline links plus 更多, with
# the remaining actions in its menu so clinical columns retain more space.
# The last two columns are the frozen right-hand pane. They were 120 + 410,
# which pinned 532 px of the table. Measured against what they actually hold:
# the widest video cell is "暂无通话" at 56 px, and the action cell - two inline
# buttons plus 更多, all two-character labels - reports a 145 px sizeHint. So
# 265 px of the action column was permanently blank on every row while the data
# columns to its left were horizontally scrolling.
_TABLE_COLUMN_WIDTHS = (48, 70, 60, 100, 175, 88, 120, 100, 72, 110, 96, 160)
_BLUE_COLUMN_WIDTHS = (48, 70, 82, 102, 244, 90, 84, 90, 88, 122, 92, 158)
_BLUE_WARNING = QColor(PALETTE["warning"])
_BLUE_DANGER = QColor(PALETTE["danger"])
_BLUE_WARNING = QColor("#A9691D")
_BLUE_DANGER = QColor("#BE4B58")
def _blue_font(pixels: int = 13, *, medium: bool = False) -> QFont:
@@ -249,14 +251,14 @@ class _DiagnosisActionMenu(QMenu):
return
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
painter.fillRect(rect, QColor(PALETTE["surface"]))
painter.fillRect(rect, QColor("#FFFFFF"))
item_rect = rect
painter.setPen(Qt.PenStyle.NoPen)
painter.setBrush(QColor(PALETTE["surface_alt"]) if self.activeAction() is action else QColor(PALETTE["surface"]))
painter.setBrush(QColor("#F7F7F7") if self.activeAction() is action else QColor("#FFFFFF"))
painter.drawRoundedRect(item_rect, 3, 3)
icon_rect = QRect(item_rect.left() + 8, item_rect.center().y() - 9, 18, 18)
action.icon().paint(painter, icon_rect)
painter.setPen(QColor(PALETTE["danger"] if action.isEnabled() else PALETTE["disabled"]))
painter.setPen(QColor("#BE4B58" if action.isEnabled() else "#8E8F90"))
painter.drawText(
item_rect.adjusted(34, 0, -10, 0),
Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft,
@@ -824,8 +826,6 @@ class DiagnosisTableModel(QAbstractTableModel):
default="",
)
return f"最近渠道:{channel}" if channel else ""
if column == 6:
return DiagnosisTableModel._display(row, column)
if column == 7:
return display_text(first_value(row, "assistant_name"), "")
if column == 9:
@@ -852,7 +852,7 @@ class DiagnosisHeader(QHeaderView):
def paintSection(self, painter: QPainter, rect: QRect, logical_index: int) -> None: # noqa: N802
if self.tech_blue:
painter.save()
painter.fillRect(rect, QColor(PALETTE["surface_alt"]))
painter.fillRect(rect, QColor("#F5F8FD"))
painter.setPen(QPen(QColor(TECH_BLUE["line"]), 1))
painter.drawLine(rect.bottomLeft(), rect.bottomRight())
painter.setFont(_blue_font())
@@ -873,7 +873,7 @@ class DiagnosisHeader(QHeaderView):
painter.save()
painter.setPen(Qt.PenStyle.NoPen)
primary = QColor(TECH_BLUE["accent"]) if self.tech_blue else PRIMARY
secondary = QColor(TECH_BLUE["muted"]) if self.tech_blue else QColor(PALETTE["muted"])
secondary = QColor(TECH_BLUE["muted"]) if self.tech_blue else QColor("#606163")
painter.setBrush(primary if direction == "asc" else secondary)
painter.drawPolygon(
QPolygon(
@@ -956,7 +956,7 @@ class DiagnosisItemDelegate(QStyledItemDelegate):
painter,
option.rect,
"已确认" if _confirmed(record) else "未确认",
QColor(PALETTE["success"]) if _confirmed(record) else QColor(PALETTE["warning"]),
QColor("#287B65") if _confirmed(record) else QColor("#A9691D"),
)
elif index.column() == 6:
self._paint_followup(painter, option.rect, record)
@@ -1026,16 +1026,16 @@ class DiagnosisItemDelegate(QStyledItemDelegate):
) -> None:
hovered = model.hover_row == row
base = (
QColor(PALETTE["accent_soft"])
QColor("#EEF1FA")
if selected
else QColor(PALETTE["surface_alt"] if hovered or row % 2 else PALETTE["surface"])
else QColor("#F7F7F7" if hovered else "#F7F7F7" if row % 2 else "#FFFFFF")
)
special = not _confirmed(record) or not _has_appointment(record)
painter.fillRect(rect, base)
if special and column == 0:
stripe = QColor(PALETTE["warning"]) if not _confirmed(record) else QColor(PALETTE["accent"])
stripe = QColor("#A9691D") if not _confirmed(record) else QColor("#4F63D9")
painter.fillRect(QRect(rect.left(), rect.top(), 3, rect.height()), stripe)
painter.setPen(QPen(QColor(PALETTE["line"]), 1))
painter.setPen(QPen(QColor("#EDEDEE"), 1))
painter.drawLine(QLine(rect.bottomLeft(), rect.bottomRight()))
@staticmethod
@@ -1073,8 +1073,8 @@ class DiagnosisItemDelegate(QStyledItemDelegate):
painter,
QRect(left, content.center().y() - 10, 31, 20),
"NEW",
QColor(PALETTE["danger"]),
QColor(PALETTE["surface"]),
QColor("#BE4B58"),
QColor("#FFFFFF"),
10,
)
@@ -1084,17 +1084,17 @@ class DiagnosisItemDelegate(QStyledItemDelegate):
self._draw_text(painter, content, "未挂号", PLACEHOLDER, 13)
return
rows = _appointments(record)
painter.setPen(QPen(QColor(PALETTE["line"]), 1))
painter.setBrush(QColor(PALETTE["surface"]))
painter.setPen(QPen(QColor("#EDEDEE"), 1))
painter.setBrush(QColor("#FFFFFF"))
painter.drawRoundedRect(content, 6, 6)
y = content.top() + 4
for position, appointment in enumerate(rows or [{}]):
status = _as_int(first_value(appointment, "status", "appointment_status"), -1)
label, fg, bg = {
1: ("已预约", QColor(PALETTE["accent"]), QColor(PALETTE["accent_soft"])),
3: ("已完成", QColor(PALETTE["success"]), QColor(PALETTE["success_soft"])),
4: ("已过号", QColor(PALETTE["warning"]), QColor(PALETTE["warning_soft"])),
}.get(status, ("未知", SECONDARY, QColor(PALETTE["surface_alt"])))
1: ("已预约", QColor("#4F63D9"), QColor("#EEF1FA")),
3: ("已完成", QColor("#287B65"), QColor("#E8F6F1")),
4: ("已过号", QColor("#A9691D"), QColor("#FFF4D8")),
}.get(status, ("未知", SECONDARY, QColor("#F7F7F7")))
self._draw_tag(painter, QRect(content.left() + 6, y, 46, 20), label, bg, fg, 12)
doctor = display_text(first_value(appointment, "doctor_name"), "-")
time_text = display_text(first_value(appointment, "time_text", "appointment_time"), "-")
@@ -1109,12 +1109,12 @@ class DiagnosisItemDelegate(QStyledItemDelegate):
painter,
QRect(content.left() + 6, y + 19, max(20, content.width() - 12), 17),
time_text,
QColor(PALETTE["warning"]) if status == 4 else SECONDARY,
QColor("#A9691D") if status == 4 else SECONDARY,
13,
)
y += 42
if position < len(rows) - 1:
painter.setPen(QPen(QColor(PALETTE["line"]), 1, Qt.PenStyle.DashLine))
painter.setPen(QPen(QColor("#EDEDEE"), 1, Qt.PenStyle.DashLine))
painter.drawLine(content.left() + 6, y - 2, content.right() - 6, y - 2)
channel = first_value(
record,
@@ -1156,7 +1156,7 @@ class DiagnosisItemDelegate(QStyledItemDelegate):
painter,
QRect(content.left(), content.top() + 38, 72, 18),
"处方已作废",
QColor(PALETTE["surface_alt"]),
QColor("#F7F7F7"),
SECONDARY,
11,
outlined=True,
@@ -1169,11 +1169,11 @@ class DiagnosisItemDelegate(QStyledItemDelegate):
else:
days = _as_int(value)
color = (
QColor(PALETTE["success"])
QColor("#287B65")
if days <= 2
else QColor(PALETTE["warning"])
else QColor("#A9691D")
if days <= 6
else QColor(PALETTE["danger"])
else QColor("#BE4B58")
)
text, bold = str(days), days > 6
self._draw_text(
@@ -1323,8 +1323,6 @@ class _TechBlueDiagnosisDelegate(DiagnosisItemDelegate):
painter, content, "已确认" if _confirmed(record) else "未确认", pixels=13,
color="text" if _confirmed(record) else _BLUE_WARNING.name(),
)
elif column == 6:
self._followup(painter, content, display_text(index.data(), "—"))
elif column == 8:
prescribed = _as_bool(first_value(record, "has_prescription"))
self._text(painter, content, "已开方" if prescribed else "未开方",
@@ -1353,28 +1351,6 @@ class _TechBlueDiagnosisDelegate(DiagnosisItemDelegate):
medium=column == 2)
painter.restore()
@staticmethod
def _followup(painter: QPainter, rect: QRect, text: str) -> None:
"""Break at the date/time boundary, never in the middle of a number.
Keep the established row metrics. Long time ranges or doctor names
elide within their line; the model tooltip retains the complete text.
"""
painter.setFont(_blue_font(13))
painter.setPen(QColor(TECH_BLUE["muted"]))
metrics = painter.fontMetrics()
lines = text.splitlines()
if lines and metrics.horizontalAdvance(lines[0]) > rect.width():
lines[:1] = lines[0].split(maxsplit=1)
line_height = metrics.height()
top = rect.top() + max(0, (rect.height() - line_height * len(lines)) // 2)
for offset, line in enumerate(lines):
painter.drawText(
QRect(rect.left(), top + offset * line_height, rect.width(), line_height),
int(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter | Qt.TextFlag.TextSingleLine),
metrics.elidedText(line, Qt.TextElideMode.ElideRight, rect.width()),
)
def _appointments(self, painter: QPainter, rect: QRect, record: Any) -> None:
content = rect.adjusted(8, 0, -8, 0)
if not _has_appointment(record):
@@ -1633,7 +1609,6 @@ class DiagnosisTableHost(QFrame):
self,
*,
action_policy: Mapping[str, bool] | None = None,
video_entry_allowed: Callable[[Any], bool] | None = None,
parent: QWidget | None = None,
tech_blue: bool = False,
) -> None:
@@ -1643,7 +1618,6 @@ class DiagnosisTableHost(QFrame):
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
self.setMinimumHeight(0)
self.action_policy = dict(action_policy or {})
self.video_entry_allowed = video_entry_allowed
self.force_open_prescription = False
if tech_blue:
self.LEFT_WIDTHS = _BLUE_COLUMN_WIDTHS[:10]
@@ -1659,9 +1633,6 @@ class DiagnosisTableHost(QFrame):
self._fixed_height_timer.timeout.connect(self._sync_fixed_height)
self.main.setObjectName("DiagnosisMainTable")
self.fixed.setObjectName("DiagnosisFixedTable")
# Index widgets supply their own margins. Inherited item padding would
# shrink a 92px video cell to 76px and clip its wrapped status text.
self.fixed.setStyleSheet("QTableView#DiagnosisFixedTable::item { padding: 0; }")
for view in (self.main, self.fixed):
view.setModel(self.model)
view.setSelectionModel(self.selection)
@@ -1715,9 +1686,7 @@ class DiagnosisTableHost(QFrame):
self.main.horizontalHeader().sectionResized.connect(self._columns_resized)
self._fixed_render_signature: tuple[Any, ...] | None = None
if tech_blue:
self.setStyleSheet(clinical_stylesheet(
_TECH_BLUE_TABLE_QSS.replace("BODY_FAMILY", body_family())
))
self.setStyleSheet(_TECH_BLUE_TABLE_QSS.replace("BODY_FAMILY", body_family()))
def set_rows(self, rows: Iterable[Any]) -> None:
previous_id = DiagnosisTableModel.record_id(self.main.current_data())
@@ -1817,11 +1786,11 @@ class DiagnosisTableHost(QFrame):
host.hovered_row.connect(self._set_hover_row)
layout = QHBoxLayout(host)
layout.setContentsMargins(3, 2, 3, 2)
layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
video_capable = self.action_policy.get("video_call", False)
entry_allowed = self.video_entry_allowed is None or self.video_entry_allowed(record)
call_state = video_call_state(record)
is_text = appointment_type_value(record) == "text"
if video_capable and entry_allowed and _appointment_active(record) and (is_text or call_state == "live"):
if video_capable and _appointment_active(record) and (is_text or call_state == "live"):
button = QToolButton(host)
button.setText("图文沟通" if is_text else "进入视频问诊")
button.setProperty("rowLink", "primary")
@@ -1834,17 +1803,10 @@ class DiagnosisTableHost(QFrame):
button.clicked.connect(
lambda _checked=False, item=record: self.video_requested.emit(item)
)
layout.addWidget(button, 0, Qt.AlignmentFlag.AlignCenter)
layout.addWidget(button)
else:
status = "—"
if not entry_allowed:
# Match the admin's public status without turning an active
# doctor's room into a receiver entry for an unrelated user.
if _appointment_active(record) and can_appointment_video(appointment_type_value(record)):
status = {"live": "通话中", "pending_room": "接通中", "none": "—"}.get(
call_state, first_value(record, "video_call_hint.label", default="—")
)
elif video_capable:
if video_capable:
if call_state == "pending_room":
status = "等待接通"
elif _appointment_active(record):
@@ -1854,17 +1816,10 @@ class DiagnosisTableHost(QFrame):
_appointment_status(record),
"未挂号" if not _has_appointment(record) else "—",
)
status_text = display_text(status)
label = QLabel(status_text.replace(" · ", "\n", 1), host)
label = QLabel(display_text(status), host)
label.setProperty("fixedMuted", True)
label.setTextFormat(Qt.TextFormat.PlainText)
label.setToolTip(status_text)
label.setAlignment(Qt.AlignmentFlag.AlignCenter)
label.setWordWrap(True)
# Fill the cell instead of centering the label at its sizeHint:
# its wrapped height can grow when the available width changes.
label.setMinimumWidth(0)
label.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Expanding)
layout.addWidget(label)
return host
@@ -1933,7 +1888,6 @@ class DiagnosisTableHost(QFrame):
.replace("#8E8F90", TECH_BLUE["muted"])
+ f'QMenu {{ font-family: "{body_family()}"; font-weight: 400; }}'
)
menu.setStyleSheet(clinical_stylesheet(menu.styleSheet()))
for label, action, _semantic in demoted_actions:
_add_menu_action(
menu,
@@ -2660,19 +2614,19 @@ DIAGNOSIS_INDEX_QSS += """
#DiagnosisIndex QFrame#DiagnosisFilterCard,
#DiagnosisIndex QFrame#DiagnosisListCard {
border: 1px solid #EDEDEE;
border-radius: $ds_radius_panel;
border-radius: 13px;
}
#DiagnosisIndex QLineEdit,
#DiagnosisIndex QComboBox,
#DiagnosisIndex QDateEdit,
#DiagnosisIndex QSpinBox,
#DiagnosisIndex QPushButton {
border-radius: $ds_radius_control;
border-radius: 8px;
}
#DiagnosisIndex QToolButton[diagnosisChip="true"] { border-radius: $ds_radius_small; }
#DiagnosisIndex QToolButton[diagnosisChip="true"] { border-radius: 8px; }
#DiagnosisIndex QFrame#DiagnosisListToolbar {
border-top-left-radius: $ds_radius_panel;
border-top-right-radius: $ds_radius_panel;
border-top-left-radius: 13px;
border-top-right-radius: 13px;
}
#DiagnosisIndex QToolButton[diagnosisChip="true"]:checked[semantic="primary"],
#DiagnosisIndex QToolButton[diagnosisChip="true"]:checked[semantic="info"],
@@ -2680,27 +2634,7 @@ DIAGNOSIS_INDEX_QSS += """
#DiagnosisIndex QPushButton[variant="success"] {
color: #FFFFFF;
}
#DiagnosisIndex QLineEdit:focus,
#DiagnosisIndex QComboBox:focus,
#DiagnosisIndex QDateEdit:focus,
#DiagnosisIndex QSpinBox:focus,
#DiagnosisIndex QPushButton:focus {
border-color: $ds_focus;
}
#DiagnosisIndex QPushButton[variant="primary"]:pressed {
color: $ds_surface;
background-color: $ds_accent_pressed;
border-color: $ds_accent_pressed;
}
#DiagnosisIndex QPushButton:disabled,
#DiagnosisIndex QPushButton[variant="primary"]:disabled,
#DiagnosisIndex QPushButton[variant="success"]:disabled {
color: $ds_disabled;
background-color: $ds_disabled_surface;
border-color: $ds_line;
}
"""
DIAGNOSIS_INDEX_QSS = clinical_stylesheet(DIAGNOSIS_INDEX_QSS)
__all__ = [
@@ -32,8 +32,6 @@ from PySide6.QtWidgets import (
QWidget,
)
from .design_system import clinical_stylesheet
try:
from PySide6.QtMultimedia import QAudioOutput, QMediaPlayer
from PySide6.QtMultimediaWidgets import QVideoWidget
@@ -225,7 +223,7 @@ class InlineRecordingPlayer(QWidget):
self.setMinimumHeight(158)
self.setMaximumHeight(180)
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
self.setStyleSheet(clinical_stylesheet(_INLINE_PLAYER_QSS))
self.setStyleSheet(_INLINE_PLAYER_QSS)
root = QVBoxLayout(self)
root.setContentsMargins(1, 1, 1, 5)
@@ -468,11 +466,11 @@ class RecordingPlaybackCell(QWidget):
separator = QFrame()
separator.setObjectName("DiagnosisRecordingAlternateSeparator")
separator.setFrameShape(QFrame.Shape.HLine)
separator.setStyleSheet(clinical_stylesheet("color:$ds_line;"))
separator.setStyleSheet("color:#EDEDEE;")
layout.addWidget(separator)
label = QLabel("备用地址")
label.setObjectName("DiagnosisRecordingAlternateLabel")
label.setStyleSheet(clinical_stylesheet("color:$ds_muted; font-size:12px;"))
label.setStyleSheet("color:#606163; font-size:12px;")
layout.addWidget(label)
links = QHBoxLayout()
links.setContentsMargins(0, 0, 0, 0)
@@ -492,7 +490,7 @@ class RecordingPlaybackCell(QWidget):
layout.addLayout(links)
self.link_status = QLabel("")
self.link_status.setObjectName("DiagnosisRecordingLinkStatus")
self.link_status.setStyleSheet(clinical_stylesheet("color:$ds_danger; font-size:11px;"))
self.link_status.setStyleSheet("color:#BE4B58; font-size:11px;")
self.link_status.setWordWrap(True)
self.link_status.hide()
layout.addWidget(self.link_status)
@@ -809,7 +807,7 @@ class ImagePreviewDialog(QDialog):
self.setObjectName("DiagnosisImagePreview")
self.setWindowTitle(title)
self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose)
self.setStyleSheet(clinical_stylesheet(_IMAGE_PREVIEW_QSS))
self.setStyleSheet(_IMAGE_PREVIEW_QSS)
self.resize(880, 660)
root = QVBoxLayout(self)
File diff suppressed because it is too large Load Diff
@@ -1,646 +0,0 @@
"""Verified measurement snapshots and native glucose charts for completed AI replies.
Charts use recorded observations, never numbers extracted from the generated advice.
"""
from __future__ import annotations
import math
import re
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from datetime import date, datetime, time
from typing import Any
from PySide6.QtCore import QPointF, QRectF, QSize, Qt
from PySide6.QtGui import QColor, QMouseEvent, QPainter, QPaintEvent, QPen
from PySide6.QtWidgets import (
QAbstractItemView,
QFrame,
QHBoxLayout,
QHeaderView,
QLabel,
QPushButton,
QSizePolicy,
QTableWidget,
QTableWidgetItem,
QToolTip,
QVBoxLayout,
QWidget,
)
from .ai_consult_metric_state import UNKNOWN_COLOR, metric_color
_NUMERIC = re.compile(r"(?:\d+(?:\.\d+)?|\.\d+)(?:\s*mmol\s*/\s*l)?", re.IGNORECASE)
_DATE = re.compile(r"\d{4}-\d{2}-\d{2}")
_DATETIME = re.compile(r"\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}(?::\d{2})?")
_TIME = re.compile(r"\d{2}:\d{2}(?::\d{2})?")
_MISSING = frozenset(("", "—", "--", "-", "未填写", "未记录", "暂无"))
_SERIES = (
("fasting", "空腹血糖", Qt.PenStyle.SolidLine),
("postprandial", "餐后血糖", Qt.PenStyle.DashLine),
("other", "其他血糖", Qt.PenStyle.DotLine),
)
_SERIES_KEYS = {
"fasting": ("fasting_blood_sugar", "fasting_glucose"),
"postprandial": ("postprandial_blood_sugar", "postprandial_glucose"),
"other": ("other_blood_sugar", "other_glucose", "blood_sugar"),
}
_STATUS_LABELS = {
"high": "偏高", "low": "偏低", "normal": "正常", "abnormal": "异常",
"warning": "需关注", "0": "正常", "unknown": "未标注",
}
_CARD_QSS = """
QFrame#AiConsultGlucoseReport {
background: #FFFFFF; border: 1px solid #EDEDEE; border-radius: 10px;
}
QFrame#AiConsultGlucoseReport QLabel { background: transparent; border: 0; }
QFrame#AiConsultGlucoseReport QLabel#AiConsultGlucoseTitle {
color: #1A1C1F; font-size: 15px; font-weight: 600;
}
QFrame#AiConsultGlucoseReport QLabel#AiConsultGlucoseCount,
QFrame#AiConsultGlucoseReport QLabel#AiConsultGlucoseSource {
color: #606163; font-size: 12px;
}
QFrame#AiConsultGlucoseReport QLabel#AiConsultGlucoseState {
color: #606163; font-size: 13px; padding: 9px 0;
}
QFrame#AiConsultGlucoseReport QPushButton#AiConsultGlucoseDataToggle {
color: #4F63D9; background: #F7F8FC; border: 1px solid #E4E7F4;
border-radius: 6px; padding: 5px 9px; font-size: 12px;
}
QFrame#AiConsultGlucoseReport QPushButton#AiConsultGlucoseDataToggle:hover {
background: #EEF1FA;
}
QFrame#AiConsultGlucoseReport QTableWidget#AiConsultGlucoseTable {
color: #1A1C1F; background: #FFFFFF; alternate-background-color: #F7F8FC;
border: 1px solid #EDEDEE; border-radius: 4px; gridline-color: #EDEDEE;
font-size: 12px; selection-background-color: #EEF1FA; selection-color: #1A1C1F;
}
QFrame#AiConsultGlucoseReport QHeaderView::section {
background: #F7F8FC; color: #606163; border: 0; padding: 6px 3px; font-size: 12px;
}
"""
@dataclass(frozen=True, slots=True)
class GlucoseReading:
"""One source row. Missing series stay absent, including a whole-row gap."""
recorded_at: datetime
fasting: float | None = None
postprandial: float | None = None
other: float | None = None
has_recorded_time: bool = False
fasting_status: str = ""
postprandial_status: str = ""
other_status: str = ""
@property
def readout_count(self) -> int:
return sum(value is not None for value in (self.fasting, self.postprandial, self.other))
@property
def time_label(self) -> str:
if self.has_recorded_time:
pattern = "%Y-%m-%d %H:%M:%S" if self.recorded_at.second else "%Y-%m-%d %H:%M"
return self.recorded_at.strftime(pattern)
return self.recorded_at.strftime("%Y-%m-%d")
@dataclass(frozen=True, slots=True)
class GlucoseChartData:
readings: tuple[GlucoseReading, ...] = ()
diagnosis_id: int = 0
patient_id: int = 0
excluded_count: int = 0
unavailable_reason: str = ""
@property
def available(self) -> bool:
return self.readout_count > 0
@property
def readout_count(self) -> int:
return sum(reading.readout_count for reading in self.readings)
@property
def record_count(self) -> int:
return sum(reading.readout_count > 0 for reading in self.readings)
@property
def date_range(self) -> tuple[date, date] | None:
dates = [reading.recorded_at.date() for reading in self.readings if reading.readout_count]
return (min(dates), max(dates)) if dates else None
def _exact_owner(value: Any, expected: int) -> bool:
return type(value) is int and type(expected) is int and expected > 0 and value == expected
def _patient_matches(source: Mapping[str, Any], patient_id: int) -> bool:
if "patient_id" not in source:
return True
owner = source["patient_id"]
return type(owner) is int and owner > 0 and (patient_id <= 0 or owner == patient_id)
def _first(source: Mapping[str, Any], *keys: str) -> Any:
for key in keys:
value = source.get(key)
if value is not None and value != "":
return value
return None
def _rows(value: Any) -> list[Any]:
if isinstance(value, Sequence) and not isinstance(value, (str, bytes, bytearray)):
return list(value)
return []
def _unit_matches(source: Mapping[str, Any]) -> bool:
unit = _first(source, "unit", "glucose_unit", "blood_sugar_unit")
if unit is None:
return True
return isinstance(unit, str) and re.sub(r"\s", "", unit).casefold() == "mmol/l"
def _number(value: Any) -> tuple[float | None, bool]:
"""Return (reading, ambiguous); daily-record zero is the unfilled sentinel.
DailyRecordDialog writes every spinbox, whose zero text is 未填写. The server's
BloodRecordLogic likewise includes only >0 glucose values in its trend data.
"""
if value is None:
return None, False
if isinstance(value, str):
value = value.strip()
if value in _MISSING:
return None, False
if not _NUMERIC.fullmatch(value):
return None, True
value = re.sub(r"\s*mmol\s*/\s*l$", "", value, flags=re.IGNORECASE)
elif type(value) not in (int, float):
return None, True
try:
number = float(value)
except (OverflowError, TypeError, ValueError):
return None, True
if not math.isfinite(number) or number < 0:
return None, True
return (number, False) if number > 0 else (None, False)
def _recorded_at(row: Mapping[str, Any]) -> tuple[datetime, bool] | None:
value = _first(row, "record_date", "date", "measured_at", "time_text")
if not isinstance(value, str):
return None
value = value.strip()
try:
if _DATETIME.fullmatch(value):
return datetime.fromisoformat(value), True
if not _DATE.fullmatch(value):
return None
day = date.fromisoformat(value)
clock = row.get("record_time")
if clock is None or clock == "":
# Midnight positions a date-only observation; it is never displayed as a known time.
return datetime.combine(day, time.min), False
if not isinstance(clock, str) or not _TIME.fullmatch(clock.strip()):
return None
return datetime.combine(day, time.fromisoformat(clock.strip())), True
except ValueError:
return None
def _values(row: Mapping[str, Any], *, legacy: bool) -> tuple[dict[str, float | None], bool, bool]:
raw = {field: _first(row, *keys) for field, keys in _SERIES_KEYS.items()}
if legacy and all(value is None for value in raw.values()):
period = str(_first(row, "period", "time_slot", "meal") or "").strip().casefold()
target = "other"
if period in {"空腹", "空腹血糖", "fasting"}:
target = "fasting"
elif period in {
"餐后",
"餐后血糖",
"餐后2小时",
"餐后 2 小时",
"postprandial",
"postprandial_2h",
}:
target = "postprandial"
raw[target] = row.get("value")
parsed: dict[str, float | None] = {}
ambiguous = False
for field, value in raw.items():
parsed[field], invalid = _number(value)
ambiguous = ambiguous or invalid
return parsed, ambiguous, any(value is not None for value in raw.values())
def _statuses(row: Mapping[str, Any], *, legacy: bool) -> dict[str, str]:
"""Keep only explicit scalar states on the same verified source row."""
statuses = {}
for field, keys in _SERIES_KEYS.items():
raw = _first(row, *(f"{key}_status" for key in keys))
# Generic legacy states belong only to that row's single value/period.
if legacy and raw is None and all(_first(row, *keys) is None for keys in _SERIES_KEYS.values()):
values, _ambiguous, _has_fields = _values(row, legacy=True)
if values[field] is not None:
raw = _first(row, "value_status", "glucose_status", "blood_sugar_status", "status")
statuses[f"{field}_status"] = str(raw).strip() if type(raw) in (str, int) else ""
return statuses
def build_glucose_chart_data(
tracking: Any, *, diagnosis_id: int, patient_id: int = 0
) -> GlucoseChartData:
"""Snapshot only explicitly owned, dated observations without mutating the DTO.
Production blood_records takes precedence over legacy blood_sugar.entries to
avoid double plotting a response containing two representations of the same data.
"""
empty = GlucoseChartData(diagnosis_id=diagnosis_id, patient_id=patient_id)
if type(patient_id) is not int or patient_id < 0:
return GlucoseChartData(
diagnosis_id=diagnosis_id,
patient_id=0,
unavailable_reason="缺少可核验的患者归属信息。",
)
if not isinstance(tracking, Mapping):
return GlucoseChartData(
diagnosis_id=diagnosis_id,
patient_id=patient_id,
unavailable_reason="尚未加载本诊单的血糖记录。",
)
if not _exact_owner(tracking.get("diagnosis_id"), diagnosis_id) or not _patient_matches(
tracking, patient_id
):
return GlucoseChartData(
diagnosis_id=diagnosis_id,
patient_id=patient_id,
unavailable_reason="血糖记录未通过本诊单归属校验。",
)
expected_patient = patient_id or tracking.get("patient_id", 0)
legacy = "blood_records" not in tracking
section = tracking.get("blood_sugar") if legacy else tracking
if not isinstance(section, Mapping):
return empty
if legacy and (
("diagnosis_id" in section and not _exact_owner(section["diagnosis_id"], diagnosis_id))
or not _patient_matches(section, expected_patient)
):
return GlucoseChartData(
diagnosis_id=diagnosis_id,
patient_id=patient_id,
unavailable_reason="血糖记录未通过本诊单归属校验。",
)
expected_patient = expected_patient or section.get("patient_id", 0)
rows = (
_rows(_first(section, "entries", "records", "items"))
if legacy
else _rows(section.get("blood_records"))
)
readings: list[GlucoseReading] = []
excluded = 0
for row in rows:
if (
not isinstance(row, Mapping)
or not _exact_owner(row.get("diagnosis_id"), diagnosis_id)
or not _patient_matches(row, expected_patient)
):
excluded += 1
continue
if not _unit_matches(tracking) or not _unit_matches(section) or not _unit_matches(row):
excluded += 1
continue
recorded = _recorded_at(row)
if recorded is None:
excluded += 1
continue
values, ambiguous, has_fields = _values(row, legacy=legacy)
excluded += int(ambiguous)
if not has_fields:
continue
readings.append(GlucoseReading(
recorded[0], has_recorded_time=recorded[1], **values, **_statuses(row, legacy=legacy)
))
readings.sort(key=lambda reading: reading.recorded_at) # Stable: same-time rows stay separate.
return GlucoseChartData(tuple(readings), diagnosis_id, patient_id, excluded)
def _value_text(value: float | None) -> str:
return "—" if value is None else str(value).removesuffix(".0")
def _reading_status(reading: GlucoseReading, field: str) -> str:
if getattr(reading, field) is None:
return "未记录"
status = getattr(reading, f"{field}_status")
label = _STATUS_LABELS.get(status.casefold(), status) if status else "未标注"
return f"{label}(原始:{status})" if status and label != status else label
def _draw_marker(painter: QPainter, point: QPointF, series: str) -> None:
if series in {"postprandial", "diastolic_pressure"}:
painter.drawRect(QRectF(point.x() - 3.5, point.y() - 3.5, 7, 7))
elif series == "other":
painter.drawLine(QPointF(point.x() - 4, point.y()), QPointF(point.x() + 4, point.y()))
painter.drawLine(QPointF(point.x(), point.y() - 4), QPointF(point.x(), point.y() + 4))
else:
painter.drawEllipse(point, 3.5, 3.5)
class GlucoseTrendChart(QWidget):
"""An actual-date axis, with gaps and one point for every saved observation."""
def __init__(self, data: GlucoseChartData, parent: QWidget | None = None) -> None:
super().__init__(parent)
self.data = data
self.setObjectName("AiConsultGlucoseChart")
self.setMinimumHeight(210)
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
self.setMouseTracking(True)
self.setAccessibleName("本诊单血糖趋势图,单位 mmol/L")
description = []
for reading in data.readings:
values = ",".join(
f"{label} {_value_text(getattr(reading, field))}"
+ (" mmol/L" if getattr(reading, field) is not None else "")
+ f" · 状态 {_reading_status(reading, field)}"
for field, label, _style in _SERIES
)
if values:
description.append(f"{reading.time_label}:{values}")
self.setAccessibleDescription(
"空腹实线圆点、餐后虚线方点、其他点线十字;红色异常、绿色正常、灰色未记录/未标注。"
+ ";".join(description)
)
@staticmethod
def _point_color(reading: GlucoseReading, field: str) -> str:
return (
metric_color(getattr(reading, f"{field}_status"))
if getattr(reading, field) is not None
else UNKNOWN_COLOR
)
def sizeHint(self) -> QSize: # noqa: N802 - Qt API
return QSize(580, 220)
def _geometry(self) -> tuple[QRectF, datetime, float, float, float]:
plot = QRectF(self.rect()).adjusted(43, 32, -15, -35)
dates = [reading.recorded_at for reading in self.data.readings if reading.readout_count]
origin = min(dates) if dates else datetime.min
span = (max(dates) - origin).total_seconds() if dates else 0.0
values = [
value
for reading in self.data.readings
for value in (reading.fasting, reading.postprandial, reading.other)
if value is not None
]
lower, upper = (min(values), max(values)) if values else (0.0, 1.0)
padding = max(1.0, (upper - lower) * 0.18, upper * 0.05)
padded_upper = upper + padding
return (
plot,
origin,
span,
max(0.0, lower - padding),
padded_upper if math.isfinite(padded_upper) else upper,
)
def _position(
self,
reading: GlucoseReading,
value: float,
geometry: tuple[QRectF, datetime, float, float, float] | None = None,
) -> QPointF:
plot, origin, span, lower, upper = geometry or self._geometry()
x = (
plot.left() + plot.width() * (reading.recorded_at - origin).total_seconds() / span
if span
else plot.center().x()
)
y = plot.bottom() - plot.height() * ((value - lower) / (upper - lower))
return QPointF(x, y)
def _point_tooltip(self, position: QPointF) -> str:
hits: list[str] = []
geometry = self._geometry()
for index, reading in enumerate(self.data.readings, 1):
for field, label, _style in _SERIES:
value = getattr(reading, field)
if value is None:
continue
point = self._position(reading, value, geometry)
if (point.x() - position.x()) ** 2 + (point.y() - position.y()) ** 2 <= 100:
hits.append(
f"{reading.time_label} · 记录 {index}\n{label} {_value_text(value)} mmol/L"
f" · 状态 {_reading_status(reading, field)}"
)
return "\n\n".join(hits)
def mouseMoveEvent(self, event: QMouseEvent) -> None: # noqa: N802 - Qt API
tip = self._point_tooltip(event.position())
if tip:
QToolTip.showText(event.globalPosition().toPoint(), tip, self)
else:
QToolTip.hideText()
super().mouseMoveEvent(event)
def leaveEvent(self, event: Any) -> None: # noqa: N802 - Qt API
QToolTip.hideText()
super().leaveEvent(event)
def paintEvent(self, event: QPaintEvent) -> None: # noqa: N802 - Qt API
super().paintEvent(event)
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
font = painter.font()
font.setPixelSize(11)
painter.setFont(font)
geometry = self._geometry()
plot, _origin, _span, lower, upper = geometry
if plot.width() <= 0 or plot.height() <= 0:
painter.end()
return
painter.setPen(QColor("#606163"))
painter.drawText(QRectF(0, 0, 55, 20), Qt.AlignmentFlag.AlignLeft, "mmol/L")
legend_x = 64.0
for field, label, style in _SERIES:
if not any(getattr(reading, field) is not None for reading in self.data.readings):
continue
painter.setPen(QPen(QColor(UNKNOWN_COLOR), 2, style))
painter.setBrush(QColor(UNKNOWN_COLOR))
painter.drawLine(QPointF(legend_x, 10), QPointF(legend_x + 17, 10))
_draw_marker(painter, QPointF(legend_x + 8, 10), field)
painter.setPen(QColor(UNKNOWN_COLOR))
short_label = label.replace("血糖", "")
painter.drawText(
QRectF(legend_x + 23, 0, 40, 20), Qt.AlignmentFlag.AlignLeft, short_label
)
legend_x += 64
for tick in range(4):
y = plot.bottom() - plot.height() * tick / 3
painter.setPen(QPen(QColor("#EDEDEE"), 1))
painter.drawLine(QPointF(plot.left(), y), QPointF(plot.right(), y))
painter.setPen(QColor("#606163"))
painter.drawText(
QRectF(0, y - 8, 35, 16),
Qt.AlignmentFlag.AlignRight,
f"{lower + (upper - lower) * (tick / 3):.1f}",
)
for field, _label, style in _SERIES:
previous: QPointF | None = None
for reading in self.data.readings:
value = getattr(reading, field)
if value is None:
previous = None
continue
point = self._position(reading, value, geometry)
if previous is not None:
painter.setPen(QPen(QColor(UNKNOWN_COLOR), 2, style))
painter.drawLine(previous, point)
previous = point
# Draw status markers after all neutral line segments in this series.
for reading in self.data.readings:
value = getattr(reading, field)
if value is None:
continue
color = QColor(self._point_color(reading, field))
painter.setPen(QPen(color, 2))
painter.setBrush(color)
_draw_marker(painter, self._position(reading, value, geometry), field)
painter.setPen(QColor("#606163"))
dates = sorted(
{reading.recorded_at.date() for reading in self.data.readings if reading.readout_count}
)
if len(dates) == 1:
painter.drawText(
QRectF(plot.center().x() - 52, plot.bottom() + 9, 104, 18),
Qt.AlignmentFlag.AlignCenter,
dates[0].isoformat(),
)
elif dates:
painter.drawText(
QRectF(plot.left(), plot.bottom() + 9, 104, 18),
Qt.AlignmentFlag.AlignLeft,
dates[0].isoformat(),
)
painter.drawText(
QRectF(plot.right() - 104, plot.bottom() + 9, 104, 18),
Qt.AlignmentFlag.AlignRight,
dates[-1].isoformat(),
)
painter.end()
class GlucoseReportCard(QFrame):
def __init__(self, data: GlucoseChartData, parent: QWidget | None = None) -> None:
super().__init__(parent)
self.data = data
self.chart: GlucoseTrendChart | None = None
self.toggle_button: QPushButton | None = None
self.setObjectName("AiConsultGlucoseReport")
self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True)
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Maximum)
self.setStyleSheet(_CARD_QSS)
root = QVBoxLayout(self)
root.setContentsMargins(14, 12, 14, 12)
root.setSpacing(7)
title = QLabel("血糖变化趋势", self)
title.setObjectName("AiConsultGlucoseTitle")
root.addWidget(title)
self.table = QTableWidget(self)
self.table.setObjectName("AiConsultGlucoseTable")
self.table.hide()
if data.available:
count = QLabel(f"{data.readout_count} 次测量 · {data.record_count} 条记录", self)
count.setObjectName("AiConsultGlucoseCount")
root.addWidget(count)
self.chart = GlucoseTrendChart(data, self)
root.addWidget(self.chart)
if data.record_count == 1:
single = self._note("仅有 1 条记录,暂不连线。", "AiConsultGlucoseCount")
root.addWidget(single)
actions = QHBoxLayout()
actions.setContentsMargins(0, 0, 0, 0)
self.toggle_button = QPushButton("查看原始记录", self)
self.toggle_button.setObjectName("AiConsultGlucoseDataToggle")
self.toggle_button.setCheckable(True)
self.toggle_button.setAccessibleName("查看血糖原始记录")
self.toggle_button.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
self.toggle_button.toggled.connect(self._toggle_table)
actions.addWidget(self.toggle_button)
actions.addStretch(1)
root.addLayout(actions)
self._populate_table()
else:
root.addWidget(self._note("暂无可绘制的血糖记录", "AiConsultGlucoseState"))
reason = data.unavailable_reason or "尚无带明确日期的有效血糖读数。"
root.addWidget(self._note(reason, "AiConsultGlucoseSource"))
root.addWidget(self.table)
source = f"本诊单 #{data.diagnosis_id} 的已记录数据"
if data.date_range:
start, end = data.date_range
source += f" · {start.isoformat()}" + (f" 至 {end.isoformat()}" if end != start else "")
source += ";未填写处保留空缺。红色异常、绿色正常、灰色未记录/未标注;状态以原始记录为准。"
if data.excluded_count:
source += f"\n{data.excluded_count} 条记录含未纳入的内容(归属、日期或读数无法核验)。"
root.addWidget(self._note(source, "AiConsultGlucoseSource"))
def _note(self, text: str, name: str) -> QLabel:
label = QLabel(text, self)
label.setObjectName(name)
label.setTextFormat(Qt.TextFormat.PlainText)
label.setWordWrap(True)
label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
return label
def _populate_table(self) -> None:
table = self.table
table.setColumnCount(4)
table.setRowCount(len(self.data.readings))
table.setHorizontalHeaderLabels(["记录日期 / 时间", "空腹", "餐后", "其他"])
table.setAccessibleName("血糖原始记录,读数单位 mmol/L")
table.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
table.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
table.setAlternatingRowColors(True)
table.verticalHeader().hide()
table.verticalHeader().setDefaultSectionSize(29)
table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
table.horizontalHeader().setMinimumSectionSize(48)
table.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeMode.ResizeToContents)
table.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
table.setFixedHeight(min(224, 35 + max(1, len(self.data.readings)) * 29))
for row_index, reading in enumerate(self.data.readings):
values = [
reading.time_label,
*(_value_text(getattr(reading, field)) for field, _, _ in _SERIES),
]
for column, text in enumerate(values):
item = QTableWidgetItem(text)
if column == 0:
item.setToolTip(text)
else:
field = _SERIES[column - 1][0]
item.setForeground(QColor(GlucoseTrendChart._point_color(reading, field)))
item.setToolTip(
(f"{text} mmol/L" if text != "—" else "— · 未记录或读数不明确")
+ f" · 状态 {_reading_status(reading, field)}"
)
table.setItem(row_index, column, item)
def _toggle_table(self, checked: bool) -> None:
self.table.setVisible(checked)
if self.toggle_button is not None:
self.toggle_button.setText("收起原始记录" if checked else "查看原始记录")
self.toggle_button.setAccessibleName(
"收起血糖原始记录" if checked else "查看血糖原始记录"
)
self.updateGeometry()
@@ -1,121 +0,0 @@
"""从 AI 回复中摘出药名(中药 / 西药),供用药速览与正文高亮使用。
只用显式词表匹配,不按“…汤/…片”等后缀猜测,宁可漏标也不把普通词误标成药。
匹配按长词优先,所以「六味地黄丸」不会被拆成「地黄」。
"""
from __future__ import annotations
import re
from typing import NamedTuple
TCM = "tcm"
WESTERN = "western"
# 中药绿、西药蓝;与侧栏状态卡的完成/进行中色一致。
DRUG_COLORS = {
TCM: ("#1F7A4D", "#EAF7F0", "#BFE6D0"),
WESTERN: ("#3347B8", "#EEF1FA", "#C9D1F3"),
}
DRUG_STYLES = {
kind: f"color: {fg}; background-color: {bg}; font-weight: 700;"
for kind, (fg, bg, _border) in DRUG_COLORS.items()
}
# 常用中药饮片(两字及以上,避免单字误配)。
_TCM_HERBS = """
黄芪 党参 人参 西洋参 太子参 红参 白术 苍术 茯苓 茯神 土茯苓 猪苓 泽泻 薏苡仁 甘草 炙甘草
当归 川芎 白芍 赤芍 熟地黄 生地黄 熟地 生地 地黄 山茱萸 山萸肉 牡丹皮 丹皮 丹参 三七 红花 桃仁
黄连 黄芩 黄柏 栀子 知母 石膏 天花粉 葛根 麦冬 天冬 玉竹 黄精 石斛 沙参 北沙参 南沙参 百合
五味子 枸杞子 女贞子 墨旱莲 菟丝子 桑椹 覆盆子 金樱子 芡实 怀山药 鸡内金 神曲 麦芽 山楂
陈皮 青皮 枳实 枳壳 厚朴 半夏 法半夏 姜半夏 竹茹 干姜 炮姜 桂枝 肉桂 附子 制附子
柴胡 升麻 防风 荆芥 羌活 独活 秦艽 威灵仙 桑枝 桑叶 菊花 薄荷 蝉蜕 牛蒡子 连翘 金银花 蒲公英
板蓝根 大青叶 鱼腥草 败酱草 白花蛇舌草 夏枯草 决明子 车前子 车前草 木通 通草 滑石 萹蓄 瞿麦
茵陈 金钱草 虎杖 大黄 芒硝 火麻仁 郁李仁 杏仁 苦杏仁 桔梗 紫菀 款冬花 百部 川贝母 浙贝母 贝母
瓜蒌 全瓜蒌 薤白 远志 酸枣仁 柏子仁 夜交藤 首乌藤 合欢皮 龙骨 牡蛎 珍珠母 磁石 天麻 钩藤 石决明
地龙 全蝎 蜈蚣 僵蚕 水蛭 土鳖虫 鸡血藤 牛膝 怀牛膝 川牛膝 杜仲 续断 桑寄生 狗脊 骨碎补 补骨脂
淫羊藿 仙茅 巴戟天 肉苁蓉 锁阳 益智仁 乌药 小茴香 吴茱萸 木香 香附 郁金 延胡索 川楝子 佛手
砂仁 白豆蔻 豆蔻 草豆蔻 藿香 佩兰 苍耳子 辛夷 白芷 细辛 麻黄 紫苏 苏叶 紫苏叶 苏子 紫苏子
乌梅 五倍子 诃子 浮小麦 麻黄根 山茱萸肉 何首乌 制何首乌 阿胶 鹿角胶 龟甲 鳖甲 玄参 牛黄 冰片
麝香 苏合香 石菖蒲 益母草 泽兰 王不留行 莪术 三棱 乳香 没药 五灵脂 蒲黄 茜草 白茅根 侧柏叶
仙鹤草 艾叶 地榆 槐花 小蓟 大蓟 白及 荷叶 绞股蓝 桑白皮 地骨皮 青蒿 银柴胡 胡黄连 白薇
苦参 白鲜皮 地肤子 蛇床子 黄药子 海藻 昆布 荔枝核 橘核 鬼箭羽 翻白草 玉米须 冬瓜皮 赤小豆
""".split()
# 常用方剂与中成药(含糖尿病常用)。
_TCM_FORMULAS = """
六味地黄丸 知柏地黄丸 杞菊地黄丸 麦味地黄丸 金匮肾气丸 济生肾气丸 桂附地黄丸 左归丸 右归丸
玉泉丸 消渴丸 参芪降糖颗粒 津力达颗粒 天芪降糖胶囊 渴乐宁胶囊 金芪降糖片 降糖舒胶囊 糖脉康颗粒
芪蛭降糖胶囊 木丹颗粒 通心络胶囊 复方丹参滴丸 银杏叶片 血塞通 血栓通 丹参酮 脑心通胶囊
补中益气丸 补中益气汤 归脾丸 归脾汤 逍遥丸 逍遥散 加味逍遥丸 丹栀逍遥散 柴胡疏肝散 四逆散
四君子汤 六君子汤 香砂六君子汤 参苓白术散 理中丸 附子理中丸 四物汤 八珍汤 十全大补汤 当归补血汤
生脉饮 生脉散 玉女煎 白虎加人参汤 白虎汤 葛根芩连汤 黄连解毒汤 半夏泻心汤 大柴胡汤 小柴胡汤
血府逐瘀汤 补阳还五汤 桃红四物汤 二陈汤 温胆汤 黄连温胆汤 天麻钩藤饮 镇肝熄风汤 酸枣仁汤
天王补心丹 一贯煎 增液汤 沙参麦冬汤 益胃汤 竹叶石膏汤 五苓散 猪苓汤 真武汤 实脾饮 防己黄芪汤
玉屏风散 桂枝汤 麻黄汤 银翘散 桑菊饮 藿香正气散 藿香正气水 保和丸 平胃散 二妙丸 三妙丸 四妙丸
当归四逆汤 黄芪桂枝五物汤 独活寄生汤 身痛逐瘀汤 大补阴丸 二至丸 交泰丸 安宫牛黄丸 浓缩水丸
""".split()
# 西药(以内分泌、心血管、常见合并用药为主)。
_WESTERN = """
二甲双胍 盐酸二甲双胍 格列美脲 格列齐特 格列吡嗪 格列本脲 格列喹酮 瑞格列奈 那格列奈 阿卡波糖
伏格列波糖 米格列醇 吡格列酮 罗格列酮 西格列汀 沙格列汀 维格列汀 利格列汀 阿格列汀 达格列净
恩格列净 卡格列净 艾托格列净 利拉鲁肽 司美格鲁肽 度拉糖肽 艾塞那肽 利司那肽 贝那鲁肽 替尔泊肽
胰岛素 门冬胰岛素 赖脯胰岛素 谷赖胰岛素 甘精胰岛素 地特胰岛素 德谷胰岛素 精蛋白锌胰岛素
重组人胰岛素 生物合成人胰岛素 预混胰岛素 硝苯地平 氨氯地平 左旋氨氯地平 非洛地平 尼群地平
贝尼地平 厄贝沙坦 缬沙坦 氯沙坦 替米沙坦 坎地沙坦 奥美沙坦 沙库巴曲缬沙坦 依那普利 贝那普利
培哚普利 卡托普利 福辛普利 美托洛尔 比索洛尔 卡维地洛 阿替洛尔 氢氯噻嗪 吲达帕胺 呋塞米
螺内酯 托拉塞米 阿托伐他汀 瑞舒伐他汀 辛伐他汀 普伐他汀 匹伐他汀 依折麦布 非诺贝特 苯扎贝特
阿司匹林 氯吡格雷 替格瑞洛 华法林 利伐沙班 达比加群 硫酸氢氯吡格雷 甲钴胺 依帕司他 硫辛酸
α-硫辛酸 胰激肽原酶 羟苯磺酸钙 前列地尔 贝前列素钠 别嘌醇 非布司他 苯溴马隆 碳酸氢钠
左甲状腺素 甲巯咪唑 丙硫氧嘧啶 奥美拉唑 泮托拉唑 雷贝拉唑 埃索美拉唑 雷尼替丁 法莫替丁
多潘立酮 莫沙必利 二甲硅油 乳果糖 阿莫西林 头孢呋辛 左氧氟沙星 莫西沙星 阿奇霉素 布洛芬
对乙酰氨基酚 塞来昔布 加巴喷丁 普瑞巴林 碳酸钙 骨化三醇 维生素D 维生素B12 叶酸 硝酸甘油
单硝酸异山梨酯 曲美他嗪 地高辛 胺碘酮 坦索罗辛 非那雄胺 西地那非 他达拉非
""".split()
# 西药常带剂型后缀;一起摘出,展示时保留原文写法。
_WESTERN_FORM = r"(?:缓释片|控释片|肠溶片|分散片|片|缓释胶囊|肠溶胶囊|胶囊|注射液|注射剂|笔|颗粒)?"
class DrugMention(NamedTuple):
start: int
end: int
# 去掉剂型后缀的药名,用于速览去重;高亮范围仍覆盖原文中的完整写法。
name: str
kind: str
def _alternation(names: list[str]) -> str:
return "|".join(re.escape(name) for name in sorted(set(names), key=len, reverse=True))
# 单一正则、长词优先:中成药 > 西药 > 饮片,保证一个位置只被归入一类。
_DRUG_RE = re.compile(
rf"(?P<tcm_formula>{_alternation(_TCM_FORMULAS)})"
rf"|(?P<western>(?P<western_base>{_alternation(_WESTERN)}){_WESTERN_FORM})"
rf"|(?P<herb>{_alternation(_TCM_HERBS)})"
)
def find_drug_mentions(text: str) -> list[DrugMention]:
"""返回正文中每一处药名的位置与类别(不重叠、按出现顺序)。"""
mentions: list[DrugMention] = []
for match in _DRUG_RE.finditer(str(text or "")):
if match.group("western"):
mentions.append(DrugMention(match.start(), match.end(), match.group("western_base"), WESTERN))
else:
mentions.append(DrugMention(match.start(), match.end(), match.group(), TCM))
return mentions
def summarize_drugs(text: str) -> dict[str, list[str]]:
"""按类别去重汇总药名,保留首次出现的顺序。"""
summary: dict[str, list[str]] = {TCM: [], WESTERN: []}
for mention in find_drug_mentions(text):
names = summary[mention.kind]
if mention.name not in names:
names.append(mention.name)
return summary
@@ -1,86 +0,0 @@
"""Shared display semantics for recorded indicator states; no threshold inference."""
from __future__ import annotations
from typing import Any
ABNORMAL_COLOR = "#BD4B58"
NORMAL_COLOR = "#287B65"
UNKNOWN_COLOR = "#697386"
_ABNORMAL = frozenset(
{
"high",
"low",
"abnormal",
"warning",
"positive",
"alert",
"偏高",
"偏低",
"升高",
"降低",
"高",
"低",
"异常",
"阳性",
"警告",
"需关注",
"临界",
"超标",
"未达标",
"不达标",
"控制不佳",
"控制欠佳",
"不正常",
"非正常",
"未恢复正常",
}
)
_NORMAL = frozenset(
{
"normal",
"negative",
"正常",
"阴性",
"达标",
"已达标",
"控制良好",
"未见异常",
"无异常",
"未发现异常",
"没有异常",
"0",
}
)
def metric_state(value: Any) -> str:
"""Normalize only explicit source states; an unclassified number stays unknown."""
text = str(value).strip().casefold() if type(value) in (str, int) else ""
if text in _ABNORMAL:
return "abnormal"
if text in _NORMAL:
return "normal"
return "unknown"
def metric_color(value: Any) -> str:
return {"abnormal": ABNORMAL_COLOR, "normal": NORMAL_COLOR}.get(
metric_state(value), UNKNOWN_COLOR
)
def risk_color(value: Any) -> str:
return {
"high": ABNORMAL_COLOR,
"medium": ABNORMAL_COLOR,
"low": NORMAL_COLOR,
}.get(value if isinstance(value, str) else "", UNKNOWN_COLOR)
def combined_metric_state(values: list[Any]) -> str:
states = [metric_state(value) for value in values]
if "abnormal" in states:
return "abnormal"
return "normal" if states and all(state == "normal" for state in states) else "unknown"
@@ -1,418 +0,0 @@
"""Conservative, display-only emphasis for clinical report text.
Measurements are identified by their units or an explicit clinical label. Colors
come from matching recorded states or explicit local assertions, never numeric
thresholds. All source text remains literal HTML text.
"""
from __future__ import annotations
import re
import unicodedata
from collections.abc import Iterator, Sequence
from contextlib import contextmanager
from contextvars import ContextVar
from dataclasses import dataclass
from html import escape
from .ai_consult_drug_names import DRUG_STYLES, find_drug_mentions
from .ai_consult_metric_state import (
ABNORMAL_COLOR,
NORMAL_COLOR,
UNKNOWN_COLOR,
metric_state,
risk_color,
)
@dataclass(frozen=True)
class MetricTextState:
"""A source field, its displayed reading (including unit), and recorded state."""
label: str
value: str
status: str
_METRIC_STATES: ContextVar[tuple[MetricTextState, ...]] = ContextVar(
"metric_text_states", default=()
)
@contextmanager
def metric_text_context(states: Sequence[MetricTextState]) -> Iterator[None]:
"""Bind trusted states for synchronous rendering and restore the outer scope."""
token = _METRIC_STATES.set(tuple(states))
try:
yield
finally:
_METRIC_STATES.reset(token)
_NUMBER = r"[+\-−]?(?:\d+(?:\.\d+)?|\.\d+)"
_COMPARATOR = r"(?:(?:<=|>=|[<>≤≥≦≧≈=<>=]|小于|大于|不超过|不低于|不高于|低于|高于|约为|约)\s*)?"
_VALUE = rf"{_COMPARATOR}{_NUMBER}(?:\s*(?:[–—~~-\-]|至|到)\s*{_NUMBER})?"
_VALUE_START = r"(?<![A-Za-z0-9_.+\-−/])"
_VALUE_END = r"(?![A-Za-z0-9_.²³/]|\s*[–—~~-\-至到]\s*\d)"
_UNIT = (
r"(?:mL\s*/\s*min(?:\s*/\s*1\.73\s*m(?:²|2|\^2))?"
r"|(?:mmol|[μµu]mol)\s*/\s*L"
r"|mmol\s*/\s*mol"
r"|mg\s*/\s*(?:dL|mmol|g(?:Cr)?|L)"
r"|[μµu]g\s*/\s*(?:g|mg|L)"
r"|(?:ng|pg)\s*/\s*mL"
r"|(?:g|IU|U|mIU|mU)\s*/\s*L"
r"|g\s*/\s*dL"
r"|[μµu]IU\s*/\s*mL"
r"|kg\s*/\s*m(?:²|2|\^2)"
r"|mmHg|bpm|次\s*/\s*(?:分钟|分|min)"
r"|kg|cm|°\s*C|℃)"
)
_UNIT_END = r"(?![A-Za-z0-9_²³/])"
_PRESSURE_VALUE = rf"{_COMPARATOR}{_NUMBER}\s*[//]\s*{_NUMBER}\s*mmHg"
_UNIT_VALUE = rf"(?:{_PRESSURE_VALUE}|{_VALUE}\s*{_UNIT}){_UNIT_END}"
_UNIT_RE = re.compile(rf"{_VALUE_START}(?P<value>{_UNIT_VALUE})", re.IGNORECASE)
# A label is necessary when a number has no unit, or directly follows an ASCII
# label (a general numeric boundary intentionally rejects IDs such as abc123).
_LABEL_GAP = r"\s*[))]?\s*(?:(?:[::=]|为|约为|是|达到|下降至|降至|上升至|升至)\s*)?"
_LABEL_START = r"(?<![A-Za-z0-9_])"
_UNIT_LABELS = (
r"(?:fasting(?:[_ ]blood[_ ]sugar|[_ ](?:blood[_ ])?glucose)?|"
r"postprandial(?:[_ ]blood[_ ](?:sugar|glucose))?|"
r"FPG|FBG|PBG|PPG|TC|TG|LDL(?:-C)?|HDL(?:-C)?|UA|Scr|Cr|"
r"UACR|ACR|ALT|AST|SBP|DBP|BP|HR|eGFR|BMI|heart_rate|height|weight)"
)
_LABELED_UNIT_RE = re.compile(
rf"{_LABEL_START}{_UNIT_LABELS}{_LABEL_GAP}(?P<value>{_UNIT_VALUE})",
re.IGNORECASE,
)
_UNITLESS_RE = re.compile(
rf"{_LABEL_START}(?:BMI|体质指数|体质量指数|体重指数|eGFR|"
rf"估算肾小球滤过率|肾小球滤过率|heart_rate|心率){_LABEL_GAP}"
rf"(?P<value>{_VALUE}){_VALUE_END}",
re.IGNORECASE,
)
_HEIGHT_RE = re.compile(
rf"{_LABEL_START}(?:height|身高){_LABEL_GAP}"
rf"(?P<value>{_VALUE}\s*(?:cm|m|厘米|米)){_UNIT_END}",
re.IGNORECASE,
)
_PERCENT_LABEL = (
r"(?:HbA1c|glycated[_ ]h(?:a)?emoglobin|糖化血红蛋白(?:水平)?|"
r"SpO2|SaO2|血氧饱和度|血氧)"
)
_LABELED_PERCENT_RE = re.compile(
rf"{_LABEL_START}{_PERCENT_LABEL}{_LABEL_GAP}"
rf"(?P<value>{_VALUE}\s*[%%]){_VALUE_END}",
re.IGNORECASE,
)
_PERCENT_RE = re.compile(rf"{_VALUE_START}(?P<value>{_VALUE}\s*[%%]){_VALUE_END}")
_PERCENT_LABEL_RE = re.compile(rf"{_LABEL_START}{_PERCENT_LABEL}", re.IGNORECASE)
_UNRELATED_PERCENT_RE = re.compile(
r"占比|比例|概率|风险|增长|下降|降低|上升|提高|提升|改善|减轻|"
r"有效率|发生率|依从|完成率|百分比|报销|费用|患者|人群"
)
_CLAUSE_BOUNDARY_RE = re.compile(r"[,,。;;!!??\n]")
_SENTENCE_BOUNDARY_RE = re.compile(r"[。;;!!??\n]")
_REFERENCE_RE = re.compile(
r"目标|参考|理想|阈值|正常(?:值|范围)|\b(?:targets?|reference|ideal|thresholds?)\b",
re.IGNORECASE,
)
_CURRENT_RE = re.compile(
r"当前|现测|本次|实测|测得|检测结果|实际|目前|现值|\b(?:current|actual|measured)\b",
re.IGNORECASE,
)
_REFERENCE_SUFFIX_RE = re.compile(
r"^\s*[((](?:目标|参考|理想|阈值|正常)(?:值|范围)?[))]"
r"|^\s*\((?:target|reference|ideal|threshold)(?:\s*(?:value|range))?\)",
re.IGNORECASE,
)
_NORMAL_STATUS = (
r"(?:未见|未发现|没有|无)(?:其他)?(?:明显|显著)?异常"
r"|(?:基本|大致)?正常|(?:已|完全)?达标|控制良好"
r"|\b(?:normal|negative)\b"
)
_ABNORMAL_STATUS = (
r"(?:尚未完全|尚未|未完全|未能|不完全|未|不)达标"
r"|不正常|非正常|未恢复正常"
r"|(?:严重|明显|显著)?异常|控制不佳|控制欠佳"
r"|\b(?:not normal|abnormal|warning|high|low|positive|alert)\b"
)
_CAUTION_STATUS = r"(?:轻度|轻微|明显|显著|略)?(?:偏高|偏低|升高|降低)|临界|超标"
_STATUS_RE = re.compile(
rf"(?P<abnormal>{_ABNORMAL_STATUS})|(?P<normal>{_NORMAL_STATUS})"
rf"|(?P<caution>{_CAUTION_STATUS})",
re.IGNORECASE,
)
_RISK_STATUS_RE = re.compile(r"高风险|中风险|低风险")
_MISSING_RE = re.compile(
r"未记录|无记录|未检测|未测量|未检查|未提供|未填写|未录入|未获取|暂无数据|"
r"暂无|缺失|未知|待测|未测|未查|未做|无数据|"
r"\b(?:not recorded|not measured|not available|unrecorded|unknown|missing|N/A)\b",
re.IGNORECASE,
)
_NON_ASSERTIVE_RE = re.compile(
r"排除|排查|除外|警惕|预防|避免|防止|谨防|建议|可能|疑似|怀疑|"
r"是否|待排|待查|如果|假如|一旦|若|如|风险|倾向|有望|争取|力争|以期|"
r"应当|应该|应使|应将|应控制|应达到|应达标|需使|需将|需达到|以达到"
r"|\b(?:possible|possibly|may|might|should|if|risk|exclude|suspected)\b",
re.IGNORECASE,
)
_NEGATED_PREFIX_RE = re.compile(
r"(?:尚未|未见|未发现|未达到|未能达到|未能|不能|无法|难以|未|没有|无|不|非)"
r"(?:明显|显著|完全|充分)?$"
)
_MISSING_PLACEHOLDER_RE = re.compile(r"\s*(?:[—–--]+|/|null|none)\s*\Z", re.IGNORECASE)
# An alias identifies a source field, never a diagnosis. More specific aliases
# win over contained words, so 空腹血糖 cannot accidentally match generic 血糖.
_FIELD_ALIASES = (
("hba1c", r"HbA1c|glycated[_ ]h(?:a)?emoglobin|糖化血红蛋白(?:水平)?"),
("fasting", r"fasting(?:[_ ]blood[_ ]sugar|[_ ](?:blood[_ ])?glucose)?|FPG|FBG|空腹血糖|空腹"),
(
"postprandial",
r"postprandial(?:[_ ]blood[_ ](?:sugar|glucose))?|PBG|PPG|餐后(?:2|两|二)?(?:小时)?血糖|餐后",
),
("random_glucose", r"random[_ ](?:blood[_ ])?(?:sugar|glucose)|随机血糖"),
("glucose", r"blood[_ ](?:sugar|glucose)|glucose|血糖"),
("blood_pressure", r"blood[_ ]pressure|BP|血压"),
("systolic", r"systolic(?:[_ ](?:blood[_ ])?pressure)?|SBP|收缩压"),
("diastolic", r"diastolic(?:[_ ](?:blood[_ ])?pressure)?|DBP|舒张压"),
("bmi", r"BMI|体质指数|体质量指数|体重指数"),
("heart_rate", r"heart[_ ]rate|HR|心率"),
("height", r"height|身高"),
("weight", r"weight|体重"),
("ldl", r"LDL(?:[-_ ]C)?|低密度脂蛋白(?:胆固醇)?"),
("hdl", r"HDL(?:[-_ ]C)?|高密度脂蛋白(?:胆固醇)?"),
("cholesterol", r"TC|total[_ ]cholesterol|总胆固醇"),
("triglycerides", r"TG|triglycerides?|甘油三酯"),
("egfr", r"eGFR|估算肾小球滤过率|肾小球滤过率"),
("uacr", r"UACR|ACR|尿白蛋白(?:与)?肌酐比(?:值)?"),
("creatinine", r"Scr|Cr|creatinine|血(?:清)?肌酐|肌酐"),
("uric_acid", r"UA|uric[_ ]acid|尿酸"),
("alt", r"ALT|丙氨酸氨基转移酶|谷丙转氨酶"),
("ast", r"AST|天门冬氨酸氨基转移酶|谷草转氨酶"),
("spo2", r"SpO2|SaO2|血氧饱和度|血氧"),
("temperature", r"temperature|体温"),
("hemoglobin", r"h(?:a)?emoglobin|血红蛋白"),
)
_FIELD_PATTERNS = tuple(
(field, re.compile(rf"{_LABEL_START}(?:{aliases})(?![A-Za-z_])", re.IGNORECASE))
for field, aliases in _FIELD_ALIASES
)
_STANDALONE_VALUE_RE = re.compile(rf"\s*(?P<value>{_VALUE}(?:\s*[%%])?)\s*\Z")
def _display_key(value: str) -> str:
return re.sub(r"\s+", "", unicodedata.normalize("NFKC", value)).casefold()
def _field_mentions(text: str) -> list[tuple[int, int, str]]:
mentions = [
(match.start(), match.end(), field)
for field, pattern in _FIELD_PATTERNS
for match in pattern.finditer(text)
]
# Unknown source labels can still bind to an exact label in the rendered text.
for state in _METRIC_STATES.get():
label = state.label.strip()
if not label or any(pattern.search(label) for _, pattern in _FIELD_PATTERNS):
continue
pattern = re.compile(rf"{_LABEL_START}{re.escape(label)}(?![A-Za-z_])", re.IGNORECASE)
mentions.extend((m.start(), m.end(), _display_key(label)) for m in pattern.finditer(text))
mentions.sort(key=lambda item: (item[0], -(item[1] - item[0])))
selected: list[tuple[int, int, str]] = []
for mention in mentions:
if not selected or mention[0] >= selected[-1][1]:
selected.append(mention)
return selected
def _field_key(label: str) -> str:
mentions = _field_mentions(label)
return mentions[-1][2] if mentions else _display_key(label)
def _reading_field(text: str, start: int, metric_label: str) -> str:
_, clause_start = _clause(text, start)
mentions = _field_mentions(text[clause_start:start])
return mentions[-1][2] if mentions else _field_key(metric_label)
def _recorded_color(text: str, start: int, end: int, metric_label: str) -> str | None:
field = _reading_field(text, start, metric_label)
if not field:
return None
reading = _display_key(text[start:end])
states = {
metric_state(state.status)
for state in _METRIC_STATES.get()
if _field_key(state.label) == field and _display_key(state.value) == reading
}
if not states:
return None
if len(states) != 1:
return UNKNOWN_COLOR
return {"normal": NORMAL_COLOR, "abnormal": ABNORMAL_COLOR}.get(states.pop(), UNKNOWN_COLOR)
def _clause(text: str, position: int) -> tuple[str, int]:
start = 0
for boundary in _CLAUSE_BOUNDARY_RE.finditer(text, 0, position):
start = boundary.end()
boundary = _CLAUSE_BOUNDARY_RE.search(text, position)
end = boundary.start() if boundary else len(text)
return text[start:end], start
def _is_reference(text: str, start: int, end: int) -> bool:
clause, clause_start = _clause(text, start)
prefix = clause[: start - clause_start][-64:]
references = list(_REFERENCE_RE.finditer(prefix))
current = list(_CURRENT_RE.finditer(prefix))
if references and (not current or references[-1].start() > current[-1].start()):
return True
return bool(_REFERENCE_SUFFIX_RE.match(text[end:]))
def _is_reference_percent(text: str, start: int, end: int) -> bool:
if not _is_reference(text, start, end):
return False
sentence_start = 0
for boundary in _SENTENCE_BOUNDARY_RE.finditer(text, 0, start):
sentence_start = boundary.end()
prefix = text[max(sentence_start, start - 100) : start]
labels = list(_PERCENT_LABEL_RE.finditer(prefix))
if not labels:
return False
return not _UNRELATED_PERCENT_RE.search(prefix[labels[-1].end() :])
def _status_color(text: str, match: re.Match[str]) -> str | None:
clause, clause_start = _clause(text, match.start())
if _NON_ASSERTIVE_RE.search(clause):
return None
prefix = text[max(clause_start, match.start() - 12) : match.start()]
if _NEGATED_PREFIX_RE.search(prefix):
return None
if text[match.end() :].startswith(("率", "值", "范围", "标准", "目标", "阈值")):
return None
if match.lastgroup == "normal":
return NORMAL_COLOR
return ABNORMAL_COLOR
def _local_color(
text: str,
start: int,
end: int,
readings: Sequence[tuple[int, int]],
statuses: Sequence[tuple[re.Match[str], str]],
metric_label: str,
) -> str:
clause, clause_start = _clause(text, start)
field = _reading_field(text, start, metric_label)
colors: set[str] = set()
for status, color in statuses:
if not clause_start <= status.start() < clause_start + len(clause):
continue
left, right = (end, status.start()) if status.start() >= end else (status.end(), start)
if right < left or right - left > 32:
continue
if any(left <= other_start < right for other_start, _ in readings):
continue
# A status belonging to a new field in the same clause must not leak.
mentions = _field_mentions(text[left:right])
if any(other_field != field for _, _, other_field in mentions):
continue
colors.add(color)
return colors.pop() if len(colors) == 1 else UNKNOWN_COLOR
def metric_text_html(text: str, *, metric_label: str = "") -> str:
"""Return escaped, whitespace-preserving HTML with conservative emphasis.
Clinical values retain their original range, comparator, unit and spelling.
A bound state requires the same field alias and displayed reading, including
comparator, range and unit. Without a matching record only an asserted local
status can classify a reading. References and unclassified values stay gray.
Newlines follow Qt plain text; incoming HTML is always shown literally.
"""
text = text.replace("\r\n", "\n").replace("\r", "\n")
spans: list[tuple[int, int, str]] = []
candidates: set[tuple[int, int]] = set()
for pattern in (_UNIT_RE, _LABELED_UNIT_RE, _UNITLESS_RE, _HEIGHT_RE, _LABELED_PERCENT_RE):
for match in pattern.finditer(text):
candidates.add(match.span("value"))
for match in _PERCENT_RE.finditer(text):
start, end = match.span("value")
clause, clause_start = _clause(text, start)
hinted_percent = _field_key(metric_label) in {
"hba1c",
"spo2",
} and not _UNRELATED_PERCENT_RE.search(clause[: start - clause_start])
if hinted_percent or _is_reference_percent(text, start, end):
candidates.add((start, end))
if metric_label and (standalone := _STANDALONE_VALUE_RE.fullmatch(text)):
candidates.add(standalone.span("value"))
readings: list[tuple[int, int]] = []
for start, end in sorted(candidates, key=lambda span: (span[0], -span[1])):
if not readings or start >= readings[-1][1]:
readings.append((start, end))
statuses = [
(match, color)
for match in _STATUS_RE.finditer(text)
if (color := _status_color(text, match))
]
for start, end in readings:
if _is_reference(text, start, end) or _REFERENCE_RE.search(metric_label):
color = UNKNOWN_COLOR
else:
color = _recorded_color(text, start, end, metric_label)
if color is None:
color = _local_color(text, start, end, readings, statuses, metric_label)
spans.append((start, end, color))
spans.extend((match.start(), match.end(), color) for match, color in statuses)
for match in _RISK_STATUS_RE.finditer(text):
clause, clause_start = _clause(text, match.start())
prefix = text[max(clause_start, match.start() - 12) : match.start()]
if (
_NON_ASSERTIVE_RE.search(clause.replace("风险", ""))
or _NEGATED_PREFIX_RE.search(prefix)
or _REFERENCE_RE.search(clause)
):
continue
level = {"高风险": "high", "中风险": "medium", "低风险": "low"}[match.group()]
spans.append((match.start(), match.end(), risk_color(level)))
spans.extend(
(match.start(), match.end(), UNKNOWN_COLOR) for match in _MISSING_RE.finditer(text)
)
if metric_label and _MISSING_PLACEHOLDER_RE.fullmatch(text):
spans.append((0, len(text), UNKNOWN_COLOR))
# 药名高亮:中药绿、西药蓝,浅底加粗,让医生在正文里一眼看到用药。
styled = [(start, end, f"color: {color}; font-weight: 600;") for start, end, color in spans]
styled.extend(
(mention.start, mention.end, DRUG_STYLES[mention.kind])
for mention in find_drug_mentions(text)
)
# Prefer a full reading over a contained unitless value, then consume each
# original character once. Generated markup is never scanned by a regex.
styled.sort(key=lambda span: (span[0], -(span[1] - span[0])))
pieces = ['<span style="white-space: pre-wrap;">']
position = 0
for start, end, style in styled:
if start < position:
continue
pieces.append(escape(text[position:start]))
pieces.append(f'<span style="{style}">{escape(text[start:end])}</span>')
position = end
pieces.append(escape(text[position:]))
pieces.append("</span>")
return "".join(pieces).replace("\n", "<br>")
@@ -1,958 +0,0 @@
"""Content-selected native report visuals backed only by owned source records.
Generated prose selects topics; it never supplies numeric observations, dates,
reference limits, or risk levels. All render data is an immutable snapshot.
"""
from __future__ import annotations
import math
import re
from collections.abc import Mapping, Sequence
from dataclasses import dataclass, fields, is_dataclass
from datetime import datetime
from typing import Any
from PySide6.QtCore import QPointF, QRectF, QSize, Qt
from PySide6.QtGui import QColor, QMouseEvent, QPainter, QPaintEvent, QPen
from PySide6.QtWidgets import (
QAbstractItemView,
QFrame,
QHeaderView,
QLabel,
QPushButton,
QSizePolicy,
QTableWidget,
QTableWidgetItem,
QToolTip,
QVBoxLayout,
QWidget,
)
from .ai_consult_charts import (
GlucoseChartData,
GlucoseReportCard,
_draw_marker,
_recorded_at,
build_glucose_chart_data,
)
from .ai_consult_metric_state import UNKNOWN_COLOR, metric_color, risk_color
_NUMBER = r"(?:\d+(?:\.\d+)?|\.\d+)"
_RANGE = re.compile(rf"({_NUMBER})\s*[-–—~~至]\s*({_NUMBER})")
_TOPICS = {
"glucose": r"血糖|糖尿病|糖化|glucose|glyc[ae]m|hba1c|\ba1c\b",
"blood_pressure": r"血压|收缩压|舒张压|blood\s*pressure|hypertension|hypotension",
"lipids": r"血脂|胆固醇|甘油三酯|脂蛋白|lipid|cholesterol|triglyceride|\b[hl]dl\b",
"renal": r"肾|肌酐|尿素|尿酸|尿微量白蛋白|renal|kidney|creatinine|egfr|albumin",
"weight": r"体重|肥胖|减重|体质指数|weight|\bbmi\b|obesity",
"risk": r"风险|并发症|risk|complication",
"medication": r"用药|药物|处方|服药|药方|治疗方案|medication|prescription|\bdrug",
"activity": r"运动|活动|锻炼|exercise|activity|walking",
}
_OVERVIEW = re.compile(
r"综合|全面|总体|健康概览|病情总结|总结.*病情|病情.*总结|overall|comprehensive", re.I
)
_NEUTRAL = UNKNOWN_COLOR
_RISK_LABELS = {"low": "低风险", "medium": "中风险", "high": "高风险", "unknown": "未知"}
_STATUS_LABELS = {
"high": "偏高", "low": "偏低", "normal": "正常", "abnormal": "异常",
"warning": "需关注", "0": "正常", "unknown": "未标注",
}
def _status_label(item: VisualDatum) -> str:
if item.raw_value == "—":
return "未记录"
labels = _RISK_LABELS if item.raw_value == _RISK_LABELS.get(item.status) else _STATUS_LABELS
return labels.get(item.status.casefold(), item.status) or "未标注"
@dataclass(frozen=True, slots=True)
class VisualDatum:
label: str
raw_value: str
value: float | None = None
unit: str = ""
recorded_at: datetime | None = None
time_label: str = ""
series: str = ""
status: str = ""
color: str = _NEUTRAL
interval: tuple[float, float] | None = None
reference: tuple[float, float] | None = None
@property
def value_text(self) -> str:
return self.raw_value + (f" {self.unit}" if self.unit and self.raw_value != "—" else "")
@dataclass(frozen=True, slots=True)
class ReportVisual:
kind: str
title: str
items: tuple[VisualDatum, ...]
source: str
diagnosis_id: int
patient_id: int = 0
# Defaults are the units used by the existing diagnosis / reception fields.
# A declared source unit always takes precedence, without conversion.
_METRICS = (
("glucose", "空腹血糖", ("fasting_blood_sugar", "fasting_glucose"), "mmol/L"),
("glucose", "餐后血糖", ("postprandial_blood_sugar", "postprandial_glucose"), "mmol/L"),
("glucose", "糖化血红蛋白", ("glycated_hemoglobin", "hba1c", "glycosylated_hemoglobin"), "%"),
("blood_pressure", "收缩压", ("systolic_pressure", "systolic"), "mmHg"),
("blood_pressure", "舒张压", ("diastolic_pressure", "diastolic"), "mmHg"),
("lipids", "总胆固醇", ("total_cholesterol", "cholesterol"), "mmol/L"),
("lipids", "甘油三酯", ("triglycerides", "triglyceride"), "mmol/L"),
("lipids", "高密度脂蛋白", ("hdl_c", "hdl", "high_density_lipoprotein"), "mmol/L"),
("lipids", "低密度脂蛋白", ("ldl_c", "ldl", "low_density_lipoprotein"), "mmol/L"),
("renal", "尿微量白蛋白", ("urine_microalbumin", "microalbumin", "urinary_albumin"), "mg/L"),
("renal", "肌酐", ("creatinine", "serum_creatinine"), "μmol/L"),
("renal", "尿素氮", ("blood_urea_nitrogen", "bun"), "mmol/L"),
("renal", "尿酸", ("uric_acid",), "μmol/L"),
("renal", "估算肾小球滤过率", ("egfr",), "mL/min/1.73m²"),
("weight", "体重", ("weight",), "kg"),
("weight", "身高", ("height",), "cm"),
("weight", "BMI", ("bmi",), "kg/m²"),
)
def _mapping(value: Any) -> Mapping[str, Any]:
if isinstance(value, Mapping):
return value
if is_dataclass(value) and not isinstance(value, type):
result = {field.name: getattr(value, field.name) for field in fields(value)}
raw = result.pop("raw", None)
if isinstance(raw, Mapping):
# Preserve original ownership values rather than trusting DTO coercions.
result.update(raw)
return result
return {}
def _rows(value: Any) -> tuple[Any, ...]:
if isinstance(value, Sequence) and not isinstance(value, (str, bytes, bytearray)):
return tuple(value)
return ()
def _first(source: Mapping[str, Any], *keys: str) -> Any:
return next((source[key] for key in keys if source.get(key) not in (None, "")), None)
def _exact(value: Any, expected: int) -> bool:
return type(value) is int and type(expected) is int and expected > 0 and value == expected
def _patient_matches(source: Mapping[str, Any], expected: int) -> bool:
if "patient_id" not in source:
return True
owner = source["patient_id"]
return type(owner) is int and owner > 0 and (expected == 0 or owner == expected)
def _owned(source: Mapping[str, Any], diagnosis_id: int, patient_id: int) -> bool:
return _exact(source.get("diagnosis_id"), diagnosis_id) and _patient_matches(source, patient_id)
def _declared_owners_match(source: Mapping[str, Any], diagnosis_id: int, patient_id: int) -> bool:
return (
"diagnosis_id" not in source or _exact(source["diagnosis_id"], diagnosis_id)
) and _patient_matches(source, patient_id)
def _section(sections: Mapping[str, Any], key: str) -> Any:
section = _mapping(sections.get(key))
return None if section.get("error") else section.get("value")
def _numeric(value: Any, unit: str = "", *, allow_zero: bool = False) -> float | None:
if isinstance(value, str):
value = value.strip()
suffix = rf"(?:\s*{re.escape(unit)})?" if unit else ""
match = re.fullmatch(rf"({_NUMBER}){suffix}", value, re.I)
if match is None:
return None
value = match.group(1)
elif type(value) not in (int, float):
return None
try:
number = float(value)
except (ValueError, TypeError, OverflowError):
return None
# Zero is the unfilled spinbox sentinel for these existing clinical fields.
return number if math.isfinite(number) and (number > 0 or allow_zero and number == 0) else None
def _interval(value: Any, unit: str) -> tuple[float, float] | None:
if not isinstance(value, str):
return None
text = value.strip()
if unit and text.casefold().endswith(unit.casefold()):
text = text[: -len(unit)].strip()
match = _RANGE.fullmatch(text)
if match:
low, high = (
_numeric(match.group(1), allow_zero=True),
_numeric(match.group(2), allow_zero=True),
)
if low is not None and high is not None and low < high:
return low, high
return None
def _number_text(value: float) -> str:
return str(value).removesuffix(".0")
def _plain(value: Any) -> str:
return str(value).strip() if type(value) in (str, int, float) else ""
def _reference(
source: Mapping[str, Any], keys: tuple[str, ...], unit: str
) -> tuple[float, float] | None:
for key in keys:
value = source.get(f"{key}_reference_range")
if isinstance(value, Mapping):
ref_unit = value.get("unit", unit)
low, high = (
_numeric(value.get("low"), unit, allow_zero=True),
_numeric(value.get("high"), unit, allow_zero=True),
)
if ref_unit == unit and low is not None and high is not None and low < high:
return low, high
elif (interval := _interval(value, unit)) is not None:
return interval
low = _numeric(source.get(f"{key}_reference_low"), unit, allow_zero=True)
high = _numeric(source.get(f"{key}_reference_high"), unit, allow_zero=True)
if low is not None and high is not None and low < high:
return low, high
return None
def _snapshot_items(
detail: Mapping[str, Any],
topics: set[str],
diagnosis_id: int,
patient_id: int,
*,
glucose_trend: bool,
pressure_trend: bool,
) -> tuple[VisualDatum, ...]:
diagnosis = _mapping(detail.get("diagnosis"))
sources = [diagnosis]
for base in (diagnosis, detail):
for key in ("vitals", "lab_results", "labs"):
source = _mapping(base.get(key))
if source and _declared_owners_match(source, diagnosis_id, patient_id):
sources.append(source)
result = []
for topic, label, keys, default_unit in _METRICS:
if topic not in topics:
continue
if pressure_trend and topic == "blood_pressure":
continue
if glucose_trend and keys[0] in {"fasting_blood_sugar", "postprandial_blood_sugar"}:
continue
for source in sources:
raw = _first(source, *keys)
if raw is None:
continue
unit = _plain(_first(source, *(f"{key}_unit" for key in keys))) or default_unit
value, interval = _numeric(raw, unit), _interval(raw, unit)
if value is None and interval is None:
break
status = _plain(_first(source, *(f"{key}_status" for key in keys)))
# Reception also uses hdl_status / ldl_status for *_c aliases.
if not status and keys[0] in {"hdl_c", "ldl_c"}:
status = _plain(source.get(f"{keys[1]}_status"))
raw_text = _number_text(value) if value is not None else _plain(raw)
if interval and unit and raw_text.casefold().endswith(unit.casefold()):
raw_text = raw_text[: -len(unit)].strip()
result.append(
VisualDatum(
label,
raw_text,
value,
unit,
status=status,
color=metric_color(status),
interval=interval,
reference=_reference(source, keys, unit),
)
)
break
# The detail loader has already verified this patient's identity. Body
# measurements may live in patient rather than in the visit's diagnosis.
patient = _mapping(detail.get("patient"))
existing = {item.label for item in result}
if "weight" in topics and _patient_matches(patient, patient_id):
for _topic, label, keys, default_unit in _METRICS:
if _topic != "weight" or label in existing:
continue
unit = _plain(_first(patient, *(f"{key}_unit" for key in keys))) or default_unit
value = _numeric(_first(patient, *keys), unit)
if value is not None:
status = _plain(_first(patient, *(f"{key}_status" for key in keys)))
result.append(VisualDatum(
label, _number_text(value), value, unit, status=status,
color=metric_color(status),
))
return tuple(result)
def _tracking_visual(
tracking: Any,
*,
diagnosis_id: int,
patient_id: int,
activity: bool = False,
) -> ReportVisual | None:
source = _mapping(tracking)
if not _owned(source, diagnosis_id, patient_id):
return None
patient_id = patient_id or source.get("patient_id", 0)
items = []
definitions = (
((("duration",), "运动时长"),)
if activity
else (
(("systolic_pressure", "systolic"), "收缩压"),
(("diastolic_pressure", "diastolic"), "舒张压"),
)
)
unit = "分钟" if activity else "mmHg"
unit_keys = (
("duration_unit", "exercise_unit") if activity else ("pressure_unit", "blood_pressure_unit")
)
for raw in _rows(source.get("exercise_records" if activity else "blood_records")):
row = _mapping(raw)
if not _owned(row, diagnosis_id, patient_id) or (recorded := _recorded_at(row)) is None:
continue
declared_unit = _first(row, *unit_keys)
root_unit = _first(source, *unit_keys)
if any(value is not None and value != unit for value in (declared_unit, root_unit)):
continue
timestamp, has_time = recorded
time_label = (
timestamp.strftime("%Y-%m-%d %H:%M:%S" if timestamp.second else "%Y-%m-%d %H:%M")
if has_time
else timestamp.date().isoformat()
)
for keys, label in definitions:
value = _numeric(_first(row, *keys), unit)
status = _plain(_first(row, *(f"{key}_status" for key in keys)))
items.append(
VisualDatum(
label,
_number_text(value) if value is not None else "—",
value,
unit,
timestamp,
time_label,
keys[0],
status=status,
color=metric_color(status) if value is not None else UNKNOWN_COLOR,
)
)
if not any(item.value is not None for item in items):
return None
items.sort(key=lambda item: item.recorded_at or datetime.min)
title = "运动时长记录" if activity else "血压变化趋势"
return ReportVisual(
"exercise" if activity else "blood_pressure",
title,
tuple(items),
f"本诊单 #{diagnosis_id} 的已记录数据 · {unit};按实际记录日期排列。"
"红色异常、绿色正常、灰色未记录/未标注;状态以原始记录为准。",
diagnosis_id,
patient_id,
)
def _analysis_payload(raw: Any, diagnosis_id: int, patient_id: int) -> Mapping[str, Any]:
"""Unwrap one saved report, carrying its ownership through every envelope."""
current = _mapping(raw)
result: dict[str, Any] = {}
for _depth in range(5):
if not current or not _patient_matches(current, patient_id):
return {}
declared = current.get("diagnosis_id")
source_ids = current.get("source_diagnosis_ids", result.get("source_diagnosis_ids"))
# A patient report may cover several visits. Its explicit, exact source
# IDs can establish report ownership but never measurement ownership.
longitudinal = (
patient_id > 0
and _exact(current.get("patient_id", result.get("patient_id")), patient_id)
and diagnosis_id in _rows(source_ids)
and all(type(item) is int and item > 0 for item in _rows(source_ids))
)
if (
"diagnosis_id" in current
and not _exact(declared, diagnosis_id)
and not (longitudinal and type(declared) is int and declared > 0)
):
return {}
result.update(current)
if isinstance(current.get("report"), Mapping):
current = current["report"]
elif isinstance(current.get("latest_by_model"), Mapping):
latest = current["latest_by_model"]
current = next(
(
_mapping(latest.get(key))
for key in ("qwen", "openai")
if _mapping(latest.get(key))
),
{},
)
elif _rows(current.get("reports")):
current = _mapping(_rows(current["reports"])[0])
else:
break
source_ids = _rows(result.get("source_diagnosis_ids"))
owned = _exact(result.get("diagnosis_id"), diagnosis_id) or (
patient_id > 0
and _exact(result.get("patient_id"), patient_id)
and diagnosis_id in source_ids
and all(type(item) is int and item > 0 for item in source_ids)
)
return result if owned else {}
def _risk_visual(raw: Any, diagnosis_id: int, patient_id: int) -> ReportVisual | None:
analysis = _analysis_payload(raw, diagnosis_id, patient_id)
items = []
for raw_row in _rows(analysis.get("risk_assessment")):
row = _mapping(raw_row)
label, level = _plain(row.get("label")), row.get("level")
if not label or not _declared_owners_match(row, diagnosis_id, patient_id):
continue
if not isinstance(level, str) or level not in _RISK_LABELS:
continue
items.append(
VisualDatum(label, _RISK_LABELS[level], status=level, color=risk_color(level))
)
if not items:
return None
source_ids = _rows(analysis.get("source_diagnosis_ids"))
visits = "、".join(f"#{item}" for item in source_ids if type(item) is int and item > 0)
source = "AI 报告的定性风险标注 · 保留报告原始等级"
if visits:
source += f" · 报告来源诊单 {visits}"
return ReportVisual("risks", "风险分层", tuple(items), source, diagnosis_id, patient_id)
def _medication_visual(raw: Any, diagnosis_id: int, patient_id: int) -> ReportVisual | None:
if isinstance(raw, Mapping):
if not _owned(raw, diagnosis_id, patient_id):
return None
patient_id = patient_id or raw.get("patient_id", 0)
rows = _rows(_first(raw, "items", "records", "lists"))
else:
rows = _rows(raw)
items = []
for raw_row in rows:
row = _mapping(raw_row)
if not _owned(row, diagnosis_id, patient_id):
continue
name = _plain(_first(row, "prescription_name", "prescription_summary", "summary", "name"))
if not name:
names = [_plain(_mapping(herb).get("name")) for herb in _rows(row.get("herbs"))]
name = "、".join(value for value in names if value)
recorded = _recorded_at({"date": _first(row, "prescription_date", "create_time")})
status = _plain(_first(row, "status_text", "audit_status_text"))
if not status:
audit = row.get("audit_status")
status = (
{0: "待审核", 1: "已通过", 2: "已驳回"}.get(audit, "") if type(audit) is int else ""
)
if type(row.get("void_status")) is int and row["void_status"] == 1:
status = f"{status} · 已作废" if status else "已作废"
if not name or recorded is None or not status:
continue
timestamp, has_time = recorded
time_label = (
timestamp.isoformat(sep=" ", timespec="seconds" if timestamp.second else "minutes")
if has_time
else timestamp.date().isoformat()
)
items.append(
VisualDatum(name, status, recorded_at=timestamp, time_label=time_label, status=status)
)
if not items:
return None
items.sort(key=lambda item: item.recorded_at or datetime.min)
return ReportVisual(
"medications",
"处方记录时间线",
tuple(items),
f"本诊单 #{diagnosis_id} 的处方开具事件 · 日期、方名和状态来自原始处方。",
diagnosis_id,
patient_id,
)
def build_report_visuals(
prompt: str,
reply: str,
*,
sections: Mapping[str, Any],
diagnosis_id: int,
patient_id: int = 0,
) -> tuple[GlucoseChartData | ReportVisual, ...]:
"""Select only relevant, usable source visuals. Empty input makes no shell."""
if (
type(diagnosis_id) is not int
or diagnosis_id <= 0
or type(patient_id) is not int
or patient_id < 0
):
return ()
if not isinstance(sections, Mapping) or not _declared_owners_match(
sections, diagnosis_id, patient_id
):
return ()
detail = _mapping(_section(sections, "detail"))
if detail:
diagnosis = _mapping(detail.get("diagnosis"))
if (
not _exact(diagnosis.get("id"), diagnosis_id)
or not _declared_owners_match(diagnosis, diagnosis_id, patient_id)
or not _declared_owners_match(detail, diagnosis_id, patient_id)
):
return ()
patient = _mapping(detail.get("patient"))
patient_id = patient_id or diagnosis.get("patient_id", 0) or detail.get("patient_id", 0)
if "id" in patient and not _exact(patient["id"], patient_id or patient["id"]):
return ()
patient_id = patient_id or patient.get("id", 0)
if not all(_patient_matches(source, patient_id) for source in (detail, diagnosis, patient)):
return ()
text = f"{prompt}\n{reply}"
topics = (
set(_TOPICS)
if _OVERVIEW.search(text)
else {topic for topic, pattern in _TOPICS.items() if re.search(pattern, text, re.I)}
)
result: list[GlucoseChartData | ReportVisual] = []
tracking = _section(sections, "tracking")
if "glucose" in topics:
glucose = build_glucose_chart_data(
tracking, diagnosis_id=diagnosis_id, patient_id=patient_id
)
if glucose.available:
result.append(glucose)
pressure = (
_tracking_visual(tracking, diagnosis_id=diagnosis_id, patient_id=patient_id)
if "blood_pressure" in topics
else None
)
if pressure:
result.append(pressure)
metrics = _snapshot_items(
detail,
topics,
diagnosis_id,
patient_id,
glucose_trend=any(isinstance(item, GlucoseChartData) for item in result),
pressure_trend=pressure is not None,
)
if metrics:
result.append(
ReportVisual(
"metrics",
"相关指标快照",
metrics,
f"本诊单 #{diagnosis_id} 的病历记录 · 红色异常、绿色正常、灰色未记录/未标注;各指标独立展示。",
diagnosis_id,
patient_id,
)
)
if "risk" in topics and (
risk := _risk_visual(_section(sections, "analysis"), diagnosis_id, patient_id)
):
result.append(risk)
if "medication" in topics and (
medication := _medication_visual(
_section(sections, "prescriptions"), diagnosis_id, patient_id
)
):
result.append(medication)
if "activity" in topics and (
activity := _tracking_visual(
tracking, diagnosis_id=diagnosis_id, patient_id=patient_id, activity=True
)
):
result.append(activity)
return tuple(result)
class ReportPlot(QWidget):
"""Small native charts with exact record tooltips and accessible readouts."""
def __init__(self, data: ReportVisual, parent: QWidget | None = None) -> None:
super().__init__(parent)
self.data = data
self.setObjectName("AiConsultReportPlot")
self.setMouseTracking(True)
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
self.setMinimumWidth(0)
self.setFixedHeight(214 if self._trend else len(data.items) * self._row_height)
self.setAccessibleName(data.title)
legend = "红色异常、绿色正常、灰色未记录/未标注。"
if data.kind == "blood_pressure":
legend += "收缩压实线圆点,舒张压虚线方点。"
self.setAccessibleDescription(legend + ";".join(self._readout(item) for item in data.items))
@property
def _trend(self) -> bool:
return self.data.kind in {"blood_pressure", "exercise"}
@property
def _row_height(self) -> int:
return 88 if self.data.kind == "metrics" else 78
@property
def _columns(self) -> int:
return 2 if self.data.kind == "metrics" and self.width() >= 520 else 1
def resizeEvent(self, event: Any) -> None: # noqa: N802
super().resizeEvent(event)
if self.data.kind == "metrics":
rows = math.ceil(len(self.data.items) / self._columns)
height = rows * self._row_height
if self.height() != height:
self.setFixedHeight(height)
def sizeHint(self) -> QSize: # noqa: N802
return QSize(480, self.height())
def minimumSizeHint(self) -> QSize: # noqa: N802
return QSize(0, self.height())
@staticmethod
def _readout(item: VisualDatum) -> str:
text = " · ".join(part for part in (item.time_label, item.label, item.value_text) if part)
if item.interval:
text += "(原始记录区间)"
label = _status_label(item)
text += f" · 状态 {label}"
if item.status and label != item.status:
text += f"(原始:{item.status})"
if item.reference:
text += f" · 记录参考区间 {_number_text(item.reference[0])}–{_number_text(item.reference[1])} {item.unit}"
return text
def _geometry(self) -> tuple[QRectF, datetime, float, float, float]:
items = [item for item in self.data.items if item.value is not None and item.recorded_at]
origin = min(item.recorded_at for item in items)
span = (max(item.recorded_at for item in items) - origin).total_seconds()
low, high = min(item.value for item in items), max(item.value for item in items)
# Normalize first to keep finite, even for malformed but finite huge inputs.
scale = max(high, 1.0)
low, high = low / scale, high / scale
pad = max((high - low) * 0.18, 0.05)
upper = (high + pad) * scale
return (
QRectF(self.rect()).adjusted(43, 33, -12, -35),
origin,
span,
max(0, low - pad) * scale,
upper if math.isfinite(upper) else high * scale,
)
def _position(
self, item: VisualDatum,
geometry: tuple[QRectF, datetime, float, float, float] | None = None,
) -> QPointF:
plot, origin, span, low, high = geometry if geometry is not None else self._geometry()
x = (
plot.left() + plot.width() * (item.recorded_at - origin).total_seconds() / span
if span
else plot.center().x()
)
scale = max(high, 1.0)
y = plot.bottom() - plot.height() * (
(item.value / scale - low / scale) / (high / scale - low / scale)
)
return QPointF(x, y)
def _point_tooltip(self, position: QPointF) -> str:
if self._trend:
geometry = self._geometry()
return "\n\n".join(
self._readout(item)
for item in self.data.items
if item.value is not None
and (self._position(item, geometry) - position).manhattanLength() < 12
)
column_width = (self.width() + 24) / self._columns
column = min(self._columns - 1, max(0, int(position.x() // column_width)))
index = int(position.y() // self._row_height) * self._columns + column
return self._readout(self.data.items[index]) if 0 <= index < len(self.data.items) else ""
def mouseMoveEvent(self, event: QMouseEvent) -> None: # noqa: N802
if tip := self._point_tooltip(event.position()):
QToolTip.showText(event.globalPosition().toPoint(), tip, self)
else:
QToolTip.hideText()
super().mouseMoveEvent(event)
def leaveEvent(self, event: Any) -> None: # noqa: N802
QToolTip.hideText()
super().leaveEvent(event)
def _text(
self, painter: QPainter, rect: QRectF, text: str, *, color: str = _NEUTRAL, size: int = 12
) -> None:
font = painter.font()
font.setPixelSize(size)
painter.setFont(font)
painter.setPen(QColor(color))
painter.drawText(
rect,
Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft,
painter.fontMetrics().elidedText(
text, Qt.TextElideMode.ElideRight, max(0, int(rect.width()))
),
)
def _paint_trend(self, painter: QPainter) -> None:
geometry = self._geometry()
plot, origin, span, low, high = geometry
self._text(painter, QRectF(0, 0, 65, 22), self.data.items[0].unit, size=11)
series = tuple(dict.fromkeys(item.series for item in self.data.items))
for index, key in enumerate(series):
item = next(item for item in self.data.items if item.series == key)
style = Qt.PenStyle.DashLine if key == "diastolic_pressure" else Qt.PenStyle.SolidLine
left = 65 + index * 100
painter.setPen(QPen(QColor(_NEUTRAL), 2, style))
painter.setBrush(QColor(_NEUTRAL))
painter.drawLine(QPointF(left, 11), QPointF(left + 17, 11))
_draw_marker(painter, QPointF(left + 8, 11), key)
self._text(
painter,
QRectF(left + 23, 0, 76, 22),
item.label,
size=11,
)
for tick in range(4):
y = plot.bottom() - plot.height() * tick / 3
painter.setPen(QPen(QColor("#EDEDEE"), 1))
painter.drawLine(QPointF(plot.left(), y), QPointF(plot.right(), y))
self._text(
painter,
QRectF(0, y - 9, 40, 18),
f"{low * (1 - tick / 3) + high * tick / 3:.0f}",
size=11,
)
for key in series:
previous = None
style = Qt.PenStyle.DashLine if key == "diastolic_pressure" else Qt.PenStyle.SolidLine
for item in self.data.items:
if item.series != key:
continue
if item.value is None:
previous = None
continue
point = self._position(item, geometry)
if previous is not None:
painter.setPen(QPen(QColor(_NEUTRAL), 2, style))
painter.drawLine(previous, point)
previous = point
for item in self.data.items:
if item.series == key and item.value is not None:
painter.setPen(QPen(QColor(item.color), 2))
painter.setBrush(QColor(item.color))
_draw_marker(painter, self._position(item, geometry), key)
self._text(
painter,
QRectF(plot.left(), plot.bottom() + 8, 104, 20),
origin.date().isoformat(),
size=11,
)
if span:
last = max(item.recorded_at for item in self.data.items if item.value is not None)
self._text(
painter,
QRectF(plot.right() - 91, plot.bottom() + 8, 100, 20),
last.date().isoformat(),
size=11,
)
def _paint_snapshot(
self, painter: QPainter, item: VisualDatum, top: int, width: float
) -> None:
self._text(painter, QRectF(0, top, width, 21), item.label, color="#1A1C1F", size=12)
self._text(
painter, QRectF(0, top + 22, width, 24), item.value_text, color=item.color, size=17
)
note = f"记录状态:{_status_label(item)}" if item.status else "记录未提供状态"
if item.interval:
note = f"原始记录区间 · {note}"
if item.reference:
low, high = item.reference
values = [low, high, *(item.interval or (item.value,))]
scale = max(value for value in values if value is not None)
lower, upper = (
min(value / scale for value in values if value is not None),
max(value / scale for value in values if value is not None),
)
span = upper - lower
def x(value: float) -> float:
return 8 + (width - 16) * ((value / scale - lower) / span if span else 0.5)
painter.setPen(QPen(QColor("#E4E7EC"), 5))
painter.drawLine(QPointF(8, top + 54), QPointF(width - 8, top + 54))
painter.setPen(QPen(QColor(_NEUTRAL), 5))
painter.drawLine(QPointF(x(low), top + 54), QPointF(x(high), top + 54))
painter.setPen(QPen(QColor(item.color), 2))
painter.setBrush(QColor(item.color))
if item.interval:
painter.drawLine(
QPointF(x(item.interval[0]), top + 54), QPointF(x(item.interval[1]), top + 54)
)
else:
painter.drawEllipse(QPointF(x(item.value), top + 54), 4, 4)
note = f"{note} · 参考 {low:g}–{high:g} {item.unit}"
self._text(painter, QRectF(0, top + 65, width, 17), note, color=item.color, size=10)
else:
self._text(painter, QRectF(0, top + 53, width, 22), note, color=item.color, size=11)
def paintEvent(self, event: QPaintEvent) -> None: # noqa: N802
super().paintEvent(event)
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
if self._trend:
self._paint_trend(painter)
else:
for index, item in enumerate(self.data.items):
top = index * self._row_height
if self.data.kind == "metrics":
width = (self.width() - 24 * (self._columns - 1)) / self._columns
painter.save()
painter.translate((index % self._columns) * (width + 24), 0)
self._paint_snapshot(painter, item, (index // self._columns) * self._row_height, width)
painter.restore()
elif self.data.kind == "risks":
self._text(
painter, QRectF(0, top, self.width(), 23), item.label, color="#1A1C1F"
)
width = (self.width() - 9) / 4
for offset, (level, label) in enumerate(_RISK_LABELS.items()):
rect = QRectF(offset * (width + 3), top + 29, width, 28)
active = level == item.status
painter.setPen(Qt.PenStyle.NoPen)
painter.setBrush(QColor(item.color if active else "#F1F3F6"))
painter.drawRoundedRect(rect, 4, 4)
self._text(
painter,
rect.adjusted(6, 0, -3, 0),
label,
color="#FFFFFF" if active else _NEUTRAL,
size=11,
)
else:
painter.setPen(QPen(QColor("#E0E4EF"), 1))
painter.drawLine(QPointF(6, top + 10), QPointF(6, top + 78))
painter.setBrush(QColor(_NEUTRAL))
painter.drawEllipse(QPointF(6, top + 12), 4, 4)
for line, text in enumerate((item.time_label, item.label, item.raw_value)):
self._text(
painter,
QRectF(21, top + line * 22, self.width() - 21, 22),
text,
color="#1A1C1F" if line == 1 else _NEUTRAL,
)
painter.end()
class ReportVisualCard(QFrame):
def __init__(self, data: ReportVisual, parent: QWidget | None = None) -> None:
super().__init__(parent)
self.data = data
self.setObjectName("AiConsultReportVisual")
self.setProperty("visualKind", data.kind)
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Maximum)
self.setMinimumWidth(0)
self.setStyleSheet("""
QFrame#AiConsultReportVisual {background:#FFFFFF; border:1px solid #EDEDEE; border-radius:10px;}
QFrame#AiConsultReportVisual QLabel {border:0; background:transparent; color:#697386; font-size:12px;}
QFrame#AiConsultReportVisual QLabel#AiConsultReportVisualTitle {color:#1A1C1F; font-size:15px; font-weight:600;}
QFrame#AiConsultReportVisual QPushButton {color:#4F63D9; background:#F7F8FC; border:1px solid #E4E7F4; border-radius:6px; padding:5px 9px; font-size:12px;}
QFrame#AiConsultReportVisual QTableWidget {background:#FFFFFF; color:#1A1C1F; border:1px solid #EDEDEE; font-size:12px;}
QFrame#AiConsultReportVisual QHeaderView::section {background:#F7F8FC; color:#697386; border:0; padding:5px;}
""")
root = QVBoxLayout(self)
root.setContentsMargins(14, 12, 14, 12)
root.setSpacing(8)
title = QLabel(data.title, self)
title.setObjectName("AiConsultReportVisualTitle")
title.setWordWrap(True)
root.addWidget(title)
self.chart = ReportPlot(data, self)
root.addWidget(self.chart)
self.toggle_button = QPushButton("查看原始记录", self)
self.toggle_button.setCheckable(True)
root.addWidget(self.toggle_button, alignment=Qt.AlignmentFlag.AlignLeft)
self.table = QTableWidget(len(data.items), 5, self)
self.table.setObjectName("AiConsultReportVisualTable")
self.table.setHorizontalHeaderLabels(
["记录日期 / 时间", "指标 / 方名", "记录值", "状态", "记录参考区间"]
)
self.table.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
self.table.setWordWrap(True)
self.table.setMinimumWidth(0)
self.table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.ResizeToContents)
self.table.verticalHeader().hide()
self.table.setMaximumHeight(230)
for index, item in enumerate(data.items):
reference = (
f"{item.reference[0]:g}–{item.reference[1]:g} {item.unit}"
if item.reference
else "—"
)
values = (
item.time_label or "未提供日期",
item.label,
item.value_text + ("(原始记录区间)" if item.interval else ""),
_status_label(item) or "未提供",
reference,
)
for column, value in enumerate(values):
cell = QTableWidgetItem(value)
cell.setToolTip(ReportPlot._readout(item))
if value in {"—", "未提供", "未提供日期", "未记录", "未标注"}:
cell.setForeground(QColor(_NEUTRAL))
elif column in {2, 3}:
cell.setForeground(QColor(item.color))
self.table.setItem(index, column, cell)
self.table.hide()
root.addWidget(self.table)
self.toggle_button.toggled.connect(self._toggle_table)
source = QLabel(data.source, self)
source.setObjectName("AiConsultReportVisualSource")
source.setTextFormat(Qt.TextFormat.PlainText)
source.setWordWrap(True)
root.addWidget(source)
def _toggle_table(self, visible: bool) -> None:
self.table.setVisible(visible)
self.toggle_button.setText("收起原始记录" if visible else "查看原始记录")
def create_report_visual(
data: GlucoseChartData | ReportVisual,
parent: QWidget | None = None,
) -> QWidget:
return (
GlucoseReportCard(data, parent)
if isinstance(data, GlucoseChartData)
else ReportVisualCard(data, parent)
)
@@ -43,7 +43,6 @@ from doctor_workstation.services.app_update import (
validate_installer_download_policy,
validate_windows_installer,
)
from doctor_workstation.ui.design_system import clinical_stylesheet
from doctor_workstation.ui.widgets import friendly_error, show_toast
LOGGER = logging.getLogger(__name__)
@@ -130,11 +129,11 @@ class AppUpdateDialog(QDialog):
self.badge = QLabel("必须更新后才能继续使用" if offer.force else "发现新版本")
self.badge.setObjectName("UpdateBadge")
self.badge.setStyleSheet(clinical_stylesheet(
self.badge.setStyleSheet(
"color:#A9691D;background:#FFF5E6;border-radius:8px;padding:4px 10px;font-weight:600;"
if offer.force
else "color:#4F63D9;background:#EEF1FA;border-radius:8px;padding:4px 10px;font-weight:600;"
))
)
root.addWidget(self.badge, 0, Qt.AlignmentFlag.AlignLeft)
self.headline = QLabel(title or "医生工作站有新版本")
@@ -147,7 +146,7 @@ class AppUpdateDialog(QDialog):
latest = offer.latest_version or "新版本"
self.version_label = QLabel(f"当前版本 {current} → 最新版本 {latest}")
self.version_label.setObjectName("UpdateVersionLabel")
self.version_label.setStyleSheet(clinical_stylesheet("color:$ds_muted;"))
self.version_label.setStyleSheet("color:#606163;")
root.addWidget(self.version_label)
self.notes = QTextEdit()
@@ -161,7 +160,7 @@ class AppUpdateDialog(QDialog):
self.status_label = QLabel("")
self.status_label.setObjectName("UpdateStatus")
self.status_label.setWordWrap(True)
self.status_label.setStyleSheet(clinical_stylesheet("color:$ds_heading;"))
self.status_label.setStyleSheet("color:#1A1C1F;")
self.status_label.hide()
root.addWidget(self.status_label)
@@ -176,7 +175,7 @@ class AppUpdateDialog(QDialog):
self.progress_text = QLabel("")
self.progress_text.setObjectName("UpdateProgressText")
self.progress_text.setStyleSheet(clinical_stylesheet("color:$ds_muted;font-size:12px;"))
self.progress_text.setStyleSheet("color:#606163;font-size:12px;")
self.progress_text.hide()
root.addWidget(self.progress_text)
@@ -226,7 +225,7 @@ class AppUpdateDialog(QDialog):
def show_download_progress(self, received: int, total: int) -> None:
self.progress.show()
self.progress_text.show()
self.status_label.setStyleSheet(clinical_stylesheet("color:$ds_heading;"))
self.status_label.setStyleSheet("color:#1A1C1F;")
self.status_label.setText("正在下载安装包…")
self.status_label.show()
if total > 0:
@@ -238,7 +237,7 @@ class AppUpdateDialog(QDialog):
self.progress_text.setText(_format_bytes(received))
def show_status(self, message: str, *, determinate: bool = False) -> None:
self.status_label.setStyleSheet(clinical_stylesheet("color:$ds_heading;"))
self.status_label.setStyleSheet("color:#1A1C1F;")
self.status_label.setText(message)
self.status_label.show()
self.progress.show()
@@ -252,7 +251,7 @@ class AppUpdateDialog(QDialog):
def show_error(self, message: str) -> None:
self._busy = False
self.status_label.setText(message)
self.status_label.setStyleSheet(clinical_stylesheet("color:$ds_danger;"))
self.status_label.setStyleSheet("color:#BE4B58;")
self.status_label.show()
self.progress.hide()
self.progress_text.hide()
@@ -2,26 +2,13 @@
from __future__ import annotations
import mimetypes
import re
import sqlite3
from collections.abc import Mapping, Sequence
from contextlib import suppress
from pathlib import Path
from typing import Any
from PySide6.QtCore import (
QDate,
QDateTime,
QEvent,
QObject,
QPoint,
QRect,
Qt,
QTimer,
QUrl,
Signal,
)
from PySide6.QtCore import QDate, QDateTime, QEvent, QPoint, QRect, Qt, QTimer, QUrl, Signal
from PySide6.QtGui import QDesktopServices
from PySide6.QtWidgets import (
QAbstractItemView,
@@ -35,7 +22,6 @@ from PySide6.QtWidgets import (
QLabel,
QMessageBox,
QPlainTextEdit,
QProgressBar,
QPushButton,
QScrollArea,
QSizePolicy,
@@ -48,8 +34,6 @@ from PySide6.QtWidgets import (
)
from ...core.appointment_modes import appointment_type_description, appointment_type_value
from ...core.transcript_text import simplified_transcript
from ..design_system import clinical_stylesheet
from ..diagnosis_drawer import (
DIAGNOSIS_QSS,
CaseGrid,
@@ -99,14 +83,6 @@ from .issued_prescription_ai import can_open_issued_ai, present_issued_prescript
from .local_audio_queue import LocalAudioQueueDialog
from .prescription_ai import can_open_diagnosis_ai_report, present_diagnosis_ai_report
class _UploadProgressRelay(QObject):
"""把后台线程中的分片上传进度转回界面线程(信号跨线程自动排队)。"""
# 用 object 传字节数:Qt 的 int 是 32 位,超过 2 GB 的视频会溢出。
progressed = Signal(object, object)
_PHONE_PERMISSION = "tcm.diagnosis/phonePlain"
_PATIENT_ORDERS_PERMISSION = "tcm.diagnosis/patientOrders"
_ORDER_DETAIL_PERMISSION = "tcm.prescriptionOrder/detail"
@@ -169,6 +145,7 @@ _DIAGNOSIS_FIELDS = (
("脂肪肝程度", "fatty_liver_degree", "脂肪肝程度"),
("舌象", "tongue", "舌质、舌苔等观察"),
("舌苔", "tongue_coating", "舌苔记录"),
("脉象", "pulse", "脉象记录"),
("临床诊断", "clinical_diagnosis", "填写临床诊断"),
("治则", "treatment_principle", "治疗原则"),
("处方", "prescription", "处方摘要"),
@@ -740,21 +717,19 @@ class OrderDetailDrawer(QDialog):
QTimer.singleShot(0, self.sync_to_owner)
def sync_to_owner(self) -> None:
owner = self._owner
if owner is not None:
# The scrim is an overlay of its owner, including when that owner is
# a standalone diagnosis window rather than the workstation itself.
origin = owner.mapToGlobal(QPoint(0, 0))
self.setGeometry(QRect(origin, owner.size()))
self.drawer_panel.setFixedWidth(max(1, round(owner.width() * self.drawer_ratio)))
return
target = main_window_target_rect(self)
if target is not None:
self.setGeometry(target)
self.drawer_panel.setFixedWidth(max(1, round(target.width() * self.drawer_ratio)))
return
self.resize(1152, 720)
width = round(self.width() * self.drawer_ratio)
owner = self._owner
if owner is None:
self.resize(1152, 720)
width = round(self.width() * self.drawer_ratio)
else:
origin = owner.mapToGlobal(QPoint(0, 0))
self.setGeometry(origin.x(), origin.y(), owner.width(), owner.height())
width = round(owner.width() * self.drawer_ratio)
self.drawer_panel.setFixedWidth(max(1, width))
def eventFilter(self, watched: object, event: QEvent) -> bool: # noqa: N802 - Qt API
@@ -1536,38 +1511,9 @@ class DiagnosisDialog(QDialog):
)
toolbar.addWidget(self.video_upload_button)
layout.addLayout(toolbar)
layout.addWidget(self._build_video_upload_progress())
layout.addWidget(self._new_table("video", "DiagnosisVideoTable"), 1)
return page
def _build_video_upload_progress(self) -> QFrame:
"""上传本地回放时的进度条:按分片实时更新,医生能看到上传在进行、进行到哪。"""
frame = QFrame()
frame.setObjectName("DiagnosisVideoUploadProgress")
frame.setStyleSheet(clinical_stylesheet(
"QFrame#DiagnosisVideoUploadProgress { background-color: #EEF1FA;"
" border: 1px solid $ds_line_strong; border-radius: $ds_radius_control; }"
"QFrame#DiagnosisVideoUploadProgress QLabel { color: $ds_accent_hover; background: transparent;"
" font-size: 13px; font-weight: 500; }"
"QFrame#DiagnosisVideoUploadProgress QProgressBar { background-color: #FFFFFF;"
" border: 0; border-radius: 4px; min-height: 8px; max-height: 8px; }"
"QFrame#DiagnosisVideoUploadProgress QProgressBar::chunk { background-color: #4F63D9;"
" border-radius: 4px; }"
))
row = QVBoxLayout(frame)
row.setContentsMargins(12, 8, 12, 10)
row.setSpacing(6)
self.video_upload_status = QLabel()
self.video_upload_status.setWordWrap(True)
row.addWidget(self.video_upload_status)
self.video_upload_bar = QProgressBar()
self.video_upload_bar.setRange(0, 1000)
self.video_upload_bar.setTextVisible(False)
row.addWidget(self.video_upload_bar)
frame.hide()
self.video_upload_frame = frame
return frame
def _build_orders_tab(self) -> QWidget:
page = QWidget()
page.setObjectName("DiagnosisTabOrders")
@@ -1896,17 +1842,11 @@ class DiagnosisDialog(QDialog):
def _sync_host_geometry(self) -> None:
if self._embedded:
return
owner = self._owner
if not self._standalone_readonly and owner is not None and owner is not self:
# Ordinary windows use the centered 85% rectangle. A drawer's
# translucent scrim must cover the complete live owner client area.
origin = owner.mapToGlobal(QPoint(0, 0))
self.setGeometry(QRect(origin, owner.size()))
return
target = main_window_target_rect(self)
if target is not None:
self.setGeometry(target)
return
owner = self._owner
if owner is None:
if self.width() < 760 or self.height() < 520:
self.resize(1024, 640)
@@ -1995,7 +1935,6 @@ class DiagnosisDialog(QDialog):
QEvent.Type.Resize,
QEvent.Type.Move,
QEvent.Type.Show,
QEvent.Type.WindowStateChange,
}:
self._sync_host_geometry()
self._update_drawer_geometry()
@@ -3331,6 +3270,8 @@ class DiagnosisDialog(QDialog):
),
"tongue": first_value(diagnosis, "tongue", "tongue_coating"),
"tongue_image": first_value(diagnosis, "tongue_image"),
"pulse": first_value(diagnosis, "pulse"),
"pulse_condition": first_value(diagnosis, "pulse_condition"),
"clinical_diagnosis": build_prescription_clinical_diagnosis(diagnosis, case_record),
"doctor_name": first_value(
appointment, "doctor_name", default=first_value(diagnosis, "doctor_name")
@@ -3376,15 +3317,6 @@ class DiagnosisDialog(QDialog):
)
if not path:
return
# 明确按视频上报类型;默认的 audio/webm 会让 .webm 视频被服务端当成本机录音。
mime_type = mimetypes.guess_type(path)[0] or ""
if not mime_type.startswith("video/"):
mime_type = "video/mp4"
file_name = Path(path).name
relay = _UploadProgressRelay(self)
relay.progressed.connect(lambda sent, total: self._video_upload_progressed(file_name, sent, total))
self._video_upload_relay = relay
self._video_upload_progressed(file_name, 0, 0)
self._run_media_mutation(
lambda: invoke(
self.repository,
@@ -3392,47 +3324,13 @@ class DiagnosisDialog(QDialog):
path=path,
diagnosis_id=self._diagnosis_id,
call_record_id=call_record_id,
mime_type=mime_type,
on_progress=relay.progressed.emit,
),
"视频回放已追加到指定通话记录。"
if call_record_id is not None
else "视频回放已上传并创建通话记录。",
"video",
on_finished=lambda: self._video_upload_finished(relay),
)
def _video_upload_progressed(self, file_name: str, sent: int, total: int) -> None:
self.video_upload_frame.show()
self.video_upload_button.setEnabled(False)
if total <= 0:
self.video_upload_bar.setRange(0, 0) # 未拿到大小前显示滚动条
self.video_upload_status.setText(f"正在准备上传「{file_name}」…")
self.video_upload_button.setText("上传中…")
return
self.video_upload_bar.setRange(0, 1000)
ratio = min(1.0, max(0.0, sent / total))
self.video_upload_bar.setValue(int(ratio * 1000))
percent = int(ratio * 100)
mb = 1024 * 1024
if sent >= total:
text = f"「{file_name}」已上传完成({total / mb:.1f} MB),正在生成通话记录…"
else:
text = f"正在上传「{file_name}」 {percent}%({sent / mb:.1f} / {total / mb:.1f} MB),请勿关闭窗口"
self.video_upload_status.setText(text)
self.video_upload_button.setText(f"上传中 {percent}%")
self._show_message(text, "info")
def _video_upload_finished(self, relay: QObject) -> None:
if getattr(self, "_video_upload_relay", None) is not relay:
return
self._video_upload_relay = None
self.video_upload_frame.hide()
self.video_upload_bar.setRange(0, 1000)
self.video_upload_bar.setValue(0)
self.video_upload_button.setText("上传本地回放")
self.video_upload_button.setEnabled(True)
def _open_local_audio_queue(self) -> None:
if self._diagnosis_id <= 0 or not self._can_video_upload:
self._show_message("当前账号无本机录音上传权限或接口不可用。", "warning")
@@ -3532,14 +3430,7 @@ class DiagnosisDialog(QDialog):
"chat",
)
def _run_media_mutation(
self,
operation: Any,
success_text: str,
reload_key: str,
*,
on_finished: Any = None,
) -> None:
def _run_media_mutation(self, operation: Any, success_text: str, reload_key: str) -> None:
self._media_generation += 1
generation = self._media_generation
diagnosis_id = self._diagnosis_id
@@ -3550,7 +3441,6 @@ class DiagnosisDialog(QDialog):
success_text, reload_key, diagnosis_id, generation
),
on_error=lambda error: self._mutation_error(error, diagnosis_id, generation, "media"),
on_finished=on_finished,
)
def _media_mutation_success(
@@ -4034,8 +3924,7 @@ class DiagnosisDialog(QDialog):
content = QPlainTextEdit(dialog)
content.setObjectName("DiagnosisCallTranscriptText")
content.setReadOnly(True)
# Historical records keep their stored source; only the view is converted.
content.setPlainText(simplified_transcript(transcript))
content.setPlainText(transcript)
layout.addWidget(content, 1)
close_button = QPushButton("关闭")
close_button.setProperty("variant", "primary")

Some files were not shown because too many files have changed in this diff Show More