Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9a6146e25a | ||
|
|
068f3f8b06 | ||
|
|
6862547a9d | ||
|
|
192c31fb8c | ||
|
|
eec3204408 | ||
|
|
d3d66970b2 | ||
|
|
2a0e49dbc9 | ||
|
|
17e9e7b6b6 |
@@ -1,3 +0,0 @@
|
||||
# The bundled GB18030 source files must retain their original bytes.
|
||||
server/knowledge/tcm-ancient-books/*.txt -text -diff
|
||||
server/knowledge/tcm-ancient-books/*.baiduyun.downloading* -text -diff
|
||||
@@ -28,9 +28,6 @@ app/.test-tmp-stream/
|
||||
/.codex
|
||||
/.agents
|
||||
/server/.spool
|
||||
# Generated ancient-books search indexes; the source corpus is tracked.
|
||||
/server/knowledge/tcm-ancient-books-index.json
|
||||
/server/knowledge/tcm-ancient-books-index/
|
||||
/server/.claude
|
||||
/.spool
|
||||
TUICallKit-Vue3/.env
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
<!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>
|
||||
@@ -1,106 +0,0 @@
|
||||
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/')
|
||||
})
|
||||
@@ -1,87 +0,0 @@
|
||||
<?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);
|
||||
@@ -1,29 +0,0 @@
|
||||
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')
|
||||
@@ -1,18 +0,0 @@
|
||||
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
|
||||
@@ -1,206 +0,0 @@
|
||||
const assert = require('node:assert/strict')
|
||||
const fs = require('node:fs')
|
||||
const path = require('node:path')
|
||||
const vm = require('node:vm')
|
||||
const ts = require('typescript')
|
||||
const vue = require('vue')
|
||||
const { parse, compileScript, compileTemplate, compileStyleAsync } = require('@vue/compiler-sfc')
|
||||
|
||||
const sourceFlag = process.argv.indexOf('--source')
|
||||
const filename = sourceFlag >= 0 ? path.resolve(process.argv[sourceFlag + 1]) : path.join(__dirname, '../src/views/tcm/diagnosis/components/DailyMatrix.vue')
|
||||
const source = fs.readFileSync(filename, 'utf8')
|
||||
const { descriptor, errors } = parse(source, { filename })
|
||||
assert.deepEqual(errors, [], 'actual SFC parses')
|
||||
const script = compileScript(descriptor, { id: 'daily-record-test' })
|
||||
const template = compileTemplate({ source: descriptor.template.content, filename, id: 'daily-record-test', compilerOptions: { bindingMetadata: script.bindings } })
|
||||
assert.deepEqual(template.errors, [], 'actual template compiles')
|
||||
const calls = []
|
||||
const pending = { window: null, notes: null, bloodEdit: null }
|
||||
const api = new Proxy({}, { get(_target, name) {
|
||||
return (...args) => {
|
||||
calls.push({ name, args: JSON.parse(JSON.stringify(args)) })
|
||||
if (name === 'diagnosisTrackingWindow') return pending.window ? pending.window(...args) : Promise.resolve({})
|
||||
if (name === 'diagnosisTrackingNotes') return pending.notes ? pending.notes(...args) : Promise.resolve([])
|
||||
if (name === 'bloodRecordEdit' && pending.bloodEdit) return pending.bloodEdit(...args)
|
||||
return Promise.resolve(true)
|
||||
}
|
||||
} })
|
||||
const thresholdSource = fs.readFileSync(path.join(__dirname, '../src/utils/blood-thresholds.ts'), 'utf8')
|
||||
const thresholdExports = {}
|
||||
vm.runInNewContext(ts.transpileModule(thresholdSource, { compilerOptions: { module: ts.ModuleKind.CommonJS } }).outputText, { exports: thresholdExports })
|
||||
const moduleObject = { exports: {} }
|
||||
const lifecycle = { mounted: [], unmounted: [] }
|
||||
const runtime = { ...vue, onMounted: fn => lifecycle.mounted.push(fn), onUnmounted: fn => lifecycle.unmounted.push(fn) }
|
||||
vm.runInNewContext(ts.transpileModule(script.content, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText, {
|
||||
exports: moduleObject.exports, module: moduleObject, console, Date, Map, window: { addEventListener() {}, removeEventListener() {} },
|
||||
require(name) {
|
||||
if (name === 'vue') return runtime
|
||||
if (name === '@/api/tcm') return api
|
||||
if (name === '@/utils/perm') return { hasPermission: () => true }
|
||||
if (name === '@/utils/blood-thresholds') return thresholdExports
|
||||
if (name === '@/utils/feedback') return { default: { msgWarning: message => calls.push({ name: 'warning', message }) } }
|
||||
if (name === 'vue-echarts' || name.endsWith('.vue')) return { default: {} }
|
||||
throw new Error(`Unexpected import: ${name}`)
|
||||
}
|
||||
}, { filename })
|
||||
const props = vue.reactive({ diagnosisId: 7, patientId: 70, age: 50, readOnly: false, patientName: '合成测试' })
|
||||
let exposed
|
||||
const scope = vue.effectScope()
|
||||
const state = scope.run(() => moduleObject.exports.default.setup(props, { expose(value) { exposed = value } }))
|
||||
const date = '2026-09-20'
|
||||
const blood = [
|
||||
{ id: 103, diagnosis_id: 7, record_date: date, record_time: '19:30', fasting_blood_sugar: 7.1, record_time_estimated: 1, record_time_period: 'evening', record_time_text: '昨晚', followup_audio_task_id: 80, remark: '晚间原始行' },
|
||||
{ id: 102, diagnosis_id: 7, record_date: date, record_time: '08:30', fasting_blood_sugar: 7.1, source: 1, remark: '早间原始行' },
|
||||
{ id: 101, diagnosis_id: 7, record_date: date, record_time: '07:00', postprandial_blood_sugar: 8.4, remark: '独立原始行' }
|
||||
]
|
||||
const diet = [ { id: 201, record_date: date, breakfast_foods: '鸡蛋', breakfast_images: ['fixture-a.png'] }, { id: 202, record_date: date, lunch_foods: '豆腐', lunch_images: ['fixture-b.png'] } ]
|
||||
const exercise = [ { id: 301, record_date: date, exercise_type: '散步', duration: 20, intensity: 1, images: ['fixture-c.png'] }, { id: 302, record_date: date, exercise_type: '散步', duration: 20, intensity: 1 } ]
|
||||
function fixtures() {
|
||||
state.bloodRecords.value = structuredClone(blood)
|
||||
state.dietRecords.value = structuredClone(diet)
|
||||
state.exerciseRecords.value = structuredClone(exercise)
|
||||
}
|
||||
function rowCount(map) { const rows = map.value.get(date); return Array.isArray(rows) ? rows.length : rows ? 1 : 0 }
|
||||
function observe() {
|
||||
fixtures()
|
||||
state.handleCellClick('fasting', date)
|
||||
return { bloodRows: rowCount(state.bloodByDate), dietRows: rowCount(state.dietByDate), exerciseRows: rowCount(state.exerciseByDate), dayDetailOpen: !!state.dayDetailVisible?.value, implicitBloodEditId: state.bloodForm.value.id || null, fastingCell: state.getCell('fasting', date).value }
|
||||
}
|
||||
async function main() {
|
||||
for (const style of descriptor.styles) {
|
||||
const result = await compileStyleAsync({ source: style.content, filename, id: 'daily-record-test', scoped: style.scoped, preprocessLang: style.lang })
|
||||
assert.deepEqual(result.errors, [], 'actual styles compile')
|
||||
}
|
||||
const canonicalFlag = process.argv.indexOf('--canonical-fixture')
|
||||
if (canonicalFlag >= 0) {
|
||||
const fixture = JSON.parse(fs.readFileSync(process.argv[canonicalFlag + 1], 'utf8'))
|
||||
assert.equal(fixture.synthetic, true)
|
||||
assert.equal(fixture.source, 'real-disposable-mysql-apply')
|
||||
for (const alias of ['breakfast', 'lunch', 'dinner']) assert.equal(fixture.diet_columns.includes(alias), false)
|
||||
const actual = { ...fixture.diet_model, record_date: new Intl.DateTimeFormat('sv-SE', { timeZone: 'Asia/Shanghai' }).format(new Date(Number(fixture.diet_model.record_date) * 1000)) }
|
||||
state.dietRecords.value = [actual]
|
||||
state.openDietRecord(actual, actual.record_date)
|
||||
for (const meal of ['breakfast', 'lunch', 'dinner']) {
|
||||
assert.equal(state.dietForm.value[`${meal}_foods`], actual[`${meal}_foods`], 'real adopted meal opens in existing edit input')
|
||||
assert.deepEqual(JSON.parse(JSON.stringify(state.dietForm.value[`${meal}_images`])), actual[`${meal}_images`])
|
||||
assert.equal(state.getCell(meal, actual.record_date).value, '✓')
|
||||
}
|
||||
state.dietForm.value.note = 'only synthetic note changed'
|
||||
await state.submitDiet()
|
||||
const payload = calls.findLast(x => x.name === 'dietRecordEdit').args[0]
|
||||
for (const meal of ['breakfast', 'lunch', 'dinner']) {
|
||||
assert.equal(payload[`${meal}_foods`], actual[`${meal}_foods`], 'submit preserves untouched canonical meals')
|
||||
assert.deepEqual(payload[`${meal}_images`], actual[`${meal}_images`], 'submit preserves images')
|
||||
assert.equal(meal in payload, false, 'no extraction alias leaks to existing edit API')
|
||||
}
|
||||
console.log('DAILY_RECORDS_CANONICAL_MYSQL PASS actual_model=1 edit_inputs=1 canonical_payload=1 preserved_images=1')
|
||||
}
|
||||
if (process.argv.includes('--observe')) { console.log(JSON.stringify(observe())); scope.stop(); return }
|
||||
assert.deepEqual(observe(), { bloodRows: 3, dietRows: 2, exerciseRows: 2, dayDetailOpen: true, implicitBloodEditId: null, fastingCell: '7.1 / 7.1' })
|
||||
assert.equal(state.dayBloodRecords.value.length, 3, 'all same-day blood rows present')
|
||||
assert.equal(state.dayDietRecords.value.length, 2, 'all diet rows present')
|
||||
assert.equal(state.dayExerciseRecords.value.length, 2, 'identical exercise rows remain separate')
|
||||
assert.equal(state.recordTimeLabel(blood[0]), '19:30')
|
||||
assert.equal(state.recordTimePeriodLabel(blood[0]), '晚上')
|
||||
assert.equal(state.recordTimeLabel(diet[0]), '未记录具体时间', 'do not invent times for old diet rows')
|
||||
assert.match(descriptor.template.content, /v-for="record in dayBloodRecords"/)
|
||||
assert.match(descriptor.template.content, /v-for="record in dayDietRecords"/)
|
||||
assert.match(descriptor.template.content, /v-for="record in dayExerciseRecords"/)
|
||||
assert.match(descriptor.template.content, /估计时间/)
|
||||
assert.match(descriptor.template.content, /record\.record_time_text/)
|
||||
|
||||
state.openBloodRecord(blood[0], date)
|
||||
assert.equal(state.bloodForm.value.id, 103)
|
||||
assert.equal(state.bloodForm.value.postprandial_blood_sugar, 0, 'no field from another row merged into edit')
|
||||
state.bloodForm.value.remark = '只改备注'
|
||||
await state.submitBlood()
|
||||
let sent = calls.findLast(x => x.name === 'bloodRecordEdit').args[0]
|
||||
assert.equal(sent.id, 103)
|
||||
assert.equal(sent.record_time_estimated, 1, 'unmodified time retains estimate')
|
||||
assert.equal(sent.record_time_text, '昨晚')
|
||||
assert.equal(sent.followup_audio_task_id, 80, 'keep provenance')
|
||||
state.openBloodRecord(blood[0], date)
|
||||
state.bloodForm.value.record_time = '20:05'
|
||||
await state.submitBlood()
|
||||
sent = calls.findLast(x => x.name === 'bloodRecordEdit').args[0]
|
||||
assert.equal(sent.record_time_estimated, 0, 'manual time correction clears estimate')
|
||||
assert.equal(sent.record_time_period, '')
|
||||
assert.equal(sent.record_time_text, '')
|
||||
assert.equal(sent.followup_audio_task_id, 80)
|
||||
state.openBloodRecord({ ...blood[0], record_time: '19:30:25' }, date)
|
||||
state.bloodForm.value.record_time = '19:30'
|
||||
await state.submitBlood()
|
||||
sent = calls.findLast(x => x.name === 'bloodRecordEdit').args[0]
|
||||
assert.equal(sent.record_time_estimated, 0, 'seconds correction must not retain estimated time')
|
||||
assert.equal(state.recordTimeLabel({ record_time: '19:30:25' }), '19:30:25', 'precise original seconds remain visible')
|
||||
state.openBloodRecord(undefined, date)
|
||||
await state.submitBlood()
|
||||
sent = calls.findLast(x => x.name === 'bloodRecordAdd').args[0]
|
||||
assert.equal(sent.id, '')
|
||||
assert.equal('record_time_estimated' in sent, false, 'legacy manual add does not require migration columns')
|
||||
state.openDietRecord(diet[1], date)
|
||||
assert.equal(state.dietForm.value.id, 202)
|
||||
state.dietForm.value.lunch_images.push('fixture-new.png')
|
||||
assert.equal(diet[1].lunch_images.length, 1, 'edit image arrays cloned')
|
||||
await state.submitDiet()
|
||||
assert.equal(calls.findLast(x => x.name === 'dietRecordEdit').args[0].id, 202)
|
||||
state.openExerciseRecord(exercise[1], date)
|
||||
await state.submitExercise()
|
||||
assert.equal(calls.findLast(x => x.name === 'exerciseRecordEdit').args[0].id, 302)
|
||||
fixtures()
|
||||
props.readOnly = true
|
||||
state.dayDetailVisible.value = false
|
||||
state.handleCellClick('exercise', date)
|
||||
assert.equal(state.dayDetailVisible.value, true, 'readonly viewers can inspect actual rows')
|
||||
state.bloodDialogVisible.value = false
|
||||
state.openBloodRecord(blood[0], date)
|
||||
assert.equal(state.bloodDialogVisible.value, false, 'readonly cannot edit')
|
||||
props.readOnly = false
|
||||
|
||||
const windows = []
|
||||
pending.window = params => new Promise(resolve => windows.push({ params, resolve }))
|
||||
const oldFetch = state.fetchTracking()
|
||||
props.diagnosisId = 8
|
||||
await vue.nextTick()
|
||||
assert.equal(state.dayDetailVisible.value, false, 'patient switch closes prior details')
|
||||
assert.equal(state.bloodRecords.value.length, 0, 'patient switch immediately clears old rows')
|
||||
assert.equal(windows.length, 2)
|
||||
assert.equal(windows[0].params.id, 7)
|
||||
assert.equal(windows[1].params.id, 8)
|
||||
windows[1].resolve({ blood_records: [{ id: 888, record_date: date }] })
|
||||
await new Promise(resolve => setImmediate(resolve))
|
||||
windows[0].resolve({ blood_records: blood })
|
||||
await oldFetch
|
||||
assert.equal(state.bloodRecords.value[0].id, 888, 'late old-patient fetch cannot overwrite new data')
|
||||
assert.deepEqual(calls.filter(x => x.name === 'diagnosisTrackingNotes').slice(-2).map(x => x.args[0].diagnosis_id), [8, 7], 'both sequential requests use their own bound identity')
|
||||
|
||||
let releaseEdit
|
||||
pending.bloodEdit = () => new Promise(resolve => { releaseEdit = resolve })
|
||||
pending.window = null
|
||||
state.openBloodRecord({ ...blood[0], diagnosis_id: 8 }, date)
|
||||
const oldSubmit = state.submitBlood()
|
||||
props.diagnosisId = 9
|
||||
await vue.nextTick()
|
||||
state.bloodDialogVisible.value = true
|
||||
releaseEdit(true)
|
||||
await oldSubmit
|
||||
assert.equal(state.bloodDialogVisible.value, true, 'late old-patient submit cannot close new dialog')
|
||||
|
||||
// Single-flight guard prevents duplicate submissions of the same manual form.
|
||||
state.bloodSubmitting.value = true
|
||||
const callCount = calls.length
|
||||
await state.submitBlood()
|
||||
assert.equal(calls.length, callCount)
|
||||
state.bloodSubmitting.value = false
|
||||
const unmountedWindows = []
|
||||
pending.window = () => new Promise(resolve => unmountedWindows.push(resolve))
|
||||
const unmountedFetch = state.fetchTracking()
|
||||
for (const unmount of lifecycle.unmounted) unmount()
|
||||
unmountedWindows[0]({ blood_records: blood })
|
||||
await unmountedFetch
|
||||
assert.notEqual(state.bloodRecords.value[0]?.id, 103, 'unmounted request cannot repopulate component')
|
||||
scope.stop()
|
||||
assert.equal(typeof exposed.refresh, 'function')
|
||||
console.log('DailyMatrix actual SFC setup/template/style: 3 blood + 2 diet + 2 exercise rows, exact edit IDs, time metadata, readonly detail, stale isolation: PASS')
|
||||
}
|
||||
main().catch(error => { scope.stop(); console.error(error); process.exitCode = 1 })
|
||||
@@ -1,32 +0,0 @@
|
||||
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')
|
||||
@@ -9,7 +9,6 @@ import useAppStore from './stores/modules/app'
|
||||
import useSettingStore from './stores/modules/setting'
|
||||
import useUserStore from './stores/modules/user'
|
||||
import ChatNotifyToast from './components/chat-notify-toast/index.vue'
|
||||
import RevisitDueToast from './components/revisit-due-toast/index.vue'
|
||||
|
||||
const appStore = useAppStore()
|
||||
const settingStore = useSettingStore()
|
||||
@@ -59,8 +58,6 @@ watch(
|
||||
<el-config-provider :locale="elConfig.locale" :z-index="elConfig.zIndex">
|
||||
<router-view />
|
||||
<ChatNotifyToast v-if="showChatNotifyToast" />
|
||||
<!-- 复诊到期弹窗(右下角):与会话通知并列挂载,复用同一条件避免未绑企微时无意义轮询 -->
|
||||
<RevisitDueToast v-if="showChatNotifyToast" />
|
||||
</el-config-provider>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
import request from '@/utils/request'
|
||||
|
||||
/** AI 助手(MCP)后台接口:挂在 /mcp/admin 下,沿用后台登录令牌 */
|
||||
const opts = { urlPrefix: 'mcp' }
|
||||
|
||||
/** AI 授权列表(有 ai.grant/lists 看全部,否则只看自己的) */
|
||||
export function aiGrantLists(params: any) {
|
||||
return request.get({ url: '/admin/grants', params }, opts)
|
||||
}
|
||||
|
||||
/** 撤销 AI 授权 */
|
||||
export function aiGrantRevoke(params: { id: number }) {
|
||||
return request.post({ url: '/admin/revoke', params }, opts)
|
||||
}
|
||||
|
||||
/** AI 访问日志 */
|
||||
export function aiAccessLogLists(params: any) {
|
||||
return request.get({ url: '/admin/logs', params }, opts)
|
||||
}
|
||||
|
||||
/** AI 数据目录与覆盖情况 */
|
||||
export function aiCatalogLists(params: any) {
|
||||
return request.get({ url: '/admin/catalog', params }, opts)
|
||||
}
|
||||
@@ -5,14 +5,6 @@ export function getConfig() {
|
||||
return request.get({ url: '/config/getConfig' })
|
||||
}
|
||||
|
||||
// 运行时读取医生网页面诊切换时间,与服务端拦截规则共用配置。
|
||||
export function getDoctorWebConsultationPolicy() {
|
||||
return request.get(
|
||||
{ url: '/config/doctorWebConsultation', params: { _t: Date.now() } },
|
||||
{ withToken: false, isOpenRetry: false }
|
||||
)
|
||||
}
|
||||
|
||||
// 工作台主页
|
||||
export function getWorkbench() {
|
||||
return request.get({ url: '/workbench/index' })
|
||||
|
||||
@@ -1,157 +0,0 @@
|
||||
import request from '@/utils/request'
|
||||
|
||||
export type FollowupKind = 'diagnosis' | 'blood' | 'diet' | 'exercise' | 'tracking_note'
|
||||
export type FollowupValue = string | number | boolean | null | Array<string | number>
|
||||
export type FollowupValues = Record<string, FollowupValue>
|
||||
export interface FollowupField {
|
||||
key: string
|
||||
label: string
|
||||
type: 'text' | 'number' | 'select' | 'multiselect' | 'date'
|
||||
options?: Array<{ label: string; value: string | number }>
|
||||
readonly?: boolean
|
||||
}
|
||||
export type FollowupFields = Record<FollowupKind, FollowupField[]>
|
||||
export type FollowupAudioChannel = 0 | 1
|
||||
export type FollowupChannelRoles = 'unconfirmed' | 'left_service' | 'right_service'
|
||||
export interface FollowupTranscriptSegment {
|
||||
id: string
|
||||
start_ms: number
|
||||
end_ms: number
|
||||
text: string
|
||||
channel?: FollowupAudioChannel
|
||||
}
|
||||
export interface FollowupCapabilities {
|
||||
enabled: boolean
|
||||
audio_verified: boolean
|
||||
preview_only?: boolean
|
||||
preview_ready?: boolean
|
||||
manual_review_enabled?: boolean
|
||||
manual_review_ready?: boolean
|
||||
can_review?: boolean
|
||||
test_scope_allowed?: boolean
|
||||
can_upload: boolean
|
||||
can_apply: boolean
|
||||
can_daily: boolean
|
||||
models: Array<{ value: string; label: string }>
|
||||
limits: { max_bytes: number; max_seconds: number; chunk_bytes: number }
|
||||
fields: FollowupFields
|
||||
}
|
||||
export interface FollowupReviewItem {
|
||||
id: string
|
||||
kind: FollowupKind
|
||||
values: FollowupValues
|
||||
record_date: string | null
|
||||
record_time: string | null
|
||||
time_period: string | null
|
||||
time_estimated: boolean
|
||||
time_text: string
|
||||
date_text: string
|
||||
evidence: Array<{ text: string; start_ms?: number; end_ms?: number; segment_id?: string; position_type?: 'segment'; channel?: FollowupAudioChannel }>
|
||||
needs_review: boolean
|
||||
selected: boolean
|
||||
target_id: number | null
|
||||
current_values: FollowupValues
|
||||
expected_hash: string
|
||||
conflict: boolean
|
||||
possible_duplicate: boolean
|
||||
candidates?: Array<{
|
||||
id: number
|
||||
values: FollowupValues
|
||||
record_time: string | null
|
||||
time_estimated: boolean
|
||||
time_period: string | null
|
||||
delete_time?: number | null
|
||||
}>
|
||||
}
|
||||
export interface FollowupTaskSummary {
|
||||
id: number
|
||||
diagnosis_id: number
|
||||
file_name: string
|
||||
recorded_at: string
|
||||
status: string
|
||||
stage: string
|
||||
error_code: string
|
||||
error_message: string
|
||||
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
|
||||
transcript_available?: boolean
|
||||
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[]
|
||||
channel_roles?: FollowupChannelRoles
|
||||
uncertainties: unknown[]
|
||||
items: FollowupReviewItem[]
|
||||
fields?: FollowupFields
|
||||
applied_items: unknown[]
|
||||
review_refreshed?: boolean
|
||||
}
|
||||
interface Envelope<T> { code: number; msg?: string; data: T }
|
||||
export class FollowupAudioError extends Error {
|
||||
constructor(message: string, public readonly code = '') { super(message); this.name = 'FollowupAudioError' }
|
||||
}
|
||||
const options = { isTransformResponse: false, ignoreCancelToken: true, isOpenRetry: false, retryCount: 0 }
|
||||
const base = '/tcm.followupAudio/'
|
||||
function unwrap<T>(response: Envelope<T>): T {
|
||||
if (response.code !== 1) {
|
||||
const data = response.data
|
||||
const code = data && typeof data === 'object' && 'code' in data ? String(data.code) : ''
|
||||
throw new FollowupAudioError(response.msg || '回访录音请求失败,请刷新任务状态后确认', code)
|
||||
}
|
||||
return response.data
|
||||
}
|
||||
async function get<T>(name: string, params: Record<string, number>, signal?: AbortSignal): Promise<T> {
|
||||
return unwrap(await request.get<Envelope<T>>({ url: base + name, params, signal }, options))
|
||||
}
|
||||
async function post<T>(name: string, data: unknown, signal?: AbortSignal): Promise<T> {
|
||||
return unwrap(await request.post<Envelope<T>>({ url: base + name, data, signal, timeout: 120000 }, options))
|
||||
}
|
||||
export const followupAudioCapabilities = (diagnosisId: number, signal?: AbortSignal) => get<FollowupCapabilities>('capabilities', { diagnosis_id: diagnosisId }, signal)
|
||||
export const followupAudioLists = (diagnosisId: number, signal?: AbortSignal) => get<{ items: FollowupTaskSummary[] }>('lists', { diagnosis_id: diagnosisId }, signal)
|
||||
export const followupAudioDetail = (id: number, signal?: AbortSignal) => get<FollowupTaskDetail>('detail', { id }, signal)
|
||||
export const followupAudioUploadSession = (data: { diagnosis_id: number; file_name: string; total_bytes: number }, signal?: AbortSignal) => post<{ upload_id: string; chunk_bytes: number }>('uploadSession', data, signal)
|
||||
export async function followupAudioUploadChunk(uploadId: string, index: number, file: Blob, signal?: AbortSignal) {
|
||||
const data = new FormData()
|
||||
data.append('upload_id', uploadId)
|
||||
data.append('index', String(index))
|
||||
data.append('file', file, `chunk-${index}`)
|
||||
return unwrap(await request.post<Envelope<{ index: number; received: boolean }>>({
|
||||
url: base + 'uploadChunk', data, signal, timeout: 120000,
|
||||
headers: { 'Content-Type': 'multipart/form-data' }
|
||||
}, options))
|
||||
}
|
||||
export const followupAudioUploadComplete = (uploadId: string, signal?: AbortSignal) => post<{ upload_id: string; duration_seconds: number; sha256: string }>('uploadComplete', { upload_id: uploadId }, signal)
|
||||
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> {
|
||||
const blob = await request.get<Blob>({ url: base + 'audio', params: { id }, responseType: 'blob', signal, timeout: 120000 }, options)
|
||||
if (blob.type.includes('json')) {
|
||||
const response: Envelope<unknown> = JSON.parse(await blob.text())
|
||||
unwrap(response)
|
||||
throw new FollowupAudioError('录音响应不是音频文件')
|
||||
}
|
||||
return blob
|
||||
}
|
||||
@@ -1,195 +0,0 @@
|
||||
import request from '@/utils/request'
|
||||
|
||||
/**
|
||||
* 复诊到期弹窗(需求 4)接口:/adminapi/tcm.revisitDue/<action>
|
||||
* 契约见 docs/plans/assistant-revisit-reach-reminder-2026-10-12.md §3.3。
|
||||
* 写接口后端 show=1,成功提示由 utils/request 统一弹出,调用方不要重复 ElMessage。
|
||||
*/
|
||||
|
||||
/** 弹窗条目(RevisitDueLogic::formatItem) */
|
||||
export interface RevisitDueToastItem {
|
||||
id: number
|
||||
diagnosis_id: number
|
||||
assistant_id: number
|
||||
patient_name: string
|
||||
current_slot: number
|
||||
next_slot: number
|
||||
medication_days: number
|
||||
/** 'YYYY-MM-DD' 或 '' */
|
||||
due_date: string
|
||||
overdue_days: number | null
|
||||
/** overdue | missed(弹窗只含这两态) */
|
||||
state: string
|
||||
state_text: string
|
||||
severe: 0 | 1
|
||||
missed_count: number
|
||||
snooze_count: number
|
||||
/** 0~3,3 = 居中模态 */
|
||||
escalation_level: number
|
||||
contact_count: number
|
||||
promised_date: string
|
||||
next_remind_at: number
|
||||
next_remind_at_text: string
|
||||
/** 下一次点「延迟」会顺延的秒数(按钮文案用) */
|
||||
next_snooze_seconds: number
|
||||
appointment_date: string
|
||||
closed_state: number
|
||||
}
|
||||
|
||||
/** 汇总计数(RevisitDueLogic::buildSummary) */
|
||||
export interface RevisitDueToastSummary {
|
||||
enabled: boolean
|
||||
due_total: number
|
||||
max_overdue_days: number
|
||||
warning_total: number
|
||||
promise_max_days: number
|
||||
contact_max_per_cycle: number
|
||||
work_hours: [string, string]
|
||||
}
|
||||
|
||||
export interface RevisitDuePendingResult {
|
||||
items: RevisitDueToastItem[]
|
||||
summary: RevisitDueToastSummary
|
||||
}
|
||||
|
||||
/** 写接口返回处理后的当前行(幂等:被他人处理时也返回当前行) */
|
||||
export type RevisitDueWriteResult = RevisitDueToastItem
|
||||
|
||||
export interface RevisitDueSnoozeAllResult {
|
||||
items: RevisitDueToastItem[]
|
||||
snoozed: number
|
||||
skipped: number
|
||||
message: string
|
||||
}
|
||||
|
||||
/** 轮询接口不走统一 code 处理:权限不足 / 开关关闭时不要每分钟弹一次错误提示 */
|
||||
const POLL_OPTIONS = {
|
||||
isTransformResponse: false,
|
||||
ignoreCancelToken: true,
|
||||
isOpenRetry: false,
|
||||
retryCount: 0
|
||||
}
|
||||
|
||||
/**
|
||||
* 弹窗待办(60s 轮询):本人到期未挂号 / 过号且已到提醒时刻的项,每次返回全集。
|
||||
* 非 code=1 一律 reject(调用方静默处理),避免轮询刷错误提示。
|
||||
*/
|
||||
export async function revisitDuePending(): Promise<RevisitDuePendingResult> {
|
||||
const res = await request.get({ url: '/tcm.revisitDue/pending' }, POLL_OPTIONS)
|
||||
if (res && typeof res === 'object' && Number(res.code) === 1) {
|
||||
return res.data as RevisitDuePendingResult
|
||||
}
|
||||
return Promise.reject(res?.msg ?? 'revisit due pending failed')
|
||||
}
|
||||
|
||||
/** 仅计数,不更新弹出时间 */
|
||||
export function revisitDueSummary(): Promise<RevisitDueToastSummary> {
|
||||
return request.get({ url: '/tcm.revisitDue/summary' })
|
||||
}
|
||||
|
||||
/** 延迟一次(幂等) */
|
||||
export function revisitDueSnooze(params: { id: number }): Promise<RevisitDueWriteResult> {
|
||||
return request.post({ url: '/tcm.revisitDue/snooze', params })
|
||||
}
|
||||
|
||||
/** 批量延迟(仅 escalation_level<=1 的项) */
|
||||
export function revisitDueSnoozeAll(params: {
|
||||
ids: number[]
|
||||
}): Promise<RevisitDueSnoozeAllResult> {
|
||||
return request.post({ url: '/tcm.revisitDue/snoozeAll', params })
|
||||
}
|
||||
|
||||
/** 已联系:记录患者承诺复诊日 */
|
||||
export function revisitDueContact(params: {
|
||||
id: number
|
||||
promised_date: string
|
||||
remark?: string
|
||||
}): Promise<RevisitDueWriteResult> {
|
||||
return request.post({ url: '/tcm.revisitDue/contact', params })
|
||||
}
|
||||
|
||||
/** 人工关闭(reason lost|other,remark 必填 ≤200) */
|
||||
export function revisitDueClose(params: {
|
||||
id: number
|
||||
reason: 'lost' | 'other'
|
||||
remark: string
|
||||
}): Promise<RevisitDueWriteResult> {
|
||||
return request.post({ url: '/tcm.revisitDue/close', params })
|
||||
}
|
||||
|
||||
/** 主管视图列表行(RevisitDueLists,按角色 data_scope 收窄) */
|
||||
export interface RevisitDueListRow {
|
||||
id: number
|
||||
diagnosis_id: number
|
||||
patient_name: string
|
||||
assistant_id: number
|
||||
assistant_name: string
|
||||
dept_name: string
|
||||
current_slot: number
|
||||
next_slot: number
|
||||
medication_days: number
|
||||
/** 14/21/28/30 或 0=其它 */
|
||||
rule_days: number
|
||||
anchor_date: string
|
||||
due_date: string
|
||||
overdue_days: number | null
|
||||
days_left: number | null
|
||||
state: string
|
||||
state_text: string
|
||||
severe: 0 | 1
|
||||
appointment_state: number
|
||||
appointment_date: string
|
||||
snooze_count: number
|
||||
escalation_level: number
|
||||
contact_count: number
|
||||
promised_date: string
|
||||
missed_count: number
|
||||
closed_state: number
|
||||
closed_state_text: string
|
||||
handle_reason: string
|
||||
handle_remark: string
|
||||
first_shown_at_text: string
|
||||
last_snoozed_at_text: string
|
||||
computed_at_text: string
|
||||
}
|
||||
|
||||
/** 主管视图筛选参数(state:due|warning|booked|visited|contacted|no_days|pending|closed;days_bucket:14|21|28|30|other) */
|
||||
export interface RevisitDueListsParams {
|
||||
assistant_id?: number | ''
|
||||
dept_id?: number | ''
|
||||
state?: string
|
||||
days_bucket?: string
|
||||
min_snooze?: number | ''
|
||||
keyword?: string
|
||||
page_no?: number
|
||||
page_size?: number
|
||||
/** 1 = 导出(export-data 组件追加) */
|
||||
export?: number
|
||||
[key: string]: any
|
||||
}
|
||||
|
||||
/** 主管视图:复诊到期跟进分页列表(lists/count/page_no/page_size/extend 包络,供 usePaging / export-data 消费) */
|
||||
export function revisitDueLists(params: RevisitDueListsParams) {
|
||||
return request.get({ url: '/tcm.revisitDue/lists', params })
|
||||
}
|
||||
|
||||
/** 事件流水行(RevisitDueLogic::logs) */
|
||||
export interface RevisitDueLogRow {
|
||||
id: number
|
||||
/** 1 延迟 2 已联系 3 人工关闭 4 自动关闭-已挂号 5 自动关闭-已面诊 6 周期重置 7 重新打开 8 企微推送 9 医助变更 10 形态升级 11 首次弹出 */
|
||||
event: number
|
||||
event_text: string
|
||||
snooze_count_after: number
|
||||
level_after: number
|
||||
overdue_days: number
|
||||
/** payload JSON 解析后的对象(next_remind_at / promised_date / appointment_id / order_id / remark / from_assistant 等) */
|
||||
payload_arr: Record<string, any>
|
||||
operator_id: number
|
||||
operator_name: string
|
||||
create_time_text: string
|
||||
}
|
||||
|
||||
/** 主管视图:某条提醒的事件流水(按 due_id,时间倒序由后端决定) */
|
||||
export function revisitDueLogs(params: { due_id: number }) {
|
||||
return request.get({ url: '/tcm.revisitDue/logs', params })
|
||||
}
|
||||
@@ -24,24 +24,6 @@ export type DesktopWorkstationConfig = {
|
||||
}
|
||||
}
|
||||
|
||||
export type DesktopWorkstationDownload = DesktopPackage & {
|
||||
platform: 'windows_x64' | 'macos_arm64' | 'macos_x64'
|
||||
label: string
|
||||
}
|
||||
|
||||
export type DesktopWorkstationDownloads = {
|
||||
version: string
|
||||
packages: DesktopWorkstationDownload[]
|
||||
}
|
||||
|
||||
// 仅返回已发布的安装包,不要求医生拥有系统设置权限。
|
||||
export function getDesktopWorkstationDownloads() {
|
||||
return request.get(
|
||||
{ url: '/setting.desktop_workstation/downloads' },
|
||||
{ withToken: false }
|
||||
) as Promise<DesktopWorkstationDownloads>
|
||||
}
|
||||
|
||||
export function getDesktopWorkstationConfig() {
|
||||
return request.get({
|
||||
url: '/setting.desktop_workstation/getConfig'
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
import request from '@/utils/request'
|
||||
|
||||
export interface PrescriptionAiVisibilityConfig {
|
||||
role_ids: number[]
|
||||
admin_ids: number[]
|
||||
}
|
||||
|
||||
export interface PrescriptionAiVisibilityOptions {
|
||||
roles: { id: number; name: string }[]
|
||||
admins: { id: number; name: string; account: string }[]
|
||||
}
|
||||
|
||||
export interface PrescriptionAiCapabilities {
|
||||
agreement_visible: boolean
|
||||
can_manage_visibility: boolean
|
||||
}
|
||||
|
||||
// A failed or malformed read must never become an empty policy that can be saved.
|
||||
function readVisibilityConfig(value: unknown): PrescriptionAiVisibilityConfig {
|
||||
const config = value as Partial<PrescriptionAiVisibilityConfig> | null
|
||||
const validIds = (ids: unknown): ids is number[] =>
|
||||
Array.isArray(ids) && ids.every((id) => Number.isSafeInteger(id) && id > 0)
|
||||
if (!config || !validIds(config.role_ids) || !validIds(config.admin_ids)) {
|
||||
throw new Error('可见范围配置响应格式不正确')
|
||||
}
|
||||
return { role_ids: [...config.role_ids], admin_ids: [...config.admin_ids] }
|
||||
}
|
||||
|
||||
export async function getPrescriptionAiVisibilityConfig() {
|
||||
const data = await request.get({ url: '/tcm.prescriptionAi/getVisibilityConfig' })
|
||||
return readVisibilityConfig(data)
|
||||
}
|
||||
|
||||
export async function setPrescriptionAiVisibilityConfig(params: PrescriptionAiVisibilityConfig) {
|
||||
const data = await request.post({ url: '/tcm.prescriptionAi/setVisibilityConfig', params })
|
||||
return readVisibilityConfig(data)
|
||||
}
|
||||
|
||||
export function getPrescriptionAiVisibilityOptions() {
|
||||
return request.get({
|
||||
url: '/tcm.prescriptionAi/visibilityOptions'
|
||||
}) as Promise<PrescriptionAiVisibilityOptions>
|
||||
}
|
||||
|
||||
export function getPrescriptionAiCapabilities() {
|
||||
return request.get({
|
||||
url: '/tcm.prescriptionAi/capabilities'
|
||||
}) as Promise<PrescriptionAiCapabilities>
|
||||
}
|
||||
+4
-88
@@ -204,26 +204,8 @@ export function commissionSettlementConfirmRevoke(params: Record<string, any>) {
|
||||
return request.post({ url: '/stats.commissionSettlement/confirmRevoke', params })
|
||||
}
|
||||
|
||||
/**
|
||||
* 复诊接诊率口径:
|
||||
* - slot(默认,后端 config project.revisit_rate.default_inherit_mode):继承按继承时诊次计入每列独立分母(visit{N}_den = 新指派数 + 起算诊次 ≤ N 的继承数)
|
||||
* - exclude:继承不计分母(旧口径,assigned_count / visit{N}_count / visit{N}_rate 与 2026-10 前一致)
|
||||
*/
|
||||
export type RevisitRateInheritMode = 'exclude' | 'slot'
|
||||
|
||||
/** 被指派明细行类型:new 新指派 / inherit 继承 / all 两者(默认) */
|
||||
export type RevisitRateAssignKind = 'new' | 'inherit' | 'all'
|
||||
|
||||
/**
|
||||
* 复诊接诊率(按月):部门 → 医助分组 + 合计。
|
||||
* 返回 inherit_mode、slots,行含 assigned_count(新指派)、inherit_count、assigned_total_count、
|
||||
* visit{N}_count/_den/_rate、visit_all_count/_den/_rate、visit2_rate_new_assign(旧口径二诊率)
|
||||
*/
|
||||
export function revisitRateOverview(params: {
|
||||
month?: string
|
||||
dept_ids?: string
|
||||
inherit_mode?: RevisitRateInheritMode
|
||||
}) {
|
||||
/** 复诊接诊率(按月):当月 N 诊接诊率,部门 → 医助分组 + 合计;剔除「继承」指派 */
|
||||
export function revisitRateOverview(params: { month?: string; dept_ids?: string }) {
|
||||
return request.get({ url: '/stats.revisitRate/overview', params })
|
||||
}
|
||||
|
||||
@@ -232,29 +214,23 @@ export function revisitRateDeptOptions() {
|
||||
return request.get({ url: '/stats.revisitRate/deptOptions' })
|
||||
}
|
||||
|
||||
/**
|
||||
* 复诊接诊率:「新指派数 / 继承数 / 被指派合计」点击下钻(按诊单聚合明细)。
|
||||
* 行含 assign_type(new|inherit)、inherit_visit_slot(继承时诊次 k)、entry_slot(起算诊次)
|
||||
*/
|
||||
/** 复诊接诊率:「被指派数」点击下钻(按诊单聚合明细) */
|
||||
export function revisitRateAssignLines(params: {
|
||||
month?: string
|
||||
dept_ids?: string
|
||||
assistant_id?: number
|
||||
dept_id?: number
|
||||
inherit_mode?: RevisitRateInheritMode
|
||||
kind?: RevisitRateAssignKind
|
||||
}) {
|
||||
return request.get({ url: '/stats.revisitRate/assignLines', params })
|
||||
}
|
||||
|
||||
/** 复诊接诊率:「N 诊单数」点击下钻(具体订单明细);slot=0 为全部 N≥2(复诊合计单数),行含 visit_slot */
|
||||
/** 复诊接诊率:「N 诊单数」点击下钻(具体订单明细) */
|
||||
export function revisitRateVisitOrderLines(params: {
|
||||
month?: string
|
||||
slot: number
|
||||
dept_ids?: string
|
||||
assistant_id?: number
|
||||
dept_id?: number
|
||||
inherit_mode?: RevisitRateInheritMode
|
||||
}) {
|
||||
return request.get({ url: '/stats.revisitRate/visitOrderLines', params })
|
||||
}
|
||||
@@ -277,63 +253,3 @@ export function assistantPerformanceOverview(params: {
|
||||
}) {
|
||||
return request.get({ url: '/stats.assistantPerformance/overview', params })
|
||||
}
|
||||
|
||||
/** 「我的复诊接诊率」卡片返回(RevisitRateLogic::assistantOverview,仅本人行) */
|
||||
export interface AssistantRevisitRateResult {
|
||||
month: string
|
||||
inherit_mode: RevisitRateInheritMode
|
||||
/** 诊次列范围(2~N) */
|
||||
slots: number[]
|
||||
/** false = 本人不属于二中心子树(复诊接诊率仅统计二中心医助) */
|
||||
in_scope: boolean
|
||||
/** 本人行:assigned_count / inherit_count / assigned_total_count / visit{N}_count|_den|_rate / visit_all_*;无数据为 null */
|
||||
row: Record<string, any> | null
|
||||
}
|
||||
|
||||
/**
|
||||
* 医助个人业绩:我的复诊接诊率(按月,仅本人行;口径与复诊接诊率页一致,
|
||||
* 继承患者按继承时诊次从第 k+1 诊起计入分母)
|
||||
*/
|
||||
export function assistantPerformanceRevisitRate(params: {
|
||||
month?: string
|
||||
}): Promise<AssistantRevisitRateResult> {
|
||||
return request.get({ url: '/stats.assistantPerformance/revisitRate', params })
|
||||
}
|
||||
|
||||
|
||||
/** 独立指派周期统计,与原 revisitRate 按月报表分别调用。 */
|
||||
export type RevisitRateCohortType = 'new' | 'inherit'
|
||||
|
||||
export interface RevisitRateQuery {
|
||||
start_date: string
|
||||
end_date: string
|
||||
dept_ids?: string
|
||||
assistant_id?: number
|
||||
}
|
||||
|
||||
export interface RevisitRateDetailQuery extends RevisitRateQuery {
|
||||
scope_assistant_id?: number
|
||||
dept_id?: number
|
||||
}
|
||||
|
||||
const revisitCohortPrefix = (cohortType: RevisitRateCohortType) =>
|
||||
cohortType === 'inherit' ? '/stats.revisitInheritRate' : '/stats.revisitAssignRate'
|
||||
|
||||
export function revisitCohortOverview(params: RevisitRateQuery, cohortType: RevisitRateCohortType) {
|
||||
return request.get({ url: `${revisitCohortPrefix(cohortType)}/overview`, params })
|
||||
}
|
||||
|
||||
export function revisitCohortDeptOptions(cohortType: RevisitRateCohortType) {
|
||||
return request.get({ url: `${revisitCohortPrefix(cohortType)}/deptOptions` })
|
||||
}
|
||||
|
||||
export function revisitCohortAssignLines(params: RevisitRateDetailQuery, cohortType: RevisitRateCohortType) {
|
||||
return request.get({ url: `${revisitCohortPrefix(cohortType)}/assignLines`, params })
|
||||
}
|
||||
|
||||
export function revisitCohortVisitOrderLines(
|
||||
params: RevisitRateDetailQuery & { slot: number },
|
||||
cohortType: RevisitRateCohortType
|
||||
) {
|
||||
return request.get({ url: `${revisitCohortPrefix(cohortType)}/visitOrderLines`, params })
|
||||
}
|
||||
|
||||
+1
-26
@@ -227,29 +227,6 @@ export function getCallRecords(params: any) {
|
||||
return request.get({ url: '/tcm.diagnosis/getCallRecords', params })
|
||||
}
|
||||
|
||||
export interface ConsultationCallRecord {
|
||||
id: number
|
||||
diagnosis_id: number
|
||||
call_type?: number
|
||||
status?: number
|
||||
start_time?: number
|
||||
start_time_text?: string
|
||||
end_time_text?: string
|
||||
duration_text?: string
|
||||
transcript_text?: string | null
|
||||
transcription_status?: string
|
||||
transcription_status_text?: string
|
||||
transcription_segment_count?: number
|
||||
}
|
||||
|
||||
/** 按诊单读取每次面诊已保存的文字;不触发语音识别或转写写入。 */
|
||||
export function getConsultationTranscripts(params: { diagnosis_id: number }, signal?: AbortSignal) {
|
||||
return request.get<ConsultationCallRecord[]>(
|
||||
{ url: '/tcm.diagnosis/getCallRecords', params, signal },
|
||||
{ ignoreCancelToken: true }
|
||||
)
|
||||
}
|
||||
|
||||
// 将 TRTC 房间号写入通话记录(与云端录制回调 room 关联)
|
||||
export function bindCallRoom(params: { diagnosis_id: number; room_id: string }) {
|
||||
return request.post({ url: '/tcm.diagnosis/bindCallRoom', params })
|
||||
@@ -490,7 +467,7 @@ export function prescriptionOrderEditTime(params: { id: number; create_time: str
|
||||
return request.post({ url: '/tcm.prescriptionOrder/editTime', params })
|
||||
}
|
||||
|
||||
/** 仅修改业务订单的承运商与快递单号;处方和支付单均审核通过后,所有履约状态均可使用 */
|
||||
/** 仅修改业务订单的承运商与快递单号;所有履约状态均可使用 */
|
||||
export function prescriptionOrderDdcode(params: {
|
||||
id: number
|
||||
express_company: string
|
||||
@@ -513,10 +490,8 @@ export function prescriptionOrderPatchPrescriptionUsage(params: {
|
||||
times_per_day: number
|
||||
usage_days: number
|
||||
medication_days: number
|
||||
dosage_bag_count?: number
|
||||
aux_times_per_day?: number
|
||||
aux_usage_days?: number
|
||||
aux_dosage_bag_count?: number
|
||||
}) {
|
||||
return request.post({ url: '/tcm.prescriptionOrder/patchPrescriptionUsage', params })
|
||||
}
|
||||
|
||||
@@ -45,16 +45,3 @@ export function unbindWorkWechat() {
|
||||
export function changeFirstPassword(params: { password: string; password_confirm: string }) {
|
||||
return request.post({ url: '/login/changeFirstPassword', params })
|
||||
}
|
||||
|
||||
// 统一账号登录开关和服务器生成的固定登录入口
|
||||
export function getIamConfig() {
|
||||
return request.get({ url: '/iam/config' }, { withToken: false })
|
||||
}
|
||||
|
||||
// 浏览器绑定的一次性兑换码;不重试,也不将旧业务 token 带入认证
|
||||
export function iamLogin(ticket: string) {
|
||||
return request.post(
|
||||
{ url: '/iam/exchange', params: { ticket, terminal: config.terminal }, withCredentials: true },
|
||||
{ withToken: false, isOpenRetry: false }
|
||||
)
|
||||
}
|
||||
|
||||
@@ -34,7 +34,6 @@
|
||||
|
||||
</div>
|
||||
</div>
|
||||
<DoctorWebConsultationNotice v-if="!isMinimized" />
|
||||
<div v-show="!isMinimized" class="chat-container">
|
||||
<div v-if="!isReady" class="loading-container">
|
||||
<el-icon class="is-loading"><Loading /></el-icon>
|
||||
@@ -132,8 +131,6 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, nextTick, watch, computed, onMounted, onUnmounted } from 'vue'
|
||||
import DoctorWebConsultationNotice from '@/components/doctor-web-consultation-notice/index.vue'
|
||||
import { useDoctorWebConsultation } from '@/hooks/useDoctorWebConsultation'
|
||||
import { Loading, Close, Rank, Camera, Fold, Expand } from '@element-plus/icons-vue'
|
||||
import { uploadImageBlob, uploadVideoBlob } from '@/api/file'
|
||||
import { addDoctorNote } from '@/api/patient'
|
||||
@@ -198,9 +195,8 @@ const appointmentTypeLabel = computed(() => confirmedTypeLabel.value || appointm
|
||||
const serverAllowsVideo = ref(false)
|
||||
const serverAllowsAudio = ref(false)
|
||||
const callDisabledReason = ref('正在确认挂号类型')
|
||||
const { webConsultationBlocked, webConsultationMessage, ensureWebConsultationAllowed } = useDoctorWebConsultation()
|
||||
const canVideoCall = computed(() => !webConsultationBlocked.value && serverAllowsVideo.value && canAppointmentVideoCall(appointmentType.value))
|
||||
const canAudioCall = computed(() => !webConsultationBlocked.value && serverAllowsAudio.value && (canAppointmentVideoCall(appointmentType.value) || appointmentType.value === 'phone'))
|
||||
const canVideoCall = computed(() => serverAllowsVideo.value && canAppointmentVideoCall(appointmentType.value))
|
||||
const canAudioCall = computed(() => serverAllowsAudio.value && (canAppointmentVideoCall(appointmentType.value) || appointmentType.value === 'phone'))
|
||||
let releaseAppointmentCallGuard: (() => void) | undefined
|
||||
let chatContextVersion = 0
|
||||
let outgoingCallType = 2
|
||||
@@ -257,7 +253,6 @@ function syncAppointmentCallPolicy(res: {
|
||||
}
|
||||
|
||||
async function prepareAppointmentCall(callType: number) {
|
||||
if (!ensureWebConsultationAllowed()) throw new Error(webConsultationMessage.value)
|
||||
const contextVersion = chatContextVersion
|
||||
const allowed = () => callType === 1 ? canAudioCall.value : canVideoCall.value
|
||||
if (!visible.value || !allowed()) {
|
||||
@@ -271,7 +266,6 @@ async function prepareAppointmentCall(callType: number) {
|
||||
})
|
||||
if (!visible.value || chatContextVersion !== contextVersion) throw new Error('当前问诊已切换,请重新发起通话')
|
||||
syncAppointmentCallPolicy(res)
|
||||
if (!ensureWebConsultationAllowed()) throw new Error(webConsultationMessage.value)
|
||||
if (!allowed()) {
|
||||
feedback.msgWarning(callDisabledReason.value)
|
||||
throw new Error(callDisabledReason.value)
|
||||
@@ -719,14 +713,6 @@ function installTUICallKitRoomHooks() {
|
||||
wrap('calls')
|
||||
wrap('call')
|
||||
wrap('groupCall')
|
||||
// 已登录 SDK 的旧聊天窗口也不能在截止后接起新面诊。
|
||||
const originalAccept = server.accept
|
||||
if (typeof originalAccept === 'function') {
|
||||
server.accept = async function patchedAccept(...args: unknown[]) {
|
||||
if (!ensureWebConsultationAllowed()) throw new Error(webConsultationMessage.value)
|
||||
return originalAccept.apply(server, args)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function doBindCallRoom(rid: string) {
|
||||
@@ -1113,7 +1099,6 @@ watch(() => activeConversation.value, async (newConversation) => {
|
||||
})
|
||||
|
||||
const open = async (data: { patientId: number; patientName: string; diagnosisId?: number; appointmentId?: number; appointmentType?: string | null }) => {
|
||||
if (!ensureWebConsultationAllowed()) return
|
||||
stopChatArchiveWatch(true)
|
||||
const contextVersion = ++chatContextVersion
|
||||
releaseAppointmentCallGuard?.()
|
||||
@@ -1275,7 +1260,6 @@ const open = async (data: { patientId: number; patientName: string; diagnosisId?
|
||||
|
||||
// 群组视频通话(多人通话):当前医生作为发起方,默认先邀请当前会话患者
|
||||
const startGroupVideoCall = async () => {
|
||||
if (!ensureWebConsultationAllowed()) return
|
||||
if (!canVideoCall.value) {
|
||||
feedback.msgWarning(appointmentType.value === 'text' ? '图文问诊不支持视频通话' : callDisabledReason.value)
|
||||
return
|
||||
|
||||
@@ -1,102 +0,0 @@
|
||||
<template>
|
||||
<el-alert
|
||||
class="doctor-web-consultation-notice"
|
||||
:type="consultationReminder.type"
|
||||
:closable="false"
|
||||
show-icon
|
||||
:title="consultationReminder.title"
|
||||
>
|
||||
<p>{{ consultationReminder.description }}</p>
|
||||
<p v-if="policyLoadFailed">
|
||||
面诊切换时间更新失败,请重新获取最新设置。
|
||||
<el-button link type="primary" @click="refreshConsultationPolicy()">刷新切换时间</el-button>
|
||||
</p>
|
||||
<p v-if="consultationReminder.countdown" class="notice-countdown">
|
||||
距网页端面诊停用还有 {{ consultationReminder.countdown }}(北京时间)
|
||||
</p>
|
||||
<div class="notice-downloads">
|
||||
<a
|
||||
v-for="item in downloads.packages"
|
||||
:key="item.platform"
|
||||
class="installer-link"
|
||||
:href="item.url"
|
||||
:download="item.filename || undefined"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<el-icon><Download /></el-icon>
|
||||
下载 {{ item.label }}安装包
|
||||
</a>
|
||||
<span v-if="downloadsLoading && !downloads.packages.length">正在获取安装包…</span>
|
||||
<template v-else-if="!downloads.packages.length">
|
||||
<span>{{ downloadsFailed ? '安装包加载失败,请重试。' : '安装包暂未发布,请联系管理员获取。' }}</span>
|
||||
<el-button link type="primary" @click="loadDownloads(true)">重新获取</el-button>
|
||||
</template>
|
||||
<el-button v-else-if="downloadsFailed" link type="primary" @click="loadDownloads(true)">刷新安装包</el-button>
|
||||
</div>
|
||||
<p v-if="downloads.packages.length" class="install-instructions">
|
||||
<span v-if="downloads.version">当前版本 v{{ downloads.version }} · </span>
|
||||
安装完成后,使用当前医生账号登录桌面应用。
|
||||
</p>
|
||||
<p v-if="hasWindowsInstaller" class="install-instructions">
|
||||
Windows 安装包适用于 Windows 10 1809 及以上版本、Windows 11(64位)。
|
||||
</p>
|
||||
</el-alert>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { useDoctorWebConsultation } from '@/hooks/useDoctorWebConsultation'
|
||||
import { useDesktopWorkstationDownloads } from '@/hooks/useDesktopWorkstationDownloads'
|
||||
import { Download } from '@element-plus/icons-vue'
|
||||
import { computed, watch } from 'vue'
|
||||
|
||||
const { consultationReminder, policyLoadFailed, refreshConsultationPolicy } = useDoctorWebConsultation()
|
||||
const { downloads, downloadsLoading, downloadsFailed, loadDownloads } = useDesktopWorkstationDownloads()
|
||||
const hasWindowsInstaller = computed(() => downloads.value.packages.some(item => item.platform === 'windows_x64'))
|
||||
watch(() => consultationReminder.value.phase, () => { void loadDownloads(true) })
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.doctor-web-consultation-notice {
|
||||
flex-shrink: 0;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.doctor-web-consultation-notice p {
|
||||
margin: 4px 0 0;
|
||||
font-size: 14px;
|
||||
line-height: 1.7;
|
||||
}
|
||||
.notice-countdown {
|
||||
font-weight: 600;
|
||||
}
|
||||
.notice-downloads {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px 12px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
.installer-link {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 7px 12px;
|
||||
border-radius: 6px;
|
||||
color: #fff;
|
||||
background: #2563eb;
|
||||
font-size: 14px;
|
||||
line-height: 1.5;
|
||||
text-decoration: none;
|
||||
}
|
||||
.installer-link:hover {
|
||||
background: #1d4ed8;
|
||||
}
|
||||
.installer-link:focus-visible {
|
||||
outline: 2px solid #1d4ed8;
|
||||
outline-offset: 3px;
|
||||
}
|
||||
.doctor-web-consultation-notice .install-instructions {
|
||||
margin-top: 8px;
|
||||
font-size: 13px;
|
||||
}
|
||||
</style>
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
const config = {
|
||||
terminal: 1, //终端
|
||||
title: '互联网医院', //网站默认标题
|
||||
title: '后台管理系统', //网站默认标题
|
||||
version: '1.9.4', //版本号
|
||||
baseUrl: `${import.meta.env.VITE_APP_BASE_URL || ''}/`, //请求接口域名
|
||||
urlPrefix: 'adminapi', //请求默认前缀
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
import { onBeforeUnmount, ref, watch } from 'vue'
|
||||
import { getConsultationTranscripts, type ConsultationCallRecord } from '@/api/tcm'
|
||||
import { normalizeConsultationRecords } from '@/utils/consultation-transcripts'
|
||||
|
||||
export function useConsultationTranscripts(diagnosisId: () => number) {
|
||||
const records = ref<ConsultationCallRecord[]>([])
|
||||
const loading = ref(false)
|
||||
const error = ref('')
|
||||
let sequence = 0
|
||||
let controller: AbortController | undefined
|
||||
|
||||
const refresh = async () => {
|
||||
const id = Number(diagnosisId())
|
||||
const request = ++sequence
|
||||
controller?.abort()
|
||||
error.value = ''
|
||||
if (!Number.isSafeInteger(id) || id <= 0) {
|
||||
records.value = []
|
||||
loading.value = false
|
||||
return
|
||||
}
|
||||
controller = new AbortController()
|
||||
loading.value = true
|
||||
try {
|
||||
const result = await getConsultationTranscripts({ diagnosis_id: id }, controller.signal)
|
||||
if (request !== sequence || Number(diagnosisId()) !== id) return
|
||||
records.value = normalizeConsultationRecords(result, id)
|
||||
} catch (reason: any) {
|
||||
if (request !== sequence || Number(diagnosisId()) !== id) return
|
||||
error.value = String(reason?.msg || reason?.message || '面诊文字对话加载失败,请重试')
|
||||
} finally {
|
||||
if (request === sequence) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(diagnosisId, () => {
|
||||
records.value = []
|
||||
void refresh()
|
||||
}, { immediate: true, flush: 'sync' })
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
sequence++
|
||||
controller?.abort()
|
||||
records.value = []
|
||||
})
|
||||
return { records, loading, error, refresh }
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
import { onMounted, onUnmounted, ref, shallowRef } from 'vue'
|
||||
import {
|
||||
getDesktopWorkstationDownloads,
|
||||
type DesktopWorkstationDownload,
|
||||
type DesktopWorkstationDownloads
|
||||
} from '@/api/setting/desktop_workstation'
|
||||
|
||||
// 接诊台、列表和聊天窗口共用一个请求与短缓存。
|
||||
const downloads = shallowRef<DesktopWorkstationDownloads>({ version: '', packages: [] })
|
||||
const downloadsLoading = ref(false)
|
||||
const downloadsFailed = ref(false)
|
||||
let pending: Promise<void> | undefined
|
||||
let loadedAt = 0
|
||||
const CACHE_MS = 5 * 60 * 1000
|
||||
|
||||
export function normalizeDesktopDownloads(value: DesktopWorkstationDownloads): DesktopWorkstationDownloads {
|
||||
const platforms = ['windows_x64', 'macos_arm64', 'macos_x64']
|
||||
const packages: DesktopWorkstationDownload[] = []
|
||||
const seen = new Set<string>()
|
||||
for (const item of Array.isArray(value?.packages) ? value.packages : []) {
|
||||
if (!item || typeof item !== 'object') continue
|
||||
if (!platforms.includes(item.platform) || seen.has(item.platform)) continue
|
||||
try {
|
||||
const url = new URL(item.url)
|
||||
if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password) continue
|
||||
if (!/^[a-f\d]{64}$/i.test(item.sha256)) continue
|
||||
packages.push({ ...item, url: url.href })
|
||||
seen.add(item.platform)
|
||||
} catch { /* 配置异常时不生成无效下载链接。 */ }
|
||||
}
|
||||
return { version: String(value?.version || ''), packages }
|
||||
}
|
||||
|
||||
export function useDesktopWorkstationDownloads() {
|
||||
const loadDownloads = (force = false): Promise<void> => {
|
||||
if (pending) return pending
|
||||
if (!force && loadedAt > 0 && Date.now() - loadedAt < CACHE_MS) return Promise.resolve()
|
||||
downloadsLoading.value = true
|
||||
downloadsFailed.value = false
|
||||
pending = getDesktopWorkstationDownloads().then(data => {
|
||||
downloads.value = normalizeDesktopDownloads(data)
|
||||
loadedAt = Date.now()
|
||||
}).catch(() => {
|
||||
downloadsFailed.value = true
|
||||
}).finally(() => {
|
||||
downloadsLoading.value = false
|
||||
pending = undefined
|
||||
})
|
||||
return pending
|
||||
}
|
||||
const refreshOnFocus = () => { void loadDownloads() }
|
||||
onMounted(() => {
|
||||
void loadDownloads()
|
||||
window.addEventListener('focus', refreshOnFocus)
|
||||
})
|
||||
onUnmounted(() => window.removeEventListener('focus', refreshOnFocus))
|
||||
|
||||
return { downloads, downloadsLoading, downloadsFailed, loadDownloads }
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
|
||||
import { getDoctorWebConsultationPolicy } from '@/api/app'
|
||||
import useUserStore from '@/stores/modules/user'
|
||||
import feedback from '@/utils/feedback'
|
||||
import {
|
||||
doctorWebConsultationMessage,
|
||||
doctorWebConsultationReminder,
|
||||
hasDoctorWebConsultationExpired,
|
||||
isConsultationDoctor,
|
||||
isDoctorWebConsultationBlocked,
|
||||
normalizeDoctorWebConsultationPolicy
|
||||
} from '@/utils/doctor-web-consultation'
|
||||
|
||||
// 多个列表、公告及聊天窗口共用请求;配置更新无需重新构建前端。
|
||||
let pending: Promise<void> | undefined
|
||||
let lastAttemptAt = 0
|
||||
const REFRESH_MS = 60 * 1000
|
||||
const policyLoadFailed = ref(false)
|
||||
|
||||
export function useDoctorWebConsultation() {
|
||||
const userStore = useUserStore()
|
||||
const now = ref(Date.now())
|
||||
let timer: ReturnType<typeof setInterval> | undefined
|
||||
const updateClock = () => { now.value = Date.now() + (userStore.serverTimeOffsetMs || 0) }
|
||||
const policy = computed(() => normalizeDoctorWebConsultationPolicy(userStore.userInfo.web_consultation_policy))
|
||||
|
||||
const loadPolicy = (force = false): Promise<void> => {
|
||||
if (pending) return pending
|
||||
if (!force && lastAttemptAt > 0 && Date.now() - lastAttemptAt < REFRESH_MS) return Promise.resolve()
|
||||
lastAttemptAt = Date.now()
|
||||
pending = getDoctorWebConsultationPolicy().then(data => {
|
||||
const next = normalizeDoctorWebConsultationPolicy(data)
|
||||
if (!next) throw new Error('网页面诊时间配置无效')
|
||||
userStore.userInfo.web_consultation_policy = next
|
||||
userStore.serverTimeOffsetMs = next.server_time * 1000 - Date.now()
|
||||
policyLoadFailed.value = false
|
||||
updateClock()
|
||||
}).catch(() => {
|
||||
// 保留最近一次有效配置,后端仍逐次校验实际截止时间。
|
||||
policyLoadFailed.value = true
|
||||
}).finally(() => { pending = undefined })
|
||||
return pending
|
||||
}
|
||||
const refreshConsultationPolicy = () => loadPolicy(true)
|
||||
const refreshOnFocus = () => {
|
||||
updateClock()
|
||||
void refreshConsultationPolicy()
|
||||
}
|
||||
const refreshOnVisible = () => {
|
||||
if (document.visibilityState !== 'hidden') refreshOnFocus()
|
||||
}
|
||||
|
||||
// 登录响应和配置刷新响应均提供服务器时刻,避免本机时区/时钟影响规则。
|
||||
watch(() => userStore.serverTimeOffsetMs, updateClock, { immediate: true })
|
||||
|
||||
onMounted(() => {
|
||||
updateClock()
|
||||
void refreshConsultationPolicy()
|
||||
timer = setInterval(() => {
|
||||
updateClock()
|
||||
void loadPolicy()
|
||||
}, 1000)
|
||||
window.addEventListener('focus', refreshOnFocus)
|
||||
document.addEventListener('visibilitychange', refreshOnVisible)
|
||||
})
|
||||
onUnmounted(() => {
|
||||
clearInterval(timer)
|
||||
window.removeEventListener('focus', refreshOnFocus)
|
||||
document.removeEventListener('visibilitychange', refreshOnVisible)
|
||||
})
|
||||
|
||||
const isDoctor = computed(() => isConsultationDoctor(userStore.userInfo))
|
||||
const webConsultationExpired = computed(() => hasDoctorWebConsultationExpired(policy.value, now.value))
|
||||
const consultationReminder = computed(() => doctorWebConsultationReminder(policy.value, now.value))
|
||||
const webConsultationMessage = computed(() => doctorWebConsultationMessage(policy.value))
|
||||
const webConsultationBlocked = computed(() => isDoctorWebConsultationBlocked(userStore.userInfo, policy.value, now.value))
|
||||
const ensureWebConsultationAllowed = () => {
|
||||
updateClock()
|
||||
if (!webConsultationBlocked.value) return true
|
||||
feedback.msgWarning(webConsultationMessage.value)
|
||||
return false
|
||||
}
|
||||
|
||||
return {
|
||||
isDoctor, consultationReminder, webConsultationExpired, webConsultationBlocked,
|
||||
webConsultationMessage, ensureWebConsultationAllowed, policyLoadFailed, refreshConsultationPolicy
|
||||
}
|
||||
}
|
||||
@@ -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, '/group-login']
|
||||
const whiteList: string[] = [PageEnum.LOGIN, PageEnum.ERROR_403]
|
||||
router.beforeEach(async (to, from, next) => {
|
||||
document.title = to.meta.title ?? config.title
|
||||
const userStore = useUserStore()
|
||||
|
||||
@@ -35,11 +35,6 @@ 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')
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import type { RouteRecordRaw } from 'vue-router'
|
||||
|
||||
import { getUserInfo, iamLogin, login, logout, workWechatLogin } from '@/api/user'
|
||||
import { getUserInfo, login, logout, workWechatLogin } from '@/api/user'
|
||||
import { TOKEN_KEY } from '@/enums/cacheEnums'
|
||||
import { PageEnum } from '@/enums/pageEnum'
|
||||
import router, { filterAsyncRoutes } from '@/router'
|
||||
@@ -14,7 +14,6 @@ export interface UserState {
|
||||
routes: RouteRecordRaw[]
|
||||
perms: string[]
|
||||
isPaw: number // 0=需要修改密码,1=正常
|
||||
serverTimeOffsetMs: number
|
||||
}
|
||||
|
||||
const useUserStore = defineStore({
|
||||
@@ -28,8 +27,7 @@ const useUserStore = defineStore({
|
||||
// 权限
|
||||
perms: [],
|
||||
// 是否需要修改密码
|
||||
isPaw: 1,
|
||||
serverTimeOffsetMs: 0
|
||||
isPaw: 1
|
||||
}),
|
||||
getters: {},
|
||||
actions: {
|
||||
@@ -38,7 +36,6 @@ const useUserStore = defineStore({
|
||||
this.userInfo = {}
|
||||
this.perms = []
|
||||
this.isPaw = 1
|
||||
this.serverTimeOffsetMs = 0
|
||||
},
|
||||
login(playload: any) {
|
||||
const { account, password } = playload
|
||||
@@ -86,20 +83,11 @@ const useUserStore = defineStore({
|
||||
})
|
||||
})
|
||||
},
|
||||
async iamLogin(ticket: string) {
|
||||
const data = await iamLogin(ticket)
|
||||
this.token = data.token
|
||||
this.isPaw = data.is_paw ?? 1
|
||||
cache.set(TOKEN_KEY, data.token)
|
||||
return data
|
||||
},
|
||||
getUserInfo() {
|
||||
return new Promise((resolve, reject) => {
|
||||
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 状态
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
import type { ConsultationCallRecord } from '@/api/tcm'
|
||||
|
||||
export function normalizeConsultationRecords(value: unknown, diagnosisId: number): ConsultationCallRecord[] {
|
||||
if (!Array.isArray(value)) throw new Error('面诊记录返回格式异常,请重试')
|
||||
const seen = new Set<number>()
|
||||
return value.filter(row => {
|
||||
if (!row || !Number.isSafeInteger(Number(row.id)) || Number(row.id) <= 0 || seen.has(Number(row.id))) return false
|
||||
if (row.diagnosis_id != null && Number(row.diagnosis_id) !== diagnosisId) return false
|
||||
seen.add(Number(row.id))
|
||||
return true
|
||||
}).map(row => ({
|
||||
...row,
|
||||
id: Number(row.id),
|
||||
diagnosis_id: diagnosisId,
|
||||
transcript_text: typeof row.transcript_text === 'string' ? row.transcript_text.replace(/\r\n/g, '\n').trim() : ''
|
||||
})).sort((a, b) => b.id - a.id)
|
||||
}
|
||||
|
||||
export function consultationTranscriptText(row?: ConsultationCallRecord | null): string {
|
||||
return typeof row?.transcript_text === 'string' ? row.transcript_text.trim() : ''
|
||||
}
|
||||
|
||||
export function consultationTranscriptStatus(row: ConsultationCallRecord) {
|
||||
switch (row.transcription_status) {
|
||||
case 'running': return { label: '录音转写中', type: 'info' as const }
|
||||
case 'completed': return { label: '文字已生成', type: 'success' as const }
|
||||
case 'partial': return { label: '文字部分保存', type: 'warning' as const }
|
||||
case 'failed': return { label: '文字生成失败', type: 'danger' as const }
|
||||
default: return consultationTranscriptText(row)
|
||||
? { label: '文字已保存', type: 'success' as const }
|
||||
: { label: '未生成文字', type: 'info' as const }
|
||||
}
|
||||
}
|
||||
|
||||
export function consultationTranscriptEmptyText(row: ConsultationCallRecord): string {
|
||||
if (row.transcription_status === 'running') return '正在转写,可点击刷新查看最新保存的文字。'
|
||||
if (row.transcription_status === 'failed') return '本次面诊文字生成失败,暂无已保存的对话。'
|
||||
if (Number(row.status) === 3) return '本次通话未接听,暂无文字对话。'
|
||||
if (Number(row.status) === 4) return '本次通话已取消,暂无文字对话。'
|
||||
return '本次面诊暂无已保存的文字对话。'
|
||||
}
|
||||
|
||||
export function consultationCallLabel(row: ConsultationCallRecord): string {
|
||||
return Number(row.call_type) === 1 ? '语音面诊' : Number(row.call_type) === 2 ? '视频面诊' : '面诊记录'
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
// 所有时间由服务端配置提供,浏览器不保留独立的截止日期。
|
||||
export type DoctorWebConsultationPolicy = {
|
||||
cutoff_at: string
|
||||
approaching_at: string
|
||||
urgent_at: string
|
||||
server_time: number
|
||||
}
|
||||
|
||||
export type DoctorWebConsultationPhase = 'prepare' | 'approaching' | 'last_day' | 'expired'
|
||||
|
||||
export function normalizeDoctorWebConsultationPolicy(value: unknown): DoctorWebConsultationPolicy | undefined {
|
||||
if (!value || typeof value !== 'object') return undefined
|
||||
const policy = value as DoctorWebConsultationPolicy
|
||||
const timestamps = [policy.approaching_at, policy.urgent_at, policy.cutoff_at].map(date =>
|
||||
typeof date === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/.test(date) ? Date.parse(date) : NaN
|
||||
)
|
||||
if (timestamps.some(time => !Number.isFinite(time)) || timestamps[0] > timestamps[1] || timestamps[1] > timestamps[2]) return undefined
|
||||
if (!Number.isFinite(policy.server_time) || policy.server_time <= 0) return undefined
|
||||
return { cutoff_at: policy.cutoff_at, approaching_at: policy.approaching_at, urgent_at: policy.urgent_at, server_time: policy.server_time }
|
||||
}
|
||||
|
||||
export function doctorWebConsultationDate(policy: DoctorWebConsultationPolicy): string {
|
||||
// 无论医生电脑所在时区为何,公告始终显示北京时间。
|
||||
const parts = new Intl.DateTimeFormat('en-GB', {
|
||||
timeZone: 'Asia/Shanghai', year: 'numeric', month: '2-digit', day: '2-digit',
|
||||
hour: '2-digit', minute: '2-digit', second: '2-digit', hourCycle: 'h23'
|
||||
}).formatToParts(new Date(policy.cutoff_at))
|
||||
const part = (type: string) => parts.find(item => item.type === type)?.value || ''
|
||||
const seconds = part('second') === '00' ? '' : `:${part('second')}`
|
||||
return `${part('year')}年${part('month')}月${part('day')}日${part('hour')}:${part('minute')}${seconds}(北京时间)`
|
||||
}
|
||||
|
||||
export function doctorWebConsultationMessage(policy?: DoctorWebConsultationPolicy): string {
|
||||
return `网页端面诊已${policy ? `于${doctorWebConsultationDate(policy)}` : ''}停用,请医生使用桌面应用进行面诊。`
|
||||
}
|
||||
|
||||
export function doctorWebConsultationReminder(policy?: DoctorWebConsultationPolicy, now = Date.now()) {
|
||||
if (!policy) return {
|
||||
phase: 'prepare' as DoctorWebConsultationPhase,
|
||||
type: 'info' as const,
|
||||
title: '系统公告:医生桌面应用安装指引',
|
||||
description: '请各位医生提前下载并安装桌面应用,使用当前医生账号登录。',
|
||||
countdown: ''
|
||||
}
|
||||
const cutoffDate = doctorWebConsultationDate(policy)
|
||||
const remaining = Date.parse(policy.cutoff_at) - now
|
||||
const days = Math.floor(remaining / 86400000)
|
||||
const hours = Math.floor(remaining / 3600000) % 24
|
||||
const minutes = Math.floor(remaining / 60000) % 60
|
||||
const countdown = remaining <= 0 ? '' : remaining < 60000 ? '不足1分钟' :
|
||||
`${days > 0 ? `${days}天` : ''}${hours > 0 ? `${hours}小时` : ''}${minutes > 0 ? `${minutes}分钟` : ''}`
|
||||
|
||||
if (remaining <= 0) return {
|
||||
phase: 'expired' as DoctorWebConsultationPhase,
|
||||
type: 'error' as const,
|
||||
title: '系统公告:医生网页端面诊已停用',
|
||||
description: doctorWebConsultationMessage(policy),
|
||||
countdown: ''
|
||||
}
|
||||
if (now >= Date.parse(policy.urgent_at)) return {
|
||||
phase: 'last_day' as DoctorWebConsultationPhase,
|
||||
type: 'error' as const,
|
||||
title: '系统公告:医生网页端面诊停用最后提醒',
|
||||
description: `请各位医生在${cutoffDate}前完成桌面应用的安装与登录。届时接诊台、问诊列表的网页端面诊功能将同步停用,请使用桌面应用进行面诊。`,
|
||||
countdown
|
||||
}
|
||||
if (now >= Date.parse(policy.approaching_at)) return {
|
||||
phase: 'approaching' as DoctorWebConsultationPhase,
|
||||
type: 'warning' as const,
|
||||
title: '系统公告:医生网页端面诊即将停用',
|
||||
description: `网页端面诊将于${cutoffDate}停用。请各位医生尽快下载桌面应用,完成安装并使用当前医生账号登录,接诊台、问诊列表将同步执行此规则。`,
|
||||
countdown
|
||||
}
|
||||
return {
|
||||
phase: 'prepare' as DoctorWebConsultationPhase,
|
||||
type: 'info' as const,
|
||||
title: '系统公告:请提前安装医生桌面应用',
|
||||
description: `请各位医生提前下载并安装桌面应用,使用当前医生账号登录试用。自${cutoffDate}起,接诊台、问诊列表的网页端面诊功能将停用,请提前做好准备。`,
|
||||
countdown: ''
|
||||
}
|
||||
}
|
||||
|
||||
export function isConsultationDoctor(user: Record<string, any>): boolean {
|
||||
return Number(user.root) !== 1 && Array.isArray(user.role_ids) && user.role_ids.some(role => Number(role) === 1)
|
||||
}
|
||||
|
||||
export function hasDoctorWebConsultationExpired(policy?: DoctorWebConsultationPolicy, now = Date.now()): boolean {
|
||||
return !!policy && now >= Date.parse(policy.cutoff_at)
|
||||
}
|
||||
|
||||
export function isDoctorWebConsultationBlocked(
|
||||
user: Record<string, any>,
|
||||
policy?: DoctorWebConsultationPolicy,
|
||||
now = Date.now()
|
||||
): boolean {
|
||||
return isConsultationDoctor(user) && hasDoctorWebConsultationExpired(policy, now)
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
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
|
||||
@@ -1,111 +0,0 @@
|
||||
// 集团登录只交换短时凭据;原业务 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/'
|
||||
}
|
||||
@@ -1,403 +0,0 @@
|
||||
/**
|
||||
* 复诊节点(revisit_due)前端纯函数集合
|
||||
*
|
||||
* 数据契约与后端 `RevisitDueService::buildListPayload` 输出一致(方案 docs/plans/assistant-revisit-reach-reminder-2026-10-12.md 契约 C):
|
||||
* 所有日期为 'Y-m-d' 字符串或 '';无快照且无法计算时后端返回 state='none' 的对象,前端显示「—」。
|
||||
*
|
||||
* 本文件只做 state → 文案 / 颜色 class / el-tag type 的映射与日期、天数文案拼装,不含任何请求或响应式逻辑,
|
||||
* 供 PC 列表、H5 卡片、只读页三处共用(RevisitNodeCell.vue + readonly.vue)。
|
||||
*/
|
||||
|
||||
export type RevisitDueState =
|
||||
| 'visited'
|
||||
| 'booked'
|
||||
| 'missed'
|
||||
| 'contacted'
|
||||
| 'overdue'
|
||||
| 'warning'
|
||||
| 'pending'
|
||||
| 'no_days'
|
||||
| 'none'
|
||||
|
||||
/** 列表行 `revisit_due` 对象(契约 C) */
|
||||
export interface RevisitDue {
|
||||
current_slot: number
|
||||
next_slot: number
|
||||
valid_order_count: number
|
||||
medication_days: number
|
||||
/** 0=缺失 1=订单 2=处方 */
|
||||
days_src: 0 | 1 | 2
|
||||
/** 14/21/28/30 或 0=其它 */
|
||||
rule_days: number
|
||||
/** 0=无 1=签收 2=发货 3=下单 */
|
||||
anchor_src: 0 | 1 | 2 | 3
|
||||
anchor_date: string
|
||||
order_date: string
|
||||
due_date: string
|
||||
days_left: number | null
|
||||
overdue_days: number | null
|
||||
state: RevisitDueState | string
|
||||
state_text: string
|
||||
severe: 0 | 1
|
||||
/** 0=无 1=已约 3=已面诊 4=过号 */
|
||||
appointment_state: number
|
||||
appointment_date: string
|
||||
snooze_count: number
|
||||
escalation_level: number
|
||||
promised_date: string
|
||||
missed_count: number
|
||||
first_touch_date: string
|
||||
in_care_days: number | null
|
||||
total_medication_days: number
|
||||
closed_state: number
|
||||
}
|
||||
|
||||
/** 「复诊状态」筛选下拉选项(请求参数 revisit_state;due = overdue ∪ missed) */
|
||||
export const REVISIT_STATE_FILTER_OPTIONS: Array<{ label: string; value: string }> = [
|
||||
{ label: '到期未挂号 / 过号', value: 'due' },
|
||||
{ label: '即将到期', value: 'warning' },
|
||||
{ label: '已约待面诊', value: 'booked' },
|
||||
{ label: '已面诊', value: 'visited' },
|
||||
{ label: '已联系', value: 'contacted' },
|
||||
{ label: '缺开药天数', value: 'no_days' },
|
||||
{ label: '未到期', value: 'pending' }
|
||||
]
|
||||
|
||||
/** 「开药天数档」筛选下拉选项(请求参数 revisit_days_bucket) */
|
||||
export const REVISIT_DAYS_BUCKET_OPTIONS: Array<{ label: string; value: string }> = [
|
||||
{ label: '14 天', value: '14' },
|
||||
{ label: '21 天', value: '21' },
|
||||
{ label: '28 天', value: '28' },
|
||||
{ label: '30 天', value: '30' },
|
||||
{ label: '其它天数', value: 'other' }
|
||||
]
|
||||
|
||||
/** state → 默认文案(后端 state_text 缺失时兜底) */
|
||||
const STATE_LABEL: Record<string, string> = {
|
||||
visited: '已面诊',
|
||||
booked: '已约',
|
||||
missed: '过号',
|
||||
contacted: '已联系',
|
||||
overdue: '超期',
|
||||
warning: '即将到期',
|
||||
pending: '未到期',
|
||||
no_days: '缺开药天数',
|
||||
none: '—'
|
||||
}
|
||||
|
||||
const toInt = (v: unknown, fallback = 0): number => {
|
||||
if (v === null || v === undefined || v === '') return fallback
|
||||
const n = Number(v)
|
||||
return Number.isFinite(n) ? Math.trunc(n) : fallback
|
||||
}
|
||||
|
||||
const toNullableInt = (v: unknown): number | null => {
|
||||
if (v === null || v === undefined || v === '') return null
|
||||
const n = Number(v)
|
||||
return Number.isFinite(n) ? Math.trunc(n) : null
|
||||
}
|
||||
|
||||
const toDateStr = (v: unknown): string => {
|
||||
if (v === null || v === undefined) return ''
|
||||
const s = String(v).trim()
|
||||
if (s === '' || s === '0000-00-00') return ''
|
||||
return s
|
||||
}
|
||||
|
||||
/**
|
||||
* 把列表行 / 详情里的 `revisit_due` 原始值规整为 RevisitDue;
|
||||
* 字段缺失(旧接口)或非对象时返回 null,调用方据此不渲染。
|
||||
*/
|
||||
export function normalizeRevisitDue(raw: unknown): RevisitDue | null {
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null
|
||||
const r = raw as Record<string, unknown>
|
||||
const state = String(r.state ?? 'none').trim() || 'none'
|
||||
const daysSrc = toInt(r.days_src)
|
||||
const anchorSrc = toInt(r.anchor_src)
|
||||
return {
|
||||
current_slot: toInt(r.current_slot),
|
||||
next_slot: toInt(r.next_slot),
|
||||
valid_order_count: toInt(r.valid_order_count),
|
||||
medication_days: toInt(r.medication_days),
|
||||
days_src: (daysSrc === 1 || daysSrc === 2 ? daysSrc : 0) as 0 | 1 | 2,
|
||||
rule_days: toInt(r.rule_days),
|
||||
anchor_src: (anchorSrc >= 1 && anchorSrc <= 3 ? anchorSrc : 0) as 0 | 1 | 2 | 3,
|
||||
anchor_date: toDateStr(r.anchor_date),
|
||||
order_date: toDateStr(r.order_date),
|
||||
due_date: toDateStr(r.due_date),
|
||||
days_left: toNullableInt(r.days_left),
|
||||
overdue_days: toNullableInt(r.overdue_days),
|
||||
state,
|
||||
state_text: String(r.state_text ?? '').trim(),
|
||||
severe: toInt(r.severe) === 1 ? 1 : 0,
|
||||
appointment_state: toInt(r.appointment_state),
|
||||
appointment_date: toDateStr(r.appointment_date),
|
||||
snooze_count: toInt(r.snooze_count),
|
||||
escalation_level: toInt(r.escalation_level),
|
||||
promised_date: toDateStr(r.promised_date),
|
||||
missed_count: toInt(r.missed_count),
|
||||
first_touch_date: toDateStr(r.first_touch_date),
|
||||
in_care_days: toNullableInt(r.in_care_days),
|
||||
total_medication_days: toInt(r.total_medication_days),
|
||||
closed_state: toInt(r.closed_state)
|
||||
}
|
||||
}
|
||||
|
||||
/** 是否有可展示的复诊节点(state !== 'none') */
|
||||
export function hasRevisitDue(due: RevisitDue | null | undefined): due is RevisitDue {
|
||||
return !!due && due.state !== 'none' && due.state !== ''
|
||||
}
|
||||
|
||||
/** 行级标红:到期未挂号 / 过号未面诊;人工关闭或已自动关闭(closed_state!==0)的行不标红,与「复诊到期」chip / 筛选口径一致 */
|
||||
export function isRevisitDueHighlight(due: RevisitDue | null | undefined): boolean {
|
||||
return (
|
||||
hasRevisitDue(due) &&
|
||||
toInt(due.closed_state) === 0 &&
|
||||
(due.state === 'overdue' || due.state === 'missed')
|
||||
)
|
||||
}
|
||||
|
||||
/** 深红:超期达到 severe_overdue_days(后端已算好 severe=1) */
|
||||
export function isRevisitDueSevere(due: RevisitDue | null | undefined): boolean {
|
||||
return isRevisitDueHighlight(due) && Number(due?.severe) === 1
|
||||
}
|
||||
|
||||
/**
|
||||
* el-table :row-class-name 片段:
|
||||
* '' | 'row-revisit-overdue' | 'row-revisit-overdue row-revisit-overdue-deep'
|
||||
*/
|
||||
export function revisitRowClassName(due: RevisitDue | null | undefined): string {
|
||||
if (!isRevisitDueHighlight(due)) return ''
|
||||
return isRevisitDueSevere(due) ? 'row-revisit-overdue row-revisit-overdue-deep' : 'row-revisit-overdue'
|
||||
}
|
||||
|
||||
/** 'YYYY-MM-DD' → 'MM-DD';非法/空值返回 '' */
|
||||
export function formatRevisitMonthDay(date: string | null | undefined): string {
|
||||
const s = toDateStr(date)
|
||||
if (!s) return ''
|
||||
const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(s)
|
||||
if (m) return `${m[2]}-${m[3]}`
|
||||
return s
|
||||
}
|
||||
|
||||
/** 用药起算锚点来源文案(行 2 末尾) */
|
||||
export function revisitAnchorSrcText(src: number | null | undefined): string {
|
||||
const n = toInt(src)
|
||||
if (n === 1) return '签收起'
|
||||
if (n === 2) return '发货起'
|
||||
if (n === 3) return '下单起'
|
||||
return ''
|
||||
}
|
||||
|
||||
/** 开药天数来源文案(tooltip 用) */
|
||||
export function revisitDaysSrcText(src: number | null | undefined): string {
|
||||
const n = toInt(src)
|
||||
if (n === 1) return '订单'
|
||||
if (n === 2) return '处方'
|
||||
return '缺失'
|
||||
}
|
||||
|
||||
/** 是否缺开药天数(days_src=0 或 medication_days<=0) */
|
||||
export function isRevisitDaysMissing(due: RevisitDue | null | undefined): boolean {
|
||||
if (!hasRevisitDue(due)) return false
|
||||
return toInt(due.days_src) === 0 || toInt(due.medication_days) <= 0
|
||||
}
|
||||
|
||||
/** 「第 N 诊」文案 */
|
||||
export function revisitSlotText(due: RevisitDue | null | undefined): string {
|
||||
if (!hasRevisitDue(due)) return ''
|
||||
const slot = toInt(due.current_slot)
|
||||
return slot > 0 ? `第 ${slot} 诊` : '未成交'
|
||||
}
|
||||
|
||||
/** 「开药 X 天」或「缺开药天数」 */
|
||||
export function revisitMedicationDaysText(due: RevisitDue | null | undefined): string {
|
||||
if (!hasRevisitDue(due)) return ''
|
||||
if (isRevisitDaysMissing(due)) return '缺开药天数'
|
||||
return `开药 ${toInt(due.medication_days)} 天`
|
||||
}
|
||||
|
||||
/** 「药尽 MM-DD」;缺天数无 due_date 时返回 '' */
|
||||
export function revisitDueDateText(due: RevisitDue | null | undefined): string {
|
||||
if (!hasRevisitDue(due)) return ''
|
||||
const md = formatRevisitMonthDay(due.due_date)
|
||||
return md ? `药尽 ${md}` : ''
|
||||
}
|
||||
|
||||
/** state 兜底文案(后端 state_text 为空时使用) */
|
||||
export function revisitStateLabel(state: string | null | undefined): string {
|
||||
const key = String(state ?? '').trim()
|
||||
return STATE_LABEL[key] ?? (key || '—')
|
||||
}
|
||||
|
||||
/**
|
||||
* 状态 chip 文案:优先后端 state_text;为空时按 state + 数字自行拼装,
|
||||
* 保证旧接口 / 字段缺失时也可读。
|
||||
*/
|
||||
export function revisitStateChipText(due: RevisitDue | null | undefined): string {
|
||||
if (!hasRevisitDue(due)) return ''
|
||||
if (due.state_text) return due.state_text
|
||||
const state = String(due.state)
|
||||
switch (state) {
|
||||
case 'overdue': {
|
||||
const n = toInt(due.overdue_days)
|
||||
return n <= 0 ? '今日应挂号' : `超期 ${n} 天`
|
||||
}
|
||||
case 'missed': {
|
||||
const md = formatRevisitMonthDay(due.appointment_date)
|
||||
return md ? `过号 ${md}` : '过号'
|
||||
}
|
||||
case 'booked': {
|
||||
const md = formatRevisitMonthDay(due.appointment_date)
|
||||
return md ? `已约 ${md}` : '已约'
|
||||
}
|
||||
case 'visited': {
|
||||
const md = formatRevisitMonthDay(due.appointment_date)
|
||||
return md ? `已面诊 ${md}` : '已面诊'
|
||||
}
|
||||
case 'contacted': {
|
||||
const md = formatRevisitMonthDay(due.promised_date)
|
||||
return md ? `已联系·约 ${md}` : '已联系'
|
||||
}
|
||||
case 'warning':
|
||||
case 'pending': {
|
||||
const n = due.days_left
|
||||
return n === null ? revisitStateLabel(state) : `剩 ${n} 天`
|
||||
}
|
||||
default:
|
||||
return revisitStateLabel(state)
|
||||
}
|
||||
}
|
||||
|
||||
/** 状态 chip 的 el-tag type */
|
||||
export function revisitStateTagType(
|
||||
state: string | null | undefined
|
||||
): 'danger' | 'warning' | 'primary' | 'success' | 'info' {
|
||||
switch (String(state ?? '')) {
|
||||
case 'overdue':
|
||||
case 'missed':
|
||||
return 'danger'
|
||||
case 'warning':
|
||||
case 'no_days':
|
||||
return 'warning'
|
||||
case 'booked':
|
||||
case 'contacted':
|
||||
return 'primary'
|
||||
case 'visited':
|
||||
return 'success'
|
||||
default:
|
||||
return 'info'
|
||||
}
|
||||
}
|
||||
|
||||
/** 状态 chip 的 el-tag effect:红为 dark;描边态(已联系 / 缺天数)为 plain;其余 light */
|
||||
export function revisitStateTagEffect(state: string | null | undefined): 'dark' | 'light' | 'plain' {
|
||||
switch (String(state ?? '')) {
|
||||
case 'overdue':
|
||||
case 'missed':
|
||||
return 'dark'
|
||||
case 'contacted':
|
||||
case 'no_days':
|
||||
return 'plain'
|
||||
default:
|
||||
return 'light'
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 状态 → 徽标颜色 class(复用列表 / 只读页既有的 unserved-* 色板):
|
||||
* overdue/missed → unserved-red;warning/no_days → unserved-orange;
|
||||
* visited → unserved-green;booked/contacted → unserved-blue;其余 → unserved-muted
|
||||
*/
|
||||
export function revisitStateColorClass(
|
||||
state: string | null | undefined
|
||||
): 'unserved-red' | 'unserved-orange' | 'unserved-green' | 'unserved-blue' | 'unserved-muted' {
|
||||
switch (String(state ?? '')) {
|
||||
case 'overdue':
|
||||
case 'missed':
|
||||
return 'unserved-red'
|
||||
case 'warning':
|
||||
case 'no_days':
|
||||
return 'unserved-orange'
|
||||
case 'visited':
|
||||
return 'unserved-green'
|
||||
case 'booked':
|
||||
case 'contacted':
|
||||
return 'unserved-blue'
|
||||
default:
|
||||
return 'unserved-muted'
|
||||
}
|
||||
}
|
||||
|
||||
/** 状态 chip 附加 class(组件内样式钩子):rv-chip rv-chip--<state> [rv-chip--severe] */
|
||||
export function revisitStateChipClass(due: RevisitDue | null | undefined): string {
|
||||
if (!hasRevisitDue(due)) return 'rv-chip'
|
||||
const cls = ['rv-chip', `rv-chip--${String(due.state)}`]
|
||||
if (isRevisitDueSevere(due)) cls.push('rv-chip--severe')
|
||||
return cls.join(' ')
|
||||
}
|
||||
|
||||
/** 行 4:「已延迟 N 次」 */
|
||||
export function revisitSnoozeText(due: RevisitDue | null | undefined): string {
|
||||
if (!hasRevisitDue(due)) return ''
|
||||
const n = toInt(due.snooze_count)
|
||||
return n > 0 ? `已延迟 ${n} 次` : ''
|
||||
}
|
||||
|
||||
/** 行 4:「已联系 约 MM-DD」 */
|
||||
export function revisitContactText(due: RevisitDue | null | undefined): string {
|
||||
if (!hasRevisitDue(due)) return ''
|
||||
const md = formatRevisitMonthDay(due.promised_date)
|
||||
return md ? `已联系 约 ${md}` : ''
|
||||
}
|
||||
|
||||
/** 行 4 合并文案:仅 snooze_count>0 或 promised_date 有值时非空 */
|
||||
export function revisitFollowLineText(due: RevisitDue | null | undefined): string {
|
||||
const parts = [revisitSnoozeText(due), revisitContactText(due)].filter((s) => s !== '')
|
||||
return parts.join(' · ')
|
||||
}
|
||||
|
||||
/** 行 2:「MM-DD 开药 · 开药 X 天 · 签收起」 */
|
||||
export function revisitOrderLineText(due: RevisitDue | null | undefined): string {
|
||||
if (!hasRevisitDue(due)) return ''
|
||||
const parts: string[] = []
|
||||
const md = formatRevisitMonthDay(due.order_date)
|
||||
if (md) parts.push(`${md} 开药`)
|
||||
parts.push(revisitMedicationDaysText(due))
|
||||
if (!isRevisitDaysMissing(due)) {
|
||||
const anchor = revisitAnchorSrcText(due.anchor_src)
|
||||
if (anchor) parts.push(anchor)
|
||||
}
|
||||
return parts.filter((s) => s !== '').join(' · ')
|
||||
}
|
||||
|
||||
/** 诊次 tag tooltip 行 */
|
||||
export function revisitTooltipLines(due: RevisitDue | null | undefined): string[] {
|
||||
if (!hasRevisitDue(due)) return []
|
||||
const lines: string[] = []
|
||||
const offset = Math.max(0, toInt(due.current_slot) - toInt(due.valid_order_count))
|
||||
lines.push(`有效订单 ${toInt(due.valid_order_count)} 笔 · 诊次偏移 +${offset}`)
|
||||
if (toInt(due.next_slot) > 0) lines.push(`待复诊:第 ${toInt(due.next_slot)} 诊`)
|
||||
const first = formatRevisitMonthDay(due.first_touch_date)
|
||||
if (first) {
|
||||
const care = due.in_care_days
|
||||
lines.push(care === null ? `首次触达 ${first}` : `首次触达 ${first} · 在管 ${care} 天`)
|
||||
}
|
||||
if (toInt(due.total_medication_days) > 0) lines.push(`累计开药 ${toInt(due.total_medication_days)} 天`)
|
||||
const anchorMd = formatRevisitMonthDay(due.anchor_date)
|
||||
const anchorSrc = revisitAnchorSrcText(due.anchor_src)
|
||||
if (anchorMd && anchorSrc) lines.push(`用药起算 ${anchorMd}(${anchorSrc.replace(/起$/, '')})`)
|
||||
if (!isRevisitDaysMissing(due)) lines.push(`开药天数来源:${revisitDaysSrcText(due.days_src)}`)
|
||||
if (toInt(due.missed_count) > 0) lines.push(`曾过号 ${toInt(due.missed_count)} 次`)
|
||||
return lines
|
||||
}
|
||||
|
||||
/**
|
||||
* 只读页徽标文案:「第 N 诊 · 药尽 MM-DD · 超期 N 天」
|
||||
* 无 due_date 时省略中段;尾段为状态 chip 文案。
|
||||
*/
|
||||
export function revisitBadgeText(due: RevisitDue | null | undefined): string {
|
||||
if (!hasRevisitDue(due)) return ''
|
||||
const parts = [revisitSlotText(due), revisitDueDateText(due), revisitStateChipText(due)]
|
||||
return parts.filter((s) => s !== '').join(' · ')
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
<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>
|
||||
@@ -11,11 +11,11 @@
|
||||
<div class="text-center text-3xl font-medium mb-8">{{ config.web_name }}</div>
|
||||
|
||||
<!-- 企业微信自动授权中 -->
|
||||
<div v-if="wxWorkAutoLogin || iamLoading" class="text-center py-10">
|
||||
<div v-if="wxWorkAutoLogin" class="text-center py-10">
|
||||
<el-icon class="is-loading mb-4" :size="40" color="var(--el-color-primary)">
|
||||
<Loading />
|
||||
</el-icon>
|
||||
<div class="text-gray-500">{{ iamLoading ? '统一账号登录中...' : '企业微信授权登录中...' }}</div>
|
||||
<div class="text-gray-500">企业微信授权登录中...</div>
|
||||
</div>
|
||||
|
||||
<template v-else>
|
||||
@@ -78,20 +78,6 @@
|
||||
请使用企业微信扫描二维码登录
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<section v-if="iamEnabled" class="iam-login-alternative" aria-label="其他登录方式">
|
||||
<div class="iam-login-divider" aria-hidden="true">其他登录方式</div>
|
||||
<el-button class="iam-login-entry" size="large" @click="handleIamLogin">
|
||||
<span class="iam-login-entry__content">
|
||||
<icon name="local-icon-anquan" size="22" />
|
||||
<span>统一账号快捷登录</span>
|
||||
</span>
|
||||
<span class="iam-login-entry__arrow" aria-hidden="true">
|
||||
<icon name="el-icon-ArrowRight" size="16" />
|
||||
</span>
|
||||
</el-button>
|
||||
<p class="iam-login-hint">使用统一身份平台账号登录</p>
|
||||
</section>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
@@ -113,7 +99,7 @@ import LayoutFooter from '@/layout/components/footer.vue'
|
||||
import useAppStore from '@/stores/modules/app'
|
||||
import useUserStore from '@/stores/modules/user'
|
||||
import cache from '@/utils/cache'
|
||||
import { getIamConfig, getWorkWechatConfig } from '@/api/user'
|
||||
import { getWorkWechatConfig } from '@/api/user'
|
||||
|
||||
const passwordRef = shallowRef<InputInstance>()
|
||||
const formRef = shallowRef<FormInstance>()
|
||||
@@ -132,66 +118,6 @@ const rules = {
|
||||
password: [{ required: true, message: '请输入密码', trigger: ['blur'] }]
|
||||
}
|
||||
|
||||
// 统一账号登录是可选入口,不取代账号密码或企业微信登录。
|
||||
const iamEnabled = ref(false)
|
||||
const iamLoginUrl = ref('')
|
||||
const iamLoading = ref(false)
|
||||
let iamCallbackHandled = false
|
||||
|
||||
const loadIamConfig = async () => {
|
||||
try {
|
||||
const result = await getIamConfig()
|
||||
const url = new URL(result?.loginUrl || '', window.location.origin)
|
||||
if (result?.enabled === true && url.protocol === 'https:') {
|
||||
iamLoginUrl.value = url.href
|
||||
iamEnabled.value = true
|
||||
}
|
||||
} catch {
|
||||
// IAM 不可用时,原有登录入口保持可用。
|
||||
}
|
||||
}
|
||||
|
||||
const handleIamLogin = () => {
|
||||
if (iamEnabled.value && iamLoginUrl.value) {
|
||||
window.location.assign(iamLoginUrl.value)
|
||||
}
|
||||
}
|
||||
|
||||
const handleIamCallback = async (ticket: string | null, error: string | null) => {
|
||||
if (iamCallbackHandled) return
|
||||
iamCallbackHandled = true
|
||||
// 在任何 await 和兑换前移除票据,刷新不会重复兑换;保留其他 query/hash。
|
||||
const cleanUrl = new URL(window.location.href)
|
||||
cleanUrl.searchParams.delete('iam_ticket')
|
||||
cleanUrl.searchParams.delete('iam_error')
|
||||
// 同一回调不得随后被识别为企业微信授权。
|
||||
cleanUrl.searchParams.delete('code')
|
||||
cleanUrl.searchParams.delete('state')
|
||||
window.history.replaceState(window.history.state, '', cleanUrl.pathname + cleanUrl.search + cleanUrl.hash)
|
||||
if (error || !ticket) {
|
||||
ElMessage.error(error || '统一账号登录凭证无效,请重新登录')
|
||||
return
|
||||
}
|
||||
iamLoading.value = true
|
||||
try {
|
||||
const result = await userStore.iamLogin(ticket)
|
||||
if (result.is_paw === 0) {
|
||||
await router.push('/change-password')
|
||||
return
|
||||
}
|
||||
if (result.need_bind_work_wechat) {
|
||||
await router.push('/bind-work-wechat')
|
||||
return
|
||||
}
|
||||
redirectAfterLogin()
|
||||
} catch (error: any) {
|
||||
ElMessage.error(error?.msg || error?.message || '统一账号登录失败,请重新登录或使用账号密码')
|
||||
loginMode.value = 'account'
|
||||
} finally {
|
||||
iamLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 企业微信相关
|
||||
const loginMode = ref<'account' | 'wxwork'>('account')
|
||||
const wxWorkEnabled = ref(false)
|
||||
@@ -317,12 +243,7 @@ onMounted(async () => {
|
||||
|
||||
// 检查 URL 中是否有企业微信回调 code
|
||||
const urlParams = new URLSearchParams(window.location.search)
|
||||
void loadIamConfig()
|
||||
const hasIamCallback = urlParams.has('iam_ticket') || urlParams.has('iam_error')
|
||||
if (hasIamCallback) {
|
||||
await handleIamCallback(urlParams.get('iam_ticket'), urlParams.get('iam_error'))
|
||||
}
|
||||
const wxCode = hasIamCallback ? null : urlParams.get('code')
|
||||
const wxCode = urlParams.get('code')
|
||||
const wxState = urlParams.get('state')
|
||||
|
||||
if (wxCode && wxState === 'admin_login') {
|
||||
@@ -342,7 +263,7 @@ onMounted(async () => {
|
||||
wxWorkConfig.value = { corp_id: res.corp_id, agent_id: res.agent_id }
|
||||
|
||||
// 在企业微信内:自动跳转 OAuth 授权
|
||||
if (isInWxWork() && !hasIamCallback) {
|
||||
if (isInWxWork()) {
|
||||
const redirectUri = encodeURIComponent(getRedirectUri())
|
||||
const authUrl =
|
||||
`https://open.weixin.qq.com/connect/oauth2/authorize` +
|
||||
@@ -365,82 +286,6 @@ onMounted(async () => {
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.iam-login-alternative {
|
||||
margin-top: 28px;
|
||||
}
|
||||
|
||||
.iam-login-divider {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
margin-bottom: 18px;
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: 13px;
|
||||
line-height: 20px;
|
||||
|
||||
&::before,
|
||||
&::after {
|
||||
content: '';
|
||||
flex: 1;
|
||||
height: 1px;
|
||||
background: var(--el-border-color-light);
|
||||
}
|
||||
}
|
||||
|
||||
.iam-login-entry.el-button {
|
||||
--el-button-bg-color: var(--el-color-primary-light-9);
|
||||
--el-button-text-color: var(--el-color-primary);
|
||||
--el-button-border-color: var(--el-color-primary-light-5);
|
||||
--el-button-hover-bg-color: var(--el-color-primary-light-8);
|
||||
--el-button-hover-text-color: var(--el-color-primary);
|
||||
--el-button-hover-border-color: var(--el-color-primary);
|
||||
--el-button-active-bg-color: var(--el-color-primary-light-8);
|
||||
--el-button-active-border-color: var(--el-color-primary);
|
||||
position: relative;
|
||||
width: 100%;
|
||||
min-height: 48px;
|
||||
height: auto;
|
||||
margin: 0;
|
||||
padding: 12px 34px;
|
||||
border-radius: 8px;
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
transition: background-color 150ms ease, border-color 150ms ease;
|
||||
|
||||
&:focus-visible {
|
||||
outline: 2px solid var(--el-color-primary);
|
||||
outline-offset: 3px;
|
||||
}
|
||||
}
|
||||
|
||||
.iam-login-entry__content {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.iam-login-entry__arrow {
|
||||
position: absolute;
|
||||
right: 14px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.iam-login-hint {
|
||||
margin: 14px 0 0;
|
||||
text-align: center;
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: 12px;
|
||||
line-height: 20px;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.iam-login-entry.el-button {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
|
||||
.login {
|
||||
background-image: url('./images/login_bg.png');
|
||||
@apply min-h-screen bg-no-repeat bg-center bg-cover;
|
||||
|
||||
@@ -1,135 +0,0 @@
|
||||
<template>
|
||||
<div class="ai-access-log-page">
|
||||
<el-card class="!border-none" shadow="never">
|
||||
<el-form :inline="true">
|
||||
<el-form-item label="时间">
|
||||
<el-date-picker
|
||||
v-model="timeRange"
|
||||
type="datetimerange"
|
||||
range-separator="至"
|
||||
start-placeholder="开始时间"
|
||||
end-placeholder="结束时间"
|
||||
value-format="YYYY-MM-DD HH:mm:ss"
|
||||
clearable
|
||||
@change="resetPage"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item label="结果">
|
||||
<el-select v-model="queryParams.status" clearable placeholder="全部" class="w-[120px]" @change="resetPage">
|
||||
<el-option v-for="(label, value) in STATUS" :key="value" :label="label" :value="value" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="数据资源">
|
||||
<el-input v-model="queryParams.resource" placeholder="如 tcm.diagnosis" clearable class="w-[180px]" @keyup.enter="resetPage" @clear="resetPage" />
|
||||
</el-form-item>
|
||||
<el-form-item label="记录ID">
|
||||
<el-input v-model="queryParams.record_id" placeholder="如诊单ID" clearable class="w-[130px]" @keyup.enter="resetPage" @clear="resetPage" />
|
||||
</el-form-item>
|
||||
<el-form-item label="任务号">
|
||||
<el-input v-model="queryParams.client_task_id" placeholder="行知任务号" clearable class="w-[200px]" @keyup.enter="resetPage" @clear="resetPage" />
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-button type="primary" @click="resetPage">查询</el-button>
|
||||
<el-button @click="handleReset">重置</el-button>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<div class="page-hint">
|
||||
记录每一次 AI 查询:谁、通过哪个客户端任务、查了哪个数据资源、返回了哪些记录。按“记录ID”可以查某个诊单被哪些账号通过 AI 看过。
|
||||
</div>
|
||||
</el-card>
|
||||
|
||||
<el-card class="!border-none mt-3" shadow="never">
|
||||
<el-table :data="pager.lists" v-loading="pager.loading" size="default" stripe>
|
||||
<el-table-column label="时间" width="165" prop="create_time_text" />
|
||||
<el-table-column label="账号" min-width="120">
|
||||
<template #default="{ row }">
|
||||
<div>{{ row.admin_name || (row.admin_id ? '#' + row.admin_id : '—') }}</div>
|
||||
<div class="cell-sub">{{ row.ip }}</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="工具" width="170" prop="tool" />
|
||||
<el-table-column label="数据资源" min-width="200">
|
||||
<template #default="{ row }">
|
||||
<div>{{ row.resource_name || row.resource || '—' }}</div>
|
||||
<div class="cell-sub">{{ row.resource }}</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="结果" width="90" align="center">
|
||||
<template #default="{ row }">
|
||||
<el-tag :type="row.status === 'ok' ? 'success' : 'warning'" size="small">{{ STATUS[row.status] || row.status }}</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="条数" width="70" align="right" prop="result_rows" />
|
||||
<el-table-column label="记录ID / 原因" min-width="200">
|
||||
<template #default="{ row }">
|
||||
<el-tooltip v-if="row.record_ids" :content="row.record_ids" placement="top">
|
||||
<span class="ellipsis">{{ row.record_ids }}</span>
|
||||
</el-tooltip>
|
||||
<span v-else class="cell-sub">{{ row.message }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="参数" min-width="220">
|
||||
<template #default="{ row }">
|
||||
<el-tooltip v-if="row.arguments" :content="row.arguments" placement="top">
|
||||
<span class="ellipsis">{{ row.arguments }}</span>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="耗时" width="80" align="right">
|
||||
<template #default="{ row }">{{ row.duration_ms }}ms</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="任务号" min-width="160" prop="client_task_id" />
|
||||
</el-table>
|
||||
<div class="flex justify-end mt-4">
|
||||
<pagination v-model="pager" @change="getLists" />
|
||||
</div>
|
||||
</el-card>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts" name="aiMcpAccessLog">
|
||||
import { aiAccessLogLists } from '@/api/ai_mcp'
|
||||
import { usePaging } from '@/hooks/usePaging'
|
||||
import { onMounted, reactive, ref, watch } from 'vue'
|
||||
|
||||
const STATUS: Record<string, string> = { ok: '成功', denied: '拒绝', invalid: '参数错误', limited: '超限', error: '失败' }
|
||||
const timeRange = ref<[string, string] | null>(null)
|
||||
const queryParams = reactive({ start_time: '', end_time: '', status: '', resource: '', record_id: '', client_task_id: '' })
|
||||
|
||||
watch(timeRange, (val) => {
|
||||
queryParams.start_time = val?.[0] ?? ''
|
||||
queryParams.end_time = val?.[1] ?? ''
|
||||
})
|
||||
|
||||
const { pager, getLists, resetPage, resetParams } = usePaging({
|
||||
fetchFun: aiAccessLogLists,
|
||||
params: queryParams
|
||||
})
|
||||
|
||||
const handleReset = () => {
|
||||
timeRange.value = null
|
||||
resetParams()
|
||||
}
|
||||
|
||||
onMounted(() => getLists())
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.page-hint {
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: 13px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.cell-sub {
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: 12px;
|
||||
}
|
||||
.ellipsis {
|
||||
display: inline-block;
|
||||
max-width: 100%;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
vertical-align: bottom;
|
||||
}
|
||||
</style>
|
||||
@@ -1,123 +0,0 @@
|
||||
<template>
|
||||
<div class="ai-catalog-page">
|
||||
<el-card class="!border-none" shadow="never">
|
||||
<div class="summary">
|
||||
<div class="summary-item">
|
||||
<div class="summary-value success">{{ counts.open ?? 0 }}</div>
|
||||
<div class="summary-label">已开放</div>
|
||||
</div>
|
||||
<div class="summary-item">
|
||||
<div class="summary-value warning">{{ counts.pending ?? 0 }}</div>
|
||||
<div class="summary-label">待整改</div>
|
||||
</div>
|
||||
<div class="summary-item">
|
||||
<div class="summary-value">{{ counts.excluded ?? 0 }}</div>
|
||||
<div class="summary-label">不开放</div>
|
||||
</div>
|
||||
</div>
|
||||
<el-form :inline="true" class="mt-3">
|
||||
<el-form-item label="状态">
|
||||
<el-select v-model="queryParams.status" clearable placeholder="全部" class="w-[120px]" @change="resetPage">
|
||||
<el-option label="已开放" value="open" />
|
||||
<el-option label="待整改" value="pending" />
|
||||
<el-option label="不开放" value="excluded" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="业务分组">
|
||||
<el-select v-model="queryParams.domain" clearable filterable placeholder="全部" class="w-[180px]" @change="resetPage">
|
||||
<el-option v-for="d in domains" :key="d" :label="d" :value="d" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="关键词">
|
||||
<el-input v-model="queryParams.keyword" placeholder="名称或资源标识" clearable class="w-[200px]" @keyup.enter="resetPage" @clear="resetPage" />
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-button type="primary" @click="resetPage">查询</el-button>
|
||||
<el-button @click="resetParams">重置</el-button>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<div class="page-hint">
|
||||
后台每个只读接口都是一个“数据资源”。已开放的资源由 AI 以调用账号自己的权限和数据范围执行原有接口;
|
||||
待整改的资源写明了原因(如缺少逐条权限校验、会调用外部接口、权限点未登记),整改或审核通过后开放。
|
||||
</div>
|
||||
</el-card>
|
||||
|
||||
<el-card class="!border-none mt-3" shadow="never">
|
||||
<el-table :data="pager.lists" v-loading="pager.loading" size="default" stripe>
|
||||
<el-table-column label="资源" min-width="220">
|
||||
<template #default="{ row }">
|
||||
<div>{{ row.name }}</div>
|
||||
<div class="cell-sub">{{ row.resource }}</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="业务分组" width="150" prop="domain" />
|
||||
<el-table-column label="类型" width="80">
|
||||
<template #default="{ row }">{{ KIND[row.kind] || row.kind }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="状态" width="90" align="center">
|
||||
<template #default="{ row }">
|
||||
<el-tag :type="STATUS[row.status]?.type" size="small">{{ STATUS[row.status]?.label || row.status }}</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="原因" min-width="260" prop="reason" />
|
||||
<el-table-column label="已审核" width="80" align="center">
|
||||
<template #default="{ row }">{{ row.reviewed ? '是' : '自动' }}</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
<div class="flex justify-end mt-4">
|
||||
<pagination v-model="pager" @change="getLists" />
|
||||
</div>
|
||||
</el-card>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts" name="aiMcpCatalog">
|
||||
import { aiCatalogLists } from '@/api/ai_mcp'
|
||||
import { usePaging } from '@/hooks/usePaging'
|
||||
import { computed, onMounted, reactive } from 'vue'
|
||||
|
||||
const KIND: Record<string, string> = { list: '列表', detail: '详情', report: '统计', other: '其他', write: '写操作' }
|
||||
const STATUS: Record<string, { label: string; type: 'success' | 'warning' | 'info' }> = {
|
||||
open: { label: '已开放', type: 'success' },
|
||||
pending: { label: '待整改', type: 'warning' },
|
||||
excluded: { label: '不开放', type: 'info' }
|
||||
}
|
||||
const queryParams = reactive({ status: '', domain: '', keyword: '' })
|
||||
|
||||
const { pager, getLists, resetPage, resetParams } = usePaging({
|
||||
fetchFun: aiCatalogLists,
|
||||
params: queryParams,
|
||||
size: 50
|
||||
})
|
||||
|
||||
const counts = computed<Record<string, number>>(() => pager.extend?.counts || {})
|
||||
const domains = computed<string[]>(() => pager.extend?.domains || [])
|
||||
|
||||
onMounted(() => getLists())
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.summary {
|
||||
display: flex;
|
||||
gap: 48px;
|
||||
}
|
||||
.summary-value {
|
||||
font-size: 26px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.summary-value.success {
|
||||
color: var(--el-color-success);
|
||||
}
|
||||
.summary-value.warning {
|
||||
color: var(--el-color-warning);
|
||||
}
|
||||
.summary-label,
|
||||
.page-hint,
|
||||
.cell-sub {
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: 13px;
|
||||
}
|
||||
.page-hint {
|
||||
line-height: 1.6;
|
||||
}
|
||||
</style>
|
||||
@@ -1,135 +0,0 @@
|
||||
<template>
|
||||
<div class="ai-grant-page">
|
||||
<el-card class="!border-none" shadow="never">
|
||||
<el-alert
|
||||
v-if="pager.extend && pager.extend.enabled === false"
|
||||
type="warning"
|
||||
:closable="false"
|
||||
show-icon
|
||||
class="mb-3"
|
||||
title="AI 助手接口未启用:服务器 .env 的 [AI_MCP] ENABLED 为 false,客户端暂时无法绑定和查询。"
|
||||
/>
|
||||
<el-form :inline="true">
|
||||
<el-form-item label="状态">
|
||||
<el-select v-model="queryParams.status" clearable placeholder="全部" class="w-[120px]" @change="resetPage">
|
||||
<el-option label="有效" value="1" />
|
||||
<el-option label="已撤销" value="2" />
|
||||
<el-option label="已过期" value="3" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="关键词">
|
||||
<el-input
|
||||
v-model="queryParams.keyword"
|
||||
placeholder="姓名 / 账号 / 备注"
|
||||
clearable
|
||||
class="w-[220px]"
|
||||
@keyup.enter="resetPage"
|
||||
@clear="resetPage"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-button type="primary" @click="resetPage">查询</el-button>
|
||||
<el-button @click="resetParams">重置</el-button>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<div class="page-hint">
|
||||
员工在行知等 AI 助手里用甄养堂账号密码绑定后,会在这里生成一条只读授权。AI 只能按该账号自己的权限和数据范围查询;
|
||||
撤销后立即失效。账号改密、停用、失去“允许 AI 助手查询”权限时,授权也会自动失效。
|
||||
</div>
|
||||
</el-card>
|
||||
|
||||
<el-card class="!border-none mt-3" shadow="never">
|
||||
<el-table :data="pager.lists" v-loading="pager.loading" size="default" stripe>
|
||||
<el-table-column label="账号" min-width="140">
|
||||
<template #default="{ row }">
|
||||
<div>{{ row.admin_name || '—' }}</div>
|
||||
<div class="cell-sub">{{ row.admin_account }}</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="客户端" min-width="150">
|
||||
<template #default="{ row }">
|
||||
<div>{{ row.client }}<span v-if="row.client_instance"> · {{ row.client_instance }}</span></div>
|
||||
<div class="cell-sub">{{ row.label }}</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="令牌" width="130" prop="token_prefix" />
|
||||
<el-table-column label="状态" width="90" align="center">
|
||||
<template #default="{ row }">
|
||||
<el-tag :type="row.status_text === '有效' ? 'success' : 'info'" size="small">{{ row.status_text }}</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="最近使用" min-width="150">
|
||||
<template #default="{ row }">
|
||||
<div>{{ row.last_used_time_text || '—' }}</div>
|
||||
<div class="cell-sub">{{ row.last_used_ip }}</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="到期时间" width="150" prop="expire_time_text" />
|
||||
<el-table-column label="签发时间" width="150" prop="create_time_text" />
|
||||
<el-table-column label="撤销" min-width="140">
|
||||
<template #default="{ row }">
|
||||
<template v-if="row.revoke_time_text">
|
||||
<div>{{ row.revoke_time_text }}</div>
|
||||
<div class="cell-sub">{{ reasonText(row.revoke_reason) }}</div>
|
||||
</template>
|
||||
<span v-else>—</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="90" fixed="right">
|
||||
<template #default="{ row }">
|
||||
<el-button v-if="row.can_revoke" type="danger" link @click="handleRevoke(row)">撤销</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
<div class="flex justify-end mt-4">
|
||||
<pagination v-model="pager" @change="getLists" />
|
||||
</div>
|
||||
</el-card>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts" name="aiMcpGrant">
|
||||
import { aiGrantLists, aiGrantRevoke } from '@/api/ai_mcp'
|
||||
import { usePaging } from '@/hooks/usePaging'
|
||||
import feedback from '@/utils/feedback'
|
||||
import { onMounted, reactive } from 'vue'
|
||||
|
||||
const queryParams = reactive({ status: '', keyword: '' })
|
||||
|
||||
const { pager, getLists, resetPage, resetParams } = usePaging({
|
||||
fetchFun: aiGrantLists,
|
||||
params: queryParams
|
||||
})
|
||||
|
||||
const REASONS: Record<string, string> = {
|
||||
client_revoke: '客户端解绑',
|
||||
admin_revoke: '后台撤销',
|
||||
rebind: '重新绑定',
|
||||
expired: '到期/闲置失效',
|
||||
password_changed: '账号改密',
|
||||
admin_disabled: '账号停用',
|
||||
admin_deleted: '账号删除'
|
||||
}
|
||||
const reasonText = (reason: string) => REASONS[reason] || reason || ''
|
||||
|
||||
const handleRevoke = async (row: any) => {
|
||||
await feedback.confirm(`确认撤销 ${row.admin_name || row.admin_account} 的这条 AI 授权?撤销后该客户端需要重新绑定。`)
|
||||
await aiGrantRevoke({ id: row.id })
|
||||
feedback.msgSuccess('已撤销')
|
||||
getLists()
|
||||
}
|
||||
|
||||
onMounted(() => getLists())
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.page-hint {
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: 13px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.cell-sub {
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: 12px;
|
||||
}
|
||||
</style>
|
||||
@@ -312,17 +312,6 @@
|
||||
{{ detailPrescription.dosage_amount }}{{ detailPrescription.dosage_unit || 'g' }}
|
||||
<template v-if="detailPrescription.prescription_type === '浓缩水丸'">
|
||||
· {{ Number(detailPrescription.dosage_bag_count) > 0 ? Number(detailPrescription.dosage_bag_count) : 1 }}袋
|
||||
<el-button
|
||||
v-if="!readonly && detailData.prescription_id && !String(detailData.prescription_detail_error || '').trim()"
|
||||
v-perms="['tcm.prescriptionOrder/patchPrescriptionUsage']"
|
||||
type="primary"
|
||||
size="small"
|
||||
link
|
||||
class="ml-2"
|
||||
@click="openPatchUsageDialog"
|
||||
>
|
||||
修改
|
||||
</el-button>
|
||||
</template>
|
||||
<span v-if="detailPrescription.prescription_type === '饮片' && detailPrescription.need_decoction !== null" class="ml-2 text-gray-500">
|
||||
({{ detailPrescription.need_decoction ? '代煎' : '不代煎' }})
|
||||
@@ -336,17 +325,6 @@
|
||||
{{ detailAuxUsage.dosage_amount }}{{ detailPrescription.dosage_unit || 'g' }}
|
||||
<template v-if="detailPrescription.prescription_type === '浓缩水丸'">
|
||||
· {{ Number(detailAuxUsage.dosage_bag_count) > 0 ? Number(detailAuxUsage.dosage_bag_count) : 1 }}袋
|
||||
<el-button
|
||||
v-if="!readonly && detailData.prescription_id && !String(detailData.prescription_detail_error || '').trim()"
|
||||
v-perms="['tcm.prescriptionOrder/patchPrescriptionUsage']"
|
||||
type="primary"
|
||||
size="small"
|
||||
link
|
||||
class="ml-2"
|
||||
@click="openPatchUsageDialog"
|
||||
>
|
||||
修改
|
||||
</el-button>
|
||||
</template>
|
||||
<span v-if="detailPrescription.prescription_type === '饮片'" class="ml-2 text-gray-500">
|
||||
({{ detailAuxUsage.need_decoction ? '代煎' : '不代煎' }})
|
||||
@@ -965,15 +943,6 @@
|
||||
label-width="108px"
|
||||
>
|
||||
<div v-if="detailHasAuxHerbs" class="text-xs font-medium text-gray-500 mb-3">主方</div>
|
||||
<el-form-item
|
||||
v-if="detailPrescription?.prescription_type === '浓缩水丸'"
|
||||
label="每次袋数"
|
||||
prop="dosage_bag_count"
|
||||
>
|
||||
<el-select v-model="patchUsageForm.dosage_bag_count" class="w-full">
|
||||
<el-option v-for="count in 5" :key="count" :label="`${count}袋`" :value="count" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="每天次数" prop="times_per_day">
|
||||
<el-input-number
|
||||
v-model="patchUsageForm.times_per_day"
|
||||
@@ -999,15 +968,6 @@
|
||||
</el-form-item>
|
||||
<template v-if="detailHasAuxHerbs">
|
||||
<div class="text-xs font-medium text-gray-500 mb-3 mt-2 pt-2 border-t border-gray-100">辅方</div>
|
||||
<el-form-item
|
||||
v-if="detailPrescription?.prescription_type === '浓缩水丸'"
|
||||
label="每次袋数"
|
||||
prop="aux_dosage_bag_count"
|
||||
>
|
||||
<el-select v-model="patchUsageForm.aux_dosage_bag_count" class="w-full">
|
||||
<el-option v-for="count in 5" :key="count" :label="`${count}袋`" :value="count" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="每天次数" prop="aux_times_per_day">
|
||||
<el-input-number
|
||||
v-model="patchUsageForm.aux_times_per_day"
|
||||
@@ -1472,12 +1432,10 @@ const patchUsageVisible = ref(false)
|
||||
const patchUsageSaving = ref(false)
|
||||
const patchUsageFormRef = ref<FormInstance>()
|
||||
const patchUsageForm = reactive({
|
||||
dosage_bag_count: 1 as number | undefined,
|
||||
times_per_day: 3 as number | undefined,
|
||||
usage_days: 7 as number | undefined,
|
||||
aux_times_per_day: 3 as number | undefined,
|
||||
aux_usage_days: 7 as number | undefined,
|
||||
aux_dosage_bag_count: 1 as number | undefined,
|
||||
medication_days: undefined as number | undefined
|
||||
})
|
||||
const patchUsageRules = computed<FormRules>(() => {
|
||||
@@ -1486,15 +1444,9 @@ const patchUsageRules = computed<FormRules>(() => {
|
||||
usage_days: [{ required: true, message: '请填写主方开立天数', trigger: 'change' }],
|
||||
medication_days: [{ required: true, message: '请填写订单服用天数', trigger: 'change' }]
|
||||
}
|
||||
if (detailPrescription.value?.prescription_type === '浓缩水丸') {
|
||||
rules.dosage_bag_count = [{ required: true, message: '请选择主方每次袋数', trigger: 'change' }]
|
||||
}
|
||||
if (detailHasAuxHerbs.value) {
|
||||
rules.aux_times_per_day = [{ required: true, message: '请填写辅方每天次数', trigger: 'change' }]
|
||||
rules.aux_usage_days = [{ required: true, message: '请填写辅方开立天数', trigger: 'change' }]
|
||||
if (detailPrescription.value?.prescription_type === '浓缩水丸') {
|
||||
rules.aux_dosage_bag_count = [{ required: true, message: '请选择辅方每次袋数', trigger: 'change' }]
|
||||
}
|
||||
}
|
||||
return rules
|
||||
})
|
||||
@@ -1507,7 +1459,6 @@ function openPatchUsageDialog() {
|
||||
return
|
||||
}
|
||||
const aux = detailAuxUsage.value
|
||||
patchUsageForm.dosage_bag_count = Number(rx.dosage_bag_count) > 0 ? Number(rx.dosage_bag_count) : 1
|
||||
patchUsageForm.times_per_day =
|
||||
Number(rx.times_per_day) > 0 ? Number(rx.times_per_day) : 3
|
||||
patchUsageForm.usage_days =
|
||||
@@ -1517,20 +1468,16 @@ function openPatchUsageDialog() {
|
||||
patchUsageForm.aux_usage_days =
|
||||
aux && Number(aux.usage_days) > 0 ? Number(aux.usage_days) : 7
|
||||
const md = Number(ord.medication_days)
|
||||
patchUsageForm.aux_dosage_bag_count =
|
||||
aux && Number(aux.dosage_bag_count) > 0 ? Number(aux.dosage_bag_count) : 1
|
||||
patchUsageForm.medication_days = md > 0 ? md : Number(rx.usage_days) > 0 ? Number(rx.usage_days) : 7
|
||||
patchUsageVisible.value = true
|
||||
nextTick(() => patchUsageFormRef.value?.clearValidate())
|
||||
}
|
||||
|
||||
function resetPatchUsageForm() {
|
||||
patchUsageForm.dosage_bag_count = 1
|
||||
patchUsageForm.times_per_day = 3
|
||||
patchUsageForm.usage_days = 7
|
||||
patchUsageForm.aux_times_per_day = 3
|
||||
patchUsageForm.aux_usage_days = 7
|
||||
patchUsageForm.aux_dosage_bag_count = 1
|
||||
patchUsageForm.medication_days = undefined
|
||||
}
|
||||
|
||||
@@ -1551,25 +1498,17 @@ async function submitPatchUsage() {
|
||||
times_per_day: number
|
||||
usage_days: number
|
||||
medication_days: number
|
||||
dosage_bag_count?: number
|
||||
aux_times_per_day?: number
|
||||
aux_usage_days?: number
|
||||
aux_dosage_bag_count?: number
|
||||
} = {
|
||||
id: ordId,
|
||||
times_per_day: Number(patchUsageForm.times_per_day),
|
||||
usage_days: Number(patchUsageForm.usage_days),
|
||||
medication_days: Number(patchUsageForm.medication_days)
|
||||
}
|
||||
if (detailPrescription.value?.prescription_type === '浓缩水丸') {
|
||||
payload.dosage_bag_count = Number(patchUsageForm.dosage_bag_count)
|
||||
}
|
||||
if (detailHasAuxHerbs.value) {
|
||||
payload.aux_times_per_day = Number(patchUsageForm.aux_times_per_day)
|
||||
payload.aux_usage_days = Number(patchUsageForm.aux_usage_days)
|
||||
if (detailPrescription.value?.prescription_type === '浓缩水丸') {
|
||||
payload.aux_dosage_bag_count = Number(patchUsageForm.aux_dosage_bag_count)
|
||||
}
|
||||
}
|
||||
await prescriptionOrderPatchPrescriptionUsage(payload)
|
||||
feedback.msgSuccess('保存成功')
|
||||
@@ -1824,7 +1763,7 @@ async function refresh() {
|
||||
detailLogisticsExpress.value = String(d.express_company || 'auto') || 'auto'
|
||||
void fetchLogisticsTrace()
|
||||
}
|
||||
if (props.loadRelatedData) await fetchLogs(id)
|
||||
if (props.loadRelatedData) void fetchLogs(id)
|
||||
const diagId = d.diagnosis_id
|
||||
if (props.loadRelatedData && diagId) {
|
||||
void loadDetailUnlinkedPayOrders(diagId, id, d.pay_order_ids || [])
|
||||
|
||||
@@ -871,17 +871,8 @@
|
||||
<el-option label="京东快递" value="jd" />
|
||||
<el-option label="极兔速递" value="jt" />
|
||||
</el-select>
|
||||
<el-input
|
||||
v-model="editForm.tracking_number"
|
||||
disabled
|
||||
maxlength="80"
|
||||
placeholder="快递单号"
|
||||
class="flex-1 min-w-0"
|
||||
/>
|
||||
</div>
|
||||
<div class="text-xs text-gray-400 mt-1">
|
||||
编辑订单后需重新审核;双审通过后,请通过列表的单号操作填写或修改
|
||||
</div>
|
||||
<el-input v-model="editForm.tracking_number" maxlength="80" placeholder="快递单号" class="flex-1 min-w-0" />
|
||||
</div>
|
||||
</el-form-item>
|
||||
</el-col>
|
||||
</el-row>
|
||||
@@ -1076,17 +1067,8 @@
|
||||
<el-option label="京东快递" value="jd" />
|
||||
<el-option label="极兔速递" value="jt" />
|
||||
</el-select>
|
||||
<el-input
|
||||
v-model="editForm.tracking_number"
|
||||
disabled
|
||||
maxlength="80"
|
||||
placeholder="快递单号"
|
||||
class="flex-1 min-w-0"
|
||||
/>
|
||||
</div>
|
||||
<div class="text-xs text-gray-400 mt-1">
|
||||
编辑订单后需重新审核;双审通过后,请通过列表的单号操作填写或修改
|
||||
</div>
|
||||
<el-input v-model="editForm.tracking_number" maxlength="80" placeholder="快递单号" class="flex-1 min-w-0" />
|
||||
</div>
|
||||
</el-form-item>
|
||||
</el-col>
|
||||
<el-col :span="24">
|
||||
@@ -2993,13 +2975,9 @@ function canWithdrawRow(row: { fulfillment_status?: number }) {
|
||||
return Number(row.fulfillment_status) === 1
|
||||
}
|
||||
|
||||
function canShipRow(row: {
|
||||
fulfillment_status?: number
|
||||
prescription_audit_status?: number
|
||||
payment_slip_audit_status?: number
|
||||
}) {
|
||||
// 履约中(2) 且处方、支付单均审核通过才可发货
|
||||
return Number(row.fulfillment_status) === 2 && isDualAuditPassed(row)
|
||||
function canShipRow(row: { fulfillment_status?: number }) {
|
||||
// 履约中(2) 可发货
|
||||
return Number(row.fulfillment_status) === 2
|
||||
}
|
||||
|
||||
type ShipMode = 'gancao' | 'direct'
|
||||
@@ -3095,11 +3073,8 @@ function canRefundRow(row: { fulfillment_status?: number; payment_slip_audit_sta
|
||||
return (fs === 5 || fs === 6 || fs === 3 || fs === 9) && Number(row.payment_slip_audit_status) === 1
|
||||
}
|
||||
|
||||
function canQuickTrackRow(row: {
|
||||
prescription_audit_status?: number
|
||||
payment_slip_audit_status?: number
|
||||
}) {
|
||||
return isDualAuditPassed(row)
|
||||
function canQuickTrackRow(_row: { fulfillment_status?: number }) {
|
||||
return true
|
||||
}
|
||||
|
||||
function canUploadPharmacyRow(row: {
|
||||
@@ -3295,7 +3270,7 @@ const editSaving = ref(false)
|
||||
/** 编辑订单分步:0 收货 / 1 服务与支付单 / 2 金额与确认(与处方列表「创建业务订单」一致) */
|
||||
const editOrderStep = ref(0)
|
||||
/** 顶部「关联处方」卡片数据(来自业务订单详情中的 prescription) */
|
||||
const editOrderPrescription = ref<Record<string, any> | null>(null)
|
||||
const editOrderPrescription = ref<Record<string, any> | null>(null)
|
||||
/** 甘草 SCM 已提交:弹窗仅展示并提交快递单号与承运商 */
|
||||
const editGancaoLogisticsOnlyMode = ref(false)
|
||||
/** 用于提示文案展示甘草处方单号 */
|
||||
@@ -3480,7 +3455,7 @@ const editRules = computed<FormRules>(() => {
|
||||
return rules
|
||||
})
|
||||
|
||||
function resetEditOrderDialog() {
|
||||
function resetEditOrderDialog() {
|
||||
editOrderStep.value = 0
|
||||
editOrderPrescription.value = null
|
||||
editGancaoLogisticsOnlyMode.value = false
|
||||
@@ -3532,8 +3507,8 @@ async function openEdit(row: {
|
||||
}
|
||||
editOrderStep.value = 0
|
||||
editOrderPrescription.value = null
|
||||
editVisible.value = true
|
||||
editDialogLoading.value = true
|
||||
editVisible.value = true
|
||||
editDialogLoading.value = true
|
||||
try {
|
||||
const res: any = await prescriptionOrderDetail({ id: row.id })
|
||||
const d = res?.data ?? res
|
||||
@@ -3556,7 +3531,7 @@ async function openEdit(row: {
|
||||
editOrderPrescription.value = null
|
||||
}
|
||||
|
||||
editForm.id = d.id
|
||||
editForm.id = d.id
|
||||
editForm.prescription_id = Number(d.prescription_id) || 0
|
||||
editForm.diagnosis_id = Number(d.diagnosis_id) || 0
|
||||
editForm.assistant_id = Number(d.assistant_id) || 0
|
||||
@@ -3652,6 +3627,7 @@ async function submitEdit() {
|
||||
service_channel: editForm.service_channel || '',
|
||||
service_package: Array.isArray(editForm.service_package) ? editForm.service_package.join(',') : '',
|
||||
express_company: editForm.express_company || 'auto',
|
||||
tracking_number: editForm.tracking_number || '',
|
||||
fee_type: editForm.fee_type,
|
||||
amount: editForm.amount,
|
||||
remark_extra: editForm.remark_extra || '',
|
||||
@@ -3939,17 +3915,7 @@ const quickTrackForm = reactive({
|
||||
tracking_number: ''
|
||||
})
|
||||
|
||||
function openQuickTrack(row: {
|
||||
id: number
|
||||
express_company?: unknown
|
||||
tracking_number?: unknown
|
||||
prescription_audit_status?: number
|
||||
payment_slip_audit_status?: number
|
||||
}) {
|
||||
if (!canQuickTrackRow(row)) {
|
||||
feedback.msgWarning('处方审核和支付单审核均通过后,才可填写或修改快递单号')
|
||||
return
|
||||
}
|
||||
function openQuickTrack(row: { id: number; express_company?: unknown; tracking_number?: unknown }) {
|
||||
quickTrackRowId.value = row.id
|
||||
quickTrackForm.express_company = String(row.express_company || 'auto') || 'auto'
|
||||
quickTrackForm.tracking_number = String(row.tracking_number || '')
|
||||
@@ -3997,19 +3963,7 @@ function resolveShipModeForRow(row: { id: number; ship_mode?: unknown }) {
|
||||
return normalizeShipMode(row.ship_mode)
|
||||
}
|
||||
|
||||
function openShip(row: {
|
||||
id: number
|
||||
express_company?: unknown
|
||||
tracking_number?: unknown
|
||||
ship_mode?: unknown
|
||||
fulfillment_status?: number
|
||||
prescription_audit_status?: number
|
||||
payment_slip_audit_status?: number
|
||||
}) {
|
||||
if (!canShipRow(row)) {
|
||||
feedback.msgWarning('仅处方审核和支付单审核均通过的履约中订单可填写单号并发货')
|
||||
return
|
||||
}
|
||||
function openShip(row: { id: number; express_company?: unknown; tracking_number?: unknown; ship_mode?: unknown }) {
|
||||
shipRowId.value = Number(row.id)
|
||||
shipForm.ship_mode = resolveShipModeForRow(row)
|
||||
shipForm.express_company = String(row.express_company || 'auto') || 'auto'
|
||||
|
||||
@@ -883,17 +883,6 @@
|
||||
{{ detailPrescription.dosage_amount }}{{ detailPrescription.dosage_unit || 'g' }}
|
||||
<template v-if="detailPrescription.prescription_type === '浓缩水丸'">
|
||||
· {{ Number(detailPrescription.dosage_bag_count) > 0 ? Number(detailPrescription.dosage_bag_count) : 1 }}袋
|
||||
<el-button
|
||||
v-if="detailData.prescription_id && !String(detailData.prescription_detail_error || '').trim()"
|
||||
v-perms="['tcm.prescriptionOrder/patchPrescriptionUsage']"
|
||||
type="primary"
|
||||
size="small"
|
||||
link
|
||||
class="ml-2"
|
||||
@click="openPatchUsageDialog"
|
||||
>
|
||||
修改
|
||||
</el-button>
|
||||
</template>
|
||||
<span v-if="detailPrescription.prescription_type === '饮片' && detailPrescription.need_decoction !== null" class="ml-2 text-gray-500">
|
||||
({{ detailPrescription.need_decoction ? '代煎' : '不代煎' }})
|
||||
@@ -907,17 +896,6 @@
|
||||
{{ detailAuxUsage.dosage_amount }}{{ detailPrescription.dosage_unit || 'g' }}
|
||||
<template v-if="detailPrescription.prescription_type === '浓缩水丸'">
|
||||
· {{ Number(detailAuxUsage.dosage_bag_count) > 0 ? Number(detailAuxUsage.dosage_bag_count) : 1 }}袋
|
||||
<el-button
|
||||
v-if="detailData.prescription_id && !String(detailData.prescription_detail_error || '').trim()"
|
||||
v-perms="['tcm.prescriptionOrder/patchPrescriptionUsage']"
|
||||
type="primary"
|
||||
size="small"
|
||||
link
|
||||
class="ml-2"
|
||||
@click="openPatchUsageDialog"
|
||||
>
|
||||
修改
|
||||
</el-button>
|
||||
</template>
|
||||
<span v-if="detailPrescription.prescription_type === '饮片'" class="ml-2 text-gray-500">
|
||||
({{ detailAuxUsage.need_decoction ? '代煎' : '不代煎' }})
|
||||
@@ -1646,17 +1624,8 @@
|
||||
<el-option label="京东快递" value="jd" />
|
||||
<el-option label="极兔速递" value="jt" />
|
||||
</el-select>
|
||||
<el-input
|
||||
v-model="editForm.tracking_number"
|
||||
disabled
|
||||
maxlength="80"
|
||||
placeholder="快递单号"
|
||||
class="flex-1 min-w-0"
|
||||
/>
|
||||
</div>
|
||||
<div class="text-xs text-gray-400 mt-1">
|
||||
编辑订单后需重新审核;双审通过后,请通过列表的单号操作填写或修改
|
||||
</div>
|
||||
<el-input v-model="editForm.tracking_number" maxlength="80" placeholder="快递单号" class="flex-1 min-w-0" />
|
||||
</div>
|
||||
</el-form-item>
|
||||
</el-col>
|
||||
<el-col :span="24">
|
||||
@@ -2283,15 +2252,6 @@
|
||||
label-width="96px"
|
||||
>
|
||||
<div v-if="detailHasAuxHerbs" class="text-xs font-medium text-gray-500 mb-3">主方</div>
|
||||
<el-form-item
|
||||
v-if="detailPrescription?.prescription_type === '浓缩水丸'"
|
||||
label="每次袋数"
|
||||
prop="dosage_bag_count"
|
||||
>
|
||||
<el-select v-model="patchUsageForm.dosage_bag_count" class="w-full">
|
||||
<el-option v-for="count in 5" :key="count" :label="`${count}袋`" :value="count" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="每天次数" prop="times_per_day">
|
||||
<el-input-number
|
||||
v-model="patchUsageForm.times_per_day"
|
||||
@@ -2317,15 +2277,6 @@
|
||||
</el-form-item>
|
||||
<template v-if="detailHasAuxHerbs">
|
||||
<div class="text-xs font-medium text-gray-500 mb-3 mt-2 pt-2 border-t border-gray-100">辅方</div>
|
||||
<el-form-item
|
||||
v-if="detailPrescription?.prescription_type === '浓缩水丸'"
|
||||
label="每次袋数"
|
||||
prop="aux_dosage_bag_count"
|
||||
>
|
||||
<el-select v-model="patchUsageForm.aux_dosage_bag_count" class="w-full">
|
||||
<el-option v-for="count in 5" :key="count" :label="`${count}袋`" :value="count" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="每天次数" prop="aux_times_per_day">
|
||||
<el-input-number
|
||||
v-model="patchUsageForm.aux_times_per_day"
|
||||
@@ -3471,13 +3422,9 @@ function canWithdrawRow(row: { fulfillment_status?: number }) {
|
||||
return Number(row.fulfillment_status) === 1
|
||||
}
|
||||
|
||||
function canShipRow(row: {
|
||||
fulfillment_status?: number
|
||||
prescription_audit_status?: number
|
||||
payment_slip_audit_status?: number
|
||||
}) {
|
||||
// 履约中(2) 且处方、支付单均审核通过才可发货
|
||||
return Number(row.fulfillment_status) === 2 && isDualAuditPassed(row)
|
||||
function canShipRow(row: { fulfillment_status?: number }) {
|
||||
// 履约中(2) 可发货
|
||||
return Number(row.fulfillment_status) === 2
|
||||
}
|
||||
|
||||
function canAddPayOrderRow(row: { fulfillment_status?: number }) {
|
||||
@@ -3497,11 +3444,8 @@ function canRefundRow(row: { fulfillment_status?: number; payment_slip_audit_sta
|
||||
return (fs === 5 || fs === 6 || fs === 3 || fs === 9) && Number(row.payment_slip_audit_status) === 1
|
||||
}
|
||||
|
||||
function canQuickTrackRow(row: {
|
||||
prescription_audit_status?: number
|
||||
payment_slip_audit_status?: number
|
||||
}) {
|
||||
return isDualAuditPassed(row)
|
||||
function canQuickTrackRow(_row: { fulfillment_status?: number }) {
|
||||
return true
|
||||
}
|
||||
|
||||
function canUploadPharmacyRow(row: {
|
||||
@@ -3994,12 +3938,10 @@ const patchUsageVisible = ref(false)
|
||||
const patchUsageSaving = ref(false)
|
||||
const patchUsageFormRef = ref<FormInstance>()
|
||||
const patchUsageForm = reactive({
|
||||
dosage_bag_count: 1 as number | undefined,
|
||||
times_per_day: 3 as number | undefined,
|
||||
usage_days: 7 as number | undefined,
|
||||
aux_times_per_day: 3 as number | undefined,
|
||||
aux_usage_days: 7 as number | undefined,
|
||||
aux_dosage_bag_count: 1 as number | undefined,
|
||||
medication_days: undefined as number | undefined
|
||||
})
|
||||
const patchUsageRules = computed<FormRules>(() => {
|
||||
@@ -4008,15 +3950,9 @@ const patchUsageRules = computed<FormRules>(() => {
|
||||
usage_days: [{ required: true, message: '请填写主方开立天数', trigger: 'change' }],
|
||||
medication_days: [{ required: true, message: '请填写订单服用天数', trigger: 'change' }]
|
||||
}
|
||||
if (detailPrescription.value?.prescription_type === '浓缩水丸') {
|
||||
rules.dosage_bag_count = [{ required: true, message: '请选择主方每次袋数', trigger: 'change' }]
|
||||
}
|
||||
if (detailHasAuxHerbs.value) {
|
||||
rules.aux_times_per_day = [{ required: true, message: '请填写辅方每天次数', trigger: 'change' }]
|
||||
rules.aux_usage_days = [{ required: true, message: '请填写辅方开立天数', trigger: 'change' }]
|
||||
if (detailPrescription.value?.prescription_type === '浓缩水丸') {
|
||||
rules.aux_dosage_bag_count = [{ required: true, message: '请选择辅方每次袋数', trigger: 'change' }]
|
||||
}
|
||||
}
|
||||
return rules
|
||||
})
|
||||
@@ -4029,7 +3965,6 @@ function openPatchUsageDialog() {
|
||||
return
|
||||
}
|
||||
const aux = detailAuxUsage.value
|
||||
patchUsageForm.dosage_bag_count = Number(rx.dosage_bag_count) > 0 ? Number(rx.dosage_bag_count) : 1
|
||||
patchUsageForm.times_per_day =
|
||||
Number(rx.times_per_day) > 0 ? Number(rx.times_per_day) : 3
|
||||
patchUsageForm.usage_days =
|
||||
@@ -4039,20 +3974,16 @@ function openPatchUsageDialog() {
|
||||
patchUsageForm.aux_usage_days =
|
||||
aux && Number(aux.usage_days) > 0 ? Number(aux.usage_days) : 7
|
||||
const md = Number(ord.medication_days)
|
||||
patchUsageForm.aux_dosage_bag_count =
|
||||
aux && Number(aux.dosage_bag_count) > 0 ? Number(aux.dosage_bag_count) : 1
|
||||
patchUsageForm.medication_days = md > 0 ? md : Number(rx.usage_days) > 0 ? Number(rx.usage_days) : 7
|
||||
patchUsageVisible.value = true
|
||||
nextTick(() => patchUsageFormRef.value?.clearValidate())
|
||||
}
|
||||
|
||||
function resetPatchUsageForm() {
|
||||
patchUsageForm.dosage_bag_count = 1
|
||||
patchUsageForm.times_per_day = 3
|
||||
patchUsageForm.usage_days = 7
|
||||
patchUsageForm.aux_times_per_day = 3
|
||||
patchUsageForm.aux_usage_days = 7
|
||||
patchUsageForm.aux_dosage_bag_count = 1
|
||||
patchUsageForm.medication_days = undefined
|
||||
}
|
||||
|
||||
@@ -4073,25 +4004,17 @@ async function submitPatchUsage() {
|
||||
times_per_day: number
|
||||
usage_days: number
|
||||
medication_days: number
|
||||
dosage_bag_count?: number
|
||||
aux_times_per_day?: number
|
||||
aux_usage_days?: number
|
||||
aux_dosage_bag_count?: number
|
||||
} = {
|
||||
id: ordId,
|
||||
times_per_day: Number(patchUsageForm.times_per_day),
|
||||
usage_days: Number(patchUsageForm.usage_days),
|
||||
medication_days: Number(patchUsageForm.medication_days)
|
||||
}
|
||||
if (detailPrescription.value?.prescription_type === '浓缩水丸') {
|
||||
payload.dosage_bag_count = Number(patchUsageForm.dosage_bag_count)
|
||||
}
|
||||
if (detailHasAuxHerbs.value) {
|
||||
payload.aux_times_per_day = Number(patchUsageForm.aux_times_per_day)
|
||||
payload.aux_usage_days = Number(patchUsageForm.aux_usage_days)
|
||||
if (detailPrescription.value?.prescription_type === '浓缩水丸') {
|
||||
payload.aux_dosage_bag_count = Number(patchUsageForm.aux_dosage_bag_count)
|
||||
}
|
||||
}
|
||||
await prescriptionOrderPatchPrescriptionUsage(payload)
|
||||
feedback.msgSuccess('保存成功')
|
||||
@@ -4258,7 +4181,7 @@ const editSaving = ref(false)
|
||||
/** 编辑订单分步:0 收货 / 1 服务与支付单 / 2 金额与确认(与处方列表「创建业务订单」一致) */
|
||||
const editOrderStep = ref(0)
|
||||
/** 顶部「关联处方」卡片数据(来自业务订单详情中的 prescription) */
|
||||
const editOrderPrescription = ref<Record<string, any> | null>(null)
|
||||
const editOrderPrescription = ref<Record<string, any> | null>(null)
|
||||
|
||||
const editOrderStepLead = computed(() => {
|
||||
const texts = [
|
||||
@@ -4458,7 +4381,7 @@ const editRules = computed<FormRules>(() => {
|
||||
return rules
|
||||
})
|
||||
|
||||
function resetEditOrderDialog() {
|
||||
function resetEditOrderDialog() {
|
||||
editOrderStep.value = 0
|
||||
editOrderPrescription.value = null
|
||||
editFormRef.value?.clearValidate()
|
||||
@@ -4508,8 +4431,8 @@ async function openEdit(row: {
|
||||
}
|
||||
editOrderStep.value = 0
|
||||
editOrderPrescription.value = null
|
||||
editVisible.value = true
|
||||
editDialogLoading.value = true
|
||||
editVisible.value = true
|
||||
editDialogLoading.value = true
|
||||
try {
|
||||
const res: any = await prescriptionOrderDetail({ id: row.id })
|
||||
const d = res?.data ?? res
|
||||
@@ -4532,7 +4455,7 @@ async function openEdit(row: {
|
||||
editOrderPrescription.value = null
|
||||
}
|
||||
|
||||
editForm.id = d.id
|
||||
editForm.id = d.id
|
||||
editForm.prescription_id = Number(d.prescription_id) || 0
|
||||
editForm.diagnosis_id = Number(d.diagnosis_id) || 0
|
||||
editForm.assistant_id = Number(d.assistant_id) || 0
|
||||
@@ -4617,6 +4540,7 @@ async function submitEdit() {
|
||||
service_channel: editForm.service_channel || '',
|
||||
service_package: Array.isArray(editForm.service_package) ? editForm.service_package.join(',') : '',
|
||||
express_company: editForm.express_company || 'auto',
|
||||
tracking_number: editForm.tracking_number || '',
|
||||
fee_type: editForm.fee_type,
|
||||
amount: editForm.amount,
|
||||
remark_extra: editForm.remark_extra || '',
|
||||
@@ -4864,17 +4788,7 @@ const quickTrackForm = reactive({
|
||||
tracking_number: ''
|
||||
})
|
||||
|
||||
function openQuickTrack(row: {
|
||||
id: number
|
||||
express_company?: unknown
|
||||
tracking_number?: unknown
|
||||
prescription_audit_status?: number
|
||||
payment_slip_audit_status?: number
|
||||
}) {
|
||||
if (!canQuickTrackRow(row)) {
|
||||
feedback.msgWarning('处方审核和支付单审核均通过后,才可填写或修改快递单号')
|
||||
return
|
||||
}
|
||||
function openQuickTrack(row: { id: number; express_company?: unknown; tracking_number?: unknown }) {
|
||||
quickTrackRowId.value = row.id
|
||||
quickTrackForm.express_company = String(row.express_company || 'auto') || 'auto'
|
||||
quickTrackForm.tracking_number = String(row.tracking_number || '')
|
||||
@@ -4926,19 +4840,7 @@ const shipDialogModeDisplay = computed(() =>
|
||||
shipForm.ship_mode === 'direct' ? '洛阳药房直发' : '甘草药房直发'
|
||||
)
|
||||
|
||||
function openShip(row: {
|
||||
id: number
|
||||
express_company?: unknown
|
||||
tracking_number?: unknown
|
||||
ship_mode?: unknown
|
||||
fulfillment_status?: number
|
||||
prescription_audit_status?: number
|
||||
payment_slip_audit_status?: number
|
||||
}) {
|
||||
if (!canShipRow(row)) {
|
||||
feedback.msgWarning('仅处方审核和支付单审核均通过的履约中订单可填写单号并发货')
|
||||
return
|
||||
}
|
||||
function openShip(row: { id: number; express_company?: unknown; tracking_number?: unknown; ship_mode?: unknown }) {
|
||||
shipRowId.value = row.id
|
||||
shipForm.ship_mode = String(row.ship_mode || 'gancao') || 'gancao'
|
||||
shipForm.express_company = String(row.express_company || 'auto') || 'auto'
|
||||
|
||||
@@ -154,7 +154,7 @@
|
||||
<div class="panel-heading panel-heading--table">
|
||||
<div>
|
||||
<h2>明细数据列表</h2>
|
||||
<p>展开部门可查看人员明细;加粉=总进线=区间新增“员工+客户”组合(同一员工的同一客户只计一次,同一客户进入不同员工分别计数;包含区间内添加后已删客户,剔除继承客户、扫一扫/搜手机号/名片分享添加及区间前已存在的相同组合)<template v-if="canViewDeletedFans">,(-N)表示加粉组合中已删除</template>;开口=获客客户首次发起会话事件,按开口时间计入,同一员工的同一客户只计一次;挂号=已支付且实收低于 10 元的订单,预约=有效预约记录;开口率=开口/加粉,挂号率=挂号/加粉,面诊率=面诊/挂号(看挂号后流失),预约率=面诊/预约(看预约后未面诊),面诊接诊率=接诊诊单/面诊,接诊率=接诊诊单/总进线</p>
|
||||
<p>展开部门可查看人员明细;加粉=总进线=区间新增“员工+客户”组合(同一员工的同一客户只计一次,同一客户进入不同员工分别计数;包含区间内添加后已删客户,剔除继承客户、扫一扫/搜手机号/名片分享添加及区间前已存在的相同组合)<template v-if="canViewDeletedFans">,(-N)表示加粉组合中已删除</template>;挂号=已支付且实收低于 10 元的订单,预约=有效预约记录;开口率=开口/加粉,挂号率=挂号/加粉,面诊率=面诊/挂号(看挂号后流失),预约率=面诊/预约(看预约后未面诊),面诊接诊率=接诊诊单/面诊,接诊率=接诊诊单/总进线</p>
|
||||
</div>
|
||||
<span>{{ dashboard.rows.length }} 个顶层节点</span>
|
||||
</div>
|
||||
@@ -449,7 +449,7 @@ const timeOptions = [
|
||||
]
|
||||
const metricCards: Array<{ key: string; label: string; type: MetricType; hint: string }> = [
|
||||
{ key: 'add_fans_count', label: '加粉数', type: 'count', hint: '区间新增员工+客户组合(不同员工分别计数,含已删除)' },
|
||||
{ key: 'total_open_count', label: '开口数', type: 'count', hint: '获客客户首次发起会话;按开口时间统计,同一员工的同一客户只计一次' },
|
||||
{ key: 'total_open_count', label: '开口数', type: 'count', hint: '来源于个人业绩录入' },
|
||||
{ key: 'interview_count', label: '面诊', type: 'count', hint: '已完成预约' },
|
||||
{ key: 'completed_order_count', label: '接诊诊单', type: 'count', hint: '业务订单,按创建人归属并过滤无效单' },
|
||||
{ key: 'completed_order_amount', label: '诊单金额', type: 'money', hint: '排除取消、拒收、退款及已退款订单' },
|
||||
|
||||
@@ -144,17 +144,6 @@
|
||||
>
|
||||
<el-table-column type="selection" width="48" />
|
||||
<el-table-column label="订单号" prop="order_no" min-width="150" />
|
||||
|
||||
<el-table-column label="处方业务订单号" min-width="210">
|
||||
<template #default="{ row }">
|
||||
<div v-if="row.prescription_orders?.length" class="flex flex-col gap-1">
|
||||
<span v-for="order in row.prescription_orders" :key="order.id" class="break-all">
|
||||
{{ order.order_no }}
|
||||
</span>
|
||||
</div>
|
||||
<span v-else class="text-gray-400">未关联</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
|
||||
<el-table-column label="患者信息" min-width="150">
|
||||
<template #default="{ row }">
|
||||
@@ -313,14 +302,6 @@
|
||||
<el-tag :type="getStatusTag(detailData.status)">
|
||||
{{ getStatusText(detailData.status) }}
|
||||
</el-tag>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="处方业务订单号" :span="2">
|
||||
<div v-if="detailData.prescription_orders?.length" class="flex flex-col gap-1">
|
||||
<span v-for="order in detailData.prescription_orders" :key="order.id" class="break-all">
|
||||
{{ order.order_no }}
|
||||
</span>
|
||||
</div>
|
||||
<span v-else class="text-gray-400">未关联</span>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="患者姓名">
|
||||
{{ detailData.patient?.patient_name || '待关联' }}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
<template>
|
||||
<div class="reception-page">
|
||||
<DoctorWebConsultationNotice />
|
||||
<!-- 页头 -->
|
||||
<div class="reception-header">
|
||||
<div class="header-left">
|
||||
@@ -84,18 +83,10 @@
|
||||
<el-icon v-else><ChatDotRound /></el-icon>
|
||||
</button>
|
||||
</el-tooltip>
|
||||
<el-tooltip :content="webConsultationBlocked ? webConsultationMessage : '发起通话'" placement="top">
|
||||
<span class="row-call-action">
|
||||
<button
|
||||
class="row-icon-btn call"
|
||||
:disabled="webConsultationBlocked"
|
||||
:aria-label="webConsultationBlocked ? webConsultationMessage : '发起通话'"
|
||||
@click="handleCall(row)"
|
||||
>
|
||||
<el-icon><Phone /></el-icon>
|
||||
<span v-if="webConsultationBlocked">已停用</span>
|
||||
</button>
|
||||
</span>
|
||||
<el-tooltip content="发起通话" placement="top">
|
||||
<button class="row-icon-btn call" @click="handleCall(row)">
|
||||
<el-icon><Phone /></el-icon>
|
||||
</button>
|
||||
</el-tooltip>
|
||||
</div>
|
||||
</div>
|
||||
@@ -198,8 +189,6 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { defineAsyncComponent, onMounted, onUnmounted } from 'vue'
|
||||
import DoctorWebConsultationNotice from '@/components/doctor-web-consultation-notice/index.vue'
|
||||
import { useDoctorWebConsultation } from '@/hooks/useDoctorWebConsultation'
|
||||
import { receptionQueue, receptionDetail, notifyAssistant, addDoctorNote } from '@/api/patient'
|
||||
import NoteTimeline from './components/NoteTimeline.vue'
|
||||
import PatientInfoCard from '@/views/tcm/diagnosis/components/PatientInfoCard.vue'
|
||||
@@ -222,7 +211,6 @@ const DiagnosisEdit = defineAsyncComponent(() => import('@/views/tcm/diagnosis/e
|
||||
|
||||
const POLL_MS = 5_000
|
||||
const PAGE_SIZE = 15
|
||||
const { webConsultationBlocked, webConsultationMessage, ensureWebConsultationAllowed } = useDoctorWebConsultation()
|
||||
|
||||
interface QueueRow {
|
||||
id: number
|
||||
@@ -450,7 +438,6 @@ const handleSearch = async () => {
|
||||
}
|
||||
|
||||
const handleCall = async (row: QueueRow) => {
|
||||
if (!ensureWebConsultationAllowed()) return
|
||||
const sourcePatientId = Number(row.source_patient_id || 0)
|
||||
const diagnosisId = Number(row.diagnosis_id || 0)
|
||||
if (!sourcePatientId) {
|
||||
@@ -467,7 +454,6 @@ const handleCall = async (row: QueueRow) => {
|
||||
appointment_id: Number(row.id),
|
||||
diagnosis_id: diagnosisId
|
||||
})
|
||||
if (!ensureWebConsultationAllowed()) return
|
||||
chatDialogRef.value?.open({
|
||||
patientId: sourcePatientId,
|
||||
patientName: row.patient_name,
|
||||
@@ -1018,25 +1004,16 @@ onUnmounted(() => {
|
||||
font-size: 15px;
|
||||
padding: 0;
|
||||
}
|
||||
.row-call-action {
|
||||
display: inline-flex;
|
||||
}
|
||||
.row-icon-btn.call:disabled {
|
||||
width: auto;
|
||||
gap: 4px;
|
||||
padding: 0 6px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.row-icon-btn:hover:not(:disabled) {
|
||||
.row-icon-btn:hover {
|
||||
background: var(--rx-accent-soft);
|
||||
color: var(--rx-accent-strong);
|
||||
border-color: var(--rx-accent);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
.row-icon-btn:active:not(:disabled) {
|
||||
.row-icon-btn:active {
|
||||
transform: scale(0.92);
|
||||
}
|
||||
.row-icon-btn.notify:hover:not(:disabled) {
|
||||
.row-icon-btn.notify:hover {
|
||||
background: #fff7e6;
|
||||
color: var(--rx-warning);
|
||||
border-color: var(--rx-warning);
|
||||
|
||||
@@ -1,227 +0,0 @@
|
||||
<template>
|
||||
<div class="prescription-ai-visibility">
|
||||
<el-card v-loading="loading" shadow="never" class="!border-none">
|
||||
<div class="text-xl font-medium mb-[20px]">处方 AI 一致度可见范围</div>
|
||||
<el-alert type="info" :closable="false" show-icon class="mb-5">
|
||||
<template #title>指定用户组或用户可查看一致度</template>
|
||||
<div class="leading-6">
|
||||
用户命中任一指定系统角色,或被单独指定,即可查看桌面端“与 AI
|
||||
一致度”、逐味对照和一致度统计。AI
|
||||
报告继续按原有权限开放,已有报告不受影响,患者与处方的数据范围保持原有规则。
|
||||
</div>
|
||||
</el-alert>
|
||||
|
||||
<el-alert
|
||||
v-if="loadError"
|
||||
:title="loadError"
|
||||
type="error"
|
||||
:closable="false"
|
||||
show-icon
|
||||
class="mb-5"
|
||||
/>
|
||||
<div v-if="loading" role="status" class="mb-5">正在读取当前可见范围…</div>
|
||||
|
||||
<el-form
|
||||
v-if="hasLoaded"
|
||||
class="ls-form"
|
||||
:model="formData"
|
||||
:disabled="!ready || loading || saving"
|
||||
label-width="140px"
|
||||
>
|
||||
<el-form-item label="指定用户组" prop="role_ids">
|
||||
<div class="w-full max-w-[640px]">
|
||||
<el-select
|
||||
v-model="formData.role_ids"
|
||||
class="w-full"
|
||||
multiple
|
||||
filterable
|
||||
clearable
|
||||
placeholder="请选择系统角色,可搜索角色名称"
|
||||
>
|
||||
<el-option
|
||||
v-for="role in roleOptions"
|
||||
:key="role.id"
|
||||
:label="role.name"
|
||||
:value="role.id"
|
||||
/>
|
||||
</el-select>
|
||||
<div class="form-tips">账号拥有任一指定角色即可命中。</div>
|
||||
</div>
|
||||
</el-form-item>
|
||||
<el-form-item label="指定用户" prop="admin_ids">
|
||||
<div class="w-full max-w-[640px]">
|
||||
<el-select
|
||||
v-model="formData.admin_ids"
|
||||
class="w-full"
|
||||
multiple
|
||||
filterable
|
||||
clearable
|
||||
placeholder="请选择用户,可搜索姓名或账号"
|
||||
>
|
||||
<el-option
|
||||
v-for="admin in adminOptions"
|
||||
:key="admin.id"
|
||||
:label="admin.label"
|
||||
:value="admin.id"
|
||||
/>
|
||||
</el-select>
|
||||
<div class="form-tips">
|
||||
单独指定的用户无需同时命中用户组。当前不在可选列表中的已配置 ID
|
||||
会保留,移除后保存才会取消该项授权。
|
||||
</div>
|
||||
</div>
|
||||
</el-form-item>
|
||||
<el-form-item label="生效规则">
|
||||
<div>
|
||||
<div class="leading-6">指定用户组与指定用户按“或”生效。</div>
|
||||
<div class="form-tips">
|
||||
两项均为空时,所有账号(包括超级管理员)均隐藏一致度、对照与统计。
|
||||
拥有本页管理权限不自动获得一致度查看权,超级管理员也需命中上述名单。
|
||||
</div>
|
||||
</div>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
|
||||
<el-alert
|
||||
v-if="ready && !formData.role_ids.length && !formData.admin_ids.length"
|
||||
title="当前选择为空:保存后所有账号将隐藏一致度、对照与统计,AI 报告仍保留。"
|
||||
type="warning"
|
||||
:closable="false"
|
||||
show-icon
|
||||
class="mb-5"
|
||||
/>
|
||||
<el-alert
|
||||
v-if="saveError"
|
||||
:title="saveError"
|
||||
type="error"
|
||||
:closable="false"
|
||||
show-icon
|
||||
class="mb-5"
|
||||
/>
|
||||
<el-button :disabled="loading || saving" @click="loadConfig">
|
||||
{{ loadError ? '重试加载' : '重新加载' }}
|
||||
</el-button>
|
||||
</el-card>
|
||||
|
||||
<footer-btns v-if="canManage">
|
||||
<el-button
|
||||
type="primary"
|
||||
:loading="saving"
|
||||
:disabled="!ready || loading || saving"
|
||||
@click="handleSubmit"
|
||||
>
|
||||
{{ saving ? '正在保存' : '保存' }}
|
||||
</el-button>
|
||||
</footer-btns>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts" name="prescriptionAiVisibility">
|
||||
import { computed, reactive, ref } from 'vue'
|
||||
|
||||
import type {
|
||||
PrescriptionAiVisibilityConfig,
|
||||
PrescriptionAiVisibilityOptions
|
||||
} from '@/api/setting/prescription_ai_visibility'
|
||||
import {
|
||||
getPrescriptionAiCapabilities,
|
||||
getPrescriptionAiVisibilityConfig,
|
||||
getPrescriptionAiVisibilityOptions,
|
||||
setPrescriptionAiVisibilityConfig
|
||||
} from '@/api/setting/prescription_ai_visibility'
|
||||
import feedback from '@/utils/feedback'
|
||||
|
||||
const loading = ref(false)
|
||||
const saving = ref(false)
|
||||
const ready = ref(false)
|
||||
const hasLoaded = ref(false)
|
||||
const canManage = ref(false)
|
||||
const loadError = ref('')
|
||||
const saveError = ref('')
|
||||
const formData = reactive<PrescriptionAiVisibilityConfig>({ role_ids: [], admin_ids: [] })
|
||||
const optionsData = reactive<PrescriptionAiVisibilityOptions>({ roles: [], admins: [] })
|
||||
|
||||
const roleOptions = computed(() => {
|
||||
const options = new Map(optionsData.roles.map((role) => [role.id, role]))
|
||||
for (const id of formData.role_ids) {
|
||||
if (!options.has(id)) {
|
||||
options.set(id, { id, name: `已配置角色 #${id}(当前不在可选列表)` })
|
||||
}
|
||||
}
|
||||
return [...options.values()]
|
||||
})
|
||||
|
||||
const adminOptions = computed(() => {
|
||||
const options = new Map(
|
||||
optionsData.admins.map((admin) => [
|
||||
admin.id,
|
||||
{ id: admin.id, label: `${admin.name || `用户 #${admin.id}`}(${admin.account})` }
|
||||
])
|
||||
)
|
||||
for (const id of formData.admin_ids) {
|
||||
if (!options.has(id)) {
|
||||
options.set(id, { id, label: `已配置用户 #${id}(当前不在可选列表)` })
|
||||
}
|
||||
}
|
||||
return [...options.values()]
|
||||
})
|
||||
|
||||
const assignConfig = (config: PrescriptionAiVisibilityConfig) => {
|
||||
formData.role_ids = [...config.role_ids]
|
||||
formData.admin_ids = [...config.admin_ids]
|
||||
}
|
||||
|
||||
const loadConfig = async () => {
|
||||
if (loading.value || saving.value) return
|
||||
loading.value = true
|
||||
ready.value = false
|
||||
canManage.value = false
|
||||
loadError.value = ''
|
||||
saveError.value = ''
|
||||
try {
|
||||
const capabilities = await getPrescriptionAiCapabilities()
|
||||
if (capabilities.can_manage_visibility !== true) {
|
||||
loadError.value = '当前账号无权管理处方 AI 一致度可见范围。'
|
||||
return
|
||||
}
|
||||
canManage.value = true
|
||||
const [config, options] = await Promise.all([
|
||||
getPrescriptionAiVisibilityConfig(),
|
||||
getPrescriptionAiVisibilityOptions()
|
||||
])
|
||||
if (!Array.isArray(options?.roles) || !Array.isArray(options?.admins)) {
|
||||
throw new Error('可选用户组或用户响应格式不正确')
|
||||
}
|
||||
// Apply both responses together; an incomplete load cannot overwrite the current policy.
|
||||
assignConfig(config)
|
||||
optionsData.roles = options.roles
|
||||
optionsData.admins = options.admins
|
||||
hasLoaded.value = true
|
||||
ready.value = true
|
||||
} catch {
|
||||
loadError.value = '可见范围加载失败,尚未读取完整配置。请重试加载后再保存。'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!ready.value || !canManage.value || loading.value || saving.value) return
|
||||
saving.value = true
|
||||
saveError.value = ''
|
||||
try {
|
||||
const config = await setPrescriptionAiVisibilityConfig({
|
||||
role_ids: [...formData.role_ids],
|
||||
admin_ids: [...formData.admin_ids]
|
||||
})
|
||||
assignConfig(config)
|
||||
feedback.msgSuccess('可见范围已保存')
|
||||
} catch {
|
||||
saveError.value = '保存结果未确认,当前选择已保留。请重试保存,或重新加载以确认服务端策略。'
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
void loadConfig()
|
||||
</script>
|
||||
@@ -56,70 +56,6 @@
|
||||
/>
|
||||
<el-empty v-else description="暂无数据" />
|
||||
</el-card>
|
||||
|
||||
<!-- 我的复诊接诊率(方案 §10 D1-h):仅本人行,口径与「复诊接诊率」报表一致 -->
|
||||
<el-card v-if="canViewRevisitRate" class="!border-none mt-4" shadow="never">
|
||||
<template #header>
|
||||
<div class="card-header">
|
||||
<div class="card-header-left">
|
||||
<span class="card-title">我的复诊接诊率</span>
|
||||
<el-date-picker
|
||||
v-model="revisitMonth"
|
||||
type="month"
|
||||
value-format="YYYY-MM"
|
||||
placeholder="选择月份"
|
||||
:clearable="false"
|
||||
:disabled-date="disableFutureMonth"
|
||||
size="small"
|
||||
style="width: 130px"
|
||||
@change="fetchRevisitRate"
|
||||
/>
|
||||
</div>
|
||||
<span class="card-hint">{{ revisitMonthText }} · 与「复诊接诊率」报表同口径</span>
|
||||
</div>
|
||||
</template>
|
||||
<div v-loading="revisitLoading" class="revisit-rate-body">
|
||||
<template v-if="revisitRow">
|
||||
<div class="revisit-kpi-grid">
|
||||
<div class="revisit-kpi-card">
|
||||
<div class="stats-kpi-label">新指派数</div>
|
||||
<div class="revisit-kpi-value">
|
||||
{{ Number(revisitRow.assigned_count ?? 0) }}
|
||||
</div>
|
||||
<div class="revisit-kpi-sub">当月新指派给我的患者</div>
|
||||
</div>
|
||||
<div class="revisit-kpi-card">
|
||||
<div class="stats-kpi-label">继承数</div>
|
||||
<div class="revisit-kpi-value">
|
||||
{{ Number(revisitRow.inherit_count ?? 0) }}
|
||||
</div>
|
||||
<div class="revisit-kpi-sub">当月继承给我的患者</div>
|
||||
</div>
|
||||
<div class="revisit-kpi-card is-primary">
|
||||
<div class="stats-kpi-label">复诊合计接诊率</div>
|
||||
<div class="revisit-kpi-value">
|
||||
{{ formatRate(revisitRow.visit_all_rate) }}
|
||||
</div>
|
||||
<div class="revisit-kpi-sub">{{ visitAllFractionText }}</div>
|
||||
</div>
|
||||
<div v-for="slot in revisitSlots" :key="slot" class="revisit-kpi-card">
|
||||
<div class="stats-kpi-label">{{ slotLabel(slot) }}接诊率</div>
|
||||
<div class="revisit-kpi-value">
|
||||
{{ formatRate(slotMetric(slot, 'rate')) }}
|
||||
</div>
|
||||
<div class="revisit-kpi-sub">{{ slotFractionText(slot) }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<el-empty v-else :description="revisitEmptyText" :image-size="72" />
|
||||
<div class="revisit-caliber">
|
||||
口径:N 诊接诊率 = 当月 N 诊成交单数 ÷ N 诊分母(新指派数 + 起算诊次 ≤ N 的继承数),分母为 0 显示「—」;
|
||||
<template v-if="revisitInheritMode === 'exclude'">当前为旧口径,继承患者不计入分母;</template>
|
||||
<template v-else>继承患者按继承时诊次从第 k+1 诊起计入;</template>
|
||||
复诊合计 = 各诊次成交单数之和 ÷ 被指派合计(新指派 ∪ 继承),可超过 100%。
|
||||
</div>
|
||||
</div>
|
||||
</el-card>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -127,12 +63,7 @@
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import vCharts from 'vue-echarts'
|
||||
import {
|
||||
assistantPerformanceOverview,
|
||||
assistantPerformanceRevisitRate,
|
||||
type AssistantRevisitRateResult
|
||||
} from '@/api/stats'
|
||||
import { hasPermission } from '@/utils/perm'
|
||||
import { assistantPerformanceOverview } from '@/api/stats'
|
||||
|
||||
const loading = ref(false)
|
||||
const dateRange = ref<string[]>([])
|
||||
@@ -260,78 +191,8 @@ const handleReset = () => {
|
||||
fetchData()
|
||||
}
|
||||
|
||||
// ── 我的复诊接诊率(方案 §10 D1-h)────────────────────────
|
||||
/** 权限点由 server/sql/1.9.20261012/10_add_assistant_revisit_rate_menu.sql 登记并自动授予已有个人业绩页的角色 */
|
||||
const canViewRevisitRate = hasPermission(['stats.assistantPerformance/revisitRate'])
|
||||
|
||||
const initNow = new Date()
|
||||
const currentMonth = `${initNow.getFullYear()}-${String(initNow.getMonth() + 1).padStart(2, '0')}`
|
||||
const revisitMonth = ref<string>(currentMonth)
|
||||
const revisitLoading = ref(false)
|
||||
const revisitResult = ref<AssistantRevisitRateResult | null>(null)
|
||||
|
||||
const revisitRow = computed(() => revisitResult.value?.row ?? null)
|
||||
const revisitInheritMode = computed(() => revisitResult.value?.inherit_mode ?? 'slot')
|
||||
const revisitSlots = computed(() =>
|
||||
(revisitResult.value?.slots ?? []).map((s) => Number(s)).filter((s) => s >= 2)
|
||||
)
|
||||
const revisitMonthText = computed(() => {
|
||||
const [y, m] = (revisitResult.value?.month || revisitMonth.value).split('-')
|
||||
return y && m ? `${y} 年 ${Number(m)} 月` : revisitMonth.value
|
||||
})
|
||||
/** row=null:非二中心医助(in_scope=false)与「当月无被指派患者」文案区分 */
|
||||
const revisitEmptyText = computed(() => {
|
||||
if (revisitResult.value && revisitResult.value.in_scope === false) {
|
||||
return '暂无数据(仅二中心医助统计)'
|
||||
}
|
||||
return revisitMonth.value === currentMonth ? '本月暂无被指派患者' : '该月暂无被指派患者'
|
||||
})
|
||||
|
||||
const disableFutureMonth = (date: Date) => {
|
||||
const now = new Date()
|
||||
return date.getFullYear() * 12 + date.getMonth() > now.getFullYear() * 12 + now.getMonth()
|
||||
}
|
||||
|
||||
const cnDigits = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十']
|
||||
const slotLabel = (slot: number) => {
|
||||
if (slot >= 2 && slot <= 10) return `${cnDigits[slot]}诊`
|
||||
if (slot > 10 && slot < 20) return `十${cnDigits[slot - 10]}诊`
|
||||
return `${slot}诊`
|
||||
}
|
||||
|
||||
const formatRate = (rate: unknown) =>
|
||||
rate === null || rate === undefined || rate === '' ? '—' : `${Number(rate)}%`
|
||||
|
||||
/** 读取本人行的 visit{N}_count / visit{N}_den / visit{N}_rate */
|
||||
const slotMetric = (slot: number, kind: 'count' | 'den' | 'rate') =>
|
||||
revisitRow.value?.[`visit${slot}_${kind}`]
|
||||
|
||||
/** 「成交 N 单 / 分母 M」 */
|
||||
const fractionText = (count: unknown, den: unknown) =>
|
||||
`成交 ${Number(count ?? 0)} 单 / 分母 ${Number(den ?? 0)}`
|
||||
|
||||
const slotFractionText = (slot: number) =>
|
||||
fractionText(slotMetric(slot, 'count'), slotMetric(slot, 'den'))
|
||||
|
||||
const visitAllFractionText = computed(() =>
|
||||
fractionText(revisitRow.value?.visit_all_count, revisitRow.value?.visit_all_den)
|
||||
)
|
||||
|
||||
const fetchRevisitRate = async () => {
|
||||
if (!canViewRevisitRate) return
|
||||
revisitLoading.value = true
|
||||
try {
|
||||
revisitResult.value = await assistantPerformanceRevisitRate({ month: revisitMonth.value })
|
||||
} catch {
|
||||
// 错误提示由 utils/request 统一弹出;失败时保留上一次结果
|
||||
} finally {
|
||||
revisitLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
fetchData()
|
||||
fetchRevisitRate()
|
||||
})
|
||||
</script>
|
||||
|
||||
@@ -409,57 +270,4 @@ onMounted(() => {
|
||||
.stats-chart {
|
||||
height: 360px;
|
||||
}
|
||||
|
||||
.card-header-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.revisit-rate-body {
|
||||
min-height: 120px;
|
||||
}
|
||||
|
||||
.revisit-kpi-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.revisit-kpi-card {
|
||||
background: linear-gradient(145deg, #ffffff, #f7f9ff);
|
||||
border: 1px solid #ebf1ff;
|
||||
border-radius: 12px;
|
||||
padding: 14px 16px;
|
||||
}
|
||||
|
||||
.revisit-kpi-card.is-primary {
|
||||
background: linear-gradient(145deg, #ffffff, #eef3ff);
|
||||
border-color: #d9e4ff;
|
||||
}
|
||||
|
||||
.revisit-kpi-value {
|
||||
margin-top: 8px;
|
||||
font-size: 24px;
|
||||
line-height: 1.1;
|
||||
font-weight: 700;
|
||||
color: #1f2937;
|
||||
}
|
||||
|
||||
.revisit-kpi-card.is-primary .revisit-kpi-value {
|
||||
color: #4a78ff;
|
||||
}
|
||||
|
||||
.revisit-kpi-sub {
|
||||
margin-top: 6px;
|
||||
font-size: 12px;
|
||||
color: #909399;
|
||||
}
|
||||
|
||||
.revisit-caliber {
|
||||
margin-top: 12px;
|
||||
font-size: 12px;
|
||||
line-height: 1.6;
|
||||
color: #909399;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -67,10 +67,7 @@
|
||||
</el-form>
|
||||
<div class="log-hint">
|
||||
由每日定时任务「待分配诊单自动指派」写入:按上月二诊复诊接诊率分档轮询分配(>70% 每人3条/日,60%~70%
|
||||
每人2条/日,50%~60% 每人1条/日,<50% 不分)。「回退」可将已分配医助撤回到自动分配前的原医助(通常为一中心),并写入指派日志(原医助重新接手按「继承」记录)。
|
||||
<br />
|
||||
口径版本:<b>v1 旧口径</b> = 分母仅新指派(visit2_rate_new_assign);<b>v2 新口径</b> = 每列独立分母,继承按继承时诊次计入(visit2_rate)。
|
||||
每条日志同时记录两套率并标注本批次分档所用口径(配置 project.revisit_rate.auto_assign_tier_field);2026-10 前的历史行仅有旧口径率。
|
||||
每人2条/日,50%~60% 每人1条/日,<50% 不分)。「回退」可将已分配医助撤回到自动分配前的原医助(通常为一中心),并写入指派日志。
|
||||
</div>
|
||||
</el-card>
|
||||
|
||||
@@ -140,7 +137,7 @@
|
||||
<template #default="{ row }">
|
||||
<template v-if="Number(row.assistant_id) > 0">
|
||||
<div>{{ row.assistant_name || '#' + row.assistant_id }}</div>
|
||||
<div class="cell-sub">上月二诊接诊率 {{ formatRate(tierRate(row)) }}</div>
|
||||
<div class="cell-sub">上月二诊接诊率 {{ formatRate(row.visit2_rate) }}</div>
|
||||
</template>
|
||||
<span v-else>—</span>
|
||||
</template>
|
||||
@@ -148,29 +145,6 @@
|
||||
<el-table-column label="档位" width="100" align="center">
|
||||
<template #default="{ row }">{{ row.tier_text || '—' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="分档口径" min-width="150">
|
||||
<template #header>
|
||||
<span>分档口径</span>
|
||||
<el-tooltip
|
||||
placement="top"
|
||||
effect="dark"
|
||||
content="本批次分档所用口径;下方为两套口径的上月二诊接诊率(新口径 = 每列独立分母 / 旧口径 = 分母仅新指派)"
|
||||
>
|
||||
<el-icon class="col-hint"><InfoFilled /></el-icon>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
<template #default="{ row }">
|
||||
<template v-if="Number(row.action) === 1">
|
||||
<el-tag :type="row.rate_version === 'v2' ? 'primary' : 'info'" size="small">
|
||||
{{ row.rate_version_text || row.rate_version || 'v1' }}
|
||||
</el-tag>
|
||||
<div class="cell-sub">
|
||||
新口径 {{ formatRate(row.visit2_rate) }} · 旧口径 {{ formatRate(row.visit2_rate_new_assign) }}
|
||||
</div>
|
||||
</template>
|
||||
<span v-else class="cell-sub">—</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="轮次" width="70" align="center">
|
||||
<template #default="{ row }">
|
||||
{{ Number(row.round_no) > 0 ? '第' + row.round_no + '轮' : '—' }}
|
||||
@@ -212,7 +186,6 @@
|
||||
import { autoAssignLogLists, autoAssignLogRollback } from '@/api/stats'
|
||||
import { usePaging } from '@/hooks/usePaging'
|
||||
import feedback from '@/utils/feedback'
|
||||
import { InfoFilled } from '@element-plus/icons-vue'
|
||||
import { onMounted, reactive, ref, watch } from 'vue'
|
||||
|
||||
const dateRange = ref<[string, string] | null>(null)
|
||||
@@ -268,14 +241,6 @@ const handleReset = () => {
|
||||
const formatRate = (rate: number | null | undefined) =>
|
||||
rate === null || rate === undefined ? '—' : `${rate}%`
|
||||
|
||||
/** 「医助」列显示的接诊率 = 本批次分档所用口径的率(v1 旧口径取 visit2_rate_new_assign,历史行无该列时回落 visit2_rate) */
|
||||
const tierRate = (row: any): number | null | undefined => {
|
||||
if (row?.rate_version === 'v1' && row?.visit2_rate_new_assign !== null && row?.visit2_rate_new_assign !== undefined) {
|
||||
return row.visit2_rate_new_assign
|
||||
}
|
||||
return row?.visit2_rate
|
||||
}
|
||||
|
||||
const rowSelectable = (row: any) => Number(row.can_rollback) === 1
|
||||
|
||||
const onSelectionChange = (rows: any[]) => {
|
||||
@@ -350,12 +315,5 @@ onMounted(() => getLists())
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
|
||||
.col-hint {
|
||||
margin-left: 2px;
|
||||
vertical-align: -2px;
|
||||
color: var(--el-text-color-secondary);
|
||||
cursor: help;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,901 +0,0 @@
|
||||
<template>
|
||||
<div class="revisit-rate-page">
|
||||
<el-card class="!border-none" shadow="never">
|
||||
<el-form :inline="true" class="rate-filter-form">
|
||||
<el-form-item :label="dateLabel">
|
||||
<el-date-picker
|
||||
v-model="dateRange"
|
||||
type="daterange"
|
||||
value-format="YYYY-MM-DD"
|
||||
start-placeholder="开始日期"
|
||||
end-placeholder="结束日期"
|
||||
range-separator="至"
|
||||
:clearable="false"
|
||||
style="width: 280px"
|
||||
@change="loadData"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item label="部门">
|
||||
<el-tree-select
|
||||
v-model="deptId"
|
||||
:data="deptTreeOptions"
|
||||
placeholder="二中心(全部)"
|
||||
clearable
|
||||
filterable
|
||||
check-strictly
|
||||
node-key="id"
|
||||
:default-expand-all="true"
|
||||
:props="deptTreeProps"
|
||||
style="width: 210px"
|
||||
@change="handleDeptChange"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item label="医助">
|
||||
<el-select
|
||||
v-model="assistantId"
|
||||
placeholder="全部医助"
|
||||
filterable
|
||||
clearable
|
||||
:loading="optionsLoading"
|
||||
style="width: 180px"
|
||||
@change="loadData"
|
||||
>
|
||||
<el-option
|
||||
v-for="assistant in assistantOptions"
|
||||
:key="assistant.id"
|
||||
:label="assistant.name"
|
||||
:value="assistant.id"
|
||||
/>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-button type="primary" :loading="loading" @click="loadData">查询</el-button>
|
||||
<el-button :disabled="loading" @click="handleReset">重置</el-button>
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-popover placement="bottom-start" :width="540" trigger="hover">
|
||||
<template #reference>
|
||||
<span class="rate-caliber-trigger"
|
||||
><el-icon><InfoFilled /></el-icon>统计口径</span
|
||||
>
|
||||
</template>
|
||||
<div class="rate-caliber">
|
||||
<p>
|
||||
<b>{{ cohortLabel }}</b
|
||||
>:按所选{{
|
||||
dateLabel
|
||||
}}范围确定患者,订单从对应指派后累计至查询当天;结束日期允许选择未来日期,但未来订单不会提前计入。
|
||||
</p>
|
||||
<p v-if="isInherit">
|
||||
<b>继承诊次重新起算</b>:继承后的第 1 笔有效订单算二诊,第 2
|
||||
笔算三诊,依次递增;不使用继承前的全局诊次,也不叠加诊次偏移。只统计继承患者,不混入新指派患者。
|
||||
</p>
|
||||
<p v-else>
|
||||
只统计新指派患者,不混入继承患者。继承患者在独立的「继承复诊接诊率」页面统计。
|
||||
</p>
|
||||
<p>
|
||||
<b>N 诊接诊率</b> = N 诊单数 ÷ 本页{{ cohortLabel }};分母为 0
|
||||
显示「—」。<b>复诊合计接诊率</b> = 复诊合计单数 ÷ 本页{{
|
||||
cohortLabel
|
||||
}},表示人均复诊成交单数,可超过 100%。
|
||||
</p>
|
||||
<p>
|
||||
订单仅计入有效业务订单,剔除已取消 / 拒收 /
|
||||
退款;归属按服务端的患者持有记录计算。医助按人事部门归组;仅统计「二中心」及其组织下级,选定部门时包含其下级。
|
||||
</p>
|
||||
<p>
|
||||
部门行和合计行按诊单去重,不能直接将医助行相加。灰字为「单数 /
|
||||
分母」。
|
||||
</p>
|
||||
</div>
|
||||
</el-popover>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<el-alert class="mt-3" type="info" :closable="false" show-icon :title="reportHint" />
|
||||
<el-alert
|
||||
v-if="optionsError"
|
||||
class="mt-3"
|
||||
type="warning"
|
||||
:title="optionsError"
|
||||
:closable="false"
|
||||
/>
|
||||
<el-alert
|
||||
v-if="queryError"
|
||||
class="mt-3"
|
||||
type="error"
|
||||
:title="queryError"
|
||||
:closable="false"
|
||||
/>
|
||||
</el-card>
|
||||
|
||||
<div class="rate-kpi-grid">
|
||||
<div
|
||||
v-for="card in summaryCards"
|
||||
:key="card.key"
|
||||
class="rate-kpi-card"
|
||||
:class="{ 'is-clickable': card.clickable }"
|
||||
@click="card.clickable && card.onClick()"
|
||||
>
|
||||
<div class="rate-kpi-label">{{ card.label }}</div>
|
||||
<div class="rate-kpi-value">{{ card.value }}</div>
|
||||
<div v-if="card.sub" class="rate-kpi-sub">{{ card.sub }}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<el-card class="!border-none mt-4" shadow="never">
|
||||
<template #header>
|
||||
<div class="rate-card-header">
|
||||
<span>{{ reportTitle }} · 部门 / 医助明细</span>
|
||||
<span class="rate-card-hint">{{ dateLabel }}:{{ rangeText }}</span>
|
||||
<span v-if="observedUntil" class="rate-card-hint"
|
||||
>订单统计截至:{{ observedUntil }}</span
|
||||
>
|
||||
</div>
|
||||
<div class="rate-card-hint mt-2">
|
||||
点击{{ cohortLabel }}、各诊次单数可查看患者与订单;底栏合计按诊单去重。
|
||||
</div>
|
||||
</template>
|
||||
<el-table
|
||||
v-loading="loading"
|
||||
:data="rows"
|
||||
size="small"
|
||||
border
|
||||
row-key="row_key"
|
||||
:tree-props="{ children: 'children' }"
|
||||
:default-expand-all="true"
|
||||
show-summary
|
||||
:summary-method="getSummaries"
|
||||
>
|
||||
<el-table-column label="部门 / 医助" min-width="200" fixed>
|
||||
<template #default="{ row }">
|
||||
<span v-if="row.is_dept" class="rate-dept-cell"
|
||||
>{{ row.dept_name
|
||||
}}<span class="rate-dept-count"
|
||||
>{{ row.assistant_count }} 人</span
|
||||
></span
|
||||
>
|
||||
<span v-else>{{ row.assistant_name }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column
|
||||
:prop="cohortCountKey"
|
||||
:label="cohortLabel"
|
||||
min-width="100"
|
||||
align="right"
|
||||
>
|
||||
<template #header>
|
||||
<span>{{ cohortLabel }}</span>
|
||||
<el-tooltip
|
||||
effect="dark"
|
||||
placement="top"
|
||||
:content="`所选${dateLabel}范围内的${cohortLabel},部门和合计按诊单去重`"
|
||||
><el-icon class="rate-th-hint"><InfoFilled /></el-icon
|
||||
></el-tooltip>
|
||||
</template>
|
||||
<template #default="{ row }">
|
||||
<el-link
|
||||
v-if="canViewAssignLines && row[cohortCountKey] > 0"
|
||||
type="primary"
|
||||
:underline="false"
|
||||
@click="openAssignDetail(row)"
|
||||
>{{ row[cohortCountKey] }}</el-link
|
||||
>
|
||||
<span v-else>{{ row[cohortCountKey] ?? 0 }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<template v-for="slot in visitSlots" :key="slot">
|
||||
<el-table-column
|
||||
:prop="`visit${slot}_count`"
|
||||
:label="`${slotLabel(slot)}单数`"
|
||||
min-width="96"
|
||||
align="right"
|
||||
>
|
||||
<template #header>
|
||||
<span>{{ slotLabel(slot) }}单数</span>
|
||||
<el-tooltip effect="dark" placement="top" :content="slotCountTip(slot)"
|
||||
><el-icon class="rate-th-hint"><InfoFilled /></el-icon
|
||||
></el-tooltip>
|
||||
</template>
|
||||
<template #default="{ row }">
|
||||
<el-link
|
||||
v-if="canViewOrderLines && row[`visit${slot}_count`] > 0"
|
||||
type="primary"
|
||||
:underline="false"
|
||||
@click="openOrderDetail(slot, row)"
|
||||
>{{ row[`visit${slot}_count`] }}</el-link
|
||||
>
|
||||
<span v-else>{{ row[`visit${slot}_count`] ?? 0 }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column
|
||||
:prop="`visit${slot}_rate`"
|
||||
:label="`${slotLabel(slot)}接诊率`"
|
||||
min-width="110"
|
||||
align="right"
|
||||
>
|
||||
<template #header>
|
||||
<span>{{ slotLabel(slot) }}接诊率</span>
|
||||
<el-tooltip
|
||||
effect="dark"
|
||||
placement="top"
|
||||
:content="`${slotLabel(slot)}单数 ÷ ${cohortLabel};分母为 0 显示「—」`"
|
||||
><el-icon class="rate-th-hint"><InfoFilled /></el-icon
|
||||
></el-tooltip>
|
||||
</template>
|
||||
<template #default="{ row }">
|
||||
<div class="rate-cell">
|
||||
<span class="rate-cell-main">{{
|
||||
formatRate(row[`visit${slot}_rate`])
|
||||
}}</span
|
||||
><span class="rate-cell-sub">{{
|
||||
denText(row, `visit${slot}`)
|
||||
}}</span>
|
||||
</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</template>
|
||||
<el-table-column
|
||||
prop="visit_all_count"
|
||||
label="复诊合计单数"
|
||||
min-width="110"
|
||||
align="right"
|
||||
>
|
||||
<template #header>
|
||||
<span>复诊合计单数</span>
|
||||
<el-tooltip
|
||||
effect="dark"
|
||||
placement="top"
|
||||
content="所选患者从对应指派后累计至查询当天的全部复诊订单数"
|
||||
><el-icon class="rate-th-hint"><InfoFilled /></el-icon
|
||||
></el-tooltip>
|
||||
</template>
|
||||
<template #default="{ row }">
|
||||
<el-link
|
||||
v-if="canViewOrderLines && row.visit_all_count > 0"
|
||||
type="primary"
|
||||
:underline="false"
|
||||
@click="openOrderDetail(0, row)"
|
||||
>{{ row.visit_all_count }}</el-link
|
||||
>
|
||||
<span v-else>{{ row.visit_all_count ?? 0 }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column
|
||||
prop="visit_all_rate"
|
||||
label="复诊合计接诊率"
|
||||
min-width="128"
|
||||
align="right"
|
||||
>
|
||||
<template #header>
|
||||
<span>复诊合计接诊率</span>
|
||||
<el-tooltip
|
||||
effect="dark"
|
||||
placement="top"
|
||||
:content="`复诊合计单数 ÷ ${cohortLabel};表示人均复诊成交单数,可超过 100%`"
|
||||
><el-icon class="rate-th-hint"><InfoFilled /></el-icon
|
||||
></el-tooltip>
|
||||
</template>
|
||||
<template #default="{ row }">
|
||||
<div class="rate-cell">
|
||||
<span class="rate-cell-main">{{ formatRate(row.visit_all_rate) }}</span
|
||||
><span class="rate-cell-sub">{{ denText(row, 'visit_all') }}</span>
|
||||
</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</el-card>
|
||||
|
||||
<el-dialog
|
||||
v-model="detailVisible"
|
||||
:title="detailTitle"
|
||||
width="1080px"
|
||||
top="6vh"
|
||||
destroy-on-close
|
||||
@close="invalidateDetail"
|
||||
>
|
||||
<p class="rate-detail-hint">{{ detailHint }}</p>
|
||||
<el-alert
|
||||
v-if="detailError"
|
||||
class="mb-3"
|
||||
type="error"
|
||||
:title="detailError"
|
||||
:closable="false"
|
||||
/>
|
||||
<el-table
|
||||
v-loading="detailLoading"
|
||||
:data="detailRows"
|
||||
size="small"
|
||||
border
|
||||
stripe
|
||||
max-height="60vh"
|
||||
>
|
||||
<template v-if="detailType === 'assign'">
|
||||
<el-table-column prop="diagnosis_id" label="诊单ID" width="90" />
|
||||
<el-table-column prop="patient_name" label="患者" min-width="100">
|
||||
<template #default="{ row }">
|
||||
<el-link
|
||||
v-if="canViewPatientDetail && row.diagnosis_id"
|
||||
type="primary"
|
||||
:underline="false"
|
||||
@click="openPatientDetail(row.diagnosis_id)"
|
||||
>{{ row.patient_name || `诊单#${row.diagnosis_id}` }}</el-link
|
||||
>
|
||||
<span v-else>{{ row.patient_name || '—' }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="patient_phone" label="联系电话" min-width="120"
|
||||
><template #default="{ row }">{{
|
||||
row.patient_phone || '—'
|
||||
}}</template></el-table-column
|
||||
>
|
||||
<el-table-column
|
||||
prop="assistant_names"
|
||||
:label="isInherit ? '继承医助' : '被指派医助'"
|
||||
min-width="140"
|
||||
show-overflow-tooltip
|
||||
/>
|
||||
<el-table-column
|
||||
prop="assign_count"
|
||||
:label="isInherit ? '范围内继承次数' : '范围内指派次数'"
|
||||
width="120"
|
||||
align="right"
|
||||
/>
|
||||
<el-table-column
|
||||
prop="first_assign_time_text"
|
||||
:label="isInherit ? '首次继承时间' : '首次指派时间'"
|
||||
min-width="160"
|
||||
/>
|
||||
<el-table-column
|
||||
prop="last_assign_time_text"
|
||||
:label="isInherit ? '最近继承时间' : '最近指派时间'"
|
||||
min-width="160"
|
||||
/>
|
||||
</template>
|
||||
<template v-else>
|
||||
<el-table-column
|
||||
prop="order_no"
|
||||
label="订单号"
|
||||
min-width="180"
|
||||
show-overflow-tooltip
|
||||
>
|
||||
<template #default="{ row }">
|
||||
<el-link
|
||||
v-if="canViewOrderDetail && row.order_id"
|
||||
type="primary"
|
||||
:underline="false"
|
||||
@click="openOrderInfo(row.order_id)"
|
||||
>{{ row.order_no || `#${row.order_id}` }}</el-link
|
||||
>
|
||||
<span v-else>{{ row.order_no || `#${row.order_id}` }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column
|
||||
v-if="detailSlot === 0 || isInherit"
|
||||
prop="visit_slot"
|
||||
:label="isInherit ? '继承后诊次' : '诊次'"
|
||||
width="100"
|
||||
align="center"
|
||||
><template #default="{ row }">{{
|
||||
slotLabel(Number(row.visit_slot))
|
||||
}}</template></el-table-column
|
||||
>
|
||||
<el-table-column
|
||||
v-if="isInherit"
|
||||
prop="global_visit_slot"
|
||||
label="全局诊次(参考)"
|
||||
width="130"
|
||||
align="center"
|
||||
><template #default="{ row }">{{
|
||||
row.global_visit_slot ? slotLabel(Number(row.global_visit_slot)) : '—'
|
||||
}}</template></el-table-column
|
||||
>
|
||||
<el-table-column prop="diagnosis_id" label="诊单ID" width="90" />
|
||||
<el-table-column prop="patient_name" label="患者" min-width="100">
|
||||
<template #default="{ row }">
|
||||
<el-link
|
||||
v-if="canViewPatientDetail && row.diagnosis_id"
|
||||
type="primary"
|
||||
:underline="false"
|
||||
@click="openPatientDetail(row.diagnosis_id)"
|
||||
>{{ row.patient_name || `诊单#${row.diagnosis_id}` }}</el-link
|
||||
>
|
||||
<span v-else>{{ row.patient_name || '—' }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="patient_phone" label="联系电话" min-width="120"
|
||||
><template #default="{ row }">{{
|
||||
row.patient_phone || '—'
|
||||
}}</template></el-table-column
|
||||
>
|
||||
<el-table-column prop="amount" label="金额" width="100" align="right"
|
||||
><template #default="{ row }">¥ {{ row.amount }}</template></el-table-column
|
||||
>
|
||||
<el-table-column
|
||||
prop="cohort_assign_time_text"
|
||||
:label="isInherit ? '继承时间' : '指派时间'"
|
||||
min-width="160"
|
||||
/>
|
||||
<el-table-column prop="create_time_text" label="下单时间" min-width="160" />
|
||||
<el-table-column prop="assistant_name" label="持有医助" min-width="100" />
|
||||
<el-table-column prop="creator_name" label="订单创建人" min-width="100" />
|
||||
</template>
|
||||
</el-table>
|
||||
<div class="rate-detail-footer">共 {{ detailCount }} 条</div>
|
||||
</el-dialog>
|
||||
<order-detail-drawer ref="orderDetailRef" readonly append-to-body />
|
||||
<diagnosis-edit-popup ref="diagnosisEditRef" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, defineAsyncComponent, onBeforeUnmount, onMounted, ref } from 'vue'
|
||||
import { InfoFilled } from '@element-plus/icons-vue'
|
||||
import {
|
||||
revisitCohortAssignLines,
|
||||
revisitCohortDeptOptions,
|
||||
revisitCohortOverview,
|
||||
revisitCohortVisitOrderLines,
|
||||
type RevisitRateCohortType,
|
||||
type RevisitRateDetailQuery,
|
||||
type RevisitRateQuery
|
||||
} from '@/api/stats'
|
||||
import { hasPermission } from '@/utils/perm'
|
||||
|
||||
const props = defineProps<{ cohortType: RevisitRateCohortType }>()
|
||||
const OrderDetailDrawer = defineAsyncComponent(
|
||||
() => import('@/views/consumer/prescription/components/PrescriptionOrderDetailDrawer.vue')
|
||||
)
|
||||
const DiagnosisEditPopup = defineAsyncComponent(() => import('@/views/tcm/diagnosis/edit.vue'))
|
||||
|
||||
interface MetricPack extends Record<string, any> {
|
||||
assigned_count: number
|
||||
inherit_count: number
|
||||
assigned_total_count: number
|
||||
visit_all_count: number
|
||||
visit_all_den: number
|
||||
visit_all_rate: number | null
|
||||
}
|
||||
interface StatsRow extends MetricPack {
|
||||
row_key: string
|
||||
is_dept: 0 | 1
|
||||
dept_id: number
|
||||
dept_name: string
|
||||
assistant_id?: number
|
||||
assistant_name?: string
|
||||
assistant_count?: number
|
||||
children?: StatsRow[]
|
||||
}
|
||||
interface DeptOption {
|
||||
id: number
|
||||
pid: number
|
||||
name: string
|
||||
}
|
||||
interface DeptTreeNode extends DeptOption {
|
||||
children?: DeptTreeNode[]
|
||||
}
|
||||
interface AssistantOption {
|
||||
id: number
|
||||
name: string
|
||||
dept_id: number
|
||||
}
|
||||
interface SummaryCard {
|
||||
key: string
|
||||
label: string
|
||||
value: string
|
||||
sub: string
|
||||
clickable: boolean
|
||||
onClick: () => void
|
||||
}
|
||||
|
||||
const isInherit = computed(() => props.cohortType === 'inherit')
|
||||
const cohortLabel = computed(() => (isInherit.value ? '继承数' : '新指派数'))
|
||||
const cohortCountKey = computed(() => (isInherit.value ? 'inherit_count' : 'assigned_count'))
|
||||
const dateLabel = computed(() => (isInherit.value ? '继承日期' : '指派日期'))
|
||||
const reportTitle = computed(() => (isInherit.value ? '继承复诊接诊率' : '按指派周期复诊率'))
|
||||
const reportHint = computed(() =>
|
||||
isInherit.value
|
||||
? '按继承日期范围选择患者,订单累计至查询当天。继承后第 1 笔有效订单算二诊,第 2 笔算三诊;忽略继承前全局诊次及偏移,新指派患者另页统计。'
|
||||
: '按新指派日期范围选择患者,订单累计至查询当天,跨月继续累计。继承患者在独立的「继承复诊接诊率」页面统计。'
|
||||
)
|
||||
const permissionPrefix = computed(() =>
|
||||
isInherit.value ? 'stats.revisitInheritRate' : 'stats.revisitAssignRate'
|
||||
)
|
||||
const canViewAssignLines = computed(() => hasPermission([`${permissionPrefix.value}/assignLines`]))
|
||||
const canViewOrderLines = computed(() =>
|
||||
hasPermission([`${permissionPrefix.value}/visitOrderLines`])
|
||||
)
|
||||
const canViewOrderDetail = hasPermission(['tcm.prescriptionOrder/detail'])
|
||||
const canViewPatientDetail = hasPermission(['tcm.diagnosis/detail'])
|
||||
|
||||
const formatDate = (date: Date) =>
|
||||
`${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
|
||||
const defaultDateRange = (): [string, string] => {
|
||||
const now = new Date()
|
||||
return [formatDate(new Date(now.getFullYear(), now.getMonth(), 1)), formatDate(now)]
|
||||
}
|
||||
const dateRange = ref<[string, string]>(defaultDateRange())
|
||||
const deptId = ref<number | undefined>()
|
||||
const assistantId = ref<number | undefined>()
|
||||
const loading = ref(false)
|
||||
const queryError = ref('')
|
||||
const rows = ref<StatsRow[]>([])
|
||||
const total = ref<MetricPack | null>(null)
|
||||
const visitSlots = ref<number[]>([2, 3, 4])
|
||||
const observedUntil = ref('')
|
||||
/** 下钻只复用已展示报表的查询快照,避免读取正在编辑的筛选。 */
|
||||
const loadedQuery = ref<RevisitRateQuery | null>(null)
|
||||
let overviewRequestId = 0
|
||||
let disposed = false
|
||||
const rangeText = computed(() =>
|
||||
loadedQuery.value
|
||||
? `${loadedQuery.value.start_date} 至 ${loadedQuery.value.end_date}`
|
||||
: `${dateRange.value[0]} 至 ${dateRange.value[1]}`
|
||||
)
|
||||
const currentQuery = (): RevisitRateQuery => ({
|
||||
start_date: dateRange.value[0],
|
||||
end_date: dateRange.value[1],
|
||||
dept_ids: deptId.value ? String(deptId.value) : '',
|
||||
assistant_id: assistantId.value || undefined
|
||||
})
|
||||
|
||||
const deptOptions = ref<DeptOption[]>([])
|
||||
const allAssistants = ref<AssistantOption[]>([])
|
||||
const optionsLoading = ref(false)
|
||||
const optionsError = ref('')
|
||||
const deptTreeProps = { value: 'id', label: 'name', children: 'children' }
|
||||
const deptTreeOptions = computed<DeptTreeNode[]>(() => {
|
||||
const nodes = new Map<number, DeptTreeNode>()
|
||||
deptOptions.value.forEach((item) => nodes.set(item.id, { ...item, children: [] }))
|
||||
const roots: DeptTreeNode[] = []
|
||||
nodes.forEach((node) => {
|
||||
const parent = nodes.get(node.pid)
|
||||
if (parent && parent !== node) parent.children!.push(node)
|
||||
else roots.push(node)
|
||||
})
|
||||
const stripEmptyChildren = (node: DeptTreeNode) => {
|
||||
if (node.children?.length) node.children.forEach(stripEmptyChildren)
|
||||
else delete node.children
|
||||
}
|
||||
roots.forEach(stripEmptyChildren)
|
||||
return roots
|
||||
})
|
||||
const selectedDeptIds = computed(() => {
|
||||
if (!deptId.value) return null
|
||||
const ids = new Set<number>([Number(deptId.value)])
|
||||
let expanded = true
|
||||
while (expanded) {
|
||||
expanded = false
|
||||
deptOptions.value.forEach((item) => {
|
||||
if (ids.has(item.pid) && !ids.has(item.id)) {
|
||||
ids.add(item.id)
|
||||
expanded = true
|
||||
}
|
||||
})
|
||||
}
|
||||
return ids
|
||||
})
|
||||
const assistantOptions = computed(() =>
|
||||
allAssistants.value.filter(
|
||||
(item) => !selectedDeptIds.value || selectedDeptIds.value.has(item.dept_id)
|
||||
)
|
||||
)
|
||||
const handleDeptChange = () => {
|
||||
if (assistantId.value && !assistantOptions.value.some((item) => item.id === assistantId.value))
|
||||
assistantId.value = undefined
|
||||
void loadData()
|
||||
}
|
||||
const loadDeptOptions = async () => {
|
||||
optionsLoading.value = true
|
||||
optionsError.value = ''
|
||||
try {
|
||||
const res = await revisitCohortDeptOptions(props.cohortType)
|
||||
if (disposed) return
|
||||
deptOptions.value = (res?.rows ?? []).map((item: DeptOption) => ({
|
||||
...item,
|
||||
id: Number(item.id),
|
||||
pid: Number(item.pid)
|
||||
}))
|
||||
allAssistants.value = (res?.assistants ?? []).map((item: AssistantOption) => ({
|
||||
...item,
|
||||
id: Number(item.id),
|
||||
dept_id: Number(item.dept_id)
|
||||
}))
|
||||
} catch {
|
||||
if (!disposed) optionsError.value = '部门及医助选项加载失败,请刷新页面重试。'
|
||||
} finally {
|
||||
if (!disposed) optionsLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const cnDigits = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十']
|
||||
const slotLabel = (slot: number) => {
|
||||
if (slot === 0) return '复诊合计'
|
||||
if (slot >= 1 && slot <= 10) return `${cnDigits[slot]}诊`
|
||||
if (slot > 10 && slot < 20) return `十${cnDigits[slot - 10]}诊`
|
||||
return `${slot}诊`
|
||||
}
|
||||
const slotCountTip = (slot: number) =>
|
||||
isInherit.value
|
||||
? `所选继承患者在继承后的第 ${slot - 1} 笔有效订单数,累计至查询当天;不使用继承前全局诊次和偏移`
|
||||
: `所选新指派患者的${slotLabel(slot)}有效订单数,从对应指派后累计至查询当天`
|
||||
const formatRate = (rate: number | null | undefined) =>
|
||||
rate === null || rate === undefined ? '—' : `${rate}%`
|
||||
const denText = (row: Record<string, any>, prefix: string) =>
|
||||
`${Number(row[`${prefix}_count`] ?? 0)} / ${row[`${prefix}_den`] ?? '—'}`
|
||||
const summaryCards = computed<SummaryCard[]>(() => {
|
||||
const t = total.value
|
||||
const cards: SummaryCard[] = [
|
||||
{
|
||||
key: 'cohort',
|
||||
label: cohortLabel.value,
|
||||
value: t ? String(t[cohortCountKey.value] ?? 0) : '—',
|
||||
sub: `按${dateLabel.value}范围选择患者`,
|
||||
clickable: !!(canViewAssignLines.value && t && t[cohortCountKey.value] > 0),
|
||||
onClick: () => void openAssignDetail(null)
|
||||
}
|
||||
]
|
||||
visitSlots.value.forEach((slot) =>
|
||||
cards.push({
|
||||
key: `visit${slot}`,
|
||||
label: `${slotLabel(slot)}接诊率`,
|
||||
value: t ? formatRate(t[`visit${slot}_rate`]) : '—',
|
||||
sub: t
|
||||
? `${slotLabel(slot)}下单 ${t[`visit${slot}_count`] ?? 0} 单 / 分母 ${t[`visit${slot}_den`] ?? '—'}`
|
||||
: '',
|
||||
clickable: !!(canViewOrderLines.value && t && t[`visit${slot}_count`] > 0),
|
||||
onClick: () => void openOrderDetail(slot, null)
|
||||
})
|
||||
)
|
||||
cards.push({
|
||||
key: 'visit_all',
|
||||
label: '复诊合计接诊率',
|
||||
value: t ? formatRate(t.visit_all_rate) : '—',
|
||||
sub: t ? `复诊下单 ${t.visit_all_count ?? 0} 单 / 分母 ${t.visit_all_den ?? '—'}` : '',
|
||||
clickable: !!(canViewOrderLines.value && t && t.visit_all_count > 0),
|
||||
onClick: () => void openOrderDetail(0, null)
|
||||
})
|
||||
return cards
|
||||
})
|
||||
/** 服务端已按诊单去重,合计不能由各医助行相加。 */
|
||||
const getSummaries = ({ columns }: { columns: Array<{ property?: string }> }) =>
|
||||
columns.map((column, index) => {
|
||||
if (index === 0) return '合计'
|
||||
const t = total.value
|
||||
if (!t) return ''
|
||||
const prop = column.property || ''
|
||||
if (prop === cohortCountKey.value) return String(t[prop] ?? 0)
|
||||
const match = /^visit(\d+|_all)_(count|rate)$/.exec(prop)
|
||||
if (!match) return ''
|
||||
return match[2] === 'rate'
|
||||
? `${formatRate(t[prop])}(${denText(t, `visit${match[1]}`)})`
|
||||
: String(t[prop] ?? 0)
|
||||
})
|
||||
|
||||
const loadData = async () => {
|
||||
const requestId = ++overviewRequestId
|
||||
invalidateDetail()
|
||||
detailVisible.value = false
|
||||
loadedQuery.value = null
|
||||
rows.value = []
|
||||
total.value = null
|
||||
observedUntil.value = ''
|
||||
queryError.value = ''
|
||||
loading.value = true
|
||||
const query = currentQuery()
|
||||
try {
|
||||
const res = await revisitCohortOverview(query, props.cohortType)
|
||||
if (disposed || requestId !== overviewRequestId) return
|
||||
rows.value = res?.rows ?? []
|
||||
total.value = res?.total ?? null
|
||||
observedUntil.value = res?.observed_until ?? ''
|
||||
const slots: number[] = Array.isArray(res?.slots) ? res.slots.map(Number) : []
|
||||
visitSlots.value = slots.length
|
||||
? [
|
||||
...new Set(
|
||||
slots.filter((slot) => Number.isInteger(slot) && slot >= 2 && slot <= 50)
|
||||
)
|
||||
].sort((a, b) => a - b)
|
||||
: [2, 3, 4]
|
||||
loadedQuery.value = { ...query }
|
||||
} catch {
|
||||
if (!disposed && requestId === overviewRequestId)
|
||||
queryError.value = '报表加载失败,请重新查询。'
|
||||
} finally {
|
||||
if (!disposed && requestId === overviewRequestId) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const detailVisible = ref(false)
|
||||
const detailType = ref<'assign' | 'orders'>('assign')
|
||||
const detailTitle = ref('')
|
||||
const detailHint = ref('')
|
||||
const detailLoading = ref(false)
|
||||
const detailError = ref('')
|
||||
const detailRows = ref<any[]>([])
|
||||
const detailCount = ref(0)
|
||||
const detailSlot = ref(2)
|
||||
let detailRequestId = 0
|
||||
const invalidateDetail = () => {
|
||||
++detailRequestId
|
||||
detailLoading.value = false
|
||||
detailRows.value = []
|
||||
detailCount.value = 0
|
||||
detailError.value = ''
|
||||
}
|
||||
const rowScope = (
|
||||
row: StatsRow | null
|
||||
): Pick<RevisitRateDetailQuery, 'scope_assistant_id' | 'dept_id'> & { label: string } => {
|
||||
if (!row) return { label: '合计' }
|
||||
return row.is_dept
|
||||
? { dept_id: row.dept_id, label: row.dept_name }
|
||||
: { scope_assistant_id: row.assistant_id, label: row.assistant_name || '' }
|
||||
}
|
||||
const openDetail = async (type: 'assign' | 'orders', slot: number, row: StatsRow | null) => {
|
||||
if (loading.value || !loadedQuery.value) return
|
||||
if (type === 'assign' ? !canViewAssignLines.value : !canViewOrderLines.value) return
|
||||
const query = { ...loadedQuery.value }
|
||||
const { label, ...scope } = rowScope(row)
|
||||
const requestId = ++detailRequestId
|
||||
detailType.value = type
|
||||
detailSlot.value = slot
|
||||
detailTitle.value = `${label} · ${type === 'assign' ? `${cohortLabel.value}明细` : `${slotLabel(slot)}订单明细`}(${query.start_date} 至 ${query.end_date})`
|
||||
detailHint.value = `${dateLabel.value}:${query.start_date} 至 ${query.end_date};订单统计截至:${observedUntil.value || '查询当天'}${isInherit.value && type === 'orders' ? '。继承后首笔有效订单算二诊,全局诊次仅供参考。' : '。'}`
|
||||
detailRows.value = []
|
||||
detailCount.value = 0
|
||||
detailError.value = ''
|
||||
detailLoading.value = true
|
||||
detailVisible.value = true
|
||||
try {
|
||||
// assistant_id 保留顶层筛选,scope_assistant_id 独立约束医助行。
|
||||
const params: RevisitRateDetailQuery = { ...query, ...scope }
|
||||
const res =
|
||||
type === 'assign'
|
||||
? await revisitCohortAssignLines(params, props.cohortType)
|
||||
: await revisitCohortVisitOrderLines({ ...params, slot }, props.cohortType)
|
||||
if (disposed || requestId !== detailRequestId || !detailVisible.value) return
|
||||
detailRows.value = res?.rows ?? []
|
||||
detailCount.value = Number(res?.count ?? detailRows.value.length)
|
||||
} catch {
|
||||
if (!disposed && requestId === detailRequestId)
|
||||
detailError.value = '明细加载失败,请关闭后重试。'
|
||||
} finally {
|
||||
if (!disposed && requestId === detailRequestId) detailLoading.value = false
|
||||
}
|
||||
}
|
||||
const openAssignDetail = (row: StatsRow | null) => openDetail('assign', 0, row)
|
||||
const openOrderDetail = (slot: number, row: StatsRow | null) => openDetail('orders', slot, row)
|
||||
const orderDetailRef = ref<{ open: (id: number) => void } | null>(null)
|
||||
const openOrderInfo = (orderId: number) => {
|
||||
if (canViewOrderDetail && orderId) orderDetailRef.value?.open(orderId)
|
||||
}
|
||||
const diagnosisEditRef = ref<{ openViewOnly: (id: number) => void } | null>(null)
|
||||
const openPatientDetail = (diagnosisId: number) => {
|
||||
if (canViewPatientDetail && diagnosisId) diagnosisEditRef.value?.openViewOnly(diagnosisId)
|
||||
}
|
||||
const handleReset = () => {
|
||||
dateRange.value = defaultDateRange()
|
||||
deptId.value = undefined
|
||||
assistantId.value = undefined
|
||||
void loadData()
|
||||
}
|
||||
onMounted(() => {
|
||||
void loadDeptOptions()
|
||||
void loadData()
|
||||
})
|
||||
onBeforeUnmount(() => {
|
||||
disposed = true
|
||||
++overviewRequestId
|
||||
++detailRequestId
|
||||
})
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.revisit-rate-page {
|
||||
.rate-filter-form {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 12px 0;
|
||||
:deep(.el-form-item) {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
}
|
||||
.rate-caliber-trigger {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: 13px;
|
||||
cursor: help;
|
||||
}
|
||||
.rate-kpi-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||||
gap: 12px;
|
||||
margin-top: 16px;
|
||||
}
|
||||
.rate-kpi-card {
|
||||
background: var(--el-bg-color);
|
||||
border-radius: 8px;
|
||||
padding: 16px 20px;
|
||||
&.is-clickable {
|
||||
cursor: pointer;
|
||||
transition: box-shadow 0.15s ease;
|
||||
&:hover {
|
||||
box-shadow: var(--el-box-shadow-light);
|
||||
}
|
||||
}
|
||||
.rate-kpi-label {
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: 13px;
|
||||
}
|
||||
.rate-kpi-value {
|
||||
margin-top: 6px;
|
||||
font-size: 26px;
|
||||
font-weight: 600;
|
||||
color: var(--el-text-color-primary);
|
||||
}
|
||||
.rate-kpi-sub {
|
||||
margin-top: 2px;
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
}
|
||||
.rate-card-header {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: baseline;
|
||||
gap: 10px;
|
||||
}
|
||||
.rate-card-hint {
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
.rate-dept-cell {
|
||||
font-weight: 600;
|
||||
.rate-dept-count {
|
||||
margin-left: 6px;
|
||||
font-weight: 400;
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
}
|
||||
.rate-th-hint {
|
||||
margin-left: 2px;
|
||||
vertical-align: -2px;
|
||||
color: var(--el-text-color-secondary);
|
||||
cursor: help;
|
||||
}
|
||||
.rate-cell {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-end;
|
||||
line-height: 1.3;
|
||||
.rate-cell-main {
|
||||
font-weight: 500;
|
||||
}
|
||||
.rate-cell-sub {
|
||||
font-size: 11px;
|
||||
color: var(--el-text-color-placeholder);
|
||||
}
|
||||
}
|
||||
}
|
||||
.rate-detail-hint {
|
||||
margin: 0 0 12px;
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
.rate-detail-footer {
|
||||
margin-top: 10px;
|
||||
text-align: right;
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
.rate-caliber {
|
||||
font-size: 13px;
|
||||
line-height: 1.7;
|
||||
color: var(--el-text-color-regular);
|
||||
p + p {
|
||||
margin-top: 6px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,7 +0,0 @@
|
||||
<template>
|
||||
<cohort-report cohort-type="new" />
|
||||
</template>
|
||||
|
||||
<script setup lang="ts" name="revisitAssignRateStatsPage">
|
||||
import CohortReport from './components/CohortReport.vue'
|
||||
</script>
|
||||
@@ -1,863 +0,0 @@
|
||||
<template>
|
||||
<div class="revisit-due-page">
|
||||
<el-card class="!border-none" shadow="never">
|
||||
<el-form :inline="true" class="due-filter-form">
|
||||
<el-form-item label="医助">
|
||||
<el-select
|
||||
v-model="queryParams.assistant_id"
|
||||
clearable
|
||||
filterable
|
||||
placeholder="全部"
|
||||
class="w-[160px]"
|
||||
@change="doSearch"
|
||||
>
|
||||
<el-option
|
||||
v-for="item in assistantOptions"
|
||||
:key="item.id"
|
||||
:label="item.name"
|
||||
:value="Number(item.id)"
|
||||
/>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="部门">
|
||||
<el-tree-select
|
||||
v-model="queryParams.dept_id"
|
||||
:data="deptTreeOptions"
|
||||
placeholder="全部(二中心)"
|
||||
clearable
|
||||
filterable
|
||||
check-strictly
|
||||
node-key="id"
|
||||
:default-expand-all="true"
|
||||
:props="deptTreeProps"
|
||||
class="w-[200px]"
|
||||
@change="doSearch"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item label="状态">
|
||||
<el-select
|
||||
v-model="queryParams.state"
|
||||
clearable
|
||||
placeholder="全部"
|
||||
class="w-[170px]"
|
||||
@change="doSearch"
|
||||
>
|
||||
<el-option
|
||||
v-for="opt in stateOptions"
|
||||
:key="opt.value"
|
||||
:label="opt.label"
|
||||
:value="opt.value"
|
||||
/>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="开药天数">
|
||||
<el-select
|
||||
v-model="queryParams.days_bucket"
|
||||
clearable
|
||||
placeholder="全部"
|
||||
class="w-[120px]"
|
||||
@change="doSearch"
|
||||
>
|
||||
<el-option
|
||||
v-for="opt in REVISIT_DAYS_BUCKET_OPTIONS"
|
||||
:key="opt.value"
|
||||
:label="opt.label"
|
||||
:value="opt.value"
|
||||
/>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="延迟次数 ≥">
|
||||
<el-input-number
|
||||
v-model="minSnooze"
|
||||
:min="0"
|
||||
:max="999"
|
||||
:step="1"
|
||||
step-strictly
|
||||
controls-position="right"
|
||||
placeholder="不限"
|
||||
class="!w-[120px]"
|
||||
@change="onMinSnoozeChange"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item label="患者">
|
||||
<el-input
|
||||
v-model="queryParams.keyword"
|
||||
placeholder="患者姓名"
|
||||
clearable
|
||||
class="w-[160px]"
|
||||
@keyup.enter="doSearch"
|
||||
@clear="doSearch"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-button type="primary" @click="doSearch">查询</el-button>
|
||||
<el-button @click="handleReset">重置</el-button>
|
||||
<export-data
|
||||
class="ml-2.5"
|
||||
:fetch-fun="revisitDueLists"
|
||||
:params="queryParams"
|
||||
:page-size="pager.size"
|
||||
export-hint="导出范围与当前筛选一致(医助 / 部门 / 状态 / 开药天数 / 延迟次数 / 患者)"
|
||||
/>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<div class="due-hint">
|
||||
每位患者(诊单)一行,取最新有效业务订单为本轮周期:预计复诊日 = 用药起算日(签收 → 发货 → 下单)+ 开药天数;
|
||||
到期仍无有效挂号 / 过号未面诊的行标红,持有医助登录后台会收到右下角弹窗。
|
||||
「延迟次数」为医助在弹窗上点「延迟」的累计次数(越多说明越未跟进),「已联系」为填写患者承诺复诊日的次数,
|
||||
「人工关闭」由医助填原因关闭、在此标记供主管复核。数据范围按角色数据权限收窄;状态按今天实时推导。
|
||||
</div>
|
||||
</el-card>
|
||||
|
||||
<el-card class="!border-none mt-3" shadow="never">
|
||||
<el-table
|
||||
:data="pager.lists"
|
||||
v-loading="pager.loading"
|
||||
size="default"
|
||||
stripe
|
||||
row-key="id"
|
||||
:row-class-name="rowClassName"
|
||||
>
|
||||
<el-table-column label="患者" min-width="120" fixed="left">
|
||||
<template #default="{ row }">
|
||||
<div class="cell-main">{{ row.patient_name || '—' }}</div>
|
||||
<div class="cell-sub">诊单 #{{ row.diagnosis_id }}</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="医助" min-width="100">
|
||||
<template #default="{ row }">{{ assistantText(row) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="部门" min-width="110" show-overflow-tooltip>
|
||||
<template #default="{ row }">{{ row.dept_name || '—' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="诊次" width="110" align="center">
|
||||
<template #header>
|
||||
<span>诊次</span>
|
||||
<el-tooltip
|
||||
placement="top"
|
||||
effect="dark"
|
||||
content="患者当前已完成诊次 = 有效业务订单数 + 诊单诊次偏移,与复诊接诊率同口径;下一行为待复诊诊次"
|
||||
>
|
||||
<el-icon class="col-hint"><InfoFilled /></el-icon>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
<template #default="{ row }">
|
||||
<div class="cell-main">{{ slotText(row) }}</div>
|
||||
<div v-if="Number(row.next_slot) > 0" class="cell-sub">
|
||||
待复诊第 {{ row.next_slot }} 诊
|
||||
</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="开药天数" width="110" align="center">
|
||||
<template #default="{ row }">
|
||||
<template v-if="Number(row.medication_days) > 0">
|
||||
<span>{{ row.medication_days }} 天</span>
|
||||
<el-tag
|
||||
v-if="Number(row.rule_days) > 0"
|
||||
size="small"
|
||||
type="info"
|
||||
effect="plain"
|
||||
class="ml-1"
|
||||
>
|
||||
{{ row.rule_days }} 档
|
||||
</el-tag>
|
||||
</template>
|
||||
<span v-else class="text-missing">缺开药天数</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="预计复诊" width="110">
|
||||
<template #default="{ row }">
|
||||
<div class="cell-main">{{ row.due_date || '—' }}</div>
|
||||
<div v-if="row.anchor_date" class="cell-sub">
|
||||
起算 {{ formatRevisitMonthDay(row.anchor_date) }}
|
||||
</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="超期天数" width="100" align="center">
|
||||
<template #default="{ row }">
|
||||
<span :class="['overdue-cell', overdueCell(row).cls]">
|
||||
{{ overdueCell(row).text }}
|
||||
</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="状态" min-width="150">
|
||||
<template #default="{ row }">
|
||||
<el-tag
|
||||
:type="revisitStateTagType(row.state)"
|
||||
:effect="revisitStateTagEffect(row.state)"
|
||||
size="small"
|
||||
:class="revisitStateChipClass(dueOf(row))"
|
||||
>
|
||||
{{ chipText(row) }}
|
||||
</el-tag>
|
||||
<el-tag
|
||||
v-if="Number(row.closed_state) === 4"
|
||||
size="small"
|
||||
type="info"
|
||||
effect="plain"
|
||||
class="ml-1"
|
||||
>
|
||||
人工关闭
|
||||
</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="延迟次数" width="100" align="center">
|
||||
<template #header>
|
||||
<span>延迟次数</span>
|
||||
<el-tooltip
|
||||
placement="top"
|
||||
effect="dark"
|
||||
content="医助在到期弹窗上点「延迟」的累计次数;1~2 次 L1、3~4 次 L2、≥5 次 L3(居中强制模态)。换医助后清零"
|
||||
>
|
||||
<el-icon class="col-hint"><InfoFilled /></el-icon>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
<template #default="{ row }">
|
||||
<span :class="['snooze-cell', snoozeClass(row)]">
|
||||
{{ Number(row.snooze_count ?? 0) }}
|
||||
</span>
|
||||
<div v-if="Number(row.escalation_level) > 0" class="cell-sub">
|
||||
等级 L{{ row.escalation_level }}
|
||||
</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="已联系" width="80" align="center">
|
||||
<template #default="{ row }">{{ Number(row.contact_count ?? 0) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="承诺日" width="100">
|
||||
<template #default="{ row }">{{ row.promised_date || '—' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="过号" width="70" align="center">
|
||||
<template #default="{ row }">{{ Number(row.missed_count ?? 0) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="关闭原因" min-width="170" show-overflow-tooltip>
|
||||
<template #default="{ row }">
|
||||
<template v-if="Number(row.closed_state) === 4">
|
||||
<span>{{ handleReasonText(row.handle_reason) }}</span>
|
||||
<span v-if="row.handle_remark" class="cell-sub">
|
||||
:{{ row.handle_remark }}
|
||||
</span>
|
||||
</template>
|
||||
<span v-else-if="Number(row.closed_state) > 0" class="cell-sub">
|
||||
{{ row.closed_state_text || '—' }}
|
||||
</span>
|
||||
<span v-else>—</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="130" fixed="right" align="center">
|
||||
<template #default="{ row }">
|
||||
<el-button
|
||||
v-perms="['tcm.revisitDue/logs']"
|
||||
link
|
||||
type="primary"
|
||||
@click="openLogs(row)"
|
||||
>
|
||||
流水
|
||||
</el-button>
|
||||
<el-button link type="primary" @click="goDiagnosis(row)">去诊单</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
<div class="flex justify-end mt-4">
|
||||
<pagination v-model="pager" @change="getLists" />
|
||||
</div>
|
||||
</el-card>
|
||||
|
||||
<el-drawer
|
||||
v-model="logVisible"
|
||||
:title="logTitle"
|
||||
direction="rtl"
|
||||
size="540px"
|
||||
destroy-on-close
|
||||
>
|
||||
<div v-loading="logLoading" class="log-drawer-body">
|
||||
<div v-if="logRow" class="log-summary">
|
||||
<div class="log-summary-row">
|
||||
<span>医助:{{ assistantText(logRow) }}</span>
|
||||
<span>{{ slotText(logRow) }}</span>
|
||||
<span v-if="logRow.due_date">预计复诊 {{ logRow.due_date }}</span>
|
||||
</div>
|
||||
<div class="log-summary-row">
|
||||
<el-tag
|
||||
:type="revisitStateTagType(logRow.state)"
|
||||
:effect="revisitStateTagEffect(logRow.state)"
|
||||
size="small"
|
||||
:class="revisitStateChipClass(dueOf(logRow))"
|
||||
>
|
||||
{{ chipText(logRow) }}
|
||||
</el-tag>
|
||||
<span class="cell-sub">{{ followCountText(logRow) }}</span>
|
||||
</div>
|
||||
<div v-if="hasShownMeta(logRow)" class="log-summary-row cell-sub">
|
||||
<span v-if="logRow.first_shown_at_text">
|
||||
首次弹出 {{ logRow.first_shown_at_text }}
|
||||
</span>
|
||||
<span v-if="logRow.last_snoozed_at_text">
|
||||
最近延迟 {{ logRow.last_snoozed_at_text }}
|
||||
</span>
|
||||
<span v-if="logRow.computed_at_text">
|
||||
重算于 {{ logRow.computed_at_text }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<el-timeline v-if="logRows.length" class="mt-3">
|
||||
<el-timeline-item
|
||||
v-for="item in logRows"
|
||||
:key="item.id"
|
||||
:timestamp="item.create_time_text"
|
||||
placement="top"
|
||||
:type="eventTimelineType(item.event)"
|
||||
:hollow="!isUserEvent(item.event)"
|
||||
>
|
||||
<div class="log-event">
|
||||
<span class="log-event-title">
|
||||
{{ item.event_text || eventLabel(item.event) }}
|
||||
</span>
|
||||
<span class="log-event-operator">{{ operatorText(item) }}</span>
|
||||
</div>
|
||||
<div class="log-event-meta">
|
||||
<span>延迟 {{ Number(item.snooze_count_after ?? 0) }} 次</span>
|
||||
<span>等级 L{{ Number(item.level_after ?? 0) }}</span>
|
||||
<span>{{ logOverdueText(item.overdue_days) }}</span>
|
||||
</div>
|
||||
<div v-if="payloadEntries(item).length" class="log-event-payload">
|
||||
<span
|
||||
v-for="p in payloadEntries(item)"
|
||||
:key="p.key"
|
||||
class="log-payload-chip"
|
||||
>
|
||||
{{ p.label }}:{{ p.value }}
|
||||
</span>
|
||||
</div>
|
||||
</el-timeline-item>
|
||||
</el-timeline>
|
||||
<el-empty v-else-if="!logLoading" description="暂无流水" :image-size="80" />
|
||||
</div>
|
||||
</el-drawer>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts" name="statsRevisitDue">
|
||||
import { InfoFilled } from '@element-plus/icons-vue'
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import {
|
||||
revisitDueLists,
|
||||
revisitDueLogs,
|
||||
type RevisitDueListRow,
|
||||
type RevisitDueListsParams,
|
||||
type RevisitDueLogRow
|
||||
} from '@/api/revisitDue'
|
||||
import { revisitRateDeptOptions } from '@/api/stats'
|
||||
import { getAssistants } from '@/api/tcm'
|
||||
import { usePaging } from '@/hooks/usePaging'
|
||||
import {
|
||||
REVISIT_DAYS_BUCKET_OPTIONS,
|
||||
REVISIT_STATE_FILTER_OPTIONS,
|
||||
formatRevisitMonthDay,
|
||||
normalizeRevisitDue,
|
||||
revisitRowClassName,
|
||||
revisitStateChipClass,
|
||||
revisitStateChipText,
|
||||
revisitStateTagEffect,
|
||||
revisitStateTagType,
|
||||
type RevisitDue
|
||||
} from '@/utils/revisitDue'
|
||||
|
||||
interface DeptTreeNode {
|
||||
id: number
|
||||
name: string
|
||||
pid: number
|
||||
children?: DeptTreeNode[]
|
||||
}
|
||||
|
||||
const router = useRouter()
|
||||
|
||||
/** 状态筛选:诊单列表的 7 个状态 + 主管视图专有「人工关闭」 */
|
||||
const stateOptions = [...REVISIT_STATE_FILTER_OPTIONS, { label: '人工关闭', value: 'closed' }]
|
||||
|
||||
const assistantOptions = ref<Array<{ id: number; name: string }>>([])
|
||||
const deptTreeOptions = ref<DeptTreeNode[]>([])
|
||||
const deptTreeProps = { value: 'id', label: 'name', children: 'children' }
|
||||
|
||||
const queryParams = reactive<RevisitDueListsParams>({
|
||||
assistant_id: '',
|
||||
dept_id: '',
|
||||
state: '',
|
||||
days_bucket: '',
|
||||
min_snooze: '',
|
||||
keyword: ''
|
||||
})
|
||||
/** el-input-number 清空时为 null/undefined,单独持有后再写回 queryParams 的 '' */
|
||||
const minSnooze = ref<number | undefined>(undefined)
|
||||
|
||||
const { pager, getLists, resetPage } = usePaging({
|
||||
fetchFun: revisitDueLists,
|
||||
params: queryParams
|
||||
})
|
||||
|
||||
const doSearch = () => resetPage()
|
||||
|
||||
const onMinSnoozeChange = (val: number | undefined | null) => {
|
||||
queryParams.min_snooze = val === null || val === undefined ? '' : Number(val)
|
||||
doSearch()
|
||||
}
|
||||
|
||||
const handleReset = () => {
|
||||
queryParams.assistant_id = ''
|
||||
queryParams.dept_id = ''
|
||||
queryParams.state = ''
|
||||
queryParams.days_bucket = ''
|
||||
queryParams.min_snooze = ''
|
||||
queryParams.keyword = ''
|
||||
minSnooze.value = undefined
|
||||
doSearch()
|
||||
}
|
||||
|
||||
// ── 单元格 ──────────────────────────────────────────
|
||||
/** 列表行 → 复诊节点对象(复用 utils/revisitDue 的 chip 映射;缺失字段按默认值补齐) */
|
||||
const dueOf = (row: RevisitDueListRow | Record<string, any>): RevisitDue | null =>
|
||||
normalizeRevisitDue(row)
|
||||
|
||||
const rowClassName = ({ row }: { row: RevisitDueListRow }) => revisitRowClassName(dueOf(row))
|
||||
|
||||
const assistantText = (row: RevisitDueListRow) =>
|
||||
row.assistant_name || (Number(row.assistant_id) > 0 ? `#${row.assistant_id}` : '—')
|
||||
|
||||
const slotText = (row: RevisitDueListRow) => {
|
||||
const slot = Number(row.current_slot ?? 0)
|
||||
return slot > 0 ? `第 ${slot} 诊` : '未成交'
|
||||
}
|
||||
|
||||
const chipText = (row: RevisitDueListRow) =>
|
||||
revisitStateChipText(dueOf(row)) || row.state_text || '—'
|
||||
|
||||
/** 抽屉摘要:「延迟 N 次 · 已联系 N 次 · 过号 N 次」 */
|
||||
const followCountText = (row: RevisitDueListRow) => {
|
||||
const snooze = Number(row.snooze_count ?? 0)
|
||||
const contact = Number(row.contact_count ?? 0)
|
||||
const missed = Number(row.missed_count ?? 0)
|
||||
return `延迟 ${snooze} 次 · 已联系 ${contact} 次 · 过号 ${missed} 次`
|
||||
}
|
||||
|
||||
const hasShownMeta = (row: RevisitDueListRow) =>
|
||||
!!(row.first_shown_at_text || row.last_snoozed_at_text || row.computed_at_text)
|
||||
|
||||
const toNullableNumber = (v: unknown): number | null => {
|
||||
if (v === null || v === undefined || v === '') return null
|
||||
const n = Number(v)
|
||||
return Number.isFinite(n) ? n : null
|
||||
}
|
||||
|
||||
/** 超期天数列:到期/过号红字(深红 = severe),其它状态显示剩余天数或历史超期 */
|
||||
const overdueCell = (row: RevisitDueListRow): { text: string; cls: string } => {
|
||||
const od = toNullableNumber(row.overdue_days)
|
||||
const dl = toNullableNumber(row.days_left)
|
||||
const isDue = row.state === 'overdue' || row.state === 'missed'
|
||||
if (isDue && od !== null && od >= 0) {
|
||||
return {
|
||||
text: od === 0 ? '今日到期' : `${od} 天`,
|
||||
cls: Number(row.severe) === 1 ? 'is-severe' : 'is-overdue'
|
||||
}
|
||||
}
|
||||
if (od !== null && od > 0) {
|
||||
return { text: `${od} 天`, cls: 'is-muted' }
|
||||
}
|
||||
if (dl !== null && dl >= 0) {
|
||||
return { text: `剩 ${dl} 天`, cls: 'is-muted' }
|
||||
}
|
||||
return { text: '—', cls: '' }
|
||||
}
|
||||
|
||||
const snoozeClass = (row: RevisitDueListRow) => {
|
||||
const level = Number(row.escalation_level ?? 0)
|
||||
if (level >= 3) return 'is-level-3'
|
||||
if (level === 2) return 'is-level-2'
|
||||
if (level === 1) return 'is-level-1'
|
||||
return ''
|
||||
}
|
||||
|
||||
const handleReasonText = (reason: string | null | undefined) => {
|
||||
const key = String(reason ?? '').trim()
|
||||
if (key === 'lost') return '患者流失'
|
||||
if (key === 'other') return '其它'
|
||||
return key || '人工关闭'
|
||||
}
|
||||
|
||||
// ── 流水抽屉 ──────────────────────────────────────────
|
||||
const logVisible = ref(false)
|
||||
const logLoading = ref(false)
|
||||
const logRow = ref<RevisitDueListRow | null>(null)
|
||||
const logRows = ref<RevisitDueLogRow[]>([])
|
||||
|
||||
const logTitle = computed(() =>
|
||||
logRow.value ? `${logRow.value.patient_name || '患者'} · 复诊到期流水` : '复诊到期流水'
|
||||
)
|
||||
|
||||
const EVENT_LABEL: Record<number, string> = {
|
||||
1: '延迟',
|
||||
2: '已联系',
|
||||
3: '人工关闭',
|
||||
4: '自动关闭 · 已挂号',
|
||||
5: '自动关闭 · 已面诊',
|
||||
6: '周期重置(新订单)',
|
||||
7: '重新打开(挂号取消 / 过号)',
|
||||
8: '企微推送',
|
||||
9: '医助变更',
|
||||
10: '形态升级',
|
||||
11: '首次弹出'
|
||||
}
|
||||
|
||||
const eventLabel = (event: number) => EVENT_LABEL[Number(event)] ?? `事件 ${event}`
|
||||
|
||||
/** 1 延迟 / 2 已联系 / 3 人工关闭 由医助操作,实心节点;其余系统事件空心 */
|
||||
const isUserEvent = (event: number) => [1, 2, 3].includes(Number(event))
|
||||
|
||||
type TimelineType = 'primary' | 'success' | 'warning' | 'danger' | 'info'
|
||||
|
||||
const eventTimelineType = (event: number): TimelineType => {
|
||||
switch (Number(event)) {
|
||||
case 1:
|
||||
return 'warning'
|
||||
case 2:
|
||||
case 6:
|
||||
return 'primary'
|
||||
case 4:
|
||||
case 5:
|
||||
return 'success'
|
||||
case 7:
|
||||
case 10:
|
||||
return 'danger'
|
||||
default:
|
||||
return 'info'
|
||||
}
|
||||
}
|
||||
|
||||
const operatorText = (item: RevisitDueLogRow) => {
|
||||
if (item.operator_name) return item.operator_name
|
||||
return Number(item.operator_id) > 0 ? `#${item.operator_id}` : '系统'
|
||||
}
|
||||
|
||||
const logOverdueText = (days: number | null | undefined) => {
|
||||
const n = toNullableNumber(days)
|
||||
if (n === null) return ''
|
||||
if (n > 0) return `超期 ${n} 天`
|
||||
if (n === 0) return '到期当天'
|
||||
return `未到期(剩 ${-n} 天)`
|
||||
}
|
||||
|
||||
const PAYLOAD_LABEL: Record<string, string> = {
|
||||
next_remind_at: '下次提醒',
|
||||
next_remind_at_text: '下次提醒',
|
||||
promised_date: '承诺日',
|
||||
appointment_id: '挂号单',
|
||||
appointment_date: '预约日',
|
||||
order_id: '订单',
|
||||
source_order_id: '周期订单',
|
||||
remark: '备注',
|
||||
reason: '原因',
|
||||
from_assistant: '原医助',
|
||||
from_assistant_id: '原医助',
|
||||
to_assistant: '新医助',
|
||||
to_assistant_id: '新医助',
|
||||
interval: '间隔(秒)',
|
||||
level: '等级',
|
||||
channel: '渠道',
|
||||
message: '说明'
|
||||
}
|
||||
|
||||
const formatPayloadValue = (key: string, value: unknown): string => {
|
||||
if (value === null || value === undefined || value === '') return ''
|
||||
if (typeof value === 'object') return JSON.stringify(value)
|
||||
// 秒级时间戳(next_remind_at 等)转本地时间
|
||||
if (/_at$/.test(key) && typeof value === 'number' && value > 1e9) {
|
||||
const d = new Date(value * 1000)
|
||||
const pad = (n: number) => String(n).padStart(2, '0')
|
||||
const date = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
|
||||
return `${date} ${pad(d.getHours())}:${pad(d.getMinutes())}`
|
||||
}
|
||||
return String(value)
|
||||
}
|
||||
|
||||
interface PayloadEntry {
|
||||
key: string
|
||||
label: string
|
||||
value: string
|
||||
}
|
||||
|
||||
/** payload_arr → [{key,label,value}],有 *_text 版本时隐藏对应原始时间戳 */
|
||||
const payloadEntries = (item: RevisitDueLogRow): PayloadEntry[] => {
|
||||
const payload = item.payload_arr
|
||||
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return []
|
||||
const out: PayloadEntry[] = []
|
||||
for (const [key, raw] of Object.entries(payload)) {
|
||||
if (`${key}_text` in payload) continue
|
||||
const value = formatPayloadValue(key, raw)
|
||||
if (value === '') continue
|
||||
out.push({ key, label: PAYLOAD_LABEL[key] ?? key, value })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
const openLogs = async (row: RevisitDueListRow) => {
|
||||
logRow.value = row
|
||||
logVisible.value = true
|
||||
logLoading.value = true
|
||||
logRows.value = []
|
||||
try {
|
||||
// 契约「返回 list」:兼容直接返回数组或 { list } / { lists } 包络
|
||||
const res: any = await revisitDueLogs({ due_id: Number(row.id) })
|
||||
const list = Array.isArray(res) ? res : (res?.list ?? res?.lists ?? [])
|
||||
logRows.value = Array.isArray(list) ? list : []
|
||||
} finally {
|
||||
logLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const goDiagnosis = (row: RevisitDueListRow) => {
|
||||
const id = Number(row.diagnosis_id ?? 0)
|
||||
if (id <= 0) return
|
||||
router.push({ path: '/tcm/diagnosis', query: { id: String(id) } })
|
||||
}
|
||||
|
||||
// ── 下拉数据 ──────────────────────────────────────────
|
||||
const buildDeptTree = (flat: Array<{ id: number; pid: number; name: string }>): DeptTreeNode[] => {
|
||||
const map = new Map<number, DeptTreeNode>()
|
||||
for (const d of flat) {
|
||||
map.set(Number(d.id), { id: Number(d.id), pid: Number(d.pid), name: d.name, children: [] })
|
||||
}
|
||||
const roots: DeptTreeNode[] = []
|
||||
for (const d of flat) {
|
||||
const node = map.get(Number(d.id))!
|
||||
if (Number(d.pid) > 0 && map.has(Number(d.pid))) {
|
||||
map.get(Number(d.pid))!.children!.push(node)
|
||||
} else {
|
||||
roots.push(node)
|
||||
}
|
||||
}
|
||||
const strip = (n: DeptTreeNode) => {
|
||||
if (n.children?.length) {
|
||||
n.children.forEach(strip)
|
||||
} else {
|
||||
delete n.children
|
||||
}
|
||||
}
|
||||
roots.forEach(strip)
|
||||
return roots
|
||||
}
|
||||
|
||||
const loadOptions = async () => {
|
||||
const [assistants, depts] = await Promise.allSettled([
|
||||
getAssistants(),
|
||||
revisitRateDeptOptions()
|
||||
])
|
||||
if (assistants.status === 'fulfilled') {
|
||||
assistantOptions.value = Array.isArray(assistants.value) ? assistants.value : []
|
||||
}
|
||||
if (depts.status === 'fulfilled') {
|
||||
deptTreeOptions.value = buildDeptTree(depts.value?.rows ?? [])
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
// 下拉与列表并行加载,不阻塞首屏
|
||||
void loadOptions()
|
||||
getLists()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.revisit-due-page {
|
||||
.due-filter-form {
|
||||
:deep(.el-form-item) {
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
}
|
||||
|
||||
.due-hint {
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.cell-main {
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.cell-sub {
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.col-hint {
|
||||
margin-left: 2px;
|
||||
vertical-align: -2px;
|
||||
color: var(--el-text-color-secondary);
|
||||
cursor: help;
|
||||
}
|
||||
|
||||
.text-missing {
|
||||
color: #ea580c;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.overdue-cell.is-overdue {
|
||||
color: var(--el-color-danger);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.overdue-cell.is-severe {
|
||||
color: #b91c1c;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.overdue-cell.is-muted {
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.snooze-cell {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.snooze-cell.is-level-1 {
|
||||
color: #ea580c;
|
||||
}
|
||||
|
||||
.snooze-cell.is-level-2 {
|
||||
color: var(--el-color-danger);
|
||||
}
|
||||
|
||||
.snooze-cell.is-level-3 {
|
||||
color: #b91c1c;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
/* 行级标红:与诊单列表一致(utils/revisitDue.ts revisitRowClassName) */
|
||||
:deep(.el-table__row.row-revisit-overdue) {
|
||||
border-left: 3px solid var(--el-color-danger);
|
||||
background: linear-gradient(90deg, rgba(var(--el-color-danger-rgb), 0.06) 0%, transparent 100%) !important;
|
||||
}
|
||||
|
||||
:deep(.el-table__row.row-revisit-overdue:hover > td) {
|
||||
background: linear-gradient(90deg, rgba(var(--el-color-danger-rgb), 0.1) 0%, transparent 100%) !important;
|
||||
}
|
||||
|
||||
:deep(.el-table__row.row-revisit-overdue.row-revisit-overdue-deep) {
|
||||
border-left-color: #b91c1c;
|
||||
background: linear-gradient(90deg, rgba(var(--el-color-danger-rgb), 0.1) 0%, transparent 100%) !important;
|
||||
}
|
||||
|
||||
:deep(.el-table__row.row-revisit-overdue.row-revisit-overdue-deep:hover > td) {
|
||||
background: linear-gradient(90deg, rgba(var(--el-color-danger-rgb), 0.14) 0%, transparent 100%) !important;
|
||||
}
|
||||
|
||||
/* 状态 chip 配色:与 RevisitNodeCell 一致 */
|
||||
:deep(.rv-chip) {
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
:deep(.rv-chip--overdue),
|
||||
:deep(.rv-chip--missed) {
|
||||
--el-tag-bg-color: #dc2626;
|
||||
--el-tag-border-color: #dc2626;
|
||||
}
|
||||
|
||||
:deep(.rv-chip--severe) {
|
||||
font-weight: 700;
|
||||
--el-tag-bg-color: #b91c1c;
|
||||
--el-tag-border-color: #b91c1c;
|
||||
}
|
||||
|
||||
:deep(.rv-chip--warning) {
|
||||
--el-tag-text-color: #ea580c;
|
||||
--el-tag-bg-color: rgba(234, 88, 12, 0.1);
|
||||
--el-tag-border-color: rgba(234, 88, 12, 0.3);
|
||||
}
|
||||
|
||||
:deep(.rv-chip--no_days) {
|
||||
--el-tag-text-color: #ea580c;
|
||||
--el-tag-border-color: #ea580c;
|
||||
}
|
||||
|
||||
:deep(.rv-chip--visited) {
|
||||
--el-tag-text-color: #16a34a;
|
||||
--el-tag-bg-color: rgba(22, 163, 74, 0.1);
|
||||
--el-tag-border-color: rgba(22, 163, 74, 0.3);
|
||||
}
|
||||
|
||||
:deep(.rv-chip--booked) {
|
||||
--el-tag-text-color: #4a5dff;
|
||||
--el-tag-bg-color: rgba(74, 93, 255, 0.1);
|
||||
--el-tag-border-color: rgba(74, 93, 255, 0.3);
|
||||
}
|
||||
}
|
||||
|
||||
.log-drawer-body {
|
||||
min-height: 200px;
|
||||
}
|
||||
|
||||
.log-summary {
|
||||
padding: 12px 14px;
|
||||
border-radius: 8px;
|
||||
background: var(--el-fill-color-light);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.log-summary-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 6px 14px;
|
||||
}
|
||||
|
||||
.log-event {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.log-event-title {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: var(--el-text-color-primary);
|
||||
}
|
||||
|
||||
.log-event-operator {
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.log-event-meta {
|
||||
margin-top: 4px;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px 12px;
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
|
||||
.log-event-payload {
|
||||
margin-top: 6px;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.log-payload-chip {
|
||||
font-size: 12px;
|
||||
line-height: 20px;
|
||||
padding: 0 8px;
|
||||
border-radius: 4px;
|
||||
background: var(--el-fill-color);
|
||||
color: var(--el-text-color-regular);
|
||||
word-break: break-all;
|
||||
}
|
||||
</style>
|
||||
@@ -1,7 +0,0 @@
|
||||
<template>
|
||||
<cohort-report cohort-type="inherit" />
|
||||
</template>
|
||||
|
||||
<script setup lang="ts" name="revisitInheritRateStatsPage">
|
||||
import CohortReport from '../revisit_assign_rate/components/CohortReport.vue'
|
||||
</script>
|
||||
@@ -29,18 +29,12 @@
|
||||
@change="loadData"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item label="口径">
|
||||
<el-radio-group v-model="inheritMode" size="small" @change="loadData">
|
||||
<el-radio-button value="exclude">原口径(继承不计分母)</el-radio-button>
|
||||
<el-radio-button value="slot">新口径(继承按继承时诊次计入)</el-radio-button>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-button type="primary" :loading="loading" @click="loadData">查询</el-button>
|
||||
<el-button :disabled="loading" @click="handleReset">重置</el-button>
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-popover placement="bottom-start" :width="560" trigger="hover">
|
||||
<el-popover placement="bottom-start" :width="500" trigger="hover">
|
||||
<template #reference>
|
||||
<span class="rate-caliber-trigger">
|
||||
<el-icon><InfoFilled /></el-icon>
|
||||
@@ -49,29 +43,16 @@
|
||||
</template>
|
||||
<div class="rate-caliber">
|
||||
<p>
|
||||
<b>{{ isSlotMode ? '新指派数' : '当月被指派数' }}</b>:当月内诊单被指派给医助(按指派操作时间落月,<b>不含勾选「继承」的指派</b>)的诊单数,按「医助 × 诊单」去重;部门行 / 合计行按诊单去重;<b>再剔除</b>名下存在履约「拒收 / 退款」业务订单的诊单。与业绩看板「被指派数」同口径。
|
||||
</p>
|
||||
<template v-if="isSlotMode">
|
||||
<p>
|
||||
<b>继承数</b>:当月勾选「继承」转接给该医助的诊单数(同一诊单多次继承取最早;同月既新指派又继承给同一医助只算新指派;历史「回退自动分配」行按继承处理;指派给自己的记录忽略)。<b>继承时诊次 k</b> = 继承时刻之前患者已完成的诊次(有效实单数 + 偏移),<b>起算诊次 = max(2, k+1)</b>:继承者只对第 k+1 诊及以后负责。
|
||||
</p>
|
||||
<p>
|
||||
<b>N 诊分母</b> = 新指派数 + 起算诊次 ≤ N 的继承数(每列独立);<b>N 诊接诊率</b> = N 诊单数 ÷ N 诊分母,分母为 0 显示「—」。<b>复诊合计</b>:单数 = 各诊次单数之和,分母 = 新指派 ∪ 继承(被指派合计),比率可超过 100%(人均复诊成交单数)。
|
||||
</p>
|
||||
<p class="rate-caliber-note">
|
||||
继承分母依赖指派记录的「继承」标记(2026-06 起写入),之前的转接无法回溯;切换为「旧口径」可对照上线前数字。
|
||||
</p>
|
||||
</template>
|
||||
<template v-else>
|
||||
<p>
|
||||
<b>旧口径</b>:继承指派不计入分母,N 诊分母 = 新指派数(对所有 N 相同),新指派数 / N 诊单数 / N 诊接诊率与 2026-10 之前完全一致;继承数恒为 0。切换为「新口径」后继承按继承时诊次计入每列独立分母。
|
||||
</p>
|
||||
</template>
|
||||
<p>
|
||||
<b>诊次(第 N 次下单)</b>:患者(诊单)名下计入业绩的业务订单(剔除已取消 / 拒收 / 退款)按下单时间升序编号为「实单序号」,<b>统计诊次 = 实单序号 + 诊单偏移</b>(默认偏移 0 → 第 1 笔实单为一诊)。诊次<b>跨月累计不重置</b>。诊单可在「业务订单」tab 配置偏移量。
|
||||
<b>当月被指派总数</b>:当月内诊单被指派给医助(按指派操作时间落月,<b>剔除勾选「继承」的指派</b>)的诊单数,按「医助 × 诊单」去重;部门行 / 合计行按诊单去重;<b>再剔除</b>名下存在履约「拒收 / 退款」业务订单的诊单。
|
||||
</p>
|
||||
<p>
|
||||
<b>当月 N 诊单数</b>:当月内下单且诊次为 N 的订单数,归属下单时点<b>持有该患者的医助</b>(指派可在往月;释放后不再归属;继承会转移持有人)。往月指派、当月成交会推高分子,比率可能超过 100%。
|
||||
<b>诊次(第 N 次下单)</b>:患者(诊单)名下计入业绩的业务订单(剔除已取消 / 拒收 / 退款)按下单时间升序编号为「实单序号」,<b>统计诊次 = 实单序号 + 诊单偏移</b>(默认偏移 0 → 第 1 笔实单为一诊;偏移 1 → 第 1 笔实单为二诊;偏移 2 → 第 1 笔实单为三诊,5 笔实单等价七诊)。诊次<b>跨月累计不重置</b>。诊单可在「业务订单」tab 配置偏移量。
|
||||
</p>
|
||||
<p>
|
||||
<b>当月 N 诊单数</b>:当月内下单且诊次为 N 的订单数,归属下单时点<b>持有该患者的医助</b>(指派可在往月;释放后不再归属;「继承」指派会转移持有人但不计被指派数)。
|
||||
</p>
|
||||
<p>
|
||||
<b>当月 N 诊接诊率</b> = 当月 N 诊单数 ÷ 当月被指派总数。往月指派、当月成交会推高分子,比率可能超过 100%;医助当月无新指派但旗下有成交时,被指派数为 0、比率显示「—」。
|
||||
</p>
|
||||
<p>
|
||||
医助按人事部门归组;<b>仅统计「二中心」及其组织下级</b>;部门下拉与未选时的默认范围均限定在该子树,选定部门时含其组织下级。
|
||||
@@ -100,9 +81,7 @@
|
||||
<template #header>
|
||||
<div class="rate-card-header">
|
||||
<span>部门 · 医助明细({{ monthText }})</span>
|
||||
<span class="rate-card-hint">
|
||||
点击「新指派数 / 继承数 / 被指派合计 / N诊单数 / 复诊合计单数」可查看具体诊单与订单;接诊率下方灰字为「单数 / 分母」;底栏合计按诊单去重
|
||||
</span>
|
||||
<span class="rate-card-hint">点击「被指派数 / N诊单数」可查看具体诊单与订单;底栏合计的被指派数按诊单去重</span>
|
||||
</div>
|
||||
</template>
|
||||
<el-table
|
||||
@@ -125,88 +104,19 @@
|
||||
<span v-else>{{ row.assistant_name }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column
|
||||
prop="assigned_count"
|
||||
:label="isSlotMode ? '新指派数' : '当月被指派数'"
|
||||
min-width="96"
|
||||
align="right"
|
||||
>
|
||||
<template #header>
|
||||
<span>{{ isSlotMode ? '新指派数' : '当月被指派数' }}</span>
|
||||
<el-tooltip
|
||||
effect="dark"
|
||||
placement="top"
|
||||
content="当月非继承指派的「医助 × 诊单」去重数(剔除名下有拒收/退款订单的诊单),与业绩看板「被指派数」同口径"
|
||||
>
|
||||
<el-icon class="rate-th-hint"><InfoFilled /></el-icon>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
<el-table-column prop="assigned_count" label="当月被指派数" min-width="110" align="right">
|
||||
<template #default="{ row }">
|
||||
<el-link
|
||||
v-if="canViewAssignLines && row.assigned_count > 0"
|
||||
type="primary"
|
||||
:underline="false"
|
||||
@click="openAssignDetail(row, 'new')"
|
||||
@click="openAssignDetail(row)"
|
||||
>
|
||||
{{ row.assigned_count }}
|
||||
</el-link>
|
||||
<span v-else>{{ row.assigned_count }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column
|
||||
v-if="isSlotMode"
|
||||
prop="inherit_count"
|
||||
label="继承数"
|
||||
min-width="88"
|
||||
align="right"
|
||||
>
|
||||
<template #header>
|
||||
<span>继承数</span>
|
||||
<el-tooltip
|
||||
effect="dark"
|
||||
placement="top"
|
||||
content="当月勾选「继承」转接给该医助的诊单数(按继承时诊次 k 从第 k+1 诊起计入分母;点击查看每条的继承时诊次与起算诊次)"
|
||||
>
|
||||
<el-icon class="rate-th-hint"><InfoFilled /></el-icon>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
<template #default="{ row }">
|
||||
<el-link
|
||||
v-if="canViewAssignLines && row.inherit_count > 0"
|
||||
type="primary"
|
||||
:underline="false"
|
||||
@click="openAssignDetail(row, 'inherit')"
|
||||
>
|
||||
{{ row.inherit_count }}
|
||||
</el-link>
|
||||
<span v-else>{{ row.inherit_count ?? 0 }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column
|
||||
v-if="isSlotMode"
|
||||
prop="assigned_total_count"
|
||||
label="被指派合计"
|
||||
min-width="100"
|
||||
align="right"
|
||||
>
|
||||
<template #header>
|
||||
<span>被指派合计</span>
|
||||
<el-tooltip effect="dark" placement="top" content="新指派 ∪ 继承(按诊单去重),即「复诊合计接诊率」的分母">
|
||||
<el-icon class="rate-th-hint"><InfoFilled /></el-icon>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
<template #default="{ row }">
|
||||
<el-link
|
||||
v-if="canViewAssignLines && row.assigned_total_count > 0"
|
||||
type="primary"
|
||||
:underline="false"
|
||||
@click="openAssignDetail(row, 'all')"
|
||||
>
|
||||
{{ row.assigned_total_count }}
|
||||
</el-link>
|
||||
<span v-else>{{ row.assigned_total_count ?? 0 }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<template v-for="slot in visitSlots" :key="slot">
|
||||
<el-table-column
|
||||
:prop="`visit${slot}_count`"
|
||||
@@ -239,64 +149,12 @@
|
||||
<el-table-column
|
||||
:prop="`visit${slot}_rate`"
|
||||
:label="`${slotLabel(slot)}接诊率`"
|
||||
min-width="104"
|
||||
min-width="96"
|
||||
align="right"
|
||||
>
|
||||
<template #header>
|
||||
<span>{{ slotLabel(slot) }}接诊率</span>
|
||||
<el-tooltip effect="dark" placement="top" :content="rateHeaderTip(slot)">
|
||||
<el-icon class="rate-th-hint"><InfoFilled /></el-icon>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
<template #default="{ row }">
|
||||
<div class="rate-cell">
|
||||
<span class="rate-cell-main">{{ formatRate(row[`visit${slot}_rate`]) }}</span>
|
||||
<span v-if="isSlotMode" class="rate-cell-sub">{{ denText(row, `visit${slot}`) }}</span>
|
||||
</div>
|
||||
</template>
|
||||
<template #default="{ row }">{{ formatRate(row[`visit${slot}_rate`]) }}</template>
|
||||
</el-table-column>
|
||||
</template>
|
||||
<el-table-column prop="visit_all_count" label="复诊合计单数" min-width="110" align="right">
|
||||
<template #header>
|
||||
<span>复诊合计单数</span>
|
||||
<el-tooltip effect="dark" placement="top" content="当月内下单、诊次 ≥ 2 的订单数之和(= 各 N 诊单数之和)">
|
||||
<el-icon class="rate-th-hint"><InfoFilled /></el-icon>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
<template #default="{ row }">
|
||||
<el-link
|
||||
v-if="canViewOrderLines && row.visit_all_count > 0"
|
||||
type="primary"
|
||||
:underline="false"
|
||||
@click="openOrderDetail(0, row)"
|
||||
>
|
||||
{{ row.visit_all_count }}
|
||||
</el-link>
|
||||
<span v-else>{{ row.visit_all_count ?? 0 }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="visit_all_rate" label="复诊合计接诊率" min-width="118" align="right">
|
||||
<template #header>
|
||||
<span>复诊合计接诊率</span>
|
||||
<el-tooltip
|
||||
effect="dark"
|
||||
placement="top"
|
||||
:content="
|
||||
isSlotMode
|
||||
? '复诊合计单数 ÷ 被指派合计(新指派 ∪ 继承);可超过 100%,语义为人均复诊成交单数'
|
||||
: '复诊合计单数 ÷ 新指派数(旧口径继承不计分母);可超过 100%'
|
||||
"
|
||||
>
|
||||
<el-icon class="rate-th-hint"><InfoFilled /></el-icon>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
<template #default="{ row }">
|
||||
<div class="rate-cell">
|
||||
<span class="rate-cell-main">{{ formatRate(row.visit_all_rate) }}</span>
|
||||
<span v-if="isSlotMode" class="rate-cell-sub">{{ denText(row, 'visit_all') }}</span>
|
||||
</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</el-card>
|
||||
|
||||
@@ -304,7 +162,7 @@
|
||||
<el-dialog
|
||||
v-model="detailVisible"
|
||||
:title="detailTitle"
|
||||
width="1080px"
|
||||
width="980px"
|
||||
top="6vh"
|
||||
destroy-on-close
|
||||
>
|
||||
@@ -335,33 +193,6 @@
|
||||
<template #default="{ row }">{{ row.patient_phone || '—' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="assistant_names" label="被指派医助" min-width="140" show-overflow-tooltip />
|
||||
<el-table-column v-if="isSlotMode" prop="assign_type" label="指派类型" width="110" align="center">
|
||||
<template #default="{ row }">
|
||||
<el-tag :type="row.assign_type === 'inherit' ? 'warning' : 'success'" size="small">
|
||||
{{ row.assign_type_text || (row.assign_type === 'inherit' ? '继承' : '新指派') }}
|
||||
</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column v-if="isSlotMode" prop="inherit_visit_slot" label="继承时诊次" width="100" align="center">
|
||||
<template #header>
|
||||
<span>继承时诊次</span>
|
||||
<el-tooltip effect="dark" placement="top" content="k:继承时刻之前患者已完成的诊次(有效实单数 + 偏移);新指派无此值">
|
||||
<el-icon class="rate-th-hint"><InfoFilled /></el-icon>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
<template #default="{ row }">
|
||||
{{ row.assign_type === 'inherit' ? `第 ${Number(row.inherit_visit_slot ?? 0)} 诊` : '—' }}
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="entry_slot" label="起算诊次" width="96" align="center">
|
||||
<template #header>
|
||||
<span>起算诊次</span>
|
||||
<el-tooltip effect="dark" placement="top" content="从该诊次列起计入分母:继承 = max(2, k+1);新指派 = 2(二诊)">
|
||||
<el-icon class="rate-th-hint"><InfoFilled /></el-icon>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
<template #default="{ row }">{{ entrySlotText(row.entry_slot) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="assign_count" label="当月指派次数" width="110" align="right" />
|
||||
<el-table-column prop="last_assign_time_text" label="最近指派时间" min-width="160" />
|
||||
</template>
|
||||
@@ -379,9 +210,6 @@
|
||||
<span v-else>{{ row.order_no || `#${row.order_id}` }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column v-if="detailSlot === 0" prop="visit_slot" label="诊次" width="80" align="center">
|
||||
<template #default="{ row }">{{ slotLabel(Number(row.visit_slot)) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="diagnosis_id" label="诊单ID" width="90" />
|
||||
<el-table-column prop="patient_name" label="患者" min-width="100">
|
||||
<template #default="{ row }">
|
||||
@@ -423,9 +251,7 @@ import {
|
||||
revisitRateAssignLines,
|
||||
revisitRateDeptOptions,
|
||||
revisitRateOverview,
|
||||
revisitRateVisitOrderLines,
|
||||
type RevisitRateAssignKind,
|
||||
type RevisitRateInheritMode
|
||||
revisitRateVisitOrderLines
|
||||
} from '@/api/stats'
|
||||
import { hasPermission } from '@/utils/perm'
|
||||
|
||||
@@ -437,14 +263,7 @@ const OrderDetailDrawer = defineAsyncComponent(
|
||||
const DiagnosisEditPopup = defineAsyncComponent(() => import('@/views/tcm/diagnosis/edit.vue'))
|
||||
|
||||
interface MetricPack extends Record<string, any> {
|
||||
/** 新指派数(语义不变) */
|
||||
assigned_count: number
|
||||
inherit_count?: number
|
||||
assigned_total_count?: number
|
||||
visit_all_count?: number
|
||||
visit_all_den?: number
|
||||
visit_all_rate?: number | null
|
||||
visit2_rate_new_assign?: number | null
|
||||
}
|
||||
|
||||
interface StatsRow extends MetricPack {
|
||||
@@ -470,14 +289,11 @@ const canViewOrderLines = hasPermission(['stats.revisitRate/visitOrderLines'])
|
||||
const canViewOrderDetail = hasPermission(['tcm.prescriptionOrder/detail'])
|
||||
const canViewPatientDetail = hasPermission(['tcm.diagnosis/detail'])
|
||||
|
||||
/** 接口动态返回的诊次分档(最少 2~4,按分子最大诊次 / 最大起算诊次扩展到五诊、六诊…) */
|
||||
/** 接口动态返回的诊次分档(最少 2~4,按数据扩展到五诊、六诊…) */
|
||||
const visitSlots = ref<number[]>([2, 3, 4])
|
||||
|
||||
const cnDigits = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十']
|
||||
const slotLabel = (slot: number) => {
|
||||
if (slot === 0) {
|
||||
return '复诊合计'
|
||||
}
|
||||
if (slot >= 2 && slot <= 10) {
|
||||
return `${cnDigits[slot]}诊`
|
||||
}
|
||||
@@ -491,8 +307,6 @@ const initNow = new Date()
|
||||
const currentMonth = `${initNow.getFullYear()}-${String(initNow.getMonth() + 1).padStart(2, '0')}`
|
||||
const month = ref<string>(currentMonth)
|
||||
const deptId = ref<number | undefined>(undefined)
|
||||
/** 口径:首次加载不传、取后端默认(config default_inherit_mode),之后以用户选择为准 */
|
||||
const inheritMode = ref<RevisitRateInheritMode | ''>('')
|
||||
const loading = ref(false)
|
||||
const rows = ref<StatsRow[]>([])
|
||||
const total = ref<MetricPack | null>(null)
|
||||
@@ -500,8 +314,6 @@ const total = ref<MetricPack | null>(null)
|
||||
const deptTreeOptions = ref<DeptTreeNode[]>([])
|
||||
const deptTreeProps = { value: 'id', label: 'name', children: 'children' }
|
||||
|
||||
const isSlotMode = computed(() => inheritMode.value !== 'exclude')
|
||||
|
||||
const monthText = computed(() => {
|
||||
const [y, m] = month.value.split('-')
|
||||
return y && m ? `${y}年${Number(m)}月` : month.value
|
||||
@@ -510,30 +322,9 @@ const monthText = computed(() => {
|
||||
const formatRate = (rate: number | null | undefined) =>
|
||||
rate === null || rate === undefined ? '—' : `${rate}%`
|
||||
|
||||
/** 接诊率单元格下方灰字:单数 / 分母 */
|
||||
const denText = (row: Record<string, any>, prefix: string) => {
|
||||
const cnt = Number(row[`${prefix}_count`] ?? 0)
|
||||
const den = row[`${prefix}_den`]
|
||||
return `${cnt} / ${den === null || den === undefined ? '—' : den}`
|
||||
}
|
||||
|
||||
const rateHeaderTip = (slot: number) =>
|
||||
isSlotMode.value
|
||||
? `${slotLabel(slot)}单数 ÷ ${slotLabel(slot)}分母;分母 = 当月新指派数 + 起算诊次 ≤ ${slot} 的继承数;分母为 0 显示「—」`
|
||||
: `${slotLabel(slot)}单数 ÷ 当月新指派数(旧口径:继承不计分母);分母为 0 显示「—」`
|
||||
|
||||
const entrySlotText = (entry: unknown) => {
|
||||
const n = Number(entry ?? 0)
|
||||
if (n <= 0) {
|
||||
return '—'
|
||||
}
|
||||
return n > 50 ? `${n}(仅计合计)` : slotLabel(n)
|
||||
}
|
||||
|
||||
const baseQuery = () => ({
|
||||
month: month.value,
|
||||
dept_ids: deptId.value ? String(deptId.value) : '',
|
||||
inherit_mode: (inheritMode.value || undefined) as RevisitRateInheritMode | undefined
|
||||
dept_ids: deptId.value ? String(deptId.value) : ''
|
||||
})
|
||||
|
||||
interface SummaryCard {
|
||||
@@ -550,11 +341,11 @@ const summaryCards = computed<SummaryCard[]>(() => {
|
||||
const cards: SummaryCard[] = [
|
||||
{
|
||||
key: 'assigned',
|
||||
label: isSlotMode.value ? '当月新指派数' : '当月被指派数',
|
||||
label: '当月被指派总数',
|
||||
value: t ? String(t.assigned_count) : '—',
|
||||
sub: t && isSlotMode.value ? `继承 ${t.inherit_count ?? 0} · 被指派合计 ${t.assigned_total_count ?? 0}` : '',
|
||||
sub: '',
|
||||
clickable: !!(canViewAssignLines && t && t.assigned_count > 0),
|
||||
onClick: () => openAssignDetail(null, 'new')
|
||||
onClick: () => openAssignDetail(null)
|
||||
}
|
||||
]
|
||||
for (const slot of visitSlots.value) {
|
||||
@@ -564,19 +355,11 @@ const summaryCards = computed<SummaryCard[]>(() => {
|
||||
key: `visit${slot}`,
|
||||
label: `当月${slotLabel(slot)}接诊率`,
|
||||
value: t ? formatRate(rate) : '—',
|
||||
sub: t ? `${slotLabel(slot)}下单 ${cnt} 单 / 分母 ${t[`visit${slot}_den`] ?? '—'}` : '',
|
||||
sub: t ? `${slotLabel(slot)}下单 ${cnt} 单` : '',
|
||||
clickable: !!(canViewOrderLines && cnt > 0),
|
||||
onClick: () => openOrderDetail(slot, null)
|
||||
})
|
||||
}
|
||||
cards.push({
|
||||
key: 'visit_all',
|
||||
label: '当月复诊合计接诊率',
|
||||
value: t ? formatRate(t.visit_all_rate) : '—',
|
||||
sub: t ? `复诊下单 ${t.visit_all_count ?? 0} 单 / 被指派合计 ${t.visit_all_den ?? '—'}` : '',
|
||||
clickable: !!(canViewOrderLines && t && Number(t.visit_all_count) > 0),
|
||||
onClick: () => openOrderDetail(0, null)
|
||||
})
|
||||
return cards
|
||||
})
|
||||
|
||||
@@ -591,16 +374,15 @@ const getSummaries = ({ columns }: { columns: any[] }) => {
|
||||
return ''
|
||||
}
|
||||
const prop = String(col.property || '')
|
||||
if (prop === 'assigned_count' || prop === 'inherit_count' || prop === 'assigned_total_count') {
|
||||
return String(t[prop] ?? 0)
|
||||
if (prop === 'assigned_count') {
|
||||
return String(t.assigned_count)
|
||||
}
|
||||
const m = /^visit(\d+|all)_(count|den|rate)$/.exec(prop)
|
||||
if (m) {
|
||||
if (m[2] === 'rate') {
|
||||
return `${formatRate(t[prop])}(${denText(t, `visit${m[1]}`)})`
|
||||
}
|
||||
if (/^visit\d+_count$/.test(prop)) {
|
||||
return String(t[prop] ?? '')
|
||||
}
|
||||
if (/^visit\d+_rate$/.test(prop)) {
|
||||
return formatRate(t[prop])
|
||||
}
|
||||
return ''
|
||||
})
|
||||
}
|
||||
@@ -622,9 +404,6 @@ const loadData = async () => {
|
||||
if (res?.month) {
|
||||
month.value = res.month
|
||||
}
|
||||
if (res?.inherit_mode === 'slot' || res?.inherit_mode === 'exclude') {
|
||||
inheritMode.value = res.inherit_mode
|
||||
}
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
@@ -670,8 +449,6 @@ const detailType = ref<'assign' | 'orders'>('assign')
|
||||
const detailTitle = ref('')
|
||||
const detailLoading = ref(false)
|
||||
const detailRows = ref<any[]>([])
|
||||
/** 订单明细的诊次(0 = 复诊合计,表格多显示「诊次」列) */
|
||||
const detailSlot = ref(2)
|
||||
|
||||
/** row 为 null 时表示合计(当前部门筛选范围) */
|
||||
const rowScope = (row: StatsRow | null): { assistant_id?: number; dept_id?: number; label: string } => {
|
||||
@@ -684,19 +461,13 @@ const rowScope = (row: StatsRow | null): { assistant_id?: number; dept_id?: numb
|
||||
return { assistant_id: row.assistant_id, label: row.assistant_name || '' }
|
||||
}
|
||||
|
||||
const assignKindLabel: Record<RevisitRateAssignKind, string> = {
|
||||
new: '新指派明细',
|
||||
inherit: '继承明细',
|
||||
all: '被指派合计明细'
|
||||
}
|
||||
|
||||
const openAssignDetail = async (row: StatsRow | null, kind: RevisitRateAssignKind = 'all') => {
|
||||
const openAssignDetail = async (row: StatsRow | null) => {
|
||||
if (!canViewAssignLines) {
|
||||
return
|
||||
}
|
||||
const scope = rowScope(row)
|
||||
detailType.value = 'assign'
|
||||
detailTitle.value = `${scope.label} · ${assignKindLabel[kind]}(${monthText.value})`
|
||||
detailTitle.value = `${scope.label} · 被指派明细(${monthText.value})`
|
||||
detailVisible.value = true
|
||||
detailLoading.value = true
|
||||
detailRows.value = []
|
||||
@@ -704,8 +475,7 @@ const openAssignDetail = async (row: StatsRow | null, kind: RevisitRateAssignKin
|
||||
const res = await revisitRateAssignLines({
|
||||
...baseQuery(),
|
||||
assistant_id: scope.assistant_id,
|
||||
dept_id: scope.dept_id,
|
||||
kind
|
||||
dept_id: scope.dept_id
|
||||
})
|
||||
detailRows.value = res?.rows ?? []
|
||||
} finally {
|
||||
@@ -713,14 +483,12 @@ const openAssignDetail = async (row: StatsRow | null, kind: RevisitRateAssignKin
|
||||
}
|
||||
}
|
||||
|
||||
/** slot=0 表示全部诊次 ≥ 2(复诊合计单数) */
|
||||
const openOrderDetail = async (slot: number, row: StatsRow | null) => {
|
||||
if (!canViewOrderLines) {
|
||||
return
|
||||
}
|
||||
const scope = rowScope(row)
|
||||
detailType.value = 'orders'
|
||||
detailSlot.value = slot
|
||||
detailTitle.value = `${scope.label} · ${slotLabel(slot)}订单明细(${monthText.value})`
|
||||
detailVisible.value = true
|
||||
detailLoading.value = true
|
||||
@@ -761,7 +529,6 @@ const openPatientDetail = (diagnosisId: number) => {
|
||||
const handleReset = () => {
|
||||
month.value = currentMonth
|
||||
deptId.value = undefined
|
||||
inheritMode.value = ''
|
||||
loadData()
|
||||
}
|
||||
|
||||
@@ -856,22 +623,6 @@ onMounted(() => {
|
||||
color: var(--el-text-color-secondary);
|
||||
cursor: help;
|
||||
}
|
||||
|
||||
.rate-cell {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-end;
|
||||
line-height: 1.3;
|
||||
|
||||
.rate-cell-main {
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.rate-cell-sub {
|
||||
font-size: 11px;
|
||||
color: var(--el-text-color-placeholder);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.rate-detail-footer {
|
||||
@@ -889,10 +640,5 @@ onMounted(() => {
|
||||
p + p {
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.rate-caliber-note {
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: 12px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
<template>
|
||||
<div class="appointment-list">
|
||||
<DoctorWebConsultationNotice />
|
||||
<el-card class="list-card !border-none" shadow="never">
|
||||
<!-- 单行工具栏:Tab(主) + 搜索(辅) -->
|
||||
<div class="list-toolbar">
|
||||
@@ -560,7 +559,6 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import DoctorWebConsultationNotice from '@/components/doctor-web-consultation-notice/index.vue'
|
||||
import { appointmentTypeDescription, canAppointmentVideoCall } from '@/utils/appointment-type'
|
||||
import { usePaging } from '@/hooks/usePaging'
|
||||
import { defineAsyncComponent, onMounted, onUnmounted, watch } from 'vue'
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
<template>
|
||||
<div class="apt-h5">
|
||||
<DoctorWebConsultationNotice />
|
||||
<template v-if="currentView === 'list'">
|
||||
<header class="apt-h5-topbar">
|
||||
<div class="apt-h5-search">
|
||||
@@ -413,7 +412,6 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts" name="tcmAppointmentH5">
|
||||
import DoctorWebConsultationNotice from '@/components/doctor-web-consultation-notice/index.vue'
|
||||
import { appointmentTypeDescription, canAppointmentVideoCall } from '@/utils/appointment-type'
|
||||
import { appointmentDetail, appointmentLists, cancelAppointment, completeAppointment } from '@/api/doctor'
|
||||
import { getWeappConfig } from '@/api/channel/weapp'
|
||||
|
||||
@@ -12,21 +12,9 @@
|
||||
{{ assistantLogCellText(row, 'to') }}
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="继承" width="118" align="center">
|
||||
<template #header>
|
||||
<span>继承</span>
|
||||
<el-tooltip
|
||||
placement="top"
|
||||
content="继承时第 k 诊:继承时刻之前患者已完成的诊次(有效实单数 + 偏移),复诊接诊率从第 k+1 诊起计入新医助分母;2026-10 前的继承记录无此快照"
|
||||
>
|
||||
<el-icon class="assign-log-col-hint"><QuestionFilled /></el-icon>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
<el-table-column label="继承" width="72" align="center">
|
||||
<template #default="{ row }">
|
||||
<template v-if="Number(row.is_inherit) === 1">
|
||||
<el-tag type="success" size="small">是</el-tag>
|
||||
<div v-if="inheritSlotText(row)" class="assign-log-inherit-slot">{{ inheritSlotText(row) }}</div>
|
||||
</template>
|
||||
<el-tag v-if="Number(row.is_inherit) === 1" type="success" size="small">是</el-tag>
|
||||
<span v-else class="text-gray-400">否</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
@@ -97,20 +85,6 @@ function relatedPoCreateTimeCell(row: Record<string, unknown>): string {
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
|
||||
}
|
||||
|
||||
/** 对应日志表 inherit_visit_slot / inherit_visit_slot_calc_time:后端已拼好「继承时第 k 诊」文案,缺失时按快照列兜底 */
|
||||
function inheritSlotText(row: Record<string, unknown>): string {
|
||||
const text = row.inherit_visit_slot_text
|
||||
if (text != null && String(text).trim() !== '') {
|
||||
return String(text)
|
||||
}
|
||||
const calcTime = Number(row.inherit_visit_slot_calc_time)
|
||||
if (!Number.isFinite(calcTime) || calcTime <= 0) {
|
||||
return ''
|
||||
}
|
||||
const k = Number(row.inherit_visit_slot)
|
||||
return Number.isFinite(k) && k > 0 ? `继承时第 ${k} 诊` : '继承时未成交'
|
||||
}
|
||||
|
||||
function assistantLogCellText(row: Record<string, unknown>, side: 'from' | 'to'): string {
|
||||
const nameKey = side === 'from' ? 'from_assistant_name' : 'to_assistant_name'
|
||||
const idKey = side === 'from' ? 'from_assistant_id' : 'to_assistant_id'
|
||||
@@ -158,11 +132,4 @@ defineExpose({ refresh: load })
|
||||
color: var(--el-text-color-secondary);
|
||||
cursor: help;
|
||||
}
|
||||
|
||||
.assign-log-inherit-slot {
|
||||
margin-top: 2px;
|
||||
font-size: 12px;
|
||||
line-height: 1.3;
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,168 +0,0 @@
|
||||
<template>
|
||||
<section class="consultation-transcripts">
|
||||
<header class="transcript-toolbar">
|
||||
<div>
|
||||
<h3>面诊文字对话</h3>
|
||||
<p>按每次通话分别查看已保存的文字记录。</p>
|
||||
</div>
|
||||
<el-button :loading="loading" @click="refresh"><el-icon><Refresh /></el-icon>刷新</el-button>
|
||||
</header>
|
||||
|
||||
<el-alert v-if="error" :title="error" type="error" :closable="false" show-icon class="transcript-error" />
|
||||
<div v-loading="loading" class="transcript-body">
|
||||
<template v-if="records.length">
|
||||
<aside class="transcript-sessions" aria-label="历次面诊记录">
|
||||
<el-input v-model="search" clearable placeholder="搜索面诊时间或对话内容" :prefix-icon="Search" />
|
||||
<p class="session-count">{{ filteredRecords.length }} 条面诊记录</p>
|
||||
<div class="session-list">
|
||||
<button
|
||||
v-for="row in pageRecords"
|
||||
:key="row.id"
|
||||
type="button"
|
||||
class="session-item"
|
||||
:class="{ selected: selectedId === row.id }"
|
||||
:aria-pressed="selectedId === row.id"
|
||||
@click="selectedId = row.id"
|
||||
>
|
||||
<span class="session-time">{{ row.start_time_text || '开始时间未记录' }}</span>
|
||||
<span class="session-meta">{{ consultationCallLabel(row) }} · 记录 #{{ row.id }}</span>
|
||||
<el-tag size="small" :type="consultationTranscriptStatus(row).type">{{ consultationTranscriptStatus(row).label }}</el-tag>
|
||||
<span class="session-preview">{{ preview(row) }}</span>
|
||||
</button>
|
||||
</div>
|
||||
<el-pagination
|
||||
v-if="filteredRecords.length > PAGE_SIZE"
|
||||
v-model:current-page="page"
|
||||
:page-size="PAGE_SIZE"
|
||||
:total="filteredRecords.length"
|
||||
layout="prev, pager, next"
|
||||
small
|
||||
/>
|
||||
</aside>
|
||||
|
||||
<article v-if="selectedRecord" class="transcript-detail" :key="`${diagnosisId}-${selectedRecord.id}`">
|
||||
<header class="transcript-detail-header">
|
||||
<div>
|
||||
<h4>{{ selectedRecord.start_time_text || '开始时间未记录' }} · {{ consultationCallLabel(selectedRecord) }}</h4>
|
||||
<p>
|
||||
通话记录 #{{ selectedRecord.id }}
|
||||
<span v-if="selectedRecord.duration_text"> · 时长 {{ selectedRecord.duration_text }}</span>
|
||||
<span v-if="selectedRecord.end_time_text"> · 结束 {{ selectedRecord.end_time_text }}</span>
|
||||
</p>
|
||||
</div>
|
||||
<el-button v-if="selectedText" :loading="copying" @click="copyTranscript">复制全文</el-button>
|
||||
</header>
|
||||
<div class="transcript-status">
|
||||
<el-tag :type="consultationTranscriptStatus(selectedRecord).type">{{ consultationTranscriptStatus(selectedRecord).label }}</el-tag>
|
||||
<span>{{ callStatusText(selectedRecord.status) }}</span>
|
||||
<span v-if="selectedRecord.transcription_segment_count">{{ selectedRecord.transcription_segment_count }} 段对话</span>
|
||||
</div>
|
||||
<p v-if="selectedRecord.transcription_status === 'partial'" class="transcript-note">本次文字记录不完整,以下展示已保存的内容。</p>
|
||||
<p v-else-if="selectedRecord.transcription_status === 'failed' && selectedText" class="transcript-note">本次转写未完成,以下展示已保存的内容。</p>
|
||||
<p v-else-if="selectedRecord.transcription_status === 'running' && selectedText" class="transcript-note">转写仍在进行,可刷新查看最新保存的文字。</p>
|
||||
<pre v-if="selectedText" class="transcript-text">{{ selectedText }}</pre>
|
||||
<el-empty v-else :description="consultationTranscriptEmptyText(selectedRecord)" :image-size="72" />
|
||||
</article>
|
||||
<el-empty v-else description="没有匹配的面诊记录,请调整搜索内容" class="transcript-detail" :image-size="72" />
|
||||
</template>
|
||||
<el-empty v-else-if="!loading && !error" description="该诊单暂无面诊通话记录" :image-size="80" class="transcript-empty" />
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { Refresh, Search } from '@element-plus/icons-vue'
|
||||
import type { ConsultationCallRecord } from '@/api/tcm'
|
||||
import { useConsultationTranscripts } from '@/hooks/useConsultationTranscripts'
|
||||
import {
|
||||
consultationCallLabel,
|
||||
consultationTranscriptEmptyText,
|
||||
consultationTranscriptStatus,
|
||||
consultationTranscriptText
|
||||
} from '@/utils/consultation-transcripts'
|
||||
import feedback from '@/utils/feedback'
|
||||
|
||||
const props = defineProps<{ diagnosisId: number }>()
|
||||
const { records, loading, error, refresh } = useConsultationTranscripts(() => props.diagnosisId)
|
||||
const search = ref('')
|
||||
const selectedId = ref<number | null>(null)
|
||||
const page = ref(1)
|
||||
const copying = ref(false)
|
||||
const PAGE_SIZE = 10
|
||||
const filteredRecords = computed(() => {
|
||||
const term = search.value.trim().toLocaleLowerCase()
|
||||
return records.value.filter(row => row.diagnosis_id === props.diagnosisId &&
|
||||
(!term || `${row.start_time_text || ''} ${row.id} ${consultationTranscriptText(row)}`.toLocaleLowerCase().includes(term)))
|
||||
})
|
||||
const pageRecords = computed(() => filteredRecords.value.slice((page.value - 1) * PAGE_SIZE, page.value * PAGE_SIZE))
|
||||
const selectedRecord = computed(() => filteredRecords.value.find(row => row.id === selectedId.value))
|
||||
const selectedText = computed(() => consultationTranscriptText(selectedRecord.value))
|
||||
watch(filteredRecords, rows => {
|
||||
if (!rows.some(row => row.id === selectedId.value)) {
|
||||
const selected = rows.find(row => consultationTranscriptText(row)) || rows[0]
|
||||
selectedId.value = selected?.id ?? null
|
||||
page.value = selected ? Math.floor(rows.indexOf(selected) / PAGE_SIZE) + 1 : 1
|
||||
}
|
||||
page.value = Math.min(page.value, Math.max(1, Math.ceil(rows.length / PAGE_SIZE)))
|
||||
}, { immediate: true, flush: 'sync' })
|
||||
watch(search, () => { page.value = 1 }, { flush: 'sync' })
|
||||
|
||||
function preview(row: ConsultationCallRecord): string {
|
||||
const text = consultationTranscriptText(row).replace(/\s+/g, ' ')
|
||||
return text ? text.slice(0, 90) + (text.length > 90 ? '…' : '') : consultationTranscriptEmptyText(row)
|
||||
}
|
||||
function callStatusText(value?: number): string {
|
||||
return ({ 1: '进行中', 2: '已结束', 3: '未接听', 4: '已取消' } as Record<number, string>)[Number(value)] || '状态未记录'
|
||||
}
|
||||
async function copyTranscript() {
|
||||
const text = selectedText.value
|
||||
if (!text || copying.value) return
|
||||
if (!navigator.clipboard?.writeText) {
|
||||
feedback.msgWarning('当前浏览器不支持自动复制,请选中文字复制')
|
||||
return
|
||||
}
|
||||
copying.value = true
|
||||
try {
|
||||
await navigator.clipboard.writeText(text)
|
||||
feedback.msgSuccess('已复制本次面诊文字对话')
|
||||
} catch {
|
||||
feedback.msgWarning('复制失败,请选中文字复制')
|
||||
} finally {
|
||||
copying.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.consultation-transcripts { padding: 4px 0 16px; }
|
||||
.transcript-toolbar, .transcript-detail-header { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; }
|
||||
.transcript-toolbar { margin-bottom: 20px; }
|
||||
.transcript-toolbar h3, .transcript-detail h4 { margin: 0; color: var(--el-text-color-primary); font-weight: 600; }
|
||||
.transcript-toolbar h3 { font-size: 18px; }
|
||||
.transcript-toolbar p, .transcript-detail-header p { margin: 7px 0 0; color: var(--el-text-color-secondary); line-height: 1.7; font-size: 13px; }
|
||||
.transcript-error { margin-bottom: 16px; }
|
||||
.transcript-body { display: flex; min-height: 360px; border-top: 1px solid var(--el-border-color-lighter); }
|
||||
.transcript-sessions { flex: 0 0 282px; min-width: 0; padding: 18px 18px 0 0; border-right: 1px solid var(--el-border-color-lighter); }
|
||||
.session-count { margin: 12px 0 8px; color: var(--el-text-color-secondary); font-size: 12px; }
|
||||
.session-list { display: flex; flex-direction: column; gap: 8px; max-height: 580px; overflow-y: auto; margin-bottom: 12px; }
|
||||
.session-item { display: flex; flex-direction: column; align-items: flex-start; gap: 8px; width: 100%; padding: 13px 12px; border: 1px solid var(--el-border-color-lighter); border-radius: 7px; background: var(--el-bg-color); text-align: left; cursor: pointer; font: inherit; }
|
||||
.session-item:hover, .session-item.selected { border-color: var(--el-color-primary); background: var(--el-color-primary-light-9); }
|
||||
.session-item:focus-visible { outline: 2px solid var(--el-color-primary); outline-offset: -2px; }
|
||||
.session-time { color: var(--el-text-color-primary); font-size: 14px; font-weight: 600; }
|
||||
.session-meta, .session-preview { color: var(--el-text-color-secondary); font-size: 12px; line-height: 1.6; }
|
||||
.session-preview { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; overflow-wrap: anywhere; }
|
||||
.transcript-detail { flex: 1; min-width: 0; padding: 20px 0 0 24px; }
|
||||
.transcript-detail h4 { font-size: 16px; line-height: 1.7; }
|
||||
.transcript-status { display: flex; align-items: center; flex-wrap: wrap; gap: 12px; margin: 16px 0; color: var(--el-text-color-secondary); font-size: 13px; }
|
||||
.transcript-note { padding: 10px 12px; background: var(--el-color-warning-light-9); color: var(--el-color-warning-dark-2); font-size: 13px; line-height: 1.7; }
|
||||
.transcript-text { margin: 0; padding: 20px 0; color: var(--el-text-color-primary); white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; font-size: 15px; line-height: 2; user-select: text; }
|
||||
.transcript-empty { flex: 1; }
|
||||
@media (max-width: 900px) {
|
||||
.transcript-body { flex-direction: column; }
|
||||
.transcript-sessions { flex-basis: auto; padding: 16px 0; border-right: 0; border-bottom: 1px solid var(--el-border-color-lighter); }
|
||||
.session-list { max-height: 300px; }
|
||||
.transcript-detail { padding: 20px 0 0; }
|
||||
.transcript-detail-header { flex-wrap: wrap; }
|
||||
}
|
||||
</style>
|
||||
@@ -68,11 +68,7 @@
|
||||
'is-high': getCell(row.key, date).isHigh,
|
||||
'is-patient-self': getCell(row.key, date).isPatientSelf && getCell(row.key, date).hasRecord
|
||||
}"
|
||||
:role="isCellClickable(row.key, date) ? 'button' : undefined"
|
||||
:tabindex="isCellClickable(row.key, date) ? 0 : undefined"
|
||||
@click="handleCellClick(row.key, date)"
|
||||
@keydown.enter="handleCellClick(row.key, date)"
|
||||
@keydown.space.prevent="handleCellClick(row.key, date)"
|
||||
>
|
||||
<template v-if="row.key === 'tracking' && getTrackingContent(date)">
|
||||
<el-tooltip placement="top" effect="light" :show-after="150">
|
||||
@@ -94,9 +90,6 @@
|
||||
</template>
|
||||
<template v-else-if="getCell(row.key, date).value">
|
||||
<span>{{ getCell(row.key, date).value }}</span>
|
||||
<span v-if="getDayRecordCount(row.key, date) > 1" class="daily-matrix__record-count">
|
||||
{{ getDayRecordCount(row.key, date) }}条
|
||||
</span>
|
||||
<span v-if="getCell(row.key, date).isHigh" class="daily-matrix__cell-up">↑</span>
|
||||
<el-tooltip
|
||||
v-if="getCell(row.key, date).isPatientSelf"
|
||||
@@ -107,10 +100,7 @@
|
||||
<span class="daily-matrix__cell-patient">自录</span>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
<template v-else>
|
||||
<span v-if="getDayRecordCount(row.key, date) > 0" class="daily-matrix__record-count">查看{{ getDayRecordCount(row.key, date) }}条</span>
|
||||
<span v-else>—</span>
|
||||
</template>
|
||||
<template v-else>—</template>
|
||||
</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
@@ -119,7 +109,6 @@
|
||||
|
||||
<div class="daily-matrix__chart">
|
||||
<div class="daily-matrix__section-title">血糖趋势</div>
|
||||
<p class="daily-matrix__hint">按日展示最新有效血糖值;点击表格查看当天全部原始记录。</p>
|
||||
<v-charts
|
||||
v-if="bloodTrendHasData"
|
||||
class="daily-matrix__chart-canvas"
|
||||
@@ -139,84 +128,6 @@
|
||||
/>
|
||||
</div>
|
||||
|
||||
<el-drawer v-model="dayDetailVisible" :title="`${detailDate} 日常记录明细`" size="min(640px, 100vw)">
|
||||
<p class="daily-matrix__hint">每张卡片是一条独立记录;相同数值也不会合并。请在对应记录上点击编辑。</p>
|
||||
<section class="daily-matrix__detail-section">
|
||||
<div class="daily-matrix__detail-heading">
|
||||
<h3>血糖血压 · {{ dayBloodRecords.length }}条</h3>
|
||||
<el-button v-if="canEditDailyRecord" link type="primary" @click="openBloodRecord(undefined, detailDate)">新增一条</el-button>
|
||||
</div>
|
||||
<el-empty v-if="!dayBloodRecords.length" description="当天暂无血糖血压记录" :image-size="48" />
|
||||
<article v-for="record in dayBloodRecords" :key="record.id" class="daily-matrix__detail-record">
|
||||
<header class="daily-matrix__detail-heading">
|
||||
<strong>{{ recordTimeLabel(record) }} <small>#{{ record.id }}</small></strong>
|
||||
<el-button v-if="canEditDailyRecord" link type="primary" @click="openBloodRecord(record, detailDate)">编辑此条</el-button>
|
||||
</header>
|
||||
<div class="daily-matrix__detail-tags">
|
||||
<el-tag v-if="Number(record.record_time_estimated) === 1" type="warning" size="small">估计时间</el-tag>
|
||||
<el-tag v-if="record.record_time_period" type="info" size="small">时段:{{ recordTimePeriodLabel(record) }}</el-tag>
|
||||
<el-tag v-if="record.followup_audio_task_id" size="small">随访录音</el-tag>
|
||||
<span v-if="Number(record.source) === 1" class="daily-matrix__cell-patient">患者自录</span>
|
||||
</div>
|
||||
<p v-if="record.record_time_text" class="daily-matrix__time-evidence">时间原文:{{ record.record_time_text }}</p>
|
||||
<dl class="daily-matrix__detail-fields">
|
||||
<template v-for="field in bloodDetailFields(record)" :key="field.label">
|
||||
<dt>{{ field.label }}</dt><dd>{{ field.value }}</dd>
|
||||
</template>
|
||||
</dl>
|
||||
</article>
|
||||
</section>
|
||||
<section class="daily-matrix__detail-section">
|
||||
<div class="daily-matrix__detail-heading">
|
||||
<h3>饮食 · {{ dayDietRecords.length }}条</h3>
|
||||
<el-button v-if="canEditDailyRecord" link type="primary" @click="openDietRecord(undefined, detailDate)">新增一条</el-button>
|
||||
</div>
|
||||
<el-empty v-if="!dayDietRecords.length" description="当天暂无饮食记录" :image-size="48" />
|
||||
<article v-for="record in dayDietRecords" :key="record.id" class="daily-matrix__detail-record">
|
||||
<header class="daily-matrix__detail-heading">
|
||||
<strong>{{ recordTimeLabel(record) }} <small>#{{ record.id }}</small></strong>
|
||||
<el-button v-if="canEditDailyRecord" link type="primary" @click="openDietRecord(record, detailDate)">编辑此条</el-button>
|
||||
</header>
|
||||
<dl class="daily-matrix__detail-fields">
|
||||
<template v-for="meal in mealFields" :key="meal.key">
|
||||
<dt>{{ meal.label }}</dt>
|
||||
<dd>
|
||||
{{ record[`${meal.key}_foods`] || record[meal.key] || '—' }}
|
||||
<div v-if="record[`${meal.key}_images`]?.length" class="daily-matrix__detail-images">
|
||||
<el-image v-for="(url, index) in record[`${meal.key}_images`]" :key="`${url}-${index}`"
|
||||
:src="url" :preview-src-list="record[`${meal.key}_images`]" :initial-index="index" preview-teleported fit="cover" />
|
||||
</div>
|
||||
</dd>
|
||||
</template>
|
||||
<dt>备注</dt><dd>{{ record.note || '—' }}</dd>
|
||||
</dl>
|
||||
</article>
|
||||
</section>
|
||||
<section class="daily-matrix__detail-section">
|
||||
<div class="daily-matrix__detail-heading">
|
||||
<h3>运动 · {{ dayExerciseRecords.length }}条</h3>
|
||||
<el-button v-if="canEditDailyRecord" link type="primary" @click="openExerciseRecord(undefined, detailDate)">新增一条</el-button>
|
||||
</div>
|
||||
<el-empty v-if="!dayExerciseRecords.length" description="当天暂无运动记录" :image-size="48" />
|
||||
<article v-for="record in dayExerciseRecords" :key="record.id" class="daily-matrix__detail-record">
|
||||
<header class="daily-matrix__detail-heading">
|
||||
<strong>{{ recordTimeLabel(record) }} <small>#{{ record.id }}</small></strong>
|
||||
<el-button v-if="canEditDailyRecord" link type="primary" @click="openExerciseRecord(record, detailDate)">编辑此条</el-button>
|
||||
</header>
|
||||
<dl class="daily-matrix__detail-fields">
|
||||
<dt>运动</dt><dd>{{ record.exercise_type || '—' }}</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">
|
||||
<el-image v-for="(url, index) in record.images" :key="`${url}-${index}`" :src="url"
|
||||
:preview-src-list="record.images" :initial-index="index" preview-teleported fit="cover" />
|
||||
</div>
|
||||
</article>
|
||||
</section>
|
||||
</el-drawer>
|
||||
|
||||
<el-dialog v-model="bloodDialogVisible" :title="bloodDialogTitle" width="600px" :close-on-click-modal="false">
|
||||
<el-form :model="bloodForm" label-width="120px">
|
||||
<el-form-item label="记录日期" required>
|
||||
@@ -237,12 +148,6 @@
|
||||
class="w-full"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item v-if="Number(bloodForm.record_time_estimated) === 1" label="时间说明">
|
||||
<div class="daily-matrix__time-evidence">
|
||||
估计时间 · {{ recordTimePeriodLabel(bloodForm) }};原文:{{ bloodForm.record_time_text || '未提供' }}。
|
||||
手动修改记录时间后会清除估计标记;只改数值则保留来源。
|
||||
</div>
|
||||
</el-form-item>
|
||||
<el-form-item label="空腹血糖">
|
||||
<el-input-number v-model="bloodForm.fasting_blood_sugar" :precision="2" :step="0.1" :min="0" :max="50" />
|
||||
<span class="ml-2">mmol/L</span>
|
||||
@@ -343,13 +248,11 @@
|
||||
<el-option label="其他" value="其他" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<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 label="运动时长(分钟)" required>
|
||||
<el-input-number v-model="exerciseForm.duration" :min="0" :max="300" />
|
||||
</el-form-item>
|
||||
<el-form-item label="运动强度">
|
||||
<el-select v-model="exerciseIntensity" placeholder="未记录" class="w-full">
|
||||
<el-option label="未记录" value="" />
|
||||
<el-form-item label="运动强度" required>
|
||||
<el-select v-model="exerciseForm.intensity" placeholder="请选择运动强度" class="w-full">
|
||||
<el-option label="低强度" :value="1" />
|
||||
<el-option label="中强度" :value="2" />
|
||||
<el-option label="高强度" :value="3" />
|
||||
@@ -450,10 +353,6 @@ interface BloodRecord {
|
||||
patient_id?: number
|
||||
record_date?: string
|
||||
record_time?: string
|
||||
record_time_estimated?: number | string
|
||||
record_time_period?: string
|
||||
record_time_text?: string
|
||||
followup_audio_task_id?: number | null
|
||||
record_date_ts?: number
|
||||
fasting_blood_sugar?: any
|
||||
postprandial_blood_sugar?: any
|
||||
@@ -465,11 +364,12 @@ interface BloodRecord {
|
||||
remark?: string
|
||||
/** 来源:0-医生录入 1-患者自录(小程序日常记录页) */
|
||||
source?: number
|
||||
/** 合并后该日是否含有「患者自录」记录 */
|
||||
has_patient_self?: boolean
|
||||
[key: string]: any
|
||||
}
|
||||
|
||||
interface DietRecord {
|
||||
record_time?: string
|
||||
id?: number | string
|
||||
diagnosis_id?: number
|
||||
patient_id?: number
|
||||
@@ -488,14 +388,13 @@ interface DietRecord {
|
||||
}
|
||||
|
||||
interface ExerciseRecord {
|
||||
record_time?: string
|
||||
id?: number | string
|
||||
diagnosis_id?: number
|
||||
patient_id?: number
|
||||
record_date?: string
|
||||
exercise_type?: string
|
||||
duration?: number | null
|
||||
intensity?: number | null
|
||||
duration?: number
|
||||
intensity?: number
|
||||
intensity_text?: string
|
||||
images?: string[]
|
||||
note?: string
|
||||
@@ -538,9 +437,6 @@ const bloodDialogVisible = ref(false)
|
||||
const dietDialogVisible = ref(false)
|
||||
const exerciseDialogVisible = ref(false)
|
||||
const trackingDialogVisible = ref(false)
|
||||
const dayDetailVisible = ref(false)
|
||||
const detailDate = ref('')
|
||||
const originalBloodTime = ref('')
|
||||
const bloodSubmitting = ref(false)
|
||||
const dietSubmitting = ref(false)
|
||||
const exerciseSubmitting = ref(false)
|
||||
@@ -549,11 +445,6 @@ 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: '',
|
||||
@@ -564,7 +455,7 @@ const bloodDialogTitle = computed(() => (bloodForm.value.id ? '编辑血糖血
|
||||
const dietDialogTitle = computed(() => (dietForm.value.id ? '编辑饮食记录' : '新增饮食记录'))
|
||||
const exerciseDialogTitle = computed(() => (exerciseForm.value.id ? '编辑运动记录' : '新增运动记录'))
|
||||
const todayDate = computed(() => formatDate(new Date()))
|
||||
const trackingCanSubmit = computed(() => canEditDailyRecord.value && trackingForm.value.note_date === todayDate.value)
|
||||
const trackingCanSubmit = computed(() => !readOnly.value && trackingForm.value.note_date === todayDate.value)
|
||||
const trackingDialogTitle = computed(() => (trackingCanSubmit.value ? '新增/追加跟踪备注' : '查看跟踪备注'))
|
||||
const tableWrapRef = ref<HTMLElement | null>(null)
|
||||
const tableWrapWidth = ref(0)
|
||||
@@ -692,63 +583,70 @@ const hasPatientSelfRecord = computed(() => {
|
||||
return bloodRecords.value.some((r) => Number((r as any).source) === 1)
|
||||
})
|
||||
|
||||
// Group actual rows, never a synthetic record bearing the first row's id.
|
||||
function groupRecordsByDate<T extends { record_date?: string }>(records: T[]): Map<string, T[]> {
|
||||
const map = new Map<string, T[]>()
|
||||
for (const record of records) {
|
||||
const bloodByDate = computed(() => {
|
||||
const map = new Map<string, BloodRecord>()
|
||||
for (const record of bloodRecords.value) {
|
||||
const date = String(record.record_date || '')
|
||||
if (!date) continue
|
||||
const rows = map.get(date) || []
|
||||
rows.push(record)
|
||||
map.set(date, rows)
|
||||
if (!map.has(date)) {
|
||||
map.set(date, {
|
||||
id: record.id,
|
||||
diagnosis_id: record.diagnosis_id,
|
||||
patient_id: record.patient_id,
|
||||
record_date: date,
|
||||
record_time: record.record_time || '',
|
||||
record_date_ts: record.record_date_ts,
|
||||
has_patient_self: false
|
||||
})
|
||||
}
|
||||
const merged = map.get(date)!
|
||||
const fields: Array<keyof BloodRecord> = [
|
||||
'fasting_blood_sugar',
|
||||
'postprandial_blood_sugar',
|
||||
'other_blood_sugar',
|
||||
'systolic_pressure',
|
||||
'diastolic_pressure',
|
||||
'western_medicine',
|
||||
'insulin',
|
||||
'remark'
|
||||
]
|
||||
for (const field of fields) {
|
||||
if (
|
||||
(merged[field] === undefined || merged[field] === null || merged[field] === '') &&
|
||||
record[field] !== undefined &&
|
||||
record[field] !== null &&
|
||||
record[field] !== ''
|
||||
) {
|
||||
;(merged as any)[field] = record[field]
|
||||
}
|
||||
}
|
||||
// 当天有任意 source=1 的记录则标记为患者自录
|
||||
if (Number(record.source) === 1) {
|
||||
merged.has_patient_self = true
|
||||
}
|
||||
}
|
||||
return map
|
||||
}
|
||||
})
|
||||
|
||||
const bloodByDate = computed(() => groupRecordsByDate(bloodRecords.value))
|
||||
const dietByDate = computed(() => groupRecordsByDate(dietRecords.value))
|
||||
const exerciseByDate = computed(() => groupRecordsByDate(exerciseRecords.value))
|
||||
const dayBloodRecords = computed(() => bloodByDate.value.get(detailDate.value) || [])
|
||||
const dayDietRecords = computed(() => dietByDate.value.get(detailDate.value) || [])
|
||||
const dayExerciseRecords = computed(() => exerciseByDate.value.get(detailDate.value) || [])
|
||||
const mealFields = [{ key: 'breakfast', label: '早餐' }, { key: 'lunch', label: '午餐' }, { key: 'dinner', label: '晚餐' }]
|
||||
|
||||
function recordTimeLabel(record: { record_time?: string }) {
|
||||
return record.record_time ? String(record.record_time) : '未记录具体时间'
|
||||
}
|
||||
|
||||
function recordTimePeriodLabel(record: BloodRecord) {
|
||||
const labels: Record<string, string> = {
|
||||
dawn: '凌晨', early_morning: '清晨', morning: '上午', noon: '中午',
|
||||
afternoon: '下午', evening: '晚上', night: '夜间', bedtime: '睡前'
|
||||
const dietByDate = computed(() => {
|
||||
const map = new Map<string, DietRecord>()
|
||||
for (const record of dietRecords.value) {
|
||||
const date = String(record.record_date || '')
|
||||
if (!date || map.has(date)) continue
|
||||
map.set(date, record)
|
||||
}
|
||||
const period = String(record.record_time_period || '')
|
||||
return labels[period] || period || '未提供时段'
|
||||
}
|
||||
return map
|
||||
})
|
||||
|
||||
function intensityLabel(value?: number | null) {
|
||||
return ({ 1: '低强度', 2: '中强度', 3: '高强度' } as Record<number, string>)[Number(value)] || '未记录'
|
||||
}
|
||||
|
||||
function bloodDetailFields(record: BloodRecord) {
|
||||
const show = (value: unknown) => value == null || value === '' ? '—' : String(value)
|
||||
return [
|
||||
{ label: '空腹血糖', value: `${show(record.fasting_blood_sugar)} mmol/L` },
|
||||
{ label: '餐后2h血糖', value: `${show(record.postprandial_blood_sugar)} mmol/L` },
|
||||
{ label: '其他血糖', value: `${show(record.other_blood_sugar)} mmol/L` },
|
||||
{ label: '血压', value: record.systolic_pressure || record.diastolic_pressure ? `${formatBp(record)} mmHg` : '—' },
|
||||
{ label: '西药', value: show(record.western_medicine) },
|
||||
{ label: '胰岛素', value: show(record.insulin) },
|
||||
{ label: '备注', value: show(record.remark) }
|
||||
]
|
||||
}
|
||||
|
||||
function getDayRecordCount(metric: string, date: string) {
|
||||
if (['breakfast', 'lunch', 'dinner'].includes(metric)) return dietByDate.value.get(date)?.length || 0
|
||||
if (metric === 'exercise') return exerciseByDate.value.get(date)?.length || 0
|
||||
if (metric === 'tracking') return 0
|
||||
return bloodByDate.value.get(date)?.length || 0
|
||||
}
|
||||
const exerciseByDate = computed(() => {
|
||||
const map = new Map<string, ExerciseRecord>()
|
||||
for (const record of exerciseRecords.value) {
|
||||
const date = String(record.record_date || '')
|
||||
if (!date || map.has(date)) continue
|
||||
map.set(date, record)
|
||||
}
|
||||
return map
|
||||
})
|
||||
|
||||
const trackingByDate = computed(() => {
|
||||
const map = new Map<string, TrackingNoteRecord>()
|
||||
@@ -765,10 +663,9 @@ const chartDates = computed(() => [...visibleDates.value].reverse())
|
||||
const bloodTrendSeries = computed(() => {
|
||||
return chartDates.value.reduce(
|
||||
(acc, date) => {
|
||||
const records = bloodByDate.value.get(date) || []
|
||||
const latestValue = (field: keyof BloodRecord) => records.map((record) => parseTrendNumber(record[field])).find((value) => value !== null) ?? null
|
||||
acc.fasting.push(latestValue('fasting_blood_sugar'))
|
||||
acc.postprandial.push(latestValue('postprandial_blood_sugar'))
|
||||
const blood = bloodByDate.value.get(date)
|
||||
acc.fasting.push(parseTrendNumber(blood?.fasting_blood_sugar))
|
||||
acc.postprandial.push(parseTrendNumber(blood?.postprandial_blood_sugar))
|
||||
return acc
|
||||
},
|
||||
{
|
||||
@@ -857,49 +754,89 @@ function parseTrendNumber(value: unknown): number | null {
|
||||
}
|
||||
|
||||
function getCell(metric: string, date: string): { value: string; isHigh: boolean; hasRecord: boolean; isPatientSelf?: boolean } {
|
||||
const blood = bloodByDate.value.get(date) || []
|
||||
const diet = dietByDate.value.get(date) || []
|
||||
const exercise = exerciseByDate.value.get(date) || []
|
||||
const blood = bloodByDate.value.get(date)
|
||||
const diet = dietByDate.value.get(date)
|
||||
const exercise = exerciseByDate.value.get(date)
|
||||
const tracking = trackingByDate.value.get(date)
|
||||
const bloodFields: Record<string, keyof BloodRecord> = {
|
||||
fasting: 'fasting_blood_sugar', postprandial: 'postprandial_blood_sugar',
|
||||
other: 'other_blood_sugar', western: 'western_medicine', insulin: 'insulin'
|
||||
const isPatientSelf = !!blood?.has_patient_self
|
||||
switch (metric) {
|
||||
case 'fasting':
|
||||
return {
|
||||
value: blood?.fasting_blood_sugar != null && blood.fasting_blood_sugar !== '' ? String(blood.fasting_blood_sugar) : '',
|
||||
isHigh: isHighFastingBloodSugar(blood?.fasting_blood_sugar, props.age),
|
||||
hasRecord: !!blood && blood.fasting_blood_sugar != null && blood.fasting_blood_sugar !== '',
|
||||
isPatientSelf
|
||||
}
|
||||
case 'postprandial':
|
||||
return {
|
||||
value: blood?.postprandial_blood_sugar != null && blood.postprandial_blood_sugar !== '' ? String(blood.postprandial_blood_sugar) : '',
|
||||
isHigh: isHighPostprandialBloodSugar(blood?.postprandial_blood_sugar, props.age),
|
||||
hasRecord: !!blood && blood.postprandial_blood_sugar != null && blood.postprandial_blood_sugar !== '',
|
||||
isPatientSelf
|
||||
}
|
||||
case 'other':
|
||||
return {
|
||||
value: blood?.other_blood_sugar != null && blood.other_blood_sugar !== '' ? String(blood.other_blood_sugar) : '',
|
||||
isHigh: isHighOtherBloodSugar(blood?.other_blood_sugar, props.age),
|
||||
hasRecord: !!blood && blood.other_blood_sugar != null && blood.other_blood_sugar !== '',
|
||||
isPatientSelf
|
||||
}
|
||||
case 'bp':
|
||||
return {
|
||||
value: blood && (blood.systolic_pressure || blood.diastolic_pressure) ? formatBp(blood) : '',
|
||||
isHigh: isHighBloodPressure(blood),
|
||||
hasRecord: !!blood && !!(blood.systolic_pressure || blood.diastolic_pressure),
|
||||
isPatientSelf
|
||||
}
|
||||
case 'western':
|
||||
return {
|
||||
value: blood?.western_medicine || '',
|
||||
isHigh: false,
|
||||
hasRecord: !!blood?.western_medicine
|
||||
}
|
||||
case 'insulin':
|
||||
return {
|
||||
value: blood?.insulin || '',
|
||||
isHigh: false,
|
||||
hasRecord: !!blood?.insulin
|
||||
}
|
||||
case 'breakfast':
|
||||
return {
|
||||
value: diet?.breakfast || diet?.breakfast_foods ? '✓' : '',
|
||||
isHigh: false,
|
||||
hasRecord: !!(diet?.breakfast || diet?.breakfast_foods)
|
||||
}
|
||||
case 'lunch':
|
||||
return {
|
||||
value: diet?.lunch || diet?.lunch_foods ? '✓' : '',
|
||||
isHigh: false,
|
||||
hasRecord: !!(diet?.lunch || diet?.lunch_foods)
|
||||
}
|
||||
case 'dinner':
|
||||
return {
|
||||
value: diet?.dinner || diet?.dinner_foods ? '✓' : '',
|
||||
isHigh: false,
|
||||
hasRecord: !!(diet?.dinner || diet?.dinner_foods)
|
||||
}
|
||||
case 'exercise':
|
||||
return {
|
||||
value: exercise?.duration ? `${exercise.duration}min` : '',
|
||||
isHigh: false,
|
||||
hasRecord: !!exercise?.id
|
||||
}
|
||||
case 'tracking':
|
||||
return {
|
||||
value: tracking?.content ? summarizeTracking(tracking.content) : '',
|
||||
isHigh: false,
|
||||
hasRecord: !!tracking?.content
|
||||
}
|
||||
default:
|
||||
return { value: '', isHigh: false, hasRecord: false }
|
||||
}
|
||||
const field = bloodFields[metric]
|
||||
if (field || metric === 'bp') {
|
||||
const rows = blood.filter((record) => metric === 'bp'
|
||||
? !!(record.systolic_pressure || record.diastolic_pressure)
|
||||
: record[field] != null && record[field] !== '')
|
||||
const isHigh = (record: BloodRecord) => {
|
||||
if (metric === 'fasting') return isHighFastingBloodSugar(record.fasting_blood_sugar, props.age)
|
||||
if (metric === 'postprandial') return isHighPostprandialBloodSugar(record.postprandial_blood_sugar, props.age)
|
||||
if (metric === 'other') return isHighOtherBloodSugar(record.other_blood_sugar, props.age)
|
||||
return metric === 'bp' && isHighBloodPressure(record)
|
||||
}
|
||||
return {
|
||||
value: rows.map((record) => metric === 'bp' ? formatBp(record) : String(record[field])).join(' / '),
|
||||
isHigh: rows.some(isHigh), hasRecord: rows.length > 0,
|
||||
isPatientSelf: rows.some((record) => Number(record.source) === 1)
|
||||
}
|
||||
}
|
||||
if (['breakfast', 'lunch', 'dinner'].includes(metric)) {
|
||||
const count = diet.filter((record) => record[metric] || record[`${metric}_foods`] || record[`${metric}_images`]?.length).length
|
||||
return { value: count ? '✓' : '', isHigh: false, hasRecord: count > 0 }
|
||||
}
|
||||
if (metric === 'exercise') {
|
||||
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 }
|
||||
}
|
||||
return { value: '', isHigh: false, hasRecord: false }
|
||||
}
|
||||
|
||||
async function fetchTracking() {
|
||||
const seq = ++requestSeq
|
||||
const requestDiagnosisId = diagnosisId.value
|
||||
if (!requestDiagnosisId) {
|
||||
loading.value = false
|
||||
if (!diagnosisId.value) {
|
||||
bloodRecords.value = []
|
||||
dietRecords.value = []
|
||||
exerciseRecords.value = []
|
||||
@@ -908,23 +845,23 @@ async function fetchTracking() {
|
||||
}
|
||||
const { start, end } = currentRange.value
|
||||
if (rangeMode.value === 'custom' && (!start || !end)) return
|
||||
const requestDates = [...visibleDates.value]
|
||||
const seq = ++requestSeq
|
||||
loading.value = true
|
||||
try {
|
||||
const data: any = await diagnosisTrackingWindow({
|
||||
id: requestDiagnosisId,
|
||||
id: diagnosisId.value,
|
||||
start_date: start,
|
||||
end_date: end
|
||||
})
|
||||
const noteData: any = await diagnosisTrackingNotes({
|
||||
diagnosis_id: requestDiagnosisId
|
||||
diagnosis_id: diagnosisId.value
|
||||
})
|
||||
if (seq !== requestSeq || requestDiagnosisId !== diagnosisId.value) return
|
||||
if (seq !== requestSeq) return
|
||||
bloodRecords.value = Array.isArray(data?.blood_records) ? data.blood_records : []
|
||||
dietRecords.value = Array.isArray(data?.diet_records) ? data.diet_records : []
|
||||
exerciseRecords.value = Array.isArray(data?.exercise_records) ? data.exercise_records : []
|
||||
trackingNotes.value = Array.isArray(noteData)
|
||||
? noteData.filter((item: any) => requestDates.includes(String(item?.note_date || '')))
|
||||
? noteData.filter((item: any) => visibleDates.value.includes(String(item?.note_date || '')))
|
||||
: []
|
||||
} catch {
|
||||
if (seq === requestSeq) {
|
||||
@@ -953,88 +890,76 @@ function handleCustomRangeChange() {
|
||||
}
|
||||
}
|
||||
|
||||
function recordTimeKey(value: unknown) {
|
||||
const time = String(value || '')
|
||||
return /^\d{2}:\d{2}$/.test(time) ? `${time}:00` : time
|
||||
}
|
||||
|
||||
function openBloodRecord(source: BloodRecord | undefined, date: string) {
|
||||
if (!canEditDailyRecord.value) return
|
||||
bloodForm.value = { ...createBloodForm(date), ...source }
|
||||
originalBloodTime.value = recordTimeKey(source?.record_time)
|
||||
bloodDialogVisible.value = true
|
||||
}
|
||||
|
||||
function openDietRecord(source: DietRecord | undefined, date: string) {
|
||||
if (!canEditDailyRecord.value) return
|
||||
dietForm.value = {
|
||||
...createDietForm(date), ...source,
|
||||
breakfast_images: [...(source?.breakfast_images || [])],
|
||||
lunch_images: [...(source?.lunch_images || [])], dinner_images: [...(source?.dinner_images || [])]
|
||||
}
|
||||
dietDialogVisible.value = true
|
||||
}
|
||||
|
||||
function openExerciseRecord(source: ExerciseRecord | undefined, date: string) {
|
||||
if (!canEditDailyRecord.value) return
|
||||
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
|
||||
}
|
||||
|
||||
function openQuickAdd(kind: DialogKind) {
|
||||
if (!canEditDailyRecord.value) return
|
||||
const date = visibleDates.value[0] || formatDate(new Date())
|
||||
if (kind === 'blood') return openBloodRecord(undefined, date)
|
||||
if (kind === 'diet') return openDietRecord(undefined, date)
|
||||
if (kind === 'exercise') return openExerciseRecord(undefined, date)
|
||||
handleCellClick('tracking', todayDate.value)
|
||||
}
|
||||
|
||||
function handleCellClick(metric: string, date: string) {
|
||||
if (!isCellClickable(metric, date)) return
|
||||
if (metric === 'tracking') {
|
||||
const source = trackingByDate.value.get(date)
|
||||
trackingForm.value = { note_date: date, existing_content: String(source?.content || ''), content: '' }
|
||||
if (kind === 'blood') {
|
||||
bloodForm.value = createBloodForm(date)
|
||||
bloodDialogVisible.value = true
|
||||
return
|
||||
}
|
||||
if (kind === 'diet') {
|
||||
dietForm.value = createDietForm(date)
|
||||
dietDialogVisible.value = true
|
||||
return
|
||||
}
|
||||
if (kind === 'tracking') {
|
||||
const today = todayDate.value
|
||||
const source = trackingByDate.value.get(today)
|
||||
trackingForm.value = {
|
||||
note_date: today,
|
||||
existing_content: String(source?.content || ''),
|
||||
content: ''
|
||||
}
|
||||
trackingDialogVisible.value = true
|
||||
return
|
||||
}
|
||||
const count = (bloodByDate.value.get(date)?.length || 0) + (dietByDate.value.get(date)?.length || 0) + (exerciseByDate.value.get(date)?.length || 0)
|
||||
if (count) {
|
||||
detailDate.value = date
|
||||
dayDetailVisible.value = true
|
||||
exerciseForm.value = createExerciseForm(date)
|
||||
exerciseDialogVisible.value = true
|
||||
}
|
||||
|
||||
function handleCellClick(metric: string, date: string) {
|
||||
if (!canEditDailyRecord.value) return
|
||||
if (['fasting', 'postprandial', 'other', 'bp', 'western', 'insulin'].includes(metric)) {
|
||||
const source = bloodByDate.value.get(date)
|
||||
bloodForm.value = source ? { ...createBloodForm(date), ...source } : createBloodForm(date)
|
||||
bloodDialogVisible.value = true
|
||||
return
|
||||
}
|
||||
if (['breakfast', 'lunch', 'dinner'].includes(metric)) return openDietRecord(undefined, date)
|
||||
if (metric === 'exercise') return openExerciseRecord(undefined, date)
|
||||
openBloodRecord(undefined, date)
|
||||
if (['breakfast', 'lunch', 'dinner'].includes(metric)) {
|
||||
const source = dietByDate.value.get(date)
|
||||
dietForm.value = source ? { ...createDietForm(date), ...source } : createDietForm(date)
|
||||
dietDialogVisible.value = true
|
||||
return
|
||||
}
|
||||
if (metric === 'tracking') {
|
||||
const source = trackingByDate.value.get(date)
|
||||
if (!source && date !== todayDate.value) return
|
||||
trackingForm.value = {
|
||||
note_date: date,
|
||||
existing_content: String(source?.content || ''),
|
||||
content: ''
|
||||
}
|
||||
trackingDialogVisible.value = true
|
||||
return
|
||||
}
|
||||
const source = exerciseByDate.value.get(date)
|
||||
exerciseForm.value = source ? { ...createExerciseForm(date), ...source } : createExerciseForm(date)
|
||||
exerciseDialogVisible.value = true
|
||||
}
|
||||
|
||||
async function submitBlood() {
|
||||
if (!canEditDailyRecord.value || bloodSubmitting.value) return
|
||||
if (!bloodForm.value.record_date) {
|
||||
feedback.msgWarning('请选择记录日期')
|
||||
return
|
||||
}
|
||||
const targetDiagnosisId = diagnosisId.value
|
||||
const payload = { ...bloodForm.value }
|
||||
if ('record_time_estimated' in payload && recordTimeKey(payload.record_time) !== originalBloodTime.value) {
|
||||
payload.record_time_estimated = 0
|
||||
payload.record_time_period = ''
|
||||
payload.record_time_text = ''
|
||||
}
|
||||
bloodSubmitting.value = true
|
||||
try {
|
||||
if (payload.id) {
|
||||
await bloodRecordEdit(payload)
|
||||
if (bloodForm.value.id) {
|
||||
await bloodRecordEdit(bloodForm.value)
|
||||
} else {
|
||||
await bloodRecordAdd(payload)
|
||||
await bloodRecordAdd(bloodForm.value)
|
||||
}
|
||||
if (targetDiagnosisId !== diagnosisId.value) return
|
||||
bloodDialogVisible.value = false
|
||||
await fetchTracking()
|
||||
} finally {
|
||||
@@ -1043,21 +968,17 @@ async function submitBlood() {
|
||||
}
|
||||
|
||||
async function submitDiet() {
|
||||
if (!canEditDailyRecord.value || dietSubmitting.value) return
|
||||
if (!dietForm.value.record_date) {
|
||||
feedback.msgWarning('请选择记录日期')
|
||||
return
|
||||
}
|
||||
const targetDiagnosisId = diagnosisId.value
|
||||
const payload = { ...dietForm.value }
|
||||
dietSubmitting.value = true
|
||||
try {
|
||||
if (payload.id) {
|
||||
await dietRecordEdit(payload)
|
||||
if (dietForm.value.id) {
|
||||
await dietRecordEdit(dietForm.value)
|
||||
} else {
|
||||
await dietRecordAdd(payload)
|
||||
await dietRecordAdd(dietForm.value)
|
||||
}
|
||||
if (targetDiagnosisId !== diagnosisId.value) return
|
||||
dietDialogVisible.value = false
|
||||
await fetchTracking()
|
||||
} finally {
|
||||
@@ -1066,7 +987,6 @@ async function submitDiet() {
|
||||
}
|
||||
|
||||
async function submitExercise() {
|
||||
if (!canEditDailyRecord.value || exerciseSubmitting.value) return
|
||||
if (!exerciseForm.value.record_date) {
|
||||
feedback.msgWarning('请选择记录日期')
|
||||
return
|
||||
@@ -1075,20 +995,17 @@ async function submitExercise() {
|
||||
feedback.msgWarning('请选择运动类型')
|
||||
return
|
||||
}
|
||||
if (!exerciseForm.value.id && !exerciseForm.value.duration) {
|
||||
if (!exerciseForm.value.duration) {
|
||||
feedback.msgWarning('请输入运动时长')
|
||||
return
|
||||
}
|
||||
const targetDiagnosisId = diagnosisId.value
|
||||
const payload = { ...exerciseForm.value, duration: exerciseForm.value.duration ?? null, intensity: exerciseForm.value.intensity ?? null }
|
||||
exerciseSubmitting.value = true
|
||||
try {
|
||||
if (payload.id) {
|
||||
await exerciseRecordEdit(payload)
|
||||
if (exerciseForm.value.id) {
|
||||
await exerciseRecordEdit(exerciseForm.value)
|
||||
} else {
|
||||
await exerciseRecordAdd(payload)
|
||||
await exerciseRecordAdd(exerciseForm.value)
|
||||
}
|
||||
if (targetDiagnosisId !== diagnosisId.value) return
|
||||
exerciseDialogVisible.value = false
|
||||
await fetchTracking()
|
||||
} finally {
|
||||
@@ -1097,7 +1014,6 @@ async function submitExercise() {
|
||||
}
|
||||
|
||||
async function submitTracking() {
|
||||
if (trackingSubmitting.value) return
|
||||
if (!trackingForm.value.note_date) {
|
||||
feedback.msgWarning('请选择记录日期')
|
||||
return
|
||||
@@ -1111,14 +1027,12 @@ async function submitTracking() {
|
||||
feedback.msgWarning('请输入跟踪备注')
|
||||
return
|
||||
}
|
||||
const targetDiagnosisId = diagnosisId.value
|
||||
trackingSubmitting.value = true
|
||||
try {
|
||||
await diagnosisAddTrackingNote({
|
||||
diagnosis_id: targetDiagnosisId,
|
||||
diagnosis_id: diagnosisId.value,
|
||||
tracking_content: content
|
||||
})
|
||||
if (targetDiagnosisId !== diagnosisId.value) return
|
||||
trackingDialogVisible.value = false
|
||||
await fetchTracking()
|
||||
} finally {
|
||||
@@ -1143,23 +1057,17 @@ function getTrackingPreview(content: string) {
|
||||
}
|
||||
|
||||
function isCellClickable(metric: string, date: string) {
|
||||
if (metric === 'tracking') return !!getTrackingContent(date) || (canEditDailyRecord.value && date === todayDate.value)
|
||||
return canEditDailyRecord.value || getDayRecordCount(metric, date) > 0
|
||||
if (!canEditDailyRecord.value) return false
|
||||
if (metric !== 'tracking') return true
|
||||
return date === todayDate.value || !!getTrackingContent(date)
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.diagnosisId,
|
||||
() => {
|
||||
dayDetailVisible.value = false
|
||||
bloodDialogVisible.value = false
|
||||
dietDialogVisible.value = false
|
||||
exerciseDialogVisible.value = false
|
||||
trackingDialogVisible.value = false
|
||||
bloodRecords.value = []
|
||||
dietRecords.value = []
|
||||
exerciseRecords.value = []
|
||||
trackingNotes.value = []
|
||||
void fetchTracking()
|
||||
(value) => {
|
||||
if (value) {
|
||||
fetchTracking()
|
||||
}
|
||||
void nextTick(updateTableWrapWidth)
|
||||
}
|
||||
)
|
||||
@@ -1173,7 +1081,6 @@ onMounted(() => {
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
requestSeq++
|
||||
window.removeEventListener('resize', updateTableWrapWidth)
|
||||
})
|
||||
|
||||
@@ -1209,29 +1116,6 @@ defineExpose({ refresh: fetchTracking })
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
&__hint, &__time-evidence {
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: 12px;
|
||||
line-height: 1.6;
|
||||
margin: 0 0 12px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
&__record-count { color: var(--el-color-primary); font-size: 11px; white-space: nowrap; }
|
||||
&__detail-section + &__detail-section { margin-top: 24px; }
|
||||
&__detail-heading { display: flex; justify-content: space-between; align-items: center; gap: 12px; }
|
||||
&__detail-heading h3 { margin: 0 0 8px; }
|
||||
&__detail-heading small { color: var(--el-text-color-secondary); font-weight: normal; }
|
||||
&__detail-record { border: 1px solid var(--el-border-color); border-radius: 8px; padding: 12px; margin-bottom: 12px; }
|
||||
&__detail-tags { display: flex; gap: 8px; flex-wrap: wrap; margin: 8px 0; }
|
||||
&__detail-fields {
|
||||
display: grid; grid-template-columns: 96px minmax(0, 1fr); gap: 8px; margin: 12px 0 0;
|
||||
dt { color: var(--el-text-color-secondary); }
|
||||
dd { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
}
|
||||
&__detail-images { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 8px; }
|
||||
&__detail-images .el-image { width: 64px; height: 64px; border-radius: 4px; }
|
||||
|
||||
&__chart {
|
||||
margin-top: 16px;
|
||||
padding: 16px 18px;
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
<template>
|
||||
<span v-if="readonly" class="readonly-value">{{ fieldText(modelValue, field) }}</span>
|
||||
<el-input-number v-else-if="field.type === 'number'" :model-value="numberValue" :disabled="disabled" :controls="false" @update:model-value="(value: number | undefined | null) => emit('update:modelValue', value ?? null)" />
|
||||
<el-select v-else-if="field.type === 'select' || field.type === 'multiselect'" :model-value="selectValue" :multiple="field.type === 'multiselect'" :disabled="disabled" clearable filterable @update:model-value="(value: FollowupValue) => emit('update:modelValue', value)">
|
||||
<el-option v-for="option in field.options || []" :key="String(option.value)" :label="option.label" :value="option.value" />
|
||||
</el-select>
|
||||
<el-date-picker v-else-if="field.type === 'date'" :model-value="textValue" type="date" value-format="YYYY-MM-DD" :disabled="disabled" @update:model-value="(value: string | null) => emit('update:modelValue', value || null)" />
|
||||
<el-input v-else :model-value="textValue" type="textarea" :autosize="{ minRows: 1, maxRows: 5 }" :disabled="disabled" @update:model-value="(value: FollowupValue) => emit('update:modelValue', value)" />
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import type { FollowupField, FollowupValue } from '@/api/followupAudio'
|
||||
import { fieldText } from './followupAudioState'
|
||||
const props = defineProps<{ field: FollowupField; modelValue?: FollowupValue; disabled?: boolean; readonly?: boolean }>()
|
||||
const emit = defineEmits<{ (event: 'update:modelValue', value: FollowupValue): void }>()
|
||||
const numberValue = computed(() => props.modelValue === null || props.modelValue === undefined || props.modelValue === '' ? undefined : Number(props.modelValue))
|
||||
const textValue = computed(() => props.modelValue === null || props.modelValue === undefined ? '' : String(props.modelValue))
|
||||
const selectValue = computed(() => {
|
||||
const canonical = (value: string | number) => props.field.options?.find(option => String(option.value) === String(value))?.value ?? value
|
||||
if (props.field.type === 'multiselect') return Array.isArray(props.modelValue) ? props.modelValue.map(canonical) : []
|
||||
return typeof props.modelValue === 'string' || typeof props.modelValue === 'number' ? canonical(props.modelValue) : ''
|
||||
})
|
||||
</script>
|
||||
<style scoped>
|
||||
.readonly-value { white-space: pre-wrap; overflow-wrap: anywhere; line-height: 1.6; }
|
||||
</style>
|
||||
@@ -1,722 +0,0 @@
|
||||
<template>
|
||||
<section v-if="featureEnabled" class="followup-panel" aria-label="回访录音">
|
||||
<div class="panel-toolbar">
|
||||
<div class="toolbar-title">
|
||||
<el-button v-if="selectedId" link type="primary" :disabled="busy" @click="backToList">返回列表</el-button>
|
||||
<h3 v-else>回访录音 <span>{{ tasks.length }}</span></h3>
|
||||
</div>
|
||||
<div class="toolbar-actions">
|
||||
<el-button link :aria-expanded="helpVisible" @click="helpVisible = !helpVisible">使用说明</el-button>
|
||||
<el-button :loading="loading" :disabled="busy" @click="refresh">刷新</el-button>
|
||||
<el-button v-if="!selectedId && !viewOnly && capabilities.can_upload" type="primary" :disabled="!canUpload || busy || createUncertain" @click="openUpload">上传录音</el-button>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="helpVisible" class="help-box">
|
||||
<p v-if="previewOnly">{{ capabilities.preview_only ? '当前仅开放测试识别与提炼,可核对并保存审核草稿;测试预览任务不提供确认写入。' : '这是历史测试任务,不写入病例;新上传的真实录音可按正常业务流程审核后确认入单。' }}</p>
|
||||
<p v-else>录音只生成建议,不会自动写入。逐项核对后选择采纳,再确认写入;日常记录按日期和时段分别保留。</p>
|
||||
<p>仅当前可见标签页每 5 秒刷新;已编辑内容不会被覆盖。后台分析不受关闭页面影响,未知结果请先核对任务或账单,勿重复上传。</p>
|
||||
<p v-if="detail">任务 #{{ detail.id }} · 版本 {{ detail.version }} · 保留至 {{ formatExpiry(detail.expires_at) }}</p>
|
||||
</div>
|
||||
<el-alert v-if="previewOnly" type="warning" :closable="false" :title="capabilities.preview_only ? '仅测试识别与提炼,不写入病例' : '历史测试任务,仅供查看和审阅'" description="此任务保留测试用途。新业务录音请新建任务,人工核对后确认入单。" show-icon />
|
||||
<el-alert v-if="!audioReady" type="warning" :closable="false" :title="capabilities.preview_only ? '测试预览尚未就绪,暂不可上传或重试。已有任务可查看。' : '当前环境尚未通过音频能力验证,暂不可上传或重试。已有任务可查看。'" />
|
||||
<el-alert v-else-if="capabilities.can_upload && !capabilities.models.length" type="warning" :closable="false" title="暂无可用的分析模型,暂不可上传。已有任务可查看。" />
|
||||
<el-alert v-if="basicDirty" type="warning" :closable="false" :title="previewOnly ? '病历有未保存修改,测试预览不会覆盖这些修改。' : '病历有未保存修改,请先保存病历,再写入录音建议。'" />
|
||||
<el-alert v-if="createUncertain" type="warning" :closable="false" title="创建结果未确认,已停止重复提交。请刷新列表并联系管理员核对,不要重新上传同一录音。" />
|
||||
<el-alert v-if="errorMessage" type="error" :closable="false" :title="errorMessage" show-icon />
|
||||
<div v-if="!selectedId" class="task-list">
|
||||
<el-table :data="tasks" max-height="440" size="small" table-layout="fixed" empty-text="暂无录音,上传后可提炼回访资料" aria-label="录音任务列表">
|
||||
<el-table-column label="录音" min-width="210">
|
||||
<template #default="{ row }">
|
||||
<el-button class="filename-button" link type="primary" :disabled="busy" @click="openTask(row.id)">{{ row.file_name }}</el-button>
|
||||
<div class="task-time">{{ row.recorded_at }}</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<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="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>
|
||||
<div v-else-if="!detail" class="detail-loading" role="status">正在加载录音任务…</div>
|
||||
<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>
|
||||
<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 || '任务处理失败,不能写入;请先核对失败原因。'" />
|
||||
<el-alert v-if="retainedTranscriptNotice(detail)" type="warning" :closable="false" :title="retainedTranscriptNotice(detail)" />
|
||||
<el-alert v-if="detail.status === 'needs_reconciliation'" type="error" :closable="false" title="上游结果待核对,禁止重发。请管理员先确认上游任务或账单。" />
|
||||
<el-alert v-if="detail.status === 'expired'" type="warning" :closable="false" title="录音和转录已过保留期,不能继续写入;已采纳的业务记录保留。" />
|
||||
<el-button v-if="detail.can_retry && detail.status === 'failed' && !viewOnly" class="retry-button" :disabled="!canUpload || busy" @click="retryTask">重试已确认失败的任务</el-button>
|
||||
<div class="summary-box">
|
||||
<div class="muted">回访摘要 · AI未核实草稿,不代表已确认病情</div>
|
||||
<p>{{ detail.summary || '暂无回访摘要' }}</p>
|
||||
<div class="summary-counts"><span>{{ detail.status === 'applied' ? '已写入' : '已选' }} <strong>{{ selectedCount }}</strong> 项</span><span>待核实 <strong>{{ pendingCount }}</strong> 项</span></div>
|
||||
</div>
|
||||
<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">
|
||||
<el-button v-if="detail.audio_available" size="small" :loading="audioLoading" @click="reloadAudio">{{ audioUrl ? '重新加载录音' : '加载录音播放' }}</el-button>
|
||||
<span v-else class="muted">录音不可播放或已清理</span>
|
||||
<audio v-if="audioUrl" :key="audioUrl" ref="audioElement" :src="audioUrl" controls preload="metadata" />
|
||||
</div>
|
||||
<div v-if="hasStereo && detail.audio_available" class="channel-playback" aria-label="声道回听">
|
||||
<el-button size="small" :type="playbackChannel === 'original' ? 'primary' : 'default'" :aria-pressed="playbackChannel === 'original'" :disabled="audioLoading || channelLoading" @click="playChannel('original')">完整对话</el-button>
|
||||
<el-button v-for="channel in ([0, 1] as const)" :key="channel" size="small" :type="playbackChannel === channel ? 'primary' : 'default'" :aria-pressed="playbackChannel === channel" :disabled="audioLoading || channelLoading" @click="playChannel(channel)">{{ channelPlaybackLabel(channel, savedChannelRoles) }}</el-button>
|
||||
<span class="muted" role="status">{{ channelLoading ? '正在切换声道…' : !audioUrl ? '尚未加载录音' : playbackChannel === 'original' ? '回听模式:双方对话' : `回听模式:仅${playbackChannel === 0 ? '左' : '右'}声道` }}</span>
|
||||
</div>
|
||||
<p v-if="playbackError" class="review-error" role="alert">{{ playbackError }}</p>
|
||||
<p v-if="detail.audio_available" class="muted">回听对话默认从该区间前 3 秒开始,连续播放双方声音;可随时切换为只听一方。</p>
|
||||
</template>
|
||||
</FollowupAudioReview>
|
||||
<el-collapse v-model="detailSections" class="original-collapse">
|
||||
<el-collapse-item title="完整对话转写" name="original">
|
||||
<div v-if="transcriptSegments.length" class="transcript-segments">
|
||||
<p class="muted">双方转写按同一时间区间并列展示,不表示发言先后;重叠发言与具体问答请结合录音核对。</p>
|
||||
<section v-for="window in conversationWindows" :key="window.id" class="transcript-segment">
|
||||
<div class="segment-heading"><span>{{ audioTimestamp(window.start_ms) }}–{{ audioTimestamp(window.end_ms) }}</span><el-button v-if="detail.audio_available" link type="primary" @click="loadDialogue(window.start_ms)">回听双方对话</el-button></div>
|
||||
<div class="dialogue-sides">
|
||||
<div v-for="segment in window.segments" :key="segment.id" class="dialogue-side">
|
||||
<strong>{{ followupChannelLabel(segment.channel, savedChannelRoles) }}</strong>
|
||||
<pre>{{ segment.text || '(该区间无转写文本,不代表没有说话)' }}</pre>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
<pre v-else class="transcript-text">{{ detail.transcript || '暂无转录' }}</pre>
|
||||
</el-collapse-item>
|
||||
</el-collapse>
|
||||
<div v-if="detail.status === 'review'" class="review-actions">
|
||||
<div class="selection-summary"><strong>已选 {{ selectedCount }} 项</strong><span>{{ saveStatusText }}</span></div>
|
||||
<div v-if="canEditReview" class="action-buttons">
|
||||
<el-button link :disabled="busy" :loading="mutation === 'save'" @click="saveDraft()">{{ saveState === 'error' || saveState === 'conflict' ? '重试保存草稿' : '立即保存草稿' }}</el-button>
|
||||
<el-button v-if="canApplyReview" type="primary" :disabled="busy || basicDirty || !selectedCount || !!applyIssue" :loading="mutation === 'apply'" @click="applySelected">确认写入</el-button>
|
||||
</div>
|
||||
<p v-if="applyIssue" class="review-error" role="alert">{{ applyIssue }}</p>
|
||||
</div>
|
||||
<p v-if="detail.status === 'applied'" class="applied-note">{{ previewOnly ? '该任务已有历史采纳记录;当前为测试预览,不允许再次写入。' : '本次审核已完成,所选项已写入诊单或日常记录,不能重复写入。' }}</p>
|
||||
</section>
|
||||
<el-dialog v-model="uploadVisible" title="上传回访录音" width="min(520px, calc(100vw - 32px))" append-to-body :close-on-click-modal="false" :close-on-press-escape="!uploading" :show-close="!uploading" :before-close="closeUpload">
|
||||
<el-form label-position="top" class="upload-form">
|
||||
<el-form-item label="录音文件">
|
||||
<input ref="fileInput" type="file" accept="audio/mpeg,audio/mp4,audio/wav,audio/amr,.mp3,.m4a,.wav,.amr" :disabled="!canUpload || busy || createUncertain" aria-label="录音文件" @change="chooseFile" />
|
||||
<small>支持 MP3 / M4A / WAV / AMR,最多 {{ Math.floor(capabilities.limits.max_bytes / 1024 / 1024) }} MB / {{ Math.floor(capabilities.limits.max_seconds / 60) }} 分钟。</small>
|
||||
</el-form-item>
|
||||
<el-form-item label="实际通话时间(北京时间)">
|
||||
<el-date-picker v-model="recordedAt" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="用于识别昨天、前天等相对日期" :disabled="!canUpload || busy || createUncertain" />
|
||||
</el-form-item>
|
||||
<el-form-item label="本次录音的声道角色">
|
||||
<el-select v-model="uploadChannelRoles" aria-label="本次录音的声道角色" :disabled="!canUpload || busy || createUncertain">
|
||||
<el-option label="暂不确定 / 单声道" value="unconfirmed" />
|
||||
<el-option label="左客服 / 右患者或家属" value="left_service" />
|
||||
<el-option label="右客服 / 左患者或家属" value="right_service" />
|
||||
</el-select>
|
||||
<small>已知角色会在提炼前提供给模型;不确定请勿猜测。单声道不按左右区分身份。</small>
|
||||
</el-form-item>
|
||||
<el-collapse class="advanced-settings">
|
||||
<el-collapse-item title="高级设置 · 分析模型" name="model">
|
||||
<el-form-item label="分析模型">
|
||||
<el-select v-model="modelKey" :disabled="!canUpload || busy || createUncertain" placeholder="选择已配置的模型"><el-option v-for="model in capabilities.models" :key="model.value" :label="model.label" :value="model.value" /></el-select>
|
||||
</el-form-item>
|
||||
</el-collapse-item>
|
||||
</el-collapse>
|
||||
</el-form>
|
||||
<el-alert v-if="errorMessage" type="error" :closable="false" :title="errorMessage" show-icon />
|
||||
<el-alert v-if="createUncertain && !uploading" type="warning" :closable="false" title="创建结果未确认,请关闭弹窗后刷新任务列表并联系管理员核对,不要重新上传。" />
|
||||
<el-progress v-if="uploading" :percentage="uploadProgress" />
|
||||
<p v-if="uploadStage" class="upload-stage" role="status">{{ uploadStage }}</p>
|
||||
<p class="muted">{{ previewOnly ? '本次仅测试识别与提炼,可保存审核草稿,不允许写入病历。' : '分析仅生成建议,人工确认后才会写入。' }}</p>
|
||||
<template #footer><el-button :disabled="uploading" @click="closeUpload()">取消</el-button><el-button type="primary" :disabled="!canUpload || busy || createUncertain" :loading="uploading" @click="submitUpload">上传并分析</el-button></template>
|
||||
</el-dialog>
|
||||
</section>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import {
|
||||
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, 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;
|
||||
basicDirty?: boolean; beforeApply?: () => boolean
|
||||
}>(), { viewOnly: false, active: true, basicDirty: false })
|
||||
const emit = defineEmits<{ (event: 'applied', diagnosisId: number): void }>()
|
||||
const tasks = ref<FollowupTaskSummary[]>([])
|
||||
const detail = ref<FollowupTaskDetail | null>(null)
|
||||
const reviewItems = ref<FollowupReviewItem[]>([])
|
||||
const selectedId = ref(0)
|
||||
const snapshot = ref('[]')
|
||||
const channelRoles = ref<FollowupChannelRoles>('unconfirmed')
|
||||
const roleSnapshot = ref<FollowupChannelRoles>('unconfirmed')
|
||||
const editingRoles = ref(false)
|
||||
const saveState = ref<'idle' | 'pending' | 'saving' | 'saved' | 'error' | 'conflict'>('idle')
|
||||
const persistedRevision = ref(0)
|
||||
const committedDirty = computed(() => roleDirty.value || JSON.stringify(reviewItems.value) !== snapshot.value)
|
||||
const saveStatusText = computed(() => saveState.value === 'saving' ? '正在自动保存…'
|
||||
: saveState.value === 'error' ? '保存失败,修改仍保留;请重试保存'
|
||||
: saveState.value === 'conflict' ? '自动保存已暂停;请重新核对后重试保存'
|
||||
: committedDirty.value ? '等待自动保存…'
|
||||
: reviewRef.value?.hasUnsavedChanges() ? '当前单项尚未完成核对'
|
||||
: saveState.value === 'saved' ? '审核草稿已自动保存' : '草稿已同步')
|
||||
const roleDirty = computed(() => channelRoles.value !== roleSnapshot.value)
|
||||
const savedChannelRoles = computed(() => normalizedChannelRoles(detail.value?.channel_roles))
|
||||
const transcriptSegments = computed(() => [...(detail.value?.transcript_segments || [])].sort((a, b) => a.start_ms - b.start_ms || (a.channel ?? -1) - (b.channel ?? -1)))
|
||||
const conversationWindows = computed(() => dialogueWindows(transcriptSegments.value))
|
||||
const hasStereo = computed(() => hasStereoTranscript(transcriptSegments.value))
|
||||
const reviewRef = ref<{ hasUnsavedChanges: () => boolean } | null>(null)
|
||||
const dirty = computed(() => roleDirty.value || JSON.stringify(reviewItems.value) !== snapshot.value || !!reviewRef.value?.hasUnsavedChanges())
|
||||
const uploadVisible = ref(false)
|
||||
const helpVisible = ref(false)
|
||||
const detailSections = ref<string[]>([])
|
||||
const file = ref<File | null>(null)
|
||||
const fileInput = ref<HTMLInputElement | null>(null)
|
||||
const recordedAt = ref('')
|
||||
const uploadChannelRoles = ref<FollowupChannelRoles>('unconfirmed')
|
||||
const modelKey = ref(props.capabilities.models[0]?.value || '')
|
||||
const loading = ref(false)
|
||||
const uploading = ref(false)
|
||||
const uploadProgress = ref(0)
|
||||
const uploadStage = ref('')
|
||||
const createUncertain = ref(false)
|
||||
const mutation = ref<'save' | 'apply' | 'retry' | 'delete' | 'reextract' | ''>('')
|
||||
const errorMessage = ref('')
|
||||
const audioUrl = ref('')
|
||||
const audioElement = ref<HTMLAudioElement | null>(null)
|
||||
const audioLoading = ref(false)
|
||||
const playbackChannel = ref<FollowupPlaybackChannel>('original')
|
||||
const channelLoading = ref(false)
|
||||
const playbackError = ref('')
|
||||
const documentVisible = ref(typeof document === 'undefined' || document.visibilityState !== 'hidden')
|
||||
const busy = computed(() => uploading.value || !!mutation.value)
|
||||
const featureEnabled = computed(() => followupFeatureEnabled(props.capabilities))
|
||||
const previewOnly = computed(() => !!props.capabilities.preview_only || !!detail.value?.preview_only)
|
||||
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 ? '测试预览仅保存审核草稿,不允许确认写入病历'
|
||||
: saveState.value === 'conflict' ? '记录版本已变化,请重新核对后重试保存草稿'
|
||||
: saveState.value === 'error' ? '草稿保存失败,请重试保存成功后再确认写入'
|
||||
: saveState.value === 'saving' || committedDirty.value ? '审核草稿尚未保存完成,请稍候再确认写入'
|
||||
: roleDirty.value ? '声道角色标注尚未保存,请先保存草稿并重新核对建议'
|
||||
: hasStereo.value && savedChannelRoles.value === 'unconfirmed' ? '请先回听并确认声道角色,保存草稿后重新核对建议'
|
||||
: changedReviewTarget(reviewItems.value, detail.value?.items || [])
|
||||
? '写入目标或记录日期已更改,请先保存审核草稿取得新快照,再核对并采纳'
|
||||
: 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
|
||||
let autosaveTimer: ReturnType<typeof setTimeout> | undefined
|
||||
let hydrating = false
|
||||
let savePromise: Promise<void> | null = null
|
||||
let pollRunning = false
|
||||
let audioRequest = 0
|
||||
let playbackRequest = 0
|
||||
let playback: ReturnType<typeof createFollowupAudioPlayback> | null = null
|
||||
let playbackElement: HTMLAudioElement | null = null
|
||||
let lastDiagnosis = 0
|
||||
function clearTimer() { if (timer !== undefined) clearTimeout(timer); timer = undefined }
|
||||
function releaseAudio() {
|
||||
audioRequest++; playbackRequest++
|
||||
playback?.dispose(); playback = null; playbackElement = null
|
||||
audioElement.value?.pause()
|
||||
if (audioUrl.value) URL.revokeObjectURL(audioUrl.value)
|
||||
audioUrl.value = ''; audioLoading.value = false; channelLoading.value = false; playbackChannel.value = 'original'; playbackError.value = ''
|
||||
}
|
||||
function stop() {
|
||||
scope.invalidate(); clearTimer(); clearAutosave(); releaseAudio()
|
||||
savePromise = null
|
||||
if (saveState.value === 'saving') { saveState.value = 'error'; errorMessage.value = '保存结果尚未确认;修改仍保留,请刷新核对版本后重试保存。' }
|
||||
loading.value = false; uploading.value = false; mutation.value = ''; pollRunning = false
|
||||
}
|
||||
function installDetail(fresh: FollowupTaskDetail, preserve: boolean, preserveRoles = preserve) {
|
||||
// Completed tasks use the server's confirmed snapshot, never an unsaved local draft.
|
||||
preserve = preserve && fresh.status === 'review'
|
||||
const keepRoles = preserveRoles && roleDirty.value && fresh.status === 'review'
|
||||
if (!fresh.audio_available) releaseAudio()
|
||||
if (retainedTranscriptNotice(fresh) && (!detail.value || detail.value.status !== fresh.status || !detail.value.transcript_available)) {
|
||||
if (!detailSections.value.includes('original')) detailSections.value = [...detailSections.value, 'original']
|
||||
}
|
||||
hydrating = true
|
||||
try {
|
||||
detail.value = fresh
|
||||
const nextItems = preserve ? rebaseReviewItems(reviewItems.value, fresh.items) : cloneReviewItems(fresh.items)
|
||||
if (JSON.stringify(nextItems) !== JSON.stringify(reviewItems.value)) reviewItems.value = nextItems
|
||||
snapshot.value = JSON.stringify(fresh.items)
|
||||
roleSnapshot.value = normalizedChannelRoles(fresh.channel_roles)
|
||||
if (!keepRoles) channelRoles.value = roleSnapshot.value
|
||||
} finally { hydrating = false }
|
||||
}
|
||||
function resetRoles() { hydrating = true; channelRoles.value = 'unconfirmed'; roleSnapshot.value = 'unconfirmed'; hydrating = false; editingRoles.value = false; saveState.value = 'idle'; persistedRevision.value = 0 }
|
||||
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
|
||||
}
|
||||
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()
|
||||
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'
|
||||
installDetail(fresh, preserve)
|
||||
if (newlyApplied && !previewOnly.value) emit('applied', props.diagnosisId)
|
||||
if (preserve && fresh.status === 'review') { clearAutosave(); saveState.value = 'conflict'; errorMessage.value = '服务端记录或版本已变化;已保留你的字段与日期修改,并取消所有选择。自动保存已暂停,请重新核对后重试保存草稿。' }
|
||||
else if (preserve && newlyApplied) errorMessage.value = '任务已由其他人确认,已显示实际写入结果;本页未保存的修改未写入。'
|
||||
}
|
||||
async function refresh() {
|
||||
if (!effectiveActive.value || !props.diagnosisId || pollRunning || busy.value) return
|
||||
const ticket = scope.capture()
|
||||
pollRunning = true; loading.value = true; clearTimer()
|
||||
try {
|
||||
const response = await followupAudioLists(props.diagnosisId, ticket.signal)
|
||||
if (!scope.current(ticket)) return
|
||||
tasks.value = response.items
|
||||
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 {
|
||||
if (scope.current(ticket)) {
|
||||
pollRunning = false; loading.value = false
|
||||
if (effectiveActive.value) timer = setTimeout(() => { void refresh() }, 5000)
|
||||
}
|
||||
}
|
||||
}
|
||||
async function confirmLeave(): Promise<boolean> {
|
||||
if (busy.value) { ElMessage.warning('正在上传或提交审核,请等待本次操作结束'); return false }
|
||||
if (!dirty.value) return true
|
||||
try {
|
||||
await ElMessageBox.confirm('审核修改尚未保存。关闭诊单或切换录音将丢失这些修改,是否继续?', '保留审核修改', { type: 'warning', confirmButtonText: '继续离开', cancelButtonText: '返回保存' })
|
||||
return true
|
||||
} catch { return false }
|
||||
}
|
||||
async function openTask(id: number) {
|
||||
if (!featureEnabled.value || id === selectedId.value || busy.value) return
|
||||
const previous = scope.capture()
|
||||
if (!await confirmLeave() || !scope.current(previous)) return
|
||||
stop(); resetRoles(); selectedId.value = id; detail.value = null; reviewItems.value = []; snapshot.value = '[]'; errorMessage.value = ''; detailSections.value = []
|
||||
const ticket = scope.capture()
|
||||
try { await readDetail(id) } catch (error) { if (scope.current(ticket)) errorMessage.value = followupError(error) }
|
||||
if (scope.current(ticket)) await refresh()
|
||||
}
|
||||
async function backToList() {
|
||||
const ticket = scope.capture()
|
||||
if (!await confirmLeave() || !scope.current(ticket)) return
|
||||
stop(); resetRoles(); selectedId.value = 0; detail.value = null; reviewItems.value = []; snapshot.value = '[]'; detailSections.value = []; errorMessage.value = ''
|
||||
await refresh()
|
||||
}
|
||||
function openUpload() {
|
||||
if (!canUpload.value || busy.value || createUncertain.value) return
|
||||
if (!file.value) uploadChannelRoles.value = 'unconfirmed'
|
||||
uploadVisible.value = true
|
||||
}
|
||||
function closeUpload(done?: () => void) { if (uploading.value) return; uploadVisible.value = false; done?.() }
|
||||
function statusType(status: string) {
|
||||
if (status === 'failed' || status === 'needs_reconciliation') return 'danger'
|
||||
if (status === 'applied') return 'success'
|
||||
if (status === 'review') return 'warning'
|
||||
return 'info'
|
||||
}
|
||||
function chooseFile(event: Event) {
|
||||
const nextFile = (event.target as HTMLInputElement).files?.[0] || null
|
||||
// Cancelling the picker or selecting the first file must not discard a role chosen earlier.
|
||||
if (!nextFile) return
|
||||
if (file.value && nextFile !== file.value) {
|
||||
uploadChannelRoles.value = 'unconfirmed'
|
||||
ElMessage.warning('录音已更换,请重新核对本次录音的声道角色')
|
||||
}
|
||||
file.value = nextFile; uploadProgress.value = 0; uploadStage.value = ''
|
||||
}
|
||||
async function submitUpload() {
|
||||
if (busy.value || createUncertain.value) return
|
||||
const problem = uploadIssue(file.value, recordedAt.value, modelKey.value, props.capabilities, props.viewOnly)
|
||||
if (problem) { ElMessage.warning(problem); return }
|
||||
const recording = file.value
|
||||
if (!recording) return
|
||||
const ticket = scope.capture()
|
||||
uploading.value = true; uploadProgress.value = 0; errorMessage.value = ''; clearTimer()
|
||||
let creating = false
|
||||
try {
|
||||
uploadStage.value = '正在创建私有上传会话'
|
||||
const session = await followupAudioUploadSession({ diagnosis_id: props.diagnosisId, file_name: recording.name, total_bytes: recording.size }, ticket.signal)
|
||||
if (!scope.current(ticket) || !canUpload.value) return
|
||||
uploadStage.value = '正在上传录音分片'
|
||||
const finished = await uploadChunks(recording, session.chunk_bytes,
|
||||
(index, chunk) => followupAudioUploadChunk(session.upload_id, index, chunk, ticket.signal),
|
||||
() => scope.current(ticket) && canUpload.value, percent => { uploadProgress.value = percent })
|
||||
if (!finished) return
|
||||
uploadStage.value = '正在校验录音时长和完整性'
|
||||
await followupAudioUploadComplete(session.upload_id, ticket.signal)
|
||||
if (!scope.current(ticket) || !canUpload.value) return
|
||||
uploadStage.value = '正在创建分析任务'; creating = true; createUncertain.value = true
|
||||
const result = await followupAudioCreate({ diagnosis_id: props.diagnosisId, upload_id: session.upload_id, recorded_at: recordedAt.value, model_key: modelKey.value, channel_roles: uploadChannelRoles.value }, ticket.signal)
|
||||
if (!scope.current(ticket)) return
|
||||
createUncertain.value = false; uploading.value = false; uploadVisible.value = false; file.value = null; if (fileInput.value) fileInput.value.value = ''
|
||||
uploadStage.value = result.reused
|
||||
? result.reuse_message || '同一录音已有任务,已打开原任务,不会重复调用模型'
|
||||
: props.capabilities.preview_only ? '测试任务已创建,后台将识别与提炼;此任务不允许写入业务记录' : '任务已创建,后台将进行分析;审核前不会写入业务记录'
|
||||
if (result.reused) ElMessage.warning(uploadStage.value)
|
||||
await openTask(result.task_id)
|
||||
} catch (error) {
|
||||
if (scope.current(ticket)) { errorMessage.value = followupError(error); createUncertain.value = creating && !(error instanceof FollowupAudioError); uploadStage.value = '本次操作已停止,未自动重试' }
|
||||
} finally { if (scope.current(ticket)) { uploading.value = false; await refresh() } }
|
||||
}
|
||||
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)) {
|
||||
clearAutosave(); saveState.value = 'conflict'
|
||||
try { await readDetail(selectedId.value, true) } catch { if (scope.current(ticket)) errorMessage.value += ';刷新失败,当前编辑仍已保留,请稍后刷新。' }
|
||||
}
|
||||
}
|
||||
function clearAutosave() { if (autosaveTimer !== undefined) clearTimeout(autosaveTimer); autosaveTimer = undefined }
|
||||
function scheduleAutosave() {
|
||||
clearAutosave()
|
||||
if (hydrating || !effectiveActive.value || !canEditReview.value || !committedDirty.value || ['error', 'conflict'].includes(saveState.value)) return
|
||||
if (mutation.value === 'save') return
|
||||
saveState.value = 'pending'
|
||||
autosaveTimer = setTimeout(() => { autosaveTimer = undefined; void saveDraft(true) }, 650)
|
||||
}
|
||||
// Merge only changes made after the request began. Server-owned evidence and hashes always win.
|
||||
function mergeSaveResponse(sent: FollowupReviewItem[], saved: FollowupReviewItem[], local: FollowupReviewItem[]) {
|
||||
const before = new Map(sent.map(item => [item.id, item]))
|
||||
const latest = new Map(local.map(item => [item.id, item]))
|
||||
return cloneReviewItems(saved).map(item => {
|
||||
const previous = before.get(item.id), edit = latest.get(item.id)
|
||||
if (!previous || !edit) return item
|
||||
const serverRequiresReview = (item.needs_review && !previous.needs_review) || (previous.selected && !item.selected)
|
||||
for (const key of ['values', 'record_date', 'record_time', 'time_period', 'target_id', 'selected', 'needs_review'] as const) {
|
||||
if (serverRequiresReview && (key === 'selected' || key === 'needs_review')) continue
|
||||
if (JSON.stringify(previous[key]) !== JSON.stringify(edit[key])) Object.assign(item, { [key]: edit[key] })
|
||||
}
|
||||
return item
|
||||
})
|
||||
}
|
||||
async function saveDraft(automatic = false): Promise<void> {
|
||||
if (savePromise) return savePromise
|
||||
if (!canEditReview.value || !detail.value || busy.value || !effectiveActive.value) return
|
||||
if (!automatic && reviewRef.value?.hasUnsavedChanges()) { ElMessage.warning('请先保存或取消正在核对的单项修改'); return }
|
||||
if (automatic && (!committedDirty.value || ['error', 'conflict'].includes(saveState.value))) return
|
||||
clearAutosave()
|
||||
const ticket = scope.capture(), taskId = detail.value.id, diagnosisId = props.diagnosisId
|
||||
const current = () => scope.current(ticket) && selectedId.value === taskId && props.diagnosisId === diagnosisId
|
||||
const changedRoles = roleDirty.value, sentRoles = channelRoles.value
|
||||
const sentItems = cloneReviewItems(reviewItems.value), version = detail.value.version
|
||||
mutation.value = 'save'; saveState.value = 'saving'; errorMessage.value = ''; clearTimer()
|
||||
const operation = (async () => {
|
||||
try {
|
||||
const saved = await followupAudioSaveDraft({ id: taskId, version, items: sentItems, ...(changedRoles && hasStereo.value ? { channel_roles: sentRoles } : {}) }, ticket.signal)
|
||||
if (!current()) return
|
||||
if (detail.value && saved.version < detail.value.version) {
|
||||
saveState.value = 'conflict'; errorMessage.value = '服务端已有更新版本;自动保存已暂停,请核对当前记录后重试保存。'; return
|
||||
}
|
||||
if (saved.review_refreshed) {
|
||||
const latestRoles = channelRoles.value
|
||||
installDetail(saved, true, false)
|
||||
if (latestRoles !== sentRoles) { hydrating = true; channelRoles.value = latestRoles; hydrating = false }
|
||||
saveState.value = 'conflict'
|
||||
errorMessage.value = '业务记录已变化,版本已刷新;当前编辑已保留,全部选择已取消。自动保存已暂停,请重新核对后重试保存草稿。'
|
||||
} else {
|
||||
const latestRoles = channelRoles.value
|
||||
const merged = changedRoles ? rebaseReviewItems(reviewItems.value, saved.items) : mergeSaveResponse(sentItems, saved.items, reviewItems.value)
|
||||
hydrating = true
|
||||
try {
|
||||
detail.value = saved; snapshot.value = JSON.stringify(saved.items)
|
||||
roleSnapshot.value = normalizedChannelRoles(saved.channel_roles)
|
||||
channelRoles.value = latestRoles === sentRoles ? roleSnapshot.value : latestRoles
|
||||
if (JSON.stringify(merged) !== JSON.stringify(reviewItems.value)) reviewItems.value = merged
|
||||
} finally { hydrating = false }
|
||||
editingRoles.value = roleDirty.value
|
||||
saveState.value = committedDirty.value ? 'pending' : 'saved'
|
||||
if (!committedDirty.value) persistedRevision.value++
|
||||
if (!automatic) ElMessage.success(changedRoles ? '角色标注已保存,全部建议须重新核对;不会自动重新提炼' : previewOnly.value ? '测试审核草稿已保存,不会写入病历' : '审核草稿已保存,尚未写入病历')
|
||||
}
|
||||
} catch (error) {
|
||||
if (current()) {
|
||||
saveState.value = 'error'
|
||||
await handleReviewError(error)
|
||||
if (current() && !['conflict'].includes(saveState.value)) errorMessage.value += ';自动保存已暂停,修改仍保留,请重试保存草稿。'
|
||||
}
|
||||
} finally {
|
||||
if (current()) {
|
||||
mutation.value = ''; savePromise = null
|
||||
scheduleAutosave()
|
||||
await refresh()
|
||||
}
|
||||
}
|
||||
})()
|
||||
savePromise = operation
|
||||
return operation
|
||||
}
|
||||
async function applySelected() {
|
||||
if (!canApplyReview.value || !detail.value || busy.value || !selectedCount.value) return
|
||||
if (reviewRef.value?.hasUnsavedChanges()) { ElMessage.warning('请先保存或取消正在核对的单项修改'); return }
|
||||
if (props.basicDirty || (props.beforeApply && !props.beforeApply())) { ElMessage.warning('请先保存病历表单,当前修改不会被覆盖'); return }
|
||||
if (applyIssue.value) { ElMessage.warning(applyIssue.value); return }
|
||||
const ticket = scope.capture()
|
||||
try { await ElMessageBox.confirm(`将一次性采纳 ${selectedCount.value} 项;任一项冲突则整批不写入。确认已核对原话、日期和时间?`, '确认采纳', { type: 'warning', confirmButtonText: '全部采纳', cancelButtonText: '返回核对' }) } catch { return }
|
||||
if (!scope.current(ticket) || !canApplyReview.value || !selectedCount.value || props.basicDirty || (props.beforeApply && !props.beforeApply()) || !detail.value) return
|
||||
if (applyIssue.value) { ElMessage.warning(applyIssue.value); return }
|
||||
const diagnosisId = props.diagnosisId
|
||||
mutation.value = 'apply'; errorMessage.value = ''; clearTimer()
|
||||
try {
|
||||
await followupAudioApply({ id: detail.value.id, version: detail.value.version, items: cloneReviewItems(reviewItems.value) }, ticket.signal)
|
||||
if (!scope.current(ticket) || !canApplyReview.value) return
|
||||
detail.value = { ...detail.value, status: 'applied' }; snapshot.value = JSON.stringify(reviewItems.value)
|
||||
ElMessage.success('所选记录已全部采纳'); emit('applied', diagnosisId)
|
||||
await readDetail(selectedId.value)
|
||||
} 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()
|
||||
try { await ElMessageBox.confirm('仅对服务端已确认失败、允许重试的任务重新分析。确认继续?', '确认重试', { type: 'warning' }) } catch { return }
|
||||
if (!scope.current(ticket) || !detail.value?.can_retry || detail.value.status !== 'failed' || !canUpload.value) return
|
||||
mutation.value = 'retry'; clearTimer()
|
||||
try { await followupAudioRetry(detail.value.id, ticket.signal); if (scope.current(ticket)) await readDetail(selectedId.value) }
|
||||
catch (error) { if (scope.current(ticket)) errorMessage.value = followupError(error) }
|
||||
finally { if (scope.current(ticket)) { mutation.value = ''; await refresh() } }
|
||||
}
|
||||
async function loadDialogue(milliseconds: number) { await loadAudio(dialoguePlaybackStart(milliseconds)) }
|
||||
async function reloadAudio() { releaseAudio(); await loadAudio() }
|
||||
async function playChannel(channel: FollowupPlaybackChannel) { await loadAudio((audioElement.value?.currentTime || 0) * 1000, channel === 'original' ? undefined : channel) }
|
||||
async function loadAudio(milliseconds?: number, channel?: FollowupAudioChannel) {
|
||||
if (!featureEnabled.value || !detail.value?.audio_available) return
|
||||
const operation = ++playbackRequest
|
||||
playbackError.value = ''
|
||||
if (channel !== undefined && (!hasStereo.value || (channel !== 0 && channel !== 1))) {
|
||||
releaseAudio(); playbackError.value = '未取得可验证的双声道片段,无法隔离声道;请使用原音播放。'; return
|
||||
}
|
||||
const ticket = scope.capture(); const id = detail.value.id
|
||||
if (!audioUrl.value) {
|
||||
const requestId = ++audioRequest; audioLoading.value = true
|
||||
try {
|
||||
const blob = await followupAudioBlob(id, ticket.signal)
|
||||
if (!scope.current(ticket) || requestId !== audioRequest || id !== selectedId.value) return
|
||||
audioUrl.value = URL.createObjectURL(blob)
|
||||
} catch (error) { if (scope.current(ticket) && requestId === audioRequest) errorMessage.value = followupError(error) }
|
||||
finally { if (scope.current(ticket) && requestId === audioRequest) audioLoading.value = false }
|
||||
}
|
||||
await nextTick()
|
||||
if (!scope.current(ticket) || operation !== playbackRequest || id !== selectedId.value || !audioUrl.value || !audioElement.value) return
|
||||
const element = audioElement.value
|
||||
if (playbackElement !== element) { playback?.dispose(); playback = createFollowupAudioPlayback(element); playbackElement = element }
|
||||
const routing = playback
|
||||
channelLoading.value = true
|
||||
try {
|
||||
if (!routing || !await routing.select(channel ?? 'original')) return
|
||||
if (!scope.current(ticket) || operation !== playbackRequest || id !== selectedId.value) return
|
||||
playbackChannel.value = channel ?? 'original'
|
||||
if (typeof milliseconds !== 'number' || !Number.isFinite(milliseconds)) return
|
||||
element.currentTime = Math.max(0, milliseconds / 1000)
|
||||
try { await element.play() } catch { if (scope.current(ticket) && operation === playbackRequest) playbackError.value = '播放未启动,请使用播放器控件继续。' }
|
||||
} catch (error) {
|
||||
if (scope.current(ticket) && operation === playbackRequest) { playbackChannel.value = 'original'; playbackError.value = followupError(error) }
|
||||
} finally { if (scope.current(ticket) && operation === playbackRequest) channelLoading.value = false }
|
||||
}
|
||||
function formatExpiry(value: number | string) {
|
||||
if (!value) return '由保留策略控制'
|
||||
const date = typeof value === 'number' || /^\d+$/.test(value) ? new Date(Number(value) * 1000) : new Date(value)
|
||||
return Number.isNaN(date.getTime()) ? String(value) : date.toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' })
|
||||
}
|
||||
function onVisibility() { documentVisible.value = document.visibilityState !== 'hidden' }
|
||||
watch([() => props.diagnosisId, effectiveActive, () => !!props.capabilities.preview_only], ([id, active]) => {
|
||||
stop()
|
||||
if (id !== lastDiagnosis) {
|
||||
resetRoles(); lastDiagnosis = id; selectedId.value = 0; detail.value = null; reviewItems.value = []; snapshot.value = '[]'
|
||||
tasks.value = []; file.value = null; recordedAt.value = ''; uploadChannelRoles.value = 'unconfirmed'; uploadVisible.value = false; detailSections.value = []; helpVisible.value = false; errorMessage.value = ''; uploadStage.value = ''; createUncertain.value = false
|
||||
}
|
||||
if (active) { void refresh(); scheduleAutosave() }
|
||||
}, { immediate: true })
|
||||
watch([() => JSON.stringify(reviewItems.value), channelRoles], () => { if (!hydrating) scheduleAutosave() }, { flush: 'sync' })
|
||||
watch(() => props.capabilities.models, models => {
|
||||
if (!models.some(model => model.value === modelKey.value)) modelKey.value = models[0]?.value || ''
|
||||
})
|
||||
onMounted(() => document.addEventListener('visibilitychange', onVisibility))
|
||||
onBeforeUnmount(() => { stop(); document.removeEventListener('visibilitychange', onVisibility) })
|
||||
defineExpose({ confirmLeave, refresh, hasUnsavedChanges: () => dirty.value })
|
||||
</script>
|
||||
<style scoped>
|
||||
.followup-panel { display: grid; gap: 12px; min-width: 0; color: var(--el-text-color-primary); font-size: 14px; }
|
||||
.panel-toolbar, .toolbar-actions, .detail-heading { display: flex; align-items: center; justify-content: space-between; gap: 12px; min-width: 0; }
|
||||
.toolbar-actions { justify-content: flex-end; gap: 8px; flex-wrap: wrap; }
|
||||
.toolbar-actions :deep(.el-button + .el-button) { margin-left: 0; }
|
||||
h3 { margin: 0; font-size: 14px; font-weight: 600; }
|
||||
.toolbar-title h3 span { margin-left: 5px; font-weight: 400; color: var(--el-text-color-secondary); }
|
||||
.help-box { background: #fff; border: 1px solid #e2e8f0; border-radius: 10px; padding: 10px 14px; color: var(--el-text-color-secondary); font-size: 12px; line-height: 1.7; }
|
||||
.help-box p { margin: 3px 0; }
|
||||
.task-list, .task-detail { min-width: 0; max-width: 100%; border: 1px solid #e2e8f0; border-radius: 10px; background: #fff; overflow: hidden; }
|
||||
.task-list { padding: 4px 12px; }
|
||||
.task-list :deep(.el-table) { --el-table-header-bg-color: #f8fafc; }
|
||||
.task-list :deep(.el-table .cell) { line-height: 1.5; }
|
||||
.filename-button { max-width: 100%; height: auto; text-align: left; white-space: normal; word-break: break-word; line-height: 1.6; }
|
||||
.filename-button :deep(span) { overflow-wrap: anywhere; }
|
||||
.task-time, .recording-title > span { display: block; color: var(--el-text-color-secondary); font-size: 12px; margin-top: 3px; }
|
||||
.task-detail { padding: 16px; display: grid; gap: 14px; overflow: visible; }
|
||||
.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; }
|
||||
.retry-button { justify-self: start; }
|
||||
.summary-box { padding-bottom: 12px; border-bottom: 1px solid #e2e8f0; }
|
||||
.summary-box > p { margin: 0 0 10px; line-height: 1.7; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.summary-counts { display: flex; gap: 20px; color: var(--el-text-color-secondary); font-size: 12px; }
|
||||
.summary-counts strong { color: var(--el-text-color-primary); font-weight: 600; }
|
||||
.channel-role-box { display: grid; gap: 6px; font-size: 12px; }
|
||||
.role-summary { display: flex; align-items: center; gap: 12px; }
|
||||
.channel-role-box label { display: flex; align-items: center; flex-wrap: wrap; gap: 10px; }
|
||||
.channel-role-box :deep(.el-select) { width: 260px; max-width: 100%; }
|
||||
.channel-playback { display: flex; align-items: center; flex-wrap: wrap; gap: 6px; margin: 8px 0; }
|
||||
.channel-playback :deep(.el-button + .el-button) { margin-left: 0; }
|
||||
.transcript-segments { max-height: 320px; overflow-y: auto; margin-top: 12px; }
|
||||
.transcript-segment { padding: 10px 0; border-bottom: 1px solid #e2e8f0; }
|
||||
.segment-heading { display: flex; align-items: center; justify-content: space-between; gap: 8px; color: var(--el-text-color-secondary); font-size: 12px; }
|
||||
.transcript-segment pre { margin: 5px 0 0; white-space: pre-wrap; overflow-wrap: anywhere; font-family: inherit; }
|
||||
.dialogue-sides { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 240px), 1fr)); gap: 10px; margin-top: 8px; }
|
||||
.dialogue-side { padding: 10px; background: var(--el-fill-color-light); border-radius: 6px; min-width: 0; }
|
||||
.dialogue-side strong { font-size: 12px; color: var(--el-text-color-secondary); }
|
||||
.original-collapse { --el-collapse-border-color: #e2e8f0; border-top: 0; }
|
||||
.original-collapse :deep(.el-collapse-item__header) { height: 38px; font-size: 13px; color: var(--el-text-color-regular); }
|
||||
.original-collapse :deep(.el-collapse-item__content) { padding-bottom: 10px; }
|
||||
.audio-player { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; }
|
||||
.audio-player audio { width: 100%; max-width: 440px; height: 36px; }
|
||||
.transcript-text { max-height: 280px; overflow-y: auto; margin: 12px 0 0; padding: 12px; background: #f8fafc; border-radius: 6px; white-space: pre-wrap; overflow-wrap: anywhere; font-family: inherit; }
|
||||
.review-actions { display: flex; flex-wrap: wrap; justify-content: space-between; gap: 12px; align-items: center; padding-top: 2px; }
|
||||
.selection-summary { display: grid; gap: 3px; font-size: 13px; }
|
||||
.selection-summary span { color: var(--el-text-color-secondary); font-size: 12px; }
|
||||
.action-buttons { display: flex; gap: 8px; }
|
||||
.action-buttons :deep(.el-button + .el-button) { margin-left: 0; }
|
||||
.review-error { color: var(--el-color-danger); width: 100%; margin: 0; font-size: 12px; }
|
||||
.muted, .upload-stage { color: var(--el-text-color-secondary); font-size: 12px; line-height: 1.6; margin: 0; }
|
||||
.upload-stage { margin: 10px 0; color: var(--el-text-color-regular); }
|
||||
.upload-form { min-width: 0; }
|
||||
.upload-form input { max-width: 100%; }
|
||||
.upload-form small { display: block; color: var(--el-text-color-secondary); line-height: 1.5; margin-top: 6px; }
|
||||
.upload-form :deep(.el-date-editor), .upload-form :deep(.el-select) { width: 100%; }
|
||||
@media (max-width: 640px) {
|
||||
.panel-toolbar { align-items: flex-start; flex-wrap: wrap; gap: 8px; }
|
||||
.toolbar-actions { gap: 6px; }
|
||||
.task-list { padding: 0 4px; }
|
||||
.task-detail { padding: 12px; gap: 12px; }
|
||||
.detail-heading { flex-wrap: wrap; gap: 6px; }
|
||||
.review-actions { align-items: flex-start; }
|
||||
.action-buttons { margin-left: auto; }
|
||||
}
|
||||
</style>
|
||||
@@ -1,273 +0,0 @@
|
||||
<template>
|
||||
<section class="followup-review" aria-label="回访录音人工审核">
|
||||
<el-tabs v-model="group" class="review-tabs" aria-label="提炼结果分类">
|
||||
<el-tab-pane :label="`全部 ${counts.all}`" name="all" />
|
||||
<el-tab-pane :label="`诊单资料 ${counts.diagnosis}`" name="diagnosis" />
|
||||
<el-tab-pane :label="`日常记录 ${counts.daily}`" name="daily" />
|
||||
<el-tab-pane :label="`待核实 ${counts.pending + (uncertainties?.length || 0)}`" name="pending" />
|
||||
</el-tabs>
|
||||
<div class="review-caption"><span>{{ applied ? '审核结果' : '提炼结果' }} · {{ visibleItems.length }} 项</span><span v-if="!applied">跨分类已选 {{ counts.selected }} 项</span></div>
|
||||
<p v-if="!canDaily && counts.daily" class="permission-note">日常记录仅供查看,当前账号没有编辑权限。</p>
|
||||
<div class="review-table">
|
||||
<el-table :data="visibleItems" max-height="360" row-key="id" size="small" table-layout="fixed" :empty-text="items.length ? '此分类暂无内容' : '暂无结构化结果,可查看录音原文'" aria-label="回访提炼结果">
|
||||
<el-table-column v-if="!applied" label="采纳" width="50" align="center">
|
||||
<template #default="{ row }"><el-checkbox :model-value="row.selected" :disabled="disabled || (!row.selected && selectionBlocked(row))" :aria-label="`采纳${itemTitle(row)}`" @update:model-value="(value: boolean | string | number) => toggleSelection(row, !!value)" /></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="字段 / 内容" min-width="210">
|
||||
<template #default="{ row }">
|
||||
<div v-for="field in itemFields(row).slice(0, 2)" :key="field.key" class="result-line"><span>{{ field.label }}:</span>{{ fieldText(row.values[field.key], field) }}</div>
|
||||
<span v-if="!itemFields(row).length" class="muted">暂无有效字段</span>
|
||||
<div class="item-meta">{{ itemKindLabel(row) }}<span v-if="itemFields(row).length > 2"> · 共 {{ itemFields(row).length }} 个字段</span><span v-if="row.target_id"> · 更新已有记录</span></div>
|
||||
<div v-if="row.kind !== 'diagnosis'" class="item-meta mobile-event-time">{{ row.record_date || '日期待核实' }} · {{ reviewTimeValue(row.record_time) || row.time_period || '时间待核实' }}{{ row.time_estimated ? '(推定)' : '' }}</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="日期 / 时段" width="130">
|
||||
<template #default="{ row }"><span>{{ row.kind === 'diagnosis' ? '—' : row.record_date || '待补充日期' }}</span><div v-if="row.kind !== 'diagnosis'" class="item-meta">{{ reviewTimeValue(row.record_time) || row.time_period || '未提及时间' }}{{ row.time_estimated ? '(推定)' : '' }}</div></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="状态" width="90">
|
||||
<template #default="{ row }"><el-tag size="small" :type="itemStatus(row).type">{{ itemStatus(row).label }}</el-tag></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="60" align="right" fixed="right">
|
||||
<template #default="{ row }"><el-button link type="primary" @click="openReview(row.id)">{{ applied || disabled ? '查看' : '核对' }}</el-button></template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</div>
|
||||
<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="同页核对与回听">
|
||||
<div class="review-player"><slot name="player" /></div>
|
||||
<p v-if="navigationNotice" class="editor-notice" role="status">{{ navigationNotice }}</p>
|
||||
<div v-if="editor" class="inline-editor-heading"><strong>{{ applied || disabled ? '查看审核结果' : '核对提炼内容' }} · {{ editorPosition }} / {{ items.length }}</strong><el-button link @click="cancelReview()">{{ editorDirty ? '取消本项修改' : '收起核对' }}</el-button></div>
|
||||
<section v-if="editor" class="review-editor">
|
||||
<div class="editor-heading"><strong>{{ followupKindLabels[editor.kind] }}</strong><el-tag size="small" :type="itemStatus(editor).type">{{ itemStatus(editor).label }}</el-tag></div>
|
||||
<p v-if="editorNotice" class="editor-notice" role="status">{{ editorNotice }}</p>
|
||||
<div class="evidence">
|
||||
<div class="evidence-title">录音原话</div>
|
||||
<blockquote v-for="(quote, index) in editor.evidence" :key="index"><div v-if="quote.channel === 0 || quote.channel === 1" class="muted">{{ followupChannelLabel(quote.channel, channelRoles) }}</div><span>{{ quote.text }}</span><el-button v-if="evidencePlaybackLabel(quote)" link type="primary" @click="seekEvidence(quote)">{{ evidencePlaybackLabel(quote) }}</el-button></blockquote>
|
||||
<p v-if="editor.evidence.some(quote => quote.position_type === 'segment')" class="muted">回听位置为转写片段范围,不是原话的逐字时间戳;默认回听双方对话,请结合原始录音核对。</p>
|
||||
<p v-if="!editor.evidence.length" class="muted">未提供原话证据,请人工核实。</p>
|
||||
<p v-if="editor.date_text || editor.time_text" class="muted">时间原话:{{ editor.date_text || '未提及日期' }} · {{ editor.time_text || '未提及时间' }}</p>
|
||||
</div>
|
||||
<div v-if="editor.conflict || editor.possible_duplicate || editor.time_estimated" class="review-flags"><span v-if="editor.conflict">与已有值冲突</span><span v-if="editor.possible_duplicate">可能存在重复记录</span><span v-if="editor.time_estimated">时间由时段推定</span></div>
|
||||
<template v-if="editor.kind !== 'diagnosis'">
|
||||
<div v-if="disabled || applied" class="readonly-event"><span>{{ editor.record_date || '未记录日期' }} · {{ reviewTimeValue(editor.record_time) || editor.time_period || '未记录时间' }}</span><span>{{ editor.target_id ? `更新记录 #${editor.target_id}` : '新增独立记录' }}</span></div>
|
||||
<div v-else class="event-time">
|
||||
<label class="target-field">写入目标<el-select :model-value="editor.target_id || 0" @update:model-value="(value: number) => chooseTarget(value)"><el-option label="新增独立记录(不覆盖已有行)" :value="0" /><el-option v-for="candidate in editorCandidates" :key="candidate.id" :value="candidate.id" :disabled="!!candidate.delete_time" :label="candidateLabel(editor, candidate)" /></el-select></label>
|
||||
<label>记录日期<el-date-picker :model-value="editor.record_date" type="date" value-format="YYYY-MM-DD" placeholder="请核实日期" @update:model-value="(value: string | null) => patchEditor({ record_date: value || null, target_id: null })" /></label>
|
||||
<label>记录时间<el-time-picker :model-value="reviewTimeValue(editor.record_time)" value-format="HH:mm" format="HH:mm" placeholder="未提及可留空" @update:model-value="(value: string | null) => patchEditor({ record_time: value || null })" /></label>
|
||||
<label>原始时段<el-input :model-value="editor.time_period || ''" placeholder="如早晨、餐后" @update:model-value="(value: string) => patchEditor({ time_period: value || null })" /></label>
|
||||
</div>
|
||||
<p v-if="targetChanged && !applied" class="target-hint" role="status">日期或目标已更改。保存本项后将自动同步草稿并刷新目标当前值,请依据新值重新核对。</p>
|
||||
</template>
|
||||
<div class="field-grid field-grid--header"><span>字段</span><span>{{ applied ? '写入前值' : targetChanged ? '旧目标值(待刷新)' : '当前值' }}</span><span>{{ applied || disabled ? '审核值' : '拟采纳值' }}</span></div>
|
||||
<div v-for="field in itemFields(editor)" :key="field.key" class="field-grid">
|
||||
<div class="field-label">{{ field.label }}<small v-if="field.readonly">只读</small></div>
|
||||
<div class="current-value">{{ fieldText(editor.current_values[field.key], field) }}</div>
|
||||
<div class="suggested-value"><FollowupAudioField :field="field" :model-value="editor.values[field.key]" :readonly="disabled || applied || field.readonly" @update:model-value="value => setValue(field.key, value)" /><el-button v-if="!disabled && !applied" link type="danger" :disabled="Object.keys(editor.values).length <= 1" @click="removeField(field.key)">移除</el-button></div>
|
||||
</div>
|
||||
<p v-if="!disabled && !applied" class="muted">仅可更正或移除本项提议字段,不采纳整项请取消勾选;新增内容请返回原诊单编辑人工补录。</p>
|
||||
<el-checkbox v-if="!disabled && !applied" :model-value="!editor.needs_review" class="review-confirm" @update:model-value="(value: boolean | string | number) => confirmReview(!!value)">我已核对原话、冲突 / 重复及日期时间,确认本项内容</el-checkbox>
|
||||
<p v-if="editorIssue && !disabled && !applied" class="review-error" role="status">{{ editorIssue }}</p>
|
||||
</section>
|
||||
<div v-if="editor && !disabled && !applied" class="editor-footer">
|
||||
<span class="draft-hint" role="status">{{ saveState === 'saving' || saveState === 'pending' ? '审核草稿同步中,不写入病例' : saveState === 'error' || saveState === 'conflict' ? '草稿同步需处理,请查看下方提示' : '核对结果自动保存为草稿,最终确认后才写入病例' }}</span>
|
||||
<el-button @click="skipAndNext">暂不采纳并下一项</el-button>
|
||||
<el-button :disabled="!editorDirty" @click="saveReview(false)">保存本项修改</el-button>
|
||||
<el-button type="primary" :disabled="!!editorIssue || targetChanged" @click="saveReview(true, true)">{{ nextReviewId ? '采纳并下一项' : '完成核对并选中' }}</el-button>
|
||||
</div>
|
||||
</section>
|
||||
</section>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, ref, watch } from 'vue'
|
||||
import type { FollowupAudioChannel, FollowupChannelRoles, FollowupField, FollowupFields, FollowupReviewItem, FollowupValue } from '@/api/followupAudio'
|
||||
import FollowupAudioField from './FollowupAudioField.vue'
|
||||
import { cloneReviewItems, evidencePlaybackLabel, fieldText, followupChannelLabel, followupKindLabels, hasEditableReviewFields, reviewCounts, reviewFieldIssue, reviewIssue, reviewPending, reviewTimeValue } from './followupAudioState'
|
||||
const props = defineProps<{ items: FollowupReviewItem[]; fields: FollowupFields; disabled: boolean; canDaily: boolean; applied?: boolean; uncertainties?: unknown[]; snapshotItems?: FollowupReviewItem[]; channelRoles?: FollowupChannelRoles; saveState?: string; persistedRevision?: number }>()
|
||||
const emit = defineEmits<{ (event: 'update:items', items: FollowupReviewItem[]): void; (event: 'seek', milliseconds: number, channel?: FollowupAudioChannel): void; (event: 'saved-next'): void }>()
|
||||
type Group = 'all' | 'diagnosis' | 'daily' | 'pending'
|
||||
type Editable = Partial<Pick<FollowupReviewItem, 'values' | 'record_date' | 'record_time' | 'time_period' | 'selected' | 'target_id' | 'needs_review'>>
|
||||
const group = ref<Group>('all')
|
||||
const editor = ref<FollowupReviewItem | null>(null)
|
||||
const editorSource = ref('')
|
||||
const editorNotice = ref('')
|
||||
const navigationNotice = ref('')
|
||||
const reviewWorkspace = ref<HTMLElement | null>(null)
|
||||
const editorPosition = computed(() => props.items.findIndex(item => item.id === editor.value?.id) + 1)
|
||||
const nextReviewId = computed(() => {
|
||||
const index = visibleItems.value.findIndex(item => item.id === editor.value?.id)
|
||||
return index < 0 ? null : visibleItems.value.slice(index + 1).find(item => !item.selected && !selectionBlocked(item))?.id || null
|
||||
})
|
||||
const counts = computed(() => reviewCounts(props.items, props.fields, props.canDaily))
|
||||
const visibleItems = computed(() => props.items.filter(item => group.value === 'all' || (group.value === 'diagnosis' && item.kind === 'diagnosis') || (group.value === 'daily' && item.kind !== 'diagnosis') || (group.value === 'pending' && reviewPending(item, props.fields, props.canDaily))))
|
||||
const editorDirty = computed(() => !!editor.value && JSON.stringify(editor.value) !== editorSource.value)
|
||||
const targetChanged = computed(() => {
|
||||
if (!editor.value || !editorSource.value) return false
|
||||
const source: FollowupReviewItem = props.snapshotItems?.find(item => item.id === editor.value?.id) || JSON.parse(editorSource.value)
|
||||
return editor.value.target_id !== source.target_id || editor.value.record_date !== source.record_date
|
||||
})
|
||||
const editorCandidates = computed(() => {
|
||||
if (!editor.value || !editorSource.value) return []
|
||||
const source: FollowupReviewItem = props.snapshotItems?.find(item => item.id === editor.value?.id) || JSON.parse(editorSource.value)
|
||||
return editor.value.record_date === source.record_date ? editor.value.candidates || [] : []
|
||||
})
|
||||
const editorIssue = computed(() => editor.value ? reviewFieldIssue({ ...editor.value, selected: true }, props.fields) || reviewIssue({ ...editor.value, selected: true }, props.canDaily) : '')
|
||||
function patch(id: string, update: Editable) { emit('update:items', props.items.map(item => item.id === id ? { ...item, ...update } : item)) }
|
||||
function itemFields(item: FollowupReviewItem): FollowupField[] { return Object.keys(item.values).map(key => (props.fields[item.kind] || []).find(field => field.key === key) || { key, label: key, type: 'text', readonly: true }) }
|
||||
function itemKindLabel(item: FollowupReviewItem) { return followupKindLabels[item.kind] }
|
||||
function itemTitle(item: FollowupReviewItem) { return itemFields(item).map(field => field.label).join('、') || followupKindLabels[item.kind] }
|
||||
function selectionBlocked(item: FollowupReviewItem) { return props.disabled || !!props.applied || !hasEditableReviewFields(item, props.fields) || (item.kind !== 'diagnosis' && !props.canDaily) || !!reviewFieldIssue({ ...item, selected: true }, props.fields) }
|
||||
function toggleSelection(item: FollowupReviewItem, selected: boolean) {
|
||||
if (props.disabled || props.applied) return
|
||||
if (!selected) { patch(item.id, { selected: false }); return }
|
||||
if (selectionBlocked(item)) return
|
||||
if (reviewPending(item, props.fields, props.canDaily)) { openReview(item.id); return }
|
||||
patch(item.id, { selected: true })
|
||||
}
|
||||
function itemStatus(item: FollowupReviewItem): { label: string; type: 'success' | 'info' | 'warning' } {
|
||||
if (props.applied) return { label: item.selected ? '已写入' : '未采纳', type: item.selected ? 'success' : 'info' }
|
||||
if (!hasEditableReviewFields(item, props.fields)) return { label: '只读字段', type: 'info' }
|
||||
if (reviewPending(item, props.fields, props.canDaily)) return { label: '待核实', type: 'warning' }
|
||||
return { label: item.selected ? '已选择' : '已核对', type: item.selected ? 'success' : 'info' }
|
||||
}
|
||||
function openReview(id: string) {
|
||||
if (editor.value?.id === id && editorDirty.value && !props.applied) {
|
||||
void nextTick(() => { reviewWorkspace.value?.scrollIntoView({ block: 'start' }); reviewWorkspace.value?.focus({ preventScroll: true }) })
|
||||
return
|
||||
}
|
||||
if (editor.value && editor.value.id !== id && editorDirty.value && !props.applied) {
|
||||
editorNotice.value = '当前项有未保存修改,请先保存或取消本项修改,再核对其他项。'
|
||||
return
|
||||
}
|
||||
const item = props.items.find(candidate => candidate.id === id)
|
||||
if (!item) return
|
||||
editor.value = cloneReviewItems([item])[0]; editorSource.value = JSON.stringify(editor.value); editorNotice.value = ''; navigationNotice.value = ''
|
||||
void nextTick(() => { reviewWorkspace.value?.scrollIntoView({ block: 'start' }); reviewWorkspace.value?.focus({ preventScroll: true }) })
|
||||
}
|
||||
function cancelReview(done?: () => void) { editor.value = null; editorSource.value = ''; editorNotice.value = ''; done?.() }
|
||||
function patchEditor(update: Editable) {
|
||||
if (!editor.value || props.disabled || props.applied) return
|
||||
// Detail/snapshot items are editable drafts, not the server-owned original proposal.
|
||||
if (update.values && Object.keys(update.values).some(key => !Object.prototype.hasOwnProperty.call(editor.value?.values, key))) return
|
||||
editor.value = { ...editor.value, ...update, selected: false, needs_review: true }
|
||||
}
|
||||
function setValue(key: string, value: FollowupValue) {
|
||||
if (!editor.value || !Object.prototype.hasOwnProperty.call(editor.value.values, key)
|
||||
|| !(props.fields[editor.value.kind] || []).some(field => field.key === key && !field.readonly)) return
|
||||
patchEditor({ values: { ...editor.value.values, [key]: value } })
|
||||
}
|
||||
function removeField(key: string) { if (!editor.value || Object.keys(editor.value.values).length <= 1) return; const values = { ...editor.value.values }; delete values[key]; patchEditor({ values }) }
|
||||
function chooseTarget(id: number) {
|
||||
if (!editor.value || (id && !editorCandidates.value.some(candidate => candidate.id === id && !candidate.delete_time))) return
|
||||
patchEditor({ target_id: id || null })
|
||||
}
|
||||
function confirmReview(confirmed: boolean) {
|
||||
if (!editor.value || props.disabled || props.applied) return
|
||||
editor.value = { ...editor.value, needs_review: !confirmed, selected: confirmed ? editor.value.selected : false }
|
||||
}
|
||||
function saveReview(select: boolean, advance = false) {
|
||||
if (!editor.value || props.disabled || props.applied || (select && (editorIssue.value || targetChanged.value))) return
|
||||
const item = editor.value
|
||||
const nextId = advance ? nextReviewId.value : null
|
||||
patch(item.id, { values: { ...item.values }, record_date: item.record_date, record_time: item.record_time, time_period: item.time_period, target_id: item.target_id, selected: select || (!editorIssue.value && !targetChanged.value && item.selected), needs_review: targetChanged.value || item.needs_review })
|
||||
cancelReview()
|
||||
emit('saved-next')
|
||||
if (nextId) openReview(nextId)
|
||||
else if (advance) navigationNotice.value = '当前列表已核对至末项;可切换分类继续,或确认写入已选内容。'
|
||||
}
|
||||
function skipAndNext() {
|
||||
if (!editor.value || props.disabled || props.applied) return
|
||||
if (editorDirty.value) { editorNotice.value = '当前项有未保存修改,请先保存或取消修改后再跳过。'; return }
|
||||
const nextId = nextReviewId.value
|
||||
patch(editor.value.id, { selected: false })
|
||||
cancelReview(); emit('saved-next')
|
||||
if (nextId) openReview(nextId)
|
||||
else navigationNotice.value = '本项暂不采纳,未写入病例;可切换分类继续核对。'
|
||||
}
|
||||
function candidateLabel(item: FollowupReviewItem, candidate: NonNullable<FollowupReviewItem['candidates']>[number]) {
|
||||
const preview = (props.fields[item.kind] || []).filter(field => Object.prototype.hasOwnProperty.call(candidate.values, field.key)).slice(0, 2).map(field => `${field.label} ${fieldText(candidate.values[field.key], field)}`).join(',')
|
||||
return `#${candidate.id} · ${candidate.record_time || candidate.time_period || '时间未记录'}${candidate.time_estimated ? '(推定)' : ''}${preview ? ` · ${preview}` : ''}`
|
||||
}
|
||||
function seekEvidence(quote: FollowupReviewItem['evidence'][number]) {
|
||||
if (!evidencePlaybackLabel(quote) || typeof quote.start_ms !== 'number') return
|
||||
emit('seek', quote.start_ms)
|
||||
}
|
||||
function uncertaintyText(value: unknown) { return typeof value === 'string' ? value : JSON.stringify(value) }
|
||||
watch(() => props.items.find(item => item.id === editor.value?.id), fresh => {
|
||||
if (!editor.value) return
|
||||
if (!fresh) { cancelReview(); return }
|
||||
const current = JSON.stringify(fresh)
|
||||
if (current === editorSource.value) return
|
||||
const edited = editor.value
|
||||
editor.value = editorDirty.value && !props.applied ? { ...cloneReviewItems([fresh])[0], values: { ...edited.values }, record_date: edited.record_date, record_time: edited.record_time, time_period: edited.time_period, target_id: edited.target_id, selected: false, needs_review: true } : cloneReviewItems([fresh])[0]
|
||||
editorSource.value = current
|
||||
editorNotice.value = '任务数据已更新,当前编辑已保留;请重新核对后选择。'
|
||||
}, { deep: true })
|
||||
watch(() => props.applied, applied => { if (applied && editor.value) openReview(editor.value.id) })
|
||||
defineExpose({ hasUnsavedChanges: () => editorDirty.value })
|
||||
</script>
|
||||
<style scoped>
|
||||
.followup-review, .review-table { min-width: 0; max-width: 100%; }
|
||||
.review-tabs :deep(.el-tabs__header) { margin: 0 0 8px; }
|
||||
.review-tabs :deep(.el-tabs__item) { padding: 0 14px; font-size: 13px; height: 36px; }
|
||||
.review-tabs :deep(.el-tabs__nav-wrap::after) { height: 1px; background: #e2e8f0; }
|
||||
.review-caption { display: flex; gap: 12px; justify-content: space-between; margin: 0 0 8px; color: var(--el-text-color-secondary); font-size: 12px; }
|
||||
.review-table { overflow: hidden; }
|
||||
.review-table :deep(.el-table) { --el-table-header-bg-color: #f8fafc; }
|
||||
.review-table :deep(.el-table .cell) { line-height: 1.6; }
|
||||
.result-line { white-space: nowrap; text-overflow: ellipsis; overflow: hidden; }
|
||||
.result-line > span { color: #64748b; }
|
||||
.item-meta, .muted, .permission-note { color: #64748b; font-size: 12px; }
|
||||
.item-meta { margin-top: 2px; }
|
||||
.mobile-event-time { display: none; }
|
||||
.permission-note { margin: 0 0 8px; }
|
||||
.uncertainty-list { margin-top: 12px; padding: 10px 12px; background: #f8fafc; border-radius: 6px; font-size: 13px; line-height: 1.6; overflow-wrap: anywhere; }
|
||||
.uncertainty-list strong { font-size: 12px; font-weight: 500; color: var(--el-text-color-secondary); }
|
||||
.uncertainty-list ul { padding-left: 18px; margin: 6px 0 0; }
|
||||
.review-editor { display: grid; gap: 12px; min-width: 0; max-height: 65vh; overflow-y: auto; padding-right: 4px; }
|
||||
.editor-heading { display: flex; align-items: center; gap: 10px; }
|
||||
.editor-heading strong { font-size: 14px; }
|
||||
.evidence { padding: 10px 12px; background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 6px; overflow-wrap: anywhere; }
|
||||
.evidence-title { color: var(--el-text-color-secondary); font-size: 12px; }
|
||||
.evidence blockquote { margin: 6px 0; white-space: pre-wrap; line-height: 1.6; }
|
||||
.evidence blockquote :deep(.el-button) { margin-left: 8px; }
|
||||
.evidence p { margin: 6px 0 0; }
|
||||
.review-flags { display: flex; flex-wrap: wrap; gap: 6px 14px; color: var(--el-color-warning-dark-2); font-size: 12px; }
|
||||
.event-time { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; }
|
||||
.event-time label { display: grid; gap: 5px; font-size: 12px; color: var(--el-text-color-regular); }
|
||||
.event-time .target-field { grid-column: 1 / -1; }
|
||||
.event-time :deep(.el-date-editor), .event-time :deep(.el-select), .suggested-value :deep(.el-input-number), .suggested-value :deep(.el-select), .suggested-value :deep(.el-date-editor) { width: 100%; }
|
||||
.readonly-event { display: flex; flex-wrap: wrap; gap: 8px 20px; font-size: 13px; }
|
||||
.target-hint, .editor-notice { margin: 0; color: var(--el-color-warning-dark-2); font-size: 12px; line-height: 1.6; }
|
||||
.field-grid { display: grid; grid-template-columns: 1fr 1fr 1.6fr; align-items: start; gap: 12px; padding-bottom: 10px; border-bottom: 1px solid #e2e8f0; font-size: 13px; }
|
||||
.field-grid--header { color: var(--el-text-color-secondary); font-size: 12px; padding-bottom: 6px; }
|
||||
.field-label small { display: block; color: var(--el-text-color-secondary); margin-top: 3px; }
|
||||
.current-value { white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.suggested-value { min-width: 0; display: grid; gap: 4px; }
|
||||
.suggested-value > :deep(.el-button) { justify-self: end; font-size: 12px; }
|
||||
.review-confirm { white-space: normal; height: auto; min-height: 32px; align-items: flex-start; }
|
||||
.review-confirm :deep(.el-checkbox__input) { margin-top: 4px; }
|
||||
.review-confirm :deep(.el-checkbox__label) { white-space: normal; line-height: 1.6; font-size: 13px; }
|
||||
.review-workspace { margin-top: 14px; scroll-margin-top: 12px; outline: none; }
|
||||
.review-workspace:focus-visible { outline: 2px solid var(--el-color-primary); outline-offset: 4px; }
|
||||
.review-player { position: sticky; top: 0; z-index: 2; background: var(--el-bg-color, #fff); padding: 10px 0; border-bottom: 1px solid var(--el-border-color-lighter); }
|
||||
.inline-editor-heading { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin: 14px 0; }
|
||||
.draft-hint { flex: 1 1 100%; font-size: 12px; color: var(--el-text-color-secondary); }
|
||||
.review-error { color: var(--el-color-danger); font-size: 12px; margin: 0; }
|
||||
.editor-footer { display: flex; justify-content: flex-end; flex-wrap: wrap; gap: 8px; }
|
||||
.editor-footer :deep(.el-button + .el-button) { margin-left: 0; }
|
||||
@media (max-width: 640px) {
|
||||
.mobile-event-time { display: block; }
|
||||
.review-tabs :deep(.el-tabs__item) { padding: 0 10px; }
|
||||
.review-caption { gap: 6px; flex-wrap: wrap; }
|
||||
.event-time { grid-template-columns: 1fr; }
|
||||
.field-grid { grid-template-columns: 1fr; gap: 6px; }
|
||||
.field-grid--header { display: none; }
|
||||
.field-label { font-weight: 600; }
|
||||
.current-value::before { content: '当前值:'; color: var(--el-text-color-secondary); }
|
||||
.suggested-value::before { content: '审核值:'; color: var(--el-text-color-secondary); }
|
||||
.editor-footer { gap: 6px; }
|
||||
}
|
||||
</style>
|
||||
@@ -1,303 +0,0 @@
|
||||
<template>
|
||||
<div :class="['rv-cell', { 'rv-cell--compact': compact }]">
|
||||
<!-- 行 1:[第 N 诊] tag + 已开方/未开方 + 复诊医生 -->
|
||||
<div class="rv-line rv-line--head">
|
||||
<el-tooltip
|
||||
v-if="showDue && tooltipLines.length"
|
||||
placement="top"
|
||||
:show-after="300"
|
||||
:hide-after="0"
|
||||
>
|
||||
<template #content>
|
||||
<div class="rv-tooltip">
|
||||
<div v-for="line in tooltipLines" :key="line">{{ line }}</div>
|
||||
</div>
|
||||
</template>
|
||||
<el-tag size="small" :type="slotTagType" effect="light" class="rv-slot-tag">
|
||||
{{ slotText }}
|
||||
</el-tag>
|
||||
</el-tooltip>
|
||||
<el-tag
|
||||
v-else-if="showDue"
|
||||
size="small"
|
||||
:type="slotTagType"
|
||||
effect="light"
|
||||
class="rv-slot-tag"
|
||||
>
|
||||
{{ slotText }}
|
||||
</el-tag>
|
||||
<span
|
||||
v-if="prescribedLabel"
|
||||
:class="['rv-prescribed', hasPrescription ? 'rv-prescribed--yes' : 'rv-prescribed--no']"
|
||||
>
|
||||
{{ prescribedLabel }}
|
||||
</span>
|
||||
<span v-if="followupDoctorName" class="rv-doctor">
|
||||
<span v-if="prescribedLabel" class="rv-dot">·</span>{{ followupDoctorName }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<template v-if="showDue">
|
||||
<!-- 行 2:最新开药日 · 开药 X 天 · 锚点来源;缺天数时橙色 -->
|
||||
<div class="rv-line rv-line--order">
|
||||
<span v-if="orderDateText" class="rv-order-date">{{ orderDateText }} 开药</span>
|
||||
<span v-if="orderDateText" class="rv-dot">·</span>
|
||||
<span :class="['rv-days', { 'rv-days--missing': daysMissing }]">{{ medicationText }}</span>
|
||||
<template v-if="!daysMissing && anchorText">
|
||||
<span class="rv-dot">·</span>
|
||||
<span class="rv-anchor">{{ anchorText }}</span>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<!-- 行 3:药尽 MM-DD + 状态 chip -->
|
||||
<div class="rv-line rv-line--due">
|
||||
<span v-if="dueDateText" class="rv-due-date">{{ dueDateText }}</span>
|
||||
<el-tag
|
||||
v-if="chipText"
|
||||
size="small"
|
||||
:type="chipType"
|
||||
:effect="chipEffect"
|
||||
:class="chipClass"
|
||||
>
|
||||
{{ chipText }}
|
||||
</el-tag>
|
||||
</div>
|
||||
|
||||
<!-- 行 4:已延迟 N 次 · 已联系 约 MM-DD(有值才显示) -->
|
||||
<div v-if="followLineText" class="rv-line rv-line--follow">{{ followLineText }}</div>
|
||||
</template>
|
||||
<span v-else class="rv-none">—</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 复诊节点单元格(PC 列表 / H5 卡片紧凑 / 只读页 三处共用)
|
||||
*
|
||||
* 只负责展示,不发请求;数据来自列表行 `revisit_due`(契约 C),由父组件用
|
||||
* `normalizeRevisitDue` 规整后传入。state='none' 或 due 为 null 时仅显示行 1 + 「—」。
|
||||
*/
|
||||
import { computed } from 'vue'
|
||||
|
||||
import {
|
||||
formatRevisitMonthDay,
|
||||
hasRevisitDue,
|
||||
isRevisitDaysMissing,
|
||||
revisitAnchorSrcText,
|
||||
revisitDueDateText,
|
||||
revisitFollowLineText,
|
||||
revisitMedicationDaysText,
|
||||
revisitSlotText,
|
||||
revisitStateChipClass,
|
||||
revisitStateChipText,
|
||||
revisitStateTagEffect,
|
||||
revisitStateTagType,
|
||||
revisitTooltipLines,
|
||||
type RevisitDue
|
||||
} from '@/utils/revisitDue'
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
/** 规整后的复诊节点对象;null / state='none' 显示「—」 */
|
||||
due: RevisitDue | null
|
||||
/** H5 紧凑模式:更小字号、更紧行距 */
|
||||
compact?: boolean
|
||||
/** 是否已开方(决定「已开方/未开方」默认文案与颜色) */
|
||||
hasPrescription?: boolean
|
||||
/** 复诊医生(原列表 followup_doctor_name) */
|
||||
followupDoctorName?: string
|
||||
/** 自定义「已开方/未开方」文案;传 '' 隐藏该段(H5 卡片头已有标签时用) */
|
||||
prescribedText?: string
|
||||
}>(),
|
||||
{
|
||||
compact: false,
|
||||
hasPrescription: false,
|
||||
followupDoctorName: ''
|
||||
}
|
||||
)
|
||||
|
||||
const showDue = computed(() => hasRevisitDue(props.due))
|
||||
|
||||
const prescribedLabel = computed(() => {
|
||||
if (props.prescribedText !== undefined) return props.prescribedText
|
||||
return props.hasPrescription ? '已开方' : '未开方'
|
||||
})
|
||||
|
||||
const slotText = computed(() => revisitSlotText(props.due))
|
||||
const slotTagType = computed<'primary' | 'info'>(() =>
|
||||
showDue.value && Number(props.due?.current_slot) > 0 ? 'primary' : 'info'
|
||||
)
|
||||
const tooltipLines = computed(() => revisitTooltipLines(props.due))
|
||||
|
||||
const orderDateText = computed(() => (showDue.value ? formatRevisitMonthDay(props.due?.order_date) : ''))
|
||||
const daysMissing = computed(() => isRevisitDaysMissing(props.due))
|
||||
const medicationText = computed(() => revisitMedicationDaysText(props.due))
|
||||
const anchorText = computed(() => (showDue.value ? revisitAnchorSrcText(props.due?.anchor_src) : ''))
|
||||
|
||||
const dueDateText = computed(() => revisitDueDateText(props.due))
|
||||
const chipText = computed(() => revisitStateChipText(props.due))
|
||||
const chipType = computed(() => revisitStateTagType(props.due?.state))
|
||||
const chipEffect = computed(() => revisitStateTagEffect(props.due?.state))
|
||||
const chipClass = computed(() => revisitStateChipClass(props.due))
|
||||
|
||||
const followLineText = computed(() => revisitFollowLineText(props.due))
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.rv-cell {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 3px;
|
||||
line-height: 1.35;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.rv-line {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.rv-line--head {
|
||||
font-size: 13px;
|
||||
color: var(--el-text-color-primary);
|
||||
}
|
||||
|
||||
.rv-slot-tag {
|
||||
font-weight: 600;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.rv-prescribed {
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.rv-prescribed--yes {
|
||||
color: #4a5dff;
|
||||
}
|
||||
|
||||
.rv-prescribed--no {
|
||||
color: var(--el-text-color-placeholder);
|
||||
}
|
||||
|
||||
.rv-doctor {
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
|
||||
.rv-dot {
|
||||
color: var(--el-text-color-placeholder);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.rv-line--order {
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
|
||||
.rv-days--missing {
|
||||
color: #ea580c;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.rv-anchor {
|
||||
color: var(--el-text-color-placeholder);
|
||||
}
|
||||
|
||||
.rv-line--due {
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.rv-due-date {
|
||||
font-weight: 500;
|
||||
color: var(--el-text-color-primary);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
/* 状态 chip:el-tag 基础色由 type/effect 决定,这里只补深红加粗与描边细节。
|
||||
前缀 .rv-cell 提高特异性,压过 Element 的 .el-tag--dark.el-tag--danger 变量定义 */
|
||||
.rv-cell .rv-chip {
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.rv-cell .rv-chip--overdue,
|
||||
.rv-cell .rv-chip--missed {
|
||||
--el-tag-bg-color: #dc2626;
|
||||
--el-tag-border-color: #dc2626;
|
||||
}
|
||||
|
||||
.rv-cell .rv-chip--severe,
|
||||
.rv-cell .rv-chip--overdue.rv-chip--severe,
|
||||
.rv-cell .rv-chip--missed.rv-chip--severe {
|
||||
font-weight: 700;
|
||||
--el-tag-bg-color: #b91c1c;
|
||||
--el-tag-border-color: #b91c1c;
|
||||
}
|
||||
|
||||
.rv-cell .rv-chip--warning {
|
||||
--el-tag-text-color: #ea580c;
|
||||
--el-tag-bg-color: rgba(234, 88, 12, 0.1);
|
||||
--el-tag-border-color: rgba(234, 88, 12, 0.3);
|
||||
}
|
||||
|
||||
.rv-cell .rv-chip--no_days {
|
||||
--el-tag-text-color: #ea580c;
|
||||
--el-tag-border-color: #ea580c;
|
||||
}
|
||||
|
||||
.rv-cell .rv-chip--visited {
|
||||
--el-tag-text-color: #16a34a;
|
||||
--el-tag-bg-color: rgba(22, 163, 74, 0.1);
|
||||
--el-tag-border-color: rgba(22, 163, 74, 0.3);
|
||||
}
|
||||
|
||||
.rv-cell .rv-chip--booked {
|
||||
--el-tag-text-color: #4a5dff;
|
||||
--el-tag-bg-color: rgba(74, 93, 255, 0.1);
|
||||
--el-tag-border-color: rgba(74, 93, 255, 0.3);
|
||||
}
|
||||
|
||||
.rv-cell .rv-chip--contacted {
|
||||
--el-tag-text-color: #4a5dff;
|
||||
--el-tag-border-color: #4a5dff;
|
||||
}
|
||||
|
||||
.rv-line--follow {
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
|
||||
.rv-none {
|
||||
font-size: 13px;
|
||||
color: var(--el-text-color-placeholder);
|
||||
}
|
||||
|
||||
.rv-tooltip {
|
||||
line-height: 1.6;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
/* H5 紧凑模式 */
|
||||
.rv-cell--compact {
|
||||
gap: 2px;
|
||||
|
||||
.rv-line--head,
|
||||
.rv-line--due,
|
||||
.rv-prescribed {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.rv-line--order,
|
||||
.rv-line--follow,
|
||||
.rv-doctor {
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.rv-none {
|
||||
font-size: 12px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,59 +0,0 @@
|
||||
export type FollowupPlaybackChannel = 'original' | 0 | 1
|
||||
|
||||
function browserAudioContext(): AudioContext | null {
|
||||
const browser = globalThis as typeof globalThis & { webkitAudioContext?: typeof AudioContext }
|
||||
const Constructor = browser.AudioContext || browser.webkitAudioContext
|
||||
return Constructor ? new Constructor() : null
|
||||
}
|
||||
|
||||
/** One authorized HTML audio element owns one lazy graph; isolated audio is duplicated to both speakers. */
|
||||
export function createFollowupAudioPlayback(element: HTMLMediaElement, createContext: () => AudioContext | null = browserAudioContext) {
|
||||
let context: AudioContext | null = null
|
||||
let source: MediaElementAudioSourceNode | null = null
|
||||
let splitter: ChannelSplitterNode | null = null
|
||||
let merger: ChannelMergerNode | null = null
|
||||
let disposed = false
|
||||
let generation = 0
|
||||
function disconnect() { source?.disconnect(); splitter?.disconnect(); merger?.disconnect() }
|
||||
return {
|
||||
async select(channel: FollowupPlaybackChannel): Promise<boolean> {
|
||||
if (disposed) return false
|
||||
const ticket = ++generation
|
||||
element.pause()
|
||||
if (channel === 'original' && !context) return true
|
||||
try {
|
||||
if (!context) {
|
||||
context = createContext()
|
||||
if (!context) throw new Error('当前浏览器不支持 Web Audio,无法隔离声道;请使用原音播放。')
|
||||
source = context.createMediaElementSource(element)
|
||||
splitter = context.createChannelSplitter(2)
|
||||
merger = context.createChannelMerger(2)
|
||||
}
|
||||
if (!source) throw new Error('音频播放节点未就绪')
|
||||
disconnect()
|
||||
if (channel === 'original') source.connect(context.destination)
|
||||
else {
|
||||
if (!splitter || !merger) throw new Error('声道播放节点未就绪')
|
||||
source.connect(splitter)
|
||||
splitter.connect(merger, channel, 0)
|
||||
splitter.connect(merger, channel, 1)
|
||||
merger.connect(context.destination)
|
||||
}
|
||||
await context.resume()
|
||||
if (!disposed && ticket === generation && context.state !== 'running') throw new Error('音频上下文未运行')
|
||||
return !disposed && ticket === generation
|
||||
} catch (error) {
|
||||
if (disposed || ticket !== generation) return false
|
||||
disconnect()
|
||||
// Keep an explicit original-audio fallback; never autoplay it after failed isolation.
|
||||
if (source && context) source.connect(context.destination)
|
||||
throw new Error(`无法隔离声道,已停止本次回听;可选择原音播放。${error instanceof Error ? error.message : ''}`)
|
||||
}
|
||||
},
|
||||
dispose() {
|
||||
if (disposed) return
|
||||
disposed = true; generation++; element.pause(); disconnect()
|
||||
if (context) void context.close().catch(() => { /* Element is already detached and all nodes disconnected. */ })
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,196 +0,0 @@
|
||||
import type { FollowupAudioChannel, FollowupCapabilities, FollowupChannelRoles, FollowupField, FollowupFields, FollowupReviewItem, FollowupTaskDetail, FollowupTaskSummary, FollowupTranscriptSegment, FollowupValue } from '@/api/followupAudio'
|
||||
|
||||
export const FOLLOWUP_CHUNK_BYTES = 2097152
|
||||
export const followupKindLabels = { diagnosis: '诊单资料', blood: '血糖 / 血压', diet: '饮食', exercise: '运动', tracking_note: '跟踪备注' }
|
||||
export const followupStatusLabels: Record<string, string> = {
|
||||
queued: '等待处理', running: '正在分析', review: '待人工审核', applied: '已采纳',
|
||||
failed: '处理失败', needs_reconciliation: '结果待核对', expired: '已过保留期'
|
||||
}
|
||||
const followupStageLabels: Record<string, string> = { transcribing: '正在转写', extracting: '正在提炼', validating: '正在校验', review: '待人工审核' }
|
||||
export function followupTaskStatus(task: Pick<FollowupTaskSummary, 'status' | 'stage'>): string {
|
||||
return (task.status === 'running' && followupStageLabels[task.stage]) || followupStatusLabels[task.status] || task.status
|
||||
}
|
||||
export function followupProgressText(task: FollowupTaskSummary): string {
|
||||
const progress = task.pipeline_progress
|
||||
const valid = progress && Number.isSafeInteger(progress.transcribed) && Number.isSafeInteger(progress.total)
|
||||
&& progress.total > 0 && progress.transcribed >= 0 && progress.transcribed <= progress.total
|
||||
return `${followupTaskStatus(task)}${valid ? ` · 转写片段 ${progress.transcribed} / ${progress.total}` : ''};人工审核前不会写入业务记录。`
|
||||
}
|
||||
export function retainedTranscriptNotice(task: FollowupTaskDetail): string {
|
||||
if (!task.transcript_available || !task.transcript.trim()) return ''
|
||||
if (task.status === 'failed') return '处理失败,已完成片段的转写仍可查看。保留转写不代表提炼成功,不能直接写入病历。'
|
||||
if (task.status === 'needs_reconciliation') return '结果待核对,已完成片段的转写仍可查看。请先核对上游结果,不要重复发送。'
|
||||
return ''
|
||||
}
|
||||
export function evidencePlaybackLabel(quote: FollowupReviewItem['evidence'][number]): string {
|
||||
if (typeof quote.start_ms !== 'number' || !Number.isFinite(quote.start_ms) || quote.start_ms < 0) return ''
|
||||
if (quote.channel !== undefined && quote.channel !== 0 && quote.channel !== 1) return ''
|
||||
if (quote.position_type === 'segment') {
|
||||
if (!quote.segment_id || typeof quote.end_ms !== 'number' || !Number.isFinite(quote.end_ms) || quote.end_ms <= quote.start_ms) return ''
|
||||
return `回听对话 ${audioTimestamp(quote.start_ms)}–${audioTimestamp(quote.end_ms)}`
|
||||
}
|
||||
return `播放 ${audioTimestamp(quote.start_ms)}`
|
||||
}
|
||||
export function audioTimestamp(ms: number): string { const seconds = Math.max(0, Math.floor(ms / 1000)); return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}` }
|
||||
export function normalizedChannelRoles(value: unknown): FollowupChannelRoles { return value === 'left_service' || value === 'right_service' ? value : 'unconfirmed' }
|
||||
export function hasStereoTranscript(segments: FollowupTranscriptSegment[] = []): boolean { return segments.some(segment => segment.channel === 0) && segments.some(segment => segment.channel === 1) }
|
||||
export function followupChannelLabel(channel?: FollowupAudioChannel, roles: FollowupChannelRoles = 'unconfirmed'): string {
|
||||
if (channel !== 0 && channel !== 1) return '未标注声道'
|
||||
const side = channel === 0 ? '左声道' : '右声道'
|
||||
const confirmed = normalizedChannelRoles(roles)
|
||||
if (confirmed === 'unconfirmed') return `${side} · 角色待确认`
|
||||
const service = confirmed === 'left_service' ? channel === 0 : channel === 1
|
||||
return `${side} · ${service ? '客服端' : '患者/家属端'}(人工标注)`
|
||||
}
|
||||
/** Preserve coarse ASR windows; never invent speaker turn order or word-level timestamps. */
|
||||
export function dialogueWindows(segments: FollowupTranscriptSegment[]) {
|
||||
const windows = new Map<string, { id: string; start_ms: number; end_ms: number; segments: FollowupTranscriptSegment[] }>()
|
||||
for (const segment of segments) {
|
||||
const id = `${segment.start_ms}:${segment.end_ms}`
|
||||
if (!windows.has(id)) windows.set(id, { id, start_ms: segment.start_ms, end_ms: segment.end_ms, segments: [] })
|
||||
windows.get(id)!.segments.push(segment)
|
||||
}
|
||||
return [...windows.values()].sort((a, b) => a.start_ms - b.start_ms || a.end_ms - b.end_ms)
|
||||
.map(window => ({ ...window, segments: [...window.segments].sort((a, b) => (a.channel ?? -1) - (b.channel ?? -1)) }))
|
||||
}
|
||||
export function dialoguePlaybackStart(milliseconds: number): number {
|
||||
return Number.isFinite(milliseconds) ? Math.max(0, milliseconds - 3000) : 0
|
||||
}
|
||||
export function channelPlaybackLabel(channel: FollowupAudioChannel, roles: FollowupChannelRoles): string {
|
||||
if (roles === 'unconfirmed') return channel === 0 ? '只听左声道' : '只听右声道'
|
||||
const service = roles === 'left_service' ? channel === 0 : channel === 1
|
||||
return service ? '只听客服' : '只听患者/家属'
|
||||
}
|
||||
export const cloneReviewItems = (items: FollowupReviewItem[]): FollowupReviewItem[] => JSON.parse(JSON.stringify(items))
|
||||
export function fieldText(value: FollowupValue | undefined, field: FollowupField): string {
|
||||
if (value === undefined || value === null || value === '' || (Array.isArray(value) && !value.length)) return '未记录'
|
||||
const display = (part: string | number | boolean) => field.options?.find(option => String(option.value) === String(part))?.label || String(part)
|
||||
return Array.isArray(value) ? value.map(display).join('、') : display(value)
|
||||
}
|
||||
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)) {
|
||||
const field = fields[item.kind]?.find(candidate => candidate.key === key)
|
||||
if (!field || field.readonly) return `${field?.label || key} 当前不可编辑,请先取消采纳该字段`
|
||||
}
|
||||
return ''
|
||||
}
|
||||
export function reviewIssue(item: FollowupReviewItem, canDaily: boolean): string {
|
||||
if (!item.selected) return ''
|
||||
if (item.needs_review) return '请明确核对不确定、冲突或重复内容'
|
||||
if (item.kind !== 'diagnosis' && !canDaily) return '没有日常记录编辑权限'
|
||||
if (!Object.keys(item.values).length) return '至少填写一个有效字段'
|
||||
if (item.kind !== 'diagnosis' && !validDate(item.record_date)) return '请核对并填写有效的记录日期'
|
||||
if (item.record_time && !/^([01]\d|2[0-3]):[0-5]\d(?::[0-5]\d)?$/.test(item.record_time)) return '请填写有效的记录时间'
|
||||
return ''
|
||||
}
|
||||
/** Pending is independent of selection so filtering never hides unresolved items. */
|
||||
export function reviewPending(item: FollowupReviewItem, fields: FollowupFields, canDaily: boolean): boolean {
|
||||
return item.needs_review || !!reviewFieldIssue({ ...item, selected: true }, fields) || !!reviewIssue({ ...item, selected: true }, canDaily)
|
||||
}
|
||||
export function reviewCounts(items: FollowupReviewItem[], fields: FollowupFields, canDaily: boolean) {
|
||||
return {
|
||||
all: items.length,
|
||||
diagnosis: items.filter(item => item.kind === 'diagnosis').length,
|
||||
daily: items.filter(item => item.kind !== 'diagnosis').length,
|
||||
pending: items.filter(item => reviewPending(item, fields, canDaily)).length,
|
||||
selected: items.filter(item => item.selected).length
|
||||
}
|
||||
}
|
||||
export function changedReviewTarget(items: FollowupReviewItem[], snapshot: FollowupReviewItem[]): boolean {
|
||||
const previous = new Map(snapshot.map(item => [item.id, item]))
|
||||
return items.some(item => {
|
||||
const original = previous.get(item.id)
|
||||
return item.selected && original && (item.target_id !== original.target_id || item.record_date !== original.record_date)
|
||||
})
|
||||
}
|
||||
/** The API accepts legacy seconds, while the review editor exposes minute precision. */
|
||||
export function reviewTimeValue(value: string | null): string | null {
|
||||
return value && /^([01]\d|2[0-3]):[0-5]\d(?::[0-5]\d)?$/.test(value) ? value.slice(0, 5) : null
|
||||
}
|
||||
export function validDate(value: string | null): boolean {
|
||||
if (!value || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false
|
||||
const [year, month, day] = value.split('-').map(Number)
|
||||
const date = new Date(Date.UTC(year, month - 1, day))
|
||||
return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day
|
||||
}
|
||||
/** A stale snapshot refresh never discards user values or reselects an item for them. */
|
||||
export function rebaseReviewItems(local: FollowupReviewItem[], fresh: FollowupReviewItem[]): FollowupReviewItem[] {
|
||||
const previous = new Map(local.map(item => [item.id, item]))
|
||||
return cloneReviewItems(fresh).map(item => {
|
||||
const edit = previous.get(item.id)
|
||||
return edit ? { ...item, values: { ...edit.values }, record_date: edit.record_date, record_time: edit.record_time,
|
||||
time_period: edit.time_period, target_id: edit.target_id, selected: false, needs_review: true } : item
|
||||
})
|
||||
}
|
||||
/** Missing preview readiness/scope fails closed; normal deployments retain their full-verification rules. */
|
||||
export function followupFeatureEnabled(caps: FollowupCapabilities | null): boolean {
|
||||
return !!caps?.enabled && (!caps.preview_only || caps.test_scope_allowed === true)
|
||||
}
|
||||
export function followupAudioReady(caps: FollowupCapabilities | null): boolean {
|
||||
return !!caps && (caps.preview_only ? caps.preview_ready === true && caps.test_scope_allowed === true : caps.audio_verified || (caps.manual_review_enabled === true && caps.manual_review_ready === true))
|
||||
}
|
||||
export function followupCanReview(caps: FollowupCapabilities | null, previewTask = false): boolean {
|
||||
return followupFeatureEnabled(caps) && !!caps && (caps.preview_only || previewTask ? caps.can_review === true : caps.can_apply)
|
||||
}
|
||||
export function followupCanApply(caps: FollowupCapabilities | null, previewTask = false): boolean {
|
||||
return followupFeatureEnabled(caps) && followupAudioReady(caps) && !!caps && !caps.preview_only && !previewTask && caps.can_apply
|
||||
}
|
||||
export function uploadIssue(file: Pick<File, 'size' | 'name'> | null, recordedAt: string, model: string, caps: FollowupCapabilities | null, viewOnly: boolean): string {
|
||||
if (viewOnly || !caps || !followupFeatureEnabled(caps) || !followupAudioReady(caps) || !caps.can_upload) return '当前不可上传录音'
|
||||
if (!file || !file.size) return '请选择非空录音文件'
|
||||
if (file.size > caps.limits.max_bytes) return '录音文件超过大小限制'
|
||||
if (!/\.(mp3|wav|m4a|amr)$/i.test(file.name)) return '请选择支持的录音格式'
|
||||
if (!/^\d{4}-\d{2}-\d{2} ([01]\d|2[0-3]):[0-5]\d:[0-5]\d$/.test(recordedAt) || !validDate(recordedAt.slice(0, 10))) return '请填写实际录音时间(北京时间)'
|
||||
if (!caps.models.some(option => option.value === model)) return '请选择可用的分析模型'
|
||||
return ''
|
||||
}
|
||||
/** All async operations capture one generation; invalidate on patient switch, hide or dispose. */
|
||||
export function createFollowupScope() {
|
||||
let generation = 0
|
||||
let controller = new AbortController()
|
||||
return {
|
||||
capture: () => ({ generation, signal: controller.signal }),
|
||||
current: (ticket: { generation: number; signal: AbortSignal }) => ticket.generation === generation && !ticket.signal.aborted,
|
||||
invalidate() { controller.abort(); generation++; controller = new AbortController() }
|
||||
}
|
||||
}
|
||||
export async function uploadChunks(
|
||||
file: Blob,
|
||||
chunkBytes: number,
|
||||
send: (index: number, chunk: Blob) => Promise<{ received: boolean }>,
|
||||
isCurrent: () => boolean,
|
||||
progress: (percent: number) => void
|
||||
): Promise<boolean> {
|
||||
if (!Number.isSafeInteger(chunkBytes) || chunkBytes < 65536 || chunkBytes > FOLLOWUP_CHUNK_BYTES) throw new Error('服务端分片配置不匹配,请联系管理员')
|
||||
for (let start = 0, index = 0; start < file.size; start += chunkBytes, index++) {
|
||||
if (!isCurrent()) return false
|
||||
const result = await send(index, file.slice(start, start + chunkBytes))
|
||||
if (!isCurrent()) return false
|
||||
if (!result.received) throw new Error('录音分片未被服务端确认,上传已停止')
|
||||
progress(Math.round(Math.min(start + chunkBytes, file.size) / file.size * 100))
|
||||
}
|
||||
return isCurrent()
|
||||
}
|
||||
export function followupError(error: unknown): string {
|
||||
return error instanceof Error ? error.message : '请求失败;当前审核内容已保留,请刷新任务状态后确认'
|
||||
}
|
||||
@@ -52,7 +52,7 @@
|
||||
</p>
|
||||
</div>
|
||||
</template>
|
||||
<el-tabs v-model="activeTab" :before-leave="beforeTabLeave" class="diagnosis-tabs tcm-diagnosis-tabs">
|
||||
<el-tabs v-model="activeTab" class="diagnosis-tabs tcm-diagnosis-tabs">
|
||||
<!-- 基本信息标签页 -->
|
||||
<el-tab-pane label="病历" name="basic">
|
||||
<el-form
|
||||
@@ -660,7 +660,6 @@
|
||||
lazy
|
||||
>
|
||||
<daily-matrix
|
||||
ref="dailyMatrixRef"
|
||||
v-if="formData.id"
|
||||
:diagnosis-id="Number(formData.id)"
|
||||
:patient-id="Number(formData.patient_id)"
|
||||
@@ -671,33 +670,6 @@
|
||||
<el-empty v-else description="请先保存诊单后查看" />
|
||||
</el-tab-pane>
|
||||
|
||||
<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-else-if="visible && followupCapabilities?.enabled && followupCapabilitiesDiagnosisId === Number(formData.id)"
|
||||
:key="Number(formData.id)"
|
||||
ref="followupAudioRef"
|
||||
:diagnosis-id="Number(formData.id)"
|
||||
:view-only="viewOnly"
|
||||
:active="activeTab === 'followupAudio'"
|
||||
:capabilities="followupCapabilities"
|
||||
:basic-dirty="basicDirty"
|
||||
:before-apply="canApplyFollowup"
|
||||
@applied="handleFollowupApplied"
|
||||
/>
|
||||
<el-alert
|
||||
v-else
|
||||
:title="followupCapabilities?.test_scope_allowed === false ? '当前诊单未开放回访录音' : '当前未启用回访录音,请联系管理员确认'"
|
||||
type="info"
|
||||
:closable="false"
|
||||
show-icon
|
||||
/>
|
||||
</el-tab-pane>
|
||||
|
||||
<!-- 病历记录标签页(开方后自动显示) -->
|
||||
<el-tab-pane label="处方" name="bingli" :disabled="!formData.id" v-if="hasPermission(['tcm.diagnosis/chufang'])">
|
||||
<div v-if="formData.id" class="bingli-tab-content">
|
||||
@@ -744,20 +716,6 @@
|
||||
<el-empty v-else description="请先保存诊单后再查看视频录制回放记录" />
|
||||
</el-tab-pane>
|
||||
<el-tab-pane
|
||||
v-if="hasCallTranscriptPermission"
|
||||
label="面诊文字对话"
|
||||
name="callTranscript"
|
||||
:disabled="!formData.id"
|
||||
lazy
|
||||
>
|
||||
<consultation-transcript-panel
|
||||
v-if="visible && activeTab === 'callTranscript' && formData.id"
|
||||
:key="Number(formData.id)"
|
||||
:diagnosis-id="Number(formData.id)"
|
||||
/>
|
||||
<el-empty v-else-if="!formData.id" description="请先保存诊单后再查看面诊文字对话" />
|
||||
</el-tab-pane>
|
||||
<el-tab-pane
|
||||
v-if="hasPermission(['tcm.diagnosis/chat'])"
|
||||
label="聊天记录"
|
||||
name="chat"
|
||||
@@ -827,7 +785,6 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, ref, watch } from 'vue'
|
||||
import { tcmDiagnosisAdd, tcmDiagnosisEdit, tcmDiagnosisDetail, checkPhone, checkIdCard, diagnosisTrackingNotes } from '@/api/tcm'
|
||||
import { getDictData } from '@/api/app'
|
||||
import feedback from '@/utils/feedback'
|
||||
@@ -837,11 +794,8 @@ import useAppStore from '@/stores/modules/app'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { QuestionFilled } from '@element-plus/icons-vue'
|
||||
import DailyMatrix from './components/DailyMatrix.vue'
|
||||
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'
|
||||
@@ -857,15 +811,6 @@ const getImageUrl = (url: string) => (url?.indexOf?.('http') === 0 ? url : appSt
|
||||
const caseRecordListRef = ref()
|
||||
const callRecordPanelRef = ref<{ refresh?: () => void } | null>(null)
|
||||
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
|
||||
|
||||
const visible = ref(false)
|
||||
/** 只读查看:与 consumers 处方等处「查看诊单」一致,全部 Tab 仅展示不可保存 */
|
||||
@@ -877,8 +822,6 @@ const submitting = ref(false)
|
||||
/** 拥有后手机号可正常编辑,失焦不再强制脱敏 */
|
||||
const hasPhonePlainPermission = computed(() => hasPermission(['tcm.diagnosis/phonePlain']))
|
||||
const hasDailyRecordPermission = computed(() => hasPermission(['tcm.diagnosis/dailyRecord']))
|
||||
const hasCallTranscriptPermission = computed(() => hasPermission(['tcm.diagnosis/huifang']) || hasPermission(['tcm.diagnosis/getCallRecords']))
|
||||
const hasFollowupAudioPermission = computed(() => hasPermission(['tcm.diagnosis/followupAudio']))
|
||||
const patientBasicLocked = ref(false)
|
||||
const canEditPatientBasicFromApi = ref(true)
|
||||
const latestPrescriptionOrder = ref<{
|
||||
@@ -946,15 +889,12 @@ watch(() => activeTab.value, async (tab) => {
|
||||
}
|
||||
})
|
||||
|
||||
watch([visible, activeTab, hasCallTranscriptPermission], () => {
|
||||
watch([visible, activeTab], () => {
|
||||
if (!visible.value) return
|
||||
if (activeTab.value === 'chat' && !hasPermission(['tcm.diagnosis/chat'])) {
|
||||
activeTab.value = 'basic'
|
||||
}
|
||||
if (activeTab.value === 'visit' && !hasPermission(['tcm.diagnosis/huifang'])) {
|
||||
activeTab.value = 'basic'
|
||||
}
|
||||
if (activeTab.value === 'callTranscript' && !hasCallTranscriptPermission.value) {
|
||||
activeTab.value = 'basic'
|
||||
}
|
||||
if (
|
||||
@@ -1030,77 +970,6 @@ const formData = ref({
|
||||
external_userid: ''
|
||||
})
|
||||
|
||||
// Include unmasked identity values so merely revealing a number is not an unsaved edit.
|
||||
const basicFingerprint = () => JSON.stringify({ ...formData.value,
|
||||
phone: originalPhone.value || formData.value.phone, id_card: originalIdCard.value || formData.value.id_card })
|
||||
const basicDirty = computed(() => !viewOnly.value && !!basicSnapshot.value && basicFingerprint() !== basicSnapshot.value)
|
||||
const canApplyFollowup = () => !basicDirty.value && visible.value && !viewOnly.value
|
||||
async function beforeTabLeave(next: string | number, previous: string | number): Promise<boolean> {
|
||||
if (next === 'followupAudio' && basicDirty.value) {
|
||||
feedback.msgWarning('病历有未保存修改,请先保存后再进入回访录音审核,当前输入已保留')
|
||||
return false
|
||||
}
|
||||
if (previous === 'followupAudio') return await followupAudioRef.value?.confirmLeave() ?? true
|
||||
return true
|
||||
}
|
||||
async function handleFollowupApplied(diagnosisId: number) {
|
||||
if (!visible.value || Number(formData.value.id) !== diagnosisId) return
|
||||
const generation = diagnosisGeneration
|
||||
try {
|
||||
// The response itself is also guarded, including edits made while it is in flight.
|
||||
await loadDiagnosisDetailIntoForm(diagnosisId, true)
|
||||
if (generation !== diagnosisGeneration || !visible.value || Number(formData.value.id) !== diagnosisId) return
|
||||
await dailyMatrixRef.value?.refresh?.()
|
||||
emit('success')
|
||||
} catch {
|
||||
if (generation === diagnosisGeneration) feedback.msgWarning('录音已采纳,但病历或日常记录刷新失败,请手动刷新查看')
|
||||
}
|
||||
}
|
||||
function resetFollowupCapabilities() {
|
||||
capabilitiesRequest?.abort()
|
||||
capabilitiesRequest = undefined
|
||||
followupCapabilities.value = null
|
||||
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(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 = [
|
||||
{ value: '', label: '未设置' },
|
||||
@@ -1391,14 +1260,8 @@ const getDictOptions = async () => {
|
||||
}
|
||||
}
|
||||
|
||||
async function loadDiagnosisDetailIntoForm(id: number, preserveDirty = false): Promise<void> {
|
||||
const generation = diagnosisGeneration
|
||||
async function loadDiagnosisDetailIntoForm(id: number): Promise<void> {
|
||||
const data = await tcmDiagnosisDetail({ id })
|
||||
if (generation !== diagnosisGeneration || !visible.value) return
|
||||
if (preserveDirty && basicDirty.value) {
|
||||
feedback.msgWarning('录音已采纳,病历仍保留你的未保存修改;请核对后再保存,未用刷新覆盖输入')
|
||||
return
|
||||
}
|
||||
|
||||
originalPhone.value = data.phone || ''
|
||||
originalIdCard.value = data.id_card || ''
|
||||
@@ -1414,7 +1277,6 @@ async function loadDiagnosisDetailIntoForm(id: number, preserveDirty = false): P
|
||||
formData.value.show_card = Number(data.show_card) === 0 ? 0 : 1
|
||||
const y = data.diabetes_discovery_year
|
||||
formData.value.diabetes_discovery_year = y == null || y === '' ? '' : String(y)
|
||||
basicSnapshot.value = basicFingerprint()
|
||||
}
|
||||
|
||||
const resetPatientBasicLockState = () => {
|
||||
@@ -1424,11 +1286,6 @@ const resetPatientBasicLockState = () => {
|
||||
}
|
||||
|
||||
const open = async (type: string, id?: number) => {
|
||||
const generation = ++diagnosisGeneration
|
||||
submitting.value = false
|
||||
basicSnapshot.value = ''
|
||||
resetFollowupCapabilities()
|
||||
formData.value.id = ''
|
||||
viewOnly.value = false
|
||||
mode.value = type
|
||||
visible.value = true
|
||||
@@ -1439,7 +1296,6 @@ const open = async (type: string, id?: number) => {
|
||||
|
||||
// 加载字典数据
|
||||
await getDictOptions()
|
||||
if (generation !== diagnosisGeneration || !visible.value) return
|
||||
|
||||
if (type === 'edit' && id) {
|
||||
await loadDiagnosisDetailIntoForm(id)
|
||||
@@ -1454,11 +1310,6 @@ const open = async (type: string, id?: number) => {
|
||||
/** 只读打开:与编辑同一套界面与全部 Tab,不可保存 */
|
||||
const openViewOnly = async (id: number) => {
|
||||
if (!id) return
|
||||
const generation = ++diagnosisGeneration
|
||||
submitting.value = false
|
||||
basicSnapshot.value = ''
|
||||
resetFollowupCapabilities()
|
||||
formData.value.id = ''
|
||||
viewOnly.value = true
|
||||
mode.value = 'edit'
|
||||
visible.value = true
|
||||
@@ -1467,17 +1318,13 @@ const openViewOnly = async (id: number) => {
|
||||
idCardRevealUnlocked.value = false
|
||||
resetPatientBasicLockState()
|
||||
await getDictOptions()
|
||||
if (generation !== diagnosisGeneration || !visible.value) return
|
||||
await loadDiagnosisDetailIntoForm(id)
|
||||
}
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (viewOnly.value || submitting.value) return
|
||||
const generation = diagnosisGeneration
|
||||
if (viewOnly.value) return
|
||||
await formRef.value?.validate()
|
||||
if (generation !== diagnosisGeneration || !visible.value) return
|
||||
// A user can keep typing while the request is pending. Only mark submitted bytes saved.
|
||||
const submittedForm = JSON.parse(basicFingerprint()) as typeof formData.value
|
||||
|
||||
submitting.value = true
|
||||
try {
|
||||
// 准备提交数据,使用原始完整数据
|
||||
@@ -1489,7 +1336,6 @@ const handleSubmit = async () => {
|
||||
|
||||
if (mode.value === 'add') {
|
||||
const result = await tcmDiagnosisAdd(submitData)
|
||||
if (generation !== diagnosisGeneration || !visible.value) return
|
||||
|
||||
// 如果是新增,保存成功后切换到编辑模式,这样可以添加血糖血压记录
|
||||
if (result && result.id) {
|
||||
@@ -1497,14 +1343,11 @@ const handleSubmit = async () => {
|
||||
phoneRevealUnlocked.value = false
|
||||
idCardRevealUnlocked.value = false
|
||||
formData.value.id = result.id
|
||||
submittedForm.id = result.id
|
||||
|
||||
// 重新获取详情,确保patient_id等字段正确
|
||||
try {
|
||||
const detail = await tcmDiagnosisDetail({ id: result.id })
|
||||
if (generation !== diagnosisGeneration || !visible.value) return
|
||||
formData.value.patient_id = detail.patient_id
|
||||
submittedForm.patient_id = detail.patient_id
|
||||
|
||||
// 更新原始数据
|
||||
originalPhone.value = detail.phone || ''
|
||||
@@ -1524,13 +1367,11 @@ const handleSubmit = async () => {
|
||||
await tcmDiagnosisEdit(submitData)
|
||||
}
|
||||
|
||||
if (generation !== diagnosisGeneration || !visible.value) return
|
||||
basicSnapshot.value = JSON.stringify(submittedForm)
|
||||
emit('success')
|
||||
} catch (error) {
|
||||
console.error('提交失败:', error)
|
||||
} finally {
|
||||
if (generation === diagnosisGeneration) submitting.value = false
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1554,11 +1395,7 @@ const handleOpenPrescription = () => {
|
||||
prescriptionRef.value?.open(data)
|
||||
}
|
||||
|
||||
const handleClose = async () => {
|
||||
if (followupAudioRef.value && !await followupAudioRef.value.confirmLeave()) return
|
||||
diagnosisGeneration++
|
||||
resetFollowupCapabilities()
|
||||
basicSnapshot.value = ''
|
||||
const handleClose = () => {
|
||||
formRef.value?.resetFields()
|
||||
formData.value = {
|
||||
id: '',
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
formData.pending_assign !== '1' &&
|
||||
formData.pending_booking !== '1' &&
|
||||
formData.completed_appointment !== '1' &&
|
||||
formData.revisit_state === '' &&
|
||||
!hasLatestAppointmentFilter() &&
|
||||
formData.appointment_date === tab.value
|
||||
}
|
||||
@@ -31,14 +30,6 @@
|
||||
待预约
|
||||
<em v-if="pendingBookingCount !== undefined">{{ pendingBookingCount }}</em>
|
||||
</span>
|
||||
<!-- 复诊到期:到期未挂号 ∪ 过号未面诊(revisit_state=due),点击默认按药尽日升序 -->
|
||||
<span
|
||||
:class="['chip', 'chip-revisit-due', { active: formData.revisit_state === 'due' }]"
|
||||
@click="handleRevisitDueTabClick"
|
||||
>
|
||||
复诊到期
|
||||
<em v-if="revisitDueCount !== undefined">{{ revisitDueCount }}</em>
|
||||
</span>
|
||||
<span
|
||||
:class="['chip', 'chip-completed-visit', { active: formData.completed_appointment === '1' }]"
|
||||
@click="handleCompletedVisitTabClick"
|
||||
@@ -156,36 +147,6 @@
|
||||
:value="String(item.value)"
|
||||
/>
|
||||
</el-select>
|
||||
<el-select
|
||||
v-model="formData.revisit_state"
|
||||
placeholder="复诊状态"
|
||||
clearable
|
||||
size="small"
|
||||
class="revisit-state-select"
|
||||
@change="handleRevisitFilterChange"
|
||||
>
|
||||
<el-option
|
||||
v-for="item in revisitStateFilterOptions"
|
||||
:key="item.value"
|
||||
:label="item.label"
|
||||
:value="item.value"
|
||||
/>
|
||||
</el-select>
|
||||
<el-select
|
||||
v-model="formData.revisit_days_bucket"
|
||||
placeholder="开药天数档"
|
||||
clearable
|
||||
size="small"
|
||||
class="revisit-days-bucket-select"
|
||||
@change="doSearch"
|
||||
>
|
||||
<el-option
|
||||
v-for="item in revisitDaysBucketOptions"
|
||||
:key="item.value"
|
||||
:label="item.label"
|
||||
:value="item.value"
|
||||
/>
|
||||
</el-select>
|
||||
<el-button size="small" @click="handleReset">重置</el-button>
|
||||
</div>
|
||||
</el-card>
|
||||
@@ -317,20 +278,22 @@
|
||||
<span v-else class="status-unconfirmed">未确认</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<!-- 复诊节点:吞掉原「复诊」「开方」两列;排序走后端 sort_revisit_due(药尽日,NULL 置后) -->
|
||||
<el-table-column
|
||||
label="复诊节点"
|
||||
prop="revisit_due_date"
|
||||
min-width="180"
|
||||
sortable="custom"
|
||||
>
|
||||
<el-table-column label="复诊" min-width="120">
|
||||
<template #default="{ row }">
|
||||
<revisit-node-cell
|
||||
:due="revisitDueOf(row)"
|
||||
:has-prescription="!!row.has_prescription"
|
||||
:followup-doctor-name="row.followup_doctor_name || ''"
|
||||
:prescribed-text="prescribedTextOf(row)"
|
||||
/>
|
||||
<div v-if="row.has_prescription" class="followup-cell">
|
||||
<div class="followup-time">{{ row.followup_time_text || '—' }}</div>
|
||||
<div class="followup-doctor">{{ row.followup_doctor_name || '—' }}</div>
|
||||
<el-tag
|
||||
v-if="row.followup_rx_voided"
|
||||
type="info"
|
||||
size="small"
|
||||
effect="plain"
|
||||
class="followup-void-tag"
|
||||
>
|
||||
处方已作废
|
||||
</el-tag>
|
||||
</div>
|
||||
<span v-else class="followup-none">无</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="助理" width="100" show-overflow-tooltip>
|
||||
@@ -338,6 +301,12 @@
|
||||
<span class="assistant-cell">{{ getAssistantName(row.assistant_id || row.assistant) }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="开方" width="72" align="center">
|
||||
<template #default="{ row }">
|
||||
<span v-if="row.has_prescription" class="status-prescribed">已开方</span>
|
||||
<span v-else class="status-unprescribed">未开方</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column
|
||||
label="未服务天数"
|
||||
prop="unserved_days"
|
||||
@@ -550,6 +519,7 @@
|
||||
</el-form-item>
|
||||
<el-form-item label="继承">
|
||||
<el-checkbox v-model="assignForm.is_inherit">继承</el-checkbox>
|
||||
<span class="text-gray-400 text-xs ml-2">勾选后写入指派记录</span>
|
||||
</el-form-item>
|
||||
<el-form-item v-if="assignMode === 'batch'" label="已选择">
|
||||
<div class="text-gray-500">{{ batchAssignIds.length }} 条诊单记录</div>
|
||||
@@ -767,7 +737,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts" name="tcmDiagnosis">
|
||||
import { tcmDiagnosisLists, tcmDiagnosisDelete, tcmDiagnosisAssign, tcmDiagnosisGuahaoLogList, getAssistants, generateMiniProgramQrcode, generateOrderQrcode, getWechatChatRecords, addWechatChatRecord, deleteWechatChatRecord, getWechatExternalContact, fillIdCard, diagnosisReadonlyDetail } from '@/api/tcm'
|
||||
import { tcmDiagnosisLists, tcmDiagnosisDelete, tcmDiagnosisAssign, tcmDiagnosisGuahaoLogList, getAssistants, generateMiniProgramQrcode, generateOrderQrcode, getWechatChatRecords, addWechatChatRecord, deleteWechatChatRecord, getWechatExternalContact, fillIdCard } from '@/api/tcm'
|
||||
import { orderCreate } from '@/api/order'
|
||||
import { cancelAppointment } from '@/api/doctor'
|
||||
import { usePaging } from '@/hooks/usePaging'
|
||||
@@ -782,15 +752,6 @@ import { useRoute, useRouter } from 'vue-router'
|
||||
import { computed, defineAsyncComponent, onMounted, onUnmounted, watch } from 'vue'
|
||||
import dayjs from 'dayjs'
|
||||
import DaterangePicker from '@/components/daterange-picker/index.vue'
|
||||
import RevisitNodeCell from './components/RevisitNodeCell.vue'
|
||||
import { formatGender } from '@/utils/diag-display'
|
||||
import {
|
||||
normalizeRevisitDue,
|
||||
REVISIT_DAYS_BUCKET_OPTIONS,
|
||||
REVISIT_STATE_FILTER_OPTIONS,
|
||||
revisitRowClassName,
|
||||
type RevisitDue
|
||||
} from '@/utils/revisitDue'
|
||||
|
||||
const EditPopup = defineAsyncComponent(() => import('./edit.vue'))
|
||||
const DetailPopup = defineAsyncComponent(() => import('./detail.vue'))
|
||||
@@ -837,12 +798,6 @@ const formData = reactive({
|
||||
latest_assign_end_date: '' as string,
|
||||
/** 未服务天数排序:desc=天数多到少 asc=少到多 */
|
||||
sort_unserved_days: '' as '' | 'asc' | 'desc',
|
||||
/** 复诊状态筛选:due(到期未挂号∪过号)|warning|booked|visited|contacted|no_days|pending,空=不限 */
|
||||
revisit_state: '' as string,
|
||||
/** 开药天数档筛选:14|21|28|30|other,空=不限 */
|
||||
revisit_days_bucket: '' as string,
|
||||
/** 复诊节点(药尽日)排序:asc=最早到期在前(NULL 置后) desc 反之;与 sort_unserved_days 互斥 */
|
||||
sort_revisit_due: '' as '' | 'asc' | 'desc',
|
||||
diagnosis_confirmed: '' as '' | '0' | '1',
|
||||
appointment_date: '' as string,
|
||||
has_appointment: '' as '' | '0' | '1',
|
||||
@@ -943,13 +898,11 @@ function buildSharedDiagnosisFilterPayload(): Record<string, unknown> {
|
||||
latest_appointment_end_date: formData.latest_appointment_end_date,
|
||||
latest_appointment_channel_source: formData.latest_appointment_channel_source,
|
||||
latest_assign_start_date: formData.latest_assign_start_date,
|
||||
latest_assign_end_date: formData.latest_assign_end_date,
|
||||
revisit_state: formData.revisit_state,
|
||||
revisit_days_bucket: formData.revisit_days_bucket
|
||||
latest_assign_end_date: formData.latest_assign_end_date
|
||||
}
|
||||
}
|
||||
|
||||
/** 顶部 Tab 角标 count 请求:带上共用筛选,再叠加各 Tab 专属条件(revisit_state 视为 Tab 条件,角标间互不影响) */
|
||||
/** 顶部 Tab 角标 count 请求:带上共用筛选,再叠加各 Tab 专属条件 */
|
||||
function buildDateCountRequestPayload(overrides: Record<string, unknown> = {}): Record<string, unknown> {
|
||||
return {
|
||||
page_no: 1,
|
||||
@@ -962,8 +915,6 @@ function buildDateCountRequestPayload(overrides: Record<string, unknown> = {}):
|
||||
pending_assign_order_month: '',
|
||||
pending_assign_keyword: '',
|
||||
sort_unserved_days: '',
|
||||
revisit_state: '',
|
||||
sort_revisit_due: '',
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
@@ -1009,9 +960,6 @@ function clearSecondaryFiltersWhenPendingAssignWideSearch() {
|
||||
formData.latest_assign_start_date = ''
|
||||
formData.latest_assign_end_date = ''
|
||||
formData.sort_unserved_days = ''
|
||||
formData.revisit_state = ''
|
||||
formData.revisit_days_bucket = ''
|
||||
formData.sort_revisit_due = ''
|
||||
formData.pending_assign_order_month = ''
|
||||
activeTab.value = 'all'
|
||||
if (kw1 !== '') {
|
||||
@@ -1048,7 +996,6 @@ const handleDateTabClick = async (value: string) => {
|
||||
formData.pending_booking = ''
|
||||
formData.completed_appointment = ''
|
||||
formData.has_appointment = ''
|
||||
clearRevisitTabFilters()
|
||||
clearLatestAppointmentFilters()
|
||||
formData.appointment_date = value
|
||||
pager.page = 1
|
||||
@@ -1065,7 +1012,6 @@ const handlePendingBookingTabClick = async () => {
|
||||
formData.completed_appointment = ''
|
||||
formData.appointment_date = ''
|
||||
formData.has_appointment = '0'
|
||||
clearRevisitTabFilters()
|
||||
clearLatestAppointmentFilters()
|
||||
pager.page = 1
|
||||
await getLists()
|
||||
@@ -1081,7 +1027,6 @@ const handleCompletedVisitTabClick = async () => {
|
||||
formData.completed_appointment = '1'
|
||||
formData.has_appointment = ''
|
||||
formData.appointment_date = ''
|
||||
clearRevisitTabFilters()
|
||||
clearLatestAppointmentFilters()
|
||||
pager.page = 1
|
||||
await getLists()
|
||||
@@ -1094,7 +1039,6 @@ const handlePendingAssignTabClick = async () => {
|
||||
formData.completed_appointment = ''
|
||||
formData.has_appointment = ''
|
||||
formData.appointment_date = ''
|
||||
clearRevisitTabFilters()
|
||||
clearLatestAppointmentFilters()
|
||||
if (!formData.pending_assign_order_month) {
|
||||
formData.pending_assign_order_month = dayjs().format('YYYY-MM')
|
||||
@@ -1113,66 +1057,10 @@ const onPendingAssignOrderMonthChange = async (val: string | null) => {
|
||||
fetchDateCounts()
|
||||
}
|
||||
|
||||
/** 复诊状态 / 开药天数档 下拉选项(文案与请求值映射在 utils/revisitDue.ts) */
|
||||
const revisitStateFilterOptions = REVISIT_STATE_FILTER_OPTIONS
|
||||
const revisitDaysBucketOptions = REVISIT_DAYS_BUCKET_OPTIONS
|
||||
|
||||
/** 顶部「复诊到期」角标:revisit_state=due 的 count */
|
||||
const revisitDueCount = ref<number | undefined>(undefined)
|
||||
|
||||
/** 切换其它顶部 Tab 时清掉复诊 chip 状态与其排序(revisit_days_bucket 属「更多筛选」,保留) */
|
||||
const clearRevisitTabFilters = () => {
|
||||
formData.revisit_state = ''
|
||||
formData.sort_revisit_due = ''
|
||||
}
|
||||
|
||||
/** 顶部「复诊到期」chip:到期未挂号 ∪ 过号未面诊,默认按药尽日升序(超期最多在前) */
|
||||
const handleRevisitDueTabClick = async () => {
|
||||
formData.pending_assign = ''
|
||||
formData.pending_assign_order_month = ''
|
||||
formData.pending_assign_keyword = ''
|
||||
formData.pending_booking = ''
|
||||
formData.completed_appointment = ''
|
||||
formData.appointment_date = ''
|
||||
formData.has_appointment = ''
|
||||
clearLatestAppointmentFilters()
|
||||
formData.revisit_state = 'due'
|
||||
formData.sort_revisit_due = 'asc'
|
||||
formData.sort_unserved_days = ''
|
||||
pager.page = 1
|
||||
await getLists()
|
||||
fetchDateCounts()
|
||||
}
|
||||
|
||||
/** 「更多筛选 → 复诊状态」下拉:与顶部日期 Tab 互斥(同 chip 语义),选中后不再默认当天挂号 */
|
||||
const handleRevisitFilterChange = () => {
|
||||
if (formData.revisit_state !== '') {
|
||||
formData.appointment_date = ''
|
||||
formData.pending_booking = ''
|
||||
formData.completed_appointment = ''
|
||||
const noSortYet = formData.sort_revisit_due === '' && formData.sort_unserved_days === ''
|
||||
if (formData.revisit_state === 'due' && noSortYet) {
|
||||
formData.sort_revisit_due = 'asc'
|
||||
}
|
||||
} else {
|
||||
formData.sort_revisit_due = ''
|
||||
}
|
||||
doSearch()
|
||||
}
|
||||
|
||||
/** 列表行 revisit_due → 规整对象(旧接口无字段时为 null,单元格显示「—」) */
|
||||
const revisitDueOf = (row: any): RevisitDue | null => normalizeRevisitDue(row?.revisit_due)
|
||||
|
||||
/** 「复诊节点」行 1 的开方文案:已开方 / 已开方(处方已作废) / 未开方 */
|
||||
const prescribedTextOf = (row: any): string => {
|
||||
if (!row?.has_prescription) return '未开方'
|
||||
return row.followup_rx_voided ? '已开方(处方已作废)' : '已开方'
|
||||
}
|
||||
|
||||
// 获取各日期挂号数量 + 全部 + 待预约 + 已完成 + 待分配医助数量 + 复诊到期数量
|
||||
// 获取各日期挂号数量 + 全部 + 待预约 + 已完成 + 待分配医助数量
|
||||
const fetchDateCounts = async () => {
|
||||
try {
|
||||
const [yesterday, dayBefore, today, tomorrow, dayAfter, all, noApt, doneVisit, pending, revisitDue] = await Promise.all([
|
||||
const [yesterday, dayBefore, today, tomorrow, dayAfter, all, noApt, doneVisit, pending] = await Promise.all([
|
||||
tcmDiagnosisLists(
|
||||
buildDateCountRequestPayload({ appointment_date: yesterdayStr.value, has_appointment: '' }) as any
|
||||
),
|
||||
@@ -1193,10 +1081,7 @@ const fetchDateCounts = async () => {
|
||||
tcmDiagnosisLists(
|
||||
buildDateCountRequestPayload({ completed_appointment: 1, has_appointment: '' }) as any
|
||||
),
|
||||
tcmDiagnosisLists(buildPendingAssignCountPayload() as any),
|
||||
tcmDiagnosisLists(
|
||||
buildDateCountRequestPayload({ revisit_state: 'due', has_appointment: '' }) as any
|
||||
)
|
||||
tcmDiagnosisLists(buildPendingAssignCountPayload() as any)
|
||||
])
|
||||
dateCounts.value = {
|
||||
[yesterdayStr.value]: yesterday?.count ?? 0,
|
||||
@@ -1209,7 +1094,6 @@ const fetchDateCounts = async () => {
|
||||
pendingBookingCount.value = noApt?.count ?? 0
|
||||
completedVisitCount.value = doneVisit?.count ?? 0
|
||||
pendingAssignCount.value = pending?.count ?? 0
|
||||
revisitDueCount.value = revisitDue?.count ?? 0
|
||||
} catch (e) {
|
||||
console.error('获取日期数量失败', e)
|
||||
}
|
||||
@@ -1368,11 +1252,12 @@ const handleTableSortChange = ({
|
||||
prop: string
|
||||
order: 'ascending' | 'descending' | null
|
||||
}) => {
|
||||
const dir: '' | 'asc' | 'desc' =
|
||||
order === 'ascending' ? 'asc' : order === 'descending' ? 'desc' : ''
|
||||
// 按列 prop 分派;两种排序后端互斥,切换列时清掉另一列
|
||||
formData.sort_unserved_days = prop === 'unserved_days' ? dir : ''
|
||||
formData.sort_revisit_due = prop === 'revisit_due_date' ? dir : ''
|
||||
if (prop === 'unserved_days') {
|
||||
formData.sort_unserved_days =
|
||||
order === 'ascending' ? 'asc' : order === 'descending' ? 'desc' : ''
|
||||
} else {
|
||||
formData.sort_unserved_days = ''
|
||||
}
|
||||
pager.page = 1
|
||||
getLists()
|
||||
}
|
||||
@@ -1426,9 +1311,6 @@ const handleReset = () => {
|
||||
formData.latest_assign_start_date = ''
|
||||
formData.latest_assign_end_date = ''
|
||||
formData.sort_unserved_days = ''
|
||||
formData.revisit_state = ''
|
||||
formData.revisit_days_bucket = ''
|
||||
formData.sort_revisit_due = ''
|
||||
formData.diagnosis_confirmed = ''
|
||||
formData.appointment_date = ''
|
||||
formData.has_appointment = ''
|
||||
@@ -1461,10 +1343,8 @@ const unservedDaysClass = (n: unknown) => {
|
||||
return 'unserved-green'
|
||||
}
|
||||
|
||||
// 行高亮优先级(方案 D3-c 默认 overdue_first):复诊超期/过号 > 未确认 > 未挂号
|
||||
// 行高亮:未确认诊单优先,其次未挂号
|
||||
const getRowClassName = ({ row }: { row: any }) => {
|
||||
const revisitCls = revisitRowClassName(revisitDueOf(row))
|
||||
if (revisitCls) return revisitCls
|
||||
if (!isDiagnosisConfirmed(row)) return 'row-unconfirmed'
|
||||
if (!row.has_appointment) return 'row-no-appointment'
|
||||
return ''
|
||||
@@ -1476,8 +1356,6 @@ const prescriptionRef = ref()
|
||||
const appointmentRef = ref()
|
||||
/** 从路由带 id 进入时,诊单弹窗为异步组件,需在 ref 就绪后再 open */
|
||||
const pendingRouteDiagnosisId = ref<number | null>(null)
|
||||
/** 路由 ?id=&action=appointment 深链(复诊到期弹窗「去挂号」):挂号弹窗同为异步组件,先暂存行再 open */
|
||||
const pendingRouteAppointmentRow = ref<Record<string, any> | null>(null)
|
||||
const userStore = useUserStore()
|
||||
|
||||
watch(
|
||||
@@ -1492,53 +1370,6 @@ watch(
|
||||
{ flush: 'post' }
|
||||
)
|
||||
|
||||
watch(
|
||||
[appointmentRef, pendingRouteAppointmentRow],
|
||||
() => {
|
||||
const row = pendingRouteAppointmentRow.value
|
||||
const opener = appointmentRef.value as { open?: (row: any) => void } | undefined
|
||||
if (!row || !opener?.open) return
|
||||
pendingRouteAppointmentRow.value = null
|
||||
handleAppointment(row)
|
||||
},
|
||||
{ flush: 'post' }
|
||||
)
|
||||
|
||||
/**
|
||||
* 深链打开挂号弹窗:优先用当前列表里的行(字段最全);不在本页时回退只读详情接口拼最小行
|
||||
* (appointment.vue open() 只读 patient_id / patient_name / gender_desc / age)。
|
||||
*/
|
||||
const openAppointmentFromRoute = async (diagnosisId: number) => {
|
||||
// 深链打开挂号弹窗前先校验挂号权限(与行内「预约」按钮 v-perms 同口径)
|
||||
if (!hasPermission(['tcm.diagnosis/guahao'])) {
|
||||
feedback.msgWarning('无挂号权限')
|
||||
return
|
||||
}
|
||||
const inList = (pager.lists as any[]).find((r) => Number(r?.id) === diagnosisId)
|
||||
if (inList) {
|
||||
pendingRouteAppointmentRow.value = inList
|
||||
return
|
||||
}
|
||||
try {
|
||||
const res: any = await diagnosisReadonlyDetail({ id: diagnosisId })
|
||||
const diag = res?.diagnosis
|
||||
if (!diag || !diag.patient_id) {
|
||||
feedback.msgWarning('未找到该诊单或患者信息不完整,无法打开挂号')
|
||||
return
|
||||
}
|
||||
pendingRouteAppointmentRow.value = {
|
||||
...diag,
|
||||
id: diagnosisId,
|
||||
patient_id: diag.patient_id,
|
||||
patient_name: diag.patient_name || '',
|
||||
gender_desc: formatGender(diag.gender),
|
||||
age: diag.age ?? 0
|
||||
}
|
||||
} catch (e: any) {
|
||||
feedback.msgWarning(e?.msg || e?.message || '加载诊单失败,无法打开挂号')
|
||||
}
|
||||
}
|
||||
|
||||
const watchCallVisible = ref(false)
|
||||
const watchCallDiagnosisId = ref(0)
|
||||
|
||||
@@ -1783,13 +1614,13 @@ const handleConfirmAssign = async () => {
|
||||
feedback.msgWarning('请选择医助')
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
assignLoading.value = true
|
||||
try {
|
||||
if (assignMode.value === 'single') {
|
||||
// 单独指派
|
||||
await tcmDiagnosisAssign({
|
||||
id: currentRow.value.id,
|
||||
await tcmDiagnosisAssign({
|
||||
id: currentRow.value.id,
|
||||
assistant_id: assignForm.value.assistant_id,
|
||||
is_inherit: assignForm.value.is_inherit ? 1 : 0
|
||||
})
|
||||
@@ -2389,57 +2220,22 @@ const goReadonly = (row: any) => {
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
// 默认展示当天挂号,突出重点
|
||||
formData.appointment_date = todayStr.value
|
||||
// 字典与列表并行,避免 await 字典阻塞首屏列表(LCP)
|
||||
getDictOptions()
|
||||
if (String(route.query.revisit_state ?? '') === 'due') {
|
||||
// 复诊到期弹窗「查看全部」深链:直接激活「复诊到期」chip(内部会 getLists + fetchDateCounts)
|
||||
void handleRevisitDueTabClick()
|
||||
} else {
|
||||
// 默认展示当天挂号,突出重点
|
||||
formData.appointment_date = todayStr.value
|
||||
getLists()
|
||||
scheduleDeferredDateCounts()
|
||||
}
|
||||
getLists()
|
||||
scheduleDeferredDateCounts()
|
||||
|
||||
silentListPollTimer = setInterval(silentRefreshListsAndDateCounts, SILENT_LIST_POLL_MS)
|
||||
|
||||
const raw = route.query.id
|
||||
if (raw != null && raw !== '') {
|
||||
const num = Number(raw)
|
||||
if (!Number.isNaN(num) && num > 0) {
|
||||
if (String(route.query.action ?? '') === 'appointment') {
|
||||
// 复诊到期弹窗「去挂号」深链:等首屏列表回来后再找行,找不到走详情接口
|
||||
void getListsPromiseForRoute().then(() => openAppointmentFromRoute(num))
|
||||
} else {
|
||||
pendingRouteDiagnosisId.value = num
|
||||
}
|
||||
}
|
||||
if (!Number.isNaN(num)) pendingRouteDiagnosisId.value = num
|
||||
}
|
||||
})
|
||||
|
||||
/** onMounted 里 getLists() 已发起;等待首屏列表 loading 结束(最多 8s)再找行,失败/超时不阻断 */
|
||||
const getListsPromiseForRoute = () =>
|
||||
new Promise<void>((resolve) => {
|
||||
if (!pager.loading) {
|
||||
resolve()
|
||||
return
|
||||
}
|
||||
let settled = false
|
||||
const finish = () => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
stop()
|
||||
resolve()
|
||||
}
|
||||
const stop = watch(
|
||||
() => pager.loading,
|
||||
(loading) => {
|
||||
if (!loading) finish()
|
||||
}
|
||||
)
|
||||
setTimeout(finish, 8000)
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
if (silentListPollTimer != null) {
|
||||
clearInterval(silentListPollTimer)
|
||||
@@ -2517,21 +2313,6 @@ onUnmounted(() => {
|
||||
}
|
||||
}
|
||||
|
||||
.chip-revisit-due {
|
||||
margin-left: 8px;
|
||||
color: var(--el-color-danger);
|
||||
background: var(--el-color-danger-light-9);
|
||||
|
||||
&:hover {
|
||||
background: var(--el-color-danger-light-8);
|
||||
}
|
||||
|
||||
&.active {
|
||||
color: #fff;
|
||||
background: var(--el-color-danger);
|
||||
}
|
||||
}
|
||||
|
||||
.chip-completed-visit {
|
||||
margin-left: 8px;
|
||||
color: var(--el-color-success);
|
||||
@@ -2670,14 +2451,6 @@ onUnmounted(() => {
|
||||
.latest-appointment-channel {
|
||||
width: 170px;
|
||||
}
|
||||
|
||||
.revisit-state-select {
|
||||
width: 170px;
|
||||
}
|
||||
|
||||
.revisit-days-bucket-select {
|
||||
width: 130px;
|
||||
}
|
||||
}
|
||||
|
||||
.list-card {
|
||||
@@ -2868,6 +2641,17 @@ onUnmounted(() => {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.status-prescribed {
|
||||
font-size: 13px;
|
||||
color: #4A5DFF;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.status-unprescribed {
|
||||
font-size: 13px;
|
||||
color: var(--el-text-color-placeholder);
|
||||
}
|
||||
|
||||
/* 未服务天数(T3):null=灰;>=7=红;3-6=橙;<=2=绿 */
|
||||
.unserved-days {
|
||||
display: inline-block;
|
||||
@@ -2912,6 +2696,33 @@ onUnmounted(() => {
|
||||
}
|
||||
}
|
||||
|
||||
.followup-cell {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
line-height: 1.35;
|
||||
|
||||
.followup-time {
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
color: var(--el-text-color-primary);
|
||||
}
|
||||
|
||||
.followup-doctor {
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
|
||||
.followup-void-tag {
|
||||
align-self: flex-start;
|
||||
}
|
||||
}
|
||||
|
||||
.followup-none {
|
||||
font-size: 13px;
|
||||
color: var(--el-text-color-placeholder);
|
||||
}
|
||||
|
||||
.assistant-cell {
|
||||
font-size: 13px;
|
||||
color: var(--el-text-color-secondary);
|
||||
@@ -2971,22 +2782,6 @@ onUnmounted(() => {
|
||||
:deep(.el-table__row.row-no-appointment:hover > td) {
|
||||
background: linear-gradient(90deg, rgba(var(--el-color-info-rgb), 0.08) 0%, transparent 100%) !important;
|
||||
}
|
||||
/* 复诊到期未挂号 / 过号未面诊:红色左边条(同 row-unconfirmed 结构,warning → danger) */
|
||||
:deep(.el-table__row.row-revisit-overdue) {
|
||||
border-left: 3px solid var(--el-color-danger);
|
||||
background: linear-gradient(90deg, rgba(var(--el-color-danger-rgb), 0.06) 0%, transparent 100%) !important;
|
||||
}
|
||||
:deep(.el-table__row.row-revisit-overdue:hover > td) {
|
||||
background: linear-gradient(90deg, rgba(var(--el-color-danger-rgb), 0.1) 0%, transparent 100%) !important;
|
||||
}
|
||||
/* 超期 ≥ severe_overdue_days:底色加深到 10%,悬停 14% */
|
||||
:deep(.el-table__row.row-revisit-overdue.row-revisit-overdue-deep) {
|
||||
border-left-color: #b91c1c;
|
||||
background: linear-gradient(90deg, rgba(var(--el-color-danger-rgb), 0.1) 0%, transparent 100%) !important;
|
||||
}
|
||||
:deep(.el-table__row.row-revisit-overdue.row-revisit-overdue-deep:hover > td) {
|
||||
background: linear-gradient(90deg, rgba(var(--el-color-danger-rgb), 0.14) 0%, transparent 100%) !important;
|
||||
}
|
||||
}
|
||||
|
||||
.record-list {
|
||||
|
||||
@@ -25,7 +25,6 @@
|
||||
formData.pending_assign !== '1' &&
|
||||
formData.pending_booking !== '1' &&
|
||||
formData.completed_appointment !== '1' &&
|
||||
formData.revisit_state === '' &&
|
||||
formData.appointment_date === tab.value
|
||||
}
|
||||
]"
|
||||
@@ -41,13 +40,6 @@
|
||||
待预约
|
||||
<em v-if="pendingBookingCount !== undefined">{{ pendingBookingCount }}</em>
|
||||
</span>
|
||||
<span
|
||||
:class="['dh5-chip', 'dh5-chip--revisit', { active: formData.revisit_state === 'due' }]"
|
||||
@click="handleRevisitDueTabClick"
|
||||
>
|
||||
复诊到期
|
||||
<em v-if="revisitDueCount !== undefined">{{ revisitDueCount }}</em>
|
||||
</span>
|
||||
<span
|
||||
:class="['dh5-chip', 'dh5-chip--done', { active: formData.completed_appointment === '1' }]"
|
||||
@click="handleCompletedVisitTabClick"
|
||||
@@ -178,17 +170,13 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 复诊节点块(已开方或有复诊节点数据时显示;卡片头已有「已开方」标签,此处隐藏开方文案) -->
|
||||
<div v-if="row.has_prescription || hasRevisitDue(revisitDueOf(row))" class="dh5-row dh5-row--followup">
|
||||
<!-- 复诊块(仅已开方时显示) -->
|
||||
<div v-if="row.has_prescription" class="dh5-row dh5-row--followup">
|
||||
<span class="dh5-row-key">复诊</span>
|
||||
<div class="dh5-row-val dh5-row-val--revisit">
|
||||
<revisit-node-cell
|
||||
compact
|
||||
:due="revisitDueOf(row)"
|
||||
:has-prescription="!!row.has_prescription"
|
||||
:followup-doctor-name="row.followup_doctor_name || ''"
|
||||
:prescribed-text="row.followup_rx_voided ? '处方作废' : ''"
|
||||
/>
|
||||
<div class="dh5-row-val">
|
||||
<span>{{ row.followup_time_text || '—' }}</span>
|
||||
<span class="dh5-meta-doctor">{{ row.followup_doctor_name || '—' }}</span>
|
||||
<span v-if="row.followup_rx_voided" class="dh5-tag dh5-tag--gray">处方作废</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -637,13 +625,6 @@ import {
|
||||
import useUserStore from '@/stores/modules/user'
|
||||
import { defineAsyncComponent, computed, reactive, ref, onMounted, onUnmounted } from 'vue'
|
||||
import dayjs from 'dayjs'
|
||||
import RevisitNodeCell from './components/RevisitNodeCell.vue'
|
||||
import {
|
||||
hasRevisitDue,
|
||||
isRevisitDueHighlight,
|
||||
normalizeRevisitDue,
|
||||
type RevisitDue
|
||||
} from '@/utils/revisitDue'
|
||||
|
||||
const EditPopup = defineAsyncComponent(() => import('./edit.vue'))
|
||||
const DetailPopup = defineAsyncComponent(() => import('./detail.vue'))
|
||||
@@ -704,9 +685,7 @@ const formData = reactive({
|
||||
has_appointment: '' as '' | '0' | '1',
|
||||
pending_assign: '' as '' | '1',
|
||||
pending_booking: '' as '' | '1',
|
||||
completed_appointment: '' as '' | '1',
|
||||
/** 顶部「复诊到期」chip:due = 到期未挂号 ∪ 过号未面诊(后端 revisit_state) */
|
||||
revisit_state: '' as '' | 'due'
|
||||
completed_appointment: '' as '' | '1'
|
||||
})
|
||||
|
||||
const showMoreFilter = ref(false)
|
||||
@@ -761,7 +740,6 @@ const handleReset = () => {
|
||||
formData.pending_assign = ''
|
||||
formData.pending_booking = ''
|
||||
formData.completed_appointment = ''
|
||||
formData.revisit_state = ''
|
||||
pager.page = 1
|
||||
getLists()
|
||||
fetchDateCounts()
|
||||
@@ -789,7 +767,6 @@ const handleDateTabClick = async (value: string) => {
|
||||
formData.pending_assign = ''
|
||||
formData.pending_booking = ''
|
||||
formData.completed_appointment = ''
|
||||
formData.revisit_state = ''
|
||||
formData.has_appointment = ''
|
||||
formData.appointment_date = value
|
||||
pager.page = 1
|
||||
@@ -801,7 +778,6 @@ const handlePendingBookingTabClick = async () => {
|
||||
formData.pending_assign = ''
|
||||
formData.pending_booking = '1'
|
||||
formData.completed_appointment = ''
|
||||
formData.revisit_state = ''
|
||||
formData.appointment_date = ''
|
||||
formData.has_appointment = '0'
|
||||
pager.page = 1
|
||||
@@ -813,7 +789,6 @@ const handleCompletedVisitTabClick = async () => {
|
||||
formData.pending_assign = ''
|
||||
formData.pending_booking = ''
|
||||
formData.completed_appointment = '1'
|
||||
formData.revisit_state = ''
|
||||
formData.has_appointment = ''
|
||||
formData.appointment_date = ''
|
||||
pager.page = 1
|
||||
@@ -825,7 +800,6 @@ const handlePendingAssignTabClick = async () => {
|
||||
formData.pending_assign = '1'
|
||||
formData.pending_booking = ''
|
||||
formData.completed_appointment = ''
|
||||
formData.revisit_state = ''
|
||||
formData.has_appointment = ''
|
||||
formData.appointment_date = ''
|
||||
pager.page = 1
|
||||
@@ -833,27 +807,9 @@ const handlePendingAssignTabClick = async () => {
|
||||
fetchDateCounts()
|
||||
}
|
||||
|
||||
/** 顶部「复诊到期」chip:到期未挂号 ∪ 过号未面诊;后端按 revisit_state=due 过滤,排序默认药尽日升序 */
|
||||
const handleRevisitDueTabClick = async () => {
|
||||
formData.pending_assign = ''
|
||||
formData.pending_booking = ''
|
||||
formData.completed_appointment = ''
|
||||
formData.has_appointment = ''
|
||||
formData.appointment_date = ''
|
||||
formData.revisit_state = 'due'
|
||||
pager.page = 1
|
||||
await getLists()
|
||||
fetchDateCounts()
|
||||
}
|
||||
|
||||
const revisitDueCount = ref<number | undefined>(undefined)
|
||||
|
||||
/** 列表行 revisit_due → 规整对象(旧接口无字段时为 null,不渲染复诊块) */
|
||||
const revisitDueOf = (row: any): RevisitDue | null => normalizeRevisitDue(row?.revisit_due)
|
||||
|
||||
const fetchDateCounts = async () => {
|
||||
try {
|
||||
const [yesterday, dayBefore, today, tomorrow, dayAfter, all, noApt, doneVisit, pending, revisitDue] = await Promise.all([
|
||||
const [yesterday, dayBefore, today, tomorrow, dayAfter, all, noApt, doneVisit, pending] = await Promise.all([
|
||||
tcmDiagnosisLists({ appointment_date: yesterdayStr.value, page_no: 1, page_size: 1 }),
|
||||
tcmDiagnosisLists({ appointment_date: dayBeforeStr.value, page_no: 1, page_size: 1 }),
|
||||
tcmDiagnosisLists({ appointment_date: todayStr.value, page_no: 1, page_size: 1 }),
|
||||
@@ -862,8 +818,7 @@ const fetchDateCounts = async () => {
|
||||
tcmDiagnosisLists({ page_no: 1, page_size: 1 }),
|
||||
tcmDiagnosisLists({ has_appointment: 0, page_no: 1, page_size: 1 }),
|
||||
tcmDiagnosisLists({ completed_appointment: 1, page_no: 1, page_size: 1 }),
|
||||
tcmDiagnosisLists({ pending_assign: 1, page_no: 1, page_size: 1 }),
|
||||
tcmDiagnosisLists({ revisit_state: 'due', page_no: 1, page_size: 1 })
|
||||
tcmDiagnosisLists({ pending_assign: 1, page_no: 1, page_size: 1 })
|
||||
])
|
||||
dateCounts.value = {
|
||||
[yesterdayStr.value]: yesterday?.count ?? 0,
|
||||
@@ -876,7 +831,6 @@ const fetchDateCounts = async () => {
|
||||
pendingBookingCount.value = noApt?.count ?? 0
|
||||
completedVisitCount.value = doneVisit?.count ?? 0
|
||||
pendingAssignCount.value = pending?.count ?? 0
|
||||
revisitDueCount.value = revisitDue?.count ?? 0
|
||||
} catch (e) {
|
||||
console.error('获取日期数量失败', e)
|
||||
}
|
||||
@@ -944,9 +898,7 @@ const isDiagnosisConfirmed = (row: any) => {
|
||||
return records.length > 0 && records.some((r: any) => r.is_confirmed == 1)
|
||||
}
|
||||
|
||||
// 卡片左边条优先级(同 PC 行高亮):复诊超期/过号 > 未确认 > 未挂号
|
||||
const getCardClass = (row: any) => {
|
||||
if (isRevisitDueHighlight(revisitDueOf(row))) return 'dh5-card--overdue'
|
||||
if (!isDiagnosisConfirmed(row)) return 'dh5-card--unconfirmed'
|
||||
if (!row.has_appointment) return 'dh5-card--noapt'
|
||||
return ''
|
||||
@@ -1630,8 +1582,6 @@ $dh5-card-bg: #ffffff;
|
||||
.dh5-chip--booking.active { background: $dh5-warn; }
|
||||
.dh5-chip--done.active { background: $dh5-success; }
|
||||
.dh5-chip--pending.active { background: $dh5-danger; }
|
||||
.dh5-chip--revisit { color: #b91c1c; background: rgba(239, 68, 68, 0.10); }
|
||||
.dh5-chip--revisit.active { color: #fff; background: $dh5-danger; }
|
||||
|
||||
.dh5-quick {
|
||||
display: flex;
|
||||
@@ -1725,12 +1675,6 @@ $dh5-card-bg: #ffffff;
|
||||
|
||||
.dh5-card--unconfirmed::before { background: $dh5-danger; }
|
||||
.dh5-card--noapt::before { background: $dh5-warn; }
|
||||
/* 复诊到期未挂号 / 过号未面诊:左边条同 danger,外框与底色轻微染红以区分「未确认」 */
|
||||
.dh5-card--overdue::before { background: $dh5-danger; }
|
||||
.dh5-card--overdue {
|
||||
border-color: rgba(239, 68, 68, 0.35);
|
||||
background: linear-gradient(90deg, rgba(239, 68, 68, 0.05) 0%, $dh5-card-bg 60%);
|
||||
}
|
||||
|
||||
.dh5-card-head {
|
||||
display: flex;
|
||||
@@ -1856,11 +1800,6 @@ $dh5-card-bg: #ffffff;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
/* 复诊节点块:单元格组件自带多行布局,取消外层 flex 换行间距 */
|
||||
.dh5-row-val--revisit {
|
||||
display: block;
|
||||
}
|
||||
|
||||
/* 挂号块 - 状态色 */
|
||||
.dh5-row--apt {
|
||||
background: #fafbfc;
|
||||
|
||||
@@ -25,17 +25,6 @@
|
||||
</span>
|
||||
</el-tooltip>
|
||||
<span v-else class="unserved-badge unserved-muted">从未打卡</span>
|
||||
<!-- 复诊节点徽标:第 N 诊 · 药尽 MM-DD · 超期 N 天(接口无 revisit_due 字段时不渲染) -->
|
||||
<el-tooltip
|
||||
v-if="revisitBadgeLabel"
|
||||
placement="bottom"
|
||||
:disabled="!revisitTooltipText"
|
||||
:content="revisitTooltipText"
|
||||
>
|
||||
<span :class="['unserved-badge', 'revisit-badge', revisitBadgeColorClass]">
|
||||
{{ revisitBadgeLabel }}
|
||||
</span>
|
||||
</el-tooltip>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -167,12 +156,6 @@ import { diagnosisReadonlyDetail } from '@/api/tcm'
|
||||
import { getDoctorNotes } from '@/api/patient'
|
||||
import { formatGender } from '@/utils/diag-display'
|
||||
import { hasPermission } from '@/utils/perm'
|
||||
import {
|
||||
normalizeRevisitDue,
|
||||
revisitBadgeText,
|
||||
revisitStateColorClass,
|
||||
revisitTooltipLines
|
||||
} from '@/utils/revisitDue'
|
||||
import PatientInfoCard from './components/PatientInfoCard.vue'
|
||||
import PatientCaseCard from './components/PatientCaseCard.vue'
|
||||
import DailyMatrix from './components/DailyMatrix.vue'
|
||||
@@ -210,17 +193,6 @@ const unservedDays = computed<number | null>(() => {
|
||||
})
|
||||
const lastBloodAt = computed<string>(() => detail.value?.last_blood_record_at || '')
|
||||
|
||||
/** 复诊节点:readonlyDetail 顶层 revisit_due(兼容挂在 diagnosis 下);字段不存在 → null → 不渲染徽标 */
|
||||
const revisitDue = computed(() =>
|
||||
normalizeRevisitDue(detail.value?.revisit_due ?? detail.value?.diagnosis?.revisit_due)
|
||||
)
|
||||
const revisitBadgeLabel = computed(() => revisitBadgeText(revisitDue.value))
|
||||
const revisitBadgeColorClass = computed(() => {
|
||||
const due = revisitDue.value
|
||||
return due ? revisitStateColorClass(due.state) : 'unserved-muted'
|
||||
})
|
||||
const revisitTooltipText = computed(() => revisitTooltipLines(revisitDue.value).join(';'))
|
||||
|
||||
/**
|
||||
* 「未服务天数」着色规则(与 T3 列表一致):
|
||||
* null/undefined → 灰;>=7 → 红;3-6 → 橙;<=2 → 绿
|
||||
@@ -380,13 +352,6 @@ onMounted(fetchDetail)
|
||||
border-color: #fecaca;
|
||||
background: rgba(220, 38, 38, 0.08);
|
||||
}
|
||||
|
||||
/* 复诊节点徽标专用:已约 / 已联系 */
|
||||
&.unserved-blue {
|
||||
color: #4a5dff;
|
||||
border-color: #c7d2fe;
|
||||
background: rgba(74, 93, 255, 0.08);
|
||||
}
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
|
||||
@@ -26,19 +26,15 @@ const render = moduleFrom(template.code).render
|
||||
const passthrough = { setup: (_, { slots }) => () => vue.h('div', [slots.default?.(), slots.headerToolbar?.()]) }
|
||||
const picker = text => ({ setup: () => () => vue.h('button', text) })
|
||||
|
||||
function chat(policy = {}, migrationBlocked = vue.ref(false)) {
|
||||
function chat(policy = {}) {
|
||||
const requests = [], warnings = [], sdkCalls = []
|
||||
const guard = moduleFrom(read('utils/appointment-call-guard.ts'))
|
||||
const server = Object.fromEntries(['calls', 'call', 'groupCall', 'accept'].map(name => [name, async params => { sdkCalls.push({ name, params }) }]))
|
||||
const server = Object.fromEntries(['calls', 'call', 'groupCall'].map(name => [name, async params => { sdkCalls.push({ name, params }) }]))
|
||||
const api = { getCallSignature: async params => { requests.push(params); return policy } }
|
||||
const result = moduleFrom(script.content, name => {
|
||||
if (name === 'vue') return { ...vue, onMounted() {}, onUnmounted() {} }
|
||||
if (name === '@/utils/appointment-type') return types
|
||||
if (name === '@/utils/appointment-call-guard') return guard
|
||||
if (name === '@/hooks/useDoctorWebConsultation') return {
|
||||
useDoctorWebConsultation: () => ({ webConsultationBlocked: migrationBlocked, webConsultationMessage: vue.ref('网页端面诊已停用,请医生使用桌面应用进行面诊。'), ensureWebConsultationAllowed: () => !migrationBlocked.value })
|
||||
}
|
||||
if (name === '@/utils/doctor-web-consultation') return moduleFrom(read('utils/doctor-web-consultation.ts'))
|
||||
if (name === '@/utils/im-chat-archive-trigger') return moduleFrom(read('utils/im-chat-archive-trigger.ts'))
|
||||
if (name === '@/api/tcm') return api
|
||||
if (name === '@/utils/feedback') return { default: { msgWarning: text => warnings.push(text) } }
|
||||
@@ -148,31 +144,3 @@ test('singleton call guard switches to current chat and cancels a pending old co
|
||||
releaseNew()
|
||||
await assert.rejects(guard.checkAppointmentOutgoingCall({ type: 2 }), /先打开/)
|
||||
})
|
||||
|
||||
test('a cached video session stops every outgoing SDK path and incoming accept after migration', async () => {
|
||||
const blocked = vue.ref(false)
|
||||
const { state, server, sdkCalls, requests } = chat(policy('video'), blocked)
|
||||
state.installTUICallKitRoomHooks()
|
||||
assert.equal(state.canVideoCall.value, true)
|
||||
blocked.value = true
|
||||
assert.equal(state.canVideoCall.value, false)
|
||||
assert.equal(state.canAudioCall.value, false)
|
||||
for (const method of ['call', 'calls', 'groupCall', 'accept']) {
|
||||
await assert.rejects(server[method]({ type: 2 }), /桌面应用/)
|
||||
}
|
||||
await state.startGroupVideoCall()
|
||||
assert.deepEqual(sdkCalls, [])
|
||||
assert.deepEqual(requests, [])
|
||||
})
|
||||
|
||||
test('a signature request spanning the deadline never reaches the calling SDK', async () => {
|
||||
const blocked = vue.ref(false)
|
||||
const { state, server, sdkCalls, api } = chat(policy('video'), blocked)
|
||||
state.installTUICallKitRoomHooks()
|
||||
api.getCallSignature = async () => {
|
||||
blocked.value = true
|
||||
return policy('video')
|
||||
}
|
||||
await assert.rejects(server.calls({ type: 2 }), /桌面应用/)
|
||||
assert.deepEqual(sdkCalls, [])
|
||||
})
|
||||
|
||||
@@ -1,214 +0,0 @@
|
||||
const assert = require('node:assert/strict')
|
||||
const fs = require('node:fs')
|
||||
const path = require('node:path')
|
||||
const test = require('node:test')
|
||||
const ts = require('typescript')
|
||||
const vue = require('vue')
|
||||
const { parse, compileScript, compileTemplate } = require('@vue/compiler-sfc')
|
||||
const { renderToString } = require('@vue/server-renderer')
|
||||
|
||||
const read = name => fs.readFileSync(path.join(__dirname, '../src', name), 'utf8')
|
||||
function moduleFrom(source, dependencies = require, globals = {}) {
|
||||
const code = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
const module = { exports: {} }
|
||||
new Function('require', 'module', 'exports', ...Object.keys(globals), code)(dependencies, module, module.exports, ...Object.values(globals))
|
||||
return module.exports
|
||||
}
|
||||
const util = moduleFrom(read('utils/consultation-transcripts.ts'))
|
||||
const row = (id, diagnosis = 101, text = `医生:记录${id}的问题\n患者:记录${id}的回答`) => ({
|
||||
id, diagnosis_id: diagnosis, call_type: 2, status: 2, start_time: 1792444800,
|
||||
start_time_text: '2026-10-20 09:20:00', end_time_text: '2026-10-20 09:30:00',
|
||||
duration_text: '10分钟', transcript_text: text, transcription_status: 'completed', transcription_segment_count: 2
|
||||
})
|
||||
const drain = () => new Promise(resolve => setImmediate(resolve))
|
||||
|
||||
test('each call keeps its own transcript even when multiple visits have the same date', () => {
|
||||
const rows = util.normalizeConsultationRecords([row(10), row(11), row(12, 202, '串诊单文字'), row(10), null, { id: 0 }], 101)
|
||||
assert.deepEqual(rows.map(item => item.id), [11, 10])
|
||||
assert.equal(rows[0].transcript_text, row(11).transcript_text)
|
||||
assert.equal(rows[1].transcript_text, row(10).transcript_text)
|
||||
assert.throws(() => util.normalizeConsultationRecords({ lists: [] }, 101), /格式异常/)
|
||||
const legacy = util.normalizeConsultationRecords([{ id: '13', transcript_text: '医生:你好\r\n患者:你好' }], 101)[0]
|
||||
assert.equal(legacy.diagnosis_id, 101)
|
||||
assert.equal(legacy.transcript_text, '医生:你好\n患者:你好')
|
||||
})
|
||||
|
||||
test('running, partial and failed calls retain their saved words without pretending they are complete', () => {
|
||||
for (const [status, label] of [['running', '录音转写中'], ['partial', '文字部分保存'], ['failed', '文字生成失败']]) {
|
||||
const record = { ...row(1), transcription_status: status }
|
||||
assert.equal(util.consultationTranscriptStatus(record).label, label)
|
||||
assert.equal(util.consultationTranscriptText(record), row(1).transcript_text)
|
||||
}
|
||||
assert.match(util.consultationTranscriptEmptyText({ ...row(1), transcription_status: 'running', transcript_text: '' }), /正在转写/)
|
||||
assert.match(util.consultationTranscriptEmptyText({ status: 3 }), /未接听/)
|
||||
assert.match(util.consultationTranscriptEmptyText({ status: 4 }), /已取消/)
|
||||
assert.equal(util.consultationTranscriptStatus({ transcript_text: '历史已保存文字' }).label, '文字已保存')
|
||||
})
|
||||
|
||||
function hookFixture(initial = 101) {
|
||||
const id = vue.ref(initial), requests = [], cleanup = []
|
||||
const hook = moduleFrom(read('hooks/useConsultationTranscripts.ts'), name => {
|
||||
if (name === 'vue') return { ...vue, onBeforeUnmount: fn => cleanup.push(fn) }
|
||||
if (name === '@/api/tcm') return { getConsultationTranscripts: (params, signal) => new Promise((resolve, reject) => requests.push({ params, signal, resolve, reject })) }
|
||||
if (name === '@/utils/consultation-transcripts') return util
|
||||
throw new Error(name)
|
||||
})
|
||||
const scope = vue.effectScope()
|
||||
const state = scope.run(() => hook.useConsultationTranscripts(() => id.value))
|
||||
return { id, requests, state, dispose() { cleanup.forEach(fn => fn()); scope.stop() } }
|
||||
}
|
||||
|
||||
test('changing diagnosis clears the old words immediately and ignores late responses and failures', async () => {
|
||||
const f = hookFixture()
|
||||
assert.deepEqual(f.requests[0].params, { diagnosis_id: 101 })
|
||||
f.id.value = 202
|
||||
assert.equal(f.requests[0].signal.aborted, true)
|
||||
assert.deepEqual(f.state.records.value, [])
|
||||
f.requests[1].resolve([row(20, 202), row(99, 101, '不属于该诊单')])
|
||||
await drain()
|
||||
assert.deepEqual(f.state.records.value.map(item => item.id), [20])
|
||||
f.requests[0].reject(new Error('旧诊单请求失败'))
|
||||
await drain()
|
||||
assert.deepEqual(f.state.records.value.map(item => item.id), [20])
|
||||
assert.equal(f.state.error.value, '')
|
||||
f.id.value = 303
|
||||
assert.deepEqual(f.state.records.value, [])
|
||||
f.dispose()
|
||||
assert.equal(f.requests[2].signal.aborted, true)
|
||||
f.requests[2].resolve([row(30, 303)])
|
||||
await drain()
|
||||
assert.deepEqual(f.state.records.value, [])
|
||||
})
|
||||
|
||||
test('manual refresh preserves current records on failure and recovers on retry without writes', async () => {
|
||||
const f = hookFixture()
|
||||
f.requests[0].resolve([row(10)])
|
||||
await drain()
|
||||
const failed = f.state.refresh()
|
||||
f.requests[1].reject(new Error('网络连接失败'))
|
||||
await failed
|
||||
assert.equal(f.state.records.value[0].id, 10)
|
||||
assert.equal(f.state.error.value, '网络连接失败')
|
||||
assert.equal(f.state.loading.value, false)
|
||||
const retried = f.state.refresh()
|
||||
f.requests[2].resolve([row(11)])
|
||||
await retried
|
||||
assert.equal(f.state.error.value, '')
|
||||
assert.equal(f.state.records.value[0].id, 11)
|
||||
f.id.value = 0
|
||||
assert.equal(f.requests.length, 3)
|
||||
assert.deepEqual(f.state.records.value, [])
|
||||
f.dispose()
|
||||
})
|
||||
|
||||
const filename = 'views/tcm/diagnosis/components/ConsultationTranscriptPanel.vue'
|
||||
const { descriptor, errors } = parse(read(filename), { filename })
|
||||
assert.deepEqual(errors, [])
|
||||
const script = compileScript(descriptor, { id: 'consultation-transcript-panel' })
|
||||
const template = compileTemplate({ source: descriptor.template.content, filename, id: 'consultation-transcript-panel', compilerOptions: { bindingMetadata: script.bindings } })
|
||||
assert.deepEqual(template.errors, [])
|
||||
const render = moduleFrom(template.code).render
|
||||
|
||||
function panelFixture(records, extra = {}) {
|
||||
const props = vue.reactive({ diagnosisId: 101 })
|
||||
const data = { records: vue.ref(records), loading: vue.ref(false), error: vue.ref(''), refresh() {}, ...extra }
|
||||
const copied = [], notices = []
|
||||
const scope = vue.effectScope()
|
||||
const component = moduleFrom(script.content, name => {
|
||||
if (name === 'vue') return vue
|
||||
if (name === '@/hooks/useConsultationTranscripts') return { useConsultationTranscripts: () => data }
|
||||
if (name === '@/utils/consultation-transcripts') return util
|
||||
if (name === '@/utils/feedback') return { default: { msgWarning: text => notices.push(text), msgSuccess: text => notices.push(text) } }
|
||||
if (name === '@element-plus/icons-vue') return { Refresh: { render: () => vue.h('svg') }, Search: {} }
|
||||
throw new Error(name)
|
||||
}, { navigator: { clipboard: { writeText: async text => { copied.push(text) } } } })
|
||||
const state = scope.run(() => component.default.setup(props, { expose() {} }))
|
||||
async function html() {
|
||||
const app = vue.createSSRApp({ render: () => render({}, [], props, vue.proxyRefs(state)) })
|
||||
app.directive('loading', { getSSRProps: () => ({}) })
|
||||
for (const name of ['el-button', 'el-icon', 'el-pagination']) app.component(name, { setup: (_, { slots }) => () => vue.h('span', slots.default?.()) })
|
||||
app.component('el-tag', { props: ['type'], setup: (props, { slots }) => () => vue.h('span', { 'data-type': props.type }, slots.default?.()) })
|
||||
app.component('el-empty', { props: ['description'], setup: props => () => vue.h('p', { class: 'empty-description' }, props.description) })
|
||||
app.component('el-alert', { props: ['title'], setup: props => () => vue.h('p', { role: 'alert' }, props.title) })
|
||||
app.component('el-input', { setup: () => () => vue.h('input') })
|
||||
return renderToString(app)
|
||||
}
|
||||
return { props, state, data, copied, notices, html, dispose: () => scope.stop() }
|
||||
}
|
||||
|
||||
test('the real panel selects one call, copies only its complete text, and escapes transcript HTML', async () => {
|
||||
const f = panelFixture([row(12, 101, ''), row(11, 101, '医生:<img src=x onerror=alert(1)>\n患者:本次回答'), row(10), row(99, 202, '串诊单文字')])
|
||||
assert.equal(f.state.selectedId.value, 11)
|
||||
let html = await f.html()
|
||||
assert.match(html, /<img src=x onerror=alert\(1\)>/)
|
||||
assert.doesNotMatch(html, /<img src=x|串诊单文字/)
|
||||
assert.doesNotMatch(html.match(/<pre[^>]*>([\s\S]*?)<\/pre>/)[1], /记录10/)
|
||||
await f.state.copyTranscript()
|
||||
assert.deepEqual(f.copied, ['医生:<img src=x onerror=alert(1)>\n患者:本次回答'])
|
||||
f.state.selectedId.value = 10
|
||||
assert.equal(f.state.selectedText.value, row(10).transcript_text)
|
||||
f.data.records.value = [row(13), row(11), row(10)]
|
||||
assert.equal(f.state.selectedId.value, 10)
|
||||
f.state.search.value = '记录13'
|
||||
assert.equal(f.state.selectedId.value, 13)
|
||||
assert.equal(f.state.filteredRecords.value.length, 1)
|
||||
f.props.diagnosisId = 202
|
||||
assert.equal(f.state.selectedText.value, '')
|
||||
assert.doesNotMatch(await f.html(), /记录13的问题|本次回答/)
|
||||
f.dispose()
|
||||
})
|
||||
|
||||
test('empty, failed and partial transcription states remain explicit in the rendered panel', async () => {
|
||||
for (const status of ['running', 'partial', 'failed']) {
|
||||
const f = panelFixture([{ ...row(1), transcription_status: status }])
|
||||
const html = await f.html()
|
||||
assert.match(html, /已保存|刷新查看最新/)
|
||||
assert.match(html, /记录1的问题/)
|
||||
f.dispose()
|
||||
}
|
||||
const missing = panelFixture([row(1, 101, '')])
|
||||
assert.match(await missing.html(), /本次面诊暂无已保存的文字对话/)
|
||||
missing.dispose()
|
||||
const none = panelFixture([])
|
||||
assert.match(await none.html(), /该诊单暂无面诊通话记录/)
|
||||
none.dispose()
|
||||
const failed = panelFixture([], { error: vue.ref('无权访问该诊单') })
|
||||
assert.match(await failed.html(), /无权访问该诊单/)
|
||||
assert.doesNotMatch(await failed.html(), /该诊单暂无面诊通话记录/)
|
||||
failed.dispose()
|
||||
})
|
||||
|
||||
test('the new tab is permission gated, lazy and absent when the drawer is closed', async () => {
|
||||
const { descriptor } = parse(read('views/tcm/diagnosis/edit.vue'))
|
||||
const editScript = compileScript(descriptor, { id: 'diagnosis-edit-transcript' })
|
||||
const pane = descriptor.template.content.match(/<el-tab-pane\s+v-if="hasCallTranscriptPermission"[\s\S]*?<\/el-tab-pane>/)[0]
|
||||
const compiled = compileTemplate({ source: pane, filename: 'edit-transcript-tab.vue', id: 'edit-transcript', compilerOptions: { bindingMetadata: editScript.bindings } })
|
||||
assert.deepEqual(compiled.errors, [])
|
||||
const renderPane = moduleFrom(compiled.code).render
|
||||
async function html(allowed, active, visible, id) {
|
||||
const state = { hasCallTranscriptPermission: allowed, activeTab: active, visible, formData: { id }, ConsultationTranscriptPanel: { props: ['diagnosisId'], setup: props => () => vue.h('div', { 'data-diagnosis': props.diagnosisId }, '真实转写面板入口') } }
|
||||
const app = vue.createSSRApp({ render: () => renderPane({}, [], {}, state) })
|
||||
app.component('el-tab-pane', { props: ['disabled', 'label'], setup: (props, { slots }) => () => vue.h('section', { 'data-disabled': String(props.disabled) }, [props.label, slots.default?.()]) })
|
||||
app.component('el-empty', { props: ['description'], setup: props => () => vue.h('p', props.description) })
|
||||
return renderToString(app)
|
||||
}
|
||||
assert.doesNotMatch(await html(false, 'callTranscript', true, 101), /面诊文字对话/)
|
||||
assert.doesNotMatch(await html(true, 'basic', true, 101), /真实转写面板入口/)
|
||||
assert.doesNotMatch(await html(true, 'callTranscript', false, 101), /真实转写面板入口/)
|
||||
assert.match(await html(true, 'callTranscript', true, 101), /data-diagnosis="101"/)
|
||||
assert.match(await html(true, 'callTranscript', true, ''), /data-disabled="true"/)
|
||||
})
|
||||
|
||||
test('the read helper sends the exact diagnosis and abort signal without canceling replay requests', async () => {
|
||||
let request
|
||||
const api = moduleFrom(read('api/tcm.ts'), name => {
|
||||
if (name === '@/utils/request') return { default: { get: (...args) => { request = args; return Promise.resolve([]) } } }
|
||||
throw new Error(name)
|
||||
})
|
||||
const controller = new AbortController()
|
||||
await api.getConsultationTranscripts({ diagnosis_id: 101 }, controller.signal)
|
||||
assert.equal(request[0].url, '/tcm.diagnosis/getCallRecords')
|
||||
assert.deepEqual(request[0].params, { diagnosis_id: 101 })
|
||||
assert.equal(request[0].signal, controller.signal)
|
||||
assert.equal(request[1].ignoreCancelToken, true)
|
||||
})
|
||||
@@ -1,419 +0,0 @@
|
||||
const assert = require('node:assert/strict')
|
||||
const fs = require('node:fs')
|
||||
const path = require('node:path')
|
||||
const test = require('node:test')
|
||||
const ts = require('typescript')
|
||||
const vue = require('vue')
|
||||
const { renderToString } = require('@vue/server-renderer')
|
||||
const { parse, compileScript, compileTemplate } = require('@vue/compiler-sfc')
|
||||
|
||||
const read = name => fs.readFileSync(path.join(__dirname, '../src', name), 'utf8')
|
||||
function moduleFrom(source, dependencies = require, globals = {}) {
|
||||
const code = ts.transpileModule(source, {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 }
|
||||
}).outputText
|
||||
const module = { exports: {} }
|
||||
new Function('require', 'module', 'exports', ...Object.keys(globals), code)(dependencies, module, module.exports, ...Object.values(globals))
|
||||
return module.exports
|
||||
}
|
||||
const policy = moduleFrom(read('utils/doctor-web-consultation.ts'))
|
||||
const cutoff = Date.parse('2026-10-24T00:00:00+08:00')
|
||||
const schedule = {
|
||||
cutoff_at: '2026-10-24T00:00:00+08:00',
|
||||
approaching_at: '2026-10-22T00:00:00+08:00',
|
||||
urgent_at: '2026-10-23T00:00:00+08:00',
|
||||
server_time: cutoff / 1000
|
||||
}
|
||||
const doctor = { root: 0, role_ids: [1] }
|
||||
const installer = {
|
||||
platform: 'windows_x64', label: 'Windows 64位',
|
||||
url: 'https://cdn.example.test/doctor-setup.exe',
|
||||
filename: 'doctor-setup.exe', sha256: 'a'.repeat(64), size: 171474334, type: 'inno_setup'
|
||||
}
|
||||
|
||||
test('doctors can use the web throughout October 23, and stop exactly at Shanghai midnight', () => {
|
||||
assert.equal(Date.parse(schedule.cutoff_at), Date.parse('2026-10-23T16:00:00Z'))
|
||||
assert.equal(policy.isDoctorWebConsultationBlocked(doctor, schedule, cutoff - 1), false)
|
||||
assert.equal(policy.isDoctorWebConsultationBlocked(doctor, schedule, cutoff), true)
|
||||
assert.equal(policy.isDoctorWebConsultationBlocked(doctor, schedule, cutoff + 1), true)
|
||||
for (const user of [{ root: 1, role_ids: [1] }, { role_ids: [2] }, { role_ids: [3, 7, 8] }, {}]) {
|
||||
assert.equal(policy.isDoctorWebConsultationBlocked(user, schedule, cutoff), false)
|
||||
}
|
||||
assert.equal(policy.isDoctorWebConsultationBlocked({ role_ids: ['2', '1'] }, schedule, cutoff), true)
|
||||
})
|
||||
|
||||
test('the mounted page changes at midnight, rechecks clicks and keeps a previously synchronized clock', () => {
|
||||
let clock = cutoff - 10000
|
||||
const mounted = [], unmounted = [], warnings = []
|
||||
let tick
|
||||
const listeners = new Map()
|
||||
const surface = { addEventListener: (name, callback) => listeners.set(name, callback), removeEventListener: name => listeners.delete(name) }
|
||||
// The profile was fetched earlier; opening a new page must not reset to that old server timestamp.
|
||||
const store = vue.reactive({ userInfo: { ...doctor, web_consultation_policy: schedule }, serverTimeOffsetMs: 5000 })
|
||||
const hook = moduleFrom(read('hooks/useDoctorWebConsultation.ts'), name => {
|
||||
if (name === 'vue') return { ...vue, onMounted: fn => mounted.push(fn), onUnmounted: fn => unmounted.push(fn) }
|
||||
if (name === '@/stores/modules/user') return { default: () => store }
|
||||
if (name === '@/api/app') return { getDoctorWebConsultationPolicy: () => new Promise(() => {}) }
|
||||
if (name === '@/utils/feedback') return { default: { msgWarning: text => warnings.push(text) } }
|
||||
if (name === '@/utils/doctor-web-consultation') return policy
|
||||
throw new Error(`Unexpected import: ${name}`)
|
||||
}, { Date: { now: () => clock }, window: surface, document: surface, setInterval: fn => { tick = fn; return 1 }, clearInterval: () => { tick = undefined } })
|
||||
const state = hook.useDoctorWebConsultation()
|
||||
mounted.forEach(fn => fn())
|
||||
assert.equal(state.webConsultationBlocked.value, false)
|
||||
clock = cutoff - 5000
|
||||
tick()
|
||||
assert.equal(state.webConsultationBlocked.value, true)
|
||||
assert.equal(state.ensureWebConsultationAllowed(), false)
|
||||
assert.match(warnings[0], /桌面应用/)
|
||||
clock = cutoff - 5001
|
||||
listeners.get('focus')()
|
||||
assert.equal(state.webConsultationBlocked.value, false)
|
||||
clock = cutoff - 5000
|
||||
// Even if a suspended tab's timer has not fired, the click itself checks the clock.
|
||||
assert.equal(state.ensureWebConsultationAllowed(), false)
|
||||
const laterPage = hook.useDoctorWebConsultation()
|
||||
assert.equal(laterPage.webConsultationBlocked.value, true)
|
||||
unmounted.forEach(fn => fn())
|
||||
assert.equal(listeners.size, 0)
|
||||
assert.equal(tick, undefined)
|
||||
})
|
||||
|
||||
test('the shared system notice keeps installer downloads available throughout all reminder phases', async () => {
|
||||
const { descriptor } = parse(read('components/doctor-web-consultation-notice/index.vue'))
|
||||
const script = compileScript(descriptor, { id: 'doctor-web-notice' })
|
||||
const template = compileTemplate({ source: descriptor.template.content, filename: 'notice.vue', id: 'doctor-web-notice', compilerOptions: { bindingMetadata: script.bindings } })
|
||||
assert.deepEqual(template.errors, [])
|
||||
const render = moduleFrom(template.code).render
|
||||
async function markup(date, packages = [installer], failed = false, loading = false) {
|
||||
const component = moduleFrom(script.content, name => {
|
||||
if (name === 'vue') return vue
|
||||
if (name === '@/hooks/useDoctorWebConsultation') return { useDoctorWebConsultation: () => ({ consultationReminder: vue.ref(policy.doctorWebConsultationReminder(schedule, Date.parse(date))), policyLoadFailed: vue.ref(false), refreshConsultationPolicy() {} }) }
|
||||
if (name === '@/hooks/useDesktopWorkstationDownloads') return {
|
||||
useDesktopWorkstationDownloads: () => ({ downloads: vue.ref({ version: '1.4.8', packages }), downloadsLoading: vue.ref(loading), downloadsFailed: vue.ref(failed), loadDownloads() {} })
|
||||
}
|
||||
if (name === '@element-plus/icons-vue') return { Download: { render: () => vue.h('svg') } }
|
||||
throw new Error(name)
|
||||
})
|
||||
const state = component.default.setup({}, { expose() {} })
|
||||
const app = vue.createSSRApp({ render: () => render({}, [], {}, vue.proxyRefs(state)) })
|
||||
app.component('el-alert', { props: ['title', 'type', 'closable'], setup: (props, { slots }) => () => vue.h('section', { role: 'alert', 'data-type': props.type, 'data-closable': String(props.closable) }, [vue.h('strong', props.title), slots.default?.()]) })
|
||||
app.component('el-icon', { setup: (_, { slots }) => () => vue.h('span', slots.default?.()) })
|
||||
app.component('el-button', { setup: (_, { slots }) => () => vue.h('button', slots.default?.()) })
|
||||
return renderToString(app)
|
||||
}
|
||||
const before = await markup('2026-10-20T10:00:00+08:00')
|
||||
assert.match(before, /2026年10月24日00:00(北京时间)/)
|
||||
assert.match(before, /接诊台、问诊列表/)
|
||||
assert.match(before, /data-closable="false"/)
|
||||
assert.match(before, /data-type="info"/)
|
||||
assert.match(before, /href="https:\/\/cdn.example.test\/doctor-setup.exe"/)
|
||||
assert.match(before, /下载 Windows 64位安装包/)
|
||||
assert.match(before, /当前版本 v1.4.8/)
|
||||
assert.match(before, /Windows 10 1809/)
|
||||
const approaching = await markup('2026-10-22T12:00:00+08:00')
|
||||
assert.match(approaching, /data-type="warning"/)
|
||||
assert.match(approaching, /距网页端面诊停用还有 1天12小时/)
|
||||
const lastDay = await markup('2026-10-23T23:59:59+08:00')
|
||||
assert.match(lastDay, /最后提醒/)
|
||||
assert.match(lastDay, /不足1分钟/)
|
||||
assert.match(lastDay, /data-type="error"/)
|
||||
const after = await markup('2026-10-24T00:00:00+08:00')
|
||||
assert.match(after, /网页端面诊已停用/)
|
||||
assert.match(after, /桌面应用/)
|
||||
assert.match(after, /data-type="error"/)
|
||||
assert.match(after, /href="https:\/\/cdn.example.test\/doctor-setup.exe"/)
|
||||
assert.doesNotMatch(after, /距网页端面诊停用还有/)
|
||||
const missing = await markup('2026-10-20T10:00:00+08:00', [])
|
||||
assert.match(missing, /安装包暂未发布/)
|
||||
assert.match(missing, /重新获取/)
|
||||
assert.doesNotMatch(missing, /href=/)
|
||||
assert.match(await markup('2026-10-20T10:00:00+08:00', [], true), /安装包加载失败/)
|
||||
assert.match(await markup('2026-10-20T10:00:00+08:00', [], false, true), /正在获取安装包/)
|
||||
})
|
||||
|
||||
test('reminders switch exactly at Beijing midnight on October 22, 23 and 24', () => {
|
||||
for (const [boundary, previous, current] of [
|
||||
['2026-10-22T00:00:00+08:00', 'prepare', 'approaching'],
|
||||
['2026-10-23T00:00:00+08:00', 'approaching', 'last_day'],
|
||||
['2026-10-24T00:00:00+08:00', 'last_day', 'expired']
|
||||
]) {
|
||||
const time = Date.parse(boundary)
|
||||
assert.equal(policy.doctorWebConsultationReminder(schedule, time - 1).phase, previous)
|
||||
assert.equal(policy.doctorWebConsultationReminder(schedule, time).phase, current)
|
||||
}
|
||||
assert.equal(policy.doctorWebConsultationReminder(schedule, Date.parse('2026-10-23T15:59:59Z')).phase, 'last_day')
|
||||
assert.equal(policy.doctorWebConsultationReminder(schedule, Date.parse('2026-10-23T16:00:00Z')).phase, 'expired')
|
||||
})
|
||||
|
||||
test('an open page advances through each reminder stage without refreshing or changing the cutoff', () => {
|
||||
let clock = Date.parse('2026-10-21T23:59:59+08:00')
|
||||
let tick
|
||||
const mounted = [], unmounted = []
|
||||
const surface = { addEventListener() {}, removeEventListener() {} }
|
||||
const hook = moduleFrom(read('hooks/useDoctorWebConsultation.ts'), name => {
|
||||
if (name === 'vue') return { ...vue, onMounted: fn => mounted.push(fn), onUnmounted: fn => unmounted.push(fn) }
|
||||
if (name === '@/stores/modules/user') return { default: () => ({ userInfo: { ...doctor, web_consultation_policy: schedule }, serverTimeOffsetMs: 0 }) }
|
||||
if (name === '@/api/app') return { getDoctorWebConsultationPolicy: () => new Promise(() => {}) }
|
||||
if (name === '@/utils/feedback') return { default: { msgWarning() {} } }
|
||||
if (name === '@/utils/doctor-web-consultation') return policy
|
||||
throw new Error(name)
|
||||
}, { Date: { now: () => clock }, window: surface, document: surface, setInterval: fn => { tick = fn; return 1 }, clearInterval() {} })
|
||||
const state = hook.useDoctorWebConsultation()
|
||||
mounted.forEach(fn => fn())
|
||||
assert.equal(state.consultationReminder.value.phase, 'prepare')
|
||||
for (const [day, phase] of [[22, 'approaching'], [23, 'last_day'], [24, 'expired']]) {
|
||||
clock = Date.parse(`2026-10-${day}T00:00:00+08:00`)
|
||||
tick()
|
||||
assert.equal(state.consultationReminder.value.phase, phase)
|
||||
assert.equal(state.webConsultationBlocked.value, day === 24)
|
||||
}
|
||||
unmounted.forEach(fn => fn())
|
||||
})
|
||||
|
||||
function shiftedSchedule(cutoffAt, serverTime, approachingHours = 48, urgentHours = 24) {
|
||||
const time = Date.parse(cutoffAt)
|
||||
return {
|
||||
cutoff_at: cutoffAt,
|
||||
approaching_at: new Date(time - approachingHours * 3600000).toISOString(),
|
||||
urgent_at: new Date(time - urgentHours * 3600000).toISOString(),
|
||||
server_time: serverTime / 1000
|
||||
}
|
||||
}
|
||||
|
||||
test('arbitrary configured dates and hours drive announcements, reminders and enforcement to the second', () => {
|
||||
const custom = shiftedSchedule('2027-06-15T14:35:12+08:00', cutoff, 10, 2)
|
||||
const end = Date.parse(custom.cutoff_at)
|
||||
const approaching = Date.parse(custom.approaching_at)
|
||||
const urgent = Date.parse(custom.urgent_at)
|
||||
assert.deepEqual(policy.normalizeDoctorWebConsultationPolicy(custom), custom)
|
||||
for (const [time, phase] of [[approaching - 1, 'prepare'], [approaching, 'approaching'], [urgent - 1, 'approaching'], [urgent, 'last_day'], [end - 1, 'last_day'], [end, 'expired']]) {
|
||||
const reminder = policy.doctorWebConsultationReminder(custom, time)
|
||||
assert.equal(reminder.phase, phase)
|
||||
assert.match(reminder.description, /2027年06月15日14:35:12(北京时间)/)
|
||||
assert.doesNotMatch(reminder.description, /2026年|今天结束|最后一天/)
|
||||
assert.equal(policy.isDoctorWebConsultationBlocked(doctor, custom, time), time >= end)
|
||||
}
|
||||
assert.equal(policy.doctorWebConsultationDate({ ...custom, cutoff_at: '2027-06-15T06:35:12Z' }), '2027年06月15日14:35:12(北京时间)')
|
||||
assert.equal(policy.isDoctorWebConsultationBlocked(doctor, undefined, end), false)
|
||||
assert.equal(policy.doctorWebConsultationReminder().countdown, '')
|
||||
for (const invalid of [null, {}, { ...custom, cutoff_at: 'invalid' }, { ...custom, approaching_at: '2027-06-16T00:00:00+08:00' }, { ...custom, server_time: 0 }, { ...custom, urgent_at: '2027-06-15 13:00:00' }]) {
|
||||
assert.equal(policy.normalizeDoctorWebConsultationPolicy(invalid), undefined)
|
||||
}
|
||||
})
|
||||
|
||||
test('open notices share live configuration, poll every minute and refresh on focus with failure recovery', async () => {
|
||||
let clock = Date.parse('2027-06-15T14:00:00+08:00')
|
||||
let requests = 0, resolveRequest, rejectRequest
|
||||
const mounted = [], unmounted = [], ticks = new Set(), listeners = new Map()
|
||||
const surface = {
|
||||
visibilityState: 'visible',
|
||||
addEventListener(name, callback) {
|
||||
if (!listeners.has(name)) listeners.set(name, new Set())
|
||||
listeners.get(name).add(callback)
|
||||
},
|
||||
removeEventListener(name, callback) { listeners.get(name)?.delete(callback) }
|
||||
}
|
||||
const store = vue.reactive({ userInfo: { ...doctor, web_consultation_policy: schedule }, serverTimeOffsetMs: 0 })
|
||||
const hook = moduleFrom(read('hooks/useDoctorWebConsultation.ts'), name => {
|
||||
if (name === 'vue') return { ...vue, onMounted: fn => mounted.push(fn), onUnmounted: fn => unmounted.push(fn) }
|
||||
if (name === '@/stores/modules/user') return { default: () => store }
|
||||
if (name === '@/api/app') return {
|
||||
getDoctorWebConsultationPolicy: () => {
|
||||
requests++
|
||||
return new Promise((resolve, reject) => { resolveRequest = resolve; rejectRequest = reject })
|
||||
}
|
||||
}
|
||||
if (name === '@/utils/feedback') return { default: { msgWarning() {} } }
|
||||
if (name === '@/utils/doctor-web-consultation') return policy
|
||||
throw new Error(name)
|
||||
}, {
|
||||
Date: { now: () => clock }, window: surface, document: surface,
|
||||
setInterval: fn => { ticks.add(fn); return fn }, clearInterval: fn => ticks.delete(fn)
|
||||
})
|
||||
const first = hook.useDoctorWebConsultation()
|
||||
const second = hook.useDoctorWebConsultation()
|
||||
assert.equal(first.webConsultationBlocked.value, true)
|
||||
mounted.forEach(fn => fn())
|
||||
assert.equal(requests, 1)
|
||||
const initial = first.refreshConsultationPolicy()
|
||||
assert.equal(second.refreshConsultationPolicy(), initial)
|
||||
resolveRequest(shiftedSchedule('2027-06-15T14:35:12+08:00', clock, 10, 2))
|
||||
await initial
|
||||
assert.equal(first.webConsultationBlocked.value, false)
|
||||
assert.equal(second.webConsultationBlocked.value, false)
|
||||
assert.match(first.consultationReminder.value.description, /2027年06月15日14:35:12/)
|
||||
clock += 59000
|
||||
ticks.forEach(fn => fn())
|
||||
assert.equal(requests, 1)
|
||||
clock += 1000
|
||||
ticks.forEach(fn => fn())
|
||||
assert.equal(requests, 2)
|
||||
const polled = first.refreshConsultationPolicy()
|
||||
resolveRequest(shiftedSchedule('2027-06-15T13:59:00+08:00', clock))
|
||||
await polled
|
||||
assert.equal(second.webConsultationBlocked.value, true)
|
||||
assert.match(second.webConsultationMessage.value, /2027年06月15日13:59/)
|
||||
|
||||
listeners.get('focus').forEach(fn => fn())
|
||||
assert.equal(requests, 3)
|
||||
const failed = first.refreshConsultationPolicy()
|
||||
rejectRequest(new Error('offline'))
|
||||
await failed
|
||||
assert.equal(first.policyLoadFailed.value, true)
|
||||
assert.equal(second.webConsultationBlocked.value, true)
|
||||
listeners.get('visibilitychange').forEach(fn => fn())
|
||||
assert.equal(requests, 4)
|
||||
const retry = second.refreshConsultationPolicy()
|
||||
resolveRequest(shiftedSchedule('2028-01-01T12:30:00+08:00', clock))
|
||||
await retry
|
||||
assert.equal(first.policyLoadFailed.value, false)
|
||||
assert.equal(second.webConsultationBlocked.value, false)
|
||||
assert.match(first.consultationReminder.value.description, /2028年01月01日12:30/)
|
||||
const invalid = first.refreshConsultationPolicy()
|
||||
resolveRequest({ cutoff_at: 'invalid' })
|
||||
await invalid
|
||||
assert.equal(first.policyLoadFailed.value, true)
|
||||
assert.match(first.consultationReminder.value.description, /2028年01月01日12:30/)
|
||||
unmounted.forEach(fn => fn())
|
||||
assert.equal(ticks.size, 0)
|
||||
assert.ok([...listeners.values()].every(callbacks => callbacks.size === 0))
|
||||
})
|
||||
|
||||
test('the runtime policy endpoint is public and requests a fresh response', async () => {
|
||||
let transport
|
||||
const api = moduleFrom(read('api/app.ts'), name => {
|
||||
if (name === '@/utils/request') return { default: { get: (...args) => { transport = args; return Promise.resolve(schedule) } } }
|
||||
throw new Error(name)
|
||||
})
|
||||
assert.deepEqual(await api.getDoctorWebConsultationPolicy(), schedule)
|
||||
assert.equal(transport[0].url, '/config/doctorWebConsultation')
|
||||
assert.ok(transport[0].params._t > 0)
|
||||
assert.equal(transport[1].withToken, false)
|
||||
})
|
||||
|
||||
test('installer requests are public, deduplicated across notices, cached, and recover after failure', async () => {
|
||||
let requests = 0, resolve
|
||||
const mounted = [], unmounted = []
|
||||
const api = { getDesktopWorkstationDownloads: () => { requests++; return new Promise(done => { resolve = done }) } }
|
||||
const mod = moduleFrom(read('hooks/useDesktopWorkstationDownloads.ts'), name => {
|
||||
if (name === 'vue') return { ...vue, onMounted: fn => mounted.push(fn), onUnmounted: fn => unmounted.push(fn) }
|
||||
if (name === '@/api/setting/desktop_workstation') return api
|
||||
throw new Error(name)
|
||||
}, { window: { addEventListener() {}, removeEventListener() {} } })
|
||||
const first = mod.useDesktopWorkstationDownloads()
|
||||
const second = mod.useDesktopWorkstationDownloads()
|
||||
const pending = first.loadDownloads()
|
||||
assert.equal(second.loadDownloads(), pending)
|
||||
assert.equal(requests, 1)
|
||||
resolve({ version: '1.4.8', packages: [installer] })
|
||||
await pending
|
||||
await second.loadDownloads()
|
||||
assert.equal(requests, 1)
|
||||
assert.equal(second.downloads.value.packages.length, 1)
|
||||
api.getDesktopWorkstationDownloads = async () => { throw new Error('offline') }
|
||||
await first.loadDownloads(true)
|
||||
assert.equal(first.downloadsFailed.value, true)
|
||||
assert.equal(first.downloads.value.packages.length, 1)
|
||||
api.getDesktopWorkstationDownloads = async () => ({ version: '1.4.9', packages: [installer] })
|
||||
await second.loadDownloads(true)
|
||||
assert.equal(first.downloadsFailed.value, false)
|
||||
assert.equal(first.downloads.value.version, '1.4.9')
|
||||
assert.deepEqual(mod.normalizeDesktopDownloads({ version: '1', packages: [null, { ...installer, url: 'javascript:alert(1)' }, { ...installer, url: 'https://user:pass@example.test/setup.exe' }, { ...installer, sha256: '' }] }).packages, [])
|
||||
assert.equal(mod.normalizeDesktopDownloads({ version: '1', packages: [installer, installer] }).packages.length, 1)
|
||||
unmounted.forEach(fn => fn())
|
||||
|
||||
let transport
|
||||
const apiModule = moduleFrom(read('api/setting/desktop_workstation.ts'), name => {
|
||||
if (name === '@/utils/request') return { default: { get: (...args) => { transport = args; return Promise.resolve({}) } } }
|
||||
throw new Error(name)
|
||||
})
|
||||
await apiModule.getDesktopWorkstationDownloads()
|
||||
assert.equal(transport[0].url, '/setting.desktop_workstation/downloads')
|
||||
assert.equal(transport[1].withToken, false)
|
||||
})
|
||||
|
||||
test('consultation entries retain the shared notice while the patient list compiles without it', () => {
|
||||
for (const name of ['views/patient/reception/index.vue', 'views/tcm/diagnosis/index.vue', 'views/tcm/appointment/list.vue', 'views/tcm/appointment/list_h5.vue']) {
|
||||
const { descriptor, errors } = parse(read(name), { filename: name })
|
||||
assert.deepEqual(errors, [])
|
||||
const script = compileScript(descriptor, { id: name })
|
||||
assert.equal(script.bindings.DoctorWebConsultationNotice, name === 'views/tcm/diagnosis/index.vue' ? undefined : 'setup-const')
|
||||
assert.deepEqual(compileTemplate({ source: descriptor.template.content, filename: name, id: name, compilerOptions: { bindingMetadata: script.bindings } }).errors, [])
|
||||
}
|
||||
})
|
||||
|
||||
test('reception makes doctor cutoff visible and blocks calls while preserving administrator and assistant access', async () => {
|
||||
const { descriptor } = parse(read('views/patient/reception/index.vue'))
|
||||
const script = compileScript(descriptor, { id: 'reception-cutoff' })
|
||||
const template = compileTemplate({ source: descriptor.template.content, filename: 'reception.vue', id: 'reception-cutoff', compilerOptions: { bindingMetadata: script.bindings } })
|
||||
assert.deepEqual(template.errors, [])
|
||||
const render = moduleFrom(template.code).render
|
||||
const passthrough = { setup: (_, { slots }) => () => vue.h('div', slots.default?.()) }
|
||||
const lifecycle = { ...vue, onMounted() {}, onUnmounted() {}, defineAsyncComponent: () => passthrough }
|
||||
let clock = cutoff - 1
|
||||
const store = vue.reactive({ userInfo: { ...doctor, web_consultation_policy: schedule }, serverTimeOffsetMs: 0 })
|
||||
const warnings = [], requests = [], opened = []
|
||||
const feedback = { msgWarning: message => warnings.push(message) }
|
||||
const hook = moduleFrom(read('hooks/useDoctorWebConsultation.ts'), name => {
|
||||
if (name === 'vue') return lifecycle
|
||||
if (name === '@/stores/modules/user') return { default: () => store }
|
||||
if (name === '@/api/app') return {}
|
||||
if (name === '@/utils/feedback') return { default: feedback }
|
||||
if (name === '@/utils/doctor-web-consultation') return policy
|
||||
throw new Error(name)
|
||||
}, { Date: { now: () => clock } })
|
||||
let onSignature = () => ({})
|
||||
const state = moduleFrom(script.content, name => {
|
||||
if (name === 'vue') return lifecycle
|
||||
if (name === '@/hooks/useDoctorWebConsultation') return hook
|
||||
if (name === '@/api/patient' || name === '@/api/doctor') return {}
|
||||
if (name === '@/api/tcm') return { getCallSignature: async params => { requests.push(params); return onSignature() } }
|
||||
if (name === '@/utils/feedback') return { default: feedback }
|
||||
if (name === '@/utils/diag-display') return { formatGender: () => '男' }
|
||||
if (name === '@/utils/diabetes-discovery-display') return {}
|
||||
if (name === '@element-plus/icons-vue') return Object.fromEntries(['Phone', 'Search', 'ChatDotRound', 'Loading'].map(key => [key, passthrough]))
|
||||
if (name.endsWith('.vue')) return { default: passthrough }
|
||||
throw new Error(name)
|
||||
}, { ref: vue.ref, computed: vue.computed, watch: vue.watch }).default.setup({}, { expose() {} })
|
||||
const row = { id: 90, patient_id: 50, source_patient_id: 50, diagnosis_id: 70, patient_name: '测试患者', appointment_type: 'video' }
|
||||
state.queue.value = [row]
|
||||
state.chatDialogRef.value = { open: value => opened.push(value) }
|
||||
async function markup() {
|
||||
const app = vue.createSSRApp({ render: () => render({}, [], {}, vue.proxyRefs(state)) })
|
||||
app.config.warnHandler = () => {}
|
||||
for (const name of ['el-input', 'el-icon', 'el-tag', 'el-empty', 'el-dialog', 'el-button']) app.component(name, passthrough)
|
||||
app.component('el-tooltip', { props: ['content'], setup: (props, { slots }) => () => vue.h('div', { 'data-tooltip': props.content }, slots.default?.()) })
|
||||
for (const name of ['loading', 'perms']) app.directive(name, { getSSRProps: () => ({}) })
|
||||
return renderToString(app)
|
||||
}
|
||||
|
||||
assert.match(await markup(), /class="row-icon-btn call" aria-label="发起通话"/)
|
||||
await state.handleCall(row)
|
||||
assert.equal(requests.length, 1)
|
||||
assert.equal(opened.length, 1)
|
||||
|
||||
// A signature that returns after the deadline must never open the calling window.
|
||||
onSignature = () => { clock = cutoff; return {} }
|
||||
await state.handleCall(row)
|
||||
assert.equal(requests.length, 2)
|
||||
assert.equal(opened.length, 1)
|
||||
const expired = await markup()
|
||||
assert.match(expired, /class="row-icon-btn call" disabled aria-label="[^"]*桌面应用/)
|
||||
assert.match(expired, /<span>已停用<\/span>/)
|
||||
assert.match(expired, /data-tooltip="[^"]*桌面应用/)
|
||||
assert.doesNotMatch(expired, /class="row-icon-btn notify" disabled/)
|
||||
await state.handleCall(row)
|
||||
assert.equal(requests.length, 2)
|
||||
assert.equal(opened.length, 1)
|
||||
assert.equal(warnings.length, 2)
|
||||
|
||||
for (const identity of [{ root: 1, role_ids: [1] }, { root: 0, role_ids: [2] }]) {
|
||||
Object.assign(store.userInfo, identity)
|
||||
assert.match(await markup(), /class="row-icon-btn call" aria-label="发起通话"/)
|
||||
assert.doesNotMatch(await markup(), /<span>已停用<\/span>/)
|
||||
await state.handleCall(row)
|
||||
}
|
||||
assert.equal(requests.length, 4)
|
||||
assert.equal(opened.length, 3)
|
||||
})
|
||||
@@ -1,47 +0,0 @@
|
||||
const assert = require('node:assert/strict')
|
||||
const fs = require('node:fs')
|
||||
const path = require('node:path')
|
||||
const test = require('node:test')
|
||||
const ts = require('typescript')
|
||||
const vue = require('vue')
|
||||
const { parse, compileScript, compileTemplate } = require('@vue/compiler-sfc')
|
||||
const 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')
|
||||
})
|
||||
@@ -1,64 +0,0 @@
|
||||
const assert = require('node:assert/strict')
|
||||
const fs = require('node:fs')
|
||||
const path = require('node:path')
|
||||
const test = require('node:test')
|
||||
const ts = require('typescript')
|
||||
const vue = require('vue')
|
||||
const { parse, compileScript, compileTemplate } = require('@vue/compiler-sfc')
|
||||
const dir = path.resolve(__dirname, '../src/views/tcm/diagnosis/components')
|
||||
const reviewFile = process.env.FOLLOWUP_INLINE_REVIEW_SOURCE || path.join(dir, 'FollowupAudioReview.vue')
|
||||
function execute(source, requireFn) {
|
||||
const out = ts.transpileModule(source,{compilerOptions:{target:ts.ScriptTarget.ES2022,module:ts.ModuleKind.CommonJS}}).outputText
|
||||
const module={exports:{}};new Function('require','module','exports',out)(requireFn,module,module.exports);return module.exports
|
||||
}
|
||||
const state=execute(fs.readFileSync(path.join(dir,'followupAudioState.ts'),'utf8'),require)
|
||||
const row=(id,extra={})=>({id,kind:'blood',values:{fasting_blood_sugar:6.2},record_date:'2026-10-12',record_time:'08:00',time_period:'早晨',time_estimated:true,time_text:'早晨',date_text:'今天',evidence:[{text:'六点二',channel:1,segment_id:'right-1',start_ms:0,end_ms:15000,position_type:'segment'}],needs_review:true,selected:false,target_id:null,current_values:{},expected_hash:'original',conflict:false,possible_duplicate:false,...extra})
|
||||
function setup(extra={}){
|
||||
const descriptor=parse(fs.readFileSync(reviewFile,'utf8'),{filename:reviewFile}).descriptor
|
||||
const compiled=compileScript(descriptor,{id:'inline-review'})
|
||||
const mod=execute(compiled.content,name=>name==='vue'?vue:name==='./followupAudioState'?state:{default:{}})
|
||||
const props=vue.reactive({items:[row('one'),row('two'),row('three')],fields:{blood:[{key:'fasting_blood_sugar',label:'空腹血糖',type:'number'}]},disabled:false,canDaily:true,applied:false,saveState:'saved',...extra})
|
||||
const events=[];const scope=vue.effectScope();const review=scope.run(()=>mod.default.setup(props,{expose(){},emit(event,...args){events.push([event,...args]);if(event==='update:items')props.items=args[0]}}))
|
||||
return {review,props,events,dispose:()=>scope.stop()}
|
||||
}
|
||||
test('inline editor has one permanently mounted player slot and no modal overlay',()=>{
|
||||
const source=fs.readFileSync(reviewFile,'utf8');assert.doesNotMatch(source,/<el-dialog/);assert.equal((source.match(/<slot name="player"/g)||[]).length,1)
|
||||
assert.match(source,/position: sticky/);assert.match(source,/aria-label="同页核对与回听"/)
|
||||
const descriptor=parse(source,{filename:reviewFile}).descriptor;const script=compileScript(descriptor,{id:'inline-compile'})
|
||||
const render=compileTemplate({source:descriptor.template.content,filename:reviewFile,id:'inline-compile',compilerOptions:{bindingMetadata:script.bindings}});assert.deepEqual(render.errors,[])
|
||||
})
|
||||
test('accept-next requires explicit verification, retains immutable evidence and opens next unselected item',async()=>{
|
||||
const f=setup({items:[row('one'),row('two',{selected:true,needs_review:false}),row('three')]});f.review.openReview('one')
|
||||
f.review.saveReview(true,true);assert.equal(f.props.items[0].selected,false);assert.equal(f.review.editor.value.id,'one')
|
||||
f.review.confirmReview(true);f.review.saveReview(true,true)
|
||||
assert.equal(f.props.items[0].selected,true);assert.equal(f.props.items[0].needs_review,false);assert.equal(f.review.editor.value.id,'three')
|
||||
assert.deepEqual(f.props.items[0].evidence,row('one').evidence);assert.ok(f.events.some(e=>e[0]==='saved-next'))
|
||||
await vue.nextTick();assert.equal(f.review.editor.value.id,'three');f.dispose()
|
||||
})
|
||||
test('pending-filter accept-next captures next id before accepted row leaves filter',()=>{
|
||||
const f=setup();f.review.group.value='pending';f.review.openReview('one');f.review.confirmReview(true);f.review.saveReview(true,true)
|
||||
assert.equal(f.review.editor.value.id,'two');assert.deepEqual(f.review.visibleItems.value.map(r=>r.id),['two','three']);f.dispose()
|
||||
})
|
||||
test('skip preserves patient values, does not claim review complete, and never writes or selects',()=>{
|
||||
const f=setup();f.review.openReview('one');f.review.skipAndNext();assert.equal(f.review.editor.value.id,'two');assert.equal(f.props.items[0].needs_review,true);assert.equal(f.props.items[0].selected,false)
|
||||
assert.deepEqual(f.props.items[0].values,{fasting_blood_sugar:6.2});assert.ok(f.events.every(e=>['update:items','saved-next'].includes(e[0])));f.dispose()
|
||||
})
|
||||
test('inline row switching or skipping never silently drops unsaved edits',()=>{
|
||||
const f=setup();f.review.openReview('one');f.review.setValue('fasting_blood_sugar',6.8);f.review.openReview('two');assert.equal(f.review.editor.value.id,'one');assert.match(f.review.editorNotice.value,/未保存/)
|
||||
f.review.skipAndNext();assert.equal(f.review.editor.value.id,'one');assert.equal(f.review.editor.value.values.fasting_blood_sugar,6.8);assert.equal(f.props.items[0].values.fasting_blood_sugar,6.2);f.dispose()
|
||||
})
|
||||
test('date change remains gated until saved and authoritative target refreshed',()=>{
|
||||
const f=setup();f.review.openReview('one');f.review.patchEditor({record_date:'2026-10-11'});f.review.confirmReview(true);f.review.saveReview(true,true);assert.equal(f.props.items[0].selected,false);assert.equal(f.review.editor.value.id,'one')
|
||||
f.review.saveReview(false);assert.equal(f.props.items[0].record_date,'2026-10-11');assert.equal(f.props.items[0].needs_review,true);assert.ok(f.events.some(e=>e[0]==='saved-next'));f.dispose()
|
||||
})
|
||||
test('last item completes without wrapping or applying, read-only cannot advance mutations',()=>{
|
||||
const f=setup({items:[row('one')]});f.review.openReview('one');f.review.confirmReview(true);f.review.saveReview(true,true);assert.equal(f.review.editor.value,null);assert.match(f.review.navigationNotice.value,/末项/);assert.equal(f.events.some(e=>e[0]==='apply'),false);f.dispose()
|
||||
const g=setup({disabled:true});g.review.openReview('one');g.review.skipAndNext();g.review.saveReview(true,true);assert.equal(g.events.length,0);g.dispose()
|
||||
})
|
||||
|
||||
test('reopening the same row or toggling its selection preserves unsaved editor data',()=>{
|
||||
const f=setup();f.review.openReview('one');f.review.setValue('fasting_blood_sugar',7.1)
|
||||
f.review.openReview('one');assert.equal(f.review.editor.value.values.fasting_blood_sugar,7.1)
|
||||
f.review.toggleSelection(f.props.items[0],true);assert.equal(f.review.editor.value.values.fasting_blood_sugar,7.1)
|
||||
assert.equal(f.props.items[0].values.fasting_blood_sugar,6.2);assert.equal(f.props.items[0].selected,false);f.dispose()
|
||||
})
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,253 +0,0 @@
|
||||
const assert = require('node:assert/strict')
|
||||
const fs = require('node:fs')
|
||||
const path = require('node:path')
|
||||
const test = require('node:test')
|
||||
const ts = require('typescript')
|
||||
const vue = require('vue')
|
||||
const { parse, compileScript, compileTemplate } = require('@vue/compiler-sfc')
|
||||
|
||||
const root = path.resolve(__dirname, '..')
|
||||
const apiPath = path.join(root, 'src/api/setting/prescription_ai_visibility.ts')
|
||||
const pagePath = path.join(root, 'src/views/setting/prescription_ai_visibility/index.vue')
|
||||
const { descriptor, errors } = parse(fs.readFileSync(pagePath, 'utf8'), { filename: pagePath })
|
||||
assert.deepEqual(errors, [])
|
||||
const script = compileScript(descriptor, { id: 'prescription-ai-visibility' })
|
||||
|
||||
function moduleFrom(source, dependencies) {
|
||||
const compiled = ts.transpileModule(source, {
|
||||
compilerOptions: {
|
||||
target: ts.ScriptTarget.ES2022,
|
||||
module: ts.ModuleKind.CommonJS,
|
||||
esModuleInterop: true
|
||||
}
|
||||
}).outputText
|
||||
const module = { exports: {} }
|
||||
new Function('require', 'module', 'exports', compiled)(dependencies, module, module.exports)
|
||||
return module.exports
|
||||
}
|
||||
|
||||
const makeApi = (request) =>
|
||||
moduleFrom(fs.readFileSync(apiPath, 'utf8'), (name) => {
|
||||
assert.equal(name, '@/utils/request')
|
||||
return request
|
||||
})
|
||||
|
||||
const tick = () => new Promise((resolve) => setImmediate(resolve))
|
||||
const deferred = () => {
|
||||
let resolve
|
||||
let reject
|
||||
const promise = new Promise((yes, no) => {
|
||||
resolve = yes
|
||||
reject = no
|
||||
})
|
||||
return { promise, resolve, reject }
|
||||
}
|
||||
|
||||
function makePage(overrides = {}) {
|
||||
const saved = []
|
||||
const messages = []
|
||||
const calls = []
|
||||
const api = {
|
||||
getPrescriptionAiCapabilities: async () => {
|
||||
calls.push('capabilities')
|
||||
return { agreement_visible: false, can_manage_visibility: true }
|
||||
},
|
||||
getPrescriptionAiVisibilityConfig: async () => {
|
||||
calls.push('config')
|
||||
return { role_ids: [2, 90], admin_ids: [3, 91] }
|
||||
},
|
||||
getPrescriptionAiVisibilityOptions: async () => {
|
||||
calls.push('options')
|
||||
return {
|
||||
roles: [{ id: 2, name: '医生' }],
|
||||
admins: [{ id: 3, name: '张医生', account: 'zhang.doctor' }]
|
||||
}
|
||||
},
|
||||
setPrescriptionAiVisibilityConfig: async (params) => {
|
||||
saved.push(params)
|
||||
return params
|
||||
},
|
||||
...overrides
|
||||
}
|
||||
const component = moduleFrom(script.content, (name) => {
|
||||
if (name === 'vue') return vue
|
||||
if (name === '@/api/setting/prescription_ai_visibility') return api
|
||||
if (name === '@/utils/feedback') {
|
||||
return { msgSuccess: (message) => messages.push(message) }
|
||||
}
|
||||
throw new Error(`Unexpected import: ${name}`)
|
||||
}).default
|
||||
const page = component.setup({}, { expose() {} })
|
||||
return { page, api, saved, messages, calls }
|
||||
}
|
||||
|
||||
test('API uses the dedicated routes and rejects malformed policy responses', async () => {
|
||||
const calls = []
|
||||
let response = { role_ids: [2], admin_ids: [3] }
|
||||
const api = makeApi({
|
||||
get: async (params) => {
|
||||
calls.push(['get', params])
|
||||
return response
|
||||
},
|
||||
post: async (params) => {
|
||||
calls.push(['post', params])
|
||||
return response
|
||||
}
|
||||
})
|
||||
const data = await api.getPrescriptionAiVisibilityConfig()
|
||||
data.role_ids.push(5)
|
||||
assert.deepEqual(response.role_ids, [2])
|
||||
await api.setPrescriptionAiVisibilityConfig({ role_ids: [], admin_ids: [] })
|
||||
await api.getPrescriptionAiVisibilityOptions()
|
||||
await api.getPrescriptionAiCapabilities()
|
||||
assert.deepEqual(calls, [
|
||||
['get', { url: '/tcm.prescriptionAi/getVisibilityConfig' }],
|
||||
[
|
||||
'post',
|
||||
{
|
||||
url: '/tcm.prescriptionAi/setVisibilityConfig',
|
||||
params: { role_ids: [], admin_ids: [] }
|
||||
}
|
||||
],
|
||||
['get', { url: '/tcm.prescriptionAi/visibilityOptions' }],
|
||||
['get', { url: '/tcm.prescriptionAi/capabilities' }]
|
||||
])
|
||||
for (response of [
|
||||
null,
|
||||
{},
|
||||
{ role_ids: [], admin_ids: ['3'] },
|
||||
{ role_ids: [-1], admin_ids: [] }
|
||||
]) {
|
||||
await assert.rejects(api.getPrescriptionAiVisibilityConfig(), /响应格式不正确/)
|
||||
await assert.rejects(
|
||||
api.setPrescriptionAiVisibilityConfig({ role_ids: [], admin_ids: [] }),
|
||||
/响应格式不正确/
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
test('initial loading is pending and cannot submit before the real policy is read', async () => {
|
||||
const pending = deferred()
|
||||
const { page, saved } = makePage({ getPrescriptionAiVisibilityConfig: () => pending.promise })
|
||||
assert.equal(page.loading.value, true)
|
||||
assert.equal(page.ready.value, false)
|
||||
assert.equal(page.hasLoaded.value, false)
|
||||
await page.handleSubmit()
|
||||
assert.deepEqual(saved, [])
|
||||
pending.reject(new Error('offline'))
|
||||
await tick()
|
||||
assert.equal(page.loading.value, false)
|
||||
assert.equal(page.ready.value, false)
|
||||
assert.match(page.loadError.value, /加载失败/)
|
||||
await page.handleSubmit()
|
||||
assert.deepEqual(saved, [])
|
||||
})
|
||||
|
||||
test('a failed reload cannot apply a partial policy or overwrite saved selections', async () => {
|
||||
const { page, api, saved } = makePage()
|
||||
await tick()
|
||||
api.getPrescriptionAiVisibilityConfig = async () => ({ role_ids: [], admin_ids: [] })
|
||||
api.getPrescriptionAiVisibilityOptions = async () => {
|
||||
throw new Error('options failed')
|
||||
}
|
||||
await page.loadConfig()
|
||||
assert.deepEqual(page.formData.role_ids, [2, 90])
|
||||
assert.deepEqual(page.formData.admin_ids, [3, 91])
|
||||
assert.equal(page.hasLoaded.value, true)
|
||||
assert.equal(page.ready.value, false)
|
||||
await page.handleSubmit()
|
||||
assert.deepEqual(saved, [])
|
||||
api.getPrescriptionAiVisibilityOptions = async () => ({ roles: [], admins: [] })
|
||||
await page.loadConfig()
|
||||
assert.equal(page.ready.value, true)
|
||||
assert.equal(page.loadError.value, '')
|
||||
assert.deepEqual(page.formData.role_ids, [])
|
||||
})
|
||||
|
||||
test('missing selected IDs stay visible and user labels support both name and account search', async () => {
|
||||
const { page, saved } = makePage()
|
||||
await tick()
|
||||
assert.equal(page.canManage.value, true)
|
||||
assert.equal(page.ready.value, true)
|
||||
assert.deepEqual(
|
||||
page.roleOptions.value.map((row) => row.id),
|
||||
[2, 90]
|
||||
)
|
||||
assert.match(page.roleOptions.value[1].name, /#90.*当前不在可选列表/)
|
||||
assert.deepEqual(
|
||||
page.adminOptions.value.map((row) => row.id),
|
||||
[3, 91]
|
||||
)
|
||||
assert.match(page.adminOptions.value[0].label, /张医生.*zhang\.doctor/)
|
||||
assert.match(page.adminOptions.value[1].label, /#91.*当前不在可选列表/)
|
||||
await page.handleSubmit()
|
||||
assert.deepEqual(saved, [{ role_ids: [2, 90], admin_ids: [3, 91] }])
|
||||
})
|
||||
|
||||
test('explicitly clearing both selectors saves the empty policy and applies normalized response', async () => {
|
||||
const { page, saved, messages, api } = makePage()
|
||||
await tick()
|
||||
page.formData.role_ids = []
|
||||
page.formData.admin_ids = []
|
||||
await page.handleSubmit()
|
||||
assert.deepEqual(saved, [{ role_ids: [], admin_ids: [] }])
|
||||
assert.equal(messages.length, 1)
|
||||
page.formData.role_ids = [90, 2, 90]
|
||||
api.setPrescriptionAiVisibilityConfig = async () => ({ role_ids: [2, 90], admin_ids: [] })
|
||||
await page.handleSubmit()
|
||||
assert.deepEqual(page.formData.role_ids, [2, 90])
|
||||
assert.equal(page.saving.value, false)
|
||||
})
|
||||
|
||||
test('pending save blocks duplicate writes and reload; failed write keeps the user selection', async () => {
|
||||
const pending = deferred()
|
||||
const saved = []
|
||||
const { page, calls } = makePage({
|
||||
setPrescriptionAiVisibilityConfig: (params) => {
|
||||
saved.push(params)
|
||||
return pending.promise
|
||||
}
|
||||
})
|
||||
await tick()
|
||||
page.formData.role_ids = [90]
|
||||
const first = page.handleSubmit()
|
||||
assert.equal(page.saving.value, true)
|
||||
await page.handleSubmit()
|
||||
await page.loadConfig()
|
||||
assert.equal(saved.length, 1)
|
||||
assert.equal(calls.filter((name) => name === 'capabilities').length, 1)
|
||||
pending.reject(new Error('offline'))
|
||||
await first
|
||||
assert.equal(page.saving.value, false)
|
||||
assert.equal(page.ready.value, true)
|
||||
assert.deepEqual(page.formData.role_ids, [90])
|
||||
assert.deepEqual(page.formData.admin_ids, [3, 91])
|
||||
assert.match(page.saveError.value, /当前选择已保留/)
|
||||
})
|
||||
|
||||
test('management capability is independent from viewing and denies policy reads when absent', async () => {
|
||||
const { page, calls, saved } = makePage({
|
||||
getPrescriptionAiCapabilities: async () => ({
|
||||
agreement_visible: true,
|
||||
can_manage_visibility: false
|
||||
})
|
||||
})
|
||||
await tick()
|
||||
assert.deepEqual(calls, [])
|
||||
assert.equal(page.canManage.value, false)
|
||||
assert.equal(page.hasLoaded.value, false)
|
||||
assert.equal(page.ready.value, false)
|
||||
assert.match(page.loadError.value, /无权管理/)
|
||||
await page.handleSubmit()
|
||||
assert.deepEqual(saved, [])
|
||||
})
|
||||
|
||||
test('actual settings template compiles with its script bindings', () => {
|
||||
const compiled = compileTemplate({
|
||||
source: descriptor.template.content,
|
||||
filename: pagePath,
|
||||
id: 'prescription-ai-visibility',
|
||||
compilerOptions: { bindingMetadata: script.bindings }
|
||||
})
|
||||
assert.deepEqual(compiled.errors, [])
|
||||
})
|
||||
@@ -1,167 +0,0 @@
|
||||
const assert = require('node:assert/strict')
|
||||
const fs = require('node:fs')
|
||||
const path = require('node:path')
|
||||
const test = require('node:test')
|
||||
const ts = require('typescript')
|
||||
const vue = require('vue')
|
||||
const { parse, compileScript, compileTemplate } = require('@vue/compiler-sfc')
|
||||
|
||||
const selected = [
|
||||
'patchUsageVisible', 'patchUsageSaving', 'patchUsageFormRef', 'patchUsageForm',
|
||||
'patchUsageRules', 'openPatchUsageDialog', 'resetPatchUsageForm', 'submitPatchUsage'
|
||||
]
|
||||
|
||||
for (const page of ['components/PrescriptionOrderDetailDrawer.vue', 'order_list_h5.vue']) {
|
||||
const filename = path.join(__dirname, '../src/views/consumer/prescription', page)
|
||||
const { descriptor, errors } = parse(fs.readFileSync(filename, 'utf8'), { filename })
|
||||
assert.deepEqual(errors, [])
|
||||
const script = compileScript(descriptor, { id: page })
|
||||
const template = compileTemplate({
|
||||
source: descriptor.template.content, filename, id: page,
|
||||
compilerOptions: { bindingMetadata: script.bindings }
|
||||
})
|
||||
assert.deepEqual(template.errors, [])
|
||||
|
||||
// Run the real handlers; replace the network and the rest of the order page.
|
||||
const ast = ts.createSourceFile(filename + '.ts', descriptor.scriptSetup.content, ts.ScriptTarget.Latest, true)
|
||||
const declarations = new Map()
|
||||
for (const node of ast.statements) {
|
||||
if (ts.isFunctionDeclaration(node) && node.name) declarations.set(node.name.text, node.getText(ast))
|
||||
if (ts.isVariableStatement(node)) {
|
||||
for (const declaration of node.declarationList.declarations) {
|
||||
declarations.set(declaration.name.getText(ast), `const ${declaration.getText(ast)}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
const executed = page.startsWith('components/') ? [...selected, 'refresh'] : selected
|
||||
for (const name of executed) assert.ok(declarations.has(name), `${page}: missing ${name}`)
|
||||
const compiled = ts.transpileModule(executed.map(name => declarations.get(name)).join('\n'), {
|
||||
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS }
|
||||
}).outputText
|
||||
|
||||
function instance({ hasAux = true, prescriptionType = '浓缩水丸', bagCount = 2, mainBagCount = 2, status = 2, fail = false } = {}) {
|
||||
const calls = []
|
||||
const events = []
|
||||
const aux = { times_per_day: 3, usage_days: 10, dosage_bag_count: bagCount }
|
||||
const detailPrescription = vue.ref({ prescription_type: prescriptionType, times_per_day: 3, usage_days: 10, dosage_bag_count: mainBagCount })
|
||||
const detailAuxUsage = vue.ref(hasAux ? aux : null)
|
||||
const detailData = vue.ref({
|
||||
id: 42, prescription_id: 17, medication_days: 10, fulfillment_status: status,
|
||||
gancao_reciperl_order_no: 'TEST-SUBMITTED', ej_pharmacy_order_no: 'TEST-EJ-SUBMITTED'
|
||||
})
|
||||
const refresh = async () => {
|
||||
if (calls[0]?.dosage_bag_count) detailPrescription.value.dosage_bag_count = calls[0].dosage_bag_count
|
||||
if (calls[0]?.aux_dosage_bag_count) detailAuxUsage.value.dosage_bag_count = calls[0].aux_dosage_bag_count
|
||||
events.push('refresh')
|
||||
return { ...detailData.value }
|
||||
}
|
||||
const globals = {
|
||||
ref: vue.ref, reactive: vue.reactive, computed: vue.computed, nextTick: vue.nextTick,
|
||||
detailPrescription, detailAuxUsage, detailData, detailHasAuxHerbs: vue.ref(hasAux),
|
||||
feedback: { msgWarning() {}, msgSuccess() {} },
|
||||
prescriptionOrderPatchPrescriptionUsage: async payload => {
|
||||
calls.push(payload)
|
||||
if (fail) throw new Error('Save failed')
|
||||
},
|
||||
requestDetail: refresh, refreshCurrentPrescriptionOrderDetail: refresh,
|
||||
props: { loadRelatedData: true },
|
||||
emit: event => events.push(event),
|
||||
fetchLogs: async () => {
|
||||
events.push('logs:start')
|
||||
await Promise.resolve()
|
||||
events.push('logs:done')
|
||||
},
|
||||
getLists: () => events.push('lists')
|
||||
}
|
||||
const state = new Function(...Object.keys(globals), `${compiled}\nreturn { ${selected.join(', ')} }`)(...Object.values(globals))
|
||||
state.patchUsageFormRef.value = { validate: async () => {}, clearValidate() {} }
|
||||
return { state, calls, events, detailAuxUsage, detailPrescription }
|
||||
}
|
||||
|
||||
test(`${page}: edits auxiliary bags and refreshes the persisted value without changing usage`, async () => {
|
||||
const { state, calls, events, detailAuxUsage } = instance()
|
||||
state.openPatchUsageDialog()
|
||||
assert.equal(state.patchUsageForm.aux_dosage_bag_count, 2)
|
||||
state.patchUsageForm.aux_dosage_bag_count = 4
|
||||
await state.submitPatchUsage()
|
||||
assert.deepEqual(calls, [{
|
||||
id: 42, times_per_day: 3, usage_days: 10, medication_days: 10,
|
||||
dosage_bag_count: 2,
|
||||
aux_times_per_day: 3, aux_usage_days: 10, aux_dosage_bag_count: 4
|
||||
}])
|
||||
assert.equal(state.patchUsageVisible.value, false)
|
||||
assert.equal(detailAuxUsage.value.dosage_bag_count, 4)
|
||||
assert.ok(events.includes('refresh'))
|
||||
assert.ok(events.indexOf('logs:done') > events.indexOf('refresh'))
|
||||
const completedEvent = page.startsWith('components/') ? 'detail-changed' : 'lists'
|
||||
assert.ok(events.indexOf(completedEvent) > events.indexOf('logs:done'))
|
||||
state.openPatchUsageDialog()
|
||||
assert.equal(state.patchUsageForm.aux_dosage_bag_count, 4)
|
||||
})
|
||||
|
||||
test(`${page}: missing historical bag count defaults to one and resets on close`, () => {
|
||||
const { state } = instance({ bagCount: null, mainBagCount: null })
|
||||
state.openPatchUsageDialog()
|
||||
assert.equal(state.patchUsageForm.aux_dosage_bag_count, 1)
|
||||
assert.equal(state.patchUsageForm.dosage_bag_count, 1)
|
||||
state.patchUsageForm.dosage_bag_count = 4
|
||||
state.patchUsageForm.aux_dosage_bag_count = 5
|
||||
state.resetPatchUsageForm()
|
||||
assert.equal(state.patchUsageForm.aux_dosage_bag_count, 1)
|
||||
assert.equal(state.patchUsageForm.dosage_bag_count, 1)
|
||||
})
|
||||
|
||||
test(`${page}: only water pills with an auxiliary formula submit or require auxiliary bags`, async () => {
|
||||
for (const options of [{ hasAux: false }, { prescriptionType: '饮片' }, { prescriptionType: '颗粒' }]) {
|
||||
const { state, calls } = instance(options)
|
||||
state.openPatchUsageDialog()
|
||||
state.patchUsageForm.aux_dosage_bag_count = 5
|
||||
assert.equal(state.patchUsageRules.value.aux_dosage_bag_count, undefined)
|
||||
await state.submitPatchUsage()
|
||||
assert.ok(!Object.hasOwn(calls[0], 'aux_dosage_bag_count'))
|
||||
assert.equal(Object.hasOwn(calls[0], 'dosage_bag_count'), !options.prescriptionType)
|
||||
}
|
||||
const { state } = instance()
|
||||
assert.equal(state.patchUsageRules.value.aux_dosage_bag_count[0].required, true)
|
||||
assert.equal(state.patchUsageRules.value.dosage_bag_count[0].required, true)
|
||||
})
|
||||
|
||||
test(`${page}: main and auxiliary bags can be edited independently in every submitted order status`, async () => {
|
||||
for (let status = 1; status <= 12; status++) {
|
||||
const { state, calls, detailPrescription, detailAuxUsage } = instance({ status })
|
||||
state.openPatchUsageDialog()
|
||||
assert.equal(state.patchUsageForm.dosage_bag_count, 2)
|
||||
state.patchUsageForm.dosage_bag_count = 5
|
||||
state.patchUsageForm.aux_dosage_bag_count = 1
|
||||
await state.submitPatchUsage()
|
||||
assert.equal(calls.length, 1, `status ${status}`)
|
||||
assert.equal(calls[0].dosage_bag_count, 5)
|
||||
assert.equal(calls[0].aux_dosage_bag_count, 1)
|
||||
assert.equal(detailPrescription.value.dosage_bag_count, 5)
|
||||
assert.equal(detailAuxUsage.value.dosage_bag_count, 1)
|
||||
}
|
||||
const { state, calls } = instance({ hasAux: false })
|
||||
state.openPatchUsageDialog()
|
||||
state.patchUsageForm.dosage_bag_count = 4
|
||||
await state.submitPatchUsage()
|
||||
assert.equal(calls[0].dosage_bag_count, 4)
|
||||
assert.ok(!Object.hasOwn(calls[0], 'aux_dosage_bag_count'))
|
||||
})
|
||||
|
||||
test(`${page}: validation blocks requests and a rejected save retains the selected bags`, async () => {
|
||||
const { state, calls, events } = instance({ fail: true })
|
||||
state.openPatchUsageDialog()
|
||||
state.patchUsageForm.aux_dosage_bag_count = 3
|
||||
state.patchUsageForm.dosage_bag_count = 4
|
||||
state.patchUsageFormRef.value.validate = async () => { throw new Error('Required') }
|
||||
await state.submitPatchUsage()
|
||||
assert.equal(calls.length, 0)
|
||||
state.patchUsageFormRef.value.validate = async () => {}
|
||||
await state.submitPatchUsage()
|
||||
assert.equal(state.patchUsageForm.aux_dosage_bag_count, 3)
|
||||
assert.equal(state.patchUsageForm.dosage_bag_count, 4)
|
||||
assert.equal(state.patchUsageVisible.value, true)
|
||||
assert.equal(state.patchUsageSaving.value, false)
|
||||
assert.deepEqual(events, [])
|
||||
})
|
||||
}
|
||||
@@ -1,156 +0,0 @@
|
||||
const assert = require('node:assert/strict')
|
||||
const fs = require('node:fs')
|
||||
const path = require('node:path')
|
||||
const test = require('node:test')
|
||||
const ts = require('typescript')
|
||||
const vue = require('vue')
|
||||
const { parse, compileScript, compileTemplate } = require('@vue/compiler-sfc')
|
||||
|
||||
const handlers = [
|
||||
'isDualAuditPassed', 'canQuickTrackRow', 'canShipRow', 'openQuickTrack',
|
||||
'submitQuickTrack', 'openShip', 'openEdit', 'submitEdit', 'resetEditOrderDialog'
|
||||
]
|
||||
const stateNames = [
|
||||
'quickTrackVisible', 'quickTrackSaving', 'quickTrackRowId', 'quickTrackForm',
|
||||
'shipVisible', 'shipRowId', 'shipForm', 'editVisible', 'editDialogLoading',
|
||||
'editSaving', 'editOrderStep', 'editOrderPrescription',
|
||||
'editFormRef', 'editForm', 'editDepositMin'
|
||||
]
|
||||
|
||||
for (const page of ['order_list.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 ast = ts.createSourceFile(filename + '.ts', descriptor.scriptSetup.content, ts.ScriptTarget.Latest, true)
|
||||
// Execute the actual order handlers with only network and unrelated UI dependencies stubbed.
|
||||
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 selected = [...handlers, ...stateNames]
|
||||
for (const name of selected) assert.ok(declarations.has(name), `${page}: missing ${name}`)
|
||||
const compiled = ts.transpileModule(selected.map(name => declarations.get(name)).join('\n'), {
|
||||
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS }
|
||||
}).outputText
|
||||
|
||||
function instance(detail = {}, saveTracking = async () => {}) {
|
||||
const warnings = []
|
||||
const errors = []
|
||||
const edits = []
|
||||
const tracks = []
|
||||
const globals = {
|
||||
ref: vue.ref, reactive: vue.reactive, nextTick: vue.nextTick,
|
||||
feedback: { msgWarning: message => warnings.push(message), msgError: message => errors.push(message), msgSuccess() {} },
|
||||
prescriptionOrderDetail: async () => ({ data: detail }),
|
||||
prescriptionOrderEdit: async payload => edits.push(payload),
|
||||
prescriptionOrderDdcode: async payload => { tracks.push(payload); await saveTracking(payload) },
|
||||
canEditRow: () => true,
|
||||
parseServicePackageValues: () => [],
|
||||
loadEditPaidOrders: async () => {},
|
||||
resolveShipModeForRow: row => row.ship_mode || 'gancao',
|
||||
editGancaoLogisticsOnlyMode: vue.ref(false),
|
||||
editGancaoDisplayNo: vue.ref(''),
|
||||
detailDrawerRef: vue.ref(null),
|
||||
detailVisible: vue.ref(false),
|
||||
getLists() {}
|
||||
}
|
||||
const state = new Function(...Object.keys(globals), `${compiled}\nreturn { ${selected.join(', ')} }`)(...Object.values(globals))
|
||||
state.editFormRef.value = { validate: async () => {}, clearValidate() {} }
|
||||
return { state, warnings, errors, edits, tracks }
|
||||
}
|
||||
|
||||
test(`${page}: only two approved audits unlock tracking, including legacy string statuses`, () => {
|
||||
const { state } = instance()
|
||||
for (const rx of [undefined, null, 0, 1, 2, '0', '1', '2']) {
|
||||
for (const pay of [undefined, null, 0, 1, 2, '0', '1', '2']) {
|
||||
const row = { prescription_audit_status: rx, payment_slip_audit_status: pay, fulfillment_status: 2 }
|
||||
const allowed = [1, '1'].includes(rx) && [1, '1'].includes(pay)
|
||||
assert.equal(state.canQuickTrackRow(row), allowed, `tracking: ${rx}/${pay}`)
|
||||
assert.equal(state.canShipRow(row), allowed, `shipping: ${rx}/${pay}`)
|
||||
}
|
||||
}
|
||||
for (const status of [1, 3, 4, 5, 6, 9]) {
|
||||
assert.equal(state.canShipRow({ prescription_audit_status: 1, payment_slip_audit_status: 1, fulfillment_status: status }), false)
|
||||
}
|
||||
})
|
||||
|
||||
test(`${page}: direct handler calls cannot open tracking or shipping before both approvals`, () => {
|
||||
for (const [rx, pay] of [[0, 0], [1, 0], [0, 1], [2, 1], [1, 2]]) {
|
||||
const { state, warnings } = instance()
|
||||
const row = { id: 42, prescription_audit_status: rx, payment_slip_audit_status: pay, fulfillment_status: 2 }
|
||||
state.openQuickTrack(row)
|
||||
state.openShip(row)
|
||||
assert.equal(state.quickTrackVisible.value, false)
|
||||
assert.equal(state.shipVisible.value, false)
|
||||
assert.equal(state.quickTrackRowId.value, 0)
|
||||
assert.equal(state.shipRowId.value, 0)
|
||||
assert.equal(warnings.length, 2)
|
||||
}
|
||||
})
|
||||
|
||||
test(`${page}: approved orders can fill or replace the number and preserve the carrier`, async () => {
|
||||
for (const oldNumber of ['', 'SF-OLD']) {
|
||||
const { state, tracks } = instance()
|
||||
const row = { id: 42, prescription_audit_status: 1, payment_slip_audit_status: 1, fulfillment_status: 2, express_company: 'sf', tracking_number: oldNumber }
|
||||
state.openQuickTrack(row)
|
||||
assert.equal(state.quickTrackVisible.value, true)
|
||||
assert.equal(state.quickTrackForm.tracking_number, oldNumber)
|
||||
state.quickTrackForm.tracking_number = ' SF-NEW '
|
||||
await state.submitQuickTrack()
|
||||
assert.deepEqual(tracks, [{ id: 42, express_company: 'sf', tracking_number: 'SF-NEW' }])
|
||||
assert.equal(state.quickTrackVisible.value, false)
|
||||
state.openShip(row)
|
||||
assert.equal(state.shipVisible.value, true)
|
||||
}
|
||||
})
|
||||
|
||||
test(`${page}: a server rejection after audit revocation retains the dialog and entered number`, async () => {
|
||||
const { state } = instance({}, async () => { throw new Error('audit revoked') })
|
||||
state.openQuickTrack({ id: 42, prescription_audit_status: 1, payment_slip_audit_status: 1 })
|
||||
state.quickTrackForm.tracking_number = 'SF-NEW'
|
||||
await state.submitQuickTrack()
|
||||
assert.equal(state.quickTrackVisible.value, true)
|
||||
assert.equal(state.quickTrackSaving.value, false)
|
||||
assert.equal(state.quickTrackForm.tracking_number, 'SF-NEW')
|
||||
})
|
||||
|
||||
test(`${page}: editing preserves the existing number while saving other fields before approval`, async () => {
|
||||
const { state, edits, errors } = instance({ id: 42, prescription_audit_status: 1, payment_slip_audit_status: 0, tracking_number: 'SF-EXISTING' })
|
||||
await state.openEdit({ id: 42, prescription_audit_status: 1, payment_slip_audit_status: 1 })
|
||||
assert.deepEqual(errors, [])
|
||||
assert.equal(state.editForm.tracking_number, 'SF-EXISTING')
|
||||
state.editForm.tracking_number = 'FORGED'
|
||||
state.editForm.recipient_name = '修改后的收货人'
|
||||
state.editOrderStep.value = 2
|
||||
await state.submitEdit()
|
||||
assert.equal(edits.length, 1)
|
||||
assert.equal(edits[0].recipient_name, '修改后的收货人')
|
||||
assert.equal(Object.hasOwn(edits[0], 'tracking_number'), false)
|
||||
})
|
||||
|
||||
test(`${page}: ordinary editing cannot change tracking while resetting an approved payment audit`, async () => {
|
||||
const { state, edits, errors } = instance({ id: 42, prescription_audit_status: '1', payment_slip_audit_status: '1' })
|
||||
await state.openEdit({ id: 42 })
|
||||
assert.deepEqual(errors, [])
|
||||
state.editForm.tracking_number = 'SF-NEW'
|
||||
state.editOrderStep.value = 2
|
||||
await state.submitEdit()
|
||||
assert.equal(edits.length, 1)
|
||||
assert.equal(Object.hasOwn(edits[0], 'tracking_number'), false)
|
||||
})
|
||||
|
||||
test(`${page}: template compiles with tracking controls bound to audit restrictions`, () => {
|
||||
const template = compileTemplate({ source: descriptor.template.content, filename, id: page, compilerOptions: { bindingMetadata: script.bindings } })
|
||||
assert.deepEqual(template.errors, [])
|
||||
const inputs = [...descriptor.template.content.matchAll(/<el-input\b[^>]*v-model="editForm\.tracking_number"[^>]*>/g)]
|
||||
assert.equal(inputs.length, page === 'order_list.vue' ? 2 : 1)
|
||||
for (const [input] of inputs) assert.match(input, /\sdisabled(?:\s|\/?>)/)
|
||||
assert.match(descriptor.template.content, /v-if="canQuickTrackRow\(row\)"/)
|
||||
})
|
||||
}
|
||||
@@ -46,8 +46,6 @@ export default defineConfig(({ mode }) => {
|
||||
|
||||
return {
|
||||
base: '/admin/',
|
||||
// 临时 UI 预览可能共用 node_modules;主开发服务独立缓存,避免预构建互相覆盖。
|
||||
cacheDir: path.resolve(__dirname, 'node_modules/.vite-admin'),
|
||||
server: {
|
||||
port: 5555,
|
||||
host: '0.0.0.0',
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
.env
|
||||
.local-workstation/
|
||||
.venv/
|
||||
.venv-build/
|
||||
.venv-win7-check/
|
||||
|
||||
+1
-9
@@ -8,7 +8,7 @@
|
||||
|
||||
Windows 直接在项目根目录双击:
|
||||
|
||||
- `一键运行_医生工作站.bat`:在源码目录且 `.venv` 可用时运行最新源码;否则运行现有成品;没有成品时使用 `uv` 准备源码环境并运行。
|
||||
- `一键运行_医生工作站.bat`:优先启动现有成品;没有成品时自动使用 `uv` 准备源码环境并运行。
|
||||
- `一键打包_医生工作站.bat`:自动同步锁定的 Python/Node 依赖,检查冻结 QtWebEngine/QtMultimedia 文件,执行应用与媒体离屏冒烟验证,最后生成 `dist/DoctorWorkstation-Setup-Windows-x64-<版本>.exe` 安装包、便携 ZIP 和 SHA-256 文件。首次使用会自动下载固定版本的 Inno Setup,并校验下载文件的 SHA-256 与数字签名。
|
||||
|
||||
英文稳定别名分别是 `Run_DoctorWorkstation.bat` 和 `Build_DoctorWorkstation.bat`。分发 ZIP 解压后,可直接双击其中的 `Start_DoctorWorkstation.bat`。
|
||||
@@ -35,14 +35,6 @@ Windows 打包机需预先安装 `uv` 与 Node.js 20+;脚本会自动处理项
|
||||
- 腾讯视频:沿用现有项目的 `@trtc/calls-uikit-vue` 主链;UserSig 只从后端短时获取,客户端不包含 SDKSecretKey。当前仅支持隔离的 QtWebEngine 内嵌模式。
|
||||
- PyInstaller Windows/macOS 构建脚本、macOS 摄像头/麦克风权限配置与自动化测试。
|
||||
|
||||
## 本地后端联调
|
||||
|
||||
本机 phpStudy 站点准备好后,双击 `Run_DoctorWorkstation_Local.bat`,使用当前源码连接 `https://css.zhenyangtang.com.cn`。此入口要求域名解析到本机,启用 TLS 校验,复用本机站点的公开证书;偏好、日志和登录凭据使用独立目录及凭据命名空间。正式启动入口及正式服务器配置保持原样。本地入口首次启动需要重新登录,不会借用正式环境的会话。
|
||||
|
||||
本地入口固定使用指定的本机地址和证书校验,会修正旧偏好中的线上地址,并隔离登录页保存的设置;登录时不能切换到其他服务器。普通的“一键运行”入口仍连接正式服务器,不能用来验证尚未部署的本地后端修改。
|
||||
|
||||
仅检查配置可执行 `Run_DoctorWorkstation_Local.bat --check`。其他本机 HTTPS 站点可通过 `DOCTOR_LOCAL_API_URL` 和 `DOCTOR_LOCAL_CA_FILE` 指定域名与公开证书路径,禁止传入私钥。配置保存在已忽略的 `.local-workstation/` 中;本地后端仍使用 `server/.env` 的现有配置。
|
||||
|
||||
## 手动运行
|
||||
|
||||
先安装 [uv](https://docs.astral.sh/uv/),然后在项目根目录执行:
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
@echo off
|
||||
setlocal EnableExtensions DisableDelayedExpansion
|
||||
set "LOCAL_APP_ROOT=%~dp0"
|
||||
if not exist "%LOCAL_APP_ROOT%.venv\Scripts\python.exe" (
|
||||
echo Local Python environment is missing. Prepare the source environment first.
|
||||
exit /b 1
|
||||
)
|
||||
"%LOCAL_APP_ROOT%.venv\Scripts\python.exe" "%LOCAL_APP_ROOT%scripts\run_local_workstation.py" %*
|
||||
set "LOCAL_RESULT=%ERRORLEVEL%"
|
||||
endlocal & exit /b %LOCAL_RESULT%
|
||||
@@ -1,26 +0,0 @@
|
||||
# 已开处方 → AI 界面改造
|
||||
|
||||
## 功能分析
|
||||
|
||||
这是基于已保存资料快照的双模型分析与医生复核工作台。主流程是确认患者和批次、查看模型完成情况、对照原方差异、核查资料缺口、记录所选模型的复核意见。
|
||||
|
||||
保留六个入口:对比总览、完整报告、候选与逐味、资料与缺口、处理进度、历史与趋势。历史批次切换、刷新、重新分析、单模型重试、独立复核草稿及保存继续使用现有服务和权限逻辑。医生原方及支持报告仍可访问。
|
||||
|
||||
## 设计决定
|
||||
|
||||
- 主程序 `shell.py` 将 prescriptions 等业务页列为科技蓝页面。因此继续复用 `reception_style.TECH_BLUE`:主色 #1769E8,背景 #F3F7FD,白色面板,分割线 #DBE5F2。没有采用主程序其他页面的靛蓝令牌,也没有修改全局主题。
|
||||
- 深蓝渐变横幅改为白色标题工具栏。批次状态放在顶行,患者及原方信息单独成行,当前导航用浅蓝背景与蓝色底线标识。
|
||||
- 缩小一致度圆环和数字,保留共同药味、候选药味与药味重合的计算依据;修复指标区样式误把分隔线应用到每个子标签的问题。
|
||||
- 总览由三栏改成剂量差异主区与固定复核侧栏。三方交集和附件覆盖改为可展开的摘要,减少初始屏幕空白和对主图的挤压。
|
||||
- 复核模型和复核状态并排显示,意见输入和保存按钮放在一起。顶部保存动作显示当前模型名,切换时同步更新。
|
||||
- 短窗口收起次要信息,保留剂量主图和复核输入;展开图表时剂量滚动区域可让出高度。列表内容保持最小高度,避免刷新后条目重叠。
|
||||
- 保留未知值与零值区分、不可比/历史状态处理、模型各自失败重试以及现有一致度说明。
|
||||
|
||||
## 验证
|
||||
|
||||
- 处方 AI 五组回归测试覆盖数据处理、权限、异步读取、逐味比较、页面、模型复核与布局。
|
||||
- 新增八种窗口/展开状态组合的控件边界检查,以及展开/收起不改变比较数据和复核清单的检查。
|
||||
- 离线模拟数据预览覆盖 1440×940、1280×860、1024×700、940×640,各内容页面、展开图表、运行中、失败、历史及统计窗口。
|
||||
- 预览输出:`app/artifacts/issued_prescription_redesign/`。模拟数据仅供 UI 验证,不对应真实患者。
|
||||
|
||||
本次改动在现有未提交工作区基础上完成,仅调整桌面呈现与相关回归检查;没有重新打包或发布桌面安装程序。
|
||||
@@ -1,284 +0,0 @@
|
||||
"""Render the prescription comparison window with synthetic, offline data."""
|
||||
|
||||
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 doctor_workstation.ui.dialogs import issued_prescription_ai as ai
|
||||
from doctor_workstation.ui.theme import apply_theme
|
||||
|
||||
|
||||
def example_batch() -> dict[str, Any]:
|
||||
"""Three prescriptions that actually differ, so every state of the page has something to draw."""
|
||||
|
||||
doctor = {"生地黄": 16, "天花粉": 15, "干石斛": 20, "醋五味子": 6,
|
||||
"生麦冬": 12, "茯苓": 10, "红参片": 6, "生牡丹皮": 10}
|
||||
candidates = {
|
||||
"qwen": {"生地黄": 15, "干石斛": 12, "醋五味子": 6, "生麦冬": 12, "茯苓": 15, "麸炒白术": 12, "丹参": 15},
|
||||
"openai": {"生地黄": 12, "醋五味子": 6, "生麦冬": 10, "茯苓": 12, "生白芍": 5, "炒酸枣仁": 6},
|
||||
}
|
||||
reports = {
|
||||
"qwen": {"summary": "界面演示数据:对照药味组成、剂量及用法,辅助医生逐项复核。",
|
||||
"diagnosis": "消渴病,气阴两虚兼血热。兼证需结合舌脉资料核实。",
|
||||
"analysis": "阅读药方对比页,查看同名药材的剂量差异、仅医生方药味与仅候选方药味。",
|
||||
"risk_assessment": [{"level": "high", "label": "血压数据缺失,影响补气药安全性评估"},
|
||||
{"level": "medium", "label": "肝肾功能具体指标未提供"}],
|
||||
"missing_information": ["甲状腺功能及眼底检查报告缺失", "舌象与脉诊仅有附件,无文本记录"]},
|
||||
"openai": {"summary": "界面演示数据:两份候选方独立生成,引用编号可回查原始资料。",
|
||||
"diagnosis": "已记录气阴两虚证;辨证依据需补充。",
|
||||
"analysis": "候选方以益气养阴为主,安神药味为本模型新增,需要医师确认。",
|
||||
"risk_assessment": [{"level": "high", "label": "缺少当前用药记录,无法排除配伍风险"}],
|
||||
"missing_information": ["舌象与脉诊仅有附件,无文本记录", "近期体重变化及 BMI 数据缺失"]},
|
||||
}
|
||||
models = {}
|
||||
for key, doses in candidates.items():
|
||||
herbs, rows = [], []
|
||||
for name in sorted(set(doctor) | set(doses), key=lambda item: (item not in doses, item)):
|
||||
common = {"name": name, "unit": "g", "dose_basis": "per_dose", "formula_type": "主方"}
|
||||
left, right = doctor.get(name), doses.get(name)
|
||||
if right is not None:
|
||||
herbs.append({**common, "dosage": right})
|
||||
rows.append({
|
||||
**common, "key": name,
|
||||
"doctor": {**common, "dosage": left} if left is not None else None,
|
||||
"candidate": {**common, "dosage": right, "source_rows": [len(herbs) - 1]} if right is not None else None,
|
||||
"doctor_dosage": left, "candidate_dosage": right,
|
||||
"match_type": "candidate_only" if left is None else "doctor_only" if right is None else "matched",
|
||||
"contribution": min(left, right) / max(left, right) if left and right else None,
|
||||
})
|
||||
matched = sum(row["match_type"] == "matched" for row in rows)
|
||||
denominator = len(doctor) + len(herbs)
|
||||
models[key] = {
|
||||
"status": "success", "report_id": 10 if key == "qwen" else 11,
|
||||
"candidate": {"status": "available_for_review", "prescription_name": "候选药方 · 界面示例",
|
||||
"herbs": herbs, "dose_basis": "per_dose", "prescription_type": "浓缩水丸",
|
||||
"usage_instruction": "服法由医生复核后确认。", "usage_days": 7, "times_per_day": 2,
|
||||
"rationale": "这是用于检查界面排版的模拟药方,不对应真实患者。",
|
||||
"risk_warnings": ["药味与剂量差异需要逐项复核。"]},
|
||||
"comparison": {"status": "comparable",
|
||||
"score": 200 * sum(row["contribution"] or 0 for row in rows) / denominator,
|
||||
"herb_score": 200 * matched / denominator, "matched_count": matched,
|
||||
"doctor_count": len(doctor), "candidate_count": len(herbs), "rows": rows,
|
||||
"reason": "药味与剂量可比;服法与疗程需单独复核。", "usage_differences": []},
|
||||
"report": reports[key],
|
||||
"coverage": {"status": "incomplete", "complete": False,
|
||||
"files": [{"file_id": f"a{index:04d}", "type": "image" if index % 3 else "document",
|
||||
"status": "processed", "transmitted": True, "version_verified": True}
|
||||
for index in range(20 if key == "qwen" else 17)]
|
||||
+ [{"file_id": f"z{index:04d}", "type": "document", "status": "restricted",
|
||||
"transmitted": False, "version_verified": False,
|
||||
"reason": "FILE_UNAVAILABLE_OR_UNSUPPORTED"} for index in range(2)]},
|
||||
"progress": {"stage_label": "处理完成", "elapsed_seconds": 135 if key == "qwen" else 591,
|
||||
"attempt": 1},
|
||||
"usage": {"total_calls": 3, "calls": [
|
||||
{"stage": "text:0", "ok": True, "latency_ms": 3120, "file_count": 0,
|
||||
"usage": {"completion_tokens": 980}, "error_code": ""},
|
||||
{"stage": "files:0", "ok": True, "latency_ms": 22400,
|
||||
"file_count": 20 if key == "qwen" else 17,
|
||||
"usage": {"completion_tokens": 2140}, "error_code": ""},
|
||||
{"stage": "final", "ok": True, "latency_ms": 18800, "file_count": 0,
|
||||
"usage": {"completion_tokens": 5617}, "error_code": ""}]},
|
||||
"review": {"status": "viewed", "comment": ""},
|
||||
"algorithm_version": "prescription-soft-dice-v1.1.0",
|
||||
"prompt_version": "manual-prescription-required-candidate-v4",
|
||||
}
|
||||
return {"id": 40, "prescription_id": 7556, "patient_id": 1391, "diagnosis_id": 1391, "agreement_visible": True,
|
||||
"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",
|
||||
"source_summary": {"diagnoses_count": 2, "attachment_count": 22, "video_calls_count": 4,
|
||||
"chat_messages_count": 137, "source_record_count": 31},
|
||||
"doctor_snapshot": {"patient": {"name": "张卫君", "gender": 2, "gender_label": "女", "age": 58},
|
||||
"diagnosis": {"clinical_diagnosis": "2型糖尿病 消渴病 · 气阴两虚兼血热",
|
||||
"chief_complaint": "咳嗽反复1月余"},
|
||||
"prescription": {"herbs": [{"name": name, "dosage": dose, "unit": "g",
|
||||
"dose_basis": "per_dose", "formula_type": "主方"}
|
||||
for name, dose in doctor.items()],
|
||||
"prescription_type": "浓缩水丸", "dose_count": 1,
|
||||
"usage_instruction": "每日1剂,水煎分服。"}},
|
||||
"missing": [{"code": "TRANSCRIPT_NOT_VERIFIED_COMPLETE", "critical": True},
|
||||
{"code": "TRANSCRIPT_NOT_VERIFIED_COMPLETE", "critical": True},
|
||||
{"code": "ARCHIVE_SYNC_WATERMARK_UNAVAILABLE", "critical": False}]}
|
||||
|
||||
|
||||
def example_statistics() -> dict[str, Any]:
|
||||
"""Doctor-level shape the statistics window renders; synthetic, but structurally complete."""
|
||||
|
||||
def doctor(identifier: int, name: str, totals: tuple[int, int, int],
|
||||
qwen: tuple[int, float | None], openai: tuple[int, float | None],
|
||||
review: tuple[int, int]) -> dict[str, Any]:
|
||||
total, patients, paired = totals
|
||||
models = {}
|
||||
for key, (eligible, mean) in (("qwen", qwen), ("openai", openai)):
|
||||
share = (0.34, 0.38, 0.18, 0.07, 0.03)
|
||||
models[key] = {"eligible_count": eligible, "mean": mean,
|
||||
"median": None if mean is None else round(mean - 1.4, 1),
|
||||
"excluded_reasons": {"SOURCE_HISTORY_VERSIONS_UNAVAILABLE": max(0, total - eligible - 2),
|
||||
"incomplete_coverage": min(2, max(0, total - eligible))},
|
||||
"distribution": {name: round(eligible * fraction)
|
||||
for name, fraction in zip(
|
||||
("[0,20)", "[20,40)", "[40,60)", "[60,80)", "[80,100]"),
|
||||
share, strict=True)}}
|
||||
evaluated, qualified = review
|
||||
return {"doctor_id": identifier, "doctor_name": name, "total_count": total,
|
||||
"patient_count": patients, "paired_count": paired, "models": models,
|
||||
"review": {"evaluated_count": evaluated, "qualified_count": qualified,
|
||||
"qualified_rate": None if not evaluated else round(100 * qualified / evaluated, 1)}}
|
||||
|
||||
doctors = [doctor(26, "何医生", (18, 14, 9), (12, 21.4), (9, 18.9), (6, 4)),
|
||||
doctor(31, "李医生", (11, 9, 4), (7, 26.8), (5, 24.1), (3, 1)),
|
||||
doctor(44, "王医生", (6, 5, 1), (2, 15.2), (0, None), (0, 0))]
|
||||
return {"total_count": sum(item["total_count"] for item in doctors),
|
||||
"patient_count": sum(item["patient_count"] for item in doctors), "doctors": doctors}
|
||||
|
||||
|
||||
class PreviewRepository:
|
||||
def __init__(self) -> None:
|
||||
self.batch = example_batch()
|
||||
|
||||
def get_prescription_ai_capabilities(self) -> dict[str, Any]:
|
||||
return {"agreement_visible": True, "can_manage_visibility": False}
|
||||
|
||||
def list_prescription_ai_reports(self, **_params: Any) -> dict[str, Any]:
|
||||
return {"agreement_visible": True, "enabled": True, "lists": deepcopy(self.history()), "count": len(self.history())}
|
||||
|
||||
def history(self) -> list[dict[str, Any]]:
|
||||
"""The current batch plus the earlier ones it supersedes, newest first."""
|
||||
|
||||
older = [
|
||||
{"id": 39, "created_at": "2026-09-10 15:18:00", "status": "success", "validity": "superseded",
|
||||
"comparison_type": "non_independent",
|
||||
"models": {"qwen": {"comparison": {"status": "comparable", "score": 48.9},
|
||||
"algorithm_version": "prescription-soft-dice-v1.0.1", "prompt_version": "v3"},
|
||||
"openai": {"comparison": {"status": "comparable", "score": 41.7},
|
||||
"algorithm_version": "prescription-soft-dice-v1.0.1", "prompt_version": "v3"}}},
|
||||
{"id": 38, "created_at": "2026-09-10 14:05:00", "status": "success", "validity": "superseded",
|
||||
"models": {"qwen": {"comparison": {"status": "comparable", "score": 33.4},
|
||||
"algorithm_version": "prescription-soft-dice-v1.0.1", "prompt_version": "v3"},
|
||||
"openai": {"comparison": {"status": "comparable", "score": 31.1},
|
||||
"algorithm_version": "prescription-soft-dice-v1.0.1", "prompt_version": "v3"}}},
|
||||
{"id": 37, "created_at": "2026-09-10 13:25:00", "status": "failed", "validity": "superseded",
|
||||
"models": {"qwen": {"error_message": "模型返回未通过校验",
|
||||
"algorithm_version": "prescription-soft-dice-v1.0.1"},
|
||||
"openai": {"comparison": {"status": "not_comparable"}}}},
|
||||
{"id": 36, "created_at": "2026-09-10 12:34:00", "status": "success", "validity": "superseded",
|
||||
"models": {"qwen": {"comparison": {"status": "not_comparable"},
|
||||
"algorithm_version": "prescription-soft-dice-v1.0.0"},
|
||||
"openai": {"comparison": {"status": "not_comparable"}}}},
|
||||
]
|
||||
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)
|
||||
|
||||
def prescription_ai_statistics(self, *_args: Any, **_params: Any) -> dict[str, Any]:
|
||||
return deepcopy(example_statistics())
|
||||
|
||||
|
||||
def main() -> None:
|
||||
application = QApplication.instance() or QApplication([])
|
||||
apply_theme(application)
|
||||
output = Path(__file__).resolve().parents[1] / "artifacts" / "issued_prescription_redesign"
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def immediate(function: Any, **callbacks: Any) -> None:
|
||||
result = function()
|
||||
if callbacks.get("on_success"):
|
||||
callbacks["on_success"](result)
|
||||
if callbacks.get("on_finished"):
|
||||
callbacks["on_finished"]()
|
||||
|
||||
ai.run_async = immediate
|
||||
repository = PreviewRepository()
|
||||
dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=7556,
|
||||
current_user={"name": "张医生"})
|
||||
dialog.show()
|
||||
names = {dialog.tabs.tabText(index): index for index in range(dialog.tabs.count())}
|
||||
for filename, width, height, tab in (
|
||||
("prescription-1440.png", 1440, 940, "对比总览"),
|
||||
("prescription-1280.png", 1280, 860, "对比总览"),
|
||||
("prescription-1024.png", 1024, 700, "对比总览"),
|
||||
("prescription-940.png", 940, 640, "对比总览"),
|
||||
("original-1280.png", 1280, 860, "原方记录"),
|
||||
("analysis-1280.png", 1280, 860, "完整报告"),
|
||||
("candidate-1280.png", 1280, 860, "方义与用法"),
|
||||
("per-herb-1440.png", 1440, 940, "候选与逐味"),
|
||||
("sources-1440.png", 1440, 940, "资料与缺口"),
|
||||
("history-1440.png", 1440, 940, "历史与趋势"),
|
||||
("pipeline-1440.png", 1440, 940, "处理进度"),
|
||||
):
|
||||
dialog.resize(width, height)
|
||||
dialog.tabs.setCurrentIndex(names[tab])
|
||||
for _ in range(4):
|
||||
application.processEvents()
|
||||
assert (dialog.width(), dialog.height()) == (width, height), (filename, dialog.size())
|
||||
assert dialog.grab().save(str(output / filename))
|
||||
print(filename, "window", width, height, "workspace", dialog.tabs.width(), dialog.tabs.height())
|
||||
dialog.tabs.setCurrentIndex(names["完整报告"])
|
||||
dialog._set_report_mode("differences")
|
||||
application.processEvents()
|
||||
assert dialog.grab().save(str(output / "report-differences-1440.png"))
|
||||
dialog._set_report_mode("both")
|
||||
dialog.tabs.setCurrentIndex(names["对比总览"])
|
||||
dialog.resize(1280, 860)
|
||||
for _ in range(4):
|
||||
application.processEvents()
|
||||
dialog.review_model.setCurrentIndex(1)
|
||||
application.processEvents()
|
||||
assert dialog.grab().save(str(output / "openai-1280.png"))
|
||||
dialog.review_model.setCurrentIndex(0)
|
||||
repository.batch["status"] = "running"
|
||||
repository.batch["models"]["openai"].update(status="running", candidate=None, comparison=None, report=None)
|
||||
dialog.refresh()
|
||||
application.processEvents()
|
||||
assert dialog.grab().save(str(output / "partial-1280.png"))
|
||||
repository.batch.update(validity="superseded", status="success")
|
||||
dialog.refresh()
|
||||
application.processEvents()
|
||||
assert dialog.grab().save(str(output / "historical-1280.png"))
|
||||
repository.batch.update(validity="current", status="running")
|
||||
repository.batch["models"]["qwen"].update(status="running", candidate=None, comparison=None, report=None)
|
||||
dialog.refresh()
|
||||
application.processEvents()
|
||||
assert dialog.grab().save(str(output / "pending-1280.png"))
|
||||
# A failed model must state the reason and offer its own retry on the card itself.
|
||||
repository.batch.update(validity="current", status="partial")
|
||||
repository.batch["models"]["qwen"].update(
|
||||
status="failed", error_code="upstream_timeout", error_message="上游模型超时,未返回结果",
|
||||
candidate=None, comparison=None, report=None, retry_count=1, max_retry=3)
|
||||
repository.batch["models"]["openai"] = deepcopy(example_batch()["models"]["openai"])
|
||||
dialog.refresh()
|
||||
application.processEvents()
|
||||
assert dialog.grab().save(str(output / "failed-1280.png"))
|
||||
# The light theme is the same window with the other palette; capture it once.
|
||||
dialog.resize(1440, 940)
|
||||
dialog._switch_theme()
|
||||
for _ in range(12):
|
||||
application.processEvents()
|
||||
dialog.repaint()
|
||||
assert dialog.grab().save(str(output / "light-1440.png"))
|
||||
dialog._switch_theme()
|
||||
for _ in range(4):
|
||||
application.processEvents()
|
||||
dialog.close()
|
||||
|
||||
statistics = ai.PrescriptionAiStatisticsDialog(repository, ["*"])
|
||||
statistics.resize(1240, 880)
|
||||
statistics.show()
|
||||
for _ in range(4):
|
||||
application.processEvents()
|
||||
assert statistics.grab().save(str(output / "statistics-1240.png"))
|
||||
statistics.close()
|
||||
print("statistics-1240.png", statistics.panel.doctors.rowCount(), "doctors")
|
||||
print(output)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,111 +0,0 @@
|
||||
"""Capture agreement authorization states using synthetic data and no network."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from copy import deepcopy
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
||||
|
||||
from PySide6.QtWidgets import QApplication
|
||||
from render_issued_prescription_ai import PreviewRepository
|
||||
|
||||
from doctor_workstation.services import DemoDoctorRepository
|
||||
from doctor_workstation.ui.dialogs import issued_prescription_ai as ai
|
||||
from doctor_workstation.ui.pages import prescriptions
|
||||
from doctor_workstation.ui.theme import apply_theme
|
||||
|
||||
|
||||
class VisibilityPreviewRepository(DemoDoctorRepository, PreviewRepository):
|
||||
def __init__(self) -> None:
|
||||
DemoDoctorRepository.__init__(self)
|
||||
PreviewRepository.__init__(self)
|
||||
self.visible = True
|
||||
|
||||
def get_prescription_ai_capabilities(self) -> dict[str, Any]:
|
||||
return {"agreement_visible": self.visible, "can_manage_visibility": True}
|
||||
|
||||
def list_prescription_ai_statuses(self, ids: list[int]) -> dict[str, Any]:
|
||||
return {"enabled": True, "agreement_visible": self.visible, "items": [
|
||||
{"prescription_id": value, "agreement_visible": self.visible, "status": "success",
|
||||
"models": {"qwen": {"status": "success", "score": 68.5},
|
||||
"openai": {"status": "success", "score": 55.2}}} for value in ids]}
|
||||
|
||||
def list_prescription_ai_reports(self, **_params: Any) -> dict[str, Any]:
|
||||
rows = [{**row, "agreement_visible": self.visible} for row in self.history()]
|
||||
return {"agreement_visible": self.visible, "enabled": True, "lists": deepcopy(rows), "count": len(rows)}
|
||||
|
||||
def get_prescription_ai_report(self, _batch_id: int) -> dict[str, Any]:
|
||||
return {**deepcopy(self.batch), "agreement_visible": self.visible}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
application = QApplication.instance() or QApplication([])
|
||||
apply_theme(application)
|
||||
output = Path(__file__).resolve().parents[2] / "artifacts" / "prescription-ai-visibility"
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def immediate(function: Any, **callbacks: Any) -> None:
|
||||
try:
|
||||
result = function()
|
||||
except Exception as error:
|
||||
if callbacks.get("on_error"):
|
||||
callbacks["on_error"](error)
|
||||
else:
|
||||
raise
|
||||
else:
|
||||
if callbacks.get("on_success"):
|
||||
callbacks["on_success"](result)
|
||||
finally:
|
||||
if callbacks.get("on_finished"):
|
||||
callbacks["on_finished"]()
|
||||
|
||||
ai.run_async = immediate
|
||||
prescriptions.run_async = immediate
|
||||
repository = VisibilityPreviewRepository()
|
||||
|
||||
def capture(widget: Any, filename: str) -> None:
|
||||
for _ in range(4):
|
||||
application.processEvents()
|
||||
assert widget.grab().save(str(output / filename))
|
||||
|
||||
page = prescriptions.PrescriptionsPage(repository, ["*"], {"name": "演示医生", "root": 1})
|
||||
page.resize(1366, 800)
|
||||
page.show()
|
||||
capture(page, "list-authorized.png")
|
||||
repository.visible = False
|
||||
page.refresh()
|
||||
capture(page, "list-restricted.png")
|
||||
page.close()
|
||||
|
||||
repository.visible = True
|
||||
dialog = ai.IssuedPrescriptionAiDialog(repository, ["*"], prescription_id=7556,
|
||||
current_user={"name": "演示医生", "root": 1})
|
||||
dialog.resize(1280, 860)
|
||||
dialog.show()
|
||||
capture(dialog, "report-authorized.png")
|
||||
repository.visible = False
|
||||
repository.batch["status"] = "partial"
|
||||
repository.batch["models"]["openai"].update(
|
||||
status="failed", report=None, candidate=None, comparison=None,
|
||||
error_code="upstream_timeout", error_message="演示:模型连接超时,可重试。")
|
||||
dialog.refresh()
|
||||
dialog._goto("report")
|
||||
capture(dialog, "report-restricted.png")
|
||||
dialog._goto("overview")
|
||||
capture(dialog, "review-restricted.png")
|
||||
dialog._goto("per_herb")
|
||||
capture(dialog, "candidate-restricted.png")
|
||||
dialog.close()
|
||||
statistics = ai.PrescriptionAiStatisticsDialog(repository, ["*"])
|
||||
statistics.resize(1180, 860)
|
||||
statistics.show()
|
||||
capture(statistics, "statistics-restricted.png")
|
||||
statistics.close()
|
||||
print(output)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,101 +0,0 @@
|
||||
"""Start the source workstation against a loopback backend with isolated login state."""
|
||||
from __future__ import annotations
|
||||
|
||||
import functools
|
||||
import os
|
||||
import socket
|
||||
import sys
|
||||
from dataclasses import replace
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import certifi
|
||||
|
||||
|
||||
def validate_local_url(api: str) -> None:
|
||||
parsed = urlsplit(api)
|
||||
if (parsed.scheme != "https" or not parsed.hostname or parsed.username or parsed.password
|
||||
or parsed.query or parsed.fragment):
|
||||
raise ValueError("本地入口需要不带凭据的 HTTPS 地址")
|
||||
addresses = {row[4][0] for row in socket.getaddrinfo(parsed.hostname, parsed.port or 443)}
|
||||
if not addresses or not addresses <= {"127.0.0.1", "::1"}:
|
||||
raise ValueError("本地入口仅连接解析到本机的后端")
|
||||
|
||||
|
||||
def validate_effective_config(config, requested_api: str) -> None:
|
||||
from doctor_workstation.config import normalize_api_base_url
|
||||
validate_local_url(config.api_base_url)
|
||||
if config.api_base_url != normalize_api_base_url(requested_api) or not config.verify_ssl:
|
||||
raise ValueError("本地独立配置已改动,请在 .local-workstation/config 中核对本地服务器设置")
|
||||
|
||||
|
||||
def local_config_type(api: str):
|
||||
"""Pin this explicit local entry, including later login/config updates."""
|
||||
from doctor_workstation.config import AppConfig, normalize_api_base_url
|
||||
|
||||
validate_local_url(api)
|
||||
local_api = normalize_api_base_url(api)
|
||||
|
||||
class LocalAppConfig(AppConfig):
|
||||
def _merge_preferences(self):
|
||||
config = super()._merge_preferences()
|
||||
# Use the locked login behavior with the selected local endpoint.
|
||||
# Shared Qt settings and stale local preferences must not send a
|
||||
# local verification session back to the production backend.
|
||||
return replace(config, api_base_url=local_api, debug_mode=False,
|
||||
demo_mode=False, verify_ssl=True)
|
||||
|
||||
return LocalAppConfig
|
||||
|
||||
|
||||
def main() -> int:
|
||||
# Select the native backend before Qt creates network objects or scans TLS
|
||||
# plugins. Selecting it later can load conflicting OpenSSL DLLs on Windows.
|
||||
if sys.platform == "win32":
|
||||
os.environ["QT_TLS_BACKEND"] = "schannel"
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
api = os.environ.get("DOCTOR_LOCAL_API_URL", "https://css.zhenyangtang.com.cn")
|
||||
validate_local_url(api)
|
||||
certificate = Path(os.environ.get(
|
||||
"DOCTOR_LOCAL_CA_FILE",
|
||||
"D:/phpstudy_pro/Extensions/Nginx1.15.11/conf/ssl/css.zhenyangtang.com.cn.pem",
|
||||
))
|
||||
private_root = root / ".local-workstation"
|
||||
private_root.mkdir(parents=True, exist_ok=True)
|
||||
ca_bundle = private_root / "trusted-ca.pem"
|
||||
ca_bundle.write_bytes(Path(certifi.where()).read_bytes() + b"\n" + certificate.read_bytes())
|
||||
os.environ.update({
|
||||
"DOCTOR_CONFIG_DIR": str(private_root / "config"),
|
||||
"DOCTOR_LOG_DIR": str(private_root / "logs"),
|
||||
"DOCTOR_API_BASE_URL": api,
|
||||
"DOCTOR_DEMO_MODE": "false",
|
||||
"DOCTOR_VERIFY_SSL": "true",
|
||||
"SSL_CERT_FILE": str(ca_bundle),
|
||||
})
|
||||
sys.path.insert(0, str(root / "src"))
|
||||
# This explicit source-only entry does not edit the formal build configuration.
|
||||
LocalAppConfig = local_config_type(api)
|
||||
config = LocalAppConfig.load()
|
||||
validate_effective_config(config, api)
|
||||
config.save_preferences()
|
||||
if "--check" in sys.argv:
|
||||
print("Local backend: loopback HTTPS; TLS verification enabled; isolated configuration and credential namespace")
|
||||
return 0
|
||||
from PySide6.QtCore import QSettings
|
||||
|
||||
from doctor_workstation import app as workstation_app
|
||||
|
||||
workstation_app.AppConfig = LocalAppConfig
|
||||
workstation_app.LoginWindow = functools.partial(
|
||||
workstation_app.LoginWindow,
|
||||
settings=QSettings("ZhenYangTang", "DoctorWorkstationLocalSource"),
|
||||
)
|
||||
# The normal credential service remains untouched even after a local login.
|
||||
workstation_app.TokenStore = functools.partial(
|
||||
workstation_app.TokenStore, service_name="zyt-doctor-workstation-local-source"
|
||||
)
|
||||
return workstation_app.main()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -9,7 +9,6 @@ $FrozenExecutable = Join-Path $ProjectRoot "dist\DoctorWorkstation\DoctorWorksta
|
||||
$ProjectPython = Join-Path $ProjectRoot ".venv\Scripts\python.exe"
|
||||
$ProjectUvCache = Join-Path $ProjectRoot ".uv-cache"
|
||||
$SourceRoot = Join-Path $ProjectRoot "src"
|
||||
$SourceEntry = Join-Path $SourceRoot "doctor_workstation\__main__.py"
|
||||
|
||||
function Test-ProjectPython {
|
||||
param([Parameter(Mandatory = $true)][string]$Candidate)
|
||||
@@ -34,13 +33,7 @@ function Find-Uv {
|
||||
}
|
||||
|
||||
try {
|
||||
$Python = $null
|
||||
if ((Test-Path -LiteralPath $SourceEntry -PathType Leaf) -and
|
||||
(Test-ProjectPython -Candidate $ProjectPython)) {
|
||||
$Python = $ProjectPython
|
||||
Write-Host "Using current source tree: $SourceRoot"
|
||||
}
|
||||
elseif (Test-Path -LiteralPath $FrozenExecutable -PathType Leaf) {
|
||||
if (Test-Path -LiteralPath $FrozenExecutable -PathType Leaf) {
|
||||
Write-Host "Using packaged application: $FrozenExecutable"
|
||||
if ($ValidateOnly) {
|
||||
Write-Host "Windows run entry validation passed."
|
||||
@@ -54,7 +47,13 @@ try {
|
||||
}
|
||||
exit $ApplicationExitCode
|
||||
}
|
||||
elseif (Test-Path -LiteralPath $SourceEntry -PathType Leaf) {
|
||||
|
||||
$Python = $null
|
||||
if (Test-ProjectPython -Candidate $ProjectPython) {
|
||||
$Python = $ProjectPython
|
||||
Write-Host "Using existing project environment: $ProjectPython"
|
||||
}
|
||||
else {
|
||||
$Uv = Find-Uv
|
||||
if (-not $Uv) {
|
||||
throw "No packaged application or usable .venv was found, and uv is not installed."
|
||||
@@ -109,9 +108,6 @@ try {
|
||||
}
|
||||
$Python = $ProjectPython
|
||||
}
|
||||
else {
|
||||
throw "No source entry or packaged application was found."
|
||||
}
|
||||
|
||||
if ($ValidateOnly) {
|
||||
Write-Host "Windows run entry validation passed."
|
||||
|
||||
@@ -3,9 +3,9 @@
|
||||
__all__ = ["DEBUG_MODE", "ONLINE_API_BASE_URL", "__version__"]
|
||||
|
||||
# Single source of truth for runtime, package, installer, and executable versions.
|
||||
__version__ = "1.5.0"
|
||||
__version__ = "1.4.2"
|
||||
|
||||
# 调试模式开启时,登录页显示“演示模式”和“服务器设置”。
|
||||
# 正式发布请保持 False;此时程序只使用下面配置的线上域名。
|
||||
DEBUG_MODE = False
|
||||
DEBUG_MODE = True
|
||||
ONLINE_API_BASE_URL = "https://admin.zhenyangtang.com.cn"
|
||||
|
||||
@@ -1004,8 +1004,6 @@ class ApplicationController(QObject):
|
||||
preview_height = min(380, max(320, round(preview_width * 0.66)))
|
||||
margin = 18
|
||||
|
||||
if callable(getattr(video_window, "setProperty", None)):
|
||||
video_window.setProperty("doctorSkipOpenGeometry", True)
|
||||
video_window.showNormal()
|
||||
video_window.setMinimumSize(440, 300)
|
||||
video_window.setWindowFlag(Qt.WindowType.WindowStaysOnTopHint, True)
|
||||
@@ -1060,8 +1058,6 @@ class ApplicationController(QObject):
|
||||
window.raise_()
|
||||
if activate:
|
||||
window.activateWindow()
|
||||
if callable(getattr(window, "setProperty", None)):
|
||||
window.setProperty("doctorSkipOpenGeometry", False)
|
||||
except (AttributeError, RuntimeError):
|
||||
return
|
||||
|
||||
|
||||
@@ -2,19 +2,16 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import time
|
||||
from collections import deque
|
||||
from collections.abc import Callable, Iterator, Mapping
|
||||
from contextlib import contextmanager, suppress
|
||||
from contextlib import contextmanager
|
||||
from threading import Condition, RLock
|
||||
from typing import Any
|
||||
from urllib.parse import urljoin, urlsplit, urlunsplit
|
||||
|
||||
import httpx
|
||||
|
||||
from doctor_workstation import __version__
|
||||
from doctor_workstation.core.errors import (
|
||||
ApiBusinessError,
|
||||
ApiHttpError,
|
||||
@@ -231,29 +228,6 @@ class ApiClient:
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
def post_independent(
|
||||
self,
|
||||
endpoint: str,
|
||||
payload: Mapping[str, Any],
|
||||
*,
|
||||
timeout: float = 10.0,
|
||||
) -> Any:
|
||||
"""Send a short control request without waiting for the ordinary pool."""
|
||||
|
||||
try:
|
||||
with httpx.Client(transport=self._stream_transport, verify=self._verify) as client:
|
||||
response = client.post(
|
||||
self._endpoint_url(endpoint),
|
||||
json=dict(payload),
|
||||
headers=self._headers(None),
|
||||
timeout=timeout,
|
||||
)
|
||||
return self._unwrap(response)
|
||||
except httpx.TimeoutException as exc:
|
||||
raise ApiTimeoutError(f"POST {endpoint} timed out") from exc
|
||||
except httpx.RequestError as exc:
|
||||
raise ApiTransportError(f"POST {endpoint} failed") from exc
|
||||
|
||||
def post_event_stream(
|
||||
self,
|
||||
endpoint: str,
|
||||
@@ -273,14 +247,6 @@ class ApiClient:
|
||||
headers = self._headers({"Accept": "text/event-stream"})
|
||||
request_timeout = self.timeout if timeout is None else timeout
|
||||
try:
|
||||
if cancelled is not None and (
|
||||
self._stream_transport is None
|
||||
or isinstance(self._stream_transport, httpx.AsyncBaseTransport)
|
||||
):
|
||||
yield from self._cancellable_event_stream(
|
||||
url, payload, headers, request_timeout, cancelled
|
||||
)
|
||||
return
|
||||
with httpx.Client(
|
||||
transport=self._stream_transport,
|
||||
verify=self._verify,
|
||||
@@ -320,109 +286,6 @@ class ApiClient:
|
||||
data={"method": "POST", "endpoint": endpoint},
|
||||
) from exc
|
||||
|
||||
def _cancellable_event_stream(
|
||||
self,
|
||||
url: str,
|
||||
payload: Mapping[str, Any],
|
||||
headers: Mapping[str, str],
|
||||
timeout: float | httpx.Timeout,
|
||||
cancelled: Callable[[], bool],
|
||||
) -> Iterator[dict[str, Any]]:
|
||||
"""Own network reads and cancellation on the same worker-local event loop.
|
||||
|
||||
Closing a synchronous httpx response from another thread can wait on its
|
||||
active read lock. Cancelling an async read interrupts idle headers/body
|
||||
reads and closes their sockets on their owning loop instead.
|
||||
"""
|
||||
|
||||
async def events():
|
||||
async with httpx.AsyncClient(
|
||||
transport=self._stream_transport, verify=self._verify
|
||||
) as client, client.stream(
|
||||
"POST", url, json=dict(payload), headers=headers, timeout=timeout
|
||||
) as response:
|
||||
if not 200 <= response.status_code < 300:
|
||||
raise ApiHttpError(
|
||||
f"API returned HTTP {response.status_code}",
|
||||
status_code=response.status_code,
|
||||
request_id=self._request_id(response),
|
||||
)
|
||||
content_type = response.headers.get("content-type", "").lower()
|
||||
if "text/event-stream" not in content_type:
|
||||
await response.aread()
|
||||
if "json" in content_type:
|
||||
self._unwrap(response)
|
||||
raise ApiProtocolError("API response is not an event stream")
|
||||
frame: list[str] = []
|
||||
async for line in response.aiter_lines():
|
||||
frame.append(line)
|
||||
if not line:
|
||||
for event in _iter_event_stream(frame):
|
||||
yield event
|
||||
frame.clear()
|
||||
for event in _iter_event_stream(frame):
|
||||
yield event
|
||||
|
||||
if cancelled():
|
||||
return
|
||||
loop = asyncio.new_event_loop()
|
||||
iterator = events()
|
||||
pending: deque[dict[str, Any]] = deque()
|
||||
polling = False
|
||||
wake_handle: asyncio.Handle | None = None
|
||||
|
||||
def wake_consumer() -> None:
|
||||
nonlocal wake_handle
|
||||
if polling and wake_handle is None:
|
||||
wake_handle = loop.call_soon(loop.stop)
|
||||
|
||||
async def pump() -> None:
|
||||
try:
|
||||
async for event in iterator:
|
||||
if cancelled():
|
||||
return
|
||||
pending.append(event)
|
||||
wake_consumer()
|
||||
# Bound buffered work and let the scheduled batch wake run,
|
||||
# even when one HTTP chunk contains thousands of SSE frames.
|
||||
if len(pending) >= 256:
|
||||
await asyncio.sleep(0)
|
||||
finally:
|
||||
wake_consumer()
|
||||
|
||||
producer = loop.create_task(pump())
|
||||
|
||||
async def close_producer() -> None:
|
||||
producer.cancel()
|
||||
with suppress(asyncio.CancelledError, Exception):
|
||||
await producer
|
||||
await iterator.aclose()
|
||||
|
||||
try:
|
||||
while not cancelled():
|
||||
# Read buffered frames directly. There is one persistent async
|
||||
# producer, not a new task/event-loop crossing for every delta.
|
||||
if pending:
|
||||
yield pending.popleft()
|
||||
continue
|
||||
if producer.done():
|
||||
producer.result() # Propagate EOF errors after queued tails.
|
||||
return
|
||||
polling = True
|
||||
wake_handle = None
|
||||
timer = loop.call_later(0.03, loop.stop)
|
||||
try:
|
||||
loop.run_forever()
|
||||
finally:
|
||||
polling = False
|
||||
timer.cancel()
|
||||
if wake_handle is not None:
|
||||
wake_handle.cancel()
|
||||
finally:
|
||||
loop.run_until_complete(close_producer())
|
||||
loop.run_until_complete(loop.shutdown_asyncgens())
|
||||
loop.close()
|
||||
|
||||
def get_bytes(self, url: str, *, max_bytes: int = 5 * 1024 * 1024) -> bytes:
|
||||
"""Download a public binary asset without applying the JSON envelope contract."""
|
||||
|
||||
@@ -620,7 +483,6 @@ class ApiClient:
|
||||
result = {
|
||||
"Accept": "application/json",
|
||||
"version": self.API_VERSION,
|
||||
"User-Agent": f"ZytDoctorWorkstation/{__version__}",
|
||||
}
|
||||
if json_content_type:
|
||||
result["Content-Type"] = "application/json;charset=UTF-8"
|
||||
|
||||
@@ -6,7 +6,7 @@ import hashlib
|
||||
import json
|
||||
import struct
|
||||
import zlib
|
||||
from collections.abc import Callable, Mapping, Sequence
|
||||
from collections.abc import Mapping, Sequence
|
||||
from copy import deepcopy
|
||||
from datetime import date, datetime, timedelta
|
||||
from os import PathLike
|
||||
@@ -64,7 +64,6 @@ DEMO_PERMISSIONS: tuple[str, ...] = (
|
||||
"tcm.diagnosis/editAiReport",
|
||||
"tcm.diagnosis/aiAnalysis",
|
||||
"tcm.diagnosis/aiAssistant",
|
||||
"tcm.diagnosis/aiGeneratePrescription",
|
||||
"tcm.diagnosis/patientAiReports",
|
||||
"tcm.diagnosis/generatePatientAiReport",
|
||||
"tcm.diagnosis/dailyRecord",
|
||||
@@ -2771,14 +2770,10 @@ class DemoDoctorRepository:
|
||||
*,
|
||||
call_record_id: int | None = None,
|
||||
mime_type: str = "audio/webm",
|
||||
on_progress: Callable[[int, int], None] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Upload then attach a demo local-audio file using the production sequence."""
|
||||
|
||||
source_path = Path(path)
|
||||
size = source_path.stat().st_size if source_path.is_file() else 0
|
||||
if on_progress is not None:
|
||||
on_progress(0, size)
|
||||
is_audio = source_path.suffix.lower() in {
|
||||
".ogg",
|
||||
".opus",
|
||||
@@ -2815,8 +2810,6 @@ class DemoDoctorRepository:
|
||||
record["local_audio_status_text"] = "已保存"
|
||||
else:
|
||||
self.attach_local_call_recording(diagnosis_id, file_url, call_record_id=target_id)
|
||||
if on_progress is not None:
|
||||
on_progress(size, size)
|
||||
return {
|
||||
"diagnosis_id": diagnosis_id,
|
||||
"call_record_id": target_id,
|
||||
|
||||
@@ -19,6 +19,7 @@ from doctor_workstation.core.errors import (
|
||||
ApiBusinessError,
|
||||
ApiHttpError,
|
||||
ApiProtocolError,
|
||||
ApiTimeoutError,
|
||||
ApiTransportError,
|
||||
AuthenticationExpiredError,
|
||||
)
|
||||
@@ -206,13 +207,9 @@ class DoctorRepository(Protocol):
|
||||
prompt: str,
|
||||
*,
|
||||
task: str = "custom",
|
||||
request_id: str | None = None,
|
||||
cancelled: Callable[[], bool] | None = None,
|
||||
) -> Iterator[dict[str, Any]]:
|
||||
"""Yield normalized assistant content and preparation progress events."""
|
||||
|
||||
def cancel_diagnosis_ai(self, diagnosis_id: int, request_id: str) -> dict[str, Any]:
|
||||
"""Request server/upstream cancellation of one correlated stream."""
|
||||
"""Yield normalized ``start``/``delta``/``done`` assistant events."""
|
||||
|
||||
def generate_ai_prescription(self, diagnosis_id: int) -> dict[str, Any]:
|
||||
"""Generate a server-validated prescription draft for doctor review."""
|
||||
@@ -236,32 +233,8 @@ class DoctorRepository(Protocol):
|
||||
) -> dict[str, Any]:
|
||||
"""Append one model-specific AI diagnosis snapshot for one patient."""
|
||||
|
||||
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."""
|
||||
|
||||
def list_prescription_ai_reports(self, *, prescription_id: int = 0, diagnosis_id: int = 0, page_no: int = 1, page_size: int = 20) -> dict[str, Any]:
|
||||
"""Read immutable analysis batch history in the authorized scope."""
|
||||
|
||||
def get_prescription_ai_report(self, batch_id: int) -> dict[str, Any]:
|
||||
"""Read one analysis batch without starting model work."""
|
||||
|
||||
def regenerate_prescription_ai(self, prescription_id: int, reason: str) -> dict[str, Any]:
|
||||
"""Explicitly request a new analysis batch with a reason."""
|
||||
|
||||
def retry_prescription_ai(self, batch_id: int, model_key: str) -> dict[str, Any]:
|
||||
"""Retry only the requested failed model."""
|
||||
|
||||
def review_prescription_ai(self, batch_id: int, model_key: str, status: str, comment: str) -> dict[str, Any]:
|
||||
"""Save a doctor's review separately from immutable AI output."""
|
||||
|
||||
def prescription_ai_statistics(self, date_from: str, date_to: str, doctor_id: int | None = None) -> dict[str, Any]:
|
||||
"""Read baseline agreement statistics, never diagnostic accuracy."""
|
||||
def get_prescription(self, prescription_id: int) -> Prescription:
|
||||
"""Return one issued prescription."""
|
||||
|
||||
def create_prescription(
|
||||
self,
|
||||
@@ -683,7 +656,6 @@ class DoctorRepository(Protocol):
|
||||
*,
|
||||
call_record_id: int | None = None,
|
||||
mime_type: str = "audio/webm",
|
||||
on_progress: Callable[[int, int], None] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Upload a locally captured call recording to a real call record."""
|
||||
|
||||
@@ -1418,17 +1390,13 @@ 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."""
|
||||
"""Stream a diagnosis answer, with one legacy fallback before first content."""
|
||||
|
||||
clean_prompt, clean_task = _diagnosis_ai_request(diagnosis_id, prompt, task)
|
||||
body = {
|
||||
"id": diagnosis_id, "prompt": clean_prompt, "task": clean_task,
|
||||
"request_id": request_id or str(uuid4()),
|
||||
}
|
||||
received_event = False
|
||||
body = {"id": diagnosis_id, "prompt": clean_prompt, "task": clean_task}
|
||||
received_delta = False
|
||||
received_done = False
|
||||
try:
|
||||
for raw_event in self.client.post_event_stream(
|
||||
@@ -1439,12 +1407,13 @@ class RemoteDoctorRepository:
|
||||
):
|
||||
if cancelled is not None and cancelled():
|
||||
return
|
||||
received_event = True
|
||||
event = _normalise_diagnosis_ai_event(raw_event)
|
||||
if event is None:
|
||||
continue
|
||||
kind = event["event"]
|
||||
if kind == "done":
|
||||
if kind == "delta":
|
||||
received_delta = True
|
||||
elif kind == "done":
|
||||
received_done = True
|
||||
yield event
|
||||
if kind == "done":
|
||||
@@ -1453,16 +1422,12 @@ class RemoteDoctorRepository:
|
||||
return
|
||||
if not received_done:
|
||||
raise ApiProtocolError("AI assistant stream ended before done")
|
||||
except ApiHttpError as error:
|
||||
if (
|
||||
error.status_code not in {404, 405}
|
||||
or received_event
|
||||
or (cancelled is not None and cancelled())
|
||||
):
|
||||
except (ApiHttpError, ApiProtocolError, ApiTimeoutError, ApiTransportError):
|
||||
if received_delta or (cancelled is not None and cancelled()):
|
||||
raise
|
||||
|
||||
# Only a missing stream route on an older deployment justifies another
|
||||
# full request. Timeouts, transport failures and malformed streams do not.
|
||||
# Older deployments do not expose the stream route. Submit exactly one
|
||||
# request through the confirmed non-streaming endpoint in that case.
|
||||
result = self.analyze_diagnosis_ai(
|
||||
diagnosis_id,
|
||||
clean_prompt,
|
||||
@@ -1476,18 +1441,6 @@ 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."""
|
||||
|
||||
@@ -1621,58 +1574,14 @@ class RemoteDoctorRepository:
|
||||
payload, Prescription.from_dict, page_no=page_no, page_size=page_size
|
||||
)
|
||||
|
||||
def get_prescription(self, prescription_id: int) -> Prescription:
|
||||
"""Load one issued prescription using ``tcm.prescription/detail``."""
|
||||
def get_prescription(self, prescription_id: int) -> Prescription:
|
||||
"""Load one issued prescription using ``tcm.prescription/detail``."""
|
||||
|
||||
result = _require_mapping(
|
||||
self.client.get("tcm.prescription/detail", {"id": prescription_id}),
|
||||
"tcm.prescription/detail",
|
||||
)
|
||||
return Prescription.from_dict(result)
|
||||
|
||||
def _prescription_ai_request(self, action: str, params: dict[str, Any], *, mutation: bool = False) -> dict[str, Any]:
|
||||
endpoint = f"tcm.prescriptionAi/{action}"
|
||||
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")
|
||||
return self._prescription_ai_request("statuses", {"ids": ",".join(str(int(value)) for value in dict.fromkeys(ids))})
|
||||
|
||||
def list_prescription_ai_reports(self, *, prescription_id: int = 0, diagnosis_id: int = 0, page_no: int = 1, page_size: int = 20) -> dict[str, Any]:
|
||||
if bool(prescription_id) == bool(diagnosis_id):
|
||||
raise ValueError("Exactly one prescription_id or diagnosis_id is required")
|
||||
params = {"prescription_id": prescription_id} if prescription_id else {"diagnosis_id": diagnosis_id}
|
||||
params.update(page_no=page_no, page_size=page_size)
|
||||
return self._prescription_ai_request("reports", params)
|
||||
|
||||
def get_prescription_ai_report(self, batch_id: int) -> dict[str, Any]:
|
||||
return self._prescription_ai_request("detail", {"batch_id": batch_id})
|
||||
|
||||
def regenerate_prescription_ai(self, prescription_id: int, reason: str) -> dict[str, Any]:
|
||||
if not reason.strip():
|
||||
raise ValueError("重新分析需要填写原因")
|
||||
return self._prescription_ai_request("regenerate", {"prescription_id": prescription_id, "reason": reason.strip()}, mutation=True)
|
||||
|
||||
def retry_prescription_ai(self, batch_id: int, model_key: str) -> dict[str, Any]:
|
||||
if model_key not in {"qwen", "openai"}:
|
||||
raise ValueError("Unknown model_key")
|
||||
return self._prescription_ai_request("retry", {"batch_id": batch_id, "model_key": model_key}, mutation=True)
|
||||
|
||||
def review_prescription_ai(self, batch_id: int, model_key: str, status: str, comment: str) -> dict[str, Any]:
|
||||
if model_key not in {"qwen", "openai"} or status not in {"viewed", "needs_information", "not_adopted", "reviewed"}:
|
||||
raise ValueError("Invalid review state")
|
||||
return self._prescription_ai_request("review", {"batch_id": batch_id, "model_key": model_key, "status": status, "comment": comment}, mutation=True)
|
||||
|
||||
def prescription_ai_statistics(self, date_from: str, date_to: str, doctor_id: int | None = None) -> dict[str, Any]:
|
||||
params: dict[str, Any] = {"date_from": date_from, "date_to": date_to}
|
||||
if doctor_id is not None:
|
||||
params["doctor_id"] = doctor_id
|
||||
return self._prescription_ai_request("statistics", params)
|
||||
return Prescription.from_dict(result)
|
||||
|
||||
def create_prescription(
|
||||
self,
|
||||
@@ -2513,13 +2422,8 @@ class RemoteDoctorRepository:
|
||||
*,
|
||||
call_record_id: int | None = None,
|
||||
mime_type: str = "audio/webm",
|
||||
on_progress: Callable[[int, int], None] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Chunk-upload one local audio recording and attach it atomically.
|
||||
|
||||
``on_progress(sent_bytes, total_bytes)`` runs on the calling thread after
|
||||
every confirmed chunk; its failures never interrupt the upload.
|
||||
"""
|
||||
"""Chunk-upload one local audio recording and attach it atomically."""
|
||||
|
||||
if diagnosis_id <= 0:
|
||||
raise ValueError("diagnosis_id must be positive")
|
||||
@@ -2539,13 +2443,6 @@ class RemoteDoctorRepository:
|
||||
clean_mime = str(mime_type or "audio/webm").strip()[:120] or "audio/webm"
|
||||
final_result: Mapping[str, Any] | None = None
|
||||
bound_call_record_id = call_record_id
|
||||
|
||||
def report(sent: int) -> None:
|
||||
if on_progress is not None:
|
||||
with suppress(Exception):
|
||||
on_progress(min(sent, file_size), file_size)
|
||||
|
||||
report(0)
|
||||
with recording_path.open("rb") as stream:
|
||||
for chunk_index in range(chunk_total):
|
||||
content = stream.read(chunk_size)
|
||||
@@ -2580,7 +2477,6 @@ class RemoteDoctorRepository:
|
||||
raise ApiProtocolError(
|
||||
"uploadCallRecording returned a different call_record_id"
|
||||
)
|
||||
report((chunk_index + 1) * chunk_size)
|
||||
|
||||
if final_result is None or not bool(final_result.get("completed")):
|
||||
raise ApiProtocolError("uploadCallRecording did not complete the local audio upload")
|
||||
@@ -3004,9 +2900,6 @@ def _diagnosis_ai_request(diagnosis_id: int, prompt: str, task: str) -> tuple[st
|
||||
raise ValueError("prompt must not exceed 500 characters")
|
||||
clean_task = task.strip().lower() or "custom"
|
||||
if clean_task not in {
|
||||
"case_analysis",
|
||||
"glucose_trend",
|
||||
"lifestyle_advice",
|
||||
"summary",
|
||||
"tcm_pattern",
|
||||
"prescription_review",
|
||||
@@ -3027,10 +2920,10 @@ def _normalise_diagnosis_ai_event(raw: Mapping[str, Any]) -> dict[str, Any] | No
|
||||
payload = dict(data) if isinstance(data, Mapping) else {}
|
||||
if kind == "message":
|
||||
kind = str(payload.get("event") or payload.get("type") or "message").lower()
|
||||
if kind in {"start", "progress"}:
|
||||
if kind == "start":
|
||||
payload.pop("event", None)
|
||||
payload.pop("type", None)
|
||||
return {**payload, "event": kind}
|
||||
return {**payload, "event": "start"}
|
||||
if kind == "delta":
|
||||
text = (
|
||||
data
|
||||
|
||||
@@ -43,7 +43,6 @@ from PySide6.QtWidgets import (
|
||||
)
|
||||
|
||||
from ..core.appointment_modes import APPOINTMENT_MODES
|
||||
from .theme import main_window_target_rect
|
||||
from .widgets import (
|
||||
display_text,
|
||||
first_value,
|
||||
@@ -1767,11 +1766,6 @@ class AppointmentDrawer(QDialog):
|
||||
super().mousePressEvent(event)
|
||||
|
||||
def _sync_to_owner(self) -> None:
|
||||
target = main_window_target_rect(self)
|
||||
if target is not None:
|
||||
self.setGeometry(target)
|
||||
self._update_drawer_width()
|
||||
return
|
||||
if self._owner is None:
|
||||
self._update_drawer_width()
|
||||
return
|
||||
|
||||
@@ -1,376 +0,0 @@
|
||||
"""Shared, display-only normalization of archived chat messages and IM events."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
from collections.abc import Mapping
|
||||
from datetime import date, datetime
|
||||
from typing import Any, NamedTuple
|
||||
|
||||
|
||||
class ChatItem(NamedTuple):
|
||||
variant: str
|
||||
role: str
|
||||
text: Any
|
||||
title: str
|
||||
detail: str
|
||||
time_text: str
|
||||
tone: str
|
||||
marker: str
|
||||
|
||||
|
||||
def _first_value(source: Any, *keys: str, default: Any = None) -> Any:
|
||||
for key in keys:
|
||||
if isinstance(source, Mapping):
|
||||
value = source.get(key)
|
||||
else:
|
||||
value = getattr(source, key, None)
|
||||
raw = getattr(source, "raw", None)
|
||||
if value is None and isinstance(raw, Mapping):
|
||||
value = raw.get(key)
|
||||
if value is not None and value != "":
|
||||
return value
|
||||
return default
|
||||
|
||||
|
||||
def _as_int(value: Any, default: int = 0) -> int:
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError, OverflowError):
|
||||
return default
|
||||
|
||||
|
||||
def _truthy(value: Any) -> bool:
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
return str(value or "").strip().lower() in {"1", "true", "yes", "on", "是", "有"}
|
||||
|
||||
|
||||
def format_chat_time(value: Any, *, include_date: bool = False) -> str:
|
||||
"""Show actual archive times; accept Unix seconds/milliseconds and ISO dates."""
|
||||
if value is None or value == "" or isinstance(value, bool):
|
||||
return ""
|
||||
pattern = "%Y-%m-%d %H:%M" if include_date else "%H:%M"
|
||||
if isinstance(value, datetime):
|
||||
return value.strftime(pattern)
|
||||
if isinstance(value, date):
|
||||
return value.isoformat()
|
||||
text = str(value).strip()
|
||||
if not text:
|
||||
return ""
|
||||
if isinstance(value, (int, float)) or re.fullmatch(r"[+-]?\d+(?:\.\d+)?", text):
|
||||
numeric = float(value)
|
||||
if not math.isfinite(numeric) or numeric <= 0:
|
||||
return ""
|
||||
if numeric >= 10_000_000_000:
|
||||
numeric /= 1000
|
||||
try:
|
||||
return datetime.fromtimestamp(numeric).strftime(pattern)
|
||||
except (OverflowError, OSError, ValueError):
|
||||
return ""
|
||||
try:
|
||||
moment = datetime.fromisoformat(text.replace("Z", "+00:00"))
|
||||
except ValueError:
|
||||
# Legacy archive rows can already contain a display-only time.
|
||||
return text if include_date else text.rsplit(" ", 1)[-1][:16]
|
||||
return moment.strftime(pattern)
|
||||
|
||||
|
||||
def _decode_json_value(value: Any) -> Any:
|
||||
if isinstance(value, Mapping):
|
||||
return dict(value)
|
||||
if isinstance(value, (list, tuple)):
|
||||
return list(value)
|
||||
if not isinstance(value, str):
|
||||
return None
|
||||
text = value.strip()
|
||||
if not text or text[0] not in "[{":
|
||||
return None
|
||||
try:
|
||||
return json.loads(text)
|
||||
except (TypeError, ValueError, json.JSONDecodeError):
|
||||
return None
|
||||
|
||||
|
||||
def _normalized_token(value: Any) -> str:
|
||||
return re.sub(r"[^a-z0-9]", "", str(value or "").strip().lower())
|
||||
|
||||
|
||||
def _format_call_duration(value: Any) -> str:
|
||||
seconds = _as_int(value)
|
||||
if seconds <= 0:
|
||||
return ""
|
||||
if seconds < 60:
|
||||
return f"通话 {seconds} 秒"
|
||||
minutes, remaining = divmod(seconds, 60)
|
||||
return f"通话 {minutes} 分 {remaining} 秒" if remaining else f"通话 {minutes} 分钟"
|
||||
|
||||
|
||||
def _event_time(
|
||||
row: Mapping[str, Any], *payloads: Mapping[str, Any], include_date: bool = False
|
||||
) -> str:
|
||||
value = _first_value(
|
||||
row, "time", "create_time", "created_at", "msg_time", "timestamp", default=None
|
||||
)
|
||||
if value in (None, ""):
|
||||
for payload in payloads:
|
||||
value = _first_value(payload, "time", "timestamp", "create_time", default=None)
|
||||
if value not in (None, ""):
|
||||
break
|
||||
return format_chat_time(value, include_date=include_date)
|
||||
|
||||
|
||||
def _event_item(
|
||||
*,
|
||||
title: str,
|
||||
detail: str = "",
|
||||
time_text: str = "",
|
||||
tone: str = "neutral",
|
||||
marker: str = "系",
|
||||
) -> ChatItem:
|
||||
return ChatItem("event", "system", "", title, detail, time_text, tone, marker)
|
||||
|
||||
|
||||
def _system_event_from_payload(
|
||||
payload: Mapping[str, Any],
|
||||
row: Mapping[str, Any],
|
||||
*,
|
||||
include_date: bool = False,
|
||||
) -> ChatItem | None:
|
||||
business = _normalized_token(_first_value(payload, "businessID", "businessId", "business_id"))
|
||||
time_text = _event_time(row, payload, include_date=include_date)
|
||||
patient_name = str(
|
||||
_first_value(payload, "patientName", "patient_name", default="患者") or "患者"
|
||||
)
|
||||
if business in {"patientopenedchat", "patientopenchat", "openchat"}:
|
||||
return _event_item(
|
||||
title="患者进入在线问诊",
|
||||
detail=f"{patient_name}已进入当前会话",
|
||||
time_text=time_text,
|
||||
tone="success",
|
||||
marker="入",
|
||||
)
|
||||
if business in {"patientclosedchat", "patientclosechat", "patientleftchat", "closechat"}:
|
||||
return _event_item(
|
||||
title="患者离开在线问诊",
|
||||
detail=f"{patient_name}已离开当前会话",
|
||||
time_text=time_text,
|
||||
marker="离",
|
||||
)
|
||||
if business == "doctorenteredconsultroom":
|
||||
return _event_item(
|
||||
title="医生进入在线诊室",
|
||||
detail="本次在线问诊已准备就绪",
|
||||
time_text=time_text,
|
||||
tone="success",
|
||||
marker="医",
|
||||
)
|
||||
if business == "consultationcomplete":
|
||||
return _event_item(
|
||||
title="本次问诊已完成",
|
||||
detail="会话内容已归档",
|
||||
time_text=time_text,
|
||||
tone="success",
|
||||
marker="完",
|
||||
)
|
||||
|
||||
nested = _decode_json_value(payload.get("data"))
|
||||
rtc_payload: Mapping[str, Any] | None = None
|
||||
if business in {"rtccall", "rtcvideo", "rtcaudio"}:
|
||||
rtc_payload = payload
|
||||
elif business in {"1", "avcall"}:
|
||||
rtc_payload = {**payload, **nested} if isinstance(nested, Mapping) else payload
|
||||
elif _first_value(payload, "cmd", "command", default="") not in (None, ""):
|
||||
rtc_payload = payload
|
||||
elif isinstance(nested, Mapping):
|
||||
nested_business = _normalized_token(
|
||||
_first_value(nested, "businessID", "businessId", "business_id")
|
||||
)
|
||||
if nested_business in {"rtccall", "rtcvideo", "rtcaudio"}:
|
||||
rtc_payload = nested
|
||||
else:
|
||||
nested_event = _system_event_from_payload(nested, row, include_date=include_date)
|
||||
if nested_event is not None:
|
||||
return nested_event
|
||||
if rtc_payload is None:
|
||||
return None
|
||||
|
||||
call_data = _decode_json_value(rtc_payload.get("data"))
|
||||
if not isinstance(call_data, Mapping):
|
||||
call_data = rtc_payload
|
||||
command = _normalized_token(_first_value(call_data, "cmd", "command", "action"))
|
||||
action_type = _as_int(_first_value(rtc_payload, "actionType", "action_type"))
|
||||
if not command:
|
||||
command = {
|
||||
1: "invite",
|
||||
2: "cancel",
|
||||
3: "accept",
|
||||
4: "reject",
|
||||
5: "timeout",
|
||||
6: "hangup",
|
||||
7: "linebusy",
|
||||
}.get(action_type, "")
|
||||
call_type = _as_int(_first_value(rtc_payload, "call_type", default=2), 2)
|
||||
medium = (
|
||||
"语音" if call_type == 1 or business == "rtcaudio" or command == "audiocall" else "视频"
|
||||
)
|
||||
marker = "音" if medium == "语音" else "视"
|
||||
time_text = _event_time(row, payload, rtc_payload, call_data, include_date=include_date)
|
||||
duration = _format_call_duration(
|
||||
_first_value(
|
||||
rtc_payload,
|
||||
"call_end",
|
||||
"duration",
|
||||
"callDuration",
|
||||
default=_first_value(call_data, "call_end", "duration", "callDuration", default=0),
|
||||
)
|
||||
)
|
||||
|
||||
if command in {"videocall", "audiocall", "call", "invite", "startcall"}:
|
||||
return _event_item(
|
||||
title=f"发起{medium}问诊",
|
||||
detail=f"医生已向患者发起{medium}通话",
|
||||
time_text=time_text,
|
||||
tone="info",
|
||||
marker=marker,
|
||||
)
|
||||
if command in {"accept", "answer", "answered", "connected", "join"}:
|
||||
return _event_item(
|
||||
title=f"{medium}问诊已接通",
|
||||
detail="医生与患者已进入通话",
|
||||
time_text=time_text,
|
||||
tone="success",
|
||||
marker=marker,
|
||||
)
|
||||
if command in {"hangup", "end", "endcall", "finish", "finished"}:
|
||||
return _event_item(
|
||||
title=f"{medium}问诊已结束",
|
||||
detail=duration,
|
||||
time_text=time_text,
|
||||
marker=marker,
|
||||
)
|
||||
if command in {"reject", "refuse", "decline"}:
|
||||
return _event_item(
|
||||
title=f"{medium}问诊未接通",
|
||||
detail="患者已拒绝本次通话邀请",
|
||||
time_text=time_text,
|
||||
tone="warning",
|
||||
marker=marker,
|
||||
)
|
||||
if command in {"timeout", "busy", "linebusy", "cancel", "cancelled", "canceled"}:
|
||||
reasons = {
|
||||
"timeout": "呼叫超时,患者未接听",
|
||||
"busy": "患者当前忙线",
|
||||
"linebusy": "患者当前忙线",
|
||||
"cancel": "通话邀请已取消",
|
||||
"cancelled": "通话邀请已取消",
|
||||
"canceled": "通话邀请已取消",
|
||||
}
|
||||
return _event_item(
|
||||
title=f"{medium}问诊未接通",
|
||||
detail=reasons[command],
|
||||
time_text=time_text,
|
||||
tone="warning",
|
||||
marker=marker,
|
||||
)
|
||||
if command in {"switchtoaudio", "switchaudio"}:
|
||||
return _event_item(
|
||||
title="通话已切换为语音",
|
||||
detail="视频画面已关闭",
|
||||
time_text=time_text,
|
||||
tone="info",
|
||||
marker="音",
|
||||
)
|
||||
if command in {"switchtovideo", "switchvideo"}:
|
||||
return _event_item(
|
||||
title="通话已切换为视频",
|
||||
time_text=time_text,
|
||||
tone="info",
|
||||
marker="视",
|
||||
)
|
||||
return _event_item(
|
||||
title=f"{medium}问诊状态已更新",
|
||||
detail="通话信令已归档",
|
||||
time_text=time_text,
|
||||
tone="info",
|
||||
marker=marker,
|
||||
)
|
||||
|
||||
|
||||
def parse_chat_item(row: Mapping[str, Any], *, include_date: bool = False) -> ChatItem | None:
|
||||
raw_text = _first_value(row, "text", "content", "message", default="")
|
||||
payload = _decode_json_value(raw_text)
|
||||
if isinstance(payload, Mapping):
|
||||
business = _normalized_token(
|
||||
_first_value(payload, "businessID", "businessId", "business_id")
|
||||
)
|
||||
if business == "usertypingstatus":
|
||||
return None
|
||||
event = _system_event_from_payload(payload, row, include_date=include_date)
|
||||
if event is not None:
|
||||
return event
|
||||
|
||||
kind = str(
|
||||
_first_value(row, "msg_type", "message_type", "type", default="text") or "text"
|
||||
).lower()
|
||||
technical_keys = {
|
||||
"businessID",
|
||||
"businessId",
|
||||
"business_id",
|
||||
"actionType",
|
||||
"inviteID",
|
||||
"cmd",
|
||||
"command",
|
||||
}
|
||||
if isinstance(payload, Mapping) and (
|
||||
kind in {"custom", "other", "system"} or technical_keys.intersection(payload)
|
||||
):
|
||||
return _event_item(
|
||||
title="系统状态已同步",
|
||||
detail="技术消息已归档,不影响问诊内容",
|
||||
time_text=_event_time(row, payload, include_date=include_date),
|
||||
)
|
||||
|
||||
doctor_flag = _first_value(row, "is_from_doctor", "from_doctor", default=False)
|
||||
sender_role = _normalized_token(_first_value(row, "role", "sender_type", default=""))
|
||||
from_account = str(_first_value(row, "from_account", "sender", default="") or "").lower()
|
||||
from_doctor = (
|
||||
_truthy(doctor_flag)
|
||||
or sender_role in {"doctor", "staff", "2"}
|
||||
or from_account.startswith("doctor_")
|
||||
)
|
||||
from_ai = sender_role in {"ai", "assistant", "model"} or from_account.startswith(
|
||||
("ai_", "assistant_")
|
||||
)
|
||||
role = "ai" if from_ai else "doctor" if from_doctor else "patient"
|
||||
time_text = _event_time(row, include_date=include_date)
|
||||
|
||||
attachment_labels = {
|
||||
"image": "图片消息",
|
||||
"2": "图片消息",
|
||||
"file": "附件",
|
||||
"3": "附件",
|
||||
"sound": "语音消息",
|
||||
"audio": "语音消息",
|
||||
"video": "视频消息",
|
||||
"location": "位置消息",
|
||||
"face": "表情消息",
|
||||
}
|
||||
if kind in attachment_labels:
|
||||
file_name = str(_first_value(row, "file_name", default="") or "").strip()
|
||||
detail = str(raw_text or "").strip()
|
||||
if kind in {"file", "3"} and file_name:
|
||||
text: Any = f"附件:{file_name}"
|
||||
elif kind == "location" and detail:
|
||||
text = f"位置:{detail}"
|
||||
else:
|
||||
text = attachment_labels[kind]
|
||||
elif isinstance(payload, (Mapping, list)):
|
||||
text = payload
|
||||
else:
|
||||
text = str(raw_text or _first_value(row, "file_name", default="") or "").strip()
|
||||
if text in (None, "", {}, []):
|
||||
return None
|
||||
return ChatItem("message", role, text, "", "", time_text, "", "")
|
||||
@@ -63,8 +63,7 @@ from PySide6.QtWidgets import (
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from .chat_items import ChatItem, parse_chat_item
|
||||
from .diagnosis_editors import FlowLayout
|
||||
from .diagnosis_editors import FlowLayout
|
||||
from .diagnosis_media import shared_image_manager
|
||||
from .diagnosis_terms import FIELD_DICTIONARIES, format_timestamp, shared_terms
|
||||
|
||||
@@ -721,25 +720,6 @@ QFrame#DiagnosisChatBubble[side="doctor"] {
|
||||
border: 1px solid #F0F0F0;
|
||||
border-radius: 8px;
|
||||
}
|
||||
QFrame#DiagnosisChatEvent {
|
||||
background-color: #F7F8FA;
|
||||
border: 1px solid #EDEDEE;
|
||||
border-radius: 8px;
|
||||
}
|
||||
QLabel#DiagnosisChatEventMarker {
|
||||
color: #697386;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
}
|
||||
QLabel#DiagnosisChatEventTitle {
|
||||
color: #374151;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
}
|
||||
QLabel#DiagnosisChatEventDetail {
|
||||
color: #697386;
|
||||
font-size: 12px;
|
||||
}
|
||||
QLabel#DiagnosisChatMeta {
|
||||
color: #606163;
|
||||
font-size: 12px;
|
||||
@@ -3054,16 +3034,25 @@ class ChatPanel(QWidget):
|
||||
widget = item.widget()
|
||||
if widget is not None and widget not in {self.empty, self.toolbar, self.info}:
|
||||
widget.deleteLater()
|
||||
visible_count = 0
|
||||
self.empty.setVisible(not messages)
|
||||
for message in messages:
|
||||
item = parse_chat_item(message, include_date=True)
|
||||
if item is None:
|
||||
continue
|
||||
visible_count += 1
|
||||
if item.variant == "event":
|
||||
self.root.insertWidget(max(2, self.root.count() - 1), self._event_row(item))
|
||||
continue
|
||||
side = "doctor" if item.role == "doctor" else "patient"
|
||||
doctor_flag = _pick(message, "is_from_doctor", default=False)
|
||||
is_doctor = (
|
||||
doctor_flag.strip().lower() not in {"", "0", "false", "no"}
|
||||
if isinstance(doctor_flag, str)
|
||||
else bool(doctor_flag)
|
||||
)
|
||||
side = (
|
||||
"doctor"
|
||||
if is_doctor
|
||||
or str(_pick(message, "role", "sender_type", default="")).lower()
|
||||
in {
|
||||
"doctor",
|
||||
"staff",
|
||||
"2",
|
||||
}
|
||||
else "patient"
|
||||
)
|
||||
row = QWidget()
|
||||
row_layout = QHBoxLayout(row)
|
||||
row_layout.setContentsMargins(0, 0, 0, 0)
|
||||
@@ -3076,14 +3065,13 @@ class ChatPanel(QWidget):
|
||||
bubble_layout.setSpacing(5)
|
||||
meta = QLabel(
|
||||
f"{_text(_pick(message, 'sender_name', 'from_staff_name', 'name'), '患者' if side == 'patient' else '医生')} "
|
||||
f"{item.time_text}"
|
||||
f"{_text(_pick(message, 'create_time', 'time'), '')}"
|
||||
)
|
||||
meta.setObjectName("DiagnosisChatMeta")
|
||||
meta.setTextFormat(Qt.TextFormat.PlainText)
|
||||
message_type = str(
|
||||
_pick(message, "message_type", "msg_type", "type", default="text") or "text"
|
||||
).lower()
|
||||
body_text = _text(_pick(message, "text", "content", "message"), "不支持的消息")
|
||||
body_text = _text(_pick(message, "content", "text", "message"), "不支持的消息")
|
||||
body: QWidget
|
||||
if message_type in {"image", "2"}:
|
||||
target = str(
|
||||
@@ -3123,11 +3111,9 @@ class ChatPanel(QWidget):
|
||||
)
|
||||
body = action
|
||||
else:
|
||||
text = QLabel(body_text)
|
||||
text = QLabel(body_text)
|
||||
text.setObjectName("DiagnosisChatText")
|
||||
text.setTextFormat(Qt.TextFormat.PlainText)
|
||||
text.setWordWrap(True)
|
||||
text.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
|
||||
body = text
|
||||
bubble_layout.addWidget(meta)
|
||||
bubble_layout.addWidget(body)
|
||||
@@ -3138,50 +3124,6 @@ class ChatPanel(QWidget):
|
||||
row_layout.addWidget(bubble)
|
||||
row_layout.addStretch(1)
|
||||
self.root.insertWidget(max(2, self.root.count() - 1), row)
|
||||
self.empty.setVisible(visible_count == 0)
|
||||
|
||||
@staticmethod
|
||||
def _event_row(item: ChatItem) -> QWidget:
|
||||
row = QWidget()
|
||||
layout = QHBoxLayout(row)
|
||||
layout.setContentsMargins(0, 0, 0, 0)
|
||||
layout.addStretch(1)
|
||||
card = QFrame()
|
||||
card.setObjectName("DiagnosisChatEvent")
|
||||
card.setProperty("tone", item.tone)
|
||||
card.setMaximumWidth(620)
|
||||
card.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred)
|
||||
content = QGridLayout(card)
|
||||
content.setContentsMargins(12, 10, 12, 10)
|
||||
content.setHorizontalSpacing(9)
|
||||
content.setVerticalSpacing(4)
|
||||
marker = QLabel(item.marker)
|
||||
marker.setObjectName("DiagnosisChatEventMarker")
|
||||
marker.setTextFormat(Qt.TextFormat.PlainText)
|
||||
marker.setFixedWidth(22)
|
||||
marker.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
content.addWidget(marker, 0, 0)
|
||||
title = QLabel(item.title)
|
||||
title.setObjectName("DiagnosisChatEventTitle")
|
||||
title.setTextFormat(Qt.TextFormat.PlainText)
|
||||
title.setWordWrap(True)
|
||||
content.addWidget(title, 0, 1)
|
||||
content.setColumnStretch(1, 1)
|
||||
if item.time_text:
|
||||
time = QLabel(item.time_text)
|
||||
time.setObjectName("DiagnosisChatMeta")
|
||||
time.setTextFormat(Qt.TextFormat.PlainText)
|
||||
content.addWidget(time, 0, 2, alignment=Qt.AlignmentFlag.AlignRight)
|
||||
if item.detail:
|
||||
detail = QLabel(item.detail)
|
||||
detail.setObjectName("DiagnosisChatEventDetail")
|
||||
detail.setTextFormat(Qt.TextFormat.PlainText)
|
||||
detail.setWordWrap(True)
|
||||
detail.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
|
||||
content.addWidget(detail, 1, 1, 1, 2)
|
||||
layout.addWidget(card, 4)
|
||||
layout.addStretch(1)
|
||||
return row
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
|
||||
@@ -7,7 +7,7 @@ admin-table presentation cannot leak into another workstation page.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable, Iterable, Mapping, Sequence
|
||||
from collections.abc import Iterable, Mapping, Sequence
|
||||
from math import ceil
|
||||
from typing import Any
|
||||
|
||||
@@ -75,9 +75,12 @@ TEXT = QColor("#1A1C1F")
|
||||
SECONDARY = QColor("#606163")
|
||||
PLACEHOLDER = QColor("#8E8F90")
|
||||
_INVALID_INDEX = QModelIndex()
|
||||
# The last two columns form the compact frozen pane. Video status and ending
|
||||
# time occupy separate lines; actions keep two inline links plus 更多, with
|
||||
# the remaining actions in its menu so clinical columns retain more space.
|
||||
# The last two columns are the frozen right-hand pane. They were 120 + 410,
|
||||
# which pinned 532 px of the table. Measured against what they actually hold:
|
||||
# the widest video cell is "暂无通话" at 56 px, and the action cell - two inline
|
||||
# buttons plus 更多, all two-character labels - reports a 145 px sizeHint. So
|
||||
# 265 px of the action column was permanently blank on every row while the data
|
||||
# columns to its left were horizontally scrolling.
|
||||
_TABLE_COLUMN_WIDTHS = (48, 70, 60, 100, 175, 88, 120, 100, 72, 110, 96, 160)
|
||||
_BLUE_COLUMN_WIDTHS = (48, 70, 82, 102, 244, 90, 84, 90, 88, 122, 92, 158)
|
||||
_BLUE_WARNING = QColor("#A9691D")
|
||||
@@ -1606,7 +1609,6 @@ class DiagnosisTableHost(QFrame):
|
||||
self,
|
||||
*,
|
||||
action_policy: Mapping[str, bool] | None = None,
|
||||
video_entry_allowed: Callable[[Any], bool] | None = None,
|
||||
parent: QWidget | None = None,
|
||||
tech_blue: bool = False,
|
||||
) -> None:
|
||||
@@ -1616,7 +1618,6 @@ class DiagnosisTableHost(QFrame):
|
||||
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
|
||||
self.setMinimumHeight(0)
|
||||
self.action_policy = dict(action_policy or {})
|
||||
self.video_entry_allowed = video_entry_allowed
|
||||
self.force_open_prescription = False
|
||||
if tech_blue:
|
||||
self.LEFT_WIDTHS = _BLUE_COLUMN_WIDTHS[:10]
|
||||
@@ -1632,9 +1633,6 @@ class DiagnosisTableHost(QFrame):
|
||||
self._fixed_height_timer.timeout.connect(self._sync_fixed_height)
|
||||
self.main.setObjectName("DiagnosisMainTable")
|
||||
self.fixed.setObjectName("DiagnosisFixedTable")
|
||||
# Index widgets supply their own margins. Inherited item padding would
|
||||
# shrink a 92px video cell to 76px and clip its wrapped status text.
|
||||
self.fixed.setStyleSheet("QTableView#DiagnosisFixedTable::item { padding: 0; }")
|
||||
for view in (self.main, self.fixed):
|
||||
view.setModel(self.model)
|
||||
view.setSelectionModel(self.selection)
|
||||
@@ -1788,11 +1786,11 @@ class DiagnosisTableHost(QFrame):
|
||||
host.hovered_row.connect(self._set_hover_row)
|
||||
layout = QHBoxLayout(host)
|
||||
layout.setContentsMargins(3, 2, 3, 2)
|
||||
layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
video_capable = self.action_policy.get("video_call", False)
|
||||
entry_allowed = self.video_entry_allowed is None or self.video_entry_allowed(record)
|
||||
call_state = video_call_state(record)
|
||||
is_text = appointment_type_value(record) == "text"
|
||||
if video_capable and entry_allowed and _appointment_active(record) and (is_text or call_state == "live"):
|
||||
if video_capable and _appointment_active(record) and (is_text or call_state == "live"):
|
||||
button = QToolButton(host)
|
||||
button.setText("图文沟通" if is_text else "进入视频问诊")
|
||||
button.setProperty("rowLink", "primary")
|
||||
@@ -1805,17 +1803,10 @@ class DiagnosisTableHost(QFrame):
|
||||
button.clicked.connect(
|
||||
lambda _checked=False, item=record: self.video_requested.emit(item)
|
||||
)
|
||||
layout.addWidget(button, 0, Qt.AlignmentFlag.AlignCenter)
|
||||
layout.addWidget(button)
|
||||
else:
|
||||
status = "—"
|
||||
if not entry_allowed:
|
||||
# Match the admin's public status without turning an active
|
||||
# doctor's room into a receiver entry for an unrelated user.
|
||||
if _appointment_active(record) and can_appointment_video(appointment_type_value(record)):
|
||||
status = {"live": "通话中", "pending_room": "接通中", "none": "—"}.get(
|
||||
call_state, first_value(record, "video_call_hint.label", default="—")
|
||||
)
|
||||
elif video_capable:
|
||||
if video_capable:
|
||||
if call_state == "pending_room":
|
||||
status = "等待接通"
|
||||
elif _appointment_active(record):
|
||||
@@ -1825,17 +1816,10 @@ class DiagnosisTableHost(QFrame):
|
||||
_appointment_status(record),
|
||||
"未挂号" if not _has_appointment(record) else "—",
|
||||
)
|
||||
status_text = display_text(status)
|
||||
label = QLabel(status_text.replace(" · ", "\n", 1), host)
|
||||
label = QLabel(display_text(status), host)
|
||||
label.setProperty("fixedMuted", True)
|
||||
label.setTextFormat(Qt.TextFormat.PlainText)
|
||||
label.setToolTip(status_text)
|
||||
label.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
label.setWordWrap(True)
|
||||
# Fill the cell instead of centering the label at its sizeHint:
|
||||
# its wrapped height can grow when the available width changes.
|
||||
label.setMinimumWidth(0)
|
||||
label.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Expanding)
|
||||
layout.addWidget(label)
|
||||
return host
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,646 +0,0 @@
|
||||
"""Verified measurement snapshots and native glucose charts for completed AI replies.
|
||||
|
||||
Charts use recorded observations, never numbers extracted from the generated advice.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import re
|
||||
from collections.abc import Mapping, Sequence
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime, time
|
||||
from typing import Any
|
||||
|
||||
from PySide6.QtCore import QPointF, QRectF, QSize, Qt
|
||||
from PySide6.QtGui import QColor, QMouseEvent, QPainter, QPaintEvent, QPen
|
||||
from PySide6.QtWidgets import (
|
||||
QAbstractItemView,
|
||||
QFrame,
|
||||
QHBoxLayout,
|
||||
QHeaderView,
|
||||
QLabel,
|
||||
QPushButton,
|
||||
QSizePolicy,
|
||||
QTableWidget,
|
||||
QTableWidgetItem,
|
||||
QToolTip,
|
||||
QVBoxLayout,
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from .ai_consult_metric_state import UNKNOWN_COLOR, metric_color
|
||||
|
||||
_NUMERIC = re.compile(r"(?:\d+(?:\.\d+)?|\.\d+)(?:\s*mmol\s*/\s*l)?", re.IGNORECASE)
|
||||
_DATE = re.compile(r"\d{4}-\d{2}-\d{2}")
|
||||
_DATETIME = re.compile(r"\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}(?::\d{2})?")
|
||||
_TIME = re.compile(r"\d{2}:\d{2}(?::\d{2})?")
|
||||
_MISSING = frozenset(("", "—", "--", "-", "未填写", "未记录", "暂无"))
|
||||
_SERIES = (
|
||||
("fasting", "空腹血糖", Qt.PenStyle.SolidLine),
|
||||
("postprandial", "餐后血糖", Qt.PenStyle.DashLine),
|
||||
("other", "其他血糖", Qt.PenStyle.DotLine),
|
||||
)
|
||||
_SERIES_KEYS = {
|
||||
"fasting": ("fasting_blood_sugar", "fasting_glucose"),
|
||||
"postprandial": ("postprandial_blood_sugar", "postprandial_glucose"),
|
||||
"other": ("other_blood_sugar", "other_glucose", "blood_sugar"),
|
||||
}
|
||||
_STATUS_LABELS = {
|
||||
"high": "偏高", "low": "偏低", "normal": "正常", "abnormal": "异常",
|
||||
"warning": "需关注", "0": "正常", "unknown": "未标注",
|
||||
}
|
||||
|
||||
_CARD_QSS = """
|
||||
QFrame#AiConsultGlucoseReport {
|
||||
background: #FFFFFF; border: 1px solid #EDEDEE; border-radius: 10px;
|
||||
}
|
||||
QFrame#AiConsultGlucoseReport QLabel { background: transparent; border: 0; }
|
||||
QFrame#AiConsultGlucoseReport QLabel#AiConsultGlucoseTitle {
|
||||
color: #1A1C1F; font-size: 15px; font-weight: 600;
|
||||
}
|
||||
QFrame#AiConsultGlucoseReport QLabel#AiConsultGlucoseCount,
|
||||
QFrame#AiConsultGlucoseReport QLabel#AiConsultGlucoseSource {
|
||||
color: #606163; font-size: 12px;
|
||||
}
|
||||
QFrame#AiConsultGlucoseReport QLabel#AiConsultGlucoseState {
|
||||
color: #606163; font-size: 13px; padding: 9px 0;
|
||||
}
|
||||
QFrame#AiConsultGlucoseReport QPushButton#AiConsultGlucoseDataToggle {
|
||||
color: #4F63D9; background: #F7F8FC; border: 1px solid #E4E7F4;
|
||||
border-radius: 6px; padding: 5px 9px; font-size: 12px;
|
||||
}
|
||||
QFrame#AiConsultGlucoseReport QPushButton#AiConsultGlucoseDataToggle:hover {
|
||||
background: #EEF1FA;
|
||||
}
|
||||
QFrame#AiConsultGlucoseReport QTableWidget#AiConsultGlucoseTable {
|
||||
color: #1A1C1F; background: #FFFFFF; alternate-background-color: #F7F8FC;
|
||||
border: 1px solid #EDEDEE; border-radius: 4px; gridline-color: #EDEDEE;
|
||||
font-size: 12px; selection-background-color: #EEF1FA; selection-color: #1A1C1F;
|
||||
}
|
||||
QFrame#AiConsultGlucoseReport QHeaderView::section {
|
||||
background: #F7F8FC; color: #606163; border: 0; padding: 6px 3px; font-size: 12px;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class GlucoseReading:
|
||||
"""One source row. Missing series stay absent, including a whole-row gap."""
|
||||
|
||||
recorded_at: datetime
|
||||
fasting: float | None = None
|
||||
postprandial: float | None = None
|
||||
other: float | None = None
|
||||
has_recorded_time: bool = False
|
||||
fasting_status: str = ""
|
||||
postprandial_status: str = ""
|
||||
other_status: str = ""
|
||||
|
||||
@property
|
||||
def readout_count(self) -> int:
|
||||
return sum(value is not None for value in (self.fasting, self.postprandial, self.other))
|
||||
|
||||
@property
|
||||
def time_label(self) -> str:
|
||||
if self.has_recorded_time:
|
||||
pattern = "%Y-%m-%d %H:%M:%S" if self.recorded_at.second else "%Y-%m-%d %H:%M"
|
||||
return self.recorded_at.strftime(pattern)
|
||||
return self.recorded_at.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class GlucoseChartData:
|
||||
readings: tuple[GlucoseReading, ...] = ()
|
||||
diagnosis_id: int = 0
|
||||
patient_id: int = 0
|
||||
excluded_count: int = 0
|
||||
unavailable_reason: str = ""
|
||||
|
||||
@property
|
||||
def available(self) -> bool:
|
||||
return self.readout_count > 0
|
||||
|
||||
@property
|
||||
def readout_count(self) -> int:
|
||||
return sum(reading.readout_count for reading in self.readings)
|
||||
|
||||
@property
|
||||
def record_count(self) -> int:
|
||||
return sum(reading.readout_count > 0 for reading in self.readings)
|
||||
|
||||
@property
|
||||
def date_range(self) -> tuple[date, date] | None:
|
||||
dates = [reading.recorded_at.date() for reading in self.readings if reading.readout_count]
|
||||
return (min(dates), max(dates)) if dates else None
|
||||
|
||||
|
||||
def _exact_owner(value: Any, expected: int) -> bool:
|
||||
return type(value) is int and type(expected) is int and expected > 0 and value == expected
|
||||
|
||||
|
||||
def _patient_matches(source: Mapping[str, Any], patient_id: int) -> bool:
|
||||
if "patient_id" not in source:
|
||||
return True
|
||||
owner = source["patient_id"]
|
||||
return type(owner) is int and owner > 0 and (patient_id <= 0 or owner == patient_id)
|
||||
|
||||
|
||||
def _first(source: Mapping[str, Any], *keys: str) -> Any:
|
||||
for key in keys:
|
||||
value = source.get(key)
|
||||
if value is not None and value != "":
|
||||
return value
|
||||
return None
|
||||
|
||||
|
||||
def _rows(value: Any) -> list[Any]:
|
||||
if isinstance(value, Sequence) and not isinstance(value, (str, bytes, bytearray)):
|
||||
return list(value)
|
||||
return []
|
||||
|
||||
|
||||
def _unit_matches(source: Mapping[str, Any]) -> bool:
|
||||
unit = _first(source, "unit", "glucose_unit", "blood_sugar_unit")
|
||||
if unit is None:
|
||||
return True
|
||||
return isinstance(unit, str) and re.sub(r"\s", "", unit).casefold() == "mmol/l"
|
||||
|
||||
|
||||
def _number(value: Any) -> tuple[float | None, bool]:
|
||||
"""Return (reading, ambiguous); daily-record zero is the unfilled sentinel.
|
||||
|
||||
DailyRecordDialog writes every spinbox, whose zero text is 未填写. The server's
|
||||
BloodRecordLogic likewise includes only >0 glucose values in its trend data.
|
||||
"""
|
||||
|
||||
if value is None:
|
||||
return None, False
|
||||
if isinstance(value, str):
|
||||
value = value.strip()
|
||||
if value in _MISSING:
|
||||
return None, False
|
||||
if not _NUMERIC.fullmatch(value):
|
||||
return None, True
|
||||
value = re.sub(r"\s*mmol\s*/\s*l$", "", value, flags=re.IGNORECASE)
|
||||
elif type(value) not in (int, float):
|
||||
return None, True
|
||||
try:
|
||||
number = float(value)
|
||||
except (OverflowError, TypeError, ValueError):
|
||||
return None, True
|
||||
if not math.isfinite(number) or number < 0:
|
||||
return None, True
|
||||
return (number, False) if number > 0 else (None, False)
|
||||
|
||||
|
||||
def _recorded_at(row: Mapping[str, Any]) -> tuple[datetime, bool] | None:
|
||||
value = _first(row, "record_date", "date", "measured_at", "time_text")
|
||||
if not isinstance(value, str):
|
||||
return None
|
||||
value = value.strip()
|
||||
try:
|
||||
if _DATETIME.fullmatch(value):
|
||||
return datetime.fromisoformat(value), True
|
||||
if not _DATE.fullmatch(value):
|
||||
return None
|
||||
day = date.fromisoformat(value)
|
||||
clock = row.get("record_time")
|
||||
if clock is None or clock == "":
|
||||
# Midnight positions a date-only observation; it is never displayed as a known time.
|
||||
return datetime.combine(day, time.min), False
|
||||
if not isinstance(clock, str) or not _TIME.fullmatch(clock.strip()):
|
||||
return None
|
||||
return datetime.combine(day, time.fromisoformat(clock.strip())), True
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _values(row: Mapping[str, Any], *, legacy: bool) -> tuple[dict[str, float | None], bool, bool]:
|
||||
raw = {field: _first(row, *keys) for field, keys in _SERIES_KEYS.items()}
|
||||
if legacy and all(value is None for value in raw.values()):
|
||||
period = str(_first(row, "period", "time_slot", "meal") or "").strip().casefold()
|
||||
target = "other"
|
||||
if period in {"空腹", "空腹血糖", "fasting"}:
|
||||
target = "fasting"
|
||||
elif period in {
|
||||
"餐后",
|
||||
"餐后血糖",
|
||||
"餐后2小时",
|
||||
"餐后 2 小时",
|
||||
"postprandial",
|
||||
"postprandial_2h",
|
||||
}:
|
||||
target = "postprandial"
|
||||
raw[target] = row.get("value")
|
||||
parsed: dict[str, float | None] = {}
|
||||
ambiguous = False
|
||||
for field, value in raw.items():
|
||||
parsed[field], invalid = _number(value)
|
||||
ambiguous = ambiguous or invalid
|
||||
return parsed, ambiguous, any(value is not None for value in raw.values())
|
||||
|
||||
|
||||
def _statuses(row: Mapping[str, Any], *, legacy: bool) -> dict[str, str]:
|
||||
"""Keep only explicit scalar states on the same verified source row."""
|
||||
statuses = {}
|
||||
for field, keys in _SERIES_KEYS.items():
|
||||
raw = _first(row, *(f"{key}_status" for key in keys))
|
||||
# Generic legacy states belong only to that row's single value/period.
|
||||
if legacy and raw is None and all(_first(row, *keys) is None for keys in _SERIES_KEYS.values()):
|
||||
values, _ambiguous, _has_fields = _values(row, legacy=True)
|
||||
if values[field] is not None:
|
||||
raw = _first(row, "value_status", "glucose_status", "blood_sugar_status", "status")
|
||||
statuses[f"{field}_status"] = str(raw).strip() if type(raw) in (str, int) else ""
|
||||
return statuses
|
||||
|
||||
|
||||
def build_glucose_chart_data(
|
||||
tracking: Any, *, diagnosis_id: int, patient_id: int = 0
|
||||
) -> GlucoseChartData:
|
||||
"""Snapshot only explicitly owned, dated observations without mutating the DTO.
|
||||
|
||||
Production blood_records takes precedence over legacy blood_sugar.entries to
|
||||
avoid double plotting a response containing two representations of the same data.
|
||||
"""
|
||||
|
||||
empty = GlucoseChartData(diagnosis_id=diagnosis_id, patient_id=patient_id)
|
||||
if type(patient_id) is not int or patient_id < 0:
|
||||
return GlucoseChartData(
|
||||
diagnosis_id=diagnosis_id,
|
||||
patient_id=0,
|
||||
unavailable_reason="缺少可核验的患者归属信息。",
|
||||
)
|
||||
if not isinstance(tracking, Mapping):
|
||||
return GlucoseChartData(
|
||||
diagnosis_id=diagnosis_id,
|
||||
patient_id=patient_id,
|
||||
unavailable_reason="尚未加载本诊单的血糖记录。",
|
||||
)
|
||||
if not _exact_owner(tracking.get("diagnosis_id"), diagnosis_id) or not _patient_matches(
|
||||
tracking, patient_id
|
||||
):
|
||||
return GlucoseChartData(
|
||||
diagnosis_id=diagnosis_id,
|
||||
patient_id=patient_id,
|
||||
unavailable_reason="血糖记录未通过本诊单归属校验。",
|
||||
)
|
||||
expected_patient = patient_id or tracking.get("patient_id", 0)
|
||||
legacy = "blood_records" not in tracking
|
||||
section = tracking.get("blood_sugar") if legacy else tracking
|
||||
if not isinstance(section, Mapping):
|
||||
return empty
|
||||
if legacy and (
|
||||
("diagnosis_id" in section and not _exact_owner(section["diagnosis_id"], diagnosis_id))
|
||||
or not _patient_matches(section, expected_patient)
|
||||
):
|
||||
return GlucoseChartData(
|
||||
diagnosis_id=diagnosis_id,
|
||||
patient_id=patient_id,
|
||||
unavailable_reason="血糖记录未通过本诊单归属校验。",
|
||||
)
|
||||
expected_patient = expected_patient or section.get("patient_id", 0)
|
||||
rows = (
|
||||
_rows(_first(section, "entries", "records", "items"))
|
||||
if legacy
|
||||
else _rows(section.get("blood_records"))
|
||||
)
|
||||
readings: list[GlucoseReading] = []
|
||||
excluded = 0
|
||||
for row in rows:
|
||||
if (
|
||||
not isinstance(row, Mapping)
|
||||
or not _exact_owner(row.get("diagnosis_id"), diagnosis_id)
|
||||
or not _patient_matches(row, expected_patient)
|
||||
):
|
||||
excluded += 1
|
||||
continue
|
||||
if not _unit_matches(tracking) or not _unit_matches(section) or not _unit_matches(row):
|
||||
excluded += 1
|
||||
continue
|
||||
recorded = _recorded_at(row)
|
||||
if recorded is None:
|
||||
excluded += 1
|
||||
continue
|
||||
values, ambiguous, has_fields = _values(row, legacy=legacy)
|
||||
excluded += int(ambiguous)
|
||||
if not has_fields:
|
||||
continue
|
||||
readings.append(GlucoseReading(
|
||||
recorded[0], has_recorded_time=recorded[1], **values, **_statuses(row, legacy=legacy)
|
||||
))
|
||||
readings.sort(key=lambda reading: reading.recorded_at) # Stable: same-time rows stay separate.
|
||||
return GlucoseChartData(tuple(readings), diagnosis_id, patient_id, excluded)
|
||||
|
||||
|
||||
def _value_text(value: float | None) -> str:
|
||||
return "—" if value is None else str(value).removesuffix(".0")
|
||||
|
||||
|
||||
def _reading_status(reading: GlucoseReading, field: str) -> str:
|
||||
if getattr(reading, field) is None:
|
||||
return "未记录"
|
||||
status = getattr(reading, f"{field}_status")
|
||||
label = _STATUS_LABELS.get(status.casefold(), status) if status else "未标注"
|
||||
return f"{label}(原始:{status})" if status and label != status else label
|
||||
|
||||
|
||||
def _draw_marker(painter: QPainter, point: QPointF, series: str) -> None:
|
||||
if series in {"postprandial", "diastolic_pressure"}:
|
||||
painter.drawRect(QRectF(point.x() - 3.5, point.y() - 3.5, 7, 7))
|
||||
elif series == "other":
|
||||
painter.drawLine(QPointF(point.x() - 4, point.y()), QPointF(point.x() + 4, point.y()))
|
||||
painter.drawLine(QPointF(point.x(), point.y() - 4), QPointF(point.x(), point.y() + 4))
|
||||
else:
|
||||
painter.drawEllipse(point, 3.5, 3.5)
|
||||
|
||||
|
||||
class GlucoseTrendChart(QWidget):
|
||||
"""An actual-date axis, with gaps and one point for every saved observation."""
|
||||
|
||||
def __init__(self, data: GlucoseChartData, parent: QWidget | None = None) -> None:
|
||||
super().__init__(parent)
|
||||
self.data = data
|
||||
self.setObjectName("AiConsultGlucoseChart")
|
||||
self.setMinimumHeight(210)
|
||||
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
|
||||
self.setMouseTracking(True)
|
||||
self.setAccessibleName("本诊单血糖趋势图,单位 mmol/L")
|
||||
description = []
|
||||
for reading in data.readings:
|
||||
values = ",".join(
|
||||
f"{label} {_value_text(getattr(reading, field))}"
|
||||
+ (" mmol/L" if getattr(reading, field) is not None else "")
|
||||
+ f" · 状态 {_reading_status(reading, field)}"
|
||||
for field, label, _style in _SERIES
|
||||
)
|
||||
if values:
|
||||
description.append(f"{reading.time_label}:{values}")
|
||||
self.setAccessibleDescription(
|
||||
"空腹实线圆点、餐后虚线方点、其他点线十字;红色异常、绿色正常、灰色未记录/未标注。"
|
||||
+ ";".join(description)
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _point_color(reading: GlucoseReading, field: str) -> str:
|
||||
return (
|
||||
metric_color(getattr(reading, f"{field}_status"))
|
||||
if getattr(reading, field) is not None
|
||||
else UNKNOWN_COLOR
|
||||
)
|
||||
|
||||
def sizeHint(self) -> QSize: # noqa: N802 - Qt API
|
||||
return QSize(580, 220)
|
||||
|
||||
def _geometry(self) -> tuple[QRectF, datetime, float, float, float]:
|
||||
plot = QRectF(self.rect()).adjusted(43, 32, -15, -35)
|
||||
dates = [reading.recorded_at for reading in self.data.readings if reading.readout_count]
|
||||
origin = min(dates) if dates else datetime.min
|
||||
span = (max(dates) - origin).total_seconds() if dates else 0.0
|
||||
values = [
|
||||
value
|
||||
for reading in self.data.readings
|
||||
for value in (reading.fasting, reading.postprandial, reading.other)
|
||||
if value is not None
|
||||
]
|
||||
lower, upper = (min(values), max(values)) if values else (0.0, 1.0)
|
||||
padding = max(1.0, (upper - lower) * 0.18, upper * 0.05)
|
||||
padded_upper = upper + padding
|
||||
return (
|
||||
plot,
|
||||
origin,
|
||||
span,
|
||||
max(0.0, lower - padding),
|
||||
padded_upper if math.isfinite(padded_upper) else upper,
|
||||
)
|
||||
|
||||
def _position(
|
||||
self,
|
||||
reading: GlucoseReading,
|
||||
value: float,
|
||||
geometry: tuple[QRectF, datetime, float, float, float] | None = None,
|
||||
) -> QPointF:
|
||||
plot, origin, span, lower, upper = geometry or self._geometry()
|
||||
x = (
|
||||
plot.left() + plot.width() * (reading.recorded_at - origin).total_seconds() / span
|
||||
if span
|
||||
else plot.center().x()
|
||||
)
|
||||
y = plot.bottom() - plot.height() * ((value - lower) / (upper - lower))
|
||||
return QPointF(x, y)
|
||||
|
||||
def _point_tooltip(self, position: QPointF) -> str:
|
||||
hits: list[str] = []
|
||||
geometry = self._geometry()
|
||||
for index, reading in enumerate(self.data.readings, 1):
|
||||
for field, label, _style in _SERIES:
|
||||
value = getattr(reading, field)
|
||||
if value is None:
|
||||
continue
|
||||
point = self._position(reading, value, geometry)
|
||||
if (point.x() - position.x()) ** 2 + (point.y() - position.y()) ** 2 <= 100:
|
||||
hits.append(
|
||||
f"{reading.time_label} · 记录 {index}\n{label} {_value_text(value)} mmol/L"
|
||||
f" · 状态 {_reading_status(reading, field)}"
|
||||
)
|
||||
return "\n\n".join(hits)
|
||||
|
||||
def mouseMoveEvent(self, event: QMouseEvent) -> None: # noqa: N802 - Qt API
|
||||
tip = self._point_tooltip(event.position())
|
||||
if tip:
|
||||
QToolTip.showText(event.globalPosition().toPoint(), tip, self)
|
||||
else:
|
||||
QToolTip.hideText()
|
||||
super().mouseMoveEvent(event)
|
||||
|
||||
def leaveEvent(self, event: Any) -> None: # noqa: N802 - Qt API
|
||||
QToolTip.hideText()
|
||||
super().leaveEvent(event)
|
||||
|
||||
def paintEvent(self, event: QPaintEvent) -> None: # noqa: N802 - Qt API
|
||||
super().paintEvent(event)
|
||||
painter = QPainter(self)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
font = painter.font()
|
||||
font.setPixelSize(11)
|
||||
painter.setFont(font)
|
||||
geometry = self._geometry()
|
||||
plot, _origin, _span, lower, upper = geometry
|
||||
if plot.width() <= 0 or plot.height() <= 0:
|
||||
painter.end()
|
||||
return
|
||||
painter.setPen(QColor("#606163"))
|
||||
painter.drawText(QRectF(0, 0, 55, 20), Qt.AlignmentFlag.AlignLeft, "mmol/L")
|
||||
legend_x = 64.0
|
||||
for field, label, style in _SERIES:
|
||||
if not any(getattr(reading, field) is not None for reading in self.data.readings):
|
||||
continue
|
||||
painter.setPen(QPen(QColor(UNKNOWN_COLOR), 2, style))
|
||||
painter.setBrush(QColor(UNKNOWN_COLOR))
|
||||
painter.drawLine(QPointF(legend_x, 10), QPointF(legend_x + 17, 10))
|
||||
_draw_marker(painter, QPointF(legend_x + 8, 10), field)
|
||||
painter.setPen(QColor(UNKNOWN_COLOR))
|
||||
short_label = label.replace("血糖", "")
|
||||
painter.drawText(
|
||||
QRectF(legend_x + 23, 0, 40, 20), Qt.AlignmentFlag.AlignLeft, short_label
|
||||
)
|
||||
legend_x += 64
|
||||
for tick in range(4):
|
||||
y = plot.bottom() - plot.height() * tick / 3
|
||||
painter.setPen(QPen(QColor("#EDEDEE"), 1))
|
||||
painter.drawLine(QPointF(plot.left(), y), QPointF(plot.right(), y))
|
||||
painter.setPen(QColor("#606163"))
|
||||
painter.drawText(
|
||||
QRectF(0, y - 8, 35, 16),
|
||||
Qt.AlignmentFlag.AlignRight,
|
||||
f"{lower + (upper - lower) * (tick / 3):.1f}",
|
||||
)
|
||||
for field, _label, style in _SERIES:
|
||||
previous: QPointF | None = None
|
||||
for reading in self.data.readings:
|
||||
value = getattr(reading, field)
|
||||
if value is None:
|
||||
previous = None
|
||||
continue
|
||||
point = self._position(reading, value, geometry)
|
||||
if previous is not None:
|
||||
painter.setPen(QPen(QColor(UNKNOWN_COLOR), 2, style))
|
||||
painter.drawLine(previous, point)
|
||||
previous = point
|
||||
# Draw status markers after all neutral line segments in this series.
|
||||
for reading in self.data.readings:
|
||||
value = getattr(reading, field)
|
||||
if value is None:
|
||||
continue
|
||||
color = QColor(self._point_color(reading, field))
|
||||
painter.setPen(QPen(color, 2))
|
||||
painter.setBrush(color)
|
||||
_draw_marker(painter, self._position(reading, value, geometry), field)
|
||||
painter.setPen(QColor("#606163"))
|
||||
dates = sorted(
|
||||
{reading.recorded_at.date() for reading in self.data.readings if reading.readout_count}
|
||||
)
|
||||
if len(dates) == 1:
|
||||
painter.drawText(
|
||||
QRectF(plot.center().x() - 52, plot.bottom() + 9, 104, 18),
|
||||
Qt.AlignmentFlag.AlignCenter,
|
||||
dates[0].isoformat(),
|
||||
)
|
||||
elif dates:
|
||||
painter.drawText(
|
||||
QRectF(plot.left(), plot.bottom() + 9, 104, 18),
|
||||
Qt.AlignmentFlag.AlignLeft,
|
||||
dates[0].isoformat(),
|
||||
)
|
||||
painter.drawText(
|
||||
QRectF(plot.right() - 104, plot.bottom() + 9, 104, 18),
|
||||
Qt.AlignmentFlag.AlignRight,
|
||||
dates[-1].isoformat(),
|
||||
)
|
||||
painter.end()
|
||||
|
||||
|
||||
class GlucoseReportCard(QFrame):
|
||||
def __init__(self, data: GlucoseChartData, parent: QWidget | None = None) -> None:
|
||||
super().__init__(parent)
|
||||
self.data = data
|
||||
self.chart: GlucoseTrendChart | None = None
|
||||
self.toggle_button: QPushButton | None = None
|
||||
self.setObjectName("AiConsultGlucoseReport")
|
||||
self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True)
|
||||
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Maximum)
|
||||
self.setStyleSheet(_CARD_QSS)
|
||||
root = QVBoxLayout(self)
|
||||
root.setContentsMargins(14, 12, 14, 12)
|
||||
root.setSpacing(7)
|
||||
title = QLabel("血糖变化趋势", self)
|
||||
title.setObjectName("AiConsultGlucoseTitle")
|
||||
root.addWidget(title)
|
||||
self.table = QTableWidget(self)
|
||||
self.table.setObjectName("AiConsultGlucoseTable")
|
||||
self.table.hide()
|
||||
if data.available:
|
||||
count = QLabel(f"{data.readout_count} 次测量 · {data.record_count} 条记录", self)
|
||||
count.setObjectName("AiConsultGlucoseCount")
|
||||
root.addWidget(count)
|
||||
self.chart = GlucoseTrendChart(data, self)
|
||||
root.addWidget(self.chart)
|
||||
if data.record_count == 1:
|
||||
single = self._note("仅有 1 条记录,暂不连线。", "AiConsultGlucoseCount")
|
||||
root.addWidget(single)
|
||||
actions = QHBoxLayout()
|
||||
actions.setContentsMargins(0, 0, 0, 0)
|
||||
self.toggle_button = QPushButton("查看原始记录", self)
|
||||
self.toggle_button.setObjectName("AiConsultGlucoseDataToggle")
|
||||
self.toggle_button.setCheckable(True)
|
||||
self.toggle_button.setAccessibleName("查看血糖原始记录")
|
||||
self.toggle_button.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
|
||||
self.toggle_button.toggled.connect(self._toggle_table)
|
||||
actions.addWidget(self.toggle_button)
|
||||
actions.addStretch(1)
|
||||
root.addLayout(actions)
|
||||
self._populate_table()
|
||||
else:
|
||||
root.addWidget(self._note("暂无可绘制的血糖记录", "AiConsultGlucoseState"))
|
||||
reason = data.unavailable_reason or "尚无带明确日期的有效血糖读数。"
|
||||
root.addWidget(self._note(reason, "AiConsultGlucoseSource"))
|
||||
root.addWidget(self.table)
|
||||
source = f"本诊单 #{data.diagnosis_id} 的已记录数据"
|
||||
if data.date_range:
|
||||
start, end = data.date_range
|
||||
source += f" · {start.isoformat()}" + (f" 至 {end.isoformat()}" if end != start else "")
|
||||
source += ";未填写处保留空缺。红色异常、绿色正常、灰色未记录/未标注;状态以原始记录为准。"
|
||||
if data.excluded_count:
|
||||
source += f"\n{data.excluded_count} 条记录含未纳入的内容(归属、日期或读数无法核验)。"
|
||||
root.addWidget(self._note(source, "AiConsultGlucoseSource"))
|
||||
|
||||
def _note(self, text: str, name: str) -> QLabel:
|
||||
label = QLabel(text, self)
|
||||
label.setObjectName(name)
|
||||
label.setTextFormat(Qt.TextFormat.PlainText)
|
||||
label.setWordWrap(True)
|
||||
label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
|
||||
return label
|
||||
|
||||
def _populate_table(self) -> None:
|
||||
table = self.table
|
||||
table.setColumnCount(4)
|
||||
table.setRowCount(len(self.data.readings))
|
||||
table.setHorizontalHeaderLabels(["记录日期 / 时间", "空腹", "餐后", "其他"])
|
||||
table.setAccessibleName("血糖原始记录,读数单位 mmol/L")
|
||||
table.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
|
||||
table.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
|
||||
table.setAlternatingRowColors(True)
|
||||
table.verticalHeader().hide()
|
||||
table.verticalHeader().setDefaultSectionSize(29)
|
||||
table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
|
||||
table.horizontalHeader().setMinimumSectionSize(48)
|
||||
table.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeMode.ResizeToContents)
|
||||
table.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
|
||||
table.setFixedHeight(min(224, 35 + max(1, len(self.data.readings)) * 29))
|
||||
for row_index, reading in enumerate(self.data.readings):
|
||||
values = [
|
||||
reading.time_label,
|
||||
*(_value_text(getattr(reading, field)) for field, _, _ in _SERIES),
|
||||
]
|
||||
for column, text in enumerate(values):
|
||||
item = QTableWidgetItem(text)
|
||||
if column == 0:
|
||||
item.setToolTip(text)
|
||||
else:
|
||||
field = _SERIES[column - 1][0]
|
||||
item.setForeground(QColor(GlucoseTrendChart._point_color(reading, field)))
|
||||
item.setToolTip(
|
||||
(f"{text} mmol/L" if text != "—" else "— · 未记录或读数不明确")
|
||||
+ f" · 状态 {_reading_status(reading, field)}"
|
||||
)
|
||||
table.setItem(row_index, column, item)
|
||||
|
||||
def _toggle_table(self, checked: bool) -> None:
|
||||
self.table.setVisible(checked)
|
||||
if self.toggle_button is not None:
|
||||
self.toggle_button.setText("收起原始记录" if checked else "查看原始记录")
|
||||
self.toggle_button.setAccessibleName(
|
||||
"收起血糖原始记录" if checked else "查看血糖原始记录"
|
||||
)
|
||||
self.updateGeometry()
|
||||
@@ -1,121 +0,0 @@
|
||||
"""从 AI 回复中摘出药名(中药 / 西药),供用药速览与正文高亮使用。
|
||||
|
||||
只用显式词表匹配,不按“…汤/…片”等后缀猜测,宁可漏标也不把普通词误标成药。
|
||||
匹配按长词优先,所以「六味地黄丸」不会被拆成「地黄」。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import NamedTuple
|
||||
|
||||
TCM = "tcm"
|
||||
WESTERN = "western"
|
||||
|
||||
# 中药绿、西药蓝;与侧栏状态卡的完成/进行中色一致。
|
||||
DRUG_COLORS = {
|
||||
TCM: ("#1F7A4D", "#EAF7F0", "#BFE6D0"),
|
||||
WESTERN: ("#3347B8", "#EEF1FA", "#C9D1F3"),
|
||||
}
|
||||
DRUG_STYLES = {
|
||||
kind: f"color: {fg}; background-color: {bg}; font-weight: 700;"
|
||||
for kind, (fg, bg, _border) in DRUG_COLORS.items()
|
||||
}
|
||||
|
||||
# 常用中药饮片(两字及以上,避免单字误配)。
|
||||
_TCM_HERBS = """
|
||||
黄芪 党参 人参 西洋参 太子参 红参 白术 苍术 茯苓 茯神 土茯苓 猪苓 泽泻 薏苡仁 甘草 炙甘草
|
||||
当归 川芎 白芍 赤芍 熟地黄 生地黄 熟地 生地 地黄 山茱萸 山萸肉 牡丹皮 丹皮 丹参 三七 红花 桃仁
|
||||
黄连 黄芩 黄柏 栀子 知母 石膏 天花粉 葛根 麦冬 天冬 玉竹 黄精 石斛 沙参 北沙参 南沙参 百合
|
||||
五味子 枸杞子 女贞子 墨旱莲 菟丝子 桑椹 覆盆子 金樱子 芡实 怀山药 鸡内金 神曲 麦芽 山楂
|
||||
陈皮 青皮 枳实 枳壳 厚朴 半夏 法半夏 姜半夏 竹茹 干姜 炮姜 桂枝 肉桂 附子 制附子
|
||||
柴胡 升麻 防风 荆芥 羌活 独活 秦艽 威灵仙 桑枝 桑叶 菊花 薄荷 蝉蜕 牛蒡子 连翘 金银花 蒲公英
|
||||
板蓝根 大青叶 鱼腥草 败酱草 白花蛇舌草 夏枯草 决明子 车前子 车前草 木通 通草 滑石 萹蓄 瞿麦
|
||||
茵陈 金钱草 虎杖 大黄 芒硝 火麻仁 郁李仁 杏仁 苦杏仁 桔梗 紫菀 款冬花 百部 川贝母 浙贝母 贝母
|
||||
瓜蒌 全瓜蒌 薤白 远志 酸枣仁 柏子仁 夜交藤 首乌藤 合欢皮 龙骨 牡蛎 珍珠母 磁石 天麻 钩藤 石决明
|
||||
地龙 全蝎 蜈蚣 僵蚕 水蛭 土鳖虫 鸡血藤 牛膝 怀牛膝 川牛膝 杜仲 续断 桑寄生 狗脊 骨碎补 补骨脂
|
||||
淫羊藿 仙茅 巴戟天 肉苁蓉 锁阳 益智仁 乌药 小茴香 吴茱萸 木香 香附 郁金 延胡索 川楝子 佛手
|
||||
砂仁 白豆蔻 豆蔻 草豆蔻 藿香 佩兰 苍耳子 辛夷 白芷 细辛 麻黄 紫苏 苏叶 紫苏叶 苏子 紫苏子
|
||||
乌梅 五倍子 诃子 浮小麦 麻黄根 山茱萸肉 何首乌 制何首乌 阿胶 鹿角胶 龟甲 鳖甲 玄参 牛黄 冰片
|
||||
麝香 苏合香 石菖蒲 益母草 泽兰 王不留行 莪术 三棱 乳香 没药 五灵脂 蒲黄 茜草 白茅根 侧柏叶
|
||||
仙鹤草 艾叶 地榆 槐花 小蓟 大蓟 白及 荷叶 绞股蓝 桑白皮 地骨皮 青蒿 银柴胡 胡黄连 白薇
|
||||
苦参 白鲜皮 地肤子 蛇床子 黄药子 海藻 昆布 荔枝核 橘核 鬼箭羽 翻白草 玉米须 冬瓜皮 赤小豆
|
||||
""".split()
|
||||
|
||||
# 常用方剂与中成药(含糖尿病常用)。
|
||||
_TCM_FORMULAS = """
|
||||
六味地黄丸 知柏地黄丸 杞菊地黄丸 麦味地黄丸 金匮肾气丸 济生肾气丸 桂附地黄丸 左归丸 右归丸
|
||||
玉泉丸 消渴丸 参芪降糖颗粒 津力达颗粒 天芪降糖胶囊 渴乐宁胶囊 金芪降糖片 降糖舒胶囊 糖脉康颗粒
|
||||
芪蛭降糖胶囊 木丹颗粒 通心络胶囊 复方丹参滴丸 银杏叶片 血塞通 血栓通 丹参酮 脑心通胶囊
|
||||
补中益气丸 补中益气汤 归脾丸 归脾汤 逍遥丸 逍遥散 加味逍遥丸 丹栀逍遥散 柴胡疏肝散 四逆散
|
||||
四君子汤 六君子汤 香砂六君子汤 参苓白术散 理中丸 附子理中丸 四物汤 八珍汤 十全大补汤 当归补血汤
|
||||
生脉饮 生脉散 玉女煎 白虎加人参汤 白虎汤 葛根芩连汤 黄连解毒汤 半夏泻心汤 大柴胡汤 小柴胡汤
|
||||
血府逐瘀汤 补阳还五汤 桃红四物汤 二陈汤 温胆汤 黄连温胆汤 天麻钩藤饮 镇肝熄风汤 酸枣仁汤
|
||||
天王补心丹 一贯煎 增液汤 沙参麦冬汤 益胃汤 竹叶石膏汤 五苓散 猪苓汤 真武汤 实脾饮 防己黄芪汤
|
||||
玉屏风散 桂枝汤 麻黄汤 银翘散 桑菊饮 藿香正气散 藿香正气水 保和丸 平胃散 二妙丸 三妙丸 四妙丸
|
||||
当归四逆汤 黄芪桂枝五物汤 独活寄生汤 身痛逐瘀汤 大补阴丸 二至丸 交泰丸 安宫牛黄丸 浓缩水丸
|
||||
""".split()
|
||||
|
||||
# 西药(以内分泌、心血管、常见合并用药为主)。
|
||||
_WESTERN = """
|
||||
二甲双胍 盐酸二甲双胍 格列美脲 格列齐特 格列吡嗪 格列本脲 格列喹酮 瑞格列奈 那格列奈 阿卡波糖
|
||||
伏格列波糖 米格列醇 吡格列酮 罗格列酮 西格列汀 沙格列汀 维格列汀 利格列汀 阿格列汀 达格列净
|
||||
恩格列净 卡格列净 艾托格列净 利拉鲁肽 司美格鲁肽 度拉糖肽 艾塞那肽 利司那肽 贝那鲁肽 替尔泊肽
|
||||
胰岛素 门冬胰岛素 赖脯胰岛素 谷赖胰岛素 甘精胰岛素 地特胰岛素 德谷胰岛素 精蛋白锌胰岛素
|
||||
重组人胰岛素 生物合成人胰岛素 预混胰岛素 硝苯地平 氨氯地平 左旋氨氯地平 非洛地平 尼群地平
|
||||
贝尼地平 厄贝沙坦 缬沙坦 氯沙坦 替米沙坦 坎地沙坦 奥美沙坦 沙库巴曲缬沙坦 依那普利 贝那普利
|
||||
培哚普利 卡托普利 福辛普利 美托洛尔 比索洛尔 卡维地洛 阿替洛尔 氢氯噻嗪 吲达帕胺 呋塞米
|
||||
螺内酯 托拉塞米 阿托伐他汀 瑞舒伐他汀 辛伐他汀 普伐他汀 匹伐他汀 依折麦布 非诺贝特 苯扎贝特
|
||||
阿司匹林 氯吡格雷 替格瑞洛 华法林 利伐沙班 达比加群 硫酸氢氯吡格雷 甲钴胺 依帕司他 硫辛酸
|
||||
α-硫辛酸 胰激肽原酶 羟苯磺酸钙 前列地尔 贝前列素钠 别嘌醇 非布司他 苯溴马隆 碳酸氢钠
|
||||
左甲状腺素 甲巯咪唑 丙硫氧嘧啶 奥美拉唑 泮托拉唑 雷贝拉唑 埃索美拉唑 雷尼替丁 法莫替丁
|
||||
多潘立酮 莫沙必利 二甲硅油 乳果糖 阿莫西林 头孢呋辛 左氧氟沙星 莫西沙星 阿奇霉素 布洛芬
|
||||
对乙酰氨基酚 塞来昔布 加巴喷丁 普瑞巴林 碳酸钙 骨化三醇 维生素D 维生素B12 叶酸 硝酸甘油
|
||||
单硝酸异山梨酯 曲美他嗪 地高辛 胺碘酮 坦索罗辛 非那雄胺 西地那非 他达拉非
|
||||
""".split()
|
||||
|
||||
# 西药常带剂型后缀;一起摘出,展示时保留原文写法。
|
||||
_WESTERN_FORM = r"(?:缓释片|控释片|肠溶片|分散片|片|缓释胶囊|肠溶胶囊|胶囊|注射液|注射剂|笔|颗粒)?"
|
||||
|
||||
|
||||
class DrugMention(NamedTuple):
|
||||
start: int
|
||||
end: int
|
||||
# 去掉剂型后缀的药名,用于速览去重;高亮范围仍覆盖原文中的完整写法。
|
||||
name: str
|
||||
kind: str
|
||||
|
||||
|
||||
def _alternation(names: list[str]) -> str:
|
||||
return "|".join(re.escape(name) for name in sorted(set(names), key=len, reverse=True))
|
||||
|
||||
|
||||
# 单一正则、长词优先:中成药 > 西药 > 饮片,保证一个位置只被归入一类。
|
||||
_DRUG_RE = re.compile(
|
||||
rf"(?P<tcm_formula>{_alternation(_TCM_FORMULAS)})"
|
||||
rf"|(?P<western>(?P<western_base>{_alternation(_WESTERN)}){_WESTERN_FORM})"
|
||||
rf"|(?P<herb>{_alternation(_TCM_HERBS)})"
|
||||
)
|
||||
|
||||
|
||||
def find_drug_mentions(text: str) -> list[DrugMention]:
|
||||
"""返回正文中每一处药名的位置与类别(不重叠、按出现顺序)。"""
|
||||
|
||||
mentions: list[DrugMention] = []
|
||||
for match in _DRUG_RE.finditer(str(text or "")):
|
||||
if match.group("western"):
|
||||
mentions.append(DrugMention(match.start(), match.end(), match.group("western_base"), WESTERN))
|
||||
else:
|
||||
mentions.append(DrugMention(match.start(), match.end(), match.group(), TCM))
|
||||
return mentions
|
||||
|
||||
|
||||
def summarize_drugs(text: str) -> dict[str, list[str]]:
|
||||
"""按类别去重汇总药名,保留首次出现的顺序。"""
|
||||
|
||||
summary: dict[str, list[str]] = {TCM: [], WESTERN: []}
|
||||
for mention in find_drug_mentions(text):
|
||||
names = summary[mention.kind]
|
||||
if mention.name not in names:
|
||||
names.append(mention.name)
|
||||
return summary
|
||||
@@ -1,86 +0,0 @@
|
||||
"""Shared display semantics for recorded indicator states; no threshold inference."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
ABNORMAL_COLOR = "#BD4B58"
|
||||
NORMAL_COLOR = "#287B65"
|
||||
UNKNOWN_COLOR = "#697386"
|
||||
|
||||
_ABNORMAL = frozenset(
|
||||
{
|
||||
"high",
|
||||
"low",
|
||||
"abnormal",
|
||||
"warning",
|
||||
"positive",
|
||||
"alert",
|
||||
"偏高",
|
||||
"偏低",
|
||||
"升高",
|
||||
"降低",
|
||||
"高",
|
||||
"低",
|
||||
"异常",
|
||||
"阳性",
|
||||
"警告",
|
||||
"需关注",
|
||||
"临界",
|
||||
"超标",
|
||||
"未达标",
|
||||
"不达标",
|
||||
"控制不佳",
|
||||
"控制欠佳",
|
||||
"不正常",
|
||||
"非正常",
|
||||
"未恢复正常",
|
||||
}
|
||||
)
|
||||
_NORMAL = frozenset(
|
||||
{
|
||||
"normal",
|
||||
"negative",
|
||||
"正常",
|
||||
"阴性",
|
||||
"达标",
|
||||
"已达标",
|
||||
"控制良好",
|
||||
"未见异常",
|
||||
"无异常",
|
||||
"未发现异常",
|
||||
"没有异常",
|
||||
"0",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def metric_state(value: Any) -> str:
|
||||
"""Normalize only explicit source states; an unclassified number stays unknown."""
|
||||
text = str(value).strip().casefold() if type(value) in (str, int) else ""
|
||||
if text in _ABNORMAL:
|
||||
return "abnormal"
|
||||
if text in _NORMAL:
|
||||
return "normal"
|
||||
return "unknown"
|
||||
|
||||
|
||||
def metric_color(value: Any) -> str:
|
||||
return {"abnormal": ABNORMAL_COLOR, "normal": NORMAL_COLOR}.get(
|
||||
metric_state(value), UNKNOWN_COLOR
|
||||
)
|
||||
|
||||
|
||||
def risk_color(value: Any) -> str:
|
||||
return {
|
||||
"high": ABNORMAL_COLOR,
|
||||
"medium": ABNORMAL_COLOR,
|
||||
"low": NORMAL_COLOR,
|
||||
}.get(value if isinstance(value, str) else "", UNKNOWN_COLOR)
|
||||
|
||||
|
||||
def combined_metric_state(values: list[Any]) -> str:
|
||||
states = [metric_state(value) for value in values]
|
||||
if "abnormal" in states:
|
||||
return "abnormal"
|
||||
return "normal" if states and all(state == "normal" for state in states) else "unknown"
|
||||
@@ -1,418 +0,0 @@
|
||||
"""Conservative, display-only emphasis for clinical report text.
|
||||
|
||||
Measurements are identified by their units or an explicit clinical label. Colors
|
||||
come from matching recorded states or explicit local assertions, never numeric
|
||||
thresholds. All source text remains literal HTML text.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import unicodedata
|
||||
from collections.abc import Iterator, Sequence
|
||||
from contextlib import contextmanager
|
||||
from contextvars import ContextVar
|
||||
from dataclasses import dataclass
|
||||
from html import escape
|
||||
|
||||
from .ai_consult_drug_names import DRUG_STYLES, find_drug_mentions
|
||||
|
||||
from .ai_consult_metric_state import (
|
||||
ABNORMAL_COLOR,
|
||||
NORMAL_COLOR,
|
||||
UNKNOWN_COLOR,
|
||||
metric_state,
|
||||
risk_color,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MetricTextState:
|
||||
"""A source field, its displayed reading (including unit), and recorded state."""
|
||||
|
||||
label: str
|
||||
value: str
|
||||
status: str
|
||||
|
||||
|
||||
_METRIC_STATES: ContextVar[tuple[MetricTextState, ...]] = ContextVar(
|
||||
"metric_text_states", default=()
|
||||
)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def metric_text_context(states: Sequence[MetricTextState]) -> Iterator[None]:
|
||||
"""Bind trusted states for synchronous rendering and restore the outer scope."""
|
||||
token = _METRIC_STATES.set(tuple(states))
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
_METRIC_STATES.reset(token)
|
||||
|
||||
|
||||
_NUMBER = r"[+\-−]?(?:\d+(?:\.\d+)?|\.\d+)"
|
||||
_COMPARATOR = r"(?:(?:<=|>=|[<>≤≥≦≧≈=<>=]|小于|大于|不超过|不低于|不高于|低于|高于|约为|约)\s*)?"
|
||||
_VALUE = rf"{_COMPARATOR}{_NUMBER}(?:\s*(?:[–—~~-\-]|至|到)\s*{_NUMBER})?"
|
||||
_VALUE_START = r"(?<![A-Za-z0-9_.+\-−/])"
|
||||
_VALUE_END = r"(?![A-Za-z0-9_.²³/]|\s*[–—~~-\-至到]\s*\d)"
|
||||
_UNIT = (
|
||||
r"(?:mL\s*/\s*min(?:\s*/\s*1\.73\s*m(?:²|2|\^2))?"
|
||||
r"|(?:mmol|[μµu]mol)\s*/\s*L"
|
||||
r"|mmol\s*/\s*mol"
|
||||
r"|mg\s*/\s*(?:dL|mmol|g(?:Cr)?|L)"
|
||||
r"|[μµu]g\s*/\s*(?:g|mg|L)"
|
||||
r"|(?:ng|pg)\s*/\s*mL"
|
||||
r"|(?:g|IU|U|mIU|mU)\s*/\s*L"
|
||||
r"|g\s*/\s*dL"
|
||||
r"|[μµu]IU\s*/\s*mL"
|
||||
r"|kg\s*/\s*m(?:²|2|\^2)"
|
||||
r"|mmHg|bpm|次\s*/\s*(?:分钟|分|min)"
|
||||
r"|kg|cm|°\s*C|℃)"
|
||||
)
|
||||
_UNIT_END = r"(?![A-Za-z0-9_²³/])"
|
||||
_PRESSURE_VALUE = rf"{_COMPARATOR}{_NUMBER}\s*[//]\s*{_NUMBER}\s*mmHg"
|
||||
_UNIT_VALUE = rf"(?:{_PRESSURE_VALUE}|{_VALUE}\s*{_UNIT}){_UNIT_END}"
|
||||
_UNIT_RE = re.compile(rf"{_VALUE_START}(?P<value>{_UNIT_VALUE})", re.IGNORECASE)
|
||||
|
||||
# A label is necessary when a number has no unit, or directly follows an ASCII
|
||||
# label (a general numeric boundary intentionally rejects IDs such as abc123).
|
||||
_LABEL_GAP = r"\s*[))]?\s*(?:(?:[::=]|为|约为|是|达到|下降至|降至|上升至|升至)\s*)?"
|
||||
_LABEL_START = r"(?<![A-Za-z0-9_])"
|
||||
_UNIT_LABELS = (
|
||||
r"(?:fasting(?:[_ ]blood[_ ]sugar|[_ ](?:blood[_ ])?glucose)?|"
|
||||
r"postprandial(?:[_ ]blood[_ ](?:sugar|glucose))?|"
|
||||
r"FPG|FBG|PBG|PPG|TC|TG|LDL(?:-C)?|HDL(?:-C)?|UA|Scr|Cr|"
|
||||
r"UACR|ACR|ALT|AST|SBP|DBP|BP|HR|eGFR|BMI|heart_rate|height|weight)"
|
||||
)
|
||||
_LABELED_UNIT_RE = re.compile(
|
||||
rf"{_LABEL_START}{_UNIT_LABELS}{_LABEL_GAP}(?P<value>{_UNIT_VALUE})",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
_UNITLESS_RE = re.compile(
|
||||
rf"{_LABEL_START}(?:BMI|体质指数|体质量指数|体重指数|eGFR|"
|
||||
rf"估算肾小球滤过率|肾小球滤过率|heart_rate|心率){_LABEL_GAP}"
|
||||
rf"(?P<value>{_VALUE}){_VALUE_END}",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
_HEIGHT_RE = re.compile(
|
||||
rf"{_LABEL_START}(?:height|身高){_LABEL_GAP}"
|
||||
rf"(?P<value>{_VALUE}\s*(?:cm|m|厘米|米)){_UNIT_END}",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
_PERCENT_LABEL = (
|
||||
r"(?:HbA1c|glycated[_ ]h(?:a)?emoglobin|糖化血红蛋白(?:水平)?|"
|
||||
r"SpO2|SaO2|血氧饱和度|血氧)"
|
||||
)
|
||||
_LABELED_PERCENT_RE = re.compile(
|
||||
rf"{_LABEL_START}{_PERCENT_LABEL}{_LABEL_GAP}"
|
||||
rf"(?P<value>{_VALUE}\s*[%%]){_VALUE_END}",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
_PERCENT_RE = re.compile(rf"{_VALUE_START}(?P<value>{_VALUE}\s*[%%]){_VALUE_END}")
|
||||
_PERCENT_LABEL_RE = re.compile(rf"{_LABEL_START}{_PERCENT_LABEL}", re.IGNORECASE)
|
||||
_UNRELATED_PERCENT_RE = re.compile(
|
||||
r"占比|比例|概率|风险|增长|下降|降低|上升|提高|提升|改善|减轻|"
|
||||
r"有效率|发生率|依从|完成率|百分比|报销|费用|患者|人群"
|
||||
)
|
||||
|
||||
_CLAUSE_BOUNDARY_RE = re.compile(r"[,,。;;!!??\n]")
|
||||
_SENTENCE_BOUNDARY_RE = re.compile(r"[。;;!!??\n]")
|
||||
_REFERENCE_RE = re.compile(
|
||||
r"目标|参考|理想|阈值|正常(?:值|范围)|\b(?:targets?|reference|ideal|thresholds?)\b",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
_CURRENT_RE = re.compile(
|
||||
r"当前|现测|本次|实测|测得|检测结果|实际|目前|现值|\b(?:current|actual|measured)\b",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
_REFERENCE_SUFFIX_RE = re.compile(
|
||||
r"^\s*[((](?:目标|参考|理想|阈值|正常)(?:值|范围)?[))]"
|
||||
r"|^\s*\((?:target|reference|ideal|threshold)(?:\s*(?:value|range))?\)",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
_NORMAL_STATUS = (
|
||||
r"(?:未见|未发现|没有|无)(?:其他)?(?:明显|显著)?异常"
|
||||
r"|(?:基本|大致)?正常|(?:已|完全)?达标|控制良好"
|
||||
r"|\b(?:normal|negative)\b"
|
||||
)
|
||||
_ABNORMAL_STATUS = (
|
||||
r"(?:尚未完全|尚未|未完全|未能|不完全|未|不)达标"
|
||||
r"|不正常|非正常|未恢复正常"
|
||||
r"|(?:严重|明显|显著)?异常|控制不佳|控制欠佳"
|
||||
r"|\b(?:not normal|abnormal|warning|high|low|positive|alert)\b"
|
||||
)
|
||||
_CAUTION_STATUS = r"(?:轻度|轻微|明显|显著|略)?(?:偏高|偏低|升高|降低)|临界|超标"
|
||||
_STATUS_RE = re.compile(
|
||||
rf"(?P<abnormal>{_ABNORMAL_STATUS})|(?P<normal>{_NORMAL_STATUS})"
|
||||
rf"|(?P<caution>{_CAUTION_STATUS})",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
_RISK_STATUS_RE = re.compile(r"高风险|中风险|低风险")
|
||||
_MISSING_RE = re.compile(
|
||||
r"未记录|无记录|未检测|未测量|未检查|未提供|未填写|未录入|未获取|暂无数据|"
|
||||
r"暂无|缺失|未知|待测|未测|未查|未做|无数据|"
|
||||
r"\b(?:not recorded|not measured|not available|unrecorded|unknown|missing|N/A)\b",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
_NON_ASSERTIVE_RE = re.compile(
|
||||
r"排除|排查|除外|警惕|预防|避免|防止|谨防|建议|可能|疑似|怀疑|"
|
||||
r"是否|待排|待查|如果|假如|一旦|若|如|风险|倾向|有望|争取|力争|以期|"
|
||||
r"应当|应该|应使|应将|应控制|应达到|应达标|需使|需将|需达到|以达到"
|
||||
r"|\b(?:possible|possibly|may|might|should|if|risk|exclude|suspected)\b",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
_NEGATED_PREFIX_RE = re.compile(
|
||||
r"(?:尚未|未见|未发现|未达到|未能达到|未能|不能|无法|难以|未|没有|无|不|非)"
|
||||
r"(?:明显|显著|完全|充分)?$"
|
||||
)
|
||||
_MISSING_PLACEHOLDER_RE = re.compile(r"\s*(?:[—–--]+|/|null|none)\s*\Z", re.IGNORECASE)
|
||||
|
||||
# An alias identifies a source field, never a diagnosis. More specific aliases
|
||||
# win over contained words, so 空腹血糖 cannot accidentally match generic 血糖.
|
||||
_FIELD_ALIASES = (
|
||||
("hba1c", r"HbA1c|glycated[_ ]h(?:a)?emoglobin|糖化血红蛋白(?:水平)?"),
|
||||
("fasting", r"fasting(?:[_ ]blood[_ ]sugar|[_ ](?:blood[_ ])?glucose)?|FPG|FBG|空腹血糖|空腹"),
|
||||
(
|
||||
"postprandial",
|
||||
r"postprandial(?:[_ ]blood[_ ](?:sugar|glucose))?|PBG|PPG|餐后(?:2|两|二)?(?:小时)?血糖|餐后",
|
||||
),
|
||||
("random_glucose", r"random[_ ](?:blood[_ ])?(?:sugar|glucose)|随机血糖"),
|
||||
("glucose", r"blood[_ ](?:sugar|glucose)|glucose|血糖"),
|
||||
("blood_pressure", r"blood[_ ]pressure|BP|血压"),
|
||||
("systolic", r"systolic(?:[_ ](?:blood[_ ])?pressure)?|SBP|收缩压"),
|
||||
("diastolic", r"diastolic(?:[_ ](?:blood[_ ])?pressure)?|DBP|舒张压"),
|
||||
("bmi", r"BMI|体质指数|体质量指数|体重指数"),
|
||||
("heart_rate", r"heart[_ ]rate|HR|心率"),
|
||||
("height", r"height|身高"),
|
||||
("weight", r"weight|体重"),
|
||||
("ldl", r"LDL(?:[-_ ]C)?|低密度脂蛋白(?:胆固醇)?"),
|
||||
("hdl", r"HDL(?:[-_ ]C)?|高密度脂蛋白(?:胆固醇)?"),
|
||||
("cholesterol", r"TC|total[_ ]cholesterol|总胆固醇"),
|
||||
("triglycerides", r"TG|triglycerides?|甘油三酯"),
|
||||
("egfr", r"eGFR|估算肾小球滤过率|肾小球滤过率"),
|
||||
("uacr", r"UACR|ACR|尿白蛋白(?:与)?肌酐比(?:值)?"),
|
||||
("creatinine", r"Scr|Cr|creatinine|血(?:清)?肌酐|肌酐"),
|
||||
("uric_acid", r"UA|uric[_ ]acid|尿酸"),
|
||||
("alt", r"ALT|丙氨酸氨基转移酶|谷丙转氨酶"),
|
||||
("ast", r"AST|天门冬氨酸氨基转移酶|谷草转氨酶"),
|
||||
("spo2", r"SpO2|SaO2|血氧饱和度|血氧"),
|
||||
("temperature", r"temperature|体温"),
|
||||
("hemoglobin", r"h(?:a)?emoglobin|血红蛋白"),
|
||||
)
|
||||
_FIELD_PATTERNS = tuple(
|
||||
(field, re.compile(rf"{_LABEL_START}(?:{aliases})(?![A-Za-z_])", re.IGNORECASE))
|
||||
for field, aliases in _FIELD_ALIASES
|
||||
)
|
||||
_STANDALONE_VALUE_RE = re.compile(rf"\s*(?P<value>{_VALUE}(?:\s*[%%])?)\s*\Z")
|
||||
|
||||
|
||||
def _display_key(value: str) -> str:
|
||||
return re.sub(r"\s+", "", unicodedata.normalize("NFKC", value)).casefold()
|
||||
|
||||
|
||||
def _field_mentions(text: str) -> list[tuple[int, int, str]]:
|
||||
mentions = [
|
||||
(match.start(), match.end(), field)
|
||||
for field, pattern in _FIELD_PATTERNS
|
||||
for match in pattern.finditer(text)
|
||||
]
|
||||
# Unknown source labels can still bind to an exact label in the rendered text.
|
||||
for state in _METRIC_STATES.get():
|
||||
label = state.label.strip()
|
||||
if not label or any(pattern.search(label) for _, pattern in _FIELD_PATTERNS):
|
||||
continue
|
||||
pattern = re.compile(rf"{_LABEL_START}{re.escape(label)}(?![A-Za-z_])", re.IGNORECASE)
|
||||
mentions.extend((m.start(), m.end(), _display_key(label)) for m in pattern.finditer(text))
|
||||
mentions.sort(key=lambda item: (item[0], -(item[1] - item[0])))
|
||||
selected: list[tuple[int, int, str]] = []
|
||||
for mention in mentions:
|
||||
if not selected or mention[0] >= selected[-1][1]:
|
||||
selected.append(mention)
|
||||
return selected
|
||||
|
||||
|
||||
def _field_key(label: str) -> str:
|
||||
mentions = _field_mentions(label)
|
||||
return mentions[-1][2] if mentions else _display_key(label)
|
||||
|
||||
|
||||
def _reading_field(text: str, start: int, metric_label: str) -> str:
|
||||
_, clause_start = _clause(text, start)
|
||||
mentions = _field_mentions(text[clause_start:start])
|
||||
return mentions[-1][2] if mentions else _field_key(metric_label)
|
||||
|
||||
|
||||
def _recorded_color(text: str, start: int, end: int, metric_label: str) -> str | None:
|
||||
field = _reading_field(text, start, metric_label)
|
||||
if not field:
|
||||
return None
|
||||
reading = _display_key(text[start:end])
|
||||
states = {
|
||||
metric_state(state.status)
|
||||
for state in _METRIC_STATES.get()
|
||||
if _field_key(state.label) == field and _display_key(state.value) == reading
|
||||
}
|
||||
if not states:
|
||||
return None
|
||||
if len(states) != 1:
|
||||
return UNKNOWN_COLOR
|
||||
return {"normal": NORMAL_COLOR, "abnormal": ABNORMAL_COLOR}.get(states.pop(), UNKNOWN_COLOR)
|
||||
|
||||
|
||||
def _clause(text: str, position: int) -> tuple[str, int]:
|
||||
start = 0
|
||||
for boundary in _CLAUSE_BOUNDARY_RE.finditer(text, 0, position):
|
||||
start = boundary.end()
|
||||
boundary = _CLAUSE_BOUNDARY_RE.search(text, position)
|
||||
end = boundary.start() if boundary else len(text)
|
||||
return text[start:end], start
|
||||
|
||||
|
||||
def _is_reference(text: str, start: int, end: int) -> bool:
|
||||
clause, clause_start = _clause(text, start)
|
||||
prefix = clause[: start - clause_start][-64:]
|
||||
references = list(_REFERENCE_RE.finditer(prefix))
|
||||
current = list(_CURRENT_RE.finditer(prefix))
|
||||
if references and (not current or references[-1].start() > current[-1].start()):
|
||||
return True
|
||||
return bool(_REFERENCE_SUFFIX_RE.match(text[end:]))
|
||||
|
||||
|
||||
def _is_reference_percent(text: str, start: int, end: int) -> bool:
|
||||
if not _is_reference(text, start, end):
|
||||
return False
|
||||
sentence_start = 0
|
||||
for boundary in _SENTENCE_BOUNDARY_RE.finditer(text, 0, start):
|
||||
sentence_start = boundary.end()
|
||||
prefix = text[max(sentence_start, start - 100) : start]
|
||||
labels = list(_PERCENT_LABEL_RE.finditer(prefix))
|
||||
if not labels:
|
||||
return False
|
||||
return not _UNRELATED_PERCENT_RE.search(prefix[labels[-1].end() :])
|
||||
|
||||
|
||||
def _status_color(text: str, match: re.Match[str]) -> str | None:
|
||||
clause, clause_start = _clause(text, match.start())
|
||||
if _NON_ASSERTIVE_RE.search(clause):
|
||||
return None
|
||||
prefix = text[max(clause_start, match.start() - 12) : match.start()]
|
||||
if _NEGATED_PREFIX_RE.search(prefix):
|
||||
return None
|
||||
if text[match.end() :].startswith(("率", "值", "范围", "标准", "目标", "阈值")):
|
||||
return None
|
||||
if match.lastgroup == "normal":
|
||||
return NORMAL_COLOR
|
||||
return ABNORMAL_COLOR
|
||||
|
||||
|
||||
def _local_color(
|
||||
text: str,
|
||||
start: int,
|
||||
end: int,
|
||||
readings: Sequence[tuple[int, int]],
|
||||
statuses: Sequence[tuple[re.Match[str], str]],
|
||||
metric_label: str,
|
||||
) -> str:
|
||||
clause, clause_start = _clause(text, start)
|
||||
field = _reading_field(text, start, metric_label)
|
||||
colors: set[str] = set()
|
||||
for status, color in statuses:
|
||||
if not clause_start <= status.start() < clause_start + len(clause):
|
||||
continue
|
||||
left, right = (end, status.start()) if status.start() >= end else (status.end(), start)
|
||||
if right < left or right - left > 32:
|
||||
continue
|
||||
if any(left <= other_start < right for other_start, _ in readings):
|
||||
continue
|
||||
# A status belonging to a new field in the same clause must not leak.
|
||||
mentions = _field_mentions(text[left:right])
|
||||
if any(other_field != field for _, _, other_field in mentions):
|
||||
continue
|
||||
colors.add(color)
|
||||
return colors.pop() if len(colors) == 1 else UNKNOWN_COLOR
|
||||
|
||||
|
||||
def metric_text_html(text: str, *, metric_label: str = "") -> str:
|
||||
"""Return escaped, whitespace-preserving HTML with conservative emphasis.
|
||||
|
||||
Clinical values retain their original range, comparator, unit and spelling.
|
||||
A bound state requires the same field alias and displayed reading, including
|
||||
comparator, range and unit. Without a matching record only an asserted local
|
||||
status can classify a reading. References and unclassified values stay gray.
|
||||
Newlines follow Qt plain text; incoming HTML is always shown literally.
|
||||
"""
|
||||
text = text.replace("\r\n", "\n").replace("\r", "\n")
|
||||
spans: list[tuple[int, int, str]] = []
|
||||
candidates: set[tuple[int, int]] = set()
|
||||
for pattern in (_UNIT_RE, _LABELED_UNIT_RE, _UNITLESS_RE, _HEIGHT_RE, _LABELED_PERCENT_RE):
|
||||
for match in pattern.finditer(text):
|
||||
candidates.add(match.span("value"))
|
||||
for match in _PERCENT_RE.finditer(text):
|
||||
start, end = match.span("value")
|
||||
clause, clause_start = _clause(text, start)
|
||||
hinted_percent = _field_key(metric_label) in {
|
||||
"hba1c",
|
||||
"spo2",
|
||||
} and not _UNRELATED_PERCENT_RE.search(clause[: start - clause_start])
|
||||
if hinted_percent or _is_reference_percent(text, start, end):
|
||||
candidates.add((start, end))
|
||||
if metric_label and (standalone := _STANDALONE_VALUE_RE.fullmatch(text)):
|
||||
candidates.add(standalone.span("value"))
|
||||
|
||||
readings: list[tuple[int, int]] = []
|
||||
for start, end in sorted(candidates, key=lambda span: (span[0], -span[1])):
|
||||
if not readings or start >= readings[-1][1]:
|
||||
readings.append((start, end))
|
||||
statuses = [
|
||||
(match, color)
|
||||
for match in _STATUS_RE.finditer(text)
|
||||
if (color := _status_color(text, match))
|
||||
]
|
||||
for start, end in readings:
|
||||
if _is_reference(text, start, end) or _REFERENCE_RE.search(metric_label):
|
||||
color = UNKNOWN_COLOR
|
||||
else:
|
||||
color = _recorded_color(text, start, end, metric_label)
|
||||
if color is None:
|
||||
color = _local_color(text, start, end, readings, statuses, metric_label)
|
||||
spans.append((start, end, color))
|
||||
spans.extend((match.start(), match.end(), color) for match, color in statuses)
|
||||
for match in _RISK_STATUS_RE.finditer(text):
|
||||
clause, clause_start = _clause(text, match.start())
|
||||
prefix = text[max(clause_start, match.start() - 12) : match.start()]
|
||||
if (
|
||||
_NON_ASSERTIVE_RE.search(clause.replace("风险", ""))
|
||||
or _NEGATED_PREFIX_RE.search(prefix)
|
||||
or _REFERENCE_RE.search(clause)
|
||||
):
|
||||
continue
|
||||
level = {"高风险": "high", "中风险": "medium", "低风险": "low"}[match.group()]
|
||||
spans.append((match.start(), match.end(), risk_color(level)))
|
||||
spans.extend(
|
||||
(match.start(), match.end(), UNKNOWN_COLOR) for match in _MISSING_RE.finditer(text)
|
||||
)
|
||||
if metric_label and _MISSING_PLACEHOLDER_RE.fullmatch(text):
|
||||
spans.append((0, len(text), UNKNOWN_COLOR))
|
||||
|
||||
# 药名高亮:中药绿、西药蓝,浅底加粗,让医生在正文里一眼看到用药。
|
||||
styled = [(start, end, f"color: {color}; font-weight: 600;") for start, end, color in spans]
|
||||
styled.extend(
|
||||
(mention.start, mention.end, DRUG_STYLES[mention.kind])
|
||||
for mention in find_drug_mentions(text)
|
||||
)
|
||||
|
||||
# Prefer a full reading over a contained unitless value, then consume each
|
||||
# original character once. Generated markup is never scanned by a regex.
|
||||
styled.sort(key=lambda span: (span[0], -(span[1] - span[0])))
|
||||
pieces = ['<span style="white-space: pre-wrap;">']
|
||||
position = 0
|
||||
for start, end, style in styled:
|
||||
if start < position:
|
||||
continue
|
||||
pieces.append(escape(text[position:start]))
|
||||
pieces.append(f'<span style="{style}">{escape(text[start:end])}</span>')
|
||||
position = end
|
||||
pieces.append(escape(text[position:]))
|
||||
pieces.append("</span>")
|
||||
return "".join(pieces).replace("\n", "<br>")
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user