Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a676d0936b | ||
|
|
aab0babd7e | ||
|
|
d34fe2e67e |
@@ -0,0 +1,156 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { createRequire } from 'node:module'
|
||||
const require = createRequire(import.meta.url)
|
||||
const ts = require('typescript')
|
||||
const adminRoot = process.env.IDENTITY_UI_ROOT || path.resolve(import.meta.dirname, '..')
|
||||
const file = path.join(adminRoot, 'src/views/permission/identity/index.vue')
|
||||
const source = readFileSync(file, 'utf8')
|
||||
const script = source.match(/<script setup lang="ts">([\s\S]*?)<\/script>/)?.[1] || ''
|
||||
function load(names, scope = {}) {
|
||||
const ast = ts.createSourceFile(
|
||||
'identity.ts',
|
||||
script,
|
||||
ts.ScriptTarget.ES2022,
|
||||
true,
|
||||
ts.ScriptKind.TS
|
||||
)
|
||||
const found = ast.statements.filter(
|
||||
(node) => ts.isFunctionDeclaration(node) && names.includes(node.name?.text)
|
||||
)
|
||||
assert.equal(found.length, names.length, 'all requested functions exist in the actual SFC')
|
||||
const output = ts.transpileModule(found.map((node) => node.getText(ast)).join('\n'), {
|
||||
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS }
|
||||
}).outputText
|
||||
return new Function(...Object.keys(scope), output + '\nreturn {' + names.join(',') + '}')(
|
||||
...Object.values(scope)
|
||||
)
|
||||
}
|
||||
|
||||
test('adds exactly the requested department/access/check-time columns and retains native pagination', () => {
|
||||
for (const label of ['部门', '应用访问状态', '最近校验时间'])
|
||||
assert.ok(source.includes(`label="${label}"`), label)
|
||||
assert.match(source, /const query = reactive\(\{ q: '', state: '', page: 1, pageSize: 20 \}\)/)
|
||||
assert.match(source, /query\.page = 1/)
|
||||
assert.match(source, /v-model:current-page="query.page"/)
|
||||
const actions = source.split('<el-table-column label="操作"')[1].split('</el-table>')[0]
|
||||
assert.equal((actions.match(/type="primary"/g) || []).length, 2)
|
||||
assert.match(actions, /<el-dropdown/)
|
||||
})
|
||||
|
||||
test('department strings distinguish unassigned from unavailable data', () => {
|
||||
const { departmentText } = load(['departmentText'])
|
||||
assert.equal(departmentText({ dept_names: ['销售一部', '运营部'] }), '销售一部、运营部')
|
||||
assert.equal(departmentText({ dept_names: [] }), '未分配')
|
||||
assert.equal(departmentText({}), '未知')
|
||||
assert.equal(departmentText({ dept_names: null }), '未知')
|
||||
assert.equal(departmentText({ dept_names: [42] }), '未知')
|
||||
})
|
||||
|
||||
test('authorization is never inferred from verified binding or enabled local account', () => {
|
||||
const { applicationAccess } = load(['applicationAccess'])
|
||||
const row = { disable: 0, iam: { state: 'verified' } }
|
||||
assert.equal(applicationAccess(row).text, '未知')
|
||||
assert.equal(
|
||||
applicationAccess({ ...row, iam: { state: 'verified', access: { allowed: true } } }).text,
|
||||
'已授权'
|
||||
)
|
||||
assert.equal(
|
||||
applicationAccess({ ...row, iam: { state: 'verified', access: { allowed: false } } }).text,
|
||||
'未授权'
|
||||
)
|
||||
assert.equal(
|
||||
applicationAccess({ ...row, iam: { state: 'verified', access: { allowed: 'true' } } }).text,
|
||||
'未知'
|
||||
)
|
||||
assert.equal(
|
||||
applicationAccess({ ...row, iam: { state: 'unknown', access: { allowed: true } } }).text,
|
||||
'未知'
|
||||
)
|
||||
})
|
||||
|
||||
test('unlinked, revoked, service failure and unknown remain distinct without stale allow=true', () => {
|
||||
const { applicationAccess } = load(['applicationAccess'])
|
||||
assert.equal(applicationAccess({ iam: { state: 'unlinked' } }).text, '未关联')
|
||||
assert.equal(
|
||||
applicationAccess({ iam: { state: 'revoked', access: { allowed: false } } }).text,
|
||||
'未关联'
|
||||
)
|
||||
assert.equal(
|
||||
applicationAccess({
|
||||
iam: { state: 'unknown', access: { allowed: null, reason: 'SERVICE_UNAVAILABLE' } }
|
||||
}).text,
|
||||
'服务异常'
|
||||
)
|
||||
assert.equal(
|
||||
applicationAccess({
|
||||
iam: { state: 'verified', access: { allowed: true, reason: 'SERVICE_UNAVAILABLE' } }
|
||||
}).text,
|
||||
'服务异常'
|
||||
)
|
||||
assert.equal(
|
||||
applicationAccess({
|
||||
iam: { state: 'verified', access: { allowed: false, reason: 'NOT_LINKED' } }
|
||||
}).text,
|
||||
'未关联'
|
||||
)
|
||||
assert.equal(applicationAccess({ iam: { state: 'unknown' } }).text, '未知')
|
||||
for (const [reason, expected] of Object.entries({
|
||||
NOT_AUTHORIZED: '未授权',
|
||||
ACCOUNT_DISABLED: 'IAM账号停用',
|
||||
BINDING_CONFLICT: '关联冲突',
|
||||
ACCOUNT_MISMATCH: '身份不匹配'
|
||||
})) {
|
||||
assert.equal(
|
||||
applicationAccess({ iam: { state: 'unknown', access: { allowed: null, reason } } })
|
||||
.text,
|
||||
expected
|
||||
)
|
||||
assert.equal(
|
||||
applicationAccess({ iam: { state: 'verified', access: { allowed: true, reason } } })
|
||||
.text,
|
||||
expected
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
test('Unix seconds display Beijing time and absent/invalid timestamps never become a fake recent check', () => {
|
||||
const { checkedAtText } = load(['checkedAtText'])
|
||||
assert.equal(checkedAtText(1700000000), '2023/11/15 06:13:20')
|
||||
assert.equal(checkedAtText('1700000000'), checkedAtText(1700000000))
|
||||
for (const value of [null, undefined, 0, '', '0']) assert.equal(checkedAtText(value), '未校验')
|
||||
for (const value of [true, 'invalid', -1, Infinity, 1700000000000])
|
||||
assert.equal(checkedAtText(value), '未知')
|
||||
})
|
||||
|
||||
test('disabled writes are guarded even if an event handler is invoked directly', async () => {
|
||||
let notices = 0,
|
||||
posts = 0
|
||||
const drawerError = { value: '' }
|
||||
const scope = {
|
||||
ElMessage: { warning: () => notices++ },
|
||||
selected: { value: { disable: 1 } },
|
||||
drawerError,
|
||||
iamPost: async () => {
|
||||
posts++
|
||||
}
|
||||
}
|
||||
const { isLocalDisabled, open, submit } = load(['isLocalDisabled', 'open', 'submit'], scope)
|
||||
for (const disable of [1, true, '1']) assert.equal(isLocalDisabled({ disable }), true)
|
||||
for (const disable of [0, false, '0']) assert.equal(isLocalDisabled({ disable }), false)
|
||||
open({ disable: 1 }, 'bind')
|
||||
await submit()
|
||||
assert.equal(notices, 1)
|
||||
assert.equal(posts, 0)
|
||||
assert.match(drawerError.value, /停用/)
|
||||
})
|
||||
|
||||
test('all row write actions are disabled while audit remains readable with an explanation', () => {
|
||||
const actions = source.split('<el-table-column label="操作"')[1].split('</el-table>')[0]
|
||||
assert.ok((actions.match(/isLocalDisabled\(row\)/g) || []).length >= 5)
|
||||
assert.match(actions, /command="audit">审计记录/)
|
||||
assert.match(actions, /停用.*审计/)
|
||||
assert.match(source, /isLocalDisabled\(selected\)/)
|
||||
})
|
||||
@@ -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 ||
|
||||
'操作未完成,请刷新状态后重试。'
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
@@ -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'
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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>
|
||||
@@ -0,0 +1,723 @@
|
||||
<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="部门" min-width="140" show-overflow-tooltip>
|
||||
<template #default="{ row }">{{ departmentText(row) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="本地状态" width="110"
|
||||
><template #default="{ row }"
|
||||
><el-tag :type="isLocalDisabled(row) ? 'danger' : 'success'">{{
|
||||
isLocalDisabled(row) ? '停用' : 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="应用访问状态" width="130">
|
||||
<template #default="{ row }">
|
||||
<el-tag :type="applicationAccess(row).type">{{
|
||||
applicationAccess(row).text
|
||||
}}</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="最近校验时间" min-width="190">
|
||||
<template #default="{ row }">{{ checkedAtText(row.iam?.checked_at) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" min-width="210"
|
||||
><template #default="{ row }">
|
||||
<el-button
|
||||
link
|
||||
type="primary"
|
||||
:disabled="
|
||||
isLocalDisabled(row) ||
|
||||
(!!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="
|
||||
isLocalDisabled(row) ||
|
||||
(!!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="
|
||||
isLocalDisabled(row) ||
|
||||
(!!row.root && !reviewAllowed) ||
|
||||
!can('rebind')
|
||||
"
|
||||
>换绑</el-dropdown-item
|
||||
>
|
||||
<el-dropdown-item
|
||||
command="unbind"
|
||||
:disabled="
|
||||
isLocalDisabled(row) ||
|
||||
(!!row.root && !reviewAllowed) ||
|
||||
!can('unbind')
|
||||
"
|
||||
>解绑</el-dropdown-item
|
||||
>
|
||||
<el-dropdown-item command="audit">审计记录</el-dropdown-item>
|
||||
</el-dropdown-menu></template
|
||||
></el-dropdown
|
||||
>
|
||||
<div v-if="isLocalDisabled(row)" class="text-xs text-gray-500 mt-1">
|
||||
本地账号已停用,关联操作不可用;审计记录仍可查看。
|
||||
</div>
|
||||
</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="
|
||||
isLocalDisabled(selected) ||
|
||||
!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)
|
||||
)
|
||||
function isLocalDisabled(row: any): boolean {
|
||||
return row?.disable === true || row?.disable === 1 || row?.disable === '1'
|
||||
}
|
||||
function departmentText(row: any): string {
|
||||
if (!Array.isArray(row?.dept_names)) return '未知'
|
||||
if (row.dept_names.length === 0) return '未分配'
|
||||
if (!row.dept_names.every((name: unknown) => typeof name === 'string' && name.trim()))
|
||||
return '未知'
|
||||
return row.dept_names.map((name: string) => name.trim()).join('、')
|
||||
}
|
||||
function applicationAccess(row: any): {
|
||||
text: string
|
||||
type: 'success' | 'warning' | 'info' | 'danger'
|
||||
} {
|
||||
const iam = row?.iam
|
||||
const reason = iam?.access?.reason
|
||||
if (['SERVICE_UNAVAILABLE', 'STATUS_UNAVAILABLE'].includes(reason)) {
|
||||
return { text: '服务异常', type: 'warning' }
|
||||
}
|
||||
if (reason === 'NOT_AUTHORIZED') return { text: '未授权', type: 'warning' }
|
||||
if (reason === 'ACCOUNT_DISABLED') return { text: 'IAM账号停用', type: 'danger' }
|
||||
if (reason === 'BINDING_CONFLICT') return { text: '关联冲突', type: 'warning' }
|
||||
if (reason === 'ACCOUNT_MISMATCH') return { text: '身份不匹配', type: 'warning' }
|
||||
if (
|
||||
['unlinked', 'revoked'].includes(iam?.state) ||
|
||||
['NOT_LINKED', 'LOCAL_ACCOUNT_LINK_REQUIRED', 'BINDING_REVOKED'].includes(reason)
|
||||
) {
|
||||
return { text: '未关联', type: 'info' }
|
||||
}
|
||||
if (iam?.access?.allowed === false) return { text: '未授权', type: 'warning' }
|
||||
if (iam?.state === 'verified' && iam?.access?.allowed === true) {
|
||||
return { text: '已授权', type: 'success' }
|
||||
}
|
||||
return { text: '未知', type: 'info' }
|
||||
}
|
||||
function checkedAtText(value: unknown): string {
|
||||
if (value == null || value === '' || value === 0 || value === '0') return '未校验'
|
||||
const seconds = typeof value === 'number' || typeof value === 'string' ? Number(value) : NaN
|
||||
if (!Number.isInteger(seconds) || seconds <= 0 || seconds > 253402300799) return '未知'
|
||||
return new Date(seconds * 1000).toLocaleString('zh-CN', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
hour12: false
|
||||
})
|
||||
}
|
||||
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 (isLocalDisabled(row)) {
|
||||
ElMessage.warning('本地账号已停用,请先启用账号后再维护关联。')
|
||||
return
|
||||
}
|
||||
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() {
|
||||
if (isLocalDisabled(selected.value)) {
|
||||
drawerError.value = '本地账号已停用,请先启用账号后再维护关联。'
|
||||
return
|
||||
}
|
||||
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>
|
||||
@@ -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'
|
||||
|
||||
@@ -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, /<img src=x onerror=alert\(1\)>/)
|
||||
assert.doesNotMatch(html, /<img src=x|串诊单文字/)
|
||||
assert.doesNotMatch(html.match(/<pre[^>]*>([\s\S]*?)<\/pre>/)[1], /记录10/)
|
||||
await f.state.copyTranscript()
|
||||
assert.deepEqual(f.copied, ['医生:<img src=x onerror=alert(1)>\n患者:本次回答'])
|
||||
f.state.selectedId.value = 10
|
||||
assert.equal(f.state.selectedText.value, row(10).transcript_text)
|
||||
f.data.records.value = [row(13), row(11), row(10)]
|
||||
assert.equal(f.state.selectedId.value, 10)
|
||||
f.state.search.value = '记录13'
|
||||
assert.equal(f.state.selectedId.value, 13)
|
||||
assert.equal(f.state.filteredRecords.value.length, 1)
|
||||
f.props.diagnosisId = 202
|
||||
assert.equal(f.state.selectedText.value, '')
|
||||
assert.doesNotMatch(await f.html(), /记录13的问题|本次回答/)
|
||||
f.dispose()
|
||||
})
|
||||
|
||||
test('empty, failed and partial transcription states remain explicit in the rendered panel', async () => {
|
||||
for (const status of ['running', 'partial', 'failed']) {
|
||||
const f = panelFixture([{ ...row(1), transcription_status: status }])
|
||||
const html = await f.html()
|
||||
assert.match(html, /已保存|刷新查看最新/)
|
||||
assert.match(html, /记录1的问题/)
|
||||
f.dispose()
|
||||
}
|
||||
const missing = panelFixture([row(1, 101, '')])
|
||||
assert.match(await missing.html(), /本次面诊暂无已保存的文字对话/)
|
||||
missing.dispose()
|
||||
const none = panelFixture([])
|
||||
assert.match(await none.html(), /该诊单暂无面诊通话记录/)
|
||||
none.dispose()
|
||||
const failed = panelFixture([], { error: vue.ref('无权访问该诊单') })
|
||||
assert.match(await failed.html(), /无权访问该诊单/)
|
||||
assert.doesNotMatch(await failed.html(), /该诊单暂无面诊通话记录/)
|
||||
failed.dispose()
|
||||
})
|
||||
|
||||
test('the new tab is permission gated, lazy and absent when the drawer is closed', async () => {
|
||||
const { descriptor } = parse(read('views/tcm/diagnosis/edit.vue'))
|
||||
const editScript = compileScript(descriptor, { id: 'diagnosis-edit-transcript' })
|
||||
const pane = descriptor.template.content.match(/<el-tab-pane\s+v-if="hasCallTranscriptPermission"[\s\S]*?<\/el-tab-pane>/)[0]
|
||||
const compiled = compileTemplate({ source: pane, filename: 'edit-transcript-tab.vue', id: 'edit-transcript', compilerOptions: { bindingMetadata: editScript.bindings } })
|
||||
assert.deepEqual(compiled.errors, [])
|
||||
const renderPane = moduleFrom(compiled.code).render
|
||||
async function html(allowed, active, visible, id) {
|
||||
const state = { hasCallTranscriptPermission: allowed, activeTab: active, visible, formData: { id }, ConsultationTranscriptPanel: { props: ['diagnosisId'], setup: props => () => vue.h('div', { 'data-diagnosis': props.diagnosisId }, '真实转写面板入口') } }
|
||||
const app = vue.createSSRApp({ render: () => renderPane({}, [], {}, state) })
|
||||
app.component('el-tab-pane', { props: ['disabled', 'label'], setup: (props, { slots }) => () => vue.h('section', { 'data-disabled': String(props.disabled) }, [props.label, slots.default?.()]) })
|
||||
app.component('el-empty', { props: ['description'], setup: props => () => vue.h('p', props.description) })
|
||||
return renderToString(app)
|
||||
}
|
||||
assert.doesNotMatch(await html(false, 'callTranscript', true, 101), /面诊文字对话/)
|
||||
assert.doesNotMatch(await html(true, 'basic', true, 101), /真实转写面板入口/)
|
||||
assert.doesNotMatch(await html(true, 'callTranscript', false, 101), /真实转写面板入口/)
|
||||
assert.match(await html(true, 'callTranscript', true, 101), /data-diagnosis="101"/)
|
||||
assert.match(await html(true, 'callTranscript', true, ''), /data-disabled="true"/)
|
||||
})
|
||||
|
||||
test('the read helper sends the exact diagnosis and abort signal without canceling replay requests', async () => {
|
||||
let request
|
||||
const api = moduleFrom(read('api/tcm.ts'), name => {
|
||||
if (name === '@/utils/request') return { default: { get: (...args) => { request = args; return Promise.resolve([]) } } }
|
||||
throw new Error(name)
|
||||
})
|
||||
const controller = new AbortController()
|
||||
await api.getConsultationTranscripts({ diagnosis_id: 101 }, controller.signal)
|
||||
assert.equal(request[0].url, '/tcm.diagnosis/getCallRecords')
|
||||
assert.deepEqual(request[0].params, { diagnosis_id: 101 })
|
||||
assert.equal(request[0].signal, controller.signal)
|
||||
assert.equal(request[1].ignoreCancelToken, true)
|
||||
})
|
||||
@@ -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, [])
|
||||
})
|
||||
}
|
||||
@@ -1,6 +1,4 @@
|
||||
.env
|
||||
.local-workstation/
|
||||
resources/local-asr/
|
||||
.venv/
|
||||
.venv-build/
|
||||
.venv-win7-check/
|
||||
|
||||
@@ -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/),然后在项目根目录执行:
|
||||
|
||||
@@ -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%
|
||||
|
Before Width: | Height: | Size: 118 KiB After Width: | Height: | Size: 124 KiB |
|
Before Width: | Height: | Size: 163 KiB After Width: | Height: | Size: 167 KiB |
|
Before Width: | Height: | Size: 117 KiB After Width: | Height: | Size: 115 KiB |
|
Before Width: | Height: | Size: 165 KiB After Width: | Height: | Size: 167 KiB |
|
Before Width: | Height: | Size: 112 KiB After Width: | Height: | Size: 159 KiB |
|
Before Width: | Height: | Size: 147 KiB After Width: | Height: | Size: 188 KiB |
|
Before Width: | Height: | Size: 90 KiB After Width: | Height: | Size: 92 KiB |
|
Before Width: | Height: | Size: 67 KiB After Width: | Height: | Size: 66 KiB |
|
Before Width: | Height: | Size: 77 KiB After Width: | Height: | Size: 73 KiB |
@@ -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)],
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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 代码与新前端资源才能一起生效。已冻结安装包需重新构建,不能只更换网页资源。
|
||||
@@ -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`。
|
||||
|
||||
尚未部署远程服务端或重启正在运行的医生客户端。需要服务端加载最新代码、客户端加载本次构建后才会生效;腾讯云实时转写与简体中文配置保持原样。
|
||||
@@ -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):明确列出的多方言/地域口音范围。
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -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())
|
||||
@@ -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())
|
||||
@@ -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;此时程序只使用下面配置的线上域名。
|
||||
|
||||
@@ -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."""
|
||||
|
||||
@@ -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; }
|
||||
"""
|
||||
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
from copy import deepcopy
|
||||
from html import escape
|
||||
from math import isfinite
|
||||
from time import monotonic
|
||||
@@ -403,28 +402,6 @@ def can_open_issued_ai(permissions: Any) -> bool:
|
||||
return has_permission(permissions, "tcm.prescriptionAi/reports", default=False) and has_permission(permissions, "tcm.prescriptionAi/detail", default=False)
|
||||
|
||||
|
||||
def agreement_safe_batch(value: Any, visible: bool) -> dict[str, Any]:
|
||||
"""Discard restricted structured comparisons before retaining any UI cache."""
|
||||
|
||||
data = deepcopy(mapping(value))
|
||||
if visible:
|
||||
return data
|
||||
fields = {"comparison", "score", "herb_score", "comparison_status", "comparison_reason_code", "comparison_type",
|
||||
"algorithm_version", "normalization_version", "denominator", "dictionary_version", "dictionary_versions",
|
||||
"baseline_eligible", "baseline_exclusion_reasons", "baseline_exclusions_json"}
|
||||
for item in (data, *mapping(data.get("models")).values()):
|
||||
if isinstance(item, dict):
|
||||
for field in fields:
|
||||
item.pop(field, None)
|
||||
for model in mapping(data.get("models")).values():
|
||||
if isinstance(model, dict) and not model.get("error_code"):
|
||||
# Successful model reasons describe the comparison, while failed
|
||||
# task reasons explain generation and remain useful with reports.
|
||||
model.pop("reason", None)
|
||||
data["agreement_visible"] = False
|
||||
return data
|
||||
|
||||
|
||||
def _html(value: Any, field: str = "") -> str:
|
||||
"""Escape all stored/model content, including source URLs, before rendering."""
|
||||
if isinstance(value, Mapping):
|
||||
@@ -559,8 +536,6 @@ class IssuedPrescriptionAiDialog(QDialog):
|
||||
self._progress_frozen_seconds = 0
|
||||
self._progress_stale = False
|
||||
self._read_access_denied = False
|
||||
self._agreement_visible = False
|
||||
self._history_agreement_visible = False
|
||||
self.setWindowTitle("诊断与药方 · AI 分析报告")
|
||||
self.resize(1440, 940)
|
||||
self.setMinimumSize(940, 640)
|
||||
@@ -600,7 +575,7 @@ class IssuedPrescriptionAiDialog(QDialog):
|
||||
identity_block.addWidget(self.breadcrumb)
|
||||
title_row = QHBoxLayout()
|
||||
title_row.setSpacing(10)
|
||||
heading = self.heading = QLabel("诊断与药方对照", top)
|
||||
heading = QLabel("诊断与药方对照", top)
|
||||
heading.setObjectName("AiHeroTitle")
|
||||
title_row.addWidget(heading)
|
||||
self.chip_row = QHBoxLayout()
|
||||
@@ -928,7 +903,7 @@ class IssuedPrescriptionAiDialog(QDialog):
|
||||
footer_text = QVBoxLayout()
|
||||
footer_text.setSpacing(4)
|
||||
footer_text.addWidget(self.message)
|
||||
note = self.disclaimer = QLabel(DISCLAIMER)
|
||||
note = QLabel(DISCLAIMER)
|
||||
note.setObjectName("AiFootnote")
|
||||
note.setWordWrap(True)
|
||||
footer_text.addWidget(note)
|
||||
@@ -946,7 +921,6 @@ class IssuedPrescriptionAiDialog(QDialog):
|
||||
self._progress_timer.timeout.connect(self._render_progress)
|
||||
self._sync_actions()
|
||||
self._navigation_changed(self.tabs.currentIndex())
|
||||
self._apply_agreement_visibility(self._agreement_visible)
|
||||
|
||||
REPORT_MODES = (("both", "并排对照"), ("qwen", "仅千问"), ("openai", "仅 OpenAI"),
|
||||
("differences", "只看不同段落"))
|
||||
@@ -1089,8 +1063,6 @@ class IssuedPrescriptionAiDialog(QDialog):
|
||||
return host
|
||||
|
||||
def _goto(self, key: str) -> None:
|
||||
if not self._agreement_visible:
|
||||
key = "candidate" if key == "per_herb" else "report" if key in {"comparison_raw", "history"} else key
|
||||
page = self.tab_pages.get(key)
|
||||
if page is not None:
|
||||
self.tabs.setCurrentWidget(page)
|
||||
@@ -1098,10 +1070,7 @@ class IssuedPrescriptionAiDialog(QDialog):
|
||||
def _navigation_changed(self, index: int) -> None:
|
||||
widget = self.tabs.widget(index)
|
||||
current = next((key for key, page in self.tab_pages.items() if page is widget), "")
|
||||
if not self._agreement_visible and current in {"per_herb", "comparison_raw", "history"}:
|
||||
self._goto("report")
|
||||
return
|
||||
self.rail.set_current("per_herb" if current == "candidate" and not self._agreement_visible else current)
|
||||
self.rail.set_current(current)
|
||||
self._current_page = current
|
||||
self._apply_density()
|
||||
|
||||
@@ -1132,36 +1101,6 @@ class IssuedPrescriptionAiDialog(QDialog):
|
||||
if field in MODELS:
|
||||
self.model_views[field]["report"].setFocus()
|
||||
|
||||
def _apply_agreement_visibility(self, visible: bool) -> None:
|
||||
"""One server decision controls every comparison surface, without losing review."""
|
||||
|
||||
self._agreement_visible = visible
|
||||
self.agreement.set_agreement_visible(visible)
|
||||
self.agreement_note.setVisible(visible)
|
||||
self.heading.setText("诊断与药方对照" if visible else "诊断与药方报告")
|
||||
self.disclaimer.setText(DISCLAIMER if visible else "候选建议仅供医生复核。")
|
||||
self.comparison_panel.set_agreement_visible(visible)
|
||||
self.rail.names["overview"].setText("对比总览" if visible else "报告复核")
|
||||
self.rail.names["per_herb"].setText("候选与逐味" if visible else "AI 候选处方")
|
||||
self.nav_buttons["history"].setVisible(visible)
|
||||
for key in ("differences", "consensus"):
|
||||
self.rail.focus_values[key].parentWidget().setVisible(visible)
|
||||
if not visible:
|
||||
self._batch = agreement_safe_batch(self._batch, False) if self._batch else {}
|
||||
self._history_scope = {key: agreement_safe_batch(row, False) for key, row in self._history_scope.items()}
|
||||
self.history_page.set_history([])
|
||||
self.candidates_page.set_batch({})
|
||||
for views in self.model_views.values():
|
||||
views["comparison"].clear()
|
||||
self.comparison_panel.set_batch(self._batch)
|
||||
self.rail.set_focus({})
|
||||
self.rail.badges["overview"].clear()
|
||||
self.rail.badges["per_herb"].clear()
|
||||
self.rail.badges["overview"].hide()
|
||||
self.rail.badges["per_herb"].hide()
|
||||
if self._current_page in {"per_herb", "comparison_raw", "history"}:
|
||||
self._goto("report")
|
||||
|
||||
@property
|
||||
def save_review_button(self) -> QPushButton:
|
||||
"""The review card's own save action for the model currently being annotated."""
|
||||
@@ -1267,12 +1206,9 @@ class IssuedPrescriptionAiDialog(QDialog):
|
||||
return
|
||||
self._read_access_denied = False
|
||||
data = mapping(result)
|
||||
self._history_agreement_visible = data.get("agreement_visible") is True
|
||||
self._apply_agreement_visibility(self._history_agreement_visible)
|
||||
self._feature_enabled = data.get("enabled", True) is not False
|
||||
rows = [agreement_safe_batch(row, self._history_agreement_visible and mapping(row).get("agreement_visible") is True)
|
||||
for row in data.get("lists") or []]
|
||||
self.history_page.set_history(rows if self._agreement_visible else [])
|
||||
rows = data.get("lists") or []
|
||||
self.history_page.set_history([mapping(row) for row in rows])
|
||||
self.history.blockSignals(True)
|
||||
self.history.clear()
|
||||
self._history_scope = {}
|
||||
@@ -1385,8 +1321,6 @@ class IssuedPrescriptionAiDialog(QDialog):
|
||||
|
||||
def _read_failed(self, error: Exception, prefix: str) -> None:
|
||||
self._timer.stop()
|
||||
self._history_agreement_visible = False
|
||||
self._apply_agreement_visibility(False)
|
||||
text = str(error).lower()
|
||||
restricted = isinstance(error, (ValueError, AuthenticationExpiredError)) or getattr(error, "status_code", None) in {401, 403, 404} or any(
|
||||
marker in text for marker in ("forbidden", "unauthorized", "permission", "access_revoked", "not found", "权限", "无权", "登录", "归属", "不存在")
|
||||
@@ -1420,10 +1354,6 @@ class IssuedPrescriptionAiDialog(QDialog):
|
||||
if int(batch.get("id") or 0) != batch_id or not identity_matches or (self.prescription_id and int(batch.get("prescription_id") or 0) != self.prescription_id):
|
||||
self._detail_error(ValueError("报告归属与当前处方或诊单不一致"), generation)
|
||||
return
|
||||
visible = (self._history_agreement_visible and batch.get("agreement_visible") is True
|
||||
and mapping(expected).get("agreement_visible") is True)
|
||||
self._apply_agreement_visibility(visible)
|
||||
batch = agreement_safe_batch(batch, visible)
|
||||
first_load = not self._batch
|
||||
self._batch = batch
|
||||
self._read_access_denied = False
|
||||
@@ -1438,7 +1368,7 @@ class IssuedPrescriptionAiDialog(QDialog):
|
||||
self.identity.setText(f"处方 {batch.get('prescription_id')} · 诊单 {batch.get('diagnosis_id')} · 版本 {batch.get('prescription_revision', '—')}")
|
||||
self._set_chips([
|
||||
(label(batch.get("validity")), "info" if current_batch(batch) else "warn"),
|
||||
(label(batch.get("comparison_type")) if self._agreement_visible else "", "neutral"),
|
||||
(label(batch.get("comparison_type")), "neutral"),
|
||||
])
|
||||
self.batch_summary.setText(f"{compact_state} {_reason(batch.get('error_message') or batch.get('error_code'))}\n资料截止:{format_record_time(batch.get('cutoff_at'))} · 批次建立:{format_record_time(batch.get('created_at'))}")
|
||||
self._render_facts(batch)
|
||||
@@ -1481,11 +1411,9 @@ class IssuedPrescriptionAiDialog(QDialog):
|
||||
"risk_assessment": report.get("risk_assessment"),
|
||||
}
|
||||
_set_html(views["candidate"], _candidate_html(candidate_content))
|
||||
comparison_html = ""
|
||||
if self._agreement_visible:
|
||||
comparison_html = f"<p><b>药味与剂量一致度:{percentage(score, 1)} 纯药味重合度:{percentage(comparison.get('herb_score'), 1)}</b></p>"
|
||||
comparison_html += "<p class=sec>逐味贡献</p>" + _html(_comparison_rows(comparison.get("rows")) or "没有可展示的逐味对照。")
|
||||
comparison_html += _html({field: value for field, value in comparison.items() if field not in {"score", "herb_score", "rows"}})
|
||||
comparison_html = f"<p><b>药味与剂量一致度:{percentage(score, 1)} 纯药味重合度:{percentage(comparison.get('herb_score'), 1)}</b></p>"
|
||||
comparison_html += "<p class=sec>逐味贡献</p>" + _html(_comparison_rows(comparison.get("rows")) or "没有可展示的逐味对照。")
|
||||
comparison_html += _html({field: value for field, value in comparison.items() if field not in {"score", "herb_score", "rows"}})
|
||||
_set_html(views["comparison"], comparison_html)
|
||||
source_html = _html({"source_summary": batch.get("source_summary"), "missing": batch.get("missing"), "coverage": model.get("coverage"), "baseline_eligible": batch.get("baseline_eligible"), "baseline_exclusion_reasons": batch.get("baseline_exclusion_reasons"), "cutoff_at": format_record_time(batch.get("cutoff_at")), "generated_at": format_record_time(model.get("generated_at"))})
|
||||
reference_lines = [line for line in report_provenance_lines(model)
|
||||
@@ -1500,7 +1428,7 @@ class IssuedPrescriptionAiDialog(QDialog):
|
||||
views["comment"].setPlainText(str(review.get("comment") or ""))
|
||||
index = views["review_state"].findData(review.get("status"))
|
||||
views["review_state"].setCurrentIndex(max(0, index))
|
||||
self.candidates_page.set_batch(batch if self._agreement_visible else {})
|
||||
self.candidates_page.set_batch(batch)
|
||||
self.sources_page.set_batch(batch)
|
||||
self.pipeline_page.set_batch(batch)
|
||||
self._sync_failures(batch)
|
||||
@@ -1560,12 +1488,6 @@ class IssuedPrescriptionAiDialog(QDialog):
|
||||
"restricted": panel.restricted_count(data) if hasattr(panel, "restricted_count") else None,
|
||||
"consensus": panel.consensus_count() if hasattr(panel, "consensus_count") else None,
|
||||
})
|
||||
if not self._agreement_visible:
|
||||
for key in ("differences", "consensus"):
|
||||
self.rail.focus_values[key].clear()
|
||||
for key in ("overview", "per_herb"):
|
||||
self.rail.badges[key].clear()
|
||||
self.rail.badges[key].hide()
|
||||
|
||||
def _render_facts(self, batch: Any) -> None:
|
||||
snapshot = mapping(mapping(batch).get("doctor_snapshot"))
|
||||
@@ -1785,7 +1707,6 @@ class PrescriptionAiStatisticsDialog(QDialog):
|
||||
super().__init__(parent)
|
||||
self.repository, self.permissions = repository, permissions
|
||||
self._generation = 0
|
||||
self._agreement_visible = False
|
||||
self.setWindowTitle("医生处方 AI 一致度统计")
|
||||
self.setStyleSheet(dialog_style() + rail_qss())
|
||||
self.resize(1180, 860)
|
||||
@@ -1821,7 +1742,6 @@ class PrescriptionAiStatisticsDialog(QDialog):
|
||||
self.report.document().setDefaultStyleSheet(_report_css())
|
||||
self.report.setMinimumHeight(130)
|
||||
root.addWidget(self.report, 1)
|
||||
self.panel.hide()
|
||||
|
||||
def showEvent(self, event: Any) -> None:
|
||||
super().showEvent(event)
|
||||
@@ -1830,19 +1750,9 @@ class PrescriptionAiStatisticsDialog(QDialog):
|
||||
|
||||
def hideEvent(self, event: Any) -> None:
|
||||
self._generation += 1
|
||||
self._clear_statistics()
|
||||
super().hideEvent(event)
|
||||
|
||||
def _clear_statistics(self) -> None:
|
||||
self._agreement_visible = False
|
||||
self.panel.set_statistics({})
|
||||
self.panel.hide()
|
||||
self.report.clear()
|
||||
|
||||
def refresh(self) -> None:
|
||||
self._generation += 1
|
||||
generation = self._generation
|
||||
self._clear_statistics()
|
||||
if not has_permission(self.permissions, "tcm.prescriptionAi/statistics", default=False):
|
||||
self.summary.setText("没有查看医生统计的权限。")
|
||||
return
|
||||
@@ -1853,33 +1763,20 @@ class PrescriptionAiStatisticsDialog(QDialog):
|
||||
if doctor and (not doctor.isdecimal() or int(doctor) <= 0):
|
||||
self.summary.setText("请填写有效的医生编号。")
|
||||
return
|
||||
self.summary.setText("正在核验一致度查看权限…")
|
||||
method = getattr(self.repository, "get_prescription_ai_capabilities", None)
|
||||
if not callable(method):
|
||||
self.summary.setText("当前账号无权查看一致度统计。")
|
||||
return
|
||||
date_from, date_to = self.date_from.date().toString("yyyy-MM-dd"), self.date_to.date().toString("yyyy-MM-dd")
|
||||
run_async(method, on_success=lambda result: self._capabilities_ready(result, generation, date_from, date_to, int(doctor) if doctor else None),
|
||||
on_error=lambda error: self._error(error, generation))
|
||||
|
||||
def _capabilities_ready(self, result: Any, generation: int, date_from: str, date_to: str, doctor: int | None) -> None:
|
||||
if generation != self._generation:
|
||||
return
|
||||
if mapping(result).get("agreement_visible") is not True or not has_permission(self.permissions, "tcm.prescriptionAi/statistics", default=False):
|
||||
self._clear_statistics()
|
||||
self.summary.setText("当前账号无权查看一致度统计。")
|
||||
return
|
||||
self._agreement_visible = True
|
||||
self._generation += 1
|
||||
generation = self._generation
|
||||
self.summary.setText("正在读取统计…")
|
||||
run_async(lambda: self.repository.prescription_ai_statistics(date_from, date_to, doctor), on_success=lambda result: self._ready(result, generation), on_error=lambda error: self._error(error, generation))
|
||||
self.report.clear()
|
||||
date_from, date_to = self.date_from.date().toString("yyyy-MM-dd"), self.date_to.date().toString("yyyy-MM-dd")
|
||||
run_async(lambda: self.repository.prescription_ai_statistics(date_from, date_to, int(doctor) if doctor else None), on_success=lambda result: self._ready(result, generation), on_error=lambda error: self._error(error, generation))
|
||||
|
||||
def _error(self, error: Exception, generation: int) -> None:
|
||||
if generation == self._generation:
|
||||
self.summary.setText("统计暂不可用:" + _error_text(error))
|
||||
self._clear_statistics()
|
||||
self.report.clear()
|
||||
|
||||
def _ready(self, result: Any, generation: int) -> None:
|
||||
if generation != self._generation or not self._agreement_visible:
|
||||
if generation != self._generation:
|
||||
return
|
||||
data = mapping(result)
|
||||
if data.get("enabled") is False:
|
||||
@@ -1889,7 +1786,6 @@ class PrescriptionAiStatisticsDialog(QDialog):
|
||||
return
|
||||
self.summary.setText(f"范围内开方事件:{label(data.get('total_count'))} · 患者数:{label(data.get('patient_count'))}。小样本应谨慎解读,未按分数排名。")
|
||||
self.panel.set_statistics(data)
|
||||
self.panel.show()
|
||||
sections = []
|
||||
for row in data.get("doctors") or []:
|
||||
doctor = mapping(row)
|
||||
|
||||
@@ -190,8 +190,6 @@ class AgreementBar(QFrame):
|
||||
layout = QHBoxLayout(self)
|
||||
layout.setContentsMargins(22, 16, 22, 16)
|
||||
layout.setSpacing(24)
|
||||
self._agreement_visible = True
|
||||
self._metric_chrome: list[QWidget] = []
|
||||
self.blocks: dict[str, dict[str, Any]] = {}
|
||||
for index, key in enumerate(("qwen", "openai")):
|
||||
if index:
|
||||
@@ -199,14 +197,11 @@ class AgreementBar(QFrame):
|
||||
divider.setObjectName("AiFactDivider")
|
||||
divider.setFixedWidth(1)
|
||||
layout.addWidget(divider)
|
||||
delta = self._delta_block()
|
||||
layout.addWidget(delta)
|
||||
self._metric_chrome.extend((divider, delta))
|
||||
layout.addWidget(self._delta_block())
|
||||
divider = QFrame(self)
|
||||
divider.setObjectName("AiFactDivider")
|
||||
divider.setFixedWidth(1)
|
||||
layout.addWidget(divider)
|
||||
self._metric_chrome.append(divider)
|
||||
# Both heads line up at the top, so a model that failed does not slide its column down.
|
||||
layout.addWidget(self._model_block(key), 1, Qt.AlignmentFlag.AlignTop)
|
||||
|
||||
@@ -299,7 +294,7 @@ class AgreementBar(QFrame):
|
||||
carrier.setFixedHeight(4)
|
||||
carrier.setAccessibleName(f"{MODEL_NAMES[key]}与医生方的药味及剂量一致度")
|
||||
carrier.setVisible(False)
|
||||
self.blocks[key] = {"score": score, "caption": caption, "coverage": coverage, "elapsed": elapsed, "track": track,
|
||||
self.blocks[key] = {"score": score, "coverage": coverage, "elapsed": elapsed, "track": track,
|
||||
"status": status, "failure": failure, "failure_text": failure_text,
|
||||
"retry_slot": retry_slot, "stage": stage, "carrier": carrier}
|
||||
return holder
|
||||
@@ -318,30 +313,6 @@ class AgreementBar(QFrame):
|
||||
|
||||
self.blocks[key]["retry_slot"].addWidget(button)
|
||||
|
||||
def set_agreement_visible(self, visible: bool) -> None:
|
||||
"""Keep model states and retries available when the metric is restricted."""
|
||||
|
||||
self._agreement_visible = visible
|
||||
for widget in self._metric_chrome:
|
||||
widget.setVisible(visible)
|
||||
for key, block in self.blocks.items():
|
||||
for field in ("score", "caption", "track"):
|
||||
block[field].setVisible(visible)
|
||||
if visible:
|
||||
block["carrier"].setAccessibleName(f"{MODEL_NAMES[key]}与医生方的药味及剂量一致度")
|
||||
if not visible:
|
||||
block["score"].clear()
|
||||
block["score"].setToolTip("")
|
||||
block["track"].set_values(None, None, "")
|
||||
block["track"].setAccessibleDescription("")
|
||||
block["carrier"].setValue(0)
|
||||
block["carrier"].setToolTip("")
|
||||
block["carrier"].setAccessibleName("")
|
||||
if not visible:
|
||||
self.delta.clear()
|
||||
self.delta_note.clear()
|
||||
self.overlap.clear()
|
||||
|
||||
def set_failure(self, key: str, message: str, retryable: bool) -> None:
|
||||
block = self.blocks[key]
|
||||
block["failure_text"].setText(message)
|
||||
@@ -380,7 +351,7 @@ class AgreementBar(QFrame):
|
||||
elapsed: Mapping[str, str] | None = None) -> None:
|
||||
data = _mapping(batch)
|
||||
models = _mapping(data.get("models"))
|
||||
scores = {key: _score(_mapping(models.get(key))) if self._agreement_visible else None for key in ("qwen", "openai")}
|
||||
scores = {key: _score(_mapping(models.get(key))) for key in ("qwen", "openai")}
|
||||
for key in ("qwen", "openai"):
|
||||
block = self.blocks[key]
|
||||
value = scores[key]
|
||||
@@ -393,9 +364,6 @@ class AgreementBar(QFrame):
|
||||
spent = _mapping(elapsed).get(key, "")
|
||||
block["elapsed"].setText(spent)
|
||||
block["elapsed"].setVisible(bool(spent))
|
||||
if not self._agreement_visible:
|
||||
self.set_agreement_visible(False)
|
||||
return
|
||||
if scores["qwen"] is None or scores["openai"] is None:
|
||||
self.delta.setText("—")
|
||||
self.delta_note.setText("两个模型都可比后才给差值")
|
||||
|
||||
@@ -21,8 +21,6 @@ from typing import Any
|
||||
|
||||
from PySide6.QtGui import QFont
|
||||
|
||||
from ..design_system import PALETTE
|
||||
|
||||
DARK: dict[str, str] = {
|
||||
# ground and cards
|
||||
"canvas": "#080D18",
|
||||
@@ -64,23 +62,23 @@ DARK: dict[str, str] = {
|
||||
}
|
||||
|
||||
LIGHT: dict[str, str] = {
|
||||
"canvas": PALETTE["canvas"],
|
||||
"canvas_soft": PALETTE["surface_alt"],
|
||||
"surface": PALETTE["surface"],
|
||||
"surface_2": PALETTE["surface_alt"],
|
||||
"raised": PALETTE["sidebar"],
|
||||
"line": PALETTE["line_strong"],
|
||||
"line_soft": PALETTE["line"],
|
||||
"heading": PALETTE["heading"],
|
||||
"text": PALETTE["text"],
|
||||
"muted": PALETTE["muted"],
|
||||
"faint": PALETTE["disabled"],
|
||||
"selected_text": PALETTE["heading"],
|
||||
"accent": PALETTE["accent"],
|
||||
"accent_text": PALETTE["accent_hover"],
|
||||
"accent_pressed": PALETTE["accent_pressed"],
|
||||
"selection": PALETTE["accent_soft"],
|
||||
"selection_line": PALETTE["focus"],
|
||||
"canvas": "#F1F5FC",
|
||||
"canvas_soft": "#E7EEFA",
|
||||
"surface": "#FFFFFF",
|
||||
"surface_2": "#F5F8FE",
|
||||
"raised": "#E8EFFA",
|
||||
"line": "#D5E1F2",
|
||||
"line_soft": "#E3EBF8",
|
||||
"heading": "#0A182E",
|
||||
"text": "#2A3C56",
|
||||
"muted": "#54697F",
|
||||
"faint": "#7A8DA3",
|
||||
"selected_text": "#0A182E",
|
||||
"accent": "#1A5FD0",
|
||||
"accent_text": "#124DAE",
|
||||
"accent_pressed": "#0E3F90",
|
||||
"selection": "#E8EFFA",
|
||||
"selection_line": "#AEC7EE",
|
||||
"qwen": "#0C89AC",
|
||||
"qwen_text": "#086C88",
|
||||
"qwen_dim": "#E2F5FA",
|
||||
|
||||
@@ -537,9 +537,6 @@ class DoseDiffPanel(QFrame):
|
||||
item = self.body_layout.takeAt(0)
|
||||
widget = item.widget()
|
||||
if widget is not None:
|
||||
widget.hide()
|
||||
for label in widget.findChildren(QLabel):
|
||||
label.clear()
|
||||
widget.setParent(None)
|
||||
widget.deleteLater()
|
||||
extent = _axis_extent(deltas)
|
||||
@@ -623,9 +620,6 @@ class ConclusionsPanel(QFrame):
|
||||
entry = self.body_layout.takeAt(0)
|
||||
widget = entry.widget()
|
||||
if widget is not None:
|
||||
widget.hide()
|
||||
for label in widget.findChildren(QLabel):
|
||||
label.clear()
|
||||
widget.setParent(None)
|
||||
widget.deleteLater()
|
||||
for index, text in enumerate(items, start=1):
|
||||
@@ -850,9 +844,6 @@ class RiskPanel(QFrame):
|
||||
entry = self.body_layout.takeAt(0)
|
||||
widget = entry.widget()
|
||||
if widget is not None:
|
||||
widget.hide()
|
||||
for label in widget.findChildren(QLabel):
|
||||
label.clear()
|
||||
widget.setParent(None)
|
||||
widget.deleteLater()
|
||||
flagged = []
|
||||
@@ -1024,9 +1015,6 @@ class ChecklistPanel(QFrame):
|
||||
entry = self.body_layout.takeAt(0)
|
||||
widget = entry.widget()
|
||||
if widget is not None:
|
||||
widget.hide()
|
||||
for label in widget.findChildren(QLabel):
|
||||
label.clear()
|
||||
widget.setParent(None)
|
||||
widget.deleteLater()
|
||||
grouped: dict[str, tuple[str, str, int, str]] = {}
|
||||
@@ -1144,7 +1132,6 @@ class PrescriptionReviewWorkspace(QWidget):
|
||||
self._batch: dict[str, Any] = {}
|
||||
self.rows: list[ReviewDoseRow] = []
|
||||
self._review_widget: QWidget | None = None
|
||||
self._agreement_visible = True
|
||||
self._summary = "选择报告后查看诊断与药方"
|
||||
self.setStyleSheet(f"""
|
||||
QWidget#PrescriptionReviewWorkspace {{ background: transparent; }}
|
||||
@@ -1163,7 +1150,7 @@ class PrescriptionReviewWorkspace(QWidget):
|
||||
page = QWidget(self.page_scroll)
|
||||
self.page_scroll.setWidget(page)
|
||||
outer.addWidget(self.page_scroll)
|
||||
root = self._workspace_layout = QVBoxLayout(page)
|
||||
root = QVBoxLayout(page)
|
||||
root.setContentsMargins(0, 0, 6, 0)
|
||||
root.setSpacing(14)
|
||||
|
||||
@@ -1214,10 +1201,6 @@ class PrescriptionReviewWorkspace(QWidget):
|
||||
layout.takeAt(0)
|
||||
for index in range(layout.columnCount()):
|
||||
layout.setColumnStretch(index, 0)
|
||||
if not self._agreement_visible:
|
||||
self.first.addWidget(self.checklist, 0, 0)
|
||||
self.first.setColumnStretch(0, 1)
|
||||
return
|
||||
cards = (self.conclusions, self.attribution, self.checklist)
|
||||
if columns == 1:
|
||||
for row, card in enumerate(cards):
|
||||
@@ -1306,31 +1289,7 @@ class PrescriptionReviewWorkspace(QWidget):
|
||||
self._batch = deepcopy(data)
|
||||
self._render()
|
||||
|
||||
def set_agreement_visible(self, visible: bool) -> None:
|
||||
"""Use the existing checklist as a report-only review workspace."""
|
||||
|
||||
if visible == self._agreement_visible:
|
||||
return
|
||||
self._agreement_visible = visible
|
||||
for widget in (self.conclusions, self.attribution, self.doses, self.risks, self.links["comparison"]):
|
||||
widget.setVisible(visible)
|
||||
self._workspace_layout.setStretch(0, 5 if visible else 1)
|
||||
self._workspace_layout.setStretch(1, 4 if visible else 0)
|
||||
self._columns = 0
|
||||
self._reflow(1 if self.width() < self.STACK_BELOW else 3)
|
||||
self._render()
|
||||
|
||||
def _render(self) -> None:
|
||||
if not self._agreement_visible:
|
||||
self.rows = []
|
||||
self.doses.set_rows([])
|
||||
self.risks.set_rows([])
|
||||
self.attribution.apply({})
|
||||
self.conclusions.set_items([])
|
||||
self.checklist.set_items(checklist_items(self._batch))
|
||||
self._summary = "请结合报告与资料缺口记录复核意见。"
|
||||
self.summary_changed.emit(self._summary)
|
||||
return
|
||||
self.rows, _states = review_rows(self._batch)
|
||||
deltas = dose_deltas(self.rows)
|
||||
self.doses.set_rows(deltas)
|
||||
|
||||
@@ -29,7 +29,6 @@ from ...services.local_audio_queue import (
|
||||
LocalAudioUploadManager,
|
||||
get_local_audio_upload_manager,
|
||||
)
|
||||
from ..design_system import clinical_stylesheet
|
||||
from ..widgets import run_async
|
||||
|
||||
_STATUS_LABELS = {
|
||||
@@ -175,7 +174,7 @@ class LocalAudioQueueDialog(QDialog):
|
||||
self.setModal(True)
|
||||
self.setMinimumSize(760, 480)
|
||||
self.resize(1160, 620)
|
||||
self.setStyleSheet(clinical_stylesheet(_LOCAL_AUDIO_QSS))
|
||||
self.setStyleSheet(_LOCAL_AUDIO_QSS)
|
||||
self._build_ui()
|
||||
|
||||
self.poll_timer = QTimer(self)
|
||||
|
||||
@@ -29,7 +29,6 @@ from PySide6.QtCore import (
|
||||
QEvent,
|
||||
QIODevice,
|
||||
QMarginsF,
|
||||
QModelIndex,
|
||||
QObject,
|
||||
QPoint,
|
||||
QRectF,
|
||||
@@ -52,8 +51,6 @@ from PySide6.QtGui import (
|
||||
QPainter,
|
||||
QPdfWriter,
|
||||
QPen,
|
||||
QStandardItem,
|
||||
QStandardItemModel,
|
||||
QTextDocument,
|
||||
)
|
||||
from PySide6.QtPrintSupport import QPrintDialog, QPrinter
|
||||
@@ -64,7 +61,6 @@ from PySide6.QtWidgets import (
|
||||
QCalendarWidget,
|
||||
QCheckBox,
|
||||
QComboBox,
|
||||
QCompleter,
|
||||
QDialog,
|
||||
QDialogButtonBox,
|
||||
QDoubleSpinBox,
|
||||
@@ -85,9 +81,6 @@ from PySide6.QtWidgets import (
|
||||
QSizePolicy,
|
||||
QSpinBox,
|
||||
QSplitter,
|
||||
QStyle,
|
||||
QStyledItemDelegate,
|
||||
QStyleOptionViewItem,
|
||||
QTableWidget,
|
||||
QTableWidgetItem,
|
||||
QTabWidget,
|
||||
@@ -98,7 +91,6 @@ from PySide6.QtWidgets import (
|
||||
)
|
||||
|
||||
from .. import icons
|
||||
from ..design_system import clinical_stylesheet
|
||||
from ..diagnosis_terms import shared_terms
|
||||
from ..infinite_list import InfiniteList
|
||||
from ..theme import main_window_target_rect
|
||||
@@ -117,9 +109,9 @@ from ..widgets import (
|
||||
)
|
||||
from .diagnosis import DiagnosisDialog as _StructuredDiagnosisDialog
|
||||
|
||||
PRESCRIPTION_DRAWER_QSS = clinical_stylesheet(r"""
|
||||
PRESCRIPTION_DRAWER_QSS = r"""
|
||||
QFrame#PrescriptionDrawerSurface {
|
||||
color: $ds_text;
|
||||
color: #1A1C1F;
|
||||
background-color: #FFFFFF;
|
||||
border-left: 1px solid #EDEDEE;
|
||||
font-size: 14px;
|
||||
@@ -146,7 +138,7 @@ QLabel#PrescriptionLockTag {
|
||||
color: #BE4B58;
|
||||
background-color: #FEF0F0;
|
||||
border: 1px solid #FDE2E2;
|
||||
border-radius: $ds_radius_small;
|
||||
border-radius: 4px;
|
||||
padding: 2px 8px;
|
||||
font-size: 13px;
|
||||
}
|
||||
@@ -176,7 +168,7 @@ QLabel#PrescriptionDrawerMode {
|
||||
color: #4F63D9;
|
||||
background-color: #EEF1FA;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: $ds_radius_small;
|
||||
border-radius: 5px;
|
||||
padding: 4px 9px;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
@@ -190,7 +182,7 @@ QPushButton#PrescriptionDrawerClose {
|
||||
color: #606163;
|
||||
background-color: transparent;
|
||||
border: 0;
|
||||
border-radius: $ds_radius_control;
|
||||
border-radius: 7px;
|
||||
font-size: 22px;
|
||||
font-weight: 400;
|
||||
}
|
||||
@@ -209,12 +201,12 @@ QWidget#PrescriptionDrawerContent {
|
||||
QFrame#PrescriptionFormSection {
|
||||
background-color: #F7F7F7;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: $ds_radius_panel;
|
||||
border-radius: 10px;
|
||||
}
|
||||
QLabel#PrescriptionSectionTitle {
|
||||
color: #1A1C1F;
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
font-weight: 500;
|
||||
}
|
||||
QLabel#PrescriptionSectionHint {
|
||||
color: #6A6B6D;
|
||||
@@ -243,7 +235,7 @@ QLabel#PrescriptionUsageAux {
|
||||
QFrame#PrescriptionRpToolbar {
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: $ds_radius_panel;
|
||||
border-radius: 10px;
|
||||
}
|
||||
QFrame#PrescriptionRpMarker {
|
||||
background-color: #4F63D9;
|
||||
@@ -263,12 +255,12 @@ QLabel#PrescriptionRpLock {
|
||||
color: #BE4B58;
|
||||
background-color: #FEF3F2;
|
||||
border: 1px solid #FECDCA;
|
||||
border-radius: $ds_radius_small;
|
||||
border-radius: 5px;
|
||||
padding: 5px 8px;
|
||||
font-size: 13px;
|
||||
}
|
||||
QLabel#PrescriptionFormulaTag {
|
||||
border-radius: $ds_radius_small;
|
||||
border-radius: 4px;
|
||||
padding: 3px 8px;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
@@ -329,30 +321,19 @@ QFrame#PrescriptionDrawerSurface QDoubleSpinBox {
|
||||
color: #1A1C1F;
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: $ds_radius_control;
|
||||
border-radius: 7px;
|
||||
padding: 0 11px;
|
||||
selection-background-color: #C9D1F3;
|
||||
selection-color: #1A1C1F; font-size: 14px;
|
||||
selection-background-color: #EEF1FA; font-size: 14px;
|
||||
}
|
||||
QFrame#PrescriptionDrawerSurface QComboBox {
|
||||
min-height: 32px;
|
||||
color: #1A1C1F;
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: $ds_radius_control;
|
||||
border-radius: 7px;
|
||||
padding-left: 11px;
|
||||
padding-right: 28px;
|
||||
selection-background-color: #C9D1F3;
|
||||
selection-color: #1A1C1F; font-size: 14px;
|
||||
}
|
||||
QFrame#PrescriptionHerbTableRow QComboBox,
|
||||
QFrame#PrescriptionHerbTableRow QDoubleSpinBox {
|
||||
border: 1px solid #D2D2D3;
|
||||
font-weight: 500;
|
||||
}
|
||||
QFrame#PrescriptionHerbTableRow QComboBox:focus,
|
||||
QFrame#PrescriptionHerbTableRow QDoubleSpinBox:focus {
|
||||
border: 1px solid #4F63D9;
|
||||
selection-background-color: #EEF1FA; font-size: 14px;
|
||||
}
|
||||
QFrame#PrescriptionDrawerSurface QLineEdit[prescriptionControl="true"],
|
||||
QFrame#PrescriptionDrawerSurface QComboBox[prescriptionControl="true"],
|
||||
@@ -380,7 +361,7 @@ QFrame#PrescriptionDatePicker {
|
||||
min-height: 32px;
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: $ds_radius_control;
|
||||
border-radius: 7px;
|
||||
}
|
||||
QFrame#PrescriptionDatePicker:hover {
|
||||
border-color: #8B9AD9;
|
||||
@@ -447,7 +428,7 @@ QFrame#PrescriptionDrawerSurface QPushButton {
|
||||
color: #1A1C1F;
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: $ds_radius_control;
|
||||
border-radius: 7px;
|
||||
font-weight: 500;
|
||||
}
|
||||
QFrame#PrescriptionDrawerSurface QPushButton:hover {
|
||||
@@ -469,7 +450,7 @@ QFrame#PrescriptionDrawerSurface QPushButton#PrescriptionDrawerClose {
|
||||
color: #606163;
|
||||
background-color: transparent;
|
||||
border: 0;
|
||||
border-radius: $ds_radius_control;
|
||||
border-radius: 7px;
|
||||
font-size: 22px;
|
||||
font-weight: 400;
|
||||
}
|
||||
@@ -497,23 +478,23 @@ QFrame#PrescriptionDrawerSurface QPushButton[variant="primary"]:hover {
|
||||
border-color: #4156C4;
|
||||
}
|
||||
QFrame#PrescriptionDrawerSurface QPushButton[variant="success"] {
|
||||
color: $ds_accent;
|
||||
background-color: $ds_accent_soft;
|
||||
border-color: $ds_line;
|
||||
color: #FFFFFF;
|
||||
background-color: #287B65;
|
||||
border-color: #287B65;
|
||||
}
|
||||
QFrame#PrescriptionDrawerSurface QPushButton[variant="success"]:hover {
|
||||
background-color: $ds_accent_soft;
|
||||
border-color: $ds_focus;
|
||||
background-color: #287B65;
|
||||
border-color: #287B65;
|
||||
}
|
||||
QFrame#PrescriptionDrawerSurface QPushButton[variant="warning"] {
|
||||
color: $ds_accent;
|
||||
color: #A9691D;
|
||||
background-color: #FFFFFF;
|
||||
border-color: $ds_accent;
|
||||
border-color: #A9691D;
|
||||
}
|
||||
QFrame#PrescriptionDrawerSurface QPushButton[variant="warning"]:hover {
|
||||
color: $ds_accent_hover;
|
||||
background-color: $ds_accent_soft;
|
||||
border-color: $ds_focus;
|
||||
color: #FFFFFF;
|
||||
background-color: #A9691D;
|
||||
border-color: #A9691D;
|
||||
}
|
||||
QFrame#PrescriptionDrawerSurface QPushButton[variant="secondary"] {
|
||||
color: #4F63D9;
|
||||
@@ -616,8 +597,7 @@ QFrame#PrescriptionDrawerSurface QFrame#MessageBanner[kind="danger"] {
|
||||
QFrame#PrescriptionDrawerSurface QFrame#MessageBanner[kind="danger"] QLabel {
|
||||
color: #BE4B58;
|
||||
}
|
||||
QFrame#PrescriptionDrawerSurface QPushButton:focus { border: 1px solid $ds_focus; }
|
||||
""")
|
||||
"""
|
||||
|
||||
_CHEVRON_PATH: Path | None = None
|
||||
|
||||
@@ -649,7 +629,7 @@ def _prescription_drawer_qss() -> str:
|
||||
|
||||
|
||||
def _prescription_calendar_qss() -> str:
|
||||
return clinical_stylesheet("""
|
||||
return """
|
||||
QCalendarWidget {
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
@@ -674,13 +654,13 @@ QCalendarWidget QAbstractItemView:enabled {
|
||||
selection-color: #1A1C1F;
|
||||
outline: 0;
|
||||
}
|
||||
""")
|
||||
"""
|
||||
|
||||
|
||||
PRESCRIPTION_DIALOG_QSS = clinical_stylesheet("""
|
||||
PRESCRIPTION_DIALOG_QSS = """
|
||||
QDialog#PrescriptionDialogSurface {
|
||||
color: #1A1C1F;
|
||||
background-color: $ds_canvas;
|
||||
background-color: #F7F7F7;
|
||||
font-size: 14px;
|
||||
}
|
||||
QDialog#PrescriptionDialogSurface QLabel {
|
||||
@@ -742,7 +722,7 @@ QDialog#PrescriptionDialogSurface QTextBrowser {
|
||||
color: #1A1C1F;
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: $ds_radius_control;
|
||||
border-radius: 7px;
|
||||
selection-background-color: #EEF1FA;
|
||||
selection-color: #1A1C1F; font-size: 14px;
|
||||
}
|
||||
@@ -770,7 +750,7 @@ QDialog#PrescriptionDialogSurface QPushButton {
|
||||
color: #1A1C1F;
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: $ds_radius_control;
|
||||
border-radius: 7px;
|
||||
font-weight: 500;
|
||||
}
|
||||
QDialog#PrescriptionDialogSurface QPushButton:hover {
|
||||
@@ -800,7 +780,7 @@ QDialog#PrescriptionDialogSurface QPushButton:disabled {
|
||||
QDialog#PrescriptionDialogSurface QTabWidget::pane {
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: $ds_radius_panel;
|
||||
border-radius: 9px;
|
||||
top: -1px;
|
||||
}
|
||||
QDialog#PrescriptionDialogSurface QTabBar::tab {
|
||||
@@ -854,8 +834,7 @@ QDialog#PrescriptionDialogSurface QScrollBar::add-line:vertical,
|
||||
QDialog#PrescriptionDialogSurface QScrollBar::sub-line:vertical {
|
||||
height: 0;
|
||||
}
|
||||
QDialog#PrescriptionDialogSurface QPushButton:focus { border: 1px solid $ds_focus; }
|
||||
""")
|
||||
"""
|
||||
|
||||
|
||||
def _apply_prescription_dialog_style(dialog: QDialog) -> None:
|
||||
@@ -922,23 +901,6 @@ def _float(value: Any, default: float = 0.0) -> float:
|
||||
return default
|
||||
|
||||
|
||||
# 处方表单里的数字框、下拉框不响应鼠标滚轮:滚轮只滚动页面,
|
||||
# 避免医生滚动表单时把鼠标停在输入框上而误改剂量、药材或剂数。
|
||||
class NoWheelSpinBox(QSpinBox):
|
||||
def wheelEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual
|
||||
event.ignore()
|
||||
|
||||
|
||||
class NoWheelDoubleSpinBox(QDoubleSpinBox):
|
||||
def wheelEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual
|
||||
event.ignore()
|
||||
|
||||
|
||||
class NoWheelComboBox(QComboBox):
|
||||
def wheelEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual
|
||||
event.ignore()
|
||||
|
||||
|
||||
def _bool(value: Any) -> bool:
|
||||
if isinstance(value, str):
|
||||
return value.strip().lower() not in {"", "0", "false", "no", "off"}
|
||||
@@ -1450,47 +1412,6 @@ class MultiSelectComboBox(QComboBox):
|
||||
self.lineEdit().setText("、".join(self.values()))
|
||||
|
||||
|
||||
_MEDICINE_NAME_ROLE = Qt.ItemDataRole.UserRole + 1
|
||||
_MEDICINE_ID_ROLE = Qt.ItemDataRole.UserRole + 2
|
||||
_MEDICINE_META_ROLE = Qt.ItemDataRole.UserRole + 3
|
||||
|
||||
|
||||
class _MedicineSuggestionDelegate(QStyledItemDelegate):
|
||||
"""药材候选行:左侧药名,右侧灰色「调配中心 · 单位 · ID」,与管理端下拉一致。"""
|
||||
|
||||
def sizeHint(self, option: QStyleOptionViewItem, index: QModelIndex) -> QSize: # noqa: N802
|
||||
return QSize(super().sizeHint(option, index).width(), 36)
|
||||
|
||||
def paint(self, painter: QPainter, option: QStyleOptionViewItem, index: QModelIndex) -> None:
|
||||
opt = QStyleOptionViewItem(option)
|
||||
self.initStyleOption(opt, index)
|
||||
opt.text = ""
|
||||
widget = opt.widget
|
||||
(widget.style() if widget is not None else QApplication.style()).drawControl(
|
||||
QStyle.ControlElement.CE_ItemViewItem, opt, painter, widget
|
||||
)
|
||||
rect = option.rect.adjusted(14, 0, -14, 0)
|
||||
name = str(index.data(Qt.ItemDataRole.DisplayRole) or "")
|
||||
meta = str(index.data(_MEDICINE_META_ROLE) or "")
|
||||
enabled = bool(index.flags() & Qt.ItemFlag.ItemIsEnabled)
|
||||
metrics = option.fontMetrics
|
||||
align = Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft
|
||||
painter.save()
|
||||
if meta:
|
||||
name_width = int(rect.width() * 0.42)
|
||||
painter.setPen(QColor("#1A1C1F"))
|
||||
painter.drawText(rect.adjusted(0, 0, name_width - rect.width(), 0), align,
|
||||
metrics.elidedText(name, Qt.TextElideMode.ElideRight, name_width - 12))
|
||||
painter.setPen(QColor("#8A8B8D"))
|
||||
meta_rect = rect.adjusted(name_width, 0, 0, 0)
|
||||
painter.drawText(meta_rect, align,
|
||||
metrics.elidedText(meta, Qt.TextElideMode.ElideRight, meta_rect.width()))
|
||||
else:
|
||||
painter.setPen(QColor("#1A1C1F" if enabled else "#8A8B8D"))
|
||||
painter.drawText(rect, align, metrics.elidedText(name, Qt.TextElideMode.ElideRight, rect.width()))
|
||||
painter.restore()
|
||||
|
||||
|
||||
class RemoteMedicineComboBox(QComboBox):
|
||||
"""Editable remote medicine selector retaining both id and canonical name."""
|
||||
|
||||
@@ -1512,10 +1433,6 @@ class RemoteMedicineComboBox(QComboBox):
|
||||
# but no medicine id. New/changed text must still be selected from the
|
||||
# remote master-data list rather than submitted as arbitrary input.
|
||||
self._legacy_name = str(name or "").strip() if self._selected_id is None else ""
|
||||
# 最近一次有效选择(药材库 id + 规范名);手输文字无法匹配药材库时恢复为它。
|
||||
self._selected_name = str(name or "").strip() if self._selected_id is not None else ""
|
||||
self._last_valid: tuple[int | None, str] = (self._selected_id, str(name or "").strip())
|
||||
self._settle_pending = False
|
||||
self.setEditable(True)
|
||||
self.setInsertPolicy(QComboBox.InsertPolicy.NoInsert)
|
||||
self.setMaxVisibleItems(14)
|
||||
@@ -1523,23 +1440,6 @@ class RemoteMedicineComboBox(QComboBox):
|
||||
self.lineEdit().setPlaceholderText("搜索药材名称或拼音首字母")
|
||||
self.lineEdit().textEdited.connect(self._queue_search)
|
||||
self.currentIndexChanged.connect(self._selection_changed)
|
||||
# 与管理端 MedicineNameSelect 一致:点击或输入即弹出药材库匹配列表,
|
||||
# 只能从列表中选;列表不抢输入焦点,可边输入边看结果。
|
||||
self._suggestions = QStandardItemModel(self)
|
||||
self._completer = QCompleter(self._suggestions, self)
|
||||
self._completer.setCompletionMode(QCompleter.CompletionMode.UnfilteredPopupCompletion)
|
||||
self._completer.setCompletionRole(_MEDICINE_NAME_ROLE)
|
||||
self._completer.setMaxVisibleItems(14)
|
||||
self._completer.activated[QModelIndex].connect(self._suggestion_activated)
|
||||
popup = self._completer.popup()
|
||||
popup.setItemDelegate(_MedicineSuggestionDelegate(popup))
|
||||
popup.setStyleSheet(
|
||||
clinical_stylesheet("QListView { background-color: #FFFFFF; border: 1px solid #E4E7ED; border-radius: 6px;"
|
||||
" padding: 4px 0; font-size: 14px; outline: 0; }"
|
||||
"QListView::item:selected, QListView::item:hover { background-color: #F5F7FA; }")
|
||||
)
|
||||
self.lineEdit().setCompleter(self._completer)
|
||||
self.lineEdit().installEventFilter(self)
|
||||
self._timer = QTimer(self)
|
||||
self._timer.setSingleShot(True)
|
||||
self._timer.setInterval(250)
|
||||
@@ -1551,9 +1451,9 @@ class RemoteMedicineComboBox(QComboBox):
|
||||
|
||||
@property
|
||||
def medicine_id(self) -> int | None:
|
||||
# 只认从药材库选中的 id;不能回退到旧下拉项的 data,否则改过文字的行
|
||||
# 仍会带着原药材 id 通过校验,相当于允许直接输入药名。
|
||||
return self._selected_id
|
||||
data = self.currentData()
|
||||
value = _int(data, 0)
|
||||
return value or self._selected_id
|
||||
|
||||
@property
|
||||
def medicine_name(self) -> str:
|
||||
@@ -1562,16 +1462,12 @@ class RemoteMedicineComboBox(QComboBox):
|
||||
@property
|
||||
def has_valid_selection(self) -> bool:
|
||||
name = self.medicine_name
|
||||
if self._selected_id is not None:
|
||||
return not self._selected_name or name == self._selected_name
|
||||
return bool(self._legacy_name and name == self._legacy_name)
|
||||
return bool(self.medicine_id) or bool(self._legacy_name and name == self._legacy_name)
|
||||
|
||||
def set_value(self, medicine_id: Any, name: Any) -> None:
|
||||
self._selected_id = _int(medicine_id, 0) or None
|
||||
canonical_name = str(name or "").strip()
|
||||
self._legacy_name = canonical_name if self._selected_id is None else ""
|
||||
self._selected_name = canonical_name if self._selected_id is not None else ""
|
||||
self._last_valid = (self._selected_id, canonical_name)
|
||||
self.blockSignals(True)
|
||||
self.clear()
|
||||
if canonical_name:
|
||||
@@ -1582,117 +1478,20 @@ class RemoteMedicineComboBox(QComboBox):
|
||||
|
||||
def showPopup(self) -> None:
|
||||
if self.count() <= 1:
|
||||
# 只是打开列表浏览,不清除已选药材。
|
||||
self._queue_search(self.currentText())
|
||||
self._timer.stop()
|
||||
self._search(browse=self.has_valid_selection or not self.medicine_name)
|
||||
self._search()
|
||||
super().showPopup()
|
||||
|
||||
def _queue_search(self, _text: str) -> None:
|
||||
self._selected_id = None
|
||||
self._selected_name = ""
|
||||
self._legacy_name = ""
|
||||
self._timer.start()
|
||||
|
||||
def wheelEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual
|
||||
# 滚轮不切换药材,只滚动页面。
|
||||
event.ignore()
|
||||
|
||||
def eventFilter(self, watched: Any, event: Any) -> bool: # noqa: N802 - Qt virtual
|
||||
# 鼠标点一下输入框就列出药材库,和管理端下拉一样可以直接挑;
|
||||
# 不看焦点原因,已获得焦点时再点一次也能打开。
|
||||
if (
|
||||
watched is self.lineEdit()
|
||||
and event.type() == QEvent.Type.MouseButtonPress
|
||||
and self.isEnabled()
|
||||
and not self._completer.popup().isVisible()
|
||||
):
|
||||
self._timer.stop()
|
||||
self._search(browse=self.has_valid_selection or not self.medicine_name)
|
||||
return super().eventFilter(watched, event)
|
||||
|
||||
def focusOutEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual
|
||||
super().focusOutEvent(event)
|
||||
# 打开下拉列表也会让输入框失焦,此时还在挑选,不做校正。
|
||||
if (
|
||||
event.reason() == Qt.FocusReason.PopupFocusReason
|
||||
or self.view().isVisible()
|
||||
or self._completer.popup().isVisible()
|
||||
):
|
||||
return
|
||||
self._settle_typed_text()
|
||||
|
||||
def _suggestion_activated(self, index: QModelIndex) -> None:
|
||||
medicine_id = _int(index.data(_MEDICINE_ID_ROLE), 0)
|
||||
name = str(index.data(_MEDICINE_NAME_ROLE) or "").strip()
|
||||
if not medicine_id or not name:
|
||||
return
|
||||
for row in range(self.count()):
|
||||
data = self.itemData(row)
|
||||
if isinstance(data, Mapping) and _int(data.get("id"), 0) == medicine_id:
|
||||
self.setCurrentIndex(row)
|
||||
self._selection_changed(row)
|
||||
return
|
||||
self.set_value(medicine_id, name)
|
||||
|
||||
def _show_suggestions(self, rows: list[tuple[int, str, str]], note: str = "") -> None:
|
||||
self._suggestions.clear()
|
||||
for medicine_id, name, meta in rows:
|
||||
item = QStandardItem(name)
|
||||
item.setData(name, _MEDICINE_NAME_ROLE)
|
||||
item.setData(medicine_id, _MEDICINE_ID_ROLE)
|
||||
item.setData(meta, _MEDICINE_META_ROLE)
|
||||
item.setFlags(Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsSelectable)
|
||||
self._suggestions.appendRow(item)
|
||||
if note:
|
||||
# 提示行不可选,只告诉医生当前状态(搜索中 / 无匹配)。
|
||||
item = QStandardItem(note)
|
||||
item.setData(self.medicine_name, _MEDICINE_NAME_ROLE)
|
||||
item.setFlags(Qt.ItemFlag.NoItemFlags)
|
||||
self._suggestions.appendRow(item)
|
||||
if self.lineEdit().hasFocus() and self.isEnabled():
|
||||
self._completer.complete()
|
||||
|
||||
def _settle_typed_text(self) -> None:
|
||||
"""离开输入框时,手输文字必须落到药材库中的一味药,否则恢复原值。"""
|
||||
if self.has_valid_selection:
|
||||
return
|
||||
text = self.medicine_name
|
||||
if text and self._select_exact(text):
|
||||
return
|
||||
if not text:
|
||||
self._restore_last_valid()
|
||||
return
|
||||
# 搜索结果可能还没回来:立即按当前文字查一次,结果到达后再定。
|
||||
self._settle_pending = True
|
||||
self._timer.stop()
|
||||
self._search()
|
||||
|
||||
def _select_exact(self, text: str) -> bool:
|
||||
key = "".join(text.split()).casefold()
|
||||
for row in range(self.count()):
|
||||
data = self.itemData(row)
|
||||
if isinstance(data, Mapping) and "".join(str(data.get("name") or "").split()).casefold() == key:
|
||||
self.setCurrentIndex(row)
|
||||
self._selection_changed(row)
|
||||
return True
|
||||
return False
|
||||
|
||||
def _restore_last_valid(self) -> None:
|
||||
medicine_id, name = self._last_valid
|
||||
if medicine_id is not None or name:
|
||||
self.set_value(medicine_id, name)
|
||||
return
|
||||
self.blockSignals(True)
|
||||
self.setEditText("")
|
||||
self.blockSignals(False)
|
||||
|
||||
def _search(self, browse: bool = False) -> None:
|
||||
# browse:点开下拉时按空关键字列出药材库,与管理端打开下拉的行为一致。
|
||||
query = "" if browse else self.currentText().strip()
|
||||
def _search(self) -> None:
|
||||
query = self.currentText().strip()
|
||||
self._generation += 1
|
||||
generation = self._generation
|
||||
if self.lineEdit().hasFocus() and self._suggestions.rowCount() == 0:
|
||||
self._show_suggestions([], "正在搜索药材库…")
|
||||
run_async(
|
||||
lambda: _repository_action(
|
||||
self.repository,
|
||||
@@ -1711,7 +1510,6 @@ class RemoteMedicineComboBox(QComboBox):
|
||||
return
|
||||
rows = page_items(result)
|
||||
current_text = self.currentText().strip()
|
||||
suggestions: list[tuple[int, str, str]] = []
|
||||
self.blockSignals(True)
|
||||
self.clear()
|
||||
for row in rows:
|
||||
@@ -1726,23 +1524,11 @@ class RemoteMedicineComboBox(QComboBox):
|
||||
if meta:
|
||||
label = f"{name} {meta}"
|
||||
self.addItem(label, {"id": medicine_id, "name": name})
|
||||
suggestions.append((medicine_id, name, meta))
|
||||
self.setEditText(current_text or query)
|
||||
self.blockSignals(False)
|
||||
self._show_suggestions(
|
||||
suggestions,
|
||||
"" if suggestions else f"药材库中没有与「{query}」匹配的药材,请换个名称或拼音首字母",
|
||||
)
|
||||
if self._settle_pending and not self.hasFocus():
|
||||
self._settle_pending = False
|
||||
if not self._select_exact(query):
|
||||
self._restore_last_valid()
|
||||
|
||||
def _search_error(self, error: Exception, generation: int) -> None:
|
||||
if generation == self._generation:
|
||||
if self._settle_pending and not self.hasFocus():
|
||||
self._settle_pending = False
|
||||
self._restore_last_valid()
|
||||
self.search_failed.emit(friendly_error(error))
|
||||
|
||||
def _selection_changed(self, index: int) -> None:
|
||||
@@ -1752,9 +1538,9 @@ class RemoteMedicineComboBox(QComboBox):
|
||||
name = str(data.get("name") or "").strip()
|
||||
if name:
|
||||
self._legacy_name = ""
|
||||
self._selected_name = name
|
||||
self._last_valid = (self._selected_id, name)
|
||||
self.setEditText(name)
|
||||
else:
|
||||
self._selected_id = _int(data, 0) or self._selected_id
|
||||
|
||||
|
||||
class HerbRowWidget(QFrame):
|
||||
@@ -1789,7 +1575,7 @@ class HerbRowWidget(QFrame):
|
||||
if source_locked is None
|
||||
else bool(source_locked)
|
||||
)
|
||||
self.formula_combo = NoWheelComboBox(self)
|
||||
self.formula_combo = QComboBox(self)
|
||||
self.formula_combo.addItem("主方", "主方")
|
||||
self.formula_combo.addItem("辅方", "辅方")
|
||||
_set_combo_data(
|
||||
@@ -1805,7 +1591,7 @@ class HerbRowWidget(QFrame):
|
||||
parent=self,
|
||||
)
|
||||
self.medicine.setEnabled(not locked)
|
||||
self.dosage = NoWheelDoubleSpinBox(self)
|
||||
self.dosage = QDoubleSpinBox(self)
|
||||
self.dosage.setRange(0, 1e100)
|
||||
self.dosage.setDecimals(1)
|
||||
self.dosage.setSingleStep(0.5)
|
||||
@@ -2387,7 +2173,7 @@ class PrescriptionTemplateDialog(QDialog):
|
||||
self.name_edit.setMaxLength(100)
|
||||
self.name_edit.setPlaceholderText("请输入处方名称")
|
||||
form.addRow("处方名称", self.name_edit)
|
||||
self.formula_combo = NoWheelComboBox()
|
||||
self.formula_combo = QComboBox()
|
||||
self.formula_combo.addItem("主方", "主方")
|
||||
self.formula_combo.addItem("辅方", "辅方")
|
||||
_set_combo_data(
|
||||
@@ -2507,7 +2293,7 @@ class TemplateImportDialog(QDialog):
|
||||
self.name_edit.setPlaceholderText("请输入处方名称搜索")
|
||||
self.name_edit.returnPressed.connect(self.search)
|
||||
filters.addWidget(self.name_edit, 1)
|
||||
self.formula_combo = NoWheelComboBox()
|
||||
self.formula_combo = QComboBox()
|
||||
self.formula_combo.addItem("全部", "")
|
||||
self.formula_combo.addItem("主方", "主方")
|
||||
self.formula_combo.addItem("辅方", "辅方")
|
||||
@@ -2518,7 +2304,7 @@ class TemplateImportDialog(QDialog):
|
||||
root.addLayout(filters)
|
||||
mode_layout = QHBoxLayout()
|
||||
mode_layout.addWidget(QLabel("导入方式"))
|
||||
self.mode_combo = NoWheelComboBox()
|
||||
self.mode_combo = QComboBox()
|
||||
self.mode_combo.addItem("覆盖现有药材", "replace")
|
||||
self.mode_combo.addItem("追加到末尾", "append")
|
||||
mode_layout.addWidget(self.mode_combo)
|
||||
@@ -2725,7 +2511,7 @@ class PasteHerbsDialog(QDialog):
|
||||
root.addWidget(self.text_edit, 1)
|
||||
mode_row = QHBoxLayout()
|
||||
mode_row.addWidget(QLabel("导入方式"))
|
||||
self.mode_combo = NoWheelComboBox()
|
||||
self.mode_combo = QComboBox()
|
||||
self.mode_combo.addItem("覆盖现有药材", "replace")
|
||||
self.mode_combo.addItem("追加到末尾", "append")
|
||||
mode_row.addWidget(self.mode_combo)
|
||||
@@ -2949,8 +2735,8 @@ class PrescriptionEditorDialog(QDialog):
|
||||
self.revive_banner = MessageBanner()
|
||||
self.body_layout.addWidget(self.revive_banner)
|
||||
|
||||
self._responsive_grids: list[tuple[QGridLayout, int, list[tuple[QWidget, int]]]] = []
|
||||
self._form_columns = 3
|
||||
self._responsive_grids: list[tuple[QGridLayout, int, list[tuple[QWidget, int]]]] = []
|
||||
self._form_columns = 3
|
||||
self.patient_section = self._build_patient_section()
|
||||
self.diagnosis_section = self._build_diagnosis_section()
|
||||
self.herbs_section = self._build_herbs_section()
|
||||
@@ -3192,7 +2978,7 @@ class PrescriptionEditorDialog(QDialog):
|
||||
gender_layout.addWidget(self.gender_female)
|
||||
gender_layout.addStretch(1)
|
||||
self.gender = gender_host
|
||||
self.age = NoWheelSpinBox()
|
||||
self.age = QSpinBox()
|
||||
self.age.setRange(0, 150)
|
||||
self.visit_no = QLineEdit()
|
||||
self.visit_no.setPlaceholderText("自动生成或手动输入")
|
||||
@@ -3344,7 +3130,7 @@ class PrescriptionEditorDialog(QDialog):
|
||||
for value in self.PRESCRIPTION_TYPES:
|
||||
self.prescription_type.addItem(value, value)
|
||||
self.prescription_type.currentIndexChanged.connect(self._type_changed)
|
||||
self.dose_count = NoWheelSpinBox()
|
||||
self.dose_count = QSpinBox()
|
||||
self.dose_count.setRange(1, 2_147_483_647)
|
||||
self.dose_unit = SelectComboBox()
|
||||
self.dose_unit.addItems(["剂", "丸", "袋", "盒", "瓶", "膏", "贴"])
|
||||
@@ -3367,9 +3153,9 @@ class PrescriptionEditorDialog(QDialog):
|
||||
self.dosage_bag_count = LabeledIntCombo(range(1, 6), "袋")
|
||||
self.need_decoction = BoolRadioRow("代煎", "不代煎")
|
||||
self.bags_per_dose = LabeledIntCombo(range(1, 10), "包")
|
||||
self.times_per_day = NoWheelSpinBox()
|
||||
self.times_per_day = QSpinBox()
|
||||
self.times_per_day.setRange(1, 6)
|
||||
self.usage_days = NoWheelSpinBox()
|
||||
self.usage_days = QSpinBox()
|
||||
self.usage_days.setRange(1, 365)
|
||||
self._main_dosage_field = self._field("用量", self.dosage_amount)
|
||||
self._main_dosage_unit_field = self._field("用量单位", self.dosage_unit)
|
||||
@@ -3402,9 +3188,9 @@ class PrescriptionEditorDialog(QDialog):
|
||||
self.aux_dosage_bag_count = LabeledIntCombo(range(1, 6), "袋")
|
||||
self.aux_need_decoction = BoolRadioRow("代煎", "不代煎")
|
||||
self.aux_bags_per_dose = LabeledIntCombo(range(1, 10), "包")
|
||||
self.aux_times_per_day = NoWheelSpinBox()
|
||||
self.aux_times_per_day = QSpinBox()
|
||||
self.aux_times_per_day.setRange(1, 6)
|
||||
self.aux_usage_days = NoWheelSpinBox()
|
||||
self.aux_usage_days = QSpinBox()
|
||||
self.aux_usage_days.setRange(1, 365)
|
||||
self.aux_prescription_name = QLineEdit()
|
||||
self._aux_dosage_field = self._field("用量", self.aux_dosage_amount)
|
||||
@@ -4178,7 +3964,7 @@ class PatchPatientDialog(QDialog):
|
||||
self.patient_name = QLineEdit(str(first_value(prescription, "patient_name", default="")))
|
||||
self.patient_name.setMaxLength(50)
|
||||
form.addRow("患者姓名 *", self.patient_name)
|
||||
self.gender = NoWheelComboBox()
|
||||
self.gender = QComboBox()
|
||||
self.gender.addItem("男", 1)
|
||||
self.gender.addItem("女", 0)
|
||||
_set_combo_data(self.gender, first_value(prescription, "gender", default=1))
|
||||
@@ -5295,8 +5081,8 @@ class PrescriptionDetailDialog(QDialog):
|
||||
self.preview.setObjectName("PrescriptionPaperPreview")
|
||||
self.preview.setOpenExternalLinks(False)
|
||||
self.preview.setStyleSheet(
|
||||
clinical_stylesheet("QTextBrowser#PrescriptionPaperPreview {"
|
||||
"background-color:#F7F7F7; border:1px solid #E4E4E5; padding:0;}")
|
||||
"QTextBrowser#PrescriptionPaperPreview {"
|
||||
"background-color:#F7F7F7; border:1px solid #E4E4E5; padding:0;}"
|
||||
)
|
||||
self.preview.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
|
||||
self.preview.setDocument(self.document)
|
||||
@@ -5304,8 +5090,8 @@ class PrescriptionDetailDialog(QDialog):
|
||||
self.user_preview.setObjectName("PrescriptionUserPaperPreview")
|
||||
self.user_preview.setOpenExternalLinks(False)
|
||||
self.user_preview.setStyleSheet(
|
||||
clinical_stylesheet("QTextBrowser#PrescriptionUserPaperPreview {"
|
||||
"background-color:#F7F7F7; border:1px solid #E4E4E5; padding:0;}")
|
||||
"QTextBrowser#PrescriptionUserPaperPreview {"
|
||||
"background-color:#F7F7F7; border:1px solid #E4E4E5; padding:0;}"
|
||||
)
|
||||
self.user_preview.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
|
||||
self.user_preview.setDocument(self.user_document)
|
||||
@@ -5323,8 +5109,8 @@ class PrescriptionDetailDialog(QDialog):
|
||||
self.case_preview.setObjectName("CaseRecordPaperPreview")
|
||||
self.case_preview.setOpenExternalLinks(False)
|
||||
self.case_preview.setStyleSheet(
|
||||
clinical_stylesheet("QTextBrowser#CaseRecordPaperPreview {"
|
||||
"background-color:#F7F7F7; border:1px solid #E4E4E5; padding:0;}")
|
||||
"QTextBrowser#CaseRecordPaperPreview {"
|
||||
"background-color:#F7F7F7; border:1px solid #E4E4E5; padding:0;}"
|
||||
)
|
||||
self.case_preview.setDocument(self.case_document)
|
||||
case_index = self.tabs.addTab(self.case_preview, "详细病历")
|
||||
@@ -5525,7 +5311,7 @@ class PrescriptionOrderDialog(QDialog):
|
||||
|
||||
def _build_recipient_tab(self) -> QWidget:
|
||||
tab, form = self._form_tab()
|
||||
self.diagnosis_id = NoWheelSpinBox()
|
||||
self.diagnosis_id = QSpinBox()
|
||||
self.diagnosis_id.setRange(0, 2_000_000_000)
|
||||
self.diagnosis_id.valueChanged.connect(self._diagnosis_changed)
|
||||
form.addRow("诊单 ID *", self.diagnosis_id)
|
||||
@@ -5547,14 +5333,14 @@ class PrescriptionOrderDialog(QDialog):
|
||||
|
||||
def _build_service_tab(self) -> QWidget:
|
||||
tab, form = self._form_tab()
|
||||
self.ship_mode = NoWheelComboBox()
|
||||
self.ship_mode = QComboBox()
|
||||
self.ship_mode.addItem("甘草药房", "gancao")
|
||||
self.ship_mode.addItem("洛阳药房", "direct")
|
||||
self.ship_mode.setEnabled(self.can_select_ship_mode)
|
||||
form.addRow("发货类型", self.ship_mode)
|
||||
self.is_follow_up = QCheckBox("复诊订单")
|
||||
form.addRow("是否复诊", self.is_follow_up)
|
||||
self.medication_days = NoWheelSpinBox()
|
||||
self.medication_days = QSpinBox()
|
||||
self.medication_days.setRange(0, 365)
|
||||
self.medication_days.setSpecialValueText("未填写")
|
||||
form.addRow("服用天数", self.medication_days)
|
||||
@@ -5579,7 +5365,7 @@ class PrescriptionOrderDialog(QDialog):
|
||||
|
||||
def _build_amount_tab(self) -> QWidget:
|
||||
tab, form = self._form_tab()
|
||||
self.fee_type = NoWheelComboBox()
|
||||
self.fee_type = QComboBox()
|
||||
self.fee_type.addItem("药品费用", 3)
|
||||
self.fee_type.addItem("挂号费", 1)
|
||||
self.fee_type.addItem("问诊费", 2)
|
||||
@@ -5587,12 +5373,12 @@ class PrescriptionOrderDialog(QDialog):
|
||||
self.fee_type.addItem("尾款", 5)
|
||||
self.fee_type.addItem("其他", 6)
|
||||
form.addRow("费用类别 *", self.fee_type)
|
||||
self.amount = NoWheelDoubleSpinBox()
|
||||
self.amount = QDoubleSpinBox()
|
||||
self.amount.setRange(0, 10_000_000)
|
||||
self.amount.setDecimals(2)
|
||||
self.amount.setPrefix("¥ ")
|
||||
form.addRow("订单金额 *", self.amount)
|
||||
self.internal_cost = NoWheelDoubleSpinBox(tab)
|
||||
self.internal_cost = QDoubleSpinBox(tab)
|
||||
self.internal_cost.setRange(0, 10_000_000)
|
||||
self.internal_cost.setDecimals(2)
|
||||
self.internal_cost.setPrefix("¥ ")
|
||||
|
||||
@@ -26,7 +26,6 @@ from PySide6.QtWidgets import (
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from ..design_system import clinical_stylesheet
|
||||
from ..report_provenance import report_provenance_lines
|
||||
from ..theme import apply_reading_rhythm
|
||||
from ..widgets import (
|
||||
@@ -120,28 +119,10 @@ def preferred_ai_model(content: str = "", *, entry: str = "diagnosis") -> str:
|
||||
return "qwen" if entry in {"prescription", "diagnosis"} else "openai"
|
||||
|
||||
|
||||
DIAGNOSIS_TASK_TITLES = {
|
||||
"case_analysis": "病历分析",
|
||||
"glucose_trend": "血糖趋势",
|
||||
"medication_review": "用药评估",
|
||||
"complication_risk": "并发症风险",
|
||||
"summary": "问诊小结",
|
||||
"lifestyle_advice": "健康建议",
|
||||
}
|
||||
|
||||
|
||||
def diagnosis_ai_task(prompt: str) -> str:
|
||||
"""Map a user-facing question to the server assistant's stable task key."""
|
||||
|
||||
text = prompt.strip().lower()
|
||||
if any(marker in text for marker in ("分析病历", "分析当前病历", "当前病历给出辨证与病情摘要")):
|
||||
return "case_analysis"
|
||||
if any(marker in text for marker in ("血糖控制", "血糖趋势", "血糖记录", "glucose")):
|
||||
return "glucose_trend"
|
||||
if any(marker in text for marker in ("问诊小结", "问诊摘要")):
|
||||
return "summary"
|
||||
if any(marker in text for marker in ("健康建议", "生活方式建议", "lifestyle")):
|
||||
return "lifestyle_advice"
|
||||
if any(marker in text for marker in ("并发症", "complication")):
|
||||
return "complication_risk"
|
||||
if any(marker in text for marker in ("指南", "共识", "guideline")):
|
||||
@@ -152,28 +133,19 @@ def diagnosis_ai_task(prompt: str) -> str:
|
||||
return "prescription_review"
|
||||
if any(marker in text for marker in ("用药", "药物", "中药", "medication")):
|
||||
return "medication_review"
|
||||
has_tcm_intent = any(marker in text for marker in ("中医", "辨证", "证候", "舌象", "脉象", "tcm"))
|
||||
wants_full_report = (
|
||||
any(marker in text for marker in ("完整", "full", "complete"))
|
||||
and any(marker in text for marker in ("报告", "report"))
|
||||
)
|
||||
if has_tcm_intent and ("tcm_pattern" in text or wants_full_report):
|
||||
if any(marker in text for marker in ("辨证", "证候", "舌象", "脉象", "tcm")):
|
||||
return "tcm_pattern"
|
||||
# A summary may mention evidence such as 证候 without requesting a full
|
||||
# TCM report. Specific clinical tasks above still take precedence.
|
||||
if any(marker in text for marker in ("总结", "概括", "摘要", "summary")):
|
||||
return "summary"
|
||||
if has_tcm_intent:
|
||||
return "tcm_pattern"
|
||||
if any(marker in text for marker in ("风险", "预后", "急症", "risk")):
|
||||
return "complication_risk"
|
||||
return "custom"
|
||||
|
||||
|
||||
PRESCRIPTION_AI_QSS = clinical_stylesheet("""
|
||||
PRESCRIPTION_AI_QSS = """
|
||||
QDialog#PrescriptionAiDialog {
|
||||
color: $ds_text;
|
||||
background-color: $ds_canvas;
|
||||
color: #1A1C1F;
|
||||
background-color: #F7F7F7;
|
||||
|
||||
font-size: 13px;
|
||||
}
|
||||
@@ -183,7 +155,7 @@ QDialog#PrescriptionAiDialog QPushButton {
|
||||
color: #1A1C1F;
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: $ds_radius_control;
|
||||
border-radius: 7px;
|
||||
font-weight: 500;
|
||||
}
|
||||
QDialog#PrescriptionAiDialog QPushButton:hover {
|
||||
@@ -225,7 +197,7 @@ QLabel#PrescriptionAiSubtitle {
|
||||
QFrame#PrescriptionAiSnapshot {
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: $ds_radius_panel;
|
||||
border-radius: 10px;
|
||||
}
|
||||
QLabel#PrescriptionAiSnapshotLabel {
|
||||
color: #1A1C1F;
|
||||
@@ -233,20 +205,20 @@ QLabel#PrescriptionAiSnapshotLabel {
|
||||
font-weight: 600;
|
||||
}
|
||||
QLabel#PrescriptionAiSnapshotBody {
|
||||
color: $ds_text;
|
||||
font-size: 14px;
|
||||
color: #1A1C1F;
|
||||
font-size: 13px;
|
||||
line-height: 1.65;
|
||||
}
|
||||
QFrame#PrescriptionAiSummary {
|
||||
background-color: $ds_accent_soft;
|
||||
background-color: #F0F0F0;
|
||||
border: 0;
|
||||
border-left: 3px solid #4F63D9;
|
||||
border-radius: $ds_radius_control;
|
||||
border-radius: 0 9px 9px 0;
|
||||
}
|
||||
QFrame#PrescriptionAiCaution {
|
||||
background-color: #FFF9EE;
|
||||
border: 1px solid #F3DFB5;
|
||||
border-radius: $ds_radius_control;
|
||||
border-radius: 9px;
|
||||
}
|
||||
QLabel#PrescriptionAiSectionTitle {
|
||||
color: #1A1C1F;
|
||||
@@ -254,17 +226,17 @@ QLabel#PrescriptionAiSectionTitle {
|
||||
font-weight: 600;
|
||||
}
|
||||
QLabel#PrescriptionAiBody {
|
||||
color: $ds_text;
|
||||
font-size: 14px;
|
||||
color: #1A1C1F;
|
||||
font-size: 13px;
|
||||
line-height: 1.75;
|
||||
}
|
||||
QTextBrowser#PrescriptionAiAnswer {
|
||||
color: $ds_text;
|
||||
color: #1A1C1F;
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: $ds_radius_panel;
|
||||
padding: 16px 18px;
|
||||
selection-color: $ds_text;
|
||||
border-radius: 10px;
|
||||
padding: 12px 14px;
|
||||
selection-color: #1A1C1F;
|
||||
selection-background-color: #EEF1FA;
|
||||
}
|
||||
QLabel#PrescriptionAiMuted {
|
||||
@@ -280,7 +252,7 @@ QFrame#PrescriptionAiMeta {
|
||||
QDialog#PrescriptionAiDialog QTabWidget::pane {
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: $ds_radius_panel;
|
||||
border-radius: 10px;
|
||||
top: -1px;
|
||||
}
|
||||
QDialog#PrescriptionAiDialog QTabBar::tab {
|
||||
@@ -310,7 +282,7 @@ QDialog#PrescriptionAiDialog QTextEdit {
|
||||
color: #1A1C1F;
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: $ds_radius_control;
|
||||
border-radius: 8px;
|
||||
padding: 10px;
|
||||
selection-background-color: #EEF1FA;
|
||||
}
|
||||
@@ -331,12 +303,10 @@ QDialog#PrescriptionAiDialog QScrollBar::add-line:vertical,
|
||||
QDialog#PrescriptionAiDialog QScrollBar::sub-line:vertical {
|
||||
height: 0;
|
||||
}
|
||||
QDialog#PrescriptionAiDialog QPushButton:focus { border: 1px solid $ds_focus; }
|
||||
QDialog#PrescriptionAiDialog QPushButton:disabled { color: $ds_disabled; background-color: $ds_disabled_surface; border-color: $ds_line; }
|
||||
""")
|
||||
"""
|
||||
|
||||
_AI_ANSWER_DOCUMENT_CSS = clinical_stylesheet(
|
||||
"body { color:$ds_text; font-size:14px; line-height:1.72; } "
|
||||
_AI_ANSWER_DOCUMENT_CSS = (
|
||||
"body { color:#1A1C1F; font-size:14px; line-height:1.72; } "
|
||||
"h1 { color:#1A1C1F; font-size:20px; margin:14px 0 8px; line-height:1.4; } "
|
||||
"h2 { color:#1A1C1F; font-size:17px; margin:14px 0 7px; line-height:1.42; } "
|
||||
"h3,h4 { color:#1A1C1F; font-size:15px; margin:12px 0 6px; line-height:1.45; } "
|
||||
@@ -804,7 +774,7 @@ class PrescriptionAiReportDialog(QDialog):
|
||||
self.report_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
|
||||
self.host = QWidget()
|
||||
self.host_layout = QVBoxLayout(self.host)
|
||||
self.host_layout.setContentsMargins(18, 14, 20, 16)
|
||||
self.host_layout.setContentsMargins(4, 4, 12, 8)
|
||||
self.host_layout.setSpacing(12)
|
||||
self.report_scroll.setWidget(self.host)
|
||||
self.tabs.widget(0).layout().addWidget(self.report_scroll)
|
||||
@@ -1458,7 +1428,7 @@ class PrescriptionAiReportDialog(QDialog):
|
||||
label.setTextFormat(Qt.TextFormat.PlainText)
|
||||
label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
|
||||
label.setWordWrap(True)
|
||||
label.setStyleSheet(clinical_stylesheet("color: $ds_muted; font-size: 12px; padding: 10px 14px; background: $ds_surface_alt; border: 1px solid $ds_line; border-radius: $ds_radius_control;"))
|
||||
label.setStyleSheet("color: #555B68; font-size: 12px; padding: 10px 14px; background: #F7F8FC; border: 1px solid #E4E8F2; border-radius: 8px;")
|
||||
self.host_layout.addWidget(label)
|
||||
|
||||
def reject(self) -> None:
|
||||
|
||||
@@ -8,7 +8,6 @@ from PySide6.QtCore import QObject, QSize, Qt, Signal
|
||||
from PySide6.QtWidgets import QApplication, QPushButton, QWidget
|
||||
|
||||
from . import icons
|
||||
from .design_system import PALETTE, clinical_stylesheet
|
||||
|
||||
|
||||
class FilterDisclosure(QObject):
|
||||
@@ -36,17 +35,17 @@ class FilterDisclosure(QObject):
|
||||
self.button.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||
self.button.setFixedHeight(32)
|
||||
self.button.setIconSize(QSize(14, 14))
|
||||
self.button.setStyleSheet(clinical_stylesheet("""
|
||||
self.button.setStyleSheet("""
|
||||
QPushButton#FilterDisclosureButton {
|
||||
color: #1769E8; background: #FFFFFF; border: 1px solid #DBE5F2;
|
||||
border-radius: $ds_radius_control; padding: 0 11px; min-height: 30px; max-height: 30px;
|
||||
border-radius: 6px; padding: 0 11px; min-height: 30px; max-height: 30px;
|
||||
min-width: 92px; font-size: 13px; font-weight: 400;
|
||||
}
|
||||
QPushButton#FilterDisclosureButton:hover { background: $ds_canvas; border-color: $ds_line_strong; }
|
||||
QPushButton#FilterDisclosureButton:checked { background: $ds_accent_soft; border-color: $ds_line_strong; }
|
||||
QPushButton#FilterDisclosureButton:focus { border-color: $ds_focus; }
|
||||
QPushButton#FilterDisclosureButton:disabled { color: $ds_disabled; border-color: $ds_line; }
|
||||
"""))
|
||||
QPushButton#FilterDisclosureButton:hover { background: #F3F7FD; border-color: #ADC8F2; }
|
||||
QPushButton#FilterDisclosureButton:checked { background: #EAF2FF; border-color: #ADC8F2; }
|
||||
QPushButton#FilterDisclosureButton:focus { border-color: #1769E8; }
|
||||
QPushButton#FilterDisclosureButton:disabled { color: #8B97A8; border-color: #E3E9F1; }
|
||||
""")
|
||||
self.button.toggled.connect(self.set_expanded)
|
||||
self._apply()
|
||||
|
||||
@@ -79,4 +78,4 @@ class FilterDisclosure(QObject):
|
||||
self.button.setAccessibleName(label)
|
||||
self.button.setAccessibleDescription("显示或收起检索条件和统计信息;收起保留当前筛选条件")
|
||||
self.button.setToolTip("收起保留当前筛选条件" if self._expanded else "展开检索条件和统计信息,当前筛选条件保持不变")
|
||||
self.button.setIcon(icons.icon("chevron_up" if self._expanded else "chevron_down", PALETTE["accent"], 14))
|
||||
self.button.setIcon(icons.icon("chevron_up" if self._expanded else "chevron_down", "#1769E8", 14))
|
||||
|
||||
@@ -228,11 +228,6 @@ def _message(p: QPainter, w: float) -> None:
|
||||
|
||||
# --- Shell chrome ---------------------------------------------------------
|
||||
|
||||
@_glyph("more", "ellipsis")
|
||||
def _more(p: QPainter, w: float) -> None:
|
||||
for x in (5.0, 12.0, 19.0):
|
||||
_dot(p, x, 12.0, 1.5)
|
||||
|
||||
|
||||
@_glyph("fold", "panel_close")
|
||||
def _fold(p: QPainter, w: float) -> None:
|
||||
|
||||
@@ -16,7 +16,6 @@ from PySide6.QtWidgets import (
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from .design_system import clinical_stylesheet
|
||||
from .widgets import first_value, get_value, page_items, page_total, run_async
|
||||
|
||||
|
||||
@@ -55,16 +54,16 @@ class InfiniteList(QWidget):
|
||||
layout = QHBoxLayout(self)
|
||||
layout.setContentsMargins(12, 0, 12, 0)
|
||||
self.summary_label = QLabel("", self)
|
||||
self.summary_label.setStyleSheet(clinical_stylesheet(
|
||||
self.summary_label.setStyleSheet(
|
||||
"color: #5D6B80; font-size: 12px; background: transparent;"
|
||||
))
|
||||
)
|
||||
layout.addWidget(self.summary_label)
|
||||
layout.addStretch(1)
|
||||
self.retry_button = QPushButton("加载失败,点击重试", self)
|
||||
self.retry_button.setFlat(True)
|
||||
self.retry_button.setStyleSheet(clinical_stylesheet(
|
||||
self.retry_button.setStyleSheet(
|
||||
"color: #1769E8; font-size: 12px; padding: 0 4px; border: none; background: transparent; min-height: 20px; max-height: 20px; min-width: 0;"
|
||||
))
|
||||
)
|
||||
self.retry_button.hide()
|
||||
self.retry_button.clicked.connect(self.retry)
|
||||
layout.addWidget(self.retry_button)
|
||||
|
||||
@@ -5,21 +5,26 @@ from __future__ import annotations
|
||||
from contextlib import suppress
|
||||
from typing import Any
|
||||
|
||||
from PySide6.QtCore import QEvent, QPoint, QPointF, QRectF, QSettings, Qt, QTimer, Signal
|
||||
from PySide6.QtCore import QPoint, QPointF, QRectF, QSettings, Qt, QTimer, Signal
|
||||
from PySide6.QtGui import (
|
||||
QBrush,
|
||||
QColor,
|
||||
QFont,
|
||||
QIcon,
|
||||
QLinearGradient,
|
||||
QPainter,
|
||||
QPainterPath,
|
||||
QPen,
|
||||
QPixmap,
|
||||
QPolygonF,
|
||||
QRadialGradient,
|
||||
QResizeEvent,
|
||||
)
|
||||
from PySide6.QtWidgets import (
|
||||
QApplication,
|
||||
QCheckBox,
|
||||
QFrame,
|
||||
QGraphicsDropShadowEffect,
|
||||
QHBoxLayout,
|
||||
QLabel,
|
||||
QLayout,
|
||||
@@ -40,7 +45,6 @@ from doctor_workstation import __version__
|
||||
from doctor_workstation.resources import app_icon_path, brand_lockup_path
|
||||
|
||||
from . import icons
|
||||
from .design_system import PALETTE, clinical_stylesheet
|
||||
from .widgets import BusyOverlay, MessageBanner, friendly_error, invoke, run_async
|
||||
|
||||
|
||||
@@ -123,7 +127,7 @@ def _round_pen(color: QColor | str, width: float) -> QPen:
|
||||
|
||||
|
||||
class _BrandPanel(QWidget):
|
||||
"""A flat, readable introduction to the clinician's daily workflow."""
|
||||
"""The quiet medical illustration and copy from the supplied login artwork."""
|
||||
|
||||
def __init__(self, parent: QWidget | None = None) -> None:
|
||||
super().__init__(parent)
|
||||
@@ -133,76 +137,228 @@ class _BrandPanel(QWidget):
|
||||
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
|
||||
self._brand_lockup = QPixmap(str(brand_lockup_path()))
|
||||
|
||||
@staticmethod
|
||||
def _draw_cube(painter: QPainter, center: QPointF, size: float, kind: str) -> None:
|
||||
x, y = center.x(), center.y()
|
||||
top = QPolygonF(
|
||||
[
|
||||
QPointF(x, y - size * 0.58),
|
||||
QPointF(x + size * 0.48, y - size * 0.34),
|
||||
QPointF(x, y - size * 0.10),
|
||||
QPointF(x - size * 0.48, y - size * 0.34),
|
||||
]
|
||||
)
|
||||
left = QPolygonF(
|
||||
[
|
||||
QPointF(x - size * 0.48, y - size * 0.34),
|
||||
QPointF(x, y - size * 0.10),
|
||||
QPointF(x, y + size * 0.48),
|
||||
QPointF(x - size * 0.48, y + size * 0.24),
|
||||
]
|
||||
)
|
||||
right = QPolygonF(
|
||||
[
|
||||
QPointF(x, y - size * 0.10),
|
||||
QPointF(x + size * 0.48, y - size * 0.34),
|
||||
QPointF(x + size * 0.48, y + size * 0.24),
|
||||
QPointF(x, y + size * 0.48),
|
||||
]
|
||||
)
|
||||
painter.setPen(QPen(QColor(185, 196, 247, 205), 1.2))
|
||||
painter.setBrush(QColor(235, 239, 255, 218))
|
||||
painter.drawPolygon(top)
|
||||
painter.setBrush(QColor(210, 218, 255, 205))
|
||||
painter.drawPolygon(left)
|
||||
painter.setBrush(QColor(224, 230, 255, 220))
|
||||
painter.drawPolygon(right)
|
||||
painter.setPen(_round_pen(QColor(137, 154, 248, 135), 2.2))
|
||||
if kind == "plus":
|
||||
painter.drawLine(
|
||||
QPointF(x - size * 0.12, y + size * 0.05),
|
||||
QPointF(x + size * 0.15, y - size * 0.02),
|
||||
)
|
||||
painter.drawLine(
|
||||
QPointF(x + size * 0.02, y - size * 0.13),
|
||||
QPointF(x + size * 0.02, y + size * 0.17),
|
||||
)
|
||||
else:
|
||||
shield = QPainterPath(QPointF(x, y - size * 0.16))
|
||||
shield.lineTo(x + size * 0.15, y - size * 0.08)
|
||||
shield.lineTo(x + size * 0.10, y + size * 0.17)
|
||||
shield.lineTo(x, y + size * 0.26)
|
||||
shield.lineTo(x - size * 0.10, y + size * 0.17)
|
||||
shield.lineTo(x - size * 0.15, y - size * 0.08)
|
||||
shield.closeSubpath()
|
||||
painter.drawPath(shield)
|
||||
|
||||
def _draw_illustration(
|
||||
self, painter: QPainter, width: float, height: float
|
||||
) -> None:
|
||||
ox = max(250.0, width - 500.0)
|
||||
oy = max(365.0, height - 500.0)
|
||||
|
||||
glow = QRadialGradient(QPointF(width - 170, oy + 230), 280)
|
||||
glow.setColorAt(0.0, QColor(102, 120, 255, 62))
|
||||
glow.setColorAt(1.0, QColor(102, 120, 255, 0))
|
||||
painter.setPen(Qt.PenStyle.NoPen)
|
||||
painter.setBrush(glow)
|
||||
painter.drawEllipse(QPointF(width - 170, oy + 230), 280, 280)
|
||||
|
||||
painter.setPen(QPen(QColor(166, 180, 241, 78), 1))
|
||||
for offset in (0, 72, 144):
|
||||
painter.drawLine(
|
||||
QPointF(ox - 80, oy + 280 + offset),
|
||||
QPointF(width + 20, oy + 170 + offset),
|
||||
)
|
||||
painter.drawLine(QPointF(ox + 10, oy + 400), QPointF(ox + 10, oy + 80))
|
||||
painter.drawLine(QPointF(ox + 170, oy + 430), QPointF(ox + 170, oy + 35))
|
||||
|
||||
base = QRectF(ox + 80, oy + 365, 430, 88)
|
||||
base_gradient = QLinearGradient(base.topLeft(), base.bottomRight())
|
||||
base_gradient.setColorAt(0.0, QColor(246, 248, 255, 228))
|
||||
base_gradient.setColorAt(1.0, QColor(186, 199, 255, 184))
|
||||
painter.setBrush(base_gradient)
|
||||
painter.setPen(QPen(QColor(166, 181, 248, 158), 1))
|
||||
painter.drawEllipse(base)
|
||||
painter.setBrush(QColor(249, 250, 255, 225))
|
||||
painter.drawEllipse(QRectF(base.x() + 42, base.y() - 12, base.width() - 84, 70))
|
||||
|
||||
painter.save()
|
||||
painter.translate(35, 40)
|
||||
screen = QPolygonF(
|
||||
[
|
||||
QPointF(ox + 130, oy + 60),
|
||||
QPointF(ox + 435, oy + 100),
|
||||
QPointF(ox + 435, oy + 365),
|
||||
QPointF(ox + 130, oy + 310),
|
||||
]
|
||||
)
|
||||
painter.setBrush(QColor(218, 225, 255, 205))
|
||||
painter.setPen(QPen(QColor(145, 163, 242, 170), 1.3))
|
||||
painter.drawPolygon(screen)
|
||||
inner = QPolygonF(
|
||||
[
|
||||
QPointF(ox + 141, oy + 80),
|
||||
QPointF(ox + 425, oy + 117),
|
||||
QPointF(ox + 425, oy + 345),
|
||||
QPointF(ox + 141, oy + 295),
|
||||
]
|
||||
)
|
||||
painter.setBrush(QColor(255, 255, 255, 225))
|
||||
painter.drawPolygon(inner)
|
||||
|
||||
painter.setPen(Qt.PenStyle.NoPen)
|
||||
painter.setBrush(QColor(174, 189, 252, 180))
|
||||
painter.drawRoundedRect(QRectF(ox + 148, oy + 89, 270, 15), 7, 7)
|
||||
for dot_x in (156, 173, 190):
|
||||
painter.setBrush(QColor(255, 255, 255, 200))
|
||||
painter.drawEllipse(QPointF(ox + dot_x, oy + 96.5), 3.5, 3.5)
|
||||
|
||||
cards = (
|
||||
QRectF(ox + 150, oy + 135, 82, 80),
|
||||
QRectF(ox + 241, oy + 142, 72, 73),
|
||||
QRectF(ox + 322, oy + 151, 95, 72),
|
||||
QRectF(ox + 151, oy + 232, 264, 50),
|
||||
QRectF(ox + 151, oy + 291, 264, 42),
|
||||
)
|
||||
painter.setPen(QPen(QColor(188, 199, 246, 160), 1))
|
||||
painter.setBrush(QColor(249, 250, 255, 228))
|
||||
for card in cards:
|
||||
painter.drawRoundedRect(card, 7, 7)
|
||||
painter.setPen(_round_pen(QColor(117, 137, 236, 165), 4))
|
||||
for idx, bar_height in enumerate((20, 36, 51)):
|
||||
x = ox + 164 + idx * 17
|
||||
painter.drawLine(QPointF(x, oy + 200), QPointF(x, oy + 200 - bar_height))
|
||||
painter.setBrush(QColor(112, 132, 235, 160))
|
||||
painter.setPen(Qt.PenStyle.NoPen)
|
||||
painter.drawEllipse(QPointF(ox + 277, oy + 167), 10, 10)
|
||||
painter.drawRoundedRect(QRectF(ox + 259, oy + 180, 36, 20), 10, 10)
|
||||
painter.setPen(_round_pen(QColor(137, 153, 235, 150), 5))
|
||||
for y, length in ((170, 54), (186, 42), (249, 89), (307, 72)):
|
||||
painter.drawLine(
|
||||
QPointF(ox + 340, oy + y), QPointF(ox + 340 + length, oy + y + 5)
|
||||
)
|
||||
|
||||
self._draw_cube(painter, QPointF(ox + 352, oy - 25), 76, "plus")
|
||||
self._draw_cube(painter, QPointF(ox - 8, oy + 210), 76, "shield")
|
||||
painter.restore()
|
||||
|
||||
def paintEvent(self, event: Any) -> None: # noqa: N802 - Qt API
|
||||
del event
|
||||
painter = QPainter(self)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
bounds = QRectF(self.rect()).adjusted(1, 1, -1, -1)
|
||||
painter.setPen(Qt.PenStyle.NoPen)
|
||||
painter.setBrush(QColor(PALETTE["sidebar"]))
|
||||
painter.drawRoundedRect(bounds, 20, 20)
|
||||
left = 36.0
|
||||
width = max(240.0, self.width() - 72.0)
|
||||
painter.setRenderHint(QPainter.RenderHint.TextAntialiasing)
|
||||
bounds = QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5)
|
||||
background = QLinearGradient(bounds.topLeft(), bounds.bottomRight())
|
||||
background.setColorAt(0.0, QColor("#FFFFFF"))
|
||||
background.setColorAt(0.7, QColor("#FFFFFF"))
|
||||
background.setColorAt(1.0, QColor("#F7F7F7"))
|
||||
painter.setBrush(background)
|
||||
painter.setPen(QPen(QColor("#EDEDEE"), 1))
|
||||
painter.drawRoundedRect(bounds, 24, 24)
|
||||
|
||||
width, height = float(self.width()), float(self.height())
|
||||
self._draw_illustration(painter, width, height)
|
||||
|
||||
left = 64.0 if width >= 620 else 38.0
|
||||
if not self._brand_lockup.isNull():
|
||||
brand = self._brand_lockup.scaled(
|
||||
226, 58, Qt.AspectRatioMode.KeepAspectRatio,
|
||||
Qt.TransformationMode.SmoothTransformation,
|
||||
logo_width = 180.0
|
||||
logo_height = logo_width * (
|
||||
self._brand_lockup.height() / self._brand_lockup.width()
|
||||
)
|
||||
painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform)
|
||||
painter.drawPixmap(
|
||||
QRectF(left, 24, logo_width, logo_height),
|
||||
self._brand_lockup,
|
||||
QRectF(self._brand_lockup.rect()),
|
||||
)
|
||||
painter.drawPixmap(QPointF(left, 36), brand)
|
||||
else:
|
||||
painter.setFont(_font(22, QFont.Weight.DemiBold))
|
||||
painter.setPen(QColor(PALETTE["heading"]))
|
||||
painter.drawText(QPointF(left, 70), "甄养堂 · 医生工作站")
|
||||
|
||||
heading_y = max(158.0, min(218.0, self.height() * .27))
|
||||
painter.setPen(QColor(PALETTE["muted"]))
|
||||
painter.setFont(_font(13, QFont.Weight.Medium))
|
||||
painter.drawText(QPointF(left, heading_y - 36), "医 生 工 作 台")
|
||||
painter.setPen(QColor(PALETTE["heading"]))
|
||||
painter.setFont(_font(30, QFont.Weight.DemiBold))
|
||||
painter.drawText(QPointF(left, heading_y), "让诊疗有序,")
|
||||
painter.drawText(QPointF(left, heading_y + 44), "让沟通更专注。")
|
||||
painter.setFont(_font(14))
|
||||
painter.setPen(QColor(PALETTE["muted"]))
|
||||
painter.drawText(QPointF(left, heading_y + 82), "从接诊、病历到处方,在一个工作台完成。")
|
||||
tag_rect = QRectF(left, 238, 119, 40)
|
||||
painter.setPen(Qt.PenStyle.NoPen)
|
||||
painter.setBrush(QColor("#EEF1FA"))
|
||||
painter.drawRoundedRect(tag_rect, 11, 11)
|
||||
painter.setFont(_font(17, QFont.Weight.Medium))
|
||||
painter.setPen(QColor("#4F63D9"))
|
||||
painter.drawText(tag_rect, Qt.AlignmentFlag.AlignCenter, "医生工作站")
|
||||
|
||||
row_y = heading_y + 122
|
||||
for index, (title, detail) in enumerate((
|
||||
("今日接诊", "快速找到待接诊患者与预约安排"),
|
||||
("诊疗记录", "病历、随访与面诊资料集中查看"),
|
||||
("处方协作", "开方与审核流程清晰衔接"),
|
||||
), start=1):
|
||||
row = QRectF(left, row_y, width, 66)
|
||||
painter.setPen(Qt.PenStyle.NoPen)
|
||||
painter.setBrush(QColor(PALETTE["surface"]))
|
||||
painter.drawRoundedRect(row, 12, 12)
|
||||
painter.setFont(_font(13, QFont.Weight.DemiBold))
|
||||
painter.setPen(QColor(PALETTE["accent"]))
|
||||
painter.drawText(QRectF(left + 16, row_y, 28, 66), Qt.AlignmentFlag.AlignCenter, f"0{index}")
|
||||
painter.setFont(_font(15, QFont.Weight.Medium))
|
||||
painter.setPen(QColor(PALETTE["heading"]))
|
||||
painter.drawText(QPointF(left + 58, row_y + 27), title)
|
||||
painter.setFont(_font(12))
|
||||
painter.setPen(QColor(PALETTE["muted"]))
|
||||
painter.drawText(QPointF(left + 58, row_y + 47), detail)
|
||||
row_y += 78
|
||||
if self.height() > row_y + 50:
|
||||
painter.setFont(_font(12))
|
||||
painter.setPen(QColor(PALETTE["muted"]))
|
||||
painter.drawText(QPointF(left, self.height() - 28), "仅供获授权的医疗人员使用")
|
||||
painter.end()
|
||||
copy_left = left + 4
|
||||
painter.setFont(_font(48, QFont.Weight.Medium))
|
||||
painter.setPen(QColor("#1A1C1F"))
|
||||
painter.drawText(QPointF(copy_left, 354), "把诊间工作,")
|
||||
painter.drawText(QPointF(copy_left, 424), "留在一个")
|
||||
prefix_width = painter.fontMetrics().horizontalAdvance("留在一个")
|
||||
highlight = QLinearGradient(
|
||||
copy_left + prefix_width,
|
||||
0,
|
||||
copy_left + prefix_width + 264,
|
||||
0,
|
||||
)
|
||||
highlight.setColorAt(0.0, QColor("#4F63D9"))
|
||||
highlight.setColorAt(1.0, QColor("#4F63D9"))
|
||||
painter.setPen(QPen(QBrush(highlight), 1))
|
||||
painter.drawText(QPointF(copy_left + prefix_width, 424), "安静的界面里")
|
||||
suffix_x = (
|
||||
copy_left
|
||||
+ prefix_width
|
||||
+ painter.fontMetrics().horizontalAdvance("安静的界面里")
|
||||
)
|
||||
painter.setPen(QColor("#1A1C1F"))
|
||||
painter.drawText(QPointF(suffix_x, 424), "。")
|
||||
|
||||
body_left = left + 6
|
||||
painter.setFont(_font(20))
|
||||
painter.setPen(QColor("#606163"))
|
||||
painter.drawText(
|
||||
QPointF(body_left, 492), "接诊、问诊、患者与处方信息统一呈现,"
|
||||
)
|
||||
painter.drawText(QPointF(body_left, 525), "帮助医生专注于每一次沟通。")
|
||||
|
||||
class _PasswordField(QFrame):
|
||||
"""Keep the grouped password control visibly focused for keyboard users."""
|
||||
|
||||
def eventFilter(self, watched: Any, event: QEvent) -> bool: # noqa: N802
|
||||
if event.type() in (QEvent.Type.FocusIn, QEvent.Type.FocusOut):
|
||||
self.setProperty("focused", event.type() == QEvent.Type.FocusIn)
|
||||
self.style().unpolish(self)
|
||||
self.style().polish(self)
|
||||
self.update()
|
||||
return super().eventFilter(watched, event)
|
||||
painter.setFont(_font(16))
|
||||
painter.setPen(QColor("#6A6B6D"))
|
||||
painter.drawText(
|
||||
QPointF(body_left, height - 85), "本工作站仅供获授权的医疗人员使用"
|
||||
)
|
||||
painter.drawText(QPointF(body_left, height - 59), "请勿在公共设备保存账号信息")
|
||||
|
||||
|
||||
class _RevealButton(QToolButton):
|
||||
@@ -236,8 +392,8 @@ class _ServerButton(QPushButton):
|
||||
painter = QPainter(self)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
rect = QRectF(self.rect()).adjusted(0.75, 0.75, -0.75, -0.75)
|
||||
painter.setBrush(QColor(PALETTE["accent_soft"] if self.underMouse() else PALETTE["surface"]))
|
||||
painter.setPen(QPen(QColor(PALETTE["focus"] if self.hasFocus() else PALETTE["line_strong"]), 1))
|
||||
painter.setBrush(QColor("#FFFFFF") if self.underMouse() else QColor("#FFFFFF"))
|
||||
painter.setPen(QPen(QColor("#E4E4E5"), 1.5))
|
||||
painter.drawRoundedRect(rect, 12, 12)
|
||||
color = QColor("#1A1C1F" if self.isEnabled() else "#8E8F90")
|
||||
painter.setPen(_round_pen("#6A6B6D", 1.8))
|
||||
@@ -380,7 +536,7 @@ class LoginWindow(QMainWindow):
|
||||
border: 1px solid #E4E4E5;
|
||||
border-radius: 12px;
|
||||
}
|
||||
QFrame#PasswordField[focused="true"] { border-color: #8B9AD9; }
|
||||
QFrame#PasswordField:focus-within { border-color: #8B9AD9; }
|
||||
QFrame#LoginCard QCheckBox {
|
||||
color: #606163;
|
||||
spacing: 13px;
|
||||
@@ -450,9 +606,6 @@ class LoginWindow(QMainWindow):
|
||||
self.login_root.addWidget(self.brand_panel, 60)
|
||||
self.login_root.addWidget(self._build_login_area(), 40)
|
||||
self._restore_settings()
|
||||
for widget in (canvas, *canvas.findChildren(QWidget)):
|
||||
if widget.styleSheet():
|
||||
widget.setStyleSheet(clinical_stylesheet(widget.styleSheet()))
|
||||
|
||||
def resizeEvent(self, event: QResizeEvent) -> None: # noqa: N802 - Qt API
|
||||
"""Preserve the reference composition while remaining usable on small screens."""
|
||||
@@ -472,15 +625,18 @@ class LoginWindow(QMainWindow):
|
||||
# Keep the form fully visible when the 60/40 desktop split would
|
||||
# otherwise crop its fixed-width card. Small windows focus on login.
|
||||
self.brand_panel.setVisible(width >= 1120)
|
||||
compact_height = event.size().height() < 720
|
||||
self.card.setMinimumHeight(580 if compact_height else 620)
|
||||
self.login_area_layout.setContentsMargins(
|
||||
0, 12 if compact_height else min(104, max(24, (event.size().height() - 694) // 2)), 0, 12
|
||||
0, min(104, max(24, (event.size().height() - 694) // 2)), 0, 12
|
||||
)
|
||||
super().resizeEvent(event)
|
||||
|
||||
def _build_brand_panel(self) -> QWidget:
|
||||
panel = _BrandPanel()
|
||||
shadow = QGraphicsDropShadowEffect(panel)
|
||||
shadow.setBlurRadius(32)
|
||||
shadow.setOffset(0, 10)
|
||||
shadow.setColor(QColor(67, 82, 154, 18))
|
||||
panel.setGraphicsEffect(shadow)
|
||||
return panel
|
||||
|
||||
def _build_login_area(self) -> QWidget:
|
||||
@@ -504,6 +660,11 @@ class LoginWindow(QMainWindow):
|
||||
self.card.setFixedWidth(480)
|
||||
self.card.setMinimumHeight(620)
|
||||
self.card.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Minimum)
|
||||
card_shadow = QGraphicsDropShadowEffect(self.card)
|
||||
card_shadow.setBlurRadius(38)
|
||||
card_shadow.setOffset(0, 16)
|
||||
card_shadow.setColor(QColor(59, 77, 139, 24))
|
||||
self.card.setGraphicsEffect(card_shadow)
|
||||
card_layout = QVBoxLayout(self.card)
|
||||
card_layout.setSizeConstraint(QLayout.SizeConstraint.SetDefaultConstraint)
|
||||
card_layout.setContentsMargins(47, 42, 47, 26)
|
||||
@@ -512,13 +673,13 @@ class LoginWindow(QMainWindow):
|
||||
|
||||
title = QLabel("欢迎回来")
|
||||
title.setObjectName("LoginTitle")
|
||||
title.setStyleSheet("color:#1A1C1F; font-size:26px; font-weight:600;")
|
||||
title.setStyleSheet("color:#1A1C1F; font-size:30px; font-weight:500;")
|
||||
title.setContentsMargins(1, -3, 0, 3)
|
||||
title.setFixedHeight(46)
|
||||
card_layout.addWidget(title)
|
||||
subtitle = QLabel("使用医生账号登录工作站")
|
||||
subtitle.setProperty("role", "muted")
|
||||
subtitle.setStyleSheet("color:#606163; font-size:15px;")
|
||||
subtitle.setStyleSheet("color:#606163; font-size:18px;")
|
||||
subtitle.setContentsMargins(1, 8, 0, 0)
|
||||
subtitle.setFixedHeight(27)
|
||||
card_layout.addWidget(subtitle)
|
||||
@@ -549,7 +710,7 @@ class LoginWindow(QMainWindow):
|
||||
password_label.setFixedHeight(24)
|
||||
card_layout.addWidget(password_label)
|
||||
card_layout.addSpacing(11)
|
||||
password_field = _PasswordField()
|
||||
password_field = QFrame()
|
||||
password_field.setObjectName("PasswordField")
|
||||
password_field.setFixedHeight(54)
|
||||
password_row = QHBoxLayout(password_field)
|
||||
@@ -560,7 +721,6 @@ class LoginWindow(QMainWindow):
|
||||
self.password_edit.setEchoMode(QLineEdit.EchoMode.Password)
|
||||
self.password_edit.setPlaceholderText("请输入密码")
|
||||
self.password_edit.setAccessibleName("登录密码")
|
||||
self.password_edit.installEventFilter(password_field)
|
||||
self.password_edit.setTextMargins(0, -2, 0, 2)
|
||||
self.password_edit.returnPressed.connect(self.submit)
|
||||
password_row.addWidget(self.password_edit, 1)
|
||||
@@ -570,7 +730,6 @@ class LoginWindow(QMainWindow):
|
||||
self.reveal_button.setCheckable(True)
|
||||
self.reveal_button.setFixedSize(87, 52)
|
||||
self.reveal_button.setToolTip("显示或隐藏密码")
|
||||
self.reveal_button.installEventFilter(password_field)
|
||||
self.reveal_button.toggled.connect(self._toggle_password)
|
||||
password_row.addWidget(self.reveal_button)
|
||||
card_layout.addWidget(password_field)
|
||||
@@ -599,6 +758,11 @@ class LoginWindow(QMainWindow):
|
||||
self.login_button = QPushButton("登录工作站")
|
||||
self.login_button.setProperty("variant", "primary")
|
||||
self.login_button.setFixedHeight(58)
|
||||
login_shadow = QGraphicsDropShadowEffect(self.login_button)
|
||||
login_shadow.setBlurRadius(20)
|
||||
login_shadow.setOffset(0, 7)
|
||||
login_shadow.setColor(QColor(82, 101, 246, 45))
|
||||
self.login_button.setGraphicsEffect(login_shadow)
|
||||
self.login_button.clicked.connect(self.submit)
|
||||
card_layout.addWidget(self.login_button)
|
||||
self.debug_settings_section = QWidget()
|
||||
|
||||
@@ -37,10 +37,8 @@ from PySide6.QtCore import (
|
||||
QTimer,
|
||||
)
|
||||
from PySide6.QtWidgets import (
|
||||
QAbstractItemView,
|
||||
QAbstractScrollArea,
|
||||
QGraphicsOpacityEffect,
|
||||
QPlainTextEdit,
|
||||
QStackedWidget,
|
||||
QWidget,
|
||||
)
|
||||
@@ -77,35 +75,15 @@ def reduced_motion() -> bool:
|
||||
return os.getenv("QT_QPA_PLATFORM", "").strip().lower() == "offscreen"
|
||||
|
||||
|
||||
def _stop(target: QObject, key: str) -> None:
|
||||
"""Retire a replaced animation without firing its completion callback."""
|
||||
|
||||
running = getattr(target, "_doctor_motion", {})
|
||||
previous = running.pop(key, None)
|
||||
if previous is not None:
|
||||
previous.stop()
|
||||
previous.setParent(None)
|
||||
previous.deleteLater()
|
||||
|
||||
|
||||
def _own(target: QObject, key: str, animation: QPropertyAnimation) -> QPropertyAnimation:
|
||||
def _own(target: QWidget, key: str, animation: QPropertyAnimation) -> QPropertyAnimation:
|
||||
"""Park an animation on its target so Python does not collect it early."""
|
||||
|
||||
_stop(target, key)
|
||||
running: dict[str, QPropertyAnimation] = getattr(target, "_doctor_motion", {})
|
||||
running: dict[str, QPropertyAnimation] = getattr(target, "_doctor_motion", None) or {}
|
||||
previous = running.get(key)
|
||||
if previous is not None:
|
||||
previous.stop()
|
||||
running[key] = animation
|
||||
target._doctor_motion = running
|
||||
|
||||
def release() -> None:
|
||||
if running.get(key) is animation:
|
||||
running.pop(key)
|
||||
# A callback can hold the last Python reference to the owner. Detach
|
||||
# first so releasing that callback during deferred deletion cannot
|
||||
# recursively delete this animation through its former parent.
|
||||
animation.setParent(None)
|
||||
animation.deleteLater()
|
||||
|
||||
animation.finished.connect(release)
|
||||
return animation
|
||||
|
||||
|
||||
@@ -129,10 +107,7 @@ def animate(
|
||||
from inside its own ``finished`` emission.
|
||||
"""
|
||||
|
||||
animation_owner = owner if owner is not None else target
|
||||
animation_key = key or prop.decode()
|
||||
if reduced_motion():
|
||||
_stop(animation_owner, animation_key)
|
||||
target.setProperty(prop.decode() if isinstance(prop, bytes) else prop, end)
|
||||
if on_finished is not None:
|
||||
on_finished()
|
||||
@@ -142,24 +117,18 @@ def animate(
|
||||
animation.setEasingCurve(easing)
|
||||
animation.setStartValue(start)
|
||||
animation.setEndValue(end)
|
||||
_own(animation_owner, animation_key, animation)
|
||||
if on_finished is not None:
|
||||
animation.finished.connect(on_finished)
|
||||
_own(owner if owner is not None else target, key or prop.decode(), animation)
|
||||
animation.start(QAbstractAnimation.DeletionPolicy.KeepWhenStopped)
|
||||
return animation
|
||||
|
||||
|
||||
def _opacity_effect(widget: QWidget) -> QGraphicsOpacityEffect | None:
|
||||
def _opacity_effect(widget: QWidget) -> QGraphicsOpacityEffect:
|
||||
effect = widget.graphicsEffect()
|
||||
# Do not replace a caller's shadow or opacity effect: Qt deletes it when
|
||||
# another effect is attached. Only effects created here belong to a fade.
|
||||
if effect is not None and effect is not getattr(widget, "_doctor_opacity_effect", None):
|
||||
return None
|
||||
if effect is None:
|
||||
if not isinstance(effect, QGraphicsOpacityEffect):
|
||||
effect = QGraphicsOpacityEffect(widget)
|
||||
effect.setOpacity(1.0)
|
||||
widget.setGraphicsEffect(effect)
|
||||
widget._doctor_opacity_effect = effect
|
||||
effect.setEnabled(True)
|
||||
return effect
|
||||
|
||||
@@ -177,17 +146,9 @@ def _drop_effect(widget: QWidget) -> None:
|
||||
signal that is still being delivered.
|
||||
"""
|
||||
|
||||
effect = getattr(widget, "_doctor_opacity_effect", None)
|
||||
revision = getattr(widget, "_doctor_fade_revision", 0)
|
||||
|
||||
def detach() -> None:
|
||||
try:
|
||||
if (
|
||||
effect is not None
|
||||
and widget.graphicsEffect() is effect
|
||||
and getattr(widget, "_doctor_fade_revision", 0) == revision
|
||||
):
|
||||
widget._doctor_opacity_effect = None
|
||||
if isinstance(widget.graphicsEffect(), QGraphicsOpacityEffect):
|
||||
widget.setGraphicsEffect(None)
|
||||
except RuntimeError: # the widget went away while the fade was running
|
||||
pass
|
||||
@@ -195,13 +156,6 @@ def _drop_effect(widget: QWidget) -> None:
|
||||
QTimer.singleShot(0, detach)
|
||||
|
||||
|
||||
def _restart_fade(widget: QWidget) -> None:
|
||||
_stop(widget, "fade")
|
||||
# A completed fade may still have deferred cleanup waiting in the queue.
|
||||
# It must not remove an effect now being used by a subsequent fade.
|
||||
widget._doctor_fade_revision = getattr(widget, "_doctor_fade_revision", 0) + 1
|
||||
|
||||
|
||||
def fade_in(
|
||||
widget: QWidget,
|
||||
*,
|
||||
@@ -211,20 +165,10 @@ def fade_in(
|
||||
) -> None:
|
||||
"""Fade a widget up to full opacity, showing it first if needed."""
|
||||
|
||||
existing = widget.graphicsEffect()
|
||||
if existing is not None and existing is getattr(widget, "_doctor_opacity_effect", None):
|
||||
start = float(existing.opacity())
|
||||
_restart_fade(widget)
|
||||
if reduced_motion():
|
||||
if existing is not None and existing is getattr(widget, "_doctor_opacity_effect", None):
|
||||
existing.setOpacity(1.0)
|
||||
_drop_effect(widget)
|
||||
widget.show()
|
||||
return
|
||||
effect = _opacity_effect(widget)
|
||||
if effect is None:
|
||||
widget.show()
|
||||
return
|
||||
effect.setOpacity(start)
|
||||
widget.show()
|
||||
animate(
|
||||
@@ -249,11 +193,9 @@ def fade_out(
|
||||
) -> None:
|
||||
"""Fade a widget down, optionally hiding it when the fade completes."""
|
||||
|
||||
_restart_fade(widget)
|
||||
if reduced_motion():
|
||||
if hide:
|
||||
widget.hide()
|
||||
_drop_effect(widget)
|
||||
if on_finished is not None:
|
||||
on_finished()
|
||||
return
|
||||
@@ -266,9 +208,6 @@ def fade_out(
|
||||
if on_finished is not None:
|
||||
on_finished()
|
||||
|
||||
if effect is None:
|
||||
done()
|
||||
return
|
||||
animate(
|
||||
effect,
|
||||
b"opacity",
|
||||
@@ -290,17 +229,13 @@ def enter(widget: QWidget, *, duration: int = BASE, rise: int = RISE) -> None:
|
||||
the user has to wait out.
|
||||
"""
|
||||
|
||||
previous = getattr(widget, "_doctor_motion", {}).get("enter")
|
||||
origin = previous.endValue() if previous is not None else widget.pos()
|
||||
if reduced_motion():
|
||||
_stop(widget, "enter")
|
||||
widget.move(origin)
|
||||
fade_in(widget, duration=duration)
|
||||
widget.show()
|
||||
return
|
||||
fade_in(widget, duration=duration)
|
||||
if rise:
|
||||
if previous is None:
|
||||
widget.move(origin + QPoint(0, rise))
|
||||
origin = widget.pos()
|
||||
widget.move(origin + QPoint(0, rise))
|
||||
animate(
|
||||
widget,
|
||||
b"pos",
|
||||
@@ -325,7 +260,7 @@ def switch_stack(stack: QStackedWidget, index: int, *, rise: int = RISE) -> None
|
||||
return
|
||||
stack.setCurrentIndex(index)
|
||||
page = stack.currentWidget()
|
||||
if page is None:
|
||||
if page is None or reduced_motion():
|
||||
return
|
||||
enter(page, rise=rise)
|
||||
|
||||
@@ -339,121 +274,50 @@ SCROLL_STEP = 120
|
||||
SCROLL_MS = 190
|
||||
|
||||
|
||||
class _ScrollAnimation(QPropertyAnimation):
|
||||
"""Identify animation writes so direct scrollbar changes can interrupt us."""
|
||||
|
||||
writing = False
|
||||
|
||||
def updateCurrentValue(self, value: Any) -> None: # noqa: N802 - Qt API
|
||||
self.writing = True
|
||||
try:
|
||||
super().updateCurrentValue(value)
|
||||
finally:
|
||||
self.writing = False
|
||||
|
||||
|
||||
class _SmoothScroller(QObject):
|
||||
"""Animate a scroll area's wheel movement instead of jumping to it."""
|
||||
|
||||
_INTERRUPT_EVENTS = frozenset(
|
||||
{
|
||||
QEvent.Type.KeyPress,
|
||||
QEvent.Type.MouseButtonPress,
|
||||
QEvent.Type.TouchBegin,
|
||||
QEvent.Type.Hide,
|
||||
}
|
||||
)
|
||||
|
||||
def __init__(self, area: QAbstractScrollArea, *, orientation: Qt.Orientation) -> None:
|
||||
super().__init__(area)
|
||||
self._area = area
|
||||
self._orientation = orientation
|
||||
self._bar = (
|
||||
area.verticalScrollBar()
|
||||
if orientation is Qt.Orientation.Vertical
|
||||
else area.horizontalScrollBar()
|
||||
)
|
||||
self._target = self._bar.value()
|
||||
self._animation = _ScrollAnimation(self._bar, b"value", self)
|
||||
self._animation = QPropertyAnimation(self._bar, b"value", self)
|
||||
self._animation.setEasingCurve(EASE_ENTER)
|
||||
self._animation.setDuration(SCROLL_MS)
|
||||
# Keyboard, programmatic and drag movements must not be fought over: when
|
||||
# nothing is animating, the wheel target follows wherever the bar went.
|
||||
self._bar.valueChanged.connect(self._sync_target)
|
||||
self._bar.sliderPressed.connect(self._cancel)
|
||||
self._bar.actionTriggered.connect(self._cancel)
|
||||
self._bar.rangeChanged.connect(self._cancel)
|
||||
self._bar.installEventFilter(self)
|
||||
area.installEventFilter(self)
|
||||
area.viewport().installEventFilter(self)
|
||||
|
||||
def _cancel(self, *_: Any) -> None:
|
||||
self._animation.stop()
|
||||
self._target = self._bar.value()
|
||||
|
||||
def _sync_target(self, value: int) -> None:
|
||||
if not self._animation.writing:
|
||||
self._animation.stop()
|
||||
if self._animation.state() != QAbstractAnimation.State.Running:
|
||||
self._target = value
|
||||
|
||||
def _uses_pixels(self) -> bool:
|
||||
if isinstance(self._area, QAbstractItemView):
|
||||
mode = (
|
||||
self._area.verticalScrollMode()
|
||||
if self._orientation == Qt.Orientation.Vertical
|
||||
else self._area.horizontalScrollMode()
|
||||
)
|
||||
return mode == QAbstractItemView.ScrollMode.ScrollPerPixel
|
||||
# QPlainTextEdit's vertical scrollbar counts text blocks, not pixels.
|
||||
return not (
|
||||
isinstance(self._area, QPlainTextEdit) and self._orientation == Qt.Orientation.Vertical
|
||||
)
|
||||
|
||||
def eventFilter(self, watched: QObject, event: QEvent) -> bool: # noqa: N802 - Qt API
|
||||
event_type = event.type()
|
||||
if event_type in self._INTERRUPT_EVENTS:
|
||||
self._cancel()
|
||||
del watched
|
||||
if event.type() is not QEvent.Type.Wheel or reduced_motion():
|
||||
return False
|
||||
if event_type != QEvent.Type.Wheel:
|
||||
delta = event.angleDelta().y() or event.angleDelta().x()
|
||||
if not delta or event.modifiers() & Qt.KeyboardModifier.ControlModifier:
|
||||
return False
|
||||
horizontal = self._orientation == Qt.Orientation.Horizontal
|
||||
shifted = bool(event.modifiers() & Qt.KeyboardModifier.ShiftModifier)
|
||||
delta = event.angleDelta().x() if horizontal else event.angleDelta().y()
|
||||
if horizontal and shifted and not delta:
|
||||
delta = event.angleDelta().y()
|
||||
if (
|
||||
watched is not self._area.viewport()
|
||||
or reduced_motion()
|
||||
or not self._uses_pixels()
|
||||
or not event.pixelDelta().isNull()
|
||||
or event.phase() != Qt.ScrollPhase.NoScrollPhase
|
||||
or event.modifiers()
|
||||
& (Qt.KeyboardModifier.ControlModifier | Qt.KeyboardModifier.AltModifier)
|
||||
or (shifted and not horizontal)
|
||||
or not delta
|
||||
):
|
||||
# Trackpads already provide continuous motion and native momentum.
|
||||
# Mixing another easing curve into it adds lag and fights gestures.
|
||||
self._cancel()
|
||||
return False
|
||||
|
||||
lower, upper = self._bar.minimum(), self._bar.maximum()
|
||||
# Re-clamp first: the range can shrink underneath a running animation
|
||||
# when the content behind it reloads, which would otherwise leave the
|
||||
# pending target past the end of the new content.
|
||||
self._target = max(lower, min(upper, self._target))
|
||||
current = self._bar.value()
|
||||
step = -round(delta / 120.0 * SCROLL_STEP)
|
||||
# Reverse immediately from the visible position, not the end of a
|
||||
# backlog of wheel notches still travelling in the opposite direction.
|
||||
origin = current if (self._target - current) * step < 0 else self._target
|
||||
target = origin + step
|
||||
target = self._target - round(delta / 120.0 * SCROLL_STEP)
|
||||
target = max(lower, min(upper, target))
|
||||
# At either end, hand the wheel back so an enclosing scroll area still
|
||||
# gets it - swallowing it there is what makes nested panes feel stuck.
|
||||
if target == self._target:
|
||||
return target != current
|
||||
return False
|
||||
self._target = target
|
||||
self._animation.stop()
|
||||
self._animation.setStartValue(current)
|
||||
self._animation.setStartValue(self._bar.value())
|
||||
self._animation.setEndValue(target)
|
||||
self._animation.start()
|
||||
return True
|
||||
@@ -464,7 +328,7 @@ def install_smooth_scroll(
|
||||
*,
|
||||
orientation: Qt.Orientation = Qt.Orientation.Vertical,
|
||||
) -> None:
|
||||
"""Ease discrete wheels on pixel-based areas; preserve native gestures."""
|
||||
"""Give a scroll area eased wheel scrolling."""
|
||||
|
||||
if getattr(area, "_doctor_smooth_scroll", None) is not None:
|
||||
return
|
||||
|
||||
@@ -38,7 +38,6 @@ from PySide6.QtWidgets import (
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from ...core import UserProfile
|
||||
from ...core.appointment_modes import appointment_type_value, can_appointment_video
|
||||
from .. import icons
|
||||
from ..consultations_style import consultations_stylesheet
|
||||
@@ -1494,7 +1493,6 @@ class ConsultationsPage(QWidget):
|
||||
table_wrap_layout.setSpacing(0)
|
||||
self.table_host = DiagnosisTableHost(
|
||||
tech_blue=True,
|
||||
video_entry_allowed=self._can_enter_list_call,
|
||||
action_policy={
|
||||
"view": _canonical_allowed(permissions, "tcm.diagnosis/readonlyDetail"),
|
||||
"edit": _canonical_allowed(permissions, "tcm.diagnosis/edit"),
|
||||
@@ -3055,11 +3053,8 @@ class ConsultationsPage(QWidget):
|
||||
_as_int(payload.get(key), 0) > 0
|
||||
for key in ("appointment_id", "patient_id", "diagnosis_id")
|
||||
)
|
||||
entry_allowed = has_record and self._can_enter_list_call(record)
|
||||
self.video_button.setVisible(entry_allowed)
|
||||
self.call_toolbar_button.setVisible(entry_allowed)
|
||||
self.video_button.setEnabled(
|
||||
entry_allowed
|
||||
has_record
|
||||
and is_video_available(record)
|
||||
and (appointment_type_value(record) == "text" or video_call_is_live(record))
|
||||
and valid_ids
|
||||
@@ -3501,28 +3496,6 @@ class ConsultationsPage(QWidget):
|
||||
self._checked_changed(len(self.table_host.selected_records()))
|
||||
self._selection_changed()
|
||||
|
||||
def _can_enter_list_call(self, record: Any) -> bool:
|
||||
if not self._native_video_capable or record is None:
|
||||
return False
|
||||
# Text appointments retain their IM entry; this restriction concerns
|
||||
# receiving an existing video call from the diagnosis list.
|
||||
if appointment_type_value(record) == "text":
|
||||
return True
|
||||
if not can_appointment_video(appointment_type_value(record)):
|
||||
return False
|
||||
roles = UserProfile.from_dict({
|
||||
"role_ids": first_value(self.current_user, "role_ids", "role_id", "roles", default=[])
|
||||
}).role_ids
|
||||
if 1 in roles:
|
||||
return False
|
||||
user_id = _as_int(first_value(self.current_user, "id", "user_id", default=0))
|
||||
assistant_id = _as_int(first_value(record, "assistant_id", "assistant", default=0))
|
||||
return bool(
|
||||
user_id > 0
|
||||
and assistant_id == user_id
|
||||
and _canonical_allowed(self.permissions, "tcm.diagnosis/watchCall")
|
||||
)
|
||||
|
||||
def _request_video(self) -> None:
|
||||
record = self.table.current_data()
|
||||
if not self._native_video_capable:
|
||||
@@ -3530,9 +3503,6 @@ class ConsultationsPage(QWidget):
|
||||
return
|
||||
if record is None or not is_video_available(record):
|
||||
self.banner.show_message("仅当前“已预约”的挂号可进入视频问诊。", "warning")
|
||||
return
|
||||
if not self._can_enter_list_call(record):
|
||||
self.banner.show_message("仅本诊单指派且具有旁观权限的医助可进入视频会话。", "warning")
|
||||
return
|
||||
if appointment_type_value(record) != "text" and not video_call_is_live(record):
|
||||
self.banner.show_message("医生尚未发起视频会话,请等待会话开始。", "warning")
|
||||
|
||||
@@ -50,7 +50,6 @@ from ...core.appointment_modes import (
|
||||
)
|
||||
from .. import icons
|
||||
from ..appointment_drawer import AppointmentDrawer
|
||||
from ..design_system import PALETTE, clinical_stylesheet
|
||||
from ..dialogs import DiagnosisDialog, present_ai_consult, present_order_detail
|
||||
from ..dialogs.ai_consult import can_open_ai_consult
|
||||
from ..dialogs.prescription import PrescriptionOrderListDialog
|
||||
@@ -111,97 +110,97 @@ FULFILLMENT_TEXT = {
|
||||
}
|
||||
|
||||
_SEMANTIC_COLORS = {
|
||||
"primary": PALETTE["accent"],
|
||||
"success": PALETTE["success"],
|
||||
"warning": PALETTE["warning"],
|
||||
"danger": PALETTE["danger"],
|
||||
"info": PALETTE["accent"],
|
||||
"muted": PALETTE["muted"],
|
||||
"primary": "#4F63D9",
|
||||
"success": "#287B65",
|
||||
"warning": "#A9691D",
|
||||
"danger": "#BE4B58",
|
||||
"info": "#4F63D9",
|
||||
"muted": "#606163",
|
||||
}
|
||||
|
||||
PATIENTS_LIGHT_QSS = clinical_stylesheet("""
|
||||
PATIENTS_LIGHT_QSS = """
|
||||
#PatientsPage QWidget#PageHeader QLabel[role="pageTitle"] {
|
||||
color: $ds_heading;
|
||||
color: #1A1C1F;
|
||||
font-size: 20px;
|
||||
font-weight: 600;
|
||||
}
|
||||
#PatientsPage QWidget#PageHeader QLabel[role="muted"] {
|
||||
color: $ds_muted;
|
||||
color: #606163;
|
||||
font-size: 13px;
|
||||
}
|
||||
#PatientsPage QPushButton[patientSearchAction="true"] {
|
||||
min-height: 32px;
|
||||
max-height: 32px;
|
||||
color: $ds_surface;
|
||||
background-color: $ds_accent;
|
||||
border: 1px solid $ds_accent;
|
||||
color: #FFFFFF;
|
||||
background-color: #4F63D9;
|
||||
border: 1px solid #4F63D9;
|
||||
border-radius: 7px;
|
||||
font-weight: 500;
|
||||
}
|
||||
#PatientsPage QPushButton[patientSearchAction="true"]:hover {
|
||||
background-color: $ds_accent_hover;
|
||||
border-color: $ds_accent_hover;
|
||||
background-color: #4156C4;
|
||||
border-color: #4156C4;
|
||||
}
|
||||
#PatientsPage QFrame[patientListFilter="true"] {
|
||||
min-height: 88px;
|
||||
max-height: 88px;
|
||||
background-color: $ds_surface;
|
||||
border: 1px solid $ds_line;
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: 12px;
|
||||
}
|
||||
#PatientsPage QFrame[patientListFilter="true"] QLineEdit,
|
||||
#PatientsPage QFrame[patientListFilter="true"] QDateEdit {
|
||||
min-height: 32px;
|
||||
max-height: 32px;
|
||||
background-color: $ds_surface;
|
||||
border: 1px solid $ds_line;
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: 7px; font-size: 14px;
|
||||
}
|
||||
#PatientsPage QFrame[patientListFilter="true"] QPushButton {
|
||||
min-height: 32px; max-height: 32px;
|
||||
}
|
||||
#PatientsPage QFrame[patientListFilter="true"] QDateEdit:disabled {
|
||||
color: $ds_disabled; background-color: $ds_surface_alt;
|
||||
color: #8E8F90; background-color: #F7F7F7;
|
||||
}
|
||||
#PatientsPage QPushButton[patientStatusChip="true"] {
|
||||
min-height: 32px;
|
||||
max-height: 32px;
|
||||
padding: 0 10px;
|
||||
color: $ds_muted;
|
||||
background-color: $ds_surface_alt;
|
||||
color: #606163;
|
||||
background-color: #F7F7F7;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 5px;
|
||||
}
|
||||
#PatientsPage QPushButton[patientStatusChip="true"]:hover {
|
||||
color: $ds_accent;
|
||||
background-color: $ds_accent_soft;
|
||||
color: #4F63D9;
|
||||
background-color: #EEF1FA;
|
||||
}
|
||||
#PatientsPage QPushButton[patientStatusChip="true"]:checked {
|
||||
color: $ds_accent;
|
||||
background-color: $ds_accent_soft;
|
||||
border: 1px solid $ds_focus;
|
||||
color: #4F63D9;
|
||||
background-color: #EEF1FA;
|
||||
border: 1px solid #8B9AD9;
|
||||
}
|
||||
#PatientsPage QPushButton[patientQuickDate="true"] {
|
||||
min-height: 32px;
|
||||
max-height: 32px;
|
||||
padding: 0 9px;
|
||||
color: $ds_heading;
|
||||
color: #1A1C1F;
|
||||
background-color: transparent;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 7px;
|
||||
}
|
||||
#PatientsPage QPushButton[patientQuickDate="true"]:hover {
|
||||
color: $ds_accent;
|
||||
background-color: $ds_accent_soft;
|
||||
color: #4F63D9;
|
||||
background-color: #EEF1FA;
|
||||
}
|
||||
#PatientsPage QPushButton[patientQuickDate="true"]:checked {
|
||||
color: $ds_accent;
|
||||
background-color: $ds_accent_soft;
|
||||
border-color: $ds_focus;
|
||||
color: #4F63D9;
|
||||
background-color: #EEF1FA;
|
||||
border-color: #8B9AD9;
|
||||
}
|
||||
#PatientsPage QTabWidget#PatientWorkspaceTabs::pane {
|
||||
border: 0;
|
||||
border-top: 1px solid $ds_line;
|
||||
border-top: 1px solid #EDEDEE;
|
||||
background-color: transparent;
|
||||
}
|
||||
#PatientsPage QTabWidget#PatientWorkspaceTabs QTabBar::tab {
|
||||
@@ -209,124 +208,124 @@ PATIENTS_LIGHT_QSS = clinical_stylesheet("""
|
||||
min-height: 34px;
|
||||
padding: 0 6px;
|
||||
margin-right: 8px;
|
||||
color: $ds_muted;
|
||||
color: #606163;
|
||||
background: transparent;
|
||||
border: 0;
|
||||
border-bottom: 2px solid transparent;
|
||||
font-weight: 400;
|
||||
}
|
||||
#PatientsPage QTabWidget#PatientWorkspaceTabs QTabBar::tab:selected {
|
||||
color: $ds_accent;
|
||||
border-bottom-color: $ds_accent;
|
||||
color: #4F63D9;
|
||||
border-bottom-color: #4F63D9;
|
||||
font-weight: 500;
|
||||
}
|
||||
#PatientsPage QPushButton[summaryCard="true"] {
|
||||
min-height: 42px;
|
||||
max-height: 42px;
|
||||
padding: 0 11px;
|
||||
color: $ds_heading;
|
||||
background-color: $ds_surface_alt;
|
||||
border: 1px solid $ds_line;
|
||||
color: #1A1C1F;
|
||||
background-color: #F7F7F7;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: 9px;
|
||||
text-align: left;
|
||||
font-weight: 500;
|
||||
}
|
||||
#PatientsPage QPushButton[summaryCard="true"]:hover {
|
||||
color: $ds_accent;
|
||||
background-color: $ds_accent_soft;
|
||||
border-color: $ds_focus;
|
||||
color: #4F63D9;
|
||||
background-color: #EEF1FA;
|
||||
border-color: #8B9AD9;
|
||||
}
|
||||
#PatientsPage QPushButton[rowAction="true"] {
|
||||
min-height: 26px;
|
||||
max-height: 26px;
|
||||
padding: 0 7px;
|
||||
color: $ds_accent;
|
||||
background-color: $ds_surface;
|
||||
border: 1px solid $ds_line;
|
||||
color: #4F63D9;
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: 6px;
|
||||
font-size: 13px;
|
||||
font-weight: 400;
|
||||
}
|
||||
#PatientsPage QPushButton[rowAction="true"]:hover {
|
||||
background-color: $ds_accent_soft;
|
||||
border-color: $ds_focus;
|
||||
background-color: #EEF1FA;
|
||||
border-color: #8B9AD9;
|
||||
}
|
||||
#PatientsPage QPushButton[rowAction="true"][variant="danger"] {
|
||||
color: $ds_danger;
|
||||
background-color: $ds_danger_soft;
|
||||
border-color: $ds_danger_soft;
|
||||
color: #BE4B58;
|
||||
background-color: #FFF7F8;
|
||||
border-color: #F4C4CC;
|
||||
}
|
||||
#PatientsPage QTableWidget#PatientTable QHeaderView::section {
|
||||
min-height: 34px;
|
||||
background-color: $ds_surface_alt; font-size: 13px;
|
||||
background-color: #F7F7F7; font-size: 13px;
|
||||
}
|
||||
#PatientsPage QTableWidget#PatientTable::item { padding: 5px 7px; }
|
||||
#PatientsPage QTableWidget#PatientTable {
|
||||
gridline-color: $ds_line;
|
||||
selection-background-color: $ds_accent_soft;
|
||||
selection-color: $ds_heading; font-size: 14px;
|
||||
gridline-color: #EDEDEE;
|
||||
selection-background-color: #EEF1FA;
|
||||
selection-color: #1A1C1F; font-size: 14px;
|
||||
}
|
||||
#PatientsPage QCheckBox[patientSelector="true"]::indicator {
|
||||
width: 13px;
|
||||
height: 13px;
|
||||
background-color: $ds_surface;
|
||||
border: 1px solid $ds_line;
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: 2px;
|
||||
}
|
||||
#PatientsPage QCheckBox[patientSelector="true"]::indicator:checked {
|
||||
background-color: $ds_accent;
|
||||
border-color: $ds_accent;
|
||||
background-color: #4F63D9;
|
||||
border-color: #4F63D9;
|
||||
}
|
||||
#PatientsPage QPushButton[variant="ghost"]:checked {
|
||||
color: $ds_accent;
|
||||
background-color: $ds_accent_soft;
|
||||
border: 1px solid $ds_accent;
|
||||
color: #4F63D9;
|
||||
background-color: #EEF1FA;
|
||||
border: 1px solid #4F63D9;
|
||||
}
|
||||
#PatientsPage QPushButton[variant="ghost"]:checked:hover { background-color: $ds_accent_soft; }
|
||||
#PatientsPage QPushButton[variant="ghost"]:checked:hover { background-color: #EEF1FA; }
|
||||
#PatientsPage QPushButton[statusKind="info"]:checked {
|
||||
color: $ds_accent;
|
||||
border-color: $ds_accent;
|
||||
color: #4F63D9;
|
||||
border-color: #4F63D9;
|
||||
}
|
||||
#PatientsPage QPushButton[statusKind="warning"]:checked {
|
||||
color: $ds_warning;
|
||||
border-color: $ds_warning;
|
||||
color: #A9691D;
|
||||
border-color: #A9691D;
|
||||
}
|
||||
#PatientsPage QPushButton[statusKind="success"]:checked {
|
||||
color: $ds_success;
|
||||
border-color: $ds_success;
|
||||
color: #287B65;
|
||||
border-color: #287B65;
|
||||
}
|
||||
#PatientsPage QPushButton[statusKind="danger"]:checked {
|
||||
color: $ds_danger;
|
||||
border-color: $ds_danger;
|
||||
color: #BE4B58;
|
||||
border-color: #BE4B58;
|
||||
}
|
||||
#PatientsPage QLabel[metricKind="primary"] { color: $ds_accent; }
|
||||
#PatientsPage QLabel[metricKind="info"] { color: $ds_accent; }
|
||||
#PatientsPage QLabel[metricKind="success"] { color: $ds_success; }
|
||||
#PatientsPage QLabel[metricKind="warning"] { color: $ds_warning; }
|
||||
#PatientsPage QLabel[metricKind="danger"] { color: $ds_danger; }
|
||||
#PatientsPage QLabel[metricKind="primary"] { color: #4F63D9; }
|
||||
#PatientsPage QLabel[metricKind="info"] { color: #4F63D9; }
|
||||
#PatientsPage QLabel[metricKind="success"] { color: #287B65; }
|
||||
#PatientsPage QLabel[metricKind="warning"] { color: #A9691D; }
|
||||
#PatientsPage QLabel[metricKind="danger"] { color: #BE4B58; }
|
||||
#PatientsPage QTabWidget#PatientWorkspaceTabs::pane {
|
||||
background-color: transparent;
|
||||
border: 0;
|
||||
top: -1px;
|
||||
}
|
||||
#PatientsPage QTabWidget#PatientWorkspaceTabs QTabBar::tab {
|
||||
color: $ds_muted;
|
||||
color: #606163;
|
||||
background-color: transparent;
|
||||
border: 0;
|
||||
border-bottom: 2px solid transparent;
|
||||
font-weight: 400;
|
||||
}
|
||||
#PatientsPage QTabWidget#PatientWorkspaceTabs QTabBar::tab:hover {
|
||||
color: $ds_accent;
|
||||
background-color: $ds_accent_soft;
|
||||
color: #4F63D9;
|
||||
background-color: #EEF1FA;
|
||||
}
|
||||
#PatientsPage QTabWidget#PatientWorkspaceTabs QTabBar::tab:selected {
|
||||
color: $ds_accent;
|
||||
color: #4F63D9;
|
||||
background-color: transparent;
|
||||
border-bottom-color: $ds_accent;
|
||||
border-bottom-color: #4F63D9;
|
||||
font-weight: 500;
|
||||
}
|
||||
""")
|
||||
"""
|
||||
|
||||
|
||||
def _style_table_cell(table: SortableTable, row: int, column: int, kind: str) -> None:
|
||||
@@ -1283,7 +1282,7 @@ class _PatientDateEdit(QDateEdit):
|
||||
def paintEvent(self, event: Any) -> None:
|
||||
super().paintEvent(event)
|
||||
painter = QPainter(self)
|
||||
glyph = icons.pixmap("calendar", PALETTE["muted"] if self.isEnabled() else PALETTE["disabled"], 15)
|
||||
glyph = icons.pixmap("calendar", "#5D6B80" if self.isEnabled() else "#8A97A9", 15)
|
||||
painter.drawPixmap(QRectF(self.width() - 24, (self.height() - 15) / 2, 15, 15), glyph, QRectF(glyph.rect()))
|
||||
painter.end()
|
||||
|
||||
@@ -1301,18 +1300,18 @@ class _PatientSummaryButton(QPushButton):
|
||||
label, _, count = self.text().partition("\n")
|
||||
left = max(18, (self.width() - 204) // 2)
|
||||
icon_rect = QRectF(left, (self.height() - 36) / 2, 36, 36)
|
||||
glyph = icons.pixmap("calendar", PALETTE["accent"], 36)
|
||||
glyph = icons.pixmap("calendar", "#1769E8", 36)
|
||||
painter.drawPixmap(icon_rect, glyph, QRectF(glyph.rect()))
|
||||
font = QFont(body_family())
|
||||
font.setPixelSize(13)
|
||||
painter.setFont(font)
|
||||
painter.setPen(QColor(PALETTE["muted"]))
|
||||
painter.setPen(QColor("#5D6B80"))
|
||||
text_rect = self.rect().adjusted(left + 46, 10, -12, -32)
|
||||
painter.drawText(text_rect, Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
|
||||
painter.fontMetrics().elidedText(label, Qt.TextElideMode.ElideRight, text_rect.width()))
|
||||
font.setPixelSize(16)
|
||||
painter.setFont(font)
|
||||
painter.setPen(QColor(PALETTE["text"]))
|
||||
painter.setPen(QColor("#273244"))
|
||||
painter.drawText(self.rect().adjusted(left + 46, 31, -12, -9),
|
||||
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, count)
|
||||
painter.end()
|
||||
@@ -1325,11 +1324,11 @@ class _PatientInfoDelegate(QStyledItemDelegate):
|
||||
painter.save()
|
||||
selected = bool(option.state & QStyle.StateFlag.State_Selected)
|
||||
hovered = bool(option.state & QStyle.StateFlag.State_MouseOver)
|
||||
painter.fillRect(option.rect, QColor(PALETTE["accent_soft"] if selected else PALETTE["surface_alt"] if hovered else PALETTE["surface"]))
|
||||
painter.setPen(QColor(PALETTE["line"]))
|
||||
painter.fillRect(option.rect, QColor("#EAF2FF" if selected else "#F6F9FE" if hovered else "#FFFFFF"))
|
||||
painter.setPen(QColor("#E6EDF6"))
|
||||
painter.drawLine(option.rect.bottomLeft(), option.rect.bottomRight())
|
||||
if selected and index.column() == 0:
|
||||
painter.fillRect(option.rect.adjusted(0, 0, -option.rect.width() + 3, 0), QColor(PALETTE["accent"]))
|
||||
painter.fillRect(option.rect.adjusted(0, 0, -option.rect.width() + 3, 0), QColor("#1769E8"))
|
||||
if index.column() in (0, 9):
|
||||
painter.restore()
|
||||
return
|
||||
@@ -1338,9 +1337,9 @@ class _PatientInfoDelegate(QStyledItemDelegate):
|
||||
font = QFont(body_family())
|
||||
font.setPixelSize(14)
|
||||
painter.setFont(font)
|
||||
painter.setPen(QColor(PALETTE["text"]))
|
||||
painter.setPen(QColor("#273244"))
|
||||
|
||||
def draw(text: str, target: Any, color: str = PALETTE["text"], centered: bool = False) -> None:
|
||||
def draw(text: str, target: Any, color: str = "#273244", centered: bool = False) -> None:
|
||||
painter.setPen(QColor(color))
|
||||
text = painter.fontMetrics().elidedText(text, Qt.TextElideMode.ElideRight, target.width())
|
||||
alignment = Qt.AlignmentFlag.AlignVCenter | (Qt.AlignmentFlag.AlignHCenter if centered else Qt.AlignmentFlag.AlignLeft)
|
||||
@@ -1360,17 +1359,17 @@ class _PatientInfoDelegate(QStyledItemDelegate):
|
||||
doctor = display_text(first_value(row, "appointment_doctor_name"), "")
|
||||
status, _kind = _patient_status(row)
|
||||
if not doctor:
|
||||
draw(status, rect, PALETTE["muted"])
|
||||
draw(status, rect, "#5D6B80")
|
||||
else:
|
||||
draw(doctor, top)
|
||||
font.setPixelSize(13)
|
||||
painter.setFont(font)
|
||||
color, fill = (PALETTE["warning"], PALETTE["warning_soft"]) if status == "已过号" else (PALETTE["accent"], PALETTE["accent_soft"])
|
||||
color, fill = ("#A9691D", "#FFF7EA") if status == "已过号" else ("#1769E8", "#F0F6FF")
|
||||
if status == "已取消":
|
||||
color, fill = PALETTE["muted"], PALETTE["canvas"]
|
||||
color, fill = "#5D6B80", "#F5F7FA"
|
||||
badge = QRectF(bottom.x(), bottom.y() + 1, min(bottom.width(), painter.fontMetrics().horizontalAdvance(status) + 10), 20)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
painter.setPen(QColor(PALETTE["warning_soft"] if status == "已过号" else PALETTE["line_strong"]))
|
||||
painter.setPen(QColor("#E7CDA8" if status == "已过号" else "#C7DAF7"))
|
||||
painter.setBrush(QColor(fill))
|
||||
painter.drawRoundedRect(badge, 3, 3)
|
||||
draw(status, badge.toRect(), color, True)
|
||||
@@ -1386,7 +1385,7 @@ class _PatientInfoDelegate(QStyledItemDelegate):
|
||||
draw(value, rect)
|
||||
else:
|
||||
text = str(index.data(Qt.ItemDataRole.DisplayRole) or "")
|
||||
draw(text, rect, PALETTE["warning"] if index.column() == 6 and text == "待确认" else PALETTE["text"], index.column() == 5)
|
||||
draw(text, rect, "#A9691D" if index.column() == 6 and text == "待确认" else "#273244", index.column() == 5)
|
||||
painter.restore()
|
||||
|
||||
|
||||
@@ -1494,7 +1493,7 @@ class PatientListWorkspace(QWidget):
|
||||
self.keyword_edit.setMaximumWidth(360)
|
||||
self.keyword_edit.setPlaceholderText("患者姓名 / 手机号 / 助理 / 医生")
|
||||
self.keyword_edit.setClearButtonEnabled(True)
|
||||
self.keyword_edit.addAction(icons.icon("search", PALETTE["muted"], 16), QLineEdit.ActionPosition.LeadingPosition)
|
||||
self.keyword_edit.addAction(icons.icon("search", "#5D6B80", 16), QLineEdit.ActionPosition.LeadingPosition)
|
||||
self.keyword_edit.returnPressed.connect(self.search)
|
||||
search_row.addWidget(self.keyword_edit, 1)
|
||||
self.status_label = QLabel("患者状态:")
|
||||
@@ -1847,7 +1846,7 @@ class PatientListWorkspace(QWidget):
|
||||
)
|
||||
host = RowActions(row_actions, self.table)
|
||||
if host.more_button is not None:
|
||||
host.more_button.setIcon(icons.icon("chevron_down", PALETTE["muted"], 12))
|
||||
host.more_button.setIcon(icons.icon("chevron_down", "#5D6B80", 12))
|
||||
host.more_button.setIconSize(QSize(12, 12))
|
||||
host.more_button.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon)
|
||||
host.more_button.setLayoutDirection(Qt.LayoutDirection.RightToLeft)
|
||||
@@ -2080,7 +2079,7 @@ class _OrderComboBox(QComboBox):
|
||||
def paintEvent(self, event: Any) -> None:
|
||||
super().paintEvent(event)
|
||||
painter = QPainter(self)
|
||||
glyph = icons.pixmap("chevron_down", PALETTE["muted"], 14)
|
||||
glyph = icons.pixmap("chevron_down", "#5D6B80", 14)
|
||||
painter.drawPixmap(QRectF(self.width() - 24, (self.height() - 14) / 2, 14, 14), glyph, QRectF(glyph.rect()))
|
||||
painter.end()
|
||||
|
||||
@@ -2089,7 +2088,7 @@ class _OrderActionButton(QToolButton):
|
||||
def paintEvent(self, event: Any) -> None:
|
||||
super().paintEvent(event)
|
||||
painter = QPainter(self)
|
||||
glyph = icons.pixmap("chevron_down", PALETTE["muted"] if self.isEnabled() else PALETTE["disabled"], 14)
|
||||
glyph = icons.pixmap("chevron_down", "#5D6B80" if self.isEnabled() else "#97A4B6", 14)
|
||||
painter.drawPixmap(QRectF(self.width() - 23, (self.height() - 14) / 2, 14, 14), glyph, QRectF(glyph.rect()))
|
||||
painter.end()
|
||||
|
||||
@@ -2108,18 +2107,18 @@ class _OrderInfoDelegate(QStyledItemDelegate):
|
||||
painter.setClipRect(option.rect)
|
||||
selected = bool(option.state & QStyle.StateFlag.State_Selected)
|
||||
hovered = bool(option.state & QStyle.StateFlag.State_MouseOver)
|
||||
painter.fillRect(option.rect, QColor(PALETTE["accent_soft"] if selected else PALETTE["surface_alt"] if hovered else PALETTE["surface"]))
|
||||
painter.setPen(QColor(PALETTE["line"]))
|
||||
painter.fillRect(option.rect, QColor("#F5F8FF" if selected else "#F8FAFE" if hovered else "#FFFFFF"))
|
||||
painter.setPen(QColor("#E6EDF6"))
|
||||
painter.drawLine(option.rect.bottomLeft(), option.rect.bottomRight())
|
||||
if selected and index.column() == 0:
|
||||
painter.fillRect(option.rect.adjusted(0, 0, -option.rect.width() + 3, 0), QColor(PALETTE["accent"]))
|
||||
painter.fillRect(option.rect.adjusted(0, 0, -option.rect.width() + 3, 0), QColor("#1769E8"))
|
||||
rect = option.rect.adjusted(16, 0, -12, -1)
|
||||
font = QFont(body_family())
|
||||
font.setPixelSize(14)
|
||||
painter.setFont(font)
|
||||
text = str(index.data(Qt.ItemDataRole.DisplayRole) or "—")
|
||||
|
||||
def draw(value: str, target: Any, color: str = PALETTE["text"], right: bool = False) -> None:
|
||||
def draw(value: str, target: Any, color: str = "#273244", right: bool = False) -> None:
|
||||
painter.setPen(QColor(color))
|
||||
value = painter.fontMetrics().elidedText(value, Qt.TextElideMode.ElideRight, target.width())
|
||||
painter.drawText(target, Qt.AlignmentFlag.AlignVCenter | (Qt.AlignmentFlag.AlignRight if right else Qt.AlignmentFlag.AlignLeft), value)
|
||||
@@ -2139,7 +2138,7 @@ class _OrderInfoDelegate(QStyledItemDelegate):
|
||||
font.setWeight(QFont.Weight.Normal)
|
||||
font.setPixelSize(13)
|
||||
painter.setFont(font)
|
||||
draw(secondary, bottom, PALETTE["muted"])
|
||||
draw(secondary, bottom, "#5D6B80")
|
||||
else:
|
||||
draw(text, rect)
|
||||
elif column in (9, 11):
|
||||
@@ -2148,7 +2147,7 @@ class _OrderInfoDelegate(QStyledItemDelegate):
|
||||
draw(primary, top)
|
||||
font.setPixelSize(13)
|
||||
painter.setFont(font)
|
||||
draw(("(" if column == 9 else "") + secondary, bottom, PALETTE["muted"])
|
||||
draw(("(" if column == 9 else "") + secondary, bottom, "#5D6B80")
|
||||
else:
|
||||
draw(text, rect)
|
||||
elif column in (4, 5, 6):
|
||||
@@ -2159,10 +2158,10 @@ class _OrderInfoDelegate(QStyledItemDelegate):
|
||||
else:
|
||||
kind = "blue" if raw in {3, 5, 6, 7, 8, 11} else "danger" if raw in {4, 9, 10} else "warning" if raw in {1, 2, 12} else "neutral"
|
||||
foreground, background, border = {
|
||||
"blue": (PALETTE["accent"], PALETTE["accent_soft"], PALETTE["line_strong"]),
|
||||
"warning": (PALETTE["warning"], PALETTE["warning_soft"], PALETTE["warning_soft"]),
|
||||
"danger": (PALETTE["danger"], PALETTE["danger_soft"], PALETTE["danger_soft"]),
|
||||
"neutral": (PALETTE["muted"], PALETTE["disabled_surface"], PALETTE["line"]),
|
||||
"blue": ("#1769E8", "#F2F7FF", "#CEE0FA"),
|
||||
"warning": ("#AD640C", "#FFFAF2", "#F2DABD"),
|
||||
"danger": ("#BE4657", "#FFF5F6", "#F0D0D7"),
|
||||
"neutral": ("#5D6B80", "#F6F8FC", "#E2E9F2"),
|
||||
}[kind]
|
||||
font.setPixelSize(13)
|
||||
painter.setFont(font)
|
||||
@@ -2276,7 +2275,7 @@ class PatientOrdersWorkspace(QWidget):
|
||||
self.keyword_edit.setMinimumWidth(240)
|
||||
self.keyword_edit.setPlaceholderText("订单号 / 患者 / 手机号 / 处方ID / 诊单ID")
|
||||
self.keyword_edit.setClearButtonEnabled(True)
|
||||
self.keyword_edit.addAction(icons.icon("search", PALETTE["muted"], 16), QLineEdit.ActionPosition.LeadingPosition)
|
||||
self.keyword_edit.addAction(icons.icon("search", "#5D6B80", 16), QLineEdit.ActionPosition.LeadingPosition)
|
||||
self.keyword_edit.returnPressed.connect(self.search)
|
||||
self.filter_top_row.addWidget(self.keyword_edit, 1)
|
||||
self.audit_host = QWidget()
|
||||
@@ -2748,11 +2747,11 @@ class _ProgressInfoDelegate(QStyledItemDelegate):
|
||||
painter.setClipRect(option.rect)
|
||||
selected = bool(option.state & QStyle.StateFlag.State_Selected)
|
||||
hovered = bool(option.state & QStyle.StateFlag.State_MouseOver)
|
||||
painter.fillRect(option.rect, QColor(PALETTE["accent_soft"] if selected else PALETTE["surface_alt"] if hovered else PALETTE["surface"]))
|
||||
painter.setPen(QColor(PALETTE["line"]))
|
||||
painter.fillRect(option.rect, QColor("#F2F7FF" if selected else "#F8FAFE" if hovered else "#FFFFFF"))
|
||||
painter.setPen(QColor("#E6EDF6"))
|
||||
painter.drawLine(option.rect.bottomLeft(), option.rect.bottomRight())
|
||||
if selected and index.column() == 0:
|
||||
painter.fillRect(option.rect.adjusted(0, 0, -option.rect.width() + 3, 0), QColor(PALETTE["accent"]))
|
||||
painter.fillRect(option.rect.adjusted(0, 0, -option.rect.width() + 3, 0), QColor("#1769E8"))
|
||||
rect = option.rect.adjusted(16, 0, -16, -1)
|
||||
font = QFont(body_family())
|
||||
font.setPixelSize(14)
|
||||
@@ -2763,20 +2762,20 @@ class _ProgressInfoDelegate(QStyledItemDelegate):
|
||||
painter.setFont(font)
|
||||
raw_text = index.data(Qt.ItemDataRole.DisplayRole)
|
||||
text = "" if raw_text is None else str(raw_text)
|
||||
color = PALETTE["text"]
|
||||
color = "#273244"
|
||||
if not self.schedule and index.column() == 5 and text and text != "—":
|
||||
row = index.data(Qt.ItemDataRole.UserRole)
|
||||
status = str(first_value(row, "queue_status", default="") or "").lower()
|
||||
color = {
|
||||
"consulting": PALETTE["accent"], "next": PALETTE["accent_hover"],
|
||||
"waiting": PALETTE["warning"], "missed": PALETTE["danger"],
|
||||
}.get(status, PALETTE["muted"])
|
||||
"consulting": "#1769E8", "next": "#1555B6",
|
||||
"waiting": "#AD640C", "missed": "#BE4657",
|
||||
}.get(status, "#5D6B80")
|
||||
painter.setPen(QColor(color))
|
||||
alignment = Qt.AlignmentFlag.AlignVCenter
|
||||
alignment |= Qt.AlignmentFlag.AlignHCenter if self.schedule and 1 <= index.column() <= 5 else Qt.AlignmentFlag.AlignLeft
|
||||
painter.drawText(rect, alignment, painter.fontMetrics().elidedText(text, Qt.TextElideMode.ElideRight, rect.width()))
|
||||
if option.state & QStyle.StateFlag.State_HasFocus:
|
||||
painter.setPen(QColor(PALETTE["focus"]))
|
||||
painter.setPen(QColor("#75A5F0"))
|
||||
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||
painter.drawRect(option.rect.adjusted(1, 1, -2, -2))
|
||||
painter.restore()
|
||||
@@ -2876,7 +2875,7 @@ class PatientProgressWorkspace(QWidget):
|
||||
row = QHBoxLayout(frame)
|
||||
row.setContentsMargins(0, 0, 0, 0)
|
||||
row.setSpacing(0)
|
||||
divider = QFrame(frame)
|
||||
divider = QFrame()
|
||||
divider.setObjectName("ProgressMetricDivider")
|
||||
divider.setFixedSize(1, 60)
|
||||
divider.setVisible(key != "total")
|
||||
|
||||
@@ -24,7 +24,6 @@ from PySide6.QtWidgets import (
|
||||
)
|
||||
|
||||
from .. import motion
|
||||
from ..design_system import PALETTE
|
||||
from ..dialogs.prescription import PrescriptionTemplateDialog
|
||||
from ..dialogs.prescription_ai import PrescriptionAiReportDialog, can_open_ai_explain
|
||||
from ..filter_disclosure import FilterDisclosure
|
||||
@@ -120,7 +119,7 @@ def _metric_card(title: str, kind: str = "accent", glyph: str = "layers") -> Met
|
||||
icon.setProperty("metricIcon", True)
|
||||
icon.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
icon.setFixedSize(32, 32)
|
||||
color = PALETTE["accent"] if kind == "accent" else PALETTE["muted"]
|
||||
color = "#1769E8" if kind == "accent" else "#60789F"
|
||||
icon.setPixmap(_painted_icon(glyph, color, 25).pixmap(25, 25))
|
||||
card.layout().addWidget(icon)
|
||||
return card
|
||||
@@ -349,16 +348,16 @@ class PrescriptionLibraryPage(QWidget):
|
||||
table_layout.setSpacing(0)
|
||||
self.table = LibraryTable(
|
||||
[
|
||||
TableColumn("id", "ID", 72),
|
||||
TableColumn("prescription_name", "处方名称", 170),
|
||||
TableColumn("formula_type", "处方类型", 76, _formula_text),
|
||||
TableColumn("herbs", "药材数量", 76, _herb_count),
|
||||
TableColumn("herbs", "药材组成(部分)", 260, _herbs_detail),
|
||||
TableColumn("efficacy", "功效主治", 90, _efficacy_text),
|
||||
TableColumn("is_public", "公开范围", 134, _visibility_text),
|
||||
TableColumn("creator_name", "创建人", 136),
|
||||
TableColumn("create_time", "创建时间", 122, _create_time_cell),
|
||||
TableColumn("__actions__", "操作", 150, lambda _value, _row: ""),
|
||||
TableColumn("id", "ID", 62),
|
||||
TableColumn("prescription_name", "处方名称", 162),
|
||||
TableColumn("formula_type", "处方类型", 88, _formula_text),
|
||||
TableColumn("herbs", "药材数量", 84, _herb_count),
|
||||
TableColumn("herbs", "药材组成(部分)", 296, _herbs_detail),
|
||||
TableColumn("efficacy", "功效主治", 170, _efficacy_text),
|
||||
TableColumn("is_public", "公开范围", 135, _visibility_text),
|
||||
TableColumn("creator_name", "创建人", 100),
|
||||
TableColumn("create_time", "创建时间", 178, _create_time_cell),
|
||||
TableColumn("__actions__", "操作", 160, lambda _value, _row: ""),
|
||||
]
|
||||
)
|
||||
self.table.setObjectName("PrescriptionLibraryTable")
|
||||
@@ -372,6 +371,8 @@ class PrescriptionLibraryPage(QWidget):
|
||||
self.table.horizontalHeader().setMinimumSectionSize(36)
|
||||
self.table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Interactive)
|
||||
self.table.horizontalHeader().setDefaultAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
|
||||
for column, width in enumerate((54, 170, 76, 76, 260, 90, 134, 136, 122, 150)):
|
||||
self.table.setColumnWidth(column, width)
|
||||
for column in (0, 2, 3, 5, 9):
|
||||
self.table.horizontalHeaderItem(column).setTextAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
self.table.setWordWrap(False)
|
||||
@@ -544,7 +545,7 @@ class PrescriptionLibraryPage(QWidget):
|
||||
|
||||
name_item = self.table.item(row_index, 1)
|
||||
if name_item is not None:
|
||||
name_item.setForeground(QColor(PALETTE["heading"]))
|
||||
name_item.setForeground(QColor("#1A1C1F"))
|
||||
font = name_item.font()
|
||||
font.setWeight(QFont.Weight.Medium)
|
||||
name_item.setFont(font)
|
||||
|
||||
@@ -50,10 +50,8 @@ from PySide6.QtWidgets import (
|
||||
)
|
||||
|
||||
from .. import icons, motion
|
||||
from ..design_system import PALETTE, clinical_stylesheet
|
||||
from ..dialogs.issued_prescription_ai import (
|
||||
PrescriptionAiStatisticsDialog,
|
||||
agreement_safe_batch,
|
||||
agreement_text,
|
||||
batch_running,
|
||||
can_open_issued_ai,
|
||||
@@ -230,11 +228,11 @@ _ROLE_AVATAR = Qt.ItemDataRole.UserRole + 11
|
||||
_ROLE_LEAD_ICON = Qt.ItemDataRole.UserRole + 12
|
||||
|
||||
_TAG_PALETTE = {
|
||||
"accent": (PALETTE["accent"], PALETTE["accent_soft"]),
|
||||
"success": (PALETTE["success"], PALETTE["success_soft"]),
|
||||
"warning": (PALETTE["warning"], PALETTE["warning_soft"]),
|
||||
"danger": (PALETTE["danger"], PALETTE["danger_soft"]),
|
||||
"neutral": (PALETTE["muted"], PALETTE["surface_alt"]),
|
||||
"accent": ("#4F63D9", "#EEF1FA"),
|
||||
"success": ("#287B65", "#E7F8F1"),
|
||||
"warning": ("#A9691D", "#FFF5DF"),
|
||||
"danger": ("#BE4B58", "#FFF0F2"),
|
||||
"neutral": ("#606163", "#F7F7F7"),
|
||||
}
|
||||
|
||||
|
||||
@@ -294,7 +292,7 @@ class _RowDecorationDelegate(QStyledItemDelegate):
|
||||
glyph,
|
||||
QRectF(glyph.rect()),
|
||||
)
|
||||
painter.setPen(QColor(PALETTE["heading"]))
|
||||
painter.setPen(QColor("#1A1C1F"))
|
||||
painter.setFont(style_option.font)
|
||||
text_rect = rect.adjusted(28, 0, -8, 0)
|
||||
painter.drawText(
|
||||
@@ -307,17 +305,17 @@ class _RowDecorationDelegate(QStyledItemDelegate):
|
||||
else:
|
||||
initial = str(avatar)[:1] or "医"
|
||||
circle = QRectF(rect.left() + 8, rect.center().y() - 10, 20, 20)
|
||||
painter.setPen(QPen(QColor(PALETTE["line"]), 1.0))
|
||||
painter.setBrush(QColor(PALETTE["surface_alt"]))
|
||||
painter.setPen(QPen(QColor("#EDEDEE"), 1.0))
|
||||
painter.setBrush(QColor("#F7F7F7"))
|
||||
painter.drawEllipse(circle.adjusted(0.5, 0.5, -0.5, -0.5))
|
||||
initial_font = QFont(style_option.font)
|
||||
initial_font.setPixelSize(10)
|
||||
initial_font.setWeight(QFont.Weight.Medium)
|
||||
painter.setFont(initial_font)
|
||||
painter.setPen(QColor(PALETTE["muted"]))
|
||||
painter.setPen(QColor("#6A6B6D"))
|
||||
painter.drawText(circle, Qt.AlignmentFlag.AlignCenter, initial)
|
||||
painter.setFont(style_option.font)
|
||||
painter.setPen(QColor(PALETTE["heading"]))
|
||||
painter.setPen(QColor("#1A1C1F"))
|
||||
name_rect = rect.adjusted(35, 0, -8, 0)
|
||||
painter.drawText(
|
||||
name_rect,
|
||||
@@ -510,11 +508,11 @@ class _PrescriptionNumberDelegate(QStyledItemDelegate):
|
||||
text_option.setWrapMode(QTextOption.WrapMode.WrapAtWordBoundaryOrAnywhere)
|
||||
document.setDefaultTextOption(text_option)
|
||||
paragraphs = [
|
||||
f'<p style="margin:0;color:{PALETTE["heading"]};font-size:14px;font-weight:500">{escape(number)}</p>',
|
||||
f'<p style="margin:2px 0 0;color:{PALETTE["muted"]};font-size:12px;font-weight:400">ID: {escape(record_id)}</p>',
|
||||
f'<p style="margin:0;color:#1A1C1F;font-size:14px;font-weight:500">{escape(number)}</p>',
|
||||
f'<p style="margin:2px 0 0;color:#606163;font-size:12px;font-weight:400">ID: {escape(record_id)}</p>',
|
||||
]
|
||||
paragraphs.extend(
|
||||
f'<p style="margin:2px 0 0;color:{PALETTE["danger"]};font-size:13px;font-weight:400">'
|
||||
'<p style="margin:2px 0 0;color:#BE4B58;font-size:13px;font-weight:400">'
|
||||
+ escape(warning)
|
||||
+ "</p>"
|
||||
for warning in _order_warnings(row)
|
||||
@@ -604,14 +602,14 @@ class _DoctorOptionDelegate(QStyledItemDelegate):
|
||||
rect = option.rect.adjusted(2, 1, -2, -1)
|
||||
hovered = bool(option.state & QStyle.StateFlag.State_MouseOver)
|
||||
painter.setPen(Qt.PenStyle.NoPen)
|
||||
painter.setBrush(QColor(PALETTE["accent_soft"] if checked else PALETTE["canvas"] if hovered else PALETTE["surface"]))
|
||||
painter.setBrush(QColor("#EAF2FF" if checked else "#F3F7FD" if hovered else "#FFFFFF"))
|
||||
painter.drawRoundedRect(rect, 5, 5)
|
||||
box = QRectF(rect.left() + 10, rect.center().y() - 8, 16, 16)
|
||||
painter.setPen(QPen(QColor(PALETTE["accent"] if checked else PALETTE["line_strong"]), 1))
|
||||
painter.setBrush(QColor(PALETTE["accent"] if checked else PALETTE["surface"]))
|
||||
painter.setPen(QPen(QColor("#1769E8" if checked else "#B8C7DA"), 1))
|
||||
painter.setBrush(QColor("#1769E8" if checked else "#FFFFFF"))
|
||||
painter.drawRoundedRect(box, 3, 3)
|
||||
if checked:
|
||||
pen = QPen(QColor(PALETTE["surface"]), 2)
|
||||
pen = QPen(QColor("#FFFFFF"), 2)
|
||||
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
|
||||
painter.setPen(pen)
|
||||
x, y = int(box.x()), int(box.y())
|
||||
@@ -620,16 +618,16 @@ class _DoctorOptionDelegate(QStyledItemDelegate):
|
||||
font = QFont(body_family())
|
||||
font.setPixelSize(13)
|
||||
painter.setFont(font)
|
||||
painter.setPen(QColor(PALETTE["text"]))
|
||||
painter.setPen(QColor("#273244"))
|
||||
text_rect = rect.adjusted(38, 0, -54, 0)
|
||||
label = painter.fontMetrics().elidedText(str(index.data() or ""), Qt.TextElideMode.ElideRight, text_rect.width())
|
||||
painter.drawText(text_rect, Qt.AlignmentFlag.AlignVCenter, label)
|
||||
if checked:
|
||||
painter.setPen(QColor(PALETTE["accent"]))
|
||||
painter.setPen(QColor("#1769E8"))
|
||||
painter.drawText(rect.adjusted(0, 0, -12, 0), Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter, "已选")
|
||||
if option.state & QStyle.StateFlag.State_HasFocus:
|
||||
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||
painter.setPen(QPen(QColor(PALETTE["line_strong"]), 1))
|
||||
painter.setPen(QPen(QColor("#ADC8F2"), 1))
|
||||
painter.drawRoundedRect(rect, 5, 5)
|
||||
painter.restore()
|
||||
|
||||
@@ -675,18 +673,18 @@ class _DoctorSelectionDialog(QDialog):
|
||||
self.setObjectName("DoctorSelectionDialog")
|
||||
self.setWindowTitle("选择医生")
|
||||
self.resize(420, 500)
|
||||
self.setStyleSheet(clinical_stylesheet("""
|
||||
QDialog#DoctorSelectionDialog { background: $ds_surface; color: $ds_text; }
|
||||
QListWidget#DoctorOptionsList { background: $ds_surface; border: 1px solid $ds_line; border-radius: 6px; padding: 3px; }
|
||||
QLabel#DoctorSelectionCount { color: $ds_accent; font-size: 13px; }
|
||||
QDialog#DoctorSelectionDialog QLineEdit { border: 1px solid $ds_line; border-radius: 6px; }
|
||||
QDialog#DoctorSelectionDialog QLineEdit:focus { border-color: $ds_accent; }
|
||||
QDialog#DoctorSelectionDialog QPushButton { background: $ds_surface; color: $ds_text; border: 1px solid $ds_line; border-radius: 6px; }
|
||||
QDialog#DoctorSelectionDialog QPushButton:hover { background: $ds_canvas; border-color: $ds_line_strong; }
|
||||
QDialog#DoctorSelectionDialog QPushButton:disabled { color: $ds_disabled; }
|
||||
QDialog#DoctorSelectionDialog QPushButton#ConfirmDoctorSelection { background: $ds_accent; color: $ds_surface; border-color: $ds_accent; }
|
||||
QDialog#DoctorSelectionDialog QPushButton#ConfirmDoctorSelection:hover { background: $ds_accent_hover; border-color: $ds_accent_hover; }
|
||||
"""))
|
||||
self.setStyleSheet("""
|
||||
QDialog#DoctorSelectionDialog { background: #FFFFFF; color: #273244; }
|
||||
QListWidget#DoctorOptionsList { background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 6px; padding: 3px; }
|
||||
QLabel#DoctorSelectionCount { color: #1769E8; font-size: 13px; }
|
||||
QDialog#DoctorSelectionDialog QLineEdit { border: 1px solid #DBE5F2; border-radius: 6px; }
|
||||
QDialog#DoctorSelectionDialog QLineEdit:focus { border-color: #1769E8; }
|
||||
QDialog#DoctorSelectionDialog QPushButton { background: #FFFFFF; color: #273244; border: 1px solid #DBE5F2; border-radius: 6px; }
|
||||
QDialog#DoctorSelectionDialog QPushButton:hover { background: #F3F7FD; border-color: #ADC8F2; }
|
||||
QDialog#DoctorSelectionDialog QPushButton:disabled { color: #8A97A9; }
|
||||
QDialog#DoctorSelectionDialog QPushButton#ConfirmDoctorSelection { background: #1769E8; color: #FFFFFF; border-color: #1769E8; }
|
||||
QDialog#DoctorSelectionDialog QPushButton#ConfirmDoctorSelection:hover { background: #125DCE; border-color: #125DCE; }
|
||||
""")
|
||||
layout = QVBoxLayout(self)
|
||||
layout.setContentsMargins(16, 16, 16, 16)
|
||||
layout.setSpacing(10)
|
||||
@@ -794,9 +792,9 @@ class DoctorMultiSelect(QWidget):
|
||||
self.button.setText("、".join(names[:2]) + (f" 等{len(names)}人" if len(names) > 2 else ""))
|
||||
|
||||
|
||||
def _blue_prescription_icon(kind: str, color: str = PALETTE["accent"], size: int = 15) -> QIcon:
|
||||
def _blue_prescription_icon(kind: str, color: str = "#1769E8", size: int = 15) -> QIcon:
|
||||
result = QIcon(icons.icon(kind, color, size))
|
||||
result.addPixmap(icons.pixmap(kind, PALETTE["disabled"], size), QIcon.Mode.Disabled)
|
||||
result.addPixmap(icons.pixmap(kind, "#A4ADBA", size), QIcon.Mode.Disabled)
|
||||
return result
|
||||
|
||||
|
||||
@@ -804,7 +802,7 @@ class _PrescriptionCombo(QComboBox):
|
||||
def paintEvent(self, event: Any) -> None:
|
||||
super().paintEvent(event)
|
||||
painter = QPainter(self)
|
||||
glyph = icons.pixmap("chevron_down", PALETTE["muted"], 14)
|
||||
glyph = icons.pixmap("chevron_down", "#5D6B80", 14)
|
||||
painter.drawPixmap(QRectF(self.width() - 25, (self.height() - 14) / 2, 14, 14), glyph, QRectF(glyph.rect()))
|
||||
painter.end()
|
||||
|
||||
@@ -813,7 +811,7 @@ class _PrescriptionDateTime(QDateTimeEdit):
|
||||
def paintEvent(self, event: Any) -> None:
|
||||
super().paintEvent(event)
|
||||
painter = QPainter(self)
|
||||
glyph = icons.pixmap("calendar", PALETTE["muted"] if self.isEnabled() else PALETTE["disabled"], 14)
|
||||
glyph = icons.pixmap("calendar", "#5D6B80" if self.isEnabled() else "#8A97A9", 14)
|
||||
painter.drawPixmap(QRectF(self.width() - 25, (self.height() - 14) / 2, 14, 14), glyph, QRectF(glyph.rect()))
|
||||
painter.end()
|
||||
|
||||
@@ -826,7 +824,7 @@ class _PrescriptionDoctorButton(QPushButton):
|
||||
option.text = self.fontMetrics().elidedText(self.text(), Qt.TextElideMode.ElideRight, max(1, self.width() - 48))
|
||||
painter = QPainter(self)
|
||||
self.style().drawControl(QStyle.ControlElement.CE_PushButton, option, painter, self)
|
||||
glyph = icons.pixmap("chevron_down", PALETTE["muted"], 14)
|
||||
glyph = icons.pixmap("chevron_down", "#5D6B80", 14)
|
||||
painter.drawPixmap(QRectF(self.width() - 25, (self.height() - 14) / 2, 14, 14), glyph, QRectF(glyph.rect()))
|
||||
painter.end()
|
||||
|
||||
@@ -838,13 +836,13 @@ class _PrescriptionDoctorButton(QPushButton):
|
||||
def _prescription_cell_background(painter: QPainter, option: Any, index: QModelIndex) -> None:
|
||||
selected = bool(option.state & QStyle.StateFlag.State_Selected)
|
||||
hovered = bool(option.state & QStyle.StateFlag.State_MouseOver)
|
||||
painter.fillRect(option.rect, QColor(PALETTE["accent_soft"] if selected else PALETTE["surface_alt"] if hovered else PALETTE["surface"]))
|
||||
painter.setPen(QColor(PALETTE["line"]))
|
||||
painter.fillRect(option.rect, QColor("#F2F7FF" if selected else "#F8FAFE" if hovered else "#FFFFFF"))
|
||||
painter.setPen(QColor("#E6EDF6"))
|
||||
painter.drawLine(option.rect.bottomLeft(), option.rect.bottomRight())
|
||||
if selected and index.column() == 0:
|
||||
painter.fillRect(option.rect.adjusted(0, 0, -option.rect.width() + 3, 0), QColor(PALETTE["accent"]))
|
||||
painter.fillRect(option.rect.adjusted(0, 0, -option.rect.width() + 3, 0), QColor("#1769E8"))
|
||||
if option.state & QStyle.StateFlag.State_HasFocus:
|
||||
painter.setPen(QColor(PALETTE["focus"]))
|
||||
painter.setPen(QColor("#75A5F0"))
|
||||
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||
painter.drawRect(option.rect.adjusted(1, 1, -2, -2))
|
||||
|
||||
@@ -876,7 +874,7 @@ class _PrescriptionInfoDelegate(QStyledItemDelegate):
|
||||
font = QFont(body_family())
|
||||
font.setPixelSize(14)
|
||||
painter.setFont(font)
|
||||
painter.setPen(QColor(PALETTE["text"]))
|
||||
painter.setPen(QColor("#273244"))
|
||||
text = str(index.data(Qt.ItemDataRole.DisplayRole) or "")
|
||||
column = index.column()
|
||||
if column == 0:
|
||||
@@ -889,9 +887,9 @@ class _PrescriptionInfoDelegate(QStyledItemDelegate):
|
||||
elif column in (3, 6):
|
||||
kind = index.data(_ROLE_TAG_KIND)
|
||||
foreground, background = {
|
||||
"accent": (PALETTE["accent"], PALETTE["accent_soft"]), "success": (PALETTE["accent"], PALETTE["accent_soft"]),
|
||||
"warning": (PALETTE["warning"], PALETTE["warning_soft"]), "danger": (PALETTE["danger"], PALETTE["danger_soft"]),
|
||||
}.get(kind, (PALETTE["muted"], PALETTE["surface_alt"]))
|
||||
"accent": ("#1769E8", "#EDF4FF"), "success": ("#1769E8", "#EDF4FF"),
|
||||
"warning": ("#AD640C", "#FFF5E5"), "danger": ("#BE4657", "#FFF0F2"),
|
||||
}.get(kind, ("#5D6B80", "#F5F8FD"))
|
||||
font.setPixelSize(13)
|
||||
painter.setFont(font)
|
||||
label = painter.fontMetrics().elidedText(text, Qt.TextElideMode.ElideRight, max(1, rect.width() - 12))
|
||||
@@ -919,7 +917,7 @@ class _PrescriptionInfoDelegate(QStyledItemDelegate):
|
||||
font = QFont(body_family())
|
||||
font.setPixelSize(13)
|
||||
painter.setFont(font)
|
||||
painter.setPen(QColor(PALETTE["muted"]))
|
||||
painter.setPen(QColor("#5D6B80"))
|
||||
second_rect = first_rect.translated(0, 26)
|
||||
painter.drawText(second_rect, Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, painter.fontMetrics().elidedText(secondary, Qt.TextElideMode.ElideRight, rect.width()))
|
||||
else:
|
||||
@@ -943,11 +941,11 @@ class _PrescriptionNumberBlueDelegate(_PrescriptionNumberDelegate):
|
||||
text_option.setWrapMode(QTextOption.WrapMode.WrapAtWordBoundaryOrAnywhere)
|
||||
document.setDefaultTextOption(text_option)
|
||||
paragraphs = [
|
||||
f'<p style="margin:0;color:{PALETTE["text"]};font-size:14px;font-weight:400">{escape(number)}</p>',
|
||||
f'<p style="margin:6px 0 0;color:{PALETTE["muted"]};font-size:13px;font-weight:400">ID: {escape(record_id)}</p>',
|
||||
f'<p style="margin:0;color:#273244;font-size:14px;font-weight:400">{escape(number)}</p>',
|
||||
f'<p style="margin:6px 0 0;color:#5D6B80;font-size:13px;font-weight:400">ID: {escape(record_id)}</p>',
|
||||
]
|
||||
paragraphs.extend(
|
||||
f'<p style="margin:6px 0 0;color:{PALETTE["danger"]};font-size:13px;font-weight:400">' + escape(warning) + "</p>"
|
||||
'<p style="margin:6px 0 0;color:#BE4657;font-size:13px;font-weight:400">' + escape(warning) + "</p>"
|
||||
for warning in _order_warnings(row)
|
||||
)
|
||||
document.setHtml("".join(paragraphs))
|
||||
@@ -977,7 +975,7 @@ class _PrescriptionBlueTable(SortableTable):
|
||||
for button in widget.findChildren(QPushButton):
|
||||
kind = {"查看处方": "eye", "编辑处方": "pencil", "删除处方": "trash"}.get(button.accessibleName())
|
||||
if kind:
|
||||
button.setIcon(_blue_prescription_icon(kind, PALETTE["danger"] if kind == "trash" else PALETTE["accent"]))
|
||||
button.setIcon(_blue_prescription_icon(kind, "#BE4657" if kind == "trash" else "#1769E8"))
|
||||
|
||||
|
||||
class PrescriptionsPage(QWidget):
|
||||
@@ -1009,10 +1007,6 @@ class PrescriptionsPage(QWidget):
|
||||
self._mutation_pending = False
|
||||
self._ai_statuses: dict[int, dict[str, Any]] = {}
|
||||
self._ai_enabled = False
|
||||
self._agreement_visible = False
|
||||
self._capability_agreement_visible = False
|
||||
self._ai_capability_token = 0
|
||||
self._ai_capability_pending = False
|
||||
self._ai_request_token = 0
|
||||
self._ai_pending = False
|
||||
self._ai_timer = QTimer(self)
|
||||
@@ -1054,14 +1048,14 @@ class PrescriptionsPage(QWidget):
|
||||
self.orders_button.clicked.connect(lambda: self._open_orders())
|
||||
header.add_action(self.orders_button)
|
||||
self.ai_statistics_button = QPushButton("AI 一致度统计", header)
|
||||
self.ai_statistics_button.hide()
|
||||
self.ai_statistics_button.setVisible(has_permission(permissions, "tcm.prescriptionAi/statistics", default=False) and callable(getattr(repository, "prescription_ai_statistics", None)))
|
||||
self.ai_statistics_button.clicked.connect(self._open_ai_statistics)
|
||||
header.add_action(self.ai_statistics_button)
|
||||
self.add_button = QPushButton("新增处方", header)
|
||||
self.add_button.setObjectName("PrescriptionAddButton")
|
||||
self.add_button.setMinimumWidth(122)
|
||||
self.add_button.setProperty("variant", "primary")
|
||||
self.add_button.setIcon(_blue_prescription_icon("plus", PALETTE["surface"]))
|
||||
self.add_button.setIcon(_blue_prescription_icon("plus", "#FFFFFF"))
|
||||
self.add_button.setIconSize(QSize(15, 15))
|
||||
self.add_button.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||
self.add_button.setVisible(has_permission(permissions, "cf.prescription/add"))
|
||||
@@ -1080,7 +1074,7 @@ class PrescriptionsPage(QWidget):
|
||||
self.table_card = table_card
|
||||
root.addWidget(table_card, 1)
|
||||
for button, kind in ((self.view_button, "eye"), (self.edit_button, "pencil"), (self.delete_button, "trash")):
|
||||
button.setIcon(_blue_prescription_icon(kind, PALETTE["danger"] if kind == "trash" else PALETTE["accent"]))
|
||||
button.setIcon(_blue_prescription_icon(kind, "#BE4657" if kind == "trash" else "#1769E8"))
|
||||
self._load_doctor_options()
|
||||
|
||||
def _build_filters(self) -> QWidget:
|
||||
@@ -1227,7 +1221,7 @@ class PrescriptionsPage(QWidget):
|
||||
refresh = QPushButton("刷新")
|
||||
refresh.setProperty("variant", "ghost")
|
||||
refresh.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||
refresh.setIcon(_blue_prescription_icon("refresh", PALETTE["muted"]))
|
||||
refresh.setIcon(_blue_prescription_icon("refresh", "#5D6B80"))
|
||||
refresh.setIconSize(QSize(15, 15))
|
||||
refresh.clicked.connect(self.refresh)
|
||||
toolbar.addWidget(refresh)
|
||||
@@ -1288,7 +1282,7 @@ class PrescriptionsPage(QWidget):
|
||||
self.table.setItemDelegate(_PrescriptionInfoDelegate(self.table))
|
||||
self.table.setItemDelegateForColumn(1, _PrescriptionNumberBlueDelegate(self.table))
|
||||
self.table.horizontalHeader().sectionResized.connect(self._number_column_resized)
|
||||
self.table.horizontalHeaderItem(0).setIcon(_blue_prescription_icon("checkbox", PALETTE["disabled"], 14))
|
||||
self.table.horizontalHeaderItem(0).setIcon(_blue_prescription_icon("checkbox", "#8A97A9", 14))
|
||||
self.table.horizontalHeaderItem(0).setTextAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
self.table.itemSelectionChanged.connect(self._selection_changed)
|
||||
self.table.itemDoubleClicked.connect(lambda _item: self._view_selected())
|
||||
@@ -1443,7 +1437,6 @@ class PrescriptionsPage(QWidget):
|
||||
self._refresh_pending = False
|
||||
self._generation += 1
|
||||
generation = self._generation
|
||||
self._load_ai_capabilities()
|
||||
page_size = self._page_size
|
||||
start_time, end_time = self._date_filters()
|
||||
filters: dict[str, Any] = {
|
||||
@@ -1538,7 +1531,7 @@ class PrescriptionsPage(QWidget):
|
||||
|
||||
sn_item = self.table.item(row_index, 1)
|
||||
if sn_item is not None:
|
||||
sn_item.setForeground(QColor(PALETTE["heading"]))
|
||||
sn_item.setForeground(QColor("#1A1C1F"))
|
||||
font = sn_item.font()
|
||||
font.setWeight(QFont.Weight.Normal)
|
||||
sn_item.setFont(font)
|
||||
@@ -1663,7 +1656,6 @@ class PrescriptionsPage(QWidget):
|
||||
return
|
||||
method = getattr(self.repository, "list_prescription_ai_statuses", None)
|
||||
if not has_permission(self.permissions, "tcm.prescriptionAi/statuses", default=False):
|
||||
self._set_ai_columns(False)
|
||||
self.ai_status_notice.setText("AI 分析:当前账号没有查看分析状态的权限,请联系管理员授权。")
|
||||
return
|
||||
if not callable(method):
|
||||
@@ -1696,7 +1688,7 @@ class PrescriptionsPage(QWidget):
|
||||
changed = enabled != self._ai_enabled
|
||||
self._ai_enabled = enabled
|
||||
for column in (11, 12):
|
||||
self.table.setColumnHidden(column, not (enabled and self._agreement_visible))
|
||||
self.table.setColumnHidden(column, not enabled)
|
||||
if enabled:
|
||||
header = self.table.horizontalHeader()
|
||||
header.moveSection(header.visualIndex(11), header.visualIndex(4) + 1)
|
||||
@@ -1707,55 +1699,10 @@ class PrescriptionsPage(QWidget):
|
||||
if changed:
|
||||
self._decorate_rows()
|
||||
|
||||
def _set_agreement_visible(self, visible: bool) -> None:
|
||||
self._agreement_visible = visible
|
||||
for column in (11, 12):
|
||||
self.table.setColumnHidden(column, not (self._ai_enabled and visible))
|
||||
self.ai_statistics_button.setVisible(
|
||||
visible and has_permission(self.permissions, "tcm.prescriptionAi/statistics", default=False)
|
||||
and callable(getattr(self.repository, "prescription_ai_statistics", None)))
|
||||
if not visible:
|
||||
self._ai_statuses = {key: agreement_safe_batch(row, False) for key, row in self._ai_statuses.items()}
|
||||
for index in range(self.table.rowCount()):
|
||||
item = self.table.item(index, 12)
|
||||
if item is not None:
|
||||
item.setText("")
|
||||
item.setToolTip("")
|
||||
item.setData(Qt.ItemDataRole.AccessibleTextRole, "")
|
||||
|
||||
def _load_ai_capabilities(self) -> None:
|
||||
self._ai_capability_token += 1
|
||||
token, generation = self._ai_capability_token, self._generation
|
||||
self._ai_request_token += 1
|
||||
self._ai_pending = False
|
||||
self._capability_agreement_visible = False
|
||||
self._set_agreement_visible(False)
|
||||
method = getattr(self.repository, "get_prescription_ai_capabilities", None)
|
||||
self._ai_capability_pending = callable(method)
|
||||
if not callable(method):
|
||||
return
|
||||
run_async(method,
|
||||
on_success=lambda result: self._ai_capabilities_ready(result, token, generation),
|
||||
on_error=lambda _error: self._ai_capabilities_ready({}, token, generation))
|
||||
|
||||
def _ai_capabilities_ready(self, result: Any, token: int, generation: int) -> None:
|
||||
if token != self._ai_capability_token or generation != self._generation:
|
||||
return
|
||||
self._ai_capability_pending = False
|
||||
self._capability_agreement_visible = _row_mapping(result).get("agreement_visible") is True
|
||||
self._set_agreement_visible(self._capability_agreement_visible)
|
||||
if self._capability_agreement_visible:
|
||||
# A previous deny discarded scores, including completed cached batches.
|
||||
# Fetch them again after a fresh grant rather than displaying that cache.
|
||||
self._ai_statuses.clear()
|
||||
if self.isVisible() and not self._loading:
|
||||
self._load_ai_statuses()
|
||||
|
||||
def _ai_statuses_ready(self, result: Any, ids: list[int], token: int, generation: int) -> None:
|
||||
if token != self._ai_request_token or generation != self._generation or not self.isVisible():
|
||||
return
|
||||
data = _row_mapping(result)
|
||||
self._set_agreement_visible(self._capability_agreement_visible and data.get("agreement_visible") is True)
|
||||
self._set_ai_columns(data.get("enabled") is True)
|
||||
if not self._ai_enabled:
|
||||
self._ai_timer.stop()
|
||||
@@ -1766,17 +1713,15 @@ class PrescriptionsPage(QWidget):
|
||||
self.ai_status_notice.setToolTip("")
|
||||
self.ai_report_button.setToolTip("自动分析未启用;仍可查看已保存的历史报告。")
|
||||
return
|
||||
self.ai_status_notice.setText("AI 分析已启用:保存手工处方后自动生成两份报告。"
|
||||
+ ("可查看药味与剂量一致度。" if self._agreement_visible else ""))
|
||||
self.ai_status_notice.setText("AI 分析已启用:保存手工处方后自动生成两份报告,并显示药味与剂量一致度。")
|
||||
self.ai_status_notice.setToolTip("")
|
||||
self.ai_report_button.setToolTip("查看两份 AI 报告和候选处方。"
|
||||
+ ("可查看逐味对照。" if self._agreement_visible else ""))
|
||||
self.ai_report_button.setToolTip("查看两份 AI 报告、候选处方和逐味对照。")
|
||||
for value in ids:
|
||||
self._ai_statuses[value] = {}
|
||||
for batch in data.get("items") or []:
|
||||
value = _int(get_value(batch, "prescription_id"), 0)
|
||||
if value in ids:
|
||||
self._ai_statuses[value] = agreement_safe_batch(batch, self._agreement_visible and _row_mapping(batch).get("agreement_visible") is True)
|
||||
self._ai_statuses[value] = _row_mapping(batch)
|
||||
self._render_ai_statuses()
|
||||
if any(batch_running(self._ai_statuses.get(value)) for value in self._visible_ai_ids()):
|
||||
self._ai_timer.start()
|
||||
@@ -1796,13 +1741,13 @@ class PrescriptionsPage(QWidget):
|
||||
if batch is None and not blank:
|
||||
continue
|
||||
state = "" if blank else (state_text(batch) if batch else "尚无分析记录")
|
||||
agreement = "" if blank or not self._agreement_visible else agreement_text(batch)
|
||||
agreement = "" if blank else agreement_text(batch)
|
||||
for column, text in ((11, state), (12, agreement)):
|
||||
item = self.table.item(index, column)
|
||||
if item.text() != text:
|
||||
item.setText(text)
|
||||
changed = True
|
||||
item.setToolTip("" if blank or column == 12 and not self._agreement_visible else status_tooltip(batch))
|
||||
item.setToolTip("" if blank else status_tooltip(batch))
|
||||
item.setData(Qt.ItemDataRole.AccessibleTextRole, text)
|
||||
if changed:
|
||||
self.table.resizeRowsToContents()
|
||||
@@ -1812,7 +1757,6 @@ class PrescriptionsPage(QWidget):
|
||||
def _ai_statuses_error(self, error: Exception, token: int, generation: int) -> None:
|
||||
if token == self._ai_request_token and generation == self._generation:
|
||||
self._ai_timer.stop()
|
||||
self._set_agreement_visible(False)
|
||||
self._set_ai_columns(False)
|
||||
self.ai_status_notice.setText("AI 分析暂不可用:请稍后刷新;持续无法使用时,请联系管理员检查服务。")
|
||||
self.ai_status_notice.setToolTip(friendly_error(error))
|
||||
@@ -1837,13 +1781,13 @@ class PrescriptionsPage(QWidget):
|
||||
if _is_blank_prescription(row):
|
||||
return
|
||||
menu = QMenu(self.table)
|
||||
action = menu.addAction("AI 报告 / 逐味对照" if self._agreement_visible else "AI 报告")
|
||||
action = menu.addAction("AI 报告 / 逐味对照")
|
||||
action.triggered.connect(lambda: self._run_row_action(row, self._open_ai_report))
|
||||
self._ai_context_menu = menu
|
||||
menu.popup(self.table.viewport().mapToGlobal(position))
|
||||
|
||||
def _open_ai_statistics(self) -> None:
|
||||
if not self._agreement_visible or not has_permission(self.permissions, "tcm.prescriptionAi/statistics", default=False):
|
||||
if not has_permission(self.permissions, "tcm.prescriptionAi/statistics", default=False):
|
||||
return
|
||||
dialog = PrescriptionAiStatisticsDialog(self.repository, self.permissions, self)
|
||||
dialog.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose, True)
|
||||
@@ -2263,14 +2207,12 @@ class PrescriptionsPage(QWidget):
|
||||
if self.table.rowCount() == 0 and not self._loading:
|
||||
self.refresh()
|
||||
elif not self._loading:
|
||||
self._load_ai_capabilities()
|
||||
self._load_ai_statuses()
|
||||
|
||||
def hideEvent(self, event: Any) -> None:
|
||||
self._ai_timer.stop()
|
||||
self._ai_scroll_timer.stop()
|
||||
self._ai_request_token += 1
|
||||
self._ai_capability_token += 1
|
||||
self._ai_capability_pending = False
|
||||
self._ai_pending = False
|
||||
super().hideEvent(event)
|
||||
|
||||
|
||||
@@ -75,7 +75,6 @@ from PySide6.QtWidgets import (
|
||||
|
||||
from ...core.appointment_modes import appointment_type_description, appointment_type_value
|
||||
from .. import icons
|
||||
from ..design_system import PALETTE, clinical_stylesheet
|
||||
from ..diagnosis_drawer import DailyRecordPanel
|
||||
from ..diagnosis_editors import FlowLayout
|
||||
from ..dialogs import DiagnosisDialog
|
||||
@@ -90,7 +89,6 @@ from ..dialogs.prescription_ai import (
|
||||
)
|
||||
from ..filter_disclosure import FilterDisclosure
|
||||
from ..reception_style import body_family, heading_family, number_family
|
||||
from ..reception_workspace import RECEPTION_WORKSPACE_QSS, ReceptionWorkbench
|
||||
from ..report_provenance import report_provenance_lines
|
||||
from ..theme import mark_business_dialog
|
||||
from ..widgets import (
|
||||
@@ -323,11 +321,6 @@ QWidget#ReceptionPage QLabel#ReceptionPatientMeta {
|
||||
font-size: 13px;
|
||||
font-weight: 400;
|
||||
}
|
||||
QWidget#ReceptionPage QLabel#ReceptionCurrentAssistant {
|
||||
color: #273244;
|
||||
font-size: 13px;
|
||||
font-weight: 400;
|
||||
}
|
||||
QWidget#ReceptionPage QLabel#StatusBadge {
|
||||
font-size: 13px;
|
||||
font-weight: 400;
|
||||
@@ -1184,7 +1177,6 @@ QWidget#ReceptionPage QPushButton#ReceptionCompleteButton {
|
||||
border-radius: 5px;
|
||||
}
|
||||
QWidget#ReceptionPage QPushButton#ReceptionCompleteButton:enabled { background-color: #FFFFFF; }
|
||||
QWidget#ReceptionPage QPushButton#ReceptionMoreButton { padding: 0 6px; }
|
||||
QWidget#ReceptionPage QTabBar#ReceptionDetailTabs {
|
||||
border-top-left-radius: 0;
|
||||
border-top-right-radius: 0;
|
||||
@@ -1927,30 +1919,6 @@ def _queue_glucose_value(record: Any) -> object:
|
||||
)
|
||||
|
||||
|
||||
def _is_numeric_reading(value: object) -> bool:
|
||||
"""Separate a scalar measurement from a patient's free-text description."""
|
||||
return bool(re.fullmatch(
|
||||
r"(?:空腹(?:血糖)?[::]?\s*)?[-+]?\d+(?:\.\d+)?\s*(?:mmol/l|mg/l|mg/g|%)?",
|
||||
str("" if value is None else value).strip(), re.IGNORECASE,
|
||||
))
|
||||
|
||||
|
||||
def _reading_text(value: object, unit: str) -> str:
|
||||
text = display_text(value)
|
||||
if _is_numeric_reading(value) and unit.lower() not in text.lower():
|
||||
return f"{text} {unit}"
|
||||
return text
|
||||
|
||||
|
||||
def _history_fact(text: str, *captions: str) -> str | None:
|
||||
"""Lift an explicitly labelled fact into the overview; retain its source text."""
|
||||
for line in text.splitlines():
|
||||
caption, separator, value = re.sub(r"[::]", ":", line).partition(":")
|
||||
if separator and caption.strip() in captions and value.strip():
|
||||
return value.strip()
|
||||
return None
|
||||
|
||||
|
||||
def _glucose_tone(value: object) -> str:
|
||||
number = _as_float(value)
|
||||
if number is None:
|
||||
@@ -2021,7 +1989,7 @@ def _painted_reception_tab_icon(kind: str, size: int = 16) -> QIcon:
|
||||
outline (bubble / chart page / capsule / clipboard / calendar-clock).
|
||||
"""
|
||||
|
||||
return icons.icon(kind, PALETTE["muted"], size)
|
||||
return icons.icon(kind, "#5D6B80", size)
|
||||
|
||||
|
||||
def _painted_reception_action_icon(kind: str, color: str, size: int = 14) -> QIcon:
|
||||
@@ -2501,13 +2469,6 @@ class _ReceptionHero(QFrame):
|
||||
if layout.direction() != direction:
|
||||
layout.setDirection(direction)
|
||||
self.updateGeometry()
|
||||
action_group = getattr(self, "action_group", None)
|
||||
if action_group is not None:
|
||||
action_group.setDirection(
|
||||
QBoxLayout.Direction.LeftToRight
|
||||
if direction == QBoxLayout.Direction.TopToBottom and self.width() >= 620
|
||||
else QBoxLayout.Direction.TopToBottom
|
||||
)
|
||||
actions = getattr(self, "actions_layout", None)
|
||||
if actions is not None:
|
||||
compact = self.width() < 520
|
||||
@@ -2522,7 +2483,21 @@ class _ReceptionHero(QFrame):
|
||||
|
||||
|
||||
class _ClinicalInfoPanel(QWidget):
|
||||
"""Let the clinical history use the full reading column."""
|
||||
"""Stack history and measurements before their text gets squeezed."""
|
||||
|
||||
def resizeEvent(self, event: Any) -> None: # noqa: N802 - Qt override
|
||||
super().resizeEvent(event)
|
||||
layout = self.layout()
|
||||
if not isinstance(layout, QBoxLayout):
|
||||
return
|
||||
stacked = self.width() < 760
|
||||
direction = (
|
||||
QBoxLayout.Direction.TopToBottom if stacked else QBoxLayout.Direction.LeftToRight
|
||||
)
|
||||
if layout.direction() != direction:
|
||||
layout.setDirection(direction)
|
||||
layout.setStretch(0, 0 if stacked else 42)
|
||||
layout.setStretch(1, 0 if stacked else 58)
|
||||
|
||||
|
||||
class _ClinicalPageStack(QStackedWidget):
|
||||
@@ -2883,7 +2858,7 @@ class _ReceptionSparkIcon(QWidget):
|
||||
del event
|
||||
painter = QPainter(self)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
glyph = icons.pixmap("ai", PALETTE["accent"], 18)
|
||||
glyph = icons.pixmap("ai", "#1769E8", 18)
|
||||
painter.drawPixmap(QRectF(0, 0, 18, 18), glyph, QRectF(glyph.rect()))
|
||||
painter.end()
|
||||
|
||||
@@ -2897,9 +2872,9 @@ class _ReceptionAiSectionIcon(QWidget):
|
||||
|
||||
#: Section tone -> (plate, glyph tint, shared glyph name).
|
||||
_TONES = {
|
||||
"diagnosis": (PALETTE["accent_soft"], PALETTE["accent"], "report"),
|
||||
"risk": (PALETTE["accent_soft"], PALETTE["accent"], "alert"),
|
||||
"treatment": (PALETTE["accent_soft"], PALETTE["accent"], "meds"),
|
||||
"diagnosis": ("#EAF2FF", "#1769E8", "report"),
|
||||
"risk": ("#EAF2FF", "#1769E8", "alert"),
|
||||
"treatment": ("#EAF2FF", "#1769E8", "meds"),
|
||||
}
|
||||
|
||||
def __init__(self, tone: str, parent: QWidget | None = None) -> None:
|
||||
@@ -2950,9 +2925,9 @@ class _ReceptionAssistantIcon(QWidget):
|
||||
painter = QPainter(self)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
painter.setPen(Qt.PenStyle.NoPen)
|
||||
painter.setBrush(QColor(PALETTE["accent"]))
|
||||
painter.setBrush(QColor("#1769E8"))
|
||||
painter.drawRoundedRect(QRectF(1, 1, 22, 22), 4, 4)
|
||||
painter.setPen(QColor(PALETTE["surface"]))
|
||||
painter.setPen(QColor("#FFFFFF"))
|
||||
font = painter.font()
|
||||
font.setPixelSize(11)
|
||||
font.setBold(True)
|
||||
@@ -2976,7 +2951,7 @@ class _ReceptionSendButton(QPushButton):
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
painter.setPen(
|
||||
QPen(
|
||||
QColor(PALETTE["surface"]),
|
||||
QColor("#FFFFFF"),
|
||||
1.8,
|
||||
Qt.PenStyle.SolidLine,
|
||||
Qt.PenCapStyle.RoundCap,
|
||||
@@ -3054,7 +3029,7 @@ class _ReceptionDateButton(QPushButton):
|
||||
super().paintEvent(event)
|
||||
painter = QPainter(self)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
color = QColor(PALETTE["muted"])
|
||||
color = QColor("#5D6B80")
|
||||
painter.setPen(
|
||||
QPen(
|
||||
color,
|
||||
@@ -3088,7 +3063,7 @@ class _ReceptionAiExpandButton(QPushButton):
|
||||
del event
|
||||
painter = QPainter(self)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
color = QColor(PALETTE["accent"] if self.isEnabled() else PALETTE["disabled"])
|
||||
color = QColor("#1769E8" if self.isEnabled() else "#8E8F90")
|
||||
painter.setPen(
|
||||
QPen(
|
||||
color,
|
||||
@@ -3121,7 +3096,7 @@ class _ReceptionAiModelCombo(QComboBox):
|
||||
super().paintEvent(event)
|
||||
painter = QPainter(self)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
color = QColor(PALETTE["text"] if self.isEnabled() else PALETTE["disabled"])
|
||||
color = QColor("#273244" if self.isEnabled() else "#8E8F90")
|
||||
painter.setPen(
|
||||
QPen(
|
||||
color,
|
||||
@@ -3163,7 +3138,7 @@ class _ReceptionAiAnalysisDialog(QDialog):
|
||||
self.resize(920, 760)
|
||||
self.setMinimumSize(720, 560)
|
||||
self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose)
|
||||
self.setStyleSheet(clinical_stylesheet(RECEPTION_AI_DIALOG_QSS))
|
||||
self.setStyleSheet(RECEPTION_AI_DIALOG_QSS)
|
||||
|
||||
root = QVBoxLayout(self)
|
||||
root.setContentsMargins(18, 18, 18, 18)
|
||||
@@ -3366,11 +3341,7 @@ class _ReceptionAiAnalysisDialog(QDialog):
|
||||
source_label.setTextFormat(Qt.TextFormat.PlainText)
|
||||
source_label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
|
||||
source_label.setWordWrap(True)
|
||||
source_label.setStyleSheet(clinical_stylesheet(
|
||||
"color: $ds_muted; font-size: 12px; padding: 10px 14px; "
|
||||
"background: $ds_surface_alt; border: 1px solid $ds_line; "
|
||||
"border-radius: $ds_radius_control;"
|
||||
))
|
||||
source_label.setStyleSheet("color: #555B68; font-size: 12px; padding: 10px 14px; background: #F7F8FC; border: 1px solid #E4E8F2; border-radius: 8px;")
|
||||
body_layout.addWidget(source_label)
|
||||
self.source_label = source_label
|
||||
body_layout.addStretch(1)
|
||||
@@ -3619,9 +3590,9 @@ class _VitalMetricIcon(QWidget):
|
||||
painter = QPainter(self)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
painter.setPen(Qt.PenStyle.NoPen)
|
||||
painter.setBrush(QColor(PALETTE["accent_soft"]))
|
||||
painter.setBrush(QColor("#EAF2FF"))
|
||||
painter.drawRoundedRect(QRectF(0, 0, 22, 22), 6, 6)
|
||||
glyph = icons.pixmap(self._GLYPHS.get(self._kind, "pulse"), PALETTE["accent"], 15)
|
||||
glyph = icons.pixmap(self._GLYPHS.get(self._kind, "pulse"), "#1769E8", 15)
|
||||
painter.drawPixmap(QRectF(3.5, 3.5, 15, 15), glyph, QRectF(glyph.rect()))
|
||||
painter.end()
|
||||
|
||||
@@ -3641,7 +3612,7 @@ class _LifestyleIcon(QWidget):
|
||||
del event
|
||||
painter = QPainter(self)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
glyph = icons.pixmap(self._GLYPHS.get(self._kind, "exercise"), PALETTE["muted"], 16)
|
||||
glyph = icons.pixmap(self._GLYPHS.get(self._kind, "exercise"), "#5D6B80", 16)
|
||||
painter.drawPixmap(QRectF(0, 0, 16, 16), glyph, QRectF(glyph.rect()))
|
||||
painter.end()
|
||||
|
||||
@@ -3677,7 +3648,7 @@ class _GenderMark(QWidget):
|
||||
return
|
||||
painter = QPainter(self)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
pen = QPen(QColor(PALETTE["muted"]), 1.35)
|
||||
pen = QPen(QColor("#5D6B80"), 1.35)
|
||||
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
|
||||
pen.setJoinStyle(Qt.PenJoinStyle.RoundJoin)
|
||||
painter.setPen(pen)
|
||||
@@ -3742,7 +3713,7 @@ class _ReceptionQueueSpinner(QWidget):
|
||||
del event
|
||||
painter = QPainter(self)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
pen = QPen(QColor(PALETTE["accent"]), 2.2)
|
||||
pen = QPen(QColor("#1769E8"), 2.2)
|
||||
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
|
||||
painter.setPen(pen)
|
||||
painter.drawArc(QRectF(2, 2, 14, 14), self._angle * 16, 250 * 16)
|
||||
@@ -3784,13 +3755,13 @@ class QueueRow(QWidget):
|
||||
super().__init__(parent)
|
||||
self.setObjectName("ReceptionQueueRow")
|
||||
self._selected = False
|
||||
self.setFixedHeight(82)
|
||||
self.setFixedHeight(104)
|
||||
self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, False)
|
||||
layout = QVBoxLayout(self)
|
||||
layout.setContentsMargins(14, 12, 12, 12)
|
||||
layout.setSpacing(8)
|
||||
layout.setContentsMargins(20, 17, 16, 17)
|
||||
layout.setSpacing(10)
|
||||
top = QHBoxLayout()
|
||||
top.setSpacing(8)
|
||||
top.setSpacing(14)
|
||||
name = QLabel(
|
||||
display_text(first_value(record, "patient_name", "name", default="未命名患者"))
|
||||
)
|
||||
@@ -3838,27 +3809,23 @@ class QueueRow(QWidget):
|
||||
layout.addLayout(top)
|
||||
bottom = QHBoxLayout()
|
||||
bottom.setSpacing(8)
|
||||
summary = _queue_condition_summary(record)
|
||||
subline = QLabel("" if summary == "暂无病情摘要" else summary)
|
||||
subline.setToolTip(summary if summary != "暂无病情摘要" else "")
|
||||
subline = QLabel(_queue_condition_summary(record))
|
||||
subline.setObjectName("ReceptionQueueSubline")
|
||||
subline.setMinimumWidth(0)
|
||||
subline.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Preferred)
|
||||
bottom.addWidget(subline, 1)
|
||||
metric = _queue_glucose_value(record)
|
||||
drop = _GlucoseDropIcon(_glucose_tone(metric), self)
|
||||
drop.setVisible(metric not in (None, "") and _is_numeric_reading(metric))
|
||||
drop.setVisible(metric not in (None, ""))
|
||||
self.glucose_drop = drop
|
||||
bottom.addWidget(drop, 0, Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
|
||||
metric_label = QLabel(
|
||||
(_reading_text(metric, "mmol/L") if _is_numeric_reading(metric) else "血糖有描述")
|
||||
if metric not in (None, "") else "",
|
||||
f"{display_text(metric)} mmol/L" if metric not in (None, "") else "",
|
||||
self,
|
||||
)
|
||||
metric_label.setObjectName("ReceptionQueueMetric")
|
||||
tone = _glucose_tone(metric) if _is_numeric_reading(metric) else "description"
|
||||
tone = _glucose_tone(metric)
|
||||
metric_label.setProperty("tone", tone)
|
||||
metric_label.setToolTip(display_text(metric))
|
||||
metric_label.setVisible(metric not in (None, ""))
|
||||
bottom.addWidget(metric_label, 0, Qt.AlignmentFlag.AlignRight)
|
||||
layout.addLayout(bottom)
|
||||
@@ -3878,15 +3845,15 @@ class QueueRow(QWidget):
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
rect = QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5)
|
||||
if self._selected:
|
||||
painter.setBrush(QColor(PALETTE["accent_soft"]))
|
||||
painter.setPen(QPen(QColor(PALETTE["line"]), 1))
|
||||
painter.setBrush(QColor("#EAF2FF"))
|
||||
painter.setPen(QPen(QColor("#E5ECF6"), 1))
|
||||
else:
|
||||
painter.setBrush(QColor(PALETTE["surface"]))
|
||||
painter.setPen(QPen(QColor(PALETTE["line"]), 1))
|
||||
painter.drawRoundedRect(rect, 10, 10)
|
||||
painter.setBrush(QColor("#FFFFFF"))
|
||||
painter.setPen(QPen(QColor("#E5ECF6"), 1))
|
||||
painter.drawRoundedRect(rect, 6, 6)
|
||||
if self._selected:
|
||||
painter.setPen(Qt.PenStyle.NoPen)
|
||||
painter.setBrush(QColor(PALETTE["accent"]))
|
||||
painter.setBrush(QColor("#1769E8"))
|
||||
painter.drawRoundedRect(QRectF(1.2, 1, 3.2, self.height() - 2), 1.6, 1.6)
|
||||
|
||||
|
||||
@@ -4079,7 +4046,7 @@ class ReceptionDailyRecordsPanel(DailyRecordPanel):
|
||||
font = item.font()
|
||||
font.setWeight(QFont.Weight.DemiBold if high else QFont.Weight.Normal)
|
||||
item.setFont(font)
|
||||
item.setForeground(QBrush(QColor(PALETTE["danger"] if high else PALETTE["text"])))
|
||||
item.setForeground(QBrush(QColor("#BE4B58" if high else "#273244")))
|
||||
item.setBackground(
|
||||
QBrush(
|
||||
QColor(
|
||||
@@ -4108,11 +4075,9 @@ class ReceptionPage(QWidget):
|
||||
super().__init__(parent)
|
||||
self.setObjectName("ReceptionPage")
|
||||
self.setStyleSheet(
|
||||
clinical_stylesheet(
|
||||
(RECEPTION_QSS + RECEPTION_WORKSPACE_QSS).replace("$body_family", body_family())
|
||||
.replace("$heading_family", heading_family())
|
||||
.replace("$number_family", number_family())
|
||||
)
|
||||
RECEPTION_QSS.replace("$body_family", body_family())
|
||||
.replace("$heading_family", heading_family())
|
||||
.replace("$number_family", number_family())
|
||||
)
|
||||
self.repository = repository
|
||||
self.permissions = permissions
|
||||
@@ -4210,7 +4175,7 @@ class ReceptionPage(QWidget):
|
||||
)
|
||||
|
||||
root = QVBoxLayout(self)
|
||||
root.setContentsMargins(12, 16, 12, 12)
|
||||
root.setContentsMargins(11, 16, 11, 20)
|
||||
root.setSpacing(0)
|
||||
|
||||
splitter = QSplitter(Qt.Orientation.Horizontal)
|
||||
@@ -4221,8 +4186,8 @@ class ReceptionPage(QWidget):
|
||||
splitter.addWidget(detail_panel)
|
||||
splitter.setStretchFactor(0, 0)
|
||||
splitter.setStretchFactor(1, 1)
|
||||
splitter.setHandleWidth(12)
|
||||
splitter.setSizes([286, 1185])
|
||||
splitter.setHandleWidth(10)
|
||||
splitter.setSizes([399, 1072])
|
||||
root.addWidget(splitter, 1)
|
||||
|
||||
self.poll_timer = QTimer(self)
|
||||
@@ -4239,7 +4204,7 @@ class ReceptionPage(QWidget):
|
||||
super().resizeEvent(event)
|
||||
panel = getattr(self, "queue_panel", None)
|
||||
if panel is not None:
|
||||
width = 272 if self.width() < 1100 else 286
|
||||
width = 340 if self.width() < 1000 else 399
|
||||
if panel.minimumWidth() != width:
|
||||
panel.setFixedWidth(width)
|
||||
|
||||
@@ -4255,9 +4220,9 @@ class ReceptionPage(QWidget):
|
||||
panel = QFrame()
|
||||
panel.setObjectName("ReceptionQueuePanel")
|
||||
self.queue_panel = panel
|
||||
panel.setFixedWidth(286)
|
||||
panel.setFixedWidth(399)
|
||||
layout = QVBoxLayout(panel)
|
||||
layout.setContentsMargins(10, 14, 10, 10)
|
||||
layout.setContentsMargins(14, 14, 12, 14)
|
||||
layout.setSpacing(10)
|
||||
|
||||
header = QWidget(panel)
|
||||
@@ -4269,7 +4234,7 @@ class ReceptionPage(QWidget):
|
||||
header_layout.addWidget(title)
|
||||
header_layout.addStretch(1)
|
||||
self.refresh_button = QPushButton("", header)
|
||||
self.refresh_button.setIcon(icons.icon("refresh", PALETTE["muted"], 18))
|
||||
self.refresh_button.setIcon(icons.icon("refresh", "#5D6B80", 18))
|
||||
self.refresh_button.setObjectName("ReceptionRefreshButton")
|
||||
self.refresh_button.setFixedSize(34, 32)
|
||||
self.refresh_button.setAccessibleName("刷新接诊台")
|
||||
@@ -4309,7 +4274,7 @@ class ReceptionPage(QWidget):
|
||||
search_row.addWidget(self.search_edit, 1)
|
||||
filter_layout.addLayout(search_row)
|
||||
|
||||
filter_row = QGridLayout()
|
||||
filter_row = QHBoxLayout()
|
||||
filter_row.setSpacing(6)
|
||||
for status, label in ((None, "全部"), (1, "待接诊"), (2, "问诊中"), (3, "已完成")):
|
||||
button = QPushButton(label, self.queue_filter_panel)
|
||||
@@ -4320,8 +4285,7 @@ class ReceptionPage(QWidget):
|
||||
lambda _checked=False, value=status: self._set_queue_filter(value)
|
||||
)
|
||||
self._queue_filter_buttons[status] = button
|
||||
position = len(self._queue_filter_buttons) - 1
|
||||
filter_row.addWidget(button, position // 2, position % 2)
|
||||
filter_row.addWidget(button, 1)
|
||||
self._queue_filter_buttons[1].setChecked(True)
|
||||
filter_layout.addLayout(filter_row)
|
||||
layout.addWidget(self.queue_filter_panel)
|
||||
@@ -4365,7 +4329,7 @@ class ReceptionPage(QWidget):
|
||||
def _build_detail_panel(self) -> QWidget:
|
||||
panel = QFrame()
|
||||
panel.setObjectName("ReceptionDetailPanel")
|
||||
panel.setMinimumWidth(390)
|
||||
panel.setMinimumWidth(430)
|
||||
panel_layout = QVBoxLayout(panel)
|
||||
panel_layout.setContentsMargins(0, 0, 0, 0)
|
||||
panel_layout.setSpacing(0)
|
||||
@@ -4381,7 +4345,7 @@ class ReceptionPage(QWidget):
|
||||
scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
|
||||
scroll.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded)
|
||||
content = QWidget(scroll)
|
||||
content.setMinimumWidth(0)
|
||||
content.setMinimumWidth(390)
|
||||
content.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred)
|
||||
detail_layout = QVBoxLayout(content)
|
||||
detail_layout.setContentsMargins(0, 0, 0, 0)
|
||||
@@ -4389,9 +4353,9 @@ class ReceptionPage(QWidget):
|
||||
|
||||
hero = _ReceptionHero(content)
|
||||
hero.setObjectName("ReceptionHero")
|
||||
hero.setMinimumHeight(96)
|
||||
hero.setMinimumHeight(112)
|
||||
hero_layout = QVBoxLayout(hero)
|
||||
hero_layout.setContentsMargins(18, 16, 18, 16)
|
||||
hero_layout.setContentsMargins(16, 22, 16, 22)
|
||||
hero_layout.setSpacing(4)
|
||||
self.detail_banner = MessageBanner(parent=hero)
|
||||
hero_layout.addWidget(self.detail_banner)
|
||||
@@ -4404,7 +4368,7 @@ class ReceptionPage(QWidget):
|
||||
self.patient_avatar_label = QLabel("患", hero)
|
||||
self.patient_avatar_label.setObjectName("ReceptionAvatar")
|
||||
self.patient_avatar_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
self.patient_avatar_label.setFixedSize(48, 48)
|
||||
self.patient_avatar_label.setFixedSize(64, 64)
|
||||
identity_head.addWidget(self.patient_avatar_label)
|
||||
identity = QVBoxLayout()
|
||||
identity.setSpacing(8)
|
||||
@@ -4430,18 +4394,8 @@ class ReceptionPage(QWidget):
|
||||
actions.setContentsMargins(0, 0, 0, 0)
|
||||
actions.setSpacing(14)
|
||||
actions.addStretch(1)
|
||||
action_group = QVBoxLayout()
|
||||
hero.action_group = action_group
|
||||
action_group.setContentsMargins(0, 0, 0, 0)
|
||||
action_group.setSpacing(6)
|
||||
self.current_assistant_label = QLabel("当前医助:—", hero)
|
||||
self.current_assistant_label.setObjectName("ReceptionCurrentAssistant")
|
||||
self.current_assistant_label.setTextFormat(Qt.TextFormat.PlainText)
|
||||
self.current_assistant_label.setWordWrap(True)
|
||||
action_group.addWidget(self.current_assistant_label)
|
||||
action_group.addLayout(actions)
|
||||
patient_head.addLayout(action_group)
|
||||
patient_head.setAlignment(action_group, Qt.AlignmentFlag.AlignBottom)
|
||||
patient_head.addLayout(actions)
|
||||
patient_head.setAlignment(actions, Qt.AlignmentFlag.AlignBottom)
|
||||
|
||||
self.complete_button = _ReceptionCompleteButton(hero)
|
||||
self.complete_button.clicked.connect(self._complete_appointment)
|
||||
@@ -4460,9 +4414,7 @@ class ReceptionPage(QWidget):
|
||||
self.video_button.setProperty("variant", "primary")
|
||||
self.video_button.clicked.connect(self._request_video)
|
||||
actions.addWidget(self.video_button)
|
||||
self.more_button = QPushButton(hero)
|
||||
self.more_button.setIcon(icons.icon("more", PALETTE["muted"], 16))
|
||||
self.more_button.setIconSize(QSize(16, 16))
|
||||
self.more_button = QPushButton("···", hero)
|
||||
self.more_button.setToolTip("更多操作")
|
||||
self.more_button.setAccessibleName("更多操作")
|
||||
self.more_button.setObjectName("ReceptionMoreButton")
|
||||
@@ -4506,7 +4458,7 @@ class ReceptionPage(QWidget):
|
||||
|
||||
clinical_card = QFrame(content)
|
||||
clinical_card.setObjectName("ReceptionClinicalCard")
|
||||
clinical_card.setMinimumHeight(0)
|
||||
clinical_card.setMinimumHeight(526)
|
||||
clinical_card.setSizePolicy(
|
||||
QSizePolicy.Policy.Expanding,
|
||||
QSizePolicy.Policy.Minimum,
|
||||
@@ -4544,18 +4496,15 @@ class ReceptionPage(QWidget):
|
||||
QSizePolicy.Policy.Minimum,
|
||||
)
|
||||
consultation_layout = QHBoxLayout(consultation_page)
|
||||
consultation_layout.setContentsMargins(18, 18, 18, 18)
|
||||
consultation_layout.setContentsMargins(12, 22, 12, 13)
|
||||
consultation_layout.setSpacing(10)
|
||||
self.clinical_info_group = consultation_page
|
||||
|
||||
history_card = QFrame(consultation_page)
|
||||
history_card.setObjectName("ReceptionHistoryCard")
|
||||
history_layout = QVBoxLayout(history_card)
|
||||
history_layout.setContentsMargins(0, 0, 0, 0)
|
||||
history_layout.setSpacing(14)
|
||||
history_title = QLabel("病情与用药", history_card)
|
||||
history_title.setObjectName("ReceptionCaseHeading")
|
||||
history_layout.addWidget(history_title)
|
||||
history_layout.setContentsMargins(8, 4, 18, 0)
|
||||
history_layout.setSpacing(15)
|
||||
self.case_labels: dict[str, QLabel] = {}
|
||||
|
||||
def add_case_field(
|
||||
@@ -4565,8 +4514,7 @@ class ReceptionPage(QWidget):
|
||||
*,
|
||||
stacked: bool = False,
|
||||
) -> None:
|
||||
field = QFrame(history_card)
|
||||
field.setObjectName("ReceptionCaseField")
|
||||
field = QWidget(history_card)
|
||||
if stacked:
|
||||
field_layout = QVBoxLayout(field)
|
||||
field_layout.setContentsMargins(0, 0, 0, 0)
|
||||
@@ -4593,10 +4541,8 @@ class ReceptionPage(QWidget):
|
||||
self.case_labels[key] = value_label
|
||||
target.addWidget(field)
|
||||
|
||||
add_case_field(history_layout, "chief", "本次主诉", stacked=True)
|
||||
add_case_field(history_layout, "medication", "当前用药", stacked=True)
|
||||
add_case_field(history_layout, "course", "患病时长")
|
||||
add_case_field(history_layout, "present", "现病史原文", stacked=True)
|
||||
add_case_field(history_layout, "chief", "主诉", stacked=True)
|
||||
add_case_field(history_layout, "present", "现病史", stacked=True)
|
||||
add_case_field(history_layout, "past", "既往史")
|
||||
add_case_field(history_layout, "family", "家族史")
|
||||
add_case_field(history_layout, "allergy", "过敏史")
|
||||
@@ -4634,35 +4580,20 @@ class ReceptionPage(QWidget):
|
||||
|
||||
add_case_field(history_layout, "diet", "饮食习惯")
|
||||
history_layout.addStretch(1)
|
||||
consultation_layout.addWidget(history_card, 1)
|
||||
consultation_layout.addWidget(history_card, 42)
|
||||
|
||||
right_clinical = QWidget(consultation_page)
|
||||
right_layout = QVBoxLayout(right_clinical)
|
||||
right_layout.setContentsMargins(0, 0, 0, 0)
|
||||
right_layout.setSpacing(10)
|
||||
|
||||
self.patient_summary_card, self.patient_summary_labels = self._field_card(
|
||||
"患者基本信息",
|
||||
(("性别 / 年龄", "gender_age"), ("联系方式", "phone"),
|
||||
("患病时长", "course"), ("已记录诊断", "diagnosis")),
|
||||
)
|
||||
self.patient_summary_card.setObjectName("ReceptionPatientSummaryCard")
|
||||
self.patient_summary_card.setAccessibleName("患者基本信息")
|
||||
for label in self.patient_summary_labels.values():
|
||||
label.setObjectName("ReceptionPatientSummaryValue")
|
||||
label.setStyleSheet("")
|
||||
label.setTextFormat(Qt.TextFormat.PlainText)
|
||||
label.setMinimumWidth(0)
|
||||
label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
|
||||
right_layout.addWidget(self.patient_summary_card)
|
||||
|
||||
vitals_card = QFrame(right_clinical)
|
||||
vitals_card.setObjectName("ReceptionVitalsCard")
|
||||
vitals_card.setMinimumHeight(0)
|
||||
vitals_card.setMinimumHeight(152)
|
||||
vitals_card.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum)
|
||||
vitals_layout = QVBoxLayout(vitals_card)
|
||||
vitals_layout.setContentsMargins(14, 14, 14, 14)
|
||||
vitals_layout.setSpacing(8)
|
||||
vitals_layout.setContentsMargins(12, 4, 2, 18)
|
||||
vitals_layout.setSpacing(12)
|
||||
vitals_title = QLabel("生命体征", vitals_card)
|
||||
vitals_title.setProperty("receptionBlockTitle", True)
|
||||
vitals_layout.addWidget(vitals_title)
|
||||
@@ -4716,9 +4647,7 @@ class ReceptionPage(QWidget):
|
||||
cell_layout.addStretch(1)
|
||||
self.vital_labels[key] = value_label
|
||||
self.vital_unit_labels[key] = unit_label
|
||||
row, position, span = ((0, 0, 1), (0, 1, 1), (0, 2, 1), (1, 0, 2), (1, 2, 1))[column]
|
||||
vitals_grid.addWidget(cell, row, position, 1, span)
|
||||
for column in range(3):
|
||||
vitals_grid.addWidget(cell, 0, column)
|
||||
vitals_grid.setColumnStretch(column, 1)
|
||||
vitals_layout.addLayout(vitals_grid)
|
||||
right_layout.addWidget(vitals_card)
|
||||
@@ -4726,15 +4655,12 @@ class ReceptionPage(QWidget):
|
||||
labs_card = QFrame(right_clinical)
|
||||
labs_card.setObjectName("ReceptionLabsCard")
|
||||
labs_layout = QVBoxLayout(labs_card)
|
||||
labs_layout.setContentsMargins(14, 14, 14, 14)
|
||||
labs_layout.setContentsMargins(12, 3, 2, 0)
|
||||
labs_layout.setSpacing(9)
|
||||
labs_title = QLabel("检查结果", labs_card)
|
||||
labs_title.setProperty("receptionBlockTitle", True)
|
||||
labs_layout.addWidget(labs_title)
|
||||
labs_grid = QGridLayout()
|
||||
self.lab_grid = labs_grid
|
||||
self.lab_cells: dict[str, QFrame] = {}
|
||||
self._show_missing_labs = False
|
||||
labs_grid.setContentsMargins(0, 0, 0, 0)
|
||||
labs_grid.setHorizontalSpacing(7)
|
||||
labs_grid.setVerticalSpacing(7)
|
||||
@@ -4754,7 +4680,7 @@ class ReceptionPage(QWidget):
|
||||
cell = QFrame(labs_card)
|
||||
cell.setObjectName("ReceptionLabCell")
|
||||
cell_layout = QVBoxLayout(cell)
|
||||
cell_layout.setContentsMargins(0, 6, 0, 8)
|
||||
cell_layout.setContentsMargins(10, 10, 8, 6)
|
||||
cell_layout.setSpacing(6)
|
||||
caption_label = QLabel(caption, cell)
|
||||
caption_label.setProperty("receptionMetricCaption", True)
|
||||
@@ -4771,20 +4697,13 @@ class ReceptionPage(QWidget):
|
||||
cell_layout.addStretch(1)
|
||||
self.lab_labels[key] = value_label
|
||||
self.lab_state_labels[key] = state_label
|
||||
self.lab_cells[key] = cell
|
||||
row, column = divmod(index, 2)
|
||||
row, column = divmod(index, 4)
|
||||
labs_grid.addWidget(cell, row, column)
|
||||
labs_grid.setRowStretch(row, 1)
|
||||
labs_grid.setColumnStretch(column, 1)
|
||||
labs_layout.addLayout(labs_grid)
|
||||
self.labs_empty_label = QLabel("暂未录入检查结果", labs_card)
|
||||
self.labs_empty_label.setProperty("role", "muted")
|
||||
labs_layout.addWidget(self.labs_empty_label)
|
||||
self.lab_missing_button = QPushButton("", labs_card)
|
||||
self.lab_missing_button.setObjectName("ReceptionMissingLabsButton")
|
||||
self.lab_missing_button.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||
self.lab_missing_button.clicked.connect(self._toggle_missing_labs)
|
||||
labs_layout.addWidget(self.lab_missing_button)
|
||||
right_layout.addWidget(labs_card)
|
||||
labs_layout.addLayout(labs_grid, 1)
|
||||
right_layout.addWidget(labs_card, 1)
|
||||
consultation_layout.addWidget(right_clinical, 58)
|
||||
self.clinical_pages.addWidget(consultation_page)
|
||||
|
||||
appointment_card, self.appointment_labels = self._field_card(
|
||||
@@ -5088,6 +5007,7 @@ class ReceptionPage(QWidget):
|
||||
health_layout.addWidget(self.health_summary_label)
|
||||
self.health_scroll = add_scrolling_page(health_card)
|
||||
detail_layout.addWidget(clinical_card)
|
||||
detail_layout.addSpacing(10)
|
||||
|
||||
ai_panels = _ReceptionAiPanels(content)
|
||||
ai_panels.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum)
|
||||
@@ -5293,9 +5213,7 @@ class ReceptionPage(QWidget):
|
||||
self.ai_source_label.setTextFormat(Qt.TextFormat.PlainText)
|
||||
self.ai_source_label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
|
||||
self.ai_source_label.setWordWrap(True)
|
||||
self.ai_source_label.setStyleSheet(clinical_stylesheet(
|
||||
"color: $ds_muted; font-size: 12px;"
|
||||
))
|
||||
self.ai_source_label.setStyleSheet("color: #5B6474; font-size: 11px;")
|
||||
analysis_layout.addWidget(self.ai_source_label)
|
||||
|
||||
self.ai_detail_actions_host = QWidget(analysis_card)
|
||||
@@ -5369,7 +5287,7 @@ class ReceptionPage(QWidget):
|
||||
assistant_header.addStretch(1)
|
||||
assistant_layout.addLayout(assistant_header)
|
||||
assistant_hint = QLabel(
|
||||
"结合当前患者资料,快速核对问诊要点。",
|
||||
"您好,我是 AI 问诊助手,有什么可以帮助您了解患者情况的吗?",
|
||||
assistant_card,
|
||||
)
|
||||
assistant_hint.setObjectName("ReceptionAiAssistantHint")
|
||||
@@ -5383,10 +5301,8 @@ class ReceptionPage(QWidget):
|
||||
|
||||
self.ai_prompt_buttons: list[QPushButton] = []
|
||||
|
||||
def prompt_button(label: str, question: str) -> QPushButton:
|
||||
def prompt_button(label: str) -> QPushButton:
|
||||
button = QPushButton(label, assistant_card)
|
||||
button.setToolTip(question)
|
||||
button.setAccessibleName(question)
|
||||
button.setProperty("receptionAiPrompt", True)
|
||||
button.setMinimumWidth(0)
|
||||
button.setSizePolicy(
|
||||
@@ -5394,20 +5310,20 @@ class ReceptionPage(QWidget):
|
||||
QSizePolicy.Policy.Fixed,
|
||||
)
|
||||
button.clicked.connect(
|
||||
lambda _checked=False, prompt=question: self._open_ai_report_for_prompt(prompt)
|
||||
lambda _checked=False, prompt=label: self._open_ai_report_for_prompt(prompt)
|
||||
)
|
||||
self.ai_prompt_buttons.append(button)
|
||||
return button
|
||||
|
||||
prompt_host = _AiFlowHost(assistant_card, horizontal_spacing=6, vertical_spacing=6)
|
||||
prompt_host = _AiFlowHost(assistant_card, horizontal_spacing=8, vertical_spacing=8)
|
||||
prompt_host.setObjectName("ReceptionAiPrompts")
|
||||
for label, question in (
|
||||
("检查建议", "基于当前病史,下一步检查建议?"),
|
||||
("用药核对", "该患者的用药调整建议?"),
|
||||
("健康教育", "糖尿病教育要点有哪些?"),
|
||||
("并发症筛查", "并发症筛查建议?"),
|
||||
for label in (
|
||||
"基于当前病史,下一步检查建议?",
|
||||
"该患者的用药调整建议?",
|
||||
"糖尿病教育要点有哪些?",
|
||||
"并发症筛查建议?",
|
||||
):
|
||||
prompt_host.flow.addWidget(prompt_button(label, question))
|
||||
prompt_host.flow.addWidget(prompt_button(label))
|
||||
assistant_layout.addWidget(prompt_host)
|
||||
assistant_layout.addStretch(1)
|
||||
|
||||
@@ -5425,65 +5341,17 @@ class ReceptionPage(QWidget):
|
||||
assistant_input_row.addWidget(self.ai_send_button)
|
||||
assistant_input_host.hide()
|
||||
ai_row.addWidget(assistant_card, 23)
|
||||
insights = QWidget()
|
||||
insights_layout = QVBoxLayout(insights)
|
||||
insights_layout.setContentsMargins(0, 0, 0, 0)
|
||||
insights_layout.setSpacing(12)
|
||||
insights_layout.addWidget(right_clinical)
|
||||
insights_layout.addWidget(ai_panels)
|
||||
insights_layout.addStretch(1)
|
||||
detail_layout.addWidget(ai_panels)
|
||||
|
||||
self.detail_tabs.currentChanged.connect(self._detail_tab_changed)
|
||||
self._detail_tab_changed(0)
|
||||
|
||||
scroll.setWidget(content)
|
||||
detail_layout.removeWidget(hero)
|
||||
detail_page = QWidget()
|
||||
workspace_layout = QVBoxLayout(detail_page)
|
||||
workspace_layout.setContentsMargins(0, 0, 0, 0)
|
||||
workspace_layout.setSpacing(12)
|
||||
workspace_layout.addWidget(hero)
|
||||
self.workbench = ReceptionWorkbench(scroll, insights, detail_page)
|
||||
self.insights_scroll = self.workbench.insights_scroll
|
||||
workspace_layout.addWidget(self.workbench, 1)
|
||||
self.detail_stack.addWidget(detail_page)
|
||||
self.detail_stack.addWidget(scroll)
|
||||
panel_layout.addWidget(self.detail_stack)
|
||||
self._reset_detail_content()
|
||||
return panel
|
||||
|
||||
def _toggle_missing_labs(self) -> None:
|
||||
self._show_missing_labs = not self._show_missing_labs
|
||||
self._sync_lab_rows()
|
||||
|
||||
def _sync_lab_rows(self) -> None:
|
||||
recorded = 0
|
||||
row = column = 0
|
||||
for key, cell in self.lab_cells.items():
|
||||
self.lab_grid.removeWidget(cell)
|
||||
text = self.lab_labels[key].text().strip()
|
||||
has_value = text not in {"", "—", "正在加载…"}
|
||||
recorded += int(has_value)
|
||||
visible = has_value or self._show_missing_labs
|
||||
cell.setVisible(visible)
|
||||
if not visible:
|
||||
continue
|
||||
wide = bool(cell.property("description")) and has_value
|
||||
if wide and column:
|
||||
row += 1
|
||||
column = 0
|
||||
self.lab_grid.addWidget(cell, row, column, 1, 2 if wide else 1)
|
||||
if wide or column:
|
||||
row += 1
|
||||
column = 0
|
||||
else:
|
||||
column = 1
|
||||
missing = len(self.lab_cells) - recorded
|
||||
self.labs_empty_label.setVisible(recorded == 0 and not self._show_missing_labs)
|
||||
self.lab_missing_button.setVisible(missing > 0)
|
||||
self.lab_missing_button.setText(
|
||||
"收起未记录项" if self._show_missing_labs else f"显示 {missing} 项未记录"
|
||||
)
|
||||
|
||||
def _detail_tab_changed(self, index: int) -> None:
|
||||
if not 0 <= index < self.detail_tabs.count():
|
||||
return
|
||||
@@ -7161,7 +7029,7 @@ class ReceptionPage(QWidget):
|
||||
def _add_queue_row(self, record: Any) -> None:
|
||||
item = QListWidgetItem()
|
||||
item.setData(Qt.ItemDataRole.UserRole, record)
|
||||
item.setSizeHint(QSize(0, 88))
|
||||
item.setSizeHint(QSize(0, 120))
|
||||
self.queue_list.addItem(item)
|
||||
self.queue_list.setItemWidget(item, QueueRow(record))
|
||||
|
||||
@@ -7466,7 +7334,6 @@ class ReceptionPage(QWidget):
|
||||
self._pending_tongue_images.clear()
|
||||
self._pending_report_files.clear()
|
||||
self._render_pending_attachments()
|
||||
self.insights_scroll.verticalScrollBar().setValue(0)
|
||||
self._selected_record = record
|
||||
self._selected_appointment_id = appointment_id
|
||||
self._selected_detail = None
|
||||
@@ -8018,14 +7885,9 @@ class ReceptionPage(QWidget):
|
||||
)
|
||||
)
|
||||
)
|
||||
# reception normalises these fields from the diagnosis's current
|
||||
# assistant, matching the recipient of the notification action.
|
||||
assistant_name = display_text(first_value(appointment, "assistant_name"), "")
|
||||
assistant_id = _as_int(first_value(appointment, "assistant_id"), None)
|
||||
missing_name = "姓名暂缺" if assistant_id else "未分配" if assistant_id == 0 else "—"
|
||||
self.current_assistant_label.setText(f"当前医助:{assistant_name or missing_name}")
|
||||
self.current_assistant_label.setToolTip(self.current_assistant_label.text())
|
||||
self.appointment_labels["assistant"].setText(assistant_name or "—")
|
||||
self.appointment_labels["assistant"].setText(
|
||||
display_text(first_value(appointment, "assistant_name"))
|
||||
)
|
||||
self.appointment_labels["type"].setText(
|
||||
appointment_type_description(appointment_type_value(appointment))
|
||||
)
|
||||
@@ -8128,12 +7990,6 @@ class ReceptionPage(QWidget):
|
||||
)
|
||||
self.patient_labels["customer"].setText(display_text(customer))
|
||||
self.patient_labels["prescription"].setText("已开具" if has_prescription else "暂未开具")
|
||||
demographics = " · ".join(
|
||||
part for part in (gender if gender != "—" else "",
|
||||
f"{age}岁" if age not in (None, "") else "") if part
|
||||
)
|
||||
self._set_patient_summary_value("gender_age", demographics)
|
||||
self._set_patient_summary_value("phone", self.patient_labels["phone"].text())
|
||||
|
||||
systolic = first_value(
|
||||
diagnosis,
|
||||
@@ -8224,15 +8080,6 @@ class ReceptionPage(QWidget):
|
||||
"0",
|
||||
}
|
||||
|
||||
def _set_patient_summary_value(self, key: str, value: Any) -> None:
|
||||
label = self.patient_summary_labels[key]
|
||||
text = self._case_display_text(value)
|
||||
text = "未记录" if text == "—" else text
|
||||
label.setText(text)
|
||||
label.setProperty("missing", text in {"未记录", "正在加载…"})
|
||||
label.style().unpolish(label)
|
||||
label.style().polish(label)
|
||||
|
||||
def _set_case_metric(self, key: str, value: Any, *, alert: bool = False) -> None:
|
||||
label = self.case_metric_labels[key]
|
||||
caption = {
|
||||
@@ -8460,7 +8307,8 @@ class ReceptionPage(QWidget):
|
||||
blood_sugar_text = self._case_display_text(blood_sugar)
|
||||
if blood_sugar_text.startswith("空腹"):
|
||||
blood_sugar_text = blood_sugar_text[2:].lstrip(":: ")
|
||||
blood_sugar_text = _reading_text(blood_sugar_text, "mmol/L")
|
||||
if "mmol/l" not in blood_sugar_text.lower():
|
||||
blood_sugar_text = f"{blood_sugar_text} mmol/L"
|
||||
case_items["空腹血糖"] = blood_sugar_text
|
||||
lines.append(f"空腹血糖:{blood_sugar_text}")
|
||||
|
||||
@@ -8519,10 +8367,6 @@ class ReceptionPage(QWidget):
|
||||
)
|
||||
case_values = {
|
||||
"chief": chief,
|
||||
"medication": case_value("current_medications", "current_medicine", "current_medication")
|
||||
or _history_fact(str(present or ""), "在用药物", "当前用药", "用药情况"),
|
||||
"course": case_value("disease_course_text", "disease_course", "course_text", "diabetes_discovery_year_text")
|
||||
or _history_fact(str(present or ""), "患病时长", "病程", "患病时间"),
|
||||
"present": present,
|
||||
"past": past,
|
||||
"family": family,
|
||||
@@ -8532,10 +8376,6 @@ class ReceptionPage(QWidget):
|
||||
}
|
||||
for key, value in case_values.items():
|
||||
self.case_labels[key].setText(display_text(value))
|
||||
self._set_patient_summary_value("course", case_values["course"])
|
||||
self._set_patient_summary_value(
|
||||
"diagnosis", case_value("clinical_diagnosis", "diagnosis_name", "disease_name")
|
||||
)
|
||||
|
||||
lab_definitions: dict[str, tuple[tuple[str, ...], str, tuple[str, ...]]] = {
|
||||
"fasting": (
|
||||
@@ -8574,17 +8414,17 @@ class ReceptionPage(QWidget):
|
||||
health_lines: list[str] = []
|
||||
for key, (value_keys, unit, status_keys) in lab_definitions.items():
|
||||
value = case_value(*value_keys)
|
||||
numeric = _is_numeric_reading(value)
|
||||
text = _reading_text(value, unit)
|
||||
text = display_text(value)
|
||||
if value not in (None, "") and unit.lower() not in str(value).lower():
|
||||
text = f"{text} {unit}"
|
||||
self.lab_labels[key].setText(text)
|
||||
self.lab_cells[key].setProperty("description", value not in (None, "") and not numeric)
|
||||
status_value = case_value(*status_keys)
|
||||
computed = _lab_status_for_value(key, value) if numeric else None
|
||||
computed = _lab_status_for_value(key, value)
|
||||
status_label = self.lab_state_labels[key]
|
||||
status_label.setProperty(
|
||||
"warning", key in {"fasting", "postprandial"} and _glucose_tone(value) == "warn"
|
||||
)
|
||||
if status_value not in (None, "") and numeric:
|
||||
if status_value not in (None, ""):
|
||||
status_text = display_text(status_value)
|
||||
if status_text.strip().lower() in {"正常", "normal", "0", "阴性"}:
|
||||
status_text = "正常"
|
||||
@@ -8619,7 +8459,6 @@ class ReceptionPage(QWidget):
|
||||
status_label.setVisible(False)
|
||||
if value not in (None, ""):
|
||||
health_lines.append(f"{self.lab_labels[key].parentWidget().findChild(QLabel).text()}:{text}")
|
||||
self._sync_lab_rows()
|
||||
|
||||
clinical_diagnosis = case_value("clinical_diagnosis", "diagnosis")
|
||||
health_header = (
|
||||
@@ -8982,15 +8821,11 @@ class ReceptionPage(QWidget):
|
||||
)
|
||||
self.patient_meta_label.setText("正在核对患者、诊单与预约信息…" if seed else "—")
|
||||
self.patient_meta_label.setToolTip("")
|
||||
self.current_assistant_label.setText("当前医助:正在加载…" if seed else "当前医助:—")
|
||||
self.current_assistant_label.setToolTip("")
|
||||
self.detail_status.set_status("—", "neutral")
|
||||
for label in getattr(self, "appointment_labels", {}).values():
|
||||
label.setText("—")
|
||||
for label in getattr(self, "patient_labels", {}).values():
|
||||
label.setText("—")
|
||||
for key in self.patient_summary_labels:
|
||||
self._set_patient_summary_value(key, "正在加载…" if seed else None)
|
||||
if hasattr(self, "diagnosis_text"):
|
||||
self._set_case_placeholder(
|
||||
"正在加载病例…" if seed else "尚未填写病例信息"
|
||||
@@ -9041,8 +8876,6 @@ class ReceptionPage(QWidget):
|
||||
for key, label in self.lab_labels.items():
|
||||
label.setText("—")
|
||||
self.lab_state_labels[key].setVisible(False)
|
||||
self._show_missing_labs = False
|
||||
self._sync_lab_rows()
|
||||
self._render_notes([])
|
||||
self._update_action_state(seed or {}, {})
|
||||
|
||||
@@ -9053,10 +8886,6 @@ class ReceptionPage(QWidget):
|
||||
return
|
||||
self.patient_meta_label.setText(message)
|
||||
self.patient_meta_label.setToolTip("")
|
||||
self.current_assistant_label.setText("当前医助:—")
|
||||
self.current_assistant_label.setToolTip("")
|
||||
for key in self.patient_summary_labels:
|
||||
self._set_patient_summary_value(key, None)
|
||||
self._set_case_placeholder(message)
|
||||
self.prescription_hint.setText("处方:患者详情加载失败")
|
||||
self.prescription_hint.setProperty("casePrescriptionState", "unknown")
|
||||
@@ -9085,8 +8914,6 @@ class ReceptionPage(QWidget):
|
||||
for key, label in self.lab_labels.items():
|
||||
label.setText("—")
|
||||
self.lab_state_labels[key].setVisible(False)
|
||||
self._show_missing_labs = False
|
||||
self._sync_lab_rows()
|
||||
|
||||
def _update_action_state(self, appointment: Any, diagnosis: Any) -> None:
|
||||
appointment_id = _record_id(appointment) or self._selected_appointment_id
|
||||
|
||||
@@ -1,126 +1,119 @@
|
||||
"""Scoped surfaces for the approved patient order-management workspace."""
|
||||
|
||||
from string import Template
|
||||
|
||||
from .design_system import clinical_stylesheet
|
||||
from .reception_style import body_family
|
||||
|
||||
|
||||
def patient_orders_stylesheet() -> str:
|
||||
return clinical_stylesheet(Template(_ORDERS).safe_substitute(body=body_family()))
|
||||
|
||||
|
||||
_ORDERS = """
|
||||
#PatientOrdersWorkspace { background: transparent; color: $ds_text; }
|
||||
#OrderWorkspaceContent, #OrderWorkspaceScroll { background: transparent; border: 0; }
|
||||
#PatientOrdersWorkspace QLabel, #PatientOrdersWorkspace QPushButton,
|
||||
#PatientOrdersWorkspace QToolButton, #PatientOrdersWorkspace QLineEdit,
|
||||
#PatientOrdersWorkspace QComboBox, #PatientOrdersWorkspace QDateEdit,
|
||||
#PatientOrdersWorkspace QCheckBox, #PatientOrdersWorkspace QTableWidget {
|
||||
font-family: "$body"; font-size: 14px; font-weight: 400; color: $ds_text;
|
||||
}
|
||||
#PatientOrdersWorkspace QLabel[role="muted"] { font-size: 13px; color: $ds_muted; }
|
||||
#PatientOrdersWorkspace QFrame#OrderFilterCard,
|
||||
#PatientOrdersWorkspace QFrame#OrderTableCard {
|
||||
background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_panel;
|
||||
}
|
||||
#PatientOrdersWorkspace QFrame#OrderSummaryStrip { background: transparent; border: 0; }
|
||||
#PatientOrdersWorkspace QPushButton, #PatientOrdersWorkspace QToolButton {
|
||||
min-height: 38px; max-height: 38px; padding: 0 16px; border: 1px solid transparent;
|
||||
border-radius: $ds_radius_control; background: $ds_surface_alt; color: $ds_text;
|
||||
}
|
||||
#PatientOrdersWorkspace QPushButton:hover, #PatientOrdersWorkspace QToolButton:hover {
|
||||
background: $ds_surface_alt; border-color: $ds_line_strong; color: $ds_accent;
|
||||
}
|
||||
#PatientOrdersWorkspace QPushButton:pressed, #PatientOrdersWorkspace QToolButton:pressed { background: $ds_accent_soft; }
|
||||
#PatientOrdersWorkspace QPushButton:focus, #PatientOrdersWorkspace QToolButton:focus { border-color: $ds_focus; }
|
||||
#PatientOrdersWorkspace QPushButton#OrderSearchButton,
|
||||
#PatientOrdersWorkspace QPushButton#OrderDetailButton {
|
||||
color: $ds_surface; background: $ds_accent; border-color: $ds_accent;
|
||||
}
|
||||
#PatientOrdersWorkspace QPushButton#OrderSearchButton:hover,
|
||||
#PatientOrdersWorkspace QPushButton#OrderDetailButton:hover { background: $ds_accent_hover; border-color: $ds_accent_hover; }
|
||||
#PatientOrdersWorkspace QPushButton#OrderSearchButton:pressed,
|
||||
#PatientOrdersWorkspace QPushButton#OrderDetailButton:pressed { background: $ds_accent_pressed; border-color: $ds_accent_pressed; }
|
||||
#PatientOrdersWorkspace QPushButton#OrderSearchButton:focus,
|
||||
#PatientOrdersWorkspace QPushButton#OrderDetailButton:focus { border-color: $ds_focus; }
|
||||
#PatientOrdersWorkspace QPushButton:disabled, #PatientOrdersWorkspace QToolButton:disabled,
|
||||
#PatientOrdersWorkspace QPushButton#OrderSearchButton:disabled,
|
||||
#PatientOrdersWorkspace QPushButton#OrderDetailButton:disabled {
|
||||
color: $ds_disabled; background: $ds_disabled_surface; border-color: $ds_line;
|
||||
}
|
||||
#PatientOrdersWorkspace QLineEdit, #PatientOrdersWorkspace QComboBox,
|
||||
#PatientOrdersWorkspace QDateEdit {
|
||||
min-height: 38px; max-height: 38px; padding: 0 10px; font-size: 13px;
|
||||
background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_control;
|
||||
selection-background-color: $ds_accent_soft; selection-color: $ds_text;
|
||||
}
|
||||
#PatientOrdersWorkspace QLineEdit:focus, #PatientOrdersWorkspace QComboBox:focus,
|
||||
#PatientOrdersWorkspace QDateEdit:focus { border-color: $ds_focus; }
|
||||
#PatientOrdersWorkspace QLineEdit QToolButton {
|
||||
min-height: 0; max-height: 24px; min-width: 0; border: 0; padding: 0; background: transparent;
|
||||
}
|
||||
#PatientOrdersWorkspace QComboBox { padding-right: 30px; }
|
||||
#PatientOrdersWorkspace QComboBox::drop-down { border: 0; width: 28px; background: transparent; }
|
||||
#PatientOrdersWorkspace QComboBox::down-arrow { image: none; width: 0; height: 0; }
|
||||
#PatientOrdersWorkspace QComboBox QAbstractItemView {
|
||||
font-family: "$body"; font-size: 13px; color: $ds_text; background: $ds_surface;
|
||||
border: 1px solid $ds_line; outline: 0; selection-background-color: $ds_accent_soft; selection-color: $ds_accent;
|
||||
}
|
||||
#PatientOrdersWorkspace QComboBox QAbstractItemView::item { min-height: 30px; padding: 3px 10px; }
|
||||
#PatientOrdersWorkspace QDateEdit { padding-right: 26px; }
|
||||
#PatientOrdersWorkspace QDateEdit::drop-down { border: 0; width: 24px; background: transparent; }
|
||||
#PatientOrdersWorkspace QDateEdit::down-arrow { image: none; width: 0; height: 0; }
|
||||
#PatientOrdersWorkspace QDateEdit:disabled { color: $ds_disabled; background: $ds_disabled_surface; border-color: $ds_line; }
|
||||
#PatientOrdersWorkspace QCalendarWidget {
|
||||
font-family: "$body"; font-size: 13px; background: $ds_surface; color: $ds_text;
|
||||
}
|
||||
#PatientOrdersWorkspace QCalendarWidget QWidget#qt_calendar_navigationbar { background: $ds_surface_alt; }
|
||||
#PatientOrdersWorkspace QCalendarWidget QToolButton {
|
||||
min-height: 28px; max-height: 28px; padding: 0 8px; border: 0; background: transparent;
|
||||
font-family: "$body"; font-size: 13px; color: $ds_text;
|
||||
}
|
||||
#PatientOrdersWorkspace QCalendarWidget QToolButton:hover { background: $ds_accent_soft; }
|
||||
#PatientOrdersWorkspace QCalendarWidget QAbstractItemView {
|
||||
font-family: "$body"; font-size: 13px; background: $ds_surface; alternate-background-color: $ds_surface;
|
||||
color: $ds_text; selection-background-color: $ds_accent; selection-color: $ds_surface; outline: 0;
|
||||
}
|
||||
#PatientOrdersWorkspace QCheckBox { spacing: 9px; font-size: 13px; }
|
||||
#PatientOrdersWorkspace QCheckBox::indicator {
|
||||
width: 15px; height: 15px; border: 1px solid $ds_line_strong; border-radius: 3px; background: $ds_surface;
|
||||
}
|
||||
#PatientOrdersWorkspace QCheckBox::indicator:checked { background: $ds_accent; border-color: $ds_accent; }
|
||||
#PatientOrdersWorkspace QCheckBox::indicator:hover { border-color: $ds_focus; }
|
||||
#PatientOrdersWorkspace QCheckBox:focus { color: $ds_accent; }
|
||||
#PatientOrdersWorkspace QFrame#OrderMetricCell { background: transparent; border: 0; }
|
||||
#PatientOrdersWorkspace QFrame#OrderMetricDivider { border: 0; background: $ds_line; }
|
||||
#PatientOrdersWorkspace QLabel[orderMetricCaption="true"] { color: $ds_muted; font-size: 13px; }
|
||||
#PatientOrdersWorkspace QLabel[orderMetricValue="true"] { color: $ds_text; font-size: 18px; font-weight: 500; }
|
||||
#PatientOrdersWorkspace QLabel#OrderAmountMetric { color: $ds_accent; }
|
||||
#PatientOrdersWorkspace QLabel[role="sectionTitle"] { font-size: 14px; font-weight: 600; }
|
||||
#PatientOrdersWorkspace QTableWidget#OrderTable {
|
||||
border: 0; border-radius: 0; background: $ds_surface; alternate-background-color: $ds_surface;
|
||||
selection-background-color: $ds_accent_soft; selection-color: $ds_text; gridline-color: $ds_line;
|
||||
}
|
||||
#PatientOrdersWorkspace QTableWidget#OrderTable::item { padding: 0; border: 0; }
|
||||
#PatientOrdersWorkspace QTableWidget#OrderTable QHeaderView::section {
|
||||
min-height: 44px; padding: 0 16px; background: $ds_surface_alt; color: $ds_muted;
|
||||
border: 0; border-bottom: 1px solid $ds_line;
|
||||
font-family: "$body"; font-size: 13px; font-weight: 400;
|
||||
}
|
||||
#PatientOrdersWorkspace QWidget#OrderActionBar { background: $ds_surface; }
|
||||
#PatientOrdersWorkspace QToolButton#OrderActionButton { padding-right: 28px; }
|
||||
#PatientOrdersWorkspace QToolButton#OrderActionButton::menu-indicator { image: none; width: 0; height: 0; }
|
||||
#PatientOrdersWorkspace QWidget#InfiniteList { background: $ds_surface; border-top: 1px solid $ds_line; }
|
||||
#PatientOrdersWorkspace QMenu, QMenu#OrderActionMenu {
|
||||
font-family: "$body"; font-size: 13px; color: $ds_text; background: $ds_surface;
|
||||
border: 1px solid $ds_line; padding: 5px;
|
||||
}
|
||||
#PatientOrdersWorkspace QMenu::item, QMenu#OrderActionMenu::item { padding: 8px 24px; }
|
||||
#PatientOrdersWorkspace QMenu::item:selected, QMenu#OrderActionMenu::item:selected { color: $ds_accent; background: $ds_accent_soft; }
|
||||
#PatientOrdersWorkspace QScrollBar:vertical { background: $ds_canvas; width: 7px; margin: 0; }
|
||||
#PatientOrdersWorkspace QScrollBar:horizontal { background: $ds_canvas; height: 7px; margin: 0; }
|
||||
#PatientOrdersWorkspace QScrollBar::handle { background: $ds_line_strong; border-radius: 3px; min-width: 24px; min-height: 24px; }
|
||||
#PatientOrdersWorkspace QScrollBar::add-line, #PatientOrdersWorkspace QScrollBar::sub-line { width: 0; height: 0; }
|
||||
#PatientOrdersWorkspace QScrollBar::add-page, #PatientOrdersWorkspace QScrollBar::sub-page { background: transparent; }
|
||||
"""
|
||||
"""Scoped surfaces for the approved patient order-management workspace."""
|
||||
|
||||
from string import Template
|
||||
|
||||
from .reception_style import body_family
|
||||
|
||||
|
||||
def patient_orders_stylesheet() -> str:
|
||||
return Template(_ORDERS).substitute(body=body_family())
|
||||
|
||||
|
||||
_ORDERS = """
|
||||
#PatientOrdersWorkspace { background: transparent; color: #273244; }
|
||||
#OrderWorkspaceContent, #OrderWorkspaceScroll { background: transparent; border: 0; }
|
||||
#PatientOrdersWorkspace QLabel, #PatientOrdersWorkspace QPushButton,
|
||||
#PatientOrdersWorkspace QToolButton, #PatientOrdersWorkspace QLineEdit,
|
||||
#PatientOrdersWorkspace QComboBox, #PatientOrdersWorkspace QDateEdit,
|
||||
#PatientOrdersWorkspace QCheckBox, #PatientOrdersWorkspace QTableWidget {
|
||||
font-family: "$body"; font-size: 14px; font-weight: 400; color: #273244;
|
||||
}
|
||||
#PatientOrdersWorkspace QLabel[role="muted"] { font-size: 13px; color: #5D6B80; }
|
||||
#PatientOrdersWorkspace QFrame#OrderFilterCard,
|
||||
#PatientOrdersWorkspace QFrame#OrderSummaryStrip,
|
||||
#PatientOrdersWorkspace QFrame#OrderTableCard {
|
||||
background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 8px;
|
||||
}
|
||||
#PatientOrdersWorkspace QPushButton, #PatientOrdersWorkspace QToolButton {
|
||||
min-height: 38px; max-height: 38px; padding: 0 16px; border: 1px solid #DBE5F2;
|
||||
border-radius: 5px; background: #FFFFFF; color: #273244;
|
||||
}
|
||||
#PatientOrdersWorkspace QPushButton:hover, #PatientOrdersWorkspace QToolButton:hover {
|
||||
background: #F2F7FF; border-color: #B6CDEE; color: #1555B6;
|
||||
}
|
||||
#PatientOrdersWorkspace QPushButton:pressed, #PatientOrdersWorkspace QToolButton:pressed { background: #DCEAFF; }
|
||||
#PatientOrdersWorkspace QPushButton:focus, #PatientOrdersWorkspace QToolButton:focus { border-color: #75A5F0; }
|
||||
#PatientOrdersWorkspace QPushButton#OrderSearchButton,
|
||||
#PatientOrdersWorkspace QPushButton#OrderDetailButton {
|
||||
color: #FFFFFF; background: #1769E8; border-color: #1769E8;
|
||||
}
|
||||
#PatientOrdersWorkspace QPushButton#OrderSearchButton:hover,
|
||||
#PatientOrdersWorkspace QPushButton#OrderDetailButton:hover { background: #155BCC; border-color: #155BCC; }
|
||||
#PatientOrdersWorkspace QPushButton:disabled, #PatientOrdersWorkspace QToolButton:disabled {
|
||||
color: #97A4B6; background: #F6F8FC; border-color: #E2E9F2;
|
||||
}
|
||||
#PatientOrdersWorkspace QLineEdit, #PatientOrdersWorkspace QComboBox,
|
||||
#PatientOrdersWorkspace QDateEdit {
|
||||
min-height: 38px; max-height: 38px; padding: 0 10px; font-size: 13px;
|
||||
background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 5px;
|
||||
selection-background-color: #DCEAFF; selection-color: #273244;
|
||||
}
|
||||
#PatientOrdersWorkspace QLineEdit:focus, #PatientOrdersWorkspace QComboBox:focus,
|
||||
#PatientOrdersWorkspace QDateEdit:focus { border-color: #75A5F0; }
|
||||
#PatientOrdersWorkspace QLineEdit QToolButton {
|
||||
min-height: 0; max-height: 24px; min-width: 0; border: 0; padding: 0; background: transparent;
|
||||
}
|
||||
#PatientOrdersWorkspace QComboBox { padding-right: 30px; }
|
||||
#PatientOrdersWorkspace QComboBox::drop-down { border: 0; width: 28px; background: transparent; }
|
||||
#PatientOrdersWorkspace QComboBox::down-arrow { image: none; width: 0; height: 0; }
|
||||
#PatientOrdersWorkspace QComboBox QAbstractItemView {
|
||||
font-family: "$body"; font-size: 13px; color: #273244; background: #FFFFFF;
|
||||
border: 1px solid #DBE5F2; outline: 0; selection-background-color: #EAF2FF; selection-color: #1555B6;
|
||||
}
|
||||
#PatientOrdersWorkspace QComboBox QAbstractItemView::item { min-height: 30px; padding: 3px 10px; }
|
||||
#PatientOrdersWorkspace QDateEdit { padding-right: 26px; }
|
||||
#PatientOrdersWorkspace QDateEdit::drop-down { border: 0; width: 24px; background: transparent; }
|
||||
#PatientOrdersWorkspace QDateEdit::down-arrow { image: none; width: 0; height: 0; }
|
||||
#PatientOrdersWorkspace QDateEdit:disabled { color: #8A97A9; background: #F6F8FC; border-color: #E2E9F2; }
|
||||
#PatientOrdersWorkspace QCalendarWidget {
|
||||
font-family: "$body"; font-size: 13px; background: #FFFFFF; color: #273244;
|
||||
}
|
||||
#PatientOrdersWorkspace QCalendarWidget QWidget#qt_calendar_navigationbar { background: #F5F8FD; }
|
||||
#PatientOrdersWorkspace QCalendarWidget QToolButton {
|
||||
min-height: 28px; max-height: 28px; padding: 0 8px; border: 0; background: transparent;
|
||||
font-family: "$body"; font-size: 13px; color: #273244;
|
||||
}
|
||||
#PatientOrdersWorkspace QCalendarWidget QToolButton:hover { background: #EAF2FF; }
|
||||
#PatientOrdersWorkspace QCalendarWidget QAbstractItemView {
|
||||
font-family: "$body"; font-size: 13px; background: #FFFFFF; alternate-background-color: #FFFFFF;
|
||||
color: #273244; selection-background-color: #1769E8; selection-color: #FFFFFF; outline: 0;
|
||||
}
|
||||
#PatientOrdersWorkspace QCheckBox { spacing: 9px; font-size: 13px; }
|
||||
#PatientOrdersWorkspace QCheckBox::indicator {
|
||||
width: 15px; height: 15px; border: 1px solid #C5D5EB; border-radius: 3px; background: #FFFFFF;
|
||||
}
|
||||
#PatientOrdersWorkspace QCheckBox::indicator:checked { background: #1769E8; border-color: #1769E8; }
|
||||
#PatientOrdersWorkspace QCheckBox::indicator:hover { border-color: #75A5F0; }
|
||||
#PatientOrdersWorkspace QCheckBox:focus { color: #1555B6; }
|
||||
#PatientOrdersWorkspace QFrame#OrderMetricCell { background: transparent; border: 0; }
|
||||
#PatientOrdersWorkspace QFrame#OrderMetricDivider { border: 0; background: #DBE5F2; }
|
||||
#PatientOrdersWorkspace QLabel[orderMetricCaption="true"] { color: #5D6B80; font-size: 13px; }
|
||||
#PatientOrdersWorkspace QLabel[orderMetricValue="true"] { color: #273244; font-size: 18px; font-weight: 500; }
|
||||
#PatientOrdersWorkspace QLabel#OrderAmountMetric { color: #1769E8; }
|
||||
#PatientOrdersWorkspace QLabel[role="sectionTitle"] { font-size: 14px; font-weight: 600; }
|
||||
#PatientOrdersWorkspace QTableWidget#OrderTable {
|
||||
border: 1px solid #E6EDF6; border-radius: 0; background: #FFFFFF; alternate-background-color: #FFFFFF;
|
||||
selection-background-color: #F5F8FF; selection-color: #273244; gridline-color: #E6EDF6;
|
||||
}
|
||||
#PatientOrdersWorkspace QTableWidget#OrderTable::item { padding: 0; border: 0; }
|
||||
#PatientOrdersWorkspace QTableWidget#OrderTable QHeaderView::section {
|
||||
min-height: 44px; padding: 0 16px; background: #F8FAFD; color: #5D6B80;
|
||||
border: 0; border-bottom: 1px solid #E1E9F4;
|
||||
font-family: "$body"; font-size: 13px; font-weight: 400;
|
||||
}
|
||||
#PatientOrdersWorkspace QWidget#OrderActionBar { background: #FFFFFF; }
|
||||
#PatientOrdersWorkspace QToolButton#OrderActionButton { padding-right: 28px; }
|
||||
#PatientOrdersWorkspace QToolButton#OrderActionButton::menu-indicator { image: none; width: 0; height: 0; }
|
||||
#PatientOrdersWorkspace QWidget#InfiniteList { background: #FFFFFF; border-top: 1px solid #E6EDF6; }
|
||||
#PatientOrdersWorkspace QMenu, QMenu#OrderActionMenu {
|
||||
font-family: "$body"; font-size: 13px; color: #273244; background: #FFFFFF;
|
||||
border: 1px solid #DBE5F2; padding: 5px;
|
||||
}
|
||||
#PatientOrdersWorkspace QMenu::item, QMenu#OrderActionMenu::item { padding: 8px 24px; }
|
||||
#PatientOrdersWorkspace QMenu::item:selected, QMenu#OrderActionMenu::item:selected { color: #1555B6; background: #EAF2FF; }
|
||||
#PatientOrdersWorkspace QScrollBar:vertical { background: #F4F7FC; width: 7px; margin: 0; }
|
||||
#PatientOrdersWorkspace QScrollBar:horizontal { background: #F4F7FC; height: 7px; margin: 0; }
|
||||
#PatientOrdersWorkspace QScrollBar::handle { background: #C8D5E6; border-radius: 3px; min-width: 24px; min-height: 24px; }
|
||||
#PatientOrdersWorkspace QScrollBar::add-line, #PatientOrdersWorkspace QScrollBar::sub-line { width: 0; height: 0; }
|
||||
#PatientOrdersWorkspace QScrollBar::add-page, #PatientOrdersWorkspace QScrollBar::sub-page { background: transparent; }
|
||||
"""
|
||||
|
||||
@@ -1,55 +1,54 @@
|
||||
"""Local typography and surfaces for the approved consultation-progress page."""
|
||||
|
||||
from string import Template
|
||||
|
||||
from .design_system import clinical_stylesheet
|
||||
from .reception_style import body_family
|
||||
|
||||
|
||||
def patient_progress_stylesheet() -> str:
|
||||
return clinical_stylesheet(Template(_PROGRESS).safe_substitute(body=body_family()))
|
||||
|
||||
|
||||
_PROGRESS = """
|
||||
#PatientProgressWorkspace { background: transparent; color: $ds_text; }
|
||||
#ProgressWorkspaceContent, #ProgressWorkspaceScroll { background: transparent; border: 0; }
|
||||
#PatientProgressWorkspace QLabel, #PatientProgressWorkspace QPushButton,
|
||||
#PatientProgressWorkspace QTableWidget {
|
||||
font-family: "$body"; font-size: 14px; font-weight: 400; color: $ds_text;
|
||||
}
|
||||
#PatientProgressWorkspace QLabel[role="muted"] { font-size: 13px; color: $ds_muted; }
|
||||
#PatientProgressWorkspace QLabel[role="sectionTitle"] { font-size: 14px; font-weight: 600; }
|
||||
#PatientProgressWorkspace QLabel#EmptyStateGlyph {
|
||||
font-size: 24px; color: $ds_accent; background: $ds_surface_alt;
|
||||
border: 1px solid $ds_line; border-radius: $ds_radius_panel;
|
||||
}
|
||||
#PatientProgressWorkspace QFrame#ProgressScheduleCard,
|
||||
#PatientProgressWorkspace QFrame#ProgressQueueCard {
|
||||
background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_panel;
|
||||
}
|
||||
#PatientProgressWorkspace QFrame#ProgressOverviewCard { background: transparent; border: 0; }
|
||||
#PatientProgressWorkspace QFrame#ProgressMetricCell { background: transparent; border: 0; }
|
||||
#PatientProgressWorkspace QFrame#ProgressMetricDivider { background: $ds_line; border: 0; }
|
||||
#PatientProgressWorkspace QLabel[progressMetricValue="true"] { font-size: 18px; font-weight: 500; color: $ds_text; }
|
||||
#PatientProgressWorkspace QLabel#ProgressTotalMetric { color: $ds_accent; }
|
||||
#PatientProgressWorkspace QSplitter#ProgressSplitter { background: transparent; }
|
||||
#PatientProgressWorkspace QSplitter#ProgressSplitter::handle { background: transparent; }
|
||||
#PatientProgressWorkspace QSplitter#ProgressSplitter::handle:hover { background: $ds_accent_soft; }
|
||||
#PatientProgressWorkspace QTableWidget#ProgressScheduleTable,
|
||||
#PatientProgressWorkspace QTableWidget#ProgressQueueTable {
|
||||
border: 0; border-radius: 0; background: $ds_surface; alternate-background-color: $ds_surface;
|
||||
selection-background-color: $ds_accent_soft; selection-color: $ds_text; gridline-color: $ds_line;
|
||||
}
|
||||
#PatientProgressWorkspace QTableWidget::item { border: 0; padding: 0; }
|
||||
#PatientProgressWorkspace QHeaderView::section {
|
||||
min-height: 0; padding: 0 16px; background: $ds_surface_alt; color: $ds_muted;
|
||||
border: 0; border-bottom: 1px solid $ds_line;
|
||||
font-family: "$body"; font-size: 13px; font-weight: 400;
|
||||
}
|
||||
#PatientProgressWorkspace QWidget#InfiniteList { background: $ds_surface; border-top: 1px solid $ds_line; }
|
||||
#PatientProgressWorkspace QScrollBar:vertical { background: $ds_canvas; width: 7px; margin: 0; }
|
||||
#PatientProgressWorkspace QScrollBar:horizontal { background: $ds_canvas; height: 7px; margin: 0; }
|
||||
#PatientProgressWorkspace QScrollBar::handle { background: $ds_line_strong; border-radius: 3px; min-width: 24px; min-height: 24px; }
|
||||
#PatientProgressWorkspace QScrollBar::add-line, #PatientProgressWorkspace QScrollBar::sub-line { width: 0; height: 0; }
|
||||
#PatientProgressWorkspace QScrollBar::add-page, #PatientProgressWorkspace QScrollBar::sub-page { background: transparent; }
|
||||
"""
|
||||
"""Local typography and surfaces for the approved consultation-progress page."""
|
||||
|
||||
from string import Template
|
||||
|
||||
from .reception_style import body_family
|
||||
|
||||
|
||||
def patient_progress_stylesheet() -> str:
|
||||
return Template(_PROGRESS).substitute(body=body_family())
|
||||
|
||||
|
||||
_PROGRESS = """
|
||||
#PatientProgressWorkspace { background: transparent; color: #273244; }
|
||||
#ProgressWorkspaceContent, #ProgressWorkspaceScroll { background: transparent; border: 0; }
|
||||
#PatientProgressWorkspace QLabel, #PatientProgressWorkspace QPushButton,
|
||||
#PatientProgressWorkspace QTableWidget {
|
||||
font-family: "$body"; font-size: 14px; font-weight: 400; color: #273244;
|
||||
}
|
||||
#PatientProgressWorkspace QLabel[role="muted"] { font-size: 13px; color: #5D6B80; }
|
||||
#PatientProgressWorkspace QLabel[role="sectionTitle"] { font-size: 14px; font-weight: 600; }
|
||||
#PatientProgressWorkspace QLabel#EmptyStateGlyph {
|
||||
font-size: 24px; color: #1769E8; background: #F2F7FF;
|
||||
border: 1px solid #DBE5F2; border-radius: 22px;
|
||||
}
|
||||
#PatientProgressWorkspace QFrame#ProgressOverviewCard,
|
||||
#PatientProgressWorkspace QFrame#ProgressScheduleCard,
|
||||
#PatientProgressWorkspace QFrame#ProgressQueueCard {
|
||||
background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 8px;
|
||||
}
|
||||
#PatientProgressWorkspace QFrame#ProgressMetricCell { background: transparent; border: 0; }
|
||||
#PatientProgressWorkspace QFrame#ProgressMetricDivider { background: #DBE5F2; border: 0; }
|
||||
#PatientProgressWorkspace QLabel[progressMetricValue="true"] { font-size: 18px; font-weight: 500; color: #273244; }
|
||||
#PatientProgressWorkspace QLabel#ProgressTotalMetric { color: #1769E8; }
|
||||
#PatientProgressWorkspace QSplitter#ProgressSplitter { background: transparent; }
|
||||
#PatientProgressWorkspace QSplitter#ProgressSplitter::handle { background: transparent; }
|
||||
#PatientProgressWorkspace QSplitter#ProgressSplitter::handle:hover { background: #EAF2FF; }
|
||||
#PatientProgressWorkspace QTableWidget#ProgressScheduleTable,
|
||||
#PatientProgressWorkspace QTableWidget#ProgressQueueTable {
|
||||
border: 0; border-radius: 0; background: #FFFFFF; alternate-background-color: #FFFFFF;
|
||||
selection-background-color: #F2F7FF; selection-color: #273244; gridline-color: #E6EDF6;
|
||||
}
|
||||
#PatientProgressWorkspace QTableWidget::item { border: 0; padding: 0; }
|
||||
#PatientProgressWorkspace QHeaderView::section {
|
||||
min-height: 0; padding: 0 16px; background: #F5F8FD; color: #5D6B80;
|
||||
border: 0; border-bottom: 1px solid #E1E9F4;
|
||||
font-family: "$body"; font-size: 13px; font-weight: 400;
|
||||
}
|
||||
#PatientProgressWorkspace QWidget#InfiniteList { background: #FFFFFF; border-top: 1px solid #E6EDF6; }
|
||||
#PatientProgressWorkspace QScrollBar:vertical { background: #F4F7FC; width: 7px; margin: 0; }
|
||||
#PatientProgressWorkspace QScrollBar:horizontal { background: #F4F7FC; height: 7px; margin: 0; }
|
||||
#PatientProgressWorkspace QScrollBar::handle { background: #C8D5E6; border-radius: 3px; min-width: 24px; min-height: 24px; }
|
||||
#PatientProgressWorkspace QScrollBar::add-line, #PatientProgressWorkspace QScrollBar::sub-line { width: 0; height: 0; }
|
||||
#PatientProgressWorkspace QScrollBar::add-page, #PatientProgressWorkspace QScrollBar::sub-page { background: transparent; }
|
||||
"""
|
||||
|
||||
@@ -1,154 +1,141 @@
|
||||
"""Quiet clinical surfaces for the patient-list workspace."""
|
||||
|
||||
from string import Template
|
||||
|
||||
from .design_system import clinical_stylesheet
|
||||
from .reception_style import body_family, heading_family
|
||||
|
||||
|
||||
def patients_chrome_stylesheet() -> str:
|
||||
return clinical_stylesheet(Template(_CHROME).safe_substitute(body=body_family(), heading=heading_family()))
|
||||
|
||||
|
||||
def patient_list_stylesheet() -> str:
|
||||
return clinical_stylesheet(Template(_LIST).safe_substitute(body=body_family()))
|
||||
|
||||
|
||||
_CHROME = """
|
||||
#PatientsPage { background: $ds_canvas; }
|
||||
#PatientsPage QWidget#PageHeader QLabel {
|
||||
font-family: "$body"; font-size: 13px; font-weight: 400; color: $ds_muted;
|
||||
}
|
||||
#PatientsPage QWidget#PageHeader QLabel[role="pageTitle"] {
|
||||
font-family: "$heading"; font-size: 20px; font-weight: 600; color: $ds_heading;
|
||||
}
|
||||
#PatientsPage QPushButton#PatientRefreshButton {
|
||||
font-family: "$body"; font-size: 14px; font-weight: 400; color: $ds_text;
|
||||
min-height: 38px; max-height: 38px; padding: 0 20px;
|
||||
border: 1px solid transparent; border-radius: $ds_radius_control; background: $ds_surface_alt;
|
||||
}
|
||||
#PatientsPage QPushButton#PatientRefreshButton:hover { background: $ds_surface_alt; border-color: $ds_line_strong; }
|
||||
#PatientsPage QPushButton#PatientRefreshButton:pressed { background: $ds_accent_soft; }
|
||||
#PatientsPage QPushButton#PatientRefreshButton:focus { border-color: $ds_focus; }
|
||||
#PatientsPage QPushButton#PatientRefreshButton:disabled { color: $ds_disabled; background: $ds_disabled_surface; }
|
||||
#PatientsPage QTabWidget#PatientWorkspaceTabs::pane { border: 0; background: transparent; top: 0; }
|
||||
#PatientsPage QTabWidget#PatientWorkspaceTabs > QTabBar::tab {
|
||||
font-family: "$body"; font-size: 14px; font-weight: 400; color: $ds_text;
|
||||
min-width: 84px; min-height: 42px; padding: 0 10px; margin-right: 22px;
|
||||
border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: transparent;
|
||||
}
|
||||
#PatientsPage QTabWidget#PatientWorkspaceTabs > QTabBar::tab:selected {
|
||||
color: $ds_accent; border-bottom-color: $ds_accent; background: transparent;
|
||||
}
|
||||
#PatientsPage QTabWidget#PatientWorkspaceTabs > QTabBar::tab:hover { color: $ds_accent; background: $ds_accent_soft; }
|
||||
"""
|
||||
|
||||
_LIST = """
|
||||
#PatientListWorkspace { background: transparent; color: $ds_text; }
|
||||
#PatientWorkspaceContent, #PatientWorkspaceScroll { background: transparent; border: 0; }
|
||||
#PatientListWorkspace QLabel, #PatientListWorkspace QPushButton,
|
||||
#PatientListWorkspace QToolButton, #PatientListWorkspace QDateEdit,
|
||||
#PatientListWorkspace QTableWidget, #PatientSearchToolbar QLineEdit,
|
||||
#PatientSearchToolbar QPushButton {
|
||||
font-family: "$body"; font-size: 14px; font-weight: 400; color: $ds_text;
|
||||
}
|
||||
#PatientListWorkspace QLabel[role="muted"], #PatientListWorkspace QLabel[filterLabel="true"] {
|
||||
color: $ds_muted; font-size: 13px;
|
||||
}
|
||||
#PatientListWorkspace QFrame#PatientFilterCard,
|
||||
#PatientListWorkspace QFrame#PatientListCard {
|
||||
background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_panel;
|
||||
}
|
||||
#PatientListWorkspace QFrame#PatientSummaryStrip { background: transparent; border: 0; }
|
||||
#PatientListWorkspace QPushButton, #PatientSearchToolbar QPushButton {
|
||||
min-height: 38px; max-height: 38px; padding: 0 16px;
|
||||
border: 1px solid transparent; border-radius: $ds_radius_control; background: $ds_surface_alt;
|
||||
}
|
||||
#PatientListWorkspace QPushButton:hover, #PatientSearchToolbar QPushButton:hover {
|
||||
color: $ds_accent; background: $ds_surface_alt; border-color: $ds_line_strong;
|
||||
}
|
||||
#PatientListWorkspace QPushButton:pressed, #PatientSearchToolbar QPushButton:pressed { background: $ds_accent_soft; }
|
||||
#PatientListWorkspace QPushButton:focus, #PatientSearchToolbar QPushButton:focus { border-color: $ds_focus; }
|
||||
#PatientSearchToolbar QPushButton#PatientSearchButton {
|
||||
min-height: 38px; max-height: 38px; color: $ds_surface; background: $ds_accent; border-color: $ds_accent;
|
||||
}
|
||||
#PatientSearchToolbar QPushButton#PatientSearchButton:hover { background: $ds_accent_hover; }
|
||||
#PatientSearchToolbar QPushButton#PatientSearchButton:pressed { background: $ds_accent_pressed; }
|
||||
#PatientSearchToolbar QPushButton#PatientSearchButton:focus { border-color: $ds_focus; }
|
||||
#PatientSearchToolbar QLineEdit {
|
||||
min-height: 38px; max-height: 38px; padding: 0 8px; background: $ds_surface;
|
||||
border: 1px solid $ds_line; border-radius: $ds_radius_control; selection-background-color: $ds_accent_soft;
|
||||
}
|
||||
#PatientSearchToolbar QLineEdit:focus { border-color: $ds_focus; }
|
||||
#PatientSearchToolbar QLineEdit QToolButton { border: 0; padding: 0; background: transparent; }
|
||||
#PatientListWorkspace QPushButton[patientStatusChip="true"] {
|
||||
min-height: 44px; max-height: 44px; padding: 0 16px; font-size: 13px;
|
||||
color: $ds_text; border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: transparent;
|
||||
}
|
||||
#PatientListWorkspace QPushButton[patientStatusChip="true"]:checked {
|
||||
color: $ds_accent; border-bottom-color: $ds_accent; background: transparent;
|
||||
}
|
||||
#PatientListWorkspace QPushButton[patientStatusChip="true"]:hover { color: $ds_accent; background: $ds_surface_alt; }
|
||||
#PatientListWorkspace QPushButton[patientStatusChip="true"]:focus { background: $ds_accent_soft; }
|
||||
#PatientListWorkspace QPushButton[patientQuickDate="true"] { padding: 0 12px; font-size: 13px; }
|
||||
#PatientListWorkspace QPushButton[patientQuickDate="true"]:checked,
|
||||
#PatientListWorkspace QPushButton#PatientCustomDateButton:checked {
|
||||
color: $ds_accent; background: $ds_accent_soft; border: 1px solid transparent; font-weight: 600;
|
||||
}
|
||||
#PatientListWorkspace QPushButton[patientQuickDate="true"]:focus,
|
||||
#PatientListWorkspace QPushButton#PatientCustomDateButton:focus { border-color: $ds_focus; }
|
||||
#PatientListWorkspace QDateEdit {
|
||||
min-height: 38px; max-height: 38px; padding: 0 8px; font-size: 13px;
|
||||
background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_control;
|
||||
selection-background-color: $ds_accent_soft;
|
||||
}
|
||||
#PatientListWorkspace QDateEdit:focus { border-color: $ds_focus; }
|
||||
#PatientListWorkspace QDateEdit:disabled {
|
||||
color: $ds_disabled; background: $ds_disabled_surface; border-color: $ds_line;
|
||||
}
|
||||
#PatientListWorkspace QDateEdit::drop-down { border: 0; width: 20px; background: transparent; }
|
||||
#PatientListWorkspace QDateEdit::down-arrow { image: none; width: 0; height: 0; }
|
||||
#PatientListWorkspace QPushButton[summaryCard="true"] {
|
||||
min-height: 64px; max-height: 64px; padding: 0; background: transparent;
|
||||
border: 1px solid transparent; border-radius: $ds_radius_control;
|
||||
}
|
||||
#PatientListWorkspace QPushButton[summaryCard="true"]:hover { background: $ds_surface_alt; }
|
||||
#PatientListWorkspace QPushButton[summaryCard="true"]:focus { border-color: $ds_focus; }
|
||||
#PatientListWorkspace QFrame#PatientSummaryDivider { border: 0; background: $ds_line; }
|
||||
#PatientListWorkspace QWidget#PatientListHeading { background: transparent; }
|
||||
#PatientListWorkspace QLabel[role="sectionTitle"] { font-size: 14px; font-weight: 600; color: $ds_text; }
|
||||
#PatientListWorkspace QTableWidget#PatientTable {
|
||||
background: $ds_surface; alternate-background-color: $ds_surface; border: 0; border-radius: 0;
|
||||
selection-background-color: $ds_accent_soft; selection-color: $ds_text; gridline-color: $ds_line;
|
||||
}
|
||||
#PatientListWorkspace QTableWidget#PatientTable::item { padding: 0; border: 0; }
|
||||
#PatientListWorkspace QTableWidget#PatientTable QHeaderView::section {
|
||||
min-height: 41px; padding: 0 10px; background: $ds_surface_alt; color: $ds_muted;
|
||||
border: 0; border-top: 1px solid $ds_line; border-bottom: 1px solid $ds_line;
|
||||
font-family: "$body"; font-size: 13px; font-weight: 400;
|
||||
}
|
||||
#PatientListWorkspace QWidget#RowActions, #PatientListWorkspace QWidget#PatientSelectorHost { background: transparent; }
|
||||
#PatientListWorkspace QPushButton[rowAction="true"],
|
||||
#PatientListWorkspace QToolButton#RowActionsMore {
|
||||
min-height: 28px; max-height: 28px; padding: 0 5px; border: 1px solid transparent;
|
||||
border-radius: $ds_radius_small; background: transparent; color: $ds_accent; font-size: 13px;
|
||||
}
|
||||
#PatientListWorkspace QToolButton#RowActionsMore { color: $ds_text; padding-right: 16px; }
|
||||
#PatientListWorkspace QPushButton[rowAction="true"]:hover,
|
||||
#PatientListWorkspace QToolButton#RowActionsMore:hover { background: $ds_accent_soft; }
|
||||
#PatientListWorkspace QPushButton[rowAction="true"]:focus,
|
||||
#PatientListWorkspace QToolButton#RowActionsMore:focus { border-color: $ds_focus; }
|
||||
#PatientListWorkspace QMenu { background: $ds_surface; color: $ds_text; border: 1px solid $ds_line; padding: 4px; }
|
||||
#PatientListWorkspace QMenu::item { padding: 7px 22px; font-size: 13px; }
|
||||
#PatientListWorkspace QMenu::item:selected { background: $ds_accent_soft; color: $ds_accent; }
|
||||
#PatientListWorkspace QCheckBox[patientSelector="true"]::indicator {
|
||||
width: 13px; height: 13px; background: $ds_surface; border: 1px solid $ds_line_strong; border-radius: 3px;
|
||||
}
|
||||
#PatientListWorkspace QCheckBox[patientSelector="true"]::indicator:checked { background: $ds_accent; border-color: $ds_accent; }
|
||||
#PatientListWorkspace QWidget#InfiniteList { background: $ds_surface; border-top: 1px solid $ds_line; }
|
||||
#PatientListWorkspace QScrollBar:vertical { background: $ds_canvas; width: 7px; margin: 0; }
|
||||
#PatientListWorkspace QScrollBar:horizontal { background: $ds_canvas; height: 7px; margin: 0; }
|
||||
#PatientListWorkspace QScrollBar::handle { background: $ds_line_strong; border-radius: 3px; min-width: 24px; min-height: 24px; }
|
||||
#PatientListWorkspace QScrollBar::add-line, #PatientListWorkspace QScrollBar::sub-line { width: 0; height: 0; }
|
||||
#PatientListWorkspace QScrollBar::add-page, #PatientListWorkspace QScrollBar::sub-page { background: transparent; }
|
||||
"""
|
||||
"""Scoped technology-blue surfaces for the approved patient-list workspace."""
|
||||
|
||||
from string import Template
|
||||
|
||||
from .reception_style import body_family, heading_family
|
||||
|
||||
|
||||
def patients_chrome_stylesheet() -> str:
|
||||
return Template(_CHROME).substitute(body=body_family(), heading=heading_family())
|
||||
|
||||
|
||||
def patient_list_stylesheet() -> str:
|
||||
return Template(_LIST).substitute(body=body_family())
|
||||
|
||||
|
||||
_CHROME = """
|
||||
#PatientsPage { background: #F3F7FD; }
|
||||
#PatientsPage QWidget#PageHeader QLabel {
|
||||
font-family: "$body"; font-size: 13px; font-weight: 400; color: #5D6B80;
|
||||
}
|
||||
#PatientsPage QWidget#PageHeader QLabel[role="pageTitle"] {
|
||||
font-family: "$heading"; font-size: 20px; font-weight: 600; color: #202C3F;
|
||||
}
|
||||
#PatientsPage QPushButton#PatientRefreshButton {
|
||||
font-family: "$body"; font-size: 14px; font-weight: 400; color: #273244;
|
||||
min-height: 38px; max-height: 38px; padding: 0 20px;
|
||||
border: 1px solid #DBE5F2; border-radius: 5px; background: #FFFFFF;
|
||||
}
|
||||
#PatientsPage QPushButton#PatientRefreshButton:hover { background: #F2F7FF; border-color: #B6CDEE; }
|
||||
#PatientsPage QTabWidget#PatientWorkspaceTabs::pane { border: 0; background: transparent; top: 0; }
|
||||
#PatientsPage QTabWidget#PatientWorkspaceTabs > QTabBar::tab {
|
||||
font-family: "$body"; font-size: 14px; font-weight: 400; color: #273244;
|
||||
min-width: 84px; min-height: 42px; padding: 0 10px; margin-right: 22px;
|
||||
border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: transparent;
|
||||
}
|
||||
#PatientsPage QTabWidget#PatientWorkspaceTabs > QTabBar::tab:selected {
|
||||
color: #1769E8; border-bottom-color: #1769E8; background: transparent;
|
||||
}
|
||||
#PatientsPage QTabWidget#PatientWorkspaceTabs > QTabBar::tab:hover { color: #1769E8; background: #EAF2FF; }
|
||||
"""
|
||||
|
||||
_LIST = """
|
||||
#PatientListWorkspace { background: transparent; color: #273244; }
|
||||
#PatientWorkspaceContent, #PatientWorkspaceScroll { background: transparent; border: 0; }
|
||||
#PatientListWorkspace QLabel, #PatientListWorkspace QPushButton,
|
||||
#PatientListWorkspace QToolButton, #PatientListWorkspace QDateEdit,
|
||||
#PatientListWorkspace QTableWidget, #PatientSearchToolbar QLineEdit,
|
||||
#PatientSearchToolbar QPushButton {
|
||||
font-family: "$body"; font-size: 14px; font-weight: 400; color: #273244;
|
||||
}
|
||||
#PatientListWorkspace QLabel[role="muted"], #PatientListWorkspace QLabel[filterLabel="true"] {
|
||||
color: #5D6B80; font-size: 13px;
|
||||
}
|
||||
#PatientListWorkspace QFrame#PatientFilterCard,
|
||||
#PatientListWorkspace QFrame#PatientSummaryStrip,
|
||||
#PatientListWorkspace QFrame#PatientListCard {
|
||||
background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 8px;
|
||||
}
|
||||
#PatientListWorkspace QPushButton, #PatientSearchToolbar QPushButton {
|
||||
min-height: 38px; max-height: 38px; padding: 0 16px;
|
||||
border: 1px solid #DBE5F2; border-radius: 5px; background: #FFFFFF;
|
||||
}
|
||||
#PatientListWorkspace QPushButton:hover, #PatientSearchToolbar QPushButton:hover {
|
||||
color: #1555B6; background: #F2F7FF; border-color: #B6CDEE;
|
||||
}
|
||||
#PatientListWorkspace QPushButton:pressed, #PatientSearchToolbar QPushButton:pressed { background: #DCEAFF; }
|
||||
#PatientListWorkspace QPushButton:focus, #PatientSearchToolbar QPushButton:focus { border-color: #75A5F0; }
|
||||
#PatientSearchToolbar QPushButton#PatientSearchButton {
|
||||
min-height: 38px; max-height: 38px; color: #FFFFFF; background: #1769E8; border-color: #1769E8;
|
||||
}
|
||||
#PatientSearchToolbar QPushButton#PatientSearchButton:hover { background: #155BCC; }
|
||||
#PatientSearchToolbar QLineEdit {
|
||||
min-height: 38px; max-height: 38px; padding: 0 8px; background: #FFFFFF;
|
||||
border: 1px solid #DBE5F2; border-radius: 5px; selection-background-color: #DCEAFF;
|
||||
}
|
||||
#PatientSearchToolbar QLineEdit:focus { border-color: #75A5F0; }
|
||||
#PatientSearchToolbar QLineEdit QToolButton { border: 0; padding: 0; background: transparent; }
|
||||
#PatientListWorkspace QPushButton[patientStatusChip="true"] {
|
||||
min-height: 44px; max-height: 44px; padding: 0 16px; font-size: 13px;
|
||||
color: #273244; border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: transparent;
|
||||
}
|
||||
#PatientListWorkspace QPushButton[patientStatusChip="true"]:checked {
|
||||
color: #1769E8; border-bottom-color: #1769E8; background: transparent;
|
||||
}
|
||||
#PatientListWorkspace QPushButton[patientStatusChip="true"]:hover { color: #1769E8; background: #F2F7FF; }
|
||||
#PatientListWorkspace QPushButton[patientQuickDate="true"] { padding: 0 12px; font-size: 13px; }
|
||||
#PatientListWorkspace QPushButton[patientQuickDate="true"]:checked,
|
||||
#PatientListWorkspace QPushButton#PatientCustomDateButton:checked {
|
||||
color: #FFFFFF; background: #1769E8; border: 1px solid #1769E8;
|
||||
}
|
||||
#PatientListWorkspace QDateEdit {
|
||||
min-height: 38px; max-height: 38px; padding: 0 8px; font-size: 13px;
|
||||
background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 5px;
|
||||
selection-background-color: #DCEAFF;
|
||||
}
|
||||
#PatientListWorkspace QDateEdit:focus { border-color: #75A5F0; }
|
||||
#PatientListWorkspace QDateEdit:disabled {
|
||||
color: #8A97A9; background: #F6F8FC; border-color: #E2E9F2;
|
||||
}
|
||||
#PatientListWorkspace QDateEdit::drop-down { border: 0; width: 20px; background: transparent; }
|
||||
#PatientListWorkspace QDateEdit::down-arrow { image: none; width: 0; height: 0; }
|
||||
#PatientListWorkspace QPushButton[summaryCard="true"] {
|
||||
min-height: 64px; max-height: 64px; padding: 0; background: transparent; border: 0; border-radius: 5px;
|
||||
}
|
||||
#PatientListWorkspace QPushButton[summaryCard="true"]:hover { background: #F2F7FF; }
|
||||
#PatientListWorkspace QFrame#PatientSummaryDivider { border: 0; background: #E1E9F4; }
|
||||
#PatientListWorkspace QWidget#PatientListHeading { background: transparent; }
|
||||
#PatientListWorkspace QLabel[role="sectionTitle"] { font-size: 14px; font-weight: 600; color: #273244; }
|
||||
#PatientListWorkspace QTableWidget#PatientTable {
|
||||
background: #FFFFFF; alternate-background-color: #FFFFFF; border: 0; border-radius: 0;
|
||||
selection-background-color: #EAF2FF; selection-color: #273244; gridline-color: #E6EDF6;
|
||||
}
|
||||
#PatientListWorkspace QTableWidget#PatientTable::item { padding: 0; border: 0; }
|
||||
#PatientListWorkspace QTableWidget#PatientTable QHeaderView::section {
|
||||
min-height: 41px; padding: 0 10px; background: #F5F8FD; color: #5D6B80;
|
||||
border: 0; border-top: 1px solid #E6EDF6; border-bottom: 1px solid #E1E9F4;
|
||||
font-family: "$body"; font-size: 13px; font-weight: 400;
|
||||
}
|
||||
#PatientListWorkspace QWidget#RowActions, #PatientListWorkspace QWidget#PatientSelectorHost { background: transparent; }
|
||||
#PatientListWorkspace QPushButton[rowAction="true"],
|
||||
#PatientListWorkspace QToolButton#RowActionsMore {
|
||||
min-height: 28px; max-height: 28px; padding: 0 5px; border: 0;
|
||||
border-radius: 4px; background: transparent; color: #1769E8; font-size: 13px;
|
||||
}
|
||||
#PatientListWorkspace QToolButton#RowActionsMore { color: #273244; padding-right: 16px; }
|
||||
#PatientListWorkspace QPushButton[rowAction="true"]:hover,
|
||||
#PatientListWorkspace QToolButton#RowActionsMore:hover { background: #DCEAFF; }
|
||||
#PatientListWorkspace QMenu { background: #FFFFFF; color: #273244; border: 1px solid #DBE5F2; padding: 4px; }
|
||||
#PatientListWorkspace QMenu::item { padding: 7px 22px; font-size: 13px; }
|
||||
#PatientListWorkspace QMenu::item:selected { background: #EAF2FF; color: #1555B6; }
|
||||
#PatientListWorkspace QCheckBox[patientSelector="true"]::indicator {
|
||||
width: 13px; height: 13px; background: #FFFFFF; border: 1px solid #CBDAED; border-radius: 3px;
|
||||
}
|
||||
#PatientListWorkspace QCheckBox[patientSelector="true"]::indicator:checked { background: #1769E8; border-color: #1769E8; }
|
||||
#PatientListWorkspace QWidget#InfiniteList { background: #FFFFFF; border-top: 1px solid #E6EDF6; }
|
||||
#PatientListWorkspace QScrollBar:vertical { background: #F4F7FC; width: 7px; margin: 0; }
|
||||
#PatientListWorkspace QScrollBar:horizontal { background: #F4F7FC; height: 7px; margin: 0; }
|
||||
#PatientListWorkspace QScrollBar::handle { background: #C8D5E6; border-radius: 3px; min-width: 24px; min-height: 24px; }
|
||||
#PatientListWorkspace QScrollBar::add-line, #PatientListWorkspace QScrollBar::sub-line { width: 0; height: 0; }
|
||||
#PatientListWorkspace QScrollBar::add-page, #PatientListWorkspace QScrollBar::sub-page { background: transparent; }
|
||||
"""
|
||||
|
||||
@@ -1,419 +1,359 @@
|
||||
"""Shared clinical tokens for the prescription library and its native delegates."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterable, Sequence
|
||||
from string import Template
|
||||
from typing import Any
|
||||
|
||||
from PySide6.QtCore import QEvent, QModelIndex, QRectF, QSize, Qt, QTimer
|
||||
from PySide6.QtGui import QColor, QFont, QFontMetrics, QIcon, QPainter
|
||||
from PySide6.QtWidgets import (
|
||||
QComboBox,
|
||||
QPushButton,
|
||||
QStyle,
|
||||
QStyledItemDelegate,
|
||||
QToolTip,
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from .design_system import PALETTE, RADII, clinical_stylesheet
|
||||
from .reception_style import body_family, heading_family
|
||||
from .widgets import SortableTable, TableColumn, first_value
|
||||
|
||||
|
||||
def library_stylesheet() -> str:
|
||||
return clinical_stylesheet(Template(_LIBRARY).safe_substitute(body=body_family(), heading=heading_family()))
|
||||
|
||||
|
||||
def _library_icon(kind: str, color: str = PALETTE["accent"], size: int = 15) -> QIcon:
|
||||
# Defer the page helper lookup so importing this module alone does not
|
||||
# recurse through pages.__init__ and the library page's own style import.
|
||||
from .pages.prescriptions import _painted_icon
|
||||
|
||||
result = QIcon()
|
||||
for mode, tint in (
|
||||
(QIcon.Mode.Normal, color),
|
||||
(QIcon.Mode.Active, color),
|
||||
(QIcon.Mode.Selected, color),
|
||||
(QIcon.Mode.Disabled, PALETTE["disabled"]),
|
||||
):
|
||||
pixmap = _painted_icon(kind, tint, size).pixmap(QSize(size, size))
|
||||
for state in (QIcon.State.Off, QIcon.State.On):
|
||||
result.addPixmap(pixmap, mode, state)
|
||||
return result
|
||||
|
||||
|
||||
class LibraryComboBox(QComboBox):
|
||||
"""Keep native combo interaction while painting the local caret."""
|
||||
|
||||
def paintEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual
|
||||
super().paintEvent(event)
|
||||
painter = QPainter(self)
|
||||
try:
|
||||
rect = QRectF(self.width() - 25, (self.height() - 14) / 2, 14, 14)
|
||||
mode = QIcon.Mode.Normal if self.isEnabled() else QIcon.Mode.Disabled
|
||||
_library_icon("chevron_down", PALETTE["muted"], 14).paint(painter, rect.toRect(), mode=mode)
|
||||
finally:
|
||||
painter.end()
|
||||
|
||||
|
||||
class LibraryTable(SortableTable):
|
||||
"""Fit readable columns while preserving actions and selected template IDs."""
|
||||
|
||||
_FLEX_COLUMNS = ((1, 2), (4, 5), (5, 2))
|
||||
|
||||
def __init__(self, columns: Sequence[TableColumn], parent: QWidget | None = None) -> None:
|
||||
super().__init__(columns, parent)
|
||||
self.horizontalHeader().setStretchLastSection(False)
|
||||
self._minimum_widths = tuple(column.width for column in self.columns)
|
||||
self._manual_widths: dict[int, int] = {}
|
||||
self._fitting_columns = False
|
||||
self._fit_timer = QTimer(self)
|
||||
self._fit_timer.setSingleShot(True)
|
||||
self._fit_timer.timeout.connect(self._fit_columns)
|
||||
self.horizontalHeader().sectionResized.connect(self._column_resized)
|
||||
self.viewport().installEventFilter(self)
|
||||
|
||||
def eventFilter(self, watched: Any, event: QEvent) -> bool: # noqa: N802
|
||||
if watched is self.viewport() and event.type() in {QEvent.Type.Resize, QEvent.Type.Show}:
|
||||
self._schedule_column_fit()
|
||||
return super().eventFilter(watched, event)
|
||||
|
||||
def _schedule_column_fit(self) -> None:
|
||||
if not self._fit_timer.isActive():
|
||||
self._fit_timer.start(0)
|
||||
|
||||
def _column_resized(self, column: int, _old_size: int, size: int) -> None:
|
||||
if self._fitting_columns:
|
||||
return
|
||||
self._manual_widths[column] = max(self._minimum_widths[column], size)
|
||||
self._schedule_column_fit()
|
||||
|
||||
def _fit_columns(self) -> None:
|
||||
widths = [self._manual_widths.get(column, minimum)
|
||||
for column, minimum in enumerate(self._minimum_widths)]
|
||||
extra = max(0, self.viewport().width() - sum(widths))
|
||||
flexible = [(column, weight) for column, weight in self._FLEX_COLUMNS
|
||||
if column not in self._manual_widths]
|
||||
# If every text column was manually sized, keep those preferences as
|
||||
# minimums and let the herb preview absorb any remaining wide-screen space.
|
||||
flexible = flexible or [(4, 1)]
|
||||
total_weight = sum(weight for _column, weight in flexible)
|
||||
for column, weight in flexible:
|
||||
widths[column] += extra * weight // total_weight
|
||||
widths[flexible[0][0]] += max(0, self.viewport().width() - sum(widths))
|
||||
if widths == [self.columnWidth(column) for column in range(self.columnCount())]:
|
||||
return
|
||||
self._fitting_columns = True
|
||||
try:
|
||||
for column, width in enumerate(widths):
|
||||
self.setColumnWidth(column, width)
|
||||
finally:
|
||||
self._fitting_columns = False
|
||||
|
||||
def set_rows(self, rows: Iterable[Any]) -> None:
|
||||
selected_id = first_value(self.current_data(), "id", "template_id", default=None)
|
||||
super().set_rows(rows)
|
||||
# The shared table restores an unsorted row index after enabling sort.
|
||||
# Locate the same source object in the finished visual order instead.
|
||||
if selected_id is not None:
|
||||
for row_index in range(self.rowCount()):
|
||||
item = self.item(row_index, 0)
|
||||
row = item.data(Qt.ItemDataRole.UserRole) if item is not None else None
|
||||
row_id = first_value(row, "id", "template_id", default=None)
|
||||
if row_id is not None and str(row_id) == str(selected_id):
|
||||
self.selectRow(row_index)
|
||||
return
|
||||
self.clearSelection()
|
||||
self.setCurrentCell(-1, -1)
|
||||
|
||||
def setCellWidget(self, row: int, column: int, widget: QWidget | None) -> None: # noqa: N802
|
||||
super().setCellWidget(row, column, widget)
|
||||
if widget is None or column != 9:
|
||||
return
|
||||
widget.setObjectName("PrescriptionLibraryTableCellHost")
|
||||
widget.setAutoFillBackground(False)
|
||||
glyphs = {
|
||||
"查看处方模板": "eye",
|
||||
"AI 解释": "spark",
|
||||
"编辑处方模板": "pencil",
|
||||
"删除处方模板": "trash",
|
||||
}
|
||||
for button in widget.findChildren(QPushButton):
|
||||
if not button.property("rowAction"):
|
||||
continue
|
||||
glyph = glyphs.get(button.accessibleName()) or glyphs.get(button.toolTip())
|
||||
if glyph is not None:
|
||||
color = PALETTE["danger"] if button.property("danger") else PALETTE["accent"]
|
||||
button.setIcon(_library_icon(glyph, color, button.iconSize().width()))
|
||||
|
||||
|
||||
def _library_font(size: int = 14, *, medium: bool = False) -> QFont:
|
||||
font = QFont(heading_family() if medium else body_family())
|
||||
font.setPixelSize(size)
|
||||
font.setWeight(QFont.Weight.Medium if medium else QFont.Weight.Normal)
|
||||
return font
|
||||
|
||||
|
||||
def _elide(text: str, metrics: QFontMetrics, width: int) -> str:
|
||||
return metrics.elidedText(text, Qt.TextElideMode.ElideRight, max(1, width))
|
||||
|
||||
|
||||
def _herb_lines(text: str, metrics: QFontMetrics, width: int) -> list[str]:
|
||||
"""Wrap between complete herb entries; elide only the displayed lines."""
|
||||
entries = text.split("、")
|
||||
first = entries[0]
|
||||
next_index = 1
|
||||
while next_index < min(2, len(entries)):
|
||||
candidate = first + "、" + entries[next_index]
|
||||
if metrics.horizontalAdvance(candidate) > width:
|
||||
break
|
||||
first = candidate
|
||||
next_index += 1
|
||||
lines = [_elide(first, metrics, width)]
|
||||
if next_index < len(entries):
|
||||
lines.append(_elide("、".join(entries[next_index:]), metrics, width))
|
||||
return lines
|
||||
|
||||
|
||||
def _name_lines(text: str, metrics: QFontMetrics, width: int) -> list[str]:
|
||||
if metrics.horizontalAdvance(text) <= width:
|
||||
return [text]
|
||||
split = 1
|
||||
while split < len(text) and metrics.horizontalAdvance(text[: split + 1]) <= width:
|
||||
split += 1
|
||||
return [_elide(text[:split], metrics, width), _elide(text[split:], metrics, width)]
|
||||
|
||||
|
||||
class LibraryItemDelegate(QStyledItemDelegate):
|
||||
"""Paint the ten existing columns without changing display or source roles."""
|
||||
|
||||
def sizeHint(self, option: Any, index: QModelIndex) -> QSize: # noqa: N802
|
||||
size = super().sizeHint(option, index)
|
||||
size.setHeight(78)
|
||||
return size
|
||||
|
||||
def helpEvent(self, event: Any, view: Any, option: Any, index: QModelIndex) -> bool: # noqa: N802
|
||||
if event is not None and index.isValid() and index.column() != 9:
|
||||
text = index.data(Qt.ItemDataRole.ToolTipRole) or index.data(Qt.ItemDataRole.DisplayRole)
|
||||
if text:
|
||||
QToolTip.showText(event.globalPos(), str(text), view)
|
||||
return True
|
||||
return super().helpEvent(event, view, option, index)
|
||||
|
||||
@staticmethod
|
||||
def _paint_lines(
|
||||
painter: QPainter,
|
||||
rect: QRectF,
|
||||
lines: list[str],
|
||||
*,
|
||||
secondary_muted: bool = False,
|
||||
) -> None:
|
||||
line_height = 26
|
||||
top = rect.center().y() - len(lines) * line_height / 2
|
||||
for line_index, line in enumerate(lines):
|
||||
if secondary_muted and line_index:
|
||||
painter.setFont(_library_font(13))
|
||||
painter.setPen(QColor(PALETTE["muted"]))
|
||||
line_rect = QRectF(rect.left(), top + line_index * line_height, rect.width(), line_height)
|
||||
painter.drawText(line_rect, Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, line)
|
||||
|
||||
def paint(self, painter: QPainter, option: Any, index: QModelIndex) -> None:
|
||||
painter.save()
|
||||
try:
|
||||
painter.setClipRect(option.rect)
|
||||
selected = bool(option.state & QStyle.StateFlag.State_Selected)
|
||||
hovered = bool(option.state & QStyle.StateFlag.State_MouseOver)
|
||||
background = PALETTE["accent_soft"] if selected else PALETTE["surface_alt"] if hovered else PALETTE["surface"]
|
||||
painter.fillRect(option.rect, QColor(background))
|
||||
painter.setPen(QColor(PALETTE["line"]))
|
||||
painter.drawLine(option.rect.bottomLeft(), option.rect.bottomRight())
|
||||
if selected and index.column() == 0:
|
||||
stripe = QRectF(option.rect.left(), option.rect.top(), 3, option.rect.height() - 1)
|
||||
painter.fillRect(stripe, QColor(PALETTE["accent"]))
|
||||
if option.state & QStyle.StateFlag.State_HasFocus:
|
||||
painter.setPen(QColor(PALETTE["focus"]))
|
||||
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||
painter.drawRect(option.rect.adjusted(1, 1, -2, -2))
|
||||
|
||||
column = index.column()
|
||||
if column == 9:
|
||||
return
|
||||
rect = QRectF(option.rect.adjusted(12, 0, -12, -1))
|
||||
if rect.width() <= 0:
|
||||
return
|
||||
value = index.data(Qt.ItemDataRole.DisplayRole)
|
||||
text = "" if value is None else str(value)
|
||||
font = _library_font(medium=column == 1)
|
||||
painter.setFont(font)
|
||||
painter.setPen(QColor(PALETTE["text"]))
|
||||
metrics = QFontMetrics(font)
|
||||
width = int(rect.width())
|
||||
|
||||
if column == 2:
|
||||
painter.setFont(_library_font(13))
|
||||
metrics = painter.fontMetrics()
|
||||
label = _elide(text, metrics, width - 12)
|
||||
pill_width = min(rect.width(), metrics.horizontalAdvance(label) + 14)
|
||||
pill = QRectF(rect.center().x() - pill_width / 2, rect.center().y() - 12, pill_width, 24)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
|
||||
painter.setPen(Qt.PenStyle.NoPen)
|
||||
painter.setBrush(QColor(PALETTE["accent_soft"]))
|
||||
painter.drawRoundedRect(pill, RADII["small"], RADII["small"])
|
||||
painter.setPen(QColor(PALETTE["accent"]))
|
||||
painter.drawText(pill, Qt.AlignmentFlag.AlignCenter, label)
|
||||
elif column == 6:
|
||||
glyph = "users" if text == "所有人可见" else "lock"
|
||||
icon_rect = QRectF(rect.left(), rect.center().y() - 7, 14, 14)
|
||||
_library_icon(glyph, PALETTE["muted"], 14).paint(painter, icon_rect.toRect())
|
||||
label_rect = rect.adjusted(22, 0, 0, 0)
|
||||
painter.drawText(
|
||||
label_rect,
|
||||
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
|
||||
_elide(text, metrics, int(label_rect.width())),
|
||||
)
|
||||
elif column == 4:
|
||||
self._paint_lines(painter, rect, _herb_lines(text, metrics, width))
|
||||
elif column == 8:
|
||||
parts = text.splitlines() if "\n" in text else text.rsplit(" ", 1)
|
||||
lines = [_elide(parts[0], metrics, width)]
|
||||
if len(parts) > 1:
|
||||
lines.append(_elide(" ".join(parts[1:]), QFontMetrics(_library_font(13)), width))
|
||||
self._paint_lines(painter, rect, lines, secondary_muted=True)
|
||||
elif column == 1:
|
||||
self._paint_lines(painter, rect, _name_lines(text, metrics, width))
|
||||
else:
|
||||
alignment = Qt.AlignmentFlag.AlignCenter if column in (0, 3, 5) else (
|
||||
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter
|
||||
)
|
||||
painter.drawText(rect, alignment, _elide(text, metrics, width))
|
||||
finally:
|
||||
painter.restore()
|
||||
|
||||
|
||||
_LIBRARY = """
|
||||
#PrescriptionLibraryPage { background: $ds_canvas; color: $ds_text; }
|
||||
#PrescriptionLibraryPage QWidget#PrescriptionLibraryContent,
|
||||
#PrescriptionLibraryPage QScrollArea#PrescriptionLibraryScroll,
|
||||
#PrescriptionLibraryPage QScrollArea#PrescriptionLibraryToolbarScroll {
|
||||
background: transparent; border: 0;
|
||||
}
|
||||
#PrescriptionLibraryPage QLabel, #PrescriptionLibraryPage QPushButton,
|
||||
#PrescriptionLibraryPage QLineEdit, #PrescriptionLibraryPage QComboBox,
|
||||
#PrescriptionLibraryPage QTableWidget {
|
||||
font-family: "$body"; font-size: 14px; font-weight: 400; color: $ds_text;
|
||||
}
|
||||
#PrescriptionLibraryPage QLabel[role="pageTitle"] {
|
||||
font-family: "$heading"; font-size: 20px; font-weight: 600; color: $ds_heading;
|
||||
}
|
||||
#PrescriptionLibraryPage QLabel[role="muted"] { color: $ds_muted; font-size: 13px; }
|
||||
#PrescriptionLibraryPage QFrame#PrescriptionLibraryFilterBar,
|
||||
#PrescriptionLibraryPage QFrame#PrescriptionLibraryTableCard {
|
||||
background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_panel;
|
||||
}
|
||||
#PrescriptionLibraryPage QFrame#MetricCard { background: $ds_surface; border: 0; border-radius: $ds_radius_panel; }
|
||||
#PrescriptionLibraryPage QFrame#MetricCard QLabel[role="metricTitle"] {
|
||||
font-family: "$body"; color: $ds_muted; font-size: 13px; font-weight: 400;
|
||||
}
|
||||
#PrescriptionLibraryPage QFrame#MetricCard QLabel[role="metricValue"] {
|
||||
font-family: "$heading"; color: $ds_text; font-size: 18px; font-weight: 600;
|
||||
}
|
||||
#PrescriptionLibraryPage QFrame#MetricCard QLabel[metricIcon="true"] {
|
||||
border: 0; border-radius: 0; background: transparent;
|
||||
}
|
||||
#PrescriptionLibraryPage QPushButton {
|
||||
min-height: 38px; max-height: 38px; padding: 0 16px; border-radius: $ds_radius_control;
|
||||
border: 1px solid transparent; background: $ds_surface_alt; color: $ds_text;
|
||||
}
|
||||
#PrescriptionLibraryPage QPushButton:hover { background: $ds_surface_alt; border-color: $ds_line_strong; color: $ds_accent; }
|
||||
#PrescriptionLibraryPage QPushButton:pressed { background: $ds_accent_soft; }
|
||||
#PrescriptionLibraryPage QPushButton:focus { border-color: $ds_focus; }
|
||||
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton,
|
||||
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton {
|
||||
background: $ds_accent; border-color: $ds_accent; color: $ds_surface;
|
||||
}
|
||||
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton:hover,
|
||||
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton:hover {
|
||||
background: $ds_accent_hover; border-color: $ds_accent_hover;
|
||||
}
|
||||
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton:pressed,
|
||||
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton:pressed {
|
||||
background: $ds_accent_pressed; border-color: $ds_accent_pressed;
|
||||
}
|
||||
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton:focus,
|
||||
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton:focus { border-color: $ds_focus; }
|
||||
#PrescriptionLibraryPage QPushButton[variant="danger"] { color: $ds_danger; background: $ds_danger_soft; border-color: transparent; }
|
||||
#PrescriptionLibraryPage QPushButton[variant="danger"]:hover { border-color: $ds_danger; }
|
||||
#PrescriptionLibraryPage QPushButton[variant="danger"]:focus { border-color: $ds_focus; }
|
||||
#PrescriptionLibraryPage QPushButton:disabled,
|
||||
#PrescriptionLibraryPage QPushButton[variant="danger"]:disabled,
|
||||
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton:disabled,
|
||||
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton:disabled {
|
||||
color: $ds_disabled; background: $ds_disabled_surface; border-color: $ds_line;
|
||||
}
|
||||
#PrescriptionLibraryPage QLineEdit, #PrescriptionLibraryPage QComboBox {
|
||||
min-height: 38px; max-height: 38px; padding: 0 12px; border: 1px solid $ds_line;
|
||||
border-radius: $ds_radius_control; background: $ds_surface; color: $ds_text;
|
||||
selection-background-color: $ds_accent_soft; selection-color: $ds_text;
|
||||
}
|
||||
#PrescriptionLibraryPage QLineEdit:focus, #PrescriptionLibraryPage QComboBox:focus { border-color: $ds_focus; }
|
||||
#PrescriptionLibraryPage QLineEdit QToolButton { border: 0; background: transparent; padding: 0; }
|
||||
#PrescriptionLibraryPage QComboBox { padding-right: 30px; font-size: 13px; }
|
||||
#PrescriptionLibraryPage QComboBox::drop-down { width: 28px; border: 0; background: transparent; }
|
||||
#PrescriptionLibraryPage QComboBox::down-arrow { image: none; width: 0; height: 0; }
|
||||
#PrescriptionLibraryPage QComboBox:disabled { color: $ds_disabled; background: $ds_disabled_surface; }
|
||||
#PrescriptionLibraryPage QComboBox QAbstractItemView {
|
||||
font-family: "$body"; font-size: 13px; color: $ds_text; background: $ds_surface;
|
||||
border: 1px solid $ds_line; outline: 0; selection-background-color: $ds_accent_soft; selection-color: $ds_accent;
|
||||
}
|
||||
#PrescriptionLibraryPage QComboBox QAbstractItemView::item { min-height: 30px; padding: 3px 10px; }
|
||||
#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar { background: transparent; border: 0; }
|
||||
#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar QPushButton { padding: 0 12px; font-size: 13px; }
|
||||
#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar QPushButton[toolbarTab="true"] {
|
||||
min-width: 80px; min-height: 40px; max-height: 40px; padding: 0 10px; margin-right: 8px;
|
||||
background: transparent; border: 0; border-bottom: 2px solid transparent;
|
||||
border-radius: 0; color: $ds_text; font-size: 14px;
|
||||
}
|
||||
#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar QPushButton[toolbarTab="true"]:checked {
|
||||
color: $ds_accent; border-bottom-color: $ds_accent;
|
||||
}
|
||||
#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar QPushButton[toolbarTab="true"]:hover {
|
||||
color: $ds_accent; background: $ds_surface_alt;
|
||||
}
|
||||
#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar QPushButton[toolbarTab="true"]:focus { background: $ds_accent_soft; }
|
||||
#PrescriptionLibraryPage QTableWidget {
|
||||
border: 0; background: $ds_surface; alternate-background-color: $ds_surface;
|
||||
selection-background-color: $ds_accent_soft; selection-color: $ds_text; gridline-color: $ds_line;
|
||||
}
|
||||
#PrescriptionLibraryPage QTableWidget::item { padding: 0; border: 0; }
|
||||
#PrescriptionLibraryPage QHeaderView::section {
|
||||
min-height: 0; padding: 0 12px; background: $ds_surface_alt; color: $ds_muted;
|
||||
border: 0; border-bottom: 1px solid $ds_line;
|
||||
font-family: "$body"; font-size: 13px; font-weight: 400;
|
||||
}
|
||||
#PrescriptionLibraryPage QWidget#PrescriptionLibraryTableCellHost { background: transparent; border: 0; }
|
||||
#PrescriptionLibraryPage QPushButton[rowAction="true"] {
|
||||
min-width: 28px; max-width: 28px; min-height: 28px; max-height: 28px;
|
||||
padding: 0; border: 1px solid transparent; border-radius: $ds_radius_small; background: transparent;
|
||||
}
|
||||
#PrescriptionLibraryPage QPushButton[rowAction="true"]:hover { background: $ds_accent_soft; border-color: $ds_line_strong; }
|
||||
#PrescriptionLibraryPage QPushButton[rowAction="true"]:focus { border-color: $ds_focus; }
|
||||
#PrescriptionLibraryPage QPushButton[rowAction="true"][danger="true"]:hover { background: $ds_danger_soft; border-color: $ds_danger_soft; }
|
||||
#PrescriptionLibraryPage QPushButton[rowAction="true"][danger="true"]:focus { border-color: $ds_focus; }
|
||||
#PrescriptionLibraryPage QPushButton[rowAction="true"]:disabled { background: transparent; border-color: transparent; color: $ds_disabled; }
|
||||
#PrescriptionLibraryPage QWidget#InfiniteList { background: $ds_surface; border-top: 1px solid $ds_line; }
|
||||
#PrescriptionLibraryPage QLabel#EmptyStateGlyph {
|
||||
font-size: 24px; color: $ds_accent; background: $ds_surface_alt;
|
||||
border: 1px solid $ds_line; border-radius: $ds_radius_panel;
|
||||
}
|
||||
#PrescriptionLibraryPage QWidget#EmptyState QLabel[role="muted"] { min-width: 300px; }
|
||||
#PrescriptionLibraryPage QScrollBar:vertical { background: $ds_canvas; width: 7px; margin: 0; }
|
||||
#PrescriptionLibraryPage QScrollBar:horizontal { background: $ds_canvas; height: 7px; margin: 0; }
|
||||
#PrescriptionLibraryPage QScrollBar::handle { background: $ds_line_strong; border-radius: 3px; min-width: 24px; min-height: 24px; }
|
||||
#PrescriptionLibraryPage QScrollBar::add-line, #PrescriptionLibraryPage QScrollBar::sub-line { width: 0; height: 0; }
|
||||
#PrescriptionLibraryPage QScrollBar::add-page, #PrescriptionLibraryPage QScrollBar::sub-page { background: transparent; }
|
||||
"""
|
||||
|
||||
|
||||
__all__ = ["library_stylesheet", "LibraryComboBox", "LibraryTable", "LibraryItemDelegate"]
|
||||
"""Local technology-blue rendering for the approved prescription library."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterable
|
||||
from string import Template
|
||||
from typing import Any
|
||||
|
||||
from PySide6.QtCore import QModelIndex, QRectF, QSize, Qt
|
||||
from PySide6.QtGui import QColor, QFont, QFontMetrics, QIcon, QPainter
|
||||
from PySide6.QtWidgets import (
|
||||
QComboBox,
|
||||
QPushButton,
|
||||
QStyle,
|
||||
QStyledItemDelegate,
|
||||
QToolTip,
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from .reception_style import body_family, heading_family
|
||||
from .widgets import SortableTable, first_value
|
||||
|
||||
|
||||
def library_stylesheet() -> str:
|
||||
return Template(_LIBRARY).substitute(body=body_family(), heading=heading_family())
|
||||
|
||||
|
||||
def _library_icon(kind: str, color: str = "#1769E8", size: int = 15) -> QIcon:
|
||||
# Defer the page helper lookup so importing this module alone does not
|
||||
# recurse through pages.__init__ and the library page's own style import.
|
||||
from .pages.prescriptions import _painted_icon
|
||||
|
||||
result = QIcon()
|
||||
for mode, tint in (
|
||||
(QIcon.Mode.Normal, color),
|
||||
(QIcon.Mode.Active, color),
|
||||
(QIcon.Mode.Selected, color),
|
||||
(QIcon.Mode.Disabled, "#A4ADBA"),
|
||||
):
|
||||
pixmap = _painted_icon(kind, tint, size).pixmap(QSize(size, size))
|
||||
for state in (QIcon.State.Off, QIcon.State.On):
|
||||
result.addPixmap(pixmap, mode, state)
|
||||
return result
|
||||
|
||||
|
||||
class LibraryComboBox(QComboBox):
|
||||
"""Keep native combo interaction while painting the local caret."""
|
||||
|
||||
def paintEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual
|
||||
super().paintEvent(event)
|
||||
painter = QPainter(self)
|
||||
try:
|
||||
rect = QRectF(self.width() - 25, (self.height() - 14) / 2, 14, 14)
|
||||
mode = QIcon.Mode.Normal if self.isEnabled() else QIcon.Mode.Disabled
|
||||
_library_icon("chevron_down", "#5D6B80", 14).paint(painter, rect.toRect(), mode=mode)
|
||||
finally:
|
||||
painter.end()
|
||||
|
||||
|
||||
class LibraryTable(SortableTable):
|
||||
"""Repaint existing action widgets and restore selection by template ID."""
|
||||
|
||||
def set_rows(self, rows: Iterable[Any]) -> None:
|
||||
selected_id = first_value(self.current_data(), "id", "template_id", default=None)
|
||||
super().set_rows(rows)
|
||||
# The shared table restores an unsorted row index after enabling sort.
|
||||
# Locate the same source object in the finished visual order instead.
|
||||
if selected_id is not None:
|
||||
for row_index in range(self.rowCount()):
|
||||
item = self.item(row_index, 0)
|
||||
row = item.data(Qt.ItemDataRole.UserRole) if item is not None else None
|
||||
row_id = first_value(row, "id", "template_id", default=None)
|
||||
if row_id is not None and str(row_id) == str(selected_id):
|
||||
self.selectRow(row_index)
|
||||
return
|
||||
self.clearSelection()
|
||||
self.setCurrentCell(-1, -1)
|
||||
|
||||
def setCellWidget(self, row: int, column: int, widget: QWidget | None) -> None: # noqa: N802
|
||||
super().setCellWidget(row, column, widget)
|
||||
if widget is None or column != 9:
|
||||
return
|
||||
widget.setObjectName("PrescriptionLibraryTableCellHost")
|
||||
widget.setAutoFillBackground(False)
|
||||
glyphs = {
|
||||
"查看处方模板": "eye",
|
||||
"AI 解释": "spark",
|
||||
"编辑处方模板": "pencil",
|
||||
"删除处方模板": "trash",
|
||||
}
|
||||
for button in widget.findChildren(QPushButton):
|
||||
if not button.property("rowAction"):
|
||||
continue
|
||||
glyph = glyphs.get(button.accessibleName()) or glyphs.get(button.toolTip())
|
||||
if glyph is not None:
|
||||
color = "#BE4657" if button.property("danger") else "#1769E8"
|
||||
button.setIcon(_library_icon(glyph, color, button.iconSize().width()))
|
||||
|
||||
|
||||
def _library_font(size: int = 14, *, medium: bool = False) -> QFont:
|
||||
font = QFont(heading_family() if medium else body_family())
|
||||
font.setPixelSize(size)
|
||||
font.setWeight(QFont.Weight.Medium if medium else QFont.Weight.Normal)
|
||||
return font
|
||||
|
||||
|
||||
def _elide(text: str, metrics: QFontMetrics, width: int) -> str:
|
||||
return metrics.elidedText(text, Qt.TextElideMode.ElideRight, max(1, width))
|
||||
|
||||
|
||||
def _herb_lines(text: str, metrics: QFontMetrics, width: int) -> list[str]:
|
||||
"""Wrap between complete herb entries; elide only the displayed lines."""
|
||||
entries = text.split("、")
|
||||
first = entries[0]
|
||||
next_index = 1
|
||||
while next_index < min(2, len(entries)):
|
||||
candidate = first + "、" + entries[next_index]
|
||||
if metrics.horizontalAdvance(candidate) > width:
|
||||
break
|
||||
first = candidate
|
||||
next_index += 1
|
||||
lines = [_elide(first, metrics, width)]
|
||||
if next_index < len(entries):
|
||||
lines.append(_elide("、".join(entries[next_index:]), metrics, width))
|
||||
return lines
|
||||
|
||||
|
||||
def _name_lines(text: str, metrics: QFontMetrics, width: int) -> list[str]:
|
||||
if metrics.horizontalAdvance(text) <= width:
|
||||
return [text]
|
||||
split = 1
|
||||
while split < len(text) and metrics.horizontalAdvance(text[: split + 1]) <= width:
|
||||
split += 1
|
||||
return [_elide(text[:split], metrics, width), _elide(text[split:], metrics, width)]
|
||||
|
||||
|
||||
class LibraryItemDelegate(QStyledItemDelegate):
|
||||
"""Paint the ten existing columns without changing display or source roles."""
|
||||
|
||||
def sizeHint(self, option: Any, index: QModelIndex) -> QSize: # noqa: N802
|
||||
size = super().sizeHint(option, index)
|
||||
size.setHeight(78)
|
||||
return size
|
||||
|
||||
def helpEvent(self, event: Any, view: Any, option: Any, index: QModelIndex) -> bool: # noqa: N802
|
||||
if event is not None and index.isValid() and index.column() != 9:
|
||||
text = index.data(Qt.ItemDataRole.ToolTipRole) or index.data(Qt.ItemDataRole.DisplayRole)
|
||||
if text:
|
||||
QToolTip.showText(event.globalPos(), str(text), view)
|
||||
return True
|
||||
return super().helpEvent(event, view, option, index)
|
||||
|
||||
@staticmethod
|
||||
def _paint_lines(
|
||||
painter: QPainter,
|
||||
rect: QRectF,
|
||||
lines: list[str],
|
||||
*,
|
||||
secondary_muted: bool = False,
|
||||
) -> None:
|
||||
line_height = 26
|
||||
top = rect.center().y() - len(lines) * line_height / 2
|
||||
for line_index, line in enumerate(lines):
|
||||
if secondary_muted and line_index:
|
||||
painter.setFont(_library_font(13))
|
||||
painter.setPen(QColor("#5D6B80"))
|
||||
line_rect = QRectF(rect.left(), top + line_index * line_height, rect.width(), line_height)
|
||||
painter.drawText(line_rect, Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, line)
|
||||
|
||||
def paint(self, painter: QPainter, option: Any, index: QModelIndex) -> None:
|
||||
painter.save()
|
||||
try:
|
||||
painter.setClipRect(option.rect)
|
||||
selected = bool(option.state & QStyle.StateFlag.State_Selected)
|
||||
hovered = bool(option.state & QStyle.StateFlag.State_MouseOver)
|
||||
background = "#F2F7FF" if selected else "#F8FAFE" if hovered else "#FFFFFF"
|
||||
painter.fillRect(option.rect, QColor(background))
|
||||
painter.setPen(QColor("#E6EDF6"))
|
||||
painter.drawLine(option.rect.bottomLeft(), option.rect.bottomRight())
|
||||
if selected and index.column() == 0:
|
||||
stripe = QRectF(option.rect.left(), option.rect.top(), 3, option.rect.height() - 1)
|
||||
painter.fillRect(stripe, QColor("#1769E8"))
|
||||
if option.state & QStyle.StateFlag.State_HasFocus:
|
||||
painter.setPen(QColor("#75A5F0"))
|
||||
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||
painter.drawRect(option.rect.adjusted(1, 1, -2, -2))
|
||||
|
||||
column = index.column()
|
||||
if column == 9:
|
||||
return
|
||||
rect = QRectF(option.rect.adjusted(12, 0, -12, -1))
|
||||
if rect.width() <= 0:
|
||||
return
|
||||
value = index.data(Qt.ItemDataRole.DisplayRole)
|
||||
text = "" if value is None else str(value)
|
||||
font = _library_font(medium=column == 1)
|
||||
painter.setFont(font)
|
||||
painter.setPen(QColor("#273244"))
|
||||
metrics = QFontMetrics(font)
|
||||
width = int(rect.width())
|
||||
|
||||
if column == 2:
|
||||
painter.setFont(_library_font(13))
|
||||
metrics = painter.fontMetrics()
|
||||
label = _elide(text, metrics, width - 12)
|
||||
pill_width = min(rect.width(), metrics.horizontalAdvance(label) + 14)
|
||||
pill = QRectF(rect.center().x() - pill_width / 2, rect.center().y() - 12, pill_width, 24)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
|
||||
painter.setPen(Qt.PenStyle.NoPen)
|
||||
painter.setBrush(QColor("#EAF2FF"))
|
||||
painter.drawRoundedRect(pill, 4, 4)
|
||||
painter.setPen(QColor("#1769E8"))
|
||||
painter.drawText(pill, Qt.AlignmentFlag.AlignCenter, label)
|
||||
elif column == 6:
|
||||
glyph = "users" if text == "所有人可见" else "lock"
|
||||
icon_rect = QRectF(rect.left(), rect.center().y() - 7, 14, 14)
|
||||
_library_icon(glyph, "#5D6B80", 14).paint(painter, icon_rect.toRect())
|
||||
label_rect = rect.adjusted(22, 0, 0, 0)
|
||||
painter.drawText(
|
||||
label_rect,
|
||||
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
|
||||
_elide(text, metrics, int(label_rect.width())),
|
||||
)
|
||||
elif column == 4:
|
||||
self._paint_lines(painter, rect, _herb_lines(text, metrics, width))
|
||||
elif column == 8:
|
||||
parts = text.splitlines() if "\n" in text else text.rsplit(" ", 1)
|
||||
lines = [_elide(parts[0], metrics, width)]
|
||||
if len(parts) > 1:
|
||||
lines.append(_elide(" ".join(parts[1:]), QFontMetrics(_library_font(13)), width))
|
||||
self._paint_lines(painter, rect, lines, secondary_muted=True)
|
||||
elif column == 1:
|
||||
self._paint_lines(painter, rect, _name_lines(text, metrics, width))
|
||||
else:
|
||||
alignment = Qt.AlignmentFlag.AlignCenter if column in (0, 3, 5) else (
|
||||
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter
|
||||
)
|
||||
painter.drawText(rect, alignment, _elide(text, metrics, width))
|
||||
finally:
|
||||
painter.restore()
|
||||
|
||||
|
||||
_LIBRARY = """
|
||||
#PrescriptionLibraryPage { background: #F3F7FD; color: #273244; }
|
||||
#PrescriptionLibraryPage QWidget#PrescriptionLibraryContent,
|
||||
#PrescriptionLibraryPage QScrollArea#PrescriptionLibraryScroll,
|
||||
#PrescriptionLibraryPage QScrollArea#PrescriptionLibraryToolbarScroll {
|
||||
background: transparent; border: 0;
|
||||
}
|
||||
#PrescriptionLibraryPage QLabel, #PrescriptionLibraryPage QPushButton,
|
||||
#PrescriptionLibraryPage QLineEdit, #PrescriptionLibraryPage QComboBox,
|
||||
#PrescriptionLibraryPage QTableWidget {
|
||||
font-family: "$body"; font-size: 14px; font-weight: 400; color: #273244;
|
||||
}
|
||||
#PrescriptionLibraryPage QLabel[role="pageTitle"] {
|
||||
font-family: "$heading"; font-size: 20px; font-weight: 600; color: #202C3F;
|
||||
}
|
||||
#PrescriptionLibraryPage QLabel[role="muted"] { color: #5D6B80; font-size: 13px; }
|
||||
#PrescriptionLibraryPage QFrame#MetricCard,
|
||||
#PrescriptionLibraryPage QFrame#PrescriptionLibraryFilterBar,
|
||||
#PrescriptionLibraryPage QFrame#PrescriptionLibraryTableCard {
|
||||
background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 8px;
|
||||
}
|
||||
#PrescriptionLibraryPage QFrame#MetricCard QLabel[role="metricTitle"] {
|
||||
font-family: "$body"; color: #5D6B80; font-size: 13px; font-weight: 400;
|
||||
}
|
||||
#PrescriptionLibraryPage QFrame#MetricCard QLabel[role="metricValue"] {
|
||||
font-family: "$heading"; color: #273244; font-size: 18px; font-weight: 600;
|
||||
}
|
||||
#PrescriptionLibraryPage QFrame#MetricCard QLabel[metricIcon="true"] {
|
||||
border: 0; border-radius: 0; background: transparent;
|
||||
}
|
||||
#PrescriptionLibraryPage QPushButton {
|
||||
min-height: 38px; max-height: 38px; padding: 0 16px; border-radius: 5px;
|
||||
border: 1px solid #DBE5F2; background: #FFFFFF; color: #273244;
|
||||
}
|
||||
#PrescriptionLibraryPage QPushButton:hover { background: #F2F7FF; border-color: #B6CDEE; color: #1555B6; }
|
||||
#PrescriptionLibraryPage QPushButton:pressed { background: #DCEAFF; }
|
||||
#PrescriptionLibraryPage QPushButton:focus { border-color: #75A5F0; }
|
||||
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton,
|
||||
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton {
|
||||
background: #1769E8; border-color: #1769E8; color: #FFFFFF;
|
||||
}
|
||||
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton:hover,
|
||||
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton:hover {
|
||||
background: #155BCC; border-color: #155BCC;
|
||||
}
|
||||
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton:pressed,
|
||||
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton:pressed {
|
||||
background: #124EA9; border-color: #124EA9;
|
||||
}
|
||||
#PrescriptionLibraryPage QPushButton[variant="danger"] { color: #BE4657; border-color: #E9D8DE; }
|
||||
#PrescriptionLibraryPage QPushButton:disabled,
|
||||
#PrescriptionLibraryPage QPushButton[variant="danger"]:disabled {
|
||||
color: #97A4B6; background: #F6F8FC; border-color: #E2E9F2;
|
||||
}
|
||||
#PrescriptionLibraryPage QLineEdit, #PrescriptionLibraryPage QComboBox {
|
||||
min-height: 38px; max-height: 38px; padding: 0 12px; border: 1px solid #DBE5F2;
|
||||
border-radius: 5px; background: #FFFFFF; color: #273244;
|
||||
selection-background-color: #DCEAFF; selection-color: #273244;
|
||||
}
|
||||
#PrescriptionLibraryPage QLineEdit:focus, #PrescriptionLibraryPage QComboBox:focus { border-color: #75A5F0; }
|
||||
#PrescriptionLibraryPage QLineEdit QToolButton { border: 0; background: transparent; padding: 0; }
|
||||
#PrescriptionLibraryPage QComboBox { padding-right: 30px; font-size: 13px; }
|
||||
#PrescriptionLibraryPage QComboBox::drop-down { width: 28px; border: 0; background: transparent; }
|
||||
#PrescriptionLibraryPage QComboBox::down-arrow { image: none; width: 0; height: 0; }
|
||||
#PrescriptionLibraryPage QComboBox:disabled { color: #97A4B6; background: #F6F8FC; }
|
||||
#PrescriptionLibraryPage QComboBox QAbstractItemView {
|
||||
font-family: "$body"; font-size: 13px; color: #273244; background: #FFFFFF;
|
||||
border: 1px solid #DBE5F2; outline: 0; selection-background-color: #EAF2FF; selection-color: #1555B6;
|
||||
}
|
||||
#PrescriptionLibraryPage QComboBox QAbstractItemView::item { min-height: 30px; padding: 3px 10px; }
|
||||
#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar { background: transparent; border: 0; }
|
||||
#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar QPushButton { padding: 0 12px; font-size: 13px; }
|
||||
#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar QPushButton[toolbarTab="true"] {
|
||||
min-width: 80px; min-height: 40px; max-height: 40px; padding: 0 10px; margin-right: 8px;
|
||||
background: transparent; border: 0; border-bottom: 2px solid transparent;
|
||||
border-radius: 0; color: #273244; font-size: 14px;
|
||||
}
|
||||
#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar QPushButton[toolbarTab="true"]:checked {
|
||||
color: #1769E8; border-bottom-color: #1769E8;
|
||||
}
|
||||
#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar QPushButton[toolbarTab="true"]:hover {
|
||||
color: #1555B6; background: #F2F7FF;
|
||||
}
|
||||
#PrescriptionLibraryPage QTableWidget {
|
||||
border: 0; background: #FFFFFF; alternate-background-color: #FFFFFF;
|
||||
selection-background-color: #F2F7FF; selection-color: #273244; gridline-color: #E6EDF6;
|
||||
}
|
||||
#PrescriptionLibraryPage QTableWidget::item { padding: 0; border: 0; }
|
||||
#PrescriptionLibraryPage QHeaderView::section {
|
||||
min-height: 0; padding: 0 12px; background: #F5F8FD; color: #5D6B80;
|
||||
border: 0; border-bottom: 1px solid #DBE5F2;
|
||||
font-family: "$body"; font-size: 13px; font-weight: 400;
|
||||
}
|
||||
#PrescriptionLibraryPage QWidget#PrescriptionLibraryTableCellHost { background: transparent; border: 0; }
|
||||
#PrescriptionLibraryPage QPushButton[rowAction="true"] {
|
||||
min-width: 28px; max-width: 28px; min-height: 28px; max-height: 28px;
|
||||
padding: 0; border: 1px solid transparent; border-radius: 4px; background: transparent;
|
||||
}
|
||||
#PrescriptionLibraryPage QPushButton[rowAction="true"]:hover { background: #EAF2FF; border-color: #B6CDEE; }
|
||||
#PrescriptionLibraryPage QPushButton[rowAction="true"]:focus { border-color: #75A5F0; }
|
||||
#PrescriptionLibraryPage QPushButton[rowAction="true"][danger="true"]:hover { background: #FFF0F2; border-color: #EAC8D0; }
|
||||
#PrescriptionLibraryPage QPushButton[rowAction="true"]:disabled { background: transparent; border-color: transparent; color: #A4ADBA; }
|
||||
#PrescriptionLibraryPage QWidget#InfiniteList { background: #FFFFFF; border-top: 1px solid #E6EDF6; }
|
||||
#PrescriptionLibraryPage QLabel#EmptyStateGlyph {
|
||||
font-size: 24px; color: #1769E8; background: #F2F7FF;
|
||||
border: 1px solid #DBE5F2; border-radius: 22px;
|
||||
}
|
||||
#PrescriptionLibraryPage QWidget#EmptyState QLabel[role="muted"] { min-width: 300px; }
|
||||
#PrescriptionLibraryPage QScrollBar:vertical { background: #F4F7FC; width: 7px; margin: 0; }
|
||||
#PrescriptionLibraryPage QScrollBar:horizontal { background: #F4F7FC; height: 7px; margin: 0; }
|
||||
#PrescriptionLibraryPage QScrollBar::handle { background: #C8D5E6; border-radius: 3px; min-width: 24px; min-height: 24px; }
|
||||
#PrescriptionLibraryPage QScrollBar::add-line, #PrescriptionLibraryPage QScrollBar::sub-line { width: 0; height: 0; }
|
||||
#PrescriptionLibraryPage QScrollBar::add-page, #PrescriptionLibraryPage QScrollBar::sub-page { background: transparent; }
|
||||
"""
|
||||
|
||||
|
||||
__all__ = ["library_stylesheet", "LibraryComboBox", "LibraryTable", "LibraryItemDelegate"]
|
||||
|
||||
@@ -1,115 +1,107 @@
|
||||
"""Scoped surfaces and real fonts for the approved issued-prescription page."""
|
||||
|
||||
from string import Template
|
||||
|
||||
from .design_system import clinical_stylesheet
|
||||
from .reception_style import body_family, heading_family
|
||||
|
||||
|
||||
def prescriptions_stylesheet() -> str:
|
||||
return clinical_stylesheet(Template(_PRESCRIPTIONS).safe_substitute(body=body_family(), heading=heading_family()))
|
||||
|
||||
|
||||
_PRESCRIPTIONS = """
|
||||
#PrescriptionsPage { background: $ds_canvas; color: $ds_text; }
|
||||
#PrescriptionWorkspaceContent, #PrescriptionWorkspaceScroll { background: transparent; border: 0; }
|
||||
#PrescriptionsPage QLabel, #PrescriptionsPage QPushButton, #PrescriptionsPage QLineEdit,
|
||||
#PrescriptionsPage QComboBox, #PrescriptionsPage QDateTimeEdit, #PrescriptionsPage QTableWidget {
|
||||
font-family: "$body"; font-size: 14px; font-weight: 400; color: $ds_text;
|
||||
}
|
||||
#PrescriptionsPage QLabel[role="pageTitle"] {
|
||||
font-family: "$heading"; font-size: 20px; font-weight: 600; color: $ds_heading;
|
||||
}
|
||||
#PrescriptionsPage QLabel[role="sectionTitle"] {
|
||||
font-family: "$heading"; font-size: 14px; font-weight: 600;
|
||||
}
|
||||
#PrescriptionsPage QLabel[role="muted"], #PrescriptionsPage QLabel#PrescriptionCountBadge {
|
||||
color: $ds_muted; font-size: 13px; background: transparent; border: 0; padding: 0;
|
||||
}
|
||||
#PrescriptionsPage QFrame#PrescriptionFilterBar, #PrescriptionsPage QFrame#PrescriptionTableCard {
|
||||
background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_panel;
|
||||
}
|
||||
#PrescriptionsPage QFrame#PrescriptionToolbar { background: transparent; border: 0; }
|
||||
#PrescriptionsPage QPushButton {
|
||||
min-height: 38px; max-height: 38px; padding: 0 16px; border-radius: $ds_radius_control;
|
||||
border: 1px solid transparent; background: $ds_surface_alt; color: $ds_text;
|
||||
}
|
||||
#PrescriptionsPage QPushButton:hover { background: $ds_surface_alt; border-color: $ds_line_strong; color: $ds_accent; }
|
||||
#PrescriptionsPage QPushButton:pressed { background: $ds_accent_soft; }
|
||||
#PrescriptionsPage QPushButton:focus { border-color: $ds_focus; }
|
||||
#PrescriptionsPage QPushButton#PrescriptionAddButton, #PrescriptionsPage QPushButton#PrescriptionQueryButton {
|
||||
background: $ds_accent; color: $ds_surface; border-color: $ds_accent;
|
||||
}
|
||||
#PrescriptionsPage QPushButton#PrescriptionAddButton:hover, #PrescriptionsPage QPushButton#PrescriptionQueryButton:hover {
|
||||
background: $ds_accent_hover; border-color: $ds_accent_hover;
|
||||
}
|
||||
#PrescriptionsPage QPushButton#PrescriptionAddButton:pressed, #PrescriptionsPage QPushButton#PrescriptionQueryButton:pressed {
|
||||
background: $ds_accent_pressed; border-color: $ds_accent_pressed;
|
||||
}
|
||||
#PrescriptionsPage QPushButton#PrescriptionAddButton:focus,
|
||||
#PrescriptionsPage QPushButton#PrescriptionQueryButton:focus { border-color: $ds_focus; }
|
||||
#PrescriptionsPage QPushButton[variant="danger"] { color: $ds_danger; background: $ds_danger_soft; border-color: transparent; }
|
||||
#PrescriptionsPage QPushButton[variant="danger"]:hover { border-color: $ds_danger; }
|
||||
#PrescriptionsPage QPushButton[variant="danger"]:focus { border-color: $ds_focus; }
|
||||
#PrescriptionsPage QPushButton:disabled, #PrescriptionsPage QPushButton[variant="danger"]:disabled,
|
||||
#PrescriptionsPage QPushButton#PrescriptionAddButton:disabled,
|
||||
#PrescriptionsPage QPushButton#PrescriptionQueryButton:disabled {
|
||||
color: $ds_disabled; background: $ds_disabled_surface; border-color: $ds_line;
|
||||
}
|
||||
#PrescriptionsPage QLineEdit, #PrescriptionsPage QComboBox, #PrescriptionsPage QDateTimeEdit {
|
||||
min-height: 38px; max-height: 38px; padding: 0 12px; border: 1px solid $ds_line;
|
||||
border-radius: $ds_radius_control; background: $ds_surface; color: $ds_text;
|
||||
selection-background-color: $ds_accent_soft; selection-color: $ds_text;
|
||||
}
|
||||
#PrescriptionsPage QLineEdit:focus, #PrescriptionsPage QComboBox:focus, #PrescriptionsPage QDateTimeEdit:focus { border-color: $ds_focus; }
|
||||
#PrescriptionsPage QLineEdit QToolButton { min-width: 0; min-height: 0; border: 0; background: transparent; padding: 0; }
|
||||
#PrescriptionsPage QComboBox, #PrescriptionsPage QDateTimeEdit { padding-right: 30px; font-size: 13px; }
|
||||
#PrescriptionsPage QComboBox::drop-down, #PrescriptionsPage QDateTimeEdit::drop-down { width: 28px; border: 0; background: transparent; }
|
||||
#PrescriptionsPage QComboBox::down-arrow, #PrescriptionsPage QDateTimeEdit::down-arrow { image: none; width: 0; height: 0; }
|
||||
#PrescriptionsPage QDateTimeEdit:disabled { color: $ds_disabled; background: $ds_disabled_surface; border-color: $ds_line; }
|
||||
#PrescriptionsPage QPushButton#PrescriptionDoctorButton { text-align: left; padding-right: 30px; font-size: 13px; }
|
||||
#PrescriptionsPage QComboBox QAbstractItemView {
|
||||
font-family: "$body"; font-size: 13px; color: $ds_text; background: $ds_surface;
|
||||
border: 1px solid $ds_line; outline: 0; selection-background-color: $ds_accent_soft; selection-color: $ds_accent;
|
||||
}
|
||||
#PrescriptionsPage QComboBox QAbstractItemView::item { min-height: 30px; padding: 3px 10px; }
|
||||
#PrescriptionsPage QCalendarWidget { font-family: "$body"; font-size: 13px; background: $ds_surface; color: $ds_text; }
|
||||
#PrescriptionsPage QCalendarWidget QWidget#qt_calendar_navigationbar { background: $ds_surface_alt; }
|
||||
#PrescriptionsPage QCalendarWidget QToolButton { min-height: 28px; border: 0; padding: 0 8px; color: $ds_text; background: transparent; }
|
||||
#PrescriptionsPage QCalendarWidget QAbstractItemView { color: $ds_text; background: $ds_surface; selection-background-color: $ds_accent; selection-color: $ds_surface; outline: 0; }
|
||||
#PrescriptionsPage QFrame#PrescriptionToolbar QPushButton { padding: 0 12px; font-size: 13px; }
|
||||
#PrescriptionsPage QTableWidget#PrescriptionTable {
|
||||
border: 0; background: $ds_surface; alternate-background-color: $ds_surface;
|
||||
selection-background-color: $ds_accent_soft; selection-color: $ds_text; gridline-color: $ds_line;
|
||||
}
|
||||
#PrescriptionsPage QTableWidget#PrescriptionTable::item { border: 0; padding: 0; }
|
||||
#PrescriptionsPage QHeaderView::section {
|
||||
min-height: 0; padding: 0 12px; background: $ds_surface_alt; color: $ds_muted;
|
||||
border: 0; border-bottom: 1px solid $ds_line;
|
||||
font-family: "$body"; font-size: 13px; font-weight: 400;
|
||||
}
|
||||
#PrescriptionsPage QWidget#PrescriptionTableCellHost { border: 0; background: transparent; }
|
||||
#PrescriptionsPage QPushButton[rowAction="true"] {
|
||||
min-width: 28px; max-width: 28px; min-height: 28px; max-height: 28px;
|
||||
padding: 0; border: 1px solid transparent; border-radius: $ds_radius_small; background: transparent;
|
||||
}
|
||||
#PrescriptionsPage QPushButton[rowAction="true"][labeled="true"] {
|
||||
min-width: 64px; max-width: 64px; color: $ds_accent; font-size: 13px; padding: 0;
|
||||
}
|
||||
#PrescriptionsPage QPushButton[rowAction="true"]:hover { background: $ds_accent_soft; border-color: $ds_line_strong; }
|
||||
#PrescriptionsPage QPushButton[rowAction="true"]:focus { border-color: $ds_focus; }
|
||||
#PrescriptionsPage QPushButton[rowAction="true"][danger="true"]:hover { background: $ds_danger_soft; border-color: $ds_danger_soft; }
|
||||
#PrescriptionsPage QPushButton[rowAction="true"][danger="true"]:focus { border-color: $ds_focus; }
|
||||
#PrescriptionsPage QPushButton[rowAction="true"]:disabled,
|
||||
#PrescriptionsPage QPushButton[rowAction="true"][labeled="true"]:disabled {
|
||||
background: transparent; border-color: transparent; color: $ds_disabled;
|
||||
}
|
||||
#PrescriptionsPage QWidget#InfiniteList { background: $ds_surface; border-top: 1px solid $ds_line; }
|
||||
#PrescriptionsPage QLabel#EmptyStateGlyph { font-size: 24px; color: $ds_accent; background: $ds_surface_alt; border: 1px solid $ds_line; border-radius: $ds_radius_panel; }
|
||||
#PrescriptionsPage QWidget#EmptyState QLabel[role="muted"] { min-width: 300px; }
|
||||
#PrescriptionsPage QScrollBar:vertical { background: $ds_canvas; width: 7px; margin: 0; }
|
||||
#PrescriptionsPage QScrollBar:horizontal { background: $ds_canvas; height: 7px; margin: 0; }
|
||||
#PrescriptionsPage QScrollBar::handle { background: $ds_line_strong; border-radius: 3px; min-width: 24px; min-height: 24px; }
|
||||
#PrescriptionsPage QScrollBar::add-line, #PrescriptionsPage QScrollBar::sub-line { width: 0; height: 0; }
|
||||
#PrescriptionsPage QScrollBar::add-page, #PrescriptionsPage QScrollBar::sub-page { background: transparent; }
|
||||
"""
|
||||
"""Scoped surfaces and real fonts for the approved issued-prescription page."""
|
||||
|
||||
from string import Template
|
||||
|
||||
from .reception_style import body_family, heading_family
|
||||
|
||||
|
||||
def prescriptions_stylesheet() -> str:
|
||||
return Template(_PRESCRIPTIONS).substitute(body=body_family(), heading=heading_family())
|
||||
|
||||
|
||||
_PRESCRIPTIONS = """
|
||||
#PrescriptionsPage { background: #F3F7FD; color: #273244; }
|
||||
#PrescriptionWorkspaceContent, #PrescriptionWorkspaceScroll { background: transparent; border: 0; }
|
||||
#PrescriptionsPage QLabel, #PrescriptionsPage QPushButton, #PrescriptionsPage QLineEdit,
|
||||
#PrescriptionsPage QComboBox, #PrescriptionsPage QDateTimeEdit, #PrescriptionsPage QTableWidget {
|
||||
font-family: "$body"; font-size: 14px; font-weight: 400; color: #273244;
|
||||
}
|
||||
#PrescriptionsPage QLabel[role="pageTitle"] {
|
||||
font-family: "$heading"; font-size: 20px; font-weight: 600; color: #202C3F;
|
||||
}
|
||||
#PrescriptionsPage QLabel[role="sectionTitle"] {
|
||||
font-family: "$heading"; font-size: 14px; font-weight: 600;
|
||||
}
|
||||
#PrescriptionsPage QLabel[role="muted"], #PrescriptionsPage QLabel#PrescriptionCountBadge {
|
||||
color: #5D6B80; font-size: 13px; background: transparent; border: 0; padding: 0;
|
||||
}
|
||||
#PrescriptionsPage QFrame#PrescriptionFilterBar, #PrescriptionsPage QFrame#PrescriptionTableCard {
|
||||
background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 8px;
|
||||
}
|
||||
#PrescriptionsPage QFrame#PrescriptionToolbar { background: transparent; border: 0; }
|
||||
#PrescriptionsPage QPushButton {
|
||||
min-height: 38px; max-height: 38px; padding: 0 16px; border-radius: 5px;
|
||||
border: 1px solid #DBE5F2; background: #FFFFFF; color: #273244;
|
||||
}
|
||||
#PrescriptionsPage QPushButton:hover { background: #F2F7FF; border-color: #B6CDEE; color: #1555B6; }
|
||||
#PrescriptionsPage QPushButton:pressed { background: #DCEAFF; }
|
||||
#PrescriptionsPage QPushButton:focus { border-color: #75A5F0; }
|
||||
#PrescriptionsPage QPushButton#PrescriptionAddButton, #PrescriptionsPage QPushButton#PrescriptionQueryButton {
|
||||
background: #1769E8; color: #FFFFFF; border-color: #1769E8;
|
||||
}
|
||||
#PrescriptionsPage QPushButton#PrescriptionAddButton:hover, #PrescriptionsPage QPushButton#PrescriptionQueryButton:hover {
|
||||
background: #155BCC; border-color: #155BCC;
|
||||
}
|
||||
#PrescriptionsPage QPushButton#PrescriptionAddButton:pressed, #PrescriptionsPage QPushButton#PrescriptionQueryButton:pressed {
|
||||
background: #124EA9; border-color: #124EA9;
|
||||
}
|
||||
#PrescriptionsPage QPushButton[variant="danger"] { color: #BE4657; background: #FFFFFF; border-color: #E9D8DE; }
|
||||
#PrescriptionsPage QPushButton:disabled, #PrescriptionsPage QPushButton[variant="danger"]:disabled {
|
||||
color: #97A4B6; background: #F6F8FC; border-color: #E2E9F2;
|
||||
}
|
||||
#PrescriptionsPage QLineEdit, #PrescriptionsPage QComboBox, #PrescriptionsPage QDateTimeEdit {
|
||||
min-height: 38px; max-height: 38px; padding: 0 12px; border: 1px solid #DBE5F2;
|
||||
border-radius: 5px; background: #FFFFFF; color: #273244;
|
||||
selection-background-color: #DCEAFF; selection-color: #273244;
|
||||
}
|
||||
#PrescriptionsPage QLineEdit:focus, #PrescriptionsPage QComboBox:focus, #PrescriptionsPage QDateTimeEdit:focus { border-color: #75A5F0; }
|
||||
#PrescriptionsPage QLineEdit QToolButton { min-width: 0; min-height: 0; border: 0; background: transparent; padding: 0; }
|
||||
#PrescriptionsPage QComboBox, #PrescriptionsPage QDateTimeEdit { padding-right: 30px; font-size: 13px; }
|
||||
#PrescriptionsPage QComboBox::drop-down, #PrescriptionsPage QDateTimeEdit::drop-down { width: 28px; border: 0; background: transparent; }
|
||||
#PrescriptionsPage QComboBox::down-arrow, #PrescriptionsPage QDateTimeEdit::down-arrow { image: none; width: 0; height: 0; }
|
||||
#PrescriptionsPage QDateTimeEdit:disabled { color: #8A97A9; background: #F6F8FC; border-color: #E2E9F2; }
|
||||
#PrescriptionsPage QPushButton#PrescriptionDoctorButton { text-align: left; padding-right: 30px; font-size: 13px; }
|
||||
#PrescriptionsPage QComboBox QAbstractItemView {
|
||||
font-family: "$body"; font-size: 13px; color: #273244; background: #FFFFFF;
|
||||
border: 1px solid #DBE5F2; outline: 0; selection-background-color: #EAF2FF; selection-color: #1555B6;
|
||||
}
|
||||
#PrescriptionsPage QComboBox QAbstractItemView::item { min-height: 30px; padding: 3px 10px; }
|
||||
#PrescriptionsPage QCalendarWidget { font-family: "$body"; font-size: 13px; background: #FFFFFF; color: #273244; }
|
||||
#PrescriptionsPage QCalendarWidget QWidget#qt_calendar_navigationbar { background: #F5F8FD; }
|
||||
#PrescriptionsPage QCalendarWidget QToolButton { min-height: 28px; border: 0; padding: 0 8px; color: #273244; background: transparent; }
|
||||
#PrescriptionsPage QCalendarWidget QAbstractItemView { color: #273244; background: #FFFFFF; selection-background-color: #1769E8; selection-color: #FFFFFF; outline: 0; }
|
||||
#PrescriptionsPage QFrame#PrescriptionToolbar QPushButton { padding: 0 12px; font-size: 13px; }
|
||||
#PrescriptionsPage QTableWidget#PrescriptionTable {
|
||||
border: 0; background: #FFFFFF; alternate-background-color: #FFFFFF;
|
||||
selection-background-color: #F2F7FF; selection-color: #273244; gridline-color: #E6EDF6;
|
||||
}
|
||||
#PrescriptionsPage QTableWidget#PrescriptionTable::item { border: 0; padding: 0; }
|
||||
#PrescriptionsPage QHeaderView::section {
|
||||
min-height: 0; padding: 0 12px; background: #F5F8FD; color: #5D6B80;
|
||||
border: 0; border-bottom: 1px solid #DBE5F2;
|
||||
font-family: "$body"; font-size: 13px; font-weight: 400;
|
||||
}
|
||||
#PrescriptionsPage QWidget#PrescriptionTableCellHost { border: 0; background: transparent; }
|
||||
#PrescriptionsPage QPushButton[rowAction="true"] {
|
||||
min-width: 28px; max-width: 28px; min-height: 28px; max-height: 28px;
|
||||
padding: 0; border: 1px solid transparent; border-radius: 4px; background: transparent;
|
||||
}
|
||||
#PrescriptionsPage QPushButton[rowAction="true"][labeled="true"] {
|
||||
min-width: 64px; max-width: 64px; color: #1769E8; font-size: 13px; padding: 0;
|
||||
}
|
||||
#PrescriptionsPage QPushButton[rowAction="true"]:hover { background: #EAF2FF; border-color: #B6CDEE; }
|
||||
#PrescriptionsPage QPushButton[rowAction="true"]:focus { border-color: #75A5F0; }
|
||||
#PrescriptionsPage QPushButton[rowAction="true"][danger="true"]:hover { background: #FFF0F2; border-color: #EAC8D0; }
|
||||
#PrescriptionsPage QPushButton[rowAction="true"]:disabled,
|
||||
#PrescriptionsPage QPushButton[rowAction="true"][labeled="true"]:disabled {
|
||||
background: transparent; border-color: transparent; color: #A4ADBA;
|
||||
}
|
||||
#PrescriptionsPage QWidget#InfiniteList { background: #FFFFFF; border-top: 1px solid #E6EDF6; }
|
||||
#PrescriptionsPage QLabel#EmptyStateGlyph { font-size: 24px; color: #1769E8; background: #F2F7FF; border: 1px solid #DBE5F2; border-radius: 22px; }
|
||||
#PrescriptionsPage QWidget#EmptyState QLabel[role="muted"] { min-width: 300px; }
|
||||
#PrescriptionsPage QScrollBar:vertical { background: #F4F7FC; width: 7px; margin: 0; }
|
||||
#PrescriptionsPage QScrollBar:horizontal { background: #F4F7FC; height: 7px; margin: 0; }
|
||||
#PrescriptionsPage QScrollBar::handle { background: #C8D5E6; border-radius: 3px; min-width: 24px; min-height: 24px; }
|
||||
#PrescriptionsPage QScrollBar::add-line, #PrescriptionsPage QScrollBar::sub-line { width: 0; height: 0; }
|
||||
#PrescriptionsPage QScrollBar::add-page, #PrescriptionsPage QScrollBar::sub-page { background: transparent; }
|
||||
"""
|
||||
|
||||
@@ -1,32 +1,36 @@
|
||||
"""Shared palette and typography for the technology-blue workstation pages."""
|
||||
"""Palette and real font families for the approved reception page only."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from PySide6.QtGui import QFontDatabase
|
||||
from PySide6.QtWidgets import QApplication
|
||||
|
||||
from .design_system import PALETTE
|
||||
from .theme import _register_preferred_cjk_fonts
|
||||
from doctor_workstation.resources import resource_path
|
||||
|
||||
TECH_BLUE = {
|
||||
"accent": PALETTE["accent"],
|
||||
"accent_hover": PALETTE["accent_hover"],
|
||||
"accent_pressed": PALETTE["accent_pressed"],
|
||||
"selection": PALETTE["accent_soft"],
|
||||
"selected_text": PALETTE["accent_hover"],
|
||||
"canvas": PALETTE["canvas"],
|
||||
"sidebar": PALETTE["sidebar"],
|
||||
"surface": PALETTE["surface"],
|
||||
"raised": PALETTE["surface_alt"],
|
||||
"line": PALETTE["line"],
|
||||
"text": PALETTE["text"],
|
||||
"heading": PALETTE["heading"],
|
||||
"muted": PALETTE["muted"],
|
||||
"focus": PALETTE["focus"],
|
||||
"accent": "#1769E8",
|
||||
"accent_hover": "#155BCC",
|
||||
"accent_pressed": "#124EA9",
|
||||
"selection": "#EAF2FF",
|
||||
"selected_text": "#1555B6",
|
||||
"canvas": "#F3F7FD",
|
||||
"sidebar": "#EDF4FF",
|
||||
"surface": "#FFFFFF",
|
||||
"raised": "#F7FAFE",
|
||||
"line": "#DBE5F2",
|
||||
"text": "#273244",
|
||||
"heading": "#202C3F",
|
||||
"muted": "#5D6B80",
|
||||
"focus": "#75A5F0",
|
||||
}
|
||||
|
||||
|
||||
def _families() -> dict[str, str]:
|
||||
"""Use the application face for Chinese, Latin text and numbers alike."""
|
||||
"""Resolve after Qt starts; font registration does not change its theme."""
|
||||
|
||||
app = QApplication.instance()
|
||||
if app is None:
|
||||
@@ -35,28 +39,68 @@ def _families() -> dict[str, str]:
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
# The bundled variable font supplies real Regular, Medium and Semibold
|
||||
# weights. Keep the same glyph shapes in controls and custom-painted cells;
|
||||
# hierarchy comes from size and weight within this one family.
|
||||
family = _register_preferred_cjk_fonts()
|
||||
resolved = dict.fromkeys(("body", "heading", "number"), family)
|
||||
heading = getattr(app, "_doctor_bundled_font_family", None)
|
||||
if not heading:
|
||||
font_path = resource_path("fonts", "NotoSansSC-VF.ttf")
|
||||
if font_path.is_file():
|
||||
font_id = QFontDatabase.addApplicationFont(str(font_path))
|
||||
registered = QFontDatabase.applicationFontFamilies(font_id) if font_id >= 0 else []
|
||||
if registered:
|
||||
heading = registered[0]
|
||||
app._doctor_bundled_font_family = heading
|
||||
|
||||
available = set(QFontDatabase.families())
|
||||
# Qt's offscreen platform does not enumerate Windows fonts automatically.
|
||||
# Register only files already installed on this machine, never substitutes
|
||||
# downloaded or installed into the user's Windows font registry.
|
||||
if sys.platform == "win32":
|
||||
font_dir = (
|
||||
Path(os.environ.get("SYSTEMROOT") or os.environ.get("WINDIR") or "C:/Windows") / "Fonts"
|
||||
)
|
||||
for family, filenames in (
|
||||
("Microsoft YaHei UI", ("msyh.ttc",)),
|
||||
("Segoe UI", ("segoeui.ttf", "seguisb.ttf")),
|
||||
):
|
||||
if family in available:
|
||||
continue
|
||||
for filename in filenames:
|
||||
font_path = font_dir / filename
|
||||
if not font_path.is_file():
|
||||
continue
|
||||
font_id = QFontDatabase.addApplicationFont(str(font_path))
|
||||
if font_id >= 0:
|
||||
available.update(QFontDatabase.applicationFontFamilies(font_id))
|
||||
|
||||
fallback = heading or next(
|
||||
(
|
||||
family
|
||||
for family in ("Noto Sans SC", "Noto Sans CJK SC", "PingFang SC")
|
||||
if family in available
|
||||
),
|
||||
app.font().family(),
|
||||
)
|
||||
resolved = {
|
||||
"body": "Microsoft YaHei UI" if "Microsoft YaHei UI" in available else fallback,
|
||||
"heading": heading or fallback,
|
||||
"number": "Segoe UI" if "Segoe UI" in available else fallback,
|
||||
}
|
||||
app._reception_font_families = resolved
|
||||
return resolved
|
||||
|
||||
|
||||
def body_family() -> str:
|
||||
"""Shared reading face for controls and table cells."""
|
||||
"""Regular Chinese body copy; YaHei UI has no genuine Medium face."""
|
||||
|
||||
return _families()["body"]
|
||||
|
||||
|
||||
def heading_family() -> str:
|
||||
"""The same reading face, with genuine Medium and Semibold weights."""
|
||||
"""Bundled Noto Sans SC supplies genuine Medium and Semibold faces."""
|
||||
|
||||
return _families()["heading"]
|
||||
|
||||
|
||||
def number_family() -> str:
|
||||
"""Keep numbers and adjacent Chinese text in the same family."""
|
||||
"""Segoe UI supplies Regular and Semibold for numeric labels."""
|
||||
|
||||
return _families()["number"]
|
||||
|
||||
@@ -1,441 +0,0 @@
|
||||
"""Responsive, presentation-only containers for the reception workspace."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from PySide6.QtCore import QSize, Qt
|
||||
from PySide6.QtGui import QResizeEvent
|
||||
from PySide6.QtWidgets import (
|
||||
QAbstractScrollArea,
|
||||
QFrame,
|
||||
QHBoxLayout,
|
||||
QLayout,
|
||||
QScrollArea,
|
||||
QSizePolicy,
|
||||
QStackedWidget,
|
||||
QTabBar,
|
||||
QVBoxLayout,
|
||||
QWidget,
|
||||
)
|
||||
|
||||
|
||||
class ReceptionWorkbench(QWidget):
|
||||
"""Keep clinical material and insights available at every supported width.
|
||||
|
||||
The two scroll areas are moved between layouts when the workspace changes
|
||||
mode. Their contents, signal connections and selected clinical pages remain
|
||||
the same objects throughout the lifetime of the workbench.
|
||||
"""
|
||||
|
||||
_WIDE_BREAKPOINT = 760
|
||||
_LARGE_RAIL_BREAKPOINT = 1100
|
||||
_UNRESTRICTED_WIDTH = 16_777_215
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
clinical_scroll: QScrollArea,
|
||||
insights: QWidget,
|
||||
parent: QWidget | None = None,
|
||||
) -> None:
|
||||
super().__init__(parent)
|
||||
self.setObjectName("ReceptionWorkbench")
|
||||
self.setMinimumSize(0, 0)
|
||||
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
|
||||
self.clinical_scroll = clinical_scroll
|
||||
self._wide_mode: bool | None = None
|
||||
self._relayout_in_progress = False
|
||||
|
||||
self.insights_scroll = QScrollArea(self)
|
||||
self.insights_scroll.setObjectName("ReceptionInsightsScroll")
|
||||
self.insights_scroll.setAccessibleName("患者资料与 AI 辅助滚动区域")
|
||||
self.insights_scroll.setWidgetResizable(True)
|
||||
self.insights_scroll.setFrameShape(QFrame.Shape.NoFrame)
|
||||
self.insights_scroll.setHorizontalScrollBarPolicy(
|
||||
Qt.ScrollBarPolicy.ScrollBarAlwaysOff
|
||||
)
|
||||
self.insights_scroll.setVerticalScrollBarPolicy(
|
||||
Qt.ScrollBarPolicy.ScrollBarAsNeeded
|
||||
)
|
||||
self.insights_scroll.setWidget(insights)
|
||||
|
||||
for scroll in (self.clinical_scroll, self.insights_scroll):
|
||||
scroll.setMinimumSize(0, 0)
|
||||
scroll.setSizePolicy(
|
||||
QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding
|
||||
)
|
||||
scroll.setSizeAdjustPolicy(QAbstractScrollArea.SizeAdjustPolicy.AdjustIgnored)
|
||||
|
||||
layout = QVBoxLayout(self)
|
||||
layout.setContentsMargins(0, 0, 0, 0)
|
||||
layout.setSpacing(8)
|
||||
# Scroll contents can be arbitrarily tall. They must never dictate the
|
||||
# outer page's minimum height when the parent layout recalculates.
|
||||
layout.setSizeConstraint(QLayout.SizeConstraint.SetNoConstraint)
|
||||
|
||||
self.mode_tabs = QTabBar(self)
|
||||
self.mode_tabs.setObjectName("ReceptionWorkspaceTabs")
|
||||
self.mode_tabs.setAccessibleName("接诊工作区视图")
|
||||
self.mode_tabs.setDrawBase(False)
|
||||
self.mode_tabs.setExpanding(False)
|
||||
self.mode_tabs.addTab("病历资料")
|
||||
self.mode_tabs.addTab("患者资料与 AI")
|
||||
self.mode_tabs.currentChanged.connect(self._select_narrow_tab)
|
||||
layout.addWidget(self.mode_tabs)
|
||||
|
||||
self._wide_container = QWidget(self)
|
||||
self._wide_container.setObjectName("ReceptionWideWorkspace")
|
||||
self._wide_container.setMinimumSize(0, 0)
|
||||
self._wide_container.setSizePolicy(
|
||||
QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding
|
||||
)
|
||||
self._wide_layout = QHBoxLayout(self._wide_container)
|
||||
self._wide_layout.setContentsMargins(0, 0, 0, 0)
|
||||
self._wide_layout.setSpacing(12)
|
||||
self._wide_layout.setSizeConstraint(QLayout.SizeConstraint.SetNoConstraint)
|
||||
layout.addWidget(self._wide_container, 1)
|
||||
|
||||
self._narrow_stack = QStackedWidget(self)
|
||||
self._narrow_stack.setObjectName("ReceptionNarrowWorkspace")
|
||||
self._narrow_stack.setMinimumSize(0, 0)
|
||||
self._narrow_stack.setSizePolicy(
|
||||
QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding
|
||||
)
|
||||
self._narrow_stack.layout().setSizeConstraint(
|
||||
QLayout.SizeConstraint.SetNoConstraint
|
||||
)
|
||||
layout.addWidget(self._narrow_stack, 1)
|
||||
self._update_mode()
|
||||
|
||||
def minimumSizeHint(self) -> QSize: # noqa: N802 - Qt override
|
||||
return QSize(390, 220)
|
||||
|
||||
def sizeHint(self) -> QSize: # noqa: N802 - Qt override
|
||||
return QSize(980, 600)
|
||||
|
||||
def resizeEvent(self, event: QResizeEvent) -> None: # noqa: N802 - Qt override
|
||||
super().resizeEvent(event)
|
||||
self._update_mode()
|
||||
|
||||
def _select_narrow_tab(self, index: int) -> None:
|
||||
if self._wide_mode is False and 0 <= index < self._narrow_stack.count():
|
||||
self._narrow_stack.setCurrentIndex(index)
|
||||
|
||||
def _update_mode(self) -> None:
|
||||
if self._relayout_in_progress:
|
||||
return
|
||||
wide = self.width() >= self._WIDE_BREAKPOINT
|
||||
rail_width = 360 if self.width() >= self._LARGE_RAIL_BREAKPOINT else 320
|
||||
if self._wide_mode is wide:
|
||||
if wide and self.insights_scroll.width() != rail_width:
|
||||
self.insights_scroll.setFixedWidth(rail_width)
|
||||
return
|
||||
|
||||
self._relayout_in_progress = True
|
||||
try:
|
||||
self._wide_mode = wide
|
||||
self._wide_container.hide()
|
||||
self._narrow_stack.hide()
|
||||
self.mode_tabs.setVisible(not wide)
|
||||
if wide:
|
||||
for scroll in (self.clinical_scroll, self.insights_scroll):
|
||||
self._narrow_stack.removeWidget(scroll)
|
||||
self.clinical_scroll.setMinimumWidth(0)
|
||||
self.insights_scroll.setFixedWidth(rail_width)
|
||||
self._wide_layout.addWidget(self.clinical_scroll, 1)
|
||||
self._wide_layout.addWidget(self.insights_scroll, 0)
|
||||
self.clinical_scroll.show()
|
||||
self.insights_scroll.show()
|
||||
self._wide_container.show()
|
||||
else:
|
||||
for scroll in (self.clinical_scroll, self.insights_scroll):
|
||||
self._wide_layout.removeWidget(scroll)
|
||||
self.insights_scroll.setMinimumWidth(0)
|
||||
self.insights_scroll.setMaximumWidth(self._UNRESTRICTED_WIDTH)
|
||||
self._narrow_stack.addWidget(self.clinical_scroll)
|
||||
self._narrow_stack.addWidget(self.insights_scroll)
|
||||
self._narrow_stack.setCurrentIndex(self.mode_tabs.currentIndex())
|
||||
self._narrow_stack.show()
|
||||
self.updateGeometry()
|
||||
finally:
|
||||
self._relayout_in_progress = False
|
||||
|
||||
|
||||
# Append this after RECEPTION_QSS so the page keeps all existing interaction,
|
||||
# loading and semantic alert states while adopting the workspace's hierarchy.
|
||||
RECEPTION_WORKSPACE_QSS = r"""
|
||||
QWidget#ReceptionPage QWidget#ReceptionWorkbench,
|
||||
QWidget#ReceptionPage QWidget#ReceptionWideWorkspace,
|
||||
QWidget#ReceptionPage QStackedWidget#ReceptionNarrowWorkspace {
|
||||
background: transparent;
|
||||
border: 0;
|
||||
}
|
||||
QWidget#ReceptionPage QFrame#ReceptionQueuePanel {
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDF0F5;
|
||||
border-radius: 16px;
|
||||
}
|
||||
QWidget#ReceptionPage QLabel#ReceptionQueueTitle {
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
}
|
||||
QWidget#ReceptionPage QLabel#ReceptionQueueName {
|
||||
font-size: 15px;
|
||||
font-weight: 500;
|
||||
}
|
||||
QWidget#ReceptionPage QLabel#ReceptionQueueMeta,
|
||||
QWidget#ReceptionPage QLabel#ReceptionQueueTime,
|
||||
QWidget#ReceptionPage QLabel#ReceptionQueueSubline,
|
||||
QWidget#ReceptionPage QLabel#ReceptionQueueSummary {
|
||||
color: #5D6B80;
|
||||
font-size: 12px;
|
||||
font-weight: 400;
|
||||
}
|
||||
QWidget#ReceptionPage QLabel#ReceptionQueueMetric {
|
||||
font-size: 13px;
|
||||
}
|
||||
QWidget#ReceptionPage QLabel#ReceptionQueueMetric[tone="description"] {
|
||||
color: #5D6B80;
|
||||
font-size: 12px;
|
||||
}
|
||||
QWidget#ReceptionPage QFrame#ReceptionHero,
|
||||
QWidget#ReceptionPage QFrame#ReceptionClinicalCard {
|
||||
min-height: 0;
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDF0F5;
|
||||
border-radius: 16px;
|
||||
}
|
||||
QWidget#ReceptionPage QLabel#ReceptionPatientName {
|
||||
font-size: 20px;
|
||||
font-weight: 600;
|
||||
}
|
||||
QWidget#ReceptionPage QLabel#ReceptionPatientMeta {
|
||||
color: #5D6B80;
|
||||
font-size: 13px;
|
||||
}
|
||||
QWidget#ReceptionPage QLabel#ReceptionAvatar {
|
||||
color: #1555B6;
|
||||
background-color: #EAF2FF;
|
||||
border-radius: 12px;
|
||||
font-size: 20px;
|
||||
font-weight: 600;
|
||||
}
|
||||
QWidget#ReceptionPage QTabBar#ReceptionDetailTabs,
|
||||
QWidget#ReceptionPage QTabBar#ReceptionWorkspaceTabs {
|
||||
background-color: #FFFFFF;
|
||||
border: 0;
|
||||
border-bottom: 1px solid #E5ECF6;
|
||||
border-top-left-radius: 16px;
|
||||
border-top-right-radius: 16px;
|
||||
}
|
||||
QWidget#ReceptionPage QTabBar#ReceptionDetailTabs::tab,
|
||||
QWidget#ReceptionPage QTabBar#ReceptionWorkspaceTabs::tab {
|
||||
min-height: 40px;
|
||||
margin: 0;
|
||||
padding: 0 14px;
|
||||
color: #5D6B80;
|
||||
background-color: transparent;
|
||||
border: 0;
|
||||
border-bottom: 2px solid transparent;
|
||||
border-radius: 0;
|
||||
font-size: 13px;
|
||||
font-weight: 400;
|
||||
}
|
||||
QWidget#ReceptionPage QTabBar#ReceptionDetailTabs::tab:first {
|
||||
margin-left: 0;
|
||||
padding-left: 14px;
|
||||
}
|
||||
QWidget#ReceptionPage QTabBar#ReceptionDetailTabs::tab:hover,
|
||||
QWidget#ReceptionPage QTabBar#ReceptionWorkspaceTabs::tab:hover {
|
||||
color: #1769E8;
|
||||
background-color: #F3F7FD;
|
||||
}
|
||||
QWidget#ReceptionPage QTabBar#ReceptionDetailTabs::tab:selected,
|
||||
QWidget#ReceptionPage QTabBar#ReceptionWorkspaceTabs::tab:selected {
|
||||
color: #1769E8;
|
||||
background-color: transparent;
|
||||
border-bottom: 2px solid #1769E8;
|
||||
font-weight: 500;
|
||||
}
|
||||
QWidget#ReceptionPage QFrame#ReceptionHistoryCard {
|
||||
background-color: #FFFFFF;
|
||||
border: 0;
|
||||
border-radius: 0;
|
||||
}
|
||||
QWidget#ReceptionPage QWidget#ReceptionCaseField {
|
||||
background-color: transparent;
|
||||
border: 0;
|
||||
border-bottom: 1px solid #EDF1F7;
|
||||
border-radius: 0;
|
||||
}
|
||||
QWidget#ReceptionPage QLabel#ReceptionCaseHeading {
|
||||
color: #202C3F;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
}
|
||||
QWidget#ReceptionPage QLabel[receptionBlockTitle="true"] {
|
||||
color: #5D6B80;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
}
|
||||
QWidget#ReceptionPage QLabel[receptionBlockValue="true"] {
|
||||
font-size: 14px;
|
||||
font-weight: 400;
|
||||
}
|
||||
QWidget#ReceptionPage QLabel[receptionInlineCaption="true"] {
|
||||
min-width: 0;
|
||||
color: #5D6B80;
|
||||
font-size: 12px;
|
||||
font-weight: 400;
|
||||
}
|
||||
QWidget#ReceptionPage QLabel[receptionInlineValue="true"],
|
||||
QWidget#ReceptionPage QLabel[receptionLifestyleChip="true"] {
|
||||
font-size: 13px;
|
||||
font-weight: 400;
|
||||
}
|
||||
QWidget#ReceptionPage QFrame#ReceptionPatientSummaryCard,
|
||||
QWidget#ReceptionPage QFrame#ReceptionVitalsCard,
|
||||
QWidget#ReceptionPage QFrame#ReceptionLabsCard {
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDF0F5;
|
||||
border-radius: 16px;
|
||||
}
|
||||
QWidget#ReceptionPage QLabel#ReceptionPatientSummaryValue {
|
||||
color: #24334A;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
}
|
||||
QWidget#ReceptionPage QLabel#ReceptionPatientSummaryValue[missing="true"] {
|
||||
color: #697386;
|
||||
font-weight: 400;
|
||||
}
|
||||
QWidget#ReceptionPage QFrame#ReceptionMetricCell,
|
||||
QWidget#ReceptionPage QFrame#ReceptionMetricCell[firstMetric="true"] {
|
||||
background-color: transparent;
|
||||
border: 0;
|
||||
border-radius: 0;
|
||||
}
|
||||
QWidget#ReceptionPage QLabel[receptionMetricCaption="true"],
|
||||
QWidget#ReceptionPage QLabel[receptionMetricUnit="true"],
|
||||
QWidget#ReceptionPage QLabel[receptionBmiState="true"] {
|
||||
color: #5D6B80;
|
||||
font-size: 12px;
|
||||
font-weight: 400;
|
||||
}
|
||||
QWidget#ReceptionPage QFrame#ReceptionMetricCell QLabel[receptionMetricValue="true"] {
|
||||
font-size: 18px;
|
||||
font-weight: 500;
|
||||
}
|
||||
QWidget#ReceptionPage QFrame#ReceptionLabCell {
|
||||
min-height: 0;
|
||||
padding: 0;
|
||||
background-color: #FFFFFF;
|
||||
border: 0;
|
||||
border-bottom: 1px solid #EDF1F7;
|
||||
border-radius: 0;
|
||||
}
|
||||
QWidget#ReceptionPage QFrame#ReceptionLabCell QLabel[receptionMetricValue="true"] {
|
||||
font-size: 13px;
|
||||
font-weight: 400;
|
||||
}
|
||||
QWidget#ReceptionPage QPushButton#ReceptionMissingLabsButton {
|
||||
min-height: 28px;
|
||||
max-height: 28px;
|
||||
padding: 0;
|
||||
color: #1769E8;
|
||||
background: transparent;
|
||||
border: 0;
|
||||
text-align: left;
|
||||
font-size: 12px;
|
||||
}
|
||||
QWidget#ReceptionPage QLabel[receptionMetricState="true"] {
|
||||
min-height: 18px;
|
||||
padding: 0 5px;
|
||||
background-color: #F0F5FD;
|
||||
border: 0;
|
||||
border-radius: 4px;
|
||||
font-size: 12px;
|
||||
font-weight: 400;
|
||||
}
|
||||
QWidget#ReceptionPage QLabel[receptionMetricState="true"][alert="true"] {
|
||||
color: #BE4B58;
|
||||
background-color: #FFF4F5;
|
||||
}
|
||||
QWidget#ReceptionPage QLabel[receptionMetricState="true"][alert="true"][warning="true"] {
|
||||
color: #A9691D;
|
||||
background-color: #FFF9EF;
|
||||
border-radius: 4px;
|
||||
}
|
||||
QWidget#ReceptionPage QFrame#ReceptionAiAnalysisCard,
|
||||
QWidget#ReceptionPage QFrame#ReceptionAiAssistantCard {
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid $ds_line;
|
||||
border-radius: $ds_radius_panel;
|
||||
}
|
||||
QWidget#ReceptionPage QLabel#ReceptionAiTitle,
|
||||
QWidget#ReceptionPage QPushButton#ReceptionAiTitle {
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
}
|
||||
QWidget#ReceptionPage QLabel#ReceptionAiAssistantHint {
|
||||
color: #5D6B80;
|
||||
font-size: 13px;
|
||||
font-weight: 400;
|
||||
}
|
||||
QWidget#ReceptionPage QPushButton[receptionAiPrompt="true"] {
|
||||
min-height: 28px;
|
||||
max-height: 28px;
|
||||
padding: 0 8px;
|
||||
font-size: 12px;
|
||||
border-radius: 6px;
|
||||
}
|
||||
QWidget#ReceptionPage QScrollArea#ReceptionInsightsScroll {
|
||||
background-color: transparent;
|
||||
border: 0;
|
||||
}
|
||||
QWidget#ReceptionPage QScrollArea#ReceptionInsightsScroll QScrollBar:vertical {
|
||||
width: 8px;
|
||||
margin: 4px 2px;
|
||||
background: transparent;
|
||||
}
|
||||
QWidget#ReceptionPage QScrollArea#ReceptionInsightsScroll QScrollBar::handle:vertical {
|
||||
min-height: 32px;
|
||||
background-color: #C4D2E5;
|
||||
border-radius: 4px;
|
||||
}
|
||||
QWidget#ReceptionPage QScrollArea#ReceptionInsightsScroll QScrollBar::add-line:vertical,
|
||||
QWidget#ReceptionPage QScrollArea#ReceptionInsightsScroll QScrollBar::sub-line:vertical {
|
||||
height: 0;
|
||||
}
|
||||
QWidget#ReceptionPage QLineEdit#ReceptionQueueSearch,
|
||||
QWidget#ReceptionPage QPushButton#ReceptionDateButton,
|
||||
QWidget#ReceptionPage QPushButton#ReceptionQueueFilterToggle,
|
||||
QWidget#ReceptionPage QPushButton#ReceptionVideoButton,
|
||||
QWidget#ReceptionPage QPushButton#ReceptionNotifyButton,
|
||||
QWidget#ReceptionPage QPushButton#ReceptionHistoryButton,
|
||||
QWidget#ReceptionPage QPushButton#ReceptionImButton,
|
||||
QWidget#ReceptionPage QPushButton#ReceptionMoreButton,
|
||||
QWidget#ReceptionPage QPushButton#ReceptionCompleteButton,
|
||||
QWidget#ReceptionPage QPushButton[receptionAiPrompt="true"] {
|
||||
border-radius: $ds_radius_control;
|
||||
}
|
||||
QWidget#ReceptionPage QPushButton:focus,
|
||||
QWidget#ReceptionPage QLineEdit:focus,
|
||||
QWidget#ReceptionPage QComboBox:focus,
|
||||
QWidget#ReceptionPage QTextEdit:focus {
|
||||
border-color: $ds_focus;
|
||||
}
|
||||
QWidget#ReceptionPage QPushButton#ReceptionVideoButton:pressed {
|
||||
color: $ds_surface;
|
||||
background-color: $ds_accent_pressed;
|
||||
border-color: $ds_accent_pressed;
|
||||
}
|
||||
QWidget#ReceptionPage QLabel[receptionMetricState="true"] {
|
||||
border-radius: $ds_radius_small;
|
||||
}
|
||||
QWidget#ReceptionPage QFrame#ReceptionLabCell,
|
||||
QWidget#ReceptionPage QWidget#ReceptionCaseField {
|
||||
border-bottom-color: $ds_line;
|
||||
}
|
||||
QWidget#ReceptionPage QLabel#ReceptionPatientSummaryValue[missing="true"] {
|
||||
color: $ds_muted;
|
||||
}
|
||||
"""
|
||||
@@ -59,7 +59,6 @@ from .chat_notifications import (
|
||||
ChatNotification,
|
||||
ChatNotificationCenter,
|
||||
)
|
||||
from .design_system import PALETTE, clinical_stylesheet
|
||||
from .dialogs.ai_consult import can_open_ai_consult
|
||||
from .dialogs.ai_consult_picker import select_and_present_ai_consult
|
||||
from .dialogs.diagnosis import DiagnosisDialog
|
||||
@@ -73,7 +72,7 @@ from .pages import (
|
||||
ReceptionPage,
|
||||
)
|
||||
from .reception_style import TECH_BLUE, body_family, heading_family, number_family
|
||||
from .theme import COLORS, METRICS, TYPE, crisp_pixmap
|
||||
from .theme import COLORS, crisp_pixmap
|
||||
from .widgets import (
|
||||
EmptyState,
|
||||
StatusBadge,
|
||||
@@ -94,8 +93,8 @@ _SHELL_DESIGN_SIZE = QSize(1710, 920)
|
||||
_SHELL_MINIMUM_SIZE = QSize(1024, 640)
|
||||
_RECEPTION_SIDEBAR_WIDTH = 208
|
||||
_RECEPTION_TOPBAR_HEIGHT = 76
|
||||
_RECEPTION_SIDEBAR_COLOR = PALETTE["sidebar"]
|
||||
_RECEPTION_CHROME_LINE = PALETTE["line"]
|
||||
_RECEPTION_SIDEBAR_COLOR = "#F3F7FD"
|
||||
_RECEPTION_CHROME_LINE = "#E7EDF7"
|
||||
# Approved pages share one chrome state, so navigation among them keeps it intact.
|
||||
_TECH_BLUE_PAGES = frozenset({"appointments", "consultations", "patients", "prescriptions", "prescription_library", "reception"})
|
||||
|
||||
@@ -507,14 +506,13 @@ class _AssistantRobot(QWidget):
|
||||
painter.setPen(Qt.PenStyle.NoPen)
|
||||
if self.property("receptionTechBlue"):
|
||||
painter.setBrush(QColor(TECH_BLUE["accent"]))
|
||||
tile = QRectF(6, 6, 36, 36)
|
||||
painter.drawRoundedRect(tile, 6, 6)
|
||||
painter.drawRoundedRect(QRectF(7, 7, 44, 44), 6, 6)
|
||||
painter.setPen(QColor(TECH_BLUE["surface"]))
|
||||
font = QFont(number_family())
|
||||
font.setPixelSize(18)
|
||||
font.setPixelSize(21)
|
||||
font.setWeight(QFont.Weight.DemiBold)
|
||||
painter.setFont(font)
|
||||
painter.drawText(tile, Qt.AlignmentFlag.AlignCenter, "AI")
|
||||
painter.drawText(QRectF(7, 7, 44, 44), Qt.AlignmentFlag.AlignCenter, "AI")
|
||||
return
|
||||
painter.setBrush(QColor(COLORS["indigo_pale"]))
|
||||
painter.drawEllipse(QRectF(1, 1, 54, 54))
|
||||
@@ -564,12 +562,14 @@ class _AssistantStatus(QLabel):
|
||||
color = QColor(online_color if self._online else "#EC5266")
|
||||
painter.setPen(Qt.PenStyle.NoPen)
|
||||
painter.setBrush(color)
|
||||
diameter = 6
|
||||
diameter = 9 if reception else 6
|
||||
painter.drawEllipse(QRectF(1, (self.height() - diameter) / 2, diameter, diameter))
|
||||
painter.setPen(color)
|
||||
painter.setFont(self.font())
|
||||
font = QFont(self.font())
|
||||
font.setPixelSize(13 if reception else 10)
|
||||
painter.setFont(font)
|
||||
painter.drawText(
|
||||
QRectF(12, 0, self.width() - 12, self.height()),
|
||||
QRectF(17 if reception else 12, 0, self.width() - (17 if reception else 12), self.height()),
|
||||
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
|
||||
self.text(),
|
||||
)
|
||||
@@ -1006,7 +1006,7 @@ class ShellWindow(QMainWindow):
|
||||
chrome_widgets.extend(self.topbar.findChildren(_PaintedIconButton))
|
||||
chrome_widgets.append(self.tabs_menu_button)
|
||||
self._legacy_chrome_styles = {
|
||||
widget: clinical_stylesheet(widget.styleSheet()) for widget in chrome_widgets
|
||||
widget: widget.styleSheet() for widget in chrome_widgets
|
||||
}
|
||||
self._register_pages()
|
||||
self.search_shortcut = QShortcut(QKeySequence("Ctrl+K"), self)
|
||||
@@ -1085,7 +1085,7 @@ class ShellWindow(QMainWindow):
|
||||
font-weight: 600;
|
||||
}
|
||||
QLabel#ShellAssistantName { color: #1A1C1F; font-size: 13px; font-weight: 500; }
|
||||
QLabel#ShellAssistantStatus { color: #287B65; font-size: 12px; }
|
||||
QLabel#ShellAssistantStatus { color: #287B65; font-size: 13px; }
|
||||
QPushButton#ShellAssistantButton {
|
||||
min-height: 34px;
|
||||
color: #FFFFFF;
|
||||
@@ -1269,7 +1269,7 @@ class ShellWindow(QMainWindow):
|
||||
color: #606163;
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: 10px;
|
||||
border-radius: 999px;
|
||||
padding: 4px 10px;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
@@ -1592,16 +1592,15 @@ class ShellWindow(QMainWindow):
|
||||
self.brand_layout.setSpacing(13 if active else 10)
|
||||
self.brand_mark.setFixedSize(38 if active else 36, 38 if active else 36)
|
||||
self.nav_layout.setContentsMargins(*self._navigation_margins())
|
||||
self.nav_layout.setSpacing(4 if active else 0)
|
||||
self.assistant_card.setFixedHeight(132 if active else 157)
|
||||
self.assistant_layout.setContentsMargins(*(13, 12, 13, 12) if active else (12, 12, 12, 20))
|
||||
self.nav_layout.setSpacing(6 if active else 0)
|
||||
self.assistant_card.setFixedHeight(171 if active else 157)
|
||||
self.assistant_layout.setContentsMargins(*(13, 19, 13, 20) if active else (12, 12, 12, 20))
|
||||
self.assistant_head_layout.setContentsMargins(4 if active else 0, 0, 0, 0)
|
||||
self.assistant_head_layout.setSpacing(8 if active else 9)
|
||||
self.assistant_glyph.setFixedSize(48 if active else 56, 48 if active else 56)
|
||||
self.assistant_outer_layout.setContentsMargins(*(20, 0, 20, 0) if active else (13, 0, 13, 0))
|
||||
self.assistant_status.setFixedHeight(18)
|
||||
self.assistant_button.setFixedHeight(36 if active else 34)
|
||||
self.upload_settings_button.setFixedHeight(52 if active else 44)
|
||||
self.assistant_status.setFixedHeight(22 if active else 18)
|
||||
self.assistant_button.setFixedHeight(46 if active else 34)
|
||||
self.upload_settings_button.setFixedHeight(94 if active else 44)
|
||||
self.upload_settings_button.setIcon(_painted_shell_icon("settings", 20, reception=True) if active else QIcon())
|
||||
self.upload_settings_button.setIconSize(QSize(20, 20) if active else QSize(16, 16))
|
||||
self.upload_settings_button.setText("设置 ›" if active else "设置 ›")
|
||||
@@ -1687,15 +1686,15 @@ class ShellWindow(QMainWindow):
|
||||
}}
|
||||
QLabel#ShellBrandName {{
|
||||
font-family: "{heading_family()}"; font-weight: 600;
|
||||
color: {TECH_BLUE['heading']}; font-size: {TYPE['fs_section']};
|
||||
color: {TECH_BLUE['heading']}; font-size: 18px;
|
||||
}}
|
||||
QLabel#ShellBrandSubtitle {{ color: {TECH_BLUE['muted']}; font-size: {TYPE['fs_small']}; }}
|
||||
QLabel#ShellBrandSubtitle {{ color: {TECH_BLUE['text']}; font-size: 13px; }}
|
||||
QPushButton#ShellNavButton {{
|
||||
font-family: "{body_family()}"; font-weight: 400;
|
||||
min-height: 44px; max-height: 44px;
|
||||
min-height: 52px; max-height: 52px;
|
||||
border: 0; border-left: 5px solid transparent;
|
||||
border-radius: {METRICS["r_md"]};
|
||||
padding: 0 16px; font-size: {TYPE['fs_body']};
|
||||
border-radius: 6px;
|
||||
padding: 0 16px; font-size: 15px;
|
||||
color: {TECH_BLUE['text']};
|
||||
}}
|
||||
QPushButton#ShellNavButton:checked,
|
||||
@@ -1712,23 +1711,17 @@ class ShellWindow(QMainWindow):
|
||||
}}
|
||||
QPushButton#ShellNavButton[collapsed="true"] {{ padding: 0; }}
|
||||
QFrame#ShellAssistantCard {{
|
||||
background-color: {TECH_BLUE['surface']}; border-radius: {METRICS["r_lg"]};
|
||||
background-color: {TECH_BLUE['surface']}; border-radius: 8px;
|
||||
border: 1px solid {_RECEPTION_CHROME_LINE};
|
||||
}}
|
||||
QLabel#ShellAssistantName {{
|
||||
font-family: "{heading_family()}"; font-weight: 500; font-size: {TYPE['fs_body']};
|
||||
}}
|
||||
QLabel#ShellAssistantStatus {{
|
||||
font-size: {TYPE['fs_small']};
|
||||
font-family: "{heading_family()}"; font-weight: 500; font-size: 16px;
|
||||
}}
|
||||
QPushButton#ShellAssistantButton, QPushButton#ShellSettingsButton {{
|
||||
font-family: "{body_family()}"; font-weight: 400; font-size: {TYPE['fs_body']};
|
||||
}}
|
||||
QPushButton#ShellAssistantButton {{ border-radius: {METRICS["r_md"]}; }}
|
||||
QPushButton#ShellSettingsButton {{
|
||||
min-height: 50px; max-height: 50px;
|
||||
text-align: left; padding: 0 32px;
|
||||
font-family: "{body_family()}"; font-weight: 400; font-size: 15px;
|
||||
}}
|
||||
QPushButton#ShellAssistantButton {{ border-radius: 6px; }}
|
||||
QPushButton#ShellSettingsButton {{ text-align: left; padding: 0 32px; }}
|
||||
QPushButton#ShellAssistantButton:focus {{
|
||||
border: 2px solid {TECH_BLUE['focus']};
|
||||
}}
|
||||
@@ -1739,15 +1732,15 @@ class ShellWindow(QMainWindow):
|
||||
border-radius: 0;
|
||||
border-bottom: 1px solid {_RECEPTION_CHROME_LINE};
|
||||
}}
|
||||
QFrame#ShellGlobalSearch {{ background-color: {PALETTE["surface_alt"]}; border: 1px solid transparent; border-radius: {METRICS["r_md"]}; }}
|
||||
QFrame#ShellGlobalSearch {{ border: 1px solid {_RECEPTION_CHROME_LINE}; border-radius: 5px; }}
|
||||
QFrame#ShellUserSeparator {{ background: {_RECEPTION_CHROME_LINE}; border: 0; }}
|
||||
QLabel#ShellShortcutHint {{
|
||||
font-family: "{number_family()}"; font-size: {TYPE['fs_small']};
|
||||
font-family: "{number_family()}"; font-size: 13px;
|
||||
padding: 4px 9px; border-radius: 4px;
|
||||
border: 1px solid {_RECEPTION_CHROME_LINE};
|
||||
}}
|
||||
QLineEdit#ShellGlobalSearchInput {{
|
||||
color: {TECH_BLUE['text']}; font-size: {TYPE['fs_body']};
|
||||
color: {TECH_BLUE['text']}; font-size: 15px;
|
||||
min-height: 40px; max-height: 40px;
|
||||
}}
|
||||
QPushButton#ShellAiEntry:pressed {{ background: {TECH_BLUE['selection']}; }}
|
||||
@@ -1768,7 +1761,7 @@ class ShellWindow(QMainWindow):
|
||||
if isinstance(widget, _PaintedIconButton):
|
||||
side = 50 if widget in (self.refresh_button, self.notification_button, self.settings_button) else 34
|
||||
stylesheet += f"QToolButton#ShellPaintedIconButton {{ min-width: {side - 2}px; max-width: {side - 2}px; min-height: {side - 2}px; max-height: {side - 2}px; }}"
|
||||
widget.setStyleSheet(clinical_stylesheet(stylesheet))
|
||||
widget.setStyleSheet(stylesheet)
|
||||
|
||||
self._set_reception_geometry(active)
|
||||
for widget in (
|
||||
|
||||
@@ -41,55 +41,54 @@ from doctor_workstation.resources import resource_path
|
||||
# ``motion`` deliberately imports nothing from this module, so this stays a
|
||||
# one-way dependency: tokens here, animation there.
|
||||
from . import motion
|
||||
from .design_system import PALETTE, RADII, SPACING, clinical_stylesheet
|
||||
|
||||
# Shared reading colors keep native pages and dialog chrome consistent.
|
||||
# Neutral reading colors follow the installed Codex light chrome defaults.
|
||||
# Brand accents are independent of reading ink; use opaque text for stable contrast.
|
||||
# The legacy teal/ink aliases remain for existing callers.
|
||||
COLORS = {
|
||||
"canvas": PALETTE["canvas"],
|
||||
"canvas_mid": PALETTE["surface"],
|
||||
"canvas_glow": PALETTE["accent_soft"],
|
||||
"surface": PALETTE["surface"],
|
||||
"surface_alt": PALETTE["surface_alt"],
|
||||
"raised": PALETTE["surface_alt"],
|
||||
"glass": PALETTE["surface"],
|
||||
"glass_alt": PALETTE["surface_alt"],
|
||||
"line": PALETTE["line"],
|
||||
"line_soft": PALETTE["line_strong"],
|
||||
"text": PALETTE["heading"],
|
||||
"text_soft": PALETTE["text"],
|
||||
"muted": PALETTE["muted"],
|
||||
"disabled_surface": PALETTE["disabled_surface"],
|
||||
"disabled_text": PALETTE["disabled"],
|
||||
"indigo": PALETTE["accent"],
|
||||
"indigo_hover": PALETTE["accent_hover"],
|
||||
"indigo_pressed": PALETTE["accent_pressed"],
|
||||
"indigo_pale": PALETTE["accent_soft"],
|
||||
"focus": PALETTE["focus"],
|
||||
"selection": PALETTE["accent_soft"],
|
||||
"success": PALETTE["success"],
|
||||
"success_pale": PALETTE["success_soft"],
|
||||
"warning": PALETTE["warning"],
|
||||
"warning_pale": PALETTE["warning_soft"],
|
||||
"danger": PALETTE["danger"],
|
||||
"danger_pale": PALETTE["danger_soft"],
|
||||
"info": PALETTE["accent"],
|
||||
"info_pale": PALETTE["accent_soft"],
|
||||
"ink": PALETTE["heading"],
|
||||
"ink_soft": PALETTE["text"],
|
||||
"teal": PALETTE["accent"],
|
||||
"teal_dark": PALETTE["accent_pressed"],
|
||||
"teal_pale": PALETTE["accent_soft"],
|
||||
"canvas": "#F4F6FA",
|
||||
"canvas_mid": "#FFFFFF",
|
||||
"canvas_glow": "#EEF1FA",
|
||||
"surface": "#FFFFFF",
|
||||
"surface_alt": "#F7F7F7",
|
||||
"raised": "#F7F7F7",
|
||||
"glass": "#FFFFFF",
|
||||
"glass_alt": "#F7F7F7",
|
||||
"line": "#EDEDEE",
|
||||
"line_soft": "#E4E4E5",
|
||||
"text": "#1A1C1F",
|
||||
"text_soft": "#606163",
|
||||
"muted": "#6A6B6D",
|
||||
"disabled_surface": "#F2F2F2",
|
||||
"disabled_text": "#8E8F90",
|
||||
"indigo": "#4F63D9",
|
||||
"indigo_hover": "#4156C4",
|
||||
"indigo_pressed": "#354BB4",
|
||||
"indigo_pale": "#EEF1FA",
|
||||
"focus": "#8B9AD9",
|
||||
"selection": "#EEF1FA",
|
||||
"success": "#287B65",
|
||||
"success_pale": "#EEF7F3",
|
||||
"warning": "#A9691D",
|
||||
"warning_pale": "#FCF5E9",
|
||||
"danger": "#BE4B58",
|
||||
"danger_pale": "#FCF0F2",
|
||||
"info": "#4F63D9",
|
||||
"info_pale": "#EEF1FA",
|
||||
# Backward-compatible names used by older UI code and integrations.
|
||||
"ink": "#1A1C1F",
|
||||
"ink_soft": "#606163",
|
||||
"teal": "#4F63D9",
|
||||
"teal_dark": "#354BB4",
|
||||
"teal_pale": "#EEF1FA",
|
||||
}
|
||||
|
||||
|
||||
# --- Type scale -----------------------------------------------------------
|
||||
# Seven steps, tuned for 简体中文 at Windows 100%–150% scaling. CJK glyphs carry
|
||||
# Six steps, tuned for 简体中文 at Windows 100%–150% scaling. CJK glyphs carry
|
||||
# more ink than Latin at the same pixel size, so the steps are spaced widely
|
||||
# enough that two adjacent levels are always distinguishable.
|
||||
TYPE = {
|
||||
"fs_small": "12px", # secondary shell copy, status, keyboard hints
|
||||
"fs_caption": "13px", # table headers, hints, badges, timestamps
|
||||
"fs_body": "14px", # default UI text
|
||||
"fs_strong": "15px", # emphasised body, dialog prompts
|
||||
@@ -122,11 +121,11 @@ METRICS = {
|
||||
# ``outer - gap``. Where the gap is bigger than the outer radius the inner
|
||||
# element is far enough from the corner that its own radius is free.
|
||||
"r_xs": "4px", # chips, badges, tiny status pills
|
||||
"r_sm": f"{RADII['small']}px", # inline row actions, tags
|
||||
"r_md": f"{RADII['control']}px", # buttons, inputs, combo boxes
|
||||
"r_lg": f"{RADII['panel']}px", # cards, filter bars, panels
|
||||
"r_xl": f"{RADII['window']}px", # the shell surfaces the cards sit on
|
||||
"pad_control": f"{SPACING['control']}px", # horizontal padding inside default controls
|
||||
"r_sm": "6px", # inline row actions, tags
|
||||
"r_md": "8px", # buttons, inputs, combo boxes
|
||||
"r_lg": "12px", # cards, filter bars, panels
|
||||
"r_xl": "16px", # the shell surfaces the cards sit on
|
||||
"pad_control": "12px", # horizontal padding inside default controls
|
||||
"pad_compact": "9px",
|
||||
}
|
||||
|
||||
@@ -176,7 +175,7 @@ QDialog[businessDialog="true"] QFrame#DialogSurface,
|
||||
QDialog[businessDialog="true"] QFrame[dialogSurface="true"] {
|
||||
background-color: $surface;
|
||||
border: 1px solid $line;
|
||||
border-radius: $r_lg;
|
||||
border-radius: 14px;
|
||||
}
|
||||
QDialog[businessDialog="true"] QFrame#DialogHeader,
|
||||
QDialog[businessDialog="true"] QFrame[dialogRole="header"] {
|
||||
@@ -275,18 +274,18 @@ QFrame#Card, QFrame#Panel, QFrame#FilterBar, QFrame#DetailPanel,
|
||||
QFrame[glass="true"] {
|
||||
background-color: $glass;
|
||||
border: 1px solid $line;
|
||||
border-radius: $r_lg;
|
||||
border-radius: 12px;
|
||||
}
|
||||
QFrame#FilterBar { background-color: $surface; }
|
||||
QFrame#SubtleCard {
|
||||
background-color: $glass_alt;
|
||||
border: 1px solid $line;
|
||||
border-radius: $r_lg;
|
||||
border-radius: 12px;
|
||||
}
|
||||
QFrame#MetricCard {
|
||||
background-color: $surface;
|
||||
border: 1px solid $line;
|
||||
border-radius: $r_md;
|
||||
border-radius: 11px;
|
||||
}
|
||||
QFrame#MetricCard:hover { border-color: $line_soft; background-color: $surface_alt; }
|
||||
QFrame#MetricCard QLabel[role="metricTitle"] { color: $muted; font-size: $fs_caption; }
|
||||
@@ -297,7 +296,7 @@ QFrame#ReceptionAiCard {
|
||||
min-height: 132px;
|
||||
background-color: #FFFFFF;
|
||||
border: 1px solid $line_soft;
|
||||
border-radius: $r_lg;
|
||||
border-radius: 13px;
|
||||
}
|
||||
QLabel#ReceptionAiTitle {
|
||||
color: $indigo_pressed;
|
||||
@@ -313,7 +312,7 @@ QLabel#MetricGlyph {
|
||||
color: $indigo;
|
||||
background-color: $indigo_pale;
|
||||
border: 1px solid $line_soft;
|
||||
border-radius: $r_md;
|
||||
border-radius: 11px;
|
||||
font-size: $fs_section;
|
||||
font-weight: $fw_heading;
|
||||
}
|
||||
@@ -329,7 +328,7 @@ QGroupBox {
|
||||
margin-top: 12px;
|
||||
padding-top: 12px;
|
||||
border: 1px solid $line;
|
||||
border-radius: $r_lg;
|
||||
border-radius: 12px;
|
||||
background-color: $glass;
|
||||
font-weight: $fw_control;
|
||||
}
|
||||
@@ -351,7 +350,7 @@ QPushButton {
|
||||
}
|
||||
QPushButton:hover {
|
||||
background-color: $raised;
|
||||
border-color: $line_soft;
|
||||
border-color: $indigo_hover;
|
||||
}
|
||||
QPushButton:pressed {
|
||||
background-color: $indigo_pale;
|
||||
@@ -401,7 +400,7 @@ QPushButton[variant="primary"]:disabled {
|
||||
QPushButton[variant="secondary"] {
|
||||
color: $indigo_hover;
|
||||
background-color: $indigo_pale;
|
||||
border-color: $indigo_pale;
|
||||
border-color: $line_soft;
|
||||
}
|
||||
QPushButton[variant="secondary"]:hover {
|
||||
color: $indigo_pressed;
|
||||
@@ -462,7 +461,7 @@ QToolButton#RowActionsMore::menu-indicator { width: 0; height: 0; image: none; }
|
||||
QFrame#NoteAttachmentTile {
|
||||
background-color: $surface;
|
||||
border: 1px solid $line;
|
||||
border-radius: $r_md;
|
||||
border-radius: 10px;
|
||||
}
|
||||
QPushButton#NoteAttachmentPreview {
|
||||
min-height: 132px;
|
||||
@@ -470,7 +469,7 @@ QPushButton#NoteAttachmentPreview {
|
||||
color: $muted;
|
||||
background-color: $surface_alt;
|
||||
border: 1px solid $line;
|
||||
border-radius: $r_md;
|
||||
border-radius: 8px;
|
||||
font-weight: $fw_control;
|
||||
}
|
||||
QPushButton#NoteAttachmentPreview:hover {
|
||||
@@ -558,7 +557,7 @@ QPushButton[variant="chip"] {
|
||||
color: $text_soft;
|
||||
background-color: $surface_alt;
|
||||
border-color: $line;
|
||||
border-radius: $r_md;
|
||||
border-radius: 8px;
|
||||
}
|
||||
QPushButton[variant="chip"]:hover {
|
||||
color: $text;
|
||||
@@ -653,7 +652,7 @@ QComboBox QAbstractItemView {
|
||||
background-color: $raised;
|
||||
alternate-background-color: $surface_alt;
|
||||
border: 1px solid $line;
|
||||
border-radius: $r_md;
|
||||
border-radius: 10px;
|
||||
padding: 5px;
|
||||
outline: 0;
|
||||
selection-background-color: $indigo_pressed;
|
||||
@@ -692,7 +691,7 @@ QAbstractItemView, QTableWidget, QTableView, QListWidget, QListView, QTreeWidget
|
||||
background-color: $surface;
|
||||
alternate-background-color: $surface_alt;
|
||||
border: 0;
|
||||
border-radius: $r_lg;
|
||||
border-radius: 12px;
|
||||
gridline-color: $line;
|
||||
selection-background-color: $selection;
|
||||
selection-color: $text;
|
||||
@@ -729,17 +728,17 @@ QListWidget::item:selected, QListView::item:selected,
|
||||
QTreeWidget::item:selected, QTreeView::item:selected {
|
||||
background-color: $indigo_pale;
|
||||
color: $indigo_pressed;
|
||||
border-radius: $r_md;
|
||||
border-radius: 8px;
|
||||
}
|
||||
QListWidget::item:hover, QListView::item:hover,
|
||||
QTreeWidget::item:hover, QTreeView::item:hover {
|
||||
background-color: $surface_alt;
|
||||
border-radius: $r_md;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
QTabWidget::pane {
|
||||
border: 1px solid $line;
|
||||
border-radius: $r_lg;
|
||||
border-radius: 12px;
|
||||
background-color: $glass;
|
||||
}
|
||||
QTabBar::tab {
|
||||
@@ -749,7 +748,7 @@ QTabBar::tab {
|
||||
color: $muted;
|
||||
background-color: transparent;
|
||||
border: 1px solid transparent;
|
||||
border-radius: $r_md;
|
||||
border-radius: 9px;
|
||||
font-weight: $fw_control;
|
||||
}
|
||||
QTabBar::tab:hover { color: $text; background-color: $surface_alt; }
|
||||
@@ -792,7 +791,7 @@ QMenu {
|
||||
color: $text;
|
||||
background-color: $raised;
|
||||
border: 1px solid $line_soft;
|
||||
border-radius: $r_md;
|
||||
border-radius: 10px;
|
||||
padding: 6px;
|
||||
}
|
||||
QMenu::item {
|
||||
@@ -815,7 +814,7 @@ QCalendarWidget {
|
||||
color: $text;
|
||||
background-color: $surface;
|
||||
border: 1px solid $line;
|
||||
border-radius: $r_lg;
|
||||
border-radius: 12px;
|
||||
}
|
||||
QCalendarWidget QWidget#qt_calendar_navigationbar {
|
||||
background-color: $raised;
|
||||
@@ -914,7 +913,7 @@ QWidget#Pager QLabel#PagerActive {
|
||||
color: #FFFFFF;
|
||||
background-color: $indigo;
|
||||
border: 1px solid $indigo;
|
||||
border-radius: $r_md;
|
||||
border-radius: 8px;
|
||||
font-size: $fs_caption;
|
||||
font-weight: $fw_control;
|
||||
}
|
||||
@@ -937,7 +936,7 @@ QLabel#EmptyStateGlyph {
|
||||
|
||||
QFrame#MessageBanner {
|
||||
border: 1px solid $line;
|
||||
border-radius: $r_md;
|
||||
border-radius: 10px;
|
||||
color: $text_soft;
|
||||
}
|
||||
QFrame#MessageBanner QLabel { background-color: transparent; }
|
||||
@@ -955,7 +954,7 @@ QLabel#Toast {
|
||||
color: $text;
|
||||
background-color: $raised;
|
||||
border: 1px solid $line_soft;
|
||||
border-radius: $r_md;
|
||||
border-radius: 11px;
|
||||
padding: 11px 16px;
|
||||
font-weight: $fw_control;
|
||||
}
|
||||
@@ -995,9 +994,13 @@ QLabel#UserAvatar {
|
||||
font-weight: $fw_heading;
|
||||
}
|
||||
QWidget#LoginBrandPanel {
|
||||
background-color: $surface_alt;
|
||||
background-color: qlineargradient(
|
||||
x1: 0, y1: 0, x2: 1, y2: 1,
|
||||
stop: 0 $surface,
|
||||
stop: 1 $canvas_glow
|
||||
);
|
||||
border: 1px solid $line_soft;
|
||||
border-radius: $r_lg;
|
||||
border-radius: 22px;
|
||||
}
|
||||
QFrame#LoginCard {
|
||||
background-color: $glass;
|
||||
@@ -1039,7 +1042,6 @@ QToolTip {
|
||||
}
|
||||
"""
|
||||
).substitute(_QSS_TOKENS)
|
||||
GLOBAL_QSS = clinical_stylesheet(GLOBAL_QSS)
|
||||
|
||||
|
||||
#: Per-block reading rhythm, in device pixels. ``(top, bottom, line%)``.
|
||||
@@ -1239,7 +1241,7 @@ def _block_is_all_bold(block: Any) -> bool:
|
||||
return seen
|
||||
|
||||
|
||||
def apply_reading_rhythm(browser: QTextBrowser, *, role: str, start_position: int = 0) -> None:
|
||||
def apply_reading_rhythm(browser: QTextBrowser, *, role: str) -> None:
|
||||
"""Give a parsed reply real hierarchy and breathing room.
|
||||
|
||||
Model answers are long "section heading + two levels of bullets" documents.
|
||||
@@ -1257,7 +1259,7 @@ def apply_reading_rhythm(browser: QTextBrowser, *, role: str, start_position: in
|
||||
cursor = QTextCursor(document)
|
||||
cursor.beginEditBlock()
|
||||
try:
|
||||
block = document.findBlock(start_position)
|
||||
block = document.begin()
|
||||
while block.isValid():
|
||||
heading = block.blockFormat().headingLevel()
|
||||
text_list = block.textList()
|
||||
|
||||
@@ -44,7 +44,6 @@ from doctor_workstation.core.errors import (
|
||||
)
|
||||
|
||||
from . import icons, motion
|
||||
from .design_system import PALETTE
|
||||
|
||||
AuthenticationExpiredHandler = Callable[[AuthenticationExpiredError], bool]
|
||||
_AUTHENTICATION_EXPIRED_HANDLER: AuthenticationExpiredHandler | None = None
|
||||
@@ -799,7 +798,7 @@ class _BusyTrack(QWidget):
|
||||
chunk_width = max(36, int(rect.width() * 0.32))
|
||||
span = rect.width() + chunk_width
|
||||
x = int(self._phase * span) - chunk_width
|
||||
painter.setBrush(QColor(PALETTE["accent"]))
|
||||
painter.setBrush(QColor("#4F63D9"))
|
||||
painter.drawRoundedRect(x, 0, chunk_width, rect.height(), 3, 3)
|
||||
|
||||
|
||||
|
||||
@@ -1,387 +0,0 @@
|
||||
"""Bounded, Qt-independent AI requests for one authenticated IM window.
|
||||
|
||||
Only server-archived clinical context is submitted. This module never sends IM
|
||||
messages and never shares the ordered call/recording lifecycle worker.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from collections import deque
|
||||
from collections.abc import Callable, Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from threading import BoundedSemaphore, Event, RLock, Thread
|
||||
from time import monotonic
|
||||
from typing import Any
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
MAX_RESULT_CHARS = 65_536
|
||||
MAX_SYNC_STEPS = 24
|
||||
SYNC_TIMEOUT_SECONDS = 45.0
|
||||
_WORKER_SLOTS = BoundedSemaphore(4)
|
||||
_CANCEL_SLOTS = BoundedSemaphore(4)
|
||||
_ACTIONS = frozenset({"summary", "followup", "reply"})
|
||||
|
||||
|
||||
def _integer(value: Any, *, minimum: int) -> int | None:
|
||||
if isinstance(value, bool) or not isinstance(value, (int, str)):
|
||||
return None
|
||||
if isinstance(value, str) and re.fullmatch(r"0|[1-9][0-9]{0,18}", value) is None:
|
||||
return None
|
||||
number = int(value)
|
||||
return number if minimum <= number < 2**63 else None
|
||||
|
||||
|
||||
def _request_uuid(value: Any) -> bool:
|
||||
if not isinstance(value, str) or len(value) != 36:
|
||||
return False
|
||||
try:
|
||||
return str(UUID(value)) == value.lower()
|
||||
except (ValueError, AttributeError):
|
||||
return False
|
||||
|
||||
|
||||
def task_prompt(action: str, doctor_account: str) -> tuple[str, str]:
|
||||
"""Keep instructions separate from clinical source text and under API limits."""
|
||||
|
||||
if action not in _ACTIONS or not re.fullmatch(r"doctor_[1-9][0-9]{0,18}", doctor_account):
|
||||
raise ValueError("AI 操作或当前医生账号无效")
|
||||
shared = (
|
||||
f"这是 IM 问诊辅助,本次医生 IM 账号为 {doctor_account}。"
|
||||
"优先依据该医生与本患者最近已归档对话,结合服务端授权病历;"
|
||||
"其他医生及历史记录仅作背景,不能当成本次已确认事实。"
|
||||
"若未找到本次对话请明确说明,不猜测最新诉求。"
|
||||
"区分已知、明确否认与未知,保留日期及不确定性;"
|
||||
"不补问脉象,不编造事实、不自动确诊、不新增或更改药物剂量。"
|
||||
)
|
||||
instructions = {
|
||||
"summary": "请用简短条目总结本次病情、病程、现用治疗与待核实事项,供医生交接复核。",
|
||||
"followup": (
|
||||
"请建议最多5条优先追问,直接给出可向患者询问的自然短句,"
|
||||
"每条可附简短目的;避免重复已回答的问题,不做通用问卷。"
|
||||
),
|
||||
"reply": (
|
||||
"请起草一段医生可审阅后发给患者的简短自然回复,围绕该对话最近的患者问题。"
|
||||
"不冒称已检查、已预约或已开处方,不承诺疗效,不让患者自行停换药。"
|
||||
"只给回复草稿,不写分析过程;任何缺失资料通过必要的问题核实。"
|
||||
),
|
||||
}
|
||||
prompt = shared + instructions[action] + "此内容须由医生复核,不能自动发送。"
|
||||
if len(prompt) > 500:
|
||||
raise ValueError("AI 提示词超过接口长度限制")
|
||||
return ("summary" if action == "summary" else "custom"), prompt
|
||||
|
||||
|
||||
def _warnings(value: Any) -> list[str]:
|
||||
if not isinstance(value, (list, tuple)):
|
||||
return []
|
||||
warnings = []
|
||||
for row in value[:20]:
|
||||
if isinstance(row, str):
|
||||
text = row
|
||||
elif isinstance(row, Mapping):
|
||||
text = row.get("message") or row.get("label")
|
||||
if not text and row.get("code"):
|
||||
text = (
|
||||
"请复核回答中的脉象判断;本流程不采集脉象。"
|
||||
if row["code"] == "PULSE_EXCLUDED_FROM_ASSESSMENT"
|
||||
else "请对照原始记录复核,回答中的事实、否认或未知状态可能不一致。"
|
||||
)
|
||||
else:
|
||||
continue
|
||||
if isinstance(text, str) and text.strip():
|
||||
rendered = text.strip()[:400]
|
||||
if rendered not in warnings:
|
||||
warnings.append(rendered)
|
||||
return warnings
|
||||
|
||||
|
||||
class _RequestError(Exception):
|
||||
"""A deliberately safe, user-facing failure message."""
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Job:
|
||||
identity: dict[str, Any]
|
||||
action: str
|
||||
cancelled: Event = field(default_factory=Event)
|
||||
completed: bool = False
|
||||
succeeded: bool = False
|
||||
stream_started: bool = False
|
||||
cancel_sent: bool = False
|
||||
|
||||
|
||||
class ImAiController:
|
||||
"""One live request, a coalesced mailbox, and bounded daemon workers.
|
||||
|
||||
Qt polls ``take_result`` every 60 ms. Worker threads only mutate plain data;
|
||||
they never touch a QObject. A cancelled worker must retire before a retry
|
||||
starts, so rapid clicks cannot create an unbounded collection of requests.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
repository: Any,
|
||||
*,
|
||||
diagnosis_id: Any,
|
||||
appointment_id: Any,
|
||||
doctor_account: str,
|
||||
enabled: bool = False,
|
||||
clock: Callable[[], float] = monotonic,
|
||||
max_sync_steps: int = MAX_SYNC_STEPS,
|
||||
sync_timeout: float = SYNC_TIMEOUT_SECONDS,
|
||||
) -> None:
|
||||
self.repository = repository
|
||||
self.diagnosis_id = _integer(diagnosis_id, minimum=1)
|
||||
self.appointment_id = _integer(appointment_id, minimum=0)
|
||||
self.doctor_account = str(doctor_account)
|
||||
self.enabled = (
|
||||
enabled is True
|
||||
and repository is not None
|
||||
and self.diagnosis_id is not None
|
||||
and self.appointment_id is not None
|
||||
and re.fullmatch(r"doctor_[1-9][0-9]{0,18}", self.doctor_account) is not None
|
||||
)
|
||||
self.session_id = str(uuid4())
|
||||
self._clock = clock
|
||||
self._max_sync_steps = max(1, min(MAX_SYNC_STEPS, max_sync_steps))
|
||||
self._sync_timeout = max(0.01, min(SYNC_TIMEOUT_SECONDS, sync_timeout))
|
||||
self._lock = RLock()
|
||||
self._closed = False
|
||||
self._current: _Job | None = None
|
||||
self._running: _Job | None = None
|
||||
self._worker: Thread | None = None
|
||||
self._mailbox: dict[str, Any] | None = None
|
||||
self._seen: deque[str] = deque(maxlen=256)
|
||||
|
||||
@property
|
||||
def config(self) -> dict[str, Any]:
|
||||
return {
|
||||
"version": 1,
|
||||
"enabled": self.enabled and not self._closed,
|
||||
"sessionId": self.session_id,
|
||||
**({} if self.enabled else {"reason": "当前账号或问诊暂不能使用 AI 辅助。"}),
|
||||
}
|
||||
|
||||
def _valid_identity(self, message: Mapping[str, Any]) -> bool:
|
||||
return (
|
||||
self.enabled
|
||||
and not self._closed
|
||||
and message.get("source") == "doctor-call"
|
||||
and message.get("sessionId") == self.session_id
|
||||
and _request_uuid(message.get("requestId"))
|
||||
and isinstance(message.get("contextKey"), str)
|
||||
and 0 < len(message["contextKey"]) <= 128
|
||||
and _integer(message.get("diagnosisId"), minimum=1) == self.diagnosis_id
|
||||
and _integer(message.get("appointmentId"), minimum=0) == self.appointment_id
|
||||
and isinstance(message.get("action"), str)
|
||||
and message["action"] in _ACTIONS
|
||||
)
|
||||
|
||||
def handle(self, message: Mapping[str, Any]) -> bool:
|
||||
with self._lock:
|
||||
if not self._valid_identity(message):
|
||||
return False
|
||||
event = message.get("event")
|
||||
identity = {key: message[key] for key in (
|
||||
"sessionId", "requestId", "contextKey", "diagnosisId", "appointmentId", "action"
|
||||
)}
|
||||
if event == "im-ai-cancel":
|
||||
if self._current is None or self._current.identity != identity:
|
||||
return False
|
||||
self._cancel(self._current)
|
||||
return True
|
||||
if event != "im-ai-request" or message["requestId"] in self._seen:
|
||||
return False
|
||||
self._seen.append(message["requestId"])
|
||||
job = _Job(identity, message["action"])
|
||||
if self._running is not None:
|
||||
self._cancel(self._running)
|
||||
self._current = job
|
||||
self._publish(job, "error", message="上次请求正在结束,请稍后重试。", terminal=True)
|
||||
return True
|
||||
self._current = job
|
||||
if not _WORKER_SLOTS.acquire(blocking=False):
|
||||
self._publish(job, "error", message="AI 正在处理其他请求,请稍后重试。", terminal=True)
|
||||
return True
|
||||
self._running = job
|
||||
self._publish(job, "loading", message="正在同步当前聊天记录…")
|
||||
self._worker = Thread(target=self._run, args=(job,), name="im-ai", daemon=True)
|
||||
try:
|
||||
self._worker.start()
|
||||
except RuntimeError:
|
||||
self._running = None
|
||||
_WORKER_SLOTS.release()
|
||||
self._publish(job, "error", message="AI 请求暂时无法启动,请稍后重试。", terminal=True)
|
||||
return True
|
||||
|
||||
def _publish(self, job: _Job, status: str, *, terminal: bool = False, **fields: Any) -> None:
|
||||
with self._lock:
|
||||
if self._closed or self._current is not job or job.cancelled.is_set() or job.completed:
|
||||
return
|
||||
if terminal:
|
||||
job.completed = True
|
||||
job.succeeded = status == "success"
|
||||
self._mailbox = {**job.identity, "status": status, **fields}
|
||||
|
||||
def take_result(self) -> dict[str, Any] | None:
|
||||
with self._lock:
|
||||
result, self._mailbox = self._mailbox, None
|
||||
return None if self._closed else result
|
||||
|
||||
def _sync(self, job: _Job) -> bool:
|
||||
deadline = self._clock() + self._sync_timeout
|
||||
token = ""
|
||||
for _ in range(self._max_sync_steps):
|
||||
if job.cancelled.is_set():
|
||||
return False
|
||||
if self._clock() >= deadline:
|
||||
raise _RequestError("聊天同步超时,尚未生成,请稍后重试。")
|
||||
result = self.repository.sync_im_chat_messages(
|
||||
self.diagnosis_id, scope="current", sync_token=token
|
||||
)
|
||||
if job.cancelled.is_set():
|
||||
return False
|
||||
if self._clock() >= deadline:
|
||||
raise _RequestError("聊天同步超时,尚未生成,请稍后重试。")
|
||||
if not isinstance(result, Mapping) or result.get("errors"):
|
||||
raise _RequestError("当前聊天记录未能完整同步,尚未生成,请稍后重试。")
|
||||
if result.get("completed") is True:
|
||||
return True
|
||||
token = result.get("sync_token", "")
|
||||
if not isinstance(token, str) or re.fullmatch(r"[a-f0-9]{48}", token) is None:
|
||||
raise _RequestError("聊天同步进度无效,请更新客户端或稍后重试。")
|
||||
raise _RequestError("聊天记录仍在同步,尚未生成,请稍后重试。")
|
||||
|
||||
def _run(self, job: _Job) -> None:
|
||||
try:
|
||||
if not self._sync(job):
|
||||
return
|
||||
task, prompt = task_prompt(job.action, self.doctor_account)
|
||||
with self._lock:
|
||||
if job.cancelled.is_set() or self._closed:
|
||||
return
|
||||
job.stream_started = True
|
||||
self._publish(job, "loading", message="聊天已同步,正在整理病历资料…")
|
||||
if job.cancelled.is_set():
|
||||
return
|
||||
text = ""
|
||||
events = self.repository.stream_diagnosis_ai(
|
||||
self.diagnosis_id, prompt, task=task,
|
||||
request_id=job.identity["requestId"], cancelled=job.cancelled.is_set,
|
||||
)
|
||||
try:
|
||||
for event in events:
|
||||
if job.cancelled.is_set():
|
||||
return
|
||||
if not isinstance(event, Mapping):
|
||||
continue
|
||||
kind = event.get("event")
|
||||
if kind == "delta":
|
||||
delta = event.get("text", "")
|
||||
if not isinstance(delta, str) or len(text) + len(delta) > MAX_RESULT_CHARS:
|
||||
raise _RequestError("AI 内容超过显示上限,已停止接收,请缩小问题后重试。")
|
||||
text += delta
|
||||
self._publish(job, "streaming", text=text, message="正在生成,内容尚未完成。")
|
||||
elif kind in {"start", "progress"}:
|
||||
message = str(event.get("message") or "正在整理资料并生成…")[:240]
|
||||
self._publish(job, "streaming" if text else "loading", text=text, message=message)
|
||||
elif kind == "done":
|
||||
result_id = event.get("diagnosis_id")
|
||||
if result_id is not None and _integer(result_id, minimum=1) != self.diagnosis_id:
|
||||
raise _RequestError("AI 返回的问诊上下文不匹配,结果未采用。")
|
||||
answer = event.get("answer", event.get("content", text))
|
||||
if not isinstance(answer, str) or not answer.strip():
|
||||
raise _RequestError("AI 未返回完整内容,请重试。")
|
||||
if len(answer) > MAX_RESULT_CHARS:
|
||||
raise _RequestError("AI 内容超过显示上限,结果未采用,请缩小问题后重试。")
|
||||
self._publish(
|
||||
job, "success", terminal=True, text=answer,
|
||||
message="已生成,请由医生复核后使用。",
|
||||
modelLabel=str(event.get("model_label") or "")[:100],
|
||||
warnings=_warnings(event.get("clinical_review_warnings")),
|
||||
)
|
||||
return
|
||||
elif kind == "error":
|
||||
raise _RequestError("AI 请求未完成,请检查权限或稍后重试。")
|
||||
if not job.cancelled.is_set():
|
||||
raise _RequestError("AI 连接提前结束,内容未完成,请重试。")
|
||||
finally:
|
||||
close = getattr(events, "close", None)
|
||||
if callable(close):
|
||||
close()
|
||||
except Exception as error:
|
||||
message = str(error) if isinstance(error, _RequestError) else (
|
||||
"AI 请求失败,请检查权限或稍后重试。" if job.stream_started
|
||||
else "当前聊天同步失败,尚未生成,请检查权限或稍后重试。"
|
||||
)
|
||||
self._publish(job, "error", message=message, terminal=True)
|
||||
if job.stream_started and not job.cancelled.is_set() and not job.succeeded:
|
||||
self._request_cancel(job)
|
||||
finally:
|
||||
with self._lock:
|
||||
if self._running is job:
|
||||
self._running = None
|
||||
_WORKER_SLOTS.release()
|
||||
|
||||
def _cancel(self, job: _Job) -> None:
|
||||
if job.completed or job.cancelled.is_set():
|
||||
return
|
||||
job.cancelled.set()
|
||||
if self._current is job and not self._closed:
|
||||
self._mailbox = {
|
||||
**job.identity, "status": "cancelled",
|
||||
"message": ("已停止本次接收,上游是否结束尚未确认。" if job.stream_started
|
||||
else "已取消,尚未向 AI 提交请求。"),
|
||||
}
|
||||
if job.stream_started:
|
||||
self._request_cancel(job)
|
||||
|
||||
def _request_cancel(self, job: _Job) -> None:
|
||||
with self._lock:
|
||||
if job.cancel_sent:
|
||||
return
|
||||
job.cancel_sent = True
|
||||
if not _CANCEL_SLOTS.acquire(blocking=False):
|
||||
return
|
||||
|
||||
def send() -> None:
|
||||
try:
|
||||
result = self.repository.cancel_diagnosis_ai(self.diagnosis_id, job.identity["requestId"])
|
||||
if not isinstance(result, Mapping):
|
||||
return
|
||||
message = "已发送取消请求,上游是否结束尚未确认。"
|
||||
terminal = result.get("upstream_terminal_status")
|
||||
if result.get("upstream_terminal_confirmed") is True and terminal in {"stopped", "succeeded", "failed"}:
|
||||
message = "本次接收已停止,上游工作流已结束。"
|
||||
elif result.get("upstream_stop_confirmed") is True:
|
||||
message = "上游已接受停止请求,是否结束尚未确认。"
|
||||
with self._lock:
|
||||
if not self._closed and self._current is job and job.cancelled.is_set():
|
||||
self._mailbox = {**job.identity, "status": "cancelled", "message": message}
|
||||
except Exception:
|
||||
pass # Keep the visible unconfirmed cancellation; never expose transport details.
|
||||
finally:
|
||||
_CANCEL_SLOTS.release()
|
||||
|
||||
try:
|
||||
Thread(target=send, name="im-ai-cancel", daemon=True).start()
|
||||
except RuntimeError:
|
||||
_CANCEL_SLOTS.release()
|
||||
|
||||
def close(self) -> None:
|
||||
with self._lock:
|
||||
if self._closed:
|
||||
return
|
||||
self._closed = True
|
||||
self._mailbox = None
|
||||
if self._running is not None:
|
||||
self._cancel(self._running)
|
||||
|
||||
def wait(self, timeout: float = 1.0) -> bool:
|
||||
"""Bounded diagnostic/test helper; never called by the Qt GUI."""
|
||||
|
||||
worker = self._worker
|
||||
if worker is not None:
|
||||
worker.join(max(0.0, min(timeout, 5.0)))
|
||||
return worker is None or not worker.is_alive()
|
||||
@@ -413,7 +413,6 @@ class VideoCallLauncher:
|
||||
patient_name: str = "患者",
|
||||
patient_case: Mapping[str, Any] | None = None,
|
||||
on_open_diagnosis: Callable[[], None] | None = None,
|
||||
can_ai_assistant: bool = False,
|
||||
) -> Any:
|
||||
request = self.prepare(
|
||||
ticket,
|
||||
@@ -433,7 +432,6 @@ class VideoCallLauncher:
|
||||
patient_name=patient_name,
|
||||
patient_case=patient_case,
|
||||
on_open_diagnosis=on_open_diagnosis,
|
||||
can_ai_assistant=can_ai_assistant is True,
|
||||
)
|
||||
|
||||
|
||||
@@ -452,7 +450,6 @@ def launch_video_call(
|
||||
patient_name: str = "患者",
|
||||
patient_case: Mapping[str, Any] | None = None,
|
||||
on_open_diagnosis: Callable[[], None] | None = None,
|
||||
can_ai_assistant: bool = False,
|
||||
) -> Any:
|
||||
"""Normalize a ticket and open a call with the requested backend."""
|
||||
|
||||
@@ -471,5 +468,4 @@ def launch_video_call(
|
||||
patient_name=patient_name,
|
||||
patient_case=patient_case,
|
||||
on_open_diagnosis=on_open_diagnosis,
|
||||
can_ai_assistant=can_ai_assistant is True,
|
||||
)
|
||||
|
||||
@@ -18,7 +18,6 @@ from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any, TypeVar
|
||||
|
||||
from ..core.transcript_text import simplified_transcript
|
||||
from .launcher import VideoCallRequest, normalize_backend_ticket
|
||||
|
||||
ResultT = TypeVar("ResultT")
|
||||
@@ -135,7 +134,7 @@ def _extract_cloud_recording_outcome(result: Any) -> tuple[bool, str] | None:
|
||||
return None
|
||||
|
||||
|
||||
def normalize_transcript_segment(segment: Mapping[str, Any], session_id: str) -> dict[str, Any]:
|
||||
def _clean_transcript_segment(segment: Mapping[str, Any], session_id: str) -> dict[str, Any]:
|
||||
segment_id = str(segment.get("segment_id", segment.get("segmentId", ""))).strip()
|
||||
text = str(segment.get("text", segment.get("sourceText", ""))).strip()
|
||||
speaker_user_id = str(
|
||||
@@ -146,14 +145,13 @@ def normalize_transcript_segment(segment: Mapping[str, Any], session_id: str) ->
|
||||
raise ValueError("transcript segment_id must contain 1 to 160 characters")
|
||||
if not text or len(text) > 4_000:
|
||||
raise ValueError("transcript text must contain 1 to 4000 characters")
|
||||
text = simplified_transcript(text)
|
||||
if len(speaker_user_id) > 160:
|
||||
raise ValueError("transcript speaker_user_id is too long")
|
||||
if speaker_role not in {"doctor", "patient", "unknown"}:
|
||||
speaker_role = "unknown"
|
||||
try:
|
||||
timestamp = int(segment.get("timestamp") or 0)
|
||||
except (TypeError, ValueError, OverflowError):
|
||||
except (TypeError, ValueError):
|
||||
timestamp = 0
|
||||
return {
|
||||
"segment_id": segment_id,
|
||||
@@ -545,25 +543,10 @@ class OrderedCallLifecycle:
|
||||
with self._lock:
|
||||
if self._end_future is not None:
|
||||
raise RuntimeError("video call has already ended")
|
||||
if self._transcription_finish_future is not None:
|
||||
raise RuntimeError("call transcription has already stopped")
|
||||
if (
|
||||
self._transcription_session_id is not None
|
||||
and self._transcription_session_id != clean_session
|
||||
):
|
||||
raise RuntimeError("another transcription session already exists")
|
||||
previous = self._transcription_start_future
|
||||
if previous is not None:
|
||||
if not previous.done() or (
|
||||
not previous.cancelled()
|
||||
and previous.exception() is None
|
||||
and previous.result() is True
|
||||
):
|
||||
return previous
|
||||
# A completed failure must not poison this call's retry button.
|
||||
# Keep the exact session identity: the server may have accepted
|
||||
# an earlier request whose response never reached this client.
|
||||
self._transcription_active = False
|
||||
if self._transcription_start_future is not None:
|
||||
if self._transcription_session_id != clean_session:
|
||||
raise RuntimeError("another transcription session already exists")
|
||||
return self._transcription_start_future
|
||||
if self._start_future is None:
|
||||
self.start()
|
||||
method = getattr(self.repository, "start_call_transcription", None)
|
||||
@@ -610,7 +593,7 @@ class OrderedCallLifecycle:
|
||||
raise RuntimeError("call transcription has not started")
|
||||
if self._transcription_finish_future is not None:
|
||||
raise RuntimeError("call transcription has already stopped")
|
||||
cleaned = normalize_transcript_segment(segment, session_id)
|
||||
cleaned = _clean_transcript_segment(segment, session_id)
|
||||
segment_id = cleaned["segment_id"]
|
||||
existing = self._segment_futures.get(segment_id)
|
||||
if existing is not None:
|
||||
@@ -755,4 +738,4 @@ class OrderedCallLifecycle:
|
||||
return self._worker.wait(timeout)
|
||||
|
||||
|
||||
__all__ = ["OrderedCallLifecycle", "normalize_transcript_segment"]
|
||||
__all__ = ["OrderedCallLifecycle"]
|
||||
|
||||
@@ -1,414 +0,0 @@
|
||||
"""Incremental video assistance; never runs on the call persistence FIFO or Qt.
|
||||
|
||||
Only persisted segment notifications trigger work. One in-flight request and
|
||||
one coalesced latest revision are retained, with explicit patient/call/session
|
||||
correlation. Clinical content is never written or sent to the patient here.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import logging
|
||||
import math
|
||||
import re
|
||||
from collections.abc import Callable, Mapping
|
||||
from contextlib import suppress
|
||||
from dataclasses import dataclass, field
|
||||
from threading import BoundedSemaphore, Event, RLock, Thread
|
||||
from time import monotonic
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
from ..core.errors import (
|
||||
ApiBusinessError,
|
||||
ApiHttpError,
|
||||
ApiProtocolError,
|
||||
ApiTimeoutError,
|
||||
ApiTransportError,
|
||||
AuthenticationExpiredError,
|
||||
)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
_SLOTS = BoundedSemaphore(2)
|
||||
_CANCEL_SLOTS = BoundedSemaphore(4)
|
||||
|
||||
|
||||
def _failure_details(error: Exception) -> tuple[str, str]:
|
||||
"""Translate stable error codes, never echo an upstream exception/response."""
|
||||
if isinstance(error, ApiTimeoutError):
|
||||
code = "UPSTREAM_TIMEOUT"
|
||||
elif isinstance(error, AuthenticationExpiredError):
|
||||
code = "AUTH_REQUIRED"
|
||||
elif isinstance(error, ApiHttpError):
|
||||
code = ({401: "AUTH_REQUIRED", 403: "PERMISSION_DENIED", 404: "SERVICE_UPDATE_REQUIRED",
|
||||
405: "SERVICE_UPDATE_REQUIRED", 429: "RATE_LIMITED"}.get(error.status_code)
|
||||
or "UPSTREAM_UNAVAILABLE")
|
||||
elif isinstance(error, ApiBusinessError) and isinstance(error.data, Mapping):
|
||||
code = error.data.get("error_code") or error.data.get("code")
|
||||
elif isinstance(error, ApiProtocolError):
|
||||
code = "STREAM_INCOMPLETE"
|
||||
elif isinstance(error, ApiTransportError):
|
||||
code = "NETWORK_ERROR"
|
||||
elif isinstance(error, ValueError):
|
||||
code = "LIVE_RESULT_INVALID"
|
||||
else:
|
||||
code = "UPSTREAM_UNAVAILABLE"
|
||||
messages = {
|
||||
"UPSTREAM_TIMEOUT": "分析服务响应超时,可点击重新生成。",
|
||||
"AUTH_REQUIRED": "登录状态已失效,请重新登录后使用 AI 辅助。",
|
||||
"PERMISSION_DENIED": "当前账号没有 AI 辅助权限,请联系管理员开通。",
|
||||
"SERVICE_UPDATE_REQUIRED": "服务端尚不支持实时 AI,请更新服务端后重试。",
|
||||
"RATE_LIMITED": "分析请求较多,请稍后重新生成。",
|
||||
"LIVE_RESULT_INVALID": "本次建议未通过格式或引用校验,可点击重新生成。",
|
||||
"LIVE_CONTEXT_UNAVAILABLE": "本次通话的分析资料尚未就绪,请等待转写保存后重试。",
|
||||
"STREAM_INCOMPLETE": "分析连接提前结束,可点击重新生成。",
|
||||
"NETWORK_ERROR": "分析服务连接中断,请检查网络后重试。",
|
||||
"UPSTREAM_UNAVAILABLE": "分析服务暂时不可用,请稍后重新生成。",
|
||||
}
|
||||
if not isinstance(code, str) or code not in messages:
|
||||
code = "UPSTREAM_UNAVAILABLE"
|
||||
if code == "LIVE_RESULT_INVALID" and isinstance(getattr(error, "data", None), Mapping):
|
||||
reason = error.data.get("live_validation_reason")
|
||||
details = {
|
||||
"JSON_INVALID": "分析服务返回的格式不完整,可点击重新生成。",
|
||||
"SCHEMA_INVALID": "分析服务返回的格式不符合要求,可点击重新生成。",
|
||||
"CITATION_INVALID": "部分建议的原文引用无法核对,可点击重新生成。",
|
||||
"SOURCE_QUOTE_MISMATCH": "部分建议与引用原文不一致,可点击重新生成。",
|
||||
"SAFETY_REJECTED": "本次建议包含超出辅助范围的内容,未通过校验,可重新生成。",
|
||||
}
|
||||
if isinstance(reason, str) and reason in details:
|
||||
return code, details[reason]
|
||||
return code, messages[code]
|
||||
|
||||
|
||||
def empty_video_ai_state(available: bool) -> dict[str, Any]:
|
||||
return {
|
||||
"enabled": available, "available": available, "busy": False,
|
||||
"phase": "waiting", "message": ("接通并产生转写文字后,自动整理本次对话。" if available
|
||||
else "当前账号或服务暂不能使用 AI 辅助;语音转写可独立运行。"),
|
||||
"error": "", "revision": "", "throughTimestampMs": 0, "segmentCount": 0,
|
||||
"transcriptionStatus": "idle", "summary": [], "questions": [],
|
||||
"checks": [], "review": [], "sources": [],
|
||||
"elapsedMs": 0, "lastDurationMs": 0, "firstResultMs": None,
|
||||
"pendingSegments": 0, "errorCode": "", "analysisScope": "",
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Job:
|
||||
generation: int
|
||||
call_id: int
|
||||
session_id: str
|
||||
dirty: int
|
||||
task: str
|
||||
started_at: float = 0.0
|
||||
first_result_ms: int | None = None
|
||||
revision: str = ""
|
||||
analysis_scope: str | None = None
|
||||
request_id: str = field(default_factory=lambda: str(uuid4()))
|
||||
cancelled: Event = field(default_factory=Event)
|
||||
cancel_sent: bool = False
|
||||
|
||||
|
||||
class LiveAiController:
|
||||
def __init__(self, repository: Any, *, diagnosis_id: int, enabled: bool,
|
||||
clock: Callable[[], float] = monotonic, interval: float = 2.0) -> None:
|
||||
self.repository = repository
|
||||
self.diagnosis_id = diagnosis_id
|
||||
self.available = enabled is True and callable(getattr(repository, "stream_video_ai", None))
|
||||
self._clock = clock
|
||||
self._interval = max(0, interval)
|
||||
self._lock = RLock()
|
||||
self._state = empty_video_ai_state(self.available)
|
||||
self._mailbox: dict[str, Any] | None = copy.deepcopy(self._state)
|
||||
self._closed = False
|
||||
self._generation = 0
|
||||
self._call_id = 0
|
||||
self._session_id = ""
|
||||
self._dirty = 0
|
||||
self._attempted = 0
|
||||
self._displayed_dirty = 0
|
||||
self._due = 0.0
|
||||
self._forced_task = ""
|
||||
self._running: _Job | None = None
|
||||
self._worker: Thread | None = None
|
||||
|
||||
def _publish(self, **changes: Any) -> None:
|
||||
self._state.update(changes)
|
||||
self._state["pendingSegments"] = max(0, self._dirty - self._displayed_dirty)
|
||||
self._mailbox = copy.deepcopy(self._state)
|
||||
|
||||
def take_state(self) -> dict[str, Any] | None:
|
||||
with self._lock:
|
||||
result, self._mailbox = self._mailbox, None
|
||||
return None if self._closed else result
|
||||
|
||||
def bind(self, call_id: int, session_id: str) -> None:
|
||||
with self._lock:
|
||||
if self._closed or (self._call_id == call_id and self._session_id == session_id):
|
||||
return
|
||||
self._cancel()
|
||||
enabled = self._state["enabled"]
|
||||
self._generation += 1
|
||||
self._call_id, self._session_id = call_id, session_id
|
||||
self._dirty = self._attempted = 0
|
||||
self._displayed_dirty = 0
|
||||
self._forced_task = ""
|
||||
self._state = empty_video_ai_state(self.available)
|
||||
self._publish(enabled=enabled, transcriptionStatus="running" if session_id else "idle")
|
||||
|
||||
def reset(self) -> None:
|
||||
"""Clear the previous call before a new call's model/storage is ready."""
|
||||
self.bind(0, "")
|
||||
|
||||
def changed(self, session_id: str) -> None:
|
||||
with self._lock:
|
||||
if self._closed or session_id != self._session_id:
|
||||
return
|
||||
was_clean = self._dirty == self._attempted
|
||||
self._dirty += 1
|
||||
if was_clean:
|
||||
# Coalesce a short speech burst without repeatedly moving the deadline.
|
||||
self._due = self._clock() + (0.8 if not self._state["revision"] else self._interval)
|
||||
self._publish()
|
||||
|
||||
def transcription_error(self, message: str, *, status: str = "partial") -> None:
|
||||
with self._lock:
|
||||
if not self._closed:
|
||||
self._publish(transcriptionStatus=status, error=message[:240])
|
||||
|
||||
def transcription_starting(self) -> None:
|
||||
with self._lock:
|
||||
if not self._closed:
|
||||
self._publish(transcriptionStatus="starting", error="")
|
||||
|
||||
def transcription_running(self, session_id: str) -> None:
|
||||
"""A retried cloud recognizer is ready without resetting saved evidence."""
|
||||
with self._lock:
|
||||
if not self._closed and session_id == self._session_id:
|
||||
self._publish(transcriptionStatus="running", error="")
|
||||
|
||||
def finish(self, session_id: str, status: str) -> None:
|
||||
with self._lock:
|
||||
if not self._closed and session_id == self._session_id:
|
||||
self._publish(transcriptionStatus=status)
|
||||
|
||||
def handle(self, action: str, enabled: Any = None) -> None:
|
||||
with self._lock:
|
||||
if self._closed or not self.available:
|
||||
return
|
||||
if action == "toggle" and isinstance(enabled, bool):
|
||||
if not enabled:
|
||||
self._cancel()
|
||||
self._publish(enabled=enabled, busy=False if not enabled else self._state["busy"],
|
||||
message="已暂停自动分析。" if not enabled else "有新增对话后自动更新。")
|
||||
return
|
||||
if action not in {"refresh", "review"} or not self._dirty or self._running is not None:
|
||||
return
|
||||
if action == "review" and self._state["transcriptionStatus"] not in {"completed", "partial"}:
|
||||
return
|
||||
self._forced_task = "live_review" if action == "review" else "live_consultation"
|
||||
self._due = self._clock()
|
||||
|
||||
def tick(self) -> None:
|
||||
with self._lock:
|
||||
if self._running is not None and self._current(self._running):
|
||||
elapsed = self._elapsed(self._running)
|
||||
if elapsed // 1000 != self._state["elapsedMs"] // 1000:
|
||||
self._publish(elapsedMs=elapsed)
|
||||
if (self._closed or not self.available or not self._call_id or not self._session_id
|
||||
or self._running is not None or not self._dirty
|
||||
or (not self._forced_task and (not self._state["enabled"] or self._dirty <= self._attempted))
|
||||
or self._clock() < self._due):
|
||||
return
|
||||
if not _SLOTS.acquire(blocking=False):
|
||||
return
|
||||
job = _Job(self._generation, self._call_id, self._session_id, self._dirty,
|
||||
self._forced_task or "live_consultation", started_at=self._clock())
|
||||
self._forced_task = ""
|
||||
self._attempted = self._dirty
|
||||
self._running = job
|
||||
self._publish(busy=True, phase="analyzing", error="", errorCode="", elapsedMs=0, firstResultMs=None,
|
||||
message="正在分析最新对话,优先整理下一步追问…")
|
||||
self._worker = Thread(target=self._run, args=(job,), name="video-ai", daemon=True)
|
||||
try:
|
||||
self._worker.start()
|
||||
except RuntimeError:
|
||||
self._running = None
|
||||
_SLOTS.release()
|
||||
self._publish(busy=False, phase="error", error="分析任务无法启动,请重试。")
|
||||
|
||||
def _elapsed(self, job: _Job) -> int:
|
||||
return max(0, int((self._clock() - job.started_at) * 1000))
|
||||
|
||||
def _current(self, job: _Job) -> bool:
|
||||
return not self._closed and job.generation == self._generation and not job.cancelled.is_set()
|
||||
|
||||
def _validated_result(self, job: _Job, event: Mapping[str, Any]) -> dict[str, Any]:
|
||||
context = event.get("live_context")
|
||||
result = event.get("live_assistance")
|
||||
# Only label the scope of validated displayed content. Older servers do
|
||||
# not report it; never infer dialogue-only behavior from the task name.
|
||||
scope = event.get("analysis_scope", "")
|
||||
if not isinstance(scope, str) or scope not in {"", "current_call_only", "authorized_case"}:
|
||||
raise ValueError("invalid analysis scope")
|
||||
if (not isinstance(context, Mapping) or not isinstance(result, Mapping)
|
||||
or event.get("diagnosis_id") != self.diagnosis_id
|
||||
or context.get("call_record_id") != job.call_id
|
||||
or context.get("transcription_session_id") != job.session_id
|
||||
or not isinstance(context.get("revision"), str)
|
||||
or not re.fullmatch(r"[a-f0-9]{64}", context["revision"])):
|
||||
raise ValueError("context mismatch")
|
||||
sources = context.get("sources")
|
||||
if not isinstance(sources, list) or len(sources) > 1000:
|
||||
raise ValueError("invalid evidence")
|
||||
known: set[str] = set()
|
||||
clean_sources = []
|
||||
for source in sources:
|
||||
if (not isinstance(source, Mapping) or not isinstance(source.get("id"), str)
|
||||
or not source["id"] or source["id"] in known
|
||||
or not isinstance(source.get("text"), str) or not source["text"].strip()
|
||||
or len(source["text"]) > 4000
|
||||
or source.get("role") not in {"doctor", "patient", "unknown"}
|
||||
or isinstance(source.get("timestamp_ms"), bool)
|
||||
or not isinstance(source.get("timestamp_ms"), int) or source["timestamp_ms"] < 0):
|
||||
raise ValueError("invalid source")
|
||||
known.add(source["id"])
|
||||
clean_sources.append({key: source.get(key) for key in ("id", "text", "role", "timestamp_ms")})
|
||||
cleaned: dict[str, Any] = {}
|
||||
for key in ("summary", "questions", "checks", "review"):
|
||||
items = result.get(key, [])
|
||||
if not isinstance(items, list) or len(items) > 6:
|
||||
raise ValueError("invalid items")
|
||||
cleaned[key] = []
|
||||
for item in items:
|
||||
if (not isinstance(item, Mapping) or not isinstance(item.get("text"), str)
|
||||
or not item["text"].strip() or len(item["text"]) > (4020 if key == "summary" else 600)
|
||||
or not isinstance(item.get("evidence_ids"), list)
|
||||
or not 1 <= len(item["evidence_ids"]) <= 8
|
||||
or any(not isinstance(s, str) or s not in known for s in item["evidence_ids"])
|
||||
or len(set(item["evidence_ids"])) != len(item["evidence_ids"])):
|
||||
raise ValueError("invalid cited item")
|
||||
reason = item.get("reason", "")
|
||||
if not isinstance(reason, str) or len(reason) > 600:
|
||||
raise ValueError("invalid reason")
|
||||
cleaned[key].append({"text": item["text"], "reason": reason,
|
||||
"evidence_ids": list(item["evidence_ids"])})
|
||||
count = context.get("segment_count")
|
||||
through = context.get("through_timestamp_ms")
|
||||
if (isinstance(count, bool) or not isinstance(count, int) or count < 1
|
||||
or isinstance(through, bool) or not isinstance(through, (int, float))
|
||||
or not math.isfinite(through) or through < 0
|
||||
or context.get("transcription_status") not in {"running", "completed", "partial"}):
|
||||
raise ValueError("invalid revision metadata")
|
||||
return {**cleaned, "sources": clean_sources, "revision": context["revision"], "analysisScope": scope,
|
||||
"segmentCount": count, "throughTimestampMs": through,
|
||||
"transcriptionStatus": context.get("transcription_status", "partial")}
|
||||
|
||||
def _run(self, job: _Job) -> None:
|
||||
events = None
|
||||
success = False
|
||||
try:
|
||||
if job.cancelled.is_set():
|
||||
return
|
||||
events = self.repository.stream_video_ai(
|
||||
self.diagnosis_id, call_record_id=job.call_id, transcription_session_id=job.session_id,
|
||||
task=job.task, request_id=job.request_id, cancelled=job.cancelled.is_set,
|
||||
)
|
||||
for event in events:
|
||||
with self._lock:
|
||||
if not self._current(job):
|
||||
return
|
||||
if event.get("event") in {"start", "progress"}:
|
||||
self._publish(message=str(event.get("message") or "正在分析本次对话…")[:200])
|
||||
elif event.get("event") in {"live_update", "done"}:
|
||||
result = self._validated_result(job, event)
|
||||
if job.revision and job.revision != result["revision"]:
|
||||
raise ValueError("revision changed inside a single snapshot")
|
||||
if job.analysis_scope is not None and job.analysis_scope != result["analysisScope"]:
|
||||
raise ValueError("analysis scope changed inside a single snapshot")
|
||||
job.revision = result["revision"]
|
||||
job.analysis_scope = result["analysisScope"]
|
||||
# Preserve a newer native completion status while an older
|
||||
# in-flight snapshot still reports running.
|
||||
if self._state["transcriptionStatus"] in {"completed", "partial", "failed"}:
|
||||
result["transcriptionStatus"] = self._state["transcriptionStatus"]
|
||||
complete = event.get("event") == "done"
|
||||
duration = self._elapsed(job)
|
||||
if job.first_result_ms is None and any(
|
||||
result[key] for key in ("summary", "questions", "checks", "review")
|
||||
):
|
||||
job.first_result_ms = duration
|
||||
self._displayed_dirty = job.dirty
|
||||
self._publish(**result, busy=not complete,
|
||||
phase="ready" if complete else "analyzing", error="", errorCode="",
|
||||
elapsedMs=duration,
|
||||
firstResultMs=job.first_result_ms,
|
||||
lastDurationMs=duration if complete else self._state["lastDurationMs"],
|
||||
message="已更新,请对照原话复核。" if complete
|
||||
else "已显示可核对的建议,其余内容仍在整理。")
|
||||
if complete:
|
||||
success = True
|
||||
return
|
||||
if not job.cancelled.is_set():
|
||||
raise ApiProtocolError("incomplete stream")
|
||||
except Exception as error:
|
||||
with self._lock:
|
||||
if self._current(job):
|
||||
code, message = _failure_details(error)
|
||||
self._publish(busy=False, phase="error", error=message, errorCode=code,
|
||||
elapsedMs=self._elapsed(job), lastDurationMs=self._elapsed(job),
|
||||
message=("已显示的建议仍可核对,本次分析尚未全部完成。"
|
||||
if job.first_result_ms is not None else
|
||||
"保留上次结果;新内容尚未分析完成。" if any(
|
||||
self._state[key] for key in ("summary", "questions", "checks", "review")
|
||||
) else
|
||||
"本次暂未生成可用建议,可点击重新生成。"))
|
||||
# Log categories/timing only, never response text or patient details.
|
||||
_LOGGER.warning("video_ai_failed code=%s type=%s duration_ms=%d",
|
||||
code, type(error).__name__, self._elapsed(job))
|
||||
finally:
|
||||
if events is not None and callable(getattr(events, "close", None)):
|
||||
with suppress(Exception):
|
||||
events.close()
|
||||
with self._lock:
|
||||
if not success:
|
||||
self._send_cancel(job)
|
||||
if self._running is job:
|
||||
self._running = None
|
||||
_SLOTS.release()
|
||||
if success:
|
||||
_LOGGER.info("video_ai_completed duration_ms=%d first_result_ms=%s",
|
||||
self._elapsed(job), job.first_result_ms)
|
||||
|
||||
def _cancel(self) -> None:
|
||||
if self._running is not None:
|
||||
self._running.cancelled.set()
|
||||
self._send_cancel(self._running)
|
||||
|
||||
def _send_cancel(self, job: _Job) -> None:
|
||||
if job.cancel_sent or not _CANCEL_SLOTS.acquire(blocking=False):
|
||||
return
|
||||
job.cancel_sent = True
|
||||
|
||||
def cancel() -> None:
|
||||
try:
|
||||
self.repository.cancel_diagnosis_ai(self.diagnosis_id, job.request_id)
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
_CANCEL_SLOTS.release()
|
||||
try:
|
||||
Thread(target=cancel, name="video-ai-cancel", daemon=True).start()
|
||||
except RuntimeError:
|
||||
_CANCEL_SLOTS.release()
|
||||
|
||||
def close(self) -> None:
|
||||
with self._lock:
|
||||
self._closed = True
|
||||
self._cancel()
|
||||
self._mailbox = None
|
||||
|
||||
def wait(self, timeout: float = 1.0) -> bool:
|
||||
if self._worker is not None:
|
||||
self._worker.join(max(0, min(timeout, 5)))
|
||||
return self._worker is None or not self._worker.is_alive()
|
||||
@@ -1,446 +0,0 @@
|
||||
"""Bounded, in-memory speech recognition using an explicitly installed local model.
|
||||
|
||||
This module has no dependency on Qt, the recording queue, or the call lifecycle.
|
||||
Callbacks run on one daemon worker and must only enqueue work (for example, emit
|
||||
a Qt signal). Runtime code never downloads a model or sends audio to a service.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
import importlib.util
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import threading
|
||||
from collections import deque
|
||||
from collections.abc import Callable
|
||||
from contextlib import suppress
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any, Protocol
|
||||
|
||||
from platformdirs import user_data_path
|
||||
|
||||
from ..core.transcript_text import simplified_transcript
|
||||
|
||||
SAMPLE_RATE = 16_000
|
||||
MAX_CHUNK_SECONDS = 12
|
||||
MAX_PCM_BYTES = SAMPLE_RATE * 2 * MAX_CHUNK_SECONDS
|
||||
MAX_BASE64_CHARS = ((MAX_PCM_BYTES + 2) // 3) * 4
|
||||
MAX_SEQUENCE = 2_147_483_647
|
||||
MAX_TIMESTAMP_MS = 253_402_300_799_999
|
||||
MAX_TRANSCRIPT_CHARS = 4_000
|
||||
_SESSION_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}\Z")
|
||||
_REQUIRED_FILES = ("model.bin", "config.json", "tokenizer.json")
|
||||
_DEPENDENCIES = ("faster_whisper", "numpy", "ctranslate2", "onnxruntime", "opencc")
|
||||
_MESSAGES = {
|
||||
"model_missing": "本地语音模型未安装或文件不完整,请先运行本地转写安装工具。",
|
||||
"dependency_missing": "本地转写运行库未安装,请先安装本地转写依赖。",
|
||||
"dependency_unavailable": "本地转写运行库无法加载,请检查安装包及系统运行库。",
|
||||
"model_load_failed": "本地语音模型加载失败,请检查模型文件和本机运行环境。",
|
||||
"conversion_unavailable": "简体转换字典无法加载,请修复本地转写安装。",
|
||||
"invalid_audio": "本地转写音频格式无效,需要最长 12 秒的单声道 16 kHz PCM16 音频。",
|
||||
"invalid_metadata": "本地转写音频的角色、序号或时间戳无效。",
|
||||
"sequence_out_of_order": "本地转写音频序号重复或倒序,该片段未被接受。",
|
||||
"sequence_gap": "本地转写检测到音频片段缺失,转写结果可能不完整。",
|
||||
"overloaded": "本地转写处理速度不足,部分音频片段未转写;通话和录音继续。",
|
||||
"transcription_failed": "本地音频片段转写失败,结果可能不完整;通话和录音继续。",
|
||||
}
|
||||
|
||||
|
||||
def default_model_path() -> Path:
|
||||
"""Return the model directory without creating it or accessing the network."""
|
||||
override = os.getenv("DOCTOR_ASR_MODEL_PATH", "").strip()
|
||||
if override:
|
||||
return Path(override).expanduser().resolve()
|
||||
bundle = Path(getattr(sys, "_MEIPASS", Path(__file__).resolve().parents[3]))
|
||||
bundled_model = bundle / "resources" / "local-asr" / "model"
|
||||
if bundled_model.is_dir():
|
||||
return bundled_model
|
||||
return (
|
||||
user_data_path("ZhenyangDoctorWorkstation", appauthor="ZhenYangTang")
|
||||
/ "local-asr"
|
||||
/ "model"
|
||||
)
|
||||
|
||||
|
||||
def _missing_model_files(path: Path) -> list[str]:
|
||||
def exists(name: str) -> bool:
|
||||
try:
|
||||
file = path / name
|
||||
return file.is_file() and file.stat().st_size > 0
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
missing = [name for name in _REQUIRED_FILES if not exists(name)]
|
||||
if not any(exists(name) for name in ("vocabulary.txt", "vocabulary.json")):
|
||||
missing.append("vocabulary.txt or vocabulary.json")
|
||||
return missing
|
||||
|
||||
|
||||
def local_transcription_readiness(model_path: Path | str | None = None) -> dict[str, Any]:
|
||||
"""Cheap installation preflight; ``available`` does not claim a model has loaded."""
|
||||
path = Path(model_path).expanduser().resolve() if model_path else default_model_path()
|
||||
missing_dependencies = []
|
||||
for name in _DEPENDENCIES:
|
||||
try:
|
||||
available = importlib.util.find_spec(name) is not None
|
||||
except (ImportError, ValueError):
|
||||
available = False
|
||||
if not available:
|
||||
missing_dependencies.append(name)
|
||||
missing_files = _missing_model_files(path)
|
||||
code = (
|
||||
"model_missing" if missing_files else "dependency_missing" if missing_dependencies else ""
|
||||
)
|
||||
return {
|
||||
"available": not (missing_files or missing_dependencies),
|
||||
"modelPath": str(path),
|
||||
"missingDependencies": missing_dependencies,
|
||||
"missingFiles": missing_files,
|
||||
"code": code,
|
||||
"message": _MESSAGES.get(code, "本地转写文件检查通过,启动后将加载模型。"),
|
||||
}
|
||||
|
||||
|
||||
class LocalTranscriptionError(RuntimeError):
|
||||
"""A fixed, patient-data-free error suitable for displaying in the UI."""
|
||||
|
||||
def __init__(self, code: str) -> None:
|
||||
self.code = code if code in _MESSAGES else "transcription_failed"
|
||||
super().__init__(_MESSAGES[self.code])
|
||||
|
||||
|
||||
class SpeechEngine(Protocol):
|
||||
def transcribe(self, pcm: bytes) -> str:
|
||||
"""Return verbatim recognized text for mono, little-endian PCM16 at 16 kHz."""
|
||||
|
||||
|
||||
class FasterWhisperEngine:
|
||||
"""CPU/int8 recognition. Construct only on a background worker or setup CLI."""
|
||||
|
||||
def __init__(self, model_path: Path | str | None = None) -> None:
|
||||
path = Path(model_path).expanduser().resolve() if model_path else default_model_path()
|
||||
# In particular, require tokenizer.json: upstream may otherwise fetch a
|
||||
# tokenizer even when WhisperModel(local_files_only=True) is requested.
|
||||
if _missing_model_files(path):
|
||||
raise LocalTranscriptionError("model_missing")
|
||||
try:
|
||||
import numpy as np
|
||||
from faster_whisper import WhisperModel
|
||||
from faster_whisper.vad import get_vad_model
|
||||
except ModuleNotFoundError:
|
||||
raise LocalTranscriptionError("dependency_missing") from None
|
||||
except (ImportError, OSError):
|
||||
raise LocalTranscriptionError("dependency_unavailable") from None
|
||||
self._np = np
|
||||
try:
|
||||
# Load local dictionaries before ready, so a broken/frozen install
|
||||
# cannot claim successful ASR and then fail on its first sentence.
|
||||
simplified_transcript("")
|
||||
except ImportError:
|
||||
raise LocalTranscriptionError("dependency_missing") from None
|
||||
except Exception:
|
||||
raise LocalTranscriptionError("conversion_unavailable") from None
|
||||
try:
|
||||
self._model = WhisperModel(
|
||||
str(path),
|
||||
device="cpu",
|
||||
compute_type="int8",
|
||||
cpu_threads=min(4, max(1, (os.cpu_count() or 2) // 2)),
|
||||
num_workers=1,
|
||||
local_files_only=True,
|
||||
)
|
||||
# Silero's ONNX asset ships inside faster-whisper; preflight it so
|
||||
# a packaged application cannot report ready with a missing VAD.
|
||||
get_vad_model()
|
||||
except Exception:
|
||||
raise LocalTranscriptionError("model_load_failed") from None
|
||||
|
||||
def transcribe(self, pcm: bytes) -> str:
|
||||
if not pcm or len(pcm) % 2 or len(pcm) > MAX_PCM_BYTES:
|
||||
raise LocalTranscriptionError("invalid_audio")
|
||||
if not any(pcm):
|
||||
return ""
|
||||
audio = self._np.frombuffer(pcm, dtype="<i2").astype(self._np.float32) / 32768.0
|
||||
segments, _ = self._model.transcribe(
|
||||
audio,
|
||||
language="zh",
|
||||
task="transcribe",
|
||||
beam_size=5,
|
||||
temperature=0.0,
|
||||
condition_on_previous_text=False,
|
||||
vad_filter=True,
|
||||
vad_parameters={
|
||||
"min_speech_duration_ms": 0,
|
||||
"min_silence_duration_ms": 500,
|
||||
"speech_pad_ms": 400,
|
||||
},
|
||||
)
|
||||
# Iterating is essential: faster-whisper returns a lazy generator. Do
|
||||
# not rewrite numbers, units, negations, repetitions, or short answers.
|
||||
return "".join(segment.text for segment in segments).strip()
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class _Chunk:
|
||||
role: str
|
||||
sequence: int
|
||||
timestamp_ms: int
|
||||
pcm: bytes
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class _Session:
|
||||
id: str
|
||||
initialized: bool = False
|
||||
stopping: bool = False
|
||||
stopped: bool = False
|
||||
partial: bool = False
|
||||
last_sequence: dict[str, int] = field(default_factory=dict)
|
||||
chunks: deque[_Chunk] = field(default_factory=deque)
|
||||
errors: deque[str] = field(default_factory=deque)
|
||||
reported_errors: set[str] = field(default_factory=set)
|
||||
|
||||
|
||||
class LocalTranscriptionController:
|
||||
"""One bounded daemon worker, isolated by session object identity.
|
||||
|
||||
``start`` accepts a new session, replacing queued old work. ``submit`` only
|
||||
acknowledges enqueueing, while ``ready`` confirms successful model loading.
|
||||
``stop`` rejects further submissions and drains accepted chunks in order.
|
||||
``close`` cancels immediately without waiting for native inference. No
|
||||
callbacks from an old generation occur after start/close returns.
|
||||
|
||||
The callback must be quick, thread-safe, and must not join/wait for another
|
||||
thread that is calling this controller. It is invoked under a reentrant
|
||||
lock, which makes close/session replacement atomic with callback delivery.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
on_event: Callable[[dict[str, Any]], None],
|
||||
engine_factory: Callable[[], SpeechEngine] | None = None,
|
||||
*,
|
||||
max_pending_chunks: int = 12,
|
||||
) -> None:
|
||||
if type(max_pending_chunks) is not int or not 1 <= max_pending_chunks <= 64:
|
||||
raise ValueError("max_pending_chunks must be an integer between 1 and 64")
|
||||
self._on_event = on_event
|
||||
self._engine_factory = engine_factory or FasterWhisperEngine
|
||||
self._max_pending_chunks = max_pending_chunks
|
||||
self._condition = threading.Condition(threading.RLock())
|
||||
self._session: _Session | None = None
|
||||
self._engine: SpeechEngine | None = None
|
||||
self._closed = False
|
||||
self._worker: threading.Thread | None = None
|
||||
|
||||
def start(self, session_id: str) -> bool:
|
||||
if not isinstance(session_id, str) or not _SESSION_ID.fullmatch(session_id):
|
||||
return False
|
||||
with self._condition:
|
||||
if self._closed:
|
||||
return False
|
||||
if self._session and self._session.id == session_id:
|
||||
return not (self._session.stopping or self._session.stopped)
|
||||
if self._session:
|
||||
self._session.chunks.clear()
|
||||
self._session.errors.clear()
|
||||
self._session = _Session(session_id)
|
||||
if self._worker is None:
|
||||
self._worker = threading.Thread(
|
||||
target=self._run, name="doctor-local-asr", daemon=True
|
||||
)
|
||||
self._worker.start()
|
||||
self._condition.notify_all()
|
||||
return True
|
||||
|
||||
def submit(
|
||||
self,
|
||||
session_id: str,
|
||||
role: str,
|
||||
sequence: int,
|
||||
timestamp_ms: int,
|
||||
pcm_base64: str,
|
||||
) -> bool:
|
||||
with self._condition:
|
||||
session = self._session
|
||||
if (
|
||||
self._closed
|
||||
or session is None
|
||||
or session.id != session_id
|
||||
or session.stopping
|
||||
or session.stopped
|
||||
):
|
||||
return False
|
||||
if (
|
||||
role not in ("doctor", "patient")
|
||||
or type(sequence) is not int
|
||||
or not 0 <= sequence <= MAX_SEQUENCE
|
||||
or type(timestamp_ms) is not int
|
||||
or not 0 < timestamp_ms <= MAX_TIMESTAMP_MS
|
||||
):
|
||||
self._error_locked(session, "invalid_metadata")
|
||||
return False
|
||||
if (
|
||||
not isinstance(pcm_base64, str)
|
||||
or not pcm_base64
|
||||
or len(pcm_base64) > MAX_BASE64_CHARS
|
||||
):
|
||||
self._error_locked(session, "invalid_audio")
|
||||
return False
|
||||
try:
|
||||
pcm = base64.b64decode(pcm_base64, validate=True)
|
||||
except (ValueError, binascii.Error):
|
||||
self._error_locked(session, "invalid_audio")
|
||||
return False
|
||||
if not pcm or len(pcm) % 2 or len(pcm) > MAX_PCM_BYTES:
|
||||
self._error_locked(session, "invalid_audio")
|
||||
return False
|
||||
previous = session.last_sequence.get(role)
|
||||
if previous is not None and sequence <= previous:
|
||||
self._error_locked(session, "sequence_out_of_order")
|
||||
return False
|
||||
if previous is not None and sequence != previous + 1:
|
||||
self._error_locked(session, "sequence_gap")
|
||||
session.last_sequence[role] = sequence
|
||||
if len(session.chunks) >= self._max_pending_chunks:
|
||||
self._error_locked(session, "overloaded")
|
||||
return False
|
||||
session.chunks.append(_Chunk(role, sequence, timestamp_ms, pcm))
|
||||
self._condition.notify_all()
|
||||
return True
|
||||
|
||||
def stop(self, session_id: str) -> bool:
|
||||
with self._condition:
|
||||
session = self._session
|
||||
if self._closed or session is None or session.id != session_id:
|
||||
return False
|
||||
session.stopping = True
|
||||
self._condition.notify_all()
|
||||
return True
|
||||
|
||||
def close(self) -> None:
|
||||
with self._condition:
|
||||
self._closed = True
|
||||
if self._session:
|
||||
self._session.chunks.clear()
|
||||
self._session.errors.clear()
|
||||
self._session = None
|
||||
self._condition.notify_all()
|
||||
|
||||
def _error_locked(self, session: _Session, code: str) -> None:
|
||||
session.partial = True
|
||||
# At most one pending/report per fixed error code, even when the browser
|
||||
# continues submitting into an overloaded queue. No unbounded UI queue.
|
||||
if code not in session.reported_errors:
|
||||
session.reported_errors.add(code)
|
||||
session.errors.append(code)
|
||||
self._condition.notify_all()
|
||||
|
||||
def _emit(self, session: _Session, event: dict[str, Any]) -> None:
|
||||
with self._condition:
|
||||
if self._closed or self._session is not session:
|
||||
return
|
||||
# A detached UI must not kill the worker or expose transcript
|
||||
# contents through exception logging.
|
||||
with suppress(Exception):
|
||||
self._on_event({"sessionId": session.id, **event})
|
||||
|
||||
def _initialize(self, session: _Session) -> None:
|
||||
try:
|
||||
if self._engine is None:
|
||||
self._engine = self._engine_factory()
|
||||
except Exception as error:
|
||||
code = error.code if isinstance(error, LocalTranscriptionError) else "model_load_failed"
|
||||
with self._condition:
|
||||
if self._closed or self._session is not session:
|
||||
return
|
||||
session.initialized = True
|
||||
session.stopping = True
|
||||
session.chunks.clear()
|
||||
self._error_locked(session, code)
|
||||
return
|
||||
with self._condition:
|
||||
if self._closed or self._session is not session:
|
||||
return
|
||||
session.initialized = True
|
||||
if not session.stopping:
|
||||
self._emit(session, {"type": "ready"})
|
||||
|
||||
def _transcribe(self, session: _Session, chunk: _Chunk) -> None:
|
||||
try:
|
||||
# Reject only exact digital silence here. VAD in the real engine
|
||||
# handles room noise without an amplitude cutoff that loses quiet
|
||||
# numerals or one-word negations.
|
||||
if not any(chunk.pcm):
|
||||
return
|
||||
assert self._engine is not None
|
||||
text = self._engine.transcribe(chunk.pcm)
|
||||
if not isinstance(text, str) or len(text) > MAX_TRANSCRIPT_CHARS:
|
||||
raise LocalTranscriptionError("transcription_failed")
|
||||
# Normalize before persistence and captions, so AI evidence and the
|
||||
# doctor's visible transcript refer to the exact same text.
|
||||
text = simplified_transcript(text.strip())
|
||||
if text:
|
||||
self._emit(
|
||||
session,
|
||||
{
|
||||
"type": "segment",
|
||||
"segmentId": f"{session.id}:{chunk.role}:{chunk.sequence}",
|
||||
"role": chunk.role,
|
||||
"text": text,
|
||||
"timestamp": chunk.timestamp_ms,
|
||||
"isCompleted": True,
|
||||
},
|
||||
)
|
||||
except Exception:
|
||||
with self._condition:
|
||||
if not self._closed and self._session is session:
|
||||
self._error_locked(session, "transcription_failed")
|
||||
|
||||
def _run(self) -> None:
|
||||
try:
|
||||
while True:
|
||||
with self._condition:
|
||||
while True:
|
||||
if self._closed:
|
||||
return
|
||||
session = self._session
|
||||
if session is not None and not session.stopped:
|
||||
if session.errors:
|
||||
action, payload = "error", session.errors.popleft()
|
||||
break
|
||||
if not session.initialized:
|
||||
action, payload = "initialize", None
|
||||
break
|
||||
if session.chunks:
|
||||
action, payload = "chunk", session.chunks.popleft()
|
||||
break
|
||||
if session.stopping:
|
||||
session.stopped = True
|
||||
action, payload = "stopped", None
|
||||
break
|
||||
self._condition.wait()
|
||||
if action == "initialize":
|
||||
self._initialize(session)
|
||||
elif action == "chunk":
|
||||
self._transcribe(session, payload)
|
||||
payload = None # Release raw PCM before waiting for work.
|
||||
elif action == "error":
|
||||
self._emit(
|
||||
session,
|
||||
{"type": "error", "code": payload, "message": _MESSAGES[payload]},
|
||||
)
|
||||
else:
|
||||
self._emit(
|
||||
session,
|
||||
{
|
||||
"type": "stopped",
|
||||
"status": "partial" if session.partial else "completed",
|
||||
},
|
||||
)
|
||||
finally:
|
||||
self._engine = None
|
||||
@@ -1,124 +0,0 @@
|
||||
"""Capture the rendered call region without accessing the rest of the desktop."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import math
|
||||
from collections.abc import Mapping
|
||||
from typing import Any
|
||||
|
||||
|
||||
class ScreenshotPreviewSize:
|
||||
"""Temporarily give a compact call the same space as a normal preview."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._state: tuple[Any, Any, Any] | None = None
|
||||
|
||||
def open(self, window: Any, target: Any = None) -> None:
|
||||
from PySide6.QtCore import QRect
|
||||
|
||||
if self._state is not None or window.isMaximized() or window.isFullScreen():
|
||||
return
|
||||
screen = window.screen()
|
||||
if screen is None:
|
||||
return
|
||||
available = screen.availableGeometry().adjusted(24, 24, -24, -24)
|
||||
if available.isEmpty():
|
||||
return
|
||||
original = window.geometry()
|
||||
width = min(available.width(), max(original.width(), target.width() if target else 1120))
|
||||
height = min(available.height(), max(original.height(), target.height() if target else 760))
|
||||
if original.width() >= width and original.height() >= height:
|
||||
return
|
||||
expanded = QRect(
|
||||
available.x() + (available.width() - width) // 2,
|
||||
available.y() + (available.height() - height) // 2,
|
||||
width,
|
||||
height,
|
||||
)
|
||||
window.setGeometry(expanded)
|
||||
self._state = (original, window.geometry(), window.property("doctorSkipOpenGeometry"))
|
||||
|
||||
def restore(self, window: Any) -> None:
|
||||
state, self._state = self._state, None
|
||||
if state is None:
|
||||
return
|
||||
original, expanded, compact_flag = state
|
||||
# A diagnosis closing or a manual resize takes priority over this temporary size.
|
||||
if (
|
||||
window.isMaximized()
|
||||
or window.isFullScreen()
|
||||
or window.geometry() != expanded
|
||||
or window.property("doctorSkipOpenGeometry") != compact_flag
|
||||
):
|
||||
return
|
||||
window.setGeometry(original)
|
||||
|
||||
|
||||
def capture_view_region(web_view: Any, region: Mapping[str, Any]) -> str:
|
||||
"""Map CSS viewport coordinates to Qt logical pixels; retain composited video."""
|
||||
|
||||
from PySide6.QtCore import QBuffer, QByteArray, QIODevice, QRect, Qt
|
||||
|
||||
values: dict[str, float] = {}
|
||||
for key in ("x", "y", "width", "height", "viewportWidth", "viewportHeight"):
|
||||
value = region.get(key)
|
||||
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
||||
raise ValueError("截屏区域无效,请重试。")
|
||||
try:
|
||||
value = float(value)
|
||||
except OverflowError as error:
|
||||
raise ValueError("截屏区域无效,请重试。") from error
|
||||
if not math.isfinite(value):
|
||||
raise ValueError("截屏区域无效,请重试。")
|
||||
values[key] = value
|
||||
|
||||
viewport_width = values["viewportWidth"]
|
||||
viewport_height = values["viewportHeight"]
|
||||
if min(viewport_width, viewport_height, values["width"], values["height"]) <= 0:
|
||||
raise ValueError("视频区域尚未显示,请稍后重试。")
|
||||
left = max(0.0, values["x"])
|
||||
top = max(0.0, values["y"])
|
||||
right = min(viewport_width, values["x"] + values["width"])
|
||||
bottom = min(viewport_height, values["y"] + values["height"])
|
||||
if right <= left or bottom <= top:
|
||||
raise ValueError("视频区域尚未显示,请稍后重试。")
|
||||
|
||||
zoom = web_view.zoomFactor()
|
||||
tolerance = max(2.0, 2 * zoom)
|
||||
if (
|
||||
abs(viewport_width * zoom - web_view.width()) > tolerance
|
||||
or abs(viewport_height * zoom - web_view.height()) > tolerance
|
||||
):
|
||||
raise ValueError("视频窗口尺寸已变化,请重新截屏。")
|
||||
|
||||
# QWebEngine's zoom and Windows display scaling are independent. grab() takes
|
||||
# widget logical coordinates and returns an image at the widget's pixel ratio.
|
||||
scale_x = web_view.width() / viewport_width
|
||||
scale_y = web_view.height() / viewport_height
|
||||
x = math.ceil(left * scale_x)
|
||||
y = math.ceil(top * scale_y)
|
||||
width = math.floor(right * scale_x) - x
|
||||
height = math.floor(bottom * scale_y) - y
|
||||
if width <= 0 or height <= 0:
|
||||
raise ValueError("视频区域尚未显示,请稍后重试。")
|
||||
rect = QRect(x, y, width, height).intersected(web_view.rect())
|
||||
if rect.isEmpty():
|
||||
raise ValueError("视频区域尚未显示,请稍后重试。")
|
||||
|
||||
image = web_view.grab(rect).toImage()
|
||||
if image.isNull():
|
||||
raise ValueError("截屏失败,请稍后重试。")
|
||||
if max(image.width(), image.height()) > 1920:
|
||||
image = image.scaled(
|
||||
1920, 1920,
|
||||
Qt.AspectRatioMode.KeepAspectRatio,
|
||||
Qt.TransformationMode.SmoothTransformation,
|
||||
)
|
||||
data = QByteArray()
|
||||
buffer = QBuffer(data)
|
||||
buffer.open(QIODevice.OpenModeFlag.WriteOnly)
|
||||
if not image.save(buffer, "JPEG", 90):
|
||||
raise ValueError("截屏图片生成失败,请重试。")
|
||||
buffer.close()
|
||||
return "data:image/jpeg;base64," + base64.b64encode(bytes(data)).decode("ascii")
|
||||
@@ -11,7 +11,6 @@ import base64
|
||||
import binascii
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
import sqlite3
|
||||
@@ -29,15 +28,12 @@ from ..services.local_audio_queue import (
|
||||
LocalAudioUploadManager,
|
||||
get_local_audio_upload_manager,
|
||||
)
|
||||
from .im_ai import ImAiController
|
||||
from .launcher import (
|
||||
VideoCallRequest,
|
||||
VideoTicketError,
|
||||
require_supported_backend,
|
||||
)
|
||||
from .lifecycle import OrderedCallLifecycle, normalize_transcript_segment
|
||||
from .live_ai import LiveAiController
|
||||
from .screenshot import ScreenshotPreviewSize, capture_view_region
|
||||
from .lifecycle import OrderedCallLifecycle
|
||||
from .security import TrustedDocumentError, TrustedDocumentPolicy
|
||||
|
||||
try: # Optional by design: core-only builds must still import this module.
|
||||
@@ -192,29 +188,9 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
return None
|
||||
|
||||
class _QtVideoBridge(QObject): # type: ignore[misc, valid-type]
|
||||
def __init__(
|
||||
self,
|
||||
callback: Callable[[Mapping[str, Any]], None],
|
||||
capture_screenshot: Callable[[Mapping[str, Any]], str],
|
||||
) -> None:
|
||||
def __init__(self, callback: Callable[[Mapping[str, Any]], None]) -> None:
|
||||
super().__init__()
|
||||
self._callback = callback
|
||||
self._capture_screenshot = capture_screenshot
|
||||
|
||||
@Slot(str, result=str) # type: ignore[misc]
|
||||
def captureScreenshot(self, payload: str) -> str: # noqa: N802 - Qt bridge API
|
||||
"""Return a local preview only; persistence still needs saveScreenshot."""
|
||||
|
||||
try:
|
||||
if not isinstance(payload, str) or len(payload) > 2048:
|
||||
raise ValueError("截屏区域无效,请重试。")
|
||||
region = json.loads(payload)
|
||||
if not isinstance(region, Mapping):
|
||||
raise ValueError("截屏区域无效,请重试。")
|
||||
result = {"dataUrl": self._capture_screenshot(region)}
|
||||
except (ValueError, TypeError, RuntimeError):
|
||||
result = {"error": "无法截取当前视频画面,请稍后重试。"}
|
||||
return json.dumps(result, ensure_ascii=False)
|
||||
|
||||
@Slot(str) # type: ignore[misc]
|
||||
def notify(self, payload: str) -> None:
|
||||
@@ -298,16 +274,6 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
}
|
||||
)
|
||||
|
||||
@Slot(str, str, int, float, str) # type: ignore[misc]
|
||||
def appendLocalTranscriptionChunk( # noqa: N802
|
||||
self, session_id: str, role: str, sequence: int, timestamp: float, encoded: str
|
||||
) -> None:
|
||||
if len(encoded) > 512_000:
|
||||
return
|
||||
self._callback({"source": "doctor-call", "event": "local-transcription-chunk",
|
||||
"sessionId": session_id, "role": role, "sequence": sequence,
|
||||
"timestamp": timestamp, "data": encoded})
|
||||
|
||||
class _EmbeddedVideoWindow(QMainWindow): # type: ignore[misc, valid-type]
|
||||
status_changed = Signal(str) # type: ignore[misc]
|
||||
call_ended = Signal(str) # type: ignore[misc]
|
||||
@@ -316,8 +282,7 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
_policy_completed = Signal(str, object) # type: ignore[misc]
|
||||
_room_completed = Signal(str, bool, str) # type: ignore[misc]
|
||||
_screenshot_completed = Signal(bool, str) # type: ignore[misc]
|
||||
_transcription_completed = Signal(str, str, str, bool, str, str) # type: ignore[misc]
|
||||
_local_transcription_event = Signal(object) # type: ignore[misc]
|
||||
_transcription_completed = Signal(str, str, str, bool, str) # type: ignore[misc]
|
||||
_local_recording_completed = Signal( # type: ignore[misc]
|
||||
str, str, int, bool, str
|
||||
)
|
||||
@@ -334,8 +299,6 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
patient_name: str = "患者",
|
||||
patient_case: Mapping[str, Any] | None = None,
|
||||
on_open_diagnosis: Callable[[], None] | None = None,
|
||||
can_ai_assistant: bool = False,
|
||||
repository: Any = None,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.request = request
|
||||
@@ -348,7 +311,6 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
self.patient_name = str(patient_name or "患者").strip() or "患者"
|
||||
self.patient_case = dict(patient_case or {})
|
||||
self._on_open_diagnosis = on_open_diagnosis
|
||||
self._on_compact_close: Callable[[], None] | None = None
|
||||
try:
|
||||
self._policy = TrustedDocumentPolicy.from_url(
|
||||
location.url,
|
||||
@@ -365,33 +327,6 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
self._call_cycle_closed = False
|
||||
self._start_requested = False
|
||||
self._shutdown_requested = False
|
||||
self._im_ai = ImAiController(
|
||||
repository,
|
||||
diagnosis_id=request.diagnosis_id,
|
||||
appointment_id=request.appointment_id,
|
||||
doctor_account=request.user_id,
|
||||
enabled=can_ai_assistant is True and self.open_im,
|
||||
)
|
||||
self._im_ai_timer = QTimer(self)
|
||||
self._im_ai_timer.setInterval(60)
|
||||
self._im_ai_timer.timeout.connect(self._flush_im_ai)
|
||||
if self._im_ai.enabled:
|
||||
self._im_ai_timer.start()
|
||||
self._live_ai = LiveAiController(
|
||||
repository, diagnosis_id=request.diagnosis_id, enabled=can_ai_assistant is True,
|
||||
)
|
||||
# The default recognizer is Tencent's existing call transcriber.
|
||||
# Keep local audio recording independent; no local model is loaded.
|
||||
self._local_transcription = None
|
||||
self._asr_session_id = ""
|
||||
self._asr_ready = False
|
||||
self._asr_partial = False
|
||||
self._transcription_final_status = "idle"
|
||||
self._video_ai_timer = QTimer(self)
|
||||
self._video_ai_timer.setInterval(100)
|
||||
self._video_ai_timer.timeout.connect(self._flush_video_ai)
|
||||
self._video_ai_timer.start()
|
||||
self._screenshot_preview_size = ScreenshotPreviewSize()
|
||||
self._local_audio_capture: _LocalAudioCapture | None = None
|
||||
self._local_audio_store: LocalAudioQueueStore | None = None
|
||||
self._local_audio_uploads: LocalAudioUploadManager | None = None
|
||||
@@ -428,9 +363,7 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
self.setCentralWidget(self.web_view)
|
||||
|
||||
self._configure_settings(self._page.settings())
|
||||
self._bridge = _QtVideoBridge(
|
||||
self._handle_bridge_message, self._capture_screenshot_preview
|
||||
)
|
||||
self._bridge = _QtVideoBridge(self._handle_bridge_message)
|
||||
self._channel = QWebChannel(self._page)
|
||||
self._channel.registerObject("qtVideoBridge", self._bridge)
|
||||
self._page.setWebChannel(self._channel)
|
||||
@@ -441,7 +374,6 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
self._room_completed.connect(self._on_room_completed)
|
||||
self._screenshot_completed.connect(self._on_screenshot_completed)
|
||||
self._transcription_completed.connect(self._on_transcription_completed)
|
||||
self._local_transcription_event.connect(self._on_local_transcription)
|
||||
self._local_recording_completed.connect(self._on_local_recording_completed)
|
||||
self.web_view.loadFinished.connect(self._on_load_finished)
|
||||
self.web_view.setUrl(QUrl(self.location.url))
|
||||
@@ -517,7 +449,8 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
"embedded video companion failed to load",
|
||||
extra={"video_call": self.request.safe_log_context()},
|
||||
)
|
||||
self._request_companion_shutdown("page-load-failed")
|
||||
self._close_reason = "page-load-failed"
|
||||
self.close()
|
||||
return
|
||||
|
||||
self._media_active = True
|
||||
@@ -526,7 +459,6 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
"patientName": self.patient_name,
|
||||
"patientCase": self.patient_case,
|
||||
"mode": "chat" if self.open_im else "video",
|
||||
"imAi": self._im_ai.config,
|
||||
}
|
||||
config_json = json.dumps(config, ensure_ascii=True, separators=(",", ":"))
|
||||
script = f"""
|
||||
@@ -567,37 +499,13 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
def _after_injection(self, result: Any) -> None:
|
||||
self._injected = result is not False
|
||||
if not self._injected:
|
||||
self._request_companion_shutdown("bridge-api-missing")
|
||||
return
|
||||
if not self._im_ai_context_is_trusted():
|
||||
return
|
||||
# open() may finish IM login before runJavaScript returns. Only
|
||||
# acknowledge readiness after the native request gate is open.
|
||||
session_id = json.dumps(self._im_ai.session_id, ensure_ascii=True)
|
||||
self._page.runJavaScript(
|
||||
f"window.doctorConsultation?.imAiReady?.({session_id});"
|
||||
)
|
||||
self._close_reason = "bridge-api-missing"
|
||||
self.close()
|
||||
|
||||
def _handle_bridge_message(self, message: Mapping[str, Any]) -> None:
|
||||
if self._closing:
|
||||
return
|
||||
event = str(message.get("event", ""))
|
||||
if event.startswith("local-transcription-"):
|
||||
# An old companion must not start a second recognizer.
|
||||
return
|
||||
if event == "video-ai-action":
|
||||
self._handle_video_assistance_message(message)
|
||||
return
|
||||
if event.startswith("transcription-") and not self._local_transcription_context_is_trusted():
|
||||
return
|
||||
if event in {"im-ai-request", "im-ai-cancel"}:
|
||||
self._handle_im_ai_message(message)
|
||||
return
|
||||
if event == "screenshot-preview":
|
||||
visible = message.get("visible")
|
||||
if isinstance(visible, bool):
|
||||
self._set_screenshot_preview_visible(visible)
|
||||
return
|
||||
if event == "open-diagnosis-request":
|
||||
if self._on_open_diagnosis is not None:
|
||||
QTimer.singleShot(0, self._open_diagnosis_safely)
|
||||
@@ -640,9 +548,6 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
self._abort_local_audio_recording(str(message.get("sessionId") or ""))
|
||||
return
|
||||
if event == "transcription-start-request":
|
||||
if (self._shutdown_requested or not self._start_requested
|
||||
or self._call_cycle_closed or not self.lifecycle.call_record_id):
|
||||
return
|
||||
self._start_transcription(
|
||||
str(message.get("sessionId") or ""),
|
||||
str(message.get("language") or "zh-CN"),
|
||||
@@ -651,22 +556,6 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
if event == "transcription-segment":
|
||||
self._save_transcript_segment(message)
|
||||
return
|
||||
if event == "transcription-ready":
|
||||
session_id = str(message.get("sessionId") or "")
|
||||
if (not self._shutdown_requested and session_id
|
||||
and session_id == str(self.lifecycle.transcription_session_id or "")):
|
||||
self._live_ai.transcription_running(session_id)
|
||||
return
|
||||
if event == "transcription-error":
|
||||
if (str(message.get("sessionId") or "")
|
||||
== str(self.lifecycle.transcription_session_id or "")
|
||||
and self.lifecycle.transcription_session_id):
|
||||
self._asr_partial = True
|
||||
self._live_ai.transcription_error(
|
||||
str(message.get("message") or "腾讯云实时转写未完成,请重试。")[:240],
|
||||
status="failed",
|
||||
)
|
||||
return
|
||||
if event == "transcription-stop":
|
||||
self._finish_transcription(
|
||||
str(message.get("sessionId") or ""),
|
||||
@@ -705,139 +594,6 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
if not self.open_im or self._shutdown_requested:
|
||||
self._close_from_companion("companion-error")
|
||||
|
||||
def _im_ai_context_is_trusted(self) -> bool:
|
||||
return (
|
||||
not self._closing
|
||||
and not self._released
|
||||
and not self._shutdown_requested
|
||||
and self._injected
|
||||
and self._policy.allows_main_document(self._page.url().toString())
|
||||
)
|
||||
|
||||
def _handle_im_ai_message(self, message: Mapping[str, Any]) -> None:
|
||||
if self._im_ai_context_is_trusted():
|
||||
self._im_ai.handle(message)
|
||||
|
||||
def _flush_im_ai(self) -> None:
|
||||
if not self._im_ai_context_is_trusted():
|
||||
return
|
||||
result = self._im_ai.take_result()
|
||||
if result is not None:
|
||||
payload = json.dumps(result, ensure_ascii=True, separators=(",", ":"))
|
||||
self._page.runJavaScript(f"window.doctorConsultation?.imAiResult?.({payload});")
|
||||
|
||||
def _close_im_ai(self) -> None:
|
||||
controller = getattr(self, "_im_ai", None)
|
||||
if controller is not None:
|
||||
controller.close()
|
||||
timer = getattr(self, "_im_ai_timer", None)
|
||||
if timer is not None:
|
||||
timer.stop()
|
||||
|
||||
def _local_transcription_context_is_trusted(self) -> bool:
|
||||
return (not self._closing and not self._released and self._injected
|
||||
and self._policy.allows_main_document(self._page.url().toString()))
|
||||
|
||||
def _handle_video_assistance_message(self, message: Mapping[str, Any]) -> None:
|
||||
if not self._local_transcription_context_is_trusted():
|
||||
return
|
||||
event = message.get("event")
|
||||
if event == "video-ai-action":
|
||||
if not self._shutdown_requested:
|
||||
self._live_ai.handle(str(message.get("action") or ""), message.get("enabled"))
|
||||
return
|
||||
session_id = str(message.get("sessionId") or "")
|
||||
if event == "local-transcription-start":
|
||||
if (self._shutdown_requested or not self._start_requested or self._call_cycle_closed
|
||||
or not self.lifecycle.call_record_id
|
||||
or re.fullmatch(r"[A-Za-z0-9_-]{1,128}", session_id) is None):
|
||||
return
|
||||
existing = str(self.lifecycle.transcription_session_id or "")
|
||||
if existing and existing != session_id:
|
||||
return
|
||||
was_ready = self._asr_session_id == session_id and self._asr_ready
|
||||
if self._asr_session_id != session_id:
|
||||
self._asr_partial = False
|
||||
self._asr_ready = False
|
||||
self._asr_session_id = session_id
|
||||
self._live_ai.transcription_starting()
|
||||
accepted = self._local_transcription.start(session_id)
|
||||
if accepted and was_ready:
|
||||
self._on_local_transcription({"type": "ready", "sessionId": session_id})
|
||||
elif not accepted:
|
||||
self._on_local_transcription({"type": "error", "sessionId": session_id,
|
||||
"message": "本次转写已结束,请重新发起通话。"})
|
||||
elif session_id and session_id == self._asr_session_id:
|
||||
if event == "local-transcription-chunk":
|
||||
if session_id != str(self.lifecycle.transcription_session_id or ""):
|
||||
return
|
||||
timestamp = message.get("timestamp")
|
||||
if (isinstance(timestamp, bool) or not isinstance(timestamp, (int, float))
|
||||
or not math.isfinite(timestamp) or not 0 < timestamp < 2**53):
|
||||
return
|
||||
self._local_transcription.submit(
|
||||
session_id, str(message.get("role") or ""), message.get("sequence"),
|
||||
int(timestamp), str(message.get("data") or ""),
|
||||
)
|
||||
elif event == "local-transcription-stop":
|
||||
self._local_transcription.stop(session_id)
|
||||
|
||||
def _emit_local_transcription(self, event: dict[str, Any]) -> None:
|
||||
with suppress(RuntimeError):
|
||||
self._local_transcription_event.emit(event)
|
||||
|
||||
def _on_local_transcription(self, event: Mapping[str, Any]) -> None:
|
||||
if (not self._local_transcription_context_is_trusted()
|
||||
or event.get("sessionId") != self._asr_session_id):
|
||||
return
|
||||
kind = event.get("type")
|
||||
if kind == "ready":
|
||||
self._asr_ready = True
|
||||
elif kind == "stopped":
|
||||
self._asr_ready = False
|
||||
elif kind == "segment":
|
||||
role = event.get("role")
|
||||
if role not in {"doctor", "patient"}:
|
||||
return
|
||||
self._save_transcript_segment({
|
||||
"sessionId": self._asr_session_id,
|
||||
"segment": {
|
||||
"segment_id": event.get("segmentId"),
|
||||
"speaker_role": role,
|
||||
"speaker_user_id": (self.request.user_id if role == "doctor"
|
||||
else self.request.target_user_id),
|
||||
"timestamp": event.get("timestamp"), "text": event.get("text"),
|
||||
},
|
||||
})
|
||||
elif kind == "error":
|
||||
self._asr_partial = True
|
||||
self._live_ai.transcription_error(
|
||||
str(event.get("message") or "本地转写未完成"),
|
||||
status="partial" if self._asr_ready else "failed",
|
||||
)
|
||||
payload = json.dumps(dict(event), ensure_ascii=True, separators=(",", ":"))
|
||||
self._page.runJavaScript(f"window.doctorConsultation?.localTranscriptionEvent?.({payload});")
|
||||
|
||||
def _flush_video_ai(self) -> None:
|
||||
if not self._local_transcription_context_is_trusted() or self._shutdown_requested:
|
||||
return
|
||||
self._live_ai.tick()
|
||||
state = self._live_ai.take_state()
|
||||
if state is not None:
|
||||
payload = json.dumps(state, ensure_ascii=True, separators=(",", ":"))
|
||||
self._page.runJavaScript(f"window.doctorConsultation?.videoAiState?.({payload});")
|
||||
|
||||
def _close_video_assistance(self, *, close_asr: bool = True) -> None:
|
||||
controller = getattr(self, "_live_ai", None)
|
||||
if controller is not None:
|
||||
controller.close()
|
||||
timer = getattr(self, "_video_ai_timer", None)
|
||||
if timer is not None:
|
||||
timer.stop()
|
||||
controller = getattr(self, "_local_transcription", None)
|
||||
if close_asr and controller is not None:
|
||||
controller.close()
|
||||
|
||||
def _open_diagnosis_safely(self) -> None:
|
||||
if self._closing or self._on_open_diagnosis is None:
|
||||
return
|
||||
@@ -1222,12 +978,6 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
if self._closing or self._shutdown_requested or self._start_requested:
|
||||
return
|
||||
self._prepare_call_cycle()
|
||||
live_ai = getattr(self, "_live_ai", None)
|
||||
if live_ai is not None:
|
||||
live_ai.reset()
|
||||
self._asr_session_id = ""
|
||||
self._asr_ready = False
|
||||
self._asr_partial = False
|
||||
self._start_requested = True
|
||||
try:
|
||||
future = self.lifecycle.start(call_type=call_type)
|
||||
@@ -1237,30 +987,6 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
return
|
||||
future.add_done_callback(self._notify_start_completed)
|
||||
|
||||
def _set_screenshot_preview_visible(self, visible: bool) -> None:
|
||||
if self._closing or self._released:
|
||||
return
|
||||
if not self._policy.allows_main_document(self._page.url().toString()):
|
||||
return
|
||||
if not visible:
|
||||
self.restore_screenshot_preview()
|
||||
return
|
||||
if self._shutdown_requested or not self._media_active:
|
||||
return
|
||||
from ..ui.theme import main_window_target_rect
|
||||
|
||||
self._screenshot_preview_size.open(self, main_window_target_rect(self))
|
||||
|
||||
def restore_screenshot_preview(self) -> None:
|
||||
self._screenshot_preview_size.restore(self)
|
||||
|
||||
def _capture_screenshot_preview(self, region: Mapping[str, Any]) -> str:
|
||||
if self._closing or self._released or self._shutdown_requested or not self._media_active:
|
||||
raise ValueError("视频窗口已关闭。")
|
||||
if not self._policy.allows_main_document(self._page.url().toString()):
|
||||
raise ValueError("视频页面不可用。")
|
||||
return capture_view_region(self.web_view, region)
|
||||
|
||||
def _save_screenshot(self, data_url: str) -> None:
|
||||
prefix = "data:image/jpeg;base64,"
|
||||
if not data_url.startswith(prefix):
|
||||
@@ -1306,7 +1032,6 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
session_id: str,
|
||||
segment_id: str,
|
||||
future: Future[bool],
|
||||
normalized_segment: Mapping[str, Any] | None = None,
|
||||
) -> None:
|
||||
try:
|
||||
succeeded = bool(future.result())
|
||||
@@ -1321,8 +1046,7 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
}.get(operation, "")
|
||||
with suppress(RuntimeError):
|
||||
self._transcription_completed.emit(
|
||||
operation, session_id, segment_id, succeeded, message,
|
||||
json.dumps(normalized_segment if succeeded else None, ensure_ascii=True),
|
||||
operation, session_id, segment_id, succeeded, message
|
||||
)
|
||||
|
||||
def _on_transcription_completed(
|
||||
@@ -1332,47 +1056,16 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
segment_id: str,
|
||||
succeeded: bool,
|
||||
message: str,
|
||||
normalized_segment: str | Mapping[str, Any] | None = None,
|
||||
) -> None:
|
||||
if not self._local_transcription_context_is_trusted():
|
||||
return
|
||||
live_ai = getattr(self, "_live_ai", None)
|
||||
if (live_ai is not None
|
||||
and session_id == str(self.lifecycle.transcription_session_id or "")):
|
||||
if operation == "start" and succeeded:
|
||||
live_ai.bind(int(self.lifecycle.call_record_id), session_id)
|
||||
elif operation == "start":
|
||||
live_ai.transcription_error(message or "转写文字存储未就绪,请重试。", status="failed")
|
||||
elif operation == "segment":
|
||||
if succeeded:
|
||||
live_ai.changed(session_id)
|
||||
else:
|
||||
self._asr_partial = True
|
||||
live_ai.transcription_error("部分对话文字保存失败,分析资料可能不完整。")
|
||||
elif operation == "stop":
|
||||
live_ai.finish(session_id, self._transcription_final_status if succeeded else "partial")
|
||||
payload = json.dumps(str(message)[:200], ensure_ascii=True)
|
||||
state = "true" if succeeded else "false"
|
||||
if isinstance(normalized_segment, str):
|
||||
try:
|
||||
normalized_segment = json.loads(normalized_segment)
|
||||
except (ValueError, TypeError):
|
||||
normalized_segment = None
|
||||
caption = json.dumps(
|
||||
dict(normalized_segment)
|
||||
if succeeded and operation == "segment" and isinstance(normalized_segment, Mapping)
|
||||
else None,
|
||||
ensure_ascii=True,
|
||||
)
|
||||
self._page.runJavaScript(
|
||||
"window.doctorConsultation?.transcriptionResult?.("
|
||||
f"{json.dumps(operation)}, {json.dumps(session_id)}, "
|
||||
f"{json.dumps(segment_id)}, {state}, {payload}, {caption});"
|
||||
f"{json.dumps(segment_id)}, {state}, {payload});"
|
||||
)
|
||||
|
||||
def _start_transcription(self, session_id: str, language: str) -> None:
|
||||
if not self._local_transcription_context_is_trusted() or self._shutdown_requested:
|
||||
return
|
||||
try:
|
||||
future = self.lifecycle.start_transcription(session_id, language=language)
|
||||
except Exception as error:
|
||||
@@ -1380,7 +1073,6 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
"start", session_id, "", False, str(error)[:200]
|
||||
)
|
||||
return
|
||||
self._live_ai.transcription_starting()
|
||||
future.add_done_callback(
|
||||
lambda completed: self._notify_transcription_completed(
|
||||
"start", session_id, "", completed
|
||||
@@ -1388,8 +1080,6 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
)
|
||||
|
||||
def _save_transcript_segment(self, message: Mapping[str, Any]) -> None:
|
||||
if not self._local_transcription_context_is_trusted():
|
||||
return
|
||||
session_id = str(message.get("sessionId") or "").strip()
|
||||
segment = message.get("segment")
|
||||
segment_id = (
|
||||
@@ -1408,44 +1098,25 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
)
|
||||
return
|
||||
try:
|
||||
normalized = normalize_transcript_segment(segment, session_id)
|
||||
speaker = normalized["speaker_user_id"]
|
||||
normalized["speaker_role"] = (
|
||||
"doctor" if speaker == self.request.user_id
|
||||
else "patient" if speaker == self.request.target_user_id
|
||||
else "unknown"
|
||||
)
|
||||
future = self.lifecycle.save_transcript_segment(normalized)
|
||||
future = self.lifecycle.save_transcript_segment(segment)
|
||||
except Exception as error:
|
||||
self._on_transcription_completed(
|
||||
"segment", session_id, segment_id, False, str(error)[:200]
|
||||
)
|
||||
return
|
||||
caption = {
|
||||
"segmentId": normalized["segment_id"],
|
||||
"speakerUserId": normalized["speaker_user_id"],
|
||||
"sourceText": normalized["text"],
|
||||
"timestamp": normalized["timestamp"],
|
||||
"isCompleted": True,
|
||||
}
|
||||
future.add_done_callback(
|
||||
lambda completed: self._notify_transcription_completed(
|
||||
"segment", session_id, segment_id, completed, caption
|
||||
"segment", session_id, segment_id, completed
|
||||
)
|
||||
)
|
||||
|
||||
def _finish_transcription(self, session_id: str, status: str) -> None:
|
||||
if not self._local_transcription_context_is_trusted():
|
||||
return
|
||||
if session_id.strip() != str(self.lifecycle.transcription_session_id or ""):
|
||||
self._on_transcription_completed(
|
||||
"stop", session_id, "", False, "录音会话标识不匹配。"
|
||||
)
|
||||
return
|
||||
try:
|
||||
if getattr(self, "_asr_partial", False):
|
||||
status = "partial"
|
||||
self._transcription_final_status = status
|
||||
future = self.lifecycle.finish_transcription(status=status)
|
||||
except Exception as error:
|
||||
self._on_transcription_completed(
|
||||
@@ -1466,16 +1137,9 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
def hangup(self) -> None:
|
||||
self._request_companion_shutdown("desktop-hangup")
|
||||
|
||||
def set_compact_close_handler(self, callback: Callable[[], None] | None) -> None:
|
||||
"""Let the compact title-bar close return to the same full call window."""
|
||||
|
||||
self._on_compact_close = callback
|
||||
|
||||
def _request_companion_shutdown(self, reason: str) -> None:
|
||||
"""Let MediaRecorder finish and upload before WebEngine is destroyed."""
|
||||
|
||||
_EmbeddedVideoWindow._close_im_ai(self)
|
||||
_EmbeddedVideoWindow._close_video_assistance(self, close_asr=False)
|
||||
self._close_reason = reason
|
||||
if self._closing or self._released:
|
||||
return
|
||||
@@ -1486,7 +1150,6 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
and not self._companion_ended
|
||||
)
|
||||
if not should_wait_for_companion:
|
||||
self._shutdown_requested = True
|
||||
self.close()
|
||||
return
|
||||
if self._shutdown_requested:
|
||||
@@ -1520,9 +1183,6 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
def _begin_shutdown(self) -> None:
|
||||
if self._closing:
|
||||
return
|
||||
_EmbeddedVideoWindow._close_im_ai(self)
|
||||
_EmbeddedVideoWindow._close_video_assistance(self)
|
||||
self._on_compact_close = None
|
||||
self._closing = True
|
||||
self._media_active = False
|
||||
self._shutdown_timer.stop()
|
||||
@@ -1580,16 +1240,6 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
self._profile.deleteLater()
|
||||
|
||||
def closeEvent(self, event: Any) -> None:
|
||||
if (
|
||||
self._on_compact_close is not None
|
||||
and not self._shutdown_requested
|
||||
and not self._companion_ended
|
||||
and not self._closing
|
||||
and not self._released
|
||||
):
|
||||
event.ignore()
|
||||
self._on_compact_close()
|
||||
return
|
||||
if (
|
||||
self._injected
|
||||
and self._start_requested
|
||||
@@ -1623,7 +1273,6 @@ class VideoCallWindow:
|
||||
patient_name: str = "患者",
|
||||
patient_case: Mapping[str, Any] | None = None,
|
||||
on_open_diagnosis: Callable[[], None] | None = None,
|
||||
can_ai_assistant: bool = False,
|
||||
) -> None:
|
||||
del browser_opener # Reserved for a future authenticated handoff implementation.
|
||||
try:
|
||||
@@ -1642,7 +1291,6 @@ class VideoCallWindow:
|
||||
self.open_im = bool(open_im)
|
||||
self.patient_name = str(patient_name or "患者").strip() or "患者"
|
||||
self.patient_case = dict(patient_case or {})
|
||||
self.can_ai_assistant = can_ai_assistant is True
|
||||
self.on_open_diagnosis = on_open_diagnosis
|
||||
self.logger = logger or _LOGGER
|
||||
self.location = resolve_companion_location(
|
||||
@@ -1674,8 +1322,6 @@ class VideoCallWindow:
|
||||
patient_name=self.patient_name,
|
||||
patient_case=self.patient_case,
|
||||
on_open_diagnosis=self.on_open_diagnosis,
|
||||
can_ai_assistant=self.can_ai_assistant,
|
||||
repository=self.repository,
|
||||
)
|
||||
except Exception:
|
||||
self.lifecycle.end("window-open-failed")
|
||||
@@ -1695,7 +1341,7 @@ class VideoCallWindow:
|
||||
|
||||
def close(self) -> None:
|
||||
if self._session is not None:
|
||||
self._session._request_companion_shutdown("window-closed")
|
||||
self._session.close()
|
||||
else:
|
||||
self.lifecycle.end("unopened-session")
|
||||
|
||||
@@ -1721,7 +1367,6 @@ def open_video_call(
|
||||
patient_name: str = "患者",
|
||||
patient_case: Mapping[str, Any] | None = None,
|
||||
on_open_diagnosis: Callable[[], None] | None = None,
|
||||
can_ai_assistant: bool = False,
|
||||
) -> VideoCallWindow:
|
||||
"""Create and immediately open a trusted embedded video window."""
|
||||
|
||||
@@ -1738,7 +1383,6 @@ def open_video_call(
|
||||
patient_name=patient_name,
|
||||
patient_case=patient_case,
|
||||
on_open_diagnosis=on_open_diagnosis,
|
||||
can_ai_assistant=can_ai_assistant,
|
||||
).open()
|
||||
|
||||
|
||||
|
||||
@@ -1,446 +0,0 @@
|
||||
"""Approved SSE bursts paint progressively without extending request lifetime.
|
||||
|
||||
Real offscreen Qt, finite workers and MockTransport only; all data is synthetic.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from time import monotonic, perf_counter
|
||||
from types import SimpleNamespace
|
||||
|
||||
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from PySide6.QtCore import QEvent, QObject, Qt, QThreadPool, QTimer
|
||||
from PySide6.QtTest import QTest
|
||||
from PySide6.QtWidgets import QApplication, QLabel
|
||||
from shiboken6 import isValid
|
||||
|
||||
from doctor_workstation.core import PermissionSet
|
||||
from doctor_workstation.services import ApiClient, RemoteDoctorRepository
|
||||
from doctor_workstation.ui.dialogs import ai_consult as module
|
||||
from doctor_workstation.ui.dialogs.ai_consult_charts import GlucoseReportCard
|
||||
|
||||
SOURCE_KEYS = (
|
||||
"basic_info", "vital_signs", "chief_complaint", "present_illness", "past_history",
|
||||
"other_history", "diagnosis_info", "doctor_image_notes", "doctor_file_notes",
|
||||
"daily_tracking", "prescriptions", "video_consultation_text", "chat",
|
||||
)
|
||||
TOOLS = (
|
||||
("分析病历", "case_analysis", "病历分析", "口渴记录提示需结合现有血糖资料分析,缺少病程不能确立证型。"),
|
||||
("血糖趋势", "glucose_trend", "血糖趋势", "一条血糖只能说明当次情况,不能据此认定连续升降趋势。"),
|
||||
("用药评估", "medication_review", "用药评估", "二甲双胍的既有记录可用于核对治疗,剂量未记不能据此加量。"),
|
||||
("并发症风险", "complication_risk", "并发症风险", "糖尿病史提示筛查价值;未记录筛查不能直接认定已患或排除并发症。"),
|
||||
("生成问诊小结", "summary", "问诊小结", "本次口渴,既往有糖尿病及二甲双胍记录,病程与剂量仍需确认。"),
|
||||
("健康建议", "lifestyle_advice", "健康建议", "可规律分配饮食并记录血糖,活动量需结合现有体能逐步安排。"),
|
||||
)
|
||||
|
||||
|
||||
def receipt():
|
||||
return {"transfer_manifest_final": True, "attachment_count": 0, "items": [],
|
||||
"required_sections": [{"key": key, "availability": "absent", "status": "submitted"}
|
||||
for key in SOURCE_KEYS]}
|
||||
|
||||
|
||||
def report():
|
||||
original = [{"record_date": "2026-01-01", "role": "患者", "content": f"第 {i} 类合成来源原文 🩺"}
|
||||
for i in range(13)]
|
||||
text = "## 合成判断\n\n" + "已有信息可支持有限分析;缺少日期不能认定控制正常。" * 320
|
||||
text += "\n\n## 原始记录\n\n```json\n" + json.dumps(original, ensure_ascii=False)
|
||||
return text + "\n```\n\n**唯一完整结尾** 🩺"
|
||||
|
||||
|
||||
def wait_until(predicate, seconds=5):
|
||||
deadline = monotonic() + seconds
|
||||
while not predicate() and monotonic() < deadline:
|
||||
QTest.qWait(5)
|
||||
assert predicate(), "finite presentation/transport wait expired"
|
||||
|
||||
|
||||
def event(dialog, kind, **values):
|
||||
dialog._stream_event(dialog._generation, dialog._stream_generation, {"event": kind, **values})
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def application():
|
||||
return QApplication.instance() or QApplication([])
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def dialogs(application, monkeypatch):
|
||||
resources = []
|
||||
|
||||
def create(handler=None):
|
||||
if handler is None:
|
||||
monkeypatch.setattr(module, "QThreadPool", SimpleNamespace(
|
||||
globalInstance=lambda: SimpleNamespace(start=lambda _: None),
|
||||
))
|
||||
repository, client = object(), None
|
||||
else:
|
||||
client = ApiClient("https://example.test", transport=httpx.MockTransport(handler))
|
||||
repository = RemoteDoctorRepository(client)
|
||||
dialog = module.AiConsultDialog(repository, PermissionSet(["tcm.diagnosis/aiAssistant"]))
|
||||
monkeypatch.setattr(dialog, "_load_workspace", lambda _: None)
|
||||
dialog.open_for(diagnosis_id=501, patient_id=1501)
|
||||
dialog.show()
|
||||
application.processEvents()
|
||||
resources.append((dialog, client))
|
||||
return dialog
|
||||
|
||||
yield create
|
||||
for dialog, client in resources:
|
||||
dialog.close()
|
||||
for timer in dialog.findChildren(QTimer):
|
||||
timer.stop()
|
||||
if client is not None:
|
||||
client.close()
|
||||
dialog.deleteLater()
|
||||
assert QThreadPool.globalInstance().waitForDone(3000)
|
||||
application.sendPostedEvents(None, QEvent.Type.DeferredDelete)
|
||||
application.processEvents()
|
||||
|
||||
|
||||
def test_validated_burst_done_and_transport_finished_leave_many_real_intermediate_frames(dialogs):
|
||||
answer = report()
|
||||
calls = []
|
||||
|
||||
def handler(request):
|
||||
assert request.url.host == "example.test"
|
||||
calls.append(request)
|
||||
body = "".join(f"event: {kind}\ndata: {json.dumps(value, ensure_ascii=False)}\n\n"
|
||||
for kind, value in [
|
||||
("start", {"model_label": "原配置千问", "model_key": "qwen"}),
|
||||
("progress", {"phase": "attachments", "status": "submitted", **receipt()}),
|
||||
("delta", {"text": answer}), ("done", receipt()),
|
||||
])
|
||||
return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
|
||||
|
||||
dialog = dialogs(handler)
|
||||
dialog._ask("生成合成病历分析", task="case_analysis")
|
||||
bubble = dialog._stream_bubble
|
||||
|
||||
class PaintProbe(QObject):
|
||||
def __init__(self):
|
||||
super().__init__(bubble.body)
|
||||
self.sizes = []
|
||||
|
||||
def eventFilter(self, watched, paint_event): # noqa: N802 - Qt API
|
||||
if paint_event.type() == QEvent.Type.Paint:
|
||||
size = len(bubble.body.toPlainText())
|
||||
if not self.sizes or self.sizes[-1] != size:
|
||||
self.sizes.append(size)
|
||||
return False
|
||||
|
||||
paint_probe = PaintProbe()
|
||||
bubble.body.viewport().installEventFilter(paint_probe)
|
||||
wait_until(lambda: not dialog._asking and dialog._stream_worker is None)
|
||||
assert dialog.send_button.isEnabled() and dialog._stream_completed
|
||||
assert bubble._presentation_timer.isActive()
|
||||
assert 0 < len(bubble.body.toPlainText()) < len(answer) // 3
|
||||
assert bubble._raw_payload == answer == dialog._stream_text
|
||||
assert bubble._clinical_panel is None
|
||||
assert "本次回复已完成" in bubble.transfer_status.text()
|
||||
frames, gaps = [], []
|
||||
previous = perf_counter()
|
||||
|
||||
def sample():
|
||||
nonlocal previous
|
||||
now = perf_counter()
|
||||
gaps.append((now - previous) * 1000)
|
||||
previous = now
|
||||
size = len(bubble.body.toPlainText())
|
||||
if not frames or size != frames[-1]:
|
||||
frames.append(size)
|
||||
|
||||
heartbeat = QTimer()
|
||||
heartbeat.setInterval(5)
|
||||
heartbeat.timeout.connect(sample)
|
||||
heartbeat.start()
|
||||
try:
|
||||
wait_until(lambda: not bubble._presentation_timer.isActive() and not bubble._report_render_pending)
|
||||
finally:
|
||||
heartbeat.stop()
|
||||
assert len(frames) >= 15
|
||||
assert len(paint_probe.sizes) >= 10
|
||||
assert max(gaps) < 200 # Host-local event-loop guard, not a native-display/model SLA.
|
||||
assert len(calls) == 1
|
||||
assert json.loads(calls[0].content)["task"] == "case_analysis"
|
||||
assert "model" not in json.loads(calls[0].content)
|
||||
assert bubble._raw_payload == answer
|
||||
oracle = module._RichMessage("ai")
|
||||
oracle.document().setDefaultFont(bubble.body.document().defaultFont())
|
||||
oracle.set_payload(answer)
|
||||
module._highlight_document_metrics(oracle.document())
|
||||
assert bubble.body.toPlainText() == oracle.toPlainText()
|
||||
actual_html, expected_html = bubble.body.toHtml(), oracle.toHtml()
|
||||
mismatch = next((i for i, (a, b) in enumerate(zip(actual_html, expected_html, strict=False)) if a != b), 0)
|
||||
assert actual_html == expected_html, (mismatch, actual_html[mismatch:mismatch + 120], expected_html[mismatch:mismatch + 120])
|
||||
oracle.deleteLater()
|
||||
assert [row["key"] for row in bubble._provenance["required_sections"]] == list(SOURCE_KEYS)
|
||||
assert "原配置千问" in bubble.stamp.text()
|
||||
# Fenced original-source JSON keeps the existing full Markdown renderer.
|
||||
assert bubble._clinical_panel is None
|
||||
rendered = bubble.body.toPlainText()
|
||||
for i in range(13):
|
||||
assert f"第 {i} 类合成来源原文" in rendered
|
||||
|
||||
|
||||
@pytest.mark.parametrize("tool", TOOLS, ids=[tool[1] for tool in TOOLS])
|
||||
@pytest.mark.parametrize("legacy", [False, True])
|
||||
def test_six_actual_tool_answers_keep_source_fields_after_presentation(dialogs, tool, legacy):
|
||||
label, task, title, analysis = tool
|
||||
sources = "\n".join(
|
||||
f"- 合成来源 {i} 原文:" + json.dumps({"record_date": "2026-01-01", "note": f"原文唯一 {i}"}, ensure_ascii=False)
|
||||
for i in range(13)
|
||||
)
|
||||
answer = f"## {title}判断\n- {analysis}\n- {task}_ACTUAL_MODEL_ANSWER\n\n## 全部原文\n{sources}"
|
||||
requests = []
|
||||
|
||||
def handler(request):
|
||||
assert request.url.host == "example.test"
|
||||
requests.append(request)
|
||||
if request.url.path.endswith("/aiAssistantStream"):
|
||||
if legacy:
|
||||
return httpx.Response(404, json={"msg": "合成旧服务"})
|
||||
body = "".join(f"event: {kind}\ndata: {json.dumps(value, ensure_ascii=False)}\n\n"
|
||||
for kind, value in [("delta", {"text": answer}), ("done", receipt())])
|
||||
return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)
|
||||
assert legacy and request.url.path.endswith("/aiAssistant")
|
||||
return httpx.Response(200, json={"code": 1, "data": {"answer": answer, **receipt()}})
|
||||
|
||||
dialog = dialogs(handler)
|
||||
card = next(card for card in dialog.findChildren(module._ClickCard, "AiConsultToolCard")
|
||||
if any(child.text() == label for child in card.findChildren(QLabel)))
|
||||
target = next(child for child in card.findChildren(QLabel) if child.text() == label)
|
||||
QTest.mouseClick(target, Qt.MouseButton.LeftButton)
|
||||
bubble = dialog._stream_bubble
|
||||
wait_until(lambda: dialog._stream_worker is None and not dialog._asking)
|
||||
assert bubble._raw_payload == answer and dialog.send_button.isEnabled()
|
||||
wait_until(lambda: not bubble._presentation_timer.isActive() and not bubble._report_render_pending)
|
||||
assert bubble._raw_payload == answer
|
||||
assert len(requests) == (2 if legacy else 1)
|
||||
for request in requests:
|
||||
body = json.loads(request.content)
|
||||
assert body["task"] == task and "model_key" not in body and "model" not in body
|
||||
assert isinstance(bubble._clinical_panel, module._StructuredReportPanel)
|
||||
panel = bubble._clinical_panel
|
||||
assert panel.findChild(QLabel, "AiConsultClinicalTitle").text() == f"AI · {title}"
|
||||
text = "\n".join(view.toPlainText() for view in panel.findChildren(module.QTextBrowser))
|
||||
assert analysis in text and f"{task}_ACTUAL_MODEL_ANSWER" in text
|
||||
assert "记录日期:2026-01-01" in text and """ not in text
|
||||
for i in range(13):
|
||||
assert f"原文唯一 {i}" in text
|
||||
assert [row["key"] for row in bubble._provenance["required_sections"]] == list(SOURCE_KEYS)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("length", [1, 8, 24, 72, 513])
|
||||
@pytest.mark.parametrize("answer_only", [False, True])
|
||||
def test_tiny_and_done_answer_races_finish_once_with_exact_text(dialogs, length, answer_only):
|
||||
dialog = dialogs()
|
||||
dialog._ask("合成问诊", task="summary")
|
||||
bubble, worker = dialog._stream_bubble, dialog._stream_worker
|
||||
answer = ("合成文字🩺\n" * 100)[:length]
|
||||
finished = []
|
||||
bubble.stream_presentation_finished.connect(lambda: finished.append(True))
|
||||
if not answer_only:
|
||||
event(dialog, "delta", text=answer)
|
||||
event(dialog, "done", answer=answer, **receipt())
|
||||
assert not dialog._asking and dialog.send_button.isEnabled()
|
||||
dialog._stream_finished(dialog._generation, dialog._stream_generation, worker)
|
||||
assert dialog._stream_worker is None
|
||||
event(dialog, "done", answer="伪造迟到成功")
|
||||
wait_until(lambda: not bubble._presentation_timer.isActive())
|
||||
assert finished == [True]
|
||||
assert bubble._raw_payload == answer
|
||||
oracle = module._RichMessage("ai")
|
||||
oracle.document().setDefaultFont(bubble.body.document().defaultFont())
|
||||
oracle.set_payload(answer)
|
||||
assert bubble.body.toHtml() == oracle.toHtml()
|
||||
oracle.deleteLater()
|
||||
|
||||
|
||||
def test_completed_old_bubble_keeps_own_animation_after_new_request(dialogs):
|
||||
dialog = dialogs()
|
||||
dialog._ask("旧问题", task="case_analysis")
|
||||
old, worker = dialog._stream_bubble, dialog._stream_worker
|
||||
answer = report()
|
||||
event(dialog, "delta", text=answer)
|
||||
event(dialog, "done")
|
||||
dialog._stream_finished(dialog._generation, dialog._stream_generation, worker)
|
||||
assert dialog._stream_worker is None and old._presentation_timer.isActive()
|
||||
old_frames = []
|
||||
old.stream_frame_presented.connect(lambda: old_frames.append(True))
|
||||
dialog._ask("新问题", task="summary")
|
||||
new = dialog._stream_bubble
|
||||
event(dialog, "delta", text="新请求的唯一答案")
|
||||
event(dialog, "done")
|
||||
wait_until(lambda: not old._presentation_timer.isActive() and not old._report_render_pending)
|
||||
assert old_frames and old._raw_payload == answer
|
||||
assert new._raw_payload == "新请求的唯一答案"
|
||||
assert new.body.toPlainText() == "新请求的唯一答案"
|
||||
assert "旧问题" not in new.body.toPlainText()
|
||||
assert dialog._stream_text == "新请求的唯一答案"
|
||||
assert new._task_title == "问诊小结" and old._task_title == "病历分析"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("exit_path", ["close", "patient", "replace", "cancel"])
|
||||
def test_exit_stops_correct_bubble_and_no_late_timer_can_change_next_request(dialogs, exit_path):
|
||||
dialog = dialogs()
|
||||
dialog._ask("旧问题", task="case_analysis")
|
||||
old, worker = dialog._stream_bubble, dialog._stream_worker
|
||||
old_generation = (dialog._generation, dialog._stream_generation)
|
||||
answer = report()
|
||||
event(dialog, "delta", text=answer)
|
||||
assert old._presentation_timer.isActive()
|
||||
if exit_path == "close":
|
||||
dialog.close()
|
||||
elif exit_path == "patient":
|
||||
dialog.open_for(diagnosis_id=502, patient_id=1502)
|
||||
dialog._ask("新患者问题")
|
||||
elif exit_path == "replace":
|
||||
dialog._ask("替代问题", replace_active=True)
|
||||
else:
|
||||
dialog._cancel_stream(reason="合成超时")
|
||||
assert not old._presentation_timer.isActive()
|
||||
assert old._clinical_panel is None
|
||||
assert old._raw_payload == answer
|
||||
current = dialog._stream_bubble
|
||||
expected = current._raw_payload if current is not None else None
|
||||
dialog._stream_event(*old_generation, {"event": "done", "answer": "迟到伪造成功"})
|
||||
dialog._stream_finished(*old_generation, worker)
|
||||
QTest.qWait(80)
|
||||
assert old._raw_payload == answer
|
||||
assert not isValid(old._presentation_timer) or not old._presentation_timer.isActive()
|
||||
if current is not None:
|
||||
assert current._raw_payload == expected
|
||||
if exit_path in {"replace", "cancel"}:
|
||||
assert "唯一完整结尾" in old.body.toPlainText()
|
||||
assert "取消" in old.transfer_status.text()
|
||||
|
||||
|
||||
def test_error_preserves_all_approved_partial_and_never_formats_success(dialogs):
|
||||
dialog = dialogs()
|
||||
dialog._ask("合成判断", task="case_analysis")
|
||||
bubble, worker = dialog._stream_bubble, dialog._stream_worker
|
||||
answer = report()
|
||||
event(dialog, "delta", text=answer)
|
||||
assert len(bubble.body.toPlainText()) < len(answer)
|
||||
failure = RuntimeError("AI正文与病历的已知、阴性或未记录状态不一致")
|
||||
dialog._stream_failed(dialog._generation, dialog._stream_generation, failure)
|
||||
assert not bubble._presentation_timer.isActive()
|
||||
assert answer in bubble._raw_payload
|
||||
assert "生成中断:AI正文与病历" in bubble._raw_payload
|
||||
assert "唯一完整结尾" in bubble.body.toPlainText()
|
||||
assert not dialog._stream_completed and bubble._clinical_panel is None
|
||||
event(dialog, "done", answer="迟到伪造成功")
|
||||
dialog._stream_finished(dialog._generation, dialog._stream_generation, worker)
|
||||
QTest.qWait(80)
|
||||
assert bubble._clinical_panel is None and not bubble._presentation_timer.isActive()
|
||||
assert "迟到伪造成功" not in bubble._raw_payload
|
||||
assert dialog._stream_worker is None and dialog.send_button.isEnabled()
|
||||
|
||||
|
||||
def test_cancelled_progress_is_terminal_even_if_a_late_done_follows(dialogs):
|
||||
dialog = dialogs()
|
||||
dialog._ask("合成判断", task="case_analysis")
|
||||
bubble, worker = dialog._stream_bubble, dialog._stream_worker
|
||||
answer = report()
|
||||
event(dialog, "delta", text=answer)
|
||||
event(dialog, "progress", phase="cancelled")
|
||||
assert not dialog._asking and not bubble._presentation_timer.isActive()
|
||||
assert "取消" in bubble.transfer_status.text()
|
||||
event(dialog, "delta", text="迟到伪造正文")
|
||||
event(dialog, "done", answer="迟到伪造成功")
|
||||
dialog._stream_finished(dialog._generation, dialog._stream_generation, worker)
|
||||
QTest.qWait(80)
|
||||
assert bubble._raw_payload == answer and bubble._clinical_panel is None
|
||||
assert dialog._stream_worker is None and not dialog._stream_completed
|
||||
|
||||
|
||||
def test_eof_releases_transport_and_keeps_approved_partial_without_success_panel(dialogs):
|
||||
dialog = dialogs()
|
||||
dialog._ask("合成问诊", task="case_analysis")
|
||||
bubble, worker = dialog._stream_bubble, dialog._stream_worker
|
||||
answer = report()
|
||||
event(dialog, "delta", text=answer)
|
||||
dialog._stream_finished(dialog._generation, dialog._stream_generation, worker)
|
||||
assert dialog._stream_worker is None and not dialog._asking and dialog.send_button.isEnabled()
|
||||
assert bubble._presentation_timer.isActive()
|
||||
assert "未收到回复完成确认" in bubble.transfer_status.text()
|
||||
assert not dialog._stream_completed and bubble._clinical_panel is None
|
||||
wait_until(lambda: not bubble._presentation_timer.isActive())
|
||||
assert bubble._raw_payload == answer and "唯一完整结尾" in bubble.body.toPlainText()
|
||||
assert bubble._clinical_panel is None and not bubble._report_render_pending
|
||||
|
||||
|
||||
@pytest.mark.parametrize("owner_change", ["none", "patient_id", "diagnosis_id", "_chart_patient_id"])
|
||||
def test_done_freezes_record_snapshot_before_playback_and_rechecks_owner(dialogs, owner_change):
|
||||
dialog = dialogs()
|
||||
dialog._workspace_sections = {"tracking": {"value": {"diagnosis_id": 501, "blood_records": [
|
||||
{"diagnosis_id": 501, "patient_id": 1501, "record_date": "2026-01-01", "fasting_blood_sugar": 6.2},
|
||||
]}}}
|
||||
dialog._ask("血糖资料", task="glucose_trend")
|
||||
bubble, worker = dialog._stream_bubble, dialog._stream_worker
|
||||
answer = ("## 血糖记录\n- 已有空腹血糖 6.2 mmol/L,单条记录不能确定趋势。\n\n## 来源复核\n- "
|
||||
+ "合成来源日期与数值逐项保留。" * 500)
|
||||
event(dialog, "delta", text=answer)
|
||||
event(dialog, "done")
|
||||
dialog._stream_finished(dialog._generation, dialog._stream_generation, worker)
|
||||
assert bubble._presentation_timer.isActive() and bubble._report_render_pending
|
||||
dialog._workspace_sections["tracking"]["value"]["blood_records"][0]["fasting_blood_sugar"] = 99
|
||||
if owner_change == "none":
|
||||
dialog._ask("新的问题")
|
||||
else:
|
||||
setattr(dialog, owner_change, 9999)
|
||||
wait_until(lambda: not bubble._presentation_timer.isActive() and not bubble._report_render_pending)
|
||||
assert bubble._raw_payload == answer
|
||||
if owner_change == "none":
|
||||
assert bubble._clinical_panel is not None
|
||||
chart = bubble.findChild(GlucoseReportCard)
|
||||
assert chart is not None and chart.chart.data.readings[0].fasting == 6.2
|
||||
else:
|
||||
assert bubble._clinical_panel is None and bubble.findChild(GlucoseReportCard) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("terminal", ["close", "patient"])
|
||||
def test_session_exit_also_stops_previously_completed_bubble_animation(dialogs, terminal):
|
||||
dialog = dialogs()
|
||||
dialog._ask("已完成旧问题", task="case_analysis")
|
||||
old, worker = dialog._stream_bubble, dialog._stream_worker
|
||||
event(dialog, "delta", text=report())
|
||||
event(dialog, "done")
|
||||
dialog._stream_finished(dialog._generation, dialog._stream_generation, worker)
|
||||
dialog._ask("当前问题")
|
||||
assert old._presentation_timer.isActive()
|
||||
if terminal == "close":
|
||||
dialog.close()
|
||||
else:
|
||||
dialog.open_for(diagnosis_id=502, patient_id=1502)
|
||||
assert not old._presentation_timer.isActive()
|
||||
QTest.qWait(80)
|
||||
assert old._clinical_panel is None
|
||||
|
||||
|
||||
def test_first_frame_and_every_playback_slice_are_bounded(dialogs, monkeypatch):
|
||||
dialog = dialogs()
|
||||
dialog._ask("合成大段正文")
|
||||
bubble = dialog._stream_bubble
|
||||
chunks = []
|
||||
original = bubble.body.append_stream_text
|
||||
|
||||
def append(text):
|
||||
chunks.append(len(text))
|
||||
original(text)
|
||||
|
||||
monkeypatch.setattr(bubble.body, "append_stream_text", append)
|
||||
started = perf_counter()
|
||||
event(dialog, "delta", text=report())
|
||||
assert (perf_counter() - started) * 1000 < 80
|
||||
assert len(chunks) == 1 and chunks[0] <= 24
|
||||
event(dialog, "done")
|
||||
assert len(chunks) == 1 and not dialog._asking
|
||||
QTest.qWait(130)
|
||||
assert len(chunks) >= 3 and max(chunks) <= 256
|
||||
assert bubble._presentation_timer.isActive()
|
||||
@@ -1,276 +0,0 @@
|
||||
"""Synthetic Qt regressions for batch receipts and isolated prescription results."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from copy import deepcopy
|
||||
from types import SimpleNamespace
|
||||
|
||||
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
||||
|
||||
import pytest
|
||||
from PySide6.QtCore import QEvent, Qt, QTimer
|
||||
from PySide6.QtTest import QTest
|
||||
from PySide6.QtWidgets import QApplication, QLabel, QPushButton
|
||||
|
||||
from doctor_workstation.core import PermissionSet
|
||||
from doctor_workstation.core.errors import ApiBusinessError
|
||||
from doctor_workstation.ui.dialogs import ai_consult as module
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def application():
|
||||
return QApplication.instance() or QApplication([])
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def dialog(application, monkeypatch):
|
||||
monkeypatch.setattr(module, "QThreadPool", SimpleNamespace(
|
||||
globalInstance=lambda: SimpleNamespace(start=lambda _: None),
|
||||
))
|
||||
repository = SimpleNamespace(
|
||||
create_prescription=lambda *_: pytest.fail("test must never create a prescription"),
|
||||
generate_ai_prescription=lambda *_: pytest.fail("test must never invoke an upstream"),
|
||||
cancel_diagnosis_ai=lambda *_: {"cancel_requested": True},
|
||||
)
|
||||
instance = module.AiConsultDialog(repository, PermissionSet([
|
||||
"tcm.diagnosis/aiAssistant", "tcm.diagnosis/chufang",
|
||||
"tcm.diagnosis/aiGeneratePrescription",
|
||||
]))
|
||||
monkeypatch.setattr(instance, "_load_workspace", lambda _: None)
|
||||
monkeypatch.setattr(module, "show_toast", lambda *_: None)
|
||||
instance.open_for(diagnosis_id=501, patient_id=1501)
|
||||
instance.resize(1280, 820)
|
||||
instance.show()
|
||||
application.processEvents()
|
||||
yield instance
|
||||
for timer in instance.findChildren(QTimer):
|
||||
timer.stop()
|
||||
instance.close()
|
||||
instance.deleteLater()
|
||||
application.sendPostedEvents(None, QEvent.Type.DeferredDelete)
|
||||
application.processEvents()
|
||||
|
||||
|
||||
def sections(status):
|
||||
return [{"key": key, "status": status, "availability": "present"}
|
||||
for key, _ in module._REQUIRED_TRANSFER_SECTIONS]
|
||||
|
||||
|
||||
def receipt(status="submitted", nested=False):
|
||||
data = {
|
||||
"items": [
|
||||
{"kind": "image", "label": "图片附件1", "status": status},
|
||||
{"kind": "image", "label": "图片附件2", "status": "rejected", "reason": "file_type"},
|
||||
],
|
||||
"attachment_count": 2, "submitted_attachment_count": int(status == "submitted"),
|
||||
"rejected_attachment_count": 1, "attachment_transfer": "uploaded_files",
|
||||
"attachment_mode": "batch_evidence", "attachment_batch_count": 3,
|
||||
"transfer_manifest_final": True,
|
||||
}
|
||||
manifest = sections("submitted" if status == "submitted" else "failed")
|
||||
if nested:
|
||||
data["source_summary"] = {"required_sections": manifest}
|
||||
else:
|
||||
data["required_sections"] = manifest
|
||||
return data
|
||||
|
||||
|
||||
def emit(dialog, payload):
|
||||
dialog._stream_event(dialog._generation, dialog._stream_generation, payload)
|
||||
|
||||
|
||||
def assert_collapsed(bubble):
|
||||
assert bubble.transfer_status.isHidden() and not bubble.transfer_toggle.isChecked()
|
||||
assert "展开详情" in bubble.transfer_toggle.text()
|
||||
assert bubble._inner.itemAt(0).widget() is bubble.transfer_receipt
|
||||
assert len(bubble.findChildren(QLabel, "AiConsultTransferStatus")) == 1
|
||||
QTest.mouseClick(bubble.transfer_toggle, Qt.MouseButton.LeftButton)
|
||||
assert bubble.transfer_status.isVisible()
|
||||
QTest.mouseClick(bubble.transfer_toggle, Qt.MouseButton.LeftButton)
|
||||
assert bubble.transfer_status.isHidden()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("nested", [False, True])
|
||||
@pytest.mark.parametrize("outcome", ["success", "error"])
|
||||
def test_prescription_receipt_is_local_collapsed_and_cannot_mutate_active_question(
|
||||
dialog, monkeypatch, nested, outcome,
|
||||
):
|
||||
dialog._ask("独立的当前合成问答")
|
||||
emit(dialog, {"event": "progress", "phase": "attachments", "status": "submitted",
|
||||
"items": [{"kind": "document", "label": "文档附件9", "status": "submitted"}],
|
||||
"attachment_count": 1, "submitted_attachment_count": 1,
|
||||
"required_sections": sections("submitted")})
|
||||
current_bubble, current_worker = dialog._stream_bubble, dialog._stream_worker
|
||||
current_meta = deepcopy(dialog._stream_meta)
|
||||
current_text = current_bubble.transfer_status.text()
|
||||
status = dialog._append_bubble("ai", "合成处方等待状态")
|
||||
editor_calls = []
|
||||
monkeypatch.setattr(dialog, "_open_prescription_editor_from_chat",
|
||||
lambda *args: editor_calls.append(args))
|
||||
payload = receipt("submitted" if outcome == "success" else "failed", nested)
|
||||
original = deepcopy(payload)
|
||||
if outcome == "success":
|
||||
result = {**payload, "diagnosis_id": 501, "task": "prescription_generate",
|
||||
"prescription_draft": {"clinical_diagnosis": "合成诊断",
|
||||
"herbs": [{"name": "合成药材", "dosage": 1}]}}
|
||||
dialog._ai_prescription_ready(dialog._generation, 501, status, {}, result)
|
||||
assert len(editor_calls) == 1
|
||||
assert "AI 已生成处方草稿" in status._raw_payload
|
||||
assert "处方草稿资料处理已完成。" in status.transfer_status.text()
|
||||
else:
|
||||
payload["code"] = "REQUIRED_FILES_REJECTED"
|
||||
original = deepcopy(payload)
|
||||
dialog._prescription_action_error(dialog._generation, status, ApiBusinessError(
|
||||
"合成附件拒绝", data=payload,
|
||||
), prefix="AI处方草稿生成失败")
|
||||
assert editor_calls == []
|
||||
assert status._raw_payload == "AI处方草稿生成失败:合成附件拒绝"
|
||||
assert "本次请求失败,资料或回复未完成。" in status.transfer_status.text()
|
||||
text = status.transfer_status.text()
|
||||
assert "附件处理:同一模型已进行 3 批提交尝试。" in text
|
||||
assert "图片附件2(图片):上游拒收,未读取(格式不支持)" in text
|
||||
assert "文档附件9" not in text
|
||||
assert f"本请求附件通道:{int(outcome == 'success')} 项" in text
|
||||
assert payload == original
|
||||
assert dialog._stream_meta == current_meta
|
||||
assert dialog._stream_worker is current_worker and dialog._stream_bubble is current_bubble
|
||||
assert current_bubble.transfer_status.text() == current_text
|
||||
assert dialog._asking and not dialog._stream_completed
|
||||
assert_collapsed(status)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("outcome", ["success", "error"])
|
||||
def test_prescription_without_manifest_cannot_borrow_active_question_receipt(dialog, monkeypatch, outcome):
|
||||
dialog._ask("独立的合成问答")
|
||||
emit(dialog, {"event": "progress", "phase": "attachments", "status": "submitted", **receipt()})
|
||||
current_meta = deepcopy(dialog._stream_meta)
|
||||
status = dialog._append_bubble("ai", "合成处方等待状态")
|
||||
monkeypatch.setattr(dialog, "_open_prescription_editor_from_chat", lambda *_: None)
|
||||
if outcome == "success":
|
||||
dialog._ai_prescription_ready(dialog._generation, 501, status, {}, {
|
||||
"diagnosis_id": 501, "task": "prescription_generate",
|
||||
"prescription_draft": {"clinical_diagnosis": "合成诊断",
|
||||
"herbs": [{"name": "合成药材", "dosage": 1}]},
|
||||
})
|
||||
else:
|
||||
dialog._prescription_action_error(dialog._generation, status, ApiBusinessError(
|
||||
"合成无清单错误", data={"code": "REQUIRED_FILES_REJECTED"},
|
||||
), prefix="合成失败")
|
||||
assert not status.findChildren(QLabel, "AiConsultTransferStatus")
|
||||
assert dialog._stream_meta == current_meta
|
||||
|
||||
|
||||
def test_prescription_button_cancels_old_stream_before_beginning_owned_action(dialog, monkeypatch, application):
|
||||
begin = []
|
||||
monkeypatch.setattr(dialog, "_begin_prescription_action", lambda *args: begin.append(args))
|
||||
dialog._ask("旧的合成问答")
|
||||
old_worker, old_bubble = dialog._stream_worker, dialog._stream_bubble
|
||||
old_generation, old_stream = dialog._generation, dialog._stream_generation
|
||||
emit(dialog, {"event": "delta", "text": "旧问答已收到正文"})
|
||||
next(button for button in dialog.findChildren(QPushButton)
|
||||
if button.text() == "AI 生成处方").click()
|
||||
assert old_worker.is_cancelled()
|
||||
assert dialog._stream_generation > old_stream
|
||||
assert dialog._stream_worker is None and not dialog._asking
|
||||
assert dialog._stream_meta == {}
|
||||
assert "旧问答已收到正文" in old_bubble._raw_payload
|
||||
assert "上游是否停止尚未确认" in old_bubble.transfer_status.text()
|
||||
application.processEvents()
|
||||
assert len(begin) == 1
|
||||
generation, status = begin[0]
|
||||
assert generation == dialog._generation and status is not old_bubble
|
||||
expected = status._raw_payload
|
||||
dialog._stream_event(old_generation, old_stream, {"event": "done", "answer": "不应外显的旧结果"})
|
||||
dialog._stream_failed(old_generation, old_stream, RuntimeError("不应外显的旧错误"))
|
||||
dialog._stream_finished(old_generation, old_stream, old_worker)
|
||||
assert status._raw_payload == expected and dialog._stream_worker is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("nested", [False, True])
|
||||
@pytest.mark.parametrize(("phase", "status"), [
|
||||
("attachments", "uploading"), ("attachments", "submitted"), ("upstream", "waiting"),
|
||||
])
|
||||
def test_batch_progress_never_presents_prepared_full_text_as_already_submitted(dialog, nested, phase, status):
|
||||
dialog._ask("合成批处理问答")
|
||||
payload = receipt(nested=nested)
|
||||
payload["transfer_manifest_final"] = False
|
||||
payload["attachment_batch_count"] = 2
|
||||
if nested:
|
||||
payload["source_summary"]["required_sections"] = sections("prepared")
|
||||
else:
|
||||
payload["required_sections"] = sections("prepared")
|
||||
emit(dialog, {"event": "progress", "phase": phase, "status": status, **payload})
|
||||
bubble = dialog._stream_bubble
|
||||
text = bubble.transfer_status.text()
|
||||
assert text.splitlines()[0] == "正在分批提交附件并提取资料,完整病历尚未提交综合分析…"
|
||||
assert bubble._raw_payload == text.splitlines()[0]
|
||||
assert "基本信息:已整理,待提交" in text
|
||||
assert "基本信息:已提交" not in text
|
||||
assert "资料正文已提交" not in text and "资料已提交,正在等待 AI 正文" not in text
|
||||
assert dialog._stream_meta["attachment_mode"] == "batch_evidence"
|
||||
assert dialog._stream_meta["attachment_batch_count"] == 2
|
||||
assert dialog._asking and not dialog._stream_completed
|
||||
assert_collapsed(bubble)
|
||||
# Once the complete body is submitted, normal synthesis waiting is accurate.
|
||||
emit(dialog, {"event": "progress", "phase": "upstream", "status": "waiting",
|
||||
"required_sections": sections("submitted")})
|
||||
assert "基本信息:已提交" in bubble.transfer_status.text()
|
||||
assert "完整病历尚未提交" not in bubble.transfer_status.text()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("reason", "expected"), [
|
||||
("file_count", "(数量限制)"), ("file_type", "(格式不支持)"),
|
||||
("file_size", "(大小限制)"), ("file_access", "(附件不可读取)"),
|
||||
("private test filename https://example.test/hidden.png?secret=synthetic", ""),
|
||||
("<b>synthetic-private-error</b>", ""),
|
||||
])
|
||||
def test_rejected_receipt_uses_only_safe_reason_codes_and_stays_collapsed(dialog, reason, expected):
|
||||
dialog._ask("合成拒绝回执")
|
||||
payload = receipt()
|
||||
payload["items"][1].update({"reason": reason, "label": "synthetic-private-filename.png"})
|
||||
emit(dialog, {"event": "progress", "phase": "attachments", "status": "submitted", **payload})
|
||||
bubble = dialog._stream_bubble
|
||||
text = bubble.transfer_status.text()
|
||||
assert f"图片附件2(图片):上游拒收,未读取{expected}" in text
|
||||
assert "synthetic-private" not in text and "https://" not in text
|
||||
assert bubble.transfer_status.textFormat() == Qt.TextFormat.PlainText
|
||||
assert "本请求附件通道:1 项" in text
|
||||
assert_collapsed(bubble)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("with_skipped", [False, True])
|
||||
@pytest.mark.parametrize("reported", [None, True, -1, "1"])
|
||||
def test_rejected_and_failed_files_never_inflate_fallback_submitted_count(dialog, with_skipped, reported):
|
||||
items = [
|
||||
{"kind": "image", "label": "图片附件1", "status": "submitted"},
|
||||
{"kind": "image", "label": "图片附件2", "status": "rejected", "reason": "file_type"},
|
||||
{"kind": "image", "label": "图片附件3", "status": "failed"},
|
||||
]
|
||||
if with_skipped:
|
||||
items.append({"kind": "image", "label": "图片附件4", "status": "skipped", "reason": "not_found"})
|
||||
dialog._ask("合成计数回执")
|
||||
emit(dialog, {"event": "progress", "phase": "attachments", "status": "submitted",
|
||||
"items": items, "attachment_count": len(items), "submitted_attachment_count": reported})
|
||||
assert "本请求附件通道:1 项" in dialog._stream_bubble.transfer_status.text()
|
||||
|
||||
|
||||
def test_nonfinal_error_manifest_keeps_batch_rejections_and_explicit_outcome_counts(dialog):
|
||||
dialog._ask("合成错误回执纠正")
|
||||
emit(dialog, {"event": "progress", "phase": "attachments", "status": "submitted",
|
||||
"items": [{"kind": "image", "label": "图片附件1", "status": "submitted"}],
|
||||
"attachment_count": 1, "submitted_attachment_count": 1})
|
||||
failed = receipt("failed")
|
||||
failed.pop("transfer_manifest_final")
|
||||
dialog._stream_failed(dialog._generation, dialog._stream_generation, ApiBusinessError(
|
||||
"合成批处理失败", data={"code": "REQUIRED_FILES_REJECTED", **failed},
|
||||
))
|
||||
text = dialog._stream_bubble.transfer_status.text()
|
||||
assert "图片附件1(图片):提交失败" in text
|
||||
assert "图片附件2(图片):上游拒收,未读取(格式不支持)" in text
|
||||
assert "本请求附件通道:0 项" in text
|
||||
assert dialog._stream_meta["rejected_attachment_count"] == 1
|
||||
assert dialog._stream_meta["attachment_mode"] == "batch_evidence"
|
||||
assert dialog._stream_meta["attachment_batch_count"] == 3
|
||||
assert not dialog._asking and not dialog._stream_completed
|
||||
assert_collapsed(dialog._stream_bubble)
|
||||
@@ -1,322 +0,0 @@
|
||||
"""Only observed input states and confirmed upstream cancellation are claimed."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from threading import Event
|
||||
from time import monotonic
|
||||
from types import SimpleNamespace
|
||||
from uuid import UUID
|
||||
|
||||
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
||||
|
||||
import pytest
|
||||
from PySide6.QtTest import QTest
|
||||
from PySide6.QtWidgets import QApplication
|
||||
|
||||
from doctor_workstation.core.errors import ApiBusinessError
|
||||
from doctor_workstation.ui.dialogs import ai_consult as module
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def application():
|
||||
return QApplication.instance() or QApplication([])
|
||||
|
||||
|
||||
def dialog_for(monkeypatch, repository):
|
||||
monkeypatch.setattr(module, "QThreadPool", SimpleNamespace(globalInstance=lambda: SimpleNamespace(start=lambda worker: None)))
|
||||
dialog = module.AiConsultDialog(repository)
|
||||
monkeypatch.setattr(dialog, "_load_workspace", lambda _: None)
|
||||
dialog.open_for(diagnosis_id=501, patient_id=1501)
|
||||
return dialog
|
||||
|
||||
|
||||
def test_progress_lists_actual_materials_without_claiming_model_reading(application, monkeypatch):
|
||||
dialog = dialog_for(monkeypatch, object())
|
||||
dialog._ask("合成问题")
|
||||
generation, stream_generation = dialog._generation, dialog._stream_generation
|
||||
bubble = dialog._stream_bubble
|
||||
dialog._stream_event(generation, stream_generation, {"event": "start"})
|
||||
assert "资料已整理" not in bubble._raw_payload
|
||||
assert module.AI_STREAM_WAITING_TEXT in bubble.transfer_status.text()
|
||||
dialog._stream_event(generation, stream_generation, {
|
||||
"event": "progress", "phase": "preparing",
|
||||
"source_summary": {"diagnosis_count": 2, "doctor_note_count": 3, "patient_name": "敏感姓名"},
|
||||
})
|
||||
assert "诊单 2 条" in bubble.transfer_status.text() and "医生备注 3 条" in bubble.transfer_status.text()
|
||||
dialog._stream_event(generation, stream_generation, {
|
||||
"event": "progress", "phase": "attachments", "status": "submitting", "attachment_count": 2,
|
||||
"source_form": "evidence_summary", "evidence_cache_hit": True,
|
||||
"items": [{"label": "图片附件1", "kind": "image", "status": "submitting"},
|
||||
{"label": "敏感姓名的检查报告.pdf", "kind": "document", "status": "failed"}],
|
||||
})
|
||||
text = bubble.transfer_status.text()
|
||||
assert "图片附件1(图片):提交中" in text and "文档附件2(文档):提交失败" in text
|
||||
assert "来源归并证据摘要" in text and "复用已整理" in text
|
||||
assert "敏感姓名" not in text and "pdf" not in text and "%" not in text
|
||||
dialog._stream_event(generation, stream_generation, {
|
||||
"event": "progress", "phase": "attachments", "status": "submitted",
|
||||
"items": [{"label": "图片附件1", "kind": "image", "status": "submitted"}],
|
||||
})
|
||||
assert "引用已提交" in bubble.transfer_status.text() and "模型实际读取进度不可获取" in bubble.transfer_status.text()
|
||||
dialog._stream_event(generation, stream_generation, {"event": "progress", "phase": "upstream"})
|
||||
assert "等待 AI 正文" in bubble._raw_payload
|
||||
dialog._stream_event(generation, stream_generation, {"event": "delta", "text": "合成正文"})
|
||||
assert bubble._raw_payload == "合成正文" and "图片附件1" in bubble.transfer_status.text()
|
||||
dialog._stream_event(generation, stream_generation, {"event": "done"})
|
||||
assert "本次回复已完成" in bubble.transfer_status.text()
|
||||
dialog.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("confirmed", [False, True])
|
||||
def test_replacement_cancel_is_background_correlated_and_requires_upstream_confirmation(application, monkeypatch, confirmed):
|
||||
entered, release, returned = Event(), Event(), Event()
|
||||
calls = []
|
||||
|
||||
class Repository:
|
||||
def cancel_diagnosis_ai(self, diagnosis_id, request_id):
|
||||
calls.append((diagnosis_id, request_id))
|
||||
entered.set()
|
||||
assert release.wait(2)
|
||||
returned.set()
|
||||
return {"cancel_requested": True, "transport_closed": True, "upstream_stop_confirmed": confirmed}
|
||||
|
||||
dialog = dialog_for(monkeypatch, Repository())
|
||||
try:
|
||||
dialog._ask("旧问题")
|
||||
old_worker, old_bubble = dialog._stream_worker, dialog._stream_bubble
|
||||
request_id = old_worker.request_id
|
||||
assert str(UUID(request_id)) == request_id
|
||||
dialog._ask("新问题", replace_active=True)
|
||||
new_bubble = dialog._stream_bubble
|
||||
assert entered.wait(1)
|
||||
assert "上游是否停止尚未确认" in old_bubble.transfer_status.text()
|
||||
assert old_bubble.body.isHidden()
|
||||
assert calls == [(501, request_id)]
|
||||
assert dialog._stream_worker.request_id != request_id
|
||||
release.set()
|
||||
assert returned.wait(1)
|
||||
deadline = monotonic() + 1
|
||||
while "正在请求取消" in old_bubble.transfer_status.text() and monotonic() < deadline:
|
||||
QTest.qWait(10)
|
||||
assert ("上游已接受停止" in old_bubble.transfer_status.text()) is confirmed
|
||||
assert "尚未确认" in old_bubble.transfer_status.text()
|
||||
assert "上游工作流已停止" not in old_bubble.transfer_status.text()
|
||||
assert new_bubble._raw_payload == module.AI_STREAM_PENDING_TEXT
|
||||
finally:
|
||||
release.set()
|
||||
dialog.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("exit_path", ["timeout", "patient", "close"])
|
||||
def test_abort_paths_send_cancel_once_and_done_never_sends_cancel(application, monkeypatch, exit_path):
|
||||
called = Event()
|
||||
calls = []
|
||||
|
||||
class Repository:
|
||||
def cancel_diagnosis_ai(self, diagnosis_id, request_id):
|
||||
calls.append((diagnosis_id, request_id))
|
||||
called.set()
|
||||
return {"cancel_requested": True, "upstream_stop_confirmed": False}
|
||||
|
||||
dialog = dialog_for(monkeypatch, Repository())
|
||||
dialog._ask("已完成问题")
|
||||
dialog._stream_event(dialog._generation, dialog._stream_generation, {"event": "done", "answer": "合成结果"})
|
||||
dialog._ask("需要取消的问题")
|
||||
assert calls == []
|
||||
worker = dialog._stream_worker
|
||||
if exit_path == "timeout":
|
||||
dialog._stream_timed_out()
|
||||
elif exit_path == "patient":
|
||||
dialog.open_for(diagnosis_id=502, patient_id=1502)
|
||||
else:
|
||||
dialog.close()
|
||||
assert called.wait(1)
|
||||
worker.cancel()
|
||||
assert calls == [(501, worker.request_id)]
|
||||
dialog.close()
|
||||
|
||||
|
||||
def test_cancel_confirmation_cannot_change_reused_patient_session(application, monkeypatch):
|
||||
dialog = dialog_for(monkeypatch, object())
|
||||
dialog._ask("旧问题")
|
||||
old_worker, old_bubble, generation = dialog._stream_worker, dialog._stream_bubble, dialog._generation
|
||||
dialog.open_for(diagnosis_id=502, patient_id=1502)
|
||||
dialog._ask("新患者问题")
|
||||
before = dialog._stream_bubble._raw_payload
|
||||
dialog._stream_cancel_result(generation, 501, old_bubble, old_worker, {"upstream_stop_confirmed": True})
|
||||
assert dialog._stream_bubble._raw_payload == before
|
||||
dialog.close()
|
||||
|
||||
|
||||
def test_server_cancel_terminal_preserves_confirmed_state_without_retry(application, monkeypatch):
|
||||
dialog = dialog_for(monkeypatch, object())
|
||||
dialog._ask("服务端取消测试")
|
||||
generation, stream_generation = dialog._generation, dialog._stream_generation
|
||||
worker, bubble = dialog._stream_worker, dialog._stream_bubble
|
||||
dialog._stream_event(generation, stream_generation, {
|
||||
"event": "progress", "phase": "cancelled", "status": "cancelled",
|
||||
"upstream_stop_confirmed": True, "transport_closed": True,
|
||||
})
|
||||
dialog._stream_failed(generation, stream_generation, ApiBusinessError(
|
||||
"本次请求已取消", data={"code": "AI_ASSISTANT_CANCELLED"},
|
||||
))
|
||||
assert "上游已接受停止" in bubble.transfer_status.text() and "本次传输已结束" in bubble.transfer_status.text()
|
||||
assert not dialog._asking and worker._completed.is_set()
|
||||
assert "尚未确认" in bubble.transfer_status.text()
|
||||
assert bubble.body.isHidden()
|
||||
dialog.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("ack", [
|
||||
{"upstream_stop_confirmed": True},
|
||||
{"upstream_terminal_confirmed": True, "upstream_terminal_status": "stopped"},
|
||||
])
|
||||
def test_long_replacement_preserves_tail_and_cancels_before_gui_work(application, monkeypatch, ack):
|
||||
dialog = dialog_for(monkeypatch, object())
|
||||
dialog._ask("旧长报告")
|
||||
worker, bubble = dialog._stream_worker, dialog._stream_bubble
|
||||
worker.signals.blockSignals(True)
|
||||
body = "## 合成长报告\n\n" + "逐项核对原始记录。\n\n" * 250
|
||||
dialog._stream_event(dialog._generation, dialog._stream_generation, {"event": "delta", "text": body})
|
||||
dialog._stream_event(dialog._generation, dialog._stream_generation, {"event": "delta", "text": "GUI未刷尾段"})
|
||||
worker._queue_event({"event": "delta", "text": "mailbox未刷尾段"})
|
||||
original_append, original_status = bubble.append_stream_text, bubble.set_cancel_status
|
||||
observed = []
|
||||
|
||||
def append(*args):
|
||||
assert worker.is_cancelled(), "cancel flag must precede pending GUI rendering"
|
||||
observed.append("append")
|
||||
original_append(*args)
|
||||
|
||||
def status(*args, **kwargs):
|
||||
assert worker.is_cancelled(), "cancel flag must precede status updates"
|
||||
observed.append("status")
|
||||
original_status(*args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(bubble, "append_stream_text", append)
|
||||
monkeypatch.setattr(bubble, "set_cancel_status", status)
|
||||
monkeypatch.setattr(bubble, "set_payload", lambda *_: pytest.fail("cancel reparsed complete bubble"))
|
||||
monkeypatch.setattr(bubble.body, "set_payload", lambda *_: pytest.fail("cancel reparsed clinical text"))
|
||||
dialog._ask("新问题", replace_active=True)
|
||||
expected = body + "GUI未刷尾段mailbox未刷尾段"
|
||||
assert bubble._raw_payload == expected and worker.cancel_text == expected
|
||||
assert "GUI未刷尾段mailbox未刷尾段" in bubble.body.toPlainText()
|
||||
assert observed and "status" in observed
|
||||
before_stamp = bubble.stamp.text()
|
||||
dialog._stream_cancel_result(dialog._generation, 501, bubble, worker, ack)
|
||||
assert bubble._raw_payload == expected and bubble.stamp.text() == before_stamp
|
||||
assert not bubble.body.isHidden()
|
||||
assert dialog._stream_bubble._raw_payload == module.AI_STREAM_PENDING_TEXT
|
||||
dialog.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("exit_path", ["replacement", "timeout"])
|
||||
def test_queued_done_is_drained_without_cancel_and_preserves_all_tail(application, monkeypatch, exit_path):
|
||||
dialog = dialog_for(monkeypatch, object())
|
||||
dialog._ask("已到达完成事件的旧问题")
|
||||
worker, bubble = dialog._stream_worker, dialog._stream_bubble
|
||||
worker.signals.blockSignals(True)
|
||||
worker._queue_event({"event": "delta", "text": "完整前段"})
|
||||
worker._queue_event({"event": "delta", "text": "与完整尾段"})
|
||||
worker._queue_event({"event": "done"})
|
||||
monkeypatch.setattr(worker, "_request_cancel", lambda: pytest.fail("normal done sent cancel"))
|
||||
if exit_path == "replacement":
|
||||
dialog._ask("新问题", replace_active=True)
|
||||
else:
|
||||
dialog._stream_timed_out()
|
||||
assert dialog._stream_completed and dialog._stream_bubble is bubble
|
||||
assert dialog._stream_text == "完整前段与完整尾段"
|
||||
assert not worker.is_cancelled()
|
||||
assert bubble._raw_payload == "完整前段与完整尾段"
|
||||
assert "本次回复已完成" in bubble.transfer_status.text()
|
||||
assert "正在请求取消" not in bubble.transfer_status.text()
|
||||
dialog.close()
|
||||
|
||||
|
||||
def test_server_cancel_preserves_long_body_through_finished_without_reparse(application, monkeypatch):
|
||||
dialog = dialog_for(monkeypatch, object())
|
||||
dialog._ask("服务端取消长报告")
|
||||
generation, stream_generation = dialog._generation, dialog._stream_generation
|
||||
worker, bubble = dialog._stream_worker, dialog._stream_bubble
|
||||
body = "## 合成长报告\n\n" + "保留既有临床正文。\n\n" * 250
|
||||
dialog._stream_event(generation, stream_generation, {"event": "delta", "text": body})
|
||||
dialog._stream_event(generation, stream_generation, {"event": "delta", "text": "未刷尾段"})
|
||||
monkeypatch.setattr(bubble, "set_payload", lambda *_: pytest.fail("server cancel reparsed complete bubble"))
|
||||
monkeypatch.setattr(bubble.body, "set_payload", lambda *_: pytest.fail("server cancel reparsed clinical text"))
|
||||
dialog._stream_event(generation, stream_generation, {
|
||||
"event": "progress", "phase": "cancelled", "upstream_terminal_confirmed": True,
|
||||
"upstream_terminal_status": "stopped",
|
||||
})
|
||||
dialog._stream_failed(generation, stream_generation, ApiBusinessError(
|
||||
"本次请求已取消", data={"code": "AI_ASSISTANT_CANCELLED"},
|
||||
))
|
||||
dialog._stream_finished(generation, stream_generation, worker)
|
||||
assert bubble._raw_payload == body + "未刷尾段"
|
||||
assert "未刷尾段" in bubble.body.toPlainText()
|
||||
assert "上游工作流已停止" in bubble.transfer_status.text()
|
||||
assert not bubble.body.isHidden() and not dialog._asking
|
||||
dialog.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("confirmed,status,expected", [
|
||||
(True, "stopped", "上游工作流已停止"),
|
||||
(True, "succeeded", "上游工作流已结束(已完成)"),
|
||||
(True, "failed", "上游工作流已结束(失败)"),
|
||||
(False, "stopped", "尚未确认"),
|
||||
(True, "", "尚未确认"),
|
||||
(True, "unrecognized", "尚未确认"),
|
||||
])
|
||||
@pytest.mark.parametrize("path", ["ack", "server_terminal"])
|
||||
def test_only_confirmed_workflow_terminal_claims_ended(application, monkeypatch, confirmed, status, expected, path):
|
||||
dialog = dialog_for(monkeypatch, object())
|
||||
dialog._ask("终态校验")
|
||||
generation, stream_generation = dialog._generation, dialog._stream_generation
|
||||
worker, bubble = dialog._stream_worker, dialog._stream_bubble
|
||||
state = {"upstream_stop_confirmed": True, "upstream_terminal_confirmed": confirmed,
|
||||
"upstream_terminal_status": status, "transport_closed": True}
|
||||
if path == "ack":
|
||||
dialog._ask("新问题", replace_active=True)
|
||||
dialog._stream_cancel_result(generation, 501, bubble, worker, state)
|
||||
else:
|
||||
dialog._stream_event(generation, stream_generation, {"event": "progress", "phase": "cancelled", **state})
|
||||
dialog._stream_failed(generation, stream_generation, ApiBusinessError(
|
||||
"本次请求已取消", data={"code": "AI_ASSISTANT_CANCELLED"},
|
||||
))
|
||||
dialog._stream_finished(generation, stream_generation, worker)
|
||||
assert expected in bubble.transfer_status.text()
|
||||
if not confirmed or status not in {"stopped", "succeeded", "failed"}:
|
||||
assert "上游工作流已停止" not in bubble.transfer_status.text()
|
||||
assert "上游工作流已结束" not in bubble.transfer_status.text()
|
||||
assert bubble.body.isHidden()
|
||||
dialog.close()
|
||||
|
||||
|
||||
def test_worker_monotonic_timings_separate_queue_and_gui_delivery(application, monkeypatch):
|
||||
now = [100.0]
|
||||
monkeypatch.setattr(module, "monotonic", lambda: now[0])
|
||||
monkeypatch.setattr(module, "perf_counter", lambda: now[0])
|
||||
|
||||
class Repository:
|
||||
def stream_diagnosis_ai(self, *args, **kwargs):
|
||||
now[0] = 103.0
|
||||
yield {"event": "delta", "text": "合成正文"}
|
||||
yield {"event": "delta", "text": "尾段"}
|
||||
yield {"event": "done"}
|
||||
|
||||
dialog = dialog_for(monkeypatch, Repository())
|
||||
dialog._ask("时间戳校验")
|
||||
worker = dialog._stream_worker
|
||||
assert worker.queued_at == 100.0 and worker.run_started_at is None
|
||||
worker.signals.blockSignals(True)
|
||||
now[0] = 102.0
|
||||
worker.run()
|
||||
assert worker.run_started_at == 102.0 and worker.first_delta_received_at == 103.0
|
||||
assert worker.first_delta_processed_at is None
|
||||
now[0] = 105.0
|
||||
dialog._poll_stream_events()
|
||||
assert worker.first_delta_processed_at == 105.0
|
||||
assert worker.run_started_at - worker.queued_at == 2.0
|
||||
assert worker.first_delta_processed_at - worker.first_delta_received_at == 2.0
|
||||
assert dialog._stream_bubble._raw_payload == "合成正文尾段"
|
||||
dialog.close()
|
||||