Compare commits

...
39 Commits
Author SHA1 Message Date
gr fc347bf9a6 更新 2026-11-11 13:53:14 +08:00
Your Name 85ffda8fd0 更新 2026-10-27 16:52:13 +08:00
Your Name 5f1e362698 更新 2026-10-27 16:46:50 +08:00
Your Name 24130b4245 更新 2026-10-27 16:32:12 +08:00
gr 690da33722 i给 2026-10-27 16:05:19 +08:00
grandClaude Opus 5.5 fc73dd1aca AI 回复新增用药速览,中药/西药药名摘出并高亮
- 新增 ai_consult_drug_names:中药饮片、方剂/中成药、西药显式词表,长词优先识别,西药按通用名去重
- AI 回复标题下新增“用药速览”卡片:中药绿、西药蓝色块
- 正文药名同色浅底加粗高亮,剂量数字不着色;Markdown 回退路径同样保留底色
- 新增药名识别测试,更新药物剂量着色测试

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 15:31:48 +08:00
grandClaude Opus 5.5 bc3bae97af AI 助手侧栏请求状态按状态着色
- 状态卡新增样式:未发起灰、进行中蓝、完成绿、失败红、已取消橙
- 新增 _apply_sidebar_request_tone(),状态更新时同步切换配色;取消状态以请求 phase 判定

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 15:22:38 +08:00
grandClaude Opus 5.5 f0f555f20f 舌象原图要求模型直接观察,去掉误导性的图片识别说明
- TcmEvidenceGuard:提示词改为直接观察附带的舌象/望诊原图并描述所见,单张不清只说明该张,不再把全部望诊判为未知
- DifyChatService:本地文字识别不可用或无文字时不再给图片附加“未取得可用原文”说明,原图照常携带
- 同步更新 TcmEvidenceGuardTaskAnalysisR37Test 断言

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 15:12:24 +08:00
grandClaude Opus 5.5 c3c37e1650 CA证书包路径失效时退回系统证书库,修复附件上传 CONFIG_INVALID
- DifyRequiredAttachmentUpload:配置的 ca_file 不存在或不可读时记 warning 并改用系统证书库,仍校验对端证书与主机名
- DifyWorkflowRunStatus:同样处理,不再返回 RUN_STATUS_CONFIG_INVALID

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 15:03:47 +08:00
grandClaude Opus 5.5 ea40cfdfed AI助手临床校验改为只提示不拦截,资料不全也给出解答
- TcmClinicalReportStream 新增 BLOCKING 开关(默认 false),校验命中时照常交付原文,问题码记入 warnings()
- 问答、长报告、结构化分析、报告生成的脉象/事实状态/溯源校验改为随结果返回 clinical_review_warnings
- 处方草稿丢弃多余脉象字段、重复药名保留首味,不再整张失败
- 接诊提示词补充互联网面诊仅舌象无脉象、须合理推断给出结论

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 15:00:10 +08:00
Your Name f9cbd42113 修复 2026-10-27 14:03:35 +08:00
Your Name 7986e4baf5 更新 2026-10-23 14:11:24 +08:00
Your Name e86ee4ae66 更新 2026-10-23 13:57:11 +08:00
Your Name ff98014fa2 更新 2026-10-23 11:39:56 +08:00
Your Name 86476920cf 更新 2026-10-23 11:17:58 +08:00
Your Name f78f46b28a 更新 2026-10-23 11:01:21 +08:00
Your Name a3d2d3170d 更新 2026-10-23 10:40:43 +08:00
Your Name e974d3cfa5 更新 2026-10-23 10:17:09 +08:00
Your Name 1cbe8bfe54 Merge branch 'master-10-146' 2026-10-23 09:27:23 +08:00
Your Name 3f15786491 更新 2026-10-23 09:26:49 +08:00
Your Name 448db32fb2 Merge branch 'master-10-146' 2026-10-22 16:43:05 +08:00
Your Name 14abf67d0d 更新 2026-10-22 16:42:26 +08:00
Your Name 8fd267e229 新增 2026-10-22 11:10:04 +08:00
Your Name 7982aab721 更新 2026-10-22 11:02:57 +08:00
Your Name d61bb3e117 更新 2026-10-17 17:24:04 +08:00
Your Name 872b19ef28 更新 2026-10-17 16:57:45 +08:00
Your Name 79d6744193 Merge branch 'master-10-146' 2026-10-17 16:52:17 +08:00
Your Name ba2e2e4087 更新 2026-10-17 16:51:48 +08:00
Your Name 908f356bce 更新 2026-10-17 16:13:23 +08:00
Your Name 56f85f7d89 更新 2026-10-17 16:08:24 +08:00
gr c67b3eff69 i更新 2026-10-15 12:00:09 +08:00
gr d4b81b40c2 ige 2026-10-15 11:56:36 +08:00
long bcd42a5c39 feat(followup-audio): separate uploader-only recording delete permission 2026-10-12 16:36:47 +08:00
long 11306e6314 fix(followup-audio): handle unsigned zero menu sort during permission migration 2026-10-12 15:18:37 +08:00
long 8f7544c1ad feat(followup-audio): add independent assignable recording permission 2026-10-12 15:14:19 +08:00
long 86041042b9 feat(followup-audio): normalize extraction to record field contracts 2026-10-12 14:34:31 +08:00
long 9e3aa9fc61 feat(followup-audio): confirm role corrections and reextract cached transcripts 2026-10-12 12:24:34 +08:00
long 2dfec801e7 fix(followup-audio): keep entry visible during capability failures 2026-10-12 11:02:13 +08:00
long 14e1722291 feat(followup-audio): soft delete unadopted recordings and expose extraction doubts 2026-10-12 10:39:12 +08:00
1639 changed files with 173626 additions and 5563 deletions
+31
View File
@@ -0,0 +1,31 @@
<!doctype html>
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="referrer" content="no-referrer"><title>集团账号登录 · 互联网医院</title>
<style>body{margin:0;min-height:100vh;display:grid;place-items:center;background:#f3f7f6;color:#183d37;font-family:system-ui,sans-serif}main{width:min(390px,calc(100% - 80px));padding:40px;background:#fff;border:1px solid #dce8e4;border-radius:20px;box-shadow:0 16px 56px #163d3710}.label{font-size:13px;letter-spacing:3px;color:#6e817c}h1{font-size:30px;margin:20px 0}p{line-height:1.8;color:#60736e}button{width:100%;margin-top:20px;padding:13px;border:0;border-radius:9px;background:#176453;color:white;cursor:pointer}a{display:block;margin-top:24px;color:#176453;font-size:14px}</style></head>
<body><main><span class="label">甄养堂集团</span><h1>互联网医院</h1><p id="status" role="status">正在连接集团账号…</p><button id="retry" hidden>重新发起登录</button><a href="/admin/login">使用医院账号登录</a></main>
<script type="module">
import { beginGroupLogin, consumeGroupCallback, exchangeGroupCode, groupLoginDestination } from '/admin/group-sso.mjs'
const settings = { identityOrigin: 'http://127.0.0.1:5173', hospitalOrigin: location.origin, storage: sessionStorage }
const status = document.querySelector('#status')
const retry = document.querySelector('#retry')
let running = false
async function connect() {
if (running) return
running = true
retry.hidden = true
try {
if (location.origin !== 'http://127.0.0.1:8090') throw new Error('仅供固定回环预览')
if (location.search || location.hash) {
const transaction = consumeGroupCallback({ ...settings, url: location.href, history })
status.textContent = '正在安全进入互联网医院…'
const session = await exchangeGroupCode({ ...settings, transaction })
localStorage.setItem('like_admin_token', JSON.stringify({ value: session.token, expire: '' }))
location.replace(groupLoginDestination(session))
} else location.assign(await beginGroupLogin(settings))
} catch {
status.textContent = '本次登录未完成或凭据已过期,请重新进入。'
retry.hidden = false
} finally { running = false }
}
retry.addEventListener('click', connect)
void connect()
</script></body></html>
+106
View File
@@ -0,0 +1,106 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { webcrypto } from 'node:crypto'
import { beginGroupLogin, consumeGroupCallback, exchangeGroupCode, fixedOrigin, groupLoginDestination, GROUP_TRANSACTION_KEY, pkceChallenge } from '../src/utils/groupSso.mjs'
const identityOrigin = 'http://127.0.0.1:5173'
const hospitalOrigin = 'http://127.0.0.1:8090'
const verifier = 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk'
function store() {
const values = new Map()
return { getItem: (key) => values.get(key) ?? null, setItem: (key, value) => values.set(key, value), removeItem: (key) => values.delete(key) }
}
async function transaction() {
const storage = store()
const target = new URL(await beginGroupLogin({ identityOrigin, hospitalOrigin, storage, cryptoApi: webcrypto, now: 1000 }))
const history = { state: null, calls: [], replaceState(...args) { this.calls.push(args) } }
const url = new URL('/admin/group-login', hospitalOrigin)
url.search = new URLSearchParams({ code: 'c'.repeat(64), state: target.searchParams.get('state') }).toString()
return { storage, target, history, url }
}
function consume(fixture, overrides = {}) {
return consumeGroupCallback({ ...fixture, url: fixture.url.href, identityOrigin, hospitalOrigin, now: 1500, ...overrides })
}
test('S256 对照 RFC 7636 向量', async () => {
assert.equal(await pkceChallenge(verifier, webcrypto), 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM')
})
test('只允许 HTTPS 或回环 HTTP 固定 origin', () => {
assert.equal(fixedOrigin(identityOrigin), identityOrigin)
for (const value of ['http://example.com', identityOrigin + '/bad', identityOrigin + '?redirect=x', 'https://u:p@example.com', 'javascript:alert(1)']) {
assert.throws(() => fixedOrigin(value))
}
})
test('初始化在医院存 verifier,授权 URL 仅有 S256 challenge', async () => {
const fixture = await transaction()
const saved = JSON.parse(fixture.storage.getItem(GROUP_TRANSACTION_KEY))
assert.equal(saved.verifier.length, 43)
assert.equal(saved.state.length, 43)
assert.equal(fixture.target.pathname, '/sso/authorize')
assert.equal(fixture.target.searchParams.get('redirect_uri'), hospitalOrigin + '/admin/group-login')
assert.equal(fixture.target.searchParams.get('code_challenge'), await pkceChallenge(saved.verifier, webcrypto))
assert.equal(fixture.target.href.includes(saved.verifier), false)
})
test('回调同步清 URL 和消费本地事务,不能重放', async () => {
const fixture = await transaction()
const result = consume(fixture)
assert.equal(result.code, 'c'.repeat(64))
assert.equal(fixture.history.calls[0][2], '/admin/group-login')
assert.equal(fixture.storage.getItem(GROUP_TRANSACTION_KEY), null)
assert.throws(() => consume(fixture))
})
test('拒绝错误 state、过期、未来事务、任意 redirect、重复参数和错误医院地址', async () => {
for (const mutate of [
(f) => f.url.searchParams.set('state', 'x'.repeat(43)),
(f) => f.url.searchParams.set('redirect', 'https://example.com'),
(f) => f.url.searchParams.append('code', 'x'.repeat(64)),
(f) => { f.url.pathname = '/admin/login' },
(f) => { f.url.hash = 'unexpected' },
(f) => { const saved = JSON.parse(f.storage.getItem(GROUP_TRANSACTION_KEY)); saved.createdAt = -400000; f.storage.setItem(GROUP_TRANSACTION_KEY, JSON.stringify(saved)) },
(f) => { const saved = JSON.parse(f.storage.getItem(GROUP_TRANSACTION_KEY)); saved.createdAt = 2000; f.storage.setItem(GROUP_TRANSACTION_KEY, JSON.stringify(saved)) }
]) {
const fixture = await transaction()
mutate(fixture)
assert.throws(() => consume(fixture))
assert.equal(fixture.history.calls.length, 1)
assert.equal(fixture.storage.getItem(GROUP_TRANSACTION_KEY), null)
}
})
test('只执行中央/医院两次 POST,不携带旧 token、拒绝响应指定任意兑换地址', async () => {
const fixture = await transaction()
const current = consume(fixture)
const calls = []
const responses = [{ ticket: 't'.repeat(64), exchange_path: '/adminapi/identity.hospitalSso/exchange' }, { token: 'fixture-hospital-session-only', is_paw: 1 }]
const result = await exchangeGroupCode({ transaction: current, identityOrigin, hospitalOrigin, fetcher: async (url, options) => {
calls.push({ url, options }); return { ok: true, json: async () => ({ code: 1, data: responses.shift() }) }
} })
assert.equal(result.is_paw, 1)
assert.equal(calls.length, 2)
assert.equal(calls[0].url, identityOrigin + '/adminapi/group/sso/exchange')
assert.equal(calls[1].url, hospitalOrigin + '/adminapi/identity.hospitalSso/exchange')
assert.equal(calls[0].options.credentials, 'omit')
assert.equal(calls[1].options.credentials, 'same-origin')
assert.equal(calls.every(({ options }) => options.method === 'POST' && options.redirect === 'error' && !options.headers.Authorization && !options.headers.token), true)
let rejectedCalls = 0
await assert.rejects(exchangeGroupCode({ transaction: current, identityOrigin, hospitalOrigin, fetcher: async () => {
rejectedCalls++; return { ok: true, json: async () => ({ code: 1, data: { ticket: 't'.repeat(64), exchange_path: 'https://example.com' } }) }
} }))
assert.equal(rejectedCalls, 1)
})
test('网络失败不重试,首次改密与企微门禁保留', async () => {
const fixture = await transaction()
let count = 0
await assert.rejects(exchangeGroupCode({ transaction: consume(fixture), identityOrigin, hospitalOrigin, fetcher: async () => { count++; throw new Error('fixture offline') } }))
assert.equal(count, 1)
const secondFixture = await transaction()
count = 0
await assert.rejects(exchangeGroupCode({ transaction: consume(secondFixture), identityOrigin, hospitalOrigin, fetcher: async () => {
count++
if (count === 2) throw new Error('fixture hospital offline')
return { ok: true, json: async () => ({ code: 1, data: { ticket: 't'.repeat(64), exchange_path: '/adminapi/identity.hospitalSso/exchange' } }) }
} }))
assert.equal(count, 2)
assert.equal(groupLoginDestination({ is_paw: 0, need_bind_work_wechat: true }), '/admin/change-password')
assert.equal(groupLoginDestination({ is_paw: 1, need_bind_work_wechat: true }), '/admin/bind-work-wechat')
assert.equal(groupLoginDestination({ is_paw: 1 }), '/admin/')
})
+87
View File
@@ -0,0 +1,87 @@
<?php
declare(strict_types=1);
// 仅供回环预览:静态文件来自隔离副本,PHP 只从固定原入口加载。
$project = realpath(__DIR__ . '/../..');
$public = $project . '/server/public';
$preview = $project . '/.test-runtime/hospital-preview/admin';
$path = (string) parse_url($_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH);
$method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');
header('Referrer-Policy: no-referrer');
header('X-Content-Type-Options: nosniff');
header('Cache-Control: no-store');
function missing(): never
{
http_response_code(404);
header('Content-Type: application/json; charset=utf-8');
echo '{"code":0,"msg":"接口不存在","data":{}}';
exit;
}
if (!in_array($_SERVER['REMOTE_ADDR'] ?? '', ['127.0.0.1', '::1'], true)
|| !in_array($_SERVER['HTTP_HOST'] ?? '', ['127.0.0.1:8090', 'localhost:8090'], true)
|| array_key_exists('s', $_GET) || preg_match('/[\\\\\x00-\x20\x7f]/', $path)) {
missing();
}
if (in_array($method, ['GET', 'HEAD'], true) && ($path === '/admin' || str_starts_with($path, '/admin/'))) {
if ($path === '/admin/group-login') {
$file = $preview . '/group-login.html';
$type = 'text/html; charset=utf-8';
} elseif ($path === '/admin/group-sso.mjs') {
$file = $preview . '/group-sso.mjs';
$type = 'text/javascript; charset=utf-8';
} elseif (preg_match('~^/admin/(assets/[A-Za-z0-9_.@/-]+|ai-chat-icon\.png)$~D', $path)) {
$file = realpath($preview . substr($path, strlen('/admin')));
$base = realpath($preview);
$normalizedFile = is_string($file) ? str_replace('\\', '/', $file) : '';
$normalizedBase = is_string($base) ? str_replace('\\', '/', $base) . '/' : '';
if (!$file || !$base || !str_starts_with($normalizedFile, $normalizedBase) || !is_file($file)) { missing(); }
$types = ['js' => 'text/javascript', 'mjs' => 'text/javascript', 'css' => 'text/css', 'png' => 'image/png',
'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'gif' => 'image/gif', 'webp' => 'image/webp', 'svg' => 'image/svg+xml',
'woff' => 'font/woff', 'woff2' => 'font/woff2', 'ttf' => 'font/ttf', 'ico' => 'image/x-icon'];
$type = $types[strtolower(pathinfo($file, PATHINFO_EXTENSION))] ?? null;
if ($type === null) { missing(); }
} elseif (preg_match('~^/admin(?:/[A-Za-z0-9_-]+)*/?$~D', $path)) {
$file = $preview . '/index.html';
$type = 'text/html; charset=utf-8';
} else { missing(); }
if (!is_file($file)) { missing(); }
header('Content-Type: ' . $type);
if ($method !== 'HEAD') { readfile($file); }
exit;
}
// 不透传任意磁盘路径、安装器、测试脚本或 PHP 文件。
if (!in_array($method, ['GET', 'POST', 'OPTIONS'], true)
|| !preg_match('~^/adminapi/[A-Za-z][A-Za-z0-9_.]*/[A-Za-z][A-Za-z0-9_]*$~D', $path)) {
missing();
}
$root = $project . '/server';
if (!is_file($root . '/vendor/autoload.php') || !is_file($root . '/config/install.lock')) {
http_response_code(503);
header('Content-Type: application/json; charset=utf-8');
echo '{"code":0,"msg":"原项目服务尚未配置","data":{}}';
exit;
}
require $root . '/vendor/autoload.php';
$_SERVER['SCRIPT_FILENAME'] = $public . '/index.php';
$_SERVER['SCRIPT_NAME'] = '/index.php';
$_SERVER['PHP_SELF'] = '/index.php';
$_SERVER['PATH_INFO'] = $path;
foreach (['HTTP_X_FORWARDED_HOST', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP'] as $key) { unset($_SERVER[$key]); }
$application = new class($root . DIRECTORY_SEPARATOR) extends think\App {
public function loadEnv(string $envName = ''): void
{
parent::loadEnv($envName);
$this->env->set('APP_DEBUG', false);
$this->env->set('LOCAL_DEBUG_LOGIN_SKIP_PASSWORD', false);
}
};
$application->initialize();
$application->request->setPathinfo(ltrim($path, '/'));
$http = $application->http;
$response = $http->run();
$response->send();
$http->end($response);
@@ -0,0 +1,29 @@
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const project = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..')
const source = path.join(project, 'server/public/admin')
const runtime = path.join(project, '.test-runtime')
const output = path.join(runtime, 'hospital-preview')
const target = path.join(output, 'admin')
const sourceHtml = fs.readFileSync(path.join(source, 'index.html'), 'utf8')
const entryPath = sourceHtml.match(/<script\b[^>]*\bsrc="\/admin\/assets\/([^"/]+\.js)"/i)?.[1]
if (!entryPath) throw new Error('未找到原医院构建入口')
const entry = fs.readFileSync(path.join(source, 'assets', entryPath), 'utf8')
const original = 'baseUrl:"https://admin.zhenyangtang.com.cn//"'
if (entry.split(original).length !== 2) throw new Error('医院公开 API baseUrl 字面量必须恰好出现一次')
fs.mkdirSync(runtime, { recursive: true })
// 只忽略生成物,不修改根 .gitignore 或原发布目录。
const ignoreFile = path.join(runtime, '.gitignore')
if (!fs.existsSync(ignoreFile)) fs.writeFileSync(ignoreFile, '*\n')
fs.cpSync(source, target, { recursive: true, force: true })
fs.writeFileSync(path.join(target, 'assets', entryPath), entry.replace(original, 'baseUrl:"/"'))
// 预览只加载原本地模块;不启动原 HTML 附带的远程客服/音视频脚本及其内联初始化。
const previewHtml = sourceHtml.replace(/<script\b([^>]*)>[\s\S]*?<\/script>/gi, (tag, attrs) =>
/\bsrc="\/admin\/assets\/[^"/]+\.js"/.test(attrs) ? tag : '')
fs.writeFileSync(path.join(target, 'index.html'), previewHtml.replace('<title>后台管理系统</title>', '<title>互联网医院</title>'))
fs.copyFileSync(path.join(project, 'admin/src/utils/groupSso.mjs'), path.join(target, 'group-sso.mjs'))
fs.copyFileSync(path.join(project, 'admin/public/group-login.html'), path.join(target, 'group-login.html'))
if (fs.readFileSync(path.join(target, 'assets', entryPath), 'utf8').includes(original)) throw new Error('本地 API 适配未完成')
process.stdout.write(JSON.stringify({ path: output, entry: entryPath }) + '\n')
+18
View File
@@ -0,0 +1,18 @@
param(
[string]$PhpPath = 'C:\Users\isard\.cache\zyt-tools\php\php.exe'
)
$ErrorActionPreference = 'Stop'
$projectPath = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
if (-not (Test-Path -LiteralPath $PhpPath -PathType Leaf)) { throw 'PHP 可执行文件不存在' }
if (Get-NetTCPConnection -LocalPort 8090 -State Listen -ErrorAction SilentlyContinue) { throw '8090 端口已占用,未停止任何进程' }
& node (Join-Path $PSScriptRoot 'prepare-hospital-preview.mjs')
if ($LASTEXITCODE -ne 0) { throw '医院预览准备失败' }
$runtimePath = Join-Path $projectPath '.test-runtime\hospital-preview'
$routerPath = Join-Path $PSScriptRoot 'hospital-preview-router.php'
$publicPath = Join-Path $projectPath 'server\public'
$arguments = @('-S', '127.0.0.1:8090', '-t', ('"' + $publicPath + '"'), ('"' + $routerPath + '"'))
# 隐藏控制台,不将 PHP 请求日志重定向到文件,避免保存回调 URL 中的短码。
$process = Start-Process -FilePath $PhpPath -ArgumentList $arguments -WorkingDirectory (Join-Path $projectPath 'server') -WindowStyle Hidden -PassThru
$state = [ordered]@{ pid = $process.Id; port = 8090; path = $runtimePath }
$state | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $runtimePath 'status.json') -Encoding utf8
$state | ConvertTo-Json
+32
View File
@@ -0,0 +1,32 @@
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const project = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..')
const base = 'http://127.0.0.1:8090'
const callback = await fetch(base + '/admin/group-login')
const callbackText = await callback.text()
if (callback.status !== 200 || !callbackText.includes('集团账号登录') || !callbackText.includes('/admin/group-sso.mjs')) throw new Error('医院回调入口验证失败')
const moduleResponse = await fetch(base + '/admin/group-sso.mjs')
if (moduleResponse.status !== 200 || !(moduleResponse.headers.get('content-type') || '').includes('javascript')) throw new Error('医院登录模块验证失败')
const page = await fetch(base + '/admin/')
const html = await page.text()
if (!html.includes('<title>互联网医院</title>') || /<script[^>]+src="https?:/i.test(html)) throw new Error('预览标题或远程脚本边界验证失败')
const asset = html.match(/<script\b[^>]*\bsrc="(\/admin\/assets\/[^"/]+\.js)"/i)?.[1]
if (!asset) throw new Error('未找到预览入口模块')
const bundle = await (await fetch(base + asset)).text()
if (!bundle.includes('baseUrl:"/"') || bundle.includes('baseUrl:"https://admin.zhenyangtang.com.cn//"')) throw new Error('预览 API 地址验证失败')
const paths = ['/test.php', '/admin/assets/anything.php', '/install/install.php', '/admin/group-login?s=auth.admin/mySelf']
for (const route of paths) {
if ((await fetch(base + route)).status !== 404) throw new Error('静态路径或兼容路由未被拒绝')
}
const denied = await (await fetch(base + '/adminapi/auth.admin/mySelf')).json()
if (denied.code === 1) throw new Error('未认证 API 意外放行')
const original = fs.readFileSync(path.join(project, 'server/public' + asset), 'utf8')
if (!original.includes('baseUrl:"https://admin.zhenyangtang.com.cn//"')) throw new Error('原发布产物发生修改')
const runtime = path.join(project, '.test-runtime/hospital-preview')
if (['php.stdout.log', 'php.stderr.log'].some((name) => fs.existsSync(path.join(runtime, name)))) throw new Error('预览不应生成持久化请求日志')
const state = JSON.parse(fs.readFileSync(path.join(runtime, 'status.json'), 'utf8').replace(/^\uFEFF/, ''))
if (Object.keys(state).sort().join(',') !== 'path,pid,port') throw new Error('启动状态包含额外字段')
fs.writeFileSync(path.join(project, 'artifacts/iam-extraction/hospital-preview-status.json'), JSON.stringify(state, null, 2) + '\n')
process.stdout.write('医院预览验证通过:回调/模块/首页 200,本地 API,4 条危险路径 404,未认证拒绝,无请求日志,原产物未改。\n')
+8
View File
@@ -5,6 +5,14 @@ export function getConfig() {
return request.get({ url: '/config/getConfig' })
}
// 运行时读取医生网页面诊切换时间,与服务端拦截规则共用配置。
export function getDoctorWebConsultationPolicy() {
return request.get(
{ url: '/config/doctorWebConsultation', params: { _t: Date.now() } },
{ withToken: false, isOpenRetry: false }
)
}
// 工作台主页
export function getWorkbench() {
return request.get({ url: '/workbench/index' })
+14
View File
@@ -75,6 +75,8 @@ export interface FollowupTaskSummary {
version: number
created_at: number | string
expires_at: number | string
can_delete?: boolean
delete_block_reason?: string
can_retry: boolean
audio_available: boolean
preview_only?: boolean
@@ -82,6 +84,16 @@ export interface FollowupTaskSummary {
pipeline_progress?: { transcribed: number; total: number }
}
export interface FollowupTaskDetail extends FollowupTaskSummary {
extraction_revision?: number
extraction_channel_roles?: FollowupChannelRoles
can_reextract?: boolean
reextract_block_reason?: string
role_check?: {
conflict: boolean
suggested_roles: FollowupChannelRoles
message: string
evidence: Array<{ channel: FollowupAudioChannel; start_ms: number; end_ms: number; text: string }>
}
summary: string
transcript: string
transcript_segments?: FollowupTranscriptSegment[]
@@ -130,6 +142,8 @@ export const followupAudioUploadComplete = (uploadId: string, signal?: AbortSign
export const followupAudioCreate = (data: { diagnosis_id: number; upload_id: string; recorded_at: string; model_key: string; channel_roles?: FollowupChannelRoles }, signal?: AbortSignal) => post<{ task_id: number; status: string; reused?: boolean; reuse_message?: string }>('create', data, signal)
export const followupAudioSaveDraft = (data: { id: number; version: number; items: FollowupReviewItem[]; channel_roles?: FollowupChannelRoles }, signal?: AbortSignal) => post<FollowupTaskDetail>('saveDraft', data, signal)
export const followupAudioApply = (data: { id: number; version: number; items: FollowupReviewItem[] }, signal?: AbortSignal) => post<{ id: number; status: 'applied'; applied_items: unknown[] }>('apply', data, signal)
export const followupAudioReextract = (data: { id: number; version: number; channel_roles: Exclude<FollowupChannelRoles, 'unconfirmed'> }, signal?: AbortSignal) => post<FollowupTaskDetail>('reextract', data, signal)
export const followupAudioDelete = (data: { id: number; version: number }, signal?: AbortSignal) => post<{ id: number; status: 'deleted'; version: number }>('delete', data, signal)
export const followupAudioRetry = (id: number, signal?: AbortSignal) => post<{ id: number; status: string }>('retry', { id }, signal)
/** The existing request interceptor puts the token in a header, never in the audio URL. */
export async function followupAudioBlob(id: number, signal?: AbortSignal): Promise<Blob> {
@@ -24,6 +24,24 @@ export type DesktopWorkstationConfig = {
}
}
export type DesktopWorkstationDownload = DesktopPackage & {
platform: 'windows_x64' | 'macos_arm64' | 'macos_x64'
label: string
}
export type DesktopWorkstationDownloads = {
version: string
packages: DesktopWorkstationDownload[]
}
// 仅返回已发布的安装包,不要求医生拥有系统设置权限。
export function getDesktopWorkstationDownloads() {
return request.get(
{ url: '/setting.desktop_workstation/downloads' },
{ withToken: false }
) as Promise<DesktopWorkstationDownloads>
}
export function getDesktopWorkstationConfig() {
return request.get({
url: '/setting.desktop_workstation/getConfig'
@@ -0,0 +1,49 @@
import request from '@/utils/request'
export interface PrescriptionAiVisibilityConfig {
role_ids: number[]
admin_ids: number[]
}
export interface PrescriptionAiVisibilityOptions {
roles: { id: number; name: string }[]
admins: { id: number; name: string; account: string }[]
}
export interface PrescriptionAiCapabilities {
agreement_visible: boolean
can_manage_visibility: boolean
}
// A failed or malformed read must never become an empty policy that can be saved.
function readVisibilityConfig(value: unknown): PrescriptionAiVisibilityConfig {
const config = value as Partial<PrescriptionAiVisibilityConfig> | null
const validIds = (ids: unknown): ids is number[] =>
Array.isArray(ids) && ids.every((id) => Number.isSafeInteger(id) && id > 0)
if (!config || !validIds(config.role_ids) || !validIds(config.admin_ids)) {
throw new Error('可见范围配置响应格式不正确')
}
return { role_ids: [...config.role_ids], admin_ids: [...config.admin_ids] }
}
export async function getPrescriptionAiVisibilityConfig() {
const data = await request.get({ url: '/tcm.prescriptionAi/getVisibilityConfig' })
return readVisibilityConfig(data)
}
export async function setPrescriptionAiVisibilityConfig(params: PrescriptionAiVisibilityConfig) {
const data = await request.post({ url: '/tcm.prescriptionAi/setVisibilityConfig', params })
return readVisibilityConfig(data)
}
export function getPrescriptionAiVisibilityOptions() {
return request.get({
url: '/tcm.prescriptionAi/visibilityOptions'
}) as Promise<PrescriptionAiVisibilityOptions>
}
export function getPrescriptionAiCapabilities() {
return request.get({
url: '/tcm.prescriptionAi/capabilities'
}) as Promise<PrescriptionAiCapabilities>
}
+38
View File
@@ -299,3 +299,41 @@ export function assistantPerformanceRevisitRate(params: {
}): Promise<AssistantRevisitRateResult> {
return request.get({ url: '/stats.assistantPerformance/revisitRate', params })
}
/** 独立指派周期统计,与原 revisitRate 按月报表分别调用。 */
export type RevisitRateCohortType = 'new' | 'inherit'
export interface RevisitRateQuery {
start_date: string
end_date: string
dept_ids?: string
assistant_id?: number
}
export interface RevisitRateDetailQuery extends RevisitRateQuery {
scope_assistant_id?: number
dept_id?: number
}
const revisitCohortPrefix = (cohortType: RevisitRateCohortType) =>
cohortType === 'inherit' ? '/stats.revisitInheritRate' : '/stats.revisitAssignRate'
export function revisitCohortOverview(params: RevisitRateQuery, cohortType: RevisitRateCohortType) {
return request.get({ url: `${revisitCohortPrefix(cohortType)}/overview`, params })
}
export function revisitCohortDeptOptions(cohortType: RevisitRateCohortType) {
return request.get({ url: `${revisitCohortPrefix(cohortType)}/deptOptions` })
}
export function revisitCohortAssignLines(params: RevisitRateDetailQuery, cohortType: RevisitRateCohortType) {
return request.get({ url: `${revisitCohortPrefix(cohortType)}/assignLines`, params })
}
export function revisitCohortVisitOrderLines(
params: RevisitRateDetailQuery & { slot: number },
cohortType: RevisitRateCohortType
) {
return request.get({ url: `${revisitCohortPrefix(cohortType)}/visitOrderLines`, params })
}
+25
View File
@@ -227,6 +227,29 @@ export function getCallRecords(params: any) {
return request.get({ url: '/tcm.diagnosis/getCallRecords', params })
}
export interface ConsultationCallRecord {
id: number
diagnosis_id: number
call_type?: number
status?: number
start_time?: number
start_time_text?: string
end_time_text?: string
duration_text?: string
transcript_text?: string | null
transcription_status?: string
transcription_status_text?: string
transcription_segment_count?: number
}
/** 按诊单读取每次面诊已保存的文字;不触发语音识别或转写写入。 */
export function getConsultationTranscripts(params: { diagnosis_id: number }, signal?: AbortSignal) {
return request.get<ConsultationCallRecord[]>(
{ url: '/tcm.diagnosis/getCallRecords', params, signal },
{ ignoreCancelToken: true }
)
}
// 将 TRTC 房间号写入通话记录(与云端录制回调 room 关联)
export function bindCallRoom(params: { diagnosis_id: number; room_id: string }) {
return request.post({ url: '/tcm.diagnosis/bindCallRoom', params })
@@ -490,8 +513,10 @@ export function prescriptionOrderPatchPrescriptionUsage(params: {
times_per_day: number
usage_days: number
medication_days: number
dosage_bag_count?: number
aux_times_per_day?: number
aux_usage_days?: number
aux_dosage_bag_count?: number
}) {
return request.post({ url: '/tcm.prescriptionOrder/patchPrescriptionUsage', params })
}
+18 -2
View File
@@ -34,6 +34,7 @@
</div>
</div>
<DoctorWebConsultationNotice v-if="!isMinimized" />
<div v-show="!isMinimized" class="chat-container">
<div v-if="!isReady" class="loading-container">
<el-icon class="is-loading"><Loading /></el-icon>
@@ -131,6 +132,8 @@
<script setup lang="ts">
import { ref, nextTick, watch, computed, onMounted, onUnmounted } from 'vue'
import DoctorWebConsultationNotice from '@/components/doctor-web-consultation-notice/index.vue'
import { useDoctorWebConsultation } from '@/hooks/useDoctorWebConsultation'
import { Loading, Close, Rank, Camera, Fold, Expand } from '@element-plus/icons-vue'
import { uploadImageBlob, uploadVideoBlob } from '@/api/file'
import { addDoctorNote } from '@/api/patient'
@@ -195,8 +198,9 @@ const appointmentTypeLabel = computed(() => confirmedTypeLabel.value || appointm
const serverAllowsVideo = ref(false)
const serverAllowsAudio = ref(false)
const callDisabledReason = ref('正在确认挂号类型')
const canVideoCall = computed(() => serverAllowsVideo.value && canAppointmentVideoCall(appointmentType.value))
const canAudioCall = computed(() => serverAllowsAudio.value && (canAppointmentVideoCall(appointmentType.value) || appointmentType.value === 'phone'))
const { webConsultationBlocked, webConsultationMessage, ensureWebConsultationAllowed } = useDoctorWebConsultation()
const canVideoCall = computed(() => !webConsultationBlocked.value && serverAllowsVideo.value && canAppointmentVideoCall(appointmentType.value))
const canAudioCall = computed(() => !webConsultationBlocked.value && serverAllowsAudio.value && (canAppointmentVideoCall(appointmentType.value) || appointmentType.value === 'phone'))
let releaseAppointmentCallGuard: (() => void) | undefined
let chatContextVersion = 0
let outgoingCallType = 2
@@ -253,6 +257,7 @@ function syncAppointmentCallPolicy(res: {
}
async function prepareAppointmentCall(callType: number) {
if (!ensureWebConsultationAllowed()) throw new Error(webConsultationMessage.value)
const contextVersion = chatContextVersion
const allowed = () => callType === 1 ? canAudioCall.value : canVideoCall.value
if (!visible.value || !allowed()) {
@@ -266,6 +271,7 @@ async function prepareAppointmentCall(callType: number) {
})
if (!visible.value || chatContextVersion !== contextVersion) throw new Error('当前问诊已切换,请重新发起通话')
syncAppointmentCallPolicy(res)
if (!ensureWebConsultationAllowed()) throw new Error(webConsultationMessage.value)
if (!allowed()) {
feedback.msgWarning(callDisabledReason.value)
throw new Error(callDisabledReason.value)
@@ -713,6 +719,14 @@ function installTUICallKitRoomHooks() {
wrap('calls')
wrap('call')
wrap('groupCall')
// 已登录 SDK 的旧聊天窗口也不能在截止后接起新面诊。
const originalAccept = server.accept
if (typeof originalAccept === 'function') {
server.accept = async function patchedAccept(...args: unknown[]) {
if (!ensureWebConsultationAllowed()) throw new Error(webConsultationMessage.value)
return originalAccept.apply(server, args)
}
}
}
async function doBindCallRoom(rid: string) {
@@ -1099,6 +1113,7 @@ watch(() => activeConversation.value, async (newConversation) => {
})
const open = async (data: { patientId: number; patientName: string; diagnosisId?: number; appointmentId?: number; appointmentType?: string | null }) => {
if (!ensureWebConsultationAllowed()) return
stopChatArchiveWatch(true)
const contextVersion = ++chatContextVersion
releaseAppointmentCallGuard?.()
@@ -1260,6 +1275,7 @@ const open = async (data: { patientId: number; patientName: string; diagnosisId?
// 群组视频通话(多人通话):当前医生作为发起方,默认先邀请当前会话患者
const startGroupVideoCall = async () => {
if (!ensureWebConsultationAllowed()) return
if (!canVideoCall.value) {
feedback.msgWarning(appointmentType.value === 'text' ? '图文问诊不支持视频通话' : callDisabledReason.value)
return
@@ -0,0 +1,102 @@
<template>
<el-alert
class="doctor-web-consultation-notice"
:type="consultationReminder.type"
:closable="false"
show-icon
:title="consultationReminder.title"
>
<p>{{ consultationReminder.description }}</p>
<p v-if="policyLoadFailed">
面诊切换时间更新失败,请重新获取最新设置。
<el-button link type="primary" @click="refreshConsultationPolicy()">刷新切换时间</el-button>
</p>
<p v-if="consultationReminder.countdown" class="notice-countdown">
距网页端面诊停用还有 {{ consultationReminder.countdown }}(北京时间)
</p>
<div class="notice-downloads">
<a
v-for="item in downloads.packages"
:key="item.platform"
class="installer-link"
:href="item.url"
:download="item.filename || undefined"
target="_blank"
rel="noopener noreferrer"
>
<el-icon><Download /></el-icon>
下载 {{ item.label }}安装包
</a>
<span v-if="downloadsLoading && !downloads.packages.length">正在获取安装包…</span>
<template v-else-if="!downloads.packages.length">
<span>{{ downloadsFailed ? '安装包加载失败,请重试。' : '安装包暂未发布,请联系管理员获取。' }}</span>
<el-button link type="primary" @click="loadDownloads(true)">重新获取</el-button>
</template>
<el-button v-else-if="downloadsFailed" link type="primary" @click="loadDownloads(true)">刷新安装包</el-button>
</div>
<p v-if="downloads.packages.length" class="install-instructions">
<span v-if="downloads.version">当前版本 v{{ downloads.version }} · </span>
安装完成后,使用当前医生账号登录桌面应用。
</p>
<p v-if="hasWindowsInstaller" class="install-instructions">
Windows 安装包适用于 Windows 10 1809 及以上版本、Windows 11(64位)。
</p>
</el-alert>
</template>
<script setup lang="ts">
import { useDoctorWebConsultation } from '@/hooks/useDoctorWebConsultation'
import { useDesktopWorkstationDownloads } from '@/hooks/useDesktopWorkstationDownloads'
import { Download } from '@element-plus/icons-vue'
import { computed, watch } from 'vue'
const { consultationReminder, policyLoadFailed, refreshConsultationPolicy } = useDoctorWebConsultation()
const { downloads, downloadsLoading, downloadsFailed, loadDownloads } = useDesktopWorkstationDownloads()
const hasWindowsInstaller = computed(() => downloads.value.packages.some(item => item.platform === 'windows_x64'))
watch(() => consultationReminder.value.phase, () => { void loadDownloads(true) })
</script>
<style scoped>
.doctor-web-consultation-notice {
flex-shrink: 0;
margin-bottom: 16px;
}
.doctor-web-consultation-notice p {
margin: 4px 0 0;
font-size: 14px;
line-height: 1.7;
}
.notice-countdown {
font-weight: 600;
}
.notice-downloads {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px 12px;
margin-top: 12px;
}
.installer-link {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 7px 12px;
border-radius: 6px;
color: #fff;
background: #2563eb;
font-size: 14px;
line-height: 1.5;
text-decoration: none;
}
.installer-link:hover {
background: #1d4ed8;
}
.installer-link:focus-visible {
outline: 2px solid #1d4ed8;
outline-offset: 3px;
}
.doctor-web-consultation-notice .install-instructions {
margin-top: 8px;
font-size: 13px;
}
</style>
+1 -1
View File
@@ -1,6 +1,6 @@
const config = {
terminal: 1, //终端
title: '后台管理系统', //网站默认标题
title: '互联网医院', //网站默认标题
version: '1.9.4', //版本号
baseUrl: `${import.meta.env.VITE_APP_BASE_URL || ''}/`, //请求接口域名
urlPrefix: 'adminapi', //请求默认前缀
@@ -0,0 +1,47 @@
import { onBeforeUnmount, ref, watch } from 'vue'
import { getConsultationTranscripts, type ConsultationCallRecord } from '@/api/tcm'
import { normalizeConsultationRecords } from '@/utils/consultation-transcripts'
export function useConsultationTranscripts(diagnosisId: () => number) {
const records = ref<ConsultationCallRecord[]>([])
const loading = ref(false)
const error = ref('')
let sequence = 0
let controller: AbortController | undefined
const refresh = async () => {
const id = Number(diagnosisId())
const request = ++sequence
controller?.abort()
error.value = ''
if (!Number.isSafeInteger(id) || id <= 0) {
records.value = []
loading.value = false
return
}
controller = new AbortController()
loading.value = true
try {
const result = await getConsultationTranscripts({ diagnosis_id: id }, controller.signal)
if (request !== sequence || Number(diagnosisId()) !== id) return
records.value = normalizeConsultationRecords(result, id)
} catch (reason: any) {
if (request !== sequence || Number(diagnosisId()) !== id) return
error.value = String(reason?.msg || reason?.message || '面诊文字对话加载失败,请重试')
} finally {
if (request === sequence) loading.value = false
}
}
watch(diagnosisId, () => {
records.value = []
void refresh()
}, { immediate: true, flush: 'sync' })
onBeforeUnmount(() => {
sequence++
controller?.abort()
records.value = []
})
return { records, loading, error, refresh }
}
@@ -0,0 +1,59 @@
import { onMounted, onUnmounted, ref, shallowRef } from 'vue'
import {
getDesktopWorkstationDownloads,
type DesktopWorkstationDownload,
type DesktopWorkstationDownloads
} from '@/api/setting/desktop_workstation'
// 接诊台、列表和聊天窗口共用一个请求与短缓存。
const downloads = shallowRef<DesktopWorkstationDownloads>({ version: '', packages: [] })
const downloadsLoading = ref(false)
const downloadsFailed = ref(false)
let pending: Promise<void> | undefined
let loadedAt = 0
const CACHE_MS = 5 * 60 * 1000
export function normalizeDesktopDownloads(value: DesktopWorkstationDownloads): DesktopWorkstationDownloads {
const platforms = ['windows_x64', 'macos_arm64', 'macos_x64']
const packages: DesktopWorkstationDownload[] = []
const seen = new Set<string>()
for (const item of Array.isArray(value?.packages) ? value.packages : []) {
if (!item || typeof item !== 'object') continue
if (!platforms.includes(item.platform) || seen.has(item.platform)) continue
try {
const url = new URL(item.url)
if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password) continue
if (!/^[a-f\d]{64}$/i.test(item.sha256)) continue
packages.push({ ...item, url: url.href })
seen.add(item.platform)
} catch { /* 配置异常时不生成无效下载链接。 */ }
}
return { version: String(value?.version || ''), packages }
}
export function useDesktopWorkstationDownloads() {
const loadDownloads = (force = false): Promise<void> => {
if (pending) return pending
if (!force && loadedAt > 0 && Date.now() - loadedAt < CACHE_MS) return Promise.resolve()
downloadsLoading.value = true
downloadsFailed.value = false
pending = getDesktopWorkstationDownloads().then(data => {
downloads.value = normalizeDesktopDownloads(data)
loadedAt = Date.now()
}).catch(() => {
downloadsFailed.value = true
}).finally(() => {
downloadsLoading.value = false
pending = undefined
})
return pending
}
const refreshOnFocus = () => { void loadDownloads() }
onMounted(() => {
void loadDownloads()
window.addEventListener('focus', refreshOnFocus)
})
onUnmounted(() => window.removeEventListener('focus', refreshOnFocus))
return { downloads, downloadsLoading, downloadsFailed, loadDownloads }
}
@@ -0,0 +1,88 @@
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
import { getDoctorWebConsultationPolicy } from '@/api/app'
import useUserStore from '@/stores/modules/user'
import feedback from '@/utils/feedback'
import {
doctorWebConsultationMessage,
doctorWebConsultationReminder,
hasDoctorWebConsultationExpired,
isConsultationDoctor,
isDoctorWebConsultationBlocked,
normalizeDoctorWebConsultationPolicy
} from '@/utils/doctor-web-consultation'
// 多个列表、公告及聊天窗口共用请求;配置更新无需重新构建前端。
let pending: Promise<void> | undefined
let lastAttemptAt = 0
const REFRESH_MS = 60 * 1000
const policyLoadFailed = ref(false)
export function useDoctorWebConsultation() {
const userStore = useUserStore()
const now = ref(Date.now())
let timer: ReturnType<typeof setInterval> | undefined
const updateClock = () => { now.value = Date.now() + (userStore.serverTimeOffsetMs || 0) }
const policy = computed(() => normalizeDoctorWebConsultationPolicy(userStore.userInfo.web_consultation_policy))
const loadPolicy = (force = false): Promise<void> => {
if (pending) return pending
if (!force && lastAttemptAt > 0 && Date.now() - lastAttemptAt < REFRESH_MS) return Promise.resolve()
lastAttemptAt = Date.now()
pending = getDoctorWebConsultationPolicy().then(data => {
const next = normalizeDoctorWebConsultationPolicy(data)
if (!next) throw new Error('网页面诊时间配置无效')
userStore.userInfo.web_consultation_policy = next
userStore.serverTimeOffsetMs = next.server_time * 1000 - Date.now()
policyLoadFailed.value = false
updateClock()
}).catch(() => {
// 保留最近一次有效配置,后端仍逐次校验实际截止时间。
policyLoadFailed.value = true
}).finally(() => { pending = undefined })
return pending
}
const refreshConsultationPolicy = () => loadPolicy(true)
const refreshOnFocus = () => {
updateClock()
void refreshConsultationPolicy()
}
const refreshOnVisible = () => {
if (document.visibilityState !== 'hidden') refreshOnFocus()
}
// 登录响应和配置刷新响应均提供服务器时刻,避免本机时区/时钟影响规则。
watch(() => userStore.serverTimeOffsetMs, updateClock, { immediate: true })
onMounted(() => {
updateClock()
void refreshConsultationPolicy()
timer = setInterval(() => {
updateClock()
void loadPolicy()
}, 1000)
window.addEventListener('focus', refreshOnFocus)
document.addEventListener('visibilitychange', refreshOnVisible)
})
onUnmounted(() => {
clearInterval(timer)
window.removeEventListener('focus', refreshOnFocus)
document.removeEventListener('visibilitychange', refreshOnVisible)
})
const isDoctor = computed(() => isConsultationDoctor(userStore.userInfo))
const webConsultationExpired = computed(() => hasDoctorWebConsultationExpired(policy.value, now.value))
const consultationReminder = computed(() => doctorWebConsultationReminder(policy.value, now.value))
const webConsultationMessage = computed(() => doctorWebConsultationMessage(policy.value))
const webConsultationBlocked = computed(() => isDoctorWebConsultationBlocked(userStore.userInfo, policy.value, now.value))
const ensureWebConsultationAllowed = () => {
updateClock()
if (!webConsultationBlocked.value) return true
feedback.msgWarning(webConsultationMessage.value)
return false
}
return {
isDoctor, consultationReminder, webConsultationExpired, webConsultationBlocked,
webConsultationMessage, ensureWebConsultationAllowed, policyLoadFailed, refreshConsultationPolicy
}
}
+1 -1
View File
@@ -81,7 +81,7 @@ const defaultPath = PageEnum.INDEX
const changePasswordPath = '/change-password'
const bindWorkWechatPath = '/bind-work-wechat'
// 免登录白名单
const whiteList: string[] = [PageEnum.LOGIN, PageEnum.ERROR_403]
const whiteList: string[] = [PageEnum.LOGIN, PageEnum.ERROR_403, '/group-login']
router.beforeEach(async (to, from, next) => {
document.title = to.meta.title ?? config.title
const userStore = useUserStore()
+5
View File
@@ -35,6 +35,11 @@ export const constantRoutes: Array<RouteRecordRaw> = [
path: PageEnum.LOGIN,
component: () => import('@/views/account/login.vue')
},
{
path: '/group-login',
component: () => import('@/views/account/GroupLogin.vue'),
meta: { title: '集团账号登录 · 互联网医院', hidden: true, hideTab: true }
},
{
path: '/change-password',
component: () => import('@/views/account/change-password.vue')
+6 -1
View File
@@ -14,6 +14,7 @@ export interface UserState {
routes: RouteRecordRaw[]
perms: string[]
isPaw: number // 0=需要修改密码,1=正常
serverTimeOffsetMs: number
}
const useUserStore = defineStore({
@@ -27,7 +28,8 @@ const useUserStore = defineStore({
// 权限
perms: [],
// 是否需要修改密码
isPaw: 1
isPaw: 1,
serverTimeOffsetMs: 0
}),
getters: {},
actions: {
@@ -36,6 +38,7 @@ const useUserStore = defineStore({
this.userInfo = {}
this.perms = []
this.isPaw = 1
this.serverTimeOffsetMs = 0
},
login(playload: any) {
const { account, password } = playload
@@ -95,6 +98,8 @@ const useUserStore = defineStore({
getUserInfo()
.then((data) => {
this.userInfo = data.user
const serverTime = Number(data.user?.web_consultation_policy?.server_time)
this.serverTimeOffsetMs = serverTime > 0 ? serverTime * 1000 - Date.now() : 0
this.perms = data.permissions
this.routes = filterAsyncRoutes(data.menu)
// 更新 isPaw 状态
@@ -0,0 +1,45 @@
import type { ConsultationCallRecord } from '@/api/tcm'
export function normalizeConsultationRecords(value: unknown, diagnosisId: number): ConsultationCallRecord[] {
if (!Array.isArray(value)) throw new Error('面诊记录返回格式异常,请重试')
const seen = new Set<number>()
return value.filter(row => {
if (!row || !Number.isSafeInteger(Number(row.id)) || Number(row.id) <= 0 || seen.has(Number(row.id))) return false
if (row.diagnosis_id != null && Number(row.diagnosis_id) !== diagnosisId) return false
seen.add(Number(row.id))
return true
}).map(row => ({
...row,
id: Number(row.id),
diagnosis_id: diagnosisId,
transcript_text: typeof row.transcript_text === 'string' ? row.transcript_text.replace(/\r\n/g, '\n').trim() : ''
})).sort((a, b) => b.id - a.id)
}
export function consultationTranscriptText(row?: ConsultationCallRecord | null): string {
return typeof row?.transcript_text === 'string' ? row.transcript_text.trim() : ''
}
export function consultationTranscriptStatus(row: ConsultationCallRecord) {
switch (row.transcription_status) {
case 'running': return { label: '录音转写中', type: 'info' as const }
case 'completed': return { label: '文字已生成', type: 'success' as const }
case 'partial': return { label: '文字部分保存', type: 'warning' as const }
case 'failed': return { label: '文字生成失败', type: 'danger' as const }
default: return consultationTranscriptText(row)
? { label: '文字已保存', type: 'success' as const }
: { label: '未生成文字', type: 'info' as const }
}
}
export function consultationTranscriptEmptyText(row: ConsultationCallRecord): string {
if (row.transcription_status === 'running') return '正在转写,可点击刷新查看最新保存的文字。'
if (row.transcription_status === 'failed') return '本次面诊文字生成失败,暂无已保存的对话。'
if (Number(row.status) === 3) return '本次通话未接听,暂无文字对话。'
if (Number(row.status) === 4) return '本次通话已取消,暂无文字对话。'
return '本次面诊暂无已保存的文字对话。'
}
export function consultationCallLabel(row: ConsultationCallRecord): string {
return Number(row.call_type) === 1 ? '语音面诊' : Number(row.call_type) === 2 ? '视频面诊' : '面诊记录'
}
@@ -0,0 +1,97 @@
// 所有时间由服务端配置提供,浏览器不保留独立的截止日期。
export type DoctorWebConsultationPolicy = {
cutoff_at: string
approaching_at: string
urgent_at: string
server_time: number
}
export type DoctorWebConsultationPhase = 'prepare' | 'approaching' | 'last_day' | 'expired'
export function normalizeDoctorWebConsultationPolicy(value: unknown): DoctorWebConsultationPolicy | undefined {
if (!value || typeof value !== 'object') return undefined
const policy = value as DoctorWebConsultationPolicy
const timestamps = [policy.approaching_at, policy.urgent_at, policy.cutoff_at].map(date =>
typeof date === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/.test(date) ? Date.parse(date) : NaN
)
if (timestamps.some(time => !Number.isFinite(time)) || timestamps[0] > timestamps[1] || timestamps[1] > timestamps[2]) return undefined
if (!Number.isFinite(policy.server_time) || policy.server_time <= 0) return undefined
return { cutoff_at: policy.cutoff_at, approaching_at: policy.approaching_at, urgent_at: policy.urgent_at, server_time: policy.server_time }
}
export function doctorWebConsultationDate(policy: DoctorWebConsultationPolicy): string {
// 无论医生电脑所在时区为何,公告始终显示北京时间。
const parts = new Intl.DateTimeFormat('en-GB', {
timeZone: 'Asia/Shanghai', year: 'numeric', month: '2-digit', day: '2-digit',
hour: '2-digit', minute: '2-digit', second: '2-digit', hourCycle: 'h23'
}).formatToParts(new Date(policy.cutoff_at))
const part = (type: string) => parts.find(item => item.type === type)?.value || ''
const seconds = part('second') === '00' ? '' : `:${part('second')}`
return `${part('year')}年${part('month')}月${part('day')}日${part('hour')}:${part('minute')}${seconds}(北京时间)`
}
export function doctorWebConsultationMessage(policy?: DoctorWebConsultationPolicy): string {
return `网页端面诊已${policy ? `于${doctorWebConsultationDate(policy)}` : ''}停用,请医生使用桌面应用进行面诊。`
}
export function doctorWebConsultationReminder(policy?: DoctorWebConsultationPolicy, now = Date.now()) {
if (!policy) return {
phase: 'prepare' as DoctorWebConsultationPhase,
type: 'info' as const,
title: '系统公告:医生桌面应用安装指引',
description: '请各位医生提前下载并安装桌面应用,使用当前医生账号登录。',
countdown: ''
}
const cutoffDate = doctorWebConsultationDate(policy)
const remaining = Date.parse(policy.cutoff_at) - now
const days = Math.floor(remaining / 86400000)
const hours = Math.floor(remaining / 3600000) % 24
const minutes = Math.floor(remaining / 60000) % 60
const countdown = remaining <= 0 ? '' : remaining < 60000 ? '不足1分钟' :
`${days > 0 ? `${days}天` : ''}${hours > 0 ? `${hours}小时` : ''}${minutes > 0 ? `${minutes}分钟` : ''}`
if (remaining <= 0) return {
phase: 'expired' as DoctorWebConsultationPhase,
type: 'error' as const,
title: '系统公告:医生网页端面诊已停用',
description: doctorWebConsultationMessage(policy),
countdown: ''
}
if (now >= Date.parse(policy.urgent_at)) return {
phase: 'last_day' as DoctorWebConsultationPhase,
type: 'error' as const,
title: '系统公告:医生网页端面诊停用最后提醒',
description: `请各位医生在${cutoffDate}前完成桌面应用的安装与登录。届时接诊台、问诊列表的网页端面诊功能将同步停用,请使用桌面应用进行面诊。`,
countdown
}
if (now >= Date.parse(policy.approaching_at)) return {
phase: 'approaching' as DoctorWebConsultationPhase,
type: 'warning' as const,
title: '系统公告:医生网页端面诊即将停用',
description: `网页端面诊将于${cutoffDate}停用。请各位医生尽快下载桌面应用,完成安装并使用当前医生账号登录,接诊台、问诊列表将同步执行此规则。`,
countdown
}
return {
phase: 'prepare' as DoctorWebConsultationPhase,
type: 'info' as const,
title: '系统公告:请提前安装医生桌面应用',
description: `请各位医生提前下载并安装桌面应用,使用当前医生账号登录试用。自${cutoffDate}起,接诊台、问诊列表的网页端面诊功能将停用,请提前做好准备。`,
countdown: ''
}
}
export function isConsultationDoctor(user: Record<string, any>): boolean {
return Number(user.root) !== 1 && Array.isArray(user.role_ids) && user.role_ids.some(role => Number(role) === 1)
}
export function hasDoctorWebConsultationExpired(policy?: DoctorWebConsultationPolicy, now = Date.now()): boolean {
return !!policy && now >= Date.parse(policy.cutoff_at)
}
export function isDoctorWebConsultationBlocked(
user: Record<string, any>,
policy?: DoctorWebConsultationPolicy,
now = Date.now()
): boolean {
return isConsultationDoctor(user) && hasDoctorWebConsultationExpired(policy, now)
}
+11
View File
@@ -0,0 +1,11 @@
export interface HospitalSession { token: string; is_paw?: number; need_bind_work_wechat?: boolean; [key: string]: unknown }
export interface GroupTransaction { code: string; verifier: string; redirectUri: string }
export const GROUP_CLIENT_ID: string
export const GROUP_TRANSACTION_KEY: string
export function fixedOrigin(value: string): string
export function callbackUri(origin: string): string
export function pkceChallenge(verifier: string, cryptoApi?: Crypto): Promise<string>
export function beginGroupLogin(options: { identityOrigin: string; hospitalOrigin: string; storage: Storage; cryptoApi?: Crypto; now?: number }): Promise<string>
export function consumeGroupCallback(options: { url: string; history: History; storage: Storage; identityOrigin: string; hospitalOrigin: string; now?: number }): GroupTransaction
export function exchangeGroupCode(options: { transaction: GroupTransaction; identityOrigin: string; hospitalOrigin: string; fetcher?: typeof fetch }): Promise<HospitalSession>
export function groupLoginDestination(session: HospitalSession): string
+111
View File
@@ -0,0 +1,111 @@
// 集团登录只交换短时凭据;原业务 token 不进入 URL 或 sessionStorage。
export const GROUP_CLIENT_ID = 'internet-hospital'
export const GROUP_TRANSACTION_KEY = 'zyt_hospital_group_sso_v1'
const TRANSACTION_TTL = 5 * 60 * 1000
const CALLBACK_PATH = '/admin/group-login'
const HOSPITAL_EXCHANGE = '/adminapi/identity.hospitalSso/exchange'
const safeValue = /^[A-Za-z0-9_-]{24,512}$/
export function fixedOrigin(value) {
const url = new URL(value)
const loopback = ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname)
if ((url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) ||
url.username || url.password || url.pathname !== '/' || url.search || url.hash) {
throw new Error('集团登录地址配置无效')
}
return url.origin
}
export function callbackUri(origin) {
return fixedOrigin(origin) + CALLBACK_PATH
}
function base64url(bytes) {
return btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
}
export async function pkceChallenge(verifier, cryptoApi = globalThis.crypto) {
if (!/^[A-Za-z0-9_-]{43,128}$/.test(verifier)) throw new Error('登录事务无效,请重新发起')
return base64url(new Uint8Array(await cryptoApi.subtle.digest('SHA-256', new TextEncoder().encode(verifier))))
}
export async function beginGroupLogin({ identityOrigin, hospitalOrigin, storage, cryptoApi = globalThis.crypto, now = Date.now() }) {
const identity = fixedOrigin(identityOrigin)
const redirectUri = callbackUri(hospitalOrigin)
const verifier = base64url(cryptoApi.getRandomValues(new Uint8Array(32)))
const state = base64url(cryptoApi.getRandomValues(new Uint8Array(32)))
const challenge = await pkceChallenge(verifier, cryptoApi)
storage.setItem(GROUP_TRANSACTION_KEY, JSON.stringify({ verifier, state, redirectUri, identity, createdAt: now }))
const target = new URL('/sso/authorize', identity)
target.search = new URLSearchParams({ client_id: GROUP_CLIENT_ID, redirect_uri: redirectUri, state,
code_challenge: challenge, code_challenge_method: 'S256' }).toString()
return target.href
}
// 必须在任何 await/网络请求之前调用,URL 的所有回调参数一并清除。
export function consumeGroupCallback({ url, history, storage, identityOrigin, hospitalOrigin, now = Date.now() }) {
const current = new URL(url)
const expected = callbackUri(hospitalOrigin)
history.replaceState(history.state, '', CALLBACK_PATH)
const raw = storage.getItem(GROUP_TRANSACTION_KEY)
storage.removeItem(GROUP_TRANSACTION_KEY)
if (current.origin + current.pathname !== expected || current.hash ||
[...current.searchParams.keys()].some((key) => !['code', 'state', 'error'].includes(key)) ||
['code', 'state', 'error'].some((key) => current.searchParams.getAll(key).length > 1)) {
throw new Error('登录回调地址无效,请重新发起')
}
if (current.searchParams.has('error')) throw new Error('集团登录未完成,请返回集团后台重试')
let transaction
try { transaction = JSON.parse(raw || 'null') } catch { /* 统一按无效事务处理。 */ }
const code = current.searchParams.get('code') || ''
const state = current.searchParams.get('state') || ''
if (!transaction || !safeValue.test(code) || !safeValue.test(state) || state !== transaction.state ||
!/^[A-Za-z0-9_-]{43,128}$/.test(transaction.verifier || '') ||
transaction.identity !== fixedOrigin(identityOrigin) || transaction.redirectUri !== expected ||
!Number.isSafeInteger(transaction.createdAt) || now < transaction.createdAt || now - transaction.createdAt > TRANSACTION_TTL) {
throw new Error('登录状态已失效或不属于当前浏览器,请重新发起')
}
return { code, verifier: transaction.verifier, redirectUri: expected }
}
async function postOnce(fetcher, url, body, credentials) {
const controller = new AbortController()
const timeout = setTimeout(() => controller.abort(), 20000)
try {
const response = await fetcher(url, { method: 'POST', credentials, redirect: 'error', cache: 'no-store',
referrerPolicy: 'no-referrer', headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify(body), signal: controller.signal })
if (!response.ok) throw new Error('登录交接未完成,请重新发起')
const envelope = await response.json()
if (envelope?.code !== 1 || !envelope.data || typeof envelope.data !== 'object') {
throw new Error('登录交接未完成,请重新发起')
}
return envelope.data
} finally { clearTimeout(timeout) }
}
export async function exchangeGroupCode({ transaction, identityOrigin, hospitalOrigin, fetcher = globalThis.fetch }) {
const identity = fixedOrigin(identityOrigin)
const hospital = fixedOrigin(hospitalOrigin)
if (transaction.redirectUri !== callbackUri(hospital) || !safeValue.test(transaction.code || '') ||
!/^[A-Za-z0-9_-]{43,128}$/.test(transaction.verifier || '')) throw new Error('登录回调地址无效')
const issued = await postOnce(fetcher, identity + '/adminapi/group/sso/exchange', {
client_id: GROUP_CLIENT_ID, redirect_uri: transaction.redirectUri,
code: transaction.code, code_verifier: transaction.verifier
}, 'omit')
if (!safeValue.test(issued.ticket || '') || issued.exchange_path !== HOSPITAL_EXCHANGE) {
throw new Error('医院登录凭据无效,请重新发起')
}
const session = await postOnce(fetcher, hospital + HOSPITAL_EXCHANGE,
{ ticket: issued.ticket, code_verifier: transaction.verifier }, 'same-origin')
if (typeof session.token !== 'string' || session.token.length < 16 || session.token.length > 2048 || /[\x00-\x20\x7f]/.test(session.token)) {
throw new Error('医院登录响应无效,请重新发起')
}
return session
}
export function groupLoginDestination(session) {
if (Number(session.is_paw) === 0) return '/admin/change-password'
if (session.need_bind_work_wechat) return '/admin/bind-work-wechat'
return '/admin/'
}
+52
View File
@@ -0,0 +1,52 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { TOKEN_KEY } from '@/enums/cacheEnums'
import useUserStore from '@/stores/modules/user'
import { clearAuthInfo } from '@/utils/auth'
import cache from '@/utils/cache'
import { beginGroupLogin, consumeGroupCallback, exchangeGroupCode, groupLoginDestination } from '@/utils/groupSso.mjs'
const localOrigin = ['127.0.0.1', 'localhost', '[::1]'].includes(window.location.hostname)
const identityOrigin = String(import.meta.env.VITE_GROUP_IDENTITY_URL || (localOrigin ? 'http://127.0.0.1:5173' : ''))
const message = ref('正在连接集团账号…')
const failed = ref(false)
let running = false
async function connect() {
if (running) return
running = true
failed.value = false
try {
const options = { identityOrigin, hospitalOrigin: window.location.origin, storage: sessionStorage }
if (window.location.search || window.location.hash) {
const transaction = consumeGroupCallback({ ...options, url: window.location.href, history: window.history })
message.value = '正在安全进入互联网医院…'
const session = await exchangeGroupCode({ ...options, transaction })
clearAuthInfo()
const user = useUserStore()
user.token = session.token
user.isPaw = session.is_paw ?? 1
cache.set(TOKEN_KEY, session.token)
window.location.replace(groupLoginDestination(session))
} else {
window.location.assign(await beginGroupLogin(options))
}
} catch {
message.value = '本次登录未完成或凭据已过期,请重新进入。'
failed.value = true
} finally { running = false }
}
onMounted(connect)
</script>
<template>
<main class="group-login"><section>
<span class="group-label">甄养堂集团</span><h1>互联网医院</h1><p role="status">{{ message }}</p>
<button v-if="failed" type="button" @click="connect">重新发起登录</button>
<a href="/admin/login">使用医院账号登录</a>
</section></main>
</template>
<style scoped>
.group-login{min-height:100vh;display:grid;place-items:center;background:#f3f7f6;color:#183d37;padding:24px}.group-login section{width:min(440px,100%);padding:44px;background:white;border:1px solid #dce8e4;border-radius:20px;box-shadow:0 16px 56px #163d3710}.group-label{font-size:13px;letter-spacing:3px;color:#6e817c}.group-login h1{font-size:30px;margin:20px 0}.group-login p{line-height:1.8;color:#60736e}.group-login button{display:block;width:100%;margin:24px 0 20px;padding:13px;border:0;border-radius:9px;background:#176453;color:white;cursor:pointer}.group-login a{display:block;margin-top:24px;color:#176453;font-size:14px}
</style>
@@ -312,6 +312,17 @@
{{ detailPrescription.dosage_amount }}{{ detailPrescription.dosage_unit || 'g' }}
<template v-if="detailPrescription.prescription_type === '浓缩水丸'">
· {{ Number(detailPrescription.dosage_bag_count) > 0 ? Number(detailPrescription.dosage_bag_count) : 1 }}袋
<el-button
v-if="!readonly && detailData.prescription_id && !String(detailData.prescription_detail_error || '').trim()"
v-perms="['tcm.prescriptionOrder/patchPrescriptionUsage']"
type="primary"
size="small"
link
class="ml-2"
@click="openPatchUsageDialog"
>
修改
</el-button>
</template>
<span v-if="detailPrescription.prescription_type === '饮片' && detailPrescription.need_decoction !== null" class="ml-2 text-gray-500">
({{ detailPrescription.need_decoction ? '代煎' : '不代煎' }})
@@ -325,6 +336,17 @@
{{ detailAuxUsage.dosage_amount }}{{ detailPrescription.dosage_unit || 'g' }}
<template v-if="detailPrescription.prescription_type === '浓缩水丸'">
· {{ Number(detailAuxUsage.dosage_bag_count) > 0 ? Number(detailAuxUsage.dosage_bag_count) : 1 }}袋
<el-button
v-if="!readonly && detailData.prescription_id && !String(detailData.prescription_detail_error || '').trim()"
v-perms="['tcm.prescriptionOrder/patchPrescriptionUsage']"
type="primary"
size="small"
link
class="ml-2"
@click="openPatchUsageDialog"
>
修改
</el-button>
</template>
<span v-if="detailPrescription.prescription_type === '饮片'" class="ml-2 text-gray-500">
({{ detailAuxUsage.need_decoction ? '代煎' : '不代煎' }})
@@ -943,6 +965,15 @@
label-width="108px"
>
<div v-if="detailHasAuxHerbs" class="text-xs font-medium text-gray-500 mb-3">主方</div>
<el-form-item
v-if="detailPrescription?.prescription_type === '浓缩水丸'"
label="每次袋数"
prop="dosage_bag_count"
>
<el-select v-model="patchUsageForm.dosage_bag_count" class="w-full">
<el-option v-for="count in 5" :key="count" :label="`${count}袋`" :value="count" />
</el-select>
</el-form-item>
<el-form-item label="每天次数" prop="times_per_day">
<el-input-number
v-model="patchUsageForm.times_per_day"
@@ -968,6 +999,15 @@
</el-form-item>
<template v-if="detailHasAuxHerbs">
<div class="text-xs font-medium text-gray-500 mb-3 mt-2 pt-2 border-t border-gray-100">辅方</div>
<el-form-item
v-if="detailPrescription?.prescription_type === '浓缩水丸'"
label="每次袋数"
prop="aux_dosage_bag_count"
>
<el-select v-model="patchUsageForm.aux_dosage_bag_count" class="w-full">
<el-option v-for="count in 5" :key="count" :label="`${count}袋`" :value="count" />
</el-select>
</el-form-item>
<el-form-item label="每天次数" prop="aux_times_per_day">
<el-input-number
v-model="patchUsageForm.aux_times_per_day"
@@ -1432,10 +1472,12 @@ const patchUsageVisible = ref(false)
const patchUsageSaving = ref(false)
const patchUsageFormRef = ref<FormInstance>()
const patchUsageForm = reactive({
dosage_bag_count: 1 as number | undefined,
times_per_day: 3 as number | undefined,
usage_days: 7 as number | undefined,
aux_times_per_day: 3 as number | undefined,
aux_usage_days: 7 as number | undefined,
aux_dosage_bag_count: 1 as number | undefined,
medication_days: undefined as number | undefined
})
const patchUsageRules = computed<FormRules>(() => {
@@ -1444,9 +1486,15 @@ const patchUsageRules = computed<FormRules>(() => {
usage_days: [{ required: true, message: '请填写主方开立天数', trigger: 'change' }],
medication_days: [{ required: true, message: '请填写订单服用天数', trigger: 'change' }]
}
if (detailPrescription.value?.prescription_type === '浓缩水丸') {
rules.dosage_bag_count = [{ required: true, message: '请选择主方每次袋数', trigger: 'change' }]
}
if (detailHasAuxHerbs.value) {
rules.aux_times_per_day = [{ required: true, message: '请填写辅方每天次数', trigger: 'change' }]
rules.aux_usage_days = [{ required: true, message: '请填写辅方开立天数', trigger: 'change' }]
if (detailPrescription.value?.prescription_type === '浓缩水丸') {
rules.aux_dosage_bag_count = [{ required: true, message: '请选择辅方每次袋数', trigger: 'change' }]
}
}
return rules
})
@@ -1459,6 +1507,7 @@ function openPatchUsageDialog() {
return
}
const aux = detailAuxUsage.value
patchUsageForm.dosage_bag_count = Number(rx.dosage_bag_count) > 0 ? Number(rx.dosage_bag_count) : 1
patchUsageForm.times_per_day =
Number(rx.times_per_day) > 0 ? Number(rx.times_per_day) : 3
patchUsageForm.usage_days =
@@ -1468,16 +1517,20 @@ function openPatchUsageDialog() {
patchUsageForm.aux_usage_days =
aux && Number(aux.usage_days) > 0 ? Number(aux.usage_days) : 7
const md = Number(ord.medication_days)
patchUsageForm.aux_dosage_bag_count =
aux && Number(aux.dosage_bag_count) > 0 ? Number(aux.dosage_bag_count) : 1
patchUsageForm.medication_days = md > 0 ? md : Number(rx.usage_days) > 0 ? Number(rx.usage_days) : 7
patchUsageVisible.value = true
nextTick(() => patchUsageFormRef.value?.clearValidate())
}
function resetPatchUsageForm() {
patchUsageForm.dosage_bag_count = 1
patchUsageForm.times_per_day = 3
patchUsageForm.usage_days = 7
patchUsageForm.aux_times_per_day = 3
patchUsageForm.aux_usage_days = 7
patchUsageForm.aux_dosage_bag_count = 1
patchUsageForm.medication_days = undefined
}
@@ -1498,17 +1551,25 @@ async function submitPatchUsage() {
times_per_day: number
usage_days: number
medication_days: number
dosage_bag_count?: number
aux_times_per_day?: number
aux_usage_days?: number
aux_dosage_bag_count?: number
} = {
id: ordId,
times_per_day: Number(patchUsageForm.times_per_day),
usage_days: Number(patchUsageForm.usage_days),
medication_days: Number(patchUsageForm.medication_days)
}
if (detailPrescription.value?.prescription_type === '浓缩水丸') {
payload.dosage_bag_count = Number(patchUsageForm.dosage_bag_count)
}
if (detailHasAuxHerbs.value) {
payload.aux_times_per_day = Number(patchUsageForm.aux_times_per_day)
payload.aux_usage_days = Number(patchUsageForm.aux_usage_days)
if (detailPrescription.value?.prescription_type === '浓缩水丸') {
payload.aux_dosage_bag_count = Number(patchUsageForm.aux_dosage_bag_count)
}
}
await prescriptionOrderPatchPrescriptionUsage(payload)
feedback.msgSuccess('保存成功')
@@ -1763,7 +1824,7 @@ async function refresh() {
detailLogisticsExpress.value = String(d.express_company || 'auto') || 'auto'
void fetchLogisticsTrace()
}
if (props.loadRelatedData) void fetchLogs(id)
if (props.loadRelatedData) await fetchLogs(id)
const diagId = d.diagnosis_id
if (props.loadRelatedData && diagId) {
void loadDetailUnlinkedPayOrders(diagId, id, d.pay_order_ids || [])
@@ -883,6 +883,17 @@
{{ detailPrescription.dosage_amount }}{{ detailPrescription.dosage_unit || 'g' }}
<template v-if="detailPrescription.prescription_type === '浓缩水丸'">
· {{ Number(detailPrescription.dosage_bag_count) > 0 ? Number(detailPrescription.dosage_bag_count) : 1 }}袋
<el-button
v-if="detailData.prescription_id && !String(detailData.prescription_detail_error || '').trim()"
v-perms="['tcm.prescriptionOrder/patchPrescriptionUsage']"
type="primary"
size="small"
link
class="ml-2"
@click="openPatchUsageDialog"
>
修改
</el-button>
</template>
<span v-if="detailPrescription.prescription_type === '饮片' && detailPrescription.need_decoction !== null" class="ml-2 text-gray-500">
({{ detailPrescription.need_decoction ? '代煎' : '不代煎' }})
@@ -896,6 +907,17 @@
{{ detailAuxUsage.dosage_amount }}{{ detailPrescription.dosage_unit || 'g' }}
<template v-if="detailPrescription.prescription_type === '浓缩水丸'">
· {{ Number(detailAuxUsage.dosage_bag_count) > 0 ? Number(detailAuxUsage.dosage_bag_count) : 1 }}袋
<el-button
v-if="detailData.prescription_id && !String(detailData.prescription_detail_error || '').trim()"
v-perms="['tcm.prescriptionOrder/patchPrescriptionUsage']"
type="primary"
size="small"
link
class="ml-2"
@click="openPatchUsageDialog"
>
修改
</el-button>
</template>
<span v-if="detailPrescription.prescription_type === '饮片'" class="ml-2 text-gray-500">
({{ detailAuxUsage.need_decoction ? '代煎' : '不代煎' }})
@@ -2261,6 +2283,15 @@
label-width="96px"
>
<div v-if="detailHasAuxHerbs" class="text-xs font-medium text-gray-500 mb-3">主方</div>
<el-form-item
v-if="detailPrescription?.prescription_type === '浓缩水丸'"
label="每次袋数"
prop="dosage_bag_count"
>
<el-select v-model="patchUsageForm.dosage_bag_count" class="w-full">
<el-option v-for="count in 5" :key="count" :label="`${count}袋`" :value="count" />
</el-select>
</el-form-item>
<el-form-item label="每天次数" prop="times_per_day">
<el-input-number
v-model="patchUsageForm.times_per_day"
@@ -2286,6 +2317,15 @@
</el-form-item>
<template v-if="detailHasAuxHerbs">
<div class="text-xs font-medium text-gray-500 mb-3 mt-2 pt-2 border-t border-gray-100">辅方</div>
<el-form-item
v-if="detailPrescription?.prescription_type === '浓缩水丸'"
label="每次袋数"
prop="aux_dosage_bag_count"
>
<el-select v-model="patchUsageForm.aux_dosage_bag_count" class="w-full">
<el-option v-for="count in 5" :key="count" :label="`${count}袋`" :value="count" />
</el-select>
</el-form-item>
<el-form-item label="每天次数" prop="aux_times_per_day">
<el-input-number
v-model="patchUsageForm.aux_times_per_day"
@@ -3954,10 +3994,12 @@ const patchUsageVisible = ref(false)
const patchUsageSaving = ref(false)
const patchUsageFormRef = ref<FormInstance>()
const patchUsageForm = reactive({
dosage_bag_count: 1 as number | undefined,
times_per_day: 3 as number | undefined,
usage_days: 7 as number | undefined,
aux_times_per_day: 3 as number | undefined,
aux_usage_days: 7 as number | undefined,
aux_dosage_bag_count: 1 as number | undefined,
medication_days: undefined as number | undefined
})
const patchUsageRules = computed<FormRules>(() => {
@@ -3966,9 +4008,15 @@ const patchUsageRules = computed<FormRules>(() => {
usage_days: [{ required: true, message: '请填写主方开立天数', trigger: 'change' }],
medication_days: [{ required: true, message: '请填写订单服用天数', trigger: 'change' }]
}
if (detailPrescription.value?.prescription_type === '浓缩水丸') {
rules.dosage_bag_count = [{ required: true, message: '请选择主方每次袋数', trigger: 'change' }]
}
if (detailHasAuxHerbs.value) {
rules.aux_times_per_day = [{ required: true, message: '请填写辅方每天次数', trigger: 'change' }]
rules.aux_usage_days = [{ required: true, message: '请填写辅方开立天数', trigger: 'change' }]
if (detailPrescription.value?.prescription_type === '浓缩水丸') {
rules.aux_dosage_bag_count = [{ required: true, message: '请选择辅方每次袋数', trigger: 'change' }]
}
}
return rules
})
@@ -3981,6 +4029,7 @@ function openPatchUsageDialog() {
return
}
const aux = detailAuxUsage.value
patchUsageForm.dosage_bag_count = Number(rx.dosage_bag_count) > 0 ? Number(rx.dosage_bag_count) : 1
patchUsageForm.times_per_day =
Number(rx.times_per_day) > 0 ? Number(rx.times_per_day) : 3
patchUsageForm.usage_days =
@@ -3990,16 +4039,20 @@ function openPatchUsageDialog() {
patchUsageForm.aux_usage_days =
aux && Number(aux.usage_days) > 0 ? Number(aux.usage_days) : 7
const md = Number(ord.medication_days)
patchUsageForm.aux_dosage_bag_count =
aux && Number(aux.dosage_bag_count) > 0 ? Number(aux.dosage_bag_count) : 1
patchUsageForm.medication_days = md > 0 ? md : Number(rx.usage_days) > 0 ? Number(rx.usage_days) : 7
patchUsageVisible.value = true
nextTick(() => patchUsageFormRef.value?.clearValidate())
}
function resetPatchUsageForm() {
patchUsageForm.dosage_bag_count = 1
patchUsageForm.times_per_day = 3
patchUsageForm.usage_days = 7
patchUsageForm.aux_times_per_day = 3
patchUsageForm.aux_usage_days = 7
patchUsageForm.aux_dosage_bag_count = 1
patchUsageForm.medication_days = undefined
}
@@ -4020,17 +4073,25 @@ async function submitPatchUsage() {
times_per_day: number
usage_days: number
medication_days: number
dosage_bag_count?: number
aux_times_per_day?: number
aux_usage_days?: number
aux_dosage_bag_count?: number
} = {
id: ordId,
times_per_day: Number(patchUsageForm.times_per_day),
usage_days: Number(patchUsageForm.usage_days),
medication_days: Number(patchUsageForm.medication_days)
}
if (detailPrescription.value?.prescription_type === '浓缩水丸') {
payload.dosage_bag_count = Number(patchUsageForm.dosage_bag_count)
}
if (detailHasAuxHerbs.value) {
payload.aux_times_per_day = Number(patchUsageForm.aux_times_per_day)
payload.aux_usage_days = Number(patchUsageForm.aux_usage_days)
if (detailPrescription.value?.prescription_type === '浓缩水丸') {
payload.aux_dosage_bag_count = Number(patchUsageForm.aux_dosage_bag_count)
}
}
await prescriptionOrderPatchPrescriptionUsage(payload)
feedback.msgSuccess('保存成功')
+19
View File
@@ -144,6 +144,17 @@
>
<el-table-column type="selection" width="48" />
<el-table-column label="订单号" prop="order_no" min-width="150" />
<el-table-column label="处方业务订单号" min-width="210">
<template #default="{ row }">
<div v-if="row.prescription_orders?.length" class="flex flex-col gap-1">
<span v-for="order in row.prescription_orders" :key="order.id" class="break-all">
{{ order.order_no }}
</span>
</div>
<span v-else class="text-gray-400">未关联</span>
</template>
</el-table-column>
<el-table-column label="患者信息" min-width="150">
<template #default="{ row }">
@@ -302,6 +313,14 @@
<el-tag :type="getStatusTag(detailData.status)">
{{ getStatusText(detailData.status) }}
</el-tag>
</el-descriptions-item>
<el-descriptions-item label="处方业务订单号" :span="2">
<div v-if="detailData.prescription_orders?.length" class="flex flex-col gap-1">
<span v-for="order in detailData.prescription_orders" :key="order.id" class="break-all">
{{ order.order_no }}
</span>
</div>
<span v-else class="text-gray-400">未关联</span>
</el-descriptions-item>
<el-descriptions-item label="患者姓名">
{{ detailData.patient?.patient_name || '待关联' }}
+30 -7
View File
@@ -1,5 +1,6 @@
<template>
<div class="reception-page">
<DoctorWebConsultationNotice />
<!-- 页头 -->
<div class="reception-header">
<div class="header-left">
@@ -83,10 +84,18 @@
<el-icon v-else><ChatDotRound /></el-icon>
</button>
</el-tooltip>
<el-tooltip content="发起通话" placement="top">
<button class="row-icon-btn call" @click="handleCall(row)">
<el-icon><Phone /></el-icon>
</button>
<el-tooltip :content="webConsultationBlocked ? webConsultationMessage : '发起通话'" placement="top">
<span class="row-call-action">
<button
class="row-icon-btn call"
:disabled="webConsultationBlocked"
:aria-label="webConsultationBlocked ? webConsultationMessage : '发起通话'"
@click="handleCall(row)"
>
<el-icon><Phone /></el-icon>
<span v-if="webConsultationBlocked">已停用</span>
</button>
</span>
</el-tooltip>
</div>
</div>
@@ -189,6 +198,8 @@
<script setup lang="ts">
import { defineAsyncComponent, onMounted, onUnmounted } from 'vue'
import DoctorWebConsultationNotice from '@/components/doctor-web-consultation-notice/index.vue'
import { useDoctorWebConsultation } from '@/hooks/useDoctorWebConsultation'
import { receptionQueue, receptionDetail, notifyAssistant, addDoctorNote } from '@/api/patient'
import NoteTimeline from './components/NoteTimeline.vue'
import PatientInfoCard from '@/views/tcm/diagnosis/components/PatientInfoCard.vue'
@@ -211,6 +222,7 @@ const DiagnosisEdit = defineAsyncComponent(() => import('@/views/tcm/diagnosis/e
const POLL_MS = 5_000
const PAGE_SIZE = 15
const { webConsultationBlocked, webConsultationMessage, ensureWebConsultationAllowed } = useDoctorWebConsultation()
interface QueueRow {
id: number
@@ -438,6 +450,7 @@ const handleSearch = async () => {
}
const handleCall = async (row: QueueRow) => {
if (!ensureWebConsultationAllowed()) return
const sourcePatientId = Number(row.source_patient_id || 0)
const diagnosisId = Number(row.diagnosis_id || 0)
if (!sourcePatientId) {
@@ -454,6 +467,7 @@ const handleCall = async (row: QueueRow) => {
appointment_id: Number(row.id),
diagnosis_id: diagnosisId
})
if (!ensureWebConsultationAllowed()) return
chatDialogRef.value?.open({
patientId: sourcePatientId,
patientName: row.patient_name,
@@ -1004,16 +1018,25 @@ onUnmounted(() => {
font-size: 15px;
padding: 0;
}
.row-icon-btn:hover {
.row-call-action {
display: inline-flex;
}
.row-icon-btn.call:disabled {
width: auto;
gap: 4px;
padding: 0 6px;
font-size: 12px;
}
.row-icon-btn:hover:not(:disabled) {
background: var(--rx-accent-soft);
color: var(--rx-accent-strong);
border-color: var(--rx-accent);
transform: translateY(-1px);
}
.row-icon-btn:active {
.row-icon-btn:active:not(:disabled) {
transform: scale(0.92);
}
.row-icon-btn.notify:hover {
.row-icon-btn.notify:hover:not(:disabled) {
background: #fff7e6;
color: var(--rx-warning);
border-color: var(--rx-warning);
@@ -0,0 +1,227 @@
<template>
<div class="prescription-ai-visibility">
<el-card v-loading="loading" shadow="never" class="!border-none">
<div class="text-xl font-medium mb-[20px]">处方 AI 一致度可见范围</div>
<el-alert type="info" :closable="false" show-icon class="mb-5">
<template #title>指定用户组或用户可查看一致度</template>
<div class="leading-6">
用户命中任一指定系统角色,或被单独指定,即可查看桌面端“与 AI
一致度”、逐味对照和一致度统计。AI
报告继续按原有权限开放,已有报告不受影响,患者与处方的数据范围保持原有规则。
</div>
</el-alert>
<el-alert
v-if="loadError"
:title="loadError"
type="error"
:closable="false"
show-icon
class="mb-5"
/>
<div v-if="loading" role="status" class="mb-5">正在读取当前可见范围…</div>
<el-form
v-if="hasLoaded"
class="ls-form"
:model="formData"
:disabled="!ready || loading || saving"
label-width="140px"
>
<el-form-item label="指定用户组" prop="role_ids">
<div class="w-full max-w-[640px]">
<el-select
v-model="formData.role_ids"
class="w-full"
multiple
filterable
clearable
placeholder="请选择系统角色,可搜索角色名称"
>
<el-option
v-for="role in roleOptions"
:key="role.id"
:label="role.name"
:value="role.id"
/>
</el-select>
<div class="form-tips">账号拥有任一指定角色即可命中。</div>
</div>
</el-form-item>
<el-form-item label="指定用户" prop="admin_ids">
<div class="w-full max-w-[640px]">
<el-select
v-model="formData.admin_ids"
class="w-full"
multiple
filterable
clearable
placeholder="请选择用户,可搜索姓名或账号"
>
<el-option
v-for="admin in adminOptions"
:key="admin.id"
:label="admin.label"
:value="admin.id"
/>
</el-select>
<div class="form-tips">
单独指定的用户无需同时命中用户组。当前不在可选列表中的已配置 ID
会保留,移除后保存才会取消该项授权。
</div>
</div>
</el-form-item>
<el-form-item label="生效规则">
<div>
<div class="leading-6">指定用户组与指定用户按“或”生效。</div>
<div class="form-tips">
两项均为空时,所有账号(包括超级管理员)均隐藏一致度、对照与统计。
拥有本页管理权限不自动获得一致度查看权,超级管理员也需命中上述名单。
</div>
</div>
</el-form-item>
</el-form>
<el-alert
v-if="ready && !formData.role_ids.length && !formData.admin_ids.length"
title="当前选择为空:保存后所有账号将隐藏一致度、对照与统计,AI 报告仍保留。"
type="warning"
:closable="false"
show-icon
class="mb-5"
/>
<el-alert
v-if="saveError"
:title="saveError"
type="error"
:closable="false"
show-icon
class="mb-5"
/>
<el-button :disabled="loading || saving" @click="loadConfig">
{{ loadError ? '重试加载' : '重新加载' }}
</el-button>
</el-card>
<footer-btns v-if="canManage">
<el-button
type="primary"
:loading="saving"
:disabled="!ready || loading || saving"
@click="handleSubmit"
>
{{ saving ? '正在保存' : '保存' }}
</el-button>
</footer-btns>
</div>
</template>
<script setup lang="ts" name="prescriptionAiVisibility">
import { computed, reactive, ref } from 'vue'
import type {
PrescriptionAiVisibilityConfig,
PrescriptionAiVisibilityOptions
} from '@/api/setting/prescription_ai_visibility'
import {
getPrescriptionAiCapabilities,
getPrescriptionAiVisibilityConfig,
getPrescriptionAiVisibilityOptions,
setPrescriptionAiVisibilityConfig
} from '@/api/setting/prescription_ai_visibility'
import feedback from '@/utils/feedback'
const loading = ref(false)
const saving = ref(false)
const ready = ref(false)
const hasLoaded = ref(false)
const canManage = ref(false)
const loadError = ref('')
const saveError = ref('')
const formData = reactive<PrescriptionAiVisibilityConfig>({ role_ids: [], admin_ids: [] })
const optionsData = reactive<PrescriptionAiVisibilityOptions>({ roles: [], admins: [] })
const roleOptions = computed(() => {
const options = new Map(optionsData.roles.map((role) => [role.id, role]))
for (const id of formData.role_ids) {
if (!options.has(id)) {
options.set(id, { id, name: `已配置角色 #${id}(当前不在可选列表)` })
}
}
return [...options.values()]
})
const adminOptions = computed(() => {
const options = new Map(
optionsData.admins.map((admin) => [
admin.id,
{ id: admin.id, label: `${admin.name || `用户 #${admin.id}`}(${admin.account})` }
])
)
for (const id of formData.admin_ids) {
if (!options.has(id)) {
options.set(id, { id, label: `已配置用户 #${id}(当前不在可选列表)` })
}
}
return [...options.values()]
})
const assignConfig = (config: PrescriptionAiVisibilityConfig) => {
formData.role_ids = [...config.role_ids]
formData.admin_ids = [...config.admin_ids]
}
const loadConfig = async () => {
if (loading.value || saving.value) return
loading.value = true
ready.value = false
canManage.value = false
loadError.value = ''
saveError.value = ''
try {
const capabilities = await getPrescriptionAiCapabilities()
if (capabilities.can_manage_visibility !== true) {
loadError.value = '当前账号无权管理处方 AI 一致度可见范围。'
return
}
canManage.value = true
const [config, options] = await Promise.all([
getPrescriptionAiVisibilityConfig(),
getPrescriptionAiVisibilityOptions()
])
if (!Array.isArray(options?.roles) || !Array.isArray(options?.admins)) {
throw new Error('可选用户组或用户响应格式不正确')
}
// Apply both responses together; an incomplete load cannot overwrite the current policy.
assignConfig(config)
optionsData.roles = options.roles
optionsData.admins = options.admins
hasLoaded.value = true
ready.value = true
} catch {
loadError.value = '可见范围加载失败,尚未读取完整配置。请重试加载后再保存。'
} finally {
loading.value = false
}
}
const handleSubmit = async () => {
if (!ready.value || !canManage.value || loading.value || saving.value) return
saving.value = true
saveError.value = ''
try {
const config = await setPrescriptionAiVisibilityConfig({
role_ids: [...formData.role_ids],
admin_ids: [...formData.admin_ids]
})
assignConfig(config)
feedback.msgSuccess('可见范围已保存')
} catch {
saveError.value = '保存结果未确认,当前选择已保留。请重试保存,或重新加载以确认服务端策略。'
} finally {
saving.value = false
}
}
void loadConfig()
</script>
@@ -0,0 +1,901 @@
<template>
<div class="revisit-rate-page">
<el-card class="!border-none" shadow="never">
<el-form :inline="true" class="rate-filter-form">
<el-form-item :label="dateLabel">
<el-date-picker
v-model="dateRange"
type="daterange"
value-format="YYYY-MM-DD"
start-placeholder="开始日期"
end-placeholder="结束日期"
range-separator="至"
:clearable="false"
style="width: 280px"
@change="loadData"
/>
</el-form-item>
<el-form-item label="部门">
<el-tree-select
v-model="deptId"
:data="deptTreeOptions"
placeholder="二中心(全部)"
clearable
filterable
check-strictly
node-key="id"
:default-expand-all="true"
:props="deptTreeProps"
style="width: 210px"
@change="handleDeptChange"
/>
</el-form-item>
<el-form-item label="医助">
<el-select
v-model="assistantId"
placeholder="全部医助"
filterable
clearable
:loading="optionsLoading"
style="width: 180px"
@change="loadData"
>
<el-option
v-for="assistant in assistantOptions"
:key="assistant.id"
:label="assistant.name"
:value="assistant.id"
/>
</el-select>
</el-form-item>
<el-form-item>
<el-button type="primary" :loading="loading" @click="loadData">查询</el-button>
<el-button :disabled="loading" @click="handleReset">重置</el-button>
</el-form-item>
<el-form-item>
<el-popover placement="bottom-start" :width="540" trigger="hover">
<template #reference>
<span class="rate-caliber-trigger"
><el-icon><InfoFilled /></el-icon>统计口径</span
>
</template>
<div class="rate-caliber">
<p>
<b>{{ cohortLabel }}</b
>:按所选{{
dateLabel
}}范围确定患者,订单从对应指派后累计至查询当天;结束日期允许选择未来日期,但未来订单不会提前计入。
</p>
<p v-if="isInherit">
<b>继承诊次重新起算</b>:继承后的第 1 笔有效订单算二诊,第 2
笔算三诊,依次递增;不使用继承前的全局诊次,也不叠加诊次偏移。只统计继承患者,不混入新指派患者。
</p>
<p v-else>
只统计新指派患者,不混入继承患者。继承患者在独立的「继承复诊接诊率」页面统计。
</p>
<p>
<b>N 诊接诊率</b> = N 诊单数 ÷ 本页{{ cohortLabel }};分母为 0
显示「—」。<b>复诊合计接诊率</b> = 复诊合计单数 ÷ 本页{{
cohortLabel
}},表示人均复诊成交单数,可超过 100%。
</p>
<p>
订单仅计入有效业务订单,剔除已取消 / 拒收 /
退款;归属按服务端的患者持有记录计算。医助按人事部门归组;仅统计「二中心」及其组织下级,选定部门时包含其下级。
</p>
<p>
部门行和合计行按诊单去重,不能直接将医助行相加。灰字为「单数 /
分母」。
</p>
</div>
</el-popover>
</el-form-item>
</el-form>
<el-alert class="mt-3" type="info" :closable="false" show-icon :title="reportHint" />
<el-alert
v-if="optionsError"
class="mt-3"
type="warning"
:title="optionsError"
:closable="false"
/>
<el-alert
v-if="queryError"
class="mt-3"
type="error"
:title="queryError"
:closable="false"
/>
</el-card>
<div class="rate-kpi-grid">
<div
v-for="card in summaryCards"
:key="card.key"
class="rate-kpi-card"
:class="{ 'is-clickable': card.clickable }"
@click="card.clickable && card.onClick()"
>
<div class="rate-kpi-label">{{ card.label }}</div>
<div class="rate-kpi-value">{{ card.value }}</div>
<div v-if="card.sub" class="rate-kpi-sub">{{ card.sub }}</div>
</div>
</div>
<el-card class="!border-none mt-4" shadow="never">
<template #header>
<div class="rate-card-header">
<span>{{ reportTitle }} · 部门 / 医助明细</span>
<span class="rate-card-hint">{{ dateLabel }}:{{ rangeText }}</span>
<span v-if="observedUntil" class="rate-card-hint"
>订单统计截至:{{ observedUntil }}</span
>
</div>
<div class="rate-card-hint mt-2">
点击{{ cohortLabel }}、各诊次单数可查看患者与订单;底栏合计按诊单去重。
</div>
</template>
<el-table
v-loading="loading"
:data="rows"
size="small"
border
row-key="row_key"
:tree-props="{ children: 'children' }"
:default-expand-all="true"
show-summary
:summary-method="getSummaries"
>
<el-table-column label="部门 / 医助" min-width="200" fixed>
<template #default="{ row }">
<span v-if="row.is_dept" class="rate-dept-cell"
>{{ row.dept_name
}}<span class="rate-dept-count"
>{{ row.assistant_count }} 人</span
></span
>
<span v-else>{{ row.assistant_name }}</span>
</template>
</el-table-column>
<el-table-column
:prop="cohortCountKey"
:label="cohortLabel"
min-width="100"
align="right"
>
<template #header>
<span>{{ cohortLabel }}</span>
<el-tooltip
effect="dark"
placement="top"
:content="`所选${dateLabel}范围内的${cohortLabel},部门和合计按诊单去重`"
><el-icon class="rate-th-hint"><InfoFilled /></el-icon
></el-tooltip>
</template>
<template #default="{ row }">
<el-link
v-if="canViewAssignLines && row[cohortCountKey] > 0"
type="primary"
:underline="false"
@click="openAssignDetail(row)"
>{{ row[cohortCountKey] }}</el-link
>
<span v-else>{{ row[cohortCountKey] ?? 0 }}</span>
</template>
</el-table-column>
<template v-for="slot in visitSlots" :key="slot">
<el-table-column
:prop="`visit${slot}_count`"
:label="`${slotLabel(slot)}单数`"
min-width="96"
align="right"
>
<template #header>
<span>{{ slotLabel(slot) }}单数</span>
<el-tooltip effect="dark" placement="top" :content="slotCountTip(slot)"
><el-icon class="rate-th-hint"><InfoFilled /></el-icon
></el-tooltip>
</template>
<template #default="{ row }">
<el-link
v-if="canViewOrderLines && row[`visit${slot}_count`] > 0"
type="primary"
:underline="false"
@click="openOrderDetail(slot, row)"
>{{ row[`visit${slot}_count`] }}</el-link
>
<span v-else>{{ row[`visit${slot}_count`] ?? 0 }}</span>
</template>
</el-table-column>
<el-table-column
:prop="`visit${slot}_rate`"
:label="`${slotLabel(slot)}接诊率`"
min-width="110"
align="right"
>
<template #header>
<span>{{ slotLabel(slot) }}接诊率</span>
<el-tooltip
effect="dark"
placement="top"
:content="`${slotLabel(slot)}单数 ÷ ${cohortLabel};分母为 0 显示「—」`"
><el-icon class="rate-th-hint"><InfoFilled /></el-icon
></el-tooltip>
</template>
<template #default="{ row }">
<div class="rate-cell">
<span class="rate-cell-main">{{
formatRate(row[`visit${slot}_rate`])
}}</span
><span class="rate-cell-sub">{{
denText(row, `visit${slot}`)
}}</span>
</div>
</template>
</el-table-column>
</template>
<el-table-column
prop="visit_all_count"
label="复诊合计单数"
min-width="110"
align="right"
>
<template #header>
<span>复诊合计单数</span>
<el-tooltip
effect="dark"
placement="top"
content="所选患者从对应指派后累计至查询当天的全部复诊订单数"
><el-icon class="rate-th-hint"><InfoFilled /></el-icon
></el-tooltip>
</template>
<template #default="{ row }">
<el-link
v-if="canViewOrderLines && row.visit_all_count > 0"
type="primary"
:underline="false"
@click="openOrderDetail(0, row)"
>{{ row.visit_all_count }}</el-link
>
<span v-else>{{ row.visit_all_count ?? 0 }}</span>
</template>
</el-table-column>
<el-table-column
prop="visit_all_rate"
label="复诊合计接诊率"
min-width="128"
align="right"
>
<template #header>
<span>复诊合计接诊率</span>
<el-tooltip
effect="dark"
placement="top"
:content="`复诊合计单数 ÷ ${cohortLabel};表示人均复诊成交单数,可超过 100%`"
><el-icon class="rate-th-hint"><InfoFilled /></el-icon
></el-tooltip>
</template>
<template #default="{ row }">
<div class="rate-cell">
<span class="rate-cell-main">{{ formatRate(row.visit_all_rate) }}</span
><span class="rate-cell-sub">{{ denText(row, 'visit_all') }}</span>
</div>
</template>
</el-table-column>
</el-table>
</el-card>
<el-dialog
v-model="detailVisible"
:title="detailTitle"
width="1080px"
top="6vh"
destroy-on-close
@close="invalidateDetail"
>
<p class="rate-detail-hint">{{ detailHint }}</p>
<el-alert
v-if="detailError"
class="mb-3"
type="error"
:title="detailError"
:closable="false"
/>
<el-table
v-loading="detailLoading"
:data="detailRows"
size="small"
border
stripe
max-height="60vh"
>
<template v-if="detailType === 'assign'">
<el-table-column prop="diagnosis_id" label="诊单ID" width="90" />
<el-table-column prop="patient_name" label="患者" min-width="100">
<template #default="{ row }">
<el-link
v-if="canViewPatientDetail && row.diagnosis_id"
type="primary"
:underline="false"
@click="openPatientDetail(row.diagnosis_id)"
>{{ row.patient_name || `诊单#${row.diagnosis_id}` }}</el-link
>
<span v-else>{{ row.patient_name || '—' }}</span>
</template>
</el-table-column>
<el-table-column prop="patient_phone" label="联系电话" min-width="120"
><template #default="{ row }">{{
row.patient_phone || '—'
}}</template></el-table-column
>
<el-table-column
prop="assistant_names"
:label="isInherit ? '继承医助' : '被指派医助'"
min-width="140"
show-overflow-tooltip
/>
<el-table-column
prop="assign_count"
:label="isInherit ? '范围内继承次数' : '范围内指派次数'"
width="120"
align="right"
/>
<el-table-column
prop="first_assign_time_text"
:label="isInherit ? '首次继承时间' : '首次指派时间'"
min-width="160"
/>
<el-table-column
prop="last_assign_time_text"
:label="isInherit ? '最近继承时间' : '最近指派时间'"
min-width="160"
/>
</template>
<template v-else>
<el-table-column
prop="order_no"
label="订单号"
min-width="180"
show-overflow-tooltip
>
<template #default="{ row }">
<el-link
v-if="canViewOrderDetail && row.order_id"
type="primary"
:underline="false"
@click="openOrderInfo(row.order_id)"
>{{ row.order_no || `#${row.order_id}` }}</el-link
>
<span v-else>{{ row.order_no || `#${row.order_id}` }}</span>
</template>
</el-table-column>
<el-table-column
v-if="detailSlot === 0 || isInherit"
prop="visit_slot"
:label="isInherit ? '继承后诊次' : '诊次'"
width="100"
align="center"
><template #default="{ row }">{{
slotLabel(Number(row.visit_slot))
}}</template></el-table-column
>
<el-table-column
v-if="isInherit"
prop="global_visit_slot"
label="全局诊次(参考)"
width="130"
align="center"
><template #default="{ row }">{{
row.global_visit_slot ? slotLabel(Number(row.global_visit_slot)) : '—'
}}</template></el-table-column
>
<el-table-column prop="diagnosis_id" label="诊单ID" width="90" />
<el-table-column prop="patient_name" label="患者" min-width="100">
<template #default="{ row }">
<el-link
v-if="canViewPatientDetail && row.diagnosis_id"
type="primary"
:underline="false"
@click="openPatientDetail(row.diagnosis_id)"
>{{ row.patient_name || `诊单#${row.diagnosis_id}` }}</el-link
>
<span v-else>{{ row.patient_name || '—' }}</span>
</template>
</el-table-column>
<el-table-column prop="patient_phone" label="联系电话" min-width="120"
><template #default="{ row }">{{
row.patient_phone || '—'
}}</template></el-table-column
>
<el-table-column prop="amount" label="金额" width="100" align="right"
><template #default="{ row }">¥ {{ row.amount }}</template></el-table-column
>
<el-table-column
prop="cohort_assign_time_text"
:label="isInherit ? '继承时间' : '指派时间'"
min-width="160"
/>
<el-table-column prop="create_time_text" label="下单时间" min-width="160" />
<el-table-column prop="assistant_name" label="持有医助" min-width="100" />
<el-table-column prop="creator_name" label="订单创建人" min-width="100" />
</template>
</el-table>
<div class="rate-detail-footer">共 {{ detailCount }} 条</div>
</el-dialog>
<order-detail-drawer ref="orderDetailRef" readonly append-to-body />
<diagnosis-edit-popup ref="diagnosisEditRef" />
</div>
</template>
<script setup lang="ts">
import { computed, defineAsyncComponent, onBeforeUnmount, onMounted, ref } from 'vue'
import { InfoFilled } from '@element-plus/icons-vue'
import {
revisitCohortAssignLines,
revisitCohortDeptOptions,
revisitCohortOverview,
revisitCohortVisitOrderLines,
type RevisitRateCohortType,
type RevisitRateDetailQuery,
type RevisitRateQuery
} from '@/api/stats'
import { hasPermission } from '@/utils/perm'
const props = defineProps<{ cohortType: RevisitRateCohortType }>()
const OrderDetailDrawer = defineAsyncComponent(
() => import('@/views/consumer/prescription/components/PrescriptionOrderDetailDrawer.vue')
)
const DiagnosisEditPopup = defineAsyncComponent(() => import('@/views/tcm/diagnosis/edit.vue'))
interface MetricPack extends Record<string, any> {
assigned_count: number
inherit_count: number
assigned_total_count: number
visit_all_count: number
visit_all_den: number
visit_all_rate: number | null
}
interface StatsRow extends MetricPack {
row_key: string
is_dept: 0 | 1
dept_id: number
dept_name: string
assistant_id?: number
assistant_name?: string
assistant_count?: number
children?: StatsRow[]
}
interface DeptOption {
id: number
pid: number
name: string
}
interface DeptTreeNode extends DeptOption {
children?: DeptTreeNode[]
}
interface AssistantOption {
id: number
name: string
dept_id: number
}
interface SummaryCard {
key: string
label: string
value: string
sub: string
clickable: boolean
onClick: () => void
}
const isInherit = computed(() => props.cohortType === 'inherit')
const cohortLabel = computed(() => (isInherit.value ? '继承数' : '新指派数'))
const cohortCountKey = computed(() => (isInherit.value ? 'inherit_count' : 'assigned_count'))
const dateLabel = computed(() => (isInherit.value ? '继承日期' : '指派日期'))
const reportTitle = computed(() => (isInherit.value ? '继承复诊接诊率' : '按指派周期复诊率'))
const reportHint = computed(() =>
isInherit.value
? '按继承日期范围选择患者,订单累计至查询当天。继承后第 1 笔有效订单算二诊,第 2 笔算三诊;忽略继承前全局诊次及偏移,新指派患者另页统计。'
: '按新指派日期范围选择患者,订单累计至查询当天,跨月继续累计。继承患者在独立的「继承复诊接诊率」页面统计。'
)
const permissionPrefix = computed(() =>
isInherit.value ? 'stats.revisitInheritRate' : 'stats.revisitAssignRate'
)
const canViewAssignLines = computed(() => hasPermission([`${permissionPrefix.value}/assignLines`]))
const canViewOrderLines = computed(() =>
hasPermission([`${permissionPrefix.value}/visitOrderLines`])
)
const canViewOrderDetail = hasPermission(['tcm.prescriptionOrder/detail'])
const canViewPatientDetail = hasPermission(['tcm.diagnosis/detail'])
const formatDate = (date: Date) =>
`${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
const defaultDateRange = (): [string, string] => {
const now = new Date()
return [formatDate(new Date(now.getFullYear(), now.getMonth(), 1)), formatDate(now)]
}
const dateRange = ref<[string, string]>(defaultDateRange())
const deptId = ref<number | undefined>()
const assistantId = ref<number | undefined>()
const loading = ref(false)
const queryError = ref('')
const rows = ref<StatsRow[]>([])
const total = ref<MetricPack | null>(null)
const visitSlots = ref<number[]>([2, 3, 4])
const observedUntil = ref('')
/** 下钻只复用已展示报表的查询快照,避免读取正在编辑的筛选。 */
const loadedQuery = ref<RevisitRateQuery | null>(null)
let overviewRequestId = 0
let disposed = false
const rangeText = computed(() =>
loadedQuery.value
? `${loadedQuery.value.start_date} 至 ${loadedQuery.value.end_date}`
: `${dateRange.value[0]} 至 ${dateRange.value[1]}`
)
const currentQuery = (): RevisitRateQuery => ({
start_date: dateRange.value[0],
end_date: dateRange.value[1],
dept_ids: deptId.value ? String(deptId.value) : '',
assistant_id: assistantId.value || undefined
})
const deptOptions = ref<DeptOption[]>([])
const allAssistants = ref<AssistantOption[]>([])
const optionsLoading = ref(false)
const optionsError = ref('')
const deptTreeProps = { value: 'id', label: 'name', children: 'children' }
const deptTreeOptions = computed<DeptTreeNode[]>(() => {
const nodes = new Map<number, DeptTreeNode>()
deptOptions.value.forEach((item) => nodes.set(item.id, { ...item, children: [] }))
const roots: DeptTreeNode[] = []
nodes.forEach((node) => {
const parent = nodes.get(node.pid)
if (parent && parent !== node) parent.children!.push(node)
else roots.push(node)
})
const stripEmptyChildren = (node: DeptTreeNode) => {
if (node.children?.length) node.children.forEach(stripEmptyChildren)
else delete node.children
}
roots.forEach(stripEmptyChildren)
return roots
})
const selectedDeptIds = computed(() => {
if (!deptId.value) return null
const ids = new Set<number>([Number(deptId.value)])
let expanded = true
while (expanded) {
expanded = false
deptOptions.value.forEach((item) => {
if (ids.has(item.pid) && !ids.has(item.id)) {
ids.add(item.id)
expanded = true
}
})
}
return ids
})
const assistantOptions = computed(() =>
allAssistants.value.filter(
(item) => !selectedDeptIds.value || selectedDeptIds.value.has(item.dept_id)
)
)
const handleDeptChange = () => {
if (assistantId.value && !assistantOptions.value.some((item) => item.id === assistantId.value))
assistantId.value = undefined
void loadData()
}
const loadDeptOptions = async () => {
optionsLoading.value = true
optionsError.value = ''
try {
const res = await revisitCohortDeptOptions(props.cohortType)
if (disposed) return
deptOptions.value = (res?.rows ?? []).map((item: DeptOption) => ({
...item,
id: Number(item.id),
pid: Number(item.pid)
}))
allAssistants.value = (res?.assistants ?? []).map((item: AssistantOption) => ({
...item,
id: Number(item.id),
dept_id: Number(item.dept_id)
}))
} catch {
if (!disposed) optionsError.value = '部门及医助选项加载失败,请刷新页面重试。'
} finally {
if (!disposed) optionsLoading.value = false
}
}
const cnDigits = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十']
const slotLabel = (slot: number) => {
if (slot === 0) return '复诊合计'
if (slot >= 1 && slot <= 10) return `${cnDigits[slot]}诊`
if (slot > 10 && slot < 20) return `十${cnDigits[slot - 10]}诊`
return `${slot}诊`
}
const slotCountTip = (slot: number) =>
isInherit.value
? `所选继承患者在继承后的第 ${slot - 1} 笔有效订单数,累计至查询当天;不使用继承前全局诊次和偏移`
: `所选新指派患者的${slotLabel(slot)}有效订单数,从对应指派后累计至查询当天`
const formatRate = (rate: number | null | undefined) =>
rate === null || rate === undefined ? '—' : `${rate}%`
const denText = (row: Record<string, any>, prefix: string) =>
`${Number(row[`${prefix}_count`] ?? 0)} / ${row[`${prefix}_den`] ?? '—'}`
const summaryCards = computed<SummaryCard[]>(() => {
const t = total.value
const cards: SummaryCard[] = [
{
key: 'cohort',
label: cohortLabel.value,
value: t ? String(t[cohortCountKey.value] ?? 0) : '—',
sub: `按${dateLabel.value}范围选择患者`,
clickable: !!(canViewAssignLines.value && t && t[cohortCountKey.value] > 0),
onClick: () => void openAssignDetail(null)
}
]
visitSlots.value.forEach((slot) =>
cards.push({
key: `visit${slot}`,
label: `${slotLabel(slot)}接诊率`,
value: t ? formatRate(t[`visit${slot}_rate`]) : '—',
sub: t
? `${slotLabel(slot)}下单 ${t[`visit${slot}_count`] ?? 0} 单 / 分母 ${t[`visit${slot}_den`] ?? '—'}`
: '',
clickable: !!(canViewOrderLines.value && t && t[`visit${slot}_count`] > 0),
onClick: () => void openOrderDetail(slot, null)
})
)
cards.push({
key: 'visit_all',
label: '复诊合计接诊率',
value: t ? formatRate(t.visit_all_rate) : '—',
sub: t ? `复诊下单 ${t.visit_all_count ?? 0} 单 / 分母 ${t.visit_all_den ?? '—'}` : '',
clickable: !!(canViewOrderLines.value && t && t.visit_all_count > 0),
onClick: () => void openOrderDetail(0, null)
})
return cards
})
/** 服务端已按诊单去重,合计不能由各医助行相加。 */
const getSummaries = ({ columns }: { columns: Array<{ property?: string }> }) =>
columns.map((column, index) => {
if (index === 0) return '合计'
const t = total.value
if (!t) return ''
const prop = column.property || ''
if (prop === cohortCountKey.value) return String(t[prop] ?? 0)
const match = /^visit(\d+|_all)_(count|rate)$/.exec(prop)
if (!match) return ''
return match[2] === 'rate'
? `${formatRate(t[prop])}(${denText(t, `visit${match[1]}`)})`
: String(t[prop] ?? 0)
})
const loadData = async () => {
const requestId = ++overviewRequestId
invalidateDetail()
detailVisible.value = false
loadedQuery.value = null
rows.value = []
total.value = null
observedUntil.value = ''
queryError.value = ''
loading.value = true
const query = currentQuery()
try {
const res = await revisitCohortOverview(query, props.cohortType)
if (disposed || requestId !== overviewRequestId) return
rows.value = res?.rows ?? []
total.value = res?.total ?? null
observedUntil.value = res?.observed_until ?? ''
const slots: number[] = Array.isArray(res?.slots) ? res.slots.map(Number) : []
visitSlots.value = slots.length
? [
...new Set(
slots.filter((slot) => Number.isInteger(slot) && slot >= 2 && slot <= 50)
)
].sort((a, b) => a - b)
: [2, 3, 4]
loadedQuery.value = { ...query }
} catch {
if (!disposed && requestId === overviewRequestId)
queryError.value = '报表加载失败,请重新查询。'
} finally {
if (!disposed && requestId === overviewRequestId) loading.value = false
}
}
const detailVisible = ref(false)
const detailType = ref<'assign' | 'orders'>('assign')
const detailTitle = ref('')
const detailHint = ref('')
const detailLoading = ref(false)
const detailError = ref('')
const detailRows = ref<any[]>([])
const detailCount = ref(0)
const detailSlot = ref(2)
let detailRequestId = 0
const invalidateDetail = () => {
++detailRequestId
detailLoading.value = false
detailRows.value = []
detailCount.value = 0
detailError.value = ''
}
const rowScope = (
row: StatsRow | null
): Pick<RevisitRateDetailQuery, 'scope_assistant_id' | 'dept_id'> & { label: string } => {
if (!row) return { label: '合计' }
return row.is_dept
? { dept_id: row.dept_id, label: row.dept_name }
: { scope_assistant_id: row.assistant_id, label: row.assistant_name || '' }
}
const openDetail = async (type: 'assign' | 'orders', slot: number, row: StatsRow | null) => {
if (loading.value || !loadedQuery.value) return
if (type === 'assign' ? !canViewAssignLines.value : !canViewOrderLines.value) return
const query = { ...loadedQuery.value }
const { label, ...scope } = rowScope(row)
const requestId = ++detailRequestId
detailType.value = type
detailSlot.value = slot
detailTitle.value = `${label} · ${type === 'assign' ? `${cohortLabel.value}明细` : `${slotLabel(slot)}订单明细`}(${query.start_date} 至 ${query.end_date})`
detailHint.value = `${dateLabel.value}:${query.start_date} 至 ${query.end_date};订单统计截至:${observedUntil.value || '查询当天'}${isInherit.value && type === 'orders' ? '。继承后首笔有效订单算二诊,全局诊次仅供参考。' : '。'}`
detailRows.value = []
detailCount.value = 0
detailError.value = ''
detailLoading.value = true
detailVisible.value = true
try {
// assistant_id 保留顶层筛选,scope_assistant_id 独立约束医助行。
const params: RevisitRateDetailQuery = { ...query, ...scope }
const res =
type === 'assign'
? await revisitCohortAssignLines(params, props.cohortType)
: await revisitCohortVisitOrderLines({ ...params, slot }, props.cohortType)
if (disposed || requestId !== detailRequestId || !detailVisible.value) return
detailRows.value = res?.rows ?? []
detailCount.value = Number(res?.count ?? detailRows.value.length)
} catch {
if (!disposed && requestId === detailRequestId)
detailError.value = '明细加载失败,请关闭后重试。'
} finally {
if (!disposed && requestId === detailRequestId) detailLoading.value = false
}
}
const openAssignDetail = (row: StatsRow | null) => openDetail('assign', 0, row)
const openOrderDetail = (slot: number, row: StatsRow | null) => openDetail('orders', slot, row)
const orderDetailRef = ref<{ open: (id: number) => void } | null>(null)
const openOrderInfo = (orderId: number) => {
if (canViewOrderDetail && orderId) orderDetailRef.value?.open(orderId)
}
const diagnosisEditRef = ref<{ openViewOnly: (id: number) => void } | null>(null)
const openPatientDetail = (diagnosisId: number) => {
if (canViewPatientDetail && diagnosisId) diagnosisEditRef.value?.openViewOnly(diagnosisId)
}
const handleReset = () => {
dateRange.value = defaultDateRange()
deptId.value = undefined
assistantId.value = undefined
void loadData()
}
onMounted(() => {
void loadDeptOptions()
void loadData()
})
onBeforeUnmount(() => {
disposed = true
++overviewRequestId
++detailRequestId
})
</script>
<style lang="scss" scoped>
.revisit-rate-page {
.rate-filter-form {
display: flex;
flex-wrap: wrap;
gap: 12px 0;
:deep(.el-form-item) {
margin-bottom: 0;
}
}
.rate-caliber-trigger {
display: inline-flex;
align-items: center;
gap: 4px;
color: var(--el-text-color-secondary);
font-size: 13px;
cursor: help;
}
.rate-kpi-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 12px;
margin-top: 16px;
}
.rate-kpi-card {
background: var(--el-bg-color);
border-radius: 8px;
padding: 16px 20px;
&.is-clickable {
cursor: pointer;
transition: box-shadow 0.15s ease;
&:hover {
box-shadow: var(--el-box-shadow-light);
}
}
.rate-kpi-label {
color: var(--el-text-color-secondary);
font-size: 13px;
}
.rate-kpi-value {
margin-top: 6px;
font-size: 26px;
font-weight: 600;
color: var(--el-text-color-primary);
}
.rate-kpi-sub {
margin-top: 2px;
font-size: 12px;
color: var(--el-text-color-secondary);
}
}
.rate-card-header {
display: flex;
flex-wrap: wrap;
align-items: baseline;
gap: 10px;
}
.rate-card-hint {
font-size: 12px;
color: var(--el-text-color-secondary);
}
.rate-dept-cell {
font-weight: 600;
.rate-dept-count {
margin-left: 6px;
font-weight: 400;
font-size: 12px;
color: var(--el-text-color-secondary);
}
}
.rate-th-hint {
margin-left: 2px;
vertical-align: -2px;
color: var(--el-text-color-secondary);
cursor: help;
}
.rate-cell {
display: flex;
flex-direction: column;
align-items: flex-end;
line-height: 1.3;
.rate-cell-main {
font-weight: 500;
}
.rate-cell-sub {
font-size: 11px;
color: var(--el-text-color-placeholder);
}
}
}
.rate-detail-hint {
margin: 0 0 12px;
font-size: 12px;
color: var(--el-text-color-secondary);
}
.rate-detail-footer {
margin-top: 10px;
text-align: right;
font-size: 12px;
color: var(--el-text-color-secondary);
}
.rate-caliber {
font-size: 13px;
line-height: 1.7;
color: var(--el-text-color-regular);
p + p {
margin-top: 6px;
}
}
</style>
@@ -0,0 +1,7 @@
<template>
<cohort-report cohort-type="new" />
</template>
<script setup lang="ts" name="revisitAssignRateStatsPage">
import CohortReport from './components/CohortReport.vue'
</script>
@@ -0,0 +1,7 @@
<template>
<cohort-report cohort-type="inherit" />
</template>
<script setup lang="ts" name="revisitInheritRateStatsPage">
import CohortReport from '../revisit_assign_rate/components/CohortReport.vue'
</script>
+2
View File
@@ -1,5 +1,6 @@
<template>
<div class="appointment-list">
<DoctorWebConsultationNotice />
<el-card class="list-card !border-none" shadow="never">
<!-- 单行工具栏:Tab(主) + 搜索(辅) -->
<div class="list-toolbar">
@@ -559,6 +560,7 @@
</template>
<script setup lang="ts">
import DoctorWebConsultationNotice from '@/components/doctor-web-consultation-notice/index.vue'
import { appointmentTypeDescription, canAppointmentVideoCall } from '@/utils/appointment-type'
import { usePaging } from '@/hooks/usePaging'
import { defineAsyncComponent, onMounted, onUnmounted, watch } from 'vue'
@@ -1,5 +1,6 @@
<template>
<div class="apt-h5">
<DoctorWebConsultationNotice />
<template v-if="currentView === 'list'">
<header class="apt-h5-topbar">
<div class="apt-h5-search">
@@ -412,6 +413,7 @@
</template>
<script setup lang="ts" name="tcmAppointmentH5">
import DoctorWebConsultationNotice from '@/components/doctor-web-consultation-notice/index.vue'
import { appointmentTypeDescription, canAppointmentVideoCall } from '@/utils/appointment-type'
import { appointmentDetail, appointmentLists, cancelAppointment, completeAppointment } from '@/api/doctor'
import { getWeappConfig } from '@/api/channel/weapp'
@@ -0,0 +1,168 @@
<template>
<section class="consultation-transcripts">
<header class="transcript-toolbar">
<div>
<h3>面诊文字对话</h3>
<p>按每次通话分别查看已保存的文字记录。</p>
</div>
<el-button :loading="loading" @click="refresh"><el-icon><Refresh /></el-icon>刷新</el-button>
</header>
<el-alert v-if="error" :title="error" type="error" :closable="false" show-icon class="transcript-error" />
<div v-loading="loading" class="transcript-body">
<template v-if="records.length">
<aside class="transcript-sessions" aria-label="历次面诊记录">
<el-input v-model="search" clearable placeholder="搜索面诊时间或对话内容" :prefix-icon="Search" />
<p class="session-count">{{ filteredRecords.length }} 条面诊记录</p>
<div class="session-list">
<button
v-for="row in pageRecords"
:key="row.id"
type="button"
class="session-item"
:class="{ selected: selectedId === row.id }"
:aria-pressed="selectedId === row.id"
@click="selectedId = row.id"
>
<span class="session-time">{{ row.start_time_text || '开始时间未记录' }}</span>
<span class="session-meta">{{ consultationCallLabel(row) }} · 记录 #{{ row.id }}</span>
<el-tag size="small" :type="consultationTranscriptStatus(row).type">{{ consultationTranscriptStatus(row).label }}</el-tag>
<span class="session-preview">{{ preview(row) }}</span>
</button>
</div>
<el-pagination
v-if="filteredRecords.length > PAGE_SIZE"
v-model:current-page="page"
:page-size="PAGE_SIZE"
:total="filteredRecords.length"
layout="prev, pager, next"
small
/>
</aside>
<article v-if="selectedRecord" class="transcript-detail" :key="`${diagnosisId}-${selectedRecord.id}`">
<header class="transcript-detail-header">
<div>
<h4>{{ selectedRecord.start_time_text || '开始时间未记录' }} · {{ consultationCallLabel(selectedRecord) }}</h4>
<p>
通话记录 #{{ selectedRecord.id }}
<span v-if="selectedRecord.duration_text"> · 时长 {{ selectedRecord.duration_text }}</span>
<span v-if="selectedRecord.end_time_text"> · 结束 {{ selectedRecord.end_time_text }}</span>
</p>
</div>
<el-button v-if="selectedText" :loading="copying" @click="copyTranscript">复制全文</el-button>
</header>
<div class="transcript-status">
<el-tag :type="consultationTranscriptStatus(selectedRecord).type">{{ consultationTranscriptStatus(selectedRecord).label }}</el-tag>
<span>{{ callStatusText(selectedRecord.status) }}</span>
<span v-if="selectedRecord.transcription_segment_count">{{ selectedRecord.transcription_segment_count }} 段对话</span>
</div>
<p v-if="selectedRecord.transcription_status === 'partial'" class="transcript-note">本次文字记录不完整,以下展示已保存的内容。</p>
<p v-else-if="selectedRecord.transcription_status === 'failed' && selectedText" class="transcript-note">本次转写未完成,以下展示已保存的内容。</p>
<p v-else-if="selectedRecord.transcription_status === 'running' && selectedText" class="transcript-note">转写仍在进行,可刷新查看最新保存的文字。</p>
<pre v-if="selectedText" class="transcript-text">{{ selectedText }}</pre>
<el-empty v-else :description="consultationTranscriptEmptyText(selectedRecord)" :image-size="72" />
</article>
<el-empty v-else description="没有匹配的面诊记录,请调整搜索内容" class="transcript-detail" :image-size="72" />
</template>
<el-empty v-else-if="!loading && !error" description="该诊单暂无面诊通话记录" :image-size="80" class="transcript-empty" />
</div>
</section>
</template>
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { Refresh, Search } from '@element-plus/icons-vue'
import type { ConsultationCallRecord } from '@/api/tcm'
import { useConsultationTranscripts } from '@/hooks/useConsultationTranscripts'
import {
consultationCallLabel,
consultationTranscriptEmptyText,
consultationTranscriptStatus,
consultationTranscriptText
} from '@/utils/consultation-transcripts'
import feedback from '@/utils/feedback'
const props = defineProps<{ diagnosisId: number }>()
const { records, loading, error, refresh } = useConsultationTranscripts(() => props.diagnosisId)
const search = ref('')
const selectedId = ref<number | null>(null)
const page = ref(1)
const copying = ref(false)
const PAGE_SIZE = 10
const filteredRecords = computed(() => {
const term = search.value.trim().toLocaleLowerCase()
return records.value.filter(row => row.diagnosis_id === props.diagnosisId &&
(!term || `${row.start_time_text || ''} ${row.id} ${consultationTranscriptText(row)}`.toLocaleLowerCase().includes(term)))
})
const pageRecords = computed(() => filteredRecords.value.slice((page.value - 1) * PAGE_SIZE, page.value * PAGE_SIZE))
const selectedRecord = computed(() => filteredRecords.value.find(row => row.id === selectedId.value))
const selectedText = computed(() => consultationTranscriptText(selectedRecord.value))
watch(filteredRecords, rows => {
if (!rows.some(row => row.id === selectedId.value)) {
const selected = rows.find(row => consultationTranscriptText(row)) || rows[0]
selectedId.value = selected?.id ?? null
page.value = selected ? Math.floor(rows.indexOf(selected) / PAGE_SIZE) + 1 : 1
}
page.value = Math.min(page.value, Math.max(1, Math.ceil(rows.length / PAGE_SIZE)))
}, { immediate: true, flush: 'sync' })
watch(search, () => { page.value = 1 }, { flush: 'sync' })
function preview(row: ConsultationCallRecord): string {
const text = consultationTranscriptText(row).replace(/\s+/g, ' ')
return text ? text.slice(0, 90) + (text.length > 90 ? '…' : '') : consultationTranscriptEmptyText(row)
}
function callStatusText(value?: number): string {
return ({ 1: '进行中', 2: '已结束', 3: '未接听', 4: '已取消' } as Record<number, string>)[Number(value)] || '状态未记录'
}
async function copyTranscript() {
const text = selectedText.value
if (!text || copying.value) return
if (!navigator.clipboard?.writeText) {
feedback.msgWarning('当前浏览器不支持自动复制,请选中文字复制')
return
}
copying.value = true
try {
await navigator.clipboard.writeText(text)
feedback.msgSuccess('已复制本次面诊文字对话')
} catch {
feedback.msgWarning('复制失败,请选中文字复制')
} finally {
copying.value = false
}
}
</script>
<style scoped>
.consultation-transcripts { padding: 4px 0 16px; }
.transcript-toolbar, .transcript-detail-header { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; }
.transcript-toolbar { margin-bottom: 20px; }
.transcript-toolbar h3, .transcript-detail h4 { margin: 0; color: var(--el-text-color-primary); font-weight: 600; }
.transcript-toolbar h3 { font-size: 18px; }
.transcript-toolbar p, .transcript-detail-header p { margin: 7px 0 0; color: var(--el-text-color-secondary); line-height: 1.7; font-size: 13px; }
.transcript-error { margin-bottom: 16px; }
.transcript-body { display: flex; min-height: 360px; border-top: 1px solid var(--el-border-color-lighter); }
.transcript-sessions { flex: 0 0 282px; min-width: 0; padding: 18px 18px 0 0; border-right: 1px solid var(--el-border-color-lighter); }
.session-count { margin: 12px 0 8px; color: var(--el-text-color-secondary); font-size: 12px; }
.session-list { display: flex; flex-direction: column; gap: 8px; max-height: 580px; overflow-y: auto; margin-bottom: 12px; }
.session-item { display: flex; flex-direction: column; align-items: flex-start; gap: 8px; width: 100%; padding: 13px 12px; border: 1px solid var(--el-border-color-lighter); border-radius: 7px; background: var(--el-bg-color); text-align: left; cursor: pointer; font: inherit; }
.session-item:hover, .session-item.selected { border-color: var(--el-color-primary); background: var(--el-color-primary-light-9); }
.session-item:focus-visible { outline: 2px solid var(--el-color-primary); outline-offset: -2px; }
.session-time { color: var(--el-text-color-primary); font-size: 14px; font-weight: 600; }
.session-meta, .session-preview { color: var(--el-text-color-secondary); font-size: 12px; line-height: 1.6; }
.session-preview { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; overflow-wrap: anywhere; }
.transcript-detail { flex: 1; min-width: 0; padding: 20px 0 0 24px; }
.transcript-detail h4 { font-size: 16px; line-height: 1.7; }
.transcript-status { display: flex; align-items: center; flex-wrap: wrap; gap: 12px; margin: 16px 0; color: var(--el-text-color-secondary); font-size: 13px; }
.transcript-note { padding: 10px 12px; background: var(--el-color-warning-light-9); color: var(--el-color-warning-dark-2); font-size: 13px; line-height: 1.7; }
.transcript-text { margin: 0; padding: 20px 0; color: var(--el-text-color-primary); white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; font-size: 15px; line-height: 2; user-select: text; }
.transcript-empty { flex: 1; }
@media (max-width: 900px) {
.transcript-body { flex-direction: column; }
.transcript-sessions { flex-basis: auto; padding: 16px 0; border-right: 0; border-bottom: 1px solid var(--el-border-color-lighter); }
.session-list { max-height: 300px; }
.transcript-detail { padding: 20px 0 0; }
.transcript-detail-header { flex-wrap: wrap; }
}
</style>
@@ -205,8 +205,8 @@
</header>
<dl class="daily-matrix__detail-fields">
<dt>运动</dt><dd>{{ record.exercise_type || '—' }}</dd>
<dt>时长</dt><dd>{{ record.duration ?? '—' }} 分钟</dd>
<dt>强度</dt><dd>{{ record.intensity_text || intensityLabel(record.intensity) }}</dd>
<dt>时长</dt><dd>{{ record.duration == null ? '未记录' : `${record.duration} 分钟` }}</dd>
<dt>强度</dt><dd>{{ intensityLabel(record.intensity) }}</dd>
<dt>备注</dt><dd>{{ record.note || '—' }}</dd>
</dl>
<div v-if="record.images?.length" class="daily-matrix__detail-images">
@@ -343,11 +343,13 @@
<el-option label="其他" value="其他" />
</el-select>
</el-form-item>
<el-form-item label="运动时长(分钟)" required>
<el-input-number v-model="exerciseForm.duration" :min="0" :max="300" />
<el-form-item label="运动时长(分钟)" :required="!exerciseForm.id">
<el-input-number v-model="exerciseForm.duration" :min="0" :max="300" placeholder="未记录" />
<span v-if="exerciseForm.id" class="ml-2 text-info">留空表示未记录</span>
</el-form-item>
<el-form-item label="运动强度" required>
<el-select v-model="exerciseForm.intensity" placeholder="请选择运动强度" class="w-full">
<el-form-item label="运动强度">
<el-select v-model="exerciseIntensity" placeholder="未记录" class="w-full">
<el-option label="未记录" value="" />
<el-option label="低强度" :value="1" />
<el-option label="中强度" :value="2" />
<el-option label="高强度" :value="3" />
@@ -492,8 +494,8 @@ interface ExerciseRecord {
patient_id?: number
record_date?: string
exercise_type?: string
duration?: number
intensity?: number
duration?: number | null
intensity?: number | null
intensity_text?: string
images?: string[]
note?: string
@@ -547,6 +549,11 @@ const trackingSubmitting = ref(false)
const bloodForm = ref<BloodRecord>(createBloodForm())
const dietForm = ref<DietRecord>(createDietForm())
const exerciseForm = ref<ExerciseRecord>(createExerciseForm())
// el-option uses a string sentinel; persisted unknowns remain SQL/JSON null.
const exerciseIntensity = computed<number | ''>({
get: () => exerciseForm.value.intensity ?? '',
set: (value) => { exerciseForm.value.intensity = value === '' ? null : value }
})
const trackingForm = ref({
note_date: '',
existing_content: '',
@@ -719,8 +726,8 @@ function recordTimePeriodLabel(record: BloodRecord) {
return labels[period] || period || '未提供时段'
}
function intensityLabel(value?: number) {
return ({ 1: '低强度', 2: '中强度', 3: '高强度' } as Record<number, string>)[Number(value)] || '—'
function intensityLabel(value?: number | null) {
return ({ 1: '低强度', 2: '中强度', 3: '高强度' } as Record<number, string>)[Number(value)] || '未记录'
}
function bloodDetailFields(record: BloodRecord) {
@@ -880,7 +887,7 @@ function getCell(metric: string, date: string): { value: string; isHigh: boolean
return { value: count ? '✓' : '', isHigh: false, hasRecord: count > 0 }
}
if (metric === 'exercise') {
return { value: exercise.map((record) => record.duration ? `${record.duration}min` : record.exercise_type || '已记录').join(' / '), isHigh: false, hasRecord: exercise.length > 0 }
return { value: exercise.map((record) => record.duration != null ? `${record.duration}min` : record.exercise_type || '已记录').join(' / '), isHigh: false, hasRecord: exercise.length > 0 }
}
if (metric === 'tracking') {
return { value: tracking?.content ? summarizeTracking(tracking.content) : '', isHigh: false, hasRecord: !!tracking?.content }
@@ -970,7 +977,12 @@ function openDietRecord(source: DietRecord | undefined, date: string) {
function openExerciseRecord(source: ExerciseRecord | undefined, date: string) {
if (!canEditDailyRecord.value) return
exerciseForm.value = { ...createExerciseForm(date), ...source, images: [...(source?.images || [])] }
exerciseForm.value = {
...createExerciseForm(date), ...source,
// Existing omissions must not inherit the defaults used only for manual new records.
...(source ? { duration: source.duration ?? null, intensity: source.intensity ?? null } : {}),
images: [...(source?.images || [])]
}
exerciseDialogVisible.value = true
}
@@ -1063,12 +1075,12 @@ async function submitExercise() {
feedback.msgWarning('请选择运动类型')
return
}
if (!exerciseForm.value.duration) {
if (!exerciseForm.value.id && !exerciseForm.value.duration) {
feedback.msgWarning('请输入运动时长')
return
}
const targetDiagnosisId = diagnosisId.value
const payload = { ...exerciseForm.value }
const payload = { ...exerciseForm.value, duration: exerciseForm.value.duration ?? null, intensity: exerciseForm.value.intensity ?? null }
exerciseSubmitting.value = true
try {
if (payload.id) {
@@ -34,8 +34,8 @@
<el-table-column label="状态" width="145">
<template #default="{ row }"><el-tag size="small" :type="statusType(row.status)">{{ followupTaskStatus(row) }}</el-tag><div v-if="row.transcript_available && (row.status === 'failed' || row.status === 'needs_reconciliation')" class="task-time">转写已保留</div></template>
</el-table-column>
<el-table-column label="操作" width="65" align="right">
<template #default="{ row }"><el-button link type="primary" :disabled="busy" @click="openTask(row.id)">查看</el-button></template>
<el-table-column label="操作" width="112" align="right">
<template #default="{ row }"><el-button link type="primary" :disabled="busy" @click="openTask(row.id)">查看</el-button><el-button v-if="!viewOnly && row.can_delete !== undefined" link type="danger" :disabled="busy || !canDeleteTask(row)" :title="row.delete_block_reason || '删除未入单录音任务'" @click="deleteRecording(row)">删除</el-button></template>
</el-table-column>
</el-table>
</div>
@@ -43,7 +43,7 @@
<section v-if="selectedId && detail" class="task-detail" aria-label="录音任务详情">
<div class="detail-heading">
<div class="recording-title"><h3>{{ detail.file_name }}</h3><span>通话时间 {{ detail.recorded_at }}</span></div>
<el-tag size="small" :type="statusType(detail.status)">{{ followupTaskStatus(detail) }}</el-tag>
<div class="detail-actions"><el-tag size="small" :type="statusType(detail.status)">{{ followupTaskStatus(detail) }}</el-tag><el-button v-if="!viewOnly && detail.can_delete !== undefined" link type="danger" :disabled="busy || !canDeleteTask(detail)" :title="detail.delete_block_reason || '删除未入单录音任务'" @click="deleteRecording(detail)">删除录音</el-button></div>
</div>
<p v-if="detail.status === 'running' || detail.status === 'queued'" class="processing-state" role="status">{{ followupProgressText(detail) }}</p>
<el-alert v-if="detail.error_message || detail.status === 'failed'" :type="detail.status === 'failed' ? 'error' : 'warning'" :closable="false" :title="detail.error_message || '任务处理失败,不能写入;请先核对失败原因。'" />
@@ -56,13 +56,25 @@
<p>{{ detail.summary || '暂无回访摘要' }}</p>
<div class="summary-counts"><span>{{ detail.status === 'applied' ? '已写入' : '已选' }} <strong>{{ selectedCount }}</strong> 项</span><span>待核实 <strong>{{ pendingCount }}</strong> 项</span></div>
</div>
<section v-if="hasStereo" class="channel-role-box" aria-label="声道角色人工标注">
<el-alert v-if="detail.status === 'review' && !reviewItems.length" type="warning" :closable="false" title="未生成可写入信息" :description="detail.uncertainties.length ? `本次提炼保留了 ${detail.uncertainties.length} 条待核实原因,已展示在下方。请结合原文回听核对,尤其注意声道角色是否相符。` : '请查看回访摘要并回听录音;本次没有可供确认写入的结构化候选。'" show-icon />
<section v-if="hasStereo && !['queued', 'running'].includes(detail.status)" class="channel-role-box" aria-label="声道角色人工标注">
<div v-if="savedChannelRoles !== 'unconfirmed' && !editingRoles && !roleDirty" class="role-summary"><span>{{ savedChannelRoles === 'left_service' ? '左客服端 / 右患者或家属端' : '右客服端 / 左患者或家属端' }} · 已确认</span><el-button v-if="canEditReview" link type="primary" @click="editingRoles = true">修改</el-button></div>
<label v-else>声道角色(人工确认)<el-select :model-value="channelRoles" :disabled="!canEditReview || (busy && mutation !== 'save')" @update:model-value="setChannelRoles"><el-option label="角色待确认" value="unconfirmed" /><el-option label="左客服端 / 右患者或家属端" value="left_service" /><el-option label="右客服端 / 左患者或家属端" value="right_service" /></el-select></label>
<p v-if="savedChannelRoles === 'unconfirmed' || editingRoles || roleDirty" class="muted">声道不等于已核实的说话人身份。角色标注不自动重新提炼;变更后保存草稿会取消全部采纳,须重新核对。</p>
<p v-if="savedChannelRoles !== 'unconfirmed' && !roleDirty" class="muted">当前角色已确认,无需再次选择;只有左右标错时才需修改。</p>
<p v-if="roleDirty" class="review-error" role="status">角色标注正在等待保存;保存后请逐项重新核对。</p>
</section>
<section v-if="detail.role_check?.conflict || (detail.can_reextract !== undefined && savedChannelRoles !== extractionRoles && savedChannelRoles !== 'unconfirmed')" class="role-reextract" aria-label="角色纠错与重新提炼">
<strong>{{ detail.role_check?.conflict ? '声道角色与转写内容可能不一致' : '审核角色已修改,原提炼结果尚未更新' }}</strong>
<p>{{ detail.role_check?.message || '修改角色标注不会自动改变已生成的建议,可按核实后的角色重新提炼。' }}</p>
<blockquote v-for="(evidence, index) in detail.role_check?.evidence || []" :key="index"><span>{{ evidence.channel === 0 ? '左声道' : '右声道' }} · {{ audioTimestamp(evidence.start_ms) }}:{{ evidence.text }}</span><el-button v-if="detail.audio_available" link type="primary" @click="loadDialogue(evidence.start_ms)">回听依据</el-button></blockquote>
<p>当前提炼依据:{{ extractionRoleLabel(extractionRoles) }}。{{ reextractTarget !== 'unconfirmed' ? `待确认的新角色:${extractionRoleLabel(reextractTarget)}。` : '请先回听并修改上方角色标注。' }}建议仅供核对,系统不会自动交换角色。</p>
<el-button type="primary" plain :disabled="!canReextract || busy || dirty || reextractTarget === 'unconfirmed' || reextractTarget === extractionRoles" @click="reextractWithRoles">确认角色并重新提炼</el-button>
<p v-if="dirty">请先完成当前单项核对或取消编辑,等待审核草稿保存后再重新提炼。</p>
<p v-else-if="detail.reextract_block_reason">{{ detail.reextract_block_reason }}</p>
<p class="muted">复用已完成的转写,不重复语音识别;旧结果保留,重新提炼不自动写入病例。</p>
</section>
<p v-if="(detail.extraction_revision || 0) > 0" class="muted">第 {{ (detail.extraction_revision || 0) + 1 }} 版提炼 · {{ extractionRoleLabel(extractionRoles) }} · 历史结果已保留</p>
<FollowupAudioReview :key="selectedId" ref="reviewRef" v-model:items="reviewItems" :fields="detail.fields || capabilities.fields" :disabled="!canEditReview || uploading || (mutation !== '' && mutation !== 'save')" :can-daily="capabilities.can_daily" :applied="detail.status === 'applied'" :uncertainties="detail.uncertainties" :snapshot-items="detail.items" :channel-roles="savedChannelRoles" :save-state="saveState" :persisted-revision="persistedRevision" @saved-next="saveDraft(true)" @seek="loadDialogue">
<template #player>
<div class="audio-player">
@@ -144,13 +156,13 @@
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
FollowupAudioError, followupAudioApply, followupAudioBlob, followupAudioCreate,
FollowupAudioError, followupAudioReextract, followupAudioDelete, followupAudioApply, followupAudioBlob, followupAudioCreate,
followupAudioDetail, followupAudioLists, followupAudioRetry, followupAudioSaveDraft,
followupAudioUploadChunk, followupAudioUploadComplete, followupAudioUploadSession,
type FollowupAudioChannel, type FollowupCapabilities, type FollowupChannelRoles, type FollowupReviewItem, type FollowupTaskDetail, type FollowupTaskSummary
} from '@/api/followupAudio'
import FollowupAudioReview from './FollowupAudioReview.vue'
import { channelPlaybackLabel, dialogueWindows, dialoguePlaybackStart, audioTimestamp, changedReviewTarget, cloneReviewItems, createFollowupScope, followupAudioReady, followupCanApply, followupCanReview, followupChannelLabel, followupError, followupFeatureEnabled, followupProgressText, followupTaskStatus, hasStereoTranscript, normalizedChannelRoles, rebaseReviewItems, retainedTranscriptNotice, reviewFieldIssue, reviewIssue, reviewPending, uploadChunks, uploadIssue } from './followupAudioState'
import { channelPlaybackLabel, dialogueWindows, dialoguePlaybackStart, audioTimestamp, changedReviewTarget, cloneReviewItems, createFollowupScope, followupAudioReady, followupCanApply, followupCanReview, followupChannelLabel, followupError, followupFeatureEnabled, followupProgressText, followupTaskStatus, hasStereoTranscript, normalizedChannelRoles, rebaseReviewItems, retainedTranscriptNotice, reviewBatchIssue, reviewFieldIssue, reviewIssue, reviewPending, uploadChunks, uploadIssue } from './followupAudioState'
import { createFollowupAudioPlayback, type FollowupPlaybackChannel } from './followupAudioPlayback'
const props = withDefaults(defineProps<{
diagnosisId: number; viewOnly?: boolean; active?: boolean; capabilities: FollowupCapabilities;
@@ -194,7 +206,7 @@ const uploading = ref(false)
const uploadProgress = ref(0)
const uploadStage = ref('')
const createUncertain = ref(false)
const mutation = ref<'save' | 'apply' | 'retry' | ''>('')
const mutation = ref<'save' | 'apply' | 'retry' | 'delete' | 'reextract' | ''>('')
const errorMessage = ref('')
const audioUrl = ref('')
const audioElement = ref<HTMLAudioElement | null>(null)
@@ -210,6 +222,12 @@ const audioReady = computed(() => followupAudioReady(props.capabilities))
const canUpload = computed(() => !props.viewOnly && featureEnabled.value && audioReady.value && props.capabilities.can_upload && props.capabilities.models.length > 0)
const canEditReview = computed(() => !props.viewOnly && followupCanReview(props.capabilities, !!detail.value?.preview_only) && detail.value?.status === 'review')
const canApplyReview = computed(() => !props.viewOnly && followupCanApply(props.capabilities, !!detail.value?.preview_only) && detail.value?.status === 'review')
const extractionRoles = computed(() => normalizedChannelRoles(detail.value?.extraction_channel_roles))
const reextractTarget = computed<FollowupChannelRoles>(() => {
if (savedChannelRoles.value !== 'unconfirmed' && savedChannelRoles.value !== extractionRoles.value) return savedChannelRoles.value
return normalizedChannelRoles(detail.value?.role_check?.suggested_roles)
})
const canReextract = computed(() => !props.viewOnly && featureEnabled.value && detail.value?.status === 'review' && detail.value?.can_reextract === true)
const selectedCount = computed(() => reviewItems.value.filter(item => item.selected).length)
const pendingCount = computed(() => reviewItems.value.filter(item => reviewPending(item, detail.value?.fields || props.capabilities.fields, props.capabilities.can_daily)).length + (detail.value?.uncertainties.length || 0))
const applyIssue = computed(() => previewOnly.value ? '测试预览仅保存审核草稿,不允许确认写入病历'
@@ -220,7 +238,7 @@ const applyIssue = computed(() => previewOnly.value ? '测试预览仅保存审
: hasStereo.value && savedChannelRoles.value === 'unconfirmed' ? '请先回听并确认声道角色,保存草稿后重新核对建议'
: changedReviewTarget(reviewItems.value, detail.value?.items || [])
? '写入目标或记录日期已更改,请先保存审核草稿取得新快照,再核对并采纳'
: reviewItems.value.map(item => reviewFieldIssue(item, detail.value?.fields || props.capabilities.fields) || reviewIssue(item, props.capabilities.can_daily)).find(Boolean) || '')
: reviewBatchIssue(reviewItems.value, detail.value?.fields || props.capabilities.fields) || reviewItems.value.map(item => reviewFieldIssue(item, detail.value?.fields || props.capabilities.fields) || reviewIssue(item, props.capabilities.can_daily)).find(Boolean) || '')
const effectiveActive = computed(() => props.active && featureEnabled.value && documentVisible.value)
const scope = createFollowupScope()
let timer: ReturnType<typeof setTimeout> | undefined
@@ -270,9 +288,25 @@ function setChannelRoles(value: unknown) {
if (!canEditReview.value || (busy.value && mutation.value !== 'save') || !hasStereo.value || !['unconfirmed', 'left_service', 'right_service'].includes(String(value))) return
channelRoles.value = value as FollowupChannelRoles
}
async function readDetail(id: number, preserve = false) {
function taskUnavailable(error: unknown): boolean {
return error instanceof FollowupAudioError && (error.code === 'FOLLOWUP_AUDIO_TASK_UNAVAILABLE' || error.message.includes('FOLLOWUP_AUDIO_TASK_UNAVAILABLE'))
}
function forgetUnavailableTask(id: number) {
if (selectedId.value !== id) return
stop(); resetRoles(); selectedId.value = 0; detail.value = null; reviewItems.value = []; snapshot.value = '[]'; detailSections.value = []
tasks.value = tasks.value.filter(row => row.id !== id)
errorMessage.value = '录音已删除或不再可访问,已关闭本页缓存与播放;未写入病例。'
void refresh()
}
async function readDetail(id: number, preserve = false, verifyOnly = false) {
const ticket = scope.capture()
const fresh = await followupAudioDetail(id, ticket.signal)
let fresh: FollowupTaskDetail
try { fresh = await followupAudioDetail(id, ticket.signal) }
catch (error) {
if (scope.current(ticket) && id === selectedId.value && taskUnavailable(error)) { forgetUnavailableTask(id); return }
throw error
}
if (verifyOnly && detail.value && fresh.version === detail.value.version && fresh.status === detail.value.status) return
if (!scope.current(ticket) || id !== selectedId.value || (detail.value && fresh.version < detail.value.version)) return
preserve = preserve || (!!detail.value && dirty.value)
const newlyApplied = detail.value?.status === 'review' && fresh.status === 'applied'
@@ -292,6 +326,9 @@ async function refresh() {
const updated = tasks.value.find(task => task.id === selectedId.value)
if (updated && (!detail.value || updated.version > detail.value.version || (updated.version >= detail.value.version && updated.status !== detail.value.status) || updated.status === 'running')) {
await readDetail(updated.id, dirty.value)
} else if (!updated && selectedId.value && detail.value) {
// A limited list can omit older tasks; only an authoritative detail denial revokes them.
await readDetail(selectedId.value, false, true)
}
} catch (error) { if (scope.current(ticket)) errorMessage.value = followupError(error) }
finally {
@@ -382,6 +419,7 @@ async function submitUpload() {
}
async function handleReviewError(error: unknown) {
const ticket = scope.capture()
if (taskUnavailable(error) && detail.value) { forgetUnavailableTask(detail.value.id); return }
errorMessage.value = followupError(error)
const stale = error instanceof FollowupAudioError && error.code === 'FOLLOWUP_AUDIO_STALE_REVIEW'
if (stale || /STALE_REVIEW|版本|快照|已变化/.test(errorMessage.value)) {
@@ -488,6 +526,57 @@ async function applySelected() {
} catch (error) { if (scope.current(ticket)) await handleReviewError(error) }
finally { if (scope.current(ticket)) { mutation.value = ''; await refresh() } }
}
function extractionRoleLabel(roles: FollowupChannelRoles): string {
return roles === 'left_service' ? '左客服 / 右患者或家属' : roles === 'right_service' ? '右客服 / 左患者或家属' : '角色未确认'
}
async function reextractWithRoles() {
const roles = reextractTarget.value
if (!canReextract.value || !detail.value || busy.value || roles === 'unconfirmed' || roles === extractionRoles.value) return
if (dirty.value) { ElMessage.warning('请先完成或取消当前审核修改,等待草稿保存后再重新提炼'); return }
const ticket = scope.capture(), id = detail.value.id, version = detail.value.version, diagnosisId = props.diagnosisId
const current = () => scope.current(ticket) && diagnosisId === props.diagnosisId && selectedId.value === id
clearAutosave(); clearTimer(); mutation.value = 'reextract'; errorMessage.value = ''
let confirmed = false
try {
await ElMessageBox.confirm(`确认已回听并核实角色为“${extractionRoleLabel(roles)}”?将保留旧版结果,复用已完成的转写重新提炼,不重复语音识别;新建议须重新审核,不自动写入病例。`, '确认角色并重新提炼', { type: 'warning', confirmButtonText: '角色正确,开始重新提炼', cancelButtonText: '返回回听' })
if (!current() || !canReextract.value || dirty.value) return
confirmed = true
const fresh = await followupAudioReextract({ id, version, channel_roles: roles }, ticket.signal)
if (!current()) return
installDetail(fresh, false); saveState.value = 'idle'; editingRoles.value = false
ElMessage.success('已提交重新提炼,将复用原转写;新结果仍需审核,不自动写入病例')
} catch (error) { if (confirmed && current()) await handleReviewError(error) }
finally { if (current()) { mutation.value = ''; scheduleAutosave(); await refresh() } }
}
function canDeleteTask(task: FollowupTaskSummary): boolean {
return !props.viewOnly && featureEnabled.value && task.can_delete === true && ['review', 'failed'].includes(task.status)
}
async function deleteRecording(task: FollowupTaskSummary) {
if (busy.value || !canDeleteTask(task)) return
const ticket = scope.capture(), diagnosisId = props.diagnosisId, id = task.id, version = task.version
const current = () => scope.current(ticket) && diagnosisId === props.diagnosisId
clearAutosave(); clearTimer(); mutation.value = 'delete'; errorMessage.value = ''
let confirmed = false
try {
await ElMessageBox.confirm('删除后,该录音任务及审核草稿将从列表移除,未保存修改会丢弃;不删除或回滚病例。原录音和转写仍按原保留期限清理。重新上传同一文件将创建新的分析任务。确认删除?', '删除录音任务', { type: 'warning', confirmButtonText: '确认删除', cancelButtonText: '保留录音' })
if (!current() || !canDeleteTask(task)) return
confirmed = true
await followupAudioDelete({ id, version }, ticket.signal)
if (!current()) return
// Fence pending playback, autosaves and reads; deletion never revives a stale draft.
if (selectedId.value === id) {
stop(); resetRoles(); selectedId.value = 0; detail.value = null; reviewItems.value = []; snapshot.value = '[]'; detailSections.value = []
}
tasks.value = tasks.value.filter(row => row.id !== id)
errorMessage.value = ''
ElMessage.success('录音任务已删除,未修改病例。原资料按保留策略清理。')
await refresh()
} catch (error) {
if (confirmed && current()) errorMessage.value = followupError(error)
} finally {
if (current()) { mutation.value = ''; scheduleAutosave(); await refresh() }
}
}
async function retryTask() {
if (!detail.value?.can_retry || detail.value.status !== 'failed' || !canUpload.value || busy.value) return
const ticket = scope.capture()
@@ -577,6 +666,11 @@ h3 { margin: 0; font-size: 14px; font-weight: 600; }
.detail-heading { align-items: flex-start; }
.recording-title { min-width: 0; }
.recording-title h3 { overflow-wrap: anywhere; line-height: 1.6; }
.role-reextract { padding: 12px; border: 1px solid var(--el-color-warning-light-5); background: var(--el-color-warning-light-9); border-radius: 6px; display: grid; gap: 8px; }
.role-reextract p { margin: 0; line-height: 1.6; }
.role-reextract blockquote { margin: 0; padding: 8px; background: var(--el-bg-color); white-space: pre-wrap; overflow-wrap: anywhere; }
.role-reextract :deep(.el-button) { justify-self: start; }
.detail-actions { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
.detail-heading :deep(.el-tag) { flex-shrink: 0; }
.detail-loading { padding: 32px; text-align: center; color: var(--el-text-color-secondary); }
.processing-state, .applied-note { margin: 0; color: var(--el-text-color-secondary); font-size: 13px; }
@@ -32,8 +32,8 @@
</el-table-column>
</el-table>
</div>
<section v-if="group === 'pending' && uncertainties?.length" class="uncertainty-list" aria-label="原文待核实信息">
<strong>原文中还需补充的信息</strong>
<section v-if="(group === 'pending' || !items.length) && uncertainties?.length" class="uncertainty-list" aria-label="原文待核实信息">
<strong>本次未能确认的信息与原因</strong>
<ul><li v-for="(value, index) in uncertainties" :key="index">{{ uncertaintyText(value) }}</li></ul>
</section>
<section ref="reviewWorkspace" class="review-workspace" tabindex="-1" aria-label="同页核对与回听">
@@ -70,6 +70,22 @@ export function fieldText(value: FollowupValue | undefined, field: FollowupField
export function hasEditableReviewFields(item: FollowupReviewItem, fields: FollowupFields): boolean {
return Object.keys(item.values).some(key => fields[item.kind]?.some(field => field.key === key && !field.readonly))
}
/** Prevent multiple selected writes to the same diagnosis field; never silently pick a last value. */
export function reviewBatchIssue(items: FollowupReviewItem[], fields: FollowupFields): string {
const touched = new Set<string>()
for (const item of items.filter(item => item.selected)) {
if (item.kind === 'diagnosis') {
for (const key of Object.keys(item.values)) {
if (touched.has(key)) {
const label = fields.diagnosis?.find(field => field.key === key)?.label || key
return `${label}存在多条选中建议,请合并内容到一项或仅保留一项后再确认写入`
}
touched.add(key)
}
}
}
return ''
}
export function reviewFieldIssue(item: FollowupReviewItem, fields: FollowupFields): string {
if (!item.selected) return ''
for (const key of Object.keys(item.values)) {
+80 -14
View File
@@ -671,9 +671,14 @@
<el-empty v-else description="请先保存诊单后查看" />
</el-tab-pane>
<el-tab-pane v-if="followupCapabilities?.enabled && formData.id" label="回访录音" name="followupAudio" lazy>
<el-tab-pane v-if="formData.id && hasFollowupAudioPermission" label="回访录音" name="followupAudio" lazy>
<el-alert v-if="followupCapabilitiesLoading" title="正在检查回访录音状态…" type="info" :closable="false" show-icon />
<div v-else-if="followupCapabilitiesError" role="alert">
<el-alert :title="followupCapabilitiesError" type="error" :closable="false" show-icon />
<el-button class="mt-3" @click="loadFollowupCapabilities">重新加载</el-button>
</div>
<FollowupAudioPanel
v-if="visible && formData.id && followupCapabilities"
v-else-if="visible && followupCapabilities?.enabled && followupCapabilitiesDiagnosisId === Number(formData.id)"
:key="Number(formData.id)"
ref="followupAudioRef"
:diagnosis-id="Number(formData.id)"
@@ -684,6 +689,13 @@
:before-apply="canApplyFollowup"
@applied="handleFollowupApplied"
/>
<el-alert
v-else
:title="followupCapabilities?.test_scope_allowed === false ? '当前诊单未开放回访录音' : '当前未启用回访录音,请联系管理员确认'"
type="info"
:closable="false"
show-icon
/>
</el-tab-pane>
<!-- 病历记录标签页(开方后自动显示) -->
@@ -732,6 +744,20 @@
<el-empty v-else description="请先保存诊单后再查看视频录制回放记录" />
</el-tab-pane>
<el-tab-pane
v-if="hasCallTranscriptPermission"
label="面诊文字对话"
name="callTranscript"
:disabled="!formData.id"
lazy
>
<consultation-transcript-panel
v-if="visible && activeTab === 'callTranscript' && formData.id"
:key="Number(formData.id)"
:diagnosis-id="Number(formData.id)"
/>
<el-empty v-else-if="!formData.id" description="请先保存诊单后再查看面诊文字对话" />
</el-tab-pane>
<el-tab-pane
v-if="hasPermission(['tcm.diagnosis/chat'])"
label="聊天记录"
name="chat"
@@ -815,6 +841,7 @@ import FollowupAudioPanel from './components/FollowupAudioPanel.vue'
import { followupAudioCapabilities, type FollowupCapabilities } from '@/api/followupAudio'
import CaseRecordList from './components/CaseRecordList.vue'
import CallRecordPanel from './components/CallRecordPanel.vue'
import ConsultationTranscriptPanel from './components/ConsultationTranscriptPanel.vue'
import ImChatRecordPanel from './components/ImChatRecordPanel.vue'
import AssignLogPanel from './components/AssignLogPanel.vue'
import AppointmentRecordPanel from './components/AppointmentRecordPanel.vue'
@@ -833,6 +860,9 @@ const prescriptionRef = ref()
const dailyMatrixRef = ref<{ refresh?: () => Promise<void> | void } | null>(null)
const followupAudioRef = ref<{ confirmLeave: () => Promise<boolean> } | null>(null)
const followupCapabilities = ref<FollowupCapabilities | null>(null)
const followupCapabilitiesLoading = ref(false)
const followupCapabilitiesError = ref('')
const followupCapabilitiesDiagnosisId = ref<number | null>(null)
const basicSnapshot = ref('')
let diagnosisGeneration = 0
let capabilitiesRequest: AbortController | undefined
@@ -847,6 +877,8 @@ const submitting = ref(false)
/** 拥有后手机号可正常编辑,失焦不再强制脱敏 */
const hasPhonePlainPermission = computed(() => hasPermission(['tcm.diagnosis/phonePlain']))
const hasDailyRecordPermission = computed(() => hasPermission(['tcm.diagnosis/dailyRecord']))
const hasCallTranscriptPermission = computed(() => hasPermission(['tcm.diagnosis/huifang']) || hasPermission(['tcm.diagnosis/getCallRecords']))
const hasFollowupAudioPermission = computed(() => hasPermission(['tcm.diagnosis/followupAudio']))
const patientBasicLocked = ref(false)
const canEditPatientBasicFromApi = ref(true)
const latestPrescriptionOrder = ref<{
@@ -914,12 +946,15 @@ watch(() => activeTab.value, async (tab) => {
}
})
watch([visible, activeTab], () => {
watch([visible, activeTab, hasCallTranscriptPermission], () => {
if (!visible.value) return
if (activeTab.value === 'chat' && !hasPermission(['tcm.diagnosis/chat'])) {
activeTab.value = 'basic'
}
if (activeTab.value === 'visit' && !hasPermission(['tcm.diagnosis/huifang'])) {
activeTab.value = 'basic'
}
if (activeTab.value === 'callTranscript' && !hasCallTranscriptPermission.value) {
activeTab.value = 'basic'
}
if (
@@ -1021,18 +1056,50 @@ async function handleFollowupApplied(diagnosisId: number) {
if (generation === diagnosisGeneration) feedback.msgWarning('录音已采纳,但病历或日常记录刷新失败,请手动刷新查看')
}
}
watch([visible, () => formData.value.id], async ([isVisible, id]) => {
function resetFollowupCapabilities() {
capabilitiesRequest?.abort()
capabilitiesRequest = undefined
followupCapabilities.value = null
if (!isVisible || !id) return
followupCapabilitiesDiagnosisId.value = null
followupCapabilitiesLoading.value = false
followupCapabilitiesError.value = ''
}
async function loadFollowupCapabilities(): Promise<void> {
// A rapid second click must not create another request for the same context.
if (followupCapabilitiesLoading.value) return
resetFollowupCapabilities()
const id = Number(formData.value.id)
if (!visible.value || !id || !hasFollowupAudioPermission.value) return
const generation = diagnosisGeneration
const request = new AbortController()
capabilitiesRequest = request
followupCapabilitiesLoading.value = true
const isCurrent = () => capabilitiesRequest === request && !request.signal.aborted
&& generation === diagnosisGeneration && visible.value && Number(formData.value.id) === id
try {
const result = await followupAudioCapabilities(Number(id), request.signal)
if (!request.signal.aborted && visible.value && String(formData.value.id) === String(id)) followupCapabilities.value = result
} catch { /* Fail closed: an unavailable capability endpoint must not expose this feature. */ }
})
onBeforeUnmount(() => { diagnosisGeneration++; capabilitiesRequest?.abort() })
const result = await followupAudioCapabilities(id, request.signal)
if (!isCurrent()) return
if (typeof result?.enabled !== 'boolean') throw new Error('Invalid capability response')
followupCapabilities.value = result
followupCapabilitiesDiagnosisId.value = id
} catch {
if (!isCurrent()) return
// No endpoint failure (including permission denial) may mount the panel.
followupCapabilitiesError.value = '回访录音状态加载失败,请重新加载;若仍失败,请联系管理员检查权限或服务状态'
} finally {
if (isCurrent()) {
followupCapabilitiesLoading.value = false
capabilitiesRequest = undefined
}
}
}
watch([visible, () => formData.value.id, hasFollowupAudioPermission], () => {
// Invalidate synchronously on patient switches and permission changes.
if (!hasFollowupAudioPermission.value && activeTab.value === 'followupAudio') activeTab.value = 'basic'
resetFollowupCapabilities()
void loadFollowupCapabilities()
}, { flush: 'sync' })
onBeforeUnmount(() => { diagnosisGeneration++; resetFollowupCapabilities() })
/** 就诊卡创建来源(与 zyt_tcm_diagnosis.create_source 一致) */
const createSourceOptions = [
@@ -1360,7 +1427,7 @@ const open = async (type: string, id?: number) => {
const generation = ++diagnosisGeneration
submitting.value = false
basicSnapshot.value = ''
followupCapabilities.value = null
resetFollowupCapabilities()
formData.value.id = ''
viewOnly.value = false
mode.value = type
@@ -1390,7 +1457,7 @@ const openViewOnly = async (id: number) => {
const generation = ++diagnosisGeneration
submitting.value = false
basicSnapshot.value = ''
followupCapabilities.value = null
resetFollowupCapabilities()
formData.value.id = ''
viewOnly.value = true
mode.value = 'edit'
@@ -1490,8 +1557,7 @@ const handleOpenPrescription = () => {
const handleClose = async () => {
if (followupAudioRef.value && !await followupAudioRef.value.confirmLeave()) return
diagnosisGeneration++
capabilitiesRequest?.abort()
followupCapabilities.value = null
resetFollowupCapabilities()
basicSnapshot.value = ''
formRef.value?.resetFields()
formData.value = {
+34 -2
View File
@@ -26,15 +26,19 @@ const render = moduleFrom(template.code).render
const passthrough = { setup: (_, { slots }) => () => vue.h('div', [slots.default?.(), slots.headerToolbar?.()]) }
const picker = text => ({ setup: () => () => vue.h('button', text) })
function chat(policy = {}) {
function chat(policy = {}, migrationBlocked = vue.ref(false)) {
const requests = [], warnings = [], sdkCalls = []
const guard = moduleFrom(read('utils/appointment-call-guard.ts'))
const server = Object.fromEntries(['calls', 'call', 'groupCall'].map(name => [name, async params => { sdkCalls.push({ name, params }) }]))
const server = Object.fromEntries(['calls', 'call', 'groupCall', 'accept'].map(name => [name, async params => { sdkCalls.push({ name, params }) }]))
const api = { getCallSignature: async params => { requests.push(params); return policy } }
const result = moduleFrom(script.content, name => {
if (name === 'vue') return { ...vue, onMounted() {}, onUnmounted() {} }
if (name === '@/utils/appointment-type') return types
if (name === '@/utils/appointment-call-guard') return guard
if (name === '@/hooks/useDoctorWebConsultation') return {
useDoctorWebConsultation: () => ({ webConsultationBlocked: migrationBlocked, webConsultationMessage: vue.ref('网页端面诊已停用,请医生使用桌面应用进行面诊。'), ensureWebConsultationAllowed: () => !migrationBlocked.value })
}
if (name === '@/utils/doctor-web-consultation') return moduleFrom(read('utils/doctor-web-consultation.ts'))
if (name === '@/utils/im-chat-archive-trigger') return moduleFrom(read('utils/im-chat-archive-trigger.ts'))
if (name === '@/api/tcm') return api
if (name === '@/utils/feedback') return { default: { msgWarning: text => warnings.push(text) } }
@@ -144,3 +148,31 @@ test('singleton call guard switches to current chat and cancels a pending old co
releaseNew()
await assert.rejects(guard.checkAppointmentOutgoingCall({ type: 2 }), /先打开/)
})
test('a cached video session stops every outgoing SDK path and incoming accept after migration', async () => {
const blocked = vue.ref(false)
const { state, server, sdkCalls, requests } = chat(policy('video'), blocked)
state.installTUICallKitRoomHooks()
assert.equal(state.canVideoCall.value, true)
blocked.value = true
assert.equal(state.canVideoCall.value, false)
assert.equal(state.canAudioCall.value, false)
for (const method of ['call', 'calls', 'groupCall', 'accept']) {
await assert.rejects(server[method]({ type: 2 }), /桌面应用/)
}
await state.startGroupVideoCall()
assert.deepEqual(sdkCalls, [])
assert.deepEqual(requests, [])
})
test('a signature request spanning the deadline never reaches the calling SDK', async () => {
const blocked = vue.ref(false)
const { state, server, sdkCalls, api } = chat(policy('video'), blocked)
state.installTUICallKitRoomHooks()
api.getCallSignature = async () => {
blocked.value = true
return policy('video')
}
await assert.rejects(server.calls({ type: 2 }), /桌面应用/)
assert.deepEqual(sdkCalls, [])
})
@@ -0,0 +1,214 @@
const assert = require('node:assert/strict')
const fs = require('node:fs')
const path = require('node:path')
const test = require('node:test')
const ts = require('typescript')
const vue = require('vue')
const { parse, compileScript, compileTemplate } = require('@vue/compiler-sfc')
const { renderToString } = require('@vue/server-renderer')
const read = name => fs.readFileSync(path.join(__dirname, '../src', name), 'utf8')
function moduleFrom(source, dependencies = require, globals = {}) {
const code = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText
const module = { exports: {} }
new Function('require', 'module', 'exports', ...Object.keys(globals), code)(dependencies, module, module.exports, ...Object.values(globals))
return module.exports
}
const util = moduleFrom(read('utils/consultation-transcripts.ts'))
const row = (id, diagnosis = 101, text = `医生:记录${id}的问题\n患者:记录${id}的回答`) => ({
id, diagnosis_id: diagnosis, call_type: 2, status: 2, start_time: 1792444800,
start_time_text: '2026-10-20 09:20:00', end_time_text: '2026-10-20 09:30:00',
duration_text: '10分钟', transcript_text: text, transcription_status: 'completed', transcription_segment_count: 2
})
const drain = () => new Promise(resolve => setImmediate(resolve))
test('each call keeps its own transcript even when multiple visits have the same date', () => {
const rows = util.normalizeConsultationRecords([row(10), row(11), row(12, 202, '串诊单文字'), row(10), null, { id: 0 }], 101)
assert.deepEqual(rows.map(item => item.id), [11, 10])
assert.equal(rows[0].transcript_text, row(11).transcript_text)
assert.equal(rows[1].transcript_text, row(10).transcript_text)
assert.throws(() => util.normalizeConsultationRecords({ lists: [] }, 101), /格式异常/)
const legacy = util.normalizeConsultationRecords([{ id: '13', transcript_text: '医生:你好\r\n患者:你好' }], 101)[0]
assert.equal(legacy.diagnosis_id, 101)
assert.equal(legacy.transcript_text, '医生:你好\n患者:你好')
})
test('running, partial and failed calls retain their saved words without pretending they are complete', () => {
for (const [status, label] of [['running', '录音转写中'], ['partial', '文字部分保存'], ['failed', '文字生成失败']]) {
const record = { ...row(1), transcription_status: status }
assert.equal(util.consultationTranscriptStatus(record).label, label)
assert.equal(util.consultationTranscriptText(record), row(1).transcript_text)
}
assert.match(util.consultationTranscriptEmptyText({ ...row(1), transcription_status: 'running', transcript_text: '' }), /正在转写/)
assert.match(util.consultationTranscriptEmptyText({ status: 3 }), /未接听/)
assert.match(util.consultationTranscriptEmptyText({ status: 4 }), /已取消/)
assert.equal(util.consultationTranscriptStatus({ transcript_text: '历史已保存文字' }).label, '文字已保存')
})
function hookFixture(initial = 101) {
const id = vue.ref(initial), requests = [], cleanup = []
const hook = moduleFrom(read('hooks/useConsultationTranscripts.ts'), name => {
if (name === 'vue') return { ...vue, onBeforeUnmount: fn => cleanup.push(fn) }
if (name === '@/api/tcm') return { getConsultationTranscripts: (params, signal) => new Promise((resolve, reject) => requests.push({ params, signal, resolve, reject })) }
if (name === '@/utils/consultation-transcripts') return util
throw new Error(name)
})
const scope = vue.effectScope()
const state = scope.run(() => hook.useConsultationTranscripts(() => id.value))
return { id, requests, state, dispose() { cleanup.forEach(fn => fn()); scope.stop() } }
}
test('changing diagnosis clears the old words immediately and ignores late responses and failures', async () => {
const f = hookFixture()
assert.deepEqual(f.requests[0].params, { diagnosis_id: 101 })
f.id.value = 202
assert.equal(f.requests[0].signal.aborted, true)
assert.deepEqual(f.state.records.value, [])
f.requests[1].resolve([row(20, 202), row(99, 101, '不属于该诊单')])
await drain()
assert.deepEqual(f.state.records.value.map(item => item.id), [20])
f.requests[0].reject(new Error('旧诊单请求失败'))
await drain()
assert.deepEqual(f.state.records.value.map(item => item.id), [20])
assert.equal(f.state.error.value, '')
f.id.value = 303
assert.deepEqual(f.state.records.value, [])
f.dispose()
assert.equal(f.requests[2].signal.aborted, true)
f.requests[2].resolve([row(30, 303)])
await drain()
assert.deepEqual(f.state.records.value, [])
})
test('manual refresh preserves current records on failure and recovers on retry without writes', async () => {
const f = hookFixture()
f.requests[0].resolve([row(10)])
await drain()
const failed = f.state.refresh()
f.requests[1].reject(new Error('网络连接失败'))
await failed
assert.equal(f.state.records.value[0].id, 10)
assert.equal(f.state.error.value, '网络连接失败')
assert.equal(f.state.loading.value, false)
const retried = f.state.refresh()
f.requests[2].resolve([row(11)])
await retried
assert.equal(f.state.error.value, '')
assert.equal(f.state.records.value[0].id, 11)
f.id.value = 0
assert.equal(f.requests.length, 3)
assert.deepEqual(f.state.records.value, [])
f.dispose()
})
const filename = 'views/tcm/diagnosis/components/ConsultationTranscriptPanel.vue'
const { descriptor, errors } = parse(read(filename), { filename })
assert.deepEqual(errors, [])
const script = compileScript(descriptor, { id: 'consultation-transcript-panel' })
const template = compileTemplate({ source: descriptor.template.content, filename, id: 'consultation-transcript-panel', compilerOptions: { bindingMetadata: script.bindings } })
assert.deepEqual(template.errors, [])
const render = moduleFrom(template.code).render
function panelFixture(records, extra = {}) {
const props = vue.reactive({ diagnosisId: 101 })
const data = { records: vue.ref(records), loading: vue.ref(false), error: vue.ref(''), refresh() {}, ...extra }
const copied = [], notices = []
const scope = vue.effectScope()
const component = moduleFrom(script.content, name => {
if (name === 'vue') return vue
if (name === '@/hooks/useConsultationTranscripts') return { useConsultationTranscripts: () => data }
if (name === '@/utils/consultation-transcripts') return util
if (name === '@/utils/feedback') return { default: { msgWarning: text => notices.push(text), msgSuccess: text => notices.push(text) } }
if (name === '@element-plus/icons-vue') return { Refresh: { render: () => vue.h('svg') }, Search: {} }
throw new Error(name)
}, { navigator: { clipboard: { writeText: async text => { copied.push(text) } } } })
const state = scope.run(() => component.default.setup(props, { expose() {} }))
async function html() {
const app = vue.createSSRApp({ render: () => render({}, [], props, vue.proxyRefs(state)) })
app.directive('loading', { getSSRProps: () => ({}) })
for (const name of ['el-button', 'el-icon', 'el-pagination']) app.component(name, { setup: (_, { slots }) => () => vue.h('span', slots.default?.()) })
app.component('el-tag', { props: ['type'], setup: (props, { slots }) => () => vue.h('span', { 'data-type': props.type }, slots.default?.()) })
app.component('el-empty', { props: ['description'], setup: props => () => vue.h('p', { class: 'empty-description' }, props.description) })
app.component('el-alert', { props: ['title'], setup: props => () => vue.h('p', { role: 'alert' }, props.title) })
app.component('el-input', { setup: () => () => vue.h('input') })
return renderToString(app)
}
return { props, state, data, copied, notices, html, dispose: () => scope.stop() }
}
test('the real panel selects one call, copies only its complete text, and escapes transcript HTML', async () => {
const f = panelFixture([row(12, 101, ''), row(11, 101, '医生:<img src=x onerror=alert(1)>\n患者:本次回答'), row(10), row(99, 202, '串诊单文字')])
assert.equal(f.state.selectedId.value, 11)
let html = await f.html()
assert.match(html, /&lt;img src=x onerror=alert\(1\)&gt;/)
assert.doesNotMatch(html, /<img src=x|串诊单文字/)
assert.doesNotMatch(html.match(/<pre[^>]*>([\s\S]*?)<\/pre>/)[1], /记录10/)
await f.state.copyTranscript()
assert.deepEqual(f.copied, ['医生:<img src=x onerror=alert(1)>\n患者:本次回答'])
f.state.selectedId.value = 10
assert.equal(f.state.selectedText.value, row(10).transcript_text)
f.data.records.value = [row(13), row(11), row(10)]
assert.equal(f.state.selectedId.value, 10)
f.state.search.value = '记录13'
assert.equal(f.state.selectedId.value, 13)
assert.equal(f.state.filteredRecords.value.length, 1)
f.props.diagnosisId = 202
assert.equal(f.state.selectedText.value, '')
assert.doesNotMatch(await f.html(), /记录13的问题|本次回答/)
f.dispose()
})
test('empty, failed and partial transcription states remain explicit in the rendered panel', async () => {
for (const status of ['running', 'partial', 'failed']) {
const f = panelFixture([{ ...row(1), transcription_status: status }])
const html = await f.html()
assert.match(html, /已保存|刷新查看最新/)
assert.match(html, /记录1的问题/)
f.dispose()
}
const missing = panelFixture([row(1, 101, '')])
assert.match(await missing.html(), /本次面诊暂无已保存的文字对话/)
missing.dispose()
const none = panelFixture([])
assert.match(await none.html(), /该诊单暂无面诊通话记录/)
none.dispose()
const failed = panelFixture([], { error: vue.ref('无权访问该诊单') })
assert.match(await failed.html(), /无权访问该诊单/)
assert.doesNotMatch(await failed.html(), /该诊单暂无面诊通话记录/)
failed.dispose()
})
test('the new tab is permission gated, lazy and absent when the drawer is closed', async () => {
const { descriptor } = parse(read('views/tcm/diagnosis/edit.vue'))
const editScript = compileScript(descriptor, { id: 'diagnosis-edit-transcript' })
const pane = descriptor.template.content.match(/<el-tab-pane\s+v-if="hasCallTranscriptPermission"[\s\S]*?<\/el-tab-pane>/)[0]
const compiled = compileTemplate({ source: pane, filename: 'edit-transcript-tab.vue', id: 'edit-transcript', compilerOptions: { bindingMetadata: editScript.bindings } })
assert.deepEqual(compiled.errors, [])
const renderPane = moduleFrom(compiled.code).render
async function html(allowed, active, visible, id) {
const state = { hasCallTranscriptPermission: allowed, activeTab: active, visible, formData: { id }, ConsultationTranscriptPanel: { props: ['diagnosisId'], setup: props => () => vue.h('div', { 'data-diagnosis': props.diagnosisId }, '真实转写面板入口') } }
const app = vue.createSSRApp({ render: () => renderPane({}, [], {}, state) })
app.component('el-tab-pane', { props: ['disabled', 'label'], setup: (props, { slots }) => () => vue.h('section', { 'data-disabled': String(props.disabled) }, [props.label, slots.default?.()]) })
app.component('el-empty', { props: ['description'], setup: props => () => vue.h('p', props.description) })
return renderToString(app)
}
assert.doesNotMatch(await html(false, 'callTranscript', true, 101), /面诊文字对话/)
assert.doesNotMatch(await html(true, 'basic', true, 101), /真实转写面板入口/)
assert.doesNotMatch(await html(true, 'callTranscript', false, 101), /真实转写面板入口/)
assert.match(await html(true, 'callTranscript', true, 101), /data-diagnosis="101"/)
assert.match(await html(true, 'callTranscript', true, ''), /data-disabled="true"/)
})
test('the read helper sends the exact diagnosis and abort signal without canceling replay requests', async () => {
let request
const api = moduleFrom(read('api/tcm.ts'), name => {
if (name === '@/utils/request') return { default: { get: (...args) => { request = args; return Promise.resolve([]) } } }
throw new Error(name)
})
const controller = new AbortController()
await api.getConsultationTranscripts({ diagnosis_id: 101 }, controller.signal)
assert.equal(request[0].url, '/tcm.diagnosis/getCallRecords')
assert.deepEqual(request[0].params, { diagnosis_id: 101 })
assert.equal(request[0].signal, controller.signal)
assert.equal(request[1].ignoreCancelToken, true)
})
@@ -0,0 +1,419 @@
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)
})
@@ -0,0 +1,47 @@
const assert = require('node:assert/strict')
const fs = require('node:fs')
const path = require('node:path')
const test = require('node:test')
const ts = require('typescript')
const vue = require('vue')
const { parse, compileScript, compileTemplate } = require('@vue/compiler-sfc')
const file = process.env.FOLLOWUP_EXERCISE_MATRIX_SOURCE || path.resolve(__dirname, '../src/views/tcm/diagnosis/components/DailyMatrix.vue')
const source = fs.readFileSync(file, 'utf8')
function setup() {
const descriptor = parse(source, {filename:file}).descriptor
const compiled = compileScript(descriptor, {id:'exercise-null'})
const output = ts.transpileModule(compiled.content, {compilerOptions:{target:ts.ScriptTarget.ES2022,module:ts.ModuleKind.CommonJS}}).outputText
const calls=[]; const warnings=[]; const module={exports:{}}
const api={diagnosisTrackingWindow:async()=>({}),diagnosisTrackingNotes:async()=>[],exerciseRecordEdit:async p=>calls.push(p),exerciseRecordAdd:async p=>calls.push(p)}
new Function('require','module','exports',output)(name=>name==='vue'?{...vue,onMounted(){},onUnmounted(){}}:name==='@/utils/perm'?{hasPermission:()=>true}:name==='@/api/tcm'?api:name==='@/utils/feedback'?{default:{msgWarning:m=>warnings.push(m)}}:{default:{}},module,module.exports)
const scope=vue.effectScope()
const matrix=scope.run(()=>module.exports.default.setup({diagnosisId:1,patientId:101,readOnly:false},{expose(){}}))
return {matrix,calls,warnings,dispose:()=>scope.stop()}
}
test('real DailyMatrix edit and submit preserve null duration/intensity',async()=>{
const f=setup(); f.matrix.openExerciseRecord({id:1,record_date:'2026-09-29',exercise_type:'散步',duration:null,intensity:null},'2026-09-29')
assert.equal(f.matrix.exerciseForm.value.duration,null);assert.equal(f.matrix.exerciseForm.value.intensity,null)
f.matrix.exerciseForm.value.note='仅改备注';await f.matrix.submitExercise()
assert.equal(f.calls.length,1);assert.equal(f.calls[0].duration,null);assert.equal(f.calls[0].intensity,null);assert.deepEqual(f.warnings,[]);f.dispose()
})
test('missing keys in existing row do not inherit manual-entry defaults',()=>{
const f=setup();f.matrix.openExerciseRecord({id:2,exercise_type:'散步'},'2026-09-29')
assert.equal(f.matrix.exerciseForm.value.duration,null);assert.equal(f.matrix.exerciseForm.value.intensity,null);f.dispose()
})
test('explicit known and zero values remain unchanged; cleared duration submits null',async()=>{
const f=setup();f.matrix.openExerciseRecord({id:2,exercise_type:'散步',duration:0,intensity:1},'2026-09-29')
await f.matrix.submitExercise();assert.equal(f.calls[0].duration,0);assert.equal(f.calls[0].intensity,1)
f.matrix.exerciseForm.value.duration=undefined;await f.matrix.submitExercise();assert.equal(f.calls[1].duration,null);f.dispose()
})
test('unknown intensity option maps to null without conflating known low intensity',()=>{
const f=setup();f.matrix.openExerciseRecord({id:1,exercise_type:'散步',duration:null,intensity:null},'2026-09-29')
assert.equal(f.matrix.exerciseIntensity.value,'');f.matrix.exerciseIntensity.value=1;assert.equal(f.matrix.exerciseForm.value.intensity,1)
f.matrix.exerciseIntensity.value='';assert.equal(f.matrix.exerciseForm.value.intensity,null)
assert.equal(f.matrix.intensityLabel(null),'未记录');assert.equal(f.matrix.intensityLabel(1),'低强度');f.dispose()
})
test('matrix compiles and detail rendering explicitly distinguishes unknown from zero',()=>{
const descriptor=parse(source,{filename:file}).descriptor;const script=compileScript(descriptor,{id:'exercise-compile'})
const render=compileTemplate({source:descriptor.template.content,filename:file,id:'exercise-compile',compilerOptions:{bindingMetadata:script.bindings}})
assert.deepEqual(render.errors,[]);assert.ok(/<el-option label="未记录" value=""/.test(source), "explicit unknown option exists")
assert.ok(/record\.duration == null \? '未记录'/.test(source), 'null duration renders unknown')
})
+333 -2
View File
@@ -38,6 +38,8 @@ function setupPanel(overrides = {}, propsPatch = {}, options = {}) {
followupAudioUploadChunk: async (id, index, blob) => { calls.push(['chunk', id, index, blob.size]); return { index, received: true } },
followupAudioUploadComplete: async id => { calls.push(['complete', id]); return { upload_id: id, duration_seconds: 10, sha256: 'test' } },
followupAudioCreate: async payload => { calls.push(['create', payload]); return { task_id: 2, status: 'queued' } },
followupAudioReextract: async payload => { calls.push(['reextract', payload]); return task(payload.id, { status: 'queued', version: payload.version + 1, items: [], extraction_revision: 1, extraction_channel_roles: payload.channel_roles }) },
followupAudioDelete: async payload => { calls.push(['delete', payload]); return { id: payload.id, status: 'deleted', version: payload.version + 1 } },
followupAudioRetry: async id => { calls.push(['retry', id]); return { id, status: 'queued' } },
...overrides
}
@@ -267,7 +269,7 @@ test('authenticated audio object URLs revoked on hide and stale blobs never crea
test('editor capability gate, dirty guard and successful apply hook wire diagnosis plus daily refresh', () => {
const source = fs.readFileSync(path.join(componentDir, '../edit.vue'), 'utf8')
assert.match(source, /v-if="followupCapabilities\?\.enabled && formData.id"/)
assert.match(source, /<el-tab-pane v-if="formData.id && hasFollowupAudioPermission" label="回访录音"/)
assert.match(source, /:before-leave="beforeTabLeave"/)
assert.match(source, /next === 'followupAudio' && basicDirty.value/)
assert.match(source, /await loadDiagnosisDetailIntoForm\(diagnosisId, true\)/)
@@ -1409,7 +1411,7 @@ test('actual patient editor outside preview allowlist still opens and edits its
await editor.handleSubmit()
assert.equal(edits.length, 1, 'ordinary diagnosis mock API remains usable; no real patient write')
assert.equal(edits[0].remark, '合成普通表单编辑')
assert.match(descriptor.template.content, /v-if="followupCapabilities\?\.enabled && formData.id"/)
assert.match(descriptor.template.content, /<el-tab-pane v-if="formData.id && hasFollowupAudioPermission" label="回访录音"/)
} finally { scope.stop() }
})
@@ -1793,3 +1795,332 @@ test('detail fetch begun before an edit preserves that edit when the new snapsho
assert.equal(f.calls.filter(x => x[0] === 'save').length, 0)
f.dispose()
})
test('delete requires actor-aware capability and blocks applied/running/unknown tasks', async () => {
const f=setupPanel();await settle()
for (const row of [task(), task(1,{can_delete:false}),task(1,{can_delete:true,status:'applied'}),task(1,{can_delete:true,status:'running'}),task(1,{can_delete:true,status:'needs_reconciliation'})]) await f.panel.deleteRecording(row)
assert.equal(f.calls.filter(c=>c[0]==='delete').length,0)
f.props.viewOnly=true;await f.panel.deleteRecording(task(1,{can_delete:true}));assert.equal(f.calls.filter(c=>c[0]==='delete').length,0);f.dispose()
})
test('confirmed deletion sends optimistic version once, clears selected editor and never applies', async () => {
let removed=false;const current=task(1,{can_delete:true})
const f=setupPanel({followupAudioDetail:async()=>current,followupAudioLists:async()=>({items:removed?[]:[current]}),followupAudioDelete:async p=>{f.calls.push(['delete',p]);removed=true;return {id:p.id,status:'deleted',version:p.version+1}}})
await settle();await f.panel.openTask(1);await f.panel.deleteRecording(current)
assert.deepEqual(f.calls.find(c=>c[0]==='delete')[1],{id:1,version:1});assert.equal(f.panel.selectedId.value,0);assert.equal(f.panel.detail.value,null);assert.deepEqual(f.panel.tasks.value,[]);assert.deepEqual(f.panel.reviewItems.value,[])
assert.equal(f.calls.some(c=>c[0]==='apply'),false);assert.equal(f.panel.mutation.value,'');f.dispose()
})
test('delete cancellation keeps recording and drafts, patient switch before confirm sends nothing', async () => {
const f=setupPanel({}, {}, {confirm:async()=>{throw new Error('cancel')}});await settle();await f.panel.openTask(1);await f.panel.deleteRecording(task(1,{can_delete:true}));assert.equal(f.panel.selectedId.value,1);assert.equal(f.calls.some(c=>c[0]==='delete'),false);assert.equal(f.panel.mutation.value,'');f.dispose()
const answer=deferred();const g=setupPanel({}, {}, {confirm:()=>answer.promise});await settle();const pending=g.panel.deleteRecording(task(1,{can_delete:true}));g.props.diagnosisId=20;await settle();answer.resolve();await pending;assert.equal(g.calls.some(c=>c[0]==='delete'),false);g.dispose()
})
test('late delete result cannot clear another patient and errors preserve current recording', async () => {
const response=deferred();const f=setupPanel({followupAudioDelete:async p=>{f.calls.push(['delete',p]);return response.promise}});await settle();await f.panel.openTask(1)
const deleting=f.panel.deleteRecording(task(1,{can_delete:true}));await settle();const duplicate=f.panel.deleteRecording(task(1,{can_delete:true}));await duplicate;assert.equal(f.calls.filter(c=>c[0]==='delete').length,1)
f.props.diagnosisId=20;await settle();await f.panel.openTask(2);response.resolve({id:1,status:'deleted',version:2});await deleting;assert.equal(f.panel.selectedId.value,2);assert.equal(f.panel.detail.value.id,2);f.dispose()
const g=setupPanel({followupAudioDelete:async()=>{throw new apiModule.FollowupAudioError('版本已变化')}});await settle();await g.panel.openTask(1);await g.panel.deleteRecording(task(1,{can_delete:true}));assert.equal(g.panel.selectedId.value,1);assert.match(g.panel.errorMessage.value,/版本已变化/);g.dispose()
})
test('delete API has no automatic retry and empty results expose uncertainty reasons without tab switching', async () => {
const requests=[];const api=loadTs(path.join(root,'src/api/followupAudio.ts'),()=>({default:{post:async(config,options)=>{requests.push({config,options});return {code:1,data:{id:1,status:'deleted',version:2}}}}}))
await api.followupAudioDelete({id:1,version:1});assert.equal(requests[0].config.url,'/tcm.followupAudio/delete');assert.equal(requests[0].options.isOpenRetry,false)
const source=fs.readFileSync(path.join(componentDir,'FollowupAudioReview.vue'),'utf8');assert.match(source,/\(group === 'pending' \|\| !items.length\) && uncertainties\?\.length/)
const panelSource=fs.readFileSync(path.join(componentDir,'FollowupAudioPanel.vue'),'utf8');assert.match(panelSource,/未生成可写入信息/);assert.match(panelSource,/不删除或回滚病例/)
})
test('remote deletion revalidates missing detail and releases cached audio/editor', async () => {
let deleted=false;const f=setupPanel({followupAudioLists:async()=>({items:deleted?[]:[task()]}),followupAudioDetail:async id=>{if(deleted)throw new apiModule.FollowupAudioError('FOLLOWUP_AUDIO_TASK_UNAVAILABLE');return task(id)}})
await settle();await f.panel.openTask(1);await f.panel.loadAudio();assert.equal(f.panel.audioUrl.value,'blob:private-0')
deleted=true;await f.panel.refresh();await settle()
assert.equal(f.panel.selectedId.value,0);assert.equal(f.panel.detail.value,null);assert.equal(f.panel.audioUrl.value,'');assert.deepEqual(f.revoked,['blob:private-0']);assert.deepEqual(f.panel.reviewItems.value,[]);assert.match(f.panel.errorMessage.value,/录音已删除/);f.dispose()
})
test('list pagination omission alone never discards current unsaved edits', async () => {
let omit=false;const f=setupPanel({followupAudioLists:async()=>({items:omit?[]:[task()]})});await settle();await f.panel.openTask(1)
f.panel.reviewItems.value[0].values.fasting_blood_sugar=6.9;omit=true;await f.panel.refresh()
assert.equal(f.panel.selectedId.value,1);assert.equal(f.panel.reviewItems.value[0].values.fasting_blood_sugar,6.9);assert.notEqual(f.panel.saveState.value,'conflict');f.dispose()
})
test('deleting another row resumes current task autosave without clearing its draft', async () => {
const f=setupPanel();await settle();await f.panel.openTask(1);f.panel.reviewItems.value[0].values.fasting_blood_sugar=6.9
await f.panel.deleteRecording(task(2,{can_delete:true}));assert.equal(f.panel.selectedId.value,1);assert.equal(f.panel.reviewItems.value[0].values.fasting_blood_sugar,6.9)
f.tick();await settle();assert.ok(f.calls.some(c=>c[0]==='save'&&c[1].id===1&&c[1].items[0].values.fasting_blood_sugar===6.9));f.dispose()
})
test('autosave denial for remotely deleted task clears local playback without another save', async () => {
let deleted=false;const f=setupPanel({followupAudioLists:async()=>({items:deleted?[]:[task()]}),followupAudioSaveDraft:async()=>{deleted=true;throw new apiModule.FollowupAudioError('FOLLOWUP_AUDIO_TASK_UNAVAILABLE')}})
await settle();await f.panel.openTask(1);await f.panel.loadAudio();f.panel.reviewItems.value[0].values.fasting_blood_sugar=6.9;await f.panel.saveDraft(true);await settle()
assert.equal(f.panel.selectedId.value,0);assert.equal(f.panel.audioUrl.value,'');assert.match(f.panel.errorMessage.value,/录音已删除/);f.dispose()
})
// Execute the real editor script and its actual tab template, with deferred network I/O.
function setupAudioEntry(permissions = ['*']) {
const userStore = vue.reactive({ perms: [...permissions], userInfo: { id: 1 } })
const permissionModule = loadTs(path.join(root, 'src/utils/perm.ts'), () => ({ default: () => userStore }))
const requests = [], warnings = [], hooks = {}, exposed = {}
const filename = path.join(componentDir, '../edit.vue')
const descriptor = parse(fs.readFileSync(filename, 'utf8'), { filename }).descriptor
const script = compileScript(descriptor, { id: 'entry-runtime' })
const panelComponent = { name: 'FollowupAudioPanel' }
const module = execute(script.content, name => {
if (name === 'vue') return { ...vue, onBeforeUnmount: callback => { hooks.unmount = callback } }
if (name === '@/api/tcm') return { tcmDiagnosisDetail: async ({ id }) => ({ id: String(id), patient_id: String(id + 100), phone: '', id_card: '', remark: '原始备注' }) }
if (name === '@/api/app') return { getDictData: async () => ({}) }
if (name === '@/api/followupAudio') return { followupAudioCapabilities: (id, signal) => { const pending = deferred(); requests.push({ id, signal, ...pending }); return pending.promise } }
if (name === '@/utils/feedback') return { default: { msgWarning: message => warnings.push(message) } }
if (name === '@/utils/perm') return permissionModule
if (name === '@/stores/modules/user') return { default: () => userStore }
if (name === '@/stores/modules/app') return { default: () => ({ getImageUrl: value => value }) }
if (name === 'element-plus') return { ElMessage: { warning() {} } }
if (name === '@element-plus/icons-vue' || name === '@/api/patient') return {}
if (name.endsWith('FollowupAudioPanel.vue')) return { default: panelComponent }
if (name.endsWith('.vue')) return { default: {} }
throw new Error(`Unexpected entry import: ${name}`)
})
const tab = descriptor.template.content.match(/<el-tab-pane[^>]+name="followupAudio"[\s\S]*?<\/el-tab-pane>/)[0]
const compiled = compileTemplate({ source: tab, filename, id: 'entry-tab', compilerOptions: { bindingMetadata: script.bindings } })
assert.deepEqual(compiled.errors, [])
const render = execute(compiled.code, () => ({ ...vue, resolveComponent: name => name })).render
const scope = vue.effectScope()
const editor = scope.run(() => module.default.setup({}, { expose: value => Object.assign(exposed, value), emit() {} }))
const dailyTab = descriptor.template.content.match(/<el-tab-pane\s+v-if="hasDailyRecordPermission"[\s\S]*?<\/el-tab-pane>/)[0]
const dailyCompiled = compileTemplate({ source: dailyTab, filename, id: 'daily-tab', compilerOptions: { bindingMetadata: script.bindings } })
assert.deepEqual(dailyCompiled.errors, [])
const renderDaily = execute(dailyCompiled.code, () => ({ ...vue, resolveComponent: name => name })).render
const nodes = (renderTab = render) => {
const collected = []
const visit = node => {
if (!node || typeof node !== 'object') return
if (Array.isArray(node)) { node.forEach(visit); return }
collected.push(node)
visit(node.children)
if (node.children?.default) visit(node.children.default())
}
visit(renderTab({}, [], {}, vue.proxyRefs(editor)))
return collected
}
return { editor, exposed, requests, warnings, nodes, userStore, hasDailyTab: () => nodes(renderDaily).some(node => node.type === 'el-tab-pane'), hasTab: () => nodes().some(node => node.type === 'el-tab-pane'), hasPanel: () => nodes().some(node => node.type === panelComponent), dispose: () => { hooks.unmount(); scope.stop() } }
}
test('saved diagnosis keeps audio entry during pending/error; manual retry recovers without losing dirty input', async () => {
const f = setupAudioEntry()
try {
await f.editor.open('edit', 10)
assert.equal(f.hasTab(), true)
assert.equal(f.hasPanel(), false)
assert.equal(f.editor.followupCapabilitiesLoading.value, true)
assert.ok(f.nodes().some(node => node.props?.title === '正在检查回访录音状态…'))
f.requests[0].reject(new Error('network offline')); await settle()
assert.equal(f.hasTab(), true)
assert.equal(f.hasPanel(), false)
assert.equal(f.editor.followupCapabilitiesLoading.value, false)
assert.match(f.editor.followupCapabilitiesError.value, /加载失败/)
assert.equal(f.requests.length, 1, 'no automatic retry')
f.editor.formData.value.remark = '保留未保存输入'
assert.equal(await f.editor.beforeTabLeave('followupAudio', 'basic'), false)
const retryButton = f.nodes().find(node => node.type === 'el-button')
const retry = retryButton.props.onClick()
const duplicate = f.editor.loadFollowupCapabilities()
assert.equal(f.requests.length, 2, 'rapid retries share the in-flight context')
assert.equal(f.editor.followupCapabilitiesError.value, '')
assert.equal(f.hasPanel(), false)
f.requests[1].resolve(caps()); await retry; await duplicate
assert.equal(f.hasTab(), true)
assert.equal(f.hasPanel(), true)
assert.equal(f.editor.formData.value.remark, '保留未保存输入')
assert.equal(f.editor.basicDirty.value, true)
assert.equal(f.editor.canApplyFollowup(), false)
assert.equal(await f.editor.beforeTabLeave('followupAudio', 'basic'), false)
} finally { f.dispose() }
})
test('disabled/scope-denied and permission-denied capability responses preserve entry without a panel', async () => {
for (const response of [{ ...caps(), enabled: false }, { ...caps(), enabled: false, test_scope_allowed: false }, new Error('403 permission denied'), null]) {
const f = setupAudioEntry()
try {
await f.editor.open('edit', 10)
if (response instanceof Error) f.requests[0].reject(response)
else f.requests[0].resolve(response)
await settle()
assert.equal(f.hasTab(), true)
assert.equal(f.hasPanel(), false)
assert.equal(f.editor.followupCapabilitiesLoading.value, false)
const title = f.nodes().find(node => node.type === 'el-alert').props.title
assert.match(title, response instanceof Error || response === null ? /加载失败/ : /未启用|未开放/)
assert.equal(f.requests.length, 1)
} finally { f.dispose() }
}
})
test('old capability success/error/finally cannot affect a new patient or same-ID reopened context', async () => {
for (const oldFails of [false, true]) for (const id of [10, 20]) {
const f = setupAudioEntry()
try {
await f.editor.open('edit', 10)
const old = f.requests[0]
const opening = f.editor.open('edit', id)
assert.equal(old.signal.aborted, true, 'open resets before awaiting dictionaries')
assert.equal(f.editor.followupCapabilities.value, null)
await opening
assert.equal(f.requests.length, 2)
if (oldFails) old.reject(new Error('late old error'))
else old.resolve(caps())
await settle()
assert.equal(f.editor.followupCapabilities.value, null)
assert.equal(f.editor.followupCapabilitiesError.value, '')
assert.equal(f.editor.followupCapabilitiesLoading.value, true, 'old finally cannot end new loading')
assert.equal(f.hasPanel(), false)
f.requests[1].resolve({ ...caps(), enabled: false }); await settle()
assert.equal(f.editor.followupCapabilitiesDiagnosisId.value, id)
assert.equal(f.editor.followupCapabilities.value.enabled, false)
assert.equal(f.hasPanel(), false)
} finally { f.dispose() }
}
})
test('successful capabilities are immediately invalidated on patient switch; late retry completion stays isolated', async () => {
const f = setupAudioEntry()
try {
await f.editor.open('edit', 10); f.requests[0].resolve(caps()); await settle()
assert.equal(f.hasPanel(), true)
f.editor.formData.value.id = '20'
assert.equal(f.hasPanel(), false)
assert.equal(f.editor.followupCapabilities.value, null)
f.requests[1].reject(new Error('second patient error')); await settle()
const retry = f.editor.loadFollowupCapabilities()
await f.editor.openViewOnly(30)
assert.equal(f.requests[2].signal.aborted, true)
f.requests[3].resolve(caps()); await settle()
f.requests[2].reject(new Error('old retry error')); await retry
assert.equal(f.hasPanel(), true)
assert.equal(f.editor.followupCapabilitiesDiagnosisId.value, 30)
assert.equal(f.editor.followupCapabilitiesError.value, '')
assert.equal(f.editor.viewOnly.value, true)
} finally { f.dispose() }
})
test('close and unmount abort pending capabilities and prevent any late state resurrection', async () => {
for (const unmount of [false, true]) for (const fails of [false, true]) {
const f = setupAudioEntry()
try {
await f.editor.open('edit', 10)
if (unmount) f.dispose()
else await f.editor.handleClose()
assert.equal(f.requests[0].signal.aborted, true)
if (fails) f.requests[0].reject(new Error('late close failure'))
else f.requests[0].resolve(caps())
await settle()
assert.equal(f.editor.followupCapabilities.value, null)
assert.equal(f.editor.followupCapabilitiesLoading.value, false)
assert.equal(f.editor.followupCapabilitiesError.value, '')
assert.equal(f.hasPanel(), false)
if (!unmount) assert.equal(f.hasTab(), false)
} finally { f.dispose() }
}
})
const roleConflictTask = (extra={}) => stereoTask({items:[], channel_roles:'left_service',extraction_channel_roles:'left_service',extraction_revision:0,can_reextract:true,reextract_block_reason:'',role_check:{conflict:true,suggested_roles:'right_service',message:'合成角色冲突',evidence:[{channel:1,start_ms:0,end_ms:15000,text:'我是测试医院的医疗助理'}]},...extra})
test('role correction requires explicit confirmation and submits versioned roles without uploading or applying',async()=>{
let current=roleConflictTask();const confirmations=[]
const f=setupPanel({followupAudioDetail:async()=>current,followupAudioLists:async()=>({items:[current]}),followupAudioReextract:async p=>{f.calls.push(['reextract',p]);current=roleConflictTask({status:'queued',version:2,extraction_revision:1,extraction_channel_roles:p.channel_roles,channel_roles:p.channel_roles,can_reextract:false,role_check:{conflict:false,suggested_roles:'unconfirmed',message:'',evidence:[]}});return current}}, {}, {confirm:async(message)=>{confirmations.push(message)}})
await settle();await f.panel.openTask(1);assert.equal(f.panel.reextractTarget.value,'right_service');await f.panel.reextractWithRoles()
assert.deepEqual(f.calls.find(c=>c[0]==='reextract')[1],{id:1,version:1,channel_roles:'right_service'});assert.match(confirmations[0],/右客服/);assert.match(confirmations[0],/不重复语音识别/)
assert.equal(f.panel.detail.value.status,'queued');assert.equal(f.panel.detail.value.extraction_revision,1);assert.equal(f.calls.some(c=>['apply','create','session','chunk'].includes(c[0])),false);f.dispose()
})
test('role proposal never mutates manual roles or sends re-extraction until confirmed',async()=>{
const f=setupPanel({followupAudioDetail:async()=>roleConflictTask()}, {}, {confirm:async()=>{throw new Error('cancel')}});await settle();await f.panel.openTask(1)
assert.equal(f.panel.savedChannelRoles.value,'left_service');assert.equal(f.panel.channelRoles.value,'left_service');assert.equal(f.calls.some(c=>c[0]==='reextract'),false)
await f.panel.reextractWithRoles();assert.equal(f.calls.some(c=>c[0]==='reextract'),false);assert.equal(f.panel.detail.value.status,'review');assert.equal(f.panel.mutation.value,'');f.dispose()
})
test('re-extraction blocks dirty, readonly, unavailable, same-role and processing contexts',async()=>{
const f=setupPanel({followupAudioDetail:async()=>roleConflictTask()});await settle();await f.panel.openTask(1)
f.panel.reviewRef.value={hasUnsavedChanges:()=>true};await f.panel.reextractWithRoles();assert.equal(f.calls.some(c=>c[0]==='reextract'),false)
f.panel.reviewRef.value=null;f.props.viewOnly=true;await f.panel.reextractWithRoles();f.props.viewOnly=false
for(const patch of [{can_reextract:false},{status:'running'},{status:'applied'},{role_check:{conflict:false,suggested_roles:'left_service',evidence:[],message:''}}]){f.panel.installDetail(roleConflictTask(patch),false);await f.panel.reextractWithRoles()}
assert.equal(f.calls.some(c=>c[0]==='reextract'),false);f.dispose()
})
test('re-extraction confirmation and late results are fenced across patient changes',async()=>{
const answer=deferred();const f=setupPanel({followupAudioDetail:async()=>roleConflictTask()}, {}, {confirm:()=>answer.promise});await settle();await f.panel.openTask(1)
const pending=f.panel.reextractWithRoles();f.props.diagnosisId=20;await settle();answer.resolve();await pending;assert.equal(f.calls.some(c=>c[0]==='reextract'),false);f.dispose()
const response=deferred();const g=setupPanel({followupAudioDetail:async id=>roleConflictTask({id}),followupAudioReextract:async p=>{g.calls.push(['reextract',p]);return response.promise}});await settle();await g.panel.openTask(1)
const work=g.panel.reextractWithRoles();await settle();await g.panel.reextractWithRoles();assert.equal(g.calls.filter(c=>c[0]==='reextract').length,1);g.props.diagnosisId=30;await settle();await g.panel.openTask(2);response.resolve(roleConflictTask({status:'queued',version:2}));await work;assert.equal(g.panel.selectedId.value,2);assert.equal(g.panel.detail.value.id,2);g.dispose()
})
test('explicitly corrected review roles take priority over the advisory suggestion',async()=>{
const f=setupPanel({followupAudioDetail:async()=>roleConflictTask({channel_roles:'right_service',role_check:{conflict:false,suggested_roles:'unconfirmed',message:'',evidence:[]}})});await settle();await f.panel.openTask(1);assert.equal(f.panel.reextractTarget.value,'right_service');f.dispose()
const calls=[];const api=loadTs(path.join(root,'src/api/followupAudio.ts'),()=>({default:{post:async(config,options)=>{calls.push({config,options});return {code:1,data:roleConflictTask({status:'queued'})}}}}));await api.followupAudioReextract({id:1,version:1,channel_roles:'right_service'});assert.equal(calls[0].config.url,'/tcm.followupAudio/reextract');assert.equal(calls[0].options.isOpenRetry,false)
})
test('duplicate diagnosis suggestions are blocked clearly without losing distinct daily measurements',()=>{
const fields={diagnosis:[{key:'symptoms',label:'症状',type:'text'},{key:'remark',label:'备注',type:'text'}]}
const a=item({id:'a',kind:'diagnosis',values:{symptoms:'口干'}}),b=item({id:'b',kind:'diagnosis',values:{symptoms:'睡眠中断'}})
assert.match(state.reviewBatchIssue([a,b],fields),/症状存在多条选中建议/)
assert.equal(state.reviewBatchIssue([a,{...b,selected:false}],fields),'')
assert.equal(state.reviewBatchIssue([item(),item({id:'another',record_time:'12:00'})],fields),'')
assert.equal(a.values.symptoms,'口干');assert.equal(b.values.symptoms,'睡眠中断')
})
test('grouped audio permission independently gates saved diagnosis entry and capabilities requests', async () => {
for (const permissions of [[], ['tcm.diagnosis/dailyRecord'], ['tcm.diagnosis/detail', 'tcm.diagnosis/edit'], ['tcm.diagnosis/followupaudio']]) {
const f = setupAudioEntry(permissions)
try {
await f.editor.open('edit', 10)
assert.equal(f.hasTab(), false)
assert.equal(f.hasPanel(), false)
assert.equal(f.hasDailyTab(), permissions.includes('tcm.diagnosis/dailyRecord'))
await f.editor.loadFollowupCapabilities()
assert.equal(f.requests.length, 0, 'denied entry makes no capabilities request, including direct reload')
assert.equal(f.editor.followupCapabilitiesLoading.value, false)
assert.equal(f.editor.followupCapabilitiesError.value, '')
} finally { f.dispose() }
}
for (const permissions of [['tcm.diagnosis/followupAudio'], ['tcm.diagnosis/followupAudio', 'tcm.diagnosis/dailyRecord'], ['*']]) {
const f = setupAudioEntry(permissions)
try {
await f.editor.open('add')
assert.equal(f.hasTab(), false, 'unsaved diagnoses have no audio entry even with permission')
assert.equal(f.requests.length, 0)
await f.editor.open('edit', 10)
assert.equal(f.hasTab(), true)
assert.equal(f.hasDailyTab(), permissions.includes('*') || permissions.includes('tcm.diagnosis/dailyRecord'))
assert.equal(f.requests.length, 1)
f.requests[0].reject(new Error('transient network failure')); await settle()
assert.equal(f.hasTab(), true, 'granted entry never depends on capabilities success')
assert.equal(f.hasPanel(), false)
assert.match(f.editor.followupCapabilitiesError.value, /加载失败/)
assert.equal(f.requests.length, 1)
const retry = f.editor.loadFollowupCapabilities()
f.requests[1].resolve({ ...caps(), can_upload: false, can_apply: false, can_daily: false })
await retry
assert.equal(f.hasPanel(), true)
const panel = f.nodes().find(node => node.props?.capabilities)
assert.equal(panel.props.capabilities.can_apply, false, 'entry grant never overrides server write capability')
assert.equal(panel.props.capabilities.can_upload, false)
} finally { f.dispose() }
}
})
test('permission revocation aborts pending capabilities and grant refreshes current saved diagnosis only', async () => {
const f = setupAudioEntry(['tcm.diagnosis/followupAudio'])
try {
await f.editor.open('edit', 10)
f.editor.activeTab.value = 'followupAudio'
const old = f.requests[0]
f.userStore.perms = ['tcm.diagnosis/dailyRecord']
assert.equal(old.signal.aborted, true)
assert.equal(f.hasTab(), false)
assert.equal(f.hasDailyTab(), true)
assert.equal(f.editor.activeTab.value, 'basic')
old.resolve(caps()); await settle()
assert.equal(f.editor.followupCapabilities.value, null)
assert.equal(f.requests.length, 1)
f.userStore.perms.push('tcm.diagnosis/followupAudio')
assert.equal(f.hasTab(), true)
assert.equal(f.requests.length, 2)
f.requests[1].resolve(caps()); await settle()
assert.equal(f.hasPanel(), true)
f.userStore.perms = []
assert.equal(f.hasPanel(), false)
assert.equal(f.editor.followupCapabilities.value, null)
assert.equal(f.requests.length, 2)
} finally { f.dispose() }
})
@@ -0,0 +1,253 @@
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, [])
})
@@ -0,0 +1,167 @@
const assert = require('node:assert/strict')
const fs = require('node:fs')
const path = require('node:path')
const test = require('node:test')
const ts = require('typescript')
const vue = require('vue')
const { parse, compileScript, compileTemplate } = require('@vue/compiler-sfc')
const selected = [
'patchUsageVisible', 'patchUsageSaving', 'patchUsageFormRef', 'patchUsageForm',
'patchUsageRules', 'openPatchUsageDialog', 'resetPatchUsageForm', 'submitPatchUsage'
]
for (const page of ['components/PrescriptionOrderDetailDrawer.vue', 'order_list_h5.vue']) {
const filename = path.join(__dirname, '../src/views/consumer/prescription', page)
const { descriptor, errors } = parse(fs.readFileSync(filename, 'utf8'), { filename })
assert.deepEqual(errors, [])
const script = compileScript(descriptor, { id: page })
const template = compileTemplate({
source: descriptor.template.content, filename, id: page,
compilerOptions: { bindingMetadata: script.bindings }
})
assert.deepEqual(template.errors, [])
// Run the real handlers; replace the network and the rest of the order page.
const ast = ts.createSourceFile(filename + '.ts', descriptor.scriptSetup.content, ts.ScriptTarget.Latest, true)
const declarations = new Map()
for (const node of ast.statements) {
if (ts.isFunctionDeclaration(node) && node.name) declarations.set(node.name.text, node.getText(ast))
if (ts.isVariableStatement(node)) {
for (const declaration of node.declarationList.declarations) {
declarations.set(declaration.name.getText(ast), `const ${declaration.getText(ast)}`)
}
}
}
const executed = page.startsWith('components/') ? [...selected, 'refresh'] : selected
for (const name of executed) assert.ok(declarations.has(name), `${page}: missing ${name}`)
const compiled = ts.transpileModule(executed.map(name => declarations.get(name)).join('\n'), {
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS }
}).outputText
function instance({ hasAux = true, prescriptionType = '浓缩水丸', bagCount = 2, mainBagCount = 2, status = 2, fail = false } = {}) {
const calls = []
const events = []
const aux = { times_per_day: 3, usage_days: 10, dosage_bag_count: bagCount }
const detailPrescription = vue.ref({ prescription_type: prescriptionType, times_per_day: 3, usage_days: 10, dosage_bag_count: mainBagCount })
const detailAuxUsage = vue.ref(hasAux ? aux : null)
const detailData = vue.ref({
id: 42, prescription_id: 17, medication_days: 10, fulfillment_status: status,
gancao_reciperl_order_no: 'TEST-SUBMITTED', ej_pharmacy_order_no: 'TEST-EJ-SUBMITTED'
})
const refresh = async () => {
if (calls[0]?.dosage_bag_count) detailPrescription.value.dosage_bag_count = calls[0].dosage_bag_count
if (calls[0]?.aux_dosage_bag_count) detailAuxUsage.value.dosage_bag_count = calls[0].aux_dosage_bag_count
events.push('refresh')
return { ...detailData.value }
}
const globals = {
ref: vue.ref, reactive: vue.reactive, computed: vue.computed, nextTick: vue.nextTick,
detailPrescription, detailAuxUsage, detailData, detailHasAuxHerbs: vue.ref(hasAux),
feedback: { msgWarning() {}, msgSuccess() {} },
prescriptionOrderPatchPrescriptionUsage: async payload => {
calls.push(payload)
if (fail) throw new Error('Save failed')
},
requestDetail: refresh, refreshCurrentPrescriptionOrderDetail: refresh,
props: { loadRelatedData: true },
emit: event => events.push(event),
fetchLogs: async () => {
events.push('logs:start')
await Promise.resolve()
events.push('logs:done')
},
getLists: () => events.push('lists')
}
const state = new Function(...Object.keys(globals), `${compiled}\nreturn { ${selected.join(', ')} }`)(...Object.values(globals))
state.patchUsageFormRef.value = { validate: async () => {}, clearValidate() {} }
return { state, calls, events, detailAuxUsage, detailPrescription }
}
test(`${page}: edits auxiliary bags and refreshes the persisted value without changing usage`, async () => {
const { state, calls, events, detailAuxUsage } = instance()
state.openPatchUsageDialog()
assert.equal(state.patchUsageForm.aux_dosage_bag_count, 2)
state.patchUsageForm.aux_dosage_bag_count = 4
await state.submitPatchUsage()
assert.deepEqual(calls, [{
id: 42, times_per_day: 3, usage_days: 10, medication_days: 10,
dosage_bag_count: 2,
aux_times_per_day: 3, aux_usage_days: 10, aux_dosage_bag_count: 4
}])
assert.equal(state.patchUsageVisible.value, false)
assert.equal(detailAuxUsage.value.dosage_bag_count, 4)
assert.ok(events.includes('refresh'))
assert.ok(events.indexOf('logs:done') > events.indexOf('refresh'))
const completedEvent = page.startsWith('components/') ? 'detail-changed' : 'lists'
assert.ok(events.indexOf(completedEvent) > events.indexOf('logs:done'))
state.openPatchUsageDialog()
assert.equal(state.patchUsageForm.aux_dosage_bag_count, 4)
})
test(`${page}: missing historical bag count defaults to one and resets on close`, () => {
const { state } = instance({ bagCount: null, mainBagCount: null })
state.openPatchUsageDialog()
assert.equal(state.patchUsageForm.aux_dosage_bag_count, 1)
assert.equal(state.patchUsageForm.dosage_bag_count, 1)
state.patchUsageForm.dosage_bag_count = 4
state.patchUsageForm.aux_dosage_bag_count = 5
state.resetPatchUsageForm()
assert.equal(state.patchUsageForm.aux_dosage_bag_count, 1)
assert.equal(state.patchUsageForm.dosage_bag_count, 1)
})
test(`${page}: only water pills with an auxiliary formula submit or require auxiliary bags`, async () => {
for (const options of [{ hasAux: false }, { prescriptionType: '饮片' }, { prescriptionType: '颗粒' }]) {
const { state, calls } = instance(options)
state.openPatchUsageDialog()
state.patchUsageForm.aux_dosage_bag_count = 5
assert.equal(state.patchUsageRules.value.aux_dosage_bag_count, undefined)
await state.submitPatchUsage()
assert.ok(!Object.hasOwn(calls[0], 'aux_dosage_bag_count'))
assert.equal(Object.hasOwn(calls[0], 'dosage_bag_count'), !options.prescriptionType)
}
const { state } = instance()
assert.equal(state.patchUsageRules.value.aux_dosage_bag_count[0].required, true)
assert.equal(state.patchUsageRules.value.dosage_bag_count[0].required, true)
})
test(`${page}: main and auxiliary bags can be edited independently in every submitted order status`, async () => {
for (let status = 1; status <= 12; status++) {
const { state, calls, detailPrescription, detailAuxUsage } = instance({ status })
state.openPatchUsageDialog()
assert.equal(state.patchUsageForm.dosage_bag_count, 2)
state.patchUsageForm.dosage_bag_count = 5
state.patchUsageForm.aux_dosage_bag_count = 1
await state.submitPatchUsage()
assert.equal(calls.length, 1, `status ${status}`)
assert.equal(calls[0].dosage_bag_count, 5)
assert.equal(calls[0].aux_dosage_bag_count, 1)
assert.equal(detailPrescription.value.dosage_bag_count, 5)
assert.equal(detailAuxUsage.value.dosage_bag_count, 1)
}
const { state, calls } = instance({ hasAux: false })
state.openPatchUsageDialog()
state.patchUsageForm.dosage_bag_count = 4
await state.submitPatchUsage()
assert.equal(calls[0].dosage_bag_count, 4)
assert.ok(!Object.hasOwn(calls[0], 'aux_dosage_bag_count'))
})
test(`${page}: validation blocks requests and a rejected save retains the selected bags`, async () => {
const { state, calls, events } = instance({ fail: true })
state.openPatchUsageDialog()
state.patchUsageForm.aux_dosage_bag_count = 3
state.patchUsageForm.dosage_bag_count = 4
state.patchUsageFormRef.value.validate = async () => { throw new Error('Required') }
await state.submitPatchUsage()
assert.equal(calls.length, 0)
state.patchUsageFormRef.value.validate = async () => {}
await state.submitPatchUsage()
assert.equal(state.patchUsageForm.aux_dosage_bag_count, 3)
assert.equal(state.patchUsageForm.dosage_bag_count, 4)
assert.equal(state.patchUsageVisible.value, true)
assert.equal(state.patchUsageSaving.value, false)
assert.deepEqual(events, [])
})
}
+2
View File
@@ -46,6 +46,8 @@ export default defineConfig(({ mode }) => {
return {
base: '/admin/',
// 临时 UI 预览可能共用 node_modules;主开发服务独立缓存,避免预构建互相覆盖。
cacheDir: path.resolve(__dirname, 'node_modules/.vite-admin'),
server: {
port: 5555,
host: '0.0.0.0',
+1
View File
@@ -1,4 +1,5 @@
.env
.local-workstation/
.venv/
.venv-build/
.venv-win7-check/
+8
View File
@@ -35,6 +35,14 @@ Windows 打包机需预先安装 `uv` 与 Node.js 20+;脚本会自动处理项
- 腾讯视频:沿用现有项目的 `@trtc/calls-uikit-vue` 主链;UserSig 只从后端短时获取,客户端不包含 SDKSecretKey。当前仅支持隔离的 QtWebEngine 内嵌模式。
- PyInstaller Windows/macOS 构建脚本、macOS 摄像头/麦克风权限配置与自动化测试。
## 本地后端联调
本机 phpStudy 站点准备好后,双击 `Run_DoctorWorkstation_Local.bat`,使用当前源码连接 `https://css.zhenyangtang.com.cn`。此入口要求域名解析到本机,启用 TLS 校验,复用本机站点的公开证书;偏好、日志和登录凭据使用独立目录及凭据命名空间。正式启动入口及正式服务器配置保持原样。本地入口首次启动需要重新登录,不会借用正式环境的会话。
本地入口固定使用指定的本机地址和证书校验,会修正旧偏好中的线上地址,并隔离登录页保存的设置;登录时不能切换到其他服务器。普通的“一键运行”入口仍连接正式服务器,不能用来验证尚未部署的本地后端修改。
仅检查配置可执行 `Run_DoctorWorkstation_Local.bat --check`。其他本机 HTTPS 站点可通过 `DOCTOR_LOCAL_API_URL` 和 `DOCTOR_LOCAL_CA_FILE` 指定域名与公开证书路径,禁止传入私钥。配置保存在已忽略的 `.local-workstation/` 中;本地后端仍使用 `server/.env` 的现有配置。
## 手动运行
先安装 [uv](https://docs.astral.sh/uv/),然后在项目根目录执行:
+10
View File
@@ -0,0 +1,10 @@
@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%
+6 -3
View File
@@ -89,7 +89,7 @@ def example_batch() -> dict[str, Any]:
"algorithm_version": "prescription-soft-dice-v1.1.0",
"prompt_version": "manual-prescription-required-candidate-v4",
}
return {"id": 40, "prescription_id": 7556, "patient_id": 1391, "diagnosis_id": 1391,
return {"id": 40, "prescription_id": 7556, "patient_id": 1391, "diagnosis_id": 1391, "agreement_visible": True,
"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,8 +143,11 @@ 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 {"enabled": True, "lists": deepcopy(self.history()), "count": len(self.history())}
return {"agreement_visible": True, "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."""
@@ -170,7 +173,7 @@ class PreviewRepository:
"algorithm_version": "prescription-soft-dice-v1.0.0"},
"openai": {"comparison": {"status": "not_comparable"}}}},
]
return [self.batch, *older]
return [{**row, "agreement_visible": True} for row in [self.batch, *older]]
def get_prescription_ai_report(self, _batch_id: int) -> dict[str, Any]:
return deepcopy(self.batch)
@@ -0,0 +1,111 @@
"""Capture agreement authorization states using synthetic data and no network."""
from __future__ import annotations
import os
from copy import deepcopy
from pathlib import Path
from typing import Any
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6.QtWidgets import QApplication
from render_issued_prescription_ai import PreviewRepository
from doctor_workstation.services import DemoDoctorRepository
from doctor_workstation.ui.dialogs import issued_prescription_ai as ai
from doctor_workstation.ui.pages import prescriptions
from doctor_workstation.ui.theme import apply_theme
class VisibilityPreviewRepository(DemoDoctorRepository, PreviewRepository):
def __init__(self) -> None:
DemoDoctorRepository.__init__(self)
PreviewRepository.__init__(self)
self.visible = True
def get_prescription_ai_capabilities(self) -> dict[str, Any]:
return {"agreement_visible": self.visible, "can_manage_visibility": True}
def list_prescription_ai_statuses(self, ids: list[int]) -> dict[str, Any]:
return {"enabled": True, "agreement_visible": self.visible, "items": [
{"prescription_id": value, "agreement_visible": self.visible, "status": "success",
"models": {"qwen": {"status": "success", "score": 68.5},
"openai": {"status": "success", "score": 55.2}}} for value in ids]}
def list_prescription_ai_reports(self, **_params: Any) -> dict[str, Any]:
rows = [{**row, "agreement_visible": self.visible} for row in self.history()]
return {"agreement_visible": self.visible, "enabled": True, "lists": deepcopy(rows), "count": len(rows)}
def get_prescription_ai_report(self, _batch_id: int) -> dict[str, Any]:
return {**deepcopy(self.batch), "agreement_visible": self.visible}
def main() -> None:
application = QApplication.instance() or QApplication([])
apply_theme(application)
output = Path(__file__).resolve().parents[2] / "artifacts" / "prescription-ai-visibility"
output.mkdir(parents=True, exist_ok=True)
def immediate(function: Any, **callbacks: Any) -> None:
try:
result = function()
except Exception as error:
if callbacks.get("on_error"):
callbacks["on_error"](error)
else:
raise
else:
if callbacks.get("on_success"):
callbacks["on_success"](result)
finally:
if callbacks.get("on_finished"):
callbacks["on_finished"]()
ai.run_async = immediate
prescriptions.run_async = immediate
repository = VisibilityPreviewRepository()
def capture(widget: Any, filename: str) -> None:
for _ in range(4):
application.processEvents()
assert widget.grab().save(str(output / filename))
page = prescriptions.PrescriptionsPage(repository, ["*"], {"name": "演示医生", "root": 1})
page.resize(1366, 800)
page.show()
capture(page, "list-authorized.png")
repository.visible = False
page.refresh()
capture(page, "list-restricted.png")
page.close()
repository.visible = True
dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=7556,
current_user={"name": "演示医生", "root": 1})
dialog.resize(1280, 860)
dialog.show()
capture(dialog, "report-authorized.png")
repository.visible = False
repository.batch["status"] = "partial"
repository.batch["models"]["openai"].update(
status="failed", report=None, candidate=None, comparison=None,
error_code="upstream_timeout", error_message="演示:模型连接超时,可重试。")
dialog.refresh()
dialog._goto("report")
capture(dialog, "report-restricted.png")
dialog._goto("overview")
capture(dialog, "review-restricted.png")
dialog._goto("per_herb")
capture(dialog, "candidate-restricted.png")
dialog.close()
statistics = ai.PrescriptionAiStatisticsDialog(repository, ["*"])
statistics.resize(1180, 860)
statistics.show()
capture(statistics, "statistics-restricted.png")
statistics.close()
print(output)
if __name__ == "__main__":
main()
+101
View File
@@ -0,0 +1,101 @@
"""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 -1
View File
@@ -3,7 +3,7 @@
__all__ = ["DEBUG_MODE", "ONLINE_API_BASE_URL", "__version__"]
# Single source of truth for runtime, package, installer, and executable versions.
__version__ = "1.4.5"
__version__ = "1.5.0"
# 调试模式开启时,登录页显示“演示模式”和“服务器设置”。
# 正式发布请保持 False;此时程序只使用下面配置的线上域名。
@@ -2,16 +2,19 @@
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
from contextlib import contextmanager, suppress
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,
@@ -228,6 +231,29 @@ 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,
@@ -247,6 +273,14 @@ 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,
@@ -286,6 +320,109 @@ 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."""
@@ -483,6 +620,7 @@ 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"
@@ -6,7 +6,7 @@ import hashlib
import json
import struct
import zlib
from collections.abc import Mapping, Sequence
from collections.abc import Callable, Mapping, Sequence
from copy import deepcopy
from datetime import date, datetime, timedelta
from os import PathLike
@@ -2771,10 +2771,14 @@ 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",
@@ -2811,6 +2815,8 @@ 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,
@@ -206,9 +206,13 @@ class DoctorRepository(Protocol):
prompt: str,
*,
task: str = "custom",
request_id: str | None = None,
cancelled: Callable[[], bool] | None = None,
) -> Iterator[dict[str, Any]]:
"""Yield normalized ``start``/``delta``/``done`` assistant events."""
"""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 generate_ai_prescription(self, diagnosis_id: int) -> dict[str, Any]:
"""Generate a server-validated prescription draft for doctor review."""
@@ -235,6 +239,9 @@ 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."""
@@ -676,6 +683,7 @@ 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."""
@@ -1410,12 +1418,16 @@ 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}
body = {
"id": diagnosis_id, "prompt": clean_prompt, "task": clean_task,
"request_id": request_id or str(uuid4()),
}
received_event = False
received_done = False
try:
@@ -1464,6 +1476,18 @@ class RemoteDoctorRepository:
yield {"event": "delta", "text": answer, "fallback": True}
yield {**result, "event": "done", "fallback": True}
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."""
@@ -1611,6 +1635,9 @@ 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")
@@ -2486,8 +2513,13 @@ 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."""
"""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.
"""
if diagnosis_id <= 0:
raise ValueError("diagnosis_id must be positive")
@@ -2507,6 +2539,13 @@ 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)
@@ -2541,6 +2580,7 @@ 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")
@@ -2964,6 +3004,9 @@ 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",
@@ -2984,10 +3027,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 == "start":
if kind in {"start", "progress"}:
payload.pop("event", None)
payload.pop("type", None)
return {**payload, "event": "start"}
return {**payload, "event": kind}
if kind == "delta":
text = (
data
+376
View File
@@ -0,0 +1,376 @@
"""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, "", "")
@@ -63,7 +63,8 @@ from PySide6.QtWidgets import (
QWidget,
)
from .diagnosis_editors import FlowLayout
from .chat_items import ChatItem, parse_chat_item
from .diagnosis_editors import FlowLayout
from .diagnosis_media import shared_image_manager
from .diagnosis_terms import FIELD_DICTIONARIES, format_timestamp, shared_terms
@@ -720,6 +721,25 @@ 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;
@@ -3034,25 +3054,16 @@ class ChatPanel(QWidget):
widget = item.widget()
if widget is not None and widget not in {self.empty, self.toolbar, self.info}:
widget.deleteLater()
self.empty.setVisible(not messages)
visible_count = 0
for message in messages:
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"
)
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"
row = QWidget()
row_layout = QHBoxLayout(row)
row_layout.setContentsMargins(0, 0, 0, 0)
@@ -3065,13 +3076,14 @@ class ChatPanel(QWidget):
bubble_layout.setSpacing(5)
meta = QLabel(
f"{_text(_pick(message, 'sender_name', 'from_staff_name', 'name'), '患者' if side == 'patient' else '医生')} "
f"{_text(_pick(message, 'create_time', 'time'), '')}"
f"{item.time_text}"
)
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, "content", "text", "message"), "不支持的消息")
body_text = _text(_pick(message, "text", "content", "message"), "不支持的消息")
body: QWidget
if message_type in {"image", "2"}:
target = str(
@@ -3111,9 +3123,11 @@ 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)
@@ -3124,6 +3138,50 @@ 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)
@@ -7,7 +7,7 @@ admin-table presentation cannot leak into another workstation page.
from __future__ import annotations
from collections.abc import Iterable, Mapping, Sequence
from collections.abc import Callable, Iterable, Mapping, Sequence
from math import ceil
from typing import Any
@@ -75,12 +75,9 @@ TEXT = QColor("#1A1C1F")
SECONDARY = QColor("#606163")
PLACEHOLDER = QColor("#8E8F90")
_INVALID_INDEX = QModelIndex()
# 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.
# 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.
_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("#A9691D")
@@ -1609,6 +1606,7 @@ 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:
@@ -1618,6 +1616,7 @@ 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]
@@ -1633,6 +1632,9 @@ 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)
@@ -1786,11 +1788,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 _appointment_active(record) and (is_text or call_state == "live"):
if video_capable and entry_allowed and _appointment_active(record) and (is_text or call_state == "live"):
button = QToolButton(host)
button.setText("图文沟通" if is_text else "进入视频问诊")
button.setProperty("rowLink", "primary")
@@ -1803,10 +1805,17 @@ class DiagnosisTableHost(QFrame):
button.clicked.connect(
lambda _checked=False, item=record: self.video_requested.emit(item)
)
layout.addWidget(button)
layout.addWidget(button, 0, Qt.AlignmentFlag.AlignCenter)
else:
status = "—"
if video_capable:
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 call_state == "pending_room":
status = "等待接通"
elif _appointment_active(record):
@@ -1816,10 +1825,17 @@ class DiagnosisTableHost(QFrame):
_appointment_status(record),
"未挂号" if not _has_appointment(record) else "—",
)
label = QLabel(display_text(status), host)
status_text = display_text(status)
label = QLabel(status_text.replace(" · ", "\n", 1), 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
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,646 @@
"""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()
@@ -0,0 +1,121 @@
"""从 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
@@ -0,0 +1,86 @@
"""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"
@@ -0,0 +1,418 @@
"""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>")
@@ -0,0 +1,958 @@
"""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)
)
@@ -2,13 +2,26 @@
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, QPoint, QRect, Qt, QTimer, QUrl, Signal
from PySide6.QtCore import (
QDate,
QDateTime,
QEvent,
QObject,
QPoint,
QRect,
Qt,
QTimer,
QUrl,
Signal,
)
from PySide6.QtGui import QDesktopServices
from PySide6.QtWidgets import (
QAbstractItemView,
@@ -22,6 +35,7 @@ from PySide6.QtWidgets import (
QLabel,
QMessageBox,
QPlainTextEdit,
QProgressBar,
QPushButton,
QScrollArea,
QSizePolicy,
@@ -83,6 +97,13 @@ 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"
@@ -145,7 +166,6 @@ _DIAGNOSIS_FIELDS = (
("脂肪肝程度", "fatty_liver_degree", "脂肪肝程度"),
("舌象", "tongue", "舌质、舌苔等观察"),
("舌苔", "tongue_coating", "舌苔记录"),
("脉象", "pulse", "脉象记录"),
("临床诊断", "clinical_diagnosis", "填写临床诊断"),
("治则", "treatment_principle", "治疗原则"),
("处方", "prescription", "处方摘要"),
@@ -717,19 +737,21 @@ 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
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.resize(1152, 720)
width = round(self.width() * self.drawer_ratio)
self.drawer_panel.setFixedWidth(max(1, width))
def eventFilter(self, watched: object, event: QEvent) -> bool: # noqa: N802 - Qt API
@@ -1511,9 +1533,38 @@ 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(
"QFrame#DiagnosisVideoUploadProgress { background-color: #EEF1FA;"
" border: 1px solid #C9D1F3; border-radius: 8px; }"
"QFrame#DiagnosisVideoUploadProgress QLabel { color: #3347B8; 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")
@@ -1842,11 +1893,17 @@ 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)
@@ -1935,6 +1992,7 @@ class DiagnosisDialog(QDialog):
QEvent.Type.Resize,
QEvent.Type.Move,
QEvent.Type.Show,
QEvent.Type.WindowStateChange,
}:
self._sync_host_geometry()
self._update_drawer_geometry()
@@ -3270,8 +3328,6 @@ 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")
@@ -3317,6 +3373,15 @@ 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,
@@ -3324,13 +3389,47 @@ 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")
@@ -3430,7 +3529,14 @@ class DiagnosisDialog(QDialog):
"chat",
)
def _run_media_mutation(self, operation: Any, success_text: str, reload_key: str) -> None:
def _run_media_mutation(
self,
operation: Any,
success_text: str,
reload_key: str,
*,
on_finished: Any = None,
) -> None:
self._media_generation += 1
generation = self._media_generation
diagnosis_id = self._diagnosis_id
@@ -3441,6 +3547,7 @@ 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(
@@ -3,6 +3,7 @@
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
@@ -402,6 +403,28 @@ 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):
@@ -536,6 +559,8 @@ 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)
@@ -575,7 +600,7 @@ class IssuedPrescriptionAiDialog(QDialog):
identity_block.addWidget(self.breadcrumb)
title_row = QHBoxLayout()
title_row.setSpacing(10)
heading = QLabel("诊断与药方对照", top)
heading = self.heading = QLabel("诊断与药方对照", top)
heading.setObjectName("AiHeroTitle")
title_row.addWidget(heading)
self.chip_row = QHBoxLayout()
@@ -903,7 +928,7 @@ class IssuedPrescriptionAiDialog(QDialog):
footer_text = QVBoxLayout()
footer_text.setSpacing(4)
footer_text.addWidget(self.message)
note = QLabel(DISCLAIMER)
note = self.disclaimer = QLabel(DISCLAIMER)
note.setObjectName("AiFootnote")
note.setWordWrap(True)
footer_text.addWidget(note)
@@ -921,6 +946,7 @@ 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", "只看不同段落"))
@@ -1063,6 +1089,8 @@ 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)
@@ -1070,7 +1098,10 @@ 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), "")
self.rail.set_current(current)
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._current_page = current
self._apply_density()
@@ -1101,6 +1132,36 @@ 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."""
@@ -1206,9 +1267,12 @@ 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 = data.get("lists") or []
self.history_page.set_history([mapping(row) for row in rows])
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 [])
self.history.blockSignals(True)
self.history.clear()
self._history_scope = {}
@@ -1321,6 +1385,8 @@ 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", "权限", "无权", "登录", "归属", "不存在")
@@ -1354,6 +1420,10 @@ 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
@@ -1368,7 +1438,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")), "neutral"),
(label(batch.get("comparison_type")) if self._agreement_visible else "", "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)
@@ -1411,9 +1481,11 @@ class IssuedPrescriptionAiDialog(QDialog):
"risk_assessment": report.get("risk_assessment"),
}
_set_html(views["candidate"], _candidate_html(candidate_content))
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 = ""
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"}})
_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)
@@ -1428,7 +1500,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)
self.candidates_page.set_batch(batch if self._agreement_visible else {})
self.sources_page.set_batch(batch)
self.pipeline_page.set_batch(batch)
self._sync_failures(batch)
@@ -1488,6 +1560,12 @@ 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"))
@@ -1707,6 +1785,7 @@ 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)
@@ -1742,6 +1821,7 @@ 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)
@@ -1750,9 +1830,19 @@ 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
@@ -1763,20 +1853,33 @@ class PrescriptionAiStatisticsDialog(QDialog):
if doctor and (not doctor.isdecimal() or int(doctor) <= 0):
self.summary.setText("请填写有效的医生编号。")
return
self._generation += 1
generation = self._generation
self.summary.setText("正在读取统计…")
self.report.clear()
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(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))
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.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))
def _error(self, error: Exception, generation: int) -> None:
if generation == self._generation:
self.summary.setText("统计暂不可用:" + _error_text(error))
self.report.clear()
self._clear_statistics()
def _ready(self, result: Any, generation: int) -> None:
if generation != self._generation:
if generation != self._generation or not self._agreement_visible:
return
data = mapping(result)
if data.get("enabled") is False:
@@ -1786,6 +1889,7 @@ 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,6 +190,8 @@ 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:
@@ -197,11 +199,14 @@ class AgreementBar(QFrame):
divider.setObjectName("AiFactDivider")
divider.setFixedWidth(1)
layout.addWidget(divider)
layout.addWidget(self._delta_block())
delta = self._delta_block()
layout.addWidget(delta)
self._metric_chrome.extend((divider, delta))
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)
@@ -294,7 +299,7 @@ class AgreementBar(QFrame):
carrier.setFixedHeight(4)
carrier.setAccessibleName(f"{MODEL_NAMES[key]}与医生方的药味及剂量一致度")
carrier.setVisible(False)
self.blocks[key] = {"score": score, "coverage": coverage, "elapsed": elapsed, "track": track,
self.blocks[key] = {"score": score, "caption": caption, "coverage": coverage, "elapsed": elapsed, "track": track,
"status": status, "failure": failure, "failure_text": failure_text,
"retry_slot": retry_slot, "stage": stage, "carrier": carrier}
return holder
@@ -313,6 +318,30 @@ 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)
@@ -351,7 +380,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))) for key in ("qwen", "openai")}
scores = {key: _score(_mapping(models.get(key))) if self._agreement_visible else None for key in ("qwen", "openai")}
for key in ("qwen", "openai"):
block = self.blocks[key]
value = scores[key]
@@ -364,6 +393,9 @@ 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("两个模型都可比后才给差值")
@@ -537,6 +537,9 @@ 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)
@@ -620,6 +623,9 @@ 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):
@@ -844,6 +850,9 @@ 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 = []
@@ -1015,6 +1024,9 @@ 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]] = {}
@@ -1132,6 +1144,7 @@ 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; }}
@@ -1150,7 +1163,7 @@ class PrescriptionReviewWorkspace(QWidget):
page = QWidget(self.page_scroll)
self.page_scroll.setWidget(page)
outer.addWidget(self.page_scroll)
root = QVBoxLayout(page)
root = self._workspace_layout = QVBoxLayout(page)
root.setContentsMargins(0, 0, 6, 0)
root.setSpacing(14)
@@ -1201,6 +1214,10 @@ 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):
@@ -1289,7 +1306,31 @@ 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)
@@ -28,6 +28,7 @@ from PySide6.QtCore import (
QDate,
QEvent,
QIODevice,
QModelIndex,
QMarginsF,
QObject,
QPoint,
@@ -51,6 +52,8 @@ from PySide6.QtGui import (
QPainter,
QPdfWriter,
QPen,
QStandardItem,
QStandardItemModel,
QTextDocument,
)
from PySide6.QtPrintSupport import QPrintDialog, QPrinter
@@ -61,6 +64,7 @@ from PySide6.QtWidgets import (
QCalendarWidget,
QCheckBox,
QComboBox,
QCompleter,
QDialog,
QDialogButtonBox,
QDoubleSpinBox,
@@ -81,6 +85,9 @@ from PySide6.QtWidgets import (
QSizePolicy,
QSpinBox,
QSplitter,
QStyle,
QStyledItemDelegate,
QStyleOptionViewItem,
QTableWidget,
QTableWidgetItem,
QTabWidget,
@@ -323,7 +330,8 @@ QFrame#PrescriptionDrawerSurface QDoubleSpinBox {
border: 1px solid #EDEDEE;
border-radius: 7px;
padding: 0 11px;
selection-background-color: #EEF1FA; font-size: 14px;
selection-background-color: #C9D1F3;
selection-color: #1A1C1F; font-size: 14px;
}
QFrame#PrescriptionDrawerSurface QComboBox {
min-height: 32px;
@@ -333,7 +341,17 @@ QFrame#PrescriptionDrawerSurface QComboBox {
border-radius: 7px;
padding-left: 11px;
padding-right: 28px;
selection-background-color: #EEF1FA; font-size: 14px;
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;
}
QFrame#PrescriptionDrawerSurface QLineEdit[prescriptionControl="true"],
QFrame#PrescriptionDrawerSurface QComboBox[prescriptionControl="true"],
@@ -901,6 +919,23 @@ 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"}
@@ -1412,6 +1447,47 @@ 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."""
@@ -1433,6 +1509,10 @@ 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)
@@ -1440,6 +1520,23 @@ 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(
"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)
@@ -1451,9 +1548,9 @@ class RemoteMedicineComboBox(QComboBox):
@property
def medicine_id(self) -> int | None:
data = self.currentData()
value = _int(data, 0)
return value or self._selected_id
# 只认从药材库选中的 id;不能回退到旧下拉项的 data,否则改过文字的行
# 仍会带着原药材 id 通过校验,相当于允许直接输入药名。
return self._selected_id
@property
def medicine_name(self) -> str:
@@ -1462,12 +1559,16 @@ class RemoteMedicineComboBox(QComboBox):
@property
def has_valid_selection(self) -> bool:
name = self.medicine_name
return bool(self.medicine_id) or bool(self._legacy_name and name == self._legacy_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)
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:
@@ -1478,20 +1579,117 @@ class RemoteMedicineComboBox(QComboBox):
def showPopup(self) -> None:
if self.count() <= 1:
self._queue_search(self.currentText())
# 只是打开列表浏览,不清除已选药材。
self._timer.stop()
self._search()
self._search(browse=self.has_valid_selection or not self.medicine_name)
super().showPopup()
def _queue_search(self, _text: str) -> None:
self._selected_id = None
self._selected_name = ""
self._legacy_name = ""
self._timer.start()
def _search(self) -> None:
query = self.currentText().strip()
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()
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,
@@ -1510,6 +1708,7 @@ 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:
@@ -1524,11 +1723,23 @@ 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:
@@ -1538,9 +1749,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):
@@ -1575,7 +1786,7 @@ class HerbRowWidget(QFrame):
if source_locked is None
else bool(source_locked)
)
self.formula_combo = QComboBox(self)
self.formula_combo = NoWheelComboBox(self)
self.formula_combo.addItem("主方", "主方")
self.formula_combo.addItem("辅方", "辅方")
_set_combo_data(
@@ -1591,7 +1802,7 @@ class HerbRowWidget(QFrame):
parent=self,
)
self.medicine.setEnabled(not locked)
self.dosage = QDoubleSpinBox(self)
self.dosage = NoWheelDoubleSpinBox(self)
self.dosage.setRange(0, 1e100)
self.dosage.setDecimals(1)
self.dosage.setSingleStep(0.5)
@@ -2173,7 +2384,7 @@ class PrescriptionTemplateDialog(QDialog):
self.name_edit.setMaxLength(100)
self.name_edit.setPlaceholderText("请输入处方名称")
form.addRow("处方名称", self.name_edit)
self.formula_combo = QComboBox()
self.formula_combo = NoWheelComboBox()
self.formula_combo.addItem("主方", "主方")
self.formula_combo.addItem("辅方", "辅方")
_set_combo_data(
@@ -2293,7 +2504,7 @@ class TemplateImportDialog(QDialog):
self.name_edit.setPlaceholderText("请输入处方名称搜索")
self.name_edit.returnPressed.connect(self.search)
filters.addWidget(self.name_edit, 1)
self.formula_combo = QComboBox()
self.formula_combo = NoWheelComboBox()
self.formula_combo.addItem("全部", "")
self.formula_combo.addItem("主方", "主方")
self.formula_combo.addItem("辅方", "辅方")
@@ -2304,7 +2515,7 @@ class TemplateImportDialog(QDialog):
root.addLayout(filters)
mode_layout = QHBoxLayout()
mode_layout.addWidget(QLabel("导入方式"))
self.mode_combo = QComboBox()
self.mode_combo = NoWheelComboBox()
self.mode_combo.addItem("覆盖现有药材", "replace")
self.mode_combo.addItem("追加到末尾", "append")
mode_layout.addWidget(self.mode_combo)
@@ -2511,7 +2722,7 @@ class PasteHerbsDialog(QDialog):
root.addWidget(self.text_edit, 1)
mode_row = QHBoxLayout()
mode_row.addWidget(QLabel("导入方式"))
self.mode_combo = QComboBox()
self.mode_combo = NoWheelComboBox()
self.mode_combo.addItem("覆盖现有药材", "replace")
self.mode_combo.addItem("追加到末尾", "append")
mode_row.addWidget(self.mode_combo)
@@ -2735,8 +2946,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()
@@ -2978,7 +3189,7 @@ class PrescriptionEditorDialog(QDialog):
gender_layout.addWidget(self.gender_female)
gender_layout.addStretch(1)
self.gender = gender_host
self.age = QSpinBox()
self.age = NoWheelSpinBox()
self.age.setRange(0, 150)
self.visit_no = QLineEdit()
self.visit_no.setPlaceholderText("自动生成或手动输入")
@@ -3130,7 +3341,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 = QSpinBox()
self.dose_count = NoWheelSpinBox()
self.dose_count.setRange(1, 2_147_483_647)
self.dose_unit = SelectComboBox()
self.dose_unit.addItems(["剂", "丸", "袋", "盒", "瓶", "膏", "贴"])
@@ -3153,9 +3364,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 = QSpinBox()
self.times_per_day = NoWheelSpinBox()
self.times_per_day.setRange(1, 6)
self.usage_days = QSpinBox()
self.usage_days = NoWheelSpinBox()
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)
@@ -3188,9 +3399,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 = QSpinBox()
self.aux_times_per_day = NoWheelSpinBox()
self.aux_times_per_day.setRange(1, 6)
self.aux_usage_days = QSpinBox()
self.aux_usage_days = NoWheelSpinBox()
self.aux_usage_days.setRange(1, 365)
self.aux_prescription_name = QLineEdit()
self._aux_dosage_field = self._field("用量", self.aux_dosage_amount)
@@ -3964,7 +4175,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 = QComboBox()
self.gender = NoWheelComboBox()
self.gender.addItem("男", 1)
self.gender.addItem("女", 0)
_set_combo_data(self.gender, first_value(prescription, "gender", default=1))
@@ -5311,7 +5522,7 @@ class PrescriptionOrderDialog(QDialog):
def _build_recipient_tab(self) -> QWidget:
tab, form = self._form_tab()
self.diagnosis_id = QSpinBox()
self.diagnosis_id = NoWheelSpinBox()
self.diagnosis_id.setRange(0, 2_000_000_000)
self.diagnosis_id.valueChanged.connect(self._diagnosis_changed)
form.addRow("诊单 ID *", self.diagnosis_id)
@@ -5333,14 +5544,14 @@ class PrescriptionOrderDialog(QDialog):
def _build_service_tab(self) -> QWidget:
tab, form = self._form_tab()
self.ship_mode = QComboBox()
self.ship_mode = NoWheelComboBox()
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 = QSpinBox()
self.medication_days = NoWheelSpinBox()
self.medication_days.setRange(0, 365)
self.medication_days.setSpecialValueText("未填写")
form.addRow("服用天数", self.medication_days)
@@ -5365,7 +5576,7 @@ class PrescriptionOrderDialog(QDialog):
def _build_amount_tab(self) -> QWidget:
tab, form = self._form_tab()
self.fee_type = QComboBox()
self.fee_type = NoWheelComboBox()
self.fee_type.addItem("药品费用", 3)
self.fee_type.addItem("挂号费", 1)
self.fee_type.addItem("问诊费", 2)
@@ -5373,12 +5584,12 @@ class PrescriptionOrderDialog(QDialog):
self.fee_type.addItem("尾款", 5)
self.fee_type.addItem("其他", 6)
form.addRow("费用类别 *", self.fee_type)
self.amount = QDoubleSpinBox()
self.amount = NoWheelDoubleSpinBox()
self.amount.setRange(0, 10_000_000)
self.amount.setDecimals(2)
self.amount.setPrefix("¥ ")
form.addRow("订单金额 *", self.amount)
self.internal_cost = QDoubleSpinBox(tab)
self.internal_cost = NoWheelDoubleSpinBox(tab)
self.internal_cost.setRange(0, 10_000_000)
self.internal_cost.setDecimals(2)
self.internal_cost.setPrefix("¥ ")
@@ -119,10 +119,28 @@ 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")):
@@ -133,10 +151,19 @@ def diagnosis_ai_task(prompt: str) -> str:
return "prescription_review"
if any(marker in text for marker in ("用药", "药物", "中药", "medication")):
return "medication_review"
if any(marker in text for marker in ("辨证", "证候", "舌象", "脉象", "tcm")):
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):
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"
+5
View File
@@ -228,6 +228,11 @@ 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:
@@ -38,6 +38,7 @@ 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
@@ -1493,6 +1494,7 @@ 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"),
@@ -3053,8 +3055,11 @@ 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(
has_record
entry_allowed
and is_video_available(record)
and (appointment_type_value(record) == "text" or video_call_is_live(record))
and valid_ids
@@ -3496,6 +3501,28 @@ 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:
@@ -3503,6 +3530,9 @@ 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")
@@ -348,16 +348,16 @@ class PrescriptionLibraryPage(QWidget):
table_layout.setSpacing(0)
self.table = LibraryTable(
[
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: ""),
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: ""),
]
)
self.table.setObjectName("PrescriptionLibraryTable")
@@ -371,8 +371,6 @@ 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)
@@ -52,6 +52,7 @@ from PySide6.QtWidgets import (
from .. import icons, motion
from ..dialogs.issued_prescription_ai import (
PrescriptionAiStatisticsDialog,
agreement_safe_batch,
agreement_text,
batch_running,
can_open_issued_ai,
@@ -1007,6 +1008,10 @@ 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)
@@ -1048,7 +1053,7 @@ 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.setVisible(has_permission(permissions, "tcm.prescriptionAi/statistics", default=False) and callable(getattr(repository, "prescription_ai_statistics", None)))
self.ai_statistics_button.hide()
self.ai_statistics_button.clicked.connect(self._open_ai_statistics)
header.add_action(self.ai_statistics_button)
self.add_button = QPushButton("新增处方", header)
@@ -1437,6 +1442,7 @@ 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] = {
@@ -1656,6 +1662,7 @@ 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):
@@ -1688,7 +1695,7 @@ class PrescriptionsPage(QWidget):
changed = enabled != self._ai_enabled
self._ai_enabled = enabled
for column in (11, 12):
self.table.setColumnHidden(column, not enabled)
self.table.setColumnHidden(column, not (enabled and self._agreement_visible))
if enabled:
header = self.table.horizontalHeader()
header.moveSection(header.visualIndex(11), header.visualIndex(4) + 1)
@@ -1699,10 +1706,55 @@ 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()
@@ -1713,15 +1765,17 @@ class PrescriptionsPage(QWidget):
self.ai_status_notice.setToolTip("")
self.ai_report_button.setToolTip("自动分析未启用;仍可查看已保存的历史报告。")
return
self.ai_status_notice.setText("AI 分析已启用:保存手工处方后自动生成两份报告,并显示药味与剂量一致度。")
self.ai_status_notice.setText("AI 分析已启用:保存手工处方后自动生成两份报告。"
+ ("可查看药味与剂量一致度。" if self._agreement_visible else ""))
self.ai_status_notice.setToolTip("")
self.ai_report_button.setToolTip("查看两份 AI 报告、候选处方和逐味对照。")
self.ai_report_button.setToolTip("查看两份 AI 报告和候选处方。"
+ ("可查看逐味对照。" if self._agreement_visible else ""))
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] = _row_mapping(batch)
self._ai_statuses[value] = agreement_safe_batch(batch, self._agreement_visible and _row_mapping(batch).get("agreement_visible") is True)
self._render_ai_statuses()
if any(batch_running(self._ai_statuses.get(value)) for value in self._visible_ai_ids()):
self._ai_timer.start()
@@ -1741,13 +1795,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 else agreement_text(batch)
agreement = "" if blank or not self._agreement_visible 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 else status_tooltip(batch))
item.setToolTip("" if blank or column == 12 and not self._agreement_visible else status_tooltip(batch))
item.setData(Qt.ItemDataRole.AccessibleTextRole, text)
if changed:
self.table.resizeRowsToContents()
@@ -1757,6 +1811,7 @@ 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))
@@ -1781,13 +1836,13 @@ class PrescriptionsPage(QWidget):
if _is_blank_prescription(row):
return
menu = QMenu(self.table)
action = menu.addAction("AI 报告 / 逐味对照")
action = menu.addAction("AI 报告 / 逐味对照" if self._agreement_visible else "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 has_permission(self.permissions, "tcm.prescriptionAi/statistics", default=False):
if not self._agreement_visible or 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)
@@ -2207,12 +2262,14 @@ class PrescriptionsPage(QWidget):
if self.table.rowCount() == 0 and not self._loading:
self.refresh()
elif not self._loading:
self._load_ai_statuses()
self._load_ai_capabilities()
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)
+247 -83
View File
@@ -89,6 +89,7 @@ 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 (
@@ -321,6 +322,11 @@ 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;
@@ -1177,6 +1183,7 @@ 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;
@@ -1919,6 +1926,30 @@ 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:
@@ -2469,6 +2500,13 @@ 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
@@ -2483,21 +2521,7 @@ class _ReceptionHero(QFrame):
class _ClinicalInfoPanel(QWidget):
"""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)
"""Let the clinical history use the full reading column."""
class _ClinicalPageStack(QStackedWidget):
@@ -3755,13 +3779,13 @@ class QueueRow(QWidget):
super().__init__(parent)
self.setObjectName("ReceptionQueueRow")
self._selected = False
self.setFixedHeight(104)
self.setFixedHeight(82)
self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, False)
layout = QVBoxLayout(self)
layout.setContentsMargins(20, 17, 16, 17)
layout.setSpacing(10)
layout.setContentsMargins(14, 12, 12, 12)
layout.setSpacing(8)
top = QHBoxLayout()
top.setSpacing(14)
top.setSpacing(8)
name = QLabel(
display_text(first_value(record, "patient_name", "name", default="未命名患者"))
)
@@ -3809,23 +3833,27 @@ class QueueRow(QWidget):
layout.addLayout(top)
bottom = QHBoxLayout()
bottom.setSpacing(8)
subline = QLabel(_queue_condition_summary(record))
summary = _queue_condition_summary(record)
subline = QLabel("" if summary == "暂无病情摘要" else summary)
subline.setToolTip(summary if summary != "暂无病情摘要" else "")
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, ""))
drop.setVisible(metric not in (None, "") and _is_numeric_reading(metric))
self.glucose_drop = drop
bottom.addWidget(drop, 0, Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
metric_label = QLabel(
f"{display_text(metric)} mmol/L" if metric not in (None, "") else "",
(_reading_text(metric, "mmol/L") if _is_numeric_reading(metric) else "血糖有描述")
if metric not in (None, "") else "",
self,
)
metric_label.setObjectName("ReceptionQueueMetric")
tone = _glucose_tone(metric)
tone = _glucose_tone(metric) if _is_numeric_reading(metric) else "description"
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)
@@ -4075,7 +4103,7 @@ class ReceptionPage(QWidget):
super().__init__(parent)
self.setObjectName("ReceptionPage")
self.setStyleSheet(
RECEPTION_QSS.replace("$body_family", body_family())
(RECEPTION_QSS + RECEPTION_WORKSPACE_QSS).replace("$body_family", body_family())
.replace("$heading_family", heading_family())
.replace("$number_family", number_family())
)
@@ -4175,7 +4203,7 @@ class ReceptionPage(QWidget):
)
root = QVBoxLayout(self)
root.setContentsMargins(11, 16, 11, 20)
root.setContentsMargins(12, 16, 12, 12)
root.setSpacing(0)
splitter = QSplitter(Qt.Orientation.Horizontal)
@@ -4186,8 +4214,8 @@ class ReceptionPage(QWidget):
splitter.addWidget(detail_panel)
splitter.setStretchFactor(0, 0)
splitter.setStretchFactor(1, 1)
splitter.setHandleWidth(10)
splitter.setSizes([399, 1072])
splitter.setHandleWidth(12)
splitter.setSizes([286, 1185])
root.addWidget(splitter, 1)
self.poll_timer = QTimer(self)
@@ -4204,7 +4232,7 @@ class ReceptionPage(QWidget):
super().resizeEvent(event)
panel = getattr(self, "queue_panel", None)
if panel is not None:
width = 340 if self.width() < 1000 else 399
width = 272 if self.width() < 1100 else 286
if panel.minimumWidth() != width:
panel.setFixedWidth(width)
@@ -4220,9 +4248,9 @@ class ReceptionPage(QWidget):
panel = QFrame()
panel.setObjectName("ReceptionQueuePanel")
self.queue_panel = panel
panel.setFixedWidth(399)
panel.setFixedWidth(286)
layout = QVBoxLayout(panel)
layout.setContentsMargins(14, 14, 12, 14)
layout.setContentsMargins(10, 14, 10, 10)
layout.setSpacing(10)
header = QWidget(panel)
@@ -4274,7 +4302,7 @@ class ReceptionPage(QWidget):
search_row.addWidget(self.search_edit, 1)
filter_layout.addLayout(search_row)
filter_row = QHBoxLayout()
filter_row = QGridLayout()
filter_row.setSpacing(6)
for status, label in ((None, "全部"), (1, "待接诊"), (2, "问诊中"), (3, "已完成")):
button = QPushButton(label, self.queue_filter_panel)
@@ -4285,7 +4313,8 @@ class ReceptionPage(QWidget):
lambda _checked=False, value=status: self._set_queue_filter(value)
)
self._queue_filter_buttons[status] = button
filter_row.addWidget(button, 1)
position = len(self._queue_filter_buttons) - 1
filter_row.addWidget(button, position // 2, position % 2)
self._queue_filter_buttons[1].setChecked(True)
filter_layout.addLayout(filter_row)
layout.addWidget(self.queue_filter_panel)
@@ -4329,7 +4358,7 @@ class ReceptionPage(QWidget):
def _build_detail_panel(self) -> QWidget:
panel = QFrame()
panel.setObjectName("ReceptionDetailPanel")
panel.setMinimumWidth(430)
panel.setMinimumWidth(390)
panel_layout = QVBoxLayout(panel)
panel_layout.setContentsMargins(0, 0, 0, 0)
panel_layout.setSpacing(0)
@@ -4345,7 +4374,7 @@ class ReceptionPage(QWidget):
scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
scroll.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded)
content = QWidget(scroll)
content.setMinimumWidth(390)
content.setMinimumWidth(0)
content.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred)
detail_layout = QVBoxLayout(content)
detail_layout.setContentsMargins(0, 0, 0, 0)
@@ -4353,9 +4382,9 @@ class ReceptionPage(QWidget):
hero = _ReceptionHero(content)
hero.setObjectName("ReceptionHero")
hero.setMinimumHeight(112)
hero.setMinimumHeight(96)
hero_layout = QVBoxLayout(hero)
hero_layout.setContentsMargins(16, 22, 16, 22)
hero_layout.setContentsMargins(18, 16, 18, 16)
hero_layout.setSpacing(4)
self.detail_banner = MessageBanner(parent=hero)
hero_layout.addWidget(self.detail_banner)
@@ -4368,7 +4397,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(64, 64)
self.patient_avatar_label.setFixedSize(48, 48)
identity_head.addWidget(self.patient_avatar_label)
identity = QVBoxLayout()
identity.setSpacing(8)
@@ -4394,8 +4423,18 @@ class ReceptionPage(QWidget):
actions.setContentsMargins(0, 0, 0, 0)
actions.setSpacing(14)
actions.addStretch(1)
patient_head.addLayout(actions)
patient_head.setAlignment(actions, Qt.AlignmentFlag.AlignBottom)
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)
self.complete_button = _ReceptionCompleteButton(hero)
self.complete_button.clicked.connect(self._complete_appointment)
@@ -4414,7 +4453,9 @@ 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 = QPushButton(hero)
self.more_button.setIcon(icons.icon("more", "#5D6B80", 16))
self.more_button.setIconSize(QSize(16, 16))
self.more_button.setToolTip("更多操作")
self.more_button.setAccessibleName("更多操作")
self.more_button.setObjectName("ReceptionMoreButton")
@@ -4458,7 +4499,7 @@ class ReceptionPage(QWidget):
clinical_card = QFrame(content)
clinical_card.setObjectName("ReceptionClinicalCard")
clinical_card.setMinimumHeight(526)
clinical_card.setMinimumHeight(0)
clinical_card.setSizePolicy(
QSizePolicy.Policy.Expanding,
QSizePolicy.Policy.Minimum,
@@ -4496,15 +4537,18 @@ class ReceptionPage(QWidget):
QSizePolicy.Policy.Minimum,
)
consultation_layout = QHBoxLayout(consultation_page)
consultation_layout.setContentsMargins(12, 22, 12, 13)
consultation_layout.setContentsMargins(18, 18, 18, 18)
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(8, 4, 18, 0)
history_layout.setSpacing(15)
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)
self.case_labels: dict[str, QLabel] = {}
def add_case_field(
@@ -4514,7 +4558,8 @@ class ReceptionPage(QWidget):
*,
stacked: bool = False,
) -> None:
field = QWidget(history_card)
field = QFrame(history_card)
field.setObjectName("ReceptionCaseField")
if stacked:
field_layout = QVBoxLayout(field)
field_layout.setContentsMargins(0, 0, 0, 0)
@@ -4541,8 +4586,10 @@ 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, "present", "现病史", stacked=True)
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, "past", "既往史")
add_case_field(history_layout, "family", "家族史")
add_case_field(history_layout, "allergy", "过敏史")
@@ -4580,20 +4627,35 @@ class ReceptionPage(QWidget):
add_case_field(history_layout, "diet", "饮食习惯")
history_layout.addStretch(1)
consultation_layout.addWidget(history_card, 42)
consultation_layout.addWidget(history_card, 1)
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(152)
vitals_card.setMinimumHeight(0)
vitals_card.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum)
vitals_layout = QVBoxLayout(vitals_card)
vitals_layout.setContentsMargins(12, 4, 2, 18)
vitals_layout.setSpacing(12)
vitals_layout.setContentsMargins(14, 14, 14, 14)
vitals_layout.setSpacing(8)
vitals_title = QLabel("生命体征", vitals_card)
vitals_title.setProperty("receptionBlockTitle", True)
vitals_layout.addWidget(vitals_title)
@@ -4647,7 +4709,9 @@ class ReceptionPage(QWidget):
cell_layout.addStretch(1)
self.vital_labels[key] = value_label
self.vital_unit_labels[key] = unit_label
vitals_grid.addWidget(cell, 0, column)
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.setColumnStretch(column, 1)
vitals_layout.addLayout(vitals_grid)
right_layout.addWidget(vitals_card)
@@ -4655,12 +4719,15 @@ class ReceptionPage(QWidget):
labs_card = QFrame(right_clinical)
labs_card.setObjectName("ReceptionLabsCard")
labs_layout = QVBoxLayout(labs_card)
labs_layout.setContentsMargins(12, 3, 2, 0)
labs_layout.setContentsMargins(14, 14, 14, 14)
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)
@@ -4680,7 +4747,7 @@ class ReceptionPage(QWidget):
cell = QFrame(labs_card)
cell.setObjectName("ReceptionLabCell")
cell_layout = QVBoxLayout(cell)
cell_layout.setContentsMargins(10, 10, 8, 6)
cell_layout.setContentsMargins(0, 6, 0, 8)
cell_layout.setSpacing(6)
caption_label = QLabel(caption, cell)
caption_label.setProperty("receptionMetricCaption", True)
@@ -4697,13 +4764,20 @@ class ReceptionPage(QWidget):
cell_layout.addStretch(1)
self.lab_labels[key] = value_label
self.lab_state_labels[key] = state_label
row, column = divmod(index, 4)
self.lab_cells[key] = cell
row, column = divmod(index, 2)
labs_grid.addWidget(cell, row, column)
labs_grid.setRowStretch(row, 1)
labs_grid.setColumnStretch(column, 1)
labs_layout.addLayout(labs_grid, 1)
right_layout.addWidget(labs_card, 1)
consultation_layout.addWidget(right_clinical, 58)
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)
self.clinical_pages.addWidget(consultation_page)
appointment_card, self.appointment_labels = self._field_card(
@@ -5007,7 +5081,6 @@ 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)
@@ -5287,7 +5360,7 @@ class ReceptionPage(QWidget):
assistant_header.addStretch(1)
assistant_layout.addLayout(assistant_header)
assistant_hint = QLabel(
"您好,我是 AI 问诊助手,有什么可以帮助您了解患者情况的吗?",
"结合当前患者资料,快速核对问诊要点。",
assistant_card,
)
assistant_hint.setObjectName("ReceptionAiAssistantHint")
@@ -5301,8 +5374,10 @@ class ReceptionPage(QWidget):
self.ai_prompt_buttons: list[QPushButton] = []
def prompt_button(label: str) -> QPushButton:
def prompt_button(label: str, question: str) -> QPushButton:
button = QPushButton(label, assistant_card)
button.setToolTip(question)
button.setAccessibleName(question)
button.setProperty("receptionAiPrompt", True)
button.setMinimumWidth(0)
button.setSizePolicy(
@@ -5310,20 +5385,20 @@ class ReceptionPage(QWidget):
QSizePolicy.Policy.Fixed,
)
button.clicked.connect(
lambda _checked=False, prompt=label: self._open_ai_report_for_prompt(prompt)
lambda _checked=False, prompt=question: self._open_ai_report_for_prompt(prompt)
)
self.ai_prompt_buttons.append(button)
return button
prompt_host = _AiFlowHost(assistant_card, horizontal_spacing=8, vertical_spacing=8)
prompt_host = _AiFlowHost(assistant_card, horizontal_spacing=6, vertical_spacing=6)
prompt_host.setObjectName("ReceptionAiPrompts")
for label in (
"基于当前病史,下一步检查建议?",
"该患者的用药调整建议?",
"糖尿病教育要点有哪些?",
"并发症筛查建议?",
for label, question in (
("检查建议", "基于当前病史,下一步检查建议?"),
("用药核对", "该患者的用药调整建议?"),
("健康教育", "糖尿病教育要点有哪些?"),
("并发症筛查", "并发症筛查建议?"),
):
prompt_host.flow.addWidget(prompt_button(label))
prompt_host.flow.addWidget(prompt_button(label, question))
assistant_layout.addWidget(prompt_host)
assistant_layout.addStretch(1)
@@ -5341,17 +5416,65 @@ class ReceptionPage(QWidget):
assistant_input_row.addWidget(self.ai_send_button)
assistant_input_host.hide()
ai_row.addWidget(assistant_card, 23)
detail_layout.addWidget(ai_panels)
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)
self.detail_tabs.currentChanged.connect(self._detail_tab_changed)
self._detail_tab_changed(0)
scroll.setWidget(content)
self.detail_stack.addWidget(scroll)
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)
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
@@ -7029,7 +7152,7 @@ class ReceptionPage(QWidget):
def _add_queue_row(self, record: Any) -> None:
item = QListWidgetItem()
item.setData(Qt.ItemDataRole.UserRole, record)
item.setSizeHint(QSize(0, 120))
item.setSizeHint(QSize(0, 88))
self.queue_list.addItem(item)
self.queue_list.setItemWidget(item, QueueRow(record))
@@ -7334,6 +7457,7 @@ 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
@@ -7885,9 +8009,14 @@ class ReceptionPage(QWidget):
)
)
)
self.appointment_labels["assistant"].setText(
display_text(first_value(appointment, "assistant_name"))
)
# 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["type"].setText(
appointment_type_description(appointment_type_value(appointment))
)
@@ -7990,6 +8119,12 @@ 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,
@@ -8080,6 +8215,15 @@ 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 = {
@@ -8307,8 +8451,7 @@ 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(":: ")
if "mmol/l" not in blood_sugar_text.lower():
blood_sugar_text = f"{blood_sugar_text} mmol/L"
blood_sugar_text = _reading_text(blood_sugar_text, "mmol/L")
case_items["空腹血糖"] = blood_sugar_text
lines.append(f"空腹血糖:{blood_sugar_text}")
@@ -8367,6 +8510,10 @@ 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,
@@ -8376,6 +8523,10 @@ 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": (
@@ -8414,17 +8565,17 @@ class ReceptionPage(QWidget):
health_lines: list[str] = []
for key, (value_keys, unit, status_keys) in lab_definitions.items():
value = case_value(*value_keys)
text = display_text(value)
if value not in (None, "") and unit.lower() not in str(value).lower():
text = f"{text} {unit}"
numeric = _is_numeric_reading(value)
text = _reading_text(value, 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)
computed = _lab_status_for_value(key, value) if numeric else None
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, ""):
if status_value not in (None, "") and numeric:
status_text = display_text(status_value)
if status_text.strip().lower() in {"正常", "normal", "0", "阴性"}:
status_text = "正常"
@@ -8459,6 +8610,7 @@ 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 = (
@@ -8821,11 +8973,15 @@ 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 "尚未填写病例信息"
@@ -8876,6 +9032,8 @@ 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 {}, {})
@@ -8886,6 +9044,10 @@ 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")
@@ -8914,6 +9076,8 @@ 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
@@ -2,11 +2,11 @@
from __future__ import annotations
from collections.abc import Iterable
from collections.abc import Iterable, Sequence
from string import Template
from typing import Any
from PySide6.QtCore import QModelIndex, QRectF, QSize, Qt
from PySide6.QtCore import QEvent, QModelIndex, QRectF, QSize, Qt, QTimer
from PySide6.QtGui import QColor, QFont, QFontMetrics, QIcon, QPainter
from PySide6.QtWidgets import (
QComboBox,
@@ -18,7 +18,7 @@ from PySide6.QtWidgets import (
)
from .reception_style import body_family, heading_family
from .widgets import SortableTable, first_value
from .widgets import SortableTable, TableColumn, first_value
def library_stylesheet() -> str:
@@ -58,7 +58,58 @@ class LibraryComboBox(QComboBox):
class LibraryTable(SortableTable):
"""Repaint existing action widgets and restore selection by template ID."""
"""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)
@@ -1,15 +1,10 @@
"""Palette and real font families for the approved reception page only."""
"""Shared palette and typography for the technology-blue workstation pages."""
from __future__ import annotations
import os
import sys
from pathlib import Path
from PySide6.QtGui import QFontDatabase
from PySide6.QtWidgets import QApplication
from doctor_workstation.resources import resource_path
from .theme import _register_preferred_cjk_fonts
TECH_BLUE = {
"accent": "#1769E8",
@@ -30,7 +25,7 @@ TECH_BLUE = {
def _families() -> dict[str, str]:
"""Resolve after Qt starts; font registration does not change its theme."""
"""Use the application face for Chinese, Latin text and numbers alike."""
app = QApplication.instance()
if app is None:
@@ -39,68 +34,28 @@ def _families() -> dict[str, str]:
if cached is not None:
return cached
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,
}
# 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)
app._reception_font_families = resolved
return resolved
def body_family() -> str:
"""Regular Chinese body copy; YaHei UI has no genuine Medium face."""
"""Shared reading face for controls and table cells."""
return _families()["body"]
def heading_family() -> str:
"""Bundled Noto Sans SC supplies genuine Medium and Semibold faces."""
"""The same reading face, with genuine Medium and Semibold weights."""
return _families()["heading"]
def number_family() -> str:
"""Segoe UI supplies Regular and Semibold for numeric labels."""
"""Keep numbers and adjacent Chinese text in the same family."""
return _families()["number"]
@@ -0,0 +1,408 @@
"""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 #E5ECF6;
border-radius: 8px;
}
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 #E5ECF6;
border-radius: 8px;
}
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: 8px;
border-top-right-radius: 8px;
}
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 #E5ECF6;
border-radius: 8px;
}
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 #DCE5F0;
border-radius: 8px;
}
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;
}
"""
+31 -25
View File
@@ -72,7 +72,7 @@ from .pages import (
ReceptionPage,
)
from .reception_style import TECH_BLUE, body_family, heading_family, number_family
from .theme import COLORS, crisp_pixmap
from .theme import COLORS, TYPE, crisp_pixmap
from .widgets import (
EmptyState,
StatusBadge,
@@ -506,13 +506,14 @@ class _AssistantRobot(QWidget):
painter.setPen(Qt.PenStyle.NoPen)
if self.property("receptionTechBlue"):
painter.setBrush(QColor(TECH_BLUE["accent"]))
painter.drawRoundedRect(QRectF(7, 7, 44, 44), 6, 6)
tile = QRectF(6, 6, 36, 36)
painter.drawRoundedRect(tile, 6, 6)
painter.setPen(QColor(TECH_BLUE["surface"]))
font = QFont(number_family())
font.setPixelSize(21)
font.setPixelSize(18)
font.setWeight(QFont.Weight.DemiBold)
painter.setFont(font)
painter.drawText(QRectF(7, 7, 44, 44), Qt.AlignmentFlag.AlignCenter, "AI")
painter.drawText(tile, Qt.AlignmentFlag.AlignCenter, "AI")
return
painter.setBrush(QColor(COLORS["indigo_pale"]))
painter.drawEllipse(QRectF(1, 1, 54, 54))
@@ -562,14 +563,12 @@ class _AssistantStatus(QLabel):
color = QColor(online_color if self._online else "#EC5266")
painter.setPen(Qt.PenStyle.NoPen)
painter.setBrush(color)
diameter = 9 if reception else 6
diameter = 6
painter.drawEllipse(QRectF(1, (self.height() - diameter) / 2, diameter, diameter))
painter.setPen(color)
font = QFont(self.font())
font.setPixelSize(13 if reception else 10)
painter.setFont(font)
painter.setFont(self.font())
painter.drawText(
QRectF(17 if reception else 12, 0, self.width() - (17 if reception else 12), self.height()),
QRectF(12, 0, self.width() - 12, self.height()),
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
self.text(),
)
@@ -1085,7 +1084,7 @@ class ShellWindow(QMainWindow):
font-weight: 600;
}
QLabel#ShellAssistantName { color: #1A1C1F; font-size: 13px; font-weight: 500; }
QLabel#ShellAssistantStatus { color: #287B65; font-size: 13px; }
QLabel#ShellAssistantStatus { color: #287B65; font-size: 12px; }
QPushButton#ShellAssistantButton {
min-height: 34px;
color: #FFFFFF;
@@ -1592,15 +1591,16 @@ 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(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.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.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(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.assistant_status.setFixedHeight(18)
self.assistant_button.setFixedHeight(36 if active else 34)
self.upload_settings_button.setFixedHeight(52 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 "设置 ›")
@@ -1686,15 +1686,15 @@ class ShellWindow(QMainWindow):
}}
QLabel#ShellBrandName {{
font-family: "{heading_family()}"; font-weight: 600;
color: {TECH_BLUE['heading']}; font-size: 18px;
color: {TECH_BLUE['heading']}; font-size: {TYPE['fs_section']};
}}
QLabel#ShellBrandSubtitle {{ color: {TECH_BLUE['text']}; font-size: 13px; }}
QLabel#ShellBrandSubtitle {{ color: {TECH_BLUE['muted']}; font-size: {TYPE['fs_small']}; }}
QPushButton#ShellNavButton {{
font-family: "{body_family()}"; font-weight: 400;
min-height: 52px; max-height: 52px;
min-height: 44px; max-height: 44px;
border: 0; border-left: 5px solid transparent;
border-radius: 6px;
padding: 0 16px; font-size: 15px;
padding: 0 16px; font-size: {TYPE['fs_body']};
color: {TECH_BLUE['text']};
}}
QPushButton#ShellNavButton:checked,
@@ -1715,13 +1715,19 @@ class ShellWindow(QMainWindow):
border: 1px solid {_RECEPTION_CHROME_LINE};
}}
QLabel#ShellAssistantName {{
font-family: "{heading_family()}"; font-weight: 500; font-size: 16px;
font-family: "{heading_family()}"; font-weight: 500; font-size: {TYPE['fs_body']};
}}
QLabel#ShellAssistantStatus {{
font-size: {TYPE['fs_small']};
}}
QPushButton#ShellAssistantButton, QPushButton#ShellSettingsButton {{
font-family: "{body_family()}"; font-weight: 400; font-size: 15px;
font-family: "{body_family()}"; font-weight: 400; font-size: {TYPE['fs_body']};
}}
QPushButton#ShellAssistantButton {{ border-radius: 6px; }}
QPushButton#ShellSettingsButton {{ text-align: left; padding: 0 32px; }}
QPushButton#ShellSettingsButton {{
min-height: 50px; max-height: 50px;
text-align: left; padding: 0 32px;
}}
QPushButton#ShellAssistantButton:focus {{
border: 2px solid {TECH_BLUE['focus']};
}}
@@ -1735,12 +1741,12 @@ class ShellWindow(QMainWindow):
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: 13px;
font-family: "{number_family()}"; font-size: {TYPE['fs_small']};
padding: 4px 9px; border-radius: 4px;
border: 1px solid {_RECEPTION_CHROME_LINE};
}}
QLineEdit#ShellGlobalSearchInput {{
color: {TECH_BLUE['text']}; font-size: 15px;
color: {TECH_BLUE['text']}; font-size: {TYPE['fs_body']};
min-height: 40px; max-height: 40px;
}}
QPushButton#ShellAiEntry:pressed {{ background: {TECH_BLUE['selection']}; }}
+4 -3
View File
@@ -85,10 +85,11 @@ COLORS = {
# --- Type scale -----------------------------------------------------------
# Six steps, tuned for 简体中文 at Windows 100%–150% scaling. CJK glyphs carry
# Seven 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
@@ -1241,7 +1242,7 @@ def _block_is_all_bold(block: Any) -> bool:
return seen
def apply_reading_rhythm(browser: QTextBrowser, *, role: str) -> None:
def apply_reading_rhythm(browser: QTextBrowser, *, role: str, start_position: int = 0) -> None:
"""Give a parsed reply real hierarchy and breathing room.
Model answers are long "section heading + two levels of bullets" documents.
@@ -1259,7 +1260,7 @@ def apply_reading_rhythm(browser: QTextBrowser, *, role: str) -> None:
cursor = QTextCursor(document)
cursor.beginEditBlock()
try:
block = document.begin()
block = document.findBlock(start_position)
while block.isValid():
heading = block.blockFormat().headingLevel()
text_list = block.textList()
@@ -0,0 +1,446 @@
"""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 "&quot;" 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()
@@ -0,0 +1,276 @@
"""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)
+322
View File
@@ -0,0 +1,322 @@
"""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()
+221
View File
@@ -0,0 +1,221 @@
"""Cancellation interrupts idle I/O and uses an independent control request."""
from __future__ import annotations
import asyncio
import json
import socket
from concurrent.futures import ThreadPoolExecutor
from threading import Event, Thread, get_ident
from uuid import uuid4
import httpx
import pytest
from doctor_workstation.services.api_client import ApiClient
from doctor_workstation.services.repository import RemoteDoctorRepository
@pytest.mark.parametrize("stage", ["headers", "body"])
def test_cancel_interrupts_idle_read_and_cleans_up_on_owning_loop(stage):
entered, cancelled = Event(), Event()
body_threads, closed_threads = [], []
class IdleStream(httpx.AsyncByteStream):
async def __aiter__(self):
body_threads.append(get_ident())
entered.set()
await asyncio.sleep(30)
yield b"event: done\ndata: {}\n\n"
async def aclose(self):
closed_threads.append(get_ident())
async def handler(request):
if stage == "headers":
entered.set()
await asyncio.sleep(30)
return httpx.Response(200, headers={"content-type": "text/event-stream"}, stream=IdleStream())
client = ApiClient("https://example.test", transport=httpx.MockTransport(handler))
with ThreadPoolExecutor(max_workers=1) as executor:
future = executor.submit(lambda: list(client.post_event_stream(
"tcm.diagnosis/aiAssistantStream", {"id": 501}, cancelled=cancelled.is_set,
)))
assert entered.wait(2)
cancelled.set()
assert future.result(timeout=0.8) == []
if stage == "body":
assert body_threads == closed_threads
client.close()
@pytest.mark.parametrize("headers_sent", [False, True])
def test_default_transport_closes_idle_local_socket_without_another_line(headers_sent):
entered, disconnected, cancelled = Event(), Event(), Event()
listener = socket.socket()
listener.bind(("127.0.0.1", 0))
listener.listen(1)
listener.settimeout(3)
def serve():
try:
connection, _ = listener.accept()
with connection:
connection.settimeout(3)
request = b""
while b"\r\n\r\n" not in request:
request += connection.recv(4096)
header, body = request.split(b"\r\n\r\n", 1)
length = next(int(line.split(b":", 1)[1]) for line in header.split(b"\r\n") if line.lower().startswith(b"content-length:"))
while len(body) < length:
body += connection.recv(4096)
if headers_sent:
connection.sendall(b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\n")
entered.set()
if connection.recv(1) == b"":
disconnected.set()
finally:
listener.close()
thread = Thread(target=serve, daemon=True)
thread.start()
with ApiClient(f"http://127.0.0.1:{listener.getsockname()[1]}") as client, ThreadPoolExecutor(max_workers=1) as executor:
future = executor.submit(lambda: list(client.post_event_stream(
"tcm.diagnosis/aiAssistantStream", {"id": 501}, cancelled=cancelled.is_set,
)))
try:
assert entered.wait(2)
cancelled.set()
assert future.result(timeout=0.8) == []
assert disconnected.wait(0.8)
finally:
cancelled.set()
thread.join(timeout=1)
assert not thread.is_alive()
def test_cancel_control_post_bypasses_busy_short_request_pool(monkeypatch):
from doctor_workstation.services import api_client as module
entered, release = Event(), Event()
created = []
class Client:
def __init__(self, **options):
created.append(self)
def request(self, *args, **kwargs):
entered.set()
assert release.wait(2)
return httpx.Response(200, json={"code": 1, "data": {}})
def post(self, url, **kwargs):
return httpx.Response(200, json={"code": 1, "data": {"cancel_requested": True}})
def close(self):
pass
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
monkeypatch.setattr(module.httpx, "Client", Client)
client = ApiClient("https://example.test", max_parallel_requests=1)
with ThreadPoolExecutor(max_workers=1) as executor:
future = executor.submit(client.get, "synthetic/busy")
try:
assert entered.wait(1)
assert client.post_independent("tcm.diagnosis/cancelAiAssistant", {"id": 501}) == {"cancel_requested": True}
assert len(created) == 2
finally:
release.set()
future.result(timeout=1)
client.close()
def test_stream_progress_and_cancel_preserve_same_request_identity():
requests = []
request_id = str(uuid4())
def handler(request):
requests.append(request)
if request.url.path.endswith("cancelAiAssistant"):
return httpx.Response(200, json={"code": 1, "data": {"cancel_requested": True, "upstream_stop_confirmed": False}})
return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=(
'event: progress\ndata: {"phase":"attachments","items":[{"kind":"image","label":"图片附件1","status":"submitted"}],"attachment_count":1}\n\n'
'event: done\ndata: {}\n\n'
))
with ApiClient("https://example.test", transport=httpx.MockTransport(handler)) as client:
repository = RemoteDoctorRepository(client)
events = list(repository.stream_diagnosis_ai(501, "合成问题", request_id=request_id))
result = repository.cancel_diagnosis_ai(501, request_id)
assert events[0]["event"] == "progress" and events[0]["items"][0]["status"] == "submitted"
assert json.loads(requests[0].content)["request_id"] == request_id
assert json.loads(requests[1].content) == {"id": 501, "request_id": request_id}
assert result["cancel_requested"] and not result["upstream_stop_confirmed"]
def test_async_bridge_batches_thousands_of_frames_without_per_delta_tasks(monkeypatch):
from doctor_workstation.services import api_client as module
calls = {"tasks": 0, "loop_runs": 0}
new_event_loop = asyncio.new_event_loop
def counted_loop():
loop = new_event_loop()
create_task, run_forever = loop.create_task, loop.run_forever
def task(*args, **kwargs):
calls["tasks"] += 1
return create_task(*args, **kwargs)
def run():
calls["loop_runs"] += 1
return run_forever()
loop.create_task, loop.run_forever = task, run
return loop
monkeypatch.setattr(module.asyncio, "new_event_loop", counted_loop)
chunks = [f"片段{index}🩺" for index in range(6000)]
content = "".join("event: delta\ndata: " + json.dumps({"text": text}) + "\n\n" for text in chunks)
content += 'event: done\ndata: {}\n\n'
transport = httpx.MockTransport(lambda request: httpx.Response(
200, headers={"content-type": "text/event-stream"}, text=content,
))
with ApiClient("https://example.test", transport=transport) as client:
events = list(client.post_event_stream("synthetic/stream", {}, cancelled=lambda: False))
assert [event["data"]["text"] for event in events[:-1]] == chunks
assert events[-1]["event"] == "done"
assert calls["tasks"] <= 8
assert calls["loop_runs"] <= 40
@pytest.mark.parametrize("ending", ["eof", "error"])
def test_async_batch_drains_queued_tail_before_eof_or_error(ending):
class TailStream(httpx.AsyncByteStream):
async def __aiter__(self):
yield b'event: delta\ndata: {"text":"first"}\n\nevent: delta\ndata: {"text":"tail"}\n\n'
if ending == "error":
raise httpx.ReadError("synthetic read failure")
# A valid final SSE frame need not end with a blank line.
yield b'event: delta\ndata: {"text":"last"}'
transport = httpx.MockTransport(lambda request: httpx.Response(
200, headers={"content-type": "text/event-stream"}, stream=TailStream(),
))
with ApiClient("https://example.test", transport=transport) as client:
stream = client.post_event_stream("synthetic/stream", {}, cancelled=lambda: False)
assert next(stream)["data"]["text"] == "first"
assert next(stream)["data"]["text"] == "tail"
if ending == "error":
from doctor_workstation.core.errors import ApiTransportError
with pytest.raises(ApiTransportError, match="stream failed"):
next(stream)
else:
assert next(stream)["data"]["text"] == "last"
assert list(stream) == []
@@ -0,0 +1,624 @@
"""Strict approved-grapheme playback in real Qt; every datum is synthetic.
Controlled timeout signals bound long-input tests. A separate test observes
physical single-shot timers and actual viewport paints, without model/network IO.
"""
from __future__ import annotations
import json
import os
from pathlib import Path
from time import monotonic, perf_counter
from types import SimpleNamespace
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from PySide6.QtCore import QCoreApplication, QEvent, QObject, Qt, QThreadPool, QTimer
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication, QScrollArea
from shiboken6 import isValid
from doctor_workstation.core import PermissionSet
from doctor_workstation.ui.dialogs import ai_consult as module
from doctor_workstation.ui.dialogs.ai_consult_charts import GlucoseReportCard
class OfflineWorker(module._AiStreamWorker):
def cancel(self):
self._cancelled.set()
return self.take_events()
@pytest.fixture(scope="module")
def application():
return QApplication.instance() or QApplication([])
@pytest.fixture
def bubbles(application):
resources = []
def create():
host = QScrollArea()
host.resize(760, 480)
host.setWidgetResizable(True)
bubble = module._ChatBubble(role="ai", text="正在等待合成测试正文")
host.setWidget(bubble)
host.show()
application.processEvents()
resources.append((host, bubble))
return bubble
yield create
for host, bubble in resources:
bubble.stop_stream_presentation()
assert not bubble._presentation_timer.isActive()
host.close()
host.deleteLater()
QCoreApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete)
application.processEvents()
@pytest.fixture
def dialogs(application, monkeypatch):
resources = []
monkeypatch.setattr(module, "_AiStreamWorker", OfflineWorker)
monkeypatch.setattr(module, "QThreadPool", SimpleNamespace(
globalInstance=lambda: SimpleNamespace(start=lambda _: None)))
def create():
dialog = module.AiConsultDialog(object(), 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)
return dialog
yield create
for dialog in resources:
dialog.close()
assert not any(timer.isActive() for timer in dialog.findChildren(QTimer))
dialog.deleteLater()
assert QThreadPool.globalInstance().waitForDone(1000)
QCoreApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete)
application.processEvents()
def event(dialog, kind, **values):
dialog._stream_event(dialog._generation, dialog._stream_generation, {"event": kind, **values})
def tick(bubble):
"""Deliver exactly one real Qt timeout signal, without a wall-clock wait."""
bubble._presentation_timer.stop()
bubble._presentation_timer.timeout.emit()
def drain(bubble, limit=1000):
steps = 0
while bubble._presentation_timer.isActive() and steps < limit:
tick(bubble)
steps += 1
assert not bubble._presentation_timer.isActive(), "controlled playback exceeded finite bound"
return steps
def wait_until(predicate, seconds=2):
deadline = monotonic() + seconds
while not predicate() and monotonic() < deadline:
QTest.qWait(5)
assert predicate(), "finite Qt wait expired"
def report():
return ("## 合成血糖记录\n- 空腹血糖 6.2 mmol/L,仅一条记录不能说明长期趋势。\n"
+ "合成来源原文应保持完整,未记录的项目不能认定正常。" * 4
+ "\n\n## 合成复核计划\n- 请结合日期和现有信息复核,不据此增加用药。\n- 合成完整结尾。")
@pytest.mark.parametrize("length", [1, 2, 24, 25, 2001, 11000])
def test_first_prefix_is_one_character_and_never_accelerates_for_backlog(bubbles, length):
bubble = bubbles()
answer = "甲" * length
frames = []
bubble.stream_frame_presented.connect(lambda: frames.append(bubble.body.toPlainText()))
bubble.queue_approved_stream_text(answer)
assert frames == ["甲"]
assert bubble._raw_payload == answer
assert bubble._presentation_timer.interval() == 24
assert bubble._presentation_timer.isSingleShot()
assert bubble._presentation_timer.timerType() == Qt.TimerType.PreciseTimer
for index in range(1, min(length, 100)):
tick(bubble)
assert frames[-1] == answer[:index + 1]
assert len(frames) == min(length, 100)
def test_later_idle_burst_backlog_and_done_each_wait_for_their_own_tick(bubbles):
bubble = bubbles()
frames = []
bubble.stream_frame_presented.connect(lambda: frames.append(bubble.body.toPlainText()))
bubble.queue_approved_stream_text("首")
assert frames == ["首"] and not bubble._presentation_timer.isActive()
answer = "首" + "后来逐字。" * 400
bubble.queue_approved_stream_text(answer[:200])
assert frames == ["首"]
tick(bubble)
assert frames[-1] == answer[:2]
bubble.queue_approved_stream_text(answer)
assert len(frames) == 2
finished = []
bubble.complete_stream_presentation(lambda: finished.append(True))
assert len(frames) == 2 and not finished
for index in range(2, 202):
tick(bubble)
assert frames[-1] == answer[:index + 1]
assert not finished and bubble._raw_payload == answer
@pytest.mark.parametrize("remaining", [1, 2, 23, 24, 25])
def test_done_has_no_same_turn_remaining_text_shortcut(bubbles, remaining):
bubble = bubbles()
answer = "甲" + "乙" * remaining
bubble.queue_approved_stream_text(answer)
finished = []
bubble.complete_stream_presentation(lambda: finished.append(bubble.body.toPlainText()))
assert bubble.body.toPlainText() == "甲" and not finished
for index in range(remaining):
tick(bubble)
assert bubble.body.toPlainText() == answer[:index + 2]
assert bool(finished) == (index == remaining - 1)
assert finished == [answer]
tick(bubble)
assert finished == [answer]
def test_whole_unicode_graphemes_are_visible_exact_prefixes(bubbles):
bubble = bubbles()
characters = ["医", "🩺", "e\u0301", "👩\u200d⚕️", "🇨🇳", "क्\u200dष", "\r\n", "尾"]
answer = "".join(characters)
frames = []
bubble.stream_frame_presented.connect(lambda: frames.append(bubble.body.toPlainText()))
bubble.queue_approved_stream_text(answer)
finished = []
bubble.complete_stream_presentation(lambda: finished.append(True))
assert len(frames) == 1
for _ in characters[1:]:
tick(bubble)
expected = ["".join(characters[:index + 1]).replace("\r\n", "\n")
for index in range(len(characters))]
assert frames == expected
assert bubble._raw_payload == answer
assert bubble._presentation_offset == len(answer)
assert finished == [True]
@pytest.mark.parametrize("prefix", ["", "医", "👨\u200d👩\u200d👧", "👩\u200d⚕️"])
@pytest.mark.parametrize("count", [1, 2, 3, 4, 5, 6, 7])
def test_regional_indicator_pairs_start_at_each_contiguous_run(bubbles, prefix, count):
bubble = bubbles()
regional = "🇨🇳🇺🇸🇯🇵🇬"[:count]
groups = ([prefix] if prefix else []) + [regional[i:i + 2] for i in range(0, count, 2)] + ["终"]
answer = "".join(groups)
seen = []
bubble.stream_frame_presented.connect(lambda: seen.append(bubble.body.toPlainText()))
bubble.queue_approved_stream_text(answer)
finished = []
bubble.complete_stream_presentation(lambda: finished.append(True))
assert seen == groups[:1]
for index in range(1, len(groups)):
tick(bubble)
assert seen[-1] == "".join(groups[:index + 1])
assert bool(finished) == (index == len(groups) - 1)
assert len(seen) == len(groups)
assert bubble._raw_payload == answer and finished == [True]
@pytest.mark.parametrize("groups", [
["👨\u200d👩\u200d👧", "🇨🇳", "中", "🇺🇸", "🇯", "终"],
["🇨", "中", "🇺🇸", "🇯🇵", "终"],
["👨\u200d👩\u200d👧", "🇨🇳\u0301", "终"],
["👨\u200d👩\u200d👧", "🇨🇳", "🇺\u0301", "终"],
])
def test_regional_run_normalization_retains_surrounding_graphemes(bubbles, groups):
bubble = bubbles()
answer = "".join(groups)
bubble.queue_approved_stream_text(answer)
assert bubble.body.toPlainText() == groups[0]
for index in range(1, len(groups)):
tick(bubble)
assert bubble.body.toPlainText() == "".join(groups[:index + 1])
assert not bubble._presentation_timer.isActive()
assert bubble._raw_payload == answer
@pytest.mark.parametrize("prefix", ["", "甲", "甲乙"])
def test_split_crlf_holds_trailing_cr_and_reveals_one_normalized_newline(bubbles, prefix):
bubble = bubbles()
initial = prefix + "\r"
bubble.queue_approved_stream_text(initial)
drain(bubble)
before = bubble.body.toPlainText()
assert bubble._presentation_offset == len(prefix)
assert bubble._raw_payload == initial
answer = initial + "\n终"
bubble.queue_approved_stream_text(answer)
finished = []
bubble.complete_stream_presentation(lambda: finished.append(True))
assert bubble.body.toPlainText() == before and not finished
tick(bubble)
assert bubble.body.toPlainText() == prefix + "\n"
assert bubble._presentation_offset == len(initial) + 1 and not finished
tick(bubble)
assert bubble.body.toPlainText() == prefix + "\n终"
assert bubble._raw_payload == answer and finished == [True]
@pytest.mark.parametrize("prefix", ["", "甲", "甲乙丙丁"])
def test_true_terminal_cr_finishes_on_its_own_tick_even_with_backlog(bubbles, prefix):
bubble = bubbles()
answer = prefix + "\r"
bubble.queue_approved_stream_text(answer)
before = bubble.body.toPlainText()
finished = []
bubble.complete_stream_presentation(lambda: finished.append(bubble.body.toPlainText()))
assert bubble.body.toPlainText() == before and not finished
drain(bubble)
assert bubble.body.toPlainText() == prefix + "\n"
assert finished == [prefix + "\n"]
assert bubble._raw_payload == answer and bubble._presentation_offset == len(answer)
def test_held_cr_before_non_lf_is_not_dropped_or_joined_to_next_character(bubbles):
bubble = bubbles()
bubble.queue_approved_stream_text("甲\r")
assert bubble.body.toPlainText() == "甲"
bubble.queue_approved_stream_text("甲\r乙")
assert bubble.body.toPlainText() == "甲"
tick(bubble)
assert bubble.body.toPlainText() == "甲\n"
tick(bubble)
assert bubble.body.toPlainText() == "甲\n乙"
assert bubble._raw_payload == "甲\r乙"
@pytest.mark.parametrize("initial_count", [1, 3, 5])
def test_later_regional_indicator_extends_odd_run_after_family_on_later_tick(bubbles, initial_count):
bubble = bubbles()
family = "👨\u200d👩\u200d👧"
regional = "🇨🇳🇺🇸🇯🇵"
initial = family + regional[:initial_count]
bubble.queue_approved_stream_text(initial)
drain(bubble)
assert bubble.body.toPlainText() == initial
answer = family + regional[:initial_count + 1] + "终"
bubble.queue_approved_stream_text(answer)
assert bubble.body.toPlainText() == initial
tick(bubble)
assert bubble.body.toPlainText() == answer[:-1]
tick(bubble)
assert bubble.body.toPlainText() == answer
assert bubble._raw_payload == answer
@pytest.mark.parametrize("initial,joined", [
("e", "e\u0301"),
("👩", "👩\u200d⚕️"),
("🇨", "🇨🇳"),
("\ud83d", "\ud83d\udc69"),
])
def test_future_chunk_may_extend_visible_cluster_without_losing_raw_text(bubbles, initial, joined):
bubble = bubbles()
bubble.queue_approved_stream_text(initial)
before = bubble.body.toPlainText()
answer = joined + "终"
bubble.queue_approved_stream_text(answer)
assert bubble.body.toPlainText() == before
assert bubble._raw_payload == answer
tick(bubble)
canonical = joined.encode("utf-16", "surrogatepass").decode("utf-16")
assert bubble.body.toPlainText() == canonical
assert bubble._presentation_offset == len(joined)
tick(bubble)
assert bubble.body.toPlainText() == canonical + "终"
assert bubble._raw_payload == answer
def test_markdown_formats_during_character_playback_without_reparsing_whole_reply(bubbles, monkeypatch):
bubble = bubbles()
answer = '## 标题\n\n**重点** <b>字</b> [链接](https://example.test)\n{"原文":"🩺"}'
calls = []
original = bubble.body.set_payload
def set_payload(text):
calls.append(text)
original(text)
monkeypatch.setattr(bubble.body, "set_payload", set_payload)
bubble.queue_approved_stream_text(answer)
for index in range(1, len(answer)):
assert bubble._presentation_offset == index
if index >= len("## 标题"):
assert bubble.body.document().begin().blockFormat().headingLevel() == 2
assert "##" not in bubble.body.toPlainText()
if index >= answer.index(" <b>"):
assert bubble.body.document().find("重点").charFormat().fontWeight() >= 700
assert "**" not in bubble.body.toPlainText()
if index < answer.index("🩺") + 1:
assert "🩺" not in bubble.body.toPlainText()
tick(bubble)
assert calls == [""] # The mode switch clears the old waiting message once.
assert bubble._raw_payload == answer
assert "https://example.test" not in bubble.body.toPlainText()
bubble.complete_stream_presentation(bubble.finish_stream_text)
assert calls == ["", answer] and bubble._raw_payload == answer
oracle = module._RichMessage("ai")
oracle.set_payload(answer)
assert bubble.body.toPlainText() == oracle.toPlainText()
oracle.deleteLater()
def test_sse_markdown_is_formatted_while_request_is_still_generating(dialogs):
dialog = dialogs()
dialog._ask("合成血糖趋势", task="glucose_trend")
bubble = dialog._stream_bubble
prefix = "### 血糖趋势评估\n\n**可比较的血糖记录**"
answer = prefix + "\n\n- 空腹血糖:8.2 mmol/L。\n- 尚未轮到的最后一项。"
event(dialog, "delta", text=answer)
while bubble._presentation_offset < len(prefix):
tick(bubble)
assert dialog._asking and not dialog._stream_completed
assert not bubble._presentation_terminal and bubble._presentation_timer.isActive()
assert bubble.body.document().begin().blockFormat().headingLevel() == 3
assert bubble.body.document().find("可比较的血糖记录").charFormat().fontWeight() >= 700
assert "8.2" not in bubble.body.toPlainText()
assert "尚未轮到" not in bubble.body.toPlainText()
assert bubble._raw_payload == dialog._stream_text == answer
def test_segmentation_is_cached_on_approved_input_not_rebuilt_each_frame(bubbles, monkeypatch):
bubble = bubbles()
original = module._stream_grapheme_ends
calls = []
def segment(text):
calls.append(len(text))
return original(text)
monkeypatch.setattr(module, "_stream_grapheme_ends", segment)
bubble.queue_approved_stream_text("甲" * 2200)
for _ in range(100):
tick(bubble)
assert calls == [2200]
bubble.queue_approved_stream_text("甲" * 2300)
tick(bubble)
assert calls == [2200, 2300]
def test_physical_single_shot_timer_has_one_character_per_frame_and_no_catchup(bubbles, application):
bubble = bubbles()
answer = "物理计时器每次只显示一个字且不会追赶积压。"
frames, times, paints = [], [], []
class PaintProbe(QObject):
def eventFilter(self, watched, paint_event): # noqa: N802 - Qt API
if paint_event.type() == QEvent.Type.Paint:
text = bubble.body.toPlainText()
if not paints or paints[-1] != text:
paints.append(text)
return False
probe = PaintProbe(bubble.body)
bubble.body.viewport().installEventFilter(probe)
bubble.stream_frame_presented.connect(lambda: (frames.append(bubble.body.toPlainText()),
times.append(perf_counter())))
started = perf_counter()
bubble.queue_approved_stream_text(answer)
bubble.complete_stream_presentation(lambda: None)
assert frames == [answer[:1]]
QTest.qSleep(120) # Block dispatch: missed wall-clock ticks must not become a batch.
application.processEvents()
assert frames == [answer[:1], answer[:2]]
wait_until(lambda: not bubble._presentation_timer.isActive(), seconds=3)
elapsed = perf_counter() - started
assert frames == [answer[:index] for index in range(1, len(answer) + 1)]
assert len(paints) >= 5
assert elapsed >= 0.120 + (len(answer) - 2) * 0.023
measurement = {
"synthetic": True, "graphemes": len(answer), "interval_ms": 24,
"first_immediate": True, "event_loop_block_ms": 120,
"physical_frames": len(frames), "distinct_viewport_paints": len(paints),
"elapsed_seconds": elapsed, "characters_per_second_including_block": len(answer) / elapsed,
"frame_gaps_ms": [(b - a) * 1000 for a, b in zip(times, times[1:], strict=False)],
"model_request_count": 0,
}
if destination := os.environ.get("R40_CHARACTER_MEASUREMENT"):
Path(destination).write_text(json.dumps(measurement, indent=2), encoding="utf-8")
@pytest.mark.parametrize("answer_only", [False, True])
def test_done_releases_request_and_input_before_final_character_and_ignores_late_done(dialogs, answer_only):
dialog = dialogs()
dialog._ask("合成问题", task="summary")
bubble, worker = dialog._stream_bubble, dialog._stream_worker
answer = "本次合成回复共有多个字。"
if not answer_only:
event(dialog, "delta", text=answer)
event(dialog, "done", answer=answer)
assert not dialog._asking and dialog.send_button.isEnabled() and dialog._stream_completed
assert bubble.body.toPlainText() == answer[:1]
assert bubble._raw_payload == dialog._stream_text == answer
assert bubble._presentation_timer.isActive() and bubble._report_render_pending
assert "正在逐字显示" in dialog.side_request_status.text()
assert "正在逐字显示" in bubble.transfer_status.text()
assert "完整显示" not in dialog.side_request_status.text()
dialog._stream_finished(dialog._generation, dialog._stream_generation, worker)
assert dialog._stream_worker is None
event(dialog, "done", answer="迟到未校验正文")
assert drain(bubble) == len(answer) - 1
wait_until(lambda: not bubble._report_render_pending)
assert bubble.body.toPlainText() == answer and bubble._raw_payload == answer
assert "已完整显示" in dialog.side_request_status.text()
assert "已完整显示" in bubble.transfer_status.text()
def test_completed_old_bubble_finishes_own_characters_after_successor_starts(dialogs):
dialog = dialogs()
dialog._ask("旧合成问题", task="summary")
old, worker = dialog._stream_bubble, dialog._stream_worker
answer = "旧请求自己逐字显示完整结尾。"
event(dialog, "delta", text=answer)
event(dialog, "done")
dialog._stream_finished(dialog._generation, dialog._stream_generation, worker)
dialog._ask("新合成问题", task="medication_review")
new = dialog._stream_bubble
event(dialog, "delta", text="新请求")
current_status = dialog.side_request_status.text()
assert old._presentation_timer.isActive() and new._presentation_timer.isActive()
tick(old)
assert old.body.toPlainText() == answer[:2] and new.body.toPlainText() == "新"
assert drain(old) == len(answer) - 2
wait_until(lambda: not old._report_render_pending)
assert old._raw_payload == answer and new._raw_payload == dialog._stream_text == "新请求"
assert "已完整显示" in old.transfer_status.text()
assert dialog.side_request_status.text() == current_status
assert "已完整显示" not in dialog.side_request_status.text()
assert old._task_title == "问诊小结" and new._task_title == "用药评估"
@pytest.mark.parametrize("owner_change", ["none", "patient_id", "diagnosis_id", "_chart_patient_id"])
def test_last_character_precedes_report_conversion_and_frozen_owner_check(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 = report()
event(dialog, "delta", text=answer)
event(dialog, "done")
dialog._stream_finished(dialog._generation, dialog._stream_generation, worker)
dialog._workspace_sections["tracking"]["value"]["blood_records"][0]["fasting_blood_sugar"] = 99
if owner_change == "none":
dialog._ask("新合成问题")
else:
setattr(dialog, owner_change, 9999)
for _ in range(len(answer) - 2):
tick(bubble)
assert bubble._presentation_offset == len(answer) - 1
oracle = module._RichMessage("ai")
oracle.set_payload(answer[:-1])
# Markdown control characters are no longer visible during playback.
assert bubble.body.toPlainText().split() == oracle.toPlainText().split()
oracle.deleteLater()
assert bubble._clinical_panel is None and bubble._report_render_pending
tick(bubble)
wait_until(lambda: not bubble._report_render_pending)
assert bubble._raw_payload == answer
if owner_change == "none":
assert isinstance(bubble._clinical_panel, module._StructuredReportPanel)
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("exit_path", ["close", "patient", "replace", "cancel"])
def test_exit_stops_timers_and_no_late_callback_changes_new_owner(dialogs, exit_path):
dialog = dialogs()
dialog._ask("旧合成请求", task="case_analysis")
old, worker = dialog._stream_bubble, dialog._stream_worker
owner = (dialog._generation, dialog._stream_generation)
answer = "已通过校验的合成正文完整尾部。" * 3
event(dialog, "delta", text=answer)
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()
before = old.body.toPlainText()
tick(old) # A stale queued callback must not restart this stopped bubble.
assert old.body.toPlainText() == before
dialog._stream_event(*owner, {"event": "done", "answer": "迟到未校验成功"})
dialog._stream_finished(*owner, worker)
assert old._raw_payload == answer and old._clinical_panel is None
assert not old._presentation_timer.isActive()
if exit_path in {"replace", "cancel"}:
assert old.body.toPlainText() == answer
assert "取消" in old.transfer_status.text()
@pytest.mark.parametrize("terminal", ["error", "eof"])
def test_failure_and_eof_keep_strict_approved_partial_without_success_conversion(dialogs, terminal):
dialog = dialogs()
dialog._ask("合成失败测试", task="case_analysis")
bubble, worker = dialog._stream_bubble, dialog._stream_worker
answer = "## 已通过校验的合成段落\n" + "原文仍需逐字显示。" * 8
event(dialog, "delta", text=answer)
before = bubble.body.toPlainText()
failure = "AI正文与病历的已知、阴性或未记录状态不一致,本次报告未通过校验。"
if terminal == "error":
dialog._stream_failed(dialog._generation, dialog._stream_generation, RuntimeError(failure))
assert bubble._stream_failure_label.isVisible()
assert failure in bubble._stream_failure_label.text()
assert bubble._stream_failure_label.textFormat() == Qt.TextFormat.PlainText
assert failure in dialog.side_request_status.text()
dialog._stream_finished(dialog._generation, dialog._stream_generation, worker)
assert bubble.body.toPlainText() == before
assert not dialog._asking and dialog._stream_worker is None and dialog.send_button.isEnabled()
assert not dialog._stream_completed and bubble._clinical_panel is None
assert bubble._raw_payload == dialog._stream_text == answer
event(dialog, "done", answer="迟到未校验成功")
assert drain(bubble) == len(answer) - 1
assert bubble._raw_payload == answer and bubble._clinical_panel is None
assert not bubble._report_render_pending
assert "已完整显示" not in bubble.transfer_status.text()
assert "已完整显示" not in dialog.side_request_status.text()
assert "已通过校验的合成段落" in bubble.body.toPlainText()
assert "迟到未校验成功" not in bubble.body.toPlainText()
assert failure not in bubble._raw_payload
if terminal == "eof":
assert "未收到回复完成确认" in bubble.transfer_status.text()
def test_error_without_approved_text_remains_prominent_after_worker_finished(dialogs):
dialog = dialogs()
dialog._ask("合成无正文失败")
bubble, worker = dialog._stream_bubble, dialog._stream_worker
failure = "合成错误:正文校验未通过。"
dialog._stream_failed(dialog._generation, dialog._stream_generation, RuntimeError(failure))
dialog._stream_finished(dialog._generation, dialog._stream_generation, worker)
assert bubble._stream_failure_label.isVisible() and failure in bubble._stream_failure_label.text()
assert bubble.body.isHidden() and not bubble._presentation_timer.isActive()
assert not dialog._stream_completed and not dialog._stream_text
assert bubble._raw_payload == ""
assert bubble._clinical_panel is None
@pytest.mark.parametrize("exit_path", ["close", "patient"])
def test_session_exit_also_stops_older_done_playback(dialogs, exit_path):
dialog = dialogs()
dialog._ask("旧合成请求")
old, worker = dialog._stream_bubble, dialog._stream_worker
event(dialog, "delta", text="旧请求的文字仍在逐字呈现。" * 4)
event(dialog, "done")
dialog._stream_finished(dialog._generation, dialog._stream_generation, worker)
dialog._ask("当前合成请求")
assert old._presentation_timer.isActive()
if exit_path == "close":
dialog.close()
else:
dialog.open_for(diagnosis_id=502, patient_id=1502)
assert not old._presentation_timer.isActive()
tick(old)
assert old._clinical_panel is None and not old._presentation_timer.isActive()
assert isValid(old)
@@ -0,0 +1,238 @@
"""Active streams keep parsed prefixes and deliver small deltas without GUI floods."""
from __future__ import annotations
import os
from threading import Event
from time import monotonic
from types import SimpleNamespace
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from PySide6.QtCore import QEvent, QThreadPool, QTimer
from PySide6.QtGui import QTextBlockUserData, QTextCursor
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication
from doctor_workstation.core import PermissionSet
from doctor_workstation.ui.dialogs import ai_consult as module
@pytest.fixture(scope="module")
def application():
return QApplication.instance() or QApplication([])
@pytest.mark.parametrize("width", [1, 7, 127])
@pytest.mark.parametrize("body", [
"# 核对记录\n\n**完整前段**,含中文与 emoji 🩺。\n\n- 第一项\n- 第二项\n\n末尾唯一标记",
"# 合成代码\n\n```text\n第一行\n\n第二行\n```\n\n完整结尾",
"# 合成表格\n\n| 记录 | 数值 |\n| --- | --- |\n| 测试 | 6.8 |\n\n待核对",
])
def test_incremental_markdown_preserves_content_and_terminal_format(application, width, body):
bubble = module._ChatBubble(role="ai", text=module.AI_STREAM_WAITING_TEXT)
full = ""
for offset in range(0, len(body), width):
chunk = body[offset:offset + width]
full += chunk
bubble.append_stream_text(chunk, full)
assert bubble._raw_payload == body
preview = bubble.body.toPlainText()
assert "完整" in preview or "待核对" in preview
bubble.finish_stream_text()
oracle = module._RichMessage("ai")
oracle.set_payload(body)
assert bubble.body.toPlainText() == oracle.toPlainText()
assert bubble.body.toHtml() == oracle.toHtml()
bubble.deleteLater()
oracle.deleteLater()
def test_updates_keep_stable_paragraph_objects_and_user_selection(application, monkeypatch):
browser = module._RichMessage("ai")
browser.append_stream_text("# 已有标题\n\n已有正文,不重新解析。\n\n")
prefix = browser.document().begin()
marker = QTextBlockUserData()
prefix.setUserData(marker)
cursor = browser.textCursor()
cursor.setPosition(0)
cursor.setPosition(4, QTextCursor.MoveMode.KeepAnchor)
browser.setTextCursor(cursor)
selected = browser.textCursor().selectedText()
monkeypatch.setattr(module, "render_chat_payload", lambda *args, **kwargs: pytest.fail("reparsed whole stream"))
for _ in range(90):
browser.append_stream_text("持续新增的一小段。")
assert browser.document().begin().userData() is marker
assert browser.document().begin().text() == "已有标题"
assert browser.textCursor().selectedText() == selected
assert browser.toPlainText().count("持续新增的一小段。") == 90
browser.deleteLater()
def test_long_unfinished_block_is_complete_and_formatted_on_completion(application):
bubble = module._ChatBubble(role="ai", text="")
text = "**长段落** " + "核对来源。" * 1500 + "末尾唯一标记"
full = ""
for offset in range(0, len(text), 73):
chunk = text[offset:offset + 73]
full += chunk
bubble.append_stream_text(chunk, full)
assert bubble.body._stream_tail_plain
assert bubble.body.toPlainText().count("末尾唯一标记") == 1
bubble.finish_stream_text()
assert "**" not in bubble.body.toPlainText()
assert bubble._raw_payload == text
bubble.deleteLater()
def test_partial_render_failure_restores_document_layout(application, monkeypatch):
browser = module._RichMessage("ai")
def fail(*args, **kwargs):
raise ValueError("synthetic format failure")
monkeypatch.setattr(module, "apply_reading_rhythm", fail)
with pytest.raises(ValueError, match="synthetic"):
browser.append_stream_text("合成片段")
assert browser.document().isLayoutEnabled() and not browser._fitting
browser.deleteLater()
@pytest.mark.parametrize("suffix", [" ", "\t", " "])
def test_unterminated_whitespace_is_not_a_stable_paragraph(application, suffix):
first = "正文\n" + suffix
assert module._stable_markdown_prefix(first) == 0
browser = module._RichMessage("ai")
browser.append_stream_text(first)
browser.append_stream_text("续行")
oracle = module._RichMessage("ai")
oracle.set_payload(first + "续行")
assert browser.toPlainText() == oracle.toPlainText()
assert browser.document().blockCount() == oracle.document().blockCount()
browser.deleteLater()
oracle.deleteLater()
def test_heading_size_and_list_spacing_are_stable_during_generation(application):
browser = module._RichMessage("ai")
for text in ["普通前段\n\n", "## 小节标题\n\n", "- 第一条\n- 第二条"]:
browser.append_stream_text(text)
block = browser.document().begin().next()
assert block.text() == "小节标题" and block.blockFormat().headingLevel() == 2
separator = block.next()
assert not separator.text()
assert separator.blockFormat().topMargin() == separator.blockFormat().bottomMargin() == 0
assert separator.blockFormat().lineHeight() == 1
assert "第一条" in browser.toPlainText() and "第二条" in browser.toPlainText()
browser.deleteLater()
def test_long_fence_can_close_after_plain_preview_without_losing_lines(application):
browser = module._RichMessage("ai")
source = "## 标题 🩺\n\n```text\n" + "唯一源码一行\n\n" * 350
browser.append_stream_text(source)
assert browser._stream_tail_plain and browser._stream_tail.startswith("```text")
browser.append_stream_text("```\n\n## 后续小节\n\n唯一结尾")
assert browser.toPlainText().count("唯一源码一行") == 350
assert browser.toPlainText().count("唯一结尾") == 1
assert "```" not in browser.toPlainText()
browser.deleteLater()
@pytest.mark.parametrize("exit_path", ["replace", "patient", "close"])
def test_queued_mailbox_cannot_change_new_request_or_closed_patient(application, monkeypatch, exit_path):
monkeypatch.setattr(module, "QThreadPool", SimpleNamespace(globalInstance=lambda: SimpleNamespace(start=lambda _: None)))
dialog = module.AiConsultDialog(object(), PermissionSet(["tcm.diagnosis/aiAssistant"]))
monkeypatch.setattr(dialog, "_load_workspace", lambda _: None)
dialog.open_for(diagnosis_id=501, patient_id=1501)
dialog._ask("旧问题")
old_worker = dialog._stream_worker
old_worker.signals.blockSignals(True)
old_worker._queue_event({"event": "delta", "text": "旧患者排队的尾段"})
if exit_path == "replace":
dialog._ask("新问题", replace_active=True)
elif exit_path == "patient":
dialog.open_for(diagnosis_id=502, patient_id=1502)
dialog._ask("新问题")
else:
dialog.close()
current = dialog._stream_bubble
expected = current._raw_payload if current is not None else None
old_worker.signals.blockSignals(False)
old_worker.signals.ready.emit()
old_worker._queue_event({"event": "delta", "text": "取消后迟到片段"})
QTest.qWait(10)
assert old_worker.is_cancelled() and old_worker.take_events() == []
if current is not None:
assert current._raw_payload == expected == module.AI_STREAM_PENDING_TEXT
assert dialog._session_closed is (exit_path == "close")
dialog.close()
dialog.deleteLater()
def test_worker_coalesces_thousands_of_deltas_before_the_gui(application):
worker = module._AiStreamWorker(object(), diagnosis_id=501, prompt="合成测试", task="summary")
wakes = []
worker.signals.ready.connect(lambda: wakes.append(True))
worker._queue_event({"event": "start", "model_label": "千问"})
chunks = ["中", "🩺", "\n", " ", "**"] * 2000
for chunk in chunks:
worker._queue_event({"event": "delta", "text": chunk})
worker._queue_event({"event": "done", "answer": "".join(chunks)})
events = worker.take_events()
assert [event["event"] for event in events] == ["start", "delta", "done"]
assert events[1]["text"] == "".join(chunks)
assert len(wakes) == 3 # start, first real text, terminal; independent of chunk count.
assert worker.take_events() == []
worker._queue_event({"event": "delta", "text": "过期片段"})
worker.cancel()
worker._queue_event({"event": "delta", "text": "取消后片段"})
assert worker.take_events() == []
@pytest.mark.parametrize("ending", ["done", "error", "eof"])
def test_paused_upstream_tail_paints_and_terminal_drain_is_lossless(application, monkeypatch, ending):
paused, release = Event(), Event()
class Repository:
def stream_diagnosis_ai(self, *args, **kwargs):
yield {"event": "start", "model_label": "千问"}
yield {"event": "delta", "text": "首段即时显示"}
yield {"event": "delta", "text": ",暂停前的尾段"}
paused.set()
assert release.wait(4)
yield {"event": "delta", "text": ",终态前的最后一字"}
if ending == "done":
yield {"event": "done"}
elif ending == "error":
raise RuntimeError("合成连接中断")
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()
try:
dialog._ask("合成小结")
deadline = monotonic() + 2
while (not paused.is_set() or "暂停前的尾段" not in dialog._stream_text) and monotonic() < deadline:
QTest.qWait(10)
assert "暂停前的尾段" in dialog._stream_bubble.body.toPlainText()
assert dialog._asking and not dialog._stream_completed
# A queued GUI action runs while the network worker is paused.
actions = []
QTimer.singleShot(0, lambda: actions.append(True))
QTest.qWait(10)
assert actions == [True]
release.set()
deadline = monotonic() + 2
while dialog._asking and monotonic() < deadline:
QTest.qWait(10)
assert not dialog._asking and dialog.send_button.isEnabled()
assert "终态前的最后一字" in dialog._stream_bubble.body.toPlainText()
assert not dialog._delivery_timer.isActive()
assert dialog._stream_completed is (ending == "done")
finally:
release.set()
for timer in dialog.findChildren(QTimer):
timer.stop()
dialog.close()
QThreadPool.globalInstance().waitForDone(2000)
dialog.deleteLater()
application.sendPostedEvents(None, QEvent.Type.DeferredDelete)
+431
View File
@@ -0,0 +1,431 @@
from __future__ import annotations
import os
from copy import deepcopy
from dataclasses import FrozenInstanceError
from datetime import datetime
from typing import Any
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from PySide6.QtCore import QPoint, Qt
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication, QLabel, QToolTip
from doctor_workstation.ui.dialogs.ai_consult_charts import (
GlucoseReportCard,
build_glucose_chart_data,
)
from doctor_workstation.ui.dialogs.ai_consult_metric_state import (
ABNORMAL_COLOR,
NORMAL_COLOR,
UNKNOWN_COLOR,
)
@pytest.fixture(scope="module")
def application() -> QApplication:
return QApplication.instance() or QApplication([])
def _row(day: str = "2026-08-18", **changes: Any) -> dict[str, Any]:
return {
"diagnosis_id": 501,
"patient_id": 1501,
"record_date": day,
"fasting_blood_sugar": 6.8,
**changes,
}
def _tracking(*rows: Any, **changes: Any) -> dict[str, Any]:
return {"diagnosis_id": 501, "patient_id": 1501, "blood_records": list(rows), **changes}
def _build(tracking: Any):
return build_glucose_chart_data(tracking, diagnosis_id=501, patient_id=1501)
def test_real_dto_is_immutable_chronological_and_does_not_average_same_day() -> None:
tracking = _tracking(
_row("2026-08-20", record_time="09:10", fasting_blood_sugar="7.2 mmol/L"),
_row("2026-08-18", record_time="09:00", fasting_blood_sugar=6.1),
_row("2026-08-18", record_time="08:00", fasting_blood_sugar=5.9),
_row("2026-08-19", fasting_blood_sugar=None, postprandial_blood_sugar="9.1"),
)
before = deepcopy(tracking)
data = _build(tracking)
assert tracking == before
assert data.available and data.readout_count == 4 and data.record_count == 4
assert [reading.fasting for reading in data.readings] == [5.9, 6.1, None, 7.2]
assert data.readings[2].postprandial == 9.1
assert data.readings[0].recorded_at == datetime(2026, 8, 18, 8)
assert data.readings[0].time_label == "2026-08-18 08:00"
assert data.readings[2].time_label == "2026-08-19"
assert data.date_range is not None
assert tuple(day.isoformat() for day in data.date_range) == ("2026-08-18", "2026-08-20")
assert data.excluded_count == 0
with pytest.raises(FrozenInstanceError):
data.readings[0].fasting = 99 # type: ignore[misc]
tracking["blood_records"][0]["fasting_blood_sugar"] = 99
assert data.readings[-1].fasting == 7.2
@pytest.mark.parametrize("owner", [None, True, 501.0, "501", 502, 0])
def test_tracking_root_requires_exact_diagnosis_owner(owner: Any) -> None:
data = _build(_tracking(_row(), diagnosis_id=owner))
assert not data.available and data.readings == ()
assert "归属" in data.unavailable_reason
def test_ownerless_root_is_rejected() -> None:
tracking = _tracking(_row())
del tracking["diagnosis_id"]
assert not _build(tracking).available
@pytest.mark.parametrize("owner", [None, True, 501.0, "501", 502, 0])
def test_rows_require_exact_diagnosis_owner(owner: Any) -> None:
data = _build(_tracking(_row(diagnosis_id=owner), _row("2026-08-19")))
assert data.record_count == 1
assert data.readings[0].recorded_at.day == 19
assert data.excluded_count == 1
@pytest.mark.parametrize("owner", [None, True, 1501.0, "1501", 1502, 0])
def test_declared_patient_owner_is_strict_at_root_and_row(owner: Any) -> None:
assert not _build(_tracking(_row(), patient_id=owner)).available
data = _build(_tracking(_row(patient_id=owner)))
assert not data.available and data.readings == ()
assert data.excluded_count == 1
def test_diagnosis_owned_rows_may_omit_patient_id_but_not_diagnosis_id() -> None:
row = _row()
del row["patient_id"]
assert _build(_tracking(row)).readout_count == 1
del row["diagnosis_id"]
assert not _build(_tracking(row)).available
def test_root_patient_owner_is_used_when_the_caller_has_no_patient_id() -> None:
data = build_glucose_chart_data(_tracking(_row(patient_id=1502)), diagnosis_id=501)
assert not data.available and data.excluded_count == 1
@pytest.mark.parametrize(
"value",
[
True,
False,
float("nan"),
float("inf"),
-float("inf"),
-1,
"-1",
"6-9",
"约 6.8",
"~6.8",
"<6.8",
"6.8±0.2",
"6.8 mg/dL",
"血糖6.8",
{"value": 6.8},
"Infinity",
],
)
def test_ambiguous_readings_stay_gaps_and_are_never_guessed(value: Any) -> None:
data = _build(_tracking(_row(fasting_blood_sugar=value)))
assert not data.available and data.readout_count == 0
assert len(data.readings) == 1 and data.readings[0].fasting is None
assert data.excluded_count == 1
@pytest.mark.parametrize("value", [None, "", "—", "未填写", 0, 0.0, "0", "0.0 mmol/L"])
def test_daily_zero_and_missing_defaults_are_absent_without_ambiguous_warning(value: Any) -> None:
data = _build(
_tracking(
_row(
fasting_blood_sugar=value,
postprandial_blood_sugar=0,
other_blood_sugar=0,
remark="继续观察",
)
)
)
assert not data.available and data.readout_count == 0
assert data.excluded_count == 0
assert all(reading.readout_count == 0 for reading in data.readings)
@pytest.mark.parametrize("value", ["6.80", "6.8 mmol/L", " 6.8 MMOL / l ", 6.8])
def test_exact_mmol_readings_are_accepted(value: Any) -> None:
data = _build(_tracking(_row(fasting_blood_sugar=value)))
assert data.readings[0].fasting == 6.8
assert data.excluded_count == 0
def test_partial_ambiguous_row_preserves_verified_series_and_records_one_exclusion() -> None:
data = _build(
_tracking(
_row(fasting_blood_sugar="6-9", postprandial_blood_sugar=9.3, other_blood_sugar="约7")
)
)
assert data.available and data.readout_count == 1
assert data.readings[0].fasting is None
assert data.readings[0].postprandial == 9.3
assert data.excluded_count == 1
@pytest.mark.parametrize(
"day", [None, "", "2026-02-30", "08-18", "2026-8-18", "2026-08-18 大约", 1787040000]
)
def test_missing_or_ambiguous_date_never_becomes_today(day: Any) -> None:
data = _build(_tracking(_row(day)))
assert data.readings == () and data.excluded_count == 1
@pytest.mark.parametrize("clock", ["25:10", "8:30", "上午", True])
def test_invalid_declared_record_time_is_excluded(clock: Any) -> None:
assert _build(_tracking(_row(record_time=clock))).excluded_count == 1
def test_legacy_entries_require_owners_and_keep_periods_distinct() -> None:
tracking = {
"diagnosis_id": 501,
"blood_sugar": {
"entries": [
{"diagnosis_id": 501, "date": "2026-08-18", "value": "6.2", "period": "空腹"},
{"diagnosis_id": 501, "date": "2026-08-19", "value": "9.1", "period": "餐后"},
{
"diagnosis_id": 501,
"measured_at": "2026-08-19T20:10:00",
"value": "7.4",
"period": "睡前",
},
{"date": "2026-08-20", "value": "20.2", "period": "空腹"},
]
},
}
data = _build(tracking)
assert data.readout_count == 3 and data.excluded_count == 1
assert data.readings[0].fasting == 6.2
assert data.readings[1].postprandial == 9.1
assert data.readings[2].other == 7.4
assert data.readings[2].time_label == "2026-08-19 20:10"
tracking["blood_sugar"]["diagnosis_id"] = 502
assert not _build(tracking).available
def test_unit_metadata_cannot_relabel_mg_dl_as_mmol() -> None:
assert not _build(_tracking(_row(), unit="mg/dL")).available
assert not _build(_tracking(_row(unit="mg/dL"))).available
assert _build(_tracking(_row(unit="mmol/L"))).available
def test_production_source_takes_precedence_to_avoid_duplicate_representations() -> None:
tracking = _tracking(
_row(), blood_sugar={"entries": [{"diagnosis_id": 501, "date": "2026-08-18", "value": 9.9}]}
)
assert _build(tracking).readout_count == 1
def test_source_states_are_immutable_and_require_the_same_owned_row() -> None:
tracking = _tracking(
_row(fasting_glucose_status="normal", postprandial_glucose=9.3,
postprandial_glucose_status="low", other_glucose=7.1, other_glucose_status="warning"),
_row("2026-08-19", diagnosis_id=502, fasting_blood_sugar_status="high"),
fasting_blood_sugar_status="high",
)
before = deepcopy(tracking)
data = _build(tracking)
assert tracking == before and data.excluded_count == 1
assert len(data.readings) == 1
reading = data.readings[0]
assert (reading.fasting_status, reading.postprandial_status, reading.other_status) == (
"normal", "low", "warning",
)
tracking["blood_records"][0]["fasting_glucose_status"] = "high"
assert reading.fasting_status == "normal"
with pytest.raises(FrozenInstanceError):
reading.fasting_status = "high" # type: ignore[misc]
@pytest.mark.parametrize("status", [None, True, False, ["normal"], {"status": "normal"}])
def test_untyped_glucose_states_stay_unclassified(status: Any) -> None:
data = _build(_tracking(_row(fasting_blood_sugar_status=status)))
assert data.readings[0].fasting_status == ""
def test_glucose_points_tables_and_accessibility_share_explicit_states(application) -> None:
data = _build(_tracking(
_row("2026-08-18", fasting_blood_sugar=20, fasting_blood_sugar_status="normal",
postprandial_blood_sugar=3, postprandial_blood_sugar_status="low",
other_blood_sugar=12, other_blood_sugar_status="unclassified"),
_row("2026-08-19", fasting_blood_sugar=30),
_row("2026-08-20", fasting_blood_sugar=0, fasting_blood_sugar_status="normal"),
))
card = GlucoseReportCard(data)
card.resize(650, 420)
card.show()
application.processEvents()
assert card.chart is not None
chart = card.chart
image = chart.grab().toImage()
first = data.readings[0]
for column, field, color, status in (
(1, "fasting", NORMAL_COLOR, "normal"),
(2, "postprandial", ABNORMAL_COLOR, "low"),
(3, "other", UNKNOWN_COLOR, "unclassified"),
):
point = chart._position(first, getattr(first, field))
assert chart._point_color(first, field) == color
assert image.pixelColor(point.toPoint()).name().casefold() == color.casefold()
assert card.table.item(0, column).foreground().color().name().casefold() == color.casefold()
assert status in card.table.item(0, column).toolTip()
assert status in chart._point_tooltip(point)
assert status in chart.accessibleDescription()
assert card.table.item(1, 1).foreground().color().name() == UNKNOWN_COLOR.casefold()
assert "未标注" in card.table.item(1, 1).toolTip()
assert card.table.item(2, 1).text() == "—"
assert card.table.item(2, 1).foreground().color().name() == UNKNOWN_COLOR.casefold()
assert "未记录" in card.table.item(2, 1).toolTip()
assert "空腹血糖 — · 状态 未记录" in chart.accessibleDescription()
assert "红色异常、绿色正常、灰色未记录/未标注" in chart.accessibleDescription()
card.close()
def test_glucose_connection_is_gray_between_explicit_normal_points(application) -> None:
data = _build(_tracking(
_row("2026-08-18", fasting_blood_sugar=5, fasting_blood_sugar_status="normal"),
_row("2026-08-20", fasting_blood_sugar=5, fasting_blood_sugar_status="normal"),
))
card = GlucoseReportCard(data)
card.resize(640, 420)
card.show()
application.processEvents()
assert card.chart is not None
left, right = [card.chart._position(reading, 5) for reading in data.readings]
midpoint = (left + right) / 2
image = card.chart.grab().toImage()
center = midpoint.toPoint()
assert UNKNOWN_COLOR.casefold() in {
image.pixelColor(center.x() + dx, center.y() + dy).name()
for dx in (-1, 0, 1) for dy in (-1, 0, 1)
}
assert image.pixelColor(left.toPoint()).name() == NORMAL_COLOR.casefold()
card.close()
def test_explicit_missing_series_preserve_gaps_and_actual_date_spacing(
application: QApplication,
) -> None:
data = _build(
_tracking(
_row("2026-08-01", fasting_blood_sugar=5.8),
_row("2026-08-02", fasting_blood_sugar="6-9"),
_row("2026-08-11", fasting_blood_sugar=7.1),
)
)
assert [reading.fasting for reading in data.readings] == [5.8, None, 7.1]
card = GlucoseReportCard(data)
card.resize(700, 400)
card.show()
application.processEvents()
assert card.chart is not None
first = card.chart._position(data.readings[0], 5.8)
gap = card.chart._position(data.readings[1], 5.8)
last = card.chart._position(data.readings[2], 5.8)
assert (gap.x() - first.x()) / (last.x() - first.x()) == pytest.approx(0.1)
assert not card.grab().isNull()
card.close()
def test_single_point_hover_and_original_records_toggle(
application: QApplication, monkeypatch: pytest.MonkeyPatch
) -> None:
data = _build(_tracking(_row(record_time="08:15", fasting_blood_sugar=6.83)))
card = GlucoseReportCard(data)
card.resize(500, 420)
card.show()
application.processEvents()
assert card.objectName() == "AiConsultGlucoseReport"
assert card.chart is not None and card.chart.data is data
assert card.chart.objectName() == "AiConsultGlucoseChart"
assert card.toggle_button is not None
assert card.table.isHidden()
assert card.table.item(0, 0).text() == "2026-08-18 08:15"
assert card.table.item(0, 1).text() == "6.83"
assert card.table.item(0, 2).text() == "—"
assert "6.83 mmol/L" in card.chart.accessibleDescription()
tooltips: list[str] = []
monkeypatch.setattr(QToolTip, "showText", lambda _position, text, *_args: tooltips.append(text))
point = card.chart._position(data.readings[0], 6.83)
QTest.mouseMove(card.chart, QPoint(round(point.x()), round(point.y())))
application.processEvents()
assert tooltips and "2026-08-18 08:15" in tooltips[-1] and "6.83 mmol/L" in tooltips[-1]
QTest.mouseClick(card.toggle_button, Qt.MouseButton.LeftButton)
assert not card.table.isHidden() and card.toggle_button.isChecked()
assert card.toggle_button.text() == "收起原始记录"
QTest.mouseClick(card.toggle_button, Qt.MouseButton.LeftButton)
assert card.table.isHidden()
card.close()
def test_overlapping_observations_remain_separate_in_hover_and_table(
application: QApplication,
) -> None:
data = _build(_tracking(_row(record_time="08:15"), _row(record_time="08:15")))
card = GlucoseReportCard(data)
card.resize(500, 420)
card.show()
application.processEvents()
assert card.chart is not None
tip = card.chart._point_tooltip(card.chart._position(data.readings[0], 6.8))
assert "记录 1" in tip and "记录 2" in tip
assert card.table.rowCount() == 2
card.close()
@pytest.mark.parametrize("width", [320, 580, 880])
def test_report_card_fits_narrow_and_wide_columns(application: QApplication, width: int) -> None:
data = _build(
_tracking(
_row(other_blood_sugar=8.2, postprandial_blood_sugar=9.1),
_row("2026-08-19", fasting_blood_sugar="6-9"),
)
)
card = GlucoseReportCard(data)
card.resize(width, card.sizeHint().height())
card.show()
application.processEvents()
assert card.width() == width
assert card.chart is not None and card.chart.height() >= 210
assert card.chart.geometry().right() < width
for label in card.findChildren(QLabel):
assert label.geometry().right() < width
assert not card.grab().isNull()
assert card.toggle_button is not None
card.toggle_button.click()
application.processEvents()
assert card.table.geometry().right() < width
assert not card.grab().isNull()
card.close()
@pytest.mark.parametrize(
"tracking", [None, {}, _tracking(), _tracking(_row(fasting_blood_sugar=0, remark="仅有备注"))]
)
def test_unavailable_state_has_no_fabricated_chart_or_empty_toggle(
application: QApplication, tracking: Any
) -> None:
card = GlucoseReportCard(_build(tracking))
card.resize(380, card.sizeHint().height())
card.show()
application.processEvents()
assert card.chart is None and card.toggle_button is None and card.table.isHidden()
assert card.height() < 210
assert any("暂无可绘制" in label.text() for label in card.findChildren(QLabel))
assert not card.grab().isNull()
card.close()
+29
View File
@@ -0,0 +1,29 @@
from __future__ import annotations
from doctor_workstation.ui.dialogs.ai_consult_drug_names import (
TCM,
WESTERN,
find_drug_mentions,
summarize_drugs,
)
def test_formula_wins_over_contained_herb() -> None:
mentions = find_drug_mentions("可参考六味地黄丸加减")
assert [(m.name, m.kind) for m in mentions] == [("六味地黄丸", TCM)]
def test_western_dosage_form_is_highlighted_but_deduplicated_by_base_name() -> None:
text = "在用二甲双胍胶囊,二甲双胍早晚各1片,加用阿卡波糖"
mentions = find_drug_mentions(text)
assert text[mentions[0].start:mentions[0].end] == "二甲双胍胶囊"
assert summarize_drugs(text) == {TCM: [], WESTERN: ["二甲双胍", "阿卡波糖"]}
def test_herbs_and_western_drugs_are_split_by_kind() -> None:
summary = summarize_drugs("黄芪、丹参益气活血;格列美脲注意低血糖;黄芪可加量")
assert summary == {TCM: ["黄芪", "丹参"], WESTERN: ["格列美脲"]}
def test_plain_text_and_diet_words_are_not_drugs() -> None:
assert summarize_drugs("建议多吃山药、大枣,少吃甜食,规律运动") == {TCM: [], WESTERN: []}
+417
View File
@@ -0,0 +1,417 @@
from __future__ import annotations
import os
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from PySide6.QtGui import QTextCursor, QTextDocument
from PySide6.QtWidgets import QApplication
from doctor_workstation.ui.dialogs.ai_consult_metric_text import (
MetricTextState,
metric_text_context,
metric_text_html,
)
@pytest.fixture(scope="module", autouse=True)
def application() -> QApplication:
return QApplication.instance() or QApplication([])
def _document(text: str, *, metric_label: str = "") -> QTextDocument:
document = QTextDocument()
document.setHtml(metric_text_html(text, metric_label=metric_label))
assert document.toPlainText() == text.replace("\r\n", "\n").replace("\r", "\n")
return document
def _color(document: QTextDocument, phrase: str, offset: int = 0) -> str:
position = document.toPlainText().index(phrase) + offset
cursor = QTextCursor(document)
cursor.setPosition(position)
cursor.movePosition(QTextCursor.MoveOperation.NextCharacter, QTextCursor.MoveMode.KeepAnchor)
return cursor.charFormat().foreground().color().name().upper()
@pytest.mark.parametrize(
"text,measurement",
[
("空腹血糖6-7 mmol/L,餐后8-9mmol/L", "6-7 mmol/L"),
("空腹血糖6-7 mmol/L,餐后8-9mmol/L", "8-9mmol/L"),
("血糖<7.0 mmol/L", "<7.0 mmol/L"),
("血糖≤ 7.0 mmol/L", "≤ 7.0 mmol/L"),
("血糖<= 7.0 mmol/L", "<= 7.0 mmol/L"),
("血糖<7.0 mmol/L", "<7.0 mmol/L"),
("血糖3.9~6.1 mmol/L", "3.9~6.1 mmol/L"),
("血糖4.4至7.0 mmol/L", "4.4至7.0 mmol/L"),
("BP140/90mmHg", "140/90mmHg"),
("血压140 / 90 mmHg", "140 / 90 mmHg"),
("HbA1c7.2%", "7.2%"),
("糖化血红蛋白(HbA1c)7.2%", "7.2%"),
("BMI26.1", "26.1"),
("BMI26.1kg/m²", "26.1kg/m²"),
("体质量指数:26.1", "26.1"),
("身高175cm,体重80 kg", "175cm"),
("身高175cm,体重80 kg", "80 kg"),
("身高1.75m", "1.75m"),
("height175cm,weight80kg", "175cm"),
("height175cm,weight80kg", "80kg"),
("LDL-C130mg/dL", "130mg/dL"),
("TC:5.8mmol/L", "5.8mmol/L"),
("eGFR 85 ml/min/1.73m²", "85 ml/min/1.73m²"),
("eGFR:85", "85"),
("eGFR 85 mL/min/1.73 m2", "85 mL/min/1.73 m2"),
("ACR30mg/g", "30mg/g"),
("尿白蛋白肌酐比值30mg/gCr", "30mg/gCr"),
("肌酐88 μmol/L", "88 μmol/L"),
("尿酸300µmol/L", "300µmol/L"),
("heart_rate:72", "72"),
("heart_rate72bpm", "72bpm"),
("心率72次/分", "72次/分"),
("HR72bpm", "72bpm"),
("血氧饱和度98%", "98%"),
("体温36.8℃", "36.8℃"),
("ALT35U/L", "35U/L"),
("血红蛋白130g/L", "130g/L"),
],
)
def test_clinical_values_are_semibold_gray_and_preserve_all_characters(
text: str, measurement: str
) -> None:
document = _document(text)
for offset in range(len(measurement)):
assert _color(document, measurement, offset) == "#697386"
cursor = QTextCursor(document)
cursor.setPosition(document.toPlainText().index(measurement))
cursor.movePosition(QTextCursor.MoveOperation.NextCharacter, QTextCursor.MoveMode.KeepAnchor)
assert cursor.charFormat().fontWeight() >= 600
@pytest.mark.parametrize("cue", ["目标", "参考", "理想", "阈值"])
def test_targets_and_reference_ranges_stay_gray(cue: str) -> None:
document = _document(f"当前血糖8.2 mmol/L,{cue}:<7.0 mmol/L")
assert _color(document, "8.2 mmol/L") == "#697386"
for offset in range(len("<7.0 mmol/L")):
assert _color(document, "<7.0 mmol/L", offset) == "#697386"
def test_percent_targets_inherit_only_a_clinical_percent_label() -> None:
document = _document("HbA1c7.2%,目标<7.0%;总体完成率80%,风险降低20%")
assert _color(document, "7.2%") == "#697386"
assert _color(document, "<7.0%") == "#697386"
assert _color(document, "80%") != "#697386"
assert _color(document, "20%") != "#697386"
def test_current_readings_after_targets_do_not_keep_reference_color() -> None:
document = _document("目标<7.0 mmol/L;当前8.2 mmol/L,6.8 mmol/L(参考值)")
assert _color(document, "<7.0 mmol/L") == "#697386"
assert _color(document, "8.2 mmol/L") == "#697386"
assert _color(document, "6.8 mmol/L") == "#697386"
@pytest.mark.parametrize(
"text",
[
"诊单ID:123456;patient_id=1501;流水ABC123456;电话13800138000",
"2026-08-18,2026/08/19,08:30,第1章,1. 检查,2. 处理",
"病程3年,持续2周,随访7天,每次30分钟",
"剂量0.2mg/kg、浓度5mg/mL,外用2%利多卡因",
"统计显示80%的患者改善20%,目标完成率90%,报销比例50%",
"BMI2026-08-18;eGFR2026/08/19;heart_rate2026-08-18",
"not_BMI26.1;abceGFR85;ID7mmol/L;abc72bpm",
],
)
def test_unrelated_numbers_and_drug_doses_remain_unemphasized(text: str) -> None:
rendered = metric_text_html(text)
_document(text)
assert "color:" not in rendered
def test_drug_names_are_highlighted_but_their_doses_stay_plain() -> None:
text = "二甲双胍500mg,每日2次;胰岛素10U;阿司匹林100 mg;黄芪30g"
rendered = metric_text_html(text)
for name in ("二甲双胍", "胰岛素", "阿司匹林"):
assert f'background-color: #EEF1FA; font-weight: 700;">{name}</span>' in rendered
assert 'background-color: #EAF7F0; font-weight: 700;">黄芪</span>' in rendered
for dose in ("500mg", "10U", "100 mg", "30g"):
assert f'font-weight: 600;">{dose}' not in rendered
assert f'font-weight: 700;">{dose}' not in rendered
def test_explicit_statuses_are_emphasized_without_classifying_the_numbers() -> None:
document = _document("血糖6.0 mmol/L未达标;血压140/90mmHg正常;血糖偏高;检查异常")
assert _color(document, "6.0 mmol/L") == "#BD4B58"
assert _color(document, "140/90mmHg") == "#287B65"
assert _color(document, "未达标") == "#BD4B58"
assert _color(document, "正常") == "#287B65"
assert _color(document, "偏高") == "#BD4B58"
assert _color(document, "异常") == "#BD4B58"
@pytest.mark.parametrize(
"status,color",
[
("未达标", "#BD4B58"),
("不达标", "#BD4B58"),
("尚未完全达标", "#BD4B58"),
("未见异常", "#287B65"),
("无异常", "#287B65"),
("未见明显异常", "#287B65"),
("没有显著异常", "#287B65"),
("不正常", "#BD4B58"),
("非正常", "#BD4B58"),
("未恢复正常", "#BD4B58"),
("已达标", "#287B65"),
],
)
def test_negated_statuses_do_not_color_a_misleading_substring(status: str, color: str) -> None:
document = _document(status)
for offset in range(len(status)):
assert _color(document, status, offset) == color
@pytest.mark.parametrize(
"text",
[
"建议复查以排除异常",
"警惕血糖偏低风险",
"可能偏高,需结合进一步检查",
"若仍未达标,应复查",
"不能排除血糖异常",
"是否正常有待检查",
"未见升高;无明显升高;不偏高",
"无法达标;未达到正常;不能完全达标",
"正常值与正常范围;达标率80%",
"如血糖升高或不达标,应随访",
"需使血糖达标",
"建议控制至正常,争取早日达标",
],
)
def test_uncertain_conditional_or_recommended_statuses_stay_neutral(text: str) -> None:
_document(text)
assert "color:" not in metric_text_html(text)
@pytest.mark.parametrize(
"text",
[
"",
" 原文 保留\t制表符\n\n最后 ",
"\n首行前换行\r\n血糖<7.0 mmol/L\r末行\n",
'<script>alert("test")</script>\n<a href="https://example.com">6-7 mmol/L</a>',
'<img src="x" onerror="alert(1)">HbA1c7.2% &lt;7% &nbsp; & custom',
'<span style="color:red">正常</span> & \'" < >',
],
)
def test_html_is_literal_and_plain_text_and_whitespace_are_preserved(text: str) -> None:
document = _document(text)
html = metric_text_html(text)
assert "<script>" not in html
assert "<a " not in html
assert "<img " not in html
assert '<span style="color:red">' not in html
assert not document.find("https://example.com").charFormat().isAnchor()
assert "\n" not in html
@pytest.mark.parametrize(
"label,text,reading",
[
("空腹血糖", "FPG6.0mmol/L", "6.0mmol/L"),
("FPG", "空腹6.0 mmol/L", "6.0 mmol/L"),
("fasting_glucose", "空腹血糖6.0 mmol/L", "6.0 mmol/L"),
("HbA1c", "糖化血红蛋白7.2%", "7.2%"),
("糖化血红蛋白", "glycated hemoglobin 7.2%", "7.2%"),
("glycated haemoglobin", "HbA1c7.2%", "7.2%"),
("血压", "BP140/90mmHg", "140/90mmHg"),
("LDL-C", "低密度脂蛋白胆固醇3.2 mmol/L", "3.2 mmol/L"),
("尿素氮", "尿素氮6.0 mmol/L", "6.0 mmol/L"),
],
)
def test_recorded_states_match_field_aliases(label: str, text: str, reading: str) -> None:
with metric_text_context([MetricTextState(label, reading, "high")]):
assert _color(_document(text), reading) == "#BD4B58"
@pytest.mark.parametrize(
"status,color",
[
("high", "#BD4B58"),
("low", "#BD4B58"),
("warning", "#BD4B58"),
("未达标", "#BD4B58"),
("偏低", "#BD4B58"),
("normal", "#287B65"),
("达标", "#287B65"),
("unknown", "#697386"),
("", "#697386"),
("未记录", "#697386"),
("unexpected", "#697386"),
],
)
def test_value_only_widgets_use_the_supplied_field(status: str, color: str) -> None:
with metric_text_context([MetricTextState("FPG", "6.0 mmol/L", status)]):
document = _document("6.0 mmol/L", metric_label="空腹血糖")
assert _color(document, "6.0 mmol/L") == color
assert _color(_document("6.0 mmol/L"), "6.0 mmol/L") == "#697386"
def test_unitless_value_only_widgets_bind_without_classifying_other_numbers() -> None:
with metric_text_context([MetricTextState("BMI", "26.1", "normal")]):
assert _color(_document("26.1", metric_label="体质指数"), "26.1") == "#287B65"
assert "color:" not in metric_text_html("2026-08-18", metric_label="BMI")
def test_context_restores_outer_state_after_nested_scope_and_exception() -> None:
text = "空腹血糖6.0 mmol/L"
reading = "6.0 mmol/L"
with metric_text_context([MetricTextState("FPG", reading, "high")]):
assert _color(_document(text), reading) == "#BD4B58"
with (
pytest.raises(RuntimeError),
metric_text_context([MetricTextState("空腹", reading, "normal")]),
):
assert _color(_document(text), reading) == "#287B65"
raise RuntimeError("restore scope")
assert _color(_document(text), reading) == "#BD4B58"
assert _color(_document(text), reading) == "#697386"
def test_context_snapshots_input_sequence() -> None:
states = [MetricTextState("空腹", "6.0 mmol/L", "high")]
with metric_text_context(states):
states.clear()
assert _color(_document("空腹6.0 mmol/L"), "6.0 mmol/L") == "#BD4B58"
@pytest.mark.parametrize("statuses", [("high", "normal"), ("unknown", "normal"), ("high", "")])
def test_conflicting_same_field_and_reading_states_stay_gray(statuses: tuple[str, str]) -> None:
with metric_text_context(
[
MetricTextState("FPG", "6.0 mmol/L", statuses[0]),
MetricTextState("空腹血糖", "6.0mmol/L", statuses[1]),
]
):
assert _color(_document("空腹血糖6.0 mmol/L正常"), "6.0 mmol/L") == "#697386"
def test_equivalent_abnormal_source_flags_do_not_conflict() -> None:
with metric_text_context(
[
MetricTextState("FPG", "6.0 mmol/L", "high"),
MetricTextState("空腹血糖", "6.0mmol/L", "warning"),
]
):
assert _color(_document("空腹血糖6.0 mmol/L"), "6.0 mmol/L") == "#BD4B58"
@pytest.mark.parametrize(
"text",
[
"餐后血糖6.0 mmol/L",
"血糖6.0 mmol/L",
"空腹血糖6.1 mmol/L",
"空腹血糖6.0 mg/dL",
"空腹血糖<6.0 mmol/L",
"空腹血糖6.0-7.0 mmol/L",
],
)
def test_matching_value_cannot_leak_between_fields_units_or_readings(text: str) -> None:
with metric_text_context([MetricTextState("FPG", "6.0 mmol/L", "normal")]):
assert "#287B65" not in metric_text_html(text)
def test_range_source_requires_whole_range_and_comparator() -> None:
reading = "≤ 4.4至7.0 mmol/L"
with metric_text_context([MetricTextState("空腹", reading, "warning")]):
assert _color(_document(f"空腹血糖{reading}"), reading) == "#BD4B58"
assert _color(_document("空腹血糖4.4 mmol/L"), "4.4 mmol/L") == "#697386"
def test_known_source_state_takes_precedence_over_ai_assertion() -> None:
with metric_text_context([MetricTextState("空腹血糖", "6.0 mmol/L", "high")]):
document = _document("空腹血糖6.0 mmol/L正常")
assert _color(document, "6.0 mmol/L") == "#BD4B58"
assert _color(document, "正常") == "#287B65"
@pytest.mark.parametrize("hint", ["", "空腹血糖", "空腹血糖目标"])
def test_targets_never_inherit_source_state_even_when_value_matches(hint: str) -> None:
with metric_text_context([MetricTextState("空腹血糖", "6.0 mmol/L", "high")]):
document = _document("目标空腹血糖6.0 mmol/L", metric_label=hint)
assert _color(document, "6.0 mmol/L") == "#697386"
document = _document("6.0 mmol/L(参考值)", metric_label=hint)
assert _color(document, "6.0 mmol/L") == "#697386"
def test_percent_reference_and_same_value_source_are_separated() -> None:
with metric_text_context([MetricTextState("HbA1c", "7.2%", "high")]):
document = _document("糖化血红蛋白7.2%,目标7.2%")
assert _color(document, "7.2%") == "#BD4B58"
cursor = document.find("目标7.2%")
cursor.setPosition(cursor.selectionEnd() - 2)
cursor.movePosition(
QTextCursor.MoveOperation.NextCharacter, QTextCursor.MoveMode.KeepAnchor
)
assert cursor.charFormat().foreground().color().name().upper() == "#697386"
def test_percent_body_uses_its_separate_label_without_coloring_unrelated_percentages() -> None:
with metric_text_context([MetricTextState("HbA1c", "7.2%", "high")]):
document = _document("7.2%,目标7.2%;完成率80%,风险下降20%", metric_label="HbA1c")
assert _color(document, "7.2%") == "#BD4B58"
assert _color(document, "80%") != "#697386"
assert _color(document, "20%") != "#697386"
@pytest.mark.parametrize("cue", ["正常范围", "target", "reference range"])
def test_reference_phrases_always_stay_gray(cue: str) -> None:
with metric_text_context([MetricTextState("HbA1c", "7.2%", "high")]):
document = _document(f"HbA1c {cue}: 7.2%")
assert _color(document, "7.2%") == "#697386"
@pytest.mark.parametrize(
"text,reading,color",
[
("血糖6.0 mmol/L未达标", "6.0 mmol/L", "#BD4B58"),
("血压140/90mmHg正常", "140/90mmHg", "#287B65"),
("血糖偏高:6.0 mmol/L", "6.0 mmol/L", "#BD4B58"),
("空腹6.0 mmol/L偏低", "6.0 mmol/L", "#BD4B58"),
("BMI26.1达标", "26.1", "#287B65"),
("FPG6.0mmol/L high", "6.0mmol/L", "#BD4B58"),
("血糖6.0 mmol/L可能偏高", "6.0 mmol/L", "#697386"),
("若血糖6.0 mmol/L未达标", "6.0 mmol/L", "#697386"),
("血糖6.0 mmol/L无明显升高", "6.0 mmol/L", "#697386"),
("血糖6.0 mmol/L血压正常", "6.0 mmol/L", "#697386"),
("血糖6.0 mmol/L血压140/90mmHg正常", "6.0 mmol/L", "#697386"),
],
)
def test_local_assertion_colors_only_its_nearby_reading(
text: str, reading: str, color: str
) -> None:
assert _color(_document(text), reading) == color
@pytest.mark.parametrize(
"missing", ["未记录", "未检测", "未知", "暂无数据", "unknown", "N/A", "—", "--", "/"]
)
def test_missing_values_are_gray(missing: str) -> None:
with metric_text_context([MetricTextState("空腹血糖", missing, "normal")]):
assert _color(_document(missing, metric_label="空腹血糖"), missing) == "#697386"
@pytest.mark.parametrize(
"label,color", [("高风险", "#BD4B58"), ("中风险", "#BD4B58"), ("低风险", "#287B65")]
)
def test_asserted_risk_levels_use_the_chart_palette(label: str, color: str) -> None:
assert _color(_document(f"风险评估:{label}"), label) == color
@pytest.mark.parametrize("text", ["可能高风险", "排除高风险", "中风险参考标准", "若为低风险"])
def test_conditional_risk_or_reference_is_not_an_asserted_state(text: str) -> None:
assert "#BD4B58" not in metric_text_html(text)
assert "#287B65" not in metric_text_html(text)
@@ -0,0 +1,65 @@
"""Current no-pulse workflow; old records and old acceptance fixtures stay intact."""
from __future__ import annotations
import os
from copy import deepcopy
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from PySide6.QtCore import QEvent, QTimer
from PySide6.QtWidgets import QApplication
from doctor_workstation.core import PermissionSet
from doctor_workstation.ui.dialogs import ai_consult as module
from doctor_workstation.ui.dialogs.diagnosis import _DIAGNOSIS_FIELDS
@pytest.fixture(scope="module")
def application():
return QApplication.instance() or QApplication([])
def test_current_prompts_and_suggestions_do_not_request_pulse():
prompts = [prompt for _, prompt in module.QUICK_PROMPTS]
prompts += [prompt for _, _, prompt in module.TOOL_ITEMS]
for text in [*prompts, *module.SUGGESTIONS]:
assert "舌脉" not in text
assert "脉象" not in text
assert len(module.TOOL_ITEMS) == 6
assert len(module.SUGGESTIONS) == 5
def test_context_uses_tongue_without_repurposing_historical_pulse():
detail = {"diagnosis": {"tongue": "舌淡红", "pulse": "历史脉细", "pulse_condition": "旧字段"}}
original = deepcopy(detail)
text, labels = module.build_patient_ai_context(detail=detail)
assert labels == ["舌象"]
assert "舌淡红" in text
assert "脉" not in text
assert detail == original
def test_pulse_only_does_not_create_current_context_or_collection_field():
assert module.build_patient_ai_context(detail={"diagnosis": {"pulse": "旧脉象"}}) == ("", [])
assert "pulse" not in {key for _, key, _ in _DIAGNOSIS_FIELDS}
def test_new_prescription_seed_has_no_active_pulse_fields(application, monkeypatch):
dialog = module.AiConsultDialog(object(), PermissionSet(["tcm.diagnosis/aiAssistant"]))
monkeypatch.setattr(dialog, "_load_workspace", lambda _: None)
detail = {"diagnosis": {"id": 501, "patient_id": 1501, "tongue": "舌淡红", "pulse": "历史脉细"}}
original = deepcopy(detail)
try:
dialog.open_for(diagnosis_id=501, patient_id=1501)
seed = dialog._prescription_seed(detail)
assert "pulse" not in seed and "pulse_condition" not in seed
assert seed["tongue"] == "舌淡红"
assert detail == original
finally:
for timer in dialog.findChildren(QTimer):
timer.stop()
dialog.close()
dialog.deleteLater()
application.sendPostedEvents(None, QEvent.Type.DeferredDelete)
application.processEvents()
+254
View File
@@ -0,0 +1,254 @@
"""Long replies retain content and chart snapshots while sharing GUI time."""
from __future__ import annotations
import os
from datetime import datetime, timedelta
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from PySide6.QtCore import QEvent, Qt, QTimer
from PySide6.QtGui import QImage, QPainter, QTextDocument
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication, QLabel
from doctor_workstation.core import PermissionSet
from doctor_workstation.ui.dialogs import ai_consult as module
from doctor_workstation.ui.dialogs.ai_consult_charts import GlucoseReportCard
from doctor_workstation.ui.dialogs.ai_consult_metric_state import (
ABNORMAL_COLOR,
NORMAL_COLOR,
UNKNOWN_COLOR,
)
from doctor_workstation.ui.dialogs.ai_consult_report_visuals import (
build_report_visuals,
create_report_visual,
)
@pytest.fixture(scope="module")
def application():
return QApplication.instance() or QApplication([])
@pytest.mark.parametrize("rich", [False, True])
def test_wrapping_measurements_reuse_parsed_text_and_follow_text_font_width(application, rich):
text = ("核对原始资料及记录日期。" * 70) + "末尾标记"
if rich:
text = f'<div style="line-height:172%">{text}<br><b>末行</b></div>'
label = module._FittedText(text, rich=rich)
changes = []
label._measure_document.contentsChanged.connect(lambda: changes.append(True))
first = label._height_at_width(480)
parses = len(changes)
for _ in range(20):
assert label._height_at_width(480) == first
assert label._height_at_width(240) > first
assert len(changes) == parses # Layout negotiation must not keep reparsing HTML.
label.resize(480, 100)
label._fit()
measured_width = label._measure_document.textWidth()
for hypothetical in range(1, 800, 7):
assert label.heightForWidth(hypothetical) == label.minimumHeight()
assert label._measure_document.textWidth() == measured_width
font = label.font()
font.setPixelSize(22)
label.setFont(font)
changed = label._height_at_width(240)
oracle = QTextDocument()
oracle.setDefaultFont(font)
if rich:
oracle.setHtml(text)
else:
oracle.setPlainText(text)
oracle.setTextWidth(240)
assert changed == int(oracle.size().height()) + 1
label.setText("更短的记录")
assert label._height_at_width(240) < changed
label.deleteLater()
@pytest.mark.parametrize("payload", [
"## 标题\n\n- **重点**:核对原始记录。\n- 完整末行",
"<h2>标题</h2><p>完整末行</p>",
{"summary": "完整末行"}, "",
])
def test_rich_update_restores_document_layout_and_keeps_full_content(application, payload):
browser = module._RichMessage("ai")
browser.resize(420, 200)
browser.set_payload(payload)
assert browser.document().isLayoutEnabled()
if payload:
assert "完整末行" in browser.toPlainText()
assert browser.minimumHeight() >= int(browser.document().size().height())
browser.document().setLayoutEnabled(False)
browser.set_payload(payload)
assert not browser.document().isLayoutEnabled()
browser.deleteLater()
def test_failed_rich_render_does_not_leave_document_layout_disabled(application, monkeypatch):
browser = module._RichMessage("ai")
def fail(*args, **kwargs):
raise ValueError("synthetic render failure")
monkeypatch.setattr(module, "render_chat_payload", fail)
with pytest.raises(ValueError, match="synthetic"):
browser.set_payload("未完成的内容")
assert browser.document().isLayoutEnabled()
assert not browser._fitting
browser.deleteLater()
@pytest.fixture
def dialog(application, monkeypatch):
instance = module.AiConsultDialog(object(), PermissionSet(["tcm.diagnosis/aiAssistant"]))
monkeypatch.setattr(instance, "_load_workspace", lambda _generation: None)
instance.open_for(diagnosis_id=501, patient_id=1501)
instance._workspace_sections = {"tracking": {"value": {"diagnosis_id": 501, "blood_records": [
{"diagnosis_id": 501, "patient_id": 1501, "record_date": "2026-10-17",
"fasting_blood_sugar": 6.2, "fasting_blood_sugar_status": "normal"},
{"diagnosis_id": 501, "patient_id": 1501, "record_date": "2026-10-18",
"fasting_blood_sugar": 8.2, "fasting_blood_sugar_status": "high"},
]}}}
instance.resize(1280, 820)
instance.show()
yield instance
for timer in instance.findChildren(QTimer):
timer.stop()
instance.close()
instance.deleteLater()
application.sendPostedEvents(None, QEvent.Type.DeferredDelete)
application.processEvents()
def _complete_long_reply(dialog):
repeated = "核对血糖原始记录及时间,不补写缺失资料。" * 280
reply = ("完整合成资料:空腹血糖 6.2 mmol/L,另一条空腹血糖 8.2 mmol/L,糖化血红蛋白未记录。\n\n"
f"1. 血糖记录核对\n- 来源:{repeated}\n\n2. 随访记录\n- 复核:{repeated}\n- 独有末尾标记")
bubble = dialog._append_bubble("ai", "")
dialog._stream_bubble = bubble
generation, stream = dialog._generation, dialog._stream_generation
for start in range(0, len(reply), 137):
dialog._stream_event(generation, stream, {"event": "delta", "text": reply[start:start + 137]})
assert dialog._pending_chunks # Exercise a large unflushed tail at done.
dialog._stream_event(generation, stream, {"event": "done", "model_label": "千问"})
return bubble, reply, generation, stream
def _wait_for_report(bubble):
for _ in range(600):
if not bubble._report_render_pending:
return
QTest.qWait(5)
pytest.fail("completed report remained pending")
def test_deferred_long_report_keeps_tail_chart_snapshot_and_terminal_semantics(dialog):
bubble, reply, generation, stream = _complete_long_reply(dialog)
assert bubble._report_render_pending and bubble._clinical_panel is None
assert bubble._raw_payload == reply == dialog._stream_text
assert "独有末尾标记" in bubble.body.toPlainText()
assert dialog.send_button.isEnabled() and not dialog._asking
dialog._workspace_sections["tracking"]["value"]["blood_records"][0]["fasting_blood_sugar"] = 99
_wait_for_report(bubble)
assert bubble._clinical_panel is not None
card = bubble.findChild(GlucoseReportCard)
assert card.chart.data.readings[0].fasting == 6.2
intro = bubble._clinical_panel.findChild(QLabel, "AiConsultReportIntroBody").text()
assert all(color in intro for color in (NORMAL_COLOR, ABNORMAL_COLOR, UNKNOWN_COLOR))
dialog._stream_event(generation, stream, {"event": "delta", "text": "迟到内容"})
assert bubble._raw_payload == reply
assert len(bubble.findChildren(GlucoseReportCard)) == 1
@pytest.mark.parametrize("exit_path", ["patient", "close"])
def test_queued_report_cannot_render_after_patient_switch_or_close(dialog, exit_path):
bubble, _, _, _ = _complete_long_reply(dialog)
if exit_path == "patient":
dialog.open_for(diagnosis_id=502, patient_id=1502)
else:
dialog.close()
_wait_for_report(bubble)
assert bubble._clinical_panel is None
@pytest.mark.parametrize("field, changed", [
("patient_id", 1999), ("_chart_patient_id", 1999), ("diagnosis_id", 502),
])
def test_authoritative_owner_change_in_same_generation_cannot_attach_old_charts(dialog, field, changed):
bubble, reply, generation, _ = _complete_long_reply(dialog)
setattr(dialog, field, changed)
assert dialog._generation == generation
_wait_for_report(bubble)
assert bubble._clinical_panel is None
assert bubble.findChild(GlucoseReportCard) is None
assert bubble._raw_payload == reply
def test_new_request_keeps_previous_completed_report_and_its_frozen_records(dialog):
bubble, reply, generation, old_stream = _complete_long_reply(dialog)
dialog._cancel_stream()
current = dialog._append_bubble("ai", "")
dialog._stream_bubble = current
dialog._stream_event(generation, dialog._stream_generation, {"event": "delta", "text": "新的提问回复"})
dialog._stream_event(generation, old_stream, {"event": "done", "answer": "旧请求迟到内容"})
_wait_for_report(bubble)
assert bubble._clinical_panel is not None and bubble._raw_payload == reply
assert current._raw_payload == "新的提问回复"
assert current._clinical_panel is None
@pytest.mark.parametrize("width", [1080, 1600])
def test_deferred_long_report_tail_stays_reachable_after_wrapping(dialog, application, width):
dialog.resize(width, 820)
bubble, _, _, _ = _complete_long_reply(dialog)
_wait_for_report(bubble)
for _ in range(8):
QTest.qWait(5)
dialog.chat_scroll.verticalScrollBar().setValue(dialog.chat_scroll.verticalScrollBar().maximum())
for _ in range(8):
QTest.qWait(5)
tail = bubble._clinical_panel.findChildren(QLabel, "AiConsultReportBody")[-1]
assert "独有末尾标记" in tail.text()
bottom = tail.mapTo(dialog.chat_scroll.viewport(), tail.rect().bottomLeft())
assert dialog.chat_scroll.viewport().rect().contains(bottom)
assert dialog.chat_scroll.horizontalScrollBar().maximum() == 0
def test_trend_paint_and_hover_share_one_geometry_scan(application, monkeypatch):
rows = [
{"diagnosis_id": 501, "patient_id": 1501,
"record_date": (datetime(2026, 8, 1) + timedelta(days=day)).date().isoformat(),
"systolic_pressure": 130 + day % 12, "diastolic_pressure": 80 + day % 8}
for day in range(60)
]
data = build_report_visuals("血压", "", sections={"tracking": {"value": {
"diagnosis_id": 501, "blood_records": rows,
}}}, diagnosis_id=501, patient_id=1501)[0]
card = create_report_visual(data)
plot = card.chart
plot.resize(640, plot.height())
original = plot._geometry
calls = []
def geometry():
calls.append(True)
return original()
monkeypatch.setattr(plot, "_geometry", geometry)
image = QImage(plot.size(), QImage.Format.Format_ARGB32)
image.fill(Qt.GlobalColor.white)
painter = QPainter(image)
try:
plot._paint_trend(painter)
finally:
painter.end()
assert len(calls) == 1
position = plot._position(data.items[0])
calls.clear()
assert data.items[0].value_text in plot._point_tooltip(position)
assert len(calls) == 1
card.deleteLater()
@@ -0,0 +1,413 @@
"""Recorded glucose charts inside the actual AI report and streaming lifecycle."""
from __future__ import annotations
import os
from copy import deepcopy
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from PySide6.QtCore import QEvent, QPoint, QTimer
from PySide6.QtGui import QTextDocument
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication, QComboBox, QLabel
from doctor_workstation.core import PermissionSet
from doctor_workstation.ui.dialogs import ai_consult as module
from doctor_workstation.ui.dialogs.ai_consult_charts import GlucoseReportCard
REPORT = """以下依据已加载的血糖记录梳理变化情况,请结合原始测量时间与当前病历逐项核对。
1. 血糖记录与趋势
- 记录核对:请区分空腹和餐后记录,并结合实际测量日期阅读图表,缺失的记录不能作为零值。
- 资料说明:文字中提及的数值仅用于说明,图表只能采用健康档案中的实际测量记录。
2. 随访资料核对
- 本次复诊:请保留完整记录,核对服药时间、进食时间与居家测量方式,补充尚未填写的资料。
"""
CLINICAL_REPORT = """基于当前病历,患者有血糖波动的描述,需结合完整的测量记录与四诊信息进一步核对。
### 1. 可能证候分析
- 病史待核对:现有记录反映的变化需与实际测量条件相互核对,尚不足以确认具体证候。
### 2. 关键矛盾与不足
- 资料缺口:需区分空腹及餐后记录,核对测量日期,保留未记录的部分而不补写数值。
### 3. 建议下一步
- 核对原始记录:将历史血糖记录与用药、进食情况一起核对,由医生结合资料作进一步判断。
"""
def _tracking(diagnosis_id=501, patient_id=1501):
return {
"diagnosis_id": diagnosis_id,
"blood_records": [
{"diagnosis_id": diagnosis_id, "patient_id": patient_id,
"record_date": "2026-10-17", "record_time": "07:30",
"fasting_blood_sugar": 6.2, "postprandial_blood_sugar": 8.4},
{"diagnosis_id": diagnosis_id, "patient_id": patient_id,
"record_date": "2026-10-18", "record_time": "07:40",
"fasting_blood_sugar": 6.8, "postprandial_blood_sugar": None},
],
}
@pytest.fixture(scope="module")
def application():
return QApplication.instance() or QApplication([])
def _settle(application):
for _ in range(6):
application.processEvents()
QTest.qWait(5)
@pytest.fixture
def dialog(application, monkeypatch):
instance = module.AiConsultDialog(object(), PermissionSet(["tcm.diagnosis/aiAssistant"]))
monkeypatch.setattr(instance, "_load_workspace", lambda _generation: None)
instance.open_for(diagnosis_id=501, patient_id=1501)
instance._workspace_sections = {"tracking": {"value": _tracking()}}
instance.resize(1280, 820)
instance.show()
_settle(application)
yield instance
for timer in instance.findChildren(QTimer):
timer.stop()
instance.close()
instance.deleteLater()
application.sendPostedEvents(None, QEvent.Type.DeferredDelete)
application.processEvents()
@pytest.mark.parametrize("reply, panel_type", [
(REPORT, module._StructuredReportPanel),
(CLINICAL_REPORT, module._ClinicalAnalysisPanel),
])
def test_completed_report_formats_use_observed_measurements(dialog, reply, panel_type):
bubble = dialog._append_bubble("ai", reply)
before = deepcopy(dialog._workspace_sections)
dialog._finalize_ai_bubble(bubble)
panel = bubble.findChild(panel_type)
assert panel is not None
card = panel.findChild(GlucoseReportCard)
assert card is not None and card.chart is not None
assert card.chart.data.readout_count == 3
assert [row.fasting for row in card.chart.data.readings] == [6.2, 6.8]
assert [row.postprandial for row in card.chart.data.readings] == [8.4, None]
assert dialog._workspace_sections == before
# The chart is above the textual interpretation, not a separate chat reply.
assert panel.layout().itemAt(1).widget() is card
assert bubble.body is not None and bubble.body.isHidden()
assert bubble._raw_payload == reply
def test_stream_builds_chart_on_done_once_and_keeps_timing_and_snapshot(dialog, application):
bubble = dialog._append_bubble("ai", "")
dialog._stream_bubble = bubble
dialog._stream_prompt = "请评估该患者的血糖控制情况与趋势。"
generation, stream = dialog._generation, dialog._stream_generation
dialog._stream_event(generation, stream, {"event": "delta", "text": REPORT})
dialog._flush_stream_chunks()
assert bubble.findChild(GlucoseReportCard) is None
dialog._stream_event(generation, stream, {"event": "done", "model_label": "千问"})
_settle(application)
cards = bubble.findChildren(GlucoseReportCard)
assert len(cards) == 1 and cards[0].chart is not None
assert cards[0].chart.data.readout_count == 3
panel = bubble.findChild(module._StructuredReportPanel)
assert panel is not None
dialog._stream_finished(generation, stream, object())
assert "千问" in panel.meta_label.text()
assert len(bubble.findChildren(GlucoseReportCard)) == 1
dialog._workspace_sections["tracking"]["value"]["blood_records"][0]["fasting_blood_sugar"] = 22
assert cards[0].chart.data.readings[0].fasting == 6.2
assert dialog.send_button.isEnabled()
def test_archived_and_saved_reports_receive_the_same_chart(dialog):
dialog._render_messages([{"diagnosis_id": 501, "role": "ai", "content": REPORT}])
archived = dialog.findChildren(GlucoseReportCard)
assert len(archived) == 1 and archived[0].chart is not None
dialog._render_analysis({"diagnosis_advice": "血糖记录需与实际进食时间核对。"})
charts = [card.chart for card in dialog.findChildren(GlucoseReportCard)]
assert len(charts) == 2
assert all(chart is not None and chart.data.readout_count == 3 for chart in charts)
def test_no_measurements_keeps_full_report_without_fabricated_prose_values(dialog):
dialog._workspace_sections = {"tracking": {"value": None, "error": "记录不可用"}}
reply = REPORT + "\nAI 文本举例:空腹血糖 5.6 mmol/L,餐后 8.2 mmol/L。"
bubble = dialog._append_bubble("ai", reply)
dialog._finalize_ai_bubble(bubble)
card = bubble.findChild(GlucoseReportCard)
assert card is None
assert bubble._raw_payload == reply
assert bubble.findChild(module._StructuredReportPanel) is not None
assert bubble.findChild(module.QFrame, "AiConsultReportVisual") is None
def test_plain_answer_gets_chart_but_irrelevant_answer_stays_text_only(dialog):
bubble = dialog._append_bubble("ai", "请核对原始血糖记录。")
dialog._finalize_ai_bubble(bubble)
assert bubble.findChild(GlucoseReportCard) is not None
assert bubble.body is not None and not bubble.body.isHidden()
unrelated = dialog._append_bubble("ai", "请携带既往处方核对具体药物名称。")
dialog._finalize_ai_bubble(unrelated)
assert unrelated.findChild(GlucoseReportCard) is None
def test_switching_patient_clears_chart_context_before_loading_and_ignores_old_stream(dialog):
old_generation, old_stream = dialog._generation, dialog._stream_generation
dialog.open_for(diagnosis_id=502, patient_id=1502)
assert dialog._workspace_sections == {}
assert dialog._detail == {}
bubble = dialog._append_bubble("ai", REPORT)
dialog._finalize_ai_bubble(bubble)
card = bubble.findChild(GlucoseReportCard)
assert card is None
dialog._stream_bubble = bubble
dialog._stream_event(old_generation, old_stream, {"event": "done", "answer": REPORT})
assert bubble.findChild(GlucoseReportCard) is card
# A delayed response for the previous diagnosis cannot repopulate data.
dialog._workspace_loaded(old_generation, {"diagnosis_id": 501, "tracking": {"value": _tracking()}})
assert dialog._workspace_sections == {}
def test_changed_authoritative_patient_cannot_enable_old_chart_data(dialog):
dialog.patient_id = 1999
bubble = dialog._append_bubble("ai", REPORT)
dialog._finalize_ai_bubble(bubble)
card = bubble.findChild(GlucoseReportCard)
assert card is None
@pytest.mark.parametrize("width", [1080, 1600])
def test_report_chart_and_end_of_report_remain_reachable(dialog, application, width):
dialog.resize(width, 820)
bubble = dialog._append_bubble("ai", REPORT)
dialog._finalize_ai_bubble(bubble)
_settle(application)
card = bubble.findChild(GlucoseReportCard)
assert card is not None and card.chart is not None
assert card.chart.width() > 200 and card.chart.height() > 150
assert dialog.chat_scroll.horizontalScrollBar().maximum() == 0
assert card.chart.width() <= card.width()
assert bubble._clinical_panel is not None
final_label = bubble._clinical_panel.findChildren(QLabel, "AiConsultReportBody")[-1]
dialog.chat_scroll.verticalScrollBar().setValue(dialog.chat_scroll.verticalScrollBar().maximum())
_settle(application)
bottom = final_label.mapTo(dialog.chat_scroll.viewport(), QPoint(0, final_label.height() - 1))
assert dialog.chat_scroll.viewport().rect().contains(bottom)
def test_blood_pressure_answer_automatically_chooses_pressure_instead_of_glucose(dialog):
for index, row in enumerate(dialog._workspace_sections["tracking"]["value"]["blood_records"]):
row.update(systolic_pressure=142 - index * 4, diastolic_pressure=90 - index * 2)
reply = """以下根据本诊单实际录入的血压记录梳理近期变化,需结合原始测量时间核对。
1. 血压记录与变化
- 记录核对:当前已有连续日期的收缩压和舒张压记录,图表应按实际日期显示,保留原有测量单位。
2. 随访资料核对
- 测量条件:请核对测量时的休息状态、服药时间与设备,结合完整资料由医生进一步评估。
"""
bubble = dialog._append_bubble("ai", reply)
dialog._finalize_ai_bubble(bubble, prompt="请分析血压变化。")
assert bubble.findChild(GlucoseReportCard) is None
cards = bubble.findChildren(module.QFrame, "AiConsultReportVisual")
assert cards and any(card.property("visualKind") == "blood_pressure" for card in cards)
assert all(card.data.kind == card.property("visualKind") for card in cards)
def test_numeric_ranges_and_status_are_colored_without_changing_report_text(dialog):
reply = """以下根据患者描述核对现有血糖记录,本段数字范围需要保留原文,不能自动改成精确测量点。
1. 当前控制水平:未达标
- 空腹血糖:记录为 6-7 mmol/L,需结合原始测量时间核对。
- 餐后血糖:记录为 8-9 mmol/L,当前资料尚需进一步核对。
2. 参考目标与复诊资料
- 目标说明:目标 <7.0 mmol/L 仅为报告中引用的参考内容,应与实际记录区分。
"""
dialog._workspace_sections = {}
bubble = dialog._append_bubble("ai", reply)
dialog._finalize_ai_bubble(bubble)
assert bubble.findChild(GlucoseReportCard) is None
panel = bubble.findChild(module._StructuredReportPanel)
assert panel is not None
documents = []
for label in panel.findChildren(QLabel):
doc = QTextDocument()
doc.setHtml(label.text())
documents.append(doc)
for value in ("6-7 mmol/L", "8-9 mmol/L", "<7.0 mmol/L"):
document = next(doc for doc in documents if value in doc.toPlainText())
color = document.find(value).charFormat().foreground().color().name()
assert color not in {"#000000", "#1a1c1f"}
heading = next(doc for doc in documents if "当前控制水平" in doc.toPlainText())
assert heading.find("未达标").charFormat().foreground().color().name() == "#bd4b58"
assert bubble._raw_payload == reply
def test_refinalizing_answer_replaces_visuals_without_duplicate_cards(dialog, application):
bubble = dialog._append_bubble("ai", REPORT)
dialog._finalize_ai_bubble(bubble)
assert len(bubble.findChildren(GlucoseReportCard)) == 1
dialog._finalize_ai_bubble(bubble)
application.sendPostedEvents(None, QEvent.Type.DeferredDelete)
assert len(bubble.findChildren(GlucoseReportCard)) == 1
dialog._workspace_sections = {}
dialog._finalize_ai_bubble(bubble)
application.sendPostedEvents(None, QEvent.Type.DeferredDelete)
assert bubble.findChild(GlucoseReportCard) is None
def test_short_answer_colors_values_without_replacing_markdown_or_original_payload(dialog):
reply = "**复核记录**:血压 142/90 mmHg,HbA1c 7.2%,请结合实际资料核对。"
bubble = dialog._append_bubble("ai", reply)
dialog._finalize_ai_bubble(bubble)
assert bubble.body is not None
document = bubble.body.document()
assert document.find("142/90 mmHg").charFormat().foreground().color().name() == "#697386"
assert document.find("复核记录").charFormat().fontWeight() >= 600
assert bubble._raw_payload == reply
def test_clinical_evidence_keeps_ranges_and_does_not_shorten_approximate_readings():
evidence = module._clinical_evidence("患者空腹血糖 6-7 mmol/L,其他资料待补充。")
assert evidence[0].value == "6-7 mmol/L"
approximate = module._clinical_evidence("患者空腹血糖有时6点多,尚未携带原始记录。")
assert not any(item.label == "空腹血糖" for item in approximate)
def test_multitopic_reports_switch_charts_without_hiding_or_rebuilding_analysis(dialog, application):
dialog._workspace_sections["detail"] = {"value": {"diagnosis": {
"id": 501, "patient_id": 1501, "hba1c": 7.2, "hba1c_status": "high",
}, "patient": {"id": 1501, "weight": 68, "height": 168}}}
for index, row in enumerate(dialog._workspace_sections["tracking"]["value"]["blood_records"]):
row.update(systolic_pressure=142 - index * 4, diastolic_pressure=90 - index * 2)
bubble = dialog._append_bubble("ai", REPORT)
dialog._finalize_ai_bubble(bubble, prompt="请综合分析血糖、血压和体重。")
_settle(application)
selector = bubble.findChild(QComboBox, "AiConsultReportVisualSelector")
assert selector is not None and selector.count() == 3
group = selector.parentWidget()
cards = [item.widget() for index in range(1, group.layout().count())
if (item := group.layout().itemAt(index)).widget() is not None]
assert len(cards) == 3
identities = [id(card) for card in cards]
for index in range(selector.count()):
selector.setCurrentIndex(index)
_settle(application)
assert not cards[index].isHidden()
assert all(card.isHidden() for position, card in enumerate(cards) if position != index)
assert [id(card) for card in cards] == identities
assert dialog.chat_scroll.horizontalScrollBar().maximum() == 0
assert bubble._raw_payload == REPORT
assert bubble.findChild(module._StructuredReportPanel) is not None
def _label_color(widget, reading, object_name=""):
documents = []
for label in widget.findChildren(QLabel, object_name):
document = QTextDocument()
document.setHtml(label.text())
if reading in document.toPlainText():
documents.append(document)
assert documents, f"No rendered label contains {reading!r}"
return {doc.find(reading).charFormat().foreground().color().name() for doc in documents}
def _colored_snapshot():
return {"detail": {"value": {"diagnosis": {
"id": 501, "patient_id": 1501,
"fasting_blood_sugar": "6-7", "fasting_blood_sugar_status": "high",
"postprandial_blood_sugar": "8-9", "postprandial_blood_sugar_status": "normal",
"hba1c": 7.2, "bmi": 26.1, "bmi_status": "high",
}, "patient": {"id": 1501}}}}
def test_streamed_snapshot_uses_same_colors_in_body_chart_and_raw_records(dialog):
dialog._workspace_sections = _colored_snapshot()
before = deepcopy(dialog._workspace_sections)
reply = """以下根据本诊单录入的指标核对资料,范围保留原文,由医生结合原始记录评估。
1. 本次指标记录
- 空腹血糖:记录为 6-7 mmol/L,保留原始范围。
- 餐后血糖:记录为 8-9 mmol/L,保留原始范围。
- 糖化血红蛋白:7.2%,记录未标注状态。
2. 补充资料
- 参考目标:空腹血糖目标 6-7 mmol/L,仅供核对报告中的参考内容。
"""
bubble = dialog._append_bubble("ai", "")
dialog._stream_bubble = bubble
dialog._stream_prompt = "综合分析血糖"
generation, stream = dialog._generation, dialog._stream_generation
dialog._stream_event(generation, stream, {"event": "delta", "text": reply})
dialog._stream_event(generation, stream, {"event": "done"})
panel = bubble.findChild(module._StructuredReportPanel)
assert panel is not None
assert _label_color(panel, "6-7 mmol/L", "AiConsultReportBody") == {"#bd4b58", "#697386"}
assert _label_color(panel, "8-9 mmol/L", "AiConsultReportBody") == {"#287b65"}
assert _label_color(panel, "7.2%", "AiConsultReportBody") == {"#697386"}
card = next(card for card in panel.findChildren(module.QFrame, "AiConsultReportVisual")
if card.data.kind == "metrics")
for label, color in [("空腹血糖", "#bd4b58"), ("餐后血糖", "#287b65"), ("糖化血红蛋白", "#697386")]:
index, item = next((i, item) for i, item in enumerate(card.data.items) if item.label == label)
assert item.color.lower() == color
assert card.table.item(index, 2).foreground().color().name() == color
assert bubble._raw_payload == reply
assert dialog._workspace_sections == before
def test_trend_states_also_color_short_markdown_and_combined_pressure(dialog):
rows = dialog._workspace_sections["tracking"]["value"]["blood_records"]
rows[0].update(fasting_blood_sugar_status="high", postprandial_blood_sugar_status="normal",
systolic_pressure=142, diastolic_pressure=90,
systolic_pressure_status="normal", diastolic_pressure_status="high")
reply = "**核对记录**:空腹血糖 6.2 mmol/L,餐后血糖 8.4 mmol/L,血压 142/90 mmHg。"
bubble = dialog._append_bubble("ai", reply)
dialog._finalize_ai_bubble(bubble)
document = bubble.body.document()
for reading, color in [("6.2 mmol/L", "#bd4b58"), ("8.4 mmol/L", "#287b65"), ("142/90 mmHg", "#bd4b58")]:
assert document.find(reading).charFormat().foreground().color().name() == color
assert document.toPlainText() == "核对记录:空腹血糖 6.2 mmol/L,餐后血糖 8.4 mmol/L,血压 142/90 mmHg。"
assert document.find("核对记录").charFormat().fontWeight() >= 600
# Rendering a different record cannot inherit the previous report's source flags.
dialog._workspace_sections = {}
other = dialog._append_bubble("ai", reply)
dialog._finalize_ai_bubble(other)
assert other.body.document().find("6.2 mmol/L").charFormat().foreground().color().name() == "#697386"
assert document.find("6.2 mmol/L").charFormat().foreground().color().name() == "#bd4b58"
def test_saved_summary_and_key_facts_share_source_state_and_missing_palette(dialog):
dialog._workspace_sections = _colored_snapshot()
dialog._workspace_sections["detail"]["value"]["diagnosis"]["hba1c_status"] = "high"
dialog._apply_header(dialog._workspace_sections["detail"]["value"])
facts = dialog.findChildren(QLabel, "AiConsultKeyValue")
assert next(label for label in facts if label.text() == "26.1").styleSheet() == "color: #bd4b58;"
assert all(label.styleSheet() == "color: #697386;" for label in facts if label.text() == "未记录")
dialog._render_analysis({
"diagnosis_advice": "空腹血糖 6-7 mmol/L,餐后血糖 8-9 mmol/L。HbA1c 7.2%。",
"risk_assessment": [{"label": "随访风险", "level": "medium"}],
})
assert _label_color(dialog, "6-7 mmol/L", "AiConsultInsightText") == {"#bd4b58"}
assert _label_color(dialog, "8-9 mmol/L", "AiConsultInsightText") == {"#287b65"}
assert _label_color(dialog, "7.2%", "AiConsultInsightText") == {"#bd4b58"}
badge = next(label for label in dialog.findChildren(QLabel, "AiConsultTag") if label.text() == "中风险")
assert "#BD4B58" in badge.styleSheet()
@pytest.mark.parametrize("text", ["HbA1c 7.2%", "7.2 mmol/L 为原始记录", "指标:7.2%"])
def test_sidebar_does_not_split_decimal_measurements_into_list_markers(text):
segments = module._split_insight_segments(text)
assert len(segments) == 1
assert segments[0].kind != "list" and "7.2" in segments[0].text
def test_numbered_sidebar_summary_preserves_decimals_and_actual_list_structure():
segments = module._split_insight_segments("建议:1. 复核 HbA1c 7.2% 2. 核对空腹血糖 6.8 mmol/L")
numbered = [item for item in segments if item.kind == "list"]
assert [(item.marker, item.text) for item in numbered] == [
("1.", "复核 HbA1c 7.2%"), ("2.", "核对空腹血糖 6.8 mmol/L"),
]
+571
View File
@@ -0,0 +1,571 @@
from __future__ import annotations
import os
from copy import deepcopy
from dataclasses import FrozenInstanceError, replace
from datetime import datetime
from typing import Any
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from PySide6.QtCore import QPointF, Qt
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication, QLabel, QToolTip
from doctor_workstation.core.models import Prescription
from doctor_workstation.ui.dialogs.ai_consult_charts import GlucoseChartData, GlucoseReportCard
from doctor_workstation.ui.dialogs.ai_consult_metric_state import (
ABNORMAL_COLOR,
NORMAL_COLOR,
UNKNOWN_COLOR,
)
from doctor_workstation.ui.dialogs.ai_consult_report_visuals import (
ReportVisualCard,
build_report_visuals,
create_report_visual,
)
@pytest.fixture(scope="module")
def application() -> QApplication:
return QApplication.instance() or QApplication([])
def _row(day: str = "2026-08-18", **changes: Any) -> dict[str, Any]:
return {
"diagnosis_id": 501,
"patient_id": 1501,
"record_date": day,
"fasting_blood_sugar": 6.8,
"systolic_pressure": 146,
"diastolic_pressure": 92,
**changes,
}
def _sections(*rows: Any, **diagnosis: Any) -> dict[str, Any]:
return {
"detail": {"value": {"diagnosis": {"id": 501, "patient_id": 1501, **diagnosis}}},
"tracking": {
"value": {"diagnosis_id": 501, "patient_id": 1501, "blood_records": list(rows)}
},
}
def _build(sections: dict[str, Any], prompt: str = "分析血压", reply: str = ""):
return build_report_visuals(prompt, reply, sections=sections, diagnosis_id=501, patient_id=1501)
def _kind(data: Any) -> str:
return "glucose" if isinstance(data, GlucoseChartData) else data.kind
def test_selects_actual_topics_in_prompt_or_reply_without_unrelated_charts() -> None:
sections = _sections(_row(), weight=60, hba1c=7.2)
assert [_kind(item) for item in _build(sections)] == ["blood_pressure"]
assert [_kind(item) for item in _build(sections, "", "检查空腹血糖")] == ["glucose", "metrics"]
assert _build(sections, "解释睡眠质量") == ()
assert [_kind(item) for item in _build(sections, "综合分析")] == [
"glucose",
"blood_pressure",
"metrics",
]
@pytest.mark.parametrize(
"topic", ["血糖", "血压", "血脂", "体重", "肾功能", "风险", "用药", "运动", "综合分析"]
)
def test_no_actual_data_never_produces_chart_shell(topic: str) -> None:
assert _build({}, topic, "目标血压 120/80,HbA1c 6.5%,每日运动30分钟") == ()
assert _build(_sections(), topic) == ()
def test_ai_prose_goals_and_approximate_numbers_never_become_observations() -> None:
sections = _sections(
_row(systolic_pressure="约146", diastolic_pressure="90-95", fasting_blood_sugar="~6.8")
)
assert _build(sections, "分析血压和血糖", "今天146/92,目标120/80,血糖7.0") == ()
@pytest.mark.parametrize("owner", [None, True, "501", 501.0, 0, 502])
def test_tracking_root_and_rows_need_exact_diagnosis_owner(owner: Any) -> None:
root = _sections(_row())
root["tracking"]["value"]["diagnosis_id"] = owner
assert _build(root) == ()
rows = _sections(_row(diagnosis_id=owner), _row("2026-08-19"))
visual = _build(rows)[0]
assert len(visual.items) == 2
assert all(item.recorded_at.day == 19 for item in visual.items)
@pytest.mark.parametrize("owner", [None, True, "1501", 1501.0, 0, 1502])
def test_declared_patient_owner_is_checked_at_tracking_root_and_row(owner: Any) -> None:
root = _sections(_row())
root["tracking"]["value"]["patient_id"] = owner
assert _build(root) == ()
assert _build(_sections(_row(patient_id=owner))) == ()
@pytest.mark.parametrize("owner", [None, True, "501", 501.0, 502])
def test_mismatched_detail_disables_linked_visuals(owner: Any) -> None:
sections = _sections(_row(), id=owner, hba1c=7.2)
assert _build(sections, "综合分析") == ()
def test_detail_patient_conflicts_and_section_errors_fail_closed() -> None:
assert _build(_sections(_row(), patient_id=1502)) == ()
sections = _sections(_row(), weight=60)
sections["detail"]["value"]["patient"] = {"id": 1502}
assert _build(sections, "综合分析") == ()
sections = _sections(_row())
sections["tracking"]["error"] = "接口失败"
assert _build(sections) == ()
def test_dto_snapshot_is_immutable_and_keeps_dates_gaps_and_duplicate_rows() -> None:
sections = _sections(
_row("2026-08-21", systolic_pressure=150),
_row("2026-08-18", systolic_pressure=140),
_row("2026-08-18", systolic_pressure=141),
_row("2026-08-19", systolic_pressure=None, diastolic_pressure=None),
)
before = deepcopy(sections)
data = _build(sections)[0]
assert sections == before
assert [item.value for item in data.items if item.series == "systolic_pressure"] == [
140,
141,
None,
150,
]
assert data.items[0].recorded_at == datetime(2026, 8, 18)
with pytest.raises(FrozenInstanceError):
data.items[0].value = 100 # type: ignore[misc]
sections["tracking"]["value"]["blood_records"][1]["systolic_pressure"] = 999
assert data.items[0].value == 140
@pytest.mark.parametrize(
"value", [True, "约 130", "120-140", "<140", float("nan"), float("inf"), 0, -1]
)
def test_ambiguous_pressure_readings_are_not_plotted(value: Any) -> None:
assert _build(_sections(_row(systolic_pressure=value, diastolic_pressure=None))) == ()
def test_no_dated_pressure_is_replaced_by_a_snapshot_only_when_detail_is_real() -> None:
sections = _sections(_row("不是日期"), systolic_pressure=130, diastolic_pressure=80)
data = _build(sections)[0]
assert data.kind == "metrics"
assert [item.value for item in data.items] == [130, 80]
assert all(item.recorded_at is None and item.reference is None for item in data.items)
def test_status_colors_come_only_from_source_and_units_are_separate() -> None:
data = _build(
_sections(
hba1c=12.5,
hba1c_status="normal",
cholesterol=5.2,
cholesterol_status="high",
microalbumin=12,
microalbumin_status="low",
weight=100,
bmi=35,
),
"综合分析",
)[0]
assert data.kind == "metrics"
metrics = {item.label: item for item in data.items}
assert metrics["糖化血红蛋白"].color == NORMAL_COLOR
assert metrics["总胆固醇"].color == ABNORMAL_COLOR
assert metrics["尿微量白蛋白"].color == ABNORMAL_COLOR
assert metrics["体重"].color == metrics["BMI"].color == UNKNOWN_COLOR
assert [
(metrics[key].unit) for key in ("糖化血红蛋白", "总胆固醇", "尿微量白蛋白", "体重", "BMI")
] == ["%", "mmol/L", "mg/L", "kg", "kg/m²"]
assert all(item.reference is None for item in data.items)
assert metrics["BMI"].value == 35
def test_source_units_override_defaults_without_conversion_or_shared_scale() -> None:
data = _build(
_sections(creatinine="1.1 mg/dL", creatinine_unit="mg/dL", weight="60 kg"), "肾功能与体重"
)[0]
assert [(item.value, item.unit) for item in data.items] == [(1.1, "mg/dL"), (60, "kg")]
assert all(item.reference is None for item in data.items)
def test_recorded_interval_is_distinct_from_exact_points_and_has_no_invented_date() -> None:
data = _build(
_sections(fasting_blood_sugar="6-7", postprandial_blood_sugar="8~9 mmol/L"), "血糖"
)[0]
assert data.kind == "metrics"
assert [item.interval for item in data.items] == [(6, 7), (8, 9)]
assert all(
item.value is None and item.recorded_at is None and item.reference is None
for item in data.items
)
assert data.items[1].value_text == "8~9 mmol/L"
def test_owned_patient_body_measurements_are_used_when_not_repeated_in_diagnosis() -> None:
sections = _sections()
sections["detail"]["value"]["patient"] = {"id": 1501, "weight": 68, "height": 168}
data = _build(sections, "体重与BMI")[0]
assert [(item.label, item.value, item.unit) for item in data.items] == [
("体重", 68, "kg"), ("身高", 168, "cm"),
]
assert all(item.color == UNKNOWN_COLOR and not item.status for item in data.items)
assert not any(item.label == "BMI" for item in data.items)
def test_metric_snapshot_uses_two_columns_on_wide_reports_and_localizes_status(application):
data = _build(_sections(hba1c=7.2, hba1c_status="high", weight=68, bmi=24), "综合分析")[0]
card = create_report_visual(data)
card.resize(760, card.sizeHint().height())
card.show()
application.processEvents()
wide_height = card.chart.height()
assert card.chart._columns == 2
assert "偏高" in card.chart.accessibleDescription()
assert card.table.item(0, 3).text() == "偏高"
assert "体重" in card.chart._point_tooltip(QPointF(card.chart.width() / 2 + 20, 10))
card.resize(320, card.height())
application.processEvents()
assert card.chart._columns == 1
assert card.chart.height() > wide_height
card.close()
card.deleteLater()
def test_reference_scale_requires_actual_stored_limits_and_keeps_zero() -> None:
data = _build(
_sections(
microalbumin=18,
microalbumin_reference_range={"low": 0, "high": 30, "unit": "mg/L"},
hba1c=7.2,
hba1c_reference_range="4-6 %",
weight=60,
),
"综合分析",
)[0]
assert [item.reference for item in data.items] == [(4, 6), (0, 30), None]
incompatible = _build(
_sections(
creatinine=100, creatinine_reference_range={"low": 0, "high": 2, "unit": "mg/dL"}
),
"肾功能",
)[0]
assert incompatible.items[0].reference is None
def test_foreign_nested_lab_values_are_not_adopted() -> None:
sections = _sections()
sections["detail"]["value"]["labs"] = {"diagnosis_id": 502, "hba1c": 7.2}
assert _build(sections, "糖化血红蛋白") == ()
@pytest.mark.parametrize(
("status", "color"),
[("high", ABNORMAL_COLOR), ("low", ABNORMAL_COLOR), ("warning", ABNORMAL_COLOR),
("异常", ABNORMAL_COLOR), ("normal", NORMAL_COLOR), ("正常", NORMAL_COLOR),
("unknown", UNKNOWN_COLOR), ("unclassified", UNKNOWN_COLOR), (None, UNKNOWN_COLOR),
(True, UNKNOWN_COLOR), ({"normal": True}, UNKNOWN_COLOR)],
)
def test_snapshot_flags_use_the_shared_palette_without_thresholds(status, color) -> None:
data = _build(_sections(hba1c=40, hba1c_status=status), "糖化血红蛋白")[0]
assert data.items[0].value == 40
assert data.items[0].color == color
assert "蓝色" not in data.source and "橙" not in data.source
assert "灰色未记录/未标注" in data.source
def test_pressure_points_raw_cells_and_tooltips_keep_only_recorded_states(application) -> None:
data = _build(_sections(
_row("2026-08-18", systolic_pressure=200, systolic_pressure_status="normal",
diastolic_pressure=60, diastolic_status="low"),
_row("2026-08-19", systolic_pressure=220, diastolic_pressure=None,
diastolic_pressure_status="normal"),
_row("2026-08-20", systolic_pressure=210, systolic_status="warning",
diastolic_pressure=70, diastolic_pressure_status="unknown"),
))[0]
assert [(item.status, item.color) for item in data.items] == [
("normal", NORMAL_COLOR), ("low", ABNORMAL_COLOR),
("", UNKNOWN_COLOR), ("normal", UNKNOWN_COLOR),
("warning", ABNORMAL_COLOR), ("unknown", UNKNOWN_COLOR),
]
card = create_report_visual(data)
card.resize(650, card.sizeHint().height())
card.show()
application.processEvents()
image = card.chart.grab().toImage()
for index, item in enumerate(data.items):
for column in (2, 3):
cell = card.table.item(index, column)
assert cell.foreground().color().name() == item.color.casefold()
assert "状态" in cell.toolTip()
if item.status:
assert item.status in cell.toolTip()
if item.value is not None:
point = card.chart._position(item)
assert image.pixelColor(point.toPoint()).name() == item.color.casefold()
assert item.status in card.chart._point_tooltip(point)
assert card.table.item(3, 2).text() == "—"
assert card.table.item(3, 3).text() == "未记录"
assert "舒张压 · — · 状态 未记录" in card.chart.accessibleDescription()
assert "收缩压实线圆点,舒张压虚线方点" in card.chart.accessibleDescription()
card.close()
def test_pressure_statuses_cannot_be_borrowed_from_root_or_foreign_rows() -> None:
sections = _sections(
_row(systolic_pressure=200, diastolic_pressure=110),
_row("2026-08-19", diagnosis_id=502, systolic_pressure_status="normal"),
)
sections["tracking"]["value"]["systolic_pressure_status"] = "normal"
items = _build(sections)[0].items
assert len(items) == 2
assert all(item.status == "" and item.color == UNKNOWN_COLOR for item in items)
def test_pressure_connection_is_gray_between_explicit_abnormal_points(application) -> None:
data = _build(_sections(
_row("2026-08-18", systolic_pressure=140, systolic_pressure_status="high",
diastolic_pressure=None),
_row("2026-08-20", systolic_pressure=140, systolic_pressure_status="high",
diastolic_pressure=None),
))[0]
card = create_report_visual(data)
card.resize(640, card.sizeHint().height())
card.show()
application.processEvents()
points = [card.chart._position(item) for item in data.items if item.value is not None]
midpoint = (points[0] + points[1]) / 2
image = card.chart.grab().toImage()
assert image.pixelColor(midpoint.toPoint()).name() == UNKNOWN_COLOR.casefold()
assert image.pixelColor(points[0].toPoint()).name() == ABNORMAL_COLOR.casefold()
card.close()
def test_reference_band_is_neutral_and_never_assigns_normal_status(application) -> None:
data = _build(_sections(hba1c=5, hba1c_reference_range="4-6 %"), "糖化血红蛋白")[0]
assert data.items[0].color == UNKNOWN_COLOR and data.items[0].status == ""
card = create_report_visual(data)
card.resize(400, card.sizeHint().height())
card.show()
application.processEvents()
image = card.chart.grab().toImage()
assert image.pixelColor(20, 54).name() == UNKNOWN_COLOR.casefold()
assert card.table.item(0, 2).foreground().color().name() == UNKNOWN_COLOR.casefold()
assert card.table.item(0, 3).text() == "未标注"
assert "状态 未标注" in card.table.item(0, 2).toolTip()
card.close()
def test_risks_are_exact_categorical_annotations_not_numeric_scores() -> None:
sections = _sections()
sections["analysis"] = {
"value": {
"patient_id": 1501,
"source_diagnosis_ids": [499, 501],
"risk_assessment": [
{"label": level, "level": level, "score": 99, "probability": 0.9}
for level in ("high", "medium", "low", "unknown")
]
+ [{"label": "未核验", "level": "severe"}, {"label": "无等级", "level": None}],
}
}
data = _build(sections, "风险评估")[0]
assert data.kind == "risks"
assert [item.status for item in data.items] == ["high", "medium", "low", "unknown"]
assert [item.color for item in data.items] == [
ABNORMAL_COLOR, ABNORMAL_COLOR, NORMAL_COLOR, UNKNOWN_COLOR,
]
assert all(
item.value is None and item.reference is None and "%" not in item.raw_value
for item in data.items
)
assert "定性风险标注" in data.source and "#499、#501" in data.source
@pytest.mark.parametrize(
"metadata",
[
{},
{"patient_id": 1502, "source_diagnosis_ids": [501]},
{"patient_id": 1501, "source_diagnosis_ids": [502]},
{"diagnosis_id": "501"},
{"diagnosis_id": 502},
],
)
def test_unowned_and_foreign_risk_reports_do_not_get_visuals(metadata: Any) -> None:
sections = _sections()
sections["analysis"] = {
"value": {**metadata, "risk_assessment": [{"label": "风险项", "level": "high"}]}
}
assert _build(sections, "风险") == ()
def test_nested_saved_report_uses_its_original_owner_and_levels() -> None:
sections = _sections()
sections["analysis"] = {
"value": {
"latest_by_model": {
"qwen": {
"patient_id": 1501,
"source_diagnosis_ids": [499, 501],
"diagnosis_id": 499,
"report": {"risk_assessment": [{"label": "血糖波动", "level": "medium"}]},
}
}
}
}
assert _build(sections, "风险")[0].items[0].status == "medium"
sections["analysis"]["value"]["latest_by_model"]["qwen"]["report"]["patient_id"] = 1502
assert _build(sections, "风险") == ()
def test_prescription_timeline_accepts_dto_and_preserves_dates_name_status() -> None:
sections = _sections()
sections["prescriptions"] = {
"value": [
Prescription(
diagnosis_id=501,
prescription_date="2026-08-19",
herbs=[{"name": "黄芪"}],
audit_status=1,
),
{
"diagnosis_id": 501,
"patient_id": 1501,
"prescription_date": "2026-08-18",
"prescription_name": "益气方",
"status_text": "已审核",
},
{
"diagnosis_id": 502,
"prescription_date": "2026-08-17",
"prescription_name": "外国诊单",
"status_text": "已审核",
},
{"diagnosis_id": 501, "prescription_name": "没有日期", "status_text": "已审核"},
]
}
data = _build(sections, "用药合理性")[0]
assert data.kind == "medications"
assert [(item.time_label, item.label, item.status) for item in data.items] == [
("2026-08-18", "益气方", "已审核"),
("2026-08-19", "黄芪", "已通过"),
]
assert all(item.value is None for item in data.items)
def test_dto_coercion_does_not_hide_invalid_raw_prescription_ownership() -> None:
sections = _sections()
sections["prescriptions"] = {
"value": [
Prescription.from_dict(
{
"diagnosis_id": "501",
"prescription_date": "2026-08-18",
"prescription_name": "益气方",
"status_text": "已审核",
}
)
]
}
assert _build(sections, "用药") == ()
def test_unitless_bmi_state_remains_a_measurement_instead_of_a_risk_label(application) -> None:
data = _build(_sections(bmi=26.1, bmi_status="high"), "体重")[0]
data = replace(data, items=tuple(replace(item, unit="") for item in data.items))
card = ReportVisualCard(data)
try:
assert card.table.item(0, 3).text() == "偏高"
assert card.table.item(0, 3).foreground().color().name() == "#bd4b58"
finally:
card.deleteLater()
def test_exercise_uses_actual_duration_minutes_with_no_target_bars() -> None:
sections = _sections()
sections["tracking"]["value"]["exercise_records"] = [
_row("2026-08-18", duration=35),
_row("2026-08-19", duration="约40"),
_row("2026-08-20", duration=40, patient_id=1502),
]
data = _build(sections, "建议运动150分钟")[0]
assert data.kind == "exercise"
assert [item.value for item in data.items] == [35, None]
assert data.items[0].unit == "分钟"
def test_charts_render_at_320px_with_exact_hover_and_raw_data(application: QApplication) -> None:
sections = _sections(
_row("2026-08-18"), _row("2026-08-19"), _row("2026-08-21"), hba1c=7.2, hba1c_status="high"
)
sections["analysis"] = {
"value": {
"diagnosis_id": 501,
"risk_assessment": [{"label": "血压波动风险", "level": "medium"}],
}
}
sections["prescriptions"] = {
"value": [
{
"diagnosis_id": 501,
"prescription_date": "2026-08-19",
"prescription_name": "益气方",
"status_text": "已审核",
}
]
}
sections["tracking"]["value"]["exercise_records"] = [_row(duration=35)]
data = _build(sections, "综合分析")
assert {_kind(item) for item in data} == {
"glucose",
"blood_pressure",
"metrics",
"risks",
"medications",
"exercise",
}
for item in data:
card = create_report_visual(item)
card.resize(320, card.sizeHint().height())
card.show()
application.processEvents()
try:
assert card.width() == 320
assert card.minimumSizeHint().width() <= 320
assert not card.grab().isNull()
assert not any("暂无可绘制" in label.text() for label in card.findChildren(QLabel))
if isinstance(card, GlucoseReportCard):
continue
assert isinstance(card, ReportVisualCard)
assert (
card.objectName() == "AiConsultReportVisual"
and card.property("visualKind") == item.kind
)
QTest.mouseClick(card.toggle_button, Qt.MouseButton.LeftButton)
application.processEvents()
assert card.table.isVisible() and card.table.rowCount() == len(item.items)
assert card.table.item(0, 1).text() == item.items[0].label
position = card.chart._position(item.items[0]) if card.chart._trend else QPointF(20, 10)
assert item.items[0].label in card.chart._point_tooltip(position)
if item.kind == "blood_pressure":
first, middle, last = [
datum for datum in item.items if datum.series == "systolic_pressure"
]
positions = [card.chart._position(datum).x() for datum in (first, middle, last)]
assert (positions[1] - positions[0]) / (
positions[2] - positions[0]
) == pytest.approx(1 / 3)
QTest.mouseMove(card.chart, position.toPoint())
application.processEvents()
assert "146 mmHg" in QToolTip.text()
finally:
card.close()
card.deleteLater()
@@ -0,0 +1,177 @@
"""Paint the actual measured source text, including long unbroken record values."""
from __future__ import annotations
import json
import os
from html import escape
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from PySide6.QtCore import QEvent, Qt, QTimer
from PySide6.QtGui import QTextCursor, QTextDocument
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication, QLabel, QTextBrowser
from doctor_workstation.core import PermissionSet
from doctor_workstation.ui.dialogs import ai_consult as module
from doctor_workstation.ui.theme import apply_theme
@pytest.fixture(scope="module")
def application():
app = QApplication.instance() or QApplication([])
apply_theme(app)
return app
@pytest.mark.parametrize("rich", [True, False])
def test_long_unbroken_tail_uses_actual_paint_document_and_exact_selection(application, rich):
text = "record_date" * 100 + "TAIL_SENTINEL"
label = module._FittedText(module._reading_html(text) if rich else text, rich=rich)
label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
try:
label.show()
for width in (528, 240, 760, 528):
label.resize(width, label.height())
QTest.qWait(5)
label._fit()
view = label._text_view
document = view.document()
assert document is label._measure_document
assert document.toPlainText() == text
layout = document.firstBlock().layout()
assert layout.lineCount() > 5
assert all(layout.lineAt(n).naturalTextWidth() <= view.viewport().width()
for n in range(layout.lineCount()))
cursor = QTextCursor(document)
cursor.movePosition(QTextCursor.MoveOperation.End)
view.setTextCursor(cursor)
assert view.cursorRect().bottom() < view.viewport().height()
assert view.verticalScrollBar().maximum() == 0
image = view.viewport().grab().toImage()
# The final line actually paints at its document position, rather
# than a separate QLabel painter centering one clipped long token.
rect = view.cursorRect()
assert any(image.pixelColor(x, y).alpha() > 0
and image.pixelColor(x, y).red() < 180
for y in range(max(0, rect.top()), min(image.height(), rect.bottom() + 1))
for x in range(image.width()))
label.setSelection(len(text) - len("TAIL_SENTINEL"), len("TAIL_SENTINEL"))
assert label.hasSelectedText() and label.selectedText() == "TAIL_SENTINEL"
finally:
label.close()
label.deleteLater()
@pytest.mark.parametrize("layers", [0, 1, 2])
def test_source_fields_are_readable_without_rewriting_original_reply(application, layers):
record = {"record_date": 1775577600, "record_time": "07:30", "fasting_blood_sugar": 6.2,
"unknown_key": "保留未知字段", "zero": 0, "flag": False, "missing": None,
"nested": {"note": "<script>保留字面文本</script>;血糖 <7.0 mmol/L"}}
raw = json.dumps(record, ensure_ascii=False, separators=(",", ":"))
for _ in range(layers):
raw = escape(raw)
original = raw
rendered = QTextDocument()
rendered.setHtml(module._reading_html(raw))
plain = rendered.toPlainText()
assert "记录日期:2026-04-08" in plain
assert "记录时间:07:30" in plain
assert "6.2" in plain and "unknown_key:保留未知字段" in plain
assert "zero:0" in plain and "flag:否" in plain and "missing:未记录" in plain
assert "<script>保留字面文本</script>" in plain and "血糖 <7.0 mmol/L" in plain
assert "&quot;" not in plain
assert raw == original
@pytest.mark.parametrize("raw", [
'{"record_date":1775577600,"record_date":1775664000,"note":"原文不删"}',
'{"record_date":1775577600,"note":"未闭合尾部',
'{"record_date":1775577600,"number":NaN}',
])
def test_unsupported_source_stays_literal_and_complete(application, raw):
rendered = QTextDocument()
rendered.setHtml(module._reading_html(escape(raw)))
assert rendered.toPlainText() == raw
def test_source_continuation_keeps_date_role_and_one_owning_bullet():
record = escape('{"record_date":1775577600,"note":"原记录终点"}')
raw = ("## 一、原始资料\n- 2026-04-08 · 日常记录原文(非本次建议):\\[\n"
+ record + "\n\\]\n\n## 二、待核对\n- " + "只核对已采集资料,不添加患者事实。" * 5)
original = raw
_, sections, _ = module.parse_structured_report(raw)
assert len(sections[0].items) == 1
assert "日常记录原文(非本次建议)" in sections[0].items[0]
shown = module._report_display_text(sections[0].items[0])
assert "2026-04-08" in shown and "原记录终点" in shown
assert r"\[" not in shown and r"\]" not in shown
assert raw == original
assert "<7.0" in module._plain_markdown("血糖 <7.0,餐后 >10 mmol/L")
def test_pretty_source_is_grouped_before_markdown_changes_keys_or_values():
record = {"record_date": 1775577600, "unknown__key": "字面 **内容** 与 __标记__",
"nested": {"text": "<script>原字面值</script>"}}
raw = ("## 一、原始资料\n- 2026-04-08 · 日常记录原文:\\[\n"
+ json.dumps(record, ensure_ascii=False, indent=2)
+ "\n\\]\n## 二、复核\n- " + "保留资料,不添加患者事实。" * 5)
original = raw
_, sections, _ = module.parse_structured_report(raw)
assert len(sections[0].items) == 1
shown = QTextDocument()
shown.setHtml(module._reading_html(sections[0].items[0]))
assert "unknown__key:字面 **内容** 与 __标记__" in shown.toPlainText()
assert "<script>原字面值</script>" in shown.toPlainText()
assert raw == original
@pytest.mark.parametrize("repeat", [1, 100])
def test_pretty_negative_array_entries_keep_signs_and_do_not_become_bullets(repeat):
values = ",\n".join([" -1", " -0.25", " -3.5e-06"] * repeat)
body = '{\n "record_date":1775577600,\n "values":[\n' + values + '\n ],\n "tail":"NEGATIVE_ARRAY_TAIL"\n}'
raw = ("## 一、资料\n- 日常记录原文:\\[\n" + body
+ "\n\\]\n- 独立下一项\n## 二、核对\n- " + "保留原数据和日期,不编造。" * 5)
_, sections, _ = module.parse_structured_report(raw)
assert len(sections[0].items) == 2
shown = module._report_display_text(sections[0].items[0])
assert "-1、-0.25、-3.5e-06" in shown
assert shown.count("-3.5e-06") == repeat
assert "NEGATIVE_ARRAY_TAIL" in shown
assert sections[0].items[1] == "独立下一项"
def test_sidebar_tools_do_not_duplicate_on_report_resize_and_scroll(application, monkeypatch):
dialog = module.AiConsultDialog(object(), PermissionSet(["tcm.diagnosis/aiAssistant"]))
monkeypatch.setattr(dialog, "_load_workspace", lambda _: None)
try:
dialog.open_for(diagnosis_id=501, patient_id=1501)
original = "## 一、核对资料\n- " + "完整记录,不编造缺项。" * 100 + "\n## 二、核对结尾\n- 独有结尾"
bubble = dialog._append_bubble("ai", original)
assert bubble.finalize_clinical_analysis()
dialog.show()
for width, height in ((1280, 820), (1635, 3708), (1080, 680), (1440, 900), (1280, 820)):
dialog.resize(width, height)
QTest.qWait(30)
tools = dialog.findChildren(module._ClickCard, "AiConsultToolCard")
suggestions = dialog.findChildren(module._ClickCard, "AiConsultSuggestRow")
assert len(tools) == 6 and len(suggestions) == 5
for card, (_, text, _) in zip(tools, module.TOOL_ITEMS):
labels = card.findChildren(QLabel)
assert sum(label.text() == text for label in labels) == 1
assert len([label for label in labels if not label.pixmap().isNull()]) == 1
for value in (0, dialog.chat_scroll.verticalScrollBar().maximum()):
dialog.chat_scroll.verticalScrollBar().setValue(value)
application.processEvents()
assert bubble._raw_payload == original
assert dialog.findChild(module.QWidget, "AiConsultSideCanvas") is not None
assert dialog.findChild(module.QWidget, "AiConsultSideViewport") is not None
assert bubble.findChildren(QTextBrowser, "AiConsultFittedViewport")
finally:
for timer in dialog.findChildren(QTimer):
timer.stop()
dialog.close()
dialog.deleteLater()
application.sendPostedEvents(None, QEvent.Type.DeferredDelete)
application.processEvents()
@@ -0,0 +1,230 @@
"""Transfer receipts stay collapsed above the answer throughout its lifecycle."""
from __future__ import annotations
import os
from datetime import datetime
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
from doctor_workstation.core import PermissionSet
from doctor_workstation.ui.dialogs import ai_consult as module
from doctor_workstation.ui.dialogs.ai_consult_charts import GlucoseChartData, GlucoseReading
REPORT = """以下为合成测试资料的核对清单,所有结论需要结合原始记录及记录日期进一步确认。
1. 记录核对
- 来源范围:保留现有资料,逐项确认填写情况与来源,不补写缺失的内容。
2. 后续核对
- 记录日期:继续核对已有记录的完整性,保留最终唯一标记。
"""
@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),
))
instance = module.AiConsultDialog(object(), PermissionSet(["tcm.diagnosis/aiAssistant"]))
monkeypatch.setattr(instance, "_load_workspace", lambda _: None)
instance.open_for(diagnosis_id=501, patient_id=1501)
instance.resize(1280, 820)
instance.show()
yield instance
for timer in instance.findChildren(QTimer):
timer.stop()
instance.close()
instance.deleteLater()
application.sendPostedEvents(None, QEvent.Type.DeferredDelete)
application.processEvents()
def _manifest():
statuses = ["submitted", "prepared", "submitting", "failed", "omitted"]
return {
"source_summary": {"diagnosis_count": 2, "blood_record_count": 3},
"required_sections": [
{"key": key, "status": statuses[index % len(statuses)],
"availability": "empty" if index == 1 else "present"}
for index, (key, _) in enumerate(module._REQUIRED_TRANSFER_SECTIONS)
],
"items": [
{"kind": "image", "label": "图片附件1", "status": "submitted"},
{"kind": "document", "label": "文档附件2", "status": "skipped", "reason": "not_found"},
{"kind": "audio", "label": "音频附件3", "status": "failed"},
{"kind": "custom", "label": "附件4", "status": "omitted"},
],
"attachment_count": 4,
"submitted_attachment_count": 1,
"attachment_transfer": "uploaded_files",
"source_form": "evidence_summary",
"evidence_cache_hit": True,
}
@pytest.mark.parametrize("report", [False, True])
def test_receipt_is_collapsed_above_report_chart_and_body(application, report):
bubble = module._ChatBubble(role="ai", text=REPORT if report else "核对合成记录。")
description = module._transfer_description(_manifest(), "本次回复已完成。")
bubble.set_transfer_status(description)
chart = GlucoseChartData(readings=(GlucoseReading(datetime(2026, 10, 20), fasting=6.2),))
assert bubble.finalize_clinical_analysis(chart_data=chart) is report
bubble.resize(780, 700)
bubble.show()
application.processEvents()
assert bubble._inner.itemAt(0).widget() is bubble.transfer_receipt
assert bubble.transfer_receipt.isVisible()
assert bubble.transfer_status.isHidden()
assert not bubble.transfer_toggle.isChecked()
assert "展开详情" in bubble.transfer_toggle.text()
assert bubble.transfer_status.text() == description
assert len(bubble.findChildren(QLabel, "AiConsultTransferStatus")) == 1
QTest.mouseClick(bubble.transfer_toggle, Qt.MouseButton.LeftButton)
assert bubble.transfer_status.isVisible() and bubble.transfer_toggle.isChecked()
assert "收起详情" in bubble.transfer_toggle.text()
assert bubble.transfer_status.textInteractionFlags() & Qt.TextInteractionFlag.TextSelectableByMouse
assert all(f"{label}:" in bubble.transfer_status.text()
for _, label in module._REQUIRED_TRANSFER_SECTIONS)
assert "无(已整理,待提交)" in bubble.transfer_status.text()
assert "血糖血压记录 3 条" in bubble.transfer_status.text()
assert "文件不存在,已跳过" in bubble.transfer_status.text()
assert "音频附件3(音频):提交失败" in bubble.transfer_status.text()
assert "附件4(附件):未提交" in bubble.transfer_status.text()
assert "本请求附件通道:1 项" in bubble.transfer_status.text()
assert "资料栏目提交清单" not in bubble.body.toPlainText()
QTest.mouseClick(bubble.transfer_toggle, Qt.MouseButton.LeftButton)
assert bubble.transfer_status.isHidden()
bubble.close()
bubble.deleteLater()
def test_receipt_progress_keeps_expansion_and_does_not_reparse_body(application, monkeypatch):
bubble = module._ChatBubble(role="ai", text="合成正文保持完整。")
first = module._transfer_description(_manifest(), "正在提交资料…")
bubble.set_transfer_status(first)
bubble.transfer_toggle.click()
bubble.transfer_status.setSelection(0, 4)
selected = bubble.transfer_status.selectedText()
monkeypatch.setattr(bubble.body, "set_payload", lambda *_: pytest.fail("receipt reparsed answer"))
for _ in range(20):
bubble.set_transfer_status(first)
assert bubble.transfer_status.selectedText() == selected
next_text = module._transfer_description(_manifest(), "已收到 AI 正文,正在生成…")
bubble.set_transfer_status(next_text)
assert bubble.transfer_toggle.isChecked() and not bubble.transfer_status.isHidden()
bubble.transfer_toggle.click()
bubble.set_transfer_status(module._transfer_description(_manifest(), "本次回复已完成。"))
assert not bubble.transfer_toggle.isChecked() and bubble.transfer_status.isHidden()
assert bubble.body.toPlainText() == "合成正文保持完整。"
bubble.deleteLater()
@pytest.mark.parametrize("expanded", [False, True])
@pytest.mark.parametrize("ending", ["done", "error", "cancelled"])
def test_stream_terminal_preserves_receipt_choice_and_skipped_files(dialog, expanded, ending):
dialog._ask("核对合成记录")
generation, stream = dialog._generation, dialog._stream_generation
bubble = dialog._stream_bubble
dialog._stream_event(generation, stream, {"event": "start", **_manifest()})
assert bubble.transfer_status.isHidden()
if expanded:
bubble.transfer_toggle.click()
dialog._stream_event(generation, stream, {"event": "progress", "phase": "upstream", **_manifest()})
for chunk in ("首段合成正文。\n\n", "最后唯一标记"):
dialog._stream_event(generation, stream, {"event": "delta", "text": chunk})
dialog._flush_stream_chunks()
if ending == "done":
# A legacy terminal bulk receipt must not relabel the missing file.
stale = _manifest()
stale["items"] = [{**item, "status": "submitted"} for item in stale["items"]]
dialog._stream_event(generation, stream, {"event": "done", **stale})
elif ending == "error":
dialog._stream_failed(generation, stream, RuntimeError("合成连接中断"))
else:
dialog._cancel_stream(reason="合成测试停止")
assert bubble.transfer_toggle.isChecked() is expanded
assert bubble.transfer_status.isHidden() is not expanded
assert bubble._inner.itemAt(0).widget() is bubble.transfer_receipt
assert "文件不存在,已跳过" in bubble.transfer_status.text()
assert "最后唯一标记" in bubble.body.toPlainText()
assert "资料栏目提交清单" not in bubble._raw_payload
assert "资料栏目提交清单" not in bubble.body.toPlainText()
assert len(bubble.findChildren(QLabel, "AiConsultTransferStatus")) == 1
def test_empty_cancel_and_error_keep_collapsed_receipt(dialog):
for ending in ("error", "cancelled"):
dialog._ask("核对合成记录")
generation, stream = dialog._generation, dialog._stream_generation
bubble = dialog._stream_bubble
dialog._stream_event(generation, stream, {"event": "start", **_manifest()})
if ending == "error":
dialog._stream_failed(generation, stream, RuntimeError("合成错误"))
else:
dialog._cancel_stream(reason="合成测试停止")
assert bubble.body.isHidden()
assert bubble.transfer_status.isHidden()
assert not bubble.transfer_toggle.isChecked()
bubble.transfer_toggle.click()
assert not bubble.transfer_status.isHidden()
assert "文件不存在,已跳过" in bubble.transfer_status.text()
@pytest.mark.parametrize("expanded", [False, True])
def test_deferred_report_keeps_receipt_at_top_and_preserves_choice(dialog, expanded):
dialog._ask("核对合成记录")
generation, stream = dialog._generation, dialog._stream_generation
bubble = dialog._stream_bubble
dialog._stream_event(generation, stream, {"event": "start", **_manifest()})
if expanded:
bubble.transfer_toggle.click()
text = REPORT + "\n\n" + "合成补充记录,核对资料完整性。" * 400
dialog._stream_event(generation, stream, {"event": "delta", "text": text})
dialog._stream_event(generation, stream, {"event": "done"})
assert bubble._report_render_pending
for _ in range(200):
if not bubble._report_render_pending:
break
QTest.qWait(5)
assert not bubble._report_render_pending and bubble._clinical_panel is not None
assert bubble._inner.itemAt(0).widget() is bubble.transfer_receipt
assert bubble.transfer_toggle.isChecked() is expanded
assert bubble.transfer_status.isHidden() is not expanded
assert bubble._raw_payload == text
def test_opening_receipt_keeps_scroll_position_while_stream_continues(dialog, application):
text = "\n\n".join(["合成记录" * 30] * 35)
bubble = dialog._append_bubble("ai", "")
bubble.append_stream_text(text, text)
bubble.set_transfer_status(module._transfer_description(_manifest(), "正在生成…"))
for _ in range(6):
application.processEvents()
QTest.qWait(5)
bar = dialog.chat_scroll.verticalScrollBar()
bar.setValue(bar.maximum())
before = bar.value()
assert before > 0 and dialog._follow_chat
bubble.transfer_toggle.click()
for _ in range(6):
application.processEvents()
QTest.qWait(5)
assert bar.value() == before
assert not dialog._follow_chat
bubble.append_stream_text("新增合成末行", str(bubble._raw_payload) + "新增合成末行")
bubble.set_transfer_status(module._transfer_description(_manifest(), "本次回复已完成。"))
for _ in range(6):
application.processEvents()
QTest.qWait(5)
assert bar.value() == before and not dialog._follow_chat

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