Compare commits
59
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
537c52c1b9 | ||
|
|
4d1a8683e5 | ||
|
|
7458ff03a7 | ||
|
|
19159668fb | ||
|
|
d199d66f8c | ||
|
|
5ea3417e4c | ||
|
|
580444731b | ||
|
|
e1a3638b35 | ||
|
|
1bd1224af7 | ||
|
|
63152179bd | ||
|
|
b8f3c049be | ||
|
|
7189f33812 | ||
|
|
14936cb28a | ||
|
|
63e52f6273 | ||
|
|
91e35cb905 | ||
|
|
1e165a7894 | ||
|
|
887ab3e839 | ||
|
|
4ae38b45ed | ||
|
|
fdca55853a | ||
|
|
9dde9a34b5 | ||
|
|
dc18098566 | ||
|
|
562f8d6ce4 | ||
|
|
5374f05c80 | ||
|
|
18a0989c00 | ||
|
|
b675822377 | ||
|
|
c6df345138 | ||
|
|
365b16c14d | ||
|
|
b55f30753c | ||
|
|
0eeb572f0f | ||
|
|
fce7c78de3 | ||
|
|
630318b9ca | ||
|
|
7c916d8053 | ||
|
|
c22be5d586 | ||
|
|
6ef56bd8fb | ||
|
|
82a91858f9 | ||
|
|
954e6f00d0 | ||
|
|
b8f66e2b00 | ||
|
|
dfe5768cd2 | ||
|
|
3451f43c22 | ||
|
|
90b9fff76a | ||
|
|
dc5467cfa7 | ||
|
|
e825109d90 | ||
|
|
00bad051da | ||
|
|
2019f9dca1 | ||
|
|
e4d788ed32 | ||
|
|
301c04ca90 | ||
|
|
be79e09c83 | ||
|
|
db6d327e91 | ||
|
|
0dc41a1507 | ||
|
|
378bf32069 | ||
|
|
08892f4270 | ||
|
|
775d955577 | ||
|
|
e3a73dd29d | ||
|
|
2ea462aa31 | ||
|
|
7665725766 | ||
|
|
b9ac9a6635 | ||
|
|
de97f00597 | ||
|
|
c737960d4f | ||
|
|
875c1049c0 |
@@ -16,7 +16,15 @@
|
||||
"Bash(git *)",
|
||||
"Bash(tail -c 100000 /Users/long/.claude/projects/-Users-long-Work-zyt/7be9f770-afc3-497d-87a3-2ffa1fbe3fd1.jsonl)",
|
||||
"Read(//tmp/**)",
|
||||
"Bash(npx --no-install vue-tsc --noEmit)"
|
||||
"Bash(npx --no-install vue-tsc --noEmit)",
|
||||
"Bash(python -c \"import paramiko; print\\(paramiko.__version__\\)\")",
|
||||
"Bash(RH='[IP]' RP='xx12369.36aa!' python rssh.py)",
|
||||
"Bash(nslookup xt.zhenyangtang.com.cn)",
|
||||
"Bash(sed -i \"s/c.connect\\(os.environ\\\\['RH'\\\\]/import socket; c.connect\\(socket.gethostbyname\\('xt.zhenyangtang.com.cn'\\)/\" rssh.py)",
|
||||
"Bash(RP='xx12369.36aa!' python rssh.py)",
|
||||
"Bash(php -l app/common/service/esign/DoctorEsignIdentityService.php)",
|
||||
"Bash(php tests/DoctorEsignIdentityTest.php)",
|
||||
"Bash(php tests/PrescriptionEsignFlowTest.php)"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,6 +28,8 @@ app/.test-tmp-stream/
|
||||
/.codex
|
||||
/.agents
|
||||
/server/.spool
|
||||
/server/storage/esign/
|
||||
/server/.env.esign.local
|
||||
# Generated ancient-books search indexes; the source corpus is tracked.
|
||||
/server/knowledge/tcm-ancient-books-index.json
|
||||
/server/knowledge/tcm-ancient-books-index/
|
||||
@@ -36,3 +38,4 @@ app/.test-tmp-stream/
|
||||
TUICallKit-Vue3/.env
|
||||
/.codegraph
|
||||
app/artifacts/
|
||||
/artifacts
|
||||
|
||||
@@ -272,10 +272,17 @@ const { proxy } = getCurrentInstance()
|
||||
let targetUserID = '';
|
||||
let currentUserID = ''; // 当前登录用户ID
|
||||
let scrollTimer = null; // 滚动定时器
|
||||
/** 微信小程序:从系统后台回前台时刷新 IM/TUICall,避免无法接通视频 */
|
||||
let unsubscribeWxAppShow = null;
|
||||
/** 微信小程序:从系统后台回前台时检查 IM/TUICall 链路,异常时才重建 */
|
||||
let wxAppShowHandler = null;
|
||||
let allowChatForegroundRelogin = false;
|
||||
let foregroundReloginTimer = null;
|
||||
let pageUnloaded = false;
|
||||
/** TUICallEngine 当前绑定的 IM 实例;与页面 chat 不一致说明引擎挂在已销毁的旧实例上 */
|
||||
let callKitBoundChat = null;
|
||||
/** 串行化 TUICall 重绑 / IM 重登:并发执行时后一次 destroyed 会销毁前一次刚建好的引擎 */
|
||||
let callKitInitChain = Promise.resolve();
|
||||
let reloginTask = null;
|
||||
const CALL_PAGE_ROUTE = 'TUICallKit/src/Components/TUICallKit';
|
||||
/** 避免 onUnload 重复上报离开 */
|
||||
let patientLeaveNotified = false;
|
||||
|
||||
@@ -569,8 +576,44 @@ const { proxy } = getCurrentInstance()
|
||||
uni.setStorageSync('CallManager', userId)
|
||||
// TUICallKit 必须在 TIM chat 登录成功后再 init,且必须传入 tim,否则无法接收通话信令(聊天正常、视频接不到)
|
||||
}
|
||||
function isCallIdle() {
|
||||
try {
|
||||
const status = TUIStore?.getData?.(StoreName.CALL, NAME.CALL_STATUS);
|
||||
return status == null || status === CallStatus.IDLE;
|
||||
} catch (_) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 等 IM 进入 SDK_READY。TUICallEngine 登录时若 IM 未 ready 只等 2 秒,超时即登录失败;
|
||||
* 而 TUICallKitAPI.init 不 await 登录,失败被吞掉、也不重试,之后的来电就全部收不到。
|
||||
*/
|
||||
function waitForIMSdkReady(imChat, timeoutMs = 8000) {
|
||||
if (!imChat) return Promise.resolve(false);
|
||||
if (imChat.isReady?.()) return Promise.resolve(true);
|
||||
return new Promise((resolve) => {
|
||||
let timer = null;
|
||||
const finish = () => {
|
||||
clearTimeout(timer);
|
||||
try { imChat.off(TencentCloudChat.EVENT.SDK_READY, finish); } catch (_) {}
|
||||
resolve(!!imChat.isReady?.());
|
||||
};
|
||||
imChat.on(TencentCloudChat.EVENT.SDK_READY, finish);
|
||||
timer = setTimeout(finish, timeoutMs);
|
||||
});
|
||||
}
|
||||
/** 与当前页 IM 实例绑定后初始化音视频(TUICallEngine 依赖 tim 收发自定义信令) */
|
||||
async function initTUICallKitWithTim(imChat) {
|
||||
function initTUICallKitWithTim(imChat, options) {
|
||||
const task = callKitInitChain.catch(() => {}).then(() => doInitTUICallKitWithTim(imChat, options));
|
||||
callKitInitChain = task;
|
||||
return task;
|
||||
}
|
||||
/**
|
||||
* force:仅页面首次进入时为 true,允许清掉残留的非空闲通话状态。
|
||||
* 其它路径(回前台、发消息失败重登)遇到来电/通话中必须放弃重绑:
|
||||
* 重绑第一步 handleExceptionExit 会把正在响铃的来电直接 reject 掉。
|
||||
*/
|
||||
async function doInitTUICallKitWithTim(imChat, { force = false } = {}) {
|
||||
const app = getApp();
|
||||
const sdkAppID = app.globalData.SDKAppID;
|
||||
const userSig = app.globalData.userSig;
|
||||
@@ -580,6 +623,17 @@ const { proxy } = getCurrentInstance()
|
||||
console.warn('initTUICallKitWithTim: 缺少 im / SDKAppID / userSig / userID');
|
||||
return;
|
||||
}
|
||||
if (!force && !isCallIdle()) {
|
||||
console.warn('initTUICallKitWithTim: 通话未结束,跳过 TUICall 重绑');
|
||||
return;
|
||||
}
|
||||
if (!(await waitForIMSdkReady(imChat))) {
|
||||
console.warn('initTUICallKitWithTim: IM 未就绪,TUICall 登录可能失败');
|
||||
}
|
||||
if (!force && !isCallIdle()) {
|
||||
console.warn('initTUICallKitWithTim: 等待 IM 期间来电,跳过 TUICall 重绑');
|
||||
return;
|
||||
}
|
||||
// 非 IDLE 时 destroyed 会抛错,随后 _doInit 会因旧 engine 仍存在而直接 return,导致未绑定新 tim、接不到来电
|
||||
try {
|
||||
await TUICallKitAPI.handleExceptionExit();
|
||||
@@ -597,13 +651,20 @@ const { proxy } = getCurrentInstance()
|
||||
console.warn('CallManager.destroyed retry:', e2);
|
||||
}
|
||||
}
|
||||
// 空闲状态下 destroyed 仍失败,说明是 destroyInstance 抛错:此时事件监听已移除,但旧引擎还挂在
|
||||
// TUICallKitAPI 上,init 看到旧引擎会直接 return —— 引擎在、监听没了,来电全部丢失。丢弃旧引擎重建。
|
||||
if (isCallIdle() && TUICallKitAPI.getTUICallEngineInstance()) {
|
||||
console.warn('initTUICallKitWithTim: 旧引擎销毁失败,强制丢弃后重建');
|
||||
TUICallKitAPI._tuiCallEngine = null;
|
||||
}
|
||||
await uni.CallManager.init({
|
||||
sdkAppID: Number(sdkAppID),
|
||||
userID,
|
||||
userSig,
|
||||
globalCallPagePath: 'TUICallKit/src/Components/TUICallKit',
|
||||
globalCallPagePath: CALL_PAGE_ROUTE,
|
||||
tim: imChat
|
||||
});
|
||||
callKitBoundChat = imChat;
|
||||
}
|
||||
onLoad(async (options) => {
|
||||
try {
|
||||
@@ -717,8 +778,8 @@ const { proxy } = getCurrentInstance()
|
||||
chat.on(TencentCloudChat.EVENT.MESSAGE_RECEIVED, onMessageReceived);
|
||||
}
|
||||
|
||||
await initTUICallKitWithTim(chat);
|
||||
|
||||
await initTUICallKitWithTim(chat, { force: true });
|
||||
|
||||
await loadHistoryMessages();
|
||||
|
||||
// 打开会话时通知医生(IM自定义消息 + 后端全局事件)
|
||||
@@ -737,18 +798,20 @@ const { proxy } = getCurrentInstance()
|
||||
//uni.showToast({ title: '聊天已就绪', icon: 'success' });
|
||||
|
||||
// #ifdef MP-WEIXIN
|
||||
// 系统级前后台切换时页面 onShow 不一定等价于「回前台」,用 wx.onAppShow 刷新音视频信令链路
|
||||
// 系统级前后台切换时页面 onShow 不一定等价于「回前台」,用 wx.onAppShow 检查音视频信令链路
|
||||
// 注意 wx.onAppShow 不返回取消函数,必须保存回调引用,卸载时用 wx.offAppShow 移除
|
||||
if (typeof wx !== 'undefined' && wx.onAppShow) {
|
||||
unsubscribeWxAppShow = wx.onAppShow(() => {
|
||||
wxAppShowHandler = () => {
|
||||
if (!allowChatForegroundRelogin) return;
|
||||
const pages = getCurrentPages();
|
||||
const top = pages[pages.length - 1];
|
||||
if (!(top?.route || '').includes('pages/chat/chat')) return;
|
||||
reloginAfterMiniProgramForeground();
|
||||
});
|
||||
};
|
||||
wx.onAppShow(wxAppShowHandler);
|
||||
}
|
||||
setTimeout(() => {
|
||||
allowChatForegroundRelogin = true;
|
||||
if (!pageUnloaded) allowChatForegroundRelogin = true;
|
||||
}, 800);
|
||||
// #endif
|
||||
|
||||
@@ -793,11 +856,12 @@ const { proxy } = getCurrentInstance()
|
||||
void notifyDoctorOnChatClose();
|
||||
}
|
||||
allowChatForegroundRelogin = false;
|
||||
pageUnloaded = true;
|
||||
// #ifdef MP-WEIXIN
|
||||
if (typeof unsubscribeWxAppShow === 'function') {
|
||||
unsubscribeWxAppShow();
|
||||
unsubscribeWxAppShow = null;
|
||||
if (wxAppShowHandler && typeof wx !== 'undefined' && wx.offAppShow) {
|
||||
wx.offAppShow(wxAppShowHandler);
|
||||
}
|
||||
wxAppShowHandler = null;
|
||||
// #endif
|
||||
if (foregroundReloginTimer) {
|
||||
clearTimeout(foregroundReloginTimer);
|
||||
@@ -1071,8 +1135,16 @@ const { proxy } = getCurrentInstance()
|
||||
return m ? parseInt(m[1], 10) : null;
|
||||
}
|
||||
|
||||
/** 拉取最新 userSig 并重新登录 IM,必要时重建 chat 实例(与 onLoad 逻辑一致) */
|
||||
async function reloginIMChat() {
|
||||
/** 拉取最新 userSig 并重新登录 IM,必要时重建 chat 实例(与 onLoad 逻辑一致);并发调用合并为一次 */
|
||||
function reloginIMChat() {
|
||||
if (!reloginTask) {
|
||||
reloginTask = doReloginIMChat().finally(() => {
|
||||
reloginTask = null;
|
||||
});
|
||||
}
|
||||
return reloginTask;
|
||||
}
|
||||
async function doReloginIMChat() {
|
||||
const app = getApp();
|
||||
await video(currentUserID);
|
||||
const userSig = app.globalData.userSig;
|
||||
@@ -1084,6 +1156,10 @@ const { proxy } = getCurrentInstance()
|
||||
if (!chat) {
|
||||
throw new Error('IM 未初始化');
|
||||
}
|
||||
// 拉 userSig 期间可能来电:此时登出 IM 会让来电信令中断,必须放弃
|
||||
if (!isCallIdle()) {
|
||||
throw new Error('通话进行中,暂不重登 IM');
|
||||
}
|
||||
try {
|
||||
chat.off(TencentCloudChat.EVENT.MESSAGE_RECEIVED, onMessageReceived);
|
||||
} catch (_) {}
|
||||
@@ -1122,25 +1198,51 @@ const { proxy } = getCurrentInstance()
|
||||
await initTUICallKitWithTim(chat);
|
||||
}
|
||||
|
||||
/** 小程序切后台再回前台:拉取新 UserSig 并重登 IM、重绑 TUICallEngine(与发消息失败时的 relogin 一致) */
|
||||
async function reloginAfterMiniProgramForeground() {
|
||||
/**
|
||||
* 小程序切后台再回前台:IM SDK 会自行重连并补收后台期间的来电信令。
|
||||
* 以前这里无条件「登出 IM → 重登 → 销毁并重建 TUICallEngine」,重建窗口内(拉 userSig + IM 重登 + 引擎登录,
|
||||
* 弱网下数秒)医生的呼叫会丢失,刚补收到的来电也会被重绑流程 reject;所以现在只在链路确实坏了时才重建。
|
||||
*/
|
||||
function reloginAfterMiniProgramForeground() {
|
||||
if (!chat || !currentUserID) return;
|
||||
if (foregroundReloginTimer) clearTimeout(foregroundReloginTimer);
|
||||
foregroundReloginTimer = setTimeout(async () => {
|
||||
foregroundReloginTimer = null;
|
||||
// reloginIMChat 会先 IM logout 再 initTUICallKit;若非 IDLE,destroyed 会失败且 IM 已断开,故仅 IDLE 时刷新
|
||||
try {
|
||||
const status = TUIStore?.getData?.(StoreName.CALL, NAME.CALL_STATUS);
|
||||
if (status != null && status !== CallStatus.IDLE) {
|
||||
console.warn('前台恢复: 通话未结束,跳过 IM/TUICall 重绑');
|
||||
if (!isCallIdle()) {
|
||||
// 来电信令在后台到达时,跳转通话页的 navigateTo 可能失败,回前台后补跳,否则患者看不到来电
|
||||
ensureCallPageVisible();
|
||||
return;
|
||||
}
|
||||
await reloginIMChat();
|
||||
const imReady = await waitForIMSdkReady(chat, 5000);
|
||||
if (pageUnloaded || !isCallIdle()) return;
|
||||
const imOk = imReady && chat.getLoginUser?.() === currentUserID;
|
||||
const callKitOk = !!TUICallKitAPI.getTUICallEngineInstance() && callKitBoundChat === chat;
|
||||
if (imOk && callKitOk) return;
|
||||
console.warn('前台恢复: IM/TUICall 链路异常,重建', { imOk, callKitOk });
|
||||
if (imOk) {
|
||||
await initTUICallKitWithTim(chat);
|
||||
} else {
|
||||
await reloginIMChat();
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('前台恢复后 IM/TUICall 刷新失败:', e);
|
||||
}
|
||||
}, 400);
|
||||
}
|
||||
|
||||
function ensureCallPageVisible() {
|
||||
// 等 CallManager 自己的 navigateTo 走完再判断,避免叠出两个通话页(其中一个卸载时会把来电 reject 掉)
|
||||
setTimeout(() => {
|
||||
if (pageUnloaded || isCallIdle()) return;
|
||||
const pages = getCurrentPages();
|
||||
if (pages.some((p) => (p?.route || '').includes(CALL_PAGE_ROUTE))) return;
|
||||
uni.navigateTo({
|
||||
url: `/${CALL_PAGE_ROUTE}`,
|
||||
fail: (e) => console.warn('补跳通话页失败:', e)
|
||||
});
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
async function sendTextMessage() {
|
||||
if (!inputText.value.trim()) return;
|
||||
|
||||
@@ -1595,17 +1595,26 @@ async function goMorePage() {
|
||||
uni.navigateTo({ url: buildMorePageUrl() })
|
||||
}
|
||||
|
||||
function openGamePage(url) {
|
||||
function goEndlessGamePage() {
|
||||
// #ifdef MP-WEIXIN
|
||||
wx.navigateToMiniProgram({
|
||||
appId: 'wx0c2a9d5ebad26a3f',
|
||||
path: 'tongji/endless-game/index',
|
||||
envVersion: 'release',
|
||||
fail(err) {
|
||||
if (err?.errMsg?.includes('cancel')) return
|
||||
uni.showToast({ title: '暂时无法打开课堂', icon: 'none' })
|
||||
}
|
||||
})
|
||||
// #endif
|
||||
// #ifndef MP-WEIXIN
|
||||
uni.navigateTo({
|
||||
url,
|
||||
url: '/tongji/endless-game/index',
|
||||
fail() {
|
||||
uni.showToast({ title: '暂时无法打开游戏', icon: 'none' })
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function goEndlessGamePage() {
|
||||
openGamePage('/tongji/endless-game/index')
|
||||
// #endif
|
||||
}
|
||||
|
||||
function navToUser() {
|
||||
|
||||
@@ -0,0 +1,504 @@
|
||||
import request from '@/utils/request'
|
||||
|
||||
export type Permission =
|
||||
| 'view'
|
||||
| 'analyze'
|
||||
| 'draftReply'
|
||||
| 'record'
|
||||
| 'adoptAction'
|
||||
| 'completeAction'
|
||||
| 'reviewQuality'
|
||||
| 'manageKnowledge'
|
||||
export type Scenario = 'initial' | 'followup' | 'revisit'
|
||||
export type Days = 7 | 30 | 90
|
||||
export type JobStatus = 'queued' | 'running' | 'ready' | 'failed' | 'needs_reconciliation' | 'stale'
|
||||
export interface Page<T> {
|
||||
lists: T[]
|
||||
count: number
|
||||
page_no: number
|
||||
page_size: number
|
||||
}
|
||||
export interface Capabilities {
|
||||
enabled: boolean
|
||||
ready: boolean
|
||||
reason: string
|
||||
schema_ready: boolean
|
||||
permissions: Permission[]
|
||||
scenarios: Array<{ value: Scenario; label: string }>
|
||||
limits: { max_manual_chars: number; max_source_chars: number }
|
||||
}
|
||||
export interface Patient {
|
||||
diagnosis_id: number
|
||||
patient_id: number
|
||||
patient_name: string
|
||||
phone_masked?: string
|
||||
assistant_id: number
|
||||
}
|
||||
export interface Staff {
|
||||
id: number
|
||||
name: string
|
||||
is_self: boolean
|
||||
assistant?: boolean
|
||||
role_name?: string
|
||||
}
|
||||
export interface StaffCase extends Patient {
|
||||
im_messages: number | null
|
||||
manual_records: number
|
||||
last_activity_at: number
|
||||
}
|
||||
export interface StaffQuality {
|
||||
key: string
|
||||
label: string
|
||||
met: number
|
||||
missed: number
|
||||
insufficient: number
|
||||
not_applicable: number
|
||||
confirmed: number
|
||||
dismissed: number
|
||||
unreviewed: number
|
||||
}
|
||||
export interface StaffOverview {
|
||||
staff: Staff
|
||||
days: Days
|
||||
metrics: {
|
||||
assigned_cases: number
|
||||
im_messages: number | null
|
||||
manual_records: number
|
||||
analyzed_cases: number
|
||||
pending_actions: number
|
||||
overdue_actions: number
|
||||
completed_actions: number
|
||||
}
|
||||
quality: StaffQuality[]
|
||||
coverage_notes: string[]
|
||||
}
|
||||
export type TeamFilter = 'all' | 'today_pending' | 'today_done' | 'issues' | 'overdue' | 'attention'
|
||||
export type DailyStatus = 'all' | 'pending' | 'reported' | 'contacted' | 'exempt'
|
||||
export interface DailyCounts {
|
||||
required: number | null
|
||||
contacted: number | null
|
||||
reported: number | null
|
||||
pending: number | null
|
||||
outstanding: number | null
|
||||
exempt: number | null
|
||||
state: 'no_tasks' | 'pending' | 'reported' | 'done' | 'unavailable'
|
||||
}
|
||||
export interface DailyMeta {
|
||||
business_date: string
|
||||
timezone: 'Asia/Shanghai'
|
||||
as_of: number
|
||||
state: 'ready' | 'waiting' | 'partial' | 'unavailable'
|
||||
reason: string
|
||||
last_scan_at: number
|
||||
rule_label: string
|
||||
coverage: Array<{
|
||||
source: string
|
||||
status: 'available' | 'empty' | 'unavailable' | 'not_connected'
|
||||
note: string
|
||||
}>
|
||||
}
|
||||
export interface DailyPatient {
|
||||
key: string
|
||||
patient_id: number
|
||||
patient_name: string
|
||||
diagnosis_id: number
|
||||
diagnosis_ids: number[]
|
||||
status: Exclude<DailyStatus, 'all'>
|
||||
reasons: Array<{ type: 'revisit' | 'action'; label: string; due_at: number; source_id: number }>
|
||||
last_contact_at: number
|
||||
evidence: Array<{
|
||||
type: 'im' | 'revisit_contact' | 'action_completed'
|
||||
id: number
|
||||
at: number
|
||||
label: string
|
||||
}>
|
||||
exempt_reason: string
|
||||
}
|
||||
export interface StaffDailyContacts extends Page<DailyPatient> {
|
||||
staff: Staff
|
||||
daily: DailyMeta
|
||||
summary: DailyCounts
|
||||
}
|
||||
export type StaffAnalysisState =
|
||||
| 'no_sources'
|
||||
| 'pending'
|
||||
| 'queued'
|
||||
| 'running'
|
||||
| 'ready'
|
||||
| 'attention'
|
||||
export interface TeamStaff {
|
||||
staff: Staff
|
||||
today_contact: DailyCounts
|
||||
metrics: StaffOverview['metrics']
|
||||
unreviewed_issues: number
|
||||
last_analyzed_at: number
|
||||
analysis_state: StaffAnalysisState
|
||||
queued_jobs: number
|
||||
running_jobs: number
|
||||
attention_jobs: number
|
||||
}
|
||||
export type AlertStatus = 'open' | 'confirmed' | 'false_positive' | 'followed'
|
||||
export type AlertSeverity = 'high' | 'medium' | 'low'
|
||||
export interface ServiceAlert {
|
||||
id: number
|
||||
staff: Staff
|
||||
patient_id: number
|
||||
patient_name: string
|
||||
diagnosis_id: number
|
||||
channel: 'im' | 'call' | 'wecom'
|
||||
rule_code: string
|
||||
rule_label: string
|
||||
rule_version: number
|
||||
severity: AlertSeverity
|
||||
snippet: string
|
||||
status: AlertStatus
|
||||
occurred_at: number
|
||||
review_note: string
|
||||
reviewed_at: number
|
||||
}
|
||||
export interface AlertPage extends Page<ServiceAlert> {
|
||||
schema_ready: boolean
|
||||
summary: {
|
||||
open: number
|
||||
high_open: number
|
||||
im_open: number
|
||||
call_open: number
|
||||
assistant_open: number
|
||||
doctor_open: number
|
||||
}
|
||||
scan: {
|
||||
enabled: boolean
|
||||
state: 'disabled' | 'ready' | 'waiting' | 'error' | 'unavailable'
|
||||
last_scan_at: number
|
||||
reason: string
|
||||
}
|
||||
coverage: Array<{ channel: string; status: string; note: string }>
|
||||
empty_reason: string
|
||||
}
|
||||
export interface TeamOverview extends Page<TeamStaff> {
|
||||
days: 30
|
||||
daily: DailyMeta
|
||||
daily_summary: DailyCounts
|
||||
summary: {
|
||||
staff_count: number
|
||||
active_staff: number
|
||||
analyzed_cases: number
|
||||
unreviewed_issues: number
|
||||
pending_actions: number
|
||||
overdue_actions: number
|
||||
queued_jobs: number
|
||||
running_jobs: number
|
||||
attention_jobs: number
|
||||
}
|
||||
automation: {
|
||||
enabled: boolean
|
||||
state: 'disabled' | 'running' | 'waiting' | 'error'
|
||||
last_scan_at: number
|
||||
next_scan_at: number
|
||||
interval_seconds: number
|
||||
quiet_seconds: number
|
||||
days: 30
|
||||
reason: string
|
||||
}
|
||||
}
|
||||
export interface StaffIssue {
|
||||
job_id: number
|
||||
version: number
|
||||
diagnosis_id: number
|
||||
patient_name: string
|
||||
item_key: string
|
||||
label: string
|
||||
status: string
|
||||
reason: string
|
||||
decision: '' | 'confirmed'
|
||||
created_at: number
|
||||
}
|
||||
export interface Source {
|
||||
id: string
|
||||
channel: string
|
||||
text: string
|
||||
occurred_at: number
|
||||
speaker: 'patient' | 'service' | 'unknown'
|
||||
actor_admin_id: number
|
||||
quality_eligible: boolean
|
||||
}
|
||||
export interface Coverage {
|
||||
channel: string
|
||||
status: string
|
||||
count: number
|
||||
note: string
|
||||
}
|
||||
export interface Claim {
|
||||
text: string
|
||||
evidence_ids: string[]
|
||||
}
|
||||
export interface SuggestedAction extends Claim {
|
||||
key: string
|
||||
}
|
||||
export interface QualityCheck {
|
||||
key: string
|
||||
label: string
|
||||
status: 'met' | 'missed' | 'not_applicable' | 'insufficient'
|
||||
reason: string
|
||||
evidence_ids: string[]
|
||||
actor_admin_id: number
|
||||
}
|
||||
export interface AnalysisResult {
|
||||
summary: Claim[]
|
||||
needs: Claim[]
|
||||
unresolved: Claim[]
|
||||
tags: Claim[]
|
||||
suggested_actions: SuggestedAction[]
|
||||
quality_checks: QualityCheck[]
|
||||
}
|
||||
export interface ReplyResult {
|
||||
reply: string
|
||||
knowledge_refs: Array<{ id: number; version: number }>
|
||||
evidence_ids: string[]
|
||||
needs_confirmation: boolean
|
||||
reason: string
|
||||
}
|
||||
export type ReviewDecision = 'confirmed' | 'dismissed' | 'not_applicable'
|
||||
export interface Review {
|
||||
id: number
|
||||
item_key: string
|
||||
reviewer_id: number
|
||||
decision: ReviewDecision
|
||||
note: string
|
||||
created_at: number
|
||||
}
|
||||
export interface Job {
|
||||
id: number
|
||||
subject_admin_id: number
|
||||
type: 'analysis' | 'reply'
|
||||
diagnosis_id: number
|
||||
scenario: Scenario
|
||||
status: JobStatus
|
||||
version: number
|
||||
created_at: number
|
||||
updated_at: number
|
||||
error_code: string
|
||||
error_message: string
|
||||
result: AnalysisResult | ReplyResult | null
|
||||
coverage: Coverage[]
|
||||
sources: Source[]
|
||||
reviews: Review[]
|
||||
stale: boolean
|
||||
}
|
||||
export interface Context {
|
||||
subject_admin_id: number
|
||||
patient: Patient
|
||||
sources: Source[]
|
||||
coverage: Coverage[]
|
||||
source_hash: string
|
||||
scope_hash: string
|
||||
days: Days
|
||||
latest_job: Job | null
|
||||
latest_analysis_job: Job | null
|
||||
}
|
||||
export type BusinessState = 'pending' | 'in_progress' | 'completed' | 'cancelled'
|
||||
export interface ServiceAction {
|
||||
id: number
|
||||
diagnosis_id: number
|
||||
patient_name: string
|
||||
content: string
|
||||
contact_required: boolean
|
||||
due_at: number
|
||||
business_state: BusinessState
|
||||
completed_at: number
|
||||
completion_note: string
|
||||
assignee_id: number
|
||||
notification_status: string | number | null
|
||||
}
|
||||
export type KnowledgeStatus = 'draft' | 'published' | 'disabled'
|
||||
export interface Knowledge {
|
||||
id: number
|
||||
question: string
|
||||
answer: string
|
||||
category: string
|
||||
status: KnowledgeStatus
|
||||
version: number
|
||||
source_note: string
|
||||
updated_at: number
|
||||
}
|
||||
export class AssistantServiceError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly code = ''
|
||||
) {
|
||||
super(message)
|
||||
this.name = 'AssistantServiceError'
|
||||
}
|
||||
}
|
||||
interface Envelope<T> {
|
||||
code: number
|
||||
msg?: string
|
||||
data: T
|
||||
}
|
||||
// 异步提交不能因超时自动重发,也不能被相同 URL 的另一患者请求取消。
|
||||
const options = {
|
||||
isTransformResponse: false,
|
||||
ignoreCancelToken: true,
|
||||
isOpenRetry: false,
|
||||
retryCount: 0
|
||||
}
|
||||
const base = '/tcm.assistantService/'
|
||||
function unwrap<T>(response: Envelope<T>): T {
|
||||
if (response.code !== 1) {
|
||||
const data = response.data as { code?: string; error_code?: string } | null
|
||||
throw new AssistantServiceError(
|
||||
response.msg || '请求失败,请刷新后重试',
|
||||
data?.error_code || data?.code || ''
|
||||
)
|
||||
}
|
||||
return response.data
|
||||
}
|
||||
async function get<T>(action: string, params: object = {}, signal?: AbortSignal): Promise<T> {
|
||||
return unwrap(
|
||||
await request.get<Envelope<T>>(
|
||||
{ url: base + action, params, signal, timeout: 30000 },
|
||||
options
|
||||
)
|
||||
)
|
||||
}
|
||||
async function post<T>(action: string, data: object): Promise<T> {
|
||||
return unwrap(
|
||||
await request.post<Envelope<T>>({ url: base + action, data, timeout: 30000 }, options)
|
||||
)
|
||||
}
|
||||
type Paging = { page_no: number; page_size: number }
|
||||
type JobInput = { diagnosis_id: number; days: Days; scenario: Scenario; assistant_id?: number }
|
||||
export type StaffScope = { assistant_id: number; days: Days }
|
||||
export const assistantAlerts = (
|
||||
params: Partial<Paging> & {
|
||||
keyword?: string
|
||||
status?: AlertStatus | 'all'
|
||||
severity?: AlertSeverity | 'all'
|
||||
role?: 'all' | 'assistant' | 'doctor'
|
||||
} = {},
|
||||
signal?: AbortSignal
|
||||
) => get<AlertPage>('alerts', params, signal)
|
||||
export interface WecomDirectory {
|
||||
ready: boolean
|
||||
staff: Array<Staff & { conversations: number }>
|
||||
accounts: Array<{ external_id: string; name: string; conversations: number }>
|
||||
}
|
||||
export interface WecomConversation {
|
||||
id: string
|
||||
name: string
|
||||
conversation_type: string
|
||||
last_message_at: string
|
||||
message_count: number
|
||||
preview: string
|
||||
account: string
|
||||
}
|
||||
export interface WecomMessage {
|
||||
id: string
|
||||
sent_at: string
|
||||
direction: string
|
||||
message_type: string
|
||||
sender_name: string
|
||||
content: string
|
||||
}
|
||||
export const assistantWecomDirectory = (signal?: AbortSignal) =>
|
||||
get<WecomDirectory>('wecomDirectory', {}, signal)
|
||||
export const assistantWecomChats = (
|
||||
params: { assistant_id?: number; account?: string },
|
||||
signal?: AbortSignal
|
||||
) => get<{ conversations: WecomConversation[] }>('wecomChats', params, signal)
|
||||
export const assistantWecomMessages = (
|
||||
params: { assistant_id?: number; account?: string; conversation_id: string },
|
||||
signal?: AbortSignal
|
||||
) => get<{ messages: WecomMessage[] }>('wecomMessages', params, signal)
|
||||
export const assistantReviewAlert = (data: {
|
||||
id: number
|
||||
status: Exclude<AlertStatus, 'open'>
|
||||
note: string
|
||||
}) => post<{ id: number; status: string }>('reviewAlert', data)
|
||||
export const assistantTeamOverview = (
|
||||
params: Partial<Paging> & { keyword?: string; filter?: TeamFilter } = {},
|
||||
signal?: AbortSignal
|
||||
) => get<TeamOverview>('teamOverview', params, signal)
|
||||
export const assistantStaff = (
|
||||
params: Partial<Paging> & { keyword?: string } = {},
|
||||
signal?: AbortSignal
|
||||
) => get<Page<Staff>>('staff', params, signal)
|
||||
export const assistantStaffOverview = (params: StaffScope, signal?: AbortSignal) =>
|
||||
get<StaffOverview>('staffOverview', params, signal)
|
||||
export const assistantStaffDailyContacts = (
|
||||
params: Partial<Paging> & { assistant_id: number; status?: DailyStatus },
|
||||
signal?: AbortSignal
|
||||
) => get<StaffDailyContacts>('staffDailyContacts', params, signal)
|
||||
export const assistantStaffCases = (
|
||||
params: StaffScope & Partial<Paging> & { keyword?: string },
|
||||
signal?: AbortSignal
|
||||
) => get<Page<StaffCase>>('staffCases', params, signal)
|
||||
export const assistantStaffIssues = (params: StaffScope & Partial<Paging>, signal?: AbortSignal) =>
|
||||
get<Page<StaffIssue>>('staffIssues', params, signal)
|
||||
export const assistantAnalyzeStaff = (
|
||||
data: StaffScope & { scenario: Scenario; diagnosis_ids: number[] }
|
||||
) => post<{ jobs: Job[]; count: number }>('analyzeStaff', data)
|
||||
export const assistantCapabilities = (signal?: AbortSignal) =>
|
||||
get<Capabilities>('capabilities', {}, signal)
|
||||
export const assistantPatients = (params: Paging & { keyword?: string }, signal?: AbortSignal) =>
|
||||
get<Page<Patient>>('patients', params, signal)
|
||||
export const assistantContext = (
|
||||
params: { diagnosis_id: number; days: Days; assistant_id?: number },
|
||||
signal?: AbortSignal
|
||||
) => get<Context>('context', params, signal)
|
||||
export const assistantRecord = (data: {
|
||||
diagnosis_id: number
|
||||
content: string
|
||||
occurred_at: number
|
||||
record_type: 'service_note' | 'verified_transcript'
|
||||
speaker_confirmed: boolean
|
||||
}) => post<{ id: number }>('record', data)
|
||||
export const assistantAnalyze = (data: JobInput) => post<Job>('analyze', data)
|
||||
export const assistantDraftReply = (data: JobInput & { question: string }) =>
|
||||
post<Job>('draftReply', data)
|
||||
export const assistantJob = (id: number, signal?: AbortSignal) => get<Job>('job', { id }, signal)
|
||||
export const assistantJobs = (
|
||||
params: Paging & { diagnosis_id?: number; status?: JobStatus; assistant_id?: number },
|
||||
signal?: AbortSignal
|
||||
) => get<Page<Job>>('jobs', params, signal)
|
||||
export const assistantReviewQuality = (data: {
|
||||
job_id: number
|
||||
item_key: string
|
||||
decision: ReviewDecision
|
||||
note: string
|
||||
version: number
|
||||
}) => post<{ id: number }>('reviewQuality', data)
|
||||
export const assistantAdoptAction = (data: {
|
||||
job_id: number
|
||||
action_key: string
|
||||
version: number
|
||||
due_at: number
|
||||
content?: string
|
||||
contact_required?: boolean
|
||||
}) => post<{ id: number; todo_id: number }>('adoptAction', data)
|
||||
export const assistantActions = (
|
||||
params: Paging & { diagnosis_id?: number; state?: BusinessState; assistant_id?: number },
|
||||
signal?: AbortSignal
|
||||
) => get<Page<ServiceAction>>('actions', params, signal)
|
||||
export const assistantCompleteAction = (data: {
|
||||
id: number
|
||||
state: Exclude<BusinessState, 'pending'>
|
||||
note: string
|
||||
}) => post<{ id: number }>('completeAction', data)
|
||||
export const assistantKnowledge = (
|
||||
params: Paging & { keyword?: string; status?: KnowledgeStatus },
|
||||
signal?: AbortSignal
|
||||
) => get<Page<Knowledge>>('knowledge', params, signal)
|
||||
export const assistantSaveKnowledge = (data: {
|
||||
id?: number
|
||||
version?: number
|
||||
question: string
|
||||
answer: string
|
||||
category: string
|
||||
source_note: string
|
||||
}) => post<{ id: number; version: number }>('saveKnowledge', data)
|
||||
export const assistantPublishKnowledge = (data: {
|
||||
id: number
|
||||
version: number
|
||||
status: 'published' | 'disabled'
|
||||
}) => post<{ id: number; version: number }>('publishKnowledge', data)
|
||||
@@ -27,3 +27,8 @@ export function adminDelete(params: any) {
|
||||
export function adminDetail(params: any) {
|
||||
return request.get({ url: '/auth.admin/detail', params })
|
||||
}
|
||||
|
||||
// 解除管理员的电子签署身份
|
||||
export function adminEsignUnbind(params: { id: number }) {
|
||||
return request.post({ url: '/auth.admin/esignUnbind', params })
|
||||
}
|
||||
|
||||
@@ -159,8 +159,14 @@ export interface RevisitDueListsParams {
|
||||
dept_id?: number | ''
|
||||
state?: string
|
||||
days_bucket?: string
|
||||
/** 诊次(current_slot):'1'~'5' 精确,'6+' = 第 6 诊及以上 */
|
||||
slot?: string
|
||||
min_snooze?: number | ''
|
||||
keyword?: string
|
||||
/** 排序列(白名单:due_date = 预计复诊),缺省 due_date */
|
||||
sort_field?: 'due_date'
|
||||
/** 排序方向,缺省 desc(最新在前);无预计复诊日的行始终置后 */
|
||||
sort_order?: 'asc' | 'desc'
|
||||
page_no?: number
|
||||
page_size?: number
|
||||
/** 1 = 导出(export-data 组件追加) */
|
||||
|
||||
@@ -10,6 +10,18 @@ export function systemLogLists(params: any) {
|
||||
return request.get({ url: '/setting.system.log/lists', params }, { ignoreCancelToken: true })
|
||||
}
|
||||
|
||||
export function desktopSessionLists(params: {
|
||||
date: string
|
||||
keyword: string
|
||||
page_no: number
|
||||
page_size: number
|
||||
}) {
|
||||
return request.get(
|
||||
{ url: '/setting.system.log/desktopSessions', params },
|
||||
{ ignoreCancelToken: true }
|
||||
)
|
||||
}
|
||||
|
||||
// 清除系统缓存
|
||||
export function systemCacheClear() {
|
||||
return request.post({ url: '/setting.system.cache/clear' })
|
||||
|
||||
+215
-7
@@ -373,6 +373,184 @@ export function getMsgAuditPermitUsers() {
|
||||
|
||||
// ========== 中医处方单 ==========
|
||||
|
||||
export interface PrescriptionEsignConfig {
|
||||
enabled: boolean
|
||||
environment: 'sandbox' | 'production'
|
||||
verification_method?: 'sms' | 'quick'
|
||||
review_enabled?: boolean
|
||||
}
|
||||
|
||||
export interface PrescriptionEsignLogEntry {
|
||||
event: string
|
||||
label: string
|
||||
time: number
|
||||
source: 'tsa' | 'system' | 'local'
|
||||
actor_name?: string
|
||||
message?: string
|
||||
}
|
||||
|
||||
export interface PrescriptionEsignStatus extends PrescriptionEsignConfig {
|
||||
required: boolean
|
||||
status: 'pending' | 'authenticating' | 'signing' | 'signed' | 'failed' | 'uncertain' | 'voided' | 'legacy'
|
||||
status_label: string
|
||||
can_sign: boolean
|
||||
can_download: boolean
|
||||
can_resume_identity?: boolean
|
||||
doctor_identity_required?: boolean
|
||||
signing_authorization_required?: boolean
|
||||
signing_authorization_reason?: 'missing' | 'expired' | 'exhausted' | 'invalid'
|
||||
sms_sent?: boolean
|
||||
can_retry_verify?: boolean
|
||||
message: string
|
||||
issued_at?: number
|
||||
signature_time?: number
|
||||
signature_time_source?: 'tsa' | 'local' | ''
|
||||
doctor_signer_name?: string
|
||||
review_required?: boolean
|
||||
review_state?: PrescriptionEsignReviewStatus['state']
|
||||
review_submitted_at?: number
|
||||
awaiting_upload?: boolean
|
||||
can_submit_for_review?: boolean
|
||||
can_review_prescription?: boolean
|
||||
review_signer_name?: string
|
||||
review_signature?: string
|
||||
review_signature_time?: number
|
||||
signing_log?: PrescriptionEsignLogEntry[]
|
||||
signed_at?: number
|
||||
auth_url?: string
|
||||
}
|
||||
|
||||
export interface PrescriptionEsignFile {
|
||||
filename: string
|
||||
content_base64: string
|
||||
sha256: string
|
||||
}
|
||||
|
||||
export interface PrescriptionEsignReviewStatus {
|
||||
required: boolean
|
||||
state: 'pending' | 'signing' | 'verifying' | 'signed' | 'failed' | 'uncertain'
|
||||
can_confirm: boolean
|
||||
can_retry_verify: boolean
|
||||
can_approve: boolean
|
||||
can_setup: boolean
|
||||
actor_id: number
|
||||
actor_name: string
|
||||
signer_name: string
|
||||
signature_time: number
|
||||
message: string
|
||||
}
|
||||
|
||||
export interface PrescriptionEsignReviewTarget {
|
||||
id: number
|
||||
order_id?: number
|
||||
}
|
||||
|
||||
export function prescriptionEsignReviewStatus(params: PrescriptionEsignReviewTarget, signal?: AbortSignal): Promise<PrescriptionEsignReviewStatus> {
|
||||
return request.get({ url: '/tcm.prescription/esignReviewStatus', params, signal },
|
||||
{ isOpenRetry: false, retryCount: 0, ignoreCancelToken: true })
|
||||
}
|
||||
|
||||
export function prescriptionEsignReviewConfirm(
|
||||
params: PrescriptionEsignReviewTarget & { actor_id: number; verify_only: boolean }
|
||||
): Promise<PrescriptionEsignReviewStatus> {
|
||||
return request.post({ url: '/tcm.prescription/esignReviewConfirm', params, timeout: 360000 },
|
||||
{ isOpenRetry: false, retryCount: 0, ignoreCancelToken: true })
|
||||
}
|
||||
|
||||
export interface PrescriptionEsignIdentityStatus extends PrescriptionEsignStatus {
|
||||
identity_status: 'INIT' | 'ING' | 'SUCCESS' | 'FAIL' | 'EXPIRED' | 'UNAVAILABLE'
|
||||
can_complete: boolean
|
||||
identity_details_required?: boolean
|
||||
}
|
||||
|
||||
export interface PrescriptionEsignDoctorStatus {
|
||||
enabled: boolean
|
||||
status: 'unbound' | 'needs_mobile' | 'renewal_required' | 'authenticating' | 'binding_required' | 'ready'
|
||||
cert_expires_at: number
|
||||
certificate_state?: 'valid' | 'renewal_required' | 'unconfirmed'
|
||||
can_edit_signer_name?: boolean
|
||||
identity_details_required?: boolean
|
||||
quicksign_enabled?: boolean
|
||||
quicksign_authorizing?: boolean
|
||||
quicksign_expires_at?: number
|
||||
quicksign_remaining_times?: number
|
||||
quicksign_unavailable_reason?: '' | 'missing' | 'expired' | 'exhausted' | 'invalid'
|
||||
auth_url?: string
|
||||
message?: string
|
||||
}
|
||||
|
||||
export function prescriptionEsignConfig(): Promise<PrescriptionEsignConfig> {
|
||||
// 顶部用户菜单与处方页会同时读取;默认的重复请求取消会让先发出的一方失败(如药师菜单丢失「审核签署身份」)。
|
||||
return request.get({ url: '/tcm.prescription/esignConfig' }, { ignoreCancelToken: true })
|
||||
}
|
||||
|
||||
export function prescriptionEsignSetConfig(params: { enabled: boolean }): Promise<PrescriptionEsignConfig> {
|
||||
return request.post({ url: '/tcm.prescription/esignSetConfig', params })
|
||||
}
|
||||
|
||||
export function prescriptionEsignStatus(params: { id: number }, signal?: AbortSignal): Promise<PrescriptionEsignStatus> {
|
||||
return request.get({ url: '/tcm.prescription/esignStatus', params, signal }, { ignoreCancelToken: true })
|
||||
}
|
||||
|
||||
/** Read-only identity readiness; this endpoint never submits a signature. */
|
||||
export function prescriptionEsignIdentityStatus(params: { id: number }, signal?: AbortSignal): Promise<PrescriptionEsignIdentityStatus> {
|
||||
return request.get(
|
||||
{ url: '/tcm.prescription/esignIdentityStatus', params, signal, timeout: 15000 },
|
||||
{ isOpenRetry: false, retryCount: 0, ignoreCancelToken: true }
|
||||
)
|
||||
}
|
||||
|
||||
export function prescriptionEsignStart(params: { id: number; restart_identity?: true }): Promise<PrescriptionEsignStatus> {
|
||||
return request.post(
|
||||
{ url: '/tcm.prescription/esignStart', params, timeout: 180000 },
|
||||
{ isOpenRetry: false, retryCount: 0, ignoreCancelToken: true }
|
||||
)
|
||||
}
|
||||
|
||||
export function prescriptionEsignVerifyWillingness(params: { id: number; auth_code: string }): Promise<PrescriptionEsignIdentityStatus> {
|
||||
return request.post(
|
||||
{ url: '/tcm.prescription/esignVerifyWillingness', params, timeout: 60000 },
|
||||
{ isOpenRetry: false, retryCount: 0, ignoreCancelToken: true }
|
||||
)
|
||||
}
|
||||
|
||||
export function prescriptionEsignDoctorStatus(signal?: AbortSignal): Promise<PrescriptionEsignDoctorStatus> {
|
||||
return request.get(
|
||||
{ url: '/tcm.prescription/esignDoctorStatus', signal, timeout: 15000 },
|
||||
{ isOpenRetry: false, retryCount: 0, ignoreCancelToken: true }
|
||||
)
|
||||
}
|
||||
|
||||
export function prescriptionEsignDoctorStart(params: { mobile?: string; signer_name?: string }): Promise<PrescriptionEsignDoctorStatus> {
|
||||
return request.post(
|
||||
{ url: '/tcm.prescription/esignDoctorStart', params, timeout: 180000 },
|
||||
{ isOpenRetry: false, retryCount: 0, ignoreCancelToken: true }
|
||||
)
|
||||
}
|
||||
|
||||
export function prescriptionEsignDoctorComplete(params: { identity_number?: string }): Promise<PrescriptionEsignDoctorStatus> {
|
||||
return request.post(
|
||||
{ url: '/tcm.prescription/esignDoctorComplete', params, timeout: 180000 },
|
||||
{ isOpenRetry: false, retryCount: 0, ignoreCancelToken: true }
|
||||
)
|
||||
}
|
||||
|
||||
export function prescriptionEsignComplete(params: { id: number } & (
|
||||
{ verify_only: true; identity_number?: never } | { verify_only?: never; identity_number?: string }
|
||||
)): Promise<PrescriptionEsignStatus> {
|
||||
const payload = { id: params.id }
|
||||
if (params.verify_only) Object.assign(payload, { verify_only: true })
|
||||
else if (params.identity_number !== undefined) Object.assign(payload, { identity_number: params.identity_number })
|
||||
return request.post(
|
||||
{ url: '/tcm.prescription/esignComplete', params: payload, timeout: 180000 },
|
||||
{ isOpenRetry: false, retryCount: 0, ignoreCancelToken: true }
|
||||
)
|
||||
}
|
||||
|
||||
export function prescriptionEsignDownload(params: { id: number }): Promise<PrescriptionEsignFile> {
|
||||
return request.get({ url: '/tcm.prescription/esignDownload', params, timeout: 60000 })
|
||||
}
|
||||
|
||||
// 处方列表
|
||||
export function prescriptionLists(params: any) {
|
||||
return request.get({ url: '/tcm.prescription/lists', params })
|
||||
@@ -404,8 +582,8 @@ export function prescriptionDelete(params: { id: number }) {
|
||||
}
|
||||
|
||||
// 处方详情
|
||||
export function prescriptionDetail(params: { id: number }) {
|
||||
return request.get({ url: '/tcm.prescription/detail', params })
|
||||
export function prescriptionDetail(params: { id: number }, signal?: AbortSignal) {
|
||||
return request.get({ url: '/tcm.prescription/detail', params, signal }, signal ? { ignoreCancelToken: true } : undefined)
|
||||
}
|
||||
|
||||
// 根据诊单获取处方列表
|
||||
@@ -419,10 +597,17 @@ export function prescriptionGetByAppointment(params: { appointment_id: number })
|
||||
}
|
||||
|
||||
// 作废处方
|
||||
export function prescriptionVoid(params: { id: number }) {
|
||||
export function prescriptionVoid(params: { id: number; pending_only?: boolean }) {
|
||||
return request.post({ url: '/tcm.prescription/void', params })
|
||||
}
|
||||
|
||||
export function prescriptionSubmitForReview(params: {
|
||||
id: number
|
||||
}): Promise<{ review_submitted_at: number; can_submit_for_review: false }> {
|
||||
return request.post({ url: '/tcm.prescription/submitForReview', params },
|
||||
{ isOpenRetry: false, retryCount: 0, ignoreCancelToken: true })
|
||||
}
|
||||
|
||||
/** 处方审核:action approve | reject(驳回同时作废处方) */
|
||||
export function prescriptionAudit(params: {
|
||||
id: number
|
||||
@@ -448,7 +633,7 @@ export function prescriptionOrderExport(params: any) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 诊单下可关联的支付单(已支付 zyt_order;已占用且未撤回的会排除;编辑时传 prescription_order_id 保留当前单已选)。
|
||||
* 诊单下可关联的支付单(已支付 zyt_order;已关联其他业务订单的会排除;编辑时传 prescription_order_id 保留当前单已选)。
|
||||
* 服务端仅返回创建时间在 2026-04-20(含)之后的支付单;编辑时本单已关联的旧单仍会出现在列表中。
|
||||
*/
|
||||
export function prescriptionOrderPaidPayOrders(params: {
|
||||
@@ -477,8 +662,27 @@ export function prescriptionOrderLogisticsJdUpdate(params: { id: number }) {
|
||||
return request.post({ url: '/tcm.prescriptionOrder/logisticsJdUpdate', params })
|
||||
}
|
||||
|
||||
export function prescriptionOrderDetail(params: { id: number }) {
|
||||
return request.get({ url: '/tcm.prescriptionOrder/detail', params })
|
||||
export function prescriptionOrderDetail(params: { id: number; prescription_id?: number }, signal?: AbortSignal) {
|
||||
return request.get({ url: '/tcm.prescriptionOrder/detail', params, signal }, signal ? { ignoreCancelToken: true } : undefined)
|
||||
}
|
||||
|
||||
export interface PrescriptionBindingOrder {
|
||||
id: number
|
||||
order_no: string
|
||||
fulfillment_status: number
|
||||
is_primary: boolean
|
||||
is_linked: boolean
|
||||
}
|
||||
|
||||
export function prescriptionOrdersForBinding(params: { prescription_id: number; order_no?: string }, signal: AbortSignal) {
|
||||
return request.get<{ orders: PrescriptionBindingOrder[]; can_bind: boolean }>(
|
||||
{ url: '/tcm.prescriptionOrder/prescriptionOrdersForBinding', params, signal },
|
||||
{ ignoreCancelToken: true }
|
||||
)
|
||||
}
|
||||
|
||||
export function prescriptionOrderBindPrescription(params: { id: number; prescription_id: number }) {
|
||||
return request.post({ url: '/tcm.prescriptionOrder/bindPrescription', params })
|
||||
}
|
||||
|
||||
export function prescriptionOrderEdit(params: Record<string, unknown>) {
|
||||
@@ -651,6 +855,10 @@ export function prescriptionOrderUnlinkPayOrder(params: { id: number; pay_order_
|
||||
return request.post({ url: '/tcm.prescriptionOrder/unlinkPayOrder', params })
|
||||
}
|
||||
|
||||
export function prescriptionOrderAttachReceipt(params: { id: number; pay_order_id: number }) {
|
||||
return request.post({ url: '/tcm.prescriptionOrder/attachReceipt', params })
|
||||
}
|
||||
|
||||
/** 修改订单金额 */
|
||||
export function prescriptionOrderUpdateAmount(params: { id: number; amount: number }) {
|
||||
return request.post({ url: '/tcm.prescriptionOrder/updateAmount', params })
|
||||
@@ -663,7 +871,7 @@ export function prescriptionOrderSetShipMode(params: { id: number; ship_mode: 'g
|
||||
|
||||
// ========== 处方库 ==========
|
||||
|
||||
export type PrescriptionAiProfile = 'qwen' | 'openai'
|
||||
export type PrescriptionAiProfile = 'qwen' | 'openai' | 'doubao'
|
||||
|
||||
export interface PrescriptionLibraryHerb {
|
||||
medicine_id?: number
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 163 KiB |
@@ -0,0 +1,491 @@
|
||||
<template>
|
||||
<el-dialog
|
||||
:model-value="true"
|
||||
:title="reviewer ? '审核签署身份' : '医生电子签署身份'"
|
||||
width="min(760px, 94vw)"
|
||||
top="5vh"
|
||||
append-to-body
|
||||
:close-on-click-modal="false"
|
||||
:before-close="dismiss"
|
||||
>
|
||||
<p class="doctor-esign__message" role="status">{{ guidance }}</p>
|
||||
<p v-if="statusNotice" class="doctor-esign__message" role="status">{{ statusNotice }}</p>
|
||||
<dl v-if="state && (certificateLabel || grantActive)" class="doctor-esign__expiry">
|
||||
<template v-if="certificateLabel">
|
||||
<dt>签署证书状态</dt>
|
||||
<dd>{{ certificateLabel }}</dd>
|
||||
</template>
|
||||
<template v-if="state.cert_expires_at">
|
||||
<dt>签署证书有效期至</dt>
|
||||
<dd>{{ formatExpiry(state.cert_expires_at) }}</dd>
|
||||
</template>
|
||||
<template v-if="grantActive">
|
||||
<dt>快捷签授权有效期至</dt>
|
||||
<dd>{{ formatExpiry(state.quicksign_expires_at) }}</dd>
|
||||
<dt>快捷签剩余次数</dt>
|
||||
<dd>{{ state.quicksign_remaining_times }}</dd>
|
||||
</template>
|
||||
</dl>
|
||||
<p v-if="error" class="doctor-esign__error" role="alert">{{ error }}</p>
|
||||
<label v-if="needsSignerName" class="doctor-esign__field">
|
||||
证件姓名
|
||||
<el-input
|
||||
v-model="signerName"
|
||||
:disabled="!!pending"
|
||||
autocomplete="off"
|
||||
:spellcheck="false"
|
||||
required
|
||||
placeholder="请输入与本人有效证件一致的姓名"
|
||||
/>
|
||||
</label>
|
||||
<label v-if="needsMobile" class="doctor-esign__field">
|
||||
本人手机号码
|
||||
<el-input
|
||||
v-model="mobile"
|
||||
:disabled="!!pending"
|
||||
type="tel"
|
||||
inputmode="numeric"
|
||||
maxlength="11"
|
||||
autocomplete="off"
|
||||
placeholder="请输入 11 位大陆手机号码"
|
||||
/>
|
||||
</label>
|
||||
<label v-if="needsIdentityNumber" class="doctor-esign__field">
|
||||
本次认证使用的身份证号码
|
||||
<el-input
|
||||
v-model="identityNumber"
|
||||
:disabled="!!pending"
|
||||
type="password"
|
||||
maxlength="18"
|
||||
autocomplete="off"
|
||||
:spellcheck="false"
|
||||
placeholder="请输入 15 或 18 位大陆居民身份证号码"
|
||||
/>
|
||||
</label>
|
||||
<iframe
|
||||
v-if="frameUrl"
|
||||
:src="frameUrl"
|
||||
class="doctor-esign__frame"
|
||||
title="e签宝本人身份核验"
|
||||
sandbox="allow-forms allow-scripts allow-same-origin"
|
||||
referrerpolicy="no-referrer"
|
||||
@error="authenticationUnavailable"
|
||||
/>
|
||||
<template #footer>
|
||||
<div class="doctor-esign__actions">
|
||||
<el-button v-if="needsMobile || canAuthorizeQuick" type="primary" :disabled="!!pending" @click="start">
|
||||
{{ startLabel }}
|
||||
</el-button>
|
||||
<el-button v-if="canResume" type="primary" :disabled="!!pending" @click="openAuthentication">
|
||||
{{ state?.quicksign_authorizing ? '继续快捷签授权' : '继续人脸认证' }}
|
||||
</el-button>
|
||||
<el-button v-if="canComplete" type="primary" :disabled="!!pending" @click="complete">
|
||||
{{ state?.quicksign_authorizing ? '确认快捷签授权' : '确认绑定签署身份' }}
|
||||
</el-button>
|
||||
<el-button
|
||||
v-if="canRestartWithSignerName"
|
||||
:disabled="!!pending"
|
||||
@click="enterSignerName"
|
||||
>修改证件姓名</el-button>
|
||||
<el-button
|
||||
v-if="canResume && !state?.quicksign_authorizing && !canRestartWithSignerName"
|
||||
:disabled="!!pending"
|
||||
@click="enterMobile"
|
||||
>重新输入手机号</el-button>
|
||||
<el-button :disabled="!!pending" @click="checkStatus">
|
||||
{{ checkingIdentity ? '检查认证状态' : '重新校验证书' }}
|
||||
</el-button>
|
||||
<el-button v-if="frameUrl" link @click="authenticationUnavailable">验证页面不可用</el-button>
|
||||
<el-button @click="dismiss">关闭</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
|
||||
|
||||
import {
|
||||
prescriptionEsignDoctorComplete,
|
||||
prescriptionEsignDoctorStart,
|
||||
prescriptionEsignDoctorStatus,
|
||||
type PrescriptionEsignDoctorStatus
|
||||
} from '@/api/tcm'
|
||||
import { safeEsignAuthUrl } from '@/utils/prescription-esign'
|
||||
|
||||
const props = defineProps<{ serverTimeOffsetMs: number; reviewer?: boolean }>()
|
||||
const emit = defineEmits<{ (event: 'close'): void }>()
|
||||
type DoctorRequest = 'status' | 'start' | 'complete'
|
||||
|
||||
const enrollmentStatuses = ['unbound', 'needs_mobile', 'renewal_required']
|
||||
const statuses = [...enrollmentStatuses, 'authenticating', 'binding_required', 'ready']
|
||||
const pollInterval = 5000
|
||||
const authenticationTimeout = 10 * 60 * 1000
|
||||
const expiryFormatter = new Intl.DateTimeFormat('zh-CN', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
hourCycle: 'h23'
|
||||
})
|
||||
|
||||
const state = ref<ReturnType<typeof validateStatus> | null>(null)
|
||||
const pending = ref<DoctorRequest | null>(null)
|
||||
const frameUrl = ref('')
|
||||
const mobile = ref('')
|
||||
const signerName = ref('')
|
||||
const identityNumber = ref('')
|
||||
const editingMobile = ref(false)
|
||||
const error = ref('')
|
||||
const statusNotice = ref('')
|
||||
const now = ref(Date.now() + props.serverTimeOffsetMs)
|
||||
|
||||
const authUrl = computed(() => state.value?.auth_url ?? '')
|
||||
const authenticating = computed(() => state.value?.enabled === true && state.value.status === 'authenticating')
|
||||
const canResume = computed(() => authenticating.value && !!authUrl.value && !frameUrl.value && !editingMobile.value)
|
||||
const canEditSignerName = computed(() => props.reviewer === true && state.value?.enabled === true
|
||||
&& state.value.can_edit_signer_name === true && !state.value.quicksign_authorizing)
|
||||
const canRestartWithSignerName = computed(() => canEditSignerName.value && authenticating.value && !editingMobile.value)
|
||||
const needsSignerName = computed(() => canEditSignerName.value
|
||||
&& (state.value?.status === 'unbound' || state.value?.status === 'needs_mobile'
|
||||
|| (authenticating.value && editingMobile.value)))
|
||||
const canComplete = computed(() => state.value?.enabled === true && state.value.status === 'binding_required')
|
||||
const checkingIdentity = computed(() => authenticating.value || canComplete.value)
|
||||
const needsIdentityNumber = computed(() => canComplete.value && !state.value?.quicksign_authorizing
|
||||
&& state.value?.identity_details_required === true)
|
||||
const needsMobile = computed(() => state.value?.enabled === true
|
||||
&& (enrollmentStatuses.includes(state.value.status) || editingMobile.value))
|
||||
const certificateState = computed(() => {
|
||||
const current = state.value
|
||||
if (!current?.enabled) return ''
|
||||
if (current.status === 'unbound') return 'unbound'
|
||||
if (current.certificate_state === 'unconfirmed') return 'unconfirmed'
|
||||
if (current.status === 'renewal_required' || current.certificate_state === 'renewal_required') return 'renewal_required'
|
||||
if (current.status !== 'ready' && current.status !== 'needs_mobile') return ''
|
||||
return current.cert_expires_at * 1000 > now.value ? 'valid' : 'renewal_required'
|
||||
})
|
||||
const certificateLabel = computed(() => ({
|
||||
'': '', unbound: '未绑定', valid: '有效', renewal_required: '需要续期', unconfirmed: '暂无法确认'
|
||||
})[certificateState.value])
|
||||
const quickReady = computed(() => state.value?.enabled === true && state.value.status === 'ready'
|
||||
&& certificateState.value === 'valid' && state.value.quicksign_enabled === true)
|
||||
const grantActive = computed(() => quickReady.value && !!state.value && !state.value.quicksign_unavailable_reason
|
||||
&& (state.value.quicksign_remaining_times ?? 0) > 0 && state.value.quicksign_expires_at * 1000 > now.value)
|
||||
const canAuthorizeQuick = computed(() => quickReady.value && !grantActive.value)
|
||||
const startLabel = computed(() => {
|
||||
if (canAuthorizeQuick.value) return '授权快捷签'
|
||||
if (state.value?.status === 'renewal_required') return '开始续期认证'
|
||||
return '开始人脸认证'
|
||||
})
|
||||
const guidance = computed(() => {
|
||||
const current = state.value
|
||||
if (pending.value === 'status' && !checkingIdentity.value) return '正在向 e签宝校验证书…'
|
||||
if (!current) return ''
|
||||
if (!current.enabled) return '当前环境未启用医生电子签署身份。'
|
||||
if (needsSignerName.value) return '请填写与本人有效证件一致的姓名和本人手机号码,完成人脸认证。'
|
||||
switch (current.status) {
|
||||
case 'unbound':
|
||||
return '首次电子签署前,请验证本人身份并绑定签署证书。'
|
||||
case 'needs_mobile':
|
||||
return '请使用本人手机号码完成签署身份验证。'
|
||||
case 'renewal_required':
|
||||
return certificateState.value === 'unconfirmed'
|
||||
? '暂无法确认证书状态,可重新校验,或使用本人手机号码发起续期认证。'
|
||||
: '签署证书需要续期,请使用本人手机号码完成人脸认证。'
|
||||
case 'authenticating':
|
||||
if (editingMobile.value) return '请使用本人手机号码完成人脸认证。'
|
||||
if (current.authUrlUnavailable) return '验证链接不可用,请检查状态后重试。'
|
||||
if (!authUrl.value) return '认证请求处理中,请稍后检查状态。'
|
||||
if (!frameUrl.value) return current.quicksign_authorizing ? '请继续完成快捷签授权。' : '请继续完成本人人脸认证。'
|
||||
return current.quicksign_authorizing
|
||||
? '请使用手机支付宝扫码刷脸,并按 e签宝页面提示确认授权。'
|
||||
: '请使用手机支付宝扫描 e签宝页面中的二维码并完成人脸识别。'
|
||||
case 'binding_required':
|
||||
if (current.quicksign_authorizing) return '人脸认证已通过,请确认启用本人的快捷签。'
|
||||
if (needsIdentityNumber.value) return '人脸认证已通过。首次绑定证书需要补充与本次认证一致的身份证号码。'
|
||||
return '人脸认证已通过,请确认完成本人的签署身份认证。'
|
||||
case 'ready': {
|
||||
if (certificateState.value !== 'valid') return '请重新校验签署证书后继续。'
|
||||
if (!quickReady.value) return '医生签署身份已就绪。'
|
||||
if (grantActive.value) return props.reviewer
|
||||
? '快捷签授权有效。每张处方由药师本人确认签名。'
|
||||
: '快捷签授权有效。请回到处方中,由开方医生本人确认签名。'
|
||||
const reason = current.quicksign_unavailable_reason
|
||||
if (reason === 'expired' || (current.quicksign_expires_at > 0 && current.quicksign_expires_at * 1000 <= now.value)) {
|
||||
return '快捷签授权已过期,请重新授权。'
|
||||
}
|
||||
if (reason === 'exhausted') return '快捷签授权次数已用完,请重新授权。'
|
||||
if (reason === 'invalid') return '快捷签授权已失效,请重新授权。'
|
||||
return '签署身份已就绪。请授权使用本人的快捷签,每张处方仍需本人确认签名。'
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
let closed = false
|
||||
let generation = 0
|
||||
let statusRequest: AbortController | undefined
|
||||
let pollTimer: ReturnType<typeof setTimeout> | undefined
|
||||
let deadlineTimer: ReturnType<typeof setTimeout> | undefined
|
||||
let grantExpiryTimer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
function formatExpiry(timestamp: number) {
|
||||
return `${expiryFormatter.format(timestamp * 1000)}(北京时间)`
|
||||
}
|
||||
|
||||
function validTime(value: number) {
|
||||
return Number.isSafeInteger(value) && value >= 0 && value <= 253402300799
|
||||
}
|
||||
|
||||
function validateStatus(result: PrescriptionEsignDoctorStatus) {
|
||||
const {
|
||||
enabled, status, cert_expires_at, certificate_state,
|
||||
can_edit_signer_name = false,
|
||||
identity_details_required = false, quicksign_enabled = false, quicksign_authorizing = false,
|
||||
quicksign_expires_at = 0, quicksign_remaining_times = 0, quicksign_unavailable_reason = ''
|
||||
} = result
|
||||
if (!statuses.includes(status) || typeof enabled !== 'boolean'
|
||||
|| typeof can_edit_signer_name !== 'boolean'
|
||||
|| (certificate_state !== undefined && !['valid', 'renewal_required', 'unconfirmed'].includes(certificate_state))
|
||||
|| typeof quicksign_enabled !== 'boolean' || typeof quicksign_authorizing !== 'boolean'
|
||||
|| !validTime(cert_expires_at) || !validTime(quicksign_expires_at)
|
||||
|| typeof identity_details_required !== 'boolean'
|
||||
|| (identity_details_required && (!enabled || status !== 'binding_required' || quicksign_authorizing))
|
||||
|| (quicksign_authorizing && (!enabled || !quicksign_enabled || !['authenticating', 'binding_required'].includes(status)))
|
||||
|| !Number.isSafeInteger(quicksign_remaining_times) || quicksign_remaining_times < 0
|
||||
|| !['', 'missing', 'expired', 'exhausted', 'invalid'].includes(quicksign_unavailable_reason)) {
|
||||
throw new Error('医生签署状态无效')
|
||||
}
|
||||
const providerUrl = enabled && status === 'authenticating' ? result.auth_url : undefined
|
||||
const auth_url = safeEsignAuthUrl(providerUrl)
|
||||
return {
|
||||
enabled, status, cert_expires_at, certificate_state, can_edit_signer_name, identity_details_required, quicksign_enabled, quicksign_authorizing,
|
||||
quicksign_expires_at, quicksign_remaining_times, quicksign_unavailable_reason, auth_url,
|
||||
authUrlUnavailable: Boolean(providerUrl && !auth_url)
|
||||
}
|
||||
}
|
||||
|
||||
function clearInputs() {
|
||||
mobile.value = ''
|
||||
signerName.value = ''
|
||||
identityNumber.value = ''
|
||||
}
|
||||
|
||||
function stopAuthentication() {
|
||||
clearTimeout(pollTimer)
|
||||
clearTimeout(deadlineTimer)
|
||||
frameUrl.value = ''
|
||||
}
|
||||
|
||||
function cancelWork() {
|
||||
generation++
|
||||
statusRequest?.abort()
|
||||
statusRequest = undefined
|
||||
pending.value = null
|
||||
clearInputs()
|
||||
stopAuthentication()
|
||||
}
|
||||
|
||||
function clearStatus() {
|
||||
cancelWork()
|
||||
clearTimeout(grantExpiryTimer)
|
||||
state.value = null
|
||||
editingMobile.value = false
|
||||
error.value = ''
|
||||
statusNotice.value = ''
|
||||
}
|
||||
|
||||
function dismiss() {
|
||||
closed = true
|
||||
clearStatus()
|
||||
emit('close')
|
||||
}
|
||||
|
||||
function canAct() {
|
||||
return !closed && document.visibilityState === 'visible'
|
||||
}
|
||||
|
||||
function accept(result: ReturnType<typeof validateStatus>) {
|
||||
clearTimeout(grantExpiryTimer)
|
||||
now.value = Date.now() + props.serverTimeOffsetMs
|
||||
editingMobile.value = false
|
||||
state.value = result
|
||||
if (!authenticating.value || (frameUrl.value && frameUrl.value !== authUrl.value)) stopAuthentication()
|
||||
if (certificateState.value === 'valid') {
|
||||
const expiry = grantActive.value ? Math.min(result.cert_expires_at, result.quicksign_expires_at) : result.cert_expires_at
|
||||
const expiresIn = expiry * 1000 - now.value
|
||||
if (expiresIn <= 2147483647) {
|
||||
grantExpiryTimer = setTimeout(() => { now.value = Date.now() + props.serverTimeOffsetMs }, expiresIn)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function schedulePoll() {
|
||||
if (frameUrl.value) pollTimer = setTimeout(() => void refresh(), pollInterval)
|
||||
}
|
||||
|
||||
function openAuthentication() {
|
||||
if (!canAct() || pending.value || !canResume.value) return
|
||||
frameUrl.value = authUrl.value
|
||||
error.value = ''
|
||||
deadlineTimer = setTimeout(() => {
|
||||
cancelWork()
|
||||
error.value = '自动检查已结束,请检查状态后继续。'
|
||||
}, authenticationTimeout)
|
||||
schedulePoll()
|
||||
}
|
||||
|
||||
function authenticationUnavailable() {
|
||||
if (!frameUrl.value) return
|
||||
cancelWork()
|
||||
error.value = '无法加载 e签宝认证页面,请检查状态后重试。'
|
||||
}
|
||||
|
||||
function enterMobile() {
|
||||
if (!canAct() || pending.value || !canResume.value || state.value?.quicksign_authorizing) return
|
||||
editingMobile.value = true
|
||||
error.value = ''
|
||||
}
|
||||
|
||||
function enterSignerName() {
|
||||
if (!canAct() || pending.value || !canRestartWithSignerName.value) return
|
||||
stopAuthentication()
|
||||
editingMobile.value = true
|
||||
error.value = ''
|
||||
}
|
||||
|
||||
async function submit(
|
||||
kind: DoctorRequest,
|
||||
request: () => Promise<PrescriptionEsignDoctorStatus>
|
||||
) {
|
||||
if (!canAct() || pending.value) return
|
||||
const current = generation
|
||||
clearInputs()
|
||||
clearTimeout(pollTimer)
|
||||
error.value = ''
|
||||
statusNotice.value = ''
|
||||
pending.value = kind
|
||||
try {
|
||||
const result = validateStatus(await request())
|
||||
if (current !== generation || !canAct()) return
|
||||
accept(result)
|
||||
} catch {
|
||||
if (current !== generation || !canAct()) return
|
||||
clearStatus()
|
||||
error.value = kind === 'status' ? '签署身份状态待确认,请重新校验证书或检查认证状态。' : '签署身份操作结果待确认,请检查状态后继续。'
|
||||
return
|
||||
} finally {
|
||||
if (current === generation) pending.value = null
|
||||
}
|
||||
if (kind === 'start') openAuthentication()
|
||||
else schedulePoll()
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
if (!canAct() || pending.value) return
|
||||
const controller = new AbortController()
|
||||
statusRequest = controller
|
||||
try {
|
||||
await submit('status', () => prescriptionEsignDoctorStatus(controller.signal))
|
||||
} finally {
|
||||
if (statusRequest === controller) statusRequest = undefined
|
||||
}
|
||||
}
|
||||
|
||||
async function checkStatus() {
|
||||
if (!canAct() || pending.value) return
|
||||
const checkingFlow = checkingIdentity.value
|
||||
await refresh()
|
||||
if (!canAct() || !state.value?.enabled || error.value) return
|
||||
if (checkingFlow) statusNotice.value = '认证状态已更新。'
|
||||
else if (certificateState.value === 'valid') statusNotice.value = '证书校验通过。'
|
||||
}
|
||||
|
||||
async function start() {
|
||||
if (!canAct() || pending.value) return
|
||||
if (canAuthorizeQuick.value) {
|
||||
await submit('start', () => prescriptionEsignDoctorStart({}))
|
||||
} else if (needsMobile.value) {
|
||||
const number = mobile.value.trim()
|
||||
const name = needsSignerName.value ? signerName.value.trim() : undefined
|
||||
if (!/^1[3-9]\d{9}$/.test(number)) {
|
||||
if (name === undefined) clearInputs()
|
||||
error.value = '请输入有效的大陆手机号码。'
|
||||
return
|
||||
}
|
||||
if (name !== undefined && !/^[\p{Script=Han}A-Za-z][\p{Script=Han}A-Za-z·()\-]{1,49}$/u.test(name)) {
|
||||
error.value = '证件姓名须为 2 至 50 个字符,以汉字或英文字母开头,可包含间隔号(·)、半角括号和连字符。'
|
||||
return
|
||||
}
|
||||
await submit('start', () => prescriptionEsignDoctorStart({
|
||||
mobile: number,
|
||||
...(name !== undefined ? { signer_name: name } : {})
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
async function complete() {
|
||||
if (!canAct() || pending.value || !canComplete.value) return
|
||||
if (needsIdentityNumber.value) {
|
||||
const number = identityNumber.value.trim().toUpperCase()
|
||||
clearInputs()
|
||||
if (!/^(?:\d{15}|\d{17}[\dX])$/.test(number)) {
|
||||
error.value = '请输入本次认证使用的 15 或 18 位大陆居民身份证号码。'
|
||||
return
|
||||
}
|
||||
await submit('complete', () => prescriptionEsignDoctorComplete({ identity_number: number }))
|
||||
} else {
|
||||
await submit('complete', () => prescriptionEsignDoctorComplete({}))
|
||||
}
|
||||
}
|
||||
|
||||
function onVisibilityChange() {
|
||||
if (document.visibilityState === 'visible') void refresh()
|
||||
else {
|
||||
clearStatus()
|
||||
statusNotice.value = '身份验证已暂停,返回此页后会重新检查。'
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
document.addEventListener('visibilitychange', onVisibilityChange)
|
||||
void refresh()
|
||||
})
|
||||
onBeforeUnmount(() => {
|
||||
closed = true
|
||||
clearStatus()
|
||||
document.removeEventListener('visibilitychange', onVisibilityChange)
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.doctor-esign__message, .doctor-esign__error {
|
||||
margin: 0 0 12px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.doctor-esign__message:empty { display: none; }
|
||||
.doctor-esign__error { color: var(--el-color-danger); }
|
||||
.doctor-esign__expiry {
|
||||
display: grid;
|
||||
grid-template-columns: auto minmax(0, 1fr);
|
||||
gap: 8px 16px;
|
||||
margin: 0 0 12px;
|
||||
padding-top: 12px;
|
||||
border-top: 1px solid var(--el-border-color-light);
|
||||
}
|
||||
.doctor-esign__expiry dt { color: var(--el-text-color-secondary); }
|
||||
.doctor-esign__expiry dd { margin: 0; }
|
||||
.doctor-esign__field { display: grid; gap: 6px; max-width: 350px; }
|
||||
.doctor-esign__field + .doctor-esign__field { margin-top: 12px; }
|
||||
.doctor-esign__frame {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: min(60vh, 620px);
|
||||
border: 1px solid var(--el-border-color-light);
|
||||
border-radius: 4px;
|
||||
background: white;
|
||||
}
|
||||
.doctor-esign__actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 8px; }
|
||||
.doctor-esign__actions .el-button + .el-button { margin-left: 0; }
|
||||
</style>
|
||||
@@ -0,0 +1,898 @@
|
||||
<template>
|
||||
<section v-show="showControls || signingTime || showSteps || showSigningLog" class="esign-panel" aria-label="处方电子签署" :aria-busy="busy">
|
||||
<div class="esign-panel__heading">
|
||||
<strong>{{ reviewRequired ? '处方电子签署' : '医师电子签署' }}</strong>
|
||||
<el-tag v-if="state?.environment === 'sandbox' && state.status !== 'legacy'" type="warning" size="small">
|
||||
沙箱测试
|
||||
</el-tag>
|
||||
</div>
|
||||
<div v-if="showSteps" class="esign-panel__progress">
|
||||
<el-steps
|
||||
:active="activeStep"
|
||||
:class="{ 'esign-panel__steps--review': reviewRequired }"
|
||||
finish-status="success"
|
||||
simple
|
||||
>
|
||||
<el-step title="处方草稿已保存" />
|
||||
<el-step v-if="tracksUpload" title="上传处方" />
|
||||
<el-step v-else :title="verificationMethod === 'quick' ? '核对快捷签授权' : verificationMethod === 'sms' ? '校验短信验证码' : '验证医生身份'" />
|
||||
<el-step :title="reviewRequired || tracksUpload ? '医师签署' : '签名并完成'" />
|
||||
<el-step v-if="reviewRequired" title="药师签署" />
|
||||
</el-steps>
|
||||
</div>
|
||||
<p v-if="message" class="esign-panel__message" aria-live="polite">{{ message }}</p>
|
||||
<p v-if="statusNotice" class="esign-panel__message" role="status">{{ statusNotice }}</p>
|
||||
<div v-if="signingTime" class="esign-panel__message" aria-live="polite">
|
||||
<div v-if="signingTime.issuedTime">开具时间:{{ signingTime.issuedTime }}(北京时间)</div>
|
||||
<div v-if="signingTime.signatureTime">
|
||||
医生签署时间:{{ signingTime.signatureTime }}(北京时间 · {{ signingTime.source }})
|
||||
</div>
|
||||
<template v-else>
|
||||
<div>签署时间待核实</div>
|
||||
<div v-if="signingTime.verifiedTime">系统验签完成时间:{{ signingTime.verifiedTime }}(北京时间)</div>
|
||||
</template>
|
||||
</div>
|
||||
<p v-if="reviewSigning" class="esign-panel__message esign-panel__review-signature" aria-live="polite">
|
||||
药师签署时间:<span class="esign-panel__timestamp">{{ reviewSigning.time }}</span>(北京时间 · 可信时间戳)
|
||||
<span v-if="reviewSigning.name"> · {{ reviewSigning.name }}</span>
|
||||
</p>
|
||||
<details v-if="showSigningLog" :key="prescriptionId" class="esign-panel__log">
|
||||
<summary>签署日志</summary>
|
||||
<ol v-if="signingLog.length" class="esign-panel__log-list">
|
||||
<li v-for="(entry, index) in signingLog" :key="`${entry.event}-${entry.time}-${index}`">
|
||||
<strong>{{ entry.label }}</strong>
|
||||
<span v-if="entry.actor_name"> · {{ entry.actor_name }}</span>
|
||||
<div class="esign-panel__log-meta">
|
||||
<time :datetime="new Date(entry.time * 1000).toISOString()">{{ entry.timeText }}</time>
|
||||
(北京时间 · {{ entry.sourceLabel }})
|
||||
</div>
|
||||
<div v-if="entry.message" class="esign-panel__log-meta">{{ entry.message }}</div>
|
||||
</li>
|
||||
</ol>
|
||||
<p v-else class="esign-panel__message">暂无签署日志。</p>
|
||||
</details>
|
||||
<p v-if="error" class="esign-panel__error" role="alert">{{ error }}</p>
|
||||
<label v-if="identityDetailsRequired" class="esign-panel__identity">
|
||||
本次验证使用的身份证号
|
||||
<el-input
|
||||
v-model="identityNumber"
|
||||
type="password"
|
||||
maxlength="18"
|
||||
autocomplete="off"
|
||||
:spellcheck="false"
|
||||
placeholder="输入18位大陆居民身份证号"
|
||||
/>
|
||||
</label>
|
||||
<label v-if="smsCodeEntry" class="esign-panel__identity">
|
||||
短信验证码
|
||||
<el-input
|
||||
v-model="smsCode"
|
||||
type="password"
|
||||
inputmode="numeric"
|
||||
maxlength="6"
|
||||
autocomplete="off"
|
||||
:spellcheck="false"
|
||||
:disabled="busy"
|
||||
placeholder="输入6位短信验证码"
|
||||
/>
|
||||
</label>
|
||||
<div v-if="showControls && prescriptionId > 0" class="esign-panel__actions">
|
||||
<el-button type="primary" size="small" :disabled="busy || dialogVisible || (action.run === sendSms && smsSendCoolingDown)" @click="runAction">
|
||||
{{ action.label }}
|
||||
</el-button>
|
||||
<el-button v-if="smsCodeEntry" size="small" :disabled="busy || smsSendCoolingDown" @click="sendSms">
|
||||
{{ smsSendCoolingDown ? '请稍后重新发送' : '重新发送验证码' }}
|
||||
</el-button>
|
||||
<el-button v-if="readiness || smsCodeEntry" size="small" :disabled="busy" @click="closeAuthentication">退出签署</el-button>
|
||||
<el-button
|
||||
v-if="canOpenCertificate"
|
||||
size="small"
|
||||
:disabled="busy || dialogVisible"
|
||||
@click="doctorIdentityOpen = true"
|
||||
>签署身份与证书</el-button>
|
||||
</div>
|
||||
<EsignDoctorDialog
|
||||
v-if="doctorIdentityOpen"
|
||||
:server-time-offset-ms="userStore.serverTimeOffsetMs"
|
||||
@close="closeDoctorIdentity"
|
||||
/>
|
||||
<EsignReviewPanel
|
||||
v-if="audit && state"
|
||||
:prescription-id="prescriptionId"
|
||||
:order-id="reviewOrderId"
|
||||
:doctor-signed="state.status === 'signed'"
|
||||
:doctor-status-confirmed="confirmed"
|
||||
@change="updateReview"
|
||||
/>
|
||||
<el-dialog
|
||||
:model-value="dialogVisible"
|
||||
title="验证医生身份"
|
||||
width="min(720px, 94vw)"
|
||||
top="5vh"
|
||||
append-to-body
|
||||
destroy-on-close
|
||||
:before-close="closeAuthentication"
|
||||
:close-on-click-modal="false"
|
||||
>
|
||||
<p class="esign-panel__message">请在下方完成本人身份验证。</p>
|
||||
<iframe
|
||||
v-if="authUrl && dialogVisible"
|
||||
:src="authUrl"
|
||||
class="esign-panel__frame"
|
||||
title="e签宝本人身份核验"
|
||||
sandbox="allow-forms allow-scripts allow-same-origin"
|
||||
referrerpolicy="no-referrer"
|
||||
@error="authenticationUnavailable"
|
||||
/>
|
||||
<template #footer>
|
||||
<el-button link @click="authenticationUnavailable">验证页面不可用</el-button>
|
||||
<el-button @click="closeAuthentication">退出签署</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onDeactivated, onMounted, ref, toRaw, watch } from 'vue'
|
||||
import {
|
||||
prescriptionEsignComplete,
|
||||
prescriptionEsignDoctorStatus,
|
||||
prescriptionEsignIdentityStatus,
|
||||
prescriptionEsignStart,
|
||||
prescriptionEsignStatus,
|
||||
prescriptionEsignVerifyWillingness,
|
||||
prescriptionSubmitForReview,
|
||||
type PrescriptionEsignIdentityStatus,
|
||||
type PrescriptionEsignReviewStatus,
|
||||
type PrescriptionEsignStatus
|
||||
} from '@/api/tcm'
|
||||
import {
|
||||
canApprovePrescriptionEsign,
|
||||
canCheckEsignIdentity,
|
||||
downloadOriginalEsignPdf,
|
||||
formatSigningTime,
|
||||
prescriptionEsignTiming,
|
||||
safeEsignAuthUrl,
|
||||
validateEsignIdentityStatus,
|
||||
validateEsignStatus
|
||||
} from '@/utils/prescription-esign'
|
||||
import EsignReviewPanel from '@/components/EsignReviewPanel.vue'
|
||||
import EsignDoctorDialog from '@/components/EsignDoctorDialog.vue'
|
||||
import useUserStore from '@/stores/modules/user'
|
||||
import { DOCTOR_ESIGN_IDENTITY_PERMISSION } from '@/utils/prescription-esign'
|
||||
import { hasPermission } from '@/utils/perm'
|
||||
|
||||
const props = defineProps<{ prescriptionId: number; initialState?: PrescriptionEsignStatus; audit?: boolean; reviewOrderId?: number }>()
|
||||
const emit = defineEmits<{
|
||||
(e: 'status-change', state: PrescriptionEsignStatus): void
|
||||
(e: 'review-change', state: PrescriptionEsignReviewStatus | null): void
|
||||
}>()
|
||||
const userStore = useUserStore()
|
||||
|
||||
const reviewState = ref<PrescriptionEsignReviewStatus | null>(null)
|
||||
function updateReview(result: PrescriptionEsignReviewStatus | null) {
|
||||
reviewState.value = result
|
||||
emit('review-change', result)
|
||||
}
|
||||
|
||||
function initialStatus(): PrescriptionEsignStatus | null {
|
||||
try {
|
||||
return validateEsignStatus(props.initialState)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const state = ref<PrescriptionEsignStatus | null>(initialStatus())
|
||||
const work = ref<'status' | 'upload' | 'start' | 'identity' | 'send-sms' | 'verify-sms' | 'sign' | 'verify' | 'download' | null>(null)
|
||||
const busy = computed(() => work.value !== null)
|
||||
const confirmed = ref(false)
|
||||
const awaitingUpload = computed(() => state.value?.awaiting_upload === true)
|
||||
const tracksUpload = computed(() => awaitingUpload.value || Number(state.value?.review_submitted_at) > 0)
|
||||
const showControls = computed(() => !props.audit || !confirmed.value || !canApprovePrescriptionEsign(state.value))
|
||||
const signingTime = computed(() => prescriptionEsignTiming(state.value))
|
||||
const logSourceLabels = { tsa: '可信时间戳', system: '系统记录', local: '签名记录时间' }
|
||||
const signingLog = computed(() => {
|
||||
const entries = state.value?.signing_log
|
||||
if (!Array.isArray(entries)) return []
|
||||
|
||||
return entries.flatMap((entry) => {
|
||||
if (!entry || typeof entry.event !== 'string' || !entry.event.trim()
|
||||
|| typeof entry.label !== 'string' || !entry.label.trim()
|
||||
|| !['tsa', 'system', 'local'].includes(entry.source)) return []
|
||||
const timeText = formatSigningTime(entry.time)
|
||||
return timeText ? [{ ...entry, timeText, sourceLabel: logSourceLabels[entry.source] }] : []
|
||||
}).sort((a, b) => a.time - b.time)
|
||||
})
|
||||
const showSigningLog = computed(() => signingLog.value.length > 0
|
||||
|| (!props.audit && (state.value?.required === true || Boolean(signingTime.value))))
|
||||
const reviewSigning = computed(() => {
|
||||
const current = state.value
|
||||
if (current?.status !== 'signed' && current?.status !== 'voided') return null
|
||||
|
||||
const time = formatSigningTime(current.review_signature_time)
|
||||
if (time) return { time, name: current.review_signer_name }
|
||||
|
||||
const review = reviewState.value
|
||||
if (review?.state !== 'signed') return null
|
||||
const auditTime = formatSigningTime(review.signature_time)
|
||||
return auditTime ? { time: auditTime, name: review.signer_name } : null
|
||||
})
|
||||
const reviewRequired = computed(() => state.value?.review_required === true || reviewState.value?.required === true
|
||||
|| Boolean(reviewSigning.value))
|
||||
const showSteps = computed(() => {
|
||||
const current = state.value
|
||||
if (!current) return false
|
||||
if (reviewRequired.value) return current.status !== 'voided' || Boolean(reviewSigning.value)
|
||||
return (confirmed.value || busy.value) && current.required && current.status !== 'voided'
|
||||
&& (!props.audit || current.can_sign || current.can_retry_verify === true)
|
||||
})
|
||||
const error = ref('')
|
||||
const statusNotice = ref('')
|
||||
const doctorIdentityOpen = ref(false)
|
||||
const dialogVisible = ref(false)
|
||||
const readiness = ref<'ready' | 'details' | null>(null)
|
||||
const restartRequired = ref(false)
|
||||
const identityNumber = ref('')
|
||||
const smsCode = ref('')
|
||||
const smsCodeState = ref<'entry' | 'expired' | null>(null)
|
||||
const smsSendCoolingDown = ref(false)
|
||||
const smsProfileReady = ref(false)
|
||||
const identityDetailsRequired = computed(() => readiness.value === 'details')
|
||||
const authUrl = computed(() => safeEsignAuthUrl(state.value?.auth_url))
|
||||
type VerificationMethod = NonNullable<PrescriptionEsignStatus['verification_method']>
|
||||
const verificationMethod = computed(() => state.value?.verification_method)
|
||||
const accountSetupMessage = computed(() => {
|
||||
const current = state.value
|
||||
if (!current?.can_sign || !verificationMethod.value) return ''
|
||||
const settings = '请打开「签署身份与证书」处理后继续。'
|
||||
if (current.doctor_identity_required && !(verificationMethod.value === 'sms' && smsProfileReady.value)) {
|
||||
return `${current.message || '请先完成医生签署身份认证。'} ${settings}`
|
||||
}
|
||||
if (!current.signing_authorization_required) return ''
|
||||
const reason = current.signing_authorization_reason
|
||||
const authorization = reason === 'exhausted' ? '快捷签授权次数已用完。' : reason === 'expired' ? '快捷签授权已到期。'
|
||||
: reason === 'invalid' ? '快捷签授权已失效。' : '快捷签授权待完成。'
|
||||
return `${authorization}${settings}`
|
||||
})
|
||||
const smsCodeEntry = computed(() => confirmed.value && smsCodeState.value === 'entry'
|
||||
&& canUseMethod(state.value, 'sms') && state.value?.sms_sent === true && !accountSetupMessage.value && !readiness.value)
|
||||
const identityResumable = computed(() => !verificationMethod.value && canCheckEsignIdentity(state.value)
|
||||
&& (state.value?.can_resume_identity === true || Boolean(authUrl.value)))
|
||||
const activeStep = computed(() => {
|
||||
if (awaitingUpload.value) return 1
|
||||
if (reviewSigning.value) return 4
|
||||
if (state.value?.status === 'signed' && state.value.can_download) return 3
|
||||
if (tracksUpload.value) return 2
|
||||
if (readiness.value || work.value === 'sign' || work.value === 'verify'
|
||||
|| state.value?.status === 'signing' || state.value?.status === 'uncertain') return 2
|
||||
return 1
|
||||
})
|
||||
const message = computed(() => {
|
||||
if (props.prescriptionId <= 0) return '缺少关联处方,无法核对签署状态。'
|
||||
if (work.value === 'status') return '正在查询签署状态…'
|
||||
if (work.value === 'upload') return '正在上传处方…'
|
||||
if (work.value === 'identity' && !readiness.value && verificationMethod.value === 'quick') return '正在核对快捷签授权…'
|
||||
if (work.value === 'identity' && !readiness.value && verificationMethod.value === 'sms') return '正在查询短信验证状态…'
|
||||
if (work.value === 'send-sms') return '正在向医生绑定的手机号发送验证码…'
|
||||
if (work.value === 'verify-sms') return '正在校验短信验证码…'
|
||||
if (work.value === 'sign') return '正在签署处方…'
|
||||
if (work.value === 'verify') return '正在校验已签文件…'
|
||||
if (error.value || (!confirmed.value && !state.value)) return ''
|
||||
if (readiness.value) {
|
||||
if (verificationMethod.value === 'quick') return '快捷签授权已核对。请核对处方内容后确认签名。'
|
||||
if (verificationMethod.value === 'sms') return '短信验证码已通过。请核对处方内容后确认签名。'
|
||||
return '医生身份已验证。'
|
||||
}
|
||||
const current = state.value
|
||||
if (!current) return ''
|
||||
if (awaitingUpload.value) {
|
||||
if (current.can_submit_for_review !== true) return current.message || '请开方医生先上传处方。'
|
||||
if (current.status === 'signed' && current.can_download) return '医师已签署,请上传处方后进入审核。'
|
||||
return current.required ? '请先上传处方,再由开方医生本人签署。' : '请上传处方,提交药师审核。'
|
||||
}
|
||||
if (current.status === 'legacy' && !current.enabled) return current.message || '此处方使用手写签名。'
|
||||
if (current.status === 'signed') {
|
||||
if (reviewRequired.value && !reviewSigning.value) {
|
||||
return current.can_download ? '医师已签署,等待药师审核签署。' : '医师已签署,原件暂不可用,请查询签署状态。'
|
||||
}
|
||||
return current.can_download ? '处方已签署。' : '处方已签署,原件暂不可用。'
|
||||
}
|
||||
if (current.required && ['pending', 'authenticating', 'failed'].includes(current.status)) {
|
||||
if (accountSetupMessage.value) return accountSetupMessage.value
|
||||
if (canUseMethod(current, 'quick')) {
|
||||
return current.message || '请查询签署状态,核对快捷签授权。'
|
||||
}
|
||||
if (canUseMethod(current, 'sms')) {
|
||||
if (smsCodeEntry.value) return '请输入医生绑定的手机号收到的验证码。'
|
||||
if (smsCodeState.value === 'expired') return '本次短信验证码已失效,请重新发送。'
|
||||
if (smsProfileReady.value) return '医生签署身份已就绪,请发送本张处方的验证码。'
|
||||
if (current.message) return current.message
|
||||
return current.sms_sent ? '请查询短信验证状态。' : '请将本张处方的验证码发送到医生绑定的手机号。'
|
||||
}
|
||||
if (current.message) return current.message
|
||||
if (!current.enabled) return '电子签署暂不可用,请联系管理员。'
|
||||
if (props.audit && !current.can_sign) {
|
||||
return '请等待开方医生完成电子签署后,再审核通过。'
|
||||
}
|
||||
if (props.audit) return '请完成核身及电子签署后,再审核通过。'
|
||||
}
|
||||
return current.message || (current.can_sign ? '' : current.status_label)
|
||||
})
|
||||
const action = computed(() => {
|
||||
if (!confirmed.value) return { label: '查询签署状态', run: refresh }
|
||||
if (awaitingUpload.value) {
|
||||
return !props.audit && state.value?.can_submit_for_review === true
|
||||
? { label: '上传处方', run: upload }
|
||||
: { label: '查询签署状态', run: refresh }
|
||||
}
|
||||
if (state.value?.can_download && (state.value.status === 'signed' || state.value.status === 'voided')) {
|
||||
return { label: '下载已签 PDF', run: download }
|
||||
}
|
||||
if (state.value?.status === 'uncertain' && state.value.can_retry_verify) {
|
||||
return { label: '重试校验已签文件', run: retryVerification }
|
||||
}
|
||||
if (state.value?.can_sign && ['pending', 'authenticating', 'failed'].includes(state.value.status)) {
|
||||
if (accountSetupMessage.value) return { label: '查询签署状态', run: refresh }
|
||||
if (readiness.value) return { label: '确认签名', run: confirmSign }
|
||||
if (verificationMethod.value === 'quick') return { label: '查询签署状态', run: refresh }
|
||||
if (verificationMethod.value === 'sms') {
|
||||
if (smsCodeEntry.value) return { label: '校验验证码', run: verifySms }
|
||||
if (state.value.sms_sent && smsCodeState.value !== 'expired') return { label: '查询签署状态', run: refresh }
|
||||
const label = smsSendCoolingDown.value ? '请稍后重新发送' : state.value.sms_sent ? '重新发送验证码' : '发送验证码'
|
||||
return { label, run: sendSms }
|
||||
}
|
||||
if (restartRequired.value) return { label: '重新验证医生身份', run: () => start(true) }
|
||||
if (identityResumable.value) return { label: '检查身份验证', run: recheckIdentity }
|
||||
return { label: state.value.status === 'failed' ? '重新验证医生身份' : '验证医生身份', run: () => start() }
|
||||
}
|
||||
return { label: '查询签署状态', run: refresh }
|
||||
})
|
||||
const canOpenCertificate = computed(() => confirmed.value && hasPermission([DOCTOR_ESIGN_IDENTITY_PERMISSION])
|
||||
&& (canUseMethod(state.value, 'quick') || canUseMethod(state.value, 'sms')))
|
||||
|
||||
const pollInterval = 5000
|
||||
const authenticationTimeout = 10 * 60 * 1000
|
||||
const smsSendCooldown = 60 * 1000
|
||||
let operation = 0
|
||||
let disposed = false
|
||||
let pollTimer: ReturnType<typeof setTimeout> | undefined
|
||||
let deadlineTimer: ReturnType<typeof setTimeout> | undefined
|
||||
let identityRequest: AbortController | undefined
|
||||
let resendTimer: ReturnType<typeof setTimeout> | undefined
|
||||
let expiresAt = 0
|
||||
|
||||
function canAct() {
|
||||
return !disposed && !busy.value && props.prescriptionId > 0 && document.visibilityState === 'visible'
|
||||
}
|
||||
|
||||
function isCurrent(current: number, id: number) {
|
||||
return !disposed && current === operation && id === props.prescriptionId && document.visibilityState === 'visible'
|
||||
}
|
||||
|
||||
function canUseMethod(result: PrescriptionEsignStatus | null, method: VerificationMethod): boolean {
|
||||
return result?.verification_method === method && result.enabled && result.required && result.can_sign
|
||||
&& result.awaiting_upload !== true
|
||||
&& ['pending', 'authenticating', 'failed'].includes(result.status)
|
||||
}
|
||||
|
||||
function accept(result: PrescriptionEsignStatus) {
|
||||
state.value = result
|
||||
confirmed.value = true
|
||||
if (!result.can_sign || !['authenticating', 'failed'].includes(result.status)) restartRequired.value = false
|
||||
emit('status-change', result)
|
||||
}
|
||||
|
||||
function clearVerification() {
|
||||
clearTimeout(pollTimer)
|
||||
clearTimeout(deadlineTimer)
|
||||
pollTimer = undefined
|
||||
deadlineTimer = undefined
|
||||
identityRequest?.abort()
|
||||
identityRequest = undefined
|
||||
dialogVisible.value = false
|
||||
readiness.value = null
|
||||
identityNumber.value = ''
|
||||
smsCode.value = ''
|
||||
smsCodeState.value = null
|
||||
}
|
||||
|
||||
function cancelWork() {
|
||||
operation++
|
||||
work.value = null
|
||||
clearVerification()
|
||||
smsProfileReady.value = false
|
||||
}
|
||||
|
||||
function closeAuthentication() {
|
||||
if (dialogVisible.value || readiness.value || smsCodeEntry.value) {
|
||||
cancelWork()
|
||||
confirmed.value = false
|
||||
error.value = ''
|
||||
statusNotice.value = '已退出本次签署,可查询状态后继续。'
|
||||
}
|
||||
}
|
||||
|
||||
function closeDoctorIdentity() {
|
||||
doctorIdentityOpen.value = false
|
||||
void refresh()
|
||||
}
|
||||
|
||||
function stopVerification(message: string) {
|
||||
clearVerification()
|
||||
error.value = message
|
||||
}
|
||||
|
||||
function authenticationUnavailable() {
|
||||
if (!dialogVisible.value) return
|
||||
cancelWork()
|
||||
error.value = '验证页面无法加载,请重试或联系管理员。'
|
||||
}
|
||||
|
||||
function beginVerification(current: number, id: number) {
|
||||
expiresAt = Date.now() + authenticationTimeout
|
||||
deadlineTimer = setTimeout(() => {
|
||||
if (!isCurrent(current, id)) return
|
||||
cancelWork()
|
||||
error.value = '等待验证超时,请检查身份验证。'
|
||||
}, authenticationTimeout)
|
||||
}
|
||||
|
||||
function schedulePoll(current: number, id: number) {
|
||||
if (dialogVisible.value && isCurrent(current, id)) {
|
||||
pollTimer = setTimeout(() => void checkIdentity(current, id), pollInterval)
|
||||
}
|
||||
}
|
||||
|
||||
async function requestIdentity<T>(request: (signal: AbortSignal) => Promise<T>): Promise<T> {
|
||||
const controller = new AbortController()
|
||||
identityRequest = controller
|
||||
try {
|
||||
return await request(controller.signal)
|
||||
} finally {
|
||||
if (identityRequest === controller) identityRequest = undefined
|
||||
}
|
||||
}
|
||||
|
||||
async function queryIdentity(id: number) {
|
||||
return validateEsignIdentityStatus(await requestIdentity((signal) => prescriptionEsignIdentityStatus({ id }, signal)))
|
||||
}
|
||||
|
||||
async function checkIdentity(current: number, id: number) {
|
||||
if (!isCurrent(current, id) || identityRequest || (!dialogVisible.value && work.value !== 'identity')) return
|
||||
try {
|
||||
const result = await queryIdentity(id)
|
||||
if (!isCurrent(current, id)) return
|
||||
if (Date.now() >= expiresAt) {
|
||||
stopVerification('等待验证超时,请检查身份验证。')
|
||||
return
|
||||
}
|
||||
accept(result)
|
||||
// Only this read-only server response can unlock the explicit confirmation button.
|
||||
if (result.verification_method) {
|
||||
stopVerification('签署方式已变化,请查询签署状态。')
|
||||
} else if (result.identity_status === 'FAIL' || result.identity_status === 'EXPIRED') {
|
||||
restartRequired.value = result.can_sign && ['authenticating', 'failed'].includes(result.status)
|
||||
stopVerification(result.identity_status === 'EXPIRED' ? '本次身份验证已过期。' : '本次身份验证未通过。')
|
||||
} else if (result.status === 'signed') {
|
||||
clearVerification()
|
||||
} else if (!canCheckEsignIdentity(result) || result.identity_status === 'UNAVAILABLE') {
|
||||
stopVerification(result.message || '暂时无法核对身份验证,请重试。')
|
||||
} else if (result.identity_details_required || result.can_complete) {
|
||||
dialogVisible.value = false
|
||||
readiness.value = result.identity_details_required ? 'details' : 'ready'
|
||||
} else if (authUrl.value) {
|
||||
dialogVisible.value = true
|
||||
} else {
|
||||
stopVerification('验证链接不可用,请重试或联系管理员。')
|
||||
}
|
||||
} catch {
|
||||
if (isCurrent(current, id)) {
|
||||
confirmed.value = false
|
||||
stopVerification('身份验证查询失败,请查询签署状态后重试。')
|
||||
}
|
||||
}
|
||||
schedulePoll(current, id)
|
||||
}
|
||||
|
||||
async function recheckIdentity() {
|
||||
if (!canAct() || !confirmed.value || !identityResumable.value || dialogVisible.value || readiness.value || restartRequired.value) return
|
||||
const id = props.prescriptionId
|
||||
const current = ++operation
|
||||
work.value = 'identity'
|
||||
error.value = ''
|
||||
beginVerification(current, id)
|
||||
try {
|
||||
await checkIdentity(current, id)
|
||||
} finally {
|
||||
if (isCurrent(current, id)) work.value = null
|
||||
}
|
||||
}
|
||||
|
||||
async function start(restart = false) {
|
||||
if (!canAct() || !confirmed.value || !state.value?.can_sign || verificationMethod.value || dialogVisible.value || readiness.value
|
||||
|| !['pending', 'authenticating', 'failed'].includes(state.value.status)
|
||||
|| restart !== restartRequired.value || (!restart && identityResumable.value)) return
|
||||
const id = props.prescriptionId
|
||||
const current = ++operation
|
||||
work.value = 'start'
|
||||
confirmed.value = false
|
||||
error.value = ''
|
||||
try {
|
||||
const result = validateEsignStatus(await prescriptionEsignStart(restart ? { id, restart_identity: true } : { id }))
|
||||
if (!isCurrent(current, id)) return
|
||||
accept(result)
|
||||
restartRequired.value = false
|
||||
if (result.status === 'authenticating' && result.can_sign) {
|
||||
if (!authUrl.value) {
|
||||
error.value = '验证链接无效,请重试或联系管理员。'
|
||||
return
|
||||
}
|
||||
dialogVisible.value = true
|
||||
beginVerification(current, id)
|
||||
schedulePoll(current, id)
|
||||
}
|
||||
} catch {
|
||||
if (isCurrent(current, id)) error.value = '验证请求结果待确认,请查询签署状态。'
|
||||
} finally {
|
||||
if (isCurrent(current, id)) work.value = null
|
||||
}
|
||||
}
|
||||
|
||||
function applyMethodIdentity(result: PrescriptionEsignIdentityStatus, method: VerificationMethod, current: number, id: number) {
|
||||
if (result.can_sign && !canUseMethod(result, method)) throw new Error('签署方式已变化')
|
||||
accept(result)
|
||||
if (!canUseMethod(result, method) || accountSetupMessage.value) return
|
||||
if (result.can_complete) {
|
||||
beginVerification(current, id)
|
||||
readiness.value = 'ready'
|
||||
} else if (method === 'sms') {
|
||||
if (result.sms_sent && result.identity_status === 'ING') smsCodeState.value = 'entry'
|
||||
if (result.identity_status === 'EXPIRED' || result.identity_status === 'FAIL') smsCodeState.value = 'expired'
|
||||
}
|
||||
}
|
||||
|
||||
async function readMethodIdentity(current: number, id: number, method: VerificationMethod) {
|
||||
const result = await queryIdentity(id)
|
||||
if (!isCurrent(current, id)) return
|
||||
applyMethodIdentity(result, method, current, id)
|
||||
return result
|
||||
}
|
||||
|
||||
async function prepareQuick(result: PrescriptionEsignStatus, current: number, id: number) {
|
||||
work.value = 'identity'
|
||||
const retained = result.can_resume_identity === true
|
||||
if (retained) {
|
||||
const identity = await readMethodIdentity(current, id, 'quick')
|
||||
if (!identity || identity.identity_status !== 'EXPIRED' || !canUseMethod(identity, 'quick') || accountSetupMessage.value) return
|
||||
}
|
||||
if (!isCurrent(current, id)) return
|
||||
const prepared = validateEsignStatus(await prescriptionEsignStart(retained ? { id, restart_identity: true } : { id }))
|
||||
if (!isCurrent(current, id)) return
|
||||
accept(prepared)
|
||||
if (canUseMethod(prepared, 'quick') && prepared.can_resume_identity && !accountSetupMessage.value) {
|
||||
await readMethodIdentity(current, id, 'quick')
|
||||
}
|
||||
}
|
||||
|
||||
function startSmsCooldown() {
|
||||
clearTimeout(resendTimer)
|
||||
smsSendCoolingDown.value = true
|
||||
resendTimer = setTimeout(() => { smsSendCoolingDown.value = false }, smsSendCooldown)
|
||||
}
|
||||
|
||||
async function sendSms() {
|
||||
if (!canAct() || !confirmed.value || !canUseMethod(state.value, 'sms') || accountSetupMessage.value || readiness.value
|
||||
|| smsSendCoolingDown.value || (state.value?.sms_sent && !smsCodeEntry.value && smsCodeState.value !== 'expired')) return
|
||||
const id = props.prescriptionId
|
||||
const current = ++operation
|
||||
const restart = state.value?.sms_sent === true || state.value?.can_resume_identity === true
|
||||
clearVerification()
|
||||
smsProfileReady.value = false
|
||||
confirmed.value = false
|
||||
work.value = 'send-sms'
|
||||
error.value = ''
|
||||
startSmsCooldown()
|
||||
try {
|
||||
const result = validateEsignStatus(await prescriptionEsignStart(restart ? { id, restart_identity: true } : { id }))
|
||||
if (!isCurrent(current, id)) return
|
||||
accept(result)
|
||||
if (canUseMethod(result, 'sms') && result.sms_sent && result.can_resume_identity && !accountSetupMessage.value) {
|
||||
startSmsCooldown()
|
||||
work.value = 'identity'
|
||||
await readMethodIdentity(current, id, 'sms')
|
||||
}
|
||||
} catch {
|
||||
if (isCurrent(current, id)) {
|
||||
confirmed.value = false
|
||||
error.value = '短信发送状态待确认,请查询签署状态。'
|
||||
}
|
||||
} finally {
|
||||
if (isCurrent(current, id)) work.value = null
|
||||
}
|
||||
}
|
||||
|
||||
async function verifySms() {
|
||||
const code = smsCode.value.trim()
|
||||
smsCode.value = ''
|
||||
if (!canAct() || !smsCodeEntry.value) return
|
||||
if (!/^\d{6}$/.test(code)) {
|
||||
error.value = '请输入6位短信验证码。'
|
||||
return
|
||||
}
|
||||
const id = props.prescriptionId
|
||||
const current = ++operation
|
||||
clearVerification()
|
||||
confirmed.value = false
|
||||
work.value = 'verify-sms'
|
||||
error.value = ''
|
||||
try {
|
||||
const result = validateEsignIdentityStatus(await prescriptionEsignVerifyWillingness({ id, auth_code: code }))
|
||||
if (!isCurrent(current, id)) return
|
||||
applyMethodIdentity(result, 'sms', current, id)
|
||||
if (smsCodeEntry.value) error.value = '验证码未通过,请检查后重试。'
|
||||
} catch {
|
||||
if (isCurrent(current, id)) error.value = '短信校验结果待确认,请查询签署状态。'
|
||||
} finally {
|
||||
if (isCurrent(current, id)) work.value = null
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmSign() {
|
||||
const number = identityNumber.value.trim().toUpperCase()
|
||||
identityNumber.value = ''
|
||||
if (!canAct() || !confirmed.value || !readiness.value || !canCheckEsignIdentity(state.value)) return
|
||||
if (verificationMethod.value && (!canUseMethod(state.value, verificationMethod.value) || accountSetupMessage.value)) return
|
||||
if (Date.now() >= expiresAt) {
|
||||
stopVerification('等待验证超时,请检查身份验证。')
|
||||
return
|
||||
}
|
||||
if (identityDetailsRequired.value && !/^[1-9]\d{16}[\dX]$/.test(number)) {
|
||||
error.value = '请输入本次验证使用的18位大陆居民身份证号。'
|
||||
return
|
||||
}
|
||||
const id = props.prescriptionId
|
||||
await submitCompletion('sign', identityDetailsRequired.value ? { id, identity_number: number } : { id })
|
||||
}
|
||||
|
||||
async function retryVerification() {
|
||||
if (!canAct() || !confirmed.value || state.value?.status !== 'uncertain' || state.value.can_retry_verify !== true) return
|
||||
await submitCompletion('verify', { id: props.prescriptionId, verify_only: true })
|
||||
}
|
||||
|
||||
async function submitCompletion(kind: 'sign' | 'verify', params: Parameters<typeof prescriptionEsignComplete>[0]) {
|
||||
const current = ++operation
|
||||
const { id } = params
|
||||
// Consume readiness before dispatch. Neither an error nor a late reply replays the POST.
|
||||
clearVerification()
|
||||
confirmed.value = false
|
||||
work.value = kind
|
||||
error.value = ''
|
||||
try {
|
||||
const result = validateEsignStatus(await prescriptionEsignComplete(params))
|
||||
if (isCurrent(current, id)) accept(result)
|
||||
} catch {
|
||||
if (isCurrent(current, id)) {
|
||||
error.value = kind === 'sign' ? '签署结果待确认,请查询签署状态。' : '校验结果待确认,请查询签署状态。'
|
||||
}
|
||||
} finally {
|
||||
if (isCurrent(current, id)) work.value = null
|
||||
}
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
if (!canAct()) return
|
||||
const id = props.prescriptionId
|
||||
const current = ++operation
|
||||
clearVerification()
|
||||
smsProfileReady.value = false
|
||||
work.value = 'status'
|
||||
confirmed.value = false
|
||||
error.value = ''
|
||||
statusNotice.value = ''
|
||||
try {
|
||||
const result = validateEsignStatus(await requestIdentity((signal) => prescriptionEsignStatus({ id }, signal)))
|
||||
if (!isCurrent(current, id)) return
|
||||
accept(result)
|
||||
// A previous SMS failure can retain the setup flag after the doctor fixes the profile.
|
||||
if (canUseMethod(result, 'sms') && result.doctor_identity_required) {
|
||||
work.value = 'identity'
|
||||
const profile = await requestIdentity(prescriptionEsignDoctorStatus)
|
||||
if (!isCurrent(current, id)) return
|
||||
smsProfileReady.value = profile?.enabled === true && profile.status === 'ready'
|
||||
}
|
||||
if (accountSetupMessage.value) return
|
||||
if (canUseMethod(result, 'quick')) {
|
||||
await prepareQuick(result, current, id)
|
||||
} else if (canUseMethod(result, 'sms') && result.sms_sent && result.can_resume_identity) {
|
||||
work.value = 'identity'
|
||||
await readMethodIdentity(current, id, 'sms')
|
||||
}
|
||||
} catch {
|
||||
if (isCurrent(current, id)) {
|
||||
confirmed.value = false
|
||||
error.value = work.value === 'identity' ? '暂时无法核对签署条件,请查询签署状态后重试。' : '签署状态查询失败,请重试。'
|
||||
}
|
||||
} finally {
|
||||
if (isCurrent(current, id)) work.value = null
|
||||
}
|
||||
}
|
||||
|
||||
async function runAction() {
|
||||
const run = action.value.run
|
||||
const current = operation
|
||||
await run()
|
||||
if (run === refresh && operation === current + 1 && confirmed.value && !error.value && isCurrent(operation, props.prescriptionId)) {
|
||||
statusNotice.value = '签署状态已更新。'
|
||||
}
|
||||
}
|
||||
|
||||
async function upload() {
|
||||
const before = state.value
|
||||
if (!canAct() || !confirmed.value || props.audit || !awaitingUpload.value || before?.can_submit_for_review !== true) return
|
||||
const id = props.prescriptionId
|
||||
const current = ++operation
|
||||
work.value = 'upload'
|
||||
error.value = ''
|
||||
statusNotice.value = ''
|
||||
try {
|
||||
const result = await prescriptionSubmitForReview({ id })
|
||||
if (!isCurrent(current, id)) return
|
||||
if (!Number.isSafeInteger(result?.review_submitted_at) || result.review_submitted_at <= 0) {
|
||||
throw new Error('无法核对上传结果')
|
||||
}
|
||||
accept({
|
||||
...before,
|
||||
review_submitted_at: result.review_submitted_at,
|
||||
awaiting_upload: false,
|
||||
can_submit_for_review: false
|
||||
})
|
||||
} catch {
|
||||
if (isCurrent(current, id)) error.value = '暂未确认处方上传,请重试。'
|
||||
return
|
||||
} finally {
|
||||
if (isCurrent(current, id)) work.value = null
|
||||
}
|
||||
await refresh()
|
||||
if (isCurrent(current + 1, id)) statusNotice.value = '处方已上传。'
|
||||
}
|
||||
|
||||
async function download() {
|
||||
if (!canAct() || !confirmed.value || !state.value?.can_download
|
||||
|| (state.value.status !== 'signed' && state.value.status !== 'voided')) return
|
||||
const id = props.prescriptionId
|
||||
const current = ++operation
|
||||
work.value = 'download'
|
||||
error.value = ''
|
||||
try {
|
||||
const result = validateEsignStatus(await requestIdentity((signal) => prescriptionEsignStatus({ id }, signal)))
|
||||
if (!isCurrent(current, id)) return
|
||||
accept(result)
|
||||
if (result.can_download && (result.status === 'signed' || result.status === 'voided')) {
|
||||
await downloadOriginalEsignPdf(id, () => isCurrent(current, id))
|
||||
} else {
|
||||
error.value = '已签 PDF 暂不可下载。'
|
||||
}
|
||||
} catch {
|
||||
if (isCurrent(current, id)) error.value = '下载已签 PDF 失败,请重试。'
|
||||
} finally {
|
||||
if (isCurrent(current, id)) work.value = null
|
||||
}
|
||||
}
|
||||
|
||||
function onVisibilityChange() {
|
||||
if (document.visibilityState === 'visible') return
|
||||
if (dialogVisible.value || readiness.value) {
|
||||
confirmed.value = false
|
||||
statusNotice.value = '签署验证已暂停,可查询状态后继续。'
|
||||
}
|
||||
if (work.value === 'sign') error.value = '签署结果待确认,请查询签署状态。'
|
||||
if (work.value === 'upload') error.value = '上传结果待确认,请查询处方状态。'
|
||||
if (work.value === 'verify') error.value = '校验结果待确认,请查询签署状态。'
|
||||
if (work.value === 'send-sms') error.value = '短信发送状态待确认,请查询签署状态。'
|
||||
if (work.value === 'verify-sms') error.value = '短信校验结果待确认,请查询签署状态。'
|
||||
cancelWork()
|
||||
}
|
||||
|
||||
function resetStatus() {
|
||||
cancelWork()
|
||||
restartRequired.value = false
|
||||
confirmed.value = false
|
||||
error.value = ''
|
||||
statusNotice.value = ''
|
||||
doctorIdentityOpen.value = false
|
||||
state.value = initialStatus()
|
||||
void refresh()
|
||||
}
|
||||
|
||||
watch(() => props.prescriptionId, () => {
|
||||
reviewState.value = null
|
||||
resetStatus()
|
||||
}, { immediate: true })
|
||||
watch(() => props.initialState, (value) => {
|
||||
// An emitted state echoed by the parent preserves this interaction.
|
||||
if (toRaw(value) !== toRaw(state.value)) resetStatus()
|
||||
})
|
||||
|
||||
onMounted(() => document.addEventListener('visibilitychange', onVisibilityChange))
|
||||
onDeactivated(cancelWork)
|
||||
onBeforeUnmount(() => {
|
||||
disposed = true
|
||||
cancelWork()
|
||||
clearTimeout(resendTimer)
|
||||
document.removeEventListener('visibilitychange', onVisibilityChange)
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.esign-panel {
|
||||
margin: 12px 0;
|
||||
padding: 14px 16px;
|
||||
border: 1px solid var(--el-border-color-light);
|
||||
border-radius: 6px;
|
||||
background: var(--el-bg-color);
|
||||
}
|
||||
.esign-panel__heading, .esign-panel__actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.esign-panel :deep(.el-steps) { margin: 10px 0; padding: 10px 12px; }
|
||||
.esign-panel :deep(.el-step.is-simple .el-step__title) { font-size: 13px; line-height: 1.4; word-break: normal; }
|
||||
.esign-panel__progress { container-type: inline-size; }
|
||||
.esign-panel__steps--review {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr;
|
||||
gap: 8px 12px;
|
||||
}
|
||||
.esign-panel__steps--review :deep(.el-step.is-simple:last-of-type) { max-width: none !important; }
|
||||
.esign-panel__steps--review :deep(.el-step.is-simple .el-step__title) { max-width: none; white-space: nowrap; }
|
||||
.esign-panel__steps--review :deep(.el-step.is-simple .el-step__arrow) { display: none; }
|
||||
.esign-panel__review-signature { overflow-wrap: anywhere; }
|
||||
.esign-panel__timestamp { white-space: nowrap; }
|
||||
.esign-panel__actions { margin-top: 10px; }
|
||||
.esign-panel__actions .el-button + .el-button { margin-left: 0; }
|
||||
.esign-panel__message, .esign-panel__error { margin: 8px 0; font-size: 13px; }
|
||||
.esign-panel__message { color: var(--el-text-color-secondary); }
|
||||
.esign-panel__error { color: var(--el-color-danger); }
|
||||
.esign-panel__log {
|
||||
margin: 10px 0;
|
||||
font-size: 13px;
|
||||
}
|
||||
.esign-panel__log summary {
|
||||
width: fit-content;
|
||||
color: var(--el-color-primary);
|
||||
cursor: pointer;
|
||||
font-weight: 500;
|
||||
}
|
||||
.esign-panel__log-list {
|
||||
margin: 8px 0 0;
|
||||
padding-inline-start: 24px;
|
||||
list-style: decimal;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.esign-panel__log-list li + li { margin-top: 8px; }
|
||||
.esign-panel__log-meta { color: var(--el-text-color-secondary); }
|
||||
.esign-panel__identity { display: grid; gap: 6px; max-width: 320px; margin: 10px 0; font-size: 13px; }
|
||||
.esign-panel__frame {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: min(62vh, 620px);
|
||||
min-height: 300px;
|
||||
border: 1px solid var(--el-border-color-light);
|
||||
border-radius: 4px;
|
||||
background: white;
|
||||
}
|
||||
@container (min-width: 280px) {
|
||||
.esign-panel__steps--review { grid-template-columns: repeat(2, minmax(max-content, 1fr)); }
|
||||
}
|
||||
@container (min-width: 480px) {
|
||||
.esign-panel__steps--review { grid-template-columns: repeat(4, minmax(max-content, 1fr)); gap: 0; }
|
||||
.esign-panel__steps--review :deep(.el-step.is-simple:not(:last-of-type) .el-step__arrow) {
|
||||
display: flex;
|
||||
min-width: 18px;
|
||||
}
|
||||
}
|
||||
@media print { .esign-panel { display: none; } }
|
||||
</style>
|
||||
@@ -0,0 +1,184 @@
|
||||
<template>
|
||||
<div v-if="state?.required || error || busy" class="esign-review" :aria-busy="busy" aria-label="处方审核电子签署">
|
||||
<strong>审核电子签署</strong>
|
||||
<p v-if="state?.actor_name">当前审核人 {{ state.actor_name }}</p>
|
||||
<p v-if="state?.message" aria-live="polite">{{ state.message }}</p>
|
||||
<p v-if="busy && !state" role="status">正在查询药师签署状态…</p>
|
||||
<p v-if="statusNotice" role="status">{{ statusNotice }}</p>
|
||||
<p v-if="error" class="text-danger" role="alert">{{ error }}</p>
|
||||
<div class="esign-review__actions">
|
||||
<el-button v-if="state?.can_confirm" type="primary" size="small" :disabled="busy || !doctorStatusConfirmed" @click="confirm(false)">
|
||||
确认签名
|
||||
</el-button>
|
||||
<el-button v-if="state?.can_retry_verify" type="primary" size="small" :disabled="busy || !doctorStatusConfirmed" @click="confirm(true)">
|
||||
重试验签
|
||||
</el-button>
|
||||
<el-button v-if="state?.required && doctorSigned" size="small" :disabled="busy" @click="download">
|
||||
{{ state.state === 'signed' ? '下载双签 PDF' : '下载医生已签 PDF' }}
|
||||
</el-button>
|
||||
<el-button
|
||||
v-if="state?.can_setup && state.state !== 'signed'"
|
||||
size="small"
|
||||
:disabled="busy"
|
||||
@click="identityOpen = true"
|
||||
>
|
||||
审核签署身份
|
||||
</el-button>
|
||||
<el-button v-if="error || state?.state !== 'signed'" size="small" :disabled="busy" @click="checkStatus">
|
||||
刷新签署状态
|
||||
</el-button>
|
||||
</div>
|
||||
<EsignDoctorDialog
|
||||
v-if="identityOpen"
|
||||
reviewer
|
||||
:server-time-offset-ms="userStore.serverTimeOffsetMs"
|
||||
@close="closeIdentity"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, ref, watch } from 'vue'
|
||||
|
||||
import {
|
||||
prescriptionEsignReviewConfirm,
|
||||
prescriptionEsignReviewStatus,
|
||||
type PrescriptionEsignReviewStatus
|
||||
} from '@/api/tcm'
|
||||
import EsignDoctorDialog from '@/components/EsignDoctorDialog.vue'
|
||||
import useUserStore from '@/stores/modules/user'
|
||||
import { downloadOriginalEsignPdf } from '@/utils/prescription-esign'
|
||||
|
||||
const props = defineProps<{ prescriptionId: number; orderId?: number; doctorSigned: boolean; doctorStatusConfirmed: boolean }>()
|
||||
const emit = defineEmits<{ (e: 'change', value: PrescriptionEsignReviewStatus | null): void }>()
|
||||
const state = ref<PrescriptionEsignReviewStatus | null>(null)
|
||||
const identityOpen = ref(false)
|
||||
const busy = ref(false)
|
||||
const error = ref('')
|
||||
const statusNotice = ref('')
|
||||
const userStore = useUserStore()
|
||||
let generation = 0
|
||||
let statusRequest: AbortController | undefined
|
||||
|
||||
function errorMessage(cause: unknown, fallback: string): string {
|
||||
if (typeof cause === 'object' && cause !== null && 'msg' in cause && typeof cause.msg === 'string') {
|
||||
return cause.msg
|
||||
}
|
||||
return cause instanceof Error ? cause.message : fallback
|
||||
}
|
||||
|
||||
function accept(result: PrescriptionEsignReviewStatus) {
|
||||
if (!result || ['required', 'can_confirm', 'can_approve', 'can_retry_verify'].some((field) => typeof (result as any)[field] !== 'boolean')
|
||||
|| result.actor_id !== Number(userStore.userInfo.id)) {
|
||||
throw new Error('登录账号或审核状态已变化,请刷新页面')
|
||||
}
|
||||
state.value = result
|
||||
emit('change', props.doctorStatusConfirmed ? result : null)
|
||||
}
|
||||
|
||||
function target() {
|
||||
return { id: props.prescriptionId, ...(props.orderId ? { order_id: props.orderId } : {}) }
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
const ticket = ++generation
|
||||
statusRequest?.abort()
|
||||
statusRequest = new AbortController()
|
||||
busy.value = true
|
||||
error.value = ''
|
||||
statusNotice.value = ''
|
||||
emit('change', null)
|
||||
try {
|
||||
const result = await prescriptionEsignReviewStatus(target(), statusRequest.signal)
|
||||
if (ticket === generation) accept(result)
|
||||
} catch (cause) {
|
||||
if (ticket === generation) error.value = errorMessage(cause, '无法查询审核签署状态')
|
||||
} finally {
|
||||
if (ticket === generation) busy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function confirm(verifyOnly: boolean) {
|
||||
const actorId = state.value?.actor_id
|
||||
if (busy.value || !props.doctorStatusConfirmed || !actorId || !(verifyOnly ? state.value?.can_retry_verify : state.value?.can_confirm)) return
|
||||
const ticket = ++generation
|
||||
busy.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const result = await prescriptionEsignReviewConfirm({ ...target(), actor_id: actorId, verify_only: verifyOnly })
|
||||
if (ticket === generation) accept(result)
|
||||
} catch (cause) {
|
||||
if (ticket === generation) {
|
||||
await refresh()
|
||||
if (generation === ticket + 1) {
|
||||
error.value = errorMessage(cause, '请刷新状态或续期本人的快捷签授权后重试')
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (ticket === generation) busy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function checkStatus() {
|
||||
const current = generation
|
||||
await refresh()
|
||||
if (generation === current + 1 && state.value && !error.value) statusNotice.value = '药师签署状态已更新。'
|
||||
}
|
||||
|
||||
async function download() {
|
||||
if (busy.value || !props.doctorSigned) return
|
||||
const ticket = generation
|
||||
const actor = userStore.userInfo.id
|
||||
busy.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
await downloadOriginalEsignPdf(props.prescriptionId,
|
||||
() => generation === ticket && userStore.userInfo.id === actor)
|
||||
} catch (cause) {
|
||||
if (generation === ticket) error.value = errorMessage(cause, '下载签署原件失败,请重试')
|
||||
} finally {
|
||||
if (generation === ticket) busy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function closeIdentity() {
|
||||
identityOpen.value = false
|
||||
void checkStatus()
|
||||
}
|
||||
|
||||
watch(() => [props.prescriptionId, props.orderId, userStore.userInfo.id], () => {
|
||||
identityOpen.value = false
|
||||
state.value = null
|
||||
if (props.prescriptionId > 0) void refresh()
|
||||
}, { immediate: true })
|
||||
watch(() => props.doctorSigned, () => { if (props.prescriptionId > 0) void refresh() })
|
||||
watch(() => props.doctorStatusConfirmed, (confirmed) => emit('change', confirmed && !busy.value && !error.value ? state.value : null))
|
||||
onBeforeUnmount(() => {
|
||||
generation++
|
||||
statusRequest?.abort()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.esign-review {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
border-top: 1px solid var(--el-border-color-light);
|
||||
margin-top: 12px;
|
||||
padding-top: 12px;
|
||||
}
|
||||
|
||||
.esign-review p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.esign-review__actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.esign-review__actions :deep(.el-button + .el-button) {
|
||||
margin-left: 0;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,115 @@
|
||||
<template>
|
||||
<div v-if="prescriptionId !== null" class="prescription-audit-layout">
|
||||
<section class="prescription-audit-preview" aria-label="处方单" :aria-busy="loading">
|
||||
<PrescriptionSlip v-if="detail" :data="detail" compact />
|
||||
<el-skeleton v-else-if="loading" :rows="8" animated />
|
||||
<div v-if="error" class="prescription-audit-preview__error" role="status">
|
||||
<span>{{ error }}</span>
|
||||
<el-button v-if="prescriptionId > 0" size="small" @click="retry++">重试加载处方</el-button>
|
||||
</div>
|
||||
</section>
|
||||
<section class="prescription-audit-controls" aria-label="签署和审核">
|
||||
<slot />
|
||||
</section>
|
||||
</div>
|
||||
<slot v-else />
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from 'vue'
|
||||
import { prescriptionDetail } from '@/api/tcm'
|
||||
import PrescriptionSlip from '@/components/prescription-slip/index.vue'
|
||||
|
||||
const props = defineProps<{
|
||||
prescriptionId: number | null
|
||||
doctorSignedAt?: number
|
||||
pharmacistSignedAt?: number
|
||||
}>()
|
||||
|
||||
const detail = ref<Record<string, any> | null>(null)
|
||||
const retry = ref(0)
|
||||
const loading = ref(false)
|
||||
const error = ref('')
|
||||
|
||||
watch([
|
||||
() => props.prescriptionId,
|
||||
() => props.doctorSignedAt,
|
||||
() => props.pharmacistSignedAt,
|
||||
retry
|
||||
], async ([id, doctorAt, pharmacistAt, attempt], previous, onCleanup) => {
|
||||
if (id !== previous?.[0]) detail.value = null
|
||||
loading.value = false
|
||||
error.value = ''
|
||||
if (id === null) return
|
||||
if (!Number.isSafeInteger(id) || id <= 0) {
|
||||
error.value = '当前订单未关联处方'
|
||||
return
|
||||
}
|
||||
const current = detail.value?.esign
|
||||
if (detail.value && attempt === previous?.[3]
|
||||
&& (!doctorAt || doctorAt === (current?.signature_time || current?.signed_at))
|
||||
&& (!pharmacistAt || pharmacistAt === current?.review_signature_time)) return
|
||||
|
||||
const controller = new AbortController()
|
||||
onCleanup(() => controller.abort())
|
||||
loading.value = true
|
||||
try {
|
||||
const response = await prescriptionDetail({ id }, controller.signal)
|
||||
const result = response?.data ?? response
|
||||
if (controller.signal.aborted) return
|
||||
if (Number(result?.id) !== id) throw new Error('处方编号不匹配')
|
||||
detail.value = result
|
||||
} catch {
|
||||
if (!controller.signal.aborted) error.value = '无法加载处方单,请重试。'
|
||||
} finally {
|
||||
if (!controller.signal.aborted) loading.value = false
|
||||
}
|
||||
}, { immediate: true })
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.prescription-audit-layout {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1.42fr) minmax(320px, 1fr);
|
||||
gap: 18px;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.prescription-audit-preview,
|
||||
.prescription-audit-controls {
|
||||
min-width: 0;
|
||||
max-height: min(68vh, 780px);
|
||||
overflow: auto;
|
||||
scrollbar-gutter: stable;
|
||||
}
|
||||
|
||||
.prescription-audit-preview {
|
||||
padding: 10px;
|
||||
border: 1px solid var(--el-border-color-light);
|
||||
border-radius: 8px;
|
||||
background: var(--el-fill-color-light);
|
||||
}
|
||||
|
||||
.prescription-audit-controls { padding-right: 3px; }
|
||||
|
||||
.prescription-audit-preview__error {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 10px;
|
||||
color: var(--el-text-color-regular);
|
||||
}
|
||||
|
||||
@media (max-width: 840px) {
|
||||
.prescription-audit-layout {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
gap: 12px;
|
||||
max-height: 70vh;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.prescription-audit-preview { max-height: min(50vh, 560px); }
|
||||
.prescription-audit-controls { max-height: none; overflow: visible; }
|
||||
}
|
||||
</style>
|
||||
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<div ref="paperRef" class="rx-paper">
|
||||
<div ref="paperRef" class="rx-paper" :class="{ 'rx-paper--compact': compact }">
|
||||
<div class="rx-title">{{ isInternal ? '药房联' : slipTitle }}</div>
|
||||
<div class="rx-notice">
|
||||
<span class="rx-notice-text">
|
||||
@@ -154,21 +154,42 @@
|
||||
</div>
|
||||
|
||||
<div class="rx-bottom">
|
||||
<div class="rx-bot-row rx-bot-row-1" :class="{ 'rx-bot-row-1--user': !isInternal }">
|
||||
<div
|
||||
class="rx-bot-row rx-bot-row-1"
|
||||
:class="{ 'rx-bot-row-1--user': !isInternal, 'rx-bot-row-1--reviewed': reviewerName }"
|
||||
>
|
||||
<div class="rx-bot-cell rx-bot-doctor">
|
||||
<div class="rx-bot-label rx-bot-label--doctor">医师</div>
|
||||
<div class="rx-bot-label rx-bot-label--inline">医师</div>
|
||||
<div class="rx-bot-doctor-body">
|
||||
<img
|
||||
v-if="data?.doctor_signature"
|
||||
:src="data.doctor_signature"
|
||||
alt="医师签名"
|
||||
v-if="doctorSignature"
|
||||
:src="doctorSignature"
|
||||
:alt="doctorName"
|
||||
class="rx-bot-sign-img"
|
||||
@error="onDoctorSignatureError"
|
||||
/>
|
||||
<span v-if="!data?.doctor_signature" class="rx-bot-doctor-name">
|
||||
{{ data?.doctor_name || '—' }}
|
||||
</span>
|
||||
<span v-else class="rx-bot-doctor-name">{{ doctorName }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="reviewerName" class="rx-bot-cell rx-bot-reviewer">
|
||||
<span class="rx-bot-label rx-bot-label--inline">药师审核</span>
|
||||
<img
|
||||
v-if="reviewerSignature"
|
||||
:src="reviewerSignature"
|
||||
:alt="reviewerName"
|
||||
class="rx-bot-sign-img"
|
||||
@error="onReviewerSignatureError"
|
||||
/>
|
||||
<span v-else class="rx-bot-reviewer-name">{{ reviewerName }}</span>
|
||||
</div>
|
||||
<div
|
||||
v-else-if="showPharmacistSample"
|
||||
class="rx-bot-cell rx-bot-reviewer rx-pharmacist-sample"
|
||||
data-html2canvas-ignore="true"
|
||||
>
|
||||
<span class="rx-bot-label rx-bot-label--inline">药师</span>
|
||||
<img :src="pharmacistImage" alt="签名预览" class="rx-bot-sign-img" />
|
||||
</div>
|
||||
<div v-if="isInternal" class="rx-bot-cell rx-bot-meta">
|
||||
<span class="rx-bot-meta-key">类型:</span>
|
||||
<span class="rx-bot-meta-val">{{ typeText }}</span>
|
||||
@@ -192,9 +213,13 @@
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { computed, ref } from 'vue'
|
||||
import type { PrescriptionEsignStatus } from '@/api/tcm'
|
||||
// 来源:https://gz-1349751149.cos.ap-guangzhou.myqcloud.com/uploads/images/20261203/2026120314015402c2e8093.png
|
||||
import pharmacistImage from '@/assets/images/pharmacist-signature-20261203.png'
|
||||
import {
|
||||
getAuxHerbs,
|
||||
getMainHerbs,
|
||||
getSlipHerbs,
|
||||
rxAdviceText,
|
||||
rxAppointmentFlowText,
|
||||
rxAuxUsageText,
|
||||
@@ -226,6 +251,8 @@ const props = withDefaults(
|
||||
auxLibraryName?: string
|
||||
/** 抬头(处方联) */
|
||||
title?: string
|
||||
compact?: boolean
|
||||
showPharmacistSignatureSample?: boolean
|
||||
}>(),
|
||||
{
|
||||
variant: 'internal',
|
||||
@@ -237,6 +264,57 @@ const props = withDefaults(
|
||||
const paperRef = ref<HTMLElement | null>(null)
|
||||
const isInternal = computed(() => props.variant !== 'user')
|
||||
const slipTitle = computed(() => props.title || '成都双流甄养堂互联网医院 处方笺')
|
||||
const verifiedDoctor = computed(() => {
|
||||
const signing: PrescriptionEsignStatus | undefined = props.data?.esign
|
||||
if (signing?.status === 'signed' || (signing?.status === 'voided' && signing.can_download)) return signing
|
||||
return null
|
||||
})
|
||||
const doctorName = computed(() => {
|
||||
const signer = verifiedDoctor.value?.doctor_signer_name
|
||||
return (typeof signer === 'string' && signer.trim()) || props.data?.doctor_name || '—'
|
||||
})
|
||||
const failedDoctorSignature = ref('')
|
||||
const doctorSignature = computed(() => {
|
||||
const signature = props.data?.doctor_signature
|
||||
if (verifiedDoctor.value && !isVerifiedSignaturePng(signature)) return ''
|
||||
if (!verifiedDoctor.value && props.data?.esign?.required) return ''
|
||||
return typeof signature === 'string' && signature !== failedDoctorSignature.value ? signature : ''
|
||||
})
|
||||
const reviewerName = computed(() => {
|
||||
const signing = props.data?.esign
|
||||
if (!signing || !['signed', 'voided'].includes(signing.status)
|
||||
|| !Number.isInteger(signing.review_signature_time) || signing.review_signature_time <= 0) return ''
|
||||
return typeof signing.review_signer_name === 'string' ? signing.review_signer_name.trim() : ''
|
||||
})
|
||||
const failedReviewerSignature = ref('')
|
||||
const reviewerSignature = computed(() => {
|
||||
const signature = props.data?.esign?.review_signature
|
||||
return reviewerName.value && isVerifiedSignaturePng(signature) && signature !== failedReviewerSignature.value ? signature : ''
|
||||
})
|
||||
const showPharmacistSample = computed(() => {
|
||||
const data = props.data
|
||||
const signing: PrescriptionEsignStatus | undefined = data?.esign
|
||||
if (!props.showPharmacistSignatureSample || !data || signing?.status !== 'legacy'
|
||||
|| signing.required !== false || signing.can_download !== false || !getSlipHerbs(data).length
|
||||
|| Number(data.is_system_auto) === 1 || Number(data.void_status) === 1 || Number(data.audit_status) === 2) return false
|
||||
if (signing.review_state === 'signed' || Number(signing.review_signature_time) > 0
|
||||
|| signing.review_signature || signing.review_signer_name) return false
|
||||
return Number(data.audit_status) === 1
|
||||
|| (Number(signing.review_submitted_at ?? data.review_submitted_at) > 0
|
||||
&& typeof data.doctor_signature === 'string' && data.doctor_signature.trim() !== '')
|
||||
})
|
||||
|
||||
function isVerifiedSignaturePng(signature: unknown): signature is string {
|
||||
return typeof signature === 'string' && /^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/.test(signature)
|
||||
}
|
||||
|
||||
function onDoctorSignatureError(event: Event) {
|
||||
if (event.currentTarget instanceof HTMLImageElement) failedDoctorSignature.value = event.currentTarget.getAttribute('src') ?? ''
|
||||
}
|
||||
|
||||
function onReviewerSignatureError(event: Event) {
|
||||
if (event.currentTarget instanceof HTMLImageElement) failedReviewerSignature.value = event.currentTarget.src
|
||||
}
|
||||
|
||||
const dateText = computed(() => rxDateText(props.data))
|
||||
const prescriptionSnText = computed(() => rxPrescriptionSnText(props.data))
|
||||
@@ -257,13 +335,11 @@ const outPelletText = computed(() => rxOutPelletText(props.data))
|
||||
const typeText = computed(() => rxTypeText(props.data))
|
||||
const perDoseAmount = computed(() => rxPerDoseAmount(props.data))
|
||||
const daysText = computed(() => {
|
||||
const md = props.data?.medication_days
|
||||
if (md != null && String(md).trim() !== '') {
|
||||
return `${md} 天`
|
||||
}
|
||||
const dose = props.data?.dose_count
|
||||
if (dose != null && String(dose).trim() !== '') {
|
||||
return `${dose}剂`
|
||||
// 订单用药天数优先,其次处方服用天数;剂数(多为默认 1)不是天数,不再顶替。
|
||||
for (const value of [props.data?.medication_days, props.data?.usage_days]) {
|
||||
if (value != null && String(value).trim() !== '' && Number(value) > 0) {
|
||||
return `${value} 天`
|
||||
}
|
||||
}
|
||||
return '—'
|
||||
})
|
||||
@@ -602,6 +678,7 @@ defineExpose({
|
||||
}
|
||||
|
||||
.rx-bot-row-1 {
|
||||
--rx-reviewed-columns: minmax(164px, 1.15fr) minmax(188px, 1.3fr) 1.4fr 0.75fr 0.85fr;
|
||||
/* 类型/剂数/单剂量 三个 meta 列适当加宽,
|
||||
* 避免"浓缩丸-浓缩水丸"被强制折行后把整行挤错位 */
|
||||
grid-template-columns: 1.6fr 0.6fr 0.6fr 0.6fr 0.6fr 1.7fr 0.95fr 1.25fr;
|
||||
@@ -609,9 +686,20 @@ defineExpose({
|
||||
}
|
||||
|
||||
.rx-bot-row-1--user {
|
||||
--rx-reviewed-columns: minmax(164px, 1.6fr) minmax(188px, 1.6fr) 0.6fr;
|
||||
grid-template-columns: 1.6fr 0.6fr;
|
||||
}
|
||||
|
||||
.rx-bot-row-1--reviewed {
|
||||
grid-template-columns: var(--rx-reviewed-columns);
|
||||
}
|
||||
|
||||
@media screen {
|
||||
.rx-bot-row-1:has(> .rx-pharmacist-sample) {
|
||||
grid-template-columns: var(--rx-reviewed-columns);
|
||||
}
|
||||
}
|
||||
|
||||
.rx-hospital-row {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -662,7 +750,7 @@ defineExpose({
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.rx-bot-label--doctor {
|
||||
.rx-bot-label--inline {
|
||||
flex-shrink: 0;
|
||||
margin-bottom: 0;
|
||||
margin-right: 6px;
|
||||
@@ -670,6 +758,14 @@ defineExpose({
|
||||
align-self: center;
|
||||
}
|
||||
|
||||
.rx-bot-reviewer-name {
|
||||
min-width: 0;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
line-height: 1.4;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.rx-bot-doctor {
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
@@ -692,12 +788,18 @@ defineExpose({
|
||||
line-height: 1.2;
|
||||
white-space: nowrap;
|
||||
}
|
||||
}
|
||||
|
||||
.rx-bot-sign-img {
|
||||
flex-shrink: 0;
|
||||
max-height: 40px;
|
||||
max-width: 110px;
|
||||
object-fit: contain;
|
||||
.rx-bot-sign-img {
|
||||
flex-shrink: 0;
|
||||
max-height: 24px;
|
||||
max-width: 72px;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
@media print {
|
||||
.rx-pharmacist-sample {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -721,6 +823,38 @@ defineExpose({
|
||||
line-height: 2.5;
|
||||
}
|
||||
}
|
||||
|
||||
.rx-paper.rx-paper--compact {
|
||||
width: 100%;
|
||||
min-height: 0;
|
||||
padding: clamp(10px, 2.4vw, 24px);
|
||||
container-type: inline-size;
|
||||
|
||||
.rx-title { font-size: 22px; margin: 6px 0 18px; }
|
||||
.rx-notice { padding: 10px; }
|
||||
.rx-notice .rx-notice-meta { flex-wrap: wrap; overflow: visible; gap: 2px 14px; }
|
||||
.rx-notice .rx-notice-meta .rx-meta-item { border: 0; padding: 0; margin: 0; }
|
||||
.rx-info-cell { padding: 9px; min-width: 0; overflow-wrap: anywhere; }
|
||||
.rx-herb-name { white-space: normal; overflow-wrap: anywhere; }
|
||||
.rx-herb-cell { line-height: 1.65; }
|
||||
.rx-text { overflow-wrap: anywhere; }
|
||||
.rx-bot-row-1 { display: flex; flex-wrap: wrap; min-height: 0; }
|
||||
.rx-bot-row-1 > .rx-bot-cell { flex: 1 0 auto; max-width: 100%; border: 0; flex-wrap: wrap; }
|
||||
.rx-bot-doctor .rx-bot-doctor-name { white-space: normal; overflow-wrap: anywhere; }
|
||||
}
|
||||
|
||||
@container (max-width: 465px) {
|
||||
.rx-paper--compact .rx-info-row:not(.rx-info-row-full) {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
|
||||
.rx-info-cell:nth-child(even) { border-right: none; }
|
||||
.rx-info-cell:nth-child(n + 3) { border-top: 1px solid #c8c8c8; }
|
||||
}
|
||||
|
||||
.rx-paper--compact .rx-rp-cols-head,
|
||||
.rx-paper--compact .rx-herbs { grid-template-columns: minmax(0, 1fr); }
|
||||
.rx-paper--compact .rx-rp-col-head + .rx-rp-col-head { display: none; }
|
||||
}
|
||||
</style>
|
||||
|
||||
<!-- 全局打印样式:body * 选择器不能放进 scoped -->
|
||||
|
||||
@@ -308,8 +308,63 @@ function computeOutPellet(data: Record<string, any>): string {
|
||||
return formatNum(perDose * getDoseCount(data))
|
||||
}
|
||||
|
||||
/** 辅方出丸 = 辅方服用天数 × 每日次数 × 每袋用量 × 每次袋数;仅浓缩水丸且确有辅方药材时计算。 */
|
||||
function computeAuxOutPellet(data: Record<string, any>): string {
|
||||
if ((data.prescription_type || '浓缩水丸') !== '浓缩水丸' || !getAuxHerbs(data).length) return ''
|
||||
let raw = data.aux_usage
|
||||
if (typeof raw === 'string') {
|
||||
try {
|
||||
raw = JSON.parse(raw)
|
||||
} catch {
|
||||
raw = null
|
||||
}
|
||||
}
|
||||
const aux = normalizeAuxUsageForm(raw, '浓缩水丸')
|
||||
const days = Number(aux.usage_days)
|
||||
const times = Number(aux.times_per_day)
|
||||
const doseG = Number(aux.dosage_amount)
|
||||
const bags = Number(aux.dosage_bag_count) > 0 ? Number(aux.dosage_bag_count) : 1
|
||||
return days > 0 && times > 0 && doseG > 0 ? formatNum(days * times * doseG * bags) : ''
|
||||
}
|
||||
|
||||
/**
|
||||
* 合并业务订单的服用参数覆盖:已签署(CA 冻结)处方在订单中修改的次数/天数/袋数记在订单 usage_override,
|
||||
* 只作用于该订单的页面与药房下单,签署原文不变。与服务端 PrescriptionOrderLogic::applyUsageOverride 一致。
|
||||
*/
|
||||
export function applyOrderUsageOverride<T extends Record<string, any>>(rx: T, rawOverride: unknown): T {
|
||||
let override: unknown = rawOverride
|
||||
if (typeof override === 'string') {
|
||||
try {
|
||||
override = JSON.parse(override)
|
||||
} catch {
|
||||
override = null
|
||||
}
|
||||
}
|
||||
if (!override || typeof override !== 'object' || Array.isArray(override)) return rx
|
||||
const o = override as Record<string, any>
|
||||
const out: Record<string, any> = { ...rx }
|
||||
for (const key of ['times_per_day', 'usage_days', 'dosage_bag_count']) {
|
||||
if (o[key] != null && Number.isFinite(Number(o[key]))) out[key] = Number(o[key])
|
||||
}
|
||||
if (o.aux_usage && typeof o.aux_usage === 'object') {
|
||||
let aux = out.aux_usage
|
||||
if (typeof aux === 'string') {
|
||||
try {
|
||||
aux = JSON.parse(aux)
|
||||
} catch {
|
||||
aux = null
|
||||
}
|
||||
}
|
||||
out.aux_usage = { ...(aux && typeof aux === 'object' ? aux : {}), ...o.aux_usage }
|
||||
}
|
||||
out.usage_overridden = 1
|
||||
return out as T
|
||||
}
|
||||
|
||||
export function rxOutPelletText(data: Record<string, any> | null | undefined): string {
|
||||
if (!data) return ''
|
||||
const out = computeOutPellet(data)
|
||||
const aux = computeAuxOutPellet(data)
|
||||
if (out && aux) return `主方 ${out}克,辅方 ${aux}克`
|
||||
return out ? `${out}克` : ''
|
||||
}
|
||||
|
||||
@@ -510,7 +510,12 @@
|
||||
</el-form-item>
|
||||
</el-col>
|
||||
<el-col :span="24">
|
||||
<el-form-item label="医师签名" prop="doctor_signature" required>
|
||||
<el-alert v-if="esignError" type="error" :closable="false" class="mb-3">
|
||||
{{ esignError }} <el-button link type="primary" @click="loadEsignConfig">重试</el-button>
|
||||
</el-alert>
|
||||
<el-alert v-else-if="esignEnabled" type="info" :closable="false" class="mb-3"
|
||||
:title="esignConfig?.environment === 'sandbox' ? '沙箱测试。保存草稿后,先上传处方,再由开方医生本人签署。' : '保存草稿后,先上传处方,再由开方医生本人签署。'" />
|
||||
<el-form-item v-else-if="esignReady" label="医师签名" prop="doctor_signature" required>
|
||||
<div class="signature-pad-wrap">
|
||||
<canvas
|
||||
ref="signatureCanvasRef"
|
||||
@@ -534,6 +539,13 @@
|
||||
</div>
|
||||
|
||||
<div v-else class="rx-wrap">
|
||||
<EsignPrescriptionPanel
|
||||
v-if="visible"
|
||||
:key="savedPrescription.id"
|
||||
:prescription-id="Number(savedPrescription.id)"
|
||||
:initial-state="savedPrescription.esign"
|
||||
@status-change="onEsignStatusChange"
|
||||
/>
|
||||
<div class="rx-toolbar">
|
||||
<el-tag v-if="savedPrescription.void_status === 1" type="danger" size="small">已作废</el-tag>
|
||||
<el-tag v-else-if="approvedPreviewOnly" type="success" size="small">已通过</el-tag>
|
||||
@@ -541,7 +553,7 @@
|
||||
v-else-if="Number(savedPrescription.audit_status) === 0"
|
||||
type="warning"
|
||||
size="small"
|
||||
>待审核</el-tag>
|
||||
>{{ pendingPrescriptionReviewLabel(savedPrescription) }}</el-tag>
|
||||
<el-tag v-else-if="Number(savedPrescription.audit_status) === 2" type="danger" size="small">已驳回</el-tag>
|
||||
<div class="flex-1" />
|
||||
</div>
|
||||
@@ -679,25 +691,26 @@
|
||||
</div>
|
||||
|
||||
<div class="flex justify-end gap-2 mt-4">
|
||||
<el-button @click="handleDownloadImage">
|
||||
<el-button v-if="!requiresOriginalEsignPdf(savedPrescription.esign)" @click="handleDownloadImage">
|
||||
<el-icon><Download /></el-icon>
|
||||
下载图片
|
||||
</el-button>
|
||||
<el-button type="primary" @click="handleDownloadPdf">
|
||||
<el-button type="primary" @click="handleDownloadPdf"
|
||||
:disabled="requiresOriginalEsignPdf(savedPrescription.esign) && !savedPrescription.esign?.can_download">
|
||||
<el-icon><Document /></el-icon>
|
||||
下载PDF
|
||||
{{ requiresOriginalEsignPdf(savedPrescription.esign) ? '下载已签原始 PDF' : '下载PDF' }}
|
||||
</el-button>
|
||||
<el-tooltip
|
||||
v-if="savedPrescription.void_status !== 1 && !approvedPreviewOnly"
|
||||
:disabled="!hasPrescriptionOrderBlockVoid"
|
||||
content="该处方已存在业务订单,无法作废,请前往已开处方里修改"
|
||||
v-if="savedPrescription.void_status !== 1 && savedPrescription.can_void !== false"
|
||||
:disabled="!hasLinkedPrescriptionOrder"
|
||||
content="作废后,关联的业务订单会在同诊单重新开方时自动关联到新处方"
|
||||
placement="top"
|
||||
>
|
||||
<span class="inline-block">
|
||||
<el-button
|
||||
v-perms="['tcm.prescription/void']"
|
||||
type="danger"
|
||||
plain
|
||||
:disabled="hasPrescriptionOrderBlockVoid"
|
||||
:loading="voiding"
|
||||
@click="handleVoid"
|
||||
>
|
||||
@@ -713,7 +726,9 @@
|
||||
<template v-if="!savedPrescription" #footer>
|
||||
<div class="flex justify-end gap-2">
|
||||
<el-button @click="handleClose">取消</el-button>
|
||||
<el-button type="primary" @click="handleSave" :loading="saving">保存处方</el-button>
|
||||
<el-button type="primary" @click="handleSave" :loading="saving || esignLoading" :disabled="!esignReady">
|
||||
{{ esignEnabled ? '保存处方草稿' : '保存处方' }}
|
||||
</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-drawer>
|
||||
@@ -860,6 +875,10 @@ import { prescriptionAdd, prescriptionDetail, prescriptionGetByAppointment, pres
|
||||
import { medicineLists } from '@/api/medicine'
|
||||
import { getDictData } from '@/api/app'
|
||||
import PrescriptionSlip from '@/components/prescription-slip/index.vue'
|
||||
import EsignPrescriptionPanel from '@/components/EsignPrescriptionPanel.vue'
|
||||
import { usePrescriptionEsignConfig } from '@/hooks/usePrescriptionEsignConfig'
|
||||
import { downloadPrescriptionPdfIfRequired, pendingPrescriptionReviewLabel, requiresOriginalEsignPdf } from '@/utils/prescription-esign'
|
||||
import type { PrescriptionEsignStatus } from '@/api/tcm'
|
||||
import html2canvas from 'html2canvas'
|
||||
import { jsPDF } from 'jspdf'
|
||||
import useUserStore from '@/stores/modules/user'
|
||||
@@ -1043,6 +1062,12 @@ const signatureActivePointerId = ref<number | null>(null)
|
||||
const SIGNATURE_CSS_W = 560
|
||||
const SIGNATURE_CSS_H = 168
|
||||
const savedPrescription = ref<any>(null)
|
||||
const { config: esignConfig, enabled: esignEnabled, ready: esignReady, loading: esignLoading, error: esignError, load: loadEsignConfig } = usePrescriptionEsignConfig()
|
||||
|
||||
const onEsignStatusChange = (state: PrescriptionEsignStatus) => {
|
||||
if (savedPrescription.value) savedPrescription.value.esign = state
|
||||
emit('success')
|
||||
}
|
||||
/** 预览联次:药房联 / 处方联(与消费者处方查看一致) */
|
||||
const prescriptionTabType = ref<'internal' | 'user'>('internal') // 保留兼容 openPreview options.slipType
|
||||
/** 诊单列表「查看」仅展示处方联,不展示详细病历 A3 */
|
||||
@@ -1055,8 +1080,8 @@ const approvedPreviewOnly = computed(() => {
|
||||
return Number(s.audit_status) === 1 && Number(s.void_status) !== 1
|
||||
})
|
||||
|
||||
/** 已有关联业务订单(与列表 has_prescription_order 一致)则禁止作废 */
|
||||
const hasPrescriptionOrderBlockVoid = computed(() => {
|
||||
/** 已有关联业务订单(与列表 has_prescription_order 一致):作废时提示订单将随重新开方迁移 */
|
||||
const hasLinkedPrescriptionOrder = computed(() => {
|
||||
const s = savedPrescription.value
|
||||
if (!s) return false
|
||||
return Number(s.has_prescription_order) === 1
|
||||
@@ -1661,6 +1686,7 @@ const open = async (data: any, options?: { templateId?: number; stationName?: st
|
||||
}
|
||||
|
||||
await loadDictOptions()
|
||||
await loadEsignConfig()
|
||||
|
||||
const appointmentId = Number(data.id ?? data.appointment_id ?? 0)
|
||||
if (appointmentId) {
|
||||
@@ -2032,6 +2058,9 @@ watch(() => formData.prescription_type, (newType) => {
|
||||
})
|
||||
|
||||
const handleSave = async () => {
|
||||
if (saving.value) return
|
||||
if (!esignReady.value && !(await loadEsignConfig())) return
|
||||
if (saving.value) return
|
||||
if (!formData.clinical_diagnosis?.trim()) {
|
||||
feedback.msgWarning('请输入临床诊断')
|
||||
return
|
||||
@@ -2056,7 +2085,7 @@ const handleSave = async () => {
|
||||
}
|
||||
}
|
||||
|
||||
if (!formData.doctor_signature?.trim()) {
|
||||
if (!esignEnabled.value && !formData.doctor_signature?.trim()) {
|
||||
feedback.msgWarning('请使用电子签名板手写医师签名')
|
||||
return
|
||||
}
|
||||
@@ -2103,8 +2132,19 @@ const handleSave = async () => {
|
||||
})
|
||||
const id = res?.id
|
||||
if (id) {
|
||||
const detail = await prescriptionDetail({ id })
|
||||
savedPrescription.value = detail
|
||||
// Keep the saved id even if the follow-up detail request fails; retrying must not add twice.
|
||||
savedPrescription.value = { ...formData, id, audit_status: 0, esign: res.esign }
|
||||
feedback.msgSuccess(res.esign?.required ? '处方草稿已保存' : '处方已保存')
|
||||
try {
|
||||
const detail = await prescriptionDetail({ id })
|
||||
if (savedPrescription.value?.id === id) {
|
||||
savedPrescription.value = { ...detail, esign: savedPrescription.value.esign ?? detail.esign }
|
||||
}
|
||||
} catch {
|
||||
if (savedPrescription.value?.id === id) {
|
||||
feedback.msgWarning(res.esign?.required ? '处方详情暂未加载,可继续操作' : '处方已保存,详情暂未加载,可从已开处方继续签署')
|
||||
}
|
||||
}
|
||||
emit('success')
|
||||
} else {
|
||||
feedback.msgError('保存失败')
|
||||
@@ -2125,12 +2165,10 @@ const formatVoidTime = (ts: number | null | undefined) => {
|
||||
const handleVoid = async () => {
|
||||
const id = savedPrescription.value?.id
|
||||
if (!id) return
|
||||
if (Number(savedPrescription.value?.has_prescription_order) === 1) {
|
||||
feedback.msgWarning('该处方已存在业务订单,无法作废')
|
||||
return
|
||||
}
|
||||
try {
|
||||
await feedback.confirm('确定要作废该处方吗?作废后不可恢复。')
|
||||
await feedback.confirm(Number(savedPrescription.value?.has_prescription_order) === 1
|
||||
? '确定要作废该处方吗?作废后不可恢复;已提交洛阳药房的订单会先撤销药房订单,关联的业务订单将退回待审核,同诊单重新开方后自动关联到新处方。'
|
||||
: '确定要作废该处方吗?作废后不可恢复。')
|
||||
voiding.value = true
|
||||
await prescriptionVoid({ id })
|
||||
feedback.msgSuccess('作废成功')
|
||||
@@ -2156,6 +2194,7 @@ const fetchCaseRecord = async (diagnosisId: number) => {
|
||||
}
|
||||
|
||||
const handleNewPrescription = async () => {
|
||||
await loadEsignConfig()
|
||||
const saved = savedPrescription.value
|
||||
if (saved) {
|
||||
// 将患者信息、诊断信息填入表单,新建处方时保留
|
||||
@@ -2273,6 +2312,7 @@ const handleDownloadImage = async () => {
|
||||
|
||||
const handleDownloadPdf = async () => {
|
||||
try {
|
||||
if (await downloadPrescriptionPdfIfRequired(Number(savedPrescription.value?.id))) return
|
||||
const canvas = await captureElement()
|
||||
const imgData = canvas.toDataURL('image/png')
|
||||
const pdf = new jsPDF({
|
||||
@@ -2301,8 +2341,8 @@ const handleDownloadPdf = async () => {
|
||||
|
||||
pdf.save(`处方_${savedPrescription.value?.patient_name || '未命名'}_${Date.now()}.pdf`)
|
||||
feedback.msgSuccess('PDF已下载')
|
||||
} catch (e) {
|
||||
feedback.msgError('下载PDF失败')
|
||||
} catch (e: any) {
|
||||
feedback.msgError(e?.message || '下载PDF失败')
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { computed, ref } from 'vue'
|
||||
import { prescriptionEsignConfig, type PrescriptionEsignConfig } from '@/api/tcm'
|
||||
|
||||
/** A failed capability lookup must not silently switch a prescription to handwritten signing. */
|
||||
export function usePrescriptionEsignConfig() {
|
||||
const config = ref<PrescriptionEsignConfig | null>(null)
|
||||
const loading = ref(false)
|
||||
const error = ref('')
|
||||
let request: Promise<boolean> | null = null
|
||||
|
||||
function load(): Promise<boolean> {
|
||||
if (request) return request
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
request = prescriptionEsignConfig()
|
||||
.then((value) => {
|
||||
if (typeof value?.enabled !== 'boolean' || !['sandbox', 'production'].includes(value.environment)) {
|
||||
throw new Error('Invalid signing configuration')
|
||||
}
|
||||
config.value = value
|
||||
return true
|
||||
})
|
||||
.catch(() => {
|
||||
config.value = null
|
||||
error.value = '签署配置加载失败,请重试后保存处方'
|
||||
return false
|
||||
})
|
||||
.finally(() => {
|
||||
loading.value = false
|
||||
request = null
|
||||
})
|
||||
return request
|
||||
}
|
||||
|
||||
return {
|
||||
config,
|
||||
enabled: computed(() => config.value?.enabled === true),
|
||||
ready: computed(() => config.value !== null),
|
||||
loading,
|
||||
error,
|
||||
load
|
||||
}
|
||||
}
|
||||
@@ -11,24 +11,84 @@
|
||||
<router-link to="/user/setting">
|
||||
<el-dropdown-item>个人设置</el-dropdown-item>
|
||||
</router-link>
|
||||
<el-dropdown-item v-if="canManageDoctorEsign" command="doctor-esign">
|
||||
医生电子签署身份
|
||||
</el-dropdown-item>
|
||||
<el-dropdown-item v-if="canManageReviewEsign" command="review-esign">
|
||||
审核签署身份
|
||||
</el-dropdown-item>
|
||||
<el-dropdown-item command="switch-account">切换账号</el-dropdown-item>
|
||||
<el-dropdown-item command="cache">清除缓存</el-dropdown-item>
|
||||
<el-dropdown-item command="logout">退出登录</el-dropdown-item>
|
||||
</el-dropdown-menu>
|
||||
</template>
|
||||
</el-dropdown>
|
||||
<esign-doctor-dialog
|
||||
v-if="(canManageDoctorEsign && doctorEsignOpen) || (canManageReviewEsign && reviewEsignOpen)"
|
||||
:reviewer="reviewEsignOpen"
|
||||
:server-time-offset-ms="userStore.serverTimeOffsetMs"
|
||||
@close="closeEsign"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
|
||||
import { systemCacheClear } from '@/api/setting/system'
|
||||
import { prescriptionEsignConfig } from '@/api/tcm'
|
||||
import EsignDoctorDialog from '@/components/EsignDoctorDialog.vue'
|
||||
import useUserStore from '@/stores/modules/user'
|
||||
import feedback from '@/utils/feedback'
|
||||
import { hasPermission } from '@/utils/perm'
|
||||
import { DOCTOR_ESIGN_IDENTITY_PERMISSION } from '@/utils/prescription-esign'
|
||||
|
||||
const userStore = useUserStore()
|
||||
const route = useRoute()
|
||||
|
||||
const userInfo = computed(() => userStore.userInfo)
|
||||
const doctorEsignOpen = ref(false)
|
||||
const reviewEsignOpen = ref(false)
|
||||
const reviewEnabled = ref(false)
|
||||
// 「医生电子签署身份」是独立按钮权限,需在角色权限中勾选(超级管理员的 * 权限同样通过)。
|
||||
const canManageDoctorEsign = computed(() => {
|
||||
const { role_ids } = userInfo.value
|
||||
return Boolean(userStore.token) && Array.isArray(role_ids) && role_ids.some((id) => Number(id) === 1)
|
||||
&& hasPermission([DOCTOR_ESIGN_IDENTITY_PERMISSION])
|
||||
})
|
||||
const canManageReviewEsign = computed(() => Boolean(userStore.token) && reviewEnabled.value
|
||||
&& [ 'tcm.prescriptionOrder/auditPrescription', 'tcm.prescription/audit', 'cf.prescription/audit' ]
|
||||
.some((permission) => hasPermission([permission])))
|
||||
|
||||
function closeEsign() {
|
||||
doctorEsignOpen.value = false
|
||||
reviewEsignOpen.value = false
|
||||
}
|
||||
|
||||
watch([() => userStore.token, () => userInfo.value.id], closeEsign, { flush: 'sync' })
|
||||
watch(canManageDoctorEsign, (allowed) => { if (!allowed) doctorEsignOpen.value = false }, { flush: 'sync' })
|
||||
watch(canManageReviewEsign, (allowed) => { if (!allowed) reviewEsignOpen.value = false }, { flush: 'sync' })
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const config = await prescriptionEsignConfig()
|
||||
reviewEnabled.value = config.enabled && config.review_enabled === true && config.verification_method === 'quick'
|
||||
} catch {
|
||||
reviewEnabled.value = false
|
||||
}
|
||||
})
|
||||
|
||||
const handleCommand = async (command: string) => {
|
||||
switch (command) {
|
||||
case 'doctor-esign':
|
||||
if (canManageDoctorEsign.value) doctorEsignOpen.value = true
|
||||
break
|
||||
case 'review-esign':
|
||||
if (canManageReviewEsign.value) reviewEsignOpen.value = true
|
||||
break
|
||||
case 'switch-account':
|
||||
await feedback.confirm('当前账号将退出。请使用另一个账号登录。')
|
||||
await userStore.logout(route.fullPath)
|
||||
break
|
||||
case 'logout':
|
||||
await feedback.confirm('确定退出登录吗?')
|
||||
userStore.logout()
|
||||
|
||||
@@ -58,13 +58,17 @@ const useUserStore = defineStore({
|
||||
})
|
||||
})
|
||||
},
|
||||
logout() {
|
||||
logout(returnTo?: string) {
|
||||
return new Promise((resolve, reject) => {
|
||||
logout()
|
||||
.then(async (data) => {
|
||||
this.token = ''
|
||||
await router.push(PageEnum.LOGIN)
|
||||
clearAuthInfo()
|
||||
if (returnTo) {
|
||||
window.location.assign(router.resolve({ path: PageEnum.LOGIN, query: { redirect: returnTo, switch_account: '1' } }).href)
|
||||
} else {
|
||||
await router.push(PageEnum.LOGIN)
|
||||
}
|
||||
resolve(data)
|
||||
})
|
||||
.catch((error) => {
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
import {
|
||||
prescriptionDetail,
|
||||
prescriptionEsignDownload,
|
||||
prescriptionEsignStatus,
|
||||
type PrescriptionEsignFile,
|
||||
type PrescriptionEsignIdentityStatus,
|
||||
type PrescriptionEsignStatus
|
||||
} from '@/api/tcm'
|
||||
|
||||
/** 「医生电子签署身份」按钮权限,与服务端 DoctorEsignIdentityService::DOCTOR_IDENTITY_PERMISSION 一致。 */
|
||||
export const DOCTOR_ESIGN_IDENTITY_PERMISSION = 'tcm.prescription/esignDoctor'
|
||||
|
||||
const signingTimeFormatter = new Intl.DateTimeFormat('zh-CN', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
hourCycle: 'h23'
|
||||
})
|
||||
|
||||
export function formatSigningTime(seconds: number | undefined): string {
|
||||
if (typeof seconds !== 'number' || !Number.isInteger(seconds) || seconds <= 0 || seconds > 253402300799) return ''
|
||||
return signingTimeFormatter.format(seconds * 1000)
|
||||
}
|
||||
|
||||
export function prescriptionEsignTiming(state?: PrescriptionEsignStatus | null) {
|
||||
if (!state || (state.status !== 'signed' && state.status !== 'voided')) return null
|
||||
|
||||
const source = state.signature_time_source === 'tsa' ? '可信时间戳'
|
||||
: state.signature_time_source === 'local' ? '签名记录时间' : ''
|
||||
const signatureTime = source ? formatSigningTime(state.signature_time) : ''
|
||||
const verifiedTime = formatSigningTime(state.signed_at)
|
||||
const issuedTime = formatSigningTime(state.issued_at)
|
||||
if (state.status === 'voided' && !state.can_download && !signatureTime && !verifiedTime && !issuedTime) return null
|
||||
|
||||
return { issuedTime, signatureTime, source, verifiedTime }
|
||||
}
|
||||
|
||||
export function safeEsignAuthUrl(value: unknown): string {
|
||||
if (typeof value !== 'string' || !value.trim() || /[\u0000-\u001f\\]/.test(value)) return ''
|
||||
try {
|
||||
const url = new URL(value)
|
||||
const hosts = ['smlt.esign.cn', 'smlfront.esign.cn', 't.esign.cn', 'idverify.esign.cn']
|
||||
const allowedPort = !url.port || (url.hostname === 'smlfront.esign.cn' && url.port === '8890')
|
||||
return url.protocol === 'https:' && hosts.includes(url.hostname) && allowedPort && !url.username && !url.password ? url.href : ''
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
export function validateEsignStatus(value: unknown): PrescriptionEsignStatus {
|
||||
const state = value as PrescriptionEsignStatus | null
|
||||
const statuses = ['pending', 'authenticating', 'signing', 'signed', 'failed', 'uncertain', 'voided', 'legacy']
|
||||
if (!state || typeof state !== 'object' || !statuses.includes(state.status)
|
||||
|| !['sandbox', 'production'].includes(state.environment)
|
||||
|| ['enabled', 'required', 'can_sign', 'can_download'].some((key) => typeof (state as any)[key] !== 'boolean')
|
||||
|| (state.verification_method !== undefined && !['quick', 'sms'].includes(state.verification_method))
|
||||
|| [state.can_resume_identity, state.can_retry_verify, state.doctor_identity_required,
|
||||
state.signing_authorization_required, state.sms_sent, state.awaiting_upload,
|
||||
state.can_submit_for_review, state.can_review_prescription]
|
||||
.some((flag) => flag !== undefined && typeof flag !== 'boolean')) {
|
||||
throw new Error('无法核对处方签署状态,请刷新后重试')
|
||||
}
|
||||
return state
|
||||
}
|
||||
|
||||
export function canCheckEsignIdentity(state: PrescriptionEsignStatus | null): boolean {
|
||||
return state?.can_sign === true && (state.status === 'authenticating'
|
||||
|| (state.status === 'failed' && state.can_resume_identity === true))
|
||||
}
|
||||
|
||||
export function validateEsignIdentityStatus(value: unknown): PrescriptionEsignIdentityStatus {
|
||||
const state = validateEsignStatus(value) as PrescriptionEsignIdentityStatus
|
||||
const detailsRequired = state.identity_details_required ?? false
|
||||
const accountBased = state.verification_method === 'quick' || state.verification_method === 'sms'
|
||||
if (!['INIT', 'ING', 'SUCCESS', 'FAIL', 'EXPIRED', 'UNAVAILABLE'].includes(state.identity_status)
|
||||
|| typeof state.can_complete !== 'boolean'
|
||||
|| (state.identity_details_required !== undefined && typeof state.identity_details_required !== 'boolean')
|
||||
|| (state.can_complete && detailsRequired)
|
||||
|| (accountBased && (detailsRequired || (state.can_complete && (state.can_resume_identity !== true
|
||||
|| state.doctor_identity_required === true || state.signing_authorization_required === true
|
||||
|| (state.verification_method === 'sms' && state.sms_sent !== true)))))
|
||||
|| ((state.can_complete || detailsRequired)
|
||||
&& (state.identity_status !== 'SUCCESS' || !canCheckEsignIdentity(state)))) {
|
||||
throw new Error('无法核对身份验证结果,请刷新状态后重试')
|
||||
}
|
||||
return { ...state, identity_details_required: detailsRequired }
|
||||
}
|
||||
|
||||
export function requiresOriginalEsignPdf(status?: PrescriptionEsignStatus | null): boolean {
|
||||
try {
|
||||
const value = validateEsignStatus(status)
|
||||
return value.required || value.status !== 'legacy' || value.can_download
|
||||
} catch {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
export function canApprovePrescriptionEsign(status: unknown): boolean {
|
||||
try {
|
||||
const state = validateEsignStatus(status)
|
||||
return state.required
|
||||
? state.status === 'signed' && state.can_download
|
||||
: state.status === 'legacy' && !state.can_download
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export function pendingPrescriptionReviewLabel(row: {
|
||||
review_submitted_at?: number | string
|
||||
can_review_prescription?: boolean
|
||||
esign?: PrescriptionEsignStatus
|
||||
}): string {
|
||||
const submittedAt = row.esign?.review_submitted_at ?? row.review_submitted_at
|
||||
if (!(Number(submittedAt) > 0)) return '待上传'
|
||||
if ((row.esign?.can_review_prescription ?? row.can_review_prescription) === true) return '待审核'
|
||||
return row.esign?.status === 'signed' ? '签署待核实' : '待医师签署'
|
||||
}
|
||||
|
||||
export async function updatePrescriptionSlipEsign(data: Record<string, unknown> | null, state: PrescriptionEsignStatus): Promise<void> {
|
||||
if (!data) return
|
||||
const previous = data.esign as PrescriptionEsignStatus | undefined
|
||||
data.esign = state
|
||||
if (state.status !== 'signed' || previous?.status === 'signed') return
|
||||
|
||||
// The verified physician seal is stored on the prescription detail after signing.
|
||||
data.doctor_signature = ''
|
||||
const id = Number(data.id)
|
||||
if (!Number.isInteger(id) || id <= 0) return
|
||||
try {
|
||||
const response = await prescriptionDetail({ id })
|
||||
const detail = response?.data ?? response
|
||||
if (Number(detail?.id) === id && (data.esign as PrescriptionEsignStatus).status === 'signed'
|
||||
&& typeof detail?.doctor_signature === 'string') {
|
||||
data.doctor_signature = detail.doctor_signature
|
||||
}
|
||||
} catch {
|
||||
// The slip falls back to the verified name when the seal cannot be loaded.
|
||||
}
|
||||
}
|
||||
|
||||
/** Verify the received bytes before creating a download; never render or alter the signed PDF. */
|
||||
export async function verifyEsignPdf(file: PrescriptionEsignFile): Promise<Uint8Array> {
|
||||
if (!/^[a-f\d]{64}$/i.test(file.sha256 || '')) throw new Error('签署文件缺少有效校验信息')
|
||||
if (!globalThis.crypto?.subtle) throw new Error('请通过 HTTPS 访问,以校验签署文件')
|
||||
let bytes: Uint8Array
|
||||
try {
|
||||
bytes = Uint8Array.from(atob(file.content_base64), (c) => c.charCodeAt(0))
|
||||
} catch {
|
||||
throw new Error('签署文件内容无效,请重新下载')
|
||||
}
|
||||
if (String.fromCharCode(...bytes.subarray(0, 5)) !== '%PDF-') {
|
||||
throw new Error('签署文件不是有效 PDF,请重新下载')
|
||||
}
|
||||
const digest = await crypto.subtle.digest('SHA-256', bytes)
|
||||
const hash = Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, '0')).join('')
|
||||
if (hash !== file.sha256.toLowerCase()) throw new Error('签署文件校验失败,已停止下载,请重试')
|
||||
return bytes
|
||||
}
|
||||
|
||||
export async function downloadOriginalEsignPdf(id: number, isCurrent = () => true): Promise<void> {
|
||||
const file = await prescriptionEsignDownload({ id })
|
||||
if (!isCurrent()) return
|
||||
const bytes = await verifyEsignPdf(file)
|
||||
if (!isCurrent()) return
|
||||
const url = URL.createObjectURL(new Blob([bytes], { type: 'application/pdf' }))
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
link.download = (file.filename || `处方_${id}_已签.pdf`).replace(/[\\/:*?"<>|\u0000-\u001f]/g, '_')
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
link.remove()
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000)
|
||||
}
|
||||
|
||||
/** Legacy exports may render locally; every other state must preserve the server's original. */
|
||||
export async function downloadPrescriptionPdfIfRequired(id: number): Promise<boolean> {
|
||||
if (!Number.isInteger(id) || id <= 0) throw new Error('缺少处方编号,无法核对签署状态')
|
||||
const status = validateEsignStatus(await prescriptionEsignStatus({ id }))
|
||||
if (!requiresOriginalEsignPdf(status)) return false
|
||||
if (!status.can_download) throw new Error(status.message || '处方尚未签署完成,请完成签署后下载')
|
||||
await downloadOriginalEsignPdf(id)
|
||||
return true
|
||||
}
|
||||
@@ -39,6 +39,22 @@
|
||||
<template #prepend>
|
||||
<icon name="el-icon-User" size="16" />
|
||||
</template>
|
||||
<template v-if="rememberedAccounts.length" #append>
|
||||
<el-dropdown trigger="click" @command="selectRememberedAccount">
|
||||
<el-button>选择账号</el-button>
|
||||
<template #dropdown>
|
||||
<el-dropdown-menu>
|
||||
<el-dropdown-item
|
||||
v-for="account in rememberedAccounts"
|
||||
:key="account"
|
||||
:command="account"
|
||||
>
|
||||
{{ account }}
|
||||
</el-dropdown-item>
|
||||
</el-dropdown-menu>
|
||||
</template>
|
||||
</el-dropdown>
|
||||
</template>
|
||||
</el-input>
|
||||
</el-form-item>
|
||||
<el-form-item prop="password">
|
||||
@@ -122,6 +138,8 @@ const userStore = useUserStore()
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const remAccount = ref(false)
|
||||
const rememberedAccounts = ref<string[]>([])
|
||||
const switchingAccount = computed(() => route.query.switch_account === '1')
|
||||
const config = computed(() => appStore.config)
|
||||
const formData = reactive({
|
||||
account: '',
|
||||
@@ -214,11 +232,15 @@ const handleEnter = () => {
|
||||
|
||||
const handleLogin = async () => {
|
||||
await formRef.value?.validate()
|
||||
const result: any = await userStore.login(formData)
|
||||
const account = formData.account.trim()
|
||||
const others = rememberedAccounts.value.filter((saved) => saved !== account)
|
||||
rememberedAccounts.value = (remAccount.value ? [account, ...others] : others).slice(0, 15)
|
||||
cache.set(ACCOUNT_KEY, {
|
||||
remember: remAccount.value,
|
||||
account: remAccount.value ? formData.account : ''
|
||||
account: remAccount.value ? account : '',
|
||||
accounts: rememberedAccounts.value
|
||||
})
|
||||
const result: any = await userStore.login(formData)
|
||||
|
||||
// 检查是否需要修改密码
|
||||
if (result.is_paw === 0) {
|
||||
@@ -307,11 +329,21 @@ watch(loginMode, (val) => {
|
||||
}
|
||||
})
|
||||
|
||||
function selectRememberedAccount(account: string) {
|
||||
formData.account = account
|
||||
formData.password = ''
|
||||
remAccount.value = true
|
||||
passwordRef.value?.focus()
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
// 恢复记住账号
|
||||
const value = cache.get(ACCOUNT_KEY)
|
||||
if (value?.remember) {
|
||||
remAccount.value = value.remember
|
||||
const saved: unknown[] = Array.isArray(value?.accounts) ? value.accounts : value?.remember ? [value.account] : []
|
||||
rememberedAccounts.value = [...new Set(saved.filter((account): account is string =>
|
||||
typeof account === 'string' && account.trim().length > 0))].slice(0, 15)
|
||||
if (!switchingAccount.value && value?.remember && rememberedAccounts.value.includes(value.account)) {
|
||||
remAccount.value = true
|
||||
formData.account = value.account
|
||||
}
|
||||
|
||||
@@ -342,7 +374,7 @@ onMounted(async () => {
|
||||
wxWorkConfig.value = { corp_id: res.corp_id, agent_id: res.agent_id }
|
||||
|
||||
// 在企业微信内:自动跳转 OAuth 授权
|
||||
if (isInWxWork() && !hasIamCallback) {
|
||||
if (isInWxWork() && !hasIamCallback && !switchingAccount.value) {
|
||||
const redirectUri = encodeURIComponent(getRedirectUri())
|
||||
const authUrl =
|
||||
`https://open.weixin.qq.com/connect/oauth2/authorize` +
|
||||
|
||||
@@ -0,0 +1,879 @@
|
||||
<template>
|
||||
<section class="alert-inbox" aria-label="医助行为预警">
|
||||
<el-alert
|
||||
v-if="data?.scan.reason"
|
||||
:title="data.scan.reason"
|
||||
type="warning"
|
||||
:closable="false"
|
||||
show-icon
|
||||
class="scan-note"
|
||||
/>
|
||||
<div v-if="data" class="metric-strip" aria-label="预警汇总">
|
||||
<article class="metric" :class="{ 'metric--attention': data.summary.open > 0 }">
|
||||
<span>待处理</span>
|
||||
<strong>{{ data.summary.open }}</strong>
|
||||
<small>还没有人复核</small>
|
||||
</article>
|
||||
<article class="metric" :class="{ 'metric--high': data.summary.high_open > 0 }">
|
||||
<span>高风险</span>
|
||||
<strong>{{ data.summary.high_open }}</strong>
|
||||
<small>诊疗、承诺、脱离平台</small>
|
||||
</article>
|
||||
<article class="metric">
|
||||
<span>聊天命中</span>
|
||||
<strong>{{ data.summary.im_open }}</strong>
|
||||
<small>员工侧已归档文字</small>
|
||||
</article>
|
||||
<article class="metric" :class="{ 'metric--attention': callCoverage?.status === 'available' && data.summary.call_open > 0 }">
|
||||
<span>通话转写</span>
|
||||
<strong v-if="callCoverage?.status === 'available'">{{ data.summary.call_open }}</strong>
|
||||
<strong v-else class="metric-text">{{ callMetric }}</strong>
|
||||
<small>{{ callCoverage?.status === 'available' ? '员工侧转写命中' : callMetricNote }}</small>
|
||||
</article>
|
||||
</div>
|
||||
<div class="inbox-panel">
|
||||
<div class="table-heading">
|
||||
<div>
|
||||
<h2>命中记录</h2>
|
||||
<p class="muted">一条记录是一名员工、一条规则、一处原文。没有记录不等于今天没有沟通。</p>
|
||||
</div>
|
||||
<form class="search-form" @submit.prevent="search">
|
||||
<el-input
|
||||
v-model="keyword"
|
||||
aria-label="搜索预警"
|
||||
placeholder="搜索员工或患者"
|
||||
clearable
|
||||
@clear="search"
|
||||
/>
|
||||
<el-button native-type="submit">搜索</el-button>
|
||||
</form>
|
||||
</div>
|
||||
<div class="role-switch" role="group" aria-label="按身份查看">
|
||||
<button
|
||||
type="button"
|
||||
:class="{ active: role === 'assistant' }"
|
||||
:aria-pressed="role === 'assistant'"
|
||||
@click="setRole('assistant')"
|
||||
>
|
||||
<span>医助</span>
|
||||
<strong>{{ data?.summary.assistant_open ?? 0 }}</strong>
|
||||
<small>待处理</small>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
:class="{ active: role === 'doctor' }"
|
||||
:aria-pressed="role === 'doctor'"
|
||||
@click="setRole('doctor')"
|
||||
>
|
||||
<span>医生</span>
|
||||
<strong>{{ data?.summary.doctor_open ?? 0 }}</strong>
|
||||
<small>待处理</small>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="role-switch__all"
|
||||
:class="{ active: role === 'all' }"
|
||||
:aria-pressed="role === 'all'"
|
||||
@click="setRole('all')"
|
||||
>
|
||||
全部身份
|
||||
</button>
|
||||
</div>
|
||||
<section v-if="role === 'assistant'" class="chat-workspace" aria-label="企微聊天">
|
||||
<aside class="people-pane">
|
||||
<p class="pane-label">企微账号</p>
|
||||
<button
|
||||
v-for="account in directory?.accounts || []"
|
||||
:key="account.external_id"
|
||||
type="button"
|
||||
:class="{ active: selected.account === account.external_id }"
|
||||
@click="choosePerson({ id: 0, name: account.name || '未命名账号', account: account.external_id })"
|
||||
>
|
||||
<strong>{{ account.name || '未命名账号' }}</strong>
|
||||
<small>{{ account.conversations }} 个会话</small>
|
||||
</button>
|
||||
<p class="pane-label">已关联医助</p>
|
||||
<button
|
||||
v-for="person in linkedStaff"
|
||||
:key="person.id"
|
||||
type="button"
|
||||
:class="{ active: selected.id === person.id && !selected.account }"
|
||||
@click="choosePerson({ id: person.id, name: person.name, account: '' })"
|
||||
>
|
||||
<strong>{{ person.name || '未命名医助' }}</strong>
|
||||
<small>{{ person.conversations }} 个会话</small>
|
||||
</button>
|
||||
<p v-if="!linkedStaff.length" class="pane-note">还没有医助和企微账号同名或绑定了同一个 UserId。</p>
|
||||
</aside>
|
||||
<div class="chat-pane">
|
||||
<h3>{{ selected.name || '选择左侧的人' }}</h3>
|
||||
<WecomThread
|
||||
v-if="selected.id || selected.account"
|
||||
:assistant-id="selected.id"
|
||||
:account="selected.account"
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
<div v-if="role !== 'assistant'" class="table-toolbar">
|
||||
<div class="filter-group" role="group" aria-label="筛选预警">
|
||||
<button
|
||||
v-for="item in filters"
|
||||
:key="item.value"
|
||||
type="button"
|
||||
:aria-pressed="filter === item.value"
|
||||
:class="{ active: filter === item.value }"
|
||||
@click="setFilter(item.value)"
|
||||
>
|
||||
{{ item.label }}
|
||||
</button>
|
||||
</div>
|
||||
<span class="muted">{{
|
||||
data?.scan.last_scan_at
|
||||
? `最近扫描 ${shanghaiTime(data.scan.last_scan_at)}`
|
||||
: '扫描时间待确认'
|
||||
}}</span>
|
||||
</div>
|
||||
<el-alert
|
||||
v-if="error"
|
||||
:title="error"
|
||||
type="error"
|
||||
:closable="false"
|
||||
show-icon
|
||||
class="table-error"
|
||||
/>
|
||||
<el-skeleton v-if="role !== 'assistant' && loading && !data" :rows="6" animated class="table-skeleton" />
|
||||
<ul v-else-if="role !== 'assistant' && data?.lists.length" v-loading="loading" class="feed">
|
||||
<li
|
||||
v-for="row in data.lists"
|
||||
:key="row.id"
|
||||
:class="['feed-item', `feed-item--${roleKind(row)}`]"
|
||||
>
|
||||
<div class="feed-main">
|
||||
<div class="feed-who">
|
||||
<span :class="['role-pill', `role-pill--${roleKind(row)}`]">{{
|
||||
row.staff.role_name || '员工'
|
||||
}}</span>
|
||||
<button
|
||||
v-if="row.staff.assistant"
|
||||
type="button"
|
||||
class="staff-link"
|
||||
@click="choosePerson({ id: row.staff.id, name: row.staff.name, account: '' })"
|
||||
>
|
||||
{{ row.staff.name || '未命名医助' }}
|
||||
</button>
|
||||
<strong v-else>{{ row.staff.name || '未命名员工' }}</strong>
|
||||
<span class="patient">{{ row.patient_name || '未命名患者' }}</span>
|
||||
<small v-if="row.diagnosis_id">诊单 #{{ row.diagnosis_id }}</small>
|
||||
</div>
|
||||
<p class="snippet">{{ row.snippet }}</p>
|
||||
<p v-if="row.review_note" class="review-note">复核:{{ row.review_note }}</p>
|
||||
<div class="feed-meta">
|
||||
<time class="number">{{ shanghaiTime(row.occurred_at) }}</time>
|
||||
<span :class="['severity', `severity--${row.severity}`]"
|
||||
>{{ severityLabels[row.severity] }} · {{ row.rule_label }}</span
|
||||
>
|
||||
<span>{{ channelLabel(row.channel) }}</span>
|
||||
<span>{{ statusLabels[row.status] }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="canReview" class="feed-actions">
|
||||
<div class="review-actions">
|
||||
<button
|
||||
type="button"
|
||||
:disabled="row.status === 'confirmed'"
|
||||
@click="review(row, 'confirmed')"
|
||||
>
|
||||
成立
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
:disabled="row.status === 'false_positive'"
|
||||
@click="review(row, 'false_positive')"
|
||||
>
|
||||
误报
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
:disabled="row.status === 'followed'"
|
||||
@click="review(row, 'followed')"
|
||||
>
|
||||
已跟进
|
||||
</button>
|
||||
</div>
|
||||
<form
|
||||
v-if="noteTarget === row.id"
|
||||
class="note-form"
|
||||
@submit.prevent="review(row, 'false_positive')"
|
||||
>
|
||||
<el-input
|
||||
v-model="note"
|
||||
aria-label="误报原因"
|
||||
maxlength="200"
|
||||
placeholder="填写误报原因"
|
||||
/>
|
||||
<el-button native-type="submit" link type="primary">提交</el-button>
|
||||
</form>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
<el-empty v-else-if="role !== 'assistant'" :image-size="80" :description="emptyDescription" />
|
||||
<footer v-if="role !== 'assistant'" class="table-footer">
|
||||
<span class="muted">{{ coverageText }}</span>
|
||||
<el-pagination
|
||||
v-if="data?.count"
|
||||
v-model:current-page="page"
|
||||
:total="data.count"
|
||||
:page-size="20"
|
||||
layout="total, prev, pager, next"
|
||||
@current-change="changePage"
|
||||
/>
|
||||
</footer>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { computed, onActivated, onBeforeUnmount, onDeactivated, onMounted, ref, watch } from 'vue'
|
||||
import {
|
||||
assistantAlerts,
|
||||
assistantReviewAlert,
|
||||
assistantWecomDirectory,
|
||||
type AlertPage,
|
||||
type AlertSeverity,
|
||||
type AlertStatus,
|
||||
type ServiceAlert,
|
||||
type Staff,
|
||||
type WecomDirectory
|
||||
} from '@/api/assistantService'
|
||||
import WecomThread from './WecomThread.vue'
|
||||
import { errorText, isCancelled, shanghaiTime } from '../shared'
|
||||
|
||||
const props = defineProps<{ refreshKey: number; canReview: boolean }>()
|
||||
const emit = defineEmits<{ 'open-staff': [staff: Staff] }>()
|
||||
const data = ref<AlertPage | null>(null)
|
||||
const loading = ref(false)
|
||||
const error = ref('')
|
||||
const keyword = ref('')
|
||||
const keywordApplied = ref('')
|
||||
const filter = ref('open')
|
||||
const role = ref<'all' | 'assistant' | 'doctor'>('all')
|
||||
const page = ref(1)
|
||||
const note = ref('')
|
||||
const noteTarget = ref(0)
|
||||
const directory = ref<WecomDirectory | null>(null)
|
||||
const selected = ref({ id: 0, name: '', account: '' })
|
||||
const linkedStaff = computed(() => (directory.value?.staff || []).filter((person) => person.conversations > 0))
|
||||
const filters: Array<{
|
||||
value: string
|
||||
label: string
|
||||
status: AlertStatus | 'all'
|
||||
severity: AlertSeverity | 'all'
|
||||
}> = [
|
||||
{ value: 'open', label: '待处理', status: 'open', severity: 'all' },
|
||||
{ value: 'high', label: '高风险', status: 'open', severity: 'high' },
|
||||
{ value: 'all', label: '全部', status: 'all', severity: 'all' },
|
||||
{ value: 'confirmed', label: '已成立', status: 'confirmed', severity: 'all' },
|
||||
{ value: 'false_positive', label: '误报', status: 'false_positive', severity: 'all' },
|
||||
{ value: 'followed', label: '已跟进', status: 'followed', severity: 'all' }
|
||||
]
|
||||
const statusLabels: Record<AlertStatus, string> = {
|
||||
open: '待处理',
|
||||
confirmed: '已成立',
|
||||
false_positive: '误报',
|
||||
followed: '已跟进'
|
||||
}
|
||||
const severityLabels: Record<AlertSeverity, string> = { high: '高', medium: '中', low: '低' }
|
||||
const activeFilter = computed(() => filters.find((item) => item.value === filter.value) || filters[0])
|
||||
const coverageText = computed(
|
||||
() => data.value?.coverage.map((item) => item.note).join(' · ') || '通话转写和企微尚未接入'
|
||||
)
|
||||
const callCoverage = computed(() => data.value?.coverage.find((item) => item.channel === 'call'))
|
||||
const callMetric = computed(() => {
|
||||
if (callCoverage.value?.status === 'no_transcript') return '无正文'
|
||||
if (callCoverage.value?.status === 'not_scanned') return '未检查'
|
||||
return '未接入'
|
||||
})
|
||||
const callMetricNote = computed(() => {
|
||||
if (callCoverage.value?.status === 'no_transcript') return '医助主叫没有可判定转写'
|
||||
if (callCoverage.value?.status === 'not_scanned') return '已有转写,尚未写入预警'
|
||||
return '有录音也不计为已检查'
|
||||
})
|
||||
const emptyDescription = computed(() => {
|
||||
if (error.value) return '暂时无法读取预警,请重试'
|
||||
if (data.value && !data.value.schema_ready) return '预警表尚未就绪'
|
||||
if (data.value?.scan.state === 'disabled') return '预警扫描尚未开启'
|
||||
if (data.value?.scan.state === 'waiting' && !data.value.scan.last_scan_at) return '尚未完成首次扫描'
|
||||
if (filter.value === 'open' && role.value === 'assistant') return '当前没有医助的待处理预警'
|
||||
if (filter.value === 'open' && role.value === 'doctor') return '当前没有医生的待处理预警'
|
||||
if (filter.value === 'open' && data.value?.empty_reason) return data.value.empty_reason
|
||||
if (filter.value === 'open') return '当前没有待处理预警'
|
||||
return '当前筛选下没有预警'
|
||||
})
|
||||
let disposed = false,
|
||||
activated = true,
|
||||
mounted = false,
|
||||
listening = false,
|
||||
revision = 0
|
||||
let request: AbortController | undefined
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
const visible = () =>
|
||||
activated && (typeof document === 'undefined' || document.visibilityState !== 'hidden')
|
||||
function roleKind(row: ServiceAlert) {
|
||||
if (row.staff.assistant || row.staff.role_name === '医助') return 'assistant'
|
||||
if (row.staff.role_name === '医生') return 'doctor'
|
||||
return 'other'
|
||||
}
|
||||
function channelLabel(channel: string) {
|
||||
if (channel === 'call') return '通话'
|
||||
if (channel === 'wecom') return '企微'
|
||||
if (channel === 'im') return '聊天'
|
||||
return '其他'
|
||||
}
|
||||
function stopTimer() {
|
||||
if (timer) clearTimeout(timer)
|
||||
timer = undefined
|
||||
}
|
||||
function schedule() {
|
||||
stopTimer()
|
||||
if (!disposed && mounted && visible()) timer = setTimeout(() => void load(true), 30000)
|
||||
}
|
||||
async function load(silent = false) {
|
||||
if (disposed || !visible()) return false
|
||||
const token = ++revision
|
||||
request?.abort()
|
||||
request = new AbortController()
|
||||
if (!silent) loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const result = await assistantAlerts(
|
||||
{
|
||||
keyword: keywordApplied.value,
|
||||
status: activeFilter.value.status,
|
||||
severity: activeFilter.value.severity,
|
||||
role: role.value,
|
||||
page_no: page.value,
|
||||
page_size: 20
|
||||
},
|
||||
request.signal
|
||||
)
|
||||
if (disposed || token !== revision) return false
|
||||
if (!result.summary || !result.scan || !Array.isArray(result.lists)) {
|
||||
throw new Error('预警数据不完整,请刷新后重试')
|
||||
}
|
||||
data.value = result
|
||||
return true
|
||||
} catch (cause) {
|
||||
if (!disposed && token !== revision && !isCancelled(cause)) {
|
||||
if (!silent) data.value = null
|
||||
error.value = errorText(cause)
|
||||
}
|
||||
return false
|
||||
} finally {
|
||||
if (!disposed && token === revision) {
|
||||
loading.value = false
|
||||
schedule()
|
||||
}
|
||||
}
|
||||
}
|
||||
function search() {
|
||||
keywordApplied.value = keyword.value.trim()
|
||||
page.value = 1
|
||||
void load()
|
||||
}
|
||||
function setFilter(value: string) {
|
||||
if (filter.value === value) return
|
||||
filter.value = value
|
||||
page.value = 1
|
||||
noteTarget.value = 0
|
||||
void load()
|
||||
}
|
||||
let directoryTimer: ReturnType<typeof setTimeout> | undefined
|
||||
function stopDirectoryTimer() {
|
||||
if (directoryTimer) clearTimeout(directoryTimer)
|
||||
directoryTimer = undefined
|
||||
}
|
||||
function scheduleDirectory() {
|
||||
stopDirectoryTimer()
|
||||
if (!disposed && role.value === 'assistant') directoryTimer = setTimeout(() => void loadDirectory(true), 15000)
|
||||
}
|
||||
async function loadDirectory(silent = false) {
|
||||
try {
|
||||
const result = await assistantWecomDirectory()
|
||||
if (disposed) return
|
||||
directory.value = result
|
||||
const current = selected.value
|
||||
const stillAccount = result.accounts.some((item) => item.external_id === current.account)
|
||||
const stillStaff = result.staff.some((item) => item.id === current.id && !current.account)
|
||||
if (!stillAccount && !stillStaff) {
|
||||
const account = result.accounts.find((item) => item.conversations > 0) || result.accounts[0]
|
||||
if (account) {
|
||||
selected.value = { id: 0, name: account.name || '未命名账号', account: account.external_id }
|
||||
}
|
||||
}
|
||||
} catch (cause) {
|
||||
if (!disposed && !isCancelled(cause) && !silent) error.value = errorText(cause)
|
||||
} finally {
|
||||
scheduleDirectory()
|
||||
}
|
||||
}
|
||||
function choosePerson(target: { id: number; name: string; account: string }) {
|
||||
selected.value = target
|
||||
if (role.value !== 'assistant') {
|
||||
role.value = 'assistant'
|
||||
page.value = 1
|
||||
void load()
|
||||
}
|
||||
}
|
||||
function setRole(value: 'all' | 'assistant' | 'doctor') {
|
||||
if (role.value === value) return
|
||||
role.value = value
|
||||
page.value = 1
|
||||
noteTarget.value = 0
|
||||
if (value === 'assistant') void loadDirectory()
|
||||
else stopDirectoryTimer()
|
||||
void load()
|
||||
}
|
||||
function changePage() {
|
||||
void load()
|
||||
}
|
||||
function openStaff(row: ServiceAlert) {
|
||||
emit('open-staff', row.staff)
|
||||
}
|
||||
async function review(row: ServiceAlert, status: Exclude<AlertStatus, 'open'>) {
|
||||
if (!props.canReview || row.status === status) return
|
||||
if (status === 'false_positive' && note.value.trim() === '') {
|
||||
noteTarget.value = row.id
|
||||
note.value = ''
|
||||
return
|
||||
}
|
||||
try {
|
||||
await assistantReviewAlert({
|
||||
id: row.id,
|
||||
status,
|
||||
note: status === 'false_positive' ? note.value.trim() : ''
|
||||
})
|
||||
noteTarget.value = 0
|
||||
note.value = ''
|
||||
await load(true)
|
||||
} catch (cause) {
|
||||
if (!isCancelled(cause)) error.value = errorText(cause)
|
||||
}
|
||||
}
|
||||
function updateVisibility() {
|
||||
if (!visible()) {
|
||||
stopTimer()
|
||||
request?.abort()
|
||||
revision++
|
||||
loading.value = false
|
||||
return
|
||||
}
|
||||
void load(true)
|
||||
}
|
||||
watch(
|
||||
() => props.refreshKey,
|
||||
(_value, previous) => void load(previous !== undefined),
|
||||
{ immediate: true, flush: 'sync' }
|
||||
)
|
||||
onMounted(() => {
|
||||
mounted = true
|
||||
if (typeof document !== 'undefined') {
|
||||
document.addEventListener('visibilitychange', updateVisibility)
|
||||
listening = true
|
||||
}
|
||||
schedule()
|
||||
})
|
||||
onActivated(() => {
|
||||
activated = true
|
||||
})
|
||||
onDeactivated(() => {
|
||||
activated = false
|
||||
updateVisibility()
|
||||
})
|
||||
onBeforeUnmount(() => {
|
||||
disposed = true
|
||||
stopTimer()
|
||||
stopDirectoryTimer()
|
||||
request?.abort()
|
||||
revision++
|
||||
if (listening && typeof document !== 'undefined') {
|
||||
document.removeEventListener('visibilitychange', updateVisibility)
|
||||
}
|
||||
})
|
||||
</script>
|
||||
<style scoped>
|
||||
.alert-inbox {
|
||||
color: var(--el-text-color-primary);
|
||||
}
|
||||
.scan-note {
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.metric-strip {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
background: var(--el-bg-color);
|
||||
border: 1px solid var(--el-border-color-light);
|
||||
border-radius: 5px;
|
||||
padding: 20px 0;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.metric {
|
||||
padding: 0 22px;
|
||||
border-right: 1px solid var(--el-border-color-lighter);
|
||||
}
|
||||
.metric:last-child {
|
||||
border-right: 0;
|
||||
}
|
||||
.metric > span,
|
||||
.metric small {
|
||||
display: block;
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: 12px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.metric strong {
|
||||
display: block;
|
||||
margin: 6px 0 3px;
|
||||
font-size: 27px;
|
||||
line-height: 1.15;
|
||||
font-weight: 600;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.metric-text {
|
||||
font-size: 22px;
|
||||
font-variant-numeric: normal;
|
||||
}
|
||||
.metric--attention strong {
|
||||
color: var(--el-color-primary);
|
||||
}
|
||||
.metric--high strong {
|
||||
color: var(--el-color-danger);
|
||||
}
|
||||
.inbox-panel {
|
||||
background: var(--el-bg-color);
|
||||
border: 1px solid var(--el-border-color-light);
|
||||
border-radius: 5px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.table-heading,
|
||||
.table-toolbar,
|
||||
.table-footer {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.table-heading {
|
||||
padding: 22px 22px 14px;
|
||||
}
|
||||
.table-heading h2 {
|
||||
margin: 0;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.table-heading p,
|
||||
.muted,
|
||||
small {
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: 12px;
|
||||
line-height: 1.7;
|
||||
}
|
||||
.table-heading p {
|
||||
margin: 5px 0 0;
|
||||
}
|
||||
.search-form {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
width: 290px;
|
||||
max-width: 100%;
|
||||
}
|
||||
.role-switch {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr auto;
|
||||
gap: 10px;
|
||||
padding: 0 22px 16px;
|
||||
}
|
||||
.role-switch button {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 10px;
|
||||
padding: 14px 16px;
|
||||
border: 1px solid var(--el-border-color-light);
|
||||
border-radius: 8px;
|
||||
background: var(--el-fill-color-blank);
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
color: var(--el-text-color-primary);
|
||||
}
|
||||
.role-switch button span {
|
||||
font-size: 14px;
|
||||
font-weight: 650;
|
||||
}
|
||||
.role-switch button strong {
|
||||
font-size: 26px;
|
||||
line-height: 1;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.role-switch button small {
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
.role-switch button:first-child strong {
|
||||
color: #0f766e;
|
||||
}
|
||||
.role-switch button:nth-child(2) strong {
|
||||
color: #1e4b8a;
|
||||
}
|
||||
.role-switch button.active:first-child {
|
||||
border-color: #0f766e;
|
||||
background: #f0fdfa;
|
||||
}
|
||||
.role-switch button.active:nth-child(2) {
|
||||
border-color: #1e4b8a;
|
||||
background: #eff6ff;
|
||||
}
|
||||
.role-switch__all {
|
||||
align-items: center;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.role-switch__all.active {
|
||||
border-color: var(--el-color-primary);
|
||||
color: var(--el-color-primary);
|
||||
}
|
||||
.chat-workspace {
|
||||
display: grid;
|
||||
grid-template-columns: 240px 1fr;
|
||||
gap: 16px;
|
||||
min-height: 560px;
|
||||
padding: 0 16px 16px;
|
||||
}
|
||||
.people-pane,
|
||||
.chat-pane {
|
||||
min-width: 0;
|
||||
}
|
||||
.people-pane {
|
||||
padding: 8px;
|
||||
border: 1px solid var(--el-border-color-lighter);
|
||||
border-radius: 10px;
|
||||
background: var(--el-fill-color-blank);
|
||||
}
|
||||
.pane-label,
|
||||
.pane-note {
|
||||
margin: 8px 8px 6px;
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.people-pane button {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
justify-content: space-between;
|
||||
align-items: baseline;
|
||||
gap: 8px;
|
||||
margin-bottom: 6px;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 8px;
|
||||
background: transparent;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
.people-pane button.active {
|
||||
border-color: #1e4b8a;
|
||||
background: #eff6ff;
|
||||
}
|
||||
.people-pane strong {
|
||||
font-size: 14px;
|
||||
}
|
||||
.people-pane small {
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
.chat-pane {
|
||||
padding: 8px 8px 8px 4px;
|
||||
}
|
||||
.chat-pane h3 {
|
||||
margin: 0 0 12px;
|
||||
font-size: 18px;
|
||||
}
|
||||
@media (max-width: 900px) {
|
||||
.chat-workspace {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
.feed {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0 12px 8px;
|
||||
}
|
||||
.feed-item {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 18px;
|
||||
margin-bottom: 10px;
|
||||
padding: 14px 16px 14px 14px;
|
||||
border: 1px solid var(--el-border-color-lighter);
|
||||
border-left-width: 4px;
|
||||
border-radius: 8px;
|
||||
background: var(--el-bg-color);
|
||||
}
|
||||
.feed-item--assistant {
|
||||
border-left-color: #0f766e;
|
||||
}
|
||||
.feed-item--doctor {
|
||||
border-left-color: #1e4b8a;
|
||||
}
|
||||
.feed-item--other {
|
||||
border-left-color: var(--el-border-color);
|
||||
}
|
||||
.feed-main {
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
}
|
||||
.feed-who {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
.role-pill {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
height: 22px;
|
||||
padding: 0 8px;
|
||||
border-radius: 999px;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
.role-pill--assistant {
|
||||
color: #0f766e;
|
||||
background: #ccfbf1;
|
||||
}
|
||||
.role-pill--doctor {
|
||||
color: #1e4b8a;
|
||||
background: #dbeafe;
|
||||
}
|
||||
.role-pill--other {
|
||||
color: var(--el-text-color-regular);
|
||||
background: var(--el-fill-color);
|
||||
}
|
||||
.patient {
|
||||
color: var(--el-text-color-regular);
|
||||
}
|
||||
.feed-who small {
|
||||
margin: 0;
|
||||
}
|
||||
.snippet {
|
||||
margin: 8px 0 0;
|
||||
font-size: 14px;
|
||||
line-height: 1.65;
|
||||
}
|
||||
.review-note {
|
||||
margin: 4px 0 0;
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: 12px;
|
||||
}
|
||||
.feed-meta {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px 14px;
|
||||
margin-top: 8px;
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: 12px;
|
||||
}
|
||||
.feed-actions {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
.table-toolbar {
|
||||
padding: 0 22px 16px;
|
||||
}
|
||||
.filter-group {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
padding: 3px;
|
||||
border-radius: 4px;
|
||||
background: var(--el-fill-color-light);
|
||||
}
|
||||
.filter-group button,
|
||||
.review-actions button {
|
||||
cursor: pointer;
|
||||
border: 0;
|
||||
padding: 7px 12px;
|
||||
border-radius: 3px;
|
||||
font-size: 12px;
|
||||
background: transparent;
|
||||
color: var(--el-text-color-regular);
|
||||
}
|
||||
.filter-group button.active {
|
||||
background: var(--el-bg-color);
|
||||
color: var(--el-color-primary);
|
||||
font-weight: 600;
|
||||
}
|
||||
.review-actions {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
}
|
||||
.review-actions button:disabled {
|
||||
cursor: default;
|
||||
color: var(--el-text-color-placeholder);
|
||||
}
|
||||
.note-form {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
.table-error {
|
||||
margin: 0 22px 16px;
|
||||
width: auto;
|
||||
}
|
||||
.table-skeleton {
|
||||
padding: 22px;
|
||||
}
|
||||
.alert-table small {
|
||||
display: block;
|
||||
margin-top: 2px;
|
||||
}
|
||||
.staff-link {
|
||||
border: 0;
|
||||
background: transparent;
|
||||
padding: 0;
|
||||
cursor: pointer;
|
||||
color: var(--el-color-primary);
|
||||
font-size: 13px;
|
||||
}
|
||||
.severity {
|
||||
display: inline-block;
|
||||
margin-right: 6px;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.severity--high {
|
||||
color: var(--el-color-danger);
|
||||
}
|
||||
.severity--medium {
|
||||
color: var(--el-color-warning);
|
||||
}
|
||||
.snippet {
|
||||
quotes: none;
|
||||
font-style: normal;
|
||||
}
|
||||
.number {
|
||||
font-variant-numeric: tabular-nums;
|
||||
font-size: 13px;
|
||||
}
|
||||
.table-footer {
|
||||
padding: 16px 22px;
|
||||
}
|
||||
@media (max-width: 720px) {
|
||||
.metric-strip {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 18px 0;
|
||||
}
|
||||
.metric:nth-child(2) {
|
||||
border-right: 0;
|
||||
}
|
||||
.search-form {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,730 @@
|
||||
<template>
|
||||
<div class="case-detail">
|
||||
<el-button class="mb-4" @click="emit('back')">返回医助详情</el-button>
|
||||
<p class="muted">关联沟通核查 · 医助 #{{ assistantId }} · 患者信息仅用于定位服务证据</p>
|
||||
|
||||
<el-card shadow="never" class="patient-header">
|
||||
<div class="patient-summary">
|
||||
<div>
|
||||
<h2>{{ selected.patient_name || '未命名患者' }}</h2>
|
||||
<span
|
||||
>诊单 #{{ selected.diagnosis_id }} ·
|
||||
{{ selected.phone_masked || '当前授权患者' }}</span
|
||||
>
|
||||
</div>
|
||||
<div class="patient-controls">
|
||||
<span class="muted">最近 {{ days }} 天</span>
|
||||
<el-button :loading="contextLoading" @click="reloadContext">刷新来源</el-button
|
||||
><el-button
|
||||
v-if="can('record') && assistantId === actorId"
|
||||
:disabled="contextLoading || !!contextError"
|
||||
type="primary"
|
||||
plain
|
||||
@click="recordOpened = true"
|
||||
>录入服务记录</el-button
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</el-card>
|
||||
<el-alert
|
||||
v-if="contextError"
|
||||
:title="contextError"
|
||||
type="error"
|
||||
:closable="false"
|
||||
show-icon
|
||||
class="mb-4"
|
||||
/>
|
||||
<el-card shadow="never" v-loading="contextLoading" class="content-card">
|
||||
<el-tabs v-model="activeTab">
|
||||
<el-tab-pane label="来源时间线" name="sources"
|
||||
><SourceTimeline
|
||||
v-if="context"
|
||||
:sources="context.sources"
|
||||
:coverage="context.coverage" /><el-empty
|
||||
v-else-if="!contextLoading"
|
||||
description="来源尚未加载,请刷新来源"
|
||||
/></el-tab-pane>
|
||||
<el-tab-pane label="医助服务分析" name="analysis">
|
||||
<div v-if="!automatic" class="generation-toolbar">
|
||||
<el-select v-model="scenario" aria-label="分析场景" style="width: 170px"
|
||||
><el-option
|
||||
v-for="item in capabilities.scenarios"
|
||||
:key="item.value"
|
||||
:label="item.label"
|
||||
:value="item.value" /></el-select
|
||||
><el-button
|
||||
v-if="can('analyze')"
|
||||
type="primary"
|
||||
:loading="submitting.analysis"
|
||||
:disabled="
|
||||
!canGenerate || busy('analysis') || unknownSubmission.analysis
|
||||
"
|
||||
@click="generate('analysis')"
|
||||
>生成服务分析</el-button
|
||||
>
|
||||
</div>
|
||||
<p v-if="!context?.sources.length" class="muted">
|
||||
当前医助在此范围无可用来源,可由医助补录本人服务记录。
|
||||
</p>
|
||||
<p v-else-if="automatic" class="muted">
|
||||
系统自动分析更新后的沟通记录,结果仍需结合原文核查。
|
||||
</p>
|
||||
<el-alert
|
||||
v-if="newAnalysisAvailable"
|
||||
title="已有更新的分析结果。完成当前核查后可查看最新结果。"
|
||||
type="info"
|
||||
:closable="false"
|
||||
class="mb-4"
|
||||
><el-button link type="primary" @click="showLatestAnalysis"
|
||||
>查看最新结果</el-button
|
||||
></el-alert
|
||||
>
|
||||
<el-alert
|
||||
v-if="submitErrors.analysis"
|
||||
:title="submitErrors.analysis"
|
||||
type="error"
|
||||
:closable="false"
|
||||
class="mb-4"
|
||||
/>
|
||||
<el-button v-if="unknownSubmission.analysis" class="mb-4" @click="reloadContext"
|
||||
>查询已提交任务</el-button
|
||||
>
|
||||
<JobResult
|
||||
v-if="analysisState.job"
|
||||
:key="analysisState.job.id"
|
||||
:job="analysisState.job"
|
||||
:permissions="capabilities.permissions"
|
||||
:error="analysisState.error"
|
||||
:checking="analysisState.checking"
|
||||
:disabled="contextLoading || !!contextError"
|
||||
@refresh="refreshAnalysis"
|
||||
@adopted="handleAdopted"
|
||||
@evidence="showEvidence"
|
||||
/>
|
||||
<el-empty
|
||||
v-else-if="!contextLoading"
|
||||
:description="
|
||||
automatic
|
||||
? '尚无分析结果,系统会自动分析可用沟通记录'
|
||||
: '尚无服务分析,选择场景后生成'
|
||||
"
|
||||
:image-size="90"
|
||||
/>
|
||||
</el-tab-pane>
|
||||
<el-tab-pane label="回复草稿" name="reply">
|
||||
<el-form label-position="top"
|
||||
><el-form-item label="需要回复的服务问题"
|
||||
><el-input
|
||||
v-model="question"
|
||||
type="textarea"
|
||||
:rows="3"
|
||||
:maxlength="1000"
|
||||
show-word-limit
|
||||
placeholder="例如:患者询问复诊预约流程。请录入实际问题,答复将依据已发布的服务知识。" /></el-form-item
|
||||
></el-form>
|
||||
<div class="generation-toolbar">
|
||||
<el-select v-model="scenario" aria-label="回复场景" style="width: 170px"
|
||||
><el-option
|
||||
v-for="item in capabilities.scenarios"
|
||||
:key="item.value"
|
||||
:label="item.label"
|
||||
:value="item.value" /></el-select
|
||||
><el-button
|
||||
v-if="can('draftReply')"
|
||||
type="primary"
|
||||
:loading="submitting.reply"
|
||||
:disabled="
|
||||
!canGenerate ||
|
||||
!question.trim() ||
|
||||
busy('reply') ||
|
||||
unknownSubmission.reply
|
||||
"
|
||||
@click="generate('reply')"
|
||||
>生成回复草稿</el-button
|
||||
><span class="muted">人工核对与编辑后复制</span>
|
||||
</div>
|
||||
<el-alert
|
||||
v-if="submitErrors.reply"
|
||||
:title="submitErrors.reply"
|
||||
type="error"
|
||||
:closable="false"
|
||||
class="mb-4"
|
||||
/>
|
||||
<el-button v-if="unknownSubmission.reply" class="mb-4" @click="reloadContext"
|
||||
>查询已提交任务</el-button
|
||||
>
|
||||
<JobResult
|
||||
v-if="replyState.job"
|
||||
:key="replyState.job.id"
|
||||
:job="replyState.job"
|
||||
:permissions="capabilities.permissions"
|
||||
:error="replyState.error"
|
||||
:checking="replyState.checking"
|
||||
:disabled="contextLoading || !!contextError"
|
||||
@refresh="replyTracker.refresh"
|
||||
@adopted="handleAdopted"
|
||||
@evidence="showEvidence"
|
||||
/>
|
||||
<el-empty
|
||||
v-else-if="!contextLoading"
|
||||
description="输入实际服务问题,生成有知识依据的回复草稿"
|
||||
:image-size="90"
|
||||
/>
|
||||
</el-tab-pane>
|
||||
<el-tab-pane label="服务待办" name="actions"
|
||||
><ServiceActions
|
||||
v-if="context"
|
||||
:key="selected.diagnosis_id"
|
||||
:diagnosis-id="selected.diagnosis_id"
|
||||
:assistant-id="assistantId"
|
||||
:actor-id="actorId"
|
||||
:can-complete="can('completeAction')"
|
||||
:can-review="can('reviewQuality')"
|
||||
:refresh-key="actionsRefresh"
|
||||
@changed="emit('changed')"
|
||||
/></el-tab-pane>
|
||||
<el-tab-pane label="分析与复核记录" name="history">
|
||||
<el-alert
|
||||
v-if="historyError"
|
||||
:title="historyError"
|
||||
type="error"
|
||||
:closable="false"
|
||||
class="mb-4"
|
||||
/>
|
||||
<el-table
|
||||
v-loading="historyLoading"
|
||||
:data="history"
|
||||
empty-text="该医助在此诊单暂无分析记录"
|
||||
><el-table-column prop="id" label="任务" width="90" /><el-table-column
|
||||
label="类型"
|
||||
width="110"
|
||||
><template #default="{ row }">{{
|
||||
row.type === 'reply' ? '回复草稿' : '服务分析'
|
||||
}}</template></el-table-column
|
||||
><el-table-column label="创建时间" min-width="170"
|
||||
><template #default="{ row }">{{
|
||||
formatTime(row.created_at)
|
||||
}}</template></el-table-column
|
||||
><el-table-column label="状态" min-width="170"
|
||||
><template #default="{ row }">{{
|
||||
jobLabels[row.status as JobStatus]
|
||||
}}</template></el-table-column
|
||||
><el-table-column label="操作" width="90"
|
||||
><template #default="{ row }"
|
||||
><el-button link type="primary" @click="openHistory(row)"
|
||||
>查看</el-button
|
||||
></template
|
||||
></el-table-column
|
||||
></el-table
|
||||
>
|
||||
<el-pagination
|
||||
v-if="historyTotal"
|
||||
v-model:current-page="historyPage"
|
||||
class="mt-4"
|
||||
:total="historyTotal"
|
||||
:page-size="10"
|
||||
layout="total, prev, pager, next"
|
||||
@current-change="loadHistory"
|
||||
/>
|
||||
</el-tab-pane>
|
||||
</el-tabs>
|
||||
</el-card>
|
||||
<RecordDialog
|
||||
v-if="assistantId === actorId"
|
||||
:key="selected.diagnosis_id"
|
||||
v-model="recordOpened"
|
||||
:diagnosis-id="selected.diagnosis_id"
|
||||
:max-chars="capabilities.limits.max_manual_chars"
|
||||
@saved="reloadContext"
|
||||
/>
|
||||
|
||||
<el-drawer
|
||||
v-model="evidenceOpened"
|
||||
title="原文依据 · 生成时的来源快照"
|
||||
size="min(620px, 96vw)"
|
||||
append-to-body
|
||||
>
|
||||
<SourceTimeline :sources="evidenceSources" :coverage="[]" />
|
||||
</el-drawer>
|
||||
</div>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
computed,
|
||||
onActivated,
|
||||
onBeforeUnmount,
|
||||
onDeactivated,
|
||||
onMounted,
|
||||
reactive,
|
||||
ref,
|
||||
watch
|
||||
} from 'vue'
|
||||
import {
|
||||
assistantAnalyze,
|
||||
assistantContext,
|
||||
assistantDraftReply,
|
||||
assistantJob,
|
||||
assistantJobs,
|
||||
type Capabilities,
|
||||
type Context,
|
||||
type Days,
|
||||
type Job,
|
||||
type JobStatus,
|
||||
type Patient,
|
||||
type Permission,
|
||||
type Scenario,
|
||||
type Source
|
||||
} from '@/api/assistantService'
|
||||
import useUserStore from '@/stores/modules/user'
|
||||
import SourceTimeline from './SourceTimeline.vue'
|
||||
import RecordDialog from './RecordDialog.vue'
|
||||
import JobResult from './JobResult.vue'
|
||||
import ServiceActions from './ServiceActions.vue'
|
||||
import { createJobTracker } from '../workbench/jobTracker'
|
||||
import { errorText, formatTime, isCancelled, jobLabels } from '../shared'
|
||||
const props = defineProps<{
|
||||
patient: Patient
|
||||
assistantId: number
|
||||
days: Days
|
||||
capabilities: Capabilities
|
||||
initialJobId?: number
|
||||
automatic?: boolean
|
||||
refreshKey?: number
|
||||
}>()
|
||||
const emit = defineEmits<{ (event: 'back'): void; (event: 'changed'): void }>()
|
||||
const capabilities = computed(() => props.capabilities)
|
||||
const selected = ref<Patient>(props.patient),
|
||||
context = ref<Context | null>(null),
|
||||
days = computed(() => props.days),
|
||||
scenario = ref<Scenario>('followup'),
|
||||
question = ref(''),
|
||||
activeTab = ref('analysis')
|
||||
const contextLoading = ref(false),
|
||||
contextError = ref(''),
|
||||
recordOpened = ref(false),
|
||||
actionsRefresh = ref(0)
|
||||
const user = useUserStore(),
|
||||
actorId = computed(() => Number(user.userInfo.id || user.userInfo.admin_id || 0))
|
||||
const can = (permission: Permission) =>
|
||||
capabilities.value?.permissions.includes(permission) || false
|
||||
const canGenerate = computed(
|
||||
() =>
|
||||
!!capabilities.value?.ready &&
|
||||
!!context.value?.sources.length &&
|
||||
!contextLoading.value &&
|
||||
!contextError.value
|
||||
)
|
||||
const analysisTracker = createJobTracker({ read: assistantJob }),
|
||||
replyTracker = createJobTracker({ read: assistantJob })
|
||||
const analysisState = analysisTracker.state,
|
||||
replyState = replyTracker.state
|
||||
const trackers = { analysis: analysisTracker, reply: replyTracker }
|
||||
const submitting = reactive({ analysis: false, reply: false }),
|
||||
unknownSubmission = reactive({ analysis: false, reply: false }),
|
||||
submitErrors = reactive({ analysis: '', reply: '' })
|
||||
const busy = (type: 'analysis' | 'reply') =>
|
||||
['queued', 'running', 'needs_reconciliation'].includes(trackers[type].state.job?.status || '')
|
||||
const inFlight = new Set<string>()
|
||||
const history = ref<Job[]>([]),
|
||||
historyPage = ref(1),
|
||||
historyTotal = ref(0),
|
||||
historyLoading = ref(false),
|
||||
historyError = ref('')
|
||||
const evidenceOpened = ref(false),
|
||||
evidenceSources = ref<Source[]>([])
|
||||
const newAnalysisAvailable = computed(
|
||||
() =>
|
||||
!!context.value?.latest_analysis_job &&
|
||||
!!analysisState.job &&
|
||||
context.value.latest_analysis_job.id > analysisState.job.id
|
||||
)
|
||||
let revision = 0,
|
||||
historyRevision = 0,
|
||||
disposed = false,
|
||||
activated = true
|
||||
let contextRequest: AbortController | undefined,
|
||||
historyRequest: AbortController | undefined,
|
||||
automaticRequest: AbortController | undefined
|
||||
let automaticRevision = 0
|
||||
function clearPatient() {
|
||||
revision++
|
||||
historyRevision++
|
||||
contextRequest?.abort()
|
||||
historyRequest?.abort()
|
||||
automaticRequest?.abort()
|
||||
automaticRevision++
|
||||
context.value = null
|
||||
history.value = []
|
||||
historyTotal.value = 0
|
||||
analysisTracker.setJob(null)
|
||||
replyTracker.setJob(null)
|
||||
evidenceOpened.value = false
|
||||
evidenceSources.value = []
|
||||
recordOpened.value = false
|
||||
}
|
||||
function selectPatient(patient: Patient) {
|
||||
clearPatient()
|
||||
selected.value = patient
|
||||
activeTab.value = 'analysis'
|
||||
question.value = ''
|
||||
historyPage.value = 1
|
||||
submitting.analysis = false
|
||||
submitting.reply = false
|
||||
submitErrors.analysis = ''
|
||||
submitErrors.reply = ''
|
||||
unknownSubmission.analysis = false
|
||||
unknownSubmission.reply = false
|
||||
void reloadContext()
|
||||
}
|
||||
async function reloadContext(preferLatest: unknown = false) {
|
||||
if (!selected.value) return
|
||||
const token = ++revision,
|
||||
id = selected.value.diagnosis_id
|
||||
contextRequest?.abort()
|
||||
automaticRequest?.abort()
|
||||
automaticRevision++
|
||||
contextRequest = new AbortController()
|
||||
contextLoading.value = true
|
||||
contextError.value = ''
|
||||
context.value = null
|
||||
history.value = []
|
||||
historyTotal.value = 0
|
||||
analysisTracker.setJob(null)
|
||||
replyTracker.setJob(null)
|
||||
evidenceOpened.value = false
|
||||
evidenceSources.value = []
|
||||
try {
|
||||
const data = await assistantContext(
|
||||
{ diagnosis_id: id, days: days.value, assistant_id: props.assistantId },
|
||||
contextRequest.signal
|
||||
)
|
||||
if (disposed || token !== revision) return
|
||||
assertContext(data, id)
|
||||
context.value = data
|
||||
analysisTracker.setJob(data.latest_analysis_job)
|
||||
if (data.latest_job?.type === 'reply') replyTracker.setJob(data.latest_job)
|
||||
await loadHistory(true)
|
||||
if (disposed || token !== revision) return
|
||||
for (const tracker of Object.values(trackers)) if (tracker.state.job) void tracker.refresh()
|
||||
if (!historyError.value) {
|
||||
unknownSubmission.analysis = false
|
||||
unknownSubmission.reply = false
|
||||
submitErrors.analysis = ''
|
||||
submitErrors.reply = ''
|
||||
}
|
||||
if (props.initialJobId && preferLatest !== true) {
|
||||
const target = await assistantJob(props.initialJobId, contextRequest.signal)
|
||||
if (disposed || token !== revision) return
|
||||
if (target.diagnosis_id !== id || target.subject_admin_id !== props.assistantId)
|
||||
throw new Error('质检问题与当前医助或诊单不一致')
|
||||
trackers[target.type].setJob(target)
|
||||
activeTab.value = target.type
|
||||
}
|
||||
if (preferLatest === true) activeTab.value = 'analysis'
|
||||
actionsRefresh.value++
|
||||
} catch (cause) {
|
||||
if (!disposed && token === revision && !isCancelled(cause))
|
||||
contextError.value = errorText(cause)
|
||||
} finally {
|
||||
if (!disposed && token === revision) contextLoading.value = false
|
||||
}
|
||||
}
|
||||
function showLatestAnalysis() {
|
||||
void reloadContext(true)
|
||||
}
|
||||
function assertContext(data: Context, diagnosisId: number) {
|
||||
if (
|
||||
data.patient.diagnosis_id !== diagnosisId ||
|
||||
data.subject_admin_id !== props.assistantId ||
|
||||
[data.latest_job, data.latest_analysis_job].some(
|
||||
(job) =>
|
||||
job &&
|
||||
(job.subject_admin_id !== props.assistantId || job.diagnosis_id !== diagnosisId)
|
||||
) ||
|
||||
(data.latest_analysis_job && data.latest_analysis_job.type !== 'analysis')
|
||||
)
|
||||
throw new Error('返回的来源与当前医助或关联诊单不一致')
|
||||
}
|
||||
async function loadHistory(restore: unknown = false) {
|
||||
if (!selected.value) return
|
||||
// el-pagination 传入页码;只有显式 true 才恢复回复,最新分析由 context 独立提供。
|
||||
const shouldRestore = restore === true
|
||||
if (shouldRestore) historyPage.value = 1
|
||||
const token = ++historyRevision,
|
||||
patientToken = revision,
|
||||
id = selected.value.diagnosis_id
|
||||
historyRequest?.abort()
|
||||
historyRequest = new AbortController()
|
||||
historyLoading.value = true
|
||||
historyError.value = ''
|
||||
try {
|
||||
const data = await assistantJobs(
|
||||
{
|
||||
diagnosis_id: id,
|
||||
assistant_id: props.assistantId,
|
||||
page_no: historyPage.value,
|
||||
page_size: 10
|
||||
},
|
||||
historyRequest.signal
|
||||
)
|
||||
if (disposed || token !== historyRevision || patientToken !== revision) return
|
||||
if (
|
||||
data.lists.some(
|
||||
(job) => job.subject_admin_id !== props.assistantId || job.diagnosis_id !== id
|
||||
)
|
||||
)
|
||||
throw new Error('历史记录与当前医助或诊单不一致')
|
||||
history.value = data.lists
|
||||
historyTotal.value = data.count
|
||||
if (shouldRestore && !replyState.job) {
|
||||
const job = data.lists.find((item) => item.type === 'reply')
|
||||
if (job) replyTracker.setJob(job)
|
||||
}
|
||||
} catch (cause) {
|
||||
if (
|
||||
!disposed &&
|
||||
token === historyRevision &&
|
||||
patientToken === revision &&
|
||||
!isCancelled(cause)
|
||||
) {
|
||||
historyError.value = errorText(cause)
|
||||
history.value = []
|
||||
historyTotal.value = 0
|
||||
}
|
||||
} finally {
|
||||
if (!disposed && token === historyRevision) historyLoading.value = false
|
||||
}
|
||||
}
|
||||
async function generate(type: 'analysis' | 'reply') {
|
||||
if (props.automatic && type === 'analysis') return
|
||||
if (
|
||||
!selected.value ||
|
||||
!canGenerate.value ||
|
||||
submitting[type] ||
|
||||
busy(type) ||
|
||||
unknownSubmission[type]
|
||||
)
|
||||
return
|
||||
if (!can(type === 'analysis' ? 'analyze' : 'draftReply')) return
|
||||
if (type === 'reply' && !question.value.trim()) return
|
||||
const token = revision,
|
||||
diagnosis_id = selected.value.diagnosis_id,
|
||||
key = `${props.assistantId}:${days.value}:${diagnosis_id}:${type}`
|
||||
if (inFlight.has(key)) return
|
||||
inFlight.add(key)
|
||||
submitting[type] = true
|
||||
submitErrors[type] = ''
|
||||
const data = {
|
||||
diagnosis_id,
|
||||
assistant_id: props.assistantId,
|
||||
days: days.value,
|
||||
scenario: scenario.value
|
||||
}
|
||||
try {
|
||||
const job = await (type === 'analysis'
|
||||
? assistantAnalyze(data)
|
||||
: assistantDraftReply({ ...data, question: question.value.trim() }))
|
||||
if (disposed || token !== revision) return
|
||||
if (
|
||||
job.diagnosis_id !== diagnosis_id ||
|
||||
job.type !== type ||
|
||||
job.subject_admin_id !== props.assistantId
|
||||
)
|
||||
throw new Error('任务与当前医助或关联诊单不一致')
|
||||
trackers[type].setJob(job)
|
||||
void loadHistory()
|
||||
} catch (cause) {
|
||||
if (!disposed && token === revision) {
|
||||
submitErrors[type] = `${errorText(cause)}。请先查询已提交任务,确认状态后再操作。`
|
||||
unknownSubmission[type] = true
|
||||
}
|
||||
} finally {
|
||||
inFlight.delete(key)
|
||||
if (!disposed && token === revision) submitting[type] = false
|
||||
}
|
||||
}
|
||||
function handleAdopted() {
|
||||
actionsRefresh.value++
|
||||
emit('changed')
|
||||
}
|
||||
async function refreshAnalysis() {
|
||||
await analysisTracker.refresh()
|
||||
if (!disposed) emit('changed')
|
||||
}
|
||||
watch(
|
||||
() => [props.patient.diagnosis_id, props.assistantId, props.days],
|
||||
() => selectPatient(props.patient),
|
||||
{ flush: 'sync' }
|
||||
)
|
||||
function openHistory(job: Job) {
|
||||
trackers[job.type].setJob({ ...job, result: null })
|
||||
activeTab.value = job.type
|
||||
void trackers[job.type].refresh()
|
||||
}
|
||||
function showEvidence(sources: Source[]) {
|
||||
evidenceSources.value = sources
|
||||
evidenceOpened.value = true
|
||||
}
|
||||
async function refreshAutomatic() {
|
||||
if (
|
||||
!props.automatic ||
|
||||
disposed ||
|
||||
!activated ||
|
||||
document.visibilityState === 'hidden' ||
|
||||
contextLoading.value
|
||||
)
|
||||
return
|
||||
const token = revision,
|
||||
readToken = ++automaticRevision,
|
||||
id = selected.value.diagnosis_id
|
||||
automaticRequest?.abort()
|
||||
automaticRequest = new AbortController()
|
||||
try {
|
||||
const data = await assistantContext(
|
||||
{ diagnosis_id: id, days: days.value, assistant_id: props.assistantId },
|
||||
automaticRequest.signal
|
||||
)
|
||||
if (disposed || token !== revision || readToken !== automaticRevision) return
|
||||
assertContext(data, id)
|
||||
context.value = data
|
||||
contextError.value = ''
|
||||
if (!analysisState.job && data.latest_analysis_job)
|
||||
analysisTracker.setJob(data.latest_analysis_job)
|
||||
// 保持当前核查和输入;仅更新当前结果的有效性,不自动切换到另一份分析。
|
||||
if (analysisState.job) void analysisTracker.refresh()
|
||||
if (replyState.job) void replyTracker.refresh()
|
||||
void loadHistory()
|
||||
actionsRefresh.value++
|
||||
} catch (cause) {
|
||||
if (
|
||||
!disposed &&
|
||||
token === revision &&
|
||||
readToken === automaticRevision &&
|
||||
!isCancelled(cause)
|
||||
) {
|
||||
contextError.value = errorText(cause)
|
||||
context.value = null
|
||||
analysisTracker.setJob(null)
|
||||
replyTracker.setJob(null)
|
||||
evidenceOpened.value = false
|
||||
evidenceSources.value = []
|
||||
}
|
||||
}
|
||||
}
|
||||
watch(
|
||||
() => props.refreshKey,
|
||||
() => void refreshAutomatic()
|
||||
)
|
||||
function updateVisibility() {
|
||||
const visible = activated && document.visibilityState !== 'hidden'
|
||||
analysisTracker.setActive(visible)
|
||||
replyTracker.setActive(visible)
|
||||
if (!visible) {
|
||||
automaticRequest?.abort()
|
||||
automaticRevision++
|
||||
}
|
||||
}
|
||||
onMounted(() => {
|
||||
document.addEventListener('visibilitychange', updateVisibility)
|
||||
updateVisibility()
|
||||
selectPatient(props.patient)
|
||||
})
|
||||
onActivated(() => {
|
||||
activated = true
|
||||
updateVisibility()
|
||||
})
|
||||
onDeactivated(() => {
|
||||
activated = false
|
||||
updateVisibility()
|
||||
})
|
||||
onBeforeUnmount(() => {
|
||||
disposed = true
|
||||
revision++
|
||||
historyRevision++
|
||||
contextRequest?.abort()
|
||||
historyRequest?.abort()
|
||||
automaticRequest?.abort()
|
||||
automaticRevision++
|
||||
analysisTracker.dispose()
|
||||
replyTracker.dispose()
|
||||
document.removeEventListener('visibilitychange', updateVisibility)
|
||||
})
|
||||
</script>
|
||||
<style scoped>
|
||||
.assistant-workbench {
|
||||
padding: 4px;
|
||||
}
|
||||
.page-heading {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
margin-bottom: 20px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
h1 {
|
||||
font-size: 22px;
|
||||
font-weight: 600;
|
||||
margin: 0 0 8px;
|
||||
}
|
||||
.page-heading p,
|
||||
.patient-summary span,
|
||||
.muted {
|
||||
font-size: 13px;
|
||||
color: var(--el-text-color-secondary);
|
||||
line-height: 1.6;
|
||||
}
|
||||
.page-heading p {
|
||||
margin: 0;
|
||||
}
|
||||
.workspace-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 260px minmax(0, 1fr);
|
||||
gap: 16px;
|
||||
align-items: start;
|
||||
}
|
||||
.workspace-main {
|
||||
min-width: 0;
|
||||
}
|
||||
.patient-header {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.patient-summary,
|
||||
.patient-controls,
|
||||
.generation-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.patient-summary {
|
||||
justify-content: space-between;
|
||||
}
|
||||
h2 {
|
||||
margin: 0 0 5px;
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.generation-toolbar {
|
||||
margin: 0 0 18px;
|
||||
}
|
||||
.content-card {
|
||||
min-height: 380px;
|
||||
}
|
||||
@media (max-width: 1100px) {
|
||||
.workspace-grid {
|
||||
grid-template-columns: 220px minmax(0, 1fr);
|
||||
}
|
||||
}
|
||||
@media (max-width: 760px) {
|
||||
.workspace-grid {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
.patient-controls {
|
||||
width: 100%;
|
||||
}
|
||||
.content-card :deep(.el-card__body) {
|
||||
padding: 14px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,459 @@
|
||||
<template>
|
||||
<section class="daily-contacts" aria-label="今日维护名单">
|
||||
<header class="daily-heading">
|
||||
<div>
|
||||
<h3>
|
||||
今日维护 <span>{{ businessDate || '日期待确认' }} · 上海时间</span>
|
||||
</h3>
|
||||
<p>按患者合并到期任务;人工登记需要核实,不计入已联系。</p>
|
||||
</div>
|
||||
<el-button :loading="loading" @click="load()">刷新名单</el-button>
|
||||
</header>
|
||||
<el-alert v-if="error" :title="error" type="error" :closable="false" show-icon />
|
||||
<el-alert
|
||||
v-else-if="data && data.daily.state !== 'ready'"
|
||||
:title="data.daily.reason || '今日计划尚未完整生成,暂不能确认维护完成情况'"
|
||||
type="warning"
|
||||
:closable="false"
|
||||
show-icon
|
||||
/>
|
||||
<div v-if="data" class="daily-counts" aria-label="该医助今日患者小计">
|
||||
<span
|
||||
>应维护 <b>{{ data.summary.required ?? '—' }}</b></span
|
||||
>
|
||||
<span
|
||||
>已联系 <b>{{ data.summary.contacted ?? '—' }}</b></span
|
||||
>
|
||||
<span
|
||||
>待维护 <b>{{ data.summary.pending ?? '—' }}</b></span
|
||||
>
|
||||
<span
|
||||
>人工登记待核实 <b>{{ data.summary.reported ?? '—' }}</b></span
|
||||
>
|
||||
<span class="muted">豁免 {{ data.summary.exempt ?? '—' }}</span>
|
||||
</div>
|
||||
<div class="status-filter" role="group" aria-label="今日名单状态">
|
||||
<button
|
||||
v-for="item in statuses"
|
||||
:key="item.value"
|
||||
type="button"
|
||||
:aria-pressed="status === item.value"
|
||||
:class="{ active: status === item.value }"
|
||||
@click="setStatus(item.value)"
|
||||
>
|
||||
{{ item.label }}
|
||||
</button>
|
||||
</div>
|
||||
<el-skeleton v-if="loading && !data" :rows="5" animated />
|
||||
<template v-else>
|
||||
<p
|
||||
v-if="data && data.daily.state === 'ready' && data.summary.state === 'done'"
|
||||
class="completion-note"
|
||||
>
|
||||
今日应维护患者均有联系记录。联系记录不代表患者已回复或服务质量已达标。
|
||||
</p>
|
||||
<ul v-if="data?.lists.length" class="patient-list" :aria-busy="loading">
|
||||
<li v-for="patient in data.lists" :key="patient.key" class="patient-row">
|
||||
<div class="patient-name">
|
||||
<strong>{{ patient.patient_name || '未命名患者' }}</strong>
|
||||
<small>诊单 #{{ patient.diagnosis_ids.join('、#') }}</small>
|
||||
</div>
|
||||
<div class="patient-reasons">
|
||||
<p
|
||||
v-for="reason in patient.reasons"
|
||||
:key="`${reason.type}:${reason.source_id}`"
|
||||
>
|
||||
{{ reason.label
|
||||
}}<small v-if="reason.due_at"
|
||||
>到期 {{ shanghaiTime(reason.due_at) }}</small
|
||||
>
|
||||
</p>
|
||||
<p v-if="patient.exempt_reason" class="muted">
|
||||
豁免原因:{{ patient.exempt_reason }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="patient-state">
|
||||
<strong
|
||||
:class="{
|
||||
attention:
|
||||
patient.status === 'pending' || patient.status === 'reported'
|
||||
}"
|
||||
>
|
||||
{{ statusLabels[patient.status] }}
|
||||
</strong>
|
||||
<small v-if="patient.status === 'pending'">未发现今日联系记录</small>
|
||||
<small v-if="patient.last_contact_at"
|
||||
>联系 {{ shanghaiTime(patient.last_contact_at) }}</small
|
||||
>
|
||||
<small
|
||||
v-for="evidence in patient.evidence"
|
||||
:key="`${evidence.type}:${evidence.id}`"
|
||||
>
|
||||
{{ evidence.label }} · {{ shanghaiTime(evidence.at) }}
|
||||
</small>
|
||||
</div>
|
||||
<div class="record-links">
|
||||
<el-button
|
||||
v-for="(diagnosisId, index) in patient.diagnosis_ids"
|
||||
:key="diagnosisId"
|
||||
link
|
||||
type="primary"
|
||||
@click="openPatient(patient, diagnosisId)"
|
||||
>
|
||||
{{ index === 0 ? '查看记录' : `诊单 #${diagnosisId}` }}
|
||||
</el-button>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
<el-empty v-else :description="emptyDescription" :image-size="70" />
|
||||
</template>
|
||||
<footer class="daily-footer">
|
||||
<p>已联系仅依据该医助账号今日已归档的文字记录。电话、外部企微尚未接入。</p>
|
||||
<el-pagination
|
||||
v-if="data?.count"
|
||||
v-model:current-page="page"
|
||||
:total="data.count"
|
||||
:page-size="10"
|
||||
layout="total, prev, pager, next"
|
||||
@current-change="load()"
|
||||
/>
|
||||
</footer>
|
||||
<details v-if="data" class="coverage">
|
||||
<summary>纳入规则与资料范围</summary>
|
||||
<p>{{ data.daily.rule_label }}</p>
|
||||
<p>
|
||||
最近生成 {{ shanghaiTime(data.daily.last_scan_at) }} · 数据截至
|
||||
{{ shanghaiTime(data.daily.as_of) }}
|
||||
</p>
|
||||
<p v-for="source in data.daily.coverage" :key="source.source">{{ source.note }}</p>
|
||||
</details>
|
||||
</section>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { computed, onActivated, onBeforeUnmount, onDeactivated, onMounted, ref, watch } from 'vue'
|
||||
import {
|
||||
assistantStaffDailyContacts,
|
||||
type DailyPatient,
|
||||
type DailyStatus,
|
||||
type Patient,
|
||||
type StaffDailyContacts
|
||||
} from '@/api/assistantService'
|
||||
import { errorText, isCancelled, shanghaiTime } from '../shared'
|
||||
const props = defineProps<{
|
||||
assistantId: number
|
||||
businessDate: string
|
||||
refreshKey: number
|
||||
initialStatus?: DailyStatus
|
||||
entryKey?: number
|
||||
allowed: boolean
|
||||
}>()
|
||||
const emit = defineEmits<{
|
||||
(event: 'open', patient: Patient): void
|
||||
(event: 'date-change', date: string): void
|
||||
(event: 'unavailable'): void
|
||||
}>()
|
||||
const data = ref<StaffDailyContacts | null>(null),
|
||||
error = ref(''),
|
||||
loading = ref(false),
|
||||
page = ref(1),
|
||||
status = ref<DailyStatus>(props.initialStatus || 'pending')
|
||||
const statuses: Array<{ value: DailyStatus; label: string }> = [
|
||||
{ value: 'pending', label: '待维护' },
|
||||
{ value: 'reported', label: '人工登记待核实' },
|
||||
{ value: 'contacted', label: '已联系' },
|
||||
{ value: 'all', label: '全部' },
|
||||
{ value: 'exempt', label: '已豁免' }
|
||||
]
|
||||
const statusLabels = {
|
||||
pending: '待维护',
|
||||
reported: '人工登记待核实',
|
||||
contacted: '有联系记录',
|
||||
exempt: '已豁免'
|
||||
}
|
||||
const emptyDescription = computed(() => {
|
||||
if (error.value) return '名单读取失败,请重试'
|
||||
if (
|
||||
!data.value ||
|
||||
data.value.daily.state !== 'ready' ||
|
||||
data.value.summary.state === 'unavailable'
|
||||
)
|
||||
return '今日计划尚不可确认,请查看资料状态'
|
||||
if (data.value.summary.state === 'no_tasks') return '今日暂无应维护患者'
|
||||
return `当前筛选暂无患者${page.value > 1 ? ',可返回上一页查看' : ''}`
|
||||
})
|
||||
let disposed = false,
|
||||
activated = true,
|
||||
revision = 0
|
||||
let request: AbortController | undefined
|
||||
const visible = () =>
|
||||
activated && (typeof document === 'undefined' || document.visibilityState !== 'hidden')
|
||||
function clear() {
|
||||
revision++
|
||||
request?.abort()
|
||||
data.value = null
|
||||
error.value = ''
|
||||
loading.value = false
|
||||
}
|
||||
async function load(silent = false) {
|
||||
if (disposed || !visible() || !props.allowed || !props.businessDate) return
|
||||
const token = ++revision,
|
||||
assistantId = props.assistantId,
|
||||
businessDate = props.businessDate
|
||||
request?.abort()
|
||||
request = new AbortController()
|
||||
if (!silent) {
|
||||
loading.value = true
|
||||
data.value = null
|
||||
}
|
||||
error.value = ''
|
||||
try {
|
||||
const result = await assistantStaffDailyContacts(
|
||||
{ assistant_id: assistantId, status: status.value, page_no: page.value, page_size: 10 },
|
||||
request.signal
|
||||
)
|
||||
if (disposed || token !== revision || !props.allowed) return
|
||||
if (
|
||||
result.staff.id !== assistantId ||
|
||||
result.daily.timezone !== 'Asia/Shanghai' ||
|
||||
!/^\d{4}-\d{2}-\d{2}$/.test(result.daily.business_date)
|
||||
)
|
||||
throw new Error('名单与当前医助或业务日期不一致,请刷新后重试')
|
||||
if (result.daily.business_date !== businessDate) {
|
||||
data.value = null
|
||||
if (result.daily.business_date > businessDate)
|
||||
emit('date-change', result.daily.business_date)
|
||||
else {
|
||||
error.value = '已忽略旧业务日期的名单,请刷新后重试'
|
||||
emit('unavailable')
|
||||
}
|
||||
return
|
||||
}
|
||||
data.value = result
|
||||
} catch (cause) {
|
||||
if (!disposed && token === revision && !isCancelled(cause)) {
|
||||
data.value = null
|
||||
error.value = errorText(cause)
|
||||
emit('unavailable')
|
||||
}
|
||||
} finally {
|
||||
if (!disposed && token === revision) loading.value = false
|
||||
}
|
||||
}
|
||||
function setStatus(value: DailyStatus) {
|
||||
if (value === status.value) return
|
||||
status.value = value
|
||||
page.value = 1
|
||||
void load()
|
||||
}
|
||||
function openPatient(patient: DailyPatient, diagnosisId: number) {
|
||||
if (
|
||||
!props.allowed ||
|
||||
!data.value?.lists.some(
|
||||
(item) => item.key === patient.key && item.diagnosis_ids.includes(diagnosisId)
|
||||
)
|
||||
)
|
||||
return
|
||||
emit('open', {
|
||||
diagnosis_id: diagnosisId,
|
||||
patient_id: patient.patient_id,
|
||||
patient_name: patient.patient_name,
|
||||
assistant_id: props.assistantId
|
||||
})
|
||||
}
|
||||
watch(
|
||||
() => [props.assistantId, props.businessDate, props.allowed],
|
||||
() => {
|
||||
clear()
|
||||
page.value = 1
|
||||
void load()
|
||||
},
|
||||
{ immediate: true, flush: 'sync' }
|
||||
)
|
||||
watch(
|
||||
() => props.entryKey,
|
||||
() => {
|
||||
status.value = props.initialStatus || 'pending'
|
||||
page.value = 1
|
||||
void load()
|
||||
}
|
||||
)
|
||||
watch(
|
||||
() => props.refreshKey,
|
||||
() => void load(true)
|
||||
)
|
||||
function updateVisibility() {
|
||||
if (!visible()) {
|
||||
revision++
|
||||
request?.abort()
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
onMounted(() => {
|
||||
if (typeof document !== 'undefined')
|
||||
document.addEventListener('visibilitychange', updateVisibility)
|
||||
updateVisibility()
|
||||
})
|
||||
onActivated(() => {
|
||||
activated = true
|
||||
})
|
||||
onDeactivated(() => {
|
||||
activated = false
|
||||
updateVisibility()
|
||||
})
|
||||
onBeforeUnmount(() => {
|
||||
disposed = true
|
||||
clear()
|
||||
if (typeof document !== 'undefined')
|
||||
document.removeEventListener('visibilitychange', updateVisibility)
|
||||
})
|
||||
</script>
|
||||
<style scoped>
|
||||
.daily-heading {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: start;
|
||||
gap: 16px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
h3 {
|
||||
margin: 0;
|
||||
font-size: 17px;
|
||||
font-weight: 600;
|
||||
}
|
||||
h3 span,
|
||||
small,
|
||||
.muted,
|
||||
.daily-heading p,
|
||||
.daily-footer,
|
||||
.coverage {
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
line-height: 1.7;
|
||||
}
|
||||
h3 span {
|
||||
display: block;
|
||||
margin-top: 5px;
|
||||
font-weight: 400;
|
||||
}
|
||||
.daily-heading p {
|
||||
margin: 5px 0 0;
|
||||
}
|
||||
.daily-counts {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 12px 24px;
|
||||
padding: 18px 0;
|
||||
font-size: 13px;
|
||||
}
|
||||
.daily-counts b {
|
||||
margin-left: 6px;
|
||||
font-size: 21px;
|
||||
font-weight: 600;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.status-filter {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 5px;
|
||||
border-bottom: 1px solid var(--el-border-color-light);
|
||||
padding-bottom: 12px;
|
||||
}
|
||||
.status-filter button {
|
||||
border: 0;
|
||||
background: var(--el-fill-color-light);
|
||||
padding: 8px 12px;
|
||||
border-radius: 3px;
|
||||
cursor: pointer;
|
||||
color: var(--el-text-color-regular);
|
||||
transition:
|
||||
background-color 0.18s,
|
||||
color 0.18s;
|
||||
}
|
||||
.status-filter button.active,
|
||||
.status-filter button:hover {
|
||||
background: var(--el-color-primary-light-9);
|
||||
color: var(--el-color-primary);
|
||||
}
|
||||
.status-filter button:focus-visible,
|
||||
summary:focus-visible {
|
||||
outline: 2px solid var(--el-color-primary);
|
||||
outline-offset: 3px;
|
||||
}
|
||||
.patient-list {
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
list-style: none;
|
||||
}
|
||||
.patient-row {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(100px, 0.8fr) minmax(140px, 1.4fr) minmax(130px, 1.2fr) 84px;
|
||||
gap: 20px;
|
||||
padding: 20px 0;
|
||||
border-bottom: 1px solid var(--el-border-color-lighter);
|
||||
font-size: 13px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.patient-row strong {
|
||||
font-weight: 500;
|
||||
}
|
||||
.patient-row small,
|
||||
.record-links .el-button {
|
||||
display: block;
|
||||
margin: 4px 0 0;
|
||||
}
|
||||
.patient-reasons p {
|
||||
margin: 0 0 8px;
|
||||
}
|
||||
.patient-reasons p:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.attention {
|
||||
color: var(--el-color-primary);
|
||||
}
|
||||
.completion-note {
|
||||
background: var(--el-fill-color-light);
|
||||
padding: 12px;
|
||||
font-size: 13px;
|
||||
line-height: 1.7;
|
||||
}
|
||||
.daily-footer {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px;
|
||||
justify-content: space-between;
|
||||
margin-top: 16px;
|
||||
}
|
||||
.daily-footer p {
|
||||
max-width: 48ch;
|
||||
margin: 0;
|
||||
}
|
||||
.coverage {
|
||||
margin-top: 20px;
|
||||
}
|
||||
.coverage summary {
|
||||
cursor: pointer;
|
||||
}
|
||||
@media (max-width: 700px) {
|
||||
.patient-row {
|
||||
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
|
||||
gap: 12px 18px;
|
||||
}
|
||||
.patient-reasons {
|
||||
grid-column: 1;
|
||||
grid-row: 2;
|
||||
}
|
||||
.patient-state {
|
||||
grid-column: 2;
|
||||
grid-row: 1 / span 2;
|
||||
}
|
||||
.record-links {
|
||||
grid-column: 1 / -1;
|
||||
display: flex;
|
||||
gap: 14px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.daily-counts {
|
||||
gap: 10px 18px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,524 @@
|
||||
<template>
|
||||
<div class="job-result">
|
||||
<div class="job-header">
|
||||
<el-tag :type="job.status === 'ready' && !job.stale ? 'success' : 'warning'">{{
|
||||
jobLabels[job.status]
|
||||
}}</el-tag
|
||||
><span
|
||||
>任务 #{{ job.id }} · {{ scenarioLabels[job.scenario] }} ·
|
||||
{{ formatTime(job.created_at) }}</span
|
||||
><el-button link type="primary" :loading="checking" @click="$emit('refresh')"
|
||||
>查询状态</el-button
|
||||
>
|
||||
</div>
|
||||
<el-alert
|
||||
v-if="job.stale || job.status === 'stale'"
|
||||
title="来源、知识或授权范围已变化,此结果仅供历史查看。请刷新来源后重新生成。"
|
||||
type="warning"
|
||||
:closable="false"
|
||||
class="mb-4"
|
||||
/>
|
||||
<el-alert
|
||||
v-if="error || job.error_message"
|
||||
:title="error || job.error_message"
|
||||
type="error"
|
||||
:closable="false"
|
||||
class="mb-4"
|
||||
/>
|
||||
<el-alert
|
||||
v-if="job.status === 'needs_reconciliation'"
|
||||
title="上游调用状态尚未核实,系统不会自动重试。请联系管理员核实后再处理。"
|
||||
type="warning"
|
||||
:closable="false"
|
||||
/>
|
||||
<div
|
||||
v-if="job.status === 'queued' || job.status === 'running'"
|
||||
class="waiting"
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
>
|
||||
{{ job.status === 'queued' ? '任务已提交,等待后台处理。' : '正在根据来源生成结果。'
|
||||
}}{{ error ? '自动查询已暂停,请点击“查询状态”。' : '页面会自动查询进度。' }}
|
||||
</div>
|
||||
<template v-if="analysis">
|
||||
<el-tabs v-model="perspective">
|
||||
<el-tab-pane label="员工服务视角" name="service">
|
||||
<p class="muted">
|
||||
AI 初筛不等于考核结论;说话人或资料不足时不可评价。请逐项查看原文。
|
||||
</p>
|
||||
<article
|
||||
v-for="item in analysis.quality_checks"
|
||||
:key="item.key"
|
||||
class="quality-item"
|
||||
>
|
||||
<div class="quality-heading">
|
||||
<strong>{{ item.label }}</strong
|
||||
><el-tag :type="qualityType(item.status)" size="small">{{
|
||||
qualityLabels[item.status]
|
||||
}}</el-tag
|
||||
><span class="muted">{{
|
||||
item.actor_admin_id
|
||||
? `员工 #${item.actor_admin_id}`
|
||||
: '员工身份未核实'
|
||||
}}</span>
|
||||
</div>
|
||||
<p>{{ item.reason }}</p>
|
||||
<el-button
|
||||
v-if="item.evidence_ids.length"
|
||||
link
|
||||
type="primary"
|
||||
@click="evidence(item.evidence_ids)"
|
||||
>定位原文</el-button
|
||||
>
|
||||
<el-button
|
||||
v-if="permissions.includes('reviewQuality')"
|
||||
link
|
||||
type="primary"
|
||||
:disabled="!actionable"
|
||||
@click="openReview(item)"
|
||||
>人工复核</el-button
|
||||
>
|
||||
<p v-if="latestReview(item.key)" class="review-note">
|
||||
人工复核:{{ decisionLabels[latestReview(item.key)!.decision] }} ·
|
||||
{{ latestReview(item.key)!.note || '无备注' }} ·
|
||||
{{ formatTime(latestReview(item.key)!.created_at) }}
|
||||
</p>
|
||||
</article>
|
||||
</el-tab-pane>
|
||||
<el-tab-pane label="关联患者诉求" name="patient">
|
||||
<section
|
||||
v-for="section in claimSections"
|
||||
:key="section.key"
|
||||
class="claim-section"
|
||||
>
|
||||
<h3>{{ section.label }}</h3>
|
||||
<p v-if="!analysis[section.key].length" class="muted">
|
||||
当前来源暂无可支持的信息
|
||||
</p>
|
||||
<div
|
||||
v-for="(claim, index) in analysis[section.key]"
|
||||
:key="index"
|
||||
class="claim"
|
||||
>
|
||||
<p>{{ claim.text }}</p>
|
||||
<el-button
|
||||
v-if="claim.evidence_ids.length"
|
||||
link
|
||||
type="primary"
|
||||
@click="evidence(claim.evidence_ids)"
|
||||
>查看 {{ claim.evidence_ids.length }} 条依据</el-button
|
||||
>
|
||||
</div>
|
||||
</section>
|
||||
</el-tab-pane>
|
||||
</el-tabs>
|
||||
<section class="suggestions">
|
||||
<h3>建议跟进事项</h3>
|
||||
<p v-if="!analysis.suggested_actions.length" class="muted">暂无有依据的建议事项</p>
|
||||
<div v-for="item in analysis.suggested_actions" :key="item.key" class="claim">
|
||||
<p>{{ item.text }}</p>
|
||||
<div>
|
||||
<el-button link type="primary" @click="evidence(item.evidence_ids)"
|
||||
>查看依据</el-button
|
||||
><el-button
|
||||
v-if="canAdopt"
|
||||
link
|
||||
type="primary"
|
||||
:disabled="!actionable"
|
||||
@click="openAdopt(item)"
|
||||
>{{
|
||||
job.subject_admin_id ? '分配给该医助' : '采纳为我的待办'
|
||||
}}</el-button
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
<template v-if="reply">
|
||||
<el-alert
|
||||
v-if="reply.needs_confirmation || reply.reason"
|
||||
:title="reply.reason || '请人工核对后使用此草稿'"
|
||||
type="warning"
|
||||
:closable="false"
|
||||
class="mb-4"
|
||||
/>
|
||||
<el-input
|
||||
v-model="draft"
|
||||
aria-label="可编辑回复草稿"
|
||||
type="textarea"
|
||||
:rows="9"
|
||||
:maxlength="12000"
|
||||
show-word-limit
|
||||
:disabled="!actionable"
|
||||
/>
|
||||
<div class="draft-tools">
|
||||
<el-button
|
||||
type="primary"
|
||||
:disabled="!actionable || !draft.trim()"
|
||||
@click="copyDraft"
|
||||
>复制草稿</el-button
|
||||
><el-button :disabled="!actionable" @click="draft = reply!.reply"
|
||||
>恢复生成内容</el-button
|
||||
><el-button
|
||||
v-if="reply.evidence_ids.length"
|
||||
link
|
||||
type="primary"
|
||||
@click="evidence(reply.evidence_ids)"
|
||||
>查看患者来源</el-button
|
||||
>
|
||||
</div>
|
||||
<p class="muted">
|
||||
已发布知识依据:<span
|
||||
v-for="(ref, index) in reply.knowledge_refs"
|
||||
:key="`${ref.id}-${ref.version}`"
|
||||
>{{ index ? '、' : '' }}条目 #{{ ref.id }} / v{{ ref.version }}</span
|
||||
>。复制前请核对时效与具体适用条件。
|
||||
</p>
|
||||
</template>
|
||||
<el-dialog
|
||||
v-model="adoptOpened"
|
||||
:title="
|
||||
job.subject_admin_id
|
||||
? `分配跟进给医助 #${job.subject_admin_id}`
|
||||
: '采纳为我的服务待办'
|
||||
"
|
||||
width="min(580px, 94vw)"
|
||||
:close-on-click-modal="false"
|
||||
:show-close="!saving"
|
||||
:close-on-press-escape="!saving"
|
||||
>
|
||||
<el-form label-position="top" :disabled="saving">
|
||||
<el-form-item label="待办内容(最多 500 字)" required
|
||||
><el-input
|
||||
v-model="actionContent"
|
||||
type="textarea"
|
||||
:rows="4"
|
||||
:maxlength="500"
|
||||
show-word-limit
|
||||
/></el-form-item>
|
||||
<el-form-item label="截止时间(本地时间)" required
|
||||
><el-date-picker v-model="dueAt" type="datetime" placeholder="选择截止时间"
|
||||
/></el-form-item>
|
||||
<el-form-item>
|
||||
<el-checkbox v-model="contactRequired"
|
||||
>需要联系患者,计入到期联系任务</el-checkbox
|
||||
>
|
||||
</el-form-item>
|
||||
<p class="muted">
|
||||
{{
|
||||
job.subject_admin_id
|
||||
? `负责人为医助 #${job.subject_admin_id}`
|
||||
: '负责人为当前登录人'
|
||||
}}。采纳后创建关联待办,提醒状态与业务完成状态分别记录。
|
||||
</p>
|
||||
<el-alert
|
||||
v-if="mutationError"
|
||||
:title="mutationError"
|
||||
type="error"
|
||||
:closable="false"
|
||||
/>
|
||||
</el-form>
|
||||
<template #footer
|
||||
><el-button :disabled="saving" @click="adoptOpened = false">取消</el-button
|
||||
><el-button type="primary" :loading="saving" :disabled="!actionable" @click="adopt"
|
||||
>确认采纳</el-button
|
||||
></template
|
||||
>
|
||||
</el-dialog>
|
||||
<el-dialog
|
||||
v-model="reviewOpened"
|
||||
:title="`人工复核 · ${reviewItem?.label || ''}`"
|
||||
width="min(580px, 94vw)"
|
||||
:close-on-click-modal="false"
|
||||
:show-close="!saving"
|
||||
:close-on-press-escape="!saving"
|
||||
>
|
||||
<p>{{ reviewItem?.reason }}</p>
|
||||
<el-button
|
||||
v-if="reviewItem?.evidence_ids.length"
|
||||
link
|
||||
type="primary"
|
||||
@click="evidence(reviewItem.evidence_ids)"
|
||||
>查看原文依据</el-button
|
||||
>
|
||||
<el-form label-position="top" class="mt-4" :disabled="saving"
|
||||
><el-form-item label="复核结论"
|
||||
><el-radio-group v-model="decision"
|
||||
><el-radio value="confirmed">确认判断</el-radio
|
||||
><el-radio value="dismissed">驳回判断</el-radio
|
||||
><el-radio value="not_applicable">不适用</el-radio></el-radio-group
|
||||
></el-form-item
|
||||
><el-form-item label="复核说明" required
|
||||
><el-input
|
||||
v-model="reviewNote"
|
||||
type="textarea"
|
||||
:rows="4"
|
||||
:maxlength="1000"
|
||||
show-word-limit /></el-form-item
|
||||
></el-form>
|
||||
<el-alert v-if="mutationError" :title="mutationError" type="error" :closable="false" />
|
||||
<template #footer
|
||||
><el-button :disabled="saving" @click="reviewOpened = false">取消</el-button
|
||||
><el-button type="primary" :loading="saving" :disabled="!actionable" @click="review"
|
||||
>保存复核</el-button
|
||||
></template
|
||||
>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, ref, watch } from 'vue'
|
||||
import useClipboard from 'vue-clipboard3'
|
||||
import {
|
||||
assistantAdoptAction,
|
||||
assistantReviewQuality,
|
||||
type AnalysisResult,
|
||||
type Job,
|
||||
type Permission,
|
||||
type QualityCheck,
|
||||
type ReplyResult,
|
||||
type ReviewDecision,
|
||||
type Source,
|
||||
type SuggestedAction
|
||||
} from '@/api/assistantService'
|
||||
import feedback from '@/utils/feedback'
|
||||
import useUserStore from '@/stores/modules/user'
|
||||
import { errorText, formatTime, jobLabels } from '../shared'
|
||||
const props = defineProps<{
|
||||
job: Job
|
||||
permissions: Permission[]
|
||||
checking: boolean
|
||||
error: string
|
||||
disabled: boolean
|
||||
}>()
|
||||
const emit = defineEmits<{
|
||||
(event: 'refresh'): void
|
||||
(event: 'adopted'): void
|
||||
(event: 'evidence', sources: Source[]): void
|
||||
}>()
|
||||
const analysis = computed(() =>
|
||||
props.job.type === 'analysis' ? (props.job.result as AnalysisResult | null) : null
|
||||
)
|
||||
const reply = computed(() =>
|
||||
props.job.type === 'reply' ? (props.job.result as ReplyResult | null) : null
|
||||
)
|
||||
const actionable = computed(
|
||||
() =>
|
||||
!props.disabled &&
|
||||
!props.checking &&
|
||||
!props.error &&
|
||||
props.job.status === 'ready' &&
|
||||
!props.job.stale
|
||||
)
|
||||
const user = useUserStore()
|
||||
const canAdopt = computed(
|
||||
() =>
|
||||
props.permissions.includes('adoptAction') &&
|
||||
(!props.job.subject_admin_id ||
|
||||
props.job.subject_admin_id ===
|
||||
Number(user.userInfo.id || user.userInfo.admin_id || 0) ||
|
||||
props.permissions.includes('reviewQuality'))
|
||||
)
|
||||
const perspective = ref('service'),
|
||||
draft = ref('')
|
||||
const scenarioLabels = { initial: '初次服务', followup: '日常随访', revisit: '复诊服务' }
|
||||
const qualityLabels = {
|
||||
met: '已覆盖',
|
||||
missed: '疑似遗漏',
|
||||
not_applicable: '不适用',
|
||||
insufficient: '证据不足'
|
||||
}
|
||||
const decisionLabels = { confirmed: '已确认', dismissed: '已驳回', not_applicable: '不适用' }
|
||||
const claimSections = [
|
||||
{ key: 'summary', label: '沟通摘要' },
|
||||
{ key: 'needs', label: '患者诉求' },
|
||||
{ key: 'unresolved', label: '待解决问题' },
|
||||
{ key: 'tags', label: '服务标签候选(仅作参考)' }
|
||||
] as const
|
||||
const qualityType = (status: QualityCheck['status']) =>
|
||||
status === 'met' ? 'success' : status === 'missed' ? 'warning' : 'info'
|
||||
function latestReview(key: string) {
|
||||
return [...props.job.reviews].reverse().find((item) => item.item_key === key)
|
||||
}
|
||||
function evidence(ids: string[]) {
|
||||
const sources = ids
|
||||
.map((id) => props.job.sources.find((source) => source.id === id))
|
||||
.filter((source): source is Source => !!source)
|
||||
if (!sources.length) {
|
||||
feedback.msgWarning('此任务未返回可定位的原文,请刷新任务状态')
|
||||
return
|
||||
}
|
||||
emit('evidence', sources)
|
||||
}
|
||||
watch(
|
||||
[() => props.job.id, () => reply.value?.reply],
|
||||
() => {
|
||||
draft.value = reply.value?.reply || ''
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
const { toClipboard } = useClipboard()
|
||||
async function copyDraft() {
|
||||
if (!actionable.value) return
|
||||
try {
|
||||
await toClipboard(draft.value)
|
||||
feedback.msgSuccess('草稿已复制,请核对后使用')
|
||||
} catch {
|
||||
feedback.msgError('复制失败,请选中文本后手动复制')
|
||||
}
|
||||
}
|
||||
const adoptOpened = ref(false),
|
||||
reviewOpened = ref(false),
|
||||
saving = ref(false),
|
||||
mutationError = ref('')
|
||||
const actionItem = ref<SuggestedAction | null>(null),
|
||||
actionContent = ref(''),
|
||||
contactRequired = ref(false),
|
||||
dueAt = ref<Date | null>(null)
|
||||
const reviewItem = ref<QualityCheck | null>(null),
|
||||
decision = ref<ReviewDecision>('confirmed'),
|
||||
reviewNote = ref('')
|
||||
let disposed = false
|
||||
function openAdopt(item: SuggestedAction) {
|
||||
actionItem.value = item
|
||||
actionContent.value = item.text
|
||||
dueAt.value = null
|
||||
contactRequired.value = false
|
||||
mutationError.value = ''
|
||||
adoptOpened.value = true
|
||||
}
|
||||
function openReview(item: QualityCheck) {
|
||||
reviewItem.value = item
|
||||
decision.value = 'confirmed'
|
||||
reviewNote.value = ''
|
||||
mutationError.value = ''
|
||||
reviewOpened.value = true
|
||||
}
|
||||
async function adopt() {
|
||||
if (saving.value || !actionable.value || !canAdopt.value || !actionItem.value) return
|
||||
if (!actionContent.value.trim() || !dueAt.value || dueAt.value.getTime() <= Date.now()) {
|
||||
mutationError.value = '请填写待办内容,并选择未来的截止时间'
|
||||
return
|
||||
}
|
||||
if (Array.from(actionContent.value.trim()).length > 500) {
|
||||
mutationError.value = '待办内容不能超过 500 字,请核对后精简'
|
||||
return
|
||||
}
|
||||
saving.value = true
|
||||
mutationError.value = ''
|
||||
try {
|
||||
await assistantAdoptAction({
|
||||
job_id: props.job.id,
|
||||
version: props.job.version,
|
||||
action_key: actionItem.value.key,
|
||||
content: actionContent.value.trim(),
|
||||
contact_required: contactRequired.value,
|
||||
due_at: Math.floor(dueAt.value.getTime() / 1000)
|
||||
})
|
||||
if (disposed) return
|
||||
adoptOpened.value = false
|
||||
feedback.msgSuccess(props.job.subject_admin_id ? '已分配给该医助' : '已采纳为我的待办')
|
||||
emit('adopted')
|
||||
} catch (cause) {
|
||||
if (!disposed) {
|
||||
mutationError.value = errorText(cause)
|
||||
emit('refresh')
|
||||
}
|
||||
} finally {
|
||||
if (!disposed) saving.value = false
|
||||
}
|
||||
}
|
||||
async function review() {
|
||||
if (saving.value || !actionable.value || !reviewItem.value) return
|
||||
if (!reviewNote.value.trim()) {
|
||||
mutationError.value = '请填写复核说明'
|
||||
return
|
||||
}
|
||||
saving.value = true
|
||||
mutationError.value = ''
|
||||
try {
|
||||
await assistantReviewQuality({
|
||||
job_id: props.job.id,
|
||||
version: props.job.version,
|
||||
item_key: reviewItem.value.key,
|
||||
decision: decision.value,
|
||||
note: reviewNote.value.trim()
|
||||
})
|
||||
if (disposed) return
|
||||
reviewOpened.value = false
|
||||
feedback.msgSuccess('复核已保存')
|
||||
emit('refresh')
|
||||
} catch (cause) {
|
||||
if (!disposed) {
|
||||
mutationError.value = `${errorText(cause)}。请刷新查看已有复核后再提交。`
|
||||
emit('refresh')
|
||||
}
|
||||
} finally {
|
||||
if (!disposed) saving.value = false
|
||||
}
|
||||
}
|
||||
onBeforeUnmount(() => {
|
||||
disposed = true
|
||||
})
|
||||
</script>
|
||||
<style scoped>
|
||||
.job-header,
|
||||
.quality-heading,
|
||||
.draft-tools {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.job-header {
|
||||
font-size: 12px;
|
||||
margin-bottom: 16px;
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
.claim-section {
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
h3 {
|
||||
margin: 0 0 8px;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.claim,
|
||||
.quality-item {
|
||||
padding: 12px 0;
|
||||
border-bottom: 1px solid var(--el-border-color-lighter);
|
||||
}
|
||||
.claim p,
|
||||
.quality-item p {
|
||||
margin: 0 0 7px;
|
||||
line-height: 1.7;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.quality-heading {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.quality-item .review-note {
|
||||
margin-top: 8px;
|
||||
color: var(--el-color-primary);
|
||||
font-size: 12px;
|
||||
}
|
||||
.suggestions {
|
||||
margin-top: 20px;
|
||||
padding: 16px;
|
||||
background: var(--el-fill-color-light);
|
||||
border-radius: 4px;
|
||||
}
|
||||
.muted,
|
||||
.waiting {
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: 13px;
|
||||
line-height: 1.7;
|
||||
}
|
||||
.waiting {
|
||||
padding: 28px 0;
|
||||
}
|
||||
.draft-tools {
|
||||
margin-top: 14px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,145 @@
|
||||
<template>
|
||||
<el-card shadow="never" class="patient-picker">
|
||||
<template #header
|
||||
><strong>授权患者</strong><span class="count">{{ total }} 位</span></template
|
||||
>
|
||||
<el-input
|
||||
v-model="keyword"
|
||||
clearable
|
||||
placeholder="搜索患者姓名 / 手机号"
|
||||
aria-label="搜索授权患者"
|
||||
@keyup.enter="search"
|
||||
@clear="search"
|
||||
>
|
||||
<template #append
|
||||
><el-button :loading="loading" @click="search">搜索</el-button></template
|
||||
>
|
||||
</el-input>
|
||||
<el-alert
|
||||
v-if="error"
|
||||
class="mt-3"
|
||||
:title="error"
|
||||
type="error"
|
||||
:closable="false"
|
||||
show-icon
|
||||
/>
|
||||
<el-button v-if="error" link type="primary" @click="load">重新加载</el-button>
|
||||
<div v-loading="loading" class="patient-list">
|
||||
<button
|
||||
v-for="patient in rows"
|
||||
:key="patient.diagnosis_id"
|
||||
type="button"
|
||||
class="patient-row"
|
||||
:class="{ selected: selectedId === patient.diagnosis_id }"
|
||||
:aria-pressed="selectedId === patient.diagnosis_id"
|
||||
@click="$emit('select', patient)"
|
||||
>
|
||||
<strong>{{ patient.patient_name || '未命名患者' }}</strong>
|
||||
<span>{{ patient.phone_masked || '未提供手机号' }}</span>
|
||||
<small>诊单 #{{ patient.diagnosis_id }}</small>
|
||||
</button>
|
||||
<el-empty
|
||||
v-if="!loading && !rows.length && !error"
|
||||
description="当前范围内暂无匹配患者"
|
||||
:image-size="70"
|
||||
/>
|
||||
</div>
|
||||
<el-pagination
|
||||
v-if="total"
|
||||
v-model:current-page="page"
|
||||
small
|
||||
layout="prev, pager, next"
|
||||
:pager-count="5"
|
||||
:total="total"
|
||||
:page-size="10"
|
||||
@current-change="load"
|
||||
/>
|
||||
</el-card>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, onMounted, ref } from 'vue'
|
||||
import { assistantPatients, type Patient } from '@/api/assistantService'
|
||||
import { errorText, isCancelled } from '../shared'
|
||||
defineProps<{ selectedId: number }>()
|
||||
defineEmits<{ (event: 'select', patient: Patient): void }>()
|
||||
const keyword = ref(''),
|
||||
page = ref(1),
|
||||
total = ref(0),
|
||||
rows = ref<Patient[]>([]),
|
||||
loading = ref(false),
|
||||
error = ref('')
|
||||
let revision = 0,
|
||||
request: AbortController | undefined
|
||||
async function load() {
|
||||
const token = ++revision
|
||||
request?.abort()
|
||||
request = new AbortController()
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const data = await assistantPatients(
|
||||
{ keyword: keyword.value.trim(), page_no: page.value, page_size: 10 },
|
||||
request.signal
|
||||
)
|
||||
if (token !== revision) return
|
||||
rows.value = data.lists
|
||||
total.value = data.count
|
||||
} catch (cause) {
|
||||
if (token !== revision || isCancelled(cause)) return
|
||||
rows.value = []
|
||||
total.value = 0
|
||||
error.value = errorText(cause)
|
||||
} finally {
|
||||
if (token === revision) loading.value = false
|
||||
}
|
||||
}
|
||||
function search() {
|
||||
page.value = 1
|
||||
void load()
|
||||
}
|
||||
onMounted(load)
|
||||
onBeforeUnmount(() => {
|
||||
revision++
|
||||
request?.abort()
|
||||
})
|
||||
</script>
|
||||
<style scoped>
|
||||
.patient-picker {
|
||||
height: fit-content;
|
||||
min-width: 0;
|
||||
}
|
||||
.count {
|
||||
float: right;
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: 13px;
|
||||
}
|
||||
.patient-list {
|
||||
min-height: 180px;
|
||||
margin: 14px -8px;
|
||||
}
|
||||
.patient-row {
|
||||
width: 100%;
|
||||
text-align: left;
|
||||
display: grid;
|
||||
gap: 5px;
|
||||
padding: 12px;
|
||||
background: transparent;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 5px;
|
||||
cursor: pointer;
|
||||
color: var(--el-text-color-primary);
|
||||
}
|
||||
.patient-row + .patient-row {
|
||||
border-top-color: var(--el-border-color-lighter);
|
||||
}
|
||||
.patient-row:hover,
|
||||
.patient-row.selected {
|
||||
background: var(--el-color-primary-light-9);
|
||||
border-color: var(--el-color-primary-light-7);
|
||||
}
|
||||
.patient-row span,
|
||||
.patient-row small {
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: 12px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,118 @@
|
||||
<template>
|
||||
<el-dialog
|
||||
v-model="opened"
|
||||
title="录入服务记录"
|
||||
width="min(640px, 94vw)"
|
||||
:close-on-click-modal="false"
|
||||
:close-on-press-escape="!saving"
|
||||
:show-close="!saving"
|
||||
>
|
||||
<el-alert
|
||||
title="记录将作为本患者的服务分析来源,请核对时间与说话人。"
|
||||
type="info"
|
||||
:closable="false"
|
||||
class="mb-4"
|
||||
/>
|
||||
<el-form label-position="top" :disabled="saving" @submit.prevent="save">
|
||||
<el-form-item label="记录类型"
|
||||
><el-radio-group v-model="form.record_type"
|
||||
><el-radio value="service_note">人工服务记录</el-radio
|
||||
><el-radio value="verified_transcript">已核对转写</el-radio></el-radio-group
|
||||
></el-form-item
|
||||
>
|
||||
<el-form-item label="实际发生时间(本地时间)" required
|
||||
><el-date-picker
|
||||
v-model="occurredAt"
|
||||
type="datetime"
|
||||
placeholder="选择发生时间"
|
||||
:disabled-date="futureDate"
|
||||
/></el-form-item>
|
||||
<el-form-item label="服务内容" required
|
||||
><el-input
|
||||
v-model="form.content"
|
||||
type="textarea"
|
||||
:rows="8"
|
||||
:maxlength="maxChars"
|
||||
show-word-limit
|
||||
placeholder="记录服务诉求、已沟通事项和后续约定;转写请逐段标明实际说话人。"
|
||||
/></el-form-item>
|
||||
<el-checkbox
|
||||
v-if="form.record_type === 'verified_transcript'"
|
||||
v-model="form.speaker_confirmed"
|
||||
>我已对照原始材料核对文字、患者身份与说话人</el-checkbox
|
||||
>
|
||||
<p
|
||||
v-if="form.record_type === 'verified_transcript'"
|
||||
class="text-xs text-tx-secondary mt-2"
|
||||
>
|
||||
上传者不会自动认定为原对话的服务员工;此记录仅表示素材已核对,不直接用于员工评分。
|
||||
</p>
|
||||
<el-alert v-if="error" :title="error" type="error" :closable="false" class="mt-4" />
|
||||
</el-form>
|
||||
<template #footer
|
||||
><el-button :disabled="saving" @click="opened = false">取消</el-button
|
||||
><el-button type="primary" :loading="saving" @click="save"
|
||||
>保存记录</el-button
|
||||
></template
|
||||
>
|
||||
</el-dialog>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { reactive, ref, onBeforeUnmount } from 'vue'
|
||||
import { assistantRecord } from '@/api/assistantService'
|
||||
import feedback from '@/utils/feedback'
|
||||
import { errorText } from '../shared'
|
||||
const props = defineProps<{ diagnosisId: number; maxChars: number }>()
|
||||
const emit = defineEmits<{ (event: 'saved'): void }>()
|
||||
const opened = defineModel<boolean>({ default: false })
|
||||
const form = reactive({
|
||||
record_type: 'service_note' as 'service_note' | 'verified_transcript',
|
||||
content: '',
|
||||
speaker_confirmed: false
|
||||
})
|
||||
const occurredAt = ref<Date | null>(new Date()),
|
||||
saving = ref(false),
|
||||
error = ref('')
|
||||
let disposed = false
|
||||
const futureDate = (date: Date) => date.getTime() > Date.now()
|
||||
async function save() {
|
||||
if (saving.value) return
|
||||
error.value = ''
|
||||
if (!form.content.trim() || !occurredAt.value) {
|
||||
error.value = '请填写内容和实际发生时间'
|
||||
return
|
||||
}
|
||||
if (occurredAt.value.getTime() > Date.now()) {
|
||||
error.value = '发生时间不能晚于现在'
|
||||
return
|
||||
}
|
||||
if (form.record_type === 'verified_transcript' && !form.speaker_confirmed) {
|
||||
error.value = '请先核对并确认转写内容与说话人'
|
||||
return
|
||||
}
|
||||
saving.value = true
|
||||
try {
|
||||
await assistantRecord({
|
||||
...form,
|
||||
content: form.content.trim(),
|
||||
diagnosis_id: props.diagnosisId,
|
||||
occurred_at: Math.floor(occurredAt.value.getTime() / 1000),
|
||||
speaker_confirmed: form.record_type === 'verified_transcript' && form.speaker_confirmed
|
||||
})
|
||||
if (disposed) return
|
||||
feedback.msgSuccess('服务记录已保存')
|
||||
opened.value = false
|
||||
form.content = ''
|
||||
form.speaker_confirmed = false
|
||||
emit('saved')
|
||||
} catch (cause) {
|
||||
if (!disposed)
|
||||
error.value = `${errorText(cause)}。若连接中断,请先关闭弹窗刷新来源,确认是否已保存,避免重复录入。`
|
||||
} finally {
|
||||
if (!disposed) saving.value = false
|
||||
}
|
||||
}
|
||||
onBeforeUnmount(() => {
|
||||
disposed = true
|
||||
})
|
||||
</script>
|
||||
@@ -0,0 +1,283 @@
|
||||
<template>
|
||||
<div>
|
||||
<div class="actions-toolbar">
|
||||
<el-select
|
||||
v-model="state"
|
||||
clearable
|
||||
placeholder="全部执行状态"
|
||||
style="width: 180px"
|
||||
@change="search"
|
||||
><el-option
|
||||
v-for="(label, value) in labels"
|
||||
:key="value"
|
||||
:label="label"
|
||||
:value="value" /></el-select
|
||||
><el-button :loading="loading" @click="load">刷新待办</el-button>
|
||||
</div>
|
||||
<el-alert v-if="error" :title="error" type="error" :closable="false" class="mb-4" />
|
||||
<el-table v-loading="loading" :data="rows" empty-text="当前范围内暂无服务待办">
|
||||
<el-table-column v-if="!diagnosisId" label="关联患者 / 诊单" min-width="150">
|
||||
<template #default="{ row }"
|
||||
>{{ row.patient_name || '未命名患者'
|
||||
}}<small>诊单 #{{ row.diagnosis_id }}</small></template
|
||||
>
|
||||
</el-table-column>
|
||||
<el-table-column label="待办事项" min-width="230"
|
||||
><template #default="{ row }"
|
||||
><div class="action-text">{{ row.content }}</div>
|
||||
<small v-if="row.contact_required">需联系患者 · 纳入到期联系任务</small>
|
||||
<small v-if="row.completion_note"
|
||||
>执行备注:{{ row.completion_note }}</small
|
||||
></template
|
||||
></el-table-column
|
||||
>
|
||||
<el-table-column label="截止 / 完成时间" min-width="175"
|
||||
><template #default="{ row }"
|
||||
><span :class="{ overdue: isOverdue(row) }">{{ formatTime(row.due_at) }}</span
|
||||
><small v-if="row.completed_at"
|
||||
>完成:{{ formatTime(row.completed_at) }}</small
|
||||
></template
|
||||
></el-table-column
|
||||
>
|
||||
<el-table-column label="业务状态" width="110"
|
||||
><template #default="{ row }"
|
||||
><el-tag :type="row.business_state === 'completed' ? 'success' : 'info'">{{
|
||||
labels[row.business_state as BusinessState]
|
||||
}}</el-tag></template
|
||||
></el-table-column
|
||||
>
|
||||
<el-table-column label="提醒状态" width="115"
|
||||
><template #default="{ row }">{{
|
||||
notificationLabel(row.notification_status)
|
||||
}}</template></el-table-column
|
||||
>
|
||||
<el-table-column label="负责人" width="95"
|
||||
><template #default="{ row }">#{{ row.assignee_id }}</template></el-table-column
|
||||
>
|
||||
<el-table-column v-if="canComplete" label="操作" width="105" fixed="right"
|
||||
><template #default="{ row }"
|
||||
><el-button v-if="canUpdate(row)" link type="primary" @click="edit(row)"
|
||||
>更新执行</el-button
|
||||
><span v-else class="muted">—</span></template
|
||||
></el-table-column
|
||||
>
|
||||
</el-table>
|
||||
<el-pagination
|
||||
v-if="total"
|
||||
class="mt-4"
|
||||
v-model:current-page="page"
|
||||
:total="total"
|
||||
:page-size="10"
|
||||
layout="total, prev, pager, next"
|
||||
@current-change="load"
|
||||
/>
|
||||
<el-dialog
|
||||
v-model="opened"
|
||||
title="更新服务待办"
|
||||
width="min(560px, 94vw)"
|
||||
:close-on-click-modal="false"
|
||||
:close-on-press-escape="!saving"
|
||||
:show-close="!saving"
|
||||
>
|
||||
<p class="action-text">{{ selected?.content }}</p>
|
||||
<el-form label-position="top"
|
||||
><el-form-item label="执行状态"
|
||||
><el-radio-group v-model="nextState"
|
||||
><el-radio value="in_progress">进行中</el-radio
|
||||
><el-radio value="completed">已完成</el-radio
|
||||
><el-radio value="cancelled">已取消</el-radio></el-radio-group
|
||||
></el-form-item
|
||||
><el-form-item
|
||||
:label="
|
||||
nextState === 'in_progress' ? '执行备注' : '完成结果 / 取消原因(必填)'
|
||||
"
|
||||
><el-input
|
||||
v-model="note"
|
||||
type="textarea"
|
||||
:rows="4"
|
||||
:maxlength="1000"
|
||||
show-word-limit /></el-form-item
|
||||
></el-form>
|
||||
<el-alert v-if="mutationError" :title="mutationError" type="error" :closable="false" />
|
||||
<template #footer
|
||||
><el-button :disabled="saving" @click="opened = false">取消</el-button
|
||||
><el-button type="primary" :loading="saving" @click="save"
|
||||
>保存执行状态</el-button
|
||||
></template
|
||||
>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, ref, watch } from 'vue'
|
||||
import {
|
||||
assistantActions,
|
||||
assistantCompleteAction,
|
||||
type BusinessState,
|
||||
type ServiceAction
|
||||
} from '@/api/assistantService'
|
||||
import feedback from '@/utils/feedback'
|
||||
import { errorText, formatTime, isCancelled } from '../shared'
|
||||
const props = defineProps<{
|
||||
diagnosisId?: number
|
||||
assistantId?: number
|
||||
actorId: number
|
||||
canComplete: boolean
|
||||
canReview: boolean
|
||||
refreshKey: number
|
||||
}>()
|
||||
const emit = defineEmits<{ (event: 'changed'): void }>()
|
||||
const rows = ref<ServiceAction[]>([]),
|
||||
total = ref(0),
|
||||
page = ref(1),
|
||||
state = ref<BusinessState | ''>(''),
|
||||
loading = ref(false),
|
||||
error = ref('')
|
||||
const labels: Record<BusinessState, string> = {
|
||||
pending: '待执行',
|
||||
in_progress: '进行中',
|
||||
completed: '已完成',
|
||||
cancelled: '已取消'
|
||||
}
|
||||
let revision = 0,
|
||||
disposed = false,
|
||||
request: AbortController | undefined
|
||||
const terminal = (row: ServiceAction) =>
|
||||
row.business_state === 'completed' || row.business_state === 'cancelled'
|
||||
const canUpdate = (row: ServiceAction) =>
|
||||
props.canComplete && !terminal(row) && (props.canReview || row.assignee_id === props.actorId)
|
||||
const isOverdue = (row: ServiceAction) => !terminal(row) && row.due_at * 1000 < Date.now()
|
||||
const notificationLabels: Record<string, string> = {
|
||||
'0': '待发送',
|
||||
'1': '已发送',
|
||||
'2': '已取消',
|
||||
'3': '发送失败',
|
||||
pending: '待发送',
|
||||
sent: '已发送',
|
||||
cancelled: '已取消',
|
||||
failed: '发送失败'
|
||||
}
|
||||
const notificationLabel = (value: string | number | null) =>
|
||||
notificationLabels[String(value)] || String(value ?? '未安排')
|
||||
async function load(silent: unknown = false) {
|
||||
const token = ++revision
|
||||
request?.abort()
|
||||
request = new AbortController()
|
||||
if (silent !== true) loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const data = await assistantActions(
|
||||
{
|
||||
...(props.diagnosisId ? { diagnosis_id: props.diagnosisId } : {}),
|
||||
...(props.assistantId ? { assistant_id: props.assistantId } : {}),
|
||||
page_no: page.value,
|
||||
page_size: 10,
|
||||
...(state.value ? { state: state.value } : {})
|
||||
},
|
||||
request.signal
|
||||
)
|
||||
if (token !== revision || disposed) return
|
||||
rows.value = data.lists
|
||||
total.value = data.count
|
||||
if (selected.value) {
|
||||
const current = data.lists.find((row) => row.id === selected.value?.id)
|
||||
if (current) selected.value = current
|
||||
}
|
||||
} catch (cause) {
|
||||
if (token === revision && !disposed && !isCancelled(cause)) {
|
||||
error.value = errorText(cause)
|
||||
rows.value = []
|
||||
total.value = 0
|
||||
}
|
||||
} finally {
|
||||
if (token === revision && !disposed) loading.value = false
|
||||
}
|
||||
}
|
||||
function search() {
|
||||
page.value = 1
|
||||
rows.value = []
|
||||
total.value = 0
|
||||
opened.value = false
|
||||
selected.value = null
|
||||
void load()
|
||||
}
|
||||
const opened = ref(false),
|
||||
selected = ref<ServiceAction | null>(null),
|
||||
nextState = ref<Exclude<BusinessState, 'pending'>>('in_progress'),
|
||||
note = ref(''),
|
||||
mutationError = ref(''),
|
||||
saving = ref(false)
|
||||
function edit(row: ServiceAction) {
|
||||
selected.value = row
|
||||
nextState.value = 'in_progress'
|
||||
note.value = ''
|
||||
mutationError.value = ''
|
||||
opened.value = true
|
||||
}
|
||||
async function save() {
|
||||
if (saving.value || !selected.value || !canUpdate(selected.value)) return
|
||||
if (nextState.value !== 'in_progress' && !note.value.trim()) {
|
||||
mutationError.value = '完成或取消必须填写执行结果 / 原因'
|
||||
return
|
||||
}
|
||||
saving.value = true
|
||||
const scope = `${props.assistantId || 0}:${props.diagnosisId || 0}`
|
||||
mutationError.value = ''
|
||||
try {
|
||||
await assistantCompleteAction({
|
||||
id: selected.value.id,
|
||||
state: nextState.value,
|
||||
note: note.value.trim()
|
||||
})
|
||||
if (disposed || scope !== `${props.assistantId || 0}:${props.diagnosisId || 0}`) return
|
||||
feedback.msgSuccess('执行状态已更新')
|
||||
opened.value = false
|
||||
emit('changed')
|
||||
await load()
|
||||
} catch (cause) {
|
||||
if (!disposed && scope === `${props.assistantId || 0}:${props.diagnosisId || 0}`) {
|
||||
mutationError.value = `${errorText(cause)}。请刷新待办确认当前状态。`
|
||||
void load()
|
||||
}
|
||||
} finally {
|
||||
if (!disposed) saving.value = false
|
||||
}
|
||||
}
|
||||
watch(() => [props.diagnosisId, props.assistantId], search, {
|
||||
immediate: true,
|
||||
flush: 'sync'
|
||||
})
|
||||
watch(
|
||||
() => props.refreshKey,
|
||||
() => void load(true)
|
||||
)
|
||||
onBeforeUnmount(() => {
|
||||
disposed = true
|
||||
revision++
|
||||
request?.abort()
|
||||
})
|
||||
</script>
|
||||
<style scoped>
|
||||
.actions-toolbar {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
margin-bottom: 16px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.action-text {
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
line-height: 1.6;
|
||||
}
|
||||
small {
|
||||
display: block;
|
||||
color: var(--el-text-color-secondary);
|
||||
margin-top: 6px;
|
||||
}
|
||||
.overdue {
|
||||
color: var(--el-color-danger);
|
||||
}
|
||||
.muted {
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,104 @@
|
||||
<template>
|
||||
<div>
|
||||
<div class="coverage">
|
||||
<div v-for="item in coverage" :key="item.channel" class="coverage-item">
|
||||
<strong>{{ channelLabel(item.channel) }}</strong>
|
||||
<span>{{ coverageStatus(item.status) }} · {{ item.count }} 条</span>
|
||||
<small>{{ item.note }}</small>
|
||||
</div>
|
||||
</div>
|
||||
<el-empty
|
||||
v-if="!sources.length"
|
||||
description="此时间范围内暂无可用来源,可录入服务记录或调整范围"
|
||||
:image-size="80"
|
||||
/>
|
||||
<div v-else class="timeline" aria-label="患者沟通来源">
|
||||
<article v-for="source in ordered" :key="source.id" class="source">
|
||||
<div class="source-meta">
|
||||
<strong>{{ channelLabel(source.channel) }}</strong
|
||||
><span>{{ formatTime(source.occurred_at) }}</span
|
||||
><el-tag size="small" type="info">{{ speakerLabels[source.speaker] }}</el-tag>
|
||||
</div>
|
||||
<p>{{ source.text }}</p>
|
||||
<small
|
||||
>{{ source.id
|
||||
}}<span v-if="source.actor_admin_id"> · 员工 #{{ source.actor_admin_id }}</span>
|
||||
·
|
||||
{{
|
||||
source.quality_eligible
|
||||
? '可作为质检素材,仍需人工核对'
|
||||
: '仅作上下文,不据此评价员工'
|
||||
}}</small
|
||||
>
|
||||
</article>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import type { Coverage, Source } from '@/api/assistantService'
|
||||
import { channelLabel, formatTime } from '../shared'
|
||||
const props = defineProps<{ sources: Source[]; coverage: Coverage[] }>()
|
||||
const ordered = computed(() => [...props.sources].sort((a, b) => b.occurred_at - a.occurred_at))
|
||||
const speakerLabels = { patient: '患者', service: '服务员工', unknown: '说话人未核实' }
|
||||
const coverageLabels: Record<string, string> = {
|
||||
available: '已覆盖',
|
||||
ready: '已覆盖',
|
||||
partial: '部分覆盖',
|
||||
empty: '暂无记录',
|
||||
not_connected: '尚未接入',
|
||||
not_integrated: '尚未接入',
|
||||
unavailable: '暂不可用',
|
||||
unsupported: '尚未接入',
|
||||
truncated: '超出范围'
|
||||
}
|
||||
function coverageStatus(status: string) {
|
||||
return coverageLabels[status] || status
|
||||
}
|
||||
</script>
|
||||
<style scoped>
|
||||
.coverage {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
|
||||
gap: 10px;
|
||||
margin-bottom: 18px;
|
||||
}
|
||||
.coverage-item {
|
||||
display: grid;
|
||||
gap: 5px;
|
||||
background: var(--el-fill-color-light);
|
||||
border-radius: 4px;
|
||||
padding: 12px;
|
||||
font-size: 13px;
|
||||
}
|
||||
.coverage-item small,
|
||||
.source small {
|
||||
color: var(--el-text-color-secondary);
|
||||
line-height: 1.6;
|
||||
}
|
||||
.timeline {
|
||||
max-height: 520px;
|
||||
overflow: auto;
|
||||
padding-right: 8px;
|
||||
}
|
||||
.source {
|
||||
padding: 16px 0;
|
||||
border-bottom: 1px solid var(--el-border-color-lighter);
|
||||
}
|
||||
.source-meta {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px;
|
||||
align-items: center;
|
||||
font-size: 12px;
|
||||
}
|
||||
.source-meta span {
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
.source p {
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
line-height: 1.7;
|
||||
margin: 9px 0;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,628 @@
|
||||
<template>
|
||||
<section class="staff-detail">
|
||||
<template v-if="can('view')">
|
||||
<div v-show="!detail">
|
||||
<div class="detail-heading">
|
||||
<div>
|
||||
<h2>{{ staff.name }}</h2>
|
||||
<p>今日维护与近 30 天服务质检</p>
|
||||
</div>
|
||||
<el-button :loading="overviewLoading" @click="refresh">刷新详情</el-button>
|
||||
</div>
|
||||
<div v-if="overview && activeTab !== 'daily'" class="detail-metrics">
|
||||
<div>
|
||||
<span>沟通发言</span
|
||||
><strong>{{ overview.metrics.im_messages ?? '未接入' }}</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span>已分析诊单</span
|
||||
><strong>{{ overview.metrics.analyzed_cases }}</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span>待跟进</span><strong>{{ overview.metrics.pending_actions }}</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span>已逾期</span
|
||||
><strong :class="{ attention: overview.metrics.overdue_actions > 0 }">{{
|
||||
overview.metrics.overdue_actions
|
||||
}}</strong>
|
||||
</div>
|
||||
</div>
|
||||
<el-tabs v-model="activeTab" class="detail-tabs">
|
||||
<el-tab-pane label="今日维护" name="daily">
|
||||
<DailyContacts
|
||||
:assistant-id="staff.id"
|
||||
:business-date="businessDate || ''"
|
||||
:refresh-key="dailyRefresh"
|
||||
:initial-status="initialStatus"
|
||||
:entry-key="entryKey"
|
||||
:allowed="can('view')"
|
||||
@open="openDaily"
|
||||
@date-change="emit('date-change', $event)"
|
||||
@unavailable="dailyUnavailable"
|
||||
/>
|
||||
</el-tab-pane>
|
||||
<el-tab-pane label="服务质检 · 30 天" name="issues">
|
||||
<el-alert
|
||||
v-if="overviewError"
|
||||
:title="overviewError"
|
||||
type="error"
|
||||
:closable="false"
|
||||
class="mb-4"
|
||||
/>
|
||||
<p class="section-note">
|
||||
疑似遗漏需核查原文后复核;已确认的问题仍可在这里继续查看。
|
||||
</p>
|
||||
<el-alert
|
||||
v-if="issuesError"
|
||||
:title="issuesError"
|
||||
type="error"
|
||||
:closable="false"
|
||||
class="mb-4"
|
||||
/>
|
||||
<el-table
|
||||
v-loading="issuesLoading"
|
||||
:data="issues"
|
||||
empty-text="暂无待核查问题;没有分析结果不代表已达标"
|
||||
>
|
||||
<el-table-column label="问题 / 关联患者" min-width="180"
|
||||
><template #default="{ row }"
|
||||
><strong class="issue-label">{{ row.label }}</strong
|
||||
><small
|
||||
>{{ row.patient_name || '未命名患者' }} · 诊单 #{{
|
||||
row.diagnosis_id
|
||||
}}</small
|
||||
></template
|
||||
></el-table-column
|
||||
>
|
||||
<el-table-column prop="reason" label="需要核查的内容" min-width="240" />
|
||||
<el-table-column label="复核状态" width="100"
|
||||
><template #default="{ row }">{{
|
||||
row.decision === 'confirmed' ? '已确认' : '待复核'
|
||||
}}</template></el-table-column
|
||||
>
|
||||
<el-table-column label="操作" width="100" fixed="right"
|
||||
><template #default="{ row }"
|
||||
><el-button link type="primary" @click="openIssue(row)"
|
||||
>核查记录</el-button
|
||||
></template
|
||||
></el-table-column
|
||||
>
|
||||
</el-table>
|
||||
<el-pagination
|
||||
v-if="issuesTotal"
|
||||
v-model:current-page="issuesPage"
|
||||
class="pagination"
|
||||
:total="issuesTotal"
|
||||
:page-size="10"
|
||||
layout="total, prev, pager, next"
|
||||
@current-change="loadIssues(false)"
|
||||
/>
|
||||
</el-tab-pane>
|
||||
<el-tab-pane label="跟进执行" name="actions">
|
||||
<p class="section-note">该医助负责的全部未结与历史事项,可更新执行情况。</p>
|
||||
<ServiceActions
|
||||
:assistant-id="staff.id"
|
||||
:actor-id="actorId"
|
||||
:can-complete="can('completeAction')"
|
||||
:can-review="can('reviewQuality')"
|
||||
:refresh-key="actionsRefresh"
|
||||
@changed="changed"
|
||||
/>
|
||||
</el-tab-pane>
|
||||
<el-tab-pane label="关联沟通记录" name="cases">
|
||||
<form class="case-search" @submit.prevent="searchCases">
|
||||
<el-input
|
||||
v-model="caseKeyword"
|
||||
placeholder="搜索关联患者 / 诊单"
|
||||
aria-label="搜索关联记录"
|
||||
clearable
|
||||
@clear="searchCases"
|
||||
/><el-button native-type="submit">搜索记录</el-button>
|
||||
</form>
|
||||
<el-alert
|
||||
v-if="casesError"
|
||||
:title="casesError"
|
||||
type="error"
|
||||
:closable="false"
|
||||
class="mb-4"
|
||||
/>
|
||||
<el-table
|
||||
v-loading="casesLoading"
|
||||
:data="cases"
|
||||
row-key="diagnosis_id"
|
||||
empty-text="最近 30 天暂无关联沟通记录"
|
||||
>
|
||||
<el-table-column label="关联患者 / 诊单" min-width="150"
|
||||
><template #default="{ row }"
|
||||
>{{ row.patient_name || '未命名患者'
|
||||
}}<small>诊单 #{{ row.diagnosis_id }}</small></template
|
||||
></el-table-column
|
||||
>
|
||||
<el-table-column label="沟通发言" width="100" align="right"
|
||||
><template #default="{ row }">{{
|
||||
row.im_messages ?? '未接入'
|
||||
}}</template></el-table-column
|
||||
>
|
||||
<el-table-column
|
||||
prop="manual_records"
|
||||
label="登记记录"
|
||||
width="100"
|
||||
align="right"
|
||||
/>
|
||||
<el-table-column label="最近沟通" min-width="170"
|
||||
><template #default="{ row }">{{
|
||||
formatTime(row.last_activity_at)
|
||||
}}</template></el-table-column
|
||||
>
|
||||
<el-table-column label="操作" width="100" fixed="right"
|
||||
><template #default="{ row }"
|
||||
><el-button link type="primary" @click="openCase(row)"
|
||||
>核查记录</el-button
|
||||
></template
|
||||
></el-table-column
|
||||
>
|
||||
</el-table>
|
||||
<el-pagination
|
||||
v-if="casesTotal"
|
||||
v-model:current-page="casesPage"
|
||||
class="pagination"
|
||||
:total="casesTotal"
|
||||
:page-size="10"
|
||||
layout="total, prev, pager, next"
|
||||
@current-change="loadCases(false)"
|
||||
/>
|
||||
</el-tab-pane>
|
||||
</el-tabs>
|
||||
<details v-if="overview" class="quality-summary">
|
||||
<summary>服务质检汇总与资料说明</summary>
|
||||
<el-table
|
||||
:data="overview.quality"
|
||||
empty-text="尚无有效分析结果,系统会自动分析可用沟通记录"
|
||||
>
|
||||
<el-table-column prop="label" label="质检项" min-width="150" />
|
||||
<el-table-column prop="met" label="已覆盖" min-width="80" align="right" />
|
||||
<el-table-column
|
||||
prop="missed"
|
||||
label="疑似遗漏"
|
||||
min-width="95"
|
||||
align="right"
|
||||
/>
|
||||
<el-table-column
|
||||
prop="insufficient"
|
||||
label="证据不足"
|
||||
min-width="95"
|
||||
align="right"
|
||||
/>
|
||||
<el-table-column
|
||||
prop="confirmed"
|
||||
label="已确认"
|
||||
min-width="85"
|
||||
align="right"
|
||||
/>
|
||||
<el-table-column
|
||||
prop="dismissed"
|
||||
label="已驳回"
|
||||
min-width="85"
|
||||
align="right"
|
||||
/>
|
||||
<el-table-column
|
||||
prop="not_applicable"
|
||||
label="不适用"
|
||||
min-width="85"
|
||||
align="right"
|
||||
/>
|
||||
<el-table-column
|
||||
prop="unreviewed"
|
||||
label="待复核"
|
||||
min-width="85"
|
||||
align="right"
|
||||
/>
|
||||
</el-table>
|
||||
<ul v-if="overview.coverage_notes.length" class="coverage-notes">
|
||||
<li v-for="note in overview.coverage_notes" :key="note">{{ note }}</li>
|
||||
</ul>
|
||||
</details>
|
||||
</div>
|
||||
<CaseDetail
|
||||
v-if="detail"
|
||||
:key="`${staff.id}:${detail.patient.diagnosis_id}:${detail.jobId || 0}`"
|
||||
:patient="detail.patient"
|
||||
:assistant-id="staff.id"
|
||||
:days="30"
|
||||
:capabilities="capabilities"
|
||||
:initial-job-id="detail.jobId"
|
||||
:refresh-key="caseRefresh"
|
||||
automatic
|
||||
@back="closeDetail"
|
||||
@changed="changed"
|
||||
/>
|
||||
</template>
|
||||
</section>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, ref, watch } from 'vue'
|
||||
import {
|
||||
assistantStaffOverview,
|
||||
assistantStaffCases,
|
||||
assistantStaffIssues,
|
||||
type Capabilities,
|
||||
type Permission,
|
||||
type Patient,
|
||||
type Staff,
|
||||
type StaffCase,
|
||||
type StaffIssue,
|
||||
type StaffOverview
|
||||
} from '@/api/assistantService'
|
||||
import useUserStore from '@/stores/modules/user'
|
||||
import CaseDetail from './CaseDetail.vue'
|
||||
import ServiceActions from './ServiceActions.vue'
|
||||
import DailyContacts from './DailyContacts.vue'
|
||||
import { errorText, formatTime, isCancelled } from '../shared'
|
||||
const props = defineProps<{
|
||||
staff: Staff
|
||||
capabilities: Capabilities
|
||||
refreshKey: number
|
||||
businessDate?: string
|
||||
initialView?: 'daily' | 'issues'
|
||||
initialStatus?: import('@/api/assistantService').DailyStatus
|
||||
entryKey?: number
|
||||
}>()
|
||||
const emit = defineEmits<{
|
||||
(event: 'changed'): void
|
||||
(event: 'date-change', date: string): void
|
||||
}>()
|
||||
const user = useUserStore(),
|
||||
actorId = computed(() => Number(user.userInfo.id || user.userInfo.admin_id || 0))
|
||||
const can = (permission: Permission) => props.capabilities.permissions.includes(permission)
|
||||
const overview = ref<StaffOverview | null>(null),
|
||||
overviewLoading = ref(false),
|
||||
overviewError = ref('')
|
||||
const cases = ref<StaffCase[]>([]),
|
||||
casesPage = ref(1),
|
||||
casesTotal = ref(0),
|
||||
casesLoading = ref(false),
|
||||
casesError = ref(''),
|
||||
caseKeyword = ref(''),
|
||||
caseKeywordApplied = ref('')
|
||||
const issues = ref<StaffIssue[]>([]),
|
||||
issuesPage = ref(1),
|
||||
issuesTotal = ref(0),
|
||||
issuesLoading = ref(false),
|
||||
issuesError = ref('')
|
||||
const detail = ref<{ patient: Patient; jobId?: number; daily?: boolean } | null>(null),
|
||||
activeTab = ref<string>(props.initialView || 'daily'),
|
||||
dailyRefresh = ref(0),
|
||||
actionsRefresh = ref(0),
|
||||
caseRefresh = ref(0)
|
||||
let disposed = false,
|
||||
revision = 0,
|
||||
overviewRevision = 0,
|
||||
casesRevision = 0,
|
||||
issuesRevision = 0
|
||||
let overviewRequest: AbortController | undefined,
|
||||
casesRequest: AbortController | undefined,
|
||||
issuesRequest: AbortController | undefined
|
||||
const currentScope = () => ({ assistant_id: props.staff.id, days: 30 as const })
|
||||
function clearScope() {
|
||||
revision++
|
||||
overviewRevision++
|
||||
casesRevision++
|
||||
issuesRevision++
|
||||
overviewRequest?.abort()
|
||||
casesRequest?.abort()
|
||||
issuesRequest?.abort()
|
||||
overview.value = null
|
||||
cases.value = []
|
||||
issues.value = []
|
||||
detail.value = null
|
||||
casesPage.value = 1
|
||||
issuesPage.value = 1
|
||||
casesTotal.value = 0
|
||||
issuesTotal.value = 0
|
||||
caseKeyword.value = ''
|
||||
caseKeywordApplied.value = ''
|
||||
activeTab.value = props.initialView || 'daily'
|
||||
overviewError.value = ''
|
||||
casesError.value = ''
|
||||
issuesError.value = ''
|
||||
overviewLoading.value = false
|
||||
casesLoading.value = false
|
||||
issuesLoading.value = false
|
||||
}
|
||||
async function loadOverview(silent = false) {
|
||||
const scope = currentScope(),
|
||||
token = revision,
|
||||
requestToken = ++overviewRevision
|
||||
overviewRequest?.abort()
|
||||
overviewRequest = new AbortController()
|
||||
if (!silent) overviewLoading.value = true
|
||||
try {
|
||||
const data = await assistantStaffOverview(scope, overviewRequest.signal)
|
||||
if (disposed || token !== revision || requestToken !== overviewRevision) return
|
||||
if (data.staff.id !== scope.assistant_id || data.days !== 30)
|
||||
throw new Error('概览与当前医助或时间范围不一致')
|
||||
overview.value = data
|
||||
overviewError.value = ''
|
||||
} catch (cause) {
|
||||
if (
|
||||
!disposed &&
|
||||
token === revision &&
|
||||
requestToken === overviewRevision &&
|
||||
!isCancelled(cause)
|
||||
) {
|
||||
overviewError.value = errorText(cause)
|
||||
overview.value = null
|
||||
if (!detail.value?.daily) detail.value = null
|
||||
}
|
||||
} finally {
|
||||
if (!disposed && token === revision && requestToken === overviewRevision)
|
||||
overviewLoading.value = false
|
||||
}
|
||||
}
|
||||
async function loadCases(silent = false) {
|
||||
const scope = currentScope(),
|
||||
token = revision,
|
||||
requestToken = ++casesRevision
|
||||
casesRequest?.abort()
|
||||
casesRequest = new AbortController()
|
||||
if (!silent) {
|
||||
casesLoading.value = true
|
||||
cases.value = []
|
||||
}
|
||||
casesError.value = ''
|
||||
try {
|
||||
const data = await assistantStaffCases(
|
||||
{
|
||||
...scope,
|
||||
keyword: caseKeywordApplied.value,
|
||||
page_no: casesPage.value,
|
||||
page_size: 10
|
||||
},
|
||||
casesRequest.signal
|
||||
)
|
||||
if (disposed || token !== revision || requestToken !== casesRevision) return
|
||||
cases.value = data.lists
|
||||
casesTotal.value = data.count
|
||||
} catch (cause) {
|
||||
if (
|
||||
!disposed &&
|
||||
token === revision &&
|
||||
requestToken === casesRevision &&
|
||||
!isCancelled(cause)
|
||||
) {
|
||||
casesError.value = errorText(cause)
|
||||
cases.value = []
|
||||
casesTotal.value = 0
|
||||
}
|
||||
} finally {
|
||||
if (!disposed && token === revision && requestToken === casesRevision)
|
||||
casesLoading.value = false
|
||||
}
|
||||
}
|
||||
async function loadIssues(silent = false) {
|
||||
const scope = currentScope(),
|
||||
token = revision,
|
||||
requestToken = ++issuesRevision
|
||||
issuesRequest?.abort()
|
||||
issuesRequest = new AbortController()
|
||||
if (!silent) {
|
||||
issuesLoading.value = true
|
||||
issues.value = []
|
||||
}
|
||||
issuesError.value = ''
|
||||
try {
|
||||
const data = await assistantStaffIssues(
|
||||
{ ...scope, page_no: issuesPage.value, page_size: 10 },
|
||||
issuesRequest.signal
|
||||
)
|
||||
if (disposed || token !== revision || requestToken !== issuesRevision) return
|
||||
issues.value = data.lists
|
||||
issuesTotal.value = data.count
|
||||
} catch (cause) {
|
||||
if (
|
||||
!disposed &&
|
||||
token === revision &&
|
||||
requestToken === issuesRevision &&
|
||||
!isCancelled(cause)
|
||||
) {
|
||||
issuesError.value = errorText(cause)
|
||||
issues.value = []
|
||||
issuesTotal.value = 0
|
||||
}
|
||||
} finally {
|
||||
if (!disposed && token === revision && requestToken === issuesRevision)
|
||||
issuesLoading.value = false
|
||||
}
|
||||
}
|
||||
async function refresh(silent: unknown = false) {
|
||||
if (disposed || !can('view')) return
|
||||
dailyRefresh.value++
|
||||
const token = revision
|
||||
await Promise.all([
|
||||
loadOverview(silent === true),
|
||||
loadCases(silent === true),
|
||||
loadIssues(silent === true)
|
||||
])
|
||||
if (!disposed && token === revision) {
|
||||
actionsRefresh.value++
|
||||
caseRefresh.value++
|
||||
}
|
||||
}
|
||||
function searchCases() {
|
||||
caseKeywordApplied.value = caseKeyword.value.trim()
|
||||
casesPage.value = 1
|
||||
void loadCases()
|
||||
}
|
||||
function openCase(patient: Patient, jobId?: number) {
|
||||
if (overview.value && !overviewError.value) detail.value = { patient, jobId }
|
||||
}
|
||||
function openDaily(patient: Patient) {
|
||||
if (can('view') && patient.assistant_id === props.staff.id)
|
||||
detail.value = { patient, daily: true }
|
||||
}
|
||||
function dailyUnavailable() {
|
||||
if (detail.value?.daily) detail.value = null
|
||||
}
|
||||
function openIssue(issue: StaffIssue) {
|
||||
openCase(
|
||||
{
|
||||
diagnosis_id: issue.diagnosis_id,
|
||||
patient_id: 0,
|
||||
patient_name: issue.patient_name,
|
||||
assistant_id: props.staff.id
|
||||
},
|
||||
issue.job_id
|
||||
)
|
||||
}
|
||||
function closeDetail() {
|
||||
detail.value = null
|
||||
void refresh(true)
|
||||
}
|
||||
function changed() {
|
||||
void refresh(true)
|
||||
emit('changed')
|
||||
}
|
||||
watch(
|
||||
() => props.staff.id,
|
||||
() => {
|
||||
clearScope()
|
||||
void refresh()
|
||||
},
|
||||
{ immediate: true, flush: 'sync' }
|
||||
)
|
||||
watch(
|
||||
() => props.refreshKey,
|
||||
() => void refresh(true)
|
||||
)
|
||||
watch(
|
||||
() => props.entryKey,
|
||||
() => {
|
||||
activeTab.value = props.initialView || 'daily'
|
||||
detail.value = null
|
||||
}
|
||||
)
|
||||
watch(
|
||||
() => can('view'),
|
||||
(allowed) => {
|
||||
if (!allowed) clearScope()
|
||||
},
|
||||
{ flush: 'sync' }
|
||||
)
|
||||
onBeforeUnmount(() => {
|
||||
disposed = true
|
||||
clearScope()
|
||||
})
|
||||
</script>
|
||||
<style scoped>
|
||||
.staff-detail {
|
||||
min-width: 0;
|
||||
}
|
||||
.detail-heading {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
align-items: center;
|
||||
margin-bottom: 18px;
|
||||
}
|
||||
h2 {
|
||||
font-size: 21px;
|
||||
font-weight: 600;
|
||||
margin: 0;
|
||||
}
|
||||
.detail-heading p,
|
||||
.section-note {
|
||||
font-size: 12px;
|
||||
line-height: 1.7;
|
||||
color: var(--el-text-color-secondary);
|
||||
margin: 7px 0 0;
|
||||
}
|
||||
.detail-metrics {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
padding: 18px 0;
|
||||
margin-bottom: 20px;
|
||||
background: var(--el-fill-color-light);
|
||||
border-radius: 4px;
|
||||
}
|
||||
.detail-metrics > div {
|
||||
border-right: 1px solid var(--el-border-color-light);
|
||||
padding: 0 18px;
|
||||
}
|
||||
.detail-metrics > div:last-child {
|
||||
border: 0;
|
||||
}
|
||||
.detail-metrics span {
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
display: block;
|
||||
}
|
||||
.detail-metrics strong {
|
||||
display: block;
|
||||
font-size: 23px;
|
||||
font-weight: 600;
|
||||
font-variant-numeric: tabular-nums;
|
||||
margin-top: 5px;
|
||||
}
|
||||
.attention {
|
||||
color: var(--el-color-primary);
|
||||
}
|
||||
.section-note {
|
||||
margin: 2px 0 16px;
|
||||
}
|
||||
.issue-label {
|
||||
font-weight: 500;
|
||||
}
|
||||
small {
|
||||
display: block;
|
||||
margin-top: 4px;
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: 12px;
|
||||
}
|
||||
.pagination {
|
||||
margin-top: 16px;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
.case-search {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
max-width: 380px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.quality-summary {
|
||||
border-top: 1px solid var(--el-border-color-light);
|
||||
margin-top: 28px;
|
||||
padding-top: 18px;
|
||||
}
|
||||
.quality-summary summary {
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
.quality-summary summary:focus-visible {
|
||||
outline: 2px solid var(--el-color-primary);
|
||||
outline-offset: 4px;
|
||||
}
|
||||
.coverage-notes {
|
||||
padding-left: 18px;
|
||||
font-size: 12px;
|
||||
line-height: 1.8;
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
.detail-tabs :deep(.el-table__cell) {
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
@media (max-width: 600px) {
|
||||
.detail-metrics {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 20px 0;
|
||||
}
|
||||
.detail-metrics > div:nth-child(2) {
|
||||
border: 0;
|
||||
}
|
||||
.detail-heading {
|
||||
align-items: flex-start;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,202 @@
|
||||
<template>
|
||||
<section class="wecom-thread" aria-label="企业微信聊天记录">
|
||||
<p class="freshness">{{ freshness }}</p>
|
||||
<el-skeleton v-if="loading && !conversations.length" :rows="5" animated />
|
||||
<el-alert v-else-if="error && !conversations.length" :title="error" type="error" :closable="false" show-icon />
|
||||
<p v-else-if="!conversations.length" class="empty">
|
||||
这个账号还没有会话。页面每 15 秒自动检查一次,新消息进来后会出现在这里。
|
||||
</p>
|
||||
<div v-else class="split">
|
||||
<ul class="conversations">
|
||||
<li v-for="item in conversations" :key="item.id">
|
||||
<button
|
||||
type="button"
|
||||
:class="{ active: selected === item.id }"
|
||||
@click="openConversation(item.id)"
|
||||
>
|
||||
<strong>{{ item.name || '未命名会话' }}</strong>
|
||||
<small>{{ item.message_count }} 条 · {{ item.preview || '没有文字预览' }}</small>
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
<ol v-if="selected" class="messages">
|
||||
<li
|
||||
v-for="item in messages"
|
||||
:key="item.id"
|
||||
:class="item.direction === 'outbound' ? 'outbound' : 'inbound'"
|
||||
>
|
||||
<span>{{ item.direction === 'outbound' ? '员工' : '对方' }} · {{ item.sender_name || '未署名' }}</span>
|
||||
<p>{{ item.content || `[${item.message_type}]` }}</p>
|
||||
</li>
|
||||
</ol>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, ref, watch } from 'vue'
|
||||
import { assistantWecomChats, assistantWecomMessages, type WecomConversation, type WecomMessage } from '@/api/assistantService'
|
||||
import { errorText, isCancelled } from '../shared'
|
||||
|
||||
const props = defineProps<{ assistantId: number; account: string }>()
|
||||
const conversations = ref<WecomConversation[]>([])
|
||||
const messages = ref<WecomMessage[]>([])
|
||||
const selected = ref('')
|
||||
const loading = ref(false)
|
||||
const error = ref('')
|
||||
const refreshedAt = ref(0)
|
||||
const freshness = computed(() =>
|
||||
refreshedAt.value
|
||||
? `自动更新于 ${new Date(refreshedAt.value).toLocaleTimeString('zh-CN', { hour12: false })}`
|
||||
: '正在读取会话'
|
||||
)
|
||||
let disposed = false
|
||||
let request: AbortController | undefined
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
function stopTimer() {
|
||||
if (timer) clearTimeout(timer)
|
||||
timer = undefined
|
||||
}
|
||||
function schedule() {
|
||||
stopTimer()
|
||||
if (!disposed) timer = setTimeout(() => void loadConversations(true), 15000)
|
||||
}
|
||||
async function loadConversations(silent = false) {
|
||||
const current = selected.value
|
||||
request?.abort()
|
||||
request = new AbortController()
|
||||
if (!silent) {
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
conversations.value = []
|
||||
messages.value = []
|
||||
selected.value = ''
|
||||
}
|
||||
try {
|
||||
const result = await assistantWecomChats(
|
||||
{ assistant_id: props.assistantId, account: props.account },
|
||||
request.signal
|
||||
)
|
||||
if (disposed) return
|
||||
conversations.value = result.conversations
|
||||
refreshedAt.value = Date.now()
|
||||
const stillThere = result.conversations.some((item) => item.id === current)
|
||||
const next = stillThere ? current : result.conversations[0]?.id || ''
|
||||
if (next) await openConversation(next, silent && stillThere)
|
||||
else messages.value = []
|
||||
} catch (cause) {
|
||||
if (!disposed && !isCancelled(cause) && !silent) error.value = errorText(cause)
|
||||
} finally {
|
||||
if (!disposed) {
|
||||
loading.value = false
|
||||
schedule()
|
||||
}
|
||||
}
|
||||
}
|
||||
async function openConversation(id: string, keepVisible = false) {
|
||||
selected.value = id
|
||||
if (!keepVisible) messages.value = []
|
||||
try {
|
||||
const result = await assistantWecomMessages({
|
||||
assistant_id: props.assistantId,
|
||||
account: props.account,
|
||||
conversation_id: id
|
||||
})
|
||||
if (!disposed && selected.value === id) messages.value = result.messages
|
||||
} catch (cause) {
|
||||
if (!disposed && !isCancelled(cause) && !keepVisible) error.value = errorText(cause)
|
||||
}
|
||||
}
|
||||
watch(
|
||||
() => [props.assistantId, props.account],
|
||||
() => void loadConversations(false),
|
||||
{ immediate: true }
|
||||
)
|
||||
onBeforeUnmount(() => {
|
||||
disposed = true
|
||||
stopTimer()
|
||||
request?.abort()
|
||||
})
|
||||
</script>
|
||||
<style scoped>
|
||||
.wecom-thread {
|
||||
min-height: 240px;
|
||||
}
|
||||
.freshness,
|
||||
.empty {
|
||||
color: var(--el-text-color-secondary);
|
||||
line-height: 1.7;
|
||||
}
|
||||
.freshness {
|
||||
margin: 0 0 8px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.split {
|
||||
display: grid;
|
||||
grid-template-columns: 220px 1fr;
|
||||
gap: 12px;
|
||||
min-height: 420px;
|
||||
}
|
||||
.conversations,
|
||||
.messages {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
overflow: auto;
|
||||
max-height: 70vh;
|
||||
}
|
||||
.conversations button {
|
||||
width: 100%;
|
||||
margin-bottom: 6px;
|
||||
padding: 8px 10px;
|
||||
border: 1px solid var(--el-border-color-lighter);
|
||||
border-radius: 8px;
|
||||
background: var(--el-bg-color);
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
.conversations button.active {
|
||||
border-color: #0f766e;
|
||||
background: #f0fdfa;
|
||||
}
|
||||
.conversations strong,
|
||||
.conversations small {
|
||||
display: block;
|
||||
}
|
||||
.conversations small {
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.messages li {
|
||||
margin-bottom: 10px;
|
||||
max-width: 92%;
|
||||
}
|
||||
.messages li span {
|
||||
display: block;
|
||||
margin-bottom: 3px;
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: 12px;
|
||||
}
|
||||
.messages p {
|
||||
margin: 0;
|
||||
padding: 8px 10px;
|
||||
border-radius: 8px;
|
||||
line-height: 1.6;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
.outbound {
|
||||
margin-left: auto;
|
||||
}
|
||||
.outbound p {
|
||||
background: #dbeafe;
|
||||
}
|
||||
.inbound p {
|
||||
background: var(--el-fill-color);
|
||||
}
|
||||
@media (max-width: 720px) {
|
||||
.split {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,516 @@
|
||||
<template>
|
||||
<div class="knowledge-page">
|
||||
<div class="page-heading">
|
||||
<div>
|
||||
<h1>服务知识维护</h1>
|
||||
<p>维护就诊流程、服务规则与常见问题。仅已发布的知识参与回复草稿生成。</p>
|
||||
</div>
|
||||
<el-button
|
||||
v-if="canManage && capabilities?.schema_ready"
|
||||
type="primary"
|
||||
@click="openEditor()"
|
||||
>新增知识</el-button
|
||||
>
|
||||
</div>
|
||||
<el-alert
|
||||
v-if="bootError"
|
||||
:title="bootError"
|
||||
type="error"
|
||||
:closable="false"
|
||||
class="mb-4"
|
||||
/><el-button v-if="bootError" @click="initialize">重新加载权限</el-button>
|
||||
<el-alert
|
||||
v-if="capabilities && !capabilities.schema_ready"
|
||||
:title="capabilities.reason || '服务知识尚未完成初始化,请联系管理员'"
|
||||
type="warning"
|
||||
:closable="false"
|
||||
/>
|
||||
<el-alert
|
||||
v-else-if="capabilities && !canManage"
|
||||
title="当前账号没有知识管理权限,请联系管理员授权。"
|
||||
type="warning"
|
||||
:closable="false"
|
||||
/>
|
||||
<el-card v-if="canManage && capabilities?.schema_ready" shadow="never" v-loading="booting">
|
||||
<el-form inline class="search-form" @submit.prevent="search"
|
||||
><el-form-item label="关键词"
|
||||
><el-input
|
||||
v-model="keyword"
|
||||
placeholder="搜索问题或分类"
|
||||
clearable
|
||||
@keyup.enter="search"
|
||||
@clear="search" /></el-form-item
|
||||
><el-form-item label="发布状态"
|
||||
><el-select
|
||||
v-model="status"
|
||||
clearable
|
||||
placeholder="全部"
|
||||
style="width: 150px"
|
||||
@change="search"
|
||||
><el-option
|
||||
v-for="(label, value) in labels"
|
||||
:key="value"
|
||||
:label="label"
|
||||
:value="value" /></el-select></el-form-item
|
||||
><el-form-item
|
||||
><el-button type="primary" :loading="loading" @click="search"
|
||||
>查询</el-button
|
||||
></el-form-item
|
||||
></el-form
|
||||
>
|
||||
<el-alert v-if="error" :title="error" type="error" :closable="false" class="mb-4" />
|
||||
<el-table
|
||||
:data="rows"
|
||||
v-loading="loading"
|
||||
empty-text="暂无服务知识,请新增并核对后发布"
|
||||
>
|
||||
<el-table-column label="问题 / 答案" min-width="300"
|
||||
><template #default="{ row }"
|
||||
><strong>{{ row.question }}</strong>
|
||||
<p class="answer-preview">{{ row.answer }}</p></template
|
||||
></el-table-column
|
||||
>
|
||||
<el-table-column prop="category" label="分类" width="120" />
|
||||
<el-table-column label="状态" width="100"
|
||||
><template #default="{ row }"
|
||||
><el-tag :type="row.status === 'published' ? 'success' : 'info'">{{
|
||||
labels[row.status as KnowledgeStatus]
|
||||
}}</el-tag></template
|
||||
></el-table-column
|
||||
>
|
||||
<el-table-column label="版本" width="75"
|
||||
><template #default="{ row }">v{{ row.version }}</template></el-table-column
|
||||
>
|
||||
<el-table-column label="更新时间" min-width="175"
|
||||
><template #default="{ row }">{{
|
||||
formatTime(row.updated_at)
|
||||
}}</template></el-table-column
|
||||
>
|
||||
<el-table-column label="操作" width="100" fixed="right"
|
||||
><template #default="{ row }"
|
||||
><el-button link type="primary" @click="openEditor(row)"
|
||||
>查看 / 编辑</el-button
|
||||
></template
|
||||
></el-table-column
|
||||
>
|
||||
</el-table>
|
||||
<el-pagination
|
||||
v-if="total"
|
||||
class="mt-4"
|
||||
v-model:current-page="page"
|
||||
:total="total"
|
||||
:page-size="15"
|
||||
layout="total, prev, pager, next"
|
||||
@current-change="load"
|
||||
/>
|
||||
</el-card>
|
||||
<el-skeleton v-else-if="booting" :rows="6" animated />
|
||||
<el-dialog
|
||||
v-model="editorOpened"
|
||||
:title="form.id ? `知识 #${form.id} · v${form.version}` : '新增服务知识'"
|
||||
width="min(760px, 96vw)"
|
||||
:close-on-click-modal="false"
|
||||
:close-on-press-escape="!saving"
|
||||
:show-close="!saving"
|
||||
:before-close="beforeClose"
|
||||
>
|
||||
<el-alert
|
||||
v-if="form.id"
|
||||
:title="`当前状态:${labels[editorStatus]}。修改正文并保存后将回到草稿,需要重新发布。`"
|
||||
type="info"
|
||||
:closable="false"
|
||||
class="mb-4"
|
||||
/>
|
||||
<el-form label-position="top" :disabled="saving" @submit.prevent="saveDraft">
|
||||
<el-form-item label="常见问题" required
|
||||
><el-input v-model="form.question" :maxlength="300" show-word-limit
|
||||
/></el-form-item>
|
||||
<el-form-item label="权威服务答案" required
|
||||
><el-input
|
||||
v-model="form.answer"
|
||||
type="textarea"
|
||||
:rows="9"
|
||||
placeholder="填写已经核实的服务规则、适用范围与必要限制。"
|
||||
/></el-form-item>
|
||||
<el-form-item label="分类"
|
||||
><el-input
|
||||
v-model="form.category"
|
||||
:maxlength="64"
|
||||
placeholder="例如:预约流程、物流服务"
|
||||
/></el-form-item>
|
||||
<el-form-item label="来源 / 核实说明" required
|
||||
><el-input
|
||||
v-model="form.source_note"
|
||||
type="textarea"
|
||||
:rows="3"
|
||||
:maxlength="1000"
|
||||
show-word-limit
|
||||
placeholder="注明制度、文件、负责人或核实时间,方便后续复核。"
|
||||
/></el-form-item>
|
||||
</el-form>
|
||||
<el-alert
|
||||
v-if="editorError"
|
||||
:title="editorError"
|
||||
type="error"
|
||||
:closable="false"
|
||||
class="mb-4"
|
||||
/>
|
||||
<el-alert
|
||||
v-if="conflicted"
|
||||
title="此条目已被其他人修改。本地编辑已保留,请复制需要保留的内容,再加载最新版本并重新核对。"
|
||||
type="warning"
|
||||
:closable="false"
|
||||
class="mb-4"
|
||||
/>
|
||||
<div v-if="conflicted" class="conflict-tools">
|
||||
<el-button @click="copyLocal">复制本地编辑</el-button
|
||||
><el-button :loading="saving" @click="reloadLatest">加载最新版本</el-button>
|
||||
</div>
|
||||
<template #footer
|
||||
><div class="editor-footer">
|
||||
<el-button :disabled="saving" @click="closeEditor">关闭</el-button
|
||||
><el-button
|
||||
v-if="form.id && editorStatus === 'published'"
|
||||
type="danger"
|
||||
plain
|
||||
:disabled="saving || conflicted || dirty"
|
||||
@click="publish('disabled')"
|
||||
>停用当前版本</el-button
|
||||
><el-button
|
||||
type="primary"
|
||||
plain
|
||||
:loading="saving"
|
||||
:disabled="conflicted"
|
||||
@click="saveDraft"
|
||||
>保存草稿</el-button
|
||||
><el-button
|
||||
v-if="form.id && editorStatus !== 'published'"
|
||||
type="primary"
|
||||
:disabled="saving || conflicted || dirty"
|
||||
@click="publish('published')"
|
||||
>确认发布</el-button
|
||||
>
|
||||
</div>
|
||||
<p v-if="dirty && form.id" class="footer-note">
|
||||
有未保存编辑,请先保存草稿再发布或停用。
|
||||
</p></template
|
||||
>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, reactive, ref } from 'vue'
|
||||
import useClipboard from 'vue-clipboard3'
|
||||
import {
|
||||
assistantCapabilities,
|
||||
assistantKnowledge,
|
||||
assistantPublishKnowledge,
|
||||
assistantSaveKnowledge,
|
||||
type Capabilities,
|
||||
type Knowledge,
|
||||
type KnowledgeStatus
|
||||
} from '@/api/assistantService'
|
||||
import feedback from '@/utils/feedback'
|
||||
import { errorText, formatTime, isCancelled } from '../shared'
|
||||
const capabilities = ref<Capabilities | null>(null),
|
||||
booting = ref(false),
|
||||
bootError = ref(''),
|
||||
canManage = computed(
|
||||
() =>
|
||||
capabilities.value?.permissions.includes('view') &&
|
||||
capabilities.value?.permissions.includes('manageKnowledge')
|
||||
)
|
||||
const rows = ref<Knowledge[]>([]),
|
||||
page = ref(1),
|
||||
total = ref(0),
|
||||
keyword = ref(''),
|
||||
status = ref<KnowledgeStatus | ''>(''),
|
||||
loading = ref(false),
|
||||
error = ref('')
|
||||
const labels: Record<KnowledgeStatus, string> = {
|
||||
draft: '草稿',
|
||||
published: '已发布',
|
||||
disabled: '已停用'
|
||||
}
|
||||
let disposed = false,
|
||||
revision = 0,
|
||||
bootRevision = 0,
|
||||
request: AbortController | undefined,
|
||||
bootRequest: AbortController | undefined
|
||||
async function initialize() {
|
||||
const token = ++bootRevision
|
||||
bootRequest?.abort()
|
||||
bootRequest = new AbortController()
|
||||
booting.value = true
|
||||
bootError.value = ''
|
||||
try {
|
||||
const data = await assistantCapabilities(bootRequest.signal)
|
||||
if (!disposed && token === bootRevision) {
|
||||
capabilities.value = data
|
||||
if (canManage.value && data.schema_ready) await load()
|
||||
}
|
||||
} catch (cause) {
|
||||
if (!disposed && token === bootRevision && !isCancelled(cause))
|
||||
bootError.value = errorText(cause)
|
||||
} finally {
|
||||
if (!disposed && token === bootRevision) booting.value = false
|
||||
}
|
||||
}
|
||||
async function load() {
|
||||
if (!canManage.value) return
|
||||
const token = ++revision
|
||||
request?.abort()
|
||||
request = new AbortController()
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const data = await assistantKnowledge(
|
||||
{
|
||||
page_no: page.value,
|
||||
page_size: 15,
|
||||
keyword: keyword.value.trim(),
|
||||
...(status.value ? { status: status.value } : {})
|
||||
},
|
||||
request.signal
|
||||
)
|
||||
if (disposed || token !== revision) return
|
||||
rows.value = data.lists
|
||||
total.value = data.count
|
||||
} catch (cause) {
|
||||
if (!disposed && token === revision && !isCancelled(cause)) {
|
||||
error.value = errorText(cause)
|
||||
rows.value = []
|
||||
}
|
||||
} finally {
|
||||
if (!disposed && token === revision) loading.value = false
|
||||
}
|
||||
}
|
||||
function search() {
|
||||
page.value = 1
|
||||
void load()
|
||||
}
|
||||
const editorOpened = ref(false),
|
||||
saving = ref(false),
|
||||
editorError = ref(''),
|
||||
conflicted = ref(false),
|
||||
editorStatus = ref<KnowledgeStatus>('draft')
|
||||
const form = reactive({
|
||||
id: 0,
|
||||
version: 0,
|
||||
question: '',
|
||||
answer: '',
|
||||
category: '',
|
||||
source_note: ''
|
||||
})
|
||||
const snapshot = ref(''),
|
||||
serialize = () => JSON.stringify(form),
|
||||
dirty = computed(() => serialize() !== snapshot.value)
|
||||
function openEditor(row?: Knowledge) {
|
||||
Object.assign(form, {
|
||||
id: row?.id || 0,
|
||||
version: row?.version || 0,
|
||||
question: row?.question || '',
|
||||
answer: row?.answer || '',
|
||||
category: row?.category || '',
|
||||
source_note: row?.source_note || ''
|
||||
})
|
||||
editorStatus.value = row?.status || 'draft'
|
||||
snapshot.value = serialize()
|
||||
editorError.value = ''
|
||||
conflicted.value = false
|
||||
editorOpened.value = true
|
||||
}
|
||||
async function beforeClose(done: () => void) {
|
||||
if (saving.value) return
|
||||
if (dirty.value) {
|
||||
try {
|
||||
await feedback.confirm('尚有未保存的编辑,确认关闭并放弃这些编辑?')
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
}
|
||||
done()
|
||||
}
|
||||
function closeEditor() {
|
||||
void beforeClose(() => {
|
||||
editorOpened.value = false
|
||||
})
|
||||
}
|
||||
function mutationFailed(cause: unknown) {
|
||||
editorError.value = errorText(cause)
|
||||
const code = (cause as { code?: string })?.code || ''
|
||||
conflicted.value = /version|conflict|stale|版本|冲突|已被.*修改/i.test(
|
||||
`${code} ${editorError.value}`
|
||||
)
|
||||
if (!conflicted.value)
|
||||
editorError.value += '。连接中断时请先刷新列表确认是否已保存,再重新操作。'
|
||||
}
|
||||
async function saveDraft() {
|
||||
if (saving.value || conflicted.value || !canManage.value) return
|
||||
if (!form.question.trim() || !form.answer.trim() || !form.source_note.trim()) {
|
||||
editorError.value = '请填写问题、权威答案和来源说明'
|
||||
return
|
||||
}
|
||||
saving.value = true
|
||||
editorError.value = ''
|
||||
try {
|
||||
const data = await assistantSaveKnowledge({
|
||||
...form,
|
||||
question: form.question.trim(),
|
||||
answer: form.answer.trim(),
|
||||
category: form.category.trim(),
|
||||
source_note: form.source_note.trim()
|
||||
})
|
||||
if (disposed) return
|
||||
form.id = data.id
|
||||
form.version = data.version
|
||||
editorStatus.value = 'draft'
|
||||
snapshot.value = serialize()
|
||||
feedback.msgSuccess('草稿已保存,请核对后显式发布')
|
||||
await load()
|
||||
} catch (cause) {
|
||||
if (!disposed) mutationFailed(cause)
|
||||
} finally {
|
||||
if (!disposed) saving.value = false
|
||||
}
|
||||
}
|
||||
async function publish(nextStatus: 'published' | 'disabled') {
|
||||
if (saving.value || conflicted.value || dirty.value || !form.id || !canManage.value) return
|
||||
saving.value = true
|
||||
editorError.value = ''
|
||||
try {
|
||||
try {
|
||||
await feedback.confirm(
|
||||
nextStatus === 'published'
|
||||
? '确认内容与来源已经核实?发布后此版本将用于生成服务回复草稿。'
|
||||
: '确认停用此知识?停用后将不再作为新回复的知识依据。'
|
||||
)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
if (disposed) return
|
||||
const data = await assistantPublishKnowledge({
|
||||
id: form.id,
|
||||
version: form.version,
|
||||
status: nextStatus
|
||||
})
|
||||
if (disposed) return
|
||||
form.version = data.version
|
||||
editorStatus.value = nextStatus
|
||||
snapshot.value = serialize()
|
||||
feedback.msgSuccess(nextStatus === 'published' ? '知识已发布' : '知识已停用')
|
||||
await load()
|
||||
} catch (cause) {
|
||||
if (!disposed) mutationFailed(cause)
|
||||
} finally {
|
||||
if (!disposed) saving.value = false
|
||||
}
|
||||
}
|
||||
const { toClipboard } = useClipboard()
|
||||
async function copyLocal() {
|
||||
try {
|
||||
await toClipboard(
|
||||
`问题:${form.question}\n答案:${form.answer}\n分类:${form.category}\n来源:${form.source_note}`
|
||||
)
|
||||
feedback.msgSuccess('本地编辑已复制')
|
||||
} catch {
|
||||
feedback.msgError('复制失败,请手动选中文本复制')
|
||||
}
|
||||
}
|
||||
async function reloadLatest() {
|
||||
if (saving.value || !form.id) return
|
||||
saving.value = true
|
||||
try {
|
||||
try {
|
||||
await feedback.confirm(
|
||||
'加载最新版本将覆盖编辑框,请先复制需要保留的本地内容。确认继续?'
|
||||
)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
// 契约没有 detail 接口;逐页定位条目,不猜测新版本号。
|
||||
let cursor = 1,
|
||||
found: Knowledge | undefined,
|
||||
count = 0
|
||||
do {
|
||||
const data = await assistantKnowledge({ page_no: cursor, page_size: 100, keyword: '' })
|
||||
if (disposed) return
|
||||
found = data.lists.find((item) => item.id === form.id)
|
||||
count = data.count
|
||||
if (found || !data.lists.length) break
|
||||
cursor++
|
||||
} while ((cursor - 1) * 100 < count)
|
||||
if (!found) {
|
||||
editorError.value = '未找到该条目,可能已失去访问权限;本地编辑仍保留。'
|
||||
return
|
||||
}
|
||||
openEditor(found)
|
||||
await load()
|
||||
} catch (cause) {
|
||||
if (!disposed) editorError.value = errorText(cause)
|
||||
} finally {
|
||||
if (!disposed) saving.value = false
|
||||
}
|
||||
}
|
||||
onMounted(initialize)
|
||||
onBeforeUnmount(() => {
|
||||
disposed = true
|
||||
revision++
|
||||
bootRevision++
|
||||
request?.abort()
|
||||
bootRequest?.abort()
|
||||
})
|
||||
</script>
|
||||
<style scoped>
|
||||
.knowledge-page {
|
||||
padding: 4px;
|
||||
}
|
||||
.page-heading {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
align-items: center;
|
||||
margin-bottom: 20px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
h1 {
|
||||
font-size: 22px;
|
||||
font-weight: 600;
|
||||
margin: 0 0 8px;
|
||||
}
|
||||
.page-heading p,
|
||||
.footer-note {
|
||||
color: var(--el-text-color-secondary);
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.answer-preview {
|
||||
margin: 8px 0 0;
|
||||
color: var(--el-text-color-secondary);
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.editor-footer,
|
||||
.conflict-tools {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px;
|
||||
}
|
||||
.editor-footer .el-button {
|
||||
margin-left: 0;
|
||||
}
|
||||
.footer-note {
|
||||
margin-top: 10px;
|
||||
}
|
||||
@media (max-width: 600px) {
|
||||
.search-form :deep(.el-form-item) {
|
||||
display: flex;
|
||||
margin-right: 0;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,44 @@
|
||||
import type { JobStatus } from '@/api/assistantService'
|
||||
|
||||
export function errorText(error: unknown): string {
|
||||
if (error instanceof Error) return error.message
|
||||
if (typeof error === 'string') return error
|
||||
const value = error as {
|
||||
msg?: string
|
||||
message?: string
|
||||
response?: { data?: { msg?: string } }
|
||||
} | null
|
||||
return value?.response?.data?.msg || value?.msg || value?.message || '请求失败,请刷新后重试'
|
||||
}
|
||||
export function isCancelled(error: unknown) {
|
||||
return (error as { code?: string })?.code === 'ERR_CANCELED'
|
||||
}
|
||||
export function formatTime(value: number) {
|
||||
return value ? new Date(value * 1000).toLocaleString('zh-CN', { hour12: false }) : '—'
|
||||
}
|
||||
export function shanghaiTime(value: number) {
|
||||
return value
|
||||
? new Date(value * 1000).toLocaleString('zh-CN', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
hour12: false
|
||||
})
|
||||
: '—'
|
||||
}
|
||||
export const jobLabels: Record<JobStatus, string> = {
|
||||
queued: '等待处理',
|
||||
running: '分析中',
|
||||
ready: '已生成 · 待人工核对',
|
||||
failed: '生成失败',
|
||||
needs_reconciliation: '调用状态待核实',
|
||||
stale: '结果已过期'
|
||||
}
|
||||
const channelLabels: Record<string, string> = {
|
||||
manual: '人工服务记录',
|
||||
im: '腾讯 IM',
|
||||
tracking: '跟踪备注',
|
||||
tracking_note: '跟踪备注',
|
||||
wecom: '企业微信',
|
||||
qywx: '企业微信',
|
||||
audio: '录音 / 转写'
|
||||
}
|
||||
export const channelLabel = (channel: string) => channelLabels[channel] || channel
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,111 @@
|
||||
import { reactive } from 'vue'
|
||||
import type { Job } from '@/api/assistantService'
|
||||
import { errorText, isCancelled } from '../shared'
|
||||
|
||||
/** 单个患者会话的任务跟踪;计时器与请求版本均由实例持有。 */
|
||||
export function createJobTracker(deps: {
|
||||
read: (id: number, signal: AbortSignal) => Promise<Job>
|
||||
now?: () => number
|
||||
setTimer?: (fn: () => void, delay: number) => ReturnType<typeof setTimeout>
|
||||
clearTimer?: (id: ReturnType<typeof setTimeout>) => void
|
||||
}) {
|
||||
const state = reactive<{ job: Job | null; error: string; paused: boolean; checking: boolean }>({
|
||||
job: null,
|
||||
error: '',
|
||||
paused: false,
|
||||
checking: false
|
||||
})
|
||||
const now = deps.now || Date.now
|
||||
const schedule = deps.setTimer || setTimeout
|
||||
const unschedule = deps.clearTimer || clearTimeout
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
let request: AbortController | undefined
|
||||
let revision = 0,
|
||||
startedAt = 0,
|
||||
active = true,
|
||||
disposed = false
|
||||
const pending = () => state.job?.status === 'queued' || state.job?.status === 'running'
|
||||
function stop() {
|
||||
if (timer !== undefined) unschedule(timer)
|
||||
timer = undefined
|
||||
request?.abort()
|
||||
request = undefined
|
||||
revision++
|
||||
state.checking = false
|
||||
}
|
||||
function next() {
|
||||
if (disposed || !active || !pending()) return
|
||||
if (now() - startedAt >= 360000) {
|
||||
state.paused = true
|
||||
state.error =
|
||||
'等待超过 6 分钟,已暂停自动查询。任务可能仍在执行,请查询状态;不要重复提交。'
|
||||
return
|
||||
}
|
||||
timer = schedule(() => {
|
||||
timer = undefined
|
||||
void refresh()
|
||||
}, 3000)
|
||||
}
|
||||
async function refresh() {
|
||||
if (!state.job || disposed || !active || state.checking) return
|
||||
if (timer !== undefined) unschedule(timer)
|
||||
timer = undefined
|
||||
const token = revision,
|
||||
id = state.job.id,
|
||||
diagnosisId = state.job.diagnosis_id,
|
||||
subjectId = state.job.subject_admin_id || 0
|
||||
request = new AbortController()
|
||||
state.checking = true
|
||||
try {
|
||||
const job = await deps.read(id, request.signal)
|
||||
if (disposed || token !== revision) return
|
||||
if (
|
||||
job.id !== id ||
|
||||
job.diagnosis_id !== diagnosisId ||
|
||||
(job.subject_admin_id || 0) !== subjectId
|
||||
)
|
||||
throw new Error('任务与当前医助或关联诊单不一致,请重新核查')
|
||||
state.job = job
|
||||
state.error = ''
|
||||
state.paused = false
|
||||
next()
|
||||
} catch (error) {
|
||||
if (disposed || token !== revision || isCancelled(error)) return
|
||||
// 查询失败时隐藏旧结果,避免撤权或来源变更后继续采纳。
|
||||
if (state.job) state.job = { ...state.job, result: null }
|
||||
state.error = errorText(error)
|
||||
state.paused = true
|
||||
} finally {
|
||||
if (token === revision) state.checking = false
|
||||
}
|
||||
}
|
||||
return {
|
||||
state,
|
||||
setJob(job: Job | null) {
|
||||
stop()
|
||||
state.job = job
|
||||
state.error = ''
|
||||
state.paused = false
|
||||
startedAt = now()
|
||||
next()
|
||||
},
|
||||
refresh() {
|
||||
startedAt = now()
|
||||
return refresh()
|
||||
},
|
||||
setActive(value: boolean) {
|
||||
if (active === value) return
|
||||
active = value
|
||||
if (!active) stop()
|
||||
else if (state.job) {
|
||||
startedAt = now()
|
||||
void refresh()
|
||||
}
|
||||
},
|
||||
dispose() {
|
||||
disposed = true
|
||||
stop()
|
||||
state.job = null
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<template>
|
||||
<label v-if="options.length > 1 || (options.length === 1 && !options[0].is_primary)" class="flex flex-wrap items-center gap-2">
|
||||
<span class="text-sm text-gray-600">订单处方</span>
|
||||
<el-select
|
||||
:model-value="modelValue || undefined"
|
||||
:disabled="disabled"
|
||||
aria-label="订单处方"
|
||||
placeholder="请选择处方"
|
||||
class="w-[270px] max-w-full"
|
||||
@change="emit('change', $event)"
|
||||
>
|
||||
<el-option
|
||||
v-for="entry in options"
|
||||
:key="entry.id"
|
||||
:value="entry.id"
|
||||
:label="`${entry.is_primary ? '业务主处方' : '关联处方'} · ${entry.sn || '#' + entry.id}${Number(entry.void_status) === 1 ? '(已作废)' : ''}`"
|
||||
/>
|
||||
</el-select>
|
||||
</label>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { LinkedPrescription } from './useLinkedOrderPrescription'
|
||||
|
||||
defineProps<{ options: LinkedPrescription[]; modelValue: number; disabled?: boolean }>()
|
||||
const emit = defineEmits<{ change: [id: number] }>()
|
||||
</script>
|
||||
@@ -402,7 +402,8 @@ const ReportList = defineComponent({
|
||||
|
||||
const models: Array<{ profile: PrescriptionAiProfile; label: string; name: string }> = [
|
||||
{ profile: 'qwen', label: '千问', name: 'qwen3.6-35b' },
|
||||
{ profile: 'openai', label: 'OpenAI', name: 'gpt-5.6-sol' }
|
||||
{ profile: 'openai', label: 'OpenAI', name: 'gpt-5.6-sol' },
|
||||
{ profile: 'doubao', label: '豆包', name: 'doubao-seed-2.1-pro' }
|
||||
]
|
||||
|
||||
const AI_REPORT_EDIT_PERMISSIONS = [
|
||||
@@ -436,7 +437,8 @@ const canRefreshFromBackend = ref(false)
|
||||
const canEditFromBackend = ref(false)
|
||||
const states = reactive<Record<PrescriptionAiProfile, ReportState>>({
|
||||
qwen: createState(),
|
||||
openai: createState()
|
||||
openai: createState(),
|
||||
doubao: createState()
|
||||
})
|
||||
|
||||
const herbSummary = computed(() => {
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
<template>
|
||||
<el-dialog
|
||||
v-model="visible"
|
||||
title="关联业务订单"
|
||||
width="min(640px, calc(100vw - 24px))"
|
||||
append-to-body
|
||||
destroy-on-close
|
||||
:close-on-click-modal="false"
|
||||
:close-on-press-escape="!binding"
|
||||
:show-close="!binding"
|
||||
>
|
||||
<p class="mb-4 text-sm text-gray-500">处方 {{ prescriptionNo }}</p>
|
||||
<section v-loading="loading && !initialized" aria-label="已关联业务订单">
|
||||
<h3 class="mb-2 text-sm font-medium">已关联订单</h3>
|
||||
<p v-if="error && !initialized" class="text-sm text-red-600" role="alert">
|
||||
加载关联订单失败。<el-button link type="primary" @click="loadOrders()">重试</el-button>
|
||||
</p>
|
||||
<el-table v-else :data="linkedOrders" size="small" max-height="280" empty-text="暂无关联订单">
|
||||
<el-table-column label="业务订单号" prop="order_no" min-width="155" />
|
||||
<el-table-column label="履约状态" min-width="90">
|
||||
<template #default="{ row }">{{ fulfillmentText(row.fulfillment_status) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="处方关系" min-width="95">
|
||||
<template #default="{ row }">{{ row.is_primary ? '业务主处方' : '关联处方' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column v-if="canViewDetails" label="操作" width="64" fixed="right">
|
||||
<template #default="{ row }">
|
||||
<el-button link type="primary" :disabled="binding" @click="viewOrder(row)">详情</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</section>
|
||||
<section v-if="canBind" class="mt-5 border-t border-gray-100 pt-4" aria-label="绑定现有业务订单">
|
||||
<h3 class="mb-2 text-sm font-medium">绑定现有业务订单</h3>
|
||||
<p class="mb-3 text-sm text-gray-500">可绑定同一患者的订单,原处方须已作废或处方审核已驳回。</p>
|
||||
<el-select
|
||||
v-model="selectedOrderId"
|
||||
class="w-full"
|
||||
aria-label="选择要绑定的业务订单"
|
||||
placeholder="搜索订单号或选择订单"
|
||||
filterable
|
||||
remote
|
||||
clearable
|
||||
:remote-method="searchOrders"
|
||||
:loading="loading"
|
||||
:disabled="binding"
|
||||
:no-data-text="error ? '加载失败,请重新搜索' : '未找到原处方已作废或处方审核已驳回的订单'"
|
||||
>
|
||||
<el-option
|
||||
v-for="order in candidates"
|
||||
:key="order.id"
|
||||
:value="order.id"
|
||||
:label="`${order.order_no} · ${fulfillmentText(order.fulfillment_status)}`"
|
||||
/>
|
||||
</el-select>
|
||||
</section>
|
||||
<template #footer>
|
||||
<el-button :disabled="binding" @click="visible = false">关闭</el-button>
|
||||
<el-button
|
||||
v-if="canBind"
|
||||
type="primary"
|
||||
:loading="binding"
|
||||
:disabled="loading || !selectedOrderId"
|
||||
@click="bindOrder"
|
||||
>绑定订单</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onScopeDispose, ref, watch } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { prescriptionOrderBindPrescription, prescriptionOrdersForBinding, type PrescriptionBindingOrder } from '@/api/tcm'
|
||||
import feedback from '@/utils/feedback'
|
||||
import { hasPermission } from '@/utils/perm'
|
||||
import { fulfillmentText } from './prescription-order-utils'
|
||||
|
||||
const emit = defineEmits<{ bound: [] }>()
|
||||
const router = useRouter()
|
||||
const visible = ref(false)
|
||||
const loading = ref(false)
|
||||
const initialized = ref(false)
|
||||
const error = ref(false)
|
||||
const binding = ref(false)
|
||||
const prescriptionId = ref(0)
|
||||
const prescriptionNo = ref('')
|
||||
const linkedOrders = ref<PrescriptionBindingOrder[]>([])
|
||||
const candidates = ref<PrescriptionBindingOrder[]>([])
|
||||
const selectedOrderId = ref<number>()
|
||||
const bindingAllowed = ref(false)
|
||||
const canBind = computed(() => bindingAllowed.value && hasPermission([
|
||||
'tcm.prescriptionOrder/prescriptionOrdersForBinding', 'tcm.prescriptionOrder/bindPrescription'
|
||||
]))
|
||||
const orderListRoute = computed(() => router.getRoutes().find((r) => r.meta?.perms === 'tcm.prescriptionOrder/lists'))
|
||||
const canViewDetails = computed(() => Boolean(orderListRoute.value) && hasPermission(['tcm.prescriptionOrder/detail']))
|
||||
let activeRequest: AbortController | undefined
|
||||
|
||||
function open(row: { id: number; sn?: string }) {
|
||||
const id = Number(row.id)
|
||||
if (!Number.isSafeInteger(id) || id <= 0 || binding.value) return
|
||||
prescriptionId.value = id
|
||||
prescriptionNo.value = row.sn || `#${id}`
|
||||
linkedOrders.value = []
|
||||
candidates.value = []
|
||||
selectedOrderId.value = undefined
|
||||
bindingAllowed.value = false
|
||||
initialized.value = false
|
||||
visible.value = true
|
||||
void loadOrders()
|
||||
}
|
||||
|
||||
async function loadOrders(query = '') {
|
||||
activeRequest?.abort()
|
||||
const request = new AbortController()
|
||||
activeRequest = request
|
||||
loading.value = true
|
||||
error.value = false
|
||||
const orderNo = query.trim()
|
||||
|
||||
try {
|
||||
const result = await prescriptionOrdersForBinding(
|
||||
{ prescription_id: prescriptionId.value, ...(orderNo ? { order_no: orderNo } : {}) },
|
||||
request.signal
|
||||
)
|
||||
if (request.signal.aborted) return
|
||||
if (!orderNo) linkedOrders.value = result.orders.filter((order) => order.is_linked)
|
||||
candidates.value = result.orders.filter((order) => !order.is_linked)
|
||||
bindingAllowed.value = result.can_bind
|
||||
if (!candidates.value.some((order) => order.id === selectedOrderId.value)) selectedOrderId.value = undefined
|
||||
initialized.value = true
|
||||
} catch {
|
||||
if (request.signal.aborted) return
|
||||
candidates.value = []
|
||||
selectedOrderId.value = undefined
|
||||
error.value = true
|
||||
} finally {
|
||||
if (!request.signal.aborted) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function searchOrders(query: string) {
|
||||
if (canBind.value && !binding.value) void loadOrders(query)
|
||||
}
|
||||
|
||||
async function bindOrder() {
|
||||
const selected = candidates.value.find((order) => order.id === selectedOrderId.value)
|
||||
if (!selected || !canBind.value || loading.value || binding.value) return
|
||||
|
||||
binding.value = true
|
||||
try {
|
||||
await prescriptionOrderBindPrescription({ id: selected.id, prescription_id: prescriptionId.value })
|
||||
linkedOrders.value.unshift({ ...selected, is_linked: true })
|
||||
feedback.msgSuccess('业务订单已绑定')
|
||||
selectedOrderId.value = undefined
|
||||
emit('bound')
|
||||
await loadOrders()
|
||||
} catch {
|
||||
// 请求拦截器显示失败原因。
|
||||
} finally {
|
||||
binding.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function viewOrder(order: PrescriptionBindingOrder) {
|
||||
const path = orderListRoute.value?.path
|
||||
if (!path || !canViewDetails.value) return
|
||||
visible.value = false
|
||||
void router.push({ path, query: { review_order: order.id, review_prescription: prescriptionId.value } })
|
||||
}
|
||||
|
||||
watch(visible, (show) => {
|
||||
if (!show) activeRequest?.abort()
|
||||
}, { flush: 'sync' })
|
||||
onScopeDispose(() => activeRequest?.abort())
|
||||
|
||||
defineExpose({ open })
|
||||
</script>
|
||||
+125
-109
@@ -42,7 +42,7 @@
|
||||
</div>
|
||||
<div v-if="detailData" class="flex items-center gap-2 mr-6">
|
||||
<!-- 完整版:处方审核 / 支付审核 / 发货 / 退款等操作按钮 -->
|
||||
<slot name="header-actions" :detail="detailData" />
|
||||
<slot name="header-actions" :detail="detailData" :is-primary-prescription="isPrimaryPrescription" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -201,22 +201,22 @@
|
||||
<!-- 左侧:处方单 -->
|
||||
<el-card shadow="never" class="po-panel po-panel-rx border-gray-100 h-full relative overflow-hidden">
|
||||
<!-- 处方审核印章 -->
|
||||
<div v-if="detailData.prescription_audit_status === 1" class="audit-stamp stamp-pass">
|
||||
<div v-if="isPrimaryPrescription && detailData.prescription_audit_status === 1" class="audit-stamp stamp-pass">
|
||||
<div class="stamp-inner">审核通过</div>
|
||||
</div>
|
||||
<div v-if="detailData.prescription_audit_status === 2" class="audit-stamp stamp-reject">
|
||||
<div v-if="isPrimaryPrescription && detailData.prescription_audit_status === 2" class="audit-stamp stamp-reject">
|
||||
<div class="stamp-inner">已驳回</div>
|
||||
</div>
|
||||
<template #header>
|
||||
<div class="flex items-center justify-between">
|
||||
<div class="flex items-center gap-3">
|
||||
<span class="font-medium text-[15px]">处方详情</span>
|
||||
<span v-if="detailData.doctor_name" class="text-xs text-gray-500">
|
||||
开方人:<span class="text-primary font-medium">{{ detailData.doctor_name }}</span>
|
||||
<span v-if="detailPrescriptionDoctor" class="text-xs text-gray-500">
|
||||
开方人:<span class="text-primary font-medium">{{ detailPrescriptionDoctor }}</span>
|
||||
</span>
|
||||
<el-button
|
||||
v-if="
|
||||
!readonly &&
|
||||
!readonly && isPrimaryPrescription &&
|
||||
detailData.prescription_id &&
|
||||
detailPrescription &&
|
||||
!String(detailData.prescription_detail_error || '').trim()
|
||||
@@ -230,16 +230,17 @@
|
||||
改患者信息
|
||||
</el-button>
|
||||
<el-button
|
||||
v-if="!readonly && detailData.prescription_id && showPrescriptionAuditFilter"
|
||||
v-if="!readonly && selectedPrescriptionId && showPrescriptionAuditFilter"
|
||||
type="primary"
|
||||
size="small"
|
||||
link
|
||||
@click="emit('view-prescription')"
|
||||
:disabled="linkedPrescriptionLoading"
|
||||
@click="emit('view-prescription', selectedPrescriptionId)"
|
||||
>
|
||||
详细
|
||||
</el-button>
|
||||
<el-button
|
||||
v-if="!readonly && detailData.id && showPrescriptionAuditFilter"
|
||||
v-if="!readonly && isPrimaryPrescription && detailData.id && showPrescriptionAuditFilter"
|
||||
type="warning"
|
||||
size="small"
|
||||
link
|
||||
@@ -250,17 +251,26 @@
|
||||
测试价格
|
||||
</el-button>
|
||||
</div>
|
||||
<span class="text-xs text-gray-400">ID: {{ detailData.prescription_id || '—' }}</span>
|
||||
<span class="text-xs text-gray-400">ID: {{ selectedPrescriptionId || '—' }}</span>
|
||||
</div>
|
||||
</template>
|
||||
<LinkedOrderPrescriptionSelect
|
||||
:options="linkedPrescriptionOptions"
|
||||
:model-value="selectedPrescriptionId"
|
||||
class="mb-3"
|
||||
@change="selectLinkedPrescription"
|
||||
/>
|
||||
<el-skeleton v-if="linkedPrescriptionLoading" :rows="5" animated />
|
||||
<el-alert
|
||||
v-if="!readonly && String(detailData.prescription_detail_error || '').trim()"
|
||||
:title="detailData.prescription_detail_error"
|
||||
v-else-if="(!readonly || !isPrimaryPrescription) && selectedPrescriptionError"
|
||||
:title="selectedPrescriptionError"
|
||||
type="warning"
|
||||
:closable="false"
|
||||
show-icon
|
||||
class="mb-3"
|
||||
/>
|
||||
>
|
||||
<el-button v-if="!isPrimaryPrescription" link type="primary" @click="selectLinkedPrescription(selectedPrescriptionId)">重试</el-button>
|
||||
</el-alert>
|
||||
<template v-else-if="detailPrescription">
|
||||
<el-descriptions :column="2" border size="small" class="po-desc bg-white">
|
||||
<el-descriptions-item label="处方编号" :span="2">{{ detailPrescription.sn || '—' }}</el-descriptions-item>
|
||||
@@ -271,13 +281,13 @@
|
||||
<el-descriptions-item label="手机">
|
||||
<span
|
||||
:class="
|
||||
detailRecipientRxPhoneMismatch ? 'rx-phone-mismatch text-red-600 font-bold' : ''
|
||||
isPrimaryPrescription && detailRecipientRxPhoneMismatch ? 'rx-phone-mismatch text-red-600 font-bold' : ''
|
||||
"
|
||||
>
|
||||
{{ detailPrescription.phone || '—' }}
|
||||
</span>
|
||||
<el-tag
|
||||
v-if="detailRecipientRxPhoneMismatch"
|
||||
v-if="isPrimaryPrescription && detailRecipientRxPhoneMismatch"
|
||||
type="danger"
|
||||
size="small"
|
||||
effect="dark"
|
||||
@@ -293,7 +303,8 @@
|
||||
{{ detailPrescription.clinical_diagnosis || '—' }}
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="剂数 / 用法" :span="2" v-if="showPrescriptionAuditFilter">
|
||||
{{ detailData.dose_count ?? detailPrescription.dose_count ?? '—' }} {{ detailData.dose_unit || '剂' }} ·
|
||||
{{ (isPrimaryPrescription ? detailData.dose_count ?? detailPrescription.dose_count : detailPrescription.dose_count) ?? '—' }}
|
||||
{{ (isPrimaryPrescription ? detailData.dose_unit : detailPrescription.dose_unit) || '剂' }} ·
|
||||
{{ detailPrescription.usage_instruction || detailPrescription.usage_method || '—' }}
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="处方金额">
|
||||
@@ -313,7 +324,7 @@
|
||||
<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-if="!readonly && isPrimaryPrescription && detailData.prescription_id && !selectedPrescriptionError"
|
||||
v-perms="['tcm.prescriptionOrder/patchPrescriptionUsage']"
|
||||
type="primary"
|
||||
size="small"
|
||||
@@ -337,7 +348,7 @@
|
||||
<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-if="!readonly && isPrimaryPrescription && detailData.prescription_id && !selectedPrescriptionError"
|
||||
v-perms="['tcm.prescriptionOrder/patchPrescriptionUsage']"
|
||||
type="primary"
|
||||
size="small"
|
||||
@@ -362,7 +373,7 @@
|
||||
<span>服用方式</span>
|
||||
<el-button
|
||||
v-if="
|
||||
!readonly &&
|
||||
!readonly && isPrimaryPrescription &&
|
||||
detailData.prescription_id &&
|
||||
detailPrescription &&
|
||||
!String(detailData.prescription_detail_error || '').trim()
|
||||
@@ -416,7 +427,7 @@
|
||||
}}
|
||||
</div>
|
||||
</template>
|
||||
<div>
|
||||
<div v-if="isPrimaryPrescription">
|
||||
<span class="text-gray-500">订单设置:</span>
|
||||
{{
|
||||
detailData.medication_days != null &&
|
||||
@@ -500,6 +511,17 @@
|
||||
{{ formatOrderTime(row.create_time) }}
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column v-if="!readonly && canAttachReceipt" label="操作" width="86" fixed="right" align="center">
|
||||
<template #default="{ row }">
|
||||
<el-button
|
||||
link
|
||||
type="primary"
|
||||
:loading="linkingReceiptId === Number(row.id)"
|
||||
:disabled="changingReceipts"
|
||||
@click="confirmAttachReceipt(row)"
|
||||
>关联</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
<el-empty v-else description="无未关联的收款单" :image-size="60" />
|
||||
</el-card>
|
||||
@@ -563,16 +585,15 @@
|
||||
{{ formatOrderTime(row.create_time) }}
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column v-if="canUnlinkPayOrder" label="操作" width="80" fixed="right" align="center">
|
||||
<el-table-column v-if="!readonly && canUnlinkReceipt" label="操作" width="80" fixed="right" align="center">
|
||||
<template #default="{ row }">
|
||||
<el-button
|
||||
type="danger"
|
||||
size="small"
|
||||
link
|
||||
:loading="unlinkPayOrderId === Number(row.id)"
|
||||
:disabled="unlinkPayOrderId !== null || ![2, 5].includes(Number(row.status))"
|
||||
:title="Number(row.status) === 4 ? '已退款收款记录不可移除' : '解除关联并更新已付金额,总金额不变'"
|
||||
@click="confirmUnlinkPayOrder(row)"
|
||||
:loading="unlinkingReceiptId === Number(row.id)"
|
||||
:disabled="changingReceipts || ![2, 4, 5].includes(Number(row.status))"
|
||||
@click="confirmUnlinkReceipt(row)"
|
||||
>移除</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
@@ -964,6 +985,22 @@
|
||||
:rules="patchUsageRules"
|
||||
label-width="108px"
|
||||
>
|
||||
<el-alert
|
||||
v-if="usageFrozenBySignature"
|
||||
type="warning"
|
||||
:closable="false"
|
||||
show-icon
|
||||
class="mb-3"
|
||||
title="处方已电子签署:此处修改只作用于本订单的页面与药房下单,CA 签署的处方原件不变。"
|
||||
/>
|
||||
<el-alert
|
||||
v-if="daysLocked"
|
||||
type="info"
|
||||
:closable="false"
|
||||
show-icon
|
||||
class="mb-3"
|
||||
title="订单已发货,服用天数不可修改;次数、袋数仍可修改。"
|
||||
/>
|
||||
<div v-if="detailHasAuxHerbs" class="text-xs font-medium text-gray-500 mb-3">主方</div>
|
||||
<el-form-item
|
||||
v-if="detailPrescription?.prescription_type === '浓缩水丸'"
|
||||
@@ -988,6 +1025,7 @@
|
||||
<div class="flex items-center gap-1 w-full">
|
||||
<el-input-number
|
||||
v-model="patchUsageForm.usage_days"
|
||||
:disabled="daysLocked"
|
||||
:min="1"
|
||||
:max="999"
|
||||
:step="1"
|
||||
@@ -1022,6 +1060,7 @@
|
||||
<div class="flex items-center gap-1 w-full">
|
||||
<el-input-number
|
||||
v-model="patchUsageForm.aux_usage_days"
|
||||
:disabled="daysLocked"
|
||||
:min="1"
|
||||
:max="999"
|
||||
:step="1"
|
||||
@@ -1037,6 +1076,7 @@
|
||||
<div class="flex items-center gap-1 w-full">
|
||||
<el-input-number
|
||||
v-model="patchUsageForm.medication_days"
|
||||
:disabled="daysLocked"
|
||||
:min="1"
|
||||
:max="999"
|
||||
:step="1"
|
||||
@@ -1066,13 +1106,14 @@ import {
|
||||
prescriptionOrderAddLog,
|
||||
prescriptionOrderLogisticsTrace,
|
||||
prescriptionOrderLogisticsJdUpdate,
|
||||
prescriptionOrderPaidPayOrders,
|
||||
prescriptionOrderUnlinkPayOrder,
|
||||
prescriptionOrderPatchPrescriptionUsage
|
||||
} from '@/api/tcm'
|
||||
import { getDictData } from '@/api/app'
|
||||
import feedback from '@/utils/feedback'
|
||||
import useUserStore from '@/stores/modules/user'
|
||||
import LinkedOrderPrescriptionSelect from './LinkedOrderPrescriptionSelect.vue'
|
||||
import { useLinkedOrderPrescription } from './useLinkedOrderPrescription'
|
||||
import { usePrescriptionOrderReceipts } from './usePrescriptionOrderReceipts'
|
||||
import {
|
||||
TCM_ASSISTANT_ROLE_ID,
|
||||
PRESCRIPTION_AUDIT_ROLE_IDS,
|
||||
@@ -1130,13 +1171,13 @@ defineSlots<{
|
||||
/** 抽屉头部左侧扩展(完整版的发货类型切换等) */
|
||||
'header-extra'?: (props: { detail: any }) => any
|
||||
/** 抽屉头部右侧操作按钮(审核/发货/退款等) */
|
||||
'header-actions'?: (props: { detail: any }) => any
|
||||
'header-actions'?: (props: { detail: any; isPrimaryPrescription: boolean }) => any
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'update-amount'): void
|
||||
(e: 'patch-rx-patient'): void
|
||||
(e: 'view-prescription'): void
|
||||
(e: 'view-prescription', prescriptionId: number): void
|
||||
(e: 'test-gancao-preview'): void
|
||||
(e: 'view-patient'): void
|
||||
(e: 'detail-changed'): void
|
||||
@@ -1159,46 +1200,35 @@ const showPrescriptionAuditFilter = computed(() => {
|
||||
const detailVisible = ref(false)
|
||||
const detailLoading = ref(false)
|
||||
const detailData = ref<Record<string, any> | null>(null)
|
||||
const detailLogs = ref<any[]>([])
|
||||
const detailUnlinkedPayOrders = ref<any[]>([])
|
||||
const unlinkPayOrderId = ref<number | null>(null)
|
||||
const canUnlinkPayOrder = computed(() =>
|
||||
!props.readonly && canUpdateAmount(detailData.value) && hasPerm('tcm.prescriptionOrder/unlinkPayOrder')
|
||||
const {
|
||||
options: linkedPrescriptionOptions,
|
||||
selectedId: selectedPrescriptionId,
|
||||
isPrimary: isPrimaryPrescription,
|
||||
prescription: detailPrescription,
|
||||
loading: linkedPrescriptionLoading,
|
||||
detailError: selectedPrescriptionError,
|
||||
herbsVisible: detailHerbsVisible,
|
||||
reset: resetLinkedPrescription,
|
||||
select: selectLinkedPrescription
|
||||
} = useLinkedOrderPrescription(detailData, detailVisible, computed(() => !props.detailLoader))
|
||||
const detailPrescriptionDoctor = computed(() =>
|
||||
isPrimaryPrescription.value ? detailData.value?.doctor_name : detailPrescription.value?.doctor_name
|
||||
)
|
||||
|
||||
async function confirmUnlinkPayOrder(row: { id: number; order_no?: string; amount: number | string; status: number | string }) {
|
||||
const orderId = Number(detailData.value?.id)
|
||||
const payOrderId = Number(row.id)
|
||||
if (!canUnlinkPayOrder.value || !orderId || !payOrderId || unlinkPayOrderId.value !== null) return
|
||||
if (![2, 5].includes(Number(row.status))) return
|
||||
|
||||
unlinkPayOrderId.value = payOrderId
|
||||
try {
|
||||
await feedback.confirm(
|
||||
`确定移除收款记录「${row.order_no || '#' + payOrderId}」(¥${formatMoney(row.amount)})?` +
|
||||
'仅解除关联,原收款记录保留;订单总金额不变,已付金额与需代收金额按剩余关联收款重新计算。'
|
||||
)
|
||||
if (!detailVisible.value || Number(detailData.value?.id) !== orderId) return
|
||||
const res: any = await prescriptionOrderUnlinkPayOrder({ id: orderId, pay_order_id: payOrderId })
|
||||
const updated = res?.data ?? res
|
||||
if (Number(detailData.value?.id) === orderId && Number(updated?.id) === orderId) {
|
||||
Object.assign(detailData.value!, updated)
|
||||
}
|
||||
feedback.msgSuccess('收款关联已移除,金额已同步更新')
|
||||
emit('detail-changed')
|
||||
await refreshIfCurrent(orderId)
|
||||
} catch {
|
||||
/* 取消不提交;接口错误由拦截器提示,保留当前收款记录 */
|
||||
} finally {
|
||||
unlinkPayOrderId.value = null
|
||||
}
|
||||
}
|
||||
|
||||
const detailPrescription = computed(() => {
|
||||
const p = detailData.value?.prescription
|
||||
return p && typeof p === 'object' ? p : null
|
||||
const detailLogs = ref<any[]>([])
|
||||
const {
|
||||
unlinkedReceipts: detailUnlinkedPayOrders,
|
||||
loadUnlinkedReceipts,
|
||||
linkingReceiptId,
|
||||
unlinkingReceiptId,
|
||||
changingReceipts,
|
||||
canAttachReceipt,
|
||||
canUnlinkReceipt,
|
||||
confirmAttachReceipt,
|
||||
confirmUnlinkReceipt
|
||||
} = usePrescriptionOrderReceipts(detailData, detailVisible, (orderId) => {
|
||||
emit('detail-changed')
|
||||
if (detailVisible.value && Number(detailData.value?.id) === orderId) void fetchLogs(orderId)
|
||||
})
|
||||
|
||||
const detailDietaryText = computed(() => formatDietaryTaboo(detailPrescription.value?.dietary_taboo))
|
||||
|
||||
const detailLinkedPayOrders = computed(() => {
|
||||
@@ -1275,13 +1305,13 @@ const workflowFulfillStatus = computed(() => {
|
||||
|
||||
/** 详情抽屉:业务收货手机 vs 处方登记手机 */
|
||||
const detailRecipientRxPhoneMismatch = computed(() => {
|
||||
const rx = detailPrescription.value?.phone
|
||||
const rx = detailData.value?.prescription?.phone
|
||||
const biz = detailData.value?.recipient_phone
|
||||
return recipientVsPrescriptionPhoneMismatch(biz, rx)
|
||||
})
|
||||
|
||||
const detailPrescriptionPhoneDisplay = computed(() => {
|
||||
const s = normalizeBizPhone(detailPrescription.value?.phone)
|
||||
const s = normalizeBizPhone(detailData.value?.prescription?.phone)
|
||||
return s || '—'
|
||||
})
|
||||
|
||||
@@ -1353,7 +1383,14 @@ const detailLinkedAppointmentChannelText = computed(() => {
|
||||
|
||||
const detailRxHerbs = computed(() => normalizeSlipHerbs(detailPrescription.value?.herbs))
|
||||
|
||||
const detailHasAuxHerbs = computed(() => prescriptionHasAuxFormula(detailPrescription.value as any))
|
||||
const detailHasAuxHerbs = computed(() => prescriptionHasAuxFormula(detailPrescription.value as any))
|
||||
/** 已发货的订单服用天数锁定(服务端 days_locked,同样拦截保存) */
|
||||
const daysLocked = computed(() => detailData.value?.days_locked === true)
|
||||
/** 处方已进入电子签署(内容冻结),服用参数改写为订单级覆盖值 */
|
||||
const usageFrozenBySignature = computed(() => {
|
||||
const esign = detailData.value?.prescription?.esign
|
||||
return esign?.required === true && esign?.status !== 'pending'
|
||||
})
|
||||
|
||||
/** 详情:辅方用法(aux_usage JSON 经规范化后的对象,与处方类型一致) */
|
||||
const detailAuxUsage = computed(() => {
|
||||
@@ -1364,9 +1401,6 @@ const detailAuxUsage = computed(() => {
|
||||
return normalizeSlipAuxUsageForm(raw, rx.prescription_type || '浓缩水丸')
|
||||
})
|
||||
|
||||
/** false=无权限;true/缺省兼容旧接口(旧版未下发该字段时仍展示药材) */
|
||||
const detailHerbsVisible = computed(() => detailData.value?.prescription_detail_herbs_visible !== false)
|
||||
|
||||
/** 内部成本(财务字段):仅完整版展示 */
|
||||
const showInternalCost = computed(
|
||||
() => !props.readonly && detailData.value?.internal_cost != null && detailData.value?.internal_cost !== ''
|
||||
@@ -1440,6 +1474,9 @@ function canAddPrescriptionOrderLog() {
|
||||
|
||||
/** 与后端 canAuditPrescriptionOrder 同档:超管或 prescription_audit_roles */
|
||||
const canSetRxAuditOnAddLog = computed(() => {
|
||||
if (!isPrimaryPrescription.value) return false
|
||||
if (Number(detailData.value?.prescription_audit_status) === 0
|
||||
&& detailData.value?.can_review_prescription === false) return false
|
||||
const u = userStore.userInfo
|
||||
if (!u || Number(u.root) === 1) return true
|
||||
const ids = Array.isArray(u.role_ids) ? u.role_ids.map((n: unknown) => Number(n)) : []
|
||||
@@ -1506,6 +1543,7 @@ function openPatchUsageDialog() {
|
||||
feedback.msgWarning('无处方数据')
|
||||
return
|
||||
}
|
||||
if (rx.id && Number(rx.id) !== Number(ord.prescription_id)) 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 =
|
||||
@@ -1640,28 +1678,6 @@ async function submitAddLog() {
|
||||
}
|
||||
}
|
||||
|
||||
// ─── 未关联支付单 ───
|
||||
async function loadDetailUnlinkedPayOrders(diagnosisId: number, prescriptionOrderId: number, linkedIds: number[]) {
|
||||
if (!diagnosisId) {
|
||||
detailUnlinkedPayOrders.value = []
|
||||
return
|
||||
}
|
||||
try {
|
||||
const res: any = await prescriptionOrderPaidPayOrders({
|
||||
diagnosis_id: diagnosisId,
|
||||
prescription_order_id: prescriptionOrderId
|
||||
})
|
||||
const lists = res?.lists ?? res?.data?.lists ?? []
|
||||
// 列表已由服务端限制;此处再过滤已关联项
|
||||
const filtered = Array.isArray(lists)
|
||||
? lists.filter((item: any) => !linkedIds.includes(item.id))
|
||||
: []
|
||||
detailUnlinkedPayOrders.value = filtered
|
||||
} catch {
|
||||
detailUnlinkedPayOrders.value = []
|
||||
}
|
||||
}
|
||||
|
||||
// ─── 物流轨迹 ───
|
||||
const detailLogisticsExpress = ref<string>('auto')
|
||||
const logisticsTraceLoading = ref(false)
|
||||
@@ -1767,11 +1783,15 @@ function requestDetail(id: number) {
|
||||
return props.detailLoader ? props.detailLoader({ id }) : prescriptionOrderDetail({ id })
|
||||
}
|
||||
|
||||
async function open(id: number) {
|
||||
let detailOpenRequest = 0
|
||||
|
||||
async function open(id: number, prescriptionId?: number) {
|
||||
const request = ++detailOpenRequest
|
||||
// 页面级同参数字典请求会取消抽屉挂载时的那次(axios 去重取消),打开时兜底重试
|
||||
void loadServicePackageOptions()
|
||||
// 显式彻底清空缓存,防止前一次弹窗的数据残留
|
||||
detailData.value = null
|
||||
resetLinkedPrescription()
|
||||
detailUnlinkedPayOrders.value = []
|
||||
bumpLogisticsTraceRequestToken()
|
||||
detailLogisticsExpress.value = 'auto'
|
||||
@@ -1782,6 +1802,7 @@ async function open(id: number) {
|
||||
detailLoading.value = true
|
||||
try {
|
||||
const res: any = await requestDetail(id)
|
||||
if (request !== detailOpenRequest || !detailVisible.value) return
|
||||
const d = res?.data ?? res ?? null
|
||||
detailData.value = d
|
||||
if (d) {
|
||||
@@ -1793,29 +1814,27 @@ async function open(id: number) {
|
||||
}
|
||||
if (props.loadRelatedData) fetchLogs(id)
|
||||
|
||||
// 加载未关联的支付单
|
||||
const diagId = d.diagnosis_id
|
||||
const linkedIds = d.pay_order_ids || []
|
||||
if (props.loadRelatedData && diagId) {
|
||||
void loadDetailUnlinkedPayOrders(diagId, id, linkedIds)
|
||||
}
|
||||
if (props.loadRelatedData) void loadUnlinkedReceipts(d)
|
||||
if (prescriptionId) void selectLinkedPrescription(prescriptionId)
|
||||
}
|
||||
} catch (e: any) {
|
||||
if (request !== detailOpenRequest || !detailVisible.value) return
|
||||
feedback.msgError(e?.message || '加载失败')
|
||||
detailVisible.value = false
|
||||
} finally {
|
||||
detailLoading.value = false
|
||||
if (request === detailOpenRequest) detailLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** 静默刷新当前详情(含日志/未关联支付单;快递单号变化时重拉轨迹),供父页面操作成功后调用 */
|
||||
async function refresh() {
|
||||
const id = Number(detailData.value?.id)
|
||||
const current = detailData.value
|
||||
const id = Number(current?.id)
|
||||
if (!id) return
|
||||
try {
|
||||
const res: any = await requestDetail(id)
|
||||
const d = res?.data ?? res ?? null
|
||||
if (!d) return
|
||||
if (!d || detailData.value !== current) return
|
||||
const prevTracking = String(detailData.value?.tracking_number || '').trim()
|
||||
detailData.value = d
|
||||
const nextTracking = String(d.tracking_number || '').trim()
|
||||
@@ -1825,10 +1844,7 @@ async function refresh() {
|
||||
void fetchLogisticsTrace()
|
||||
}
|
||||
if (props.loadRelatedData) await fetchLogs(id)
|
||||
const diagId = d.diagnosis_id
|
||||
if (props.loadRelatedData && diagId) {
|
||||
void loadDetailUnlinkedPayOrders(diagId, id, d.pay_order_ids || [])
|
||||
}
|
||||
if (props.loadRelatedData) void loadUnlinkedReceipts(d)
|
||||
} catch {
|
||||
/* 静默失败,避免打断当前抽屉 */
|
||||
}
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import type { PrescriptionEsignStatus } from '@/api/tcm'
|
||||
|
||||
const doctorSigningStatus = {
|
||||
pending: { label: '待医师签署', type: 'warning' },
|
||||
authenticating: { label: '待医师确认签署', type: 'warning' },
|
||||
signing: { label: '医师签署中', type: 'primary' },
|
||||
failed: { label: '医师签署未完成', type: 'danger' },
|
||||
uncertain: { label: '医师签署待核实', type: 'warning' }
|
||||
} as const
|
||||
|
||||
const pharmacistSigningStatus = {
|
||||
pending: { label: '待药师签署', type: 'warning' },
|
||||
signing: { label: '药师签署中', type: 'primary' },
|
||||
verifying: { label: '药师验签中', type: 'primary' },
|
||||
failed: { label: '药师签署未完成', type: 'danger' },
|
||||
uncertain: { label: '药师签署待核实', type: 'warning' },
|
||||
signed: { label: '已完成双签', type: 'success' }
|
||||
} as const
|
||||
|
||||
const unknownSigningStatus = { label: '签署状态待核实', type: 'warning' } as const
|
||||
|
||||
export function prescriptionListSigningStatus(row: {
|
||||
void_status?: number | string
|
||||
esign?: PrescriptionEsignStatus | null
|
||||
}) {
|
||||
const { esign } = row
|
||||
if (Number(row.void_status) === 1 || esign?.status === 'voided') {
|
||||
return { label: '已作废', type: 'danger' } as const
|
||||
}
|
||||
if (esign?.required && esign.awaiting_upload === true && esign.status !== 'signed') {
|
||||
return { label: '上传后签署', type: 'info' } as const
|
||||
}
|
||||
|
||||
switch (esign?.status) {
|
||||
case 'pending':
|
||||
case 'authenticating':
|
||||
case 'signing':
|
||||
case 'failed':
|
||||
case 'uncertain':
|
||||
return doctorSigningStatus[esign.status]
|
||||
case 'legacy':
|
||||
return { label: '历史处方', type: 'info' } as const
|
||||
case 'signed': {
|
||||
if (esign.can_download !== true) return doctorSigningStatus.uncertain
|
||||
if (esign.awaiting_upload === true) return { label: '医师已签署', type: 'success' } as const
|
||||
if (esign.review_state !== undefined) {
|
||||
return pharmacistSigningStatus[esign.review_state] ?? unknownSigningStatus
|
||||
}
|
||||
const pharmacistSignedAt = esign.review_signature_time ?? 0
|
||||
if (Number.isInteger(pharmacistSignedAt) && pharmacistSignedAt > 0) {
|
||||
return pharmacistSigningStatus.signed
|
||||
}
|
||||
return esign.review_required === true
|
||||
? pharmacistSigningStatus.pending
|
||||
: { label: '医师已签署', type: 'success' } as const
|
||||
}
|
||||
default:
|
||||
return unknownSigningStatus
|
||||
}
|
||||
}
|
||||
@@ -168,6 +168,7 @@ export function logActionText(act: string) {
|
||||
ship: '确认发货',
|
||||
withdraw: '撤销',
|
||||
link_pay_order: '关联支付单',
|
||||
bind_prescription: '绑定关联处方',
|
||||
unlink_pay_order: '移除收款关联',
|
||||
completion_request: '完单申请',
|
||||
auto_complete: '自动完成',
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import { computed, onScopeDispose, ref, watch, type Ref } from 'vue'
|
||||
import { prescriptionOrderDetail } from '@/api/tcm'
|
||||
|
||||
export interface LinkedPrescription {
|
||||
id: number
|
||||
sn: string
|
||||
void_status: number
|
||||
is_primary: boolean
|
||||
}
|
||||
|
||||
export type OrderDetail = Record<string, any>
|
||||
|
||||
export function linkedPrescriptionOptions(order: OrderDetail | null): LinkedPrescription[] {
|
||||
const entries: LinkedPrescription[] = Array.isArray(order?.linked_prescriptions) ? order.linked_prescriptions : []
|
||||
return entries.map((entry) => ({
|
||||
...entry,
|
||||
id: Number(entry.id),
|
||||
is_primary: Number(entry.id) === Number(order?.prescription_id)
|
||||
}))
|
||||
}
|
||||
|
||||
export async function loadLinkedOrderPrescription(orderId: number, prescriptionId: number, signal: AbortSignal) {
|
||||
const response = await prescriptionOrderDetail({ id: orderId, prescription_id: prescriptionId }, signal)
|
||||
const detail = response?.data ?? response
|
||||
if (Number(detail?.id) !== orderId || Number(detail?.prescription?.id) !== prescriptionId) {
|
||||
throw new Error(detail?.prescription_detail_error || '无法加载处方详情')
|
||||
}
|
||||
return detail as OrderDetail
|
||||
}
|
||||
|
||||
export function useLinkedOrderPrescription(
|
||||
order: Ref<OrderDetail | null>,
|
||||
visible: Ref<boolean>,
|
||||
enabled?: Ref<boolean>
|
||||
) {
|
||||
const options = computed(() => enabled?.value === false ? [] : linkedPrescriptionOptions(order.value))
|
||||
const linkedId = ref(0)
|
||||
const selectedId = computed(() => linkedId.value || Number(order.value?.prescription_id) || 0)
|
||||
const isPrimary = computed(() => linkedId.value === 0)
|
||||
const linkedDetail = ref<OrderDetail | null>(null)
|
||||
const loading = ref(false)
|
||||
const error = ref('')
|
||||
const prescription = computed(() => isPrimary.value ? order.value?.prescription : linkedDetail.value?.prescription)
|
||||
const detailError = computed(() => isPrimary.value ? String(order.value?.prescription_detail_error || '').trim() : error.value)
|
||||
const herbsVisible = computed(() => (isPrimary.value ? order.value : linkedDetail.value)?.prescription_detail_herbs_visible !== false)
|
||||
let activeRequest: AbortController | undefined
|
||||
|
||||
function reset() {
|
||||
activeRequest?.abort()
|
||||
linkedId.value = 0
|
||||
linkedDetail.value = null
|
||||
loading.value = false
|
||||
error.value = ''
|
||||
}
|
||||
|
||||
async function select(id: number) {
|
||||
const orderId = Number(order.value?.id)
|
||||
const option = options.value.find((entry) => entry.id === id)
|
||||
if (!visible.value || !orderId || !option) return
|
||||
|
||||
reset()
|
||||
if (option.is_primary) return
|
||||
linkedId.value = id
|
||||
const request = new AbortController()
|
||||
activeRequest = request
|
||||
loading.value = true
|
||||
|
||||
try {
|
||||
const detail = await loadLinkedOrderPrescription(orderId, id, request.signal)
|
||||
if (!request.signal.aborted) linkedDetail.value = detail
|
||||
} catch (e) {
|
||||
if (!request.signal.aborted) error.value = e instanceof Error ? e.message : '无法加载处方详情'
|
||||
} finally {
|
||||
if (!request.signal.aborted) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(visible, (show) => {
|
||||
if (!show) reset()
|
||||
}, { flush: 'sync' })
|
||||
watch([() => order.value?.id, options], ([orderId, next], [previousOrderId]) => {
|
||||
if (orderId !== previousOrderId || (linkedId.value && !next.some((entry) => entry.id === linkedId.value && !entry.is_primary))) {
|
||||
reset()
|
||||
}
|
||||
}, { flush: 'sync' })
|
||||
onScopeDispose(() => activeRequest?.abort())
|
||||
|
||||
return { options, selectedId, isPrimary, prescription, loading, detailError, herbsVisible, reset, select }
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import { computed, onScopeDispose, ref, shallowRef, watch } from 'vue'
|
||||
import { prescriptionDetail } from '@/api/tcm'
|
||||
import { applyOrderUsageOverride } from '@/components/prescription-slip/utils'
|
||||
import feedback from '@/utils/feedback'
|
||||
import { linkedPrescriptionOptions, loadLinkedOrderPrescription, type OrderDetail } from './useLinkedOrderPrescription'
|
||||
|
||||
function mergePrimaryOrderContext(base: OrderDetail, order: OrderDetail) {
|
||||
const prescription: OrderDetail = applyOrderUsageOverride({ ...base }, order.usage_override)
|
||||
if (order.medication_days != null && String(order.medication_days).trim() !== '') {
|
||||
prescription.medication_days = order.medication_days
|
||||
}
|
||||
for (const key of ['order_no', 'recipient_name', 'recipient_phone', 'shipping_address']) {
|
||||
if (order[key] && !prescription[key]) prescription[key] = order[key]
|
||||
}
|
||||
if (order.amount != null && prescription.order_amount == null) prescription.order_amount = order.amount
|
||||
if (Number(order.dose_count) > 0) prescription.dose_count = Number(order.dose_count)
|
||||
if (order.dose_unit != null && String(order.dose_unit).trim() !== '') {
|
||||
prescription.dose_unit = String(order.dose_unit)
|
||||
}
|
||||
if (!(Number(prescription.appointment_id) > 0) && Number(order.linked_appointment?.id) > 0) {
|
||||
prescription.appointment_id = Number(order.linked_appointment.id)
|
||||
}
|
||||
return prescription
|
||||
}
|
||||
|
||||
export function usePrescriptionOrderPreview(resolveAuxLibraryName?: (prescription: OrderDetail) => Promise<string>) {
|
||||
const visible = ref(false)
|
||||
const loading = ref(false)
|
||||
const error = ref('')
|
||||
const prescription = ref<OrderDetail | null>(null)
|
||||
const auxLibraryName = ref('')
|
||||
const tabType = ref<'internal' | 'user'>('internal')
|
||||
const order = shallowRef<OrderDetail | null>(null)
|
||||
const selectedId = ref(0)
|
||||
const isPrimary = computed(() => selectedId.value === Number(order.value?.prescription_id))
|
||||
const canExport = ref(false)
|
||||
const options = computed(() => linkedPrescriptionOptions(order.value))
|
||||
let activeRequest: AbortController | undefined
|
||||
|
||||
async function select(id: number) {
|
||||
const context = order.value
|
||||
if (!visible.value || !context || !id) return
|
||||
const primary = id === Number(context.prescription_id)
|
||||
if (!primary && !options.value.some((entry) => entry.id === id)) return
|
||||
|
||||
activeRequest?.abort()
|
||||
const request = new AbortController()
|
||||
activeRequest = request
|
||||
selectedId.value = id
|
||||
canExport.value = false
|
||||
loading.value = true
|
||||
prescription.value = null
|
||||
auxLibraryName.value = ''
|
||||
error.value = ''
|
||||
|
||||
try {
|
||||
let data: OrderDetail
|
||||
let exportAllowed = primary
|
||||
if (primary) {
|
||||
const response = await prescriptionDetail({ id }, request.signal)
|
||||
const base = response?.data ?? response
|
||||
if (Number(base?.id) !== id) throw new Error('无法加载处方详情')
|
||||
data = mergePrimaryOrderContext(base, context)
|
||||
} else {
|
||||
const detail = await loadLinkedOrderPrescription(Number(context.id), id, request.signal)
|
||||
data = detail.prescription
|
||||
exportAllowed = detail.prescription_detail_herbs_visible === true
|
||||
}
|
||||
if (request.signal.aborted) return
|
||||
const libraryName = resolveAuxLibraryName ? await resolveAuxLibraryName(data) : ''
|
||||
if (request.signal.aborted) return
|
||||
prescription.value = data
|
||||
auxLibraryName.value = libraryName
|
||||
canExport.value = exportAllowed
|
||||
} catch {
|
||||
if (!request.signal.aborted) error.value = '无法加载处方详情。'
|
||||
} finally {
|
||||
if (!request.signal.aborted) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function open(context: OrderDetail, initialId?: number) {
|
||||
const entries = linkedPrescriptionOptions(context)
|
||||
const id = entries.find((entry) => entry.id === initialId)?.id
|
||||
|| entries.find((entry) => entry.is_primary)?.id
|
||||
|| entries[0]?.id
|
||||
|| Number(context.prescription_id)
|
||||
if (!id) {
|
||||
feedback.msgWarning('该订单未关联处方')
|
||||
return
|
||||
}
|
||||
|
||||
order.value = { ...context }
|
||||
tabType.value = 'internal'
|
||||
visible.value = true
|
||||
void select(id)
|
||||
}
|
||||
|
||||
watch(visible, (show) => {
|
||||
if (!show) activeRequest?.abort()
|
||||
}, { flush: 'sync' })
|
||||
onScopeDispose(() => activeRequest?.abort())
|
||||
|
||||
return { visible, loading, error, prescription, auxLibraryName, tabType, selectedId, isPrimary, canExport, options, open, select }
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import { computed, ref } from 'vue'
|
||||
import type { Ref } from 'vue'
|
||||
import { prescriptionOrderAttachReceipt, prescriptionOrderPaidPayOrders, prescriptionOrderUnlinkPayOrder } from '@/api/tcm'
|
||||
import feedback from '@/utils/feedback'
|
||||
import { hasPermission } from '@/utils/perm'
|
||||
import { formatMoney } from './prescription-order-utils'
|
||||
|
||||
type Receipt = {
|
||||
id: number | string
|
||||
order_no?: string
|
||||
amount: number | string
|
||||
}
|
||||
|
||||
export function usePrescriptionOrderReceipts(
|
||||
detail: Ref<Record<string, any> | null>,
|
||||
visible: Ref<boolean>,
|
||||
onChanged: (orderId: number) => void
|
||||
) {
|
||||
const unlinkedReceipts = ref<Receipt[]>([])
|
||||
const linkingReceiptId = ref<number | null>(null)
|
||||
const unlinkingReceiptId = ref<number | null>(null)
|
||||
const changingReceipts = computed(() => linkingReceiptId.value !== null || unlinkingReceiptId.value !== null)
|
||||
const canAttachReceipt = computed(() => Array.isArray(detail.value?.attachable_receipts))
|
||||
const canUnlinkReceipt = computed(() =>
|
||||
Number(detail.value?.id) > 0 && Number(detail.value?.fulfillment_status) !== 4
|
||||
&& hasPermission(['tcm.prescriptionOrder/unlinkPayOrder'])
|
||||
)
|
||||
const isCurrentOrder = (id: number) => visible.value && Number(detail.value?.id) === id
|
||||
|
||||
async function loadUnlinkedReceipts(order: Record<string, any>) {
|
||||
const id = Number(order.id)
|
||||
const diagnosisId = Number(order.diagnosis_id)
|
||||
if (!isCurrentOrder(id)) return
|
||||
if (Array.isArray(order.attachable_receipts) || !diagnosisId) {
|
||||
unlinkedReceipts.value = order.attachable_receipts ?? []
|
||||
return
|
||||
}
|
||||
try {
|
||||
const res = await prescriptionOrderPaidPayOrders({ diagnosis_id: diagnosisId, prescription_order_id: id })
|
||||
const rows: Receipt[] = res?.lists ?? res?.data?.lists ?? []
|
||||
const linkedIds = new Set((order.pay_order_ids ?? []).map(Number))
|
||||
if (isCurrentOrder(id)) {
|
||||
unlinkedReceipts.value = rows.filter((row) => !linkedIds.has(Number(row.id)))
|
||||
}
|
||||
} catch {
|
||||
if (isCurrentOrder(id)) unlinkedReceipts.value = []
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmAttachReceipt(receipt: Receipt) {
|
||||
const orderId = Number(detail.value?.id)
|
||||
const payId = Number(receipt.id)
|
||||
if (!orderId || !payId || !canAttachReceipt.value || changingReceipts.value) return
|
||||
linkingReceiptId.value = payId
|
||||
try {
|
||||
const orderComplete = Number(detail.value?.fulfillment_status) === 3
|
||||
const message = `将收款「${receipt.order_no || '#' + payId}」(¥${formatMoney(receipt.amount)})关联到当前订单?`
|
||||
await feedback.confirm(orderComplete ? message + '收款会先冲减需代收,超出部分计入总金额。' : message)
|
||||
if (!isCurrentOrder(orderId)) return
|
||||
const res = await prescriptionOrderAttachReceipt({ id: orderId, pay_order_id: payId })
|
||||
const updated = res?.data ?? res
|
||||
if (isCurrentOrder(orderId) && Number(updated?.id) === orderId) {
|
||||
const remaining = unlinkedReceipts.value.filter((row) => Number(row.id) !== payId)
|
||||
detail.value = { ...detail.value, ...updated, attachable_receipts: remaining }
|
||||
unlinkedReceipts.value = remaining
|
||||
}
|
||||
feedback.msgSuccess('收款已关联')
|
||||
onChanged(orderId)
|
||||
} catch {
|
||||
// 接口错误由请求拦截器提示。取消确认时保留当前列表。
|
||||
} finally {
|
||||
linkingReceiptId.value = null
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmUnlinkReceipt(receipt: Receipt & { status: number | string }) {
|
||||
const orderId = Number(detail.value?.id)
|
||||
const payId = Number(receipt.id)
|
||||
if (!payId || !canUnlinkReceipt.value || changingReceipts.value || ![2, 4, 5].includes(Number(receipt.status))) return
|
||||
unlinkingReceiptId.value = payId
|
||||
try {
|
||||
await feedback.confirm(
|
||||
`确定移除收款记录「${receipt.order_no || '#' + payId}」(¥${formatMoney(receipt.amount)})?` +
|
||||
'移除后会保留原收款记录,并按订单总金额和剩余收款重算已付金额和需代收。'
|
||||
)
|
||||
if (!isCurrentOrder(orderId)) return
|
||||
const response = await prescriptionOrderUnlinkPayOrder({ id: orderId, pay_order_id: payId })
|
||||
const updated = response?.data ?? response
|
||||
if (isCurrentOrder(orderId) && Number(updated?.id) === orderId) {
|
||||
const order = { ...detail.value, ...updated, attachable_receipts: updated.attachable_receipts }
|
||||
detail.value = order
|
||||
await loadUnlinkedReceipts(order)
|
||||
}
|
||||
feedback.msgSuccess('收款关联已移除,金额已同步更新')
|
||||
onChanged(orderId)
|
||||
} catch {
|
||||
// 请求拦截器负责显示接口报错。
|
||||
} finally {
|
||||
unlinkingReceiptId.value = null
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
unlinkedReceipts, loadUnlinkedReceipts, linkingReceiptId, unlinkingReceiptId, changingReceipts,
|
||||
canAttachReceipt, canUnlinkReceipt, confirmAttachReceipt, confirmUnlinkReceipt
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -626,7 +626,7 @@
|
||||
:gancao-preview-loading="gancaoPreviewLoading"
|
||||
@update-amount="openUpdateAmount"
|
||||
@patch-rx-patient="openPatchRxPatientDialog"
|
||||
@view-prescription="detailData && openPrescriptionView(detailData)"
|
||||
@view-prescription="(id) => detailData && openPrescriptionView(detailData, id)"
|
||||
@test-gancao-preview="testGancaoPreviewFromDetail"
|
||||
@view-patient="openDiagnosisPatientDetailFromOrder"
|
||||
@detail-changed="getLists"
|
||||
@@ -655,18 +655,19 @@
|
||||
>{{ shipModeLabel(detail.ship_mode) }}</el-tag>
|
||||
</div>
|
||||
</template>
|
||||
<template #header-actions="{ detail }">
|
||||
<template #header-actions="{ detail, isPrimaryPrescription }">
|
||||
<el-button
|
||||
v-perms="['tcm.prescriptionOrder/editTime']"
|
||||
size="small"
|
||||
@click="orderTimeDialogRef?.open(detail)"
|
||||
>修改创建时间</el-button>
|
||||
<gancao-submission-reconcile-button
|
||||
v-if="isPrimaryPrescription"
|
||||
:order="detail"
|
||||
@resolved="handleGancaoSubmissionResolved"
|
||||
/>
|
||||
<el-button
|
||||
v-if="canUploadPharmacyRow(detail)"
|
||||
v-if="isPrimaryPrescription && canUploadPharmacyRow(detail)"
|
||||
v-perms="['tcm.prescriptionOrder/uploadToPharmacy']"
|
||||
type="warning"
|
||||
size="small"
|
||||
@@ -675,7 +676,7 @@
|
||||
@click="confirmUploadToPharmacy(detail)"
|
||||
>上传药房</el-button>
|
||||
<el-button
|
||||
v-if="canRxAudit(detail)"
|
||||
v-if="isPrimaryPrescription && canRxAudit(detail)"
|
||||
v-perms="['tcm.prescriptionOrder/auditPrescription']"
|
||||
type="warning"
|
||||
size="small"
|
||||
@@ -685,7 +686,7 @@
|
||||
处方审核
|
||||
</el-button>
|
||||
<el-button
|
||||
v-if="canRevokeRxAudit(detail)"
|
||||
v-if="isPrimaryPrescription && canRevokeRxAudit(detail)"
|
||||
v-perms="['tcm.prescriptionOrder/auditPrescription']"
|
||||
type="info"
|
||||
size="small"
|
||||
@@ -990,6 +991,7 @@
|
||||
<div class="flex items-center gap-1 w-full">
|
||||
<el-input-number
|
||||
v-model="editForm.medication_days"
|
||||
:disabled="editDaysLocked"
|
||||
:min="1"
|
||||
:max="999"
|
||||
:step="1"
|
||||
@@ -1273,7 +1275,8 @@
|
||||
<el-dialog
|
||||
v-model="auditVisible"
|
||||
:title="auditTitle"
|
||||
width="480px"
|
||||
:width="auditKind === 'prescription' ? 'min(1280px, 96vw)' : '480px'"
|
||||
:top="auditKind === 'prescription' ? '5vh' : undefined"
|
||||
destroy-on-close
|
||||
@closed="auditRemark = ''"
|
||||
>
|
||||
@@ -1297,11 +1300,27 @@
|
||||
</div>
|
||||
</template>
|
||||
</el-alert>
|
||||
<p class="text-[13px] text-gray-500 mb-3 bg-gray-50/80 border border-gray-100 p-2 rounded">驳回时必须填写意见;通过时意见选填。</p>
|
||||
<el-input v-model="auditRemark" type="textarea" :rows="4" maxlength="500" show-word-limit placeholder="在此输入审核意见..." />
|
||||
<PrescriptionAuditLayout
|
||||
:prescription-id="auditKind === 'prescription' ? Number(auditRowData?.prescription_id) || 0 : null"
|
||||
:doctor-signed-at="auditEsign?.signature_time || auditEsign?.signed_at"
|
||||
:pharmacist-signed-at="auditReview?.signature_time || auditEsign?.review_signature_time"
|
||||
>
|
||||
<EsignPrescriptionPanel
|
||||
v-if="auditVisible && auditKind === 'prescription'"
|
||||
:key="auditTargetId"
|
||||
:prescription-id="Number(auditRowData?.prescription_id) || 0"
|
||||
audit
|
||||
:review-order-id="Number(auditTargetId)"
|
||||
@review-change="auditReview = $event"
|
||||
class="mb-3"
|
||||
@status-change="auditEsign = $event"
|
||||
/>
|
||||
<p class="text-[13px] text-gray-500 mb-3 bg-gray-50/80 border border-gray-100 p-2 rounded">驳回时必须填写意见;通过时意见选填。</p>
|
||||
<el-input v-model="auditRemark" type="textarea" :rows="4" maxlength="500" show-word-limit placeholder="在此输入审核意见..." />
|
||||
</PrescriptionAuditLayout>
|
||||
<template #footer>
|
||||
<el-button @click="auditVisible = false">取消</el-button>
|
||||
<el-button type="primary" :loading="auditSubmitting" @click="submitAudit('approve')">同意通过</el-button>
|
||||
<el-button type="primary" :loading="auditSubmitting" :disabled="!canApproveAudit" @click="submitAudit('approve')">同意通过</el-button>
|
||||
<el-button type="danger" :loading="auditSubmitting" @click="submitAudit('reject')">驳回阻止</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
@@ -1619,7 +1638,7 @@
|
||||
<el-radio-group v-model="addPayOrderForm.add_mode">
|
||||
<el-radio value="create">付呗</el-radio>
|
||||
<el-radio value="create_express">快递代收</el-radio>
|
||||
<el-radio value="link">关联已有</el-radio>
|
||||
<el-radio v-if="canLinkExistingReceipt" value="link">关联已有</el-radio>
|
||||
<el-radio value="completion_only">直接完单申请</el-radio>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
@@ -1778,35 +1797,60 @@
|
||||
v-model="prescriptionViewVisible"
|
||||
size="920px"
|
||||
:close-on-click-modal="false"
|
||||
@close="prescriptionViewVisible = false"
|
||||
>
|
||||
<template #header>
|
||||
<div class="flex items-center justify-between w-full pr-2 gap-3">
|
||||
<span class="text-base font-medium text-gray-800">查看处方</span>
|
||||
<div v-if="prescriptionViewData && !prescriptionViewLoading" class="flex items-center gap-2 shrink-0">
|
||||
<div v-if="prescriptionViewData && !prescriptionViewLoading && previewCanExport" class="flex items-center gap-2 shrink-0">
|
||||
<el-button
|
||||
size="small"
|
||||
:loading="prescriptionSlipExporting"
|
||||
v-if="!requiresOriginalEsignPdf(prescriptionViewData.esign)"
|
||||
@click="downloadPrescriptionSlipImage"
|
||||
>
|
||||
下载图片
|
||||
</el-button>
|
||||
<el-button
|
||||
size="small"
|
||||
:loading="prescriptionSlipExporting"
|
||||
@click="downloadPrescriptionSlipPdf"
|
||||
<el-dropdown
|
||||
trigger="click"
|
||||
:disabled="prescriptionSlipExporting"
|
||||
@command="downloadPrescriptionSlipPdf"
|
||||
>
|
||||
下载PDF
|
||||
</el-button>
|
||||
<el-button size="small" type="primary" :loading="prescriptionSlipExporting">下载 PDF (A4)</el-button>
|
||||
<template #dropdown>
|
||||
<el-dropdown-menu>
|
||||
<el-dropdown-item
|
||||
v-if="requiresOriginalEsignPdf(prescriptionViewData.esign)"
|
||||
command="esign"
|
||||
:disabled="!prescriptionViewData.esign?.can_download"
|
||||
>CA 签署处方 PDF</el-dropdown-item>
|
||||
<el-dropdown-item command="internal">药房联 PDF(当前页面样式)</el-dropdown-item>
|
||||
<el-dropdown-item command="user">处方联 PDF(当前页面样式)</el-dropdown-item>
|
||||
</el-dropdown-menu>
|
||||
</template>
|
||||
</el-dropdown>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<div v-loading="prescriptionViewLoading" class="rx-wrap">
|
||||
<LinkedOrderPrescriptionSelect
|
||||
:options="previewPrescriptionOptions"
|
||||
:model-value="previewPrescriptionId"
|
||||
:disabled="prescriptionSlipExporting"
|
||||
class="mx-4 mb-2"
|
||||
@change="selectPreviewPrescription"
|
||||
/>
|
||||
<div class="rx-wrap">
|
||||
<el-skeleton v-if="prescriptionViewLoading" :rows="6" animated class="p-4" />
|
||||
<el-alert v-else-if="prescriptionViewError" type="warning" :closable="false" :title="prescriptionViewError" class="mb-3">
|
||||
<el-button link type="primary" @click="selectPreviewPrescription(previewPrescriptionId)">重试</el-button>
|
||||
</el-alert>
|
||||
<!-- 药房联 / 处方联切换 -->
|
||||
<el-tabs
|
||||
v-if="prescriptionViewData"
|
||||
v-model="prescriptionTabType"
|
||||
class="mx-4 mt-2"
|
||||
style="margin-bottom: 0; z-index: 1; position: relative"
|
||||
:before-leave="() => !prescriptionSlipExporting"
|
||||
>
|
||||
<el-tab-pane label="药房联" name="internal" />
|
||||
<el-tab-pane label="处方联" name="user" />
|
||||
@@ -1835,6 +1879,9 @@
|
||||
size="small"
|
||||
>待审核</el-tag>
|
||||
<el-tag v-else type="danger" size="small">已驳回</el-tag>
|
||||
<el-tag v-if="!previewIsPrimary && prescriptionViewData.esign?.status_label" type="info" size="small">
|
||||
{{ prescriptionViewData.esign.status_label }}
|
||||
</el-tag>
|
||||
</div>
|
||||
|
||||
<div
|
||||
@@ -1860,13 +1907,22 @@
|
||||
<div v-if="prescriptionViewData.audit_remark" class="mt-1">驳回意见:{{ prescriptionViewData.audit_remark }}</div>
|
||||
</div>
|
||||
|
||||
<EsignPrescriptionPanel
|
||||
v-if="prescriptionViewVisible && prescriptionViewData && !prescriptionViewLoading && previewIsPrimary"
|
||||
:key="prescriptionViewData.id"
|
||||
:prescription-id="Number(prescriptionViewData.id)"
|
||||
:initial-state="prescriptionViewData.esign"
|
||||
@status-change="updatePrescriptionSlipEsign(prescriptionViewData, $event)"
|
||||
/>
|
||||
<PrescriptionSlip
|
||||
v-if="prescriptionViewData"
|
||||
:key="previewPrescriptionId"
|
||||
ref="rxSlipRef"
|
||||
:data="prescriptionViewData"
|
||||
:variant="prescriptionTabType"
|
||||
:aux-library-name="slipAuxLibraryName"
|
||||
:title="SLIP_TITLE"
|
||||
show-pharmacist-signature-sample
|
||||
/>
|
||||
|
||||
<!-- 审核痕迹(不进入导出) -->
|
||||
@@ -2058,11 +2114,14 @@
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup name="prescriptionOrderList">
|
||||
import { computed, onMounted, reactive, ref, nextTick, watch, defineAsyncComponent } from 'vue'
|
||||
import { computed, onActivated, onMounted, reactive, ref, nextTick, watch, defineAsyncComponent } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { ArrowDown, InfoFilled, QuestionFilled, Search, Calendar, Document, Link as LinkIcon, Wallet } from '@element-plus/icons-vue'
|
||||
import ListTimeFilter from '@/components/list-time-filter/index.vue'
|
||||
import PrescriptionOrderDetailDrawer from './components/PrescriptionOrderDetailDrawer.vue'
|
||||
import LinkedOrderPrescriptionSelect from './components/LinkedOrderPrescriptionSelect.vue'
|
||||
import type { LinkedPrescription } from './components/useLinkedOrderPrescription'
|
||||
import { usePrescriptionOrderPreview } from './components/usePrescriptionOrderPreview'
|
||||
import PrescriptionOrderTimeDialog from './components/PrescriptionOrderTimeDialog.vue'
|
||||
import GancaoSubmissionReconcileButton from './components/GancaoSubmissionReconcileButton.vue'
|
||||
import {
|
||||
@@ -2122,12 +2181,16 @@ import {
|
||||
prescriptionOrderLinkPayOrder,
|
||||
prescriptionOrderUploadToPharmacy,
|
||||
prescriptionOrderPreviewGancaoRecipel,
|
||||
prescriptionDetail,
|
||||
prescriptionLibraryLists,
|
||||
getDoctors,
|
||||
getAssistants
|
||||
} from '@/api/tcm'
|
||||
import PrescriptionSlip from '@/components/prescription-slip/index.vue'
|
||||
import PrescriptionSlip from '@/components/prescription-slip/index.vue'
|
||||
import { applyOrderUsageOverride } from '@/components/prescription-slip/utils'
|
||||
import EsignPrescriptionPanel from '@/components/EsignPrescriptionPanel.vue'
|
||||
import PrescriptionAuditLayout from '@/components/PrescriptionAuditLayout.vue'
|
||||
import type { PrescriptionEsignStatus } from '@/api/tcm'
|
||||
import { canApprovePrescriptionEsign, downloadOriginalEsignPdf, requiresOriginalEsignPdf, updatePrescriptionSlipEsign } from '@/utils/prescription-esign'
|
||||
import html2canvas from 'html2canvas'
|
||||
import { jsPDF } from 'jspdf'
|
||||
import { getDictData } from '@/api/app'
|
||||
@@ -2141,7 +2204,11 @@ import useUserStore from '@/stores/modules/user'
|
||||
const TcmDiagnosisEditView = defineAsyncComponent(() => import('@/views/tcm/diagnosis/edit.vue'))
|
||||
|
||||
const userStore = useUserStore()
|
||||
const canLinkExistingReceipt = computed(() =>
|
||||
userStore.perms.includes('*') || userStore.perms.includes('tcm.prescriptionOrder/attachReceipt')
|
||||
)
|
||||
const route = useRoute()
|
||||
const orderListPath = route.fullPath
|
||||
|
||||
const diagnosisViewRef = ref<{
|
||||
openViewOnly: (id: number) => Promise<void>
|
||||
@@ -2943,10 +3010,10 @@ function canEditRow(row: {
|
||||
return fs === 1 || fs === 2
|
||||
}
|
||||
|
||||
function canRxAudit(row: { prescription_audit_status?: number; fulfillment_status?: number }) {
|
||||
function canRxAudit(row: { prescription_audit_status?: number; fulfillment_status?: number; can_review_prescription?: boolean }) {
|
||||
const fs = Number(row.fulfillment_status)
|
||||
if (fs === 3 || fs === 4 || fs === 6) return false
|
||||
return Number(row.prescription_audit_status) === 0
|
||||
return Number(row.prescription_audit_status) === 0 && row.can_review_prescription === true
|
||||
}
|
||||
|
||||
function canPayAudit(row: {
|
||||
@@ -3285,8 +3352,8 @@ async function submitUpdateAmount() {
|
||||
}
|
||||
}
|
||||
|
||||
async function openDetail(id: number) {
|
||||
await detailDrawerRef.value?.open(id)
|
||||
async function openDetail(id: number, prescriptionId?: number) {
|
||||
await detailDrawerRef.value?.open(id, prescriptionId)
|
||||
}
|
||||
|
||||
const editVisible = ref(false)
|
||||
@@ -3324,6 +3391,7 @@ const editFormRef = ref<FormInstance>()
|
||||
const editForm = reactive({
|
||||
id: 0,
|
||||
prescription_id: 0,
|
||||
linked_prescriptions: [] as LinkedPrescription[],
|
||||
diagnosis_id: 0,
|
||||
recipient_name: '',
|
||||
recipient_phone: '',
|
||||
@@ -3483,6 +3551,7 @@ const editRules = computed<FormRules>(() => {
|
||||
function resetEditOrderDialog() {
|
||||
editOrderStep.value = 0
|
||||
editOrderPrescription.value = null
|
||||
editForm.linked_prescriptions = []
|
||||
editGancaoLogisticsOnlyMode.value = false
|
||||
editGancaoDisplayNo.value = ''
|
||||
editFormRef.value?.clearValidate()
|
||||
@@ -3511,6 +3580,9 @@ async function goEditOrderNextStep() {
|
||||
}
|
||||
}
|
||||
|
||||
/** 已发货订单服用天数锁定(来自订单详情 days_locked,服务端同样拦截) */
|
||||
const editDaysLocked = ref(false)
|
||||
|
||||
async function openEdit(row: {
|
||||
id: number
|
||||
creator_id?: number
|
||||
@@ -3532,6 +3604,7 @@ async function openEdit(row: {
|
||||
}
|
||||
editOrderStep.value = 0
|
||||
editOrderPrescription.value = null
|
||||
editForm.linked_prescriptions = []
|
||||
editVisible.value = true
|
||||
editDialogLoading.value = true
|
||||
try {
|
||||
@@ -3542,6 +3615,7 @@ async function openEdit(row: {
|
||||
editVisible.value = false
|
||||
return
|
||||
}
|
||||
editForm.linked_prescriptions = d.linked_prescriptions ?? []
|
||||
const rx = d.prescription
|
||||
if (rx && typeof rx === 'object') {
|
||||
editOrderPrescription.value = rx as Record<string, any>
|
||||
@@ -3584,7 +3658,8 @@ async function openEdit(row: {
|
||||
|
||||
editForm.shipping_address = d.shipping_address || ''
|
||||
editForm.is_follow_up = d.is_follow_up ? 1 : 0
|
||||
editForm.medication_days = d.medication_days > 0 ? d.medication_days : undefined
|
||||
editForm.medication_days = d.medication_days > 0 ? d.medication_days : undefined
|
||||
editDaysLocked.value = d.days_locked === true
|
||||
editForm.dose_count = d.dose_count > 0 ? d.dose_count : 1
|
||||
editForm.dose_unit = d.dose_unit || '剂'
|
||||
editForm.prev_staff = d.prev_staff || ''
|
||||
@@ -3694,20 +3769,30 @@ const auditTargetId = ref(0)
|
||||
const auditRowData = ref<any>(null)
|
||||
const auditRemark = ref('')
|
||||
const auditSubmitting = ref(false)
|
||||
const auditEsign = ref<PrescriptionEsignStatus | null>(null)
|
||||
const auditReview = ref<import('@/api/tcm').PrescriptionEsignReviewStatus | null>(null)
|
||||
const canApproveAudit = computed(() => auditKind.value === 'payment' || (
|
||||
canApprovePrescriptionEsign(auditEsign.value) && auditReview.value?.can_approve === true
|
||||
))
|
||||
|
||||
const auditTitle = computed(() =>
|
||||
auditKind.value === 'prescription' ? '处方业务审核' : '关联支付单审核'
|
||||
)
|
||||
|
||||
function openAudit(row: { id: number }, kind: 'prescription' | 'payment') {
|
||||
function openAudit(row: Record<string, any>, kind: 'prescription' | 'payment') {
|
||||
if (auditSubmitting.value) return
|
||||
if (kind === 'prescription' && !canRxAudit(row)) return
|
||||
auditKind.value = kind
|
||||
auditTargetId.value = row.id
|
||||
auditTargetId.value = Number(row.id)
|
||||
auditRowData.value = row
|
||||
auditEsign.value = null
|
||||
auditReview.value = null
|
||||
auditRemark.value = ''
|
||||
auditVisible.value = true
|
||||
}
|
||||
|
||||
async function submitAudit(action: 'approve' | 'reject') {
|
||||
if (auditSubmitting.value || (action === 'approve' && !canApproveAudit.value)) return
|
||||
if (action === 'reject' && !auditRemark.value.trim()) {
|
||||
feedback.msgError('驳回或阻止时必须填写明确的审核意见')
|
||||
return
|
||||
@@ -3921,6 +4006,17 @@ async function confirmUploadToPharmacy(row: { id: number; ship_mode?: string })
|
||||
}
|
||||
}
|
||||
|
||||
async function openOrderFromRoute() {
|
||||
if (route.fullPath !== orderListPath) return
|
||||
const id = Number(route.query.review_order)
|
||||
if (Number.isSafeInteger(id) && id > 0) await openDetail(id, Number(route.query.review_prescription))
|
||||
}
|
||||
|
||||
let orderListInitialized = false
|
||||
onActivated(() => {
|
||||
if (orderListInitialized) void openOrderFromRoute()
|
||||
})
|
||||
|
||||
onMounted(async () => {
|
||||
await loadRegionData()
|
||||
await loadServicePackageOptions()
|
||||
@@ -3928,6 +4024,8 @@ onMounted(async () => {
|
||||
applyRouteQueryToPrescriptionOrderList()
|
||||
await nextTick()
|
||||
getLists()
|
||||
orderListInitialized = true
|
||||
await openOrderFromRoute()
|
||||
})
|
||||
|
||||
// ─── 快捷填写快递单号 ────────────────────────────────────────────
|
||||
@@ -4421,7 +4519,7 @@ function openAddPayOrder(row: {
|
||||
// 加载可用支付单列表,排除当前订单已关联的
|
||||
const diagId = row.diagnosis_id || detailData.value?.diagnosis_id
|
||||
const currentLinkedIds = row.pay_order_ids || detailData.value?.pay_order_ids || []
|
||||
if (diagId) {
|
||||
if (diagId && canLinkExistingReceipt.value) {
|
||||
void loadAddPayOrderAvailable(diagId, currentLinkedIds)
|
||||
}
|
||||
}
|
||||
@@ -4541,13 +4639,20 @@ const SLIP_TITLE = `${SLIP_HOSPITAL_NAME} 处方笺`
|
||||
const SLIP_COMPANY_LINE = '成都双流甄养堂互联网医院有限公司 联系方式:4001667339'
|
||||
const SLIP_ADDRESS_LINE = '地址:四川省成都市双流区黄甲街道黄龙大道二段280号'
|
||||
|
||||
const prescriptionViewVisible = ref(false)
|
||||
const prescriptionViewLoading = ref(false)
|
||||
const prescriptionViewData = ref<any>(null)
|
||||
/** 药房联辅方标题:处方库中该辅方模板的 prescription_name(导入或药材匹配解析) */
|
||||
const slipAuxLibraryName = ref('')
|
||||
/** 查看处方联次:药房联 / 处方联 */
|
||||
const prescriptionTabType = ref<'internal' | 'user'>('internal')
|
||||
const {
|
||||
visible: prescriptionViewVisible,
|
||||
loading: prescriptionViewLoading,
|
||||
error: prescriptionViewError,
|
||||
prescription: prescriptionViewData,
|
||||
auxLibraryName: slipAuxLibraryName,
|
||||
tabType: prescriptionTabType,
|
||||
selectedId: previewPrescriptionId,
|
||||
isPrimary: previewIsPrimary,
|
||||
canExport: previewCanExport,
|
||||
options: previewPrescriptionOptions,
|
||||
open: openPrescriptionView,
|
||||
select: selectPreviewPrescription
|
||||
} = usePrescriptionOrderPreview(resolveSlipAuxLibraryName)
|
||||
const rxSlipRef = ref<InstanceType<typeof PrescriptionSlip> | null>(null)
|
||||
const prescriptionSlipExporting = ref(false)
|
||||
|
||||
@@ -4936,64 +5041,6 @@ async function resolveSlipAuxLibraryName(data: Record<string, unknown>): Promise
|
||||
return ''
|
||||
}
|
||||
|
||||
async function openPrescriptionView(row: any) {
|
||||
if (!row.prescription_id) {
|
||||
feedback.msgWarning('该订单未关联处方')
|
||||
return
|
||||
}
|
||||
|
||||
prescriptionViewVisible.value = true
|
||||
prescriptionViewLoading.value = true
|
||||
prescriptionViewData.value = null
|
||||
slipAuxLibraryName.value = ''
|
||||
prescriptionTabType.value = 'internal'
|
||||
|
||||
try {
|
||||
const res: any = await prescriptionDetail({ id: row.prescription_id })
|
||||
const base = res?.data ?? res ?? null
|
||||
if (base) {
|
||||
const md = row.medication_days
|
||||
const merged: Record<string, unknown> = { ...base }
|
||||
if (md != null && String(md).trim() !== '') {
|
||||
merged.medication_days = md
|
||||
}
|
||||
/** 订单行带入:处方笺右上角"编号"、"收件信息"、底部"合计"用 */
|
||||
if (row.order_no && !merged.order_no) merged.order_no = row.order_no
|
||||
if (row.recipient_name && !merged.recipient_name) merged.recipient_name = row.recipient_name
|
||||
if (row.recipient_phone && !merged.recipient_phone) merged.recipient_phone = row.recipient_phone
|
||||
if (row.shipping_address && !merged.shipping_address) merged.shipping_address = row.shipping_address
|
||||
if (row.amount != null && merged.order_amount == null) merged.order_amount = row.amount
|
||||
/** 笺面剂数/单位与业务订单一致(甘草预览与订单详情同口径) */
|
||||
if (row.dose_count != null && String(row.dose_count).trim() !== '' && Number(row.dose_count) > 0) {
|
||||
merged.dose_count = Number(row.dose_count)
|
||||
}
|
||||
if (row.dose_unit != null && String(row.dose_unit).trim() !== '') {
|
||||
merged.dose_unit = String(row.dose_unit)
|
||||
}
|
||||
const linkedAp = row.linked_appointment
|
||||
if (
|
||||
(!merged.appointment_id || Number(merged.appointment_id) <= 0) &&
|
||||
linkedAp &&
|
||||
typeof linkedAp === 'object' &&
|
||||
Number(linkedAp.id) > 0
|
||||
) {
|
||||
merged.appointment_id = Number(linkedAp.id)
|
||||
}
|
||||
prescriptionViewData.value = merged
|
||||
slipAuxLibraryName.value = await resolveSlipAuxLibraryName(merged)
|
||||
} else {
|
||||
prescriptionViewData.value = null
|
||||
slipAuxLibraryName.value = ''
|
||||
}
|
||||
} catch (e: any) {
|
||||
feedback.msgError(e?.message || '加载处方详情失败')
|
||||
prescriptionViewVisible.value = false
|
||||
slipAuxLibraryName.value = ''
|
||||
} finally {
|
||||
prescriptionViewLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function preloadSlipImagesToDataUrl(el: HTMLElement): Promise<void> {
|
||||
const imgs = el.querySelectorAll<HTMLImageElement>('img[src^="http"]')
|
||||
const tasks = Array.from(imgs).map(async (img) => {
|
||||
@@ -5086,7 +5133,8 @@ async function capturePrescriptionSlipCanvas(): Promise<HTMLCanvasElement> {
|
||||
function slipDownloadBaseName() {
|
||||
const name = prescriptionViewData.value?.patient_name
|
||||
const safe = typeof name === 'string' && name.trim() ? name.trim().replace(/[\\/:*?"<>|]/g, '_') : '未命名'
|
||||
return `处方_${safe}_${Date.now()}`
|
||||
const copy = prescriptionTabType.value === 'internal' ? '药房联' : '处方联'
|
||||
return `${copy}_${safe}_${Date.now()}`
|
||||
}
|
||||
|
||||
async function downloadPrescriptionSlipImage() {
|
||||
@@ -5106,10 +5154,19 @@ async function downloadPrescriptionSlipImage() {
|
||||
}
|
||||
}
|
||||
|
||||
async function downloadPrescriptionSlipPdf() {
|
||||
if (!prescriptionViewData.value) return
|
||||
/** 下载 PDF:CA 签署原件,或按当前页面样式导出药房联 / 处方联(含本订单生效的服用参数与签章) */
|
||||
async function downloadPrescriptionSlipPdf(command: 'esign' | 'internal' | 'user' = 'internal') {
|
||||
if (!prescriptionViewData.value || !previewCanExport.value) return
|
||||
prescriptionSlipExporting.value = true
|
||||
try {
|
||||
if (command === 'esign') {
|
||||
await downloadOriginalEsignPdf(Number(prescriptionViewData.value.id))
|
||||
return
|
||||
}
|
||||
if (prescriptionTabType.value !== command) {
|
||||
prescriptionTabType.value = command
|
||||
await nextTick()
|
||||
}
|
||||
const canvas = await capturePrescriptionSlipCanvas()
|
||||
const imgData = canvas.toDataURL('image/jpeg', 0.95)
|
||||
/**
|
||||
@@ -5141,8 +5198,8 @@ async function downloadPrescriptionSlipPdf() {
|
||||
}
|
||||
pdf.save(`${slipDownloadBaseName()}.pdf`)
|
||||
feedback.msgSuccess('PDF已下载')
|
||||
} catch {
|
||||
feedback.msgError('下载PDF失败')
|
||||
} catch (e: any) {
|
||||
feedback.msgError(e?.message || '下载PDF失败')
|
||||
} finally {
|
||||
prescriptionSlipExporting.value = false
|
||||
}
|
||||
|
||||
@@ -554,11 +554,12 @@
|
||||
</div>
|
||||
<div v-if="detailData" class="po-detail-drawer-actions flex flex-wrap items-center gap-2">
|
||||
<gancao-submission-reconcile-button
|
||||
v-if="isPrimaryPrescription"
|
||||
:order="detailData"
|
||||
@resolved="handleGancaoSubmissionResolved"
|
||||
/>
|
||||
<el-button
|
||||
v-if="canRxAudit(detailData)"
|
||||
v-if="isPrimaryPrescription && canRxAudit(detailData)"
|
||||
v-perms="['tcm.prescriptionOrder/auditPrescription']"
|
||||
type="warning"
|
||||
size="small"
|
||||
@@ -568,7 +569,7 @@
|
||||
处方审核
|
||||
</el-button>
|
||||
<el-button
|
||||
v-if="canRevokeRxAudit(detailData)"
|
||||
v-if="isPrimaryPrescription && canRevokeRxAudit(detailData)"
|
||||
v-perms="['tcm.prescriptionOrder/auditPrescription']"
|
||||
type="info"
|
||||
size="small"
|
||||
@@ -769,10 +770,10 @@
|
||||
<!-- 左侧:处方单 -->
|
||||
<el-card shadow="never" class="po-panel po-panel-rx border-gray-100 h-full relative overflow-hidden">
|
||||
<!-- 处方审核印章 -->
|
||||
<div v-if="detailData.prescription_audit_status === 1" class="audit-stamp stamp-pass">
|
||||
<div v-if="isPrimaryPrescription && detailData.prescription_audit_status === 1" class="audit-stamp stamp-pass">
|
||||
<div class="stamp-inner">审核通过</div>
|
||||
</div>
|
||||
<div v-if="detailData.prescription_audit_status === 2" class="audit-stamp stamp-reject">
|
||||
<div v-if="isPrimaryPrescription && detailData.prescription_audit_status === 2" class="audit-stamp stamp-reject">
|
||||
<div class="stamp-inner">已驳回</div>
|
||||
</div>
|
||||
<template #header>
|
||||
@@ -780,15 +781,16 @@
|
||||
<div class="flex w-full min-w-0 flex-wrap items-center justify-between gap-x-2 gap-y-1">
|
||||
<span class="po-panel-rx-header__title font-medium text-[15px] leading-snug">处方详情</span>
|
||||
<span class="shrink-0 text-xs text-gray-400 tabular-nums">
|
||||
ID: {{ detailData.prescription_id || '—' }}
|
||||
ID: {{ selectedPrescriptionId || '—' }}
|
||||
</span>
|
||||
</div>
|
||||
<div v-if="detailData.doctor_name" class="min-w-0 text-xs leading-snug text-gray-500">
|
||||
开方人:<span class="text-primary font-medium">{{ detailData.doctor_name }}</span>
|
||||
<div v-if="detailPrescriptionDoctor" class="min-w-0 text-xs leading-snug text-gray-500">
|
||||
开方人:<span class="text-primary font-medium">{{ detailPrescriptionDoctor }}</span>
|
||||
</div>
|
||||
<div class="flex w-full min-w-0 flex-wrap items-center gap-x-3 gap-y-1">
|
||||
<el-button
|
||||
v-if="
|
||||
isPrimaryPrescription &&
|
||||
detailData.prescription_id &&
|
||||
detailPrescription &&
|
||||
!String(detailData.prescription_detail_error || '').trim()
|
||||
@@ -802,16 +804,17 @@
|
||||
改患者信息
|
||||
</el-button>
|
||||
<el-button
|
||||
v-if="detailData.prescription_id && showPrescriptionAuditFilter"
|
||||
v-if="selectedPrescriptionId && showPrescriptionAuditFilter"
|
||||
type="primary"
|
||||
size="small"
|
||||
link
|
||||
@click="openPrescriptionView(detailData)"
|
||||
:disabled="linkedPrescriptionLoading"
|
||||
@click="openPrescriptionView(detailData, selectedPrescriptionId)"
|
||||
>
|
||||
详细
|
||||
</el-button>
|
||||
<el-button
|
||||
v-if="detailData.id && showPrescriptionAuditFilter"
|
||||
v-if="isPrimaryPrescription && detailData.id && showPrescriptionAuditFilter"
|
||||
type="warning"
|
||||
size="small"
|
||||
link
|
||||
@@ -824,14 +827,23 @@
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<LinkedOrderPrescriptionSelect
|
||||
:options="detailPrescriptionOptions"
|
||||
:model-value="selectedPrescriptionId"
|
||||
class="mb-3"
|
||||
@change="selectLinkedPrescription"
|
||||
/>
|
||||
<el-skeleton v-if="linkedPrescriptionLoading" :rows="5" animated />
|
||||
<el-alert
|
||||
v-if="String(detailData.prescription_detail_error || '').trim()"
|
||||
:title="detailData.prescription_detail_error"
|
||||
v-else-if="selectedPrescriptionError"
|
||||
:title="selectedPrescriptionError"
|
||||
type="warning"
|
||||
:closable="false"
|
||||
show-icon
|
||||
class="mb-3"
|
||||
/>
|
||||
>
|
||||
<el-button v-if="!isPrimaryPrescription" link type="primary" @click="selectLinkedPrescription(selectedPrescriptionId)">重试</el-button>
|
||||
</el-alert>
|
||||
<template v-else-if="detailPrescription">
|
||||
<el-descriptions :column="1" border size="small" class="po-desc bg-white">
|
||||
<el-descriptions-item label="处方编号" :span="2">{{ detailPrescription.sn || '—' }}</el-descriptions-item>
|
||||
@@ -842,13 +854,13 @@
|
||||
<el-descriptions-item label="手机">
|
||||
<span
|
||||
:class="
|
||||
detailRecipientRxPhoneMismatch ? 'rx-phone-mismatch text-red-600 font-bold' : ''
|
||||
isPrimaryPrescription && detailRecipientRxPhoneMismatch ? 'rx-phone-mismatch text-red-600 font-bold' : ''
|
||||
"
|
||||
>
|
||||
{{ detailPrescription.phone || '—' }}
|
||||
</span>
|
||||
<el-tag
|
||||
v-if="detailRecipientRxPhoneMismatch"
|
||||
v-if="isPrimaryPrescription && detailRecipientRxPhoneMismatch"
|
||||
type="danger"
|
||||
size="small"
|
||||
effect="dark"
|
||||
@@ -864,7 +876,8 @@
|
||||
{{ detailPrescription.clinical_diagnosis || '—' }}
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="剂数 / 用法" :span="2" v-if="showPrescriptionAuditFilter">
|
||||
{{ detailData.dose_count ?? detailPrescription.dose_count ?? '—' }} {{ detailData.dose_unit || '剂' }} ·
|
||||
{{ (isPrimaryPrescription ? detailData.dose_count ?? detailPrescription.dose_count : detailPrescription.dose_count) ?? '—' }}
|
||||
{{ (isPrimaryPrescription ? detailData.dose_unit : detailPrescription.dose_unit) || '剂' }} ·
|
||||
{{ detailPrescription.usage_instruction || detailPrescription.usage_method || '—' }}
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="处方金额">
|
||||
@@ -884,7 +897,7 @@
|
||||
<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-if="isPrimaryPrescription && detailData.prescription_id && !selectedPrescriptionError"
|
||||
v-perms="['tcm.prescriptionOrder/patchPrescriptionUsage']"
|
||||
type="primary"
|
||||
size="small"
|
||||
@@ -908,7 +921,7 @@
|
||||
<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-if="isPrimaryPrescription && detailData.prescription_id && !selectedPrescriptionError"
|
||||
v-perms="['tcm.prescriptionOrder/patchPrescriptionUsage']"
|
||||
type="primary"
|
||||
size="small"
|
||||
@@ -933,6 +946,7 @@
|
||||
<span>服用方式</span>
|
||||
<el-button
|
||||
v-if="
|
||||
isPrimaryPrescription &&
|
||||
detailData.prescription_id &&
|
||||
detailPrescription &&
|
||||
!String(detailData.prescription_detail_error || '').trim()
|
||||
@@ -986,7 +1000,7 @@
|
||||
}}
|
||||
</div>
|
||||
</template>
|
||||
<div>
|
||||
<div v-if="isPrimaryPrescription">
|
||||
<span class="text-gray-500">订单设置:</span>
|
||||
{{
|
||||
detailData.medication_days != null &&
|
||||
@@ -1079,6 +1093,17 @@
|
||||
{{ formatOrderTime(row.create_time) }}
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column v-if="canAttachReceipt" label="操作" width="86" fixed="right" align="center">
|
||||
<template #default="{ row }">
|
||||
<el-button
|
||||
link
|
||||
type="primary"
|
||||
:loading="linkingReceiptId === Number(row.id)"
|
||||
:disabled="changingReceipts"
|
||||
@click="confirmAttachReceipt(row)"
|
||||
>关联</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
<el-empty v-else description="无未关联的收款单" :image-size="60" />
|
||||
</el-card>
|
||||
@@ -1142,6 +1167,17 @@
|
||||
{{ formatOrderTime(row.create_time) }}
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column v-if="canUnlinkReceipt" label="操作" width="80" fixed="right" align="center">
|
||||
<template #default="{ row }">
|
||||
<el-button
|
||||
link
|
||||
type="danger"
|
||||
:loading="unlinkingReceiptId === Number(row.id)"
|
||||
:disabled="changingReceipts || ![2, 4, 5].includes(Number(row.status))"
|
||||
@click="confirmUnlinkReceipt(row)"
|
||||
>移除</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
<el-empty v-else description="未关联收款单" :image-size="60" />
|
||||
</el-card>
|
||||
@@ -1570,6 +1606,7 @@
|
||||
<div class="flex items-center gap-1 w-full">
|
||||
<el-input-number
|
||||
v-model="editForm.medication_days"
|
||||
:disabled="editDaysLocked"
|
||||
:min="1"
|
||||
:max="999"
|
||||
:step="1"
|
||||
@@ -1840,7 +1877,8 @@
|
||||
<el-dialog
|
||||
v-model="auditVisible"
|
||||
:title="auditTitle"
|
||||
width="92%"
|
||||
:width="auditKind === 'prescription' ? 'min(1280px, 96vw)' : '92%'"
|
||||
:top="auditKind === 'prescription' ? '5vh' : undefined"
|
||||
destroy-on-close
|
||||
class="po-h5-dialog"
|
||||
@closed="auditRemark = ''"
|
||||
@@ -1865,11 +1903,27 @@
|
||||
</div>
|
||||
</template>
|
||||
</el-alert>
|
||||
<p class="text-[13px] text-gray-500 mb-3 bg-gray-50/80 border border-gray-100 p-2 rounded">驳回时必须填写意见;通过时意见选填。</p>
|
||||
<el-input v-model="auditRemark" type="textarea" :rows="4" maxlength="500" show-word-limit placeholder="在此输入审核意见..." />
|
||||
<PrescriptionAuditLayout
|
||||
:prescription-id="auditKind === 'prescription' ? Number(auditRowData?.prescription_id) || 0 : null"
|
||||
:doctor-signed-at="auditEsign?.signature_time || auditEsign?.signed_at"
|
||||
:pharmacist-signed-at="auditReview?.signature_time || auditEsign?.review_signature_time"
|
||||
>
|
||||
<EsignPrescriptionPanel
|
||||
v-if="auditVisible && auditKind === 'prescription'"
|
||||
:key="auditTargetId"
|
||||
:prescription-id="Number(auditRowData?.prescription_id) || 0"
|
||||
audit
|
||||
:review-order-id="Number(auditTargetId)"
|
||||
@review-change="auditReview = $event"
|
||||
class="mb-3"
|
||||
@status-change="auditEsign = $event"
|
||||
/>
|
||||
<p class="text-[13px] text-gray-500 mb-3 bg-gray-50/80 border border-gray-100 p-2 rounded">驳回时必须填写意见;通过时意见选填。</p>
|
||||
<el-input v-model="auditRemark" type="textarea" :rows="4" maxlength="500" show-word-limit placeholder="在此输入审核意见..." />
|
||||
</PrescriptionAuditLayout>
|
||||
<template #footer>
|
||||
<el-button @click="auditVisible = false">取消</el-button>
|
||||
<el-button type="primary" :loading="auditSubmitting" @click="submitAudit('approve')">同意通过</el-button>
|
||||
<el-button type="primary" :loading="auditSubmitting" :disabled="!canApproveAudit" @click="submitAudit('approve')">同意通过</el-button>
|
||||
<el-button type="danger" :loading="auditSubmitting" @click="submitAudit('reject')">驳回阻止</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
@@ -2117,7 +2171,7 @@
|
||||
<el-radio-group v-model="addPayOrderForm.add_mode">
|
||||
<el-radio value="create">付呗</el-radio>
|
||||
<el-radio value="create_express">快递代收</el-radio>
|
||||
<el-radio value="link">关联已有</el-radio>
|
||||
<el-radio v-if="canLinkExistingReceipt" value="link">关联已有</el-radio>
|
||||
<el-radio value="completion_only">直接完单申请</el-radio>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
@@ -2306,6 +2360,7 @@
|
||||
<div class="flex items-center gap-1 w-full">
|
||||
<el-input-number
|
||||
v-model="patchUsageForm.usage_days"
|
||||
:disabled="patchUsageDaysLocked"
|
||||
:min="1"
|
||||
:max="999"
|
||||
:step="1"
|
||||
@@ -2340,6 +2395,7 @@
|
||||
<div class="flex items-center gap-1 w-full">
|
||||
<el-input-number
|
||||
v-model="patchUsageForm.aux_usage_days"
|
||||
:disabled="patchUsageDaysLocked"
|
||||
:min="1"
|
||||
:max="999"
|
||||
:step="1"
|
||||
@@ -2355,6 +2411,7 @@
|
||||
<div class="flex items-center gap-1 w-full">
|
||||
<el-input-number
|
||||
v-model="patchUsageForm.medication_days"
|
||||
:disabled="patchUsageDaysLocked"
|
||||
:min="1"
|
||||
:max="999"
|
||||
:step="1"
|
||||
@@ -2378,35 +2435,60 @@
|
||||
direction="btt"
|
||||
class="po-h5-drawer"
|
||||
:close-on-click-modal="false"
|
||||
@close="prescriptionViewVisible = false"
|
||||
>
|
||||
<template #header>
|
||||
<div class="flex items-center justify-between w-full pr-2 gap-3">
|
||||
<span class="text-base font-medium text-gray-800">查看处方</span>
|
||||
<div v-if="prescriptionViewData && !prescriptionViewLoading" class="flex items-center gap-2 shrink-0">
|
||||
<div v-if="prescriptionViewData && !prescriptionViewLoading && previewCanExport" class="flex items-center gap-2 shrink-0">
|
||||
<el-button
|
||||
size="small"
|
||||
:loading="prescriptionSlipExporting"
|
||||
v-if="!requiresOriginalEsignPdf(prescriptionViewData.esign)"
|
||||
@click="downloadPrescriptionSlipImage"
|
||||
>
|
||||
下载图片
|
||||
</el-button>
|
||||
<el-button
|
||||
size="small"
|
||||
:loading="prescriptionSlipExporting"
|
||||
@click="downloadPrescriptionSlipPdf"
|
||||
<el-dropdown
|
||||
trigger="click"
|
||||
:disabled="prescriptionSlipExporting"
|
||||
@command="downloadPrescriptionSlipPdf"
|
||||
>
|
||||
下载PDF
|
||||
</el-button>
|
||||
<el-button size="small" type="primary" :loading="prescriptionSlipExporting">下载 PDF (A4)</el-button>
|
||||
<template #dropdown>
|
||||
<el-dropdown-menu>
|
||||
<el-dropdown-item
|
||||
v-if="requiresOriginalEsignPdf(prescriptionViewData.esign)"
|
||||
command="esign"
|
||||
:disabled="!prescriptionViewData.esign?.can_download"
|
||||
>CA 签署处方 PDF</el-dropdown-item>
|
||||
<el-dropdown-item command="internal">药房联 PDF(当前页面样式)</el-dropdown-item>
|
||||
<el-dropdown-item command="user">处方联 PDF(当前页面样式)</el-dropdown-item>
|
||||
</el-dropdown-menu>
|
||||
</template>
|
||||
</el-dropdown>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<div v-loading="prescriptionViewLoading" class="rx-wrap">
|
||||
<LinkedOrderPrescriptionSelect
|
||||
:options="previewPrescriptionOptions"
|
||||
:model-value="previewPrescriptionId"
|
||||
:disabled="prescriptionSlipExporting"
|
||||
class="mx-4 mb-2"
|
||||
@change="selectPreviewPrescription"
|
||||
/>
|
||||
<div class="rx-wrap">
|
||||
<el-skeleton v-if="prescriptionViewLoading" :rows="6" animated class="p-4" />
|
||||
<el-alert v-else-if="prescriptionViewError" type="warning" :closable="false" :title="prescriptionViewError" class="mb-3">
|
||||
<el-button link type="primary" @click="selectPreviewPrescription(previewPrescriptionId)">重试</el-button>
|
||||
</el-alert>
|
||||
<!-- 药房联 / 处方联切换 -->
|
||||
<el-tabs
|
||||
v-if="prescriptionViewData"
|
||||
v-model="prescriptionTabType"
|
||||
class="mx-4 mt-2"
|
||||
style="margin-bottom: 0; z-index: 1; position: relative"
|
||||
:before-leave="() => !prescriptionSlipExporting"
|
||||
>
|
||||
<el-tab-pane label="药房联" name="internal" />
|
||||
<el-tab-pane label="处方联" name="user" />
|
||||
@@ -2435,6 +2517,9 @@
|
||||
size="small"
|
||||
>待审核</el-tag>
|
||||
<el-tag v-else type="danger" size="small">已驳回</el-tag>
|
||||
<el-tag v-if="!previewIsPrimary && prescriptionViewData.esign?.status_label" type="info" size="small">
|
||||
{{ prescriptionViewData.esign.status_label }}
|
||||
</el-tag>
|
||||
</div>
|
||||
|
||||
<div
|
||||
@@ -2460,12 +2545,21 @@
|
||||
<div v-if="prescriptionViewData.audit_remark" class="mt-1">驳回意见:{{ prescriptionViewData.audit_remark }}</div>
|
||||
</div>
|
||||
|
||||
<EsignPrescriptionPanel
|
||||
v-if="prescriptionViewVisible && prescriptionViewData && !prescriptionViewLoading && previewIsPrimary"
|
||||
:key="prescriptionViewData.id"
|
||||
:prescription-id="Number(prescriptionViewData.id)"
|
||||
:initial-state="prescriptionViewData.esign"
|
||||
@status-change="updatePrescriptionSlipEsign(prescriptionViewData, $event)"
|
||||
/>
|
||||
<PrescriptionSlip
|
||||
v-if="prescriptionViewData"
|
||||
:key="previewPrescriptionId"
|
||||
ref="rxSlipRef"
|
||||
:data="prescriptionViewData"
|
||||
:variant="prescriptionTabType"
|
||||
:title="SLIP_TITLE"
|
||||
show-pharmacist-signature-sample
|
||||
/>
|
||||
|
||||
<!-- 审核痕迹(不进入导出) -->
|
||||
@@ -2632,7 +2726,8 @@
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup name="prescriptionOrderListH5">
|
||||
import { computed, onMounted, reactive, ref, nextTick, watch, defineAsyncComponent } from 'vue'
|
||||
import { computed, onActivated, onMounted, reactive, ref, nextTick, watch, defineAsyncComponent } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import {
|
||||
Refresh,
|
||||
Loading,
|
||||
@@ -2648,6 +2743,7 @@ import {
|
||||
import ListTimeFilter from '@/components/list-time-filter/index.vue'
|
||||
import PrescriptionOrderTimeDialog from './components/PrescriptionOrderTimeDialog.vue'
|
||||
import GancaoSubmissionReconcileButton from './components/GancaoSubmissionReconcileButton.vue'
|
||||
import { usePrescriptionOrderReceipts } from './components/usePrescriptionOrderReceipts'
|
||||
import { useListTimeFilter } from '@/hooks/useListTimeFilter'
|
||||
import {
|
||||
prescriptionOrderAuditPayment,
|
||||
@@ -2673,7 +2769,6 @@ import {
|
||||
prescriptionOrderRequestCompletion,
|
||||
prescriptionOrderUploadToPharmacy,
|
||||
prescriptionOrderPreviewGancaoRecipel,
|
||||
prescriptionDetail,
|
||||
getDoctors,
|
||||
getAssistants
|
||||
} from '@/api/tcm'
|
||||
@@ -2690,7 +2785,15 @@ import {
|
||||
supplyModeLabel,
|
||||
supplyModeTagType
|
||||
} from './components/prescription-order-utils'
|
||||
import PrescriptionSlip from '@/components/prescription-slip/index.vue'
|
||||
import PrescriptionSlip from '@/components/prescription-slip/index.vue'
|
||||
import LinkedOrderPrescriptionSelect from './components/LinkedOrderPrescriptionSelect.vue'
|
||||
import { useLinkedOrderPrescription, type LinkedPrescription } from './components/useLinkedOrderPrescription'
|
||||
import { usePrescriptionOrderPreview } from './components/usePrescriptionOrderPreview'
|
||||
import { applyOrderUsageOverride } from '@/components/prescription-slip/utils'
|
||||
import EsignPrescriptionPanel from '@/components/EsignPrescriptionPanel.vue'
|
||||
import PrescriptionAuditLayout from '@/components/PrescriptionAuditLayout.vue'
|
||||
import type { PrescriptionEsignStatus } from '@/api/tcm'
|
||||
import { canApprovePrescriptionEsign, downloadOriginalEsignPdf, requiresOriginalEsignPdf, updatePrescriptionSlipEsign } from '@/utils/prescription-esign'
|
||||
import html2canvas from 'html2canvas'
|
||||
import { jsPDF } from 'jspdf'
|
||||
import { getDictData } from '@/api/app'
|
||||
@@ -2704,6 +2807,9 @@ import useUserStore from '@/stores/modules/user'
|
||||
const TcmDiagnosisEditView = defineAsyncComponent(() => import('@/views/tcm/diagnosis/edit.vue'))
|
||||
|
||||
const userStore = useUserStore()
|
||||
const canLinkExistingReceipt = computed(() =>
|
||||
userStore.perms.includes('*') || userStore.perms.includes('tcm.prescriptionOrder/attachReceipt')
|
||||
)
|
||||
|
||||
const diagnosisViewRef = ref<{
|
||||
openViewOnly: (id: number) => Promise<void>
|
||||
@@ -3421,10 +3527,10 @@ function canEditRow(row: {
|
||||
return fs === 1 || fs === 2
|
||||
}
|
||||
|
||||
function canRxAudit(row: { prescription_audit_status?: number; fulfillment_status?: number }) {
|
||||
function canRxAudit(row: { prescription_audit_status?: number; fulfillment_status?: number; can_review_prescription?: boolean }) {
|
||||
const fs = Number(row.fulfillment_status)
|
||||
if (fs === 3 || fs === 4 || fs === 6) return false
|
||||
return Number(row.prescription_audit_status) === 0
|
||||
return Number(row.prescription_audit_status) === 0 && row.can_review_prescription === true
|
||||
}
|
||||
|
||||
function canPayAudit(row: {
|
||||
@@ -3582,6 +3688,20 @@ function canUpdateAmount(row: { id?: number; fulfillment_status?: number } | nul
|
||||
const detailVisible = ref(false)
|
||||
const detailLoading = ref(false)
|
||||
const detailData = ref<Record<string, any> | null>(null)
|
||||
const {
|
||||
options: detailPrescriptionOptions,
|
||||
selectedId: selectedPrescriptionId,
|
||||
isPrimary: isPrimaryPrescription,
|
||||
prescription: detailPrescription,
|
||||
loading: linkedPrescriptionLoading,
|
||||
detailError: selectedPrescriptionError,
|
||||
herbsVisible: detailHerbsVisible,
|
||||
reset: resetLinkedPrescription,
|
||||
select: selectLinkedPrescription
|
||||
} = useLinkedOrderPrescription(detailData, detailVisible)
|
||||
const detailPrescriptionDoctor = computed(() =>
|
||||
isPrimaryPrescription.value ? detailData.value?.doctor_name : detailPrescription.value?.doctor_name
|
||||
)
|
||||
const orderTimeDialogRef = ref<InstanceType<typeof PrescriptionOrderTimeDialog>>()
|
||||
|
||||
async function onOrderTimeSaved(id: number) {
|
||||
@@ -3667,28 +3787,20 @@ const detailAgencyToCollect = computed(() => {
|
||||
return Math.round((total - paid) * 100) / 100
|
||||
})
|
||||
|
||||
const detailUnlinkedPayOrders = ref<any[]>([])
|
||||
|
||||
async function loadDetailUnlinkedPayOrders(diagnosisId: number, prescriptionOrderId: number, linkedIds: number[]) {
|
||||
if (!diagnosisId) {
|
||||
detailUnlinkedPayOrders.value = []
|
||||
return
|
||||
}
|
||||
try {
|
||||
const res: any = await prescriptionOrderPaidPayOrders({
|
||||
diagnosis_id: diagnosisId,
|
||||
prescription_order_id: prescriptionOrderId
|
||||
})
|
||||
const lists = res?.lists ?? res?.data?.lists ?? []
|
||||
// 列表已由服务端限制为 2026-04-20 及之后创建的支付单(本单已关联除外);此处再过滤已关联项
|
||||
const filtered = Array.isArray(lists)
|
||||
? lists.filter((item: any) => !linkedIds.includes(item.id))
|
||||
: []
|
||||
detailUnlinkedPayOrders.value = filtered
|
||||
} catch {
|
||||
detailUnlinkedPayOrders.value = []
|
||||
}
|
||||
}
|
||||
const {
|
||||
unlinkedReceipts: detailUnlinkedPayOrders,
|
||||
loadUnlinkedReceipts,
|
||||
linkingReceiptId,
|
||||
unlinkingReceiptId,
|
||||
changingReceipts,
|
||||
canAttachReceipt,
|
||||
canUnlinkReceipt,
|
||||
confirmAttachReceipt,
|
||||
confirmUnlinkReceipt
|
||||
} = usePrescriptionOrderReceipts(detailData, detailVisible, (orderId) => {
|
||||
void getLists()
|
||||
if (detailVisible.value && Number(detailData.value?.id) === orderId) void fetchLogs(orderId)
|
||||
})
|
||||
|
||||
function normalizeSlipHerbs(raw: unknown): Array<{ name: string; dosage: number }> {
|
||||
if (!raw) return []
|
||||
@@ -3701,11 +3813,6 @@ function normalizeSlipHerbs(raw: unknown): Array<{ name: string; dosage: number
|
||||
return []
|
||||
}
|
||||
|
||||
const detailPrescription = computed(() => {
|
||||
const p = detailData.value?.prescription
|
||||
return p && typeof p === 'object' ? p : null
|
||||
})
|
||||
|
||||
const detailDietaryText = computed(() => formatDietaryTaboo(detailPrescription.value?.dietary_taboo))
|
||||
|
||||
function normalizeBizPhone(v: unknown): string {
|
||||
@@ -3722,13 +3829,13 @@ function recipientVsPrescriptionPhoneMismatch(recipient: unknown, rxPhone: unkno
|
||||
|
||||
/** 详情抽屉:业务收货手机 vs 处方登记手机 */
|
||||
const detailRecipientRxPhoneMismatch = computed(() => {
|
||||
const rx = detailPrescription.value?.phone
|
||||
const rx = detailData.value?.prescription?.phone
|
||||
const biz = detailData.value?.recipient_phone
|
||||
return recipientVsPrescriptionPhoneMismatch(biz, rx)
|
||||
})
|
||||
|
||||
const detailPrescriptionPhoneDisplay = computed(() => {
|
||||
const s = normalizeBizPhone(detailPrescription.value?.phone)
|
||||
const s = normalizeBizPhone(detailData.value?.prescription?.phone)
|
||||
return s || '—'
|
||||
})
|
||||
|
||||
@@ -3751,7 +3858,9 @@ const detailLinkedAppointmentResolvedFromTag = computed(() => {
|
||||
|
||||
const detailRxHerbs = computed(() => normalizeSlipHerbs(detailPrescription.value?.herbs))
|
||||
|
||||
const detailHasAuxHerbs = computed(() => prescriptionHasAuxFormula(detailPrescription.value as any))
|
||||
const detailHasAuxHerbs = computed(() => prescriptionHasAuxFormula(detailPrescription.value as any))
|
||||
/** 已发货订单服用天数锁定(服务端 days_locked,同样拦截保存) */
|
||||
const patchUsageDaysLocked = computed(() => detailData.value?.days_locked === true)
|
||||
|
||||
const detailAuxUsage = computed(() => {
|
||||
const rx = detailPrescription.value as any
|
||||
@@ -3762,7 +3871,6 @@ const detailAuxUsage = computed(() => {
|
||||
})
|
||||
|
||||
/** false=无权限;true/缺省兼容旧接口(旧版未下发该字段时仍展示药材) */
|
||||
const detailHerbsVisible = computed(() => detailData.value?.prescription_detail_herbs_visible !== false)
|
||||
|
||||
// 完整收货地址(省市区 + 详细地址)
|
||||
const detailFullAddress = computed(() => {
|
||||
@@ -3906,6 +4014,7 @@ function logActionText(act: string) {
|
||||
ship: '确认发货',
|
||||
withdraw: '撤销',
|
||||
link_pay_order: '关联支付单',
|
||||
bind_prescription: '绑定关联处方',
|
||||
revoke_rx_audit: '撤回处方审核',
|
||||
revoke_pay_audit: '撤回支付审核',
|
||||
gancao_submit: '甘草下单',
|
||||
@@ -4028,6 +4137,7 @@ function openPatchUsageDialog() {
|
||||
feedback.msgWarning('无处方数据')
|
||||
return
|
||||
}
|
||||
if (rx.id && Number(rx.id) !== Number(ord.prescription_id)) 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 =
|
||||
@@ -4107,6 +4217,7 @@ async function submitPatchUsage() {
|
||||
}
|
||||
|
||||
function openPatchRxPatientDialog() {
|
||||
if (!isPrimaryPrescription.value) return
|
||||
const rx = detailPrescription.value
|
||||
const ord = detailData.value
|
||||
if (!rx || !ord?.id || !ord.prescription_id) {
|
||||
@@ -4144,12 +4255,13 @@ function openUpdateAmount() {
|
||||
}
|
||||
|
||||
async function refreshCurrentPrescriptionOrderDetail() {
|
||||
const id = detailData.value?.id
|
||||
const current = detailData.value
|
||||
const id = current?.id
|
||||
if (!id) return
|
||||
try {
|
||||
const res: any = await prescriptionOrderDetail({ id })
|
||||
const d = res?.data ?? res ?? null
|
||||
if (d) detailData.value = d
|
||||
if (d && detailData.value === current) detailData.value = d
|
||||
} catch {
|
||||
/* 静默失败,避免打断当前抽屉 */
|
||||
}
|
||||
@@ -4213,9 +4325,13 @@ async function submitUpdateAmount() {
|
||||
}
|
||||
}
|
||||
|
||||
async function openDetail(id: number) {
|
||||
let detailOpenRequest = 0
|
||||
|
||||
async function openDetail(id: number, prescriptionId?: number) {
|
||||
const request = ++detailOpenRequest
|
||||
// 修复 Bug:显式彻底清空缓存,防止前一次弹窗的数据残留
|
||||
detailData.value = null
|
||||
resetLinkedPrescription()
|
||||
detailUnlinkedPayOrders.value = []
|
||||
bumpLogisticsTraceRequestToken()
|
||||
detailLogisticsExpress.value = 'auto'
|
||||
@@ -4226,6 +4342,7 @@ async function openDetail(id: number) {
|
||||
detailLoading.value = true
|
||||
try {
|
||||
const res: any = await prescriptionOrderDetail({ id })
|
||||
if (request !== detailOpenRequest || !detailVisible.value) return
|
||||
const d = res?.data ?? res ?? null
|
||||
detailData.value = d
|
||||
if (d) {
|
||||
@@ -4237,18 +4354,15 @@ async function openDetail(id: number) {
|
||||
}
|
||||
fetchLogs(id)
|
||||
|
||||
// 加载未关联的支付单
|
||||
const diagId = d.diagnosis_id
|
||||
const linkedIds = d.pay_order_ids || []
|
||||
if (diagId) {
|
||||
void loadDetailUnlinkedPayOrders(diagId, id, linkedIds)
|
||||
}
|
||||
void loadUnlinkedReceipts(d)
|
||||
if (prescriptionId) void selectLinkedPrescription(prescriptionId)
|
||||
}
|
||||
} catch (e: any) {
|
||||
if (request !== detailOpenRequest || !detailVisible.value) return
|
||||
feedback.msgError(e?.message || '加载失败')
|
||||
detailVisible.value = false
|
||||
} finally {
|
||||
detailLoading.value = false
|
||||
if (request === detailOpenRequest) detailLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4283,6 +4397,7 @@ const editFormRef = ref<FormInstance>()
|
||||
const editForm = reactive({
|
||||
id: 0,
|
||||
prescription_id: 0,
|
||||
linked_prescriptions: [] as LinkedPrescription[],
|
||||
diagnosis_id: 0,
|
||||
recipient_name: '',
|
||||
recipient_phone: '',
|
||||
@@ -4461,6 +4576,7 @@ const editRules = computed<FormRules>(() => {
|
||||
function resetEditOrderDialog() {
|
||||
editOrderStep.value = 0
|
||||
editOrderPrescription.value = null
|
||||
editForm.linked_prescriptions = []
|
||||
editFormRef.value?.clearValidate()
|
||||
}
|
||||
|
||||
@@ -4487,6 +4603,9 @@ async function goEditOrderNextStep() {
|
||||
}
|
||||
}
|
||||
|
||||
/** 已发货订单服用天数锁定(来自订单详情 days_locked,服务端同样拦截) */
|
||||
const editDaysLocked = ref(false)
|
||||
|
||||
async function openEdit(row: {
|
||||
id: number
|
||||
creator_id?: number
|
||||
@@ -4508,6 +4627,7 @@ async function openEdit(row: {
|
||||
}
|
||||
editOrderStep.value = 0
|
||||
editOrderPrescription.value = null
|
||||
editForm.linked_prescriptions = []
|
||||
editVisible.value = true
|
||||
editDialogLoading.value = true
|
||||
try {
|
||||
@@ -4518,6 +4638,7 @@ async function openEdit(row: {
|
||||
editVisible.value = false
|
||||
return
|
||||
}
|
||||
editForm.linked_prescriptions = d.linked_prescriptions ?? []
|
||||
const rx = d.prescription
|
||||
if (rx && typeof rx === 'object') {
|
||||
editOrderPrescription.value = rx as Record<string, any>
|
||||
@@ -4560,7 +4681,8 @@ async function openEdit(row: {
|
||||
|
||||
editForm.shipping_address = d.shipping_address || ''
|
||||
editForm.is_follow_up = d.is_follow_up ? 1 : 0
|
||||
editForm.medication_days = d.medication_days > 0 ? d.medication_days : undefined
|
||||
editForm.medication_days = d.medication_days > 0 ? d.medication_days : undefined
|
||||
editDaysLocked.value = d.days_locked === true
|
||||
editForm.dose_count = d.dose_count > 0 ? d.dose_count : 1
|
||||
editForm.dose_unit = d.dose_unit || '剂'
|
||||
editForm.prev_staff = d.prev_staff || ''
|
||||
@@ -4654,25 +4776,37 @@ async function submitEdit() {
|
||||
}
|
||||
|
||||
const auditVisible = ref(false)
|
||||
const route = useRoute()
|
||||
const orderListPath = route.fullPath
|
||||
const auditKind = ref<'prescription' | 'payment'>('prescription')
|
||||
const auditTargetId = ref(0)
|
||||
const auditRowData = ref<any>(null)
|
||||
const auditRemark = ref('')
|
||||
const auditSubmitting = ref(false)
|
||||
const auditEsign = ref<PrescriptionEsignStatus | null>(null)
|
||||
const auditReview = ref<import('@/api/tcm').PrescriptionEsignReviewStatus | null>(null)
|
||||
const canApproveAudit = computed(() => auditKind.value === 'payment' || (
|
||||
canApprovePrescriptionEsign(auditEsign.value) && auditReview.value?.can_approve === true
|
||||
))
|
||||
|
||||
const auditTitle = computed(() =>
|
||||
auditKind.value === 'prescription' ? '处方业务审核' : '关联支付单审核'
|
||||
)
|
||||
|
||||
function openAudit(row: { id: number }, kind: 'prescription' | 'payment') {
|
||||
function openAudit(row: Record<string, any>, kind: 'prescription' | 'payment') {
|
||||
if (auditSubmitting.value) return
|
||||
if (kind === 'prescription' && !canRxAudit(row)) return
|
||||
auditKind.value = kind
|
||||
auditTargetId.value = row.id
|
||||
auditTargetId.value = Number(row.id)
|
||||
auditRowData.value = row
|
||||
auditEsign.value = null
|
||||
auditReview.value = null
|
||||
auditRemark.value = ''
|
||||
auditVisible.value = true
|
||||
}
|
||||
|
||||
async function submitAudit(action: 'approve' | 'reject') {
|
||||
if (auditSubmitting.value || (action === 'approve' && !canApproveAudit.value)) return
|
||||
if (action === 'reject' && !auditRemark.value.trim()) {
|
||||
feedback.msgError('驳回或阻止时必须填写明确的审核意见')
|
||||
return
|
||||
@@ -4848,11 +4982,24 @@ async function confirmUploadToPharmacy(row: { id: number; ship_mode?: string })
|
||||
}
|
||||
}
|
||||
|
||||
async function openOrderFromRoute() {
|
||||
if (route.fullPath !== orderListPath) return
|
||||
const id = Number(route.query.review_order)
|
||||
if (Number.isSafeInteger(id) && id > 0) await openDetail(id, Number(route.query.review_prescription))
|
||||
}
|
||||
|
||||
let orderListInitialized = false
|
||||
onActivated(() => {
|
||||
if (orderListInitialized) void openOrderFromRoute()
|
||||
})
|
||||
|
||||
onMounted(async () => {
|
||||
await loadRegionData()
|
||||
await loadServicePackageOptions()
|
||||
await loadDoctorAssistantOptions()
|
||||
getLists()
|
||||
orderListInitialized = true
|
||||
await openOrderFromRoute()
|
||||
})
|
||||
|
||||
// ─── 快捷填写快递单号 ────────────────────────────────────────────
|
||||
@@ -5297,7 +5444,7 @@ function openAddPayOrder(row: { id: number; diagnosis_id?: number; pay_order_ids
|
||||
// 加载可用支付单列表,排除当前订单已关联的
|
||||
const diagId = row.diagnosis_id || detailData.value?.diagnosis_id
|
||||
const currentLinkedIds = row.pay_order_ids || detailData.value?.pay_order_ids || []
|
||||
if (diagId) {
|
||||
if (diagId && canLinkExistingReceipt.value) {
|
||||
void loadAddPayOrderAvailable(diagId, currentLinkedIds)
|
||||
}
|
||||
}
|
||||
@@ -5425,11 +5572,19 @@ const SLIP_TITLE = `${SLIP_HOSPITAL_NAME} 处方笺`
|
||||
const SLIP_COMPANY_LINE = '成都双流甄养堂互联网医院有限公司 联系方式:4001667339'
|
||||
const SLIP_ADDRESS_LINE = '地址:四川省成都市双流区黄甲街道黄龙大道二段280号'
|
||||
|
||||
const prescriptionViewVisible = ref(false)
|
||||
const prescriptionViewLoading = ref(false)
|
||||
const prescriptionViewData = ref<any>(null)
|
||||
/** 查看处方联次:药房联 / 处方联 */
|
||||
const prescriptionTabType = ref<'internal' | 'user'>('internal')
|
||||
const {
|
||||
visible: prescriptionViewVisible,
|
||||
loading: prescriptionViewLoading,
|
||||
error: prescriptionViewError,
|
||||
prescription: prescriptionViewData,
|
||||
tabType: prescriptionTabType,
|
||||
selectedId: previewPrescriptionId,
|
||||
isPrimary: previewIsPrimary,
|
||||
canExport: previewCanExport,
|
||||
options: previewPrescriptionOptions,
|
||||
open: openPrescriptionView,
|
||||
select: selectPreviewPrescription
|
||||
} = usePrescriptionOrderPreview()
|
||||
const rxSlipRef = ref<InstanceType<typeof PrescriptionSlip> | null>(null)
|
||||
const prescriptionSlipExporting = ref(false)
|
||||
|
||||
@@ -5688,60 +5843,6 @@ function openPrescriptionViewFromEdit() {
|
||||
openPrescriptionView(editForm)
|
||||
}
|
||||
|
||||
async function openPrescriptionView(row: any) {
|
||||
if (!row.prescription_id) {
|
||||
feedback.msgWarning('该订单未关联处方')
|
||||
return
|
||||
}
|
||||
|
||||
prescriptionViewVisible.value = true
|
||||
prescriptionViewLoading.value = true
|
||||
prescriptionViewData.value = null
|
||||
prescriptionTabType.value = 'internal'
|
||||
|
||||
try {
|
||||
const res: any = await prescriptionDetail({ id: row.prescription_id })
|
||||
const base = res?.data ?? res ?? null
|
||||
if (base) {
|
||||
const md = row.medication_days
|
||||
const merged: Record<string, unknown> = { ...base }
|
||||
if (md != null && String(md).trim() !== '') {
|
||||
merged.medication_days = md
|
||||
}
|
||||
/** 订单行带入:处方笺右上角"编号"、"收件信息"、底部"合计"用 */
|
||||
if (row.order_no && !merged.order_no) merged.order_no = row.order_no
|
||||
if (row.recipient_name && !merged.recipient_name) merged.recipient_name = row.recipient_name
|
||||
if (row.recipient_phone && !merged.recipient_phone) merged.recipient_phone = row.recipient_phone
|
||||
if (row.shipping_address && !merged.shipping_address) merged.shipping_address = row.shipping_address
|
||||
if (row.amount != null && merged.order_amount == null) merged.order_amount = row.amount
|
||||
/** 笺面剂数/单位与业务订单一致(甘草预览与订单详情同口径) */
|
||||
if (row.dose_count != null && String(row.dose_count).trim() !== '' && Number(row.dose_count) > 0) {
|
||||
merged.dose_count = Number(row.dose_count)
|
||||
}
|
||||
if (row.dose_unit != null && String(row.dose_unit).trim() !== '') {
|
||||
merged.dose_unit = String(row.dose_unit)
|
||||
}
|
||||
const linkedAp = row.linked_appointment
|
||||
if (
|
||||
(!merged.appointment_id || Number(merged.appointment_id) <= 0) &&
|
||||
linkedAp &&
|
||||
typeof linkedAp === 'object' &&
|
||||
Number(linkedAp.id) > 0
|
||||
) {
|
||||
merged.appointment_id = Number(linkedAp.id)
|
||||
}
|
||||
prescriptionViewData.value = merged
|
||||
} else {
|
||||
prescriptionViewData.value = null
|
||||
}
|
||||
} catch (e: any) {
|
||||
feedback.msgError(e?.message || '加载处方详情失败')
|
||||
prescriptionViewVisible.value = false
|
||||
} finally {
|
||||
prescriptionViewLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function preloadSlipImagesToDataUrl(el: HTMLElement): Promise<void> {
|
||||
const imgs = el.querySelectorAll<HTMLImageElement>('img[src^="http"]')
|
||||
const tasks = Array.from(imgs).map(async (img) => {
|
||||
@@ -5834,7 +5935,8 @@ async function capturePrescriptionSlipCanvas(): Promise<HTMLCanvasElement> {
|
||||
function slipDownloadBaseName() {
|
||||
const name = prescriptionViewData.value?.patient_name
|
||||
const safe = typeof name === 'string' && name.trim() ? name.trim().replace(/[\\/:*?"<>|]/g, '_') : '未命名'
|
||||
return `处方_${safe}_${Date.now()}`
|
||||
const copy = prescriptionTabType.value === 'internal' ? '药房联' : '处方联'
|
||||
return `${copy}_${safe}_${Date.now()}`
|
||||
}
|
||||
|
||||
async function downloadPrescriptionSlipImage() {
|
||||
@@ -5854,10 +5956,19 @@ async function downloadPrescriptionSlipImage() {
|
||||
}
|
||||
}
|
||||
|
||||
async function downloadPrescriptionSlipPdf() {
|
||||
if (!prescriptionViewData.value) return
|
||||
/** 下载 PDF:CA 签署原件,或按当前页面样式导出药房联 / 处方联(含本订单生效的服用参数与签章) */
|
||||
async function downloadPrescriptionSlipPdf(command: 'esign' | 'internal' | 'user' = 'internal') {
|
||||
if (!prescriptionViewData.value || !previewCanExport.value) return
|
||||
prescriptionSlipExporting.value = true
|
||||
try {
|
||||
if (command === 'esign') {
|
||||
await downloadOriginalEsignPdf(Number(prescriptionViewData.value.id))
|
||||
return
|
||||
}
|
||||
if (prescriptionTabType.value !== command) {
|
||||
prescriptionTabType.value = command
|
||||
await nextTick()
|
||||
}
|
||||
const canvas = await capturePrescriptionSlipCanvas()
|
||||
const imgData = canvas.toDataURL('image/jpeg', 0.95)
|
||||
/**
|
||||
@@ -5889,8 +6000,8 @@ async function downloadPrescriptionSlipPdf() {
|
||||
}
|
||||
pdf.save(`${slipDownloadBaseName()}.pdf`)
|
||||
feedback.msgSuccess('PDF已下载')
|
||||
} catch {
|
||||
feedback.msgError('下载PDF失败')
|
||||
} catch (e: any) {
|
||||
feedback.msgError(e?.message || '下载PDF失败')
|
||||
} finally {
|
||||
prescriptionSlipExporting.value = false
|
||||
}
|
||||
|
||||
@@ -31,25 +31,48 @@
|
||||
</template>
|
||||
</prescription-order-detail-drawer>
|
||||
|
||||
<el-dialog v-model="auditVisible" :title="auditTitle" width="480px" append-to-body destroy-on-close>
|
||||
<el-alert
|
||||
title="通过时审核意见可不填;驳回时必须填写明确原因。"
|
||||
type="warning"
|
||||
:closable="false"
|
||||
show-icon
|
||||
class="mb-4"
|
||||
/>
|
||||
<el-input
|
||||
v-model="auditRemark"
|
||||
type="textarea"
|
||||
:rows="4"
|
||||
maxlength="500"
|
||||
show-word-limit
|
||||
placeholder="请输入审核意见"
|
||||
/>
|
||||
<el-dialog
|
||||
v-model="auditVisible"
|
||||
:title="auditTitle"
|
||||
:width="auditKind === 'prescription' ? 'min(1280px, 96vw)' : '480px'"
|
||||
:top="auditKind === 'prescription' ? '5vh' : undefined"
|
||||
append-to-body
|
||||
destroy-on-close
|
||||
>
|
||||
<PrescriptionAuditLayout
|
||||
:prescription-id="auditKind === 'prescription' ? Number(actionRow.prescription_id) || 0 : null"
|
||||
:doctor-signed-at="auditEsign?.signature_time || auditEsign?.signed_at"
|
||||
:pharmacist-signed-at="auditReview?.signature_time || auditEsign?.review_signature_time"
|
||||
>
|
||||
<EsignPrescriptionPanel
|
||||
v-if="auditVisible && auditKind === 'prescription'"
|
||||
:key="actionRow.id"
|
||||
:prescription-id="Number(actionRow.prescription_id) || 0"
|
||||
audit
|
||||
:review-order-id="Number(actionRow.id)"
|
||||
@review-change="auditReview = $event"
|
||||
class="mb-3"
|
||||
@status-change="auditEsign = $event"
|
||||
/>
|
||||
<el-alert
|
||||
title="通过时审核意见可不填;驳回时必须填写明确原因。"
|
||||
type="warning"
|
||||
:closable="false"
|
||||
show-icon
|
||||
class="mb-4"
|
||||
/>
|
||||
<el-input
|
||||
v-model="auditRemark"
|
||||
type="textarea"
|
||||
:rows="4"
|
||||
maxlength="500"
|
||||
show-word-limit
|
||||
placeholder="请输入审核意见"
|
||||
/>
|
||||
</PrescriptionAuditLayout>
|
||||
<template #footer>
|
||||
<el-button @click="auditVisible = false">取消</el-button>
|
||||
<el-button type="primary" :loading="submitting" @click="submitAudit('approve')">同意通过</el-button>
|
||||
<el-button type="primary" :loading="submitting" :disabled="!canApproveAudit" @click="submitAudit('approve')">同意通过</el-button>
|
||||
<el-button type="danger" :loading="submitting" @click="submitAudit('reject')">驳回</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
@@ -243,6 +266,10 @@ import { computed, reactive, ref } from 'vue'
|
||||
import { ArrowDown } from '@element-plus/icons-vue'
|
||||
import { ElMessageBox } from 'element-plus'
|
||||
import feedback from '@/utils/feedback'
|
||||
import EsignPrescriptionPanel from '@/components/EsignPrescriptionPanel.vue'
|
||||
import PrescriptionAuditLayout from '@/components/PrescriptionAuditLayout.vue'
|
||||
import type { PrescriptionEsignStatus } from '@/api/tcm'
|
||||
import { canApprovePrescriptionEsign } from '@/utils/prescription-esign'
|
||||
import PrescriptionOrderDetailDrawer from '@/views/consumer/prescription/components/PrescriptionOrderDetailDrawer.vue'
|
||||
import {
|
||||
myPatientOrderAddPayOrder,
|
||||
@@ -299,6 +326,11 @@ const completeOptions = [
|
||||
const auditVisible = ref(false)
|
||||
const auditKind = ref<'prescription' | 'payment'>('prescription')
|
||||
const auditRemark = ref('')
|
||||
const auditEsign = ref<PrescriptionEsignStatus | null>(null)
|
||||
const auditReview = ref<import('@/api/tcm').PrescriptionEsignReviewStatus | null>(null)
|
||||
const canApproveAudit = computed(() => auditKind.value === 'payment' || (
|
||||
canApprovePrescriptionEsign(auditEsign.value) && auditReview.value?.can_approve === true
|
||||
))
|
||||
const auditTitle = computed(() => auditKind.value === 'prescription' ? '处方业务审核' : '关联支付单审核')
|
||||
|
||||
const trackVisible = ref(false)
|
||||
@@ -387,6 +419,8 @@ async function openEdit(row: Record<string, any>) {
|
||||
}
|
||||
|
||||
function openAction(row: Record<string, any>, action: MyPatientOrderAction) {
|
||||
if (submitting.value && (action === 'audit_prescription' || action === 'audit_payment')) return
|
||||
if (action === 'audit_prescription' && row.can_review_prescription !== true) return
|
||||
actionRow.value = row
|
||||
switch (action) {
|
||||
case 'edit':
|
||||
@@ -395,6 +429,8 @@ function openAction(row: Record<string, any>, action: MyPatientOrderAction) {
|
||||
case 'audit_prescription':
|
||||
case 'audit_payment':
|
||||
auditKind.value = action === 'audit_prescription' ? 'prescription' : 'payment'
|
||||
auditEsign.value = null
|
||||
auditReview.value = null
|
||||
auditRemark.value = ''
|
||||
auditVisible.value = true
|
||||
break
|
||||
@@ -450,6 +486,7 @@ async function changed(message: string) {
|
||||
}
|
||||
|
||||
async function submitAudit(action: 'approve' | 'reject') {
|
||||
if (submitting.value || (action === 'approve' && !canApproveAudit.value)) return
|
||||
if (action === 'reject' && !auditRemark.value.trim()) {
|
||||
feedback.msgError('驳回时必须填写审核意见')
|
||||
return
|
||||
|
||||
@@ -50,6 +50,7 @@ export function myPatientOrderActions(row: Record<string, any>): MyPatientOrderA
|
||||
}
|
||||
if (
|
||||
permitted('tcm.prescriptionOrder/auditPrescription')
|
||||
&& row.can_review_prescription === true
|
||||
&& prescriptionAudit === 0
|
||||
&& ![3, 4, 6].includes(fulfillment)
|
||||
) {
|
||||
|
||||
@@ -73,6 +73,11 @@
|
||||
<el-table-column label="创建时间" prop="create_time" min-width="180" />
|
||||
<el-table-column label="最近登录时间" prop="login_time" min-width="180" />
|
||||
<el-table-column label="最近登录IP" prop="login_ip" min-width="120" />
|
||||
<el-table-column label="签署身份" min-width="120">
|
||||
<template #default="{ row }">
|
||||
{{ row.esign_signer_name || '-' }}
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="状态" min-width="100" v-perms="['auth.admin/edit']">
|
||||
<template #default="{ row }">
|
||||
<el-switch
|
||||
@@ -84,7 +89,7 @@
|
||||
/>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" width="120" fixed="right">
|
||||
<el-table-column label="操作" width="200" fixed="right">
|
||||
<template #default="{ row }">
|
||||
<el-button
|
||||
v-perms="['auth.admin/edit']"
|
||||
@@ -94,6 +99,15 @@
|
||||
>
|
||||
编辑
|
||||
</el-button>
|
||||
<el-button
|
||||
v-if="row.esign_signer_name"
|
||||
v-perms="['auth.admin/esignUnbind']"
|
||||
type="warning"
|
||||
link
|
||||
@click="handleEsignUnbind(row)"
|
||||
>
|
||||
解除签署
|
||||
</el-button>
|
||||
<el-button
|
||||
v-if="row.root != 1"
|
||||
v-perms="['auth.admin/delete']"
|
||||
@@ -116,7 +130,7 @@
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup name="admin">
|
||||
import { adminDelete, adminEdit, adminLists } from '@/api/perms/admin'
|
||||
import { adminDelete, adminEdit, adminEsignUnbind, adminLists } from '@/api/perms/admin'
|
||||
import { roleAll } from '@/api/perms/role'
|
||||
import { useDictOptions } from '@/hooks/useDictOptions'
|
||||
import { usePaging } from '@/hooks/usePaging'
|
||||
@@ -171,6 +185,14 @@ const handleDelete = async (id: number) => {
|
||||
getLists()
|
||||
}
|
||||
|
||||
const handleEsignUnbind = async (row: any) => {
|
||||
await feedback.confirm(
|
||||
`确定解除「${row.name}」绑定的签署身份(${row.esign_signer_name})?解除后该账号需重新人脸认证才能电子签署,已签处方不受影响。`
|
||||
)
|
||||
await adminEsignUnbind({ id: row.id })
|
||||
getLists()
|
||||
}
|
||||
|
||||
const { optionsData } = useDictOptions<{
|
||||
role: any[]
|
||||
}>({
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
<template>
|
||||
<div>
|
||||
<el-card class="!border-none" shadow="never">
|
||||
<el-form :model="filters" inline @submit.prevent="resetPage">
|
||||
<el-form-item label="统计日期">
|
||||
<el-date-picker
|
||||
v-model="filters.date"
|
||||
type="date"
|
||||
value-format="YYYY-MM-DD"
|
||||
:clearable="false"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item label="用户">
|
||||
<el-input v-model.trim="filters.keyword" placeholder="账号或姓名" clearable />
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-button native-type="submit" type="primary">查询</el-button>
|
||||
<el-button @click="resetFilters">重置</el-button>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
</el-card>
|
||||
|
||||
<el-card v-loading="pager.loading" class="!border-none mt-4" shadow="never">
|
||||
<div class="flex flex-wrap items-baseline gap-x-4 gap-y-1 mb-4">
|
||||
<h2 class="text-lg font-medium">桌面登录记录</h2>
|
||||
<span v-if="pager.extend?.total_day_seconds != null">
|
||||
当日会话累计 {{ durationText(pager.extend.total_day_seconds) }}
|
||||
</span>
|
||||
<span class="text-tx-secondary text-sm">按北京时间自然日统计</span>
|
||||
</div>
|
||||
<el-table :data="pager.lists" row-key="id" empty-text="当日没有匹配的桌面登录记录">
|
||||
<el-table-column
|
||||
label="账号"
|
||||
prop="account"
|
||||
min-width="120"
|
||||
show-overflow-tooltip
|
||||
/>
|
||||
<el-table-column label="姓名" prop="name" min-width="100" show-overflow-tooltip />
|
||||
<el-table-column label="登录时间" prop="login_time" width="176" />
|
||||
<el-table-column label="退出时间" width="176">
|
||||
<template #default="{ row }">{{ row.logout_time || '—' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="本次登录时长" min-width="130">
|
||||
<template #default="{ row }">{{ durationText(row.duration_seconds) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="计入当日" min-width="130">
|
||||
<template #default="{ row }">{{ durationText(row.day_seconds) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="状态" min-width="100">
|
||||
<template #default="{ row }">
|
||||
<el-tooltip
|
||||
v-if="row.status === 'timeout'"
|
||||
content="连续 3 分钟未收到心跳,退出时间按最后一次确认在线的时间记录"
|
||||
placement="top"
|
||||
>
|
||||
<el-tag type="warning" effect="plain">{{ row.status_label }}</el-tag>
|
||||
</el-tooltip>
|
||||
<el-tag
|
||||
v-else
|
||||
:type="row.status === 'online' ? 'success' : 'info'"
|
||||
effect="plain"
|
||||
>
|
||||
{{ row.status_label }}
|
||||
</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
<div class="flex mt-4 justify-end">
|
||||
<pagination v-model="pager" @change="getLists" />
|
||||
</div>
|
||||
</el-card>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup name="desktopSessions">
|
||||
import { desktopSessionLists } from '@/api/setting/system'
|
||||
import { usePaging } from '@/hooks/usePaging'
|
||||
|
||||
const beijingDate = () =>
|
||||
new Intl.DateTimeFormat('sv-SE', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit'
|
||||
}).format(new Date())
|
||||
|
||||
const filters = reactive({ date: beijingDate(), keyword: '' })
|
||||
const { pager, getLists, resetPage } = usePaging({
|
||||
fetchFun: desktopSessionLists,
|
||||
params: filters,
|
||||
latestOnly: true,
|
||||
firstLoading: true
|
||||
})
|
||||
|
||||
function resetFilters() {
|
||||
filters.date = beijingDate()
|
||||
filters.keyword = ''
|
||||
resetPage()
|
||||
}
|
||||
|
||||
function durationText(seconds: number) {
|
||||
const hours = Math.floor(seconds / 3600)
|
||||
const minutes = Math.floor((seconds % 3600) / 60)
|
||||
if (hours) return `${hours}小时${minutes}分${seconds % 60}秒`
|
||||
if (minutes) return `${minutes}分${seconds % 60}秒`
|
||||
return `${seconds % 60}秒`
|
||||
}
|
||||
|
||||
onMounted(() => getLists())
|
||||
</script>
|
||||
@@ -8,7 +8,7 @@
|
||||
clearable
|
||||
filterable
|
||||
placeholder="全部"
|
||||
class="w-[160px]"
|
||||
class="!w-[160px]"
|
||||
@change="doSearch"
|
||||
>
|
||||
<el-option
|
||||
@@ -30,7 +30,7 @@
|
||||
node-key="id"
|
||||
:default-expand-all="true"
|
||||
:props="deptTreeProps"
|
||||
class="w-[200px]"
|
||||
class="!w-[200px]"
|
||||
@change="doSearch"
|
||||
/>
|
||||
</el-form-item>
|
||||
@@ -39,7 +39,7 @@
|
||||
v-model="queryParams.state"
|
||||
clearable
|
||||
placeholder="全部"
|
||||
class="w-[170px]"
|
||||
class="!w-[170px]"
|
||||
@change="doSearch"
|
||||
>
|
||||
<el-option
|
||||
@@ -55,7 +55,7 @@
|
||||
v-model="queryParams.days_bucket"
|
||||
clearable
|
||||
placeholder="全部"
|
||||
class="w-[120px]"
|
||||
class="!w-[120px]"
|
||||
@change="doSearch"
|
||||
>
|
||||
<el-option
|
||||
@@ -66,6 +66,22 @@
|
||||
/>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="诊次">
|
||||
<el-select
|
||||
v-model="queryParams.slot"
|
||||
clearable
|
||||
placeholder="全部"
|
||||
class="!w-[130px]"
|
||||
@change="doSearch"
|
||||
>
|
||||
<el-option
|
||||
v-for="opt in slotOptions"
|
||||
:key="opt.value"
|
||||
:label="opt.label"
|
||||
:value="opt.value"
|
||||
/>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="延迟次数 ≥">
|
||||
<el-input-number
|
||||
v-model="minSnooze"
|
||||
@@ -84,7 +100,7 @@
|
||||
v-model="queryParams.keyword"
|
||||
placeholder="患者姓名"
|
||||
clearable
|
||||
class="w-[160px]"
|
||||
class="!w-[160px]"
|
||||
@keyup.enter="doSearch"
|
||||
@clear="doSearch"
|
||||
/>
|
||||
@@ -97,7 +113,7 @@
|
||||
:fetch-fun="revisitDueLists"
|
||||
:params="queryParams"
|
||||
:page-size="pager.size"
|
||||
export-hint="导出范围与当前筛选一致(医助 / 部门 / 状态 / 开药天数 / 延迟次数 / 患者)"
|
||||
export-hint="导出范围与当前筛选一致(医助 / 部门 / 状态 / 开药天数 / 诊次 / 延迟次数 / 患者)"
|
||||
/>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
@@ -117,6 +133,8 @@
|
||||
stripe
|
||||
row-key="id"
|
||||
:row-class-name="rowClassName"
|
||||
:default-sort="{ prop: 'due_date', order: 'descending' }"
|
||||
@sort-change="onSortChange"
|
||||
>
|
||||
<el-table-column label="患者" min-width="120" fixed="left">
|
||||
<template #default="{ row }">
|
||||
@@ -165,7 +183,13 @@
|
||||
<span v-else class="text-missing">缺开药天数</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="预计复诊" width="110">
|
||||
<el-table-column
|
||||
label="预计复诊"
|
||||
prop="due_date"
|
||||
width="120"
|
||||
sortable="custom"
|
||||
:sort-orders="['descending', 'ascending']"
|
||||
>
|
||||
<template #default="{ row }">
|
||||
<div class="cell-main">{{ row.due_date || '—' }}</div>
|
||||
<div v-if="row.anchor_date" class="cell-sub">
|
||||
@@ -377,6 +401,13 @@ const router = useRouter()
|
||||
/** 状态筛选:诊单列表的 7 个状态 + 主管视图专有「人工关闭」 */
|
||||
const stateOptions = [...REVISIT_STATE_FILTER_OPTIONS, { label: '人工关闭', value: 'closed' }]
|
||||
|
||||
/** 诊次筛选(按当前已完成诊次 current_slot):0 = 未成交,1~5 精确,6+ = 第 6 诊及以上 */
|
||||
const slotOptions = [
|
||||
{ label: '未成交', value: '0' },
|
||||
...[1, 2, 3, 4, 5].map((n) => ({ label: `第 ${n} 诊`, value: String(n) })),
|
||||
{ label: '第 6 诊及以上', value: '6+' }
|
||||
]
|
||||
|
||||
const assistantOptions = ref<Array<{ id: number; name: string }>>([])
|
||||
const deptTreeOptions = ref<DeptTreeNode[]>([])
|
||||
const deptTreeProps = { value: 'id', label: 'name', children: 'children' }
|
||||
@@ -386,8 +417,11 @@ const queryParams = reactive<RevisitDueListsParams>({
|
||||
dept_id: '',
|
||||
state: '',
|
||||
days_bucket: '',
|
||||
slot: '',
|
||||
min_snooze: '',
|
||||
keyword: ''
|
||||
keyword: '',
|
||||
sort_field: 'due_date',
|
||||
sort_order: 'desc'
|
||||
})
|
||||
/** el-input-number 清空时为 null/undefined,单独持有后再写回 queryParams 的 '' */
|
||||
const minSnooze = ref<number | undefined>(undefined)
|
||||
@@ -399,6 +433,13 @@ const { pager, getLists, resetPage } = usePaging({
|
||||
|
||||
const doSearch = () => resetPage()
|
||||
|
||||
/** 表头排序:只在倒序 / 正序间切换(sort-orders 不含 null),切换后回到第 1 页 */
|
||||
const onSortChange = ({ order }: { prop: string | null; order: string | null }) => {
|
||||
queryParams.sort_field = 'due_date'
|
||||
queryParams.sort_order = order === 'ascending' ? 'asc' : 'desc'
|
||||
doSearch()
|
||||
}
|
||||
|
||||
const onMinSnoozeChange = (val: number | undefined | null) => {
|
||||
queryParams.min_snooze = val === null || val === undefined ? '' : Number(val)
|
||||
doSearch()
|
||||
@@ -409,6 +450,7 @@ const handleReset = () => {
|
||||
queryParams.dept_id = ''
|
||||
queryParams.state = ''
|
||||
queryParams.days_bucket = ''
|
||||
queryParams.slot = ''
|
||||
queryParams.min_snooze = ''
|
||||
queryParams.keyword = ''
|
||||
minSnooze.value = undefined
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,385 @@
|
||||
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 dialogFile = 'components/EsignDoctorDialog.vue'
|
||||
const menuFile = 'layout/default/components/header/user-drop-down.vue'
|
||||
const authUrl = 'https://smlt.esign.cn/verify?flow=synthetic'
|
||||
const currentTime = Date.parse('2026-11-19T08:00:00Z')
|
||||
const status = (changes = {}) => ({ enabled: true, status: 'unbound', cert_expires_at: 0, ...changes })
|
||||
const authenticating = (changes = {}) => status({ status: 'authenticating', auth_url: authUrl, ...changes })
|
||||
const grant = (changes = {}) => status({
|
||||
status: 'ready',
|
||||
cert_expires_at: currentTime / 1000 + 86400,
|
||||
quicksign_enabled: true,
|
||||
quicksign_expires_at: currentTime / 1000 + 600,
|
||||
quicksign_remaining_times: 5,
|
||||
...changes
|
||||
})
|
||||
|
||||
function source(filename) {
|
||||
return fs.readFileSync(path.join(__dirname, '../src', filename), 'utf8')
|
||||
}
|
||||
|
||||
function compile(filename) {
|
||||
const { descriptor, errors } = parse(source(filename), { filename })
|
||||
assert.deepEqual(errors, [])
|
||||
const script = compileScript(descriptor, { id: filename })
|
||||
const template = compileTemplate({
|
||||
source: descriptor.template.content, filename, id: filename,
|
||||
compilerOptions: { bindingMetadata: script.bindings }
|
||||
})
|
||||
assert.deepEqual(template.errors, [])
|
||||
return { script: script.content, template: descriptor.template.content }
|
||||
}
|
||||
|
||||
function load(code, imports, globals = {}) {
|
||||
const compiled = ts.transpileModule(code, {
|
||||
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS }
|
||||
}).outputText
|
||||
const exports = {}
|
||||
new Function('require', 'exports', ...Object.keys(globals), compiled)((id) => {
|
||||
assert.ok(Object.hasOwn(imports, id), `Unexpected import ${id}`)
|
||||
return imports[id]
|
||||
}, exports, ...Object.values(globals))
|
||||
return exports
|
||||
}
|
||||
|
||||
const dialogScript = compile(dialogFile)
|
||||
const menuScript = compile(menuFile)
|
||||
const urlUtil = load(source('utils/prescription-esign.ts'), { '@/api/tcm': {} })
|
||||
|
||||
const flush = () => new Promise((resolve) => setImmediate(resolve))
|
||||
|
||||
function createDialog({ read = () => status(), start = () => authenticating(), complete = () => grant() } = {}) {
|
||||
const calls = []
|
||||
const mounted = []
|
||||
const unmounted = []
|
||||
const timers = new Map()
|
||||
const document = new EventTarget()
|
||||
document.visibilityState = 'visible'
|
||||
let time = currentTime
|
||||
let timerId = 0
|
||||
const component = load(dialogScript.script, {
|
||||
vue: { ...vue, onMounted: (fn) => mounted.push(fn), onBeforeUnmount: (fn) => unmounted.push(fn) },
|
||||
'@/api/tcm': {
|
||||
prescriptionEsignDoctorStatus: async (signal) => {
|
||||
calls.push(['read', signal])
|
||||
return read(signal)
|
||||
},
|
||||
prescriptionEsignDoctorStart: async (payload) => {
|
||||
calls.push(['start', payload])
|
||||
return start(payload)
|
||||
},
|
||||
prescriptionEsignDoctorComplete: async (payload) => {
|
||||
calls.push(['complete', payload])
|
||||
return complete(payload)
|
||||
}
|
||||
},
|
||||
'@/utils/prescription-esign': urlUtil
|
||||
}, {
|
||||
document,
|
||||
Date: { now: () => time },
|
||||
setTimeout(callback, delay) {
|
||||
timers.set(++timerId, { callback, due: time + delay })
|
||||
return timerId
|
||||
},
|
||||
clearTimeout(id) { timers.delete(id) }
|
||||
}).default
|
||||
const model = component.setup({ serverTimeOffsetMs: 0 }, { expose() {}, emit() {} })
|
||||
mounted.forEach((fn) => fn())
|
||||
return {
|
||||
...model,
|
||||
calls,
|
||||
writeCalls: () => calls.filter(([kind]) => kind !== 'read'),
|
||||
async advance(ms) {
|
||||
const until = time + ms
|
||||
while (timers.size) {
|
||||
const queued = [...timers.entries()].sort((a, b) => a[1].due - b[1].due)[0]
|
||||
const [id, { callback, due }] = queued
|
||||
if (due > until) break
|
||||
timers.delete(id)
|
||||
time = due
|
||||
callback()
|
||||
await flush()
|
||||
}
|
||||
time = until
|
||||
},
|
||||
visibility(value) {
|
||||
document.visibilityState = value
|
||||
document.dispatchEvent(new Event('visibilitychange'))
|
||||
},
|
||||
unmount: () => unmounted.forEach((fn) => fn())
|
||||
}
|
||||
}
|
||||
|
||||
test('account menu requires a signed-in doctor with the signing identity button grant', async () => {
|
||||
const store = vue.reactive({ token: 'synthetic', userInfo: { id: 21, role_ids: [2], root: 1 }, perms: ['*'] })
|
||||
let mounted
|
||||
const component = load(menuScript.script, {
|
||||
vue: { ...vue, onMounted: (handler) => { mounted = handler } },
|
||||
'vue-router': { useRoute: () => ({ fullPath: '/doctor' }) },
|
||||
'@/api/tcm': { prescriptionEsignConfig: async () => ({ enabled: true, review_enabled: true, verification_method: 'quick' }) },
|
||||
'@/api/setting/system': {},
|
||||
'@/components/EsignDoctorDialog.vue': {},
|
||||
'@/stores/modules/user': { default: () => store },
|
||||
'@/utils/feedback': {},
|
||||
'@/utils/perm': { hasPermission: ([perm]) => store.perms.includes(perm) || store.perms.includes('*') },
|
||||
'@/utils/prescription-esign': { DOCTOR_ESIGN_IDENTITY_PERMISSION: 'tcm.prescription/esignDoctor' }
|
||||
}).default
|
||||
const scope = vue.effectScope()
|
||||
const menu = scope.run(() => component.setup({}, { expose() {} }))
|
||||
await mounted()
|
||||
await menu.handleCommand('doctor-esign')
|
||||
assert.equal(menu.doctorEsignOpen.value, false)
|
||||
|
||||
store.userInfo = { id: 22, role_ids: [1], root: 0 }
|
||||
store.perms = ['tcm.prescription/audit']
|
||||
await menu.handleCommand('doctor-esign')
|
||||
assert.equal(menu.doctorEsignOpen.value, false)
|
||||
await menu.handleCommand('review-esign')
|
||||
assert.equal(menu.reviewEsignOpen.value, true)
|
||||
store.perms = ['cf.prescription/edit']
|
||||
assert.equal(menu.reviewEsignOpen.value, false)
|
||||
await menu.handleCommand('doctor-esign')
|
||||
assert.equal(menu.doctorEsignOpen.value, false, 'a prescription write grant alone no longer opens the signing identity')
|
||||
store.perms = ['cf.prescription/edit', 'tcm.prescription/esignDoctor']
|
||||
await menu.handleCommand('doctor-esign')
|
||||
assert.equal(menu.doctorEsignOpen.value, true)
|
||||
store.userInfo.id = 23
|
||||
assert.equal(menu.doctorEsignOpen.value, false)
|
||||
store.token = ''
|
||||
await menu.handleCommand('doctor-esign')
|
||||
assert.equal(menu.doctorEsignOpen.value, false)
|
||||
scope.stop()
|
||||
})
|
||||
|
||||
test('opening a pending enrollment performs a GET and requires an explicit resume and completion', async () => {
|
||||
let result = authenticating()
|
||||
const settings = createDialog({ read: () => result, complete: () => status({ status: 'ready' }) })
|
||||
await flush()
|
||||
assert.equal(settings.canResume.value, true)
|
||||
assert.equal(settings.frameUrl.value, '')
|
||||
assert.deepEqual(settings.writeCalls(), [])
|
||||
await settings.advance(5000)
|
||||
assert.equal(settings.calls.length, 1)
|
||||
|
||||
settings.openAuthentication()
|
||||
assert.equal(settings.frameUrl.value, authUrl)
|
||||
result = status({ status: 'binding_required' })
|
||||
await settings.advance(5000)
|
||||
assert.equal(settings.frameUrl.value, '')
|
||||
assert.equal(settings.canComplete.value, true)
|
||||
assert.equal(settings.needsIdentityNumber.value, false)
|
||||
assert.deepEqual(settings.writeCalls(), [])
|
||||
await settings.complete()
|
||||
assert.deepEqual(settings.writeCalls(), [['complete', {}]])
|
||||
assert.equal(settings.canComplete.value, false)
|
||||
settings.unmount()
|
||||
})
|
||||
|
||||
test('certificate recheck reads a fresh result without leaving the dialog or writing enrollment', async () => {
|
||||
let result = grant({ certificate_state: 'valid' })
|
||||
const settings = createDialog({ read: () => result })
|
||||
await flush()
|
||||
assert.equal(settings.certificateLabel.value, '有效')
|
||||
assert.match(dialogScript.template, /重新校验证书/)
|
||||
assert.doesNotMatch(dialogScript.template, /切换签署账号/)
|
||||
|
||||
result = status({ status: 'renewal_required', certificate_state: 'unconfirmed' })
|
||||
await settings.checkStatus()
|
||||
assert.equal(settings.certificateLabel.value, '暂无法确认')
|
||||
assert.match(settings.guidance.value, /重新校验/)
|
||||
assert.equal(settings.statusNotice.value, '')
|
||||
assert.deepEqual(settings.writeCalls(), [])
|
||||
|
||||
result = status({ status: 'renewal_required', certificate_state: 'renewal_required' })
|
||||
await settings.checkStatus()
|
||||
assert.equal(settings.certificateLabel.value, '需要续期')
|
||||
assert.equal(settings.startLabel.value, '开始续期认证')
|
||||
|
||||
result = grant({ certificate_state: 'valid', quicksign_unavailable_reason: 'expired', quicksign_expires_at: 0 })
|
||||
await settings.checkStatus()
|
||||
assert.equal(settings.statusNotice.value, '证书校验通过。')
|
||||
assert.equal(settings.certificateLabel.value, '有效')
|
||||
assert.match(settings.guidance.value, /快捷签授权已过期/)
|
||||
assert.deepEqual(settings.calls.map(([method]) => method), ['read', 'read', 'read', 'read'])
|
||||
})
|
||||
|
||||
test('certificate renewal uses the explicitly entered mobile and clears it after starting', async () => {
|
||||
const settings = createDialog({ read: () => status({ status: 'renewal_required' }) })
|
||||
await flush()
|
||||
assert.equal(settings.startLabel.value, '开始续期认证')
|
||||
settings.mobile.value = '123'
|
||||
await settings.start()
|
||||
assert.deepEqual(settings.writeCalls(), [])
|
||||
assert.equal(settings.mobile.value, '')
|
||||
settings.mobile.value = '13800138000'
|
||||
await settings.start()
|
||||
assert.deepEqual(settings.writeCalls(), [['start', { mobile: '13800138000' }]])
|
||||
assert.equal(settings.frameUrl.value, authUrl)
|
||||
assert.equal(settings.mobile.value, '')
|
||||
settings.unmount()
|
||||
})
|
||||
|
||||
test('supplemental document is masked, short-lived and submitted only once after an explicit click', async () => {
|
||||
let finish
|
||||
const settings = createDialog({
|
||||
read: () => status({ status: 'binding_required', identity_details_required: true, identity_number: 'ignored' }),
|
||||
complete: () => new Promise((resolve) => { finish = resolve })
|
||||
})
|
||||
await flush()
|
||||
assert.match(dialogScript.template, /v-model="identityNumber"[\s\S]*?type="password"[\s\S]*?autocomplete="off"/)
|
||||
assert.equal(settings.needsIdentityNumber.value, true)
|
||||
assert.equal(settings.state.value.identity_number, undefined)
|
||||
settings.identityNumber.value = '123'
|
||||
await settings.complete()
|
||||
assert.equal(settings.identityNumber.value, '')
|
||||
assert.deepEqual(settings.writeCalls(), [])
|
||||
|
||||
settings.identityNumber.value = '11010519491231002x'
|
||||
const completion = settings.complete()
|
||||
await settings.complete()
|
||||
assert.equal(settings.identityNumber.value, '')
|
||||
assert.deepEqual(settings.writeCalls(), [['complete', { identity_number: '11010519491231002X' }]])
|
||||
settings.dismiss()
|
||||
finish(grant())
|
||||
await completion
|
||||
assert.equal(settings.state.value, null)
|
||||
settings.unmount()
|
||||
})
|
||||
|
||||
test('quick authorization reuses the bound identity and exposes its validity and remaining count', async () => {
|
||||
let result = grant({ quicksign_expires_at: 0, quicksign_remaining_times: 0, quicksign_unavailable_reason: 'exhausted' })
|
||||
const quickFields = { quicksign_enabled: true, quicksign_authorizing: true }
|
||||
const settings = createDialog({
|
||||
read: () => result,
|
||||
start: () => authenticating(quickFields),
|
||||
complete: () => grant()
|
||||
})
|
||||
await flush()
|
||||
assert.equal(settings.needsMobile.value, false)
|
||||
assert.equal(settings.startLabel.value, '授权快捷签')
|
||||
assert.match(settings.guidance.value, /次数已用完/)
|
||||
await settings.start()
|
||||
assert.equal(settings.needsMobile.value, false)
|
||||
assert.equal(settings.frameUrl.value, authUrl)
|
||||
assert.deepEqual(settings.writeCalls(), [['start', {}]])
|
||||
|
||||
result = status({ ...quickFields, status: 'binding_required' })
|
||||
await settings.advance(5000)
|
||||
assert.deepEqual(settings.writeCalls(), [['start', {}]])
|
||||
assert.equal(settings.needsIdentityNumber.value, false)
|
||||
await settings.complete()
|
||||
assert.deepEqual(settings.writeCalls(), [['start', {}], ['complete', {}]])
|
||||
assert.equal(settings.grantActive.value, true)
|
||||
assert.equal(settings.state.value.quicksign_remaining_times, 5)
|
||||
assert.match(settings.formatExpiry(settings.state.value.quicksign_expires_at), /16:10(北京时间)/)
|
||||
await settings.start()
|
||||
assert.equal(settings.writeCalls().length, 2)
|
||||
await settings.advance(595000)
|
||||
assert.equal(settings.grantActive.value, false)
|
||||
assert.match(settings.guidance.value, /已过期/)
|
||||
assert.equal(settings.canAuthorizeQuick.value, true)
|
||||
settings.unmount()
|
||||
})
|
||||
|
||||
test('blocked or failed embedded pages can recover via a read without navigating the browser', async () => {
|
||||
let result = authenticating({ auth_url: 'https://smlt.esign.cn.example.test/verify' })
|
||||
const settings = createDialog({ read: () => result })
|
||||
await flush()
|
||||
assert.equal(settings.canResume.value, false)
|
||||
assert.equal(settings.state.value.auth_url, '')
|
||||
assert.match(settings.guidance.value, /验证链接不可用/)
|
||||
assert.match(dialogScript.template, /sandbox="allow-forms allow-scripts allow-same-origin"/)
|
||||
assert.match(dialogScript.template, /referrerpolicy="no-referrer"/)
|
||||
assert.doesNotMatch(source(dialogFile), /window\.open|postMessage|allow-popups|allow-top-navigation|@load|contentWindow/)
|
||||
settings.openAuthentication()
|
||||
assert.equal(settings.frameUrl.value, '')
|
||||
result = authenticating()
|
||||
await settings.refresh()
|
||||
settings.openAuthentication()
|
||||
settings.authenticationUnavailable()
|
||||
assert.equal(settings.frameUrl.value, '')
|
||||
await settings.advance(5000)
|
||||
assert.equal(settings.calls.length, 2)
|
||||
assert.deepEqual(settings.writeCalls(), [])
|
||||
settings.unmount()
|
||||
})
|
||||
|
||||
test('hidden documents abort single-flight polling and discard a late ready result', async () => {
|
||||
let finish
|
||||
let readCount = 0
|
||||
const settings = createDialog({ read: () => {
|
||||
if (++readCount === 2) return new Promise((resolve) => { finish = resolve })
|
||||
return authenticating()
|
||||
} })
|
||||
await flush()
|
||||
settings.openAuthentication()
|
||||
await settings.advance(30000)
|
||||
assert.equal(readCount, 2)
|
||||
settings.visibility('hidden')
|
||||
assert.equal(settings.calls[1][1].aborted, true)
|
||||
assert.equal(settings.frameUrl.value, '')
|
||||
finish(status({ status: 'binding_required', identity_details_required: true }))
|
||||
await flush()
|
||||
assert.equal(settings.canComplete.value, false)
|
||||
settings.visibility('visible')
|
||||
await flush()
|
||||
assert.equal(readCount, 3)
|
||||
assert.equal(settings.canResume.value, true)
|
||||
assert.equal(settings.frameUrl.value, '')
|
||||
assert.deepEqual(settings.writeCalls(), [])
|
||||
settings.unmount()
|
||||
})
|
||||
|
||||
test('the ten-minute frame deadline aborts a status request and requires an explicit resume', async () => {
|
||||
let readCount = 0
|
||||
let finish
|
||||
const settings = createDialog({ read: () => {
|
||||
if (++readCount > 1) return new Promise((resolve) => { finish = resolve })
|
||||
return authenticating()
|
||||
} })
|
||||
await flush()
|
||||
settings.openAuthentication()
|
||||
await settings.advance(600000)
|
||||
assert.equal(settings.frameUrl.value, '')
|
||||
assert.equal(settings.calls[1][1].aborted, true)
|
||||
assert.match(settings.error.value, /自动检查已结束/)
|
||||
finish(status({ status: 'binding_required' }))
|
||||
await flush()
|
||||
assert.equal(settings.canComplete.value, false)
|
||||
assert.equal(settings.canResume.value, true)
|
||||
assert.deepEqual(settings.writeCalls(), [])
|
||||
settings.unmount()
|
||||
})
|
||||
|
||||
test('failed or inconsistent results require recovery from a fresh GET and do not disclose request data', async () => {
|
||||
let result = status({ status: 'binding_required', identity_details_required: true })
|
||||
const settings = createDialog({
|
||||
read: () => result,
|
||||
complete: () => { throw new Error('synthetic identity data 11010519491231002X') }
|
||||
})
|
||||
await flush()
|
||||
settings.identityNumber.value = '11010519491231002X'
|
||||
await settings.complete()
|
||||
assert.equal(settings.state.value, null)
|
||||
assert.equal(settings.identityNumber.value, '')
|
||||
assert.doesNotMatch(settings.error.value, /110105/)
|
||||
await settings.complete()
|
||||
assert.equal(settings.writeCalls().length, 1)
|
||||
|
||||
result = status({ status: 'binding_required', quicksign_authorizing: true, quicksign_enabled: true, identity_details_required: true })
|
||||
await settings.refresh()
|
||||
assert.equal(settings.canComplete.value, false)
|
||||
assert.equal(settings.needsIdentityNumber.value, false)
|
||||
result = status({ enabled: false })
|
||||
await settings.refresh()
|
||||
assert.equal(settings.needsMobile.value, false)
|
||||
assert.match(settings.guidance.value, /未启用/)
|
||||
settings.unmount()
|
||||
})
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,60 @@
|
||||
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 { parse, compileScript, compileTemplate } = require('@vue/compiler-sfc')
|
||||
|
||||
const viewDir = path.join(__dirname, '../src/views/consumer/prescription')
|
||||
const source = fs.readFileSync(path.join(viewDir, 'components/prescription-list-signing-status.ts'), 'utf8')
|
||||
const { outputText } = ts.transpileModule(source, {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 }
|
||||
})
|
||||
const moduleExports = {}
|
||||
new Function('exports', outputText)(moduleExports)
|
||||
const { prescriptionListSigningStatus } = moduleExports
|
||||
|
||||
test('list separates prescriber and pharmacist signing from audit outcome', () => {
|
||||
const cases = [
|
||||
[{ status: 'pending', required: true, awaiting_upload: true }, '上传后签署', 'info'],
|
||||
[{ status: 'pending' }, '待医师签署', 'warning'],
|
||||
[{ status: 'authenticating' }, '待医师确认签署', 'warning'],
|
||||
[{ status: 'signing' }, '医师签署中', 'primary'],
|
||||
[{ status: 'failed' }, '医师签署未完成', 'danger'],
|
||||
[{ status: 'uncertain' }, '医师签署待核实', 'warning'],
|
||||
[{ status: 'signed', can_download: false }, '医师签署待核实', 'warning'],
|
||||
[{ status: 'signed', can_download: true }, '医师已签署', 'success'],
|
||||
[{ status: 'signed', can_download: true, awaiting_upload: true, review_required: true }, '医师已签署', 'success'],
|
||||
[{ status: 'signed', can_download: true, review_required: true }, '待药师签署', 'warning'],
|
||||
[{ status: 'signed', can_download: true, review_required: true, review_state: 'pending' }, '待药师签署', 'warning'],
|
||||
[{ status: 'signed', can_download: true, review_required: true, review_state: 'signing' }, '药师签署中', 'primary'],
|
||||
[{ status: 'signed', can_download: true, review_required: true, review_state: 'verifying' }, '药师验签中', 'primary'],
|
||||
[{ status: 'signed', can_download: true, review_required: true, review_state: 'failed' }, '药师签署未完成', 'danger'],
|
||||
[{ status: 'signed', can_download: true, review_required: true, review_state: 'uncertain' }, '药师签署待核实', 'warning'],
|
||||
[{ status: 'signed', can_download: true, review_required: true, review_state: 'signed' }, '已完成双签', 'success'],
|
||||
[{ status: 'signed', can_download: true, review_signature_time: 1712345678 }, '已完成双签', 'success'],
|
||||
[{ status: 'legacy' }, '历史处方', 'info'],
|
||||
[{ status: 'voided' }, '已作废', 'danger'],
|
||||
[{ status: 'unavailable' }, '签署状态待核实', 'warning'],
|
||||
[undefined, '签署状态待核实', 'warning']
|
||||
]
|
||||
for (const [esign, label, type] of cases) {
|
||||
for (const audit_status of [0, 1, 2]) {
|
||||
assert.deepEqual(prescriptionListSigningStatus({ esign, audit_status }), { label, type })
|
||||
}
|
||||
}
|
||||
assert.deepEqual(prescriptionListSigningStatus({ esign: { status: 'legacy' }, void_status: '1' }),
|
||||
{ label: '已作废', type: 'danger' })
|
||||
})
|
||||
|
||||
test('issued prescription template renders signing in a dedicated table column', () => {
|
||||
const filename = path.join(viewDir, 'index.vue')
|
||||
const { descriptor, errors } = parse(fs.readFileSync(filename, 'utf8'), { filename })
|
||||
assert.deepEqual(errors, [])
|
||||
const template = descriptor.template.content
|
||||
assert.match(template, /label="审核状态"[\s\S]+?listAuditStatusLabel\(row\)[\s\S]+?<\/el-table-column>/)
|
||||
assert.match(template, /label="签署状态"[\s\S]+?prescriptionListSigningStatus\(row\)\.label[\s\S]+?<\/el-table-column>/)
|
||||
const script = compileScript(descriptor, { id: 'prescription-list' })
|
||||
const compiled = compileTemplate({ filename, source: template, id: 'prescription-list', compilerOptions: { bindingMetadata: script.bindings } })
|
||||
assert.deepEqual(compiled.errors, [])
|
||||
})
|
||||
File diff suppressed because one or more lines are too long
+3
-1
@@ -81,7 +81,9 @@ DOCTOR_VERIFY_SSL=true
|
||||
|
||||
程序会自动在地址末尾追加 `/adminapi`。它与现有管理端保持相同约定:
|
||||
|
||||
- 登录:`POST /login/account`,请求包含 `account`、`password`、`terminal=1`。
|
||||
- 工作站使用 `POST /login/account` 登录,请求包含 `account`、`password` 和独立的 `terminal=21`。升级前保存的登录凭据需要重新登录一次。
|
||||
- 工作站每 60 秒调用 `POST /login/desktopHeartbeat`。每次登录的有效期截至下一个北京时间 05:00,登录和心跳响应中的 `desktop_expires_at` 为 Unix 秒。退出账号或关闭应用时通过 `POST /login/logout` 结束会话。
|
||||
- Web 后台的「桌面登录记录」支持按日期、账号或姓名调阅。跨北京时间零点的会话按实际重叠时段计入各日。断线超过心跳宽限时,退出时间按服务器最后确认在线的时间记录。
|
||||
- 鉴权请求头:`token: <登录 token>`,`version: 1.9.4`。
|
||||
- 响应 envelope:`code=1` 成功、`0` 业务失败、`-1` 登录失效、`10` 需绑定企业微信。
|
||||
- 权限与数据范围:完全以后端 `/auth.admin/mySelf` 返回为准。
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
__all__ = ["DEBUG_MODE", "ONLINE_API_BASE_URL", "__version__"]
|
||||
|
||||
# Single source of truth for runtime, package, installer, and executable versions.
|
||||
__version__ = "1.5.3"
|
||||
__version__ = "1.5.6"
|
||||
|
||||
# 调试模式开启时,登录页显示“演示模式”和“服务器设置”。
|
||||
# 正式发布请保持 False;此时程序只使用下面配置的线上域名。
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
@@ -10,7 +11,7 @@ from collections.abc import Mapping, Sequence
|
||||
from contextlib import suppress
|
||||
from typing import Any
|
||||
|
||||
from PySide6.QtCore import QLibraryInfo, QLocale, QObject, Qt, QTimer, QTranslator
|
||||
from PySide6.QtCore import QLibraryInfo, QLocale, QObject, Qt, QThreadPool, QTimer, QTranslator
|
||||
from PySide6.QtGui import QGuiApplication, QIcon
|
||||
from PySide6.QtWidgets import (
|
||||
QApplication,
|
||||
@@ -423,9 +424,18 @@ class ApplicationController(QObject):
|
||||
self._restore_worker: Any = None
|
||||
self._shutting_down = False
|
||||
self._authentication_expiry_in_progress = False
|
||||
self._desktop_session: Session | None = None
|
||||
self._heartbeat_pending = False
|
||||
self._next_heartbeat_at = 0.0
|
||||
self._session_workers = QThreadPool(self)
|
||||
self._session_workers.setMaxThreadCount(2)
|
||||
self._desktop_timer = QTimer(self)
|
||||
self._desktop_timer.setSingleShot(True)
|
||||
self._desktop_timer.setTimerType(Qt.TimerType.PreciseTimer)
|
||||
self._desktop_timer.timeout.connect(self._check_desktop_session)
|
||||
application.applicationStateChanged.connect(self._check_desktop_session)
|
||||
self._rebuild_remote_repository()
|
||||
self.app_updater = AppUpdateSession(self)
|
||||
set_authentication_expired_handler(self._on_authentication_expired)
|
||||
application.aboutToQuit.connect(self.shutdown)
|
||||
|
||||
def start(self) -> None:
|
||||
@@ -529,7 +539,7 @@ class ApplicationController(QObject):
|
||||
self.remote_repository = repository
|
||||
if old is not None and old is not self.current_repository:
|
||||
with suppress(Exception):
|
||||
old.client.close()
|
||||
old.close()
|
||||
|
||||
def _begin_session_restore(self) -> None:
|
||||
"""Validate a scoped persisted token without racing manual login."""
|
||||
@@ -655,6 +665,8 @@ class ApplicationController(QObject):
|
||||
self.login_window.set_session_restore_pending(False)
|
||||
|
||||
def _on_login_succeeded(self, payload: dict[str, Any]) -> None:
|
||||
if self._shutting_down:
|
||||
return
|
||||
self._cancel_session_restore()
|
||||
session = payload.get("session")
|
||||
repository = payload.get("repository")
|
||||
@@ -683,13 +695,22 @@ class ApplicationController(QObject):
|
||||
self.current_repository = repository
|
||||
self._authentication_expiry_in_progress = False
|
||||
self.current_demo_mode = demo_mode
|
||||
set_authentication_expired_handler(self._on_authentication_expired)
|
||||
self.shell_window = ShellWindow(repository, payload, session.permissions)
|
||||
self.shell_window.logout_requested.connect(self._logout)
|
||||
self.shell_window.close_requested.connect(self.request_quit)
|
||||
self.shell_window.video_requested.connect(self._request_video)
|
||||
self.shell_window.update_check_requested.connect(
|
||||
lambda: self.app_updater.check(interactive=True)
|
||||
)
|
||||
self._apply_window_icon(self.shell_window)
|
||||
if isinstance(repository, RemoteDoctorRepository):
|
||||
self._desktop_session = session
|
||||
self._heartbeat_pending = False
|
||||
self._next_heartbeat_at = time.time() + 60
|
||||
self._check_desktop_session()
|
||||
if self.shell_window is None:
|
||||
return
|
||||
if self.login_window is not None:
|
||||
self.login_window.hide()
|
||||
self.shell_window.show()
|
||||
@@ -697,6 +718,45 @@ class ApplicationController(QObject):
|
||||
self.shell_window.activateWindow()
|
||||
self.app_updater.schedule(delay_ms=400)
|
||||
|
||||
def _check_desktop_session(self, *_args: Any) -> None:
|
||||
"""Check wall time even when idle, minimized or returning from sleep."""
|
||||
|
||||
session = self._desktop_session
|
||||
repository = self.current_repository
|
||||
if session is None or repository is None or self._shutting_down:
|
||||
return
|
||||
now = time.time()
|
||||
remaining = session.desktop_expires_at - now
|
||||
if remaining <= 0:
|
||||
self._logout(message="已到北京时间 05:00,请重新登录医生工作站。")
|
||||
return
|
||||
# A repeating wall-clock check also catches clock changes and resume on
|
||||
# platforms where a long monotonic timer pauses during system sleep.
|
||||
self._desktop_timer.start(max(1, min(1000, math.ceil(remaining * 1000))))
|
||||
if self._heartbeat_pending or now < self._next_heartbeat_at:
|
||||
return
|
||||
self._heartbeat_pending = True
|
||||
self._next_heartbeat_at = now + 60
|
||||
|
||||
def received(deadline: int) -> None:
|
||||
if self._desktop_session is session:
|
||||
self._heartbeat_pending = False
|
||||
session.desktop_expires_at = min(session.desktop_expires_at, deadline)
|
||||
self._check_desktop_session()
|
||||
|
||||
def failed(_error: Exception) -> None:
|
||||
if self._desktop_session is session:
|
||||
self._heartbeat_pending = False
|
||||
self._next_heartbeat_at = time.time() + 15
|
||||
|
||||
run_async(
|
||||
repository.desktop_heartbeat,
|
||||
session.token,
|
||||
on_success=received,
|
||||
on_error=failed,
|
||||
pool=self._session_workers,
|
||||
)
|
||||
|
||||
def _login_guard_error(self, message: str) -> None:
|
||||
if self.login_window is not None:
|
||||
self.login_window.error_banner.show_message(message, "warning")
|
||||
@@ -720,6 +780,9 @@ class ApplicationController(QObject):
|
||||
def _logout(self, *, message: str = "") -> None:
|
||||
"""Clear authenticated resources and return to the login window."""
|
||||
|
||||
self._desktop_session = None
|
||||
self._desktop_timer.stop()
|
||||
set_authentication_expired_handler(None)
|
||||
self._restore_video_preview(activate=False)
|
||||
calls = tuple(self.video_calls.values())
|
||||
for call in calls:
|
||||
@@ -729,18 +792,27 @@ class ApplicationController(QObject):
|
||||
self.video_calls.clear()
|
||||
self.video_pending.clear()
|
||||
self._pending_im_request = None
|
||||
for dialog in self.demo_video_dialogs.values():
|
||||
for dialog in tuple(self.demo_video_dialogs.values()):
|
||||
dialog.close()
|
||||
self.demo_video_dialogs.clear()
|
||||
if self.current_repository is not None:
|
||||
repository = self.current_repository
|
||||
if isinstance(repository, RemoteDoctorRepository):
|
||||
# Stale queued requests retain their old client. Detach locally
|
||||
# before enabling login and release the remote session off-thread.
|
||||
token = repository.detach_session()
|
||||
self.remote_repository = None
|
||||
self._rebuild_remote_repository()
|
||||
run_async(repository.close, token, pool=self._session_workers)
|
||||
elif repository is not None:
|
||||
with suppress(Exception):
|
||||
self.current_repository.logout()
|
||||
repository.logout()
|
||||
self.current_repository = None
|
||||
self._show_login()
|
||||
if self.shell_window is not None:
|
||||
self.shell_window.close_requested.disconnect(self.request_quit)
|
||||
self.shell_window.close()
|
||||
self.shell_window.deleteLater()
|
||||
self.shell_window = None
|
||||
self._show_login()
|
||||
if message and self.login_window is not None:
|
||||
self.login_window.error_banner.show_message(message, "warning")
|
||||
|
||||
@@ -1130,6 +1202,8 @@ class ApplicationController(QObject):
|
||||
if self._shutting_down:
|
||||
return
|
||||
self._shutting_down = True
|
||||
self._desktop_session = None
|
||||
self._desktop_timer.stop()
|
||||
self._cancel_session_restore()
|
||||
self.app_updater.shutdown()
|
||||
set_authentication_expired_handler(None)
|
||||
@@ -1141,7 +1215,7 @@ class ApplicationController(QObject):
|
||||
self._wait_for_video_lifecycle(calls, timeout=1.25)
|
||||
if self.remote_repository is not None:
|
||||
with suppress(Exception):
|
||||
self.remote_repository.client.close()
|
||||
self.remote_repository.close()
|
||||
|
||||
|
||||
def _prefer_native_tls_backend() -> None:
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
"""Server-authoritative electronic signature DTOs and original-file validation."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import hmac
|
||||
import re
|
||||
from collections.abc import Mapping
|
||||
from typing import Any
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from .errors import ApiProtocolError
|
||||
|
||||
ESIGN_LABELS = {
|
||||
"pending": "待签署",
|
||||
"authenticating": "待完成核身",
|
||||
"signing": "签署中",
|
||||
"signed": "已签署",
|
||||
"failed": "签署失败",
|
||||
"uncertain": "签署结果待确认",
|
||||
"voided": "已失效",
|
||||
"legacy": "历史手写签名",
|
||||
}
|
||||
|
||||
_DOCTOR_IDENTITY_STATES = {
|
||||
"unbound", "needs_mobile", "authenticating", "binding_required", "ready", "renewal_required",
|
||||
}
|
||||
_QUICKSIGN_UNAVAILABLE_REASONS = ("missing", "expired", "exhausted", "invalid")
|
||||
|
||||
|
||||
def esign_config(value: Any) -> dict[str, Any]:
|
||||
if (
|
||||
not isinstance(value, Mapping)
|
||||
or not isinstance(value.get("enabled"), bool)
|
||||
or value.get("environment") not in {"sandbox", "production"}
|
||||
or ("verification_method" in value and not isinstance(value["verification_method"], str))
|
||||
):
|
||||
raise ApiProtocolError("电子签署配置格式不正确")
|
||||
return dict(value)
|
||||
|
||||
|
||||
def esign_status(value: Any) -> dict[str, Any]:
|
||||
result = esign_config(value)
|
||||
if (
|
||||
result.get("status") not in ESIGN_LABELS
|
||||
or any(not isinstance(result.get(key), bool) for key in ("required", "can_sign", "can_download"))
|
||||
or any(not isinstance(result.get(key, False), bool) for key in (
|
||||
"can_resume_identity", "can_retry_verify", "doctor_identity_required", "sms_sent",
|
||||
"signing_authorization_required", "awaiting_upload", "can_submit_for_review", "can_review_prescription",
|
||||
))
|
||||
or ("review_submitted_at" in result and (
|
||||
type(result["review_submitted_at"]) is not int or result["review_submitted_at"] < 0
|
||||
))
|
||||
or ("signing_authorization_reason" in result
|
||||
and result["signing_authorization_reason"] not in _QUICKSIGN_UNAVAILABLE_REASONS)
|
||||
):
|
||||
raise ApiProtocolError("电子签署状态格式不正确")
|
||||
return result
|
||||
|
||||
|
||||
def esign_identity_status(value: Any) -> dict[str, Any]:
|
||||
"""Validate a read-only, server-authoritative identity readiness response."""
|
||||
result = esign_status(value)
|
||||
if result.get("identity_status") not in {"INIT", "ING", "SUCCESS", "FAIL", "EXPIRED", "UNAVAILABLE"} or not isinstance(result.get("can_complete"), bool):
|
||||
raise ApiProtocolError("核身查询结果格式不正确")
|
||||
details_required = result.get("identity_details_required", False)
|
||||
if not isinstance(details_required, bool):
|
||||
raise ApiProtocolError("证书身份补录状态格式不正确")
|
||||
method = result.get("verification_method")
|
||||
authorized = (
|
||||
result["identity_status"] == "SUCCESS"
|
||||
and ((result["status"] == "authenticating" and result.get("can_resume_identity", method != "quick") is True)
|
||||
or (result["status"] == "failed" and result.get("can_resume_identity") is True))
|
||||
and result["enabled"] and result["required"] and result["can_sign"]
|
||||
and result.get("doctor_identity_required") is not True
|
||||
and result.get("signing_authorization_required") is not True
|
||||
)
|
||||
if (result["can_complete"] and not authorized) or (
|
||||
details_required and (
|
||||
not authorized or result["can_complete"] or method in {"sms", "quick"}
|
||||
)
|
||||
):
|
||||
raise ApiProtocolError("核身查询结果与签署权限不一致")
|
||||
result["identity_details_required"] = details_required
|
||||
return result
|
||||
|
||||
|
||||
def esign_doctor_status(value: Any) -> dict[str, Any]:
|
||||
"""Validate independent enrollment and retain only display or workflow fields."""
|
||||
if not isinstance(value, Mapping):
|
||||
raise ApiProtocolError("医生签署身份状态格式不正确")
|
||||
enabled, status = value.get("enabled"), value.get("status")
|
||||
expiry = value.get("cert_expires_at", 0)
|
||||
details = value.get("identity_details_required", False)
|
||||
quick_enabled = value.get("quicksign_enabled", False)
|
||||
quick_expiry = value.get("quicksign_expires_at", 0)
|
||||
quick_authorizing = value.get("quicksign_authorizing", False)
|
||||
quick_remaining = value.get("quicksign_remaining_times", 0)
|
||||
quick_unavailable = value.get("quicksign_unavailable_reason", "")
|
||||
signer_name_editable = value.get("can_edit_signer_name", False)
|
||||
if (
|
||||
not isinstance(enabled, bool)
|
||||
or not isinstance(status, str) or status not in _DOCTOR_IDENTITY_STATES
|
||||
or type(expiry) is not int or not 0 <= expiry <= 253402300799
|
||||
or not isinstance(details, bool)
|
||||
or (details and (not enabled or status != "binding_required"))
|
||||
or not isinstance(quick_enabled, bool)
|
||||
or type(quick_expiry) is not int or not 0 <= quick_expiry <= 253402300799
|
||||
or not isinstance(quick_authorizing, bool)
|
||||
or type(quick_remaining) is not int or quick_remaining < 0
|
||||
or quick_unavailable not in ("", *_QUICKSIGN_UNAVAILABLE_REASONS)
|
||||
or (quick_authorizing and (
|
||||
not enabled or not quick_enabled or details or status not in {"authenticating", "binding_required"}
|
||||
))
|
||||
or not isinstance(signer_name_editable, bool)
|
||||
):
|
||||
raise ApiProtocolError("医生签署身份状态格式不正确")
|
||||
result = {"enabled": enabled, "status": status, "cert_expires_at": expiry,
|
||||
"identity_details_required": details, "quicksign_enabled": quick_enabled,
|
||||
"quicksign_expires_at": quick_expiry, "quicksign_authorizing": quick_authorizing}
|
||||
if "quicksign_remaining_times" in value:
|
||||
result["quicksign_remaining_times"] = quick_remaining
|
||||
if quick_unavailable:
|
||||
result["quicksign_unavailable_reason"] = quick_unavailable
|
||||
if enabled and signer_name_editable and not quick_authorizing:
|
||||
# 服务端仅对未绑定签署账号的非医生审核人下发,医生账号仍以后台登记姓名认证。
|
||||
result["can_edit_signer_name"] = True
|
||||
if enabled and status == "authenticating" and value.get("auth_url"):
|
||||
result["auth_url"] = authentication_url(value["auth_url"])
|
||||
return result
|
||||
|
||||
|
||||
def esign_doctor_mobile(value: Any) -> str:
|
||||
mobile = value.strip() if isinstance(value, str) else ""
|
||||
if not re.fullmatch(r"1[3-9][0-9]{9}", mobile):
|
||||
raise ValueError("请输入 11 位中国大陆手机号码。")
|
||||
return mobile
|
||||
|
||||
|
||||
# 与服务端 /^[\p{Han}A-Za-z][\p{Han}A-Za-z·()\-]{1,49}$/u 保持一致。
|
||||
_HAN = "\u3007\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\U00020000-\U0003134f"
|
||||
_SIGNER_NAME = re.compile(f"[{_HAN}A-Za-z][{_HAN}A-Za-z·()\\-]{{1,49}}")
|
||||
|
||||
|
||||
def esign_signer_name(value: Any) -> str:
|
||||
name = value.strip() if isinstance(value, str) else ""
|
||||
if not _SIGNER_NAME.fullmatch(name):
|
||||
raise ValueError("证件姓名须为 2 至 50 个字符,以汉字或英文字母开头,可包含间隔号(·)、半角括号和连字符。")
|
||||
return name
|
||||
|
||||
|
||||
def esign_sms_code(value: Any) -> str:
|
||||
code = value.strip() if isinstance(value, str) else ""
|
||||
if not re.fullmatch(r"[0-9]{6}", code):
|
||||
raise ValueError("请输入短信中的六位数字验证码。")
|
||||
return code
|
||||
|
||||
|
||||
def certificate_identity_number(value: Any) -> str:
|
||||
"""Validate only mainland ID shape; the server verifies the authenticated person."""
|
||||
if not isinstance(value, str):
|
||||
raise ValueError("请输入 15 或 18 位中国大陆居民身份证号码,18 位号码末位可以是 X。")
|
||||
number = value.strip().upper()
|
||||
if not re.fullmatch(r"[1-9](?:[0-9]{14}|[0-9]{16}[0-9X])", number):
|
||||
raise ValueError("请输入 15 或 18 位中国大陆居民身份证号码,18 位号码末位可以是 X。")
|
||||
return number
|
||||
|
||||
|
||||
def authentication_navigation_allowed(value: Any) -> bool:
|
||||
"""Restrict embedded documents to HTTPS on the provider's own domains."""
|
||||
url = str(value or "")
|
||||
try:
|
||||
parts = urlsplit(url)
|
||||
host = parts.hostname or ""
|
||||
return bool(
|
||||
parts.scheme == "https"
|
||||
and host.isascii() and "%" not in host
|
||||
and any(host.endswith("." + domain) for domain in ("esign.cn", "tsign.cn"))
|
||||
and not parts.username and not parts.password
|
||||
and (parts.port in (None, 443) or (host == "smlfront.esign.cn" and parts.port == 8890))
|
||||
and not any(ord(char) < 33 or char == "\\" for char in url)
|
||||
)
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def authentication_url(value: Any) -> str:
|
||||
"""Accept only an HTTPS link returned by the authenticated application server."""
|
||||
url = str(value or "").strip()
|
||||
try:
|
||||
parts = urlsplit(url)
|
||||
valid = (
|
||||
parts.scheme == "https"
|
||||
and parts.hostname in {"smlt.esign.cn", "smlfront.esign.cn", "t.esign.cn", "idverify.esign.cn"}
|
||||
and not parts.username
|
||||
and not parts.password
|
||||
and (parts.port in (None, 443) or (parts.hostname == "smlfront.esign.cn" and parts.port == 8890))
|
||||
and not any(ord(char) < 32 or char == "\\" for char in url)
|
||||
)
|
||||
except ValueError:
|
||||
valid = False
|
||||
if not valid:
|
||||
raise ValueError("核身链接无效,请重新查询签署状态。")
|
||||
return url
|
||||
|
||||
|
||||
def signed_pdf_bytes(value: Any) -> bytes:
|
||||
if not isinstance(value, Mapping):
|
||||
raise ApiProtocolError("已签原件数据格式不正确")
|
||||
try:
|
||||
content = base64.b64decode(value.get("content_base64", ""), validate=True)
|
||||
except (ValueError, TypeError, binascii.Error) as error:
|
||||
raise ApiProtocolError("已签原件编码不正确") from error
|
||||
expected = str(value.get("sha256") or "").lower()
|
||||
if not content.startswith(b"%PDF-") or not hmac.compare_digest(
|
||||
hashlib.sha256(content).hexdigest(), expected
|
||||
):
|
||||
raise ApiProtocolError("已签原件校验失败,请重试下载")
|
||||
return content
|
||||
@@ -614,6 +614,7 @@ class Prescription:
|
||||
aux_usage: JSONDict = field(default_factory=dict)
|
||||
doctor_name: str = ""
|
||||
doctor_signature: str = ""
|
||||
esign: JSONDict = field(default_factory=dict)
|
||||
creator_id: int | None = None
|
||||
assistant_name: str = ""
|
||||
is_system_auto: bool = False
|
||||
@@ -623,6 +624,8 @@ class Prescription:
|
||||
audit_time: str = ""
|
||||
audit_by_name: str = ""
|
||||
audit_remark: str = ""
|
||||
review_submitted_at: int | None = None
|
||||
can_submit_for_review: bool = False
|
||||
business_prescription_audit_status: int | None = None
|
||||
business_prescription_audit_rejected: bool = False
|
||||
business_prescription_audit_remark: str = ""
|
||||
@@ -687,6 +690,7 @@ class Prescription:
|
||||
aux_usage=dict(_mapping(source.get("aux_usage"))),
|
||||
doctor_name=_text(source.get("doctor_name")),
|
||||
doctor_signature=_text(source.get("doctor_signature")),
|
||||
esign=dict(_mapping(source.get("esign"))),
|
||||
creator_id=_integer(source.get("creator_id"), None),
|
||||
assistant_name=_text(source.get("assistant_name")),
|
||||
is_system_auto=_boolean(source.get("is_system_auto")),
|
||||
@@ -696,6 +700,8 @@ class Prescription:
|
||||
audit_time=_text(source.get("audit_time")),
|
||||
audit_by_name=_text(source.get("audit_by_name")),
|
||||
audit_remark=_text(source.get("audit_remark")),
|
||||
review_submitted_at=_integer(source.get("review_submitted_at"), None),
|
||||
can_submit_for_review=source.get("can_submit_for_review") is True,
|
||||
business_prescription_audit_status=_integer(
|
||||
source.get("business_prescription_audit_status"), None
|
||||
),
|
||||
@@ -764,6 +770,7 @@ class Prescription:
|
||||
"aux_usage": dict(self.aux_usage),
|
||||
"doctor_name": self.doctor_name,
|
||||
"doctor_signature": self.doctor_signature,
|
||||
"esign": dict(self.esign),
|
||||
"is_shared": int(self.is_shared),
|
||||
"visible_role_ids": list(self.visible_role_ids),
|
||||
"audit_status": self.audit_status,
|
||||
|
||||
@@ -20,6 +20,7 @@ class Session:
|
||||
is_paw: int = 1
|
||||
need_bind_work_wechat: bool = False
|
||||
metadata: dict[str, Any] = field(default_factory=dict, repr=False)
|
||||
desktop_expires_at: int = 0
|
||||
|
||||
@property
|
||||
def authenticated(self) -> bool:
|
||||
|
||||
@@ -181,11 +181,13 @@ class ApiClient:
|
||||
*,
|
||||
headers: Mapping[str, str] | None = None,
|
||||
timeout: float | httpx.Timeout | None = None,
|
||||
max_retries: int | None = None,
|
||||
) -> Any:
|
||||
"""Issue a GET request and return the unwrapped envelope data."""
|
||||
|
||||
return self.request(
|
||||
"GET", endpoint, params=params, headers=headers, timeout=timeout
|
||||
"GET", endpoint, params=params, headers=headers, timeout=timeout,
|
||||
max_retries=max_retries,
|
||||
)
|
||||
|
||||
def post(
|
||||
@@ -239,15 +241,18 @@ class ApiClient:
|
||||
payload: Mapping[str, Any],
|
||||
*,
|
||||
timeout: float = 10.0,
|
||||
headers: Mapping[str, str] | None = None,
|
||||
) -> Any:
|
||||
"""Send a short control request without waiting for the ordinary pool."""
|
||||
|
||||
if not self._owns_client:
|
||||
return self.post(endpoint, payload, timeout=timeout, headers=headers)
|
||||
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),
|
||||
headers=self._headers(headers),
|
||||
timeout=timeout,
|
||||
)
|
||||
return self._unwrap(response)
|
||||
@@ -497,6 +502,7 @@ class ApiClient:
|
||||
files: Mapping[str, Any] | None = None,
|
||||
headers: Mapping[str, str] | None = None,
|
||||
timeout: float | httpx.Timeout | None = None,
|
||||
max_retries: int | None = None,
|
||||
) -> Any:
|
||||
"""Issue one API request with structured transport/envelope errors."""
|
||||
|
||||
@@ -514,7 +520,10 @@ class ApiClient:
|
||||
headers,
|
||||
json_content_type=files is None and data is None,
|
||||
)
|
||||
attempts = self.max_retries + 1 if verb == "GET" else 1
|
||||
if max_retries is not None and max_retries < 0:
|
||||
raise ValueError("max_retries must be non-negative")
|
||||
retries = self.max_retries if max_retries is None else max_retries
|
||||
attempts = retries + 1 if verb == "GET" else 1
|
||||
response: httpx.Response | None = None
|
||||
request_timeout = self.timeout if timeout is None else timeout
|
||||
with self._borrow_client() as client:
|
||||
|
||||
@@ -694,6 +694,19 @@ class LocalAudioUploadManager:
|
||||
finally:
|
||||
self._transcription_jobs.task_done()
|
||||
|
||||
def _find_call(self, record: LocalAudioRecord) -> dict[str, Any] | None:
|
||||
records = self.repository.list_call_records(record.diagnosis_id)
|
||||
return next(
|
||||
(row for row in records if isinstance(row, dict)
|
||||
and str(row.get("id")) == str(record.call_record_id)),
|
||||
None,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _server_text_complete(call: dict[str, Any]) -> bool:
|
||||
return (call.get("transcription_status") == "completed"
|
||||
and bool(str(call.get("transcript_text") or "").strip()))
|
||||
|
||||
def _transcribe(self, record_id: int) -> bool:
|
||||
record = self.store.claim_transcription(record_id)
|
||||
if record is None:
|
||||
@@ -702,23 +715,28 @@ class LocalAudioUploadManager:
|
||||
save = getattr(self.repository, "save_local_audio_transcript", None)
|
||||
if not callable(save):
|
||||
raise RecordingTranscriptionError("当前服务未提供文字补全接口,请更新应用及服务端。")
|
||||
records = self.repository.list_call_records(record.diagnosis_id)
|
||||
call = next(
|
||||
(row for row in records if isinstance(row, dict)
|
||||
and str(row.get("id")) == str(record.call_record_id)),
|
||||
None,
|
||||
)
|
||||
call = self._find_call(record)
|
||||
if call is None:
|
||||
raise RecordingTranscriptionError("未找到对应通话记录,请检查账号和诊单后重试文字。")
|
||||
if call.get("transcription_status") == "completed" and str(call.get("transcript_text") or "").strip():
|
||||
# 本机队列跨服务器、跨账号保留:换了服务器后旧录音的通话记录在当前服务器不存在。
|
||||
raise RecordingTranscriptionError(
|
||||
f"当前服务器的诊单 {record.diagnosis_id} 下没有通话记录 "
|
||||
f"{record.call_record_id},请确认登录的服务器与录音时一致后重试文字。"
|
||||
)
|
||||
if self._server_text_complete(call):
|
||||
self.store.finish_transcription(record.id)
|
||||
self._notify_uploaded(record.id)
|
||||
return True
|
||||
user = self.repository.get_current_user()
|
||||
if (int(getattr(user, "id", 0) or 0) <= 0
|
||||
or str(call.get("caller_id")) != str(user.id)
|
||||
user_id = int(getattr(user, "id", 0) or 0)
|
||||
if user_id <= 0:
|
||||
raise AuthenticationExpiredError("登录信息不完整,请重新登录后重试文字。")
|
||||
if (str(call.get("caller_id")) != str(user_id)
|
||||
or call.get("caller_type") != "doctor"):
|
||||
raise RecordingTranscriptionError("请使用发起这次通话的医生账号补全文字。")
|
||||
# 服务端只允许发起通话的医生账号补写文字;共用电脑时另一账号的录音会留在队列里。
|
||||
raise RecordingTranscriptionError(
|
||||
f"这段录音的通话由账号 #{call.get('caller_id')} 发起,当前登录账号为 "
|
||||
f"#{user_id},请用发起通话的医生账号登录后重试文字。"
|
||||
)
|
||||
if int(call.get("status") or 0) == 1:
|
||||
raise _CallStillEnding()
|
||||
if int(call.get("status") or 0) != 2:
|
||||
@@ -739,6 +757,15 @@ class LocalAudioUploadManager:
|
||||
if not isinstance(text, str) or not text.strip() or len(text) > 100_000:
|
||||
raise RecordingTranscriptionError("未生成可保存的文字,请检查录音及本地模型后重试。")
|
||||
self.store.save_transcription_draft(record.id, text)
|
||||
# 本机识别可能耗时数分钟,期间实时转写可能刚完成收尾。按服务端最新状态提交,
|
||||
# 否则 expected_* 校验会把这份已识别的文字拒掉。
|
||||
refreshed = self._find_call(record)
|
||||
if refreshed is not None:
|
||||
call = refreshed
|
||||
if self._server_text_complete(call):
|
||||
self.store.finish_transcription(record.id)
|
||||
self._notify_uploaded(record.id)
|
||||
return True
|
||||
result = save(
|
||||
diagnosis_id=record.diagnosis_id,
|
||||
call_record_id=record.call_record_id,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -103,6 +103,7 @@ class TokenStore:
|
||||
*,
|
||||
account: str | None = None,
|
||||
scope: str | None = None,
|
||||
desktop_expires_at: int = 0,
|
||||
) -> None:
|
||||
"""Persist a token plus optional account and API-scope metadata.
|
||||
|
||||
@@ -117,6 +118,12 @@ class TokenStore:
|
||||
self.save_account(account)
|
||||
return
|
||||
data = self._read_file()
|
||||
data.pop("desktop_session", None)
|
||||
if desktop_expires_at > 0:
|
||||
data["desktop_session"] = {
|
||||
"token_sha256": hashlib.sha256(cleaned.encode()).hexdigest(),
|
||||
"expires_at": desktop_expires_at,
|
||||
}
|
||||
if account is not None:
|
||||
account_value = account.strip()
|
||||
previous_account = str(data.get("account") or "").strip()
|
||||
@@ -151,6 +158,18 @@ class TokenStore:
|
||||
data["token"] = cleaned
|
||||
self._write_file(data)
|
||||
|
||||
def desktop_expiry(self, token: str) -> int:
|
||||
"""Read the deadline only for the matching workstation-issued token."""
|
||||
|
||||
marker = self._read_file().get("desktop_session")
|
||||
if not isinstance(marker, dict):
|
||||
return 0
|
||||
fingerprint = hashlib.sha256(token.encode()).hexdigest()
|
||||
expiry = marker.get("expires_at")
|
||||
if marker.get("token_sha256") == fingerprint and type(expiry) is int and expiry > 0:
|
||||
return expiry
|
||||
return 0
|
||||
|
||||
def clear_token(self) -> None:
|
||||
"""Delete the token while retaining remembered login credentials."""
|
||||
|
||||
@@ -161,6 +180,7 @@ class TokenStore:
|
||||
self._uses_keyring = False
|
||||
data = self._read_file()
|
||||
data.pop("token", None)
|
||||
data.pop("desktop_session", None)
|
||||
if not data.get("account"):
|
||||
data.pop("scope", None)
|
||||
self._write_file(data)
|
||||
@@ -457,14 +477,14 @@ class TokenStore:
|
||||
# Explicit allow-list guarantees accidental password-like fields are ignored.
|
||||
return {
|
||||
key: value[key]
|
||||
for key in ("token", "account", "scope", "credential")
|
||||
for key in ("token", "account", "scope", "credential", "desktop_session")
|
||||
if key in value
|
||||
}
|
||||
|
||||
def _write_file(self, data: dict[str, Any]) -> None:
|
||||
safe = {
|
||||
key: data[key]
|
||||
for key in ("token", "account", "scope", "credential")
|
||||
for key in ("token", "account", "scope", "credential", "desktop_session")
|
||||
if data.get(key)
|
||||
}
|
||||
if not safe:
|
||||
|
||||
@@ -444,6 +444,8 @@ def prescription_action(record: Any, *, force_open: bool = False) -> tuple[str,
|
||||
if explicit_legacy is not None
|
||||
else audit in {0, 1, 2}
|
||||
)
|
||||
if has_current and voided == 1:
|
||||
return "重新开方", "reissue"
|
||||
if not has_current:
|
||||
return "开方", "open"
|
||||
if audit == 1 and voided != 1:
|
||||
@@ -451,6 +453,12 @@ def prescription_action(record: Any, *, force_open: bool = False) -> tuple[str,
|
||||
return "编辑处方", "edit"
|
||||
|
||||
|
||||
def can_void_prescription(record: Any) -> bool:
|
||||
# 已有业务订单、已审核签署的处方也可作废:订单随同诊单重新开方自动关联新处方;权限与药房锁由服务端判定。
|
||||
_, mode = prescription_action(record)
|
||||
return mode in {"edit", "view"}
|
||||
|
||||
|
||||
def _prescription_action_label(record: Any, *, force_open: bool = False) -> str:
|
||||
return prescription_action(record, force_open=force_open)[0]
|
||||
|
||||
@@ -2100,6 +2108,11 @@ class DiagnosisTableHost(QFrame):
|
||||
command, item
|
||||
),
|
||||
)
|
||||
if self.action_policy.get("prescription", False) and can_void_prescription(record):
|
||||
_add_menu_action(
|
||||
menu, "作废处方", "close",
|
||||
lambda _checked=False, item=record: self.action_requested.emit("void_prescription", item),
|
||||
)
|
||||
if demoted_actions and self.action_policy.get("assign", False):
|
||||
menu.addSeparator()
|
||||
if self.action_policy.get("assign", False):
|
||||
|
||||
@@ -116,6 +116,7 @@ from .prescription_ai import (
|
||||
can_use_diagnosis_ai_assistant,
|
||||
diagnosis_ai_task,
|
||||
)
|
||||
from .prescription_esign import resume_saved_prescription, saved_prescription_message
|
||||
|
||||
AI_CONSULT_QSS = clinical_stylesheet("""
|
||||
QDialog#AiConsultDialog {
|
||||
@@ -1222,7 +1223,7 @@ def _unwrap_analysis(payload: Any) -> dict[str, Any]:
|
||||
current: Mapping[str, Any] = payload
|
||||
latest = current.get("latest_by_model")
|
||||
if isinstance(latest, Mapping):
|
||||
for key in ("qwen", "openai"):
|
||||
for key in ("qwen", "openai", "doubao"):
|
||||
row = latest.get(key)
|
||||
if isinstance(row, Mapping):
|
||||
current = row
|
||||
@@ -7085,7 +7086,7 @@ class AiConsultDialog(QDialog):
|
||||
):
|
||||
status.set_payload("AI处方草稿缺少诊断或药材,已停止开方。")
|
||||
return
|
||||
status.set_payload("AI 已生成处方草稿,请逐味复核、修改并完成医师签名。")
|
||||
status.set_payload("AI 已生成处方草稿,请逐味复核并保存。")
|
||||
self._open_prescription_editor_from_chat(
|
||||
generation,
|
||||
diagnosis_id,
|
||||
@@ -7177,45 +7178,46 @@ class AiConsultDialog(QDialog):
|
||||
}
|
||||
seed.update({key: deepcopy(value) for key, value in draft.items() if key in allowed})
|
||||
seed["ai_assisted"] = True
|
||||
linked_fields = {
|
||||
"diagnosis_id": diagnosis_id,
|
||||
"appointment_id": seed["appointment_id"],
|
||||
"case_record": deepcopy(seed["case_record"]),
|
||||
"patient_id": seed["patient_id"],
|
||||
"phone": seed["phone"],
|
||||
}
|
||||
|
||||
def save_prescription(payload: dict[str, Any]) -> Any:
|
||||
return invoke(
|
||||
self.repository, "create_prescription", prescription=deepcopy(payload | linked_fields)
|
||||
)
|
||||
|
||||
dialog = PrescriptionEditorDialog(
|
||||
self.repository,
|
||||
seed,
|
||||
mode="add",
|
||||
current_user=self._current_user(),
|
||||
permissions=self.permissions,
|
||||
save_draft=save_prescription,
|
||||
parent=self,
|
||||
)
|
||||
if dialog.exec() != QDialog.DialogCode.Accepted:
|
||||
status.set_payload("已取消开方,未保存或提交任何处方。")
|
||||
return
|
||||
saved = getattr(dialog, "saved_draft", None)
|
||||
if saved is not None:
|
||||
self._prescription_action_created(generation, diagnosis_id, status, saved)
|
||||
return
|
||||
|
||||
status.set_payload("正在保存处方。")
|
||||
payload = dialog.payload()
|
||||
payload.update(
|
||||
{
|
||||
"diagnosis_id": diagnosis_id,
|
||||
"appointment_id": seed["appointment_id"],
|
||||
"case_record": deepcopy(seed["case_record"]),
|
||||
"patient_id": seed["patient_id"],
|
||||
"phone": seed["phone"],
|
||||
}
|
||||
)
|
||||
status.set_payload("处方已填写,正在提交审核。")
|
||||
frozen_payload = deepcopy(payload)
|
||||
run_async(
|
||||
lambda: invoke(
|
||||
self.repository,
|
||||
"create_prescription",
|
||||
prescription=frozen_payload,
|
||||
),
|
||||
on_success=lambda _result: self._prescription_action_created(
|
||||
generation,
|
||||
diagnosis_id,
|
||||
status,
|
||||
),
|
||||
lambda: save_prescription(payload),
|
||||
on_success=lambda result: self._prescription_action_created(generation, diagnosis_id, status, result),
|
||||
on_error=lambda error: self._prescription_action_error(
|
||||
generation,
|
||||
status,
|
||||
error,
|
||||
prefix="处方提交失败",
|
||||
prefix="处方保存失败",
|
||||
),
|
||||
)
|
||||
|
||||
@@ -7224,11 +7226,14 @@ class AiConsultDialog(QDialog):
|
||||
generation: int,
|
||||
diagnosis_id: int,
|
||||
status: _ChatBubble,
|
||||
prescription: Any,
|
||||
) -> None:
|
||||
if generation != self._generation or diagnosis_id != self.diagnosis_id:
|
||||
return
|
||||
status.set_payload("处方已开具并提交审核。")
|
||||
message, _ = saved_prescription_message(prescription, "处方已保存。")
|
||||
status.set_payload(message)
|
||||
status.set_time_text(_join_meta("系统", datetime.now().strftime("%H:%M")))
|
||||
resume_saved_prescription(self.repository, prescription, self)
|
||||
self._reload_prescriptions(generation, diagnosis_id)
|
||||
|
||||
def _prescription_action_error(
|
||||
|
||||
@@ -127,6 +127,15 @@ _DAILY_PERMISSION = "tcm.diagnosis/dailyRecord"
|
||||
_PRESCRIPTION_PERMISSION = "tcm.diagnosis/chufang"
|
||||
_PRESCRIPTION_EDIT_PERMISSION = "cf.prescription/edit"
|
||||
_OFFSET_PERMISSION = "tcm.diagnosis/setRevisitSlotStartOffset"
|
||||
# 与「处方电子签署」预览一致的标题与标签页样式,仅作用于嵌入的三联预览。
|
||||
_EMBEDDED_PRESCRIPTION_PREVIEW_QSS = clinical_stylesheet("""
|
||||
QLabel#PrescriptionSigningHeading { font-size: 16px; font-weight: 600; color: #20354E; }
|
||||
QTabWidget::pane { background-color: #FFFFFF; border: 1px solid #EDEDEE; border-radius: $ds_radius_panel; top: -1px; }
|
||||
QTabBar::tab { min-height: 34px; padding: 0 16px; color: #606163; background-color: transparent;
|
||||
border: 0; border-bottom: 2px solid transparent; }
|
||||
QTabBar::tab:hover { color: #4156C4; background-color: #F7F7F7; }
|
||||
QTabBar::tab:selected { color: #4F63D9; background-color: #EEF1FA; border-bottom: 2px solid #4F63D9; font-weight: 600; }
|
||||
""")
|
||||
_VIDEO_PERMISSION = "tcm.diagnosis/huifang"
|
||||
_CHAT_PERMISSION = "tcm.diagnosis/chat"
|
||||
_NOTE_ADD_PERMISSION = "doctor.appointment/addDoctorNote"
|
||||
@@ -1029,7 +1038,24 @@ class DiagnosisDialog(QDialog):
|
||||
2, QHeaderView.ResizeMode.Stretch
|
||||
)
|
||||
self.readonly_prescriptions_table.setMinimumHeight(220)
|
||||
self._add_readonly_section("prescription", "历史处方", self.readonly_prescriptions_table)
|
||||
self.readonly_prescriptions_table.currentCellChanged.connect(
|
||||
lambda row, _column, _previous_row, _previous_column: self._show_readonly_prescription(row)
|
||||
)
|
||||
# 选中的处方在表格下方显示 处方联 / 药房联 / 详细病历。
|
||||
self._readonly_prescription_rows: list[Any] = []
|
||||
self.readonly_prescription_preview: Any = None
|
||||
self.readonly_prescription_preview_host = QWidget()
|
||||
self.readonly_prescription_preview_host.setObjectName("DiagnosisReadonlyPrescriptionPreview")
|
||||
self._readonly_preview_layout = QVBoxLayout(self.readonly_prescription_preview_host)
|
||||
self._readonly_preview_layout.setContentsMargins(0, 0, 0, 0)
|
||||
self.readonly_prescription_preview_host.hide()
|
||||
prescription_body = QWidget()
|
||||
prescription_layout = QVBoxLayout(prescription_body)
|
||||
prescription_layout.setContentsMargins(0, 0, 0, 0)
|
||||
prescription_layout.setSpacing(12)
|
||||
prescription_layout.addWidget(self.readonly_prescriptions_table)
|
||||
prescription_layout.addWidget(self.readonly_prescription_preview_host)
|
||||
self._add_readonly_section("prescription", "历史处方", prescription_body)
|
||||
self.readonly_content_layout.setAlignment(
|
||||
self._readonly_sections["prescription"], Qt.AlignmentFlag.AlignLeft
|
||||
)
|
||||
@@ -2817,6 +2843,9 @@ class DiagnosisDialog(QDialog):
|
||||
for panel in self._chat_panels:
|
||||
panel.set_unavailable("正在加载聊天归档…")
|
||||
elif key in self._table_registry:
|
||||
if key == "prescription":
|
||||
self._readonly_prescription_rows = []
|
||||
self._clear_readonly_prescription_preview()
|
||||
for table in self._table_registry[key]:
|
||||
table.set_matrix([])
|
||||
table.set_empty_text("正在加载…")
|
||||
@@ -3509,11 +3538,20 @@ class DiagnosisDialog(QDialog):
|
||||
appointment, "doctor_name", default=first_value(diagnosis, "doctor_name")
|
||||
),
|
||||
}
|
||||
def save_new(payload: dict[str, Any]) -> Any:
|
||||
authoritative = {
|
||||
"diagnosis_id": diagnosis_id,
|
||||
"appointment_id": appointment_id,
|
||||
"case_record": seed["case_record"],
|
||||
}
|
||||
return invoke(self.repository, "create_prescription", prescription=payload | authoritative)
|
||||
|
||||
dialog = PrescriptionEditorDialog(
|
||||
self.repository,
|
||||
seed,
|
||||
mode="add",
|
||||
current_user=getattr(self.parentWidget(), "current_user", None),
|
||||
save_draft=save_new,
|
||||
parent=self,
|
||||
)
|
||||
dialog.diagnosis_requested.connect(self._open_current_diagnosis_detail)
|
||||
@@ -3521,16 +3559,16 @@ class DiagnosisDialog(QDialog):
|
||||
dialog.setStyleSheet(DIAGNOSIS_QSS)
|
||||
if dialog.exec() != QDialog.DialogCode.Accepted:
|
||||
return
|
||||
saved_draft = getattr(dialog, "saved_draft", None)
|
||||
if saved_draft is not None:
|
||||
self._media_generation += 1
|
||||
self._media_mutation_success(
|
||||
"处方已开具并提交审核。", "prescription", diagnosis_id, self._media_generation, saved_draft
|
||||
)
|
||||
return
|
||||
payload = dialog.payload()
|
||||
payload.update(
|
||||
{
|
||||
"diagnosis_id": diagnosis_id,
|
||||
"appointment_id": appointment_id,
|
||||
"case_record": seed["case_record"],
|
||||
}
|
||||
)
|
||||
self._run_media_mutation(
|
||||
lambda: invoke(self.repository, "create_prescription", prescription=payload),
|
||||
lambda: save_new(payload),
|
||||
"处方已开具并提交审核。",
|
||||
"prescription",
|
||||
)
|
||||
@@ -3740,8 +3778,8 @@ class DiagnosisDialog(QDialog):
|
||||
self._show_message("正在提交…", "info")
|
||||
run_async(
|
||||
operation,
|
||||
on_success=lambda _result: self._media_mutation_success(
|
||||
success_text, reload_key, diagnosis_id, generation
|
||||
on_success=lambda result: self._media_mutation_success(
|
||||
success_text, reload_key, diagnosis_id, generation, result
|
||||
),
|
||||
on_error=lambda error: self._mutation_error(error, diagnosis_id, generation, "media"),
|
||||
on_finished=on_finished,
|
||||
@@ -3753,10 +3791,17 @@ class DiagnosisDialog(QDialog):
|
||||
reload_key: str,
|
||||
diagnosis_id: int,
|
||||
generation: int,
|
||||
result: Any = None,
|
||||
) -> None:
|
||||
if generation != self._media_generation or diagnosis_id != self._diagnosis_id:
|
||||
return
|
||||
self._show_message(text, "success")
|
||||
from .prescription_esign import resume_saved_prescription, saved_prescription_message
|
||||
kind = "success"
|
||||
if reload_key == "prescription":
|
||||
text, kind = saved_prescription_message(result, text)
|
||||
self._show_message(text, kind)
|
||||
if reload_key == "prescription":
|
||||
resume_saved_prescription(self.repository, result, self)
|
||||
self._loaded_tabs.discard(reload_key)
|
||||
if reload_key == "chat":
|
||||
QTimer.singleShot(
|
||||
@@ -3977,6 +4022,9 @@ class DiagnosisDialog(QDialog):
|
||||
return button
|
||||
|
||||
def _fill_prescriptions(self, rows: Sequence[Any]) -> None:
|
||||
# set_matrix 会触发选中行变化;先清空,避免按旧诊单的行加载预览。
|
||||
self._readonly_prescription_rows = []
|
||||
self._clear_readonly_prescription_preview()
|
||||
matrix: list[tuple[Any, ...]] = []
|
||||
for row in rows:
|
||||
herbs = first_value(row, "herbs", default=[]) or []
|
||||
@@ -4040,6 +4088,44 @@ class DiagnosisDialog(QDialog):
|
||||
actions_layout.addWidget(edit_button)
|
||||
actions_layout.addStretch(1)
|
||||
table.setCellWidget(row_index, 6, actions)
|
||||
self._readonly_prescription_rows = list(rows)
|
||||
if rows:
|
||||
# 默认展示最新一张;保持与点击行同一条加载路径。
|
||||
if self.readonly_prescriptions_table.currentRow() == 0:
|
||||
self._show_readonly_prescription(0)
|
||||
else:
|
||||
self.readonly_prescriptions_table.setCurrentCell(0, 0)
|
||||
|
||||
def _clear_readonly_prescription_preview(self) -> None:
|
||||
preview, self.readonly_prescription_preview = self.readonly_prescription_preview, None
|
||||
if preview is not None:
|
||||
self._readonly_preview_layout.removeWidget(preview)
|
||||
preview.deleteLater()
|
||||
self.readonly_prescription_preview_host.hide()
|
||||
|
||||
def _show_readonly_prescription(self, row_index: int) -> None:
|
||||
rows = self._readonly_prescription_rows
|
||||
if not 0 <= row_index < len(rows):
|
||||
return
|
||||
row = rows[row_index]
|
||||
prescription_id = _int(first_value(row, "id", "prescription_id", default=0), 0)
|
||||
current = self.readonly_prescription_preview
|
||||
if prescription_id <= 0 or (current is not None and current.prescription_id == prescription_id):
|
||||
return
|
||||
from .prescription import PrescriptionSigningPreview
|
||||
|
||||
self._clear_readonly_prescription_preview()
|
||||
label = display_text(first_value(row, "prescription_date", "visit_date", "create_time"), "")
|
||||
preview = PrescriptionSigningPreview(
|
||||
self.repository, row, parent=self.readonly_prescription_preview_host,
|
||||
editable=False, load_detail=True, diagnosis_id=self._diagnosis_id,
|
||||
heading=f"处方预览 · {label}" if label else "处方预览",
|
||||
)
|
||||
preview.setMinimumHeight(760)
|
||||
preview.setStyleSheet(_EMBEDDED_PRESCRIPTION_PREVIEW_QSS)
|
||||
self._readonly_preview_layout.addWidget(preview)
|
||||
self.readonly_prescription_preview = preview
|
||||
self.readonly_prescription_preview_host.show()
|
||||
|
||||
def _view_prescription(self, prescription: Any) -> None:
|
||||
prescription_id = _int(first_value(prescription, "id", "prescription_id", default=0), 0)
|
||||
@@ -4142,11 +4228,16 @@ class DiagnosisDialog(QDialog):
|
||||
def _open_prescription_edit_dialog(self, prescription: Any, prescription_id: int) -> None:
|
||||
from .prescription import PrescriptionEditorDialog
|
||||
|
||||
def save_changes(payload: dict[str, Any]) -> Any:
|
||||
return invoke(self.repository, "update_prescription", prescription=prescription_id, changes=payload)
|
||||
|
||||
diagnosis_id = self._diagnosis_id
|
||||
dialog = PrescriptionEditorDialog(
|
||||
self.repository,
|
||||
prescription,
|
||||
mode="edit",
|
||||
current_user=getattr(self.parentWidget(), "current_user", None),
|
||||
save_draft=save_changes,
|
||||
parent=self,
|
||||
)
|
||||
dialog.diagnosis_requested.connect(self._open_current_diagnosis_detail)
|
||||
@@ -4154,14 +4245,16 @@ class DiagnosisDialog(QDialog):
|
||||
dialog.setStyleSheet(DIAGNOSIS_QSS)
|
||||
if dialog.exec() != QDialog.DialogCode.Accepted:
|
||||
return
|
||||
saved_draft = getattr(dialog, "saved_draft", None)
|
||||
if saved_draft is not None:
|
||||
self._media_generation += 1
|
||||
self._media_mutation_success(
|
||||
"处方已保存并重新进入待审核。", "prescription", diagnosis_id, self._media_generation, saved_draft
|
||||
)
|
||||
return
|
||||
payload = dialog.payload()
|
||||
self._run_media_mutation(
|
||||
lambda: invoke(
|
||||
self.repository,
|
||||
"update_prescription",
|
||||
prescription=prescription_id,
|
||||
changes=payload,
|
||||
),
|
||||
lambda: save_changes(payload),
|
||||
"处方已保存并重新进入待审核。",
|
||||
"prescription",
|
||||
)
|
||||
|
||||
@@ -0,0 +1,441 @@
|
||||
"""Independent eSign identity enrollment for the signed-in doctor."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from time import monotonic
|
||||
from typing import Any
|
||||
|
||||
from PySide6.QtCore import QDateTime, Qt, QTimer, QTimeZone
|
||||
from PySide6.QtWidgets import (
|
||||
QDialog,
|
||||
QDialogButtonBox,
|
||||
QHBoxLayout,
|
||||
QLabel,
|
||||
QLineEdit,
|
||||
QPushButton,
|
||||
QVBoxLayout,
|
||||
QWidget,
|
||||
)
|
||||
from shiboken6 import isValid
|
||||
|
||||
from ...core.errors import ApiBusinessError, AuthenticationExpiredError
|
||||
from ...core.esign import (
|
||||
certificate_identity_number,
|
||||
esign_doctor_mobile,
|
||||
esign_doctor_status,
|
||||
esign_signer_name,
|
||||
)
|
||||
from ..design_system import clinical_stylesheet
|
||||
from ..widgets import MessageBanner, run_async
|
||||
from .esign_webview import UNAVAILABLE_MESSAGE, create_identity_view
|
||||
|
||||
_NEEDS_MOBILE = {"unbound", "needs_mobile", "renewal_required"}
|
||||
_STATUS_TEXT = {
|
||||
"unbound": "首次电子签署前,请验证本人身份并绑定签署证书。",
|
||||
"needs_mobile": "请输入本人手机号码,完成签署身份验证。",
|
||||
"authenticating": "请使用手机支付宝扫描 e签宝认证页面中的二维码并完成人脸识别。完成后可在这里检查状态。",
|
||||
"binding_required": "身份验证已通过。请确认绑定医生签署证书。",
|
||||
"ready": "签署身份已就绪。开具处方时,请使用短信验证码确认当次签署。",
|
||||
"renewal_required": "医生签署证书需要更新。请使用本人手机号码完成人脸认证。",
|
||||
}
|
||||
_QUICKSIGN_STATUS_TEXT = {
|
||||
"authenticating": "请在 e签宝页面使用手机支付宝扫码刷脸。如出现协议,请本人阅读后选择是否同意。刷脸后可在这里确认快捷签授权。",
|
||||
"binding_required": "已收到 e签宝授权结果。请确认启用本人快捷签。",
|
||||
}
|
||||
_QUICKSIGN_RENEWAL_TEXT = {
|
||||
"expired": "快捷签授权已过期,请重新授权。",
|
||||
"exhausted": "快捷签授权次数已用完,请重新授权。",
|
||||
"invalid": "快捷签授权已失效,请重新授权。",
|
||||
}
|
||||
_BEIJING_TIME = QTimeZone(b"Asia/Shanghai")
|
||||
_SENSITIVE_INPUT = Qt.InputMethodHint.ImhSensitiveData | Qt.InputMethodHint.ImhNoPredictiveText
|
||||
|
||||
|
||||
class EsignDoctorDialog(QDialog):
|
||||
POLL_INTERVAL_MS = 5_000
|
||||
AUTH_TIMEOUT_SECONDS = 600
|
||||
|
||||
def __init__(self, repository: Any, *, parent: QWidget | None = None) -> None:
|
||||
super().__init__(parent)
|
||||
self.repository = repository
|
||||
self.state: dict[str, Any] = {}
|
||||
self._busy = False
|
||||
self._closed = False
|
||||
self._generation = 0
|
||||
self._retry_mobile = False
|
||||
self._manual_check = False
|
||||
self._deadline: float | None = None
|
||||
self._native_window_id: int | None = None
|
||||
self._native_hide_pending = False
|
||||
self.identity_view: Any = None
|
||||
self.poll_timer = QTimer(self)
|
||||
self.poll_timer.setInterval(self.POLL_INTERVAL_MS)
|
||||
self.poll_timer.timeout.connect(self._poll)
|
||||
|
||||
self.setWindowTitle("医生电子签署身份")
|
||||
self.setMinimumSize(740, 550)
|
||||
self.resize(900, 680)
|
||||
self.setStyleSheet(clinical_stylesheet("QDialog { background:#FFFFFF; }"))
|
||||
layout = QVBoxLayout(self)
|
||||
layout.setContentsMargins(24, 24, 24, 24)
|
||||
layout.setSpacing(12)
|
||||
self.banner = MessageBanner(parent=self)
|
||||
self.banner.label.setTextFormat(Qt.TextFormat.PlainText)
|
||||
layout.addWidget(self.banner)
|
||||
|
||||
self.signer_form = QWidget(self)
|
||||
signer_layout = QVBoxLayout(self.signer_form)
|
||||
signer_layout.setContentsMargins(0, 0, 0, 0)
|
||||
signer_label = QLabel("证件姓名", self.signer_form)
|
||||
self.signer_input = QLineEdit(self.signer_form)
|
||||
self.signer_input.setInputMethodHints(Qt.InputMethodHint.ImhNoPredictiveText)
|
||||
self.signer_input.setMaxLength(50)
|
||||
self.signer_input.setPlaceholderText("请输入与本人有效证件一致的姓名")
|
||||
self.signer_input.setAccessibleName("证件姓名")
|
||||
signer_label.setBuddy(self.signer_input)
|
||||
signer_layout.addWidget(signer_label)
|
||||
signer_layout.addWidget(self.signer_input)
|
||||
layout.addWidget(self.signer_form)
|
||||
|
||||
self.mobile_form = QWidget(self)
|
||||
mobile_layout = QVBoxLayout(self.mobile_form)
|
||||
mobile_layout.setContentsMargins(0, 0, 0, 0)
|
||||
mobile_label = QLabel("本人手机号码", self.mobile_form)
|
||||
self.mobile_input = QLineEdit(self.mobile_form)
|
||||
self.mobile_input.setInputMethodHints(_SENSITIVE_INPUT | Qt.InputMethodHint.ImhDigitsOnly)
|
||||
self.mobile_input.setPlaceholderText("请输入 11 位手机号码")
|
||||
self.mobile_input.setAccessibleName("本人手机号码")
|
||||
mobile_label.setBuddy(self.mobile_input)
|
||||
mobile_layout.addWidget(mobile_label)
|
||||
mobile_layout.addWidget(self.mobile_input)
|
||||
layout.addWidget(self.mobile_form)
|
||||
|
||||
self.identity_form = QWidget(self)
|
||||
identity_layout = QVBoxLayout(self.identity_form)
|
||||
identity_layout.setContentsMargins(0, 0, 0, 0)
|
||||
identity_label = QLabel("请输入与本次人脸认证一致的身份证号码,用于首次绑定证书。", self.identity_form)
|
||||
identity_label.setWordWrap(True)
|
||||
self.identity_input = QLineEdit(self.identity_form)
|
||||
self.identity_input.setInputMethodHints(_SENSITIVE_INPUT)
|
||||
self.identity_input.setEchoMode(QLineEdit.EchoMode.Password)
|
||||
self.identity_input.setAccessibleName("证书绑定身份证号码")
|
||||
self.identity_input.setPlaceholderText("请输入 15 或 18 位中国大陆居民身份证号码")
|
||||
identity_label.setBuddy(self.identity_input)
|
||||
identity_layout.addWidget(identity_label)
|
||||
identity_layout.addWidget(self.identity_input)
|
||||
layout.addWidget(self.identity_form)
|
||||
|
||||
self.view_host = QWidget(self)
|
||||
self.view_layout = QVBoxLayout(self.view_host)
|
||||
self.view_layout.setContentsMargins(0, 0, 0, 0)
|
||||
layout.addWidget(self.view_host, 1)
|
||||
|
||||
footer = QHBoxLayout()
|
||||
self.start_button = QPushButton("开始人脸认证", self)
|
||||
self.start_button.clicked.connect(self._start)
|
||||
self.resume_button = QPushButton("继续人脸认证", self)
|
||||
self.resume_button.clicked.connect(self._open_authentication)
|
||||
self.change_mobile_button = QPushButton("重新输入手机号", self)
|
||||
self.change_mobile_button.clicked.connect(self._enter_mobile)
|
||||
self.bind_button = QPushButton("确认绑定证书", self)
|
||||
self.bind_button.clicked.connect(self._bind)
|
||||
self.refresh_button = QPushButton("检查认证状态", self)
|
||||
self.refresh_button.clicked.connect(self._check_status)
|
||||
self._buttons = (self.start_button, self.resume_button, self.bind_button,
|
||||
self.change_mobile_button, self.refresh_button)
|
||||
for button in self._buttons:
|
||||
button.setAutoDefault(False)
|
||||
footer.addWidget(button)
|
||||
for button in (self.start_button, self.resume_button, self.bind_button):
|
||||
button.setProperty("variant", "primary")
|
||||
footer.addStretch(1)
|
||||
close = QDialogButtonBox(QDialogButtonBox.StandardButton.Close, self)
|
||||
close_button = close.button(QDialogButtonBox.StandardButton.Close)
|
||||
close_button.setText("关闭")
|
||||
close_button.setAutoDefault(False)
|
||||
close.rejected.connect(self.reject)
|
||||
footer.addWidget(close)
|
||||
layout.addLayout(footer)
|
||||
self.banner.show_message("正在查询医生签署身份…", "info")
|
||||
self.refresh()
|
||||
|
||||
def _sync_actions(self) -> None:
|
||||
active = not self._busy and not self._closed and not self._native_hide_pending
|
||||
enabled = self.state.get("enabled") is True
|
||||
status = self.state.get("status")
|
||||
enrollment = enabled and (status in _NEEDS_MOBILE or self._retry_mobile)
|
||||
authenticating = enabled and status == "authenticating" and not enrollment
|
||||
binding = enabled and status == "binding_required"
|
||||
quick_authorizing = self.state.get("quicksign_authorizing") is True
|
||||
quick_start = (enabled and status == "ready" and self.state.get("quicksign_enabled") is True
|
||||
and not self.state.get("quicksign_expires_at"))
|
||||
self.start_button.setText("授权快捷签" if quick_start else "开始人脸认证")
|
||||
self.resume_button.setText("继续快捷签授权" if quick_authorizing else "继续人脸认证")
|
||||
self.bind_button.setText("确认快捷签授权" if quick_authorizing else "确认绑定证书")
|
||||
signer_editable = self.state.get("can_edit_signer_name") is True
|
||||
self.change_mobile_button.setText("修改证件姓名" if signer_editable else "重新输入手机号")
|
||||
inputs = (enrollment and signer_editable, enrollment,
|
||||
binding and self.state.get("identity_details_required") is True)
|
||||
for visible, form, field in zip(inputs, (self.signer_form, self.mobile_form, self.identity_form),
|
||||
(self.signer_input, self.mobile_input, self.identity_input), strict=True):
|
||||
if not visible:
|
||||
field.setText("")
|
||||
form.setVisible(visible)
|
||||
field.setEnabled(active and visible)
|
||||
controls = (
|
||||
enrollment or quick_start,
|
||||
authenticating and bool(self.state.get("auth_url")) and self.identity_view is None,
|
||||
binding,
|
||||
authenticating and self.identity_view is None and not quick_authorizing,
|
||||
True,
|
||||
)
|
||||
for button, visible in zip(self._buttons, controls, strict=True):
|
||||
button.setVisible(visible)
|
||||
button.setEnabled(active and visible)
|
||||
|
||||
def _apply_status(self, result: Any) -> None:
|
||||
self.state = esign_doctor_status(result)
|
||||
self._retry_mobile = False
|
||||
status = self.state["status"]
|
||||
if not self.state["enabled"] or status != "authenticating":
|
||||
self._stop_view()
|
||||
if not self.state["enabled"]:
|
||||
self.banner.show_message("当前环境未启用医生电子签署身份。", "info")
|
||||
else:
|
||||
message = (_QUICKSIGN_STATUS_TEXT[status] if self.state["quicksign_authorizing"] else _STATUS_TEXT[status])
|
||||
if self.state.get("can_edit_signer_name") and status in _NEEDS_MOBILE:
|
||||
message = "请填写与本人有效证件一致的姓名和本人手机号码,完成人脸认证。"
|
||||
if self.state["quicksign_authorizing"] and status == "authenticating" and not self.state.get("auth_url"):
|
||||
message = "e签宝快捷签授权请求处理中,请稍后检查认证状态。"
|
||||
if status == "ready" and self.state["quicksign_enabled"]:
|
||||
quick_expiry = self.state["quicksign_expires_at"]
|
||||
if quick_expiry:
|
||||
date = QDateTime.fromSecsSinceEpoch(quick_expiry, _BEIJING_TIME).toString("yyyy-MM-dd HH:mm")
|
||||
message = f"快捷签授权有效期至 {date}(北京时间)。"
|
||||
remaining = self.state.get("quicksign_remaining_times")
|
||||
if remaining is not None:
|
||||
message += f"剩余 {remaining} 次。"
|
||||
message += "每张处方仍由开方医生本人确认签名。"
|
||||
else:
|
||||
reason = self.state.get("quicksign_unavailable_reason")
|
||||
message = _QUICKSIGN_RENEWAL_TEXT.get(reason, "签署身份已就绪。请授权使用本人的快捷签。")
|
||||
message += "每张处方仍由开方医生本人确认签名。"
|
||||
expires = self.state["cert_expires_at"]
|
||||
if status == "ready" and expires:
|
||||
date = QDateTime.fromSecsSinceEpoch(expires, _BEIJING_TIME).toString("yyyy-MM-dd HH:mm")
|
||||
message += f" 签署证书有效期至 {date}(北京时间)。"
|
||||
if self._manual_check and status == "authenticating" and self.state.get("auth_url"):
|
||||
# e签宝 在认证页查询结果时才拉取刷脸结论,未查询前服务端仍是“认证中”。
|
||||
message = ("e签宝 尚未确认刷脸结果。如手机已提示认证成功,请在下方认证页面点击「查询认证结果」,"
|
||||
"确认后这里会自动更新。")
|
||||
self.banner.show_message(message, "success" if status == "ready" else "info")
|
||||
self._manual_check = False
|
||||
self._sync_actions()
|
||||
|
||||
def _request(self, method: str, *proof: str) -> None:
|
||||
if self._busy or self._closed:
|
||||
return
|
||||
self._busy = True
|
||||
generation = self._generation
|
||||
self._sync_actions()
|
||||
repository = self.repository
|
||||
succeeded = False
|
||||
|
||||
def current() -> bool:
|
||||
return isValid(self) and not self._closed and self._generation == generation
|
||||
|
||||
def loaded(result: Any) -> None:
|
||||
nonlocal succeeded
|
||||
if not current():
|
||||
return
|
||||
try:
|
||||
self._apply_status(result)
|
||||
succeeded = True
|
||||
except Exception:
|
||||
failed(ValueError())
|
||||
|
||||
def failed(error: Exception) -> None:
|
||||
if not current():
|
||||
return
|
||||
self._manual_check = False
|
||||
self._stop_view()
|
||||
if method == "get_esign_doctor_status":
|
||||
self.state = {}
|
||||
self.banner.show_message("医生签署身份状态待确认,请检查认证状态后继续。", "warning")
|
||||
else:
|
||||
# 发起或绑定被拒绝时保留当前步骤,医生可直接修正后重试。
|
||||
reason = str(error) if isinstance(error, (ApiBusinessError, AuthenticationExpiredError)) else ""
|
||||
self.banner.show_message(reason or "操作未完成,请检查认证状态后重试。", "warning")
|
||||
self._sync_actions()
|
||||
|
||||
def finished() -> None:
|
||||
if isValid(self):
|
||||
self._busy = False
|
||||
if self._closed:
|
||||
return
|
||||
self._sync_actions()
|
||||
if (succeeded and current() and method == "start_esign_doctor" and self.isVisible()
|
||||
and self.state.get("auth_url")):
|
||||
self._open_authentication()
|
||||
|
||||
def work() -> Any:
|
||||
nonlocal proof
|
||||
try:
|
||||
return getattr(repository, method)(*proof)
|
||||
finally:
|
||||
proof = ()
|
||||
|
||||
run_async(work, on_success=loaded, on_error=failed, on_finished=finished)
|
||||
|
||||
def refresh(self) -> None:
|
||||
if self._busy or self._closed:
|
||||
return
|
||||
self.mobile_input.setText("")
|
||||
self.identity_input.setText("")
|
||||
self._request("get_esign_doctor_status")
|
||||
|
||||
def _check_status(self) -> None:
|
||||
if self._busy or self._closed:
|
||||
return
|
||||
self._manual_check = True
|
||||
self.refresh()
|
||||
|
||||
def _enter_mobile(self) -> None:
|
||||
self._retry_mobile = True
|
||||
self._sync_actions()
|
||||
(self.signer_input if self.signer_form.isVisible() else self.mobile_input).setFocus()
|
||||
|
||||
def _start(self) -> None:
|
||||
if not self.start_button.isEnabled() or not self.isVisible():
|
||||
return
|
||||
if self.state.get("status") == "ready":
|
||||
self._request("start_esign_doctor", "")
|
||||
return
|
||||
signer: tuple[str, ...] = ()
|
||||
if self.signer_form.isVisible():
|
||||
try:
|
||||
signer = (esign_signer_name(self.signer_input.text()),)
|
||||
except ValueError as error:
|
||||
self.banner.show_message(str(error), "warning")
|
||||
self.signer_input.setFocus()
|
||||
return
|
||||
try:
|
||||
mobile = esign_doctor_mobile(self.mobile_input.text())
|
||||
except ValueError as error:
|
||||
self.mobile_input.setText("")
|
||||
self.banner.show_message(str(error), "warning")
|
||||
return
|
||||
self.mobile_input.setText("")
|
||||
# 证件姓名不是凭证,被拒后保留以便修正;手机号仍按原规则提交后即清空。
|
||||
self._request("start_esign_doctor", mobile, *signer)
|
||||
|
||||
def _bind(self) -> None:
|
||||
if not self.bind_button.isEnabled() or not self.isVisible():
|
||||
return
|
||||
identity_number = ""
|
||||
if self.state.get("identity_details_required") is True:
|
||||
try:
|
||||
identity_number = certificate_identity_number(self.identity_input.text())
|
||||
except ValueError as error:
|
||||
self.identity_input.setText("")
|
||||
self.banner.show_message(str(error), "warning")
|
||||
return
|
||||
self.identity_input.setText("")
|
||||
self._request("complete_esign_doctor", *([identity_number] if identity_number else []))
|
||||
|
||||
def _open_authentication(self) -> None:
|
||||
if (self._busy or self._closed or not self.isVisible() or self.identity_view is not None
|
||||
or self.state.get("status") != "authenticating" or not self.state.get("auth_url")):
|
||||
return
|
||||
try:
|
||||
self._native_window_id = int(self.winId())
|
||||
view = create_identity_view(self.view_host)
|
||||
self.identity_view = view
|
||||
view.initialized.connect(lambda: self._native_ready(view))
|
||||
view.failed.connect(lambda _message: self._view_failed(view))
|
||||
self._deadline = monotonic() + self.AUTH_TIMEOUT_SECONDS
|
||||
self.view_layout.addWidget(view)
|
||||
if self.identity_view is view:
|
||||
view.load_authentication(self.state["auth_url"])
|
||||
if self.identity_view is view:
|
||||
view.show()
|
||||
if not self._native_hide_pending:
|
||||
self.poll_timer.start()
|
||||
except Exception:
|
||||
self._stop_view()
|
||||
self.banner.show_message(UNAVAILABLE_MESSAGE, "warning")
|
||||
self._sync_actions()
|
||||
|
||||
def _poll(self) -> None:
|
||||
if self._deadline is None or self._native_hide_pending or not self.isVisible():
|
||||
return
|
||||
if monotonic() >= self._deadline:
|
||||
self._generation += 1
|
||||
self._stop_view()
|
||||
self._sync_actions()
|
||||
self.banner.show_message("本次自动检查已结束。请检查认证状态后继续。", "warning")
|
||||
else:
|
||||
self._request("get_esign_doctor_status")
|
||||
|
||||
def _view_failed(self, view: Any) -> None:
|
||||
if view is self.identity_view and not self._closed:
|
||||
self._stop_view()
|
||||
self._sync_actions()
|
||||
self.banner.show_message("无法加载 e签宝认证页面,请检查认证状态后重试。", "warning")
|
||||
|
||||
def _stop_view(self) -> None:
|
||||
self.poll_timer.stop()
|
||||
self._deadline = None
|
||||
self._native_window_id = None
|
||||
self._native_hide_pending = False
|
||||
if self.identity_view is not None:
|
||||
view, self.identity_view = self.identity_view, None
|
||||
view.stop()
|
||||
self.view_layout.removeWidget(view)
|
||||
view.deleteLater()
|
||||
|
||||
def _native_ready(self, view: Any) -> None:
|
||||
if view is self.identity_view and not self._native_hide_pending:
|
||||
self._native_window_id = None
|
||||
|
||||
def _suspend(self) -> None:
|
||||
self._generation += 1
|
||||
self.signer_input.setText("")
|
||||
self.mobile_input.setText("")
|
||||
self.identity_input.setText("")
|
||||
self._stop_view()
|
||||
if self._busy:
|
||||
self.state = {}
|
||||
self._sync_actions()
|
||||
|
||||
def _resolve_native_hide(self, native_id: int, generation: int) -> None:
|
||||
if not isValid(self) or self._closed or generation != self._generation or not self._native_hide_pending:
|
||||
return
|
||||
if self.identity_view is not None and self.isVisible() and not self.isMinimized() and int(self.winId()) != native_id:
|
||||
self._native_window_id = None
|
||||
self._native_hide_pending = False
|
||||
self.poll_timer.start()
|
||||
self._sync_actions()
|
||||
else:
|
||||
self._suspend()
|
||||
|
||||
def hideEvent(self, event: Any) -> None:
|
||||
if self._native_window_id is not None and not event.spontaneous() and not self._closed:
|
||||
# Qt can briefly hide the dialog while recreating its surface for WebEngine.
|
||||
self._native_hide_pending = True
|
||||
self.poll_timer.stop()
|
||||
native_id, generation = self._native_window_id, self._generation
|
||||
QTimer.singleShot(0, lambda: self._resolve_native_hide(native_id, generation))
|
||||
self._sync_actions()
|
||||
elif not self._closed:
|
||||
self._suspend()
|
||||
super().hideEvent(event)
|
||||
|
||||
def hide(self) -> None:
|
||||
self._suspend()
|
||||
super().hide()
|
||||
|
||||
def done(self, result: int) -> None:
|
||||
self._closed = True
|
||||
self._suspend()
|
||||
super().done(result)
|
||||
@@ -0,0 +1,173 @@
|
||||
"""Isolated official identity page; it has no application or signing bridge."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from PySide6.QtCore import Qt, QUrl, Signal
|
||||
from PySide6.QtWidgets import QVBoxLayout, QWidget
|
||||
|
||||
from ...core.esign import authentication_navigation_allowed, authentication_url
|
||||
|
||||
try:
|
||||
from PySide6.QtWebEngineCore import (
|
||||
QWebEnginePage,
|
||||
QWebEngineProfile,
|
||||
QWebEngineSettings,
|
||||
QWebEngineUrlRequestInterceptor,
|
||||
)
|
||||
from PySide6.QtWebEngineWidgets import QWebEngineView
|
||||
except (ImportError, OSError):
|
||||
WEBENGINE_AVAILABLE = False
|
||||
else:
|
||||
WEBENGINE_AVAILABLE = True
|
||||
|
||||
|
||||
UNAVAILABLE_MESSAGE = "当前安装缺少内置核身组件,请联系管理员修复或更新医生工作站后继续签署。"
|
||||
|
||||
|
||||
def _policy_url(url: QUrl) -> str:
|
||||
# 默认 toString() 会把 %20 解码成空格,导致含编码空格的官方资源或接口被误拦。
|
||||
return url.toString(QUrl.ComponentFormattingOption.FullyEncoded)
|
||||
|
||||
|
||||
if WEBENGINE_AVAILABLE:
|
||||
class IdentityPage(QWebEnginePage):
|
||||
blocked = Signal(str)
|
||||
|
||||
def __init__(self, profile: Any, parent: QWidget) -> None:
|
||||
super().__init__(profile, parent)
|
||||
self.shutting_down = False
|
||||
|
||||
def acceptNavigationRequest(self, url: QUrl, navigation_type: Any, is_main_frame: bool) -> bool:
|
||||
del navigation_type, is_main_frame
|
||||
if self.shutting_down:
|
||||
return url.toString() == "about:blank"
|
||||
if authentication_navigation_allowed(_policy_url(url)):
|
||||
return True
|
||||
self.blocked.emit("核身页面请求离开系统支持的认证范围,已停止。请联系管理员检查核身方式。")
|
||||
return False
|
||||
|
||||
def createWindow(self, window_type: Any) -> None:
|
||||
del window_type
|
||||
self.blocked.emit("当前核身页面要求打开新窗口,系统已阻止。请联系管理员使用短信核身方式。")
|
||||
return None
|
||||
|
||||
def chooseFiles(self, mode: Any, old_files: Any, accepted_types: Any) -> list[str]:
|
||||
del mode, old_files, accepted_types
|
||||
return []
|
||||
|
||||
def javaScriptConsoleMessage(self, level: Any, message: str, line: int, source: str) -> None:
|
||||
# Provider messages may contain identity/session data; never log them.
|
||||
pass
|
||||
|
||||
|
||||
class IdentityRequests(QWebEngineUrlRequestInterceptor):
|
||||
def interceptRequest(self, info: Any) -> None:
|
||||
url = info.requestUrl()
|
||||
# Inline resources are allowed; top-level/iframe navigation still goes
|
||||
# through IdentityPage. Network access stays on official HTTPS hosts.
|
||||
if url.scheme() not in {"data", "blob", "about"}:
|
||||
info.block(not authentication_navigation_allowed(_policy_url(url)))
|
||||
|
||||
|
||||
class EmbeddedIdentityView(QWidget):
|
||||
"""Own a fresh memory-only profile for the lifetime of one authentication."""
|
||||
|
||||
failed = Signal(str)
|
||||
initialized = Signal()
|
||||
|
||||
def __init__(self, parent: QWidget | None = None) -> None:
|
||||
if not WEBENGINE_AVAILABLE:
|
||||
raise RuntimeError(UNAVAILABLE_MESSAGE)
|
||||
super().__init__(parent)
|
||||
self._stopped = False
|
||||
self._auth_url: str | None = None
|
||||
self.profile = QWebEngineProfile(self)
|
||||
if not self.profile.isOffTheRecord():
|
||||
raise RuntimeError("无法创建隔离的内置核身窗口,请联系管理员。")
|
||||
self.profile.setPersistentCookiesPolicy(QWebEngineProfile.PersistentCookiesPolicy.NoPersistentCookies)
|
||||
self.profile.setHttpCacheType(QWebEngineProfile.HttpCacheType.MemoryHttpCache)
|
||||
self.interceptor = IdentityRequests(self.profile)
|
||||
self.profile.setUrlRequestInterceptor(self.interceptor)
|
||||
self.profile.downloadRequested.connect(self._deny_download)
|
||||
self.view = QWebEngineView(self)
|
||||
self.page = IdentityPage(self.profile, self.view)
|
||||
self.view.setPage(self.page)
|
||||
# The profile must outlive its page even during deferred widget deletion.
|
||||
self.profile.setParent(None)
|
||||
self.page.destroyed.connect(self.profile.deleteLater)
|
||||
self.view.setContextMenuPolicy(Qt.ContextMenuPolicy.NoContextMenu)
|
||||
self.view.setAcceptDrops(False)
|
||||
settings = self.page.settings()
|
||||
attributes = QWebEngineSettings.WebAttribute
|
||||
for name in (
|
||||
"JavascriptCanOpenWindows", "JavascriptCanAccessClipboard", "JavascriptCanPaste",
|
||||
"LocalContentCanAccessRemoteUrls", "LocalContentCanAccessFileUrls",
|
||||
"AllowRunningInsecureContent", "PluginsEnabled", "FullScreenSupportEnabled",
|
||||
"ScreenCaptureEnabled", "HyperlinkAuditingEnabled",
|
||||
):
|
||||
attribute = getattr(attributes, name, None)
|
||||
if attribute is not None:
|
||||
settings.setAttribute(attribute, False)
|
||||
settings.setUnknownUrlSchemePolicy(QWebEngineSettings.UnknownUrlSchemePolicy.DisallowUnknownUrlSchemes)
|
||||
self.page.blocked.connect(self.failed)
|
||||
self.page.certificateError.connect(self._deny_certificate)
|
||||
if hasattr(self.page, "permissionRequested"):
|
||||
self.page.permissionRequested.connect(self._deny_permission)
|
||||
else:
|
||||
self.page.featurePermissionRequested.connect(self._deny_feature)
|
||||
self.page.renderProcessTerminated.connect(
|
||||
lambda *_args: self._failure("内置核身页面已停止,请查询当前状态后重新进入。")
|
||||
)
|
||||
self.view.loadFinished.connect(self._loaded)
|
||||
layout = QVBoxLayout(self)
|
||||
layout.setContentsMargins(0, 0, 0, 0)
|
||||
layout.addWidget(self.view)
|
||||
|
||||
def load_authentication(self, url: str) -> None:
|
||||
validated = authentication_url(url)
|
||||
if validated != self._auth_url:
|
||||
self._auth_url = validated
|
||||
self.view.setUrl(QUrl(validated))
|
||||
|
||||
def _failure(self, message: str) -> None:
|
||||
if not self._stopped:
|
||||
self.failed.emit(message)
|
||||
|
||||
def _loaded(self, success: bool) -> None:
|
||||
# A successful page load has no relationship to successful identity.
|
||||
if success and not self._stopped:
|
||||
self.initialized.emit()
|
||||
elif not success:
|
||||
self._failure("内置核身页面加载失败,请检查网络并查询当前状态后重试。")
|
||||
|
||||
def _deny_download(self, download: Any) -> None:
|
||||
download.cancel()
|
||||
self._failure("核身页面中的文件下载已禁用。已签原件请使用窗口下方的下载按钮。")
|
||||
|
||||
def _deny_certificate(self, error: Any) -> None:
|
||||
error.rejectCertificate()
|
||||
self._failure("核身页面的安全证书校验失败,已停止加载。请联系管理员检查网络或证书。")
|
||||
|
||||
def _deny_feature(self, origin: Any, feature: Any) -> None:
|
||||
self.page.setFeaturePermission(origin, feature, QWebEnginePage.PermissionPolicy.PermissionDeniedByUser)
|
||||
self._failure("当前核身页面请求设备权限,已停止。请联系管理员使用短信核身方式。")
|
||||
|
||||
def _deny_permission(self, permission: Any) -> None:
|
||||
permission.deny()
|
||||
self._failure("当前核身页面请求设备权限,已停止。请联系管理员使用短信核身方式。")
|
||||
|
||||
def stop(self) -> None:
|
||||
if self._stopped:
|
||||
return
|
||||
self._stopped = True
|
||||
self.page.shutting_down = True
|
||||
self.view.stop()
|
||||
self.view.setUrl(QUrl("about:blank"))
|
||||
self.profile.cookieStore().deleteAllCookies()
|
||||
self.hide()
|
||||
|
||||
|
||||
def create_identity_view(parent: QWidget) -> EmbeddedIdentityView:
|
||||
return EmbeddedIdentityView(parent)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -46,6 +46,7 @@ from ..widgets import (
|
||||
AI_MODELS: tuple[tuple[str, str, str], ...] = (
|
||||
("qwen", "千问", "qwen3.6-35b"),
|
||||
("openai", "OpenAI", "gpt-5.6-sol"),
|
||||
("doubao", "豆包", "doubao-seed-2.1-pro"),
|
||||
)
|
||||
AI_MODEL_KEYS = frozenset(profile for profile, _label, _name in AI_MODELS)
|
||||
AI_REPORT_EDIT_PERMISSIONS = (
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -45,15 +45,24 @@ from ..appointments_style import appointments_stylesheet
|
||||
from ..dialogs import DiagnosisDialog
|
||||
from ..dialogs.ai_consult import can_open_ai_consult, present_ai_consult
|
||||
from ..dialogs.prescription import (
|
||||
PRESCRIPTION_VOIDED_RESULT,
|
||||
PrescriptionDetailDialog,
|
||||
PrescriptionEditorDialog,
|
||||
build_prescription_clinical_diagnosis,
|
||||
build_prescription_visit_no,
|
||||
can_reissue_prescription,
|
||||
prescription_edit_is_locked,
|
||||
prescription_matches_appointment,
|
||||
reissue_prescription_seed,
|
||||
)
|
||||
from ..dialogs.prescription_ai import (
|
||||
can_open_diagnosis_ai_report,
|
||||
present_diagnosis_ai_report,
|
||||
)
|
||||
from ..dialogs.prescription_esign import (
|
||||
resume_saved_prescription,
|
||||
saved_prescription_message,
|
||||
)
|
||||
from ..filter_disclosure import FilterDisclosure
|
||||
from ..icons import icon
|
||||
from ..infinite_list import InfiniteList
|
||||
@@ -240,7 +249,9 @@ def prescription_action_label(row: Any) -> str:
|
||||
)
|
||||
if not has_prescription:
|
||||
return "开方"
|
||||
return "查看" if audit == 1 and voided != 1 else "编辑处方"
|
||||
if voided == 1:
|
||||
return "重新开方"
|
||||
return "查看" if audit == 1 else "编辑处方"
|
||||
|
||||
|
||||
def _patient_cell(_value: Any, row: Any, *, can_plain: bool) -> str:
|
||||
@@ -1858,7 +1869,7 @@ class AppointmentsPage(QWidget):
|
||||
if _diagnosis_id(row) <= 0 or _appointment_id(row) <= 0:
|
||||
show_toast(self, "该预约缺少诊单信息,请先编辑患者。", "warning")
|
||||
return
|
||||
mode = "view" if prescription_action_label(row) == "查看" else "open"
|
||||
mode = {"查看": "view", "重新开方": "reissue"}.get(prescription_action_label(row), "open")
|
||||
self._begin_prescription_load(row, mode=mode)
|
||||
|
||||
def _view_case(self) -> None:
|
||||
@@ -1943,25 +1954,20 @@ class AppointmentsPage(QWidget):
|
||||
expected_id = _as_int(
|
||||
first_value(row, "current_prescription_id", default=0)
|
||||
)
|
||||
actual_appointment_id = _as_int(
|
||||
first_value(existing, "appointment_id", default=0)
|
||||
)
|
||||
expected_appointment_id = _appointment_id(row)
|
||||
identity_changed = (
|
||||
(expected_id > 0 and actual_id != expected_id)
|
||||
or (
|
||||
actual_appointment_id > 0
|
||||
and expected_appointment_id > 0
|
||||
and actual_appointment_id != expected_appointment_id
|
||||
)
|
||||
)
|
||||
if mode == "view" and (not approved or voided or identity_changed):
|
||||
if not prescription_matches_appointment(
|
||||
existing, appointment_id=_appointment_id(row), diagnosis_id=_diagnosis_id(row), previous_id=expected_id,
|
||||
):
|
||||
self.banner.show_message("返回的处方与当前挂号不一致,已停止操作。", "warning")
|
||||
return
|
||||
if mode == "view" and (not approved or voided):
|
||||
self.banner.show_message(
|
||||
"当前挂号的处方状态已变化,请刷新列表后重试。",
|
||||
"warning",
|
||||
)
|
||||
return
|
||||
if not approved or voided:
|
||||
if voided and can_reissue_prescription(existing, self.current_user, self.permissions):
|
||||
self._open_new_prescription(reissue_prescription_seed(existing))
|
||||
elif not approved and not prescription_edit_is_locked(existing):
|
||||
self._open_existing_prescription_editor(existing)
|
||||
else:
|
||||
dialog = PrescriptionDetailDialog(
|
||||
@@ -1969,12 +1975,16 @@ class AppointmentsPage(QWidget):
|
||||
can_open_diagnosis=_canonical_allowed(
|
||||
self.permissions, "tcm.diagnosis/readonlyDetail", default=False
|
||||
),
|
||||
allow_void=True,
|
||||
parent=self,
|
||||
)
|
||||
dialog.diagnosis_requested.connect(self._open_diagnosis_id)
|
||||
dialog.exec()
|
||||
if dialog.exec() == PRESCRIPTION_VOIDED_RESULT:
|
||||
self._after_prescription_void()
|
||||
if expected_id > 0 and actual_id != expected_id and not self._mutation_pending:
|
||||
self.refresh(silent=True)
|
||||
return
|
||||
if mode == "view":
|
||||
if mode in {"view", "reissue"}:
|
||||
self.banner.show_message(
|
||||
"当前挂号没有可查看的处方,请刷新列表后重试。",
|
||||
"warning",
|
||||
@@ -1987,41 +1997,55 @@ class AppointmentsPage(QWidget):
|
||||
if prescription_id <= 0:
|
||||
self.banner.show_message("处方编号不完整,无法编辑。", "danger")
|
||||
return
|
||||
def save_changes(payload: Any) -> Any:
|
||||
return invoke(self.repository, "update_prescription", prescription=prescription_id, changes=payload)
|
||||
|
||||
dialog = PrescriptionEditorDialog(
|
||||
self.repository,
|
||||
prescription,
|
||||
mode="edit",
|
||||
current_user=self.current_user,
|
||||
save_draft=save_changes,
|
||||
allow_void=True,
|
||||
parent=self,
|
||||
)
|
||||
diagnosis_signal = getattr(dialog, "diagnosis_requested", None)
|
||||
if diagnosis_signal is not None:
|
||||
diagnosis_signal.connect(self._open_diagnosis_id)
|
||||
if dialog.exec() != QDialog.DialogCode.Accepted:
|
||||
result = dialog.exec()
|
||||
if result == PRESCRIPTION_VOIDED_RESULT:
|
||||
self._after_prescription_void()
|
||||
return
|
||||
if result != QDialog.DialogCode.Accepted:
|
||||
return
|
||||
self._action_generation += 1
|
||||
generation = self._action_generation
|
||||
saved_draft = getattr(dialog, "saved_draft", None)
|
||||
if saved_draft is not None:
|
||||
self._prescription_updated(generation, saved_draft)
|
||||
return
|
||||
frozen_payload = MappingProxyType(dialog.payload())
|
||||
self._mutation_pending = True
|
||||
self._action_generation += 1
|
||||
generation = self._action_generation
|
||||
self.banner.show_message("正在保存处方…", "info")
|
||||
run_async(
|
||||
lambda: invoke(
|
||||
self.repository,
|
||||
"update_prescription",
|
||||
prescription=prescription_id,
|
||||
changes=frozen_payload,
|
||||
),
|
||||
on_success=lambda _result: self._prescription_updated(generation),
|
||||
lambda: save_changes(frozen_payload),
|
||||
on_success=lambda result: self._prescription_updated(generation, result),
|
||||
on_error=lambda error: self._action_error(error, generation),
|
||||
on_finished=lambda: self._mutation_finished(generation),
|
||||
)
|
||||
|
||||
def _prescription_updated(self, generation: int) -> None:
|
||||
def _prescription_updated(self, generation: int, prescription: Any = None) -> None:
|
||||
if generation != self._action_generation:
|
||||
return
|
||||
self.banner.show_message("处方已保存并重新进入待审核。", "success")
|
||||
message, kind = saved_prescription_message(prescription, "处方已保存并重新进入待审核。")
|
||||
self.banner.show_message(message, kind)
|
||||
resume_saved_prescription(self.repository, prescription, self)
|
||||
self.refresh(silent=True)
|
||||
|
||||
def _after_prescription_void(self) -> None:
|
||||
show_toast(self, "处方已作废。需要再次开具时,请选择「重新开方」。", "success")
|
||||
self.refresh(silent=True)
|
||||
|
||||
def _begin_case_record_load(self, row: Any) -> None:
|
||||
snapshot = deepcopy(row)
|
||||
diagnosis_id = _diagnosis_id(snapshot)
|
||||
@@ -2098,12 +2122,23 @@ class AppointmentsPage(QWidget):
|
||||
self._diagnosis_dialog().open_view_only(diagnosis_id)
|
||||
|
||||
def _open_prescription_editor(self, record: Any, case_record: Any) -> None:
|
||||
seed = self._prescription_seed(record, case_record)
|
||||
self._open_new_prescription(self._prescription_seed(record, case_record))
|
||||
|
||||
def _open_new_prescription(self, seed: dict[str, Any]) -> None:
|
||||
def save_new(payload: dict[str, Any]) -> Any:
|
||||
authoritative = {
|
||||
"diagnosis_id": seed["diagnosis_id"],
|
||||
"appointment_id": seed["appointment_id"],
|
||||
"case_record": deepcopy(seed.get("case_record", {})),
|
||||
}
|
||||
return invoke(self.repository, "create_prescription", prescription=MappingProxyType(payload | authoritative))
|
||||
|
||||
dialog = PrescriptionEditorDialog(
|
||||
self.repository,
|
||||
seed,
|
||||
mode="add",
|
||||
current_user=self.current_user,
|
||||
save_draft=save_new,
|
||||
parent=self,
|
||||
)
|
||||
diagnosis_signal = getattr(dialog, "diagnosis_requested", None)
|
||||
@@ -2111,26 +2146,28 @@ class AppointmentsPage(QWidget):
|
||||
diagnosis_signal.connect(self._open_diagnosis_id)
|
||||
if dialog.exec() != QDialog.DialogCode.Accepted:
|
||||
return
|
||||
payload = dialog.payload()
|
||||
payload["diagnosis_id"] = seed["diagnosis_id"]
|
||||
payload["appointment_id"] = seed["appointment_id"]
|
||||
payload["case_record"] = deepcopy(case_record)
|
||||
frozen_payload = MappingProxyType(payload)
|
||||
self._mutation_pending = True
|
||||
self._action_generation += 1
|
||||
generation = self._action_generation
|
||||
saved_draft = getattr(dialog, "saved_draft", None)
|
||||
if saved_draft is not None:
|
||||
self._prescription_created(generation, saved_draft)
|
||||
return
|
||||
payload = dialog.payload()
|
||||
self._mutation_pending = True
|
||||
self.banner.show_message("正在提交处方…", "info")
|
||||
run_async(
|
||||
lambda: invoke(self.repository, "create_prescription", prescription=frozen_payload),
|
||||
on_success=lambda _result: self._prescription_created(generation),
|
||||
lambda: save_new(payload),
|
||||
on_success=lambda result: self._prescription_created(generation, result),
|
||||
on_error=lambda error: self._action_error(error, generation),
|
||||
on_finished=lambda: self._mutation_finished(generation),
|
||||
)
|
||||
|
||||
def _prescription_created(self, generation: int) -> None:
|
||||
def _prescription_created(self, generation: int, prescription: Any = None) -> None:
|
||||
if generation != self._action_generation:
|
||||
return
|
||||
self.banner.show_message("处方已开具并提交审核。", "success")
|
||||
message, kind = saved_prescription_message(prescription, "处方已开具并提交审核。")
|
||||
self.banner.show_message(message, kind)
|
||||
resume_saved_prescription(self.repository, prescription, self)
|
||||
self.refresh(silent=True)
|
||||
|
||||
def _prescription_error(self, error: Exception, generation: int) -> None:
|
||||
|
||||
@@ -48,17 +48,27 @@ from ..diagnosis_index_widgets import (
|
||||
DiagnosisLoadingOverlay,
|
||||
DiagnosisTableHost,
|
||||
FlowWidget,
|
||||
can_void_prescription,
|
||||
prescription_action,
|
||||
video_call_is_live,
|
||||
)
|
||||
from ..dialogs import DiagnosisDialog
|
||||
from ..dialogs.ai_consult import can_open_ai_consult, present_ai_consult
|
||||
from ..dialogs.prescription import (
|
||||
PRESCRIPTION_VOIDED_RESULT,
|
||||
PrescriptionDetailDialog,
|
||||
PrescriptionEditorDialog,
|
||||
build_prescription_clinical_diagnosis,
|
||||
build_prescription_visit_no,
|
||||
can_reissue_prescription,
|
||||
can_void_issued_prescription,
|
||||
confirm_prescription_void,
|
||||
prescription_edit_is_locked,
|
||||
prescription_is_voided,
|
||||
prescription_matches_appointment,
|
||||
reissue_prescription_seed,
|
||||
)
|
||||
from ..dialogs.prescription_esign import resume_saved_prescription, saved_prescription_message
|
||||
from ..filter_disclosure import FilterDisclosure
|
||||
from ..infinite_list import InfiniteList
|
||||
from ..theme import mark_business_dialog
|
||||
@@ -319,16 +329,6 @@ def prescription_action_label(record: Any) -> str:
|
||||
return prescription_action(record)[0]
|
||||
|
||||
|
||||
def can_void_prescription(record: Any) -> bool:
|
||||
if record is None:
|
||||
return False
|
||||
if _as_int(first_value(record, "prescription_void_status", "void_status"), 0) == 1:
|
||||
return False
|
||||
if _as_int(first_value(record, "prescription_audit_status", "audit_status"), -1) == 1:
|
||||
return False
|
||||
return not _as_bool(first_value(record, "has_prescription_order", default=False))
|
||||
|
||||
|
||||
def _status_value(row: Any) -> tuple[str, str]:
|
||||
status = _as_int(_appointment_status(row), -1)
|
||||
fallback = APPOINTMENT_STATUS.get(status)
|
||||
@@ -2365,6 +2365,7 @@ class ConsultationsPage(QWidget):
|
||||
"view": self._open_readonly,
|
||||
"edit": self._open_edit,
|
||||
"prescription": self._open_prescription,
|
||||
"void_prescription": self._void_selected_prescription,
|
||||
"ai_consult": self._open_ai_consult,
|
||||
"appointment": self._book_selected_appointment,
|
||||
"fill_id_card": self._fill_selected_id_card,
|
||||
@@ -3226,7 +3227,7 @@ class ConsultationsPage(QWidget):
|
||||
return deepcopy(detail)
|
||||
|
||||
def _open_prescription(self) -> None:
|
||||
if not _canonical_allowed(self.permissions, "tcm.diagnosis/kaifang"):
|
||||
if self._mutation_pending or self._prescription_busy or not _canonical_allowed(self.permissions, "tcm.diagnosis/kaifang"):
|
||||
return
|
||||
record = self.table.current_data()
|
||||
if _as_int(first_value(record, "diagnosis_id", "id", default=0)) <= 0:
|
||||
@@ -3238,7 +3239,7 @@ class ConsultationsPage(QWidget):
|
||||
self._begin_prescription_load(record, mode=mode)
|
||||
|
||||
def _void_selected_prescription(self) -> None:
|
||||
if not _canonical_allowed(self.permissions, "tcm.diagnosis/kaifang"):
|
||||
if self._mutation_pending or self._prescription_busy or not _canonical_allowed(self.permissions, "tcm.diagnosis/kaifang"):
|
||||
return
|
||||
record = self.table.current_data()
|
||||
if record is None or not can_void_prescription(record):
|
||||
@@ -3267,35 +3268,32 @@ class ConsultationsPage(QWidget):
|
||||
return
|
||||
self.banner.clear()
|
||||
self._last_prescription = existing
|
||||
if mode == "void":
|
||||
self._confirm_void(existing)
|
||||
return
|
||||
if existing is not None:
|
||||
approved = _as_int(first_value(existing, "audit_status", "status"), -1) == 1
|
||||
voided = _as_int(first_value(existing, "void_status", "is_void"), 0) == 1
|
||||
voided = prescription_is_voided(existing)
|
||||
actual_id = _as_int(first_value(existing, "id", "prescription_id", default=0))
|
||||
expected_id = _as_int(
|
||||
first_value(record, "current_prescription_id", default=0)
|
||||
)
|
||||
actual_appointment_id = _as_int(
|
||||
first_value(existing, "appointment_id", default=0)
|
||||
)
|
||||
expected_appointment_id = _appointment_id(record)
|
||||
identity_changed = (
|
||||
(expected_id > 0 and actual_id != expected_id)
|
||||
or (
|
||||
actual_appointment_id > 0
|
||||
and expected_appointment_id > 0
|
||||
and actual_appointment_id != expected_appointment_id
|
||||
)
|
||||
)
|
||||
if mode == "view" and (not approved or voided or identity_changed):
|
||||
if not prescription_matches_appointment(
|
||||
existing, appointment_id=_appointment_id(record),
|
||||
diagnosis_id=_as_int(first_value(record, "diagnosis_id", "id")), previous_id=expected_id,
|
||||
):
|
||||
self.banner.show_message("返回的处方与当前挂号不一致,已停止操作。", "warning")
|
||||
return
|
||||
if mode == "view" and (not approved or voided):
|
||||
self.banner.show_message(
|
||||
"当前挂号的处方状态已变化,请刷新列表后重试。",
|
||||
"warning",
|
||||
)
|
||||
return
|
||||
if not approved or voided:
|
||||
current_changed = expected_id > 0 and actual_id != expected_id
|
||||
if mode == "void":
|
||||
self._confirm_void(existing, current_changed=current_changed)
|
||||
return
|
||||
if voided and can_reissue_prescription(existing, self.current_user, self.permissions):
|
||||
self._open_new_prescription(reissue_prescription_seed(existing))
|
||||
elif not approved and not prescription_edit_is_locked(existing):
|
||||
self._open_existing_prescription_editor(existing)
|
||||
else:
|
||||
detail = PrescriptionDetailDialog(
|
||||
@@ -3303,12 +3301,16 @@ class ConsultationsPage(QWidget):
|
||||
can_open_diagnosis=_canonical_allowed(
|
||||
self.permissions, "tcm.diagnosis/readonlyDetail"
|
||||
),
|
||||
allow_void=True,
|
||||
parent=self,
|
||||
)
|
||||
detail.diagnosis_requested.connect(self._open_diagnosis_id)
|
||||
detail.exec()
|
||||
if detail.exec() == PRESCRIPTION_VOIDED_RESULT:
|
||||
self._after_prescription_void()
|
||||
if current_changed and not self._mutation_pending:
|
||||
self.refresh(silent=True)
|
||||
return
|
||||
if mode == "view":
|
||||
if mode in {"view", "void", "reissue"}:
|
||||
self.banner.show_message(
|
||||
"当前挂号没有可查看的处方,请刷新列表后重试。",
|
||||
"warning",
|
||||
@@ -3321,28 +3323,29 @@ class ConsultationsPage(QWidget):
|
||||
if prescription_id <= 0:
|
||||
self.banner.show_message("处方编号不完整,无法编辑。", "danger")
|
||||
return
|
||||
|
||||
def save_changes(payload: Any) -> Any:
|
||||
return invoke(self.repository, "update_prescription", prescription=prescription_id, changes=payload)
|
||||
|
||||
dialog = PrescriptionEditorDialog(
|
||||
self.repository,
|
||||
prescription,
|
||||
mode="edit",
|
||||
current_user=self.current_user,
|
||||
save_draft=save_changes,
|
||||
allow_void=True,
|
||||
parent=self,
|
||||
)
|
||||
diagnosis_signal = getattr(dialog, "diagnosis_requested", None)
|
||||
if diagnosis_signal is not None:
|
||||
diagnosis_signal.connect(self._open_diagnosis_id)
|
||||
if dialog.exec() != QDialog.DialogCode.Accepted:
|
||||
result = dialog.exec()
|
||||
if result == PRESCRIPTION_VOIDED_RESULT:
|
||||
self._after_prescription_void()
|
||||
return
|
||||
frozen_payload = MappingProxyType(dialog.payload())
|
||||
self._run_mutation(
|
||||
lambda: invoke(
|
||||
self.repository,
|
||||
"update_prescription",
|
||||
prescription=prescription_id,
|
||||
changes=frozen_payload,
|
||||
),
|
||||
"处方已保存并重新进入待审核。",
|
||||
)
|
||||
if result != QDialog.DialogCode.Accepted:
|
||||
return
|
||||
self._finish_prescription_edit(dialog, save_changes, "处方已保存并重新进入待审核。")
|
||||
|
||||
def _begin_case_record_load(self, record: Any) -> None:
|
||||
record_snapshot = deepcopy(record)
|
||||
@@ -3427,12 +3430,20 @@ class ConsultationsPage(QWidget):
|
||||
}
|
||||
|
||||
def _open_prescription_editor(self, record: Any, case_record: Any) -> None:
|
||||
seed = self._prescription_seed(record, case_record)
|
||||
self._open_new_prescription(self._prescription_seed(record, case_record))
|
||||
|
||||
def _open_new_prescription(self, seed: dict[str, Any]) -> None:
|
||||
linked_fields = {key: seed[key] for key in ("diagnosis_id", "appointment_id", "case_record") if key in seed}
|
||||
|
||||
def save_new(payload: dict[str, Any]) -> Any:
|
||||
return invoke(self.repository, "create_prescription", prescription=MappingProxyType(dict(payload) | linked_fields))
|
||||
|
||||
dialog = PrescriptionEditorDialog(
|
||||
self.repository,
|
||||
seed,
|
||||
mode="add",
|
||||
current_user=self.current_user,
|
||||
save_draft=save_new,
|
||||
parent=self,
|
||||
)
|
||||
diagnosis_signal = getattr(dialog, "diagnosis_requested", None)
|
||||
@@ -3440,17 +3451,27 @@ class ConsultationsPage(QWidget):
|
||||
diagnosis_signal.connect(self._open_diagnosis_id)
|
||||
if dialog.exec() != QDialog.DialogCode.Accepted:
|
||||
return
|
||||
payload = dialog.payload()
|
||||
payload["diagnosis_id"] = seed["diagnosis_id"]
|
||||
payload["appointment_id"] = seed["appointment_id"]
|
||||
payload["case_record"] = deepcopy(case_record)
|
||||
frozen_payload = MappingProxyType(payload)
|
||||
self._run_mutation(
|
||||
lambda: invoke(self.repository, "create_prescription", prescription=frozen_payload),
|
||||
"处方已开具并提交审核。",
|
||||
)
|
||||
self._finish_prescription_edit(dialog, save_new, "处方已开具并提交审核。")
|
||||
|
||||
def _finish_prescription_edit(self, dialog: PrescriptionEditorDialog, save: Any, message: str) -> None:
|
||||
saved = getattr(dialog, "saved_draft", None)
|
||||
if saved is not None:
|
||||
self._prescription_saved(saved, message)
|
||||
return
|
||||
payload = MappingProxyType(dialog.payload())
|
||||
self._run_mutation(lambda: save(payload), message, on_saved=self._prescription_saved)
|
||||
|
||||
def _prescription_saved(self, prescription: Any, fallback: str) -> None:
|
||||
message, kind = saved_prescription_message(prescription, fallback)
|
||||
show_toast(self, message, kind)
|
||||
resume_saved_prescription(self.repository, prescription, self)
|
||||
self.refresh(silent=True)
|
||||
|
||||
def _after_prescription_void(self) -> None:
|
||||
show_toast(self, "处方已作废。需要再次开具时,请选择「重新开方」。", "success")
|
||||
self.refresh(silent=True)
|
||||
|
||||
def _confirm_void(self, prescription: Any) -> None:
|
||||
def _confirm_void(self, prescription: Any, *, current_changed: bool = False) -> None:
|
||||
if prescription is None:
|
||||
self.banner.show_message("当前诊单没有可作废的处方。", "warning")
|
||||
return
|
||||
@@ -3460,21 +3481,14 @@ class ConsultationsPage(QWidget):
|
||||
if _as_int(first_value(prescription, "void_status", "is_void"), 0) == 1:
|
||||
self.banner.show_message("该处方已经作废。", "warning")
|
||||
return
|
||||
if _as_int(first_value(prescription, "audit_status", "status"), -1) == 1:
|
||||
self.banner.show_message("审核通过且有效的处方仅供查看,不能在此作废。", "warning")
|
||||
return
|
||||
prescription_id = _as_int(first_value(prescription, "id", "prescription_id"))
|
||||
if prescription_id <= 0:
|
||||
self.banner.show_message("处方信息不完整,无法作废。", "warning")
|
||||
return
|
||||
answer = QMessageBox.warning(
|
||||
self,
|
||||
"作废处方",
|
||||
"确定作废该处方吗?作废后不可恢复。",
|
||||
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.Cancel,
|
||||
QMessageBox.StandardButton.Cancel,
|
||||
)
|
||||
if answer != QMessageBox.StandardButton.Yes:
|
||||
if not can_void_issued_prescription(prescription):
|
||||
self.banner.show_message("当前处方不可作废,请核对操作权限和订单状态。", "warning")
|
||||
return
|
||||
if not confirm_prescription_void(self, prescription, current_changed=current_changed):
|
||||
return
|
||||
self._run_mutation(
|
||||
lambda: invoke(
|
||||
@@ -3483,19 +3497,26 @@ class ConsultationsPage(QWidget):
|
||||
prescription_id=prescription_id,
|
||||
id=prescription_id,
|
||||
),
|
||||
"处方已作废。",
|
||||
"处方已作废。需要再次开具时,请选择「重新开方」。",
|
||||
)
|
||||
|
||||
def _run_mutation(self, operation: Any, success_message: str) -> None:
|
||||
def _run_mutation(self, operation: Any, success_message: str, *, on_saved: Any = None) -> None:
|
||||
self._mutation_generation += 1
|
||||
generation = self._mutation_generation
|
||||
self._mutation_pending = True
|
||||
self.table_host.setEnabled(False)
|
||||
self._checked_changed(len(self.table_host.selected_records()))
|
||||
self._selection_changed()
|
||||
def succeeded(result: Any) -> None:
|
||||
if on_saved is None:
|
||||
self._mutation_success(success_message, generation)
|
||||
elif generation == self._mutation_generation:
|
||||
self.table_host.clear_checks()
|
||||
on_saved(result, success_message)
|
||||
|
||||
run_async(
|
||||
operation,
|
||||
on_success=lambda _result: self._mutation_success(success_message, generation),
|
||||
on_success=succeeded,
|
||||
on_error=lambda error: self._mutation_error(error, generation),
|
||||
on_finished=lambda: self._mutation_finished(generation),
|
||||
)
|
||||
|
||||
@@ -48,12 +48,20 @@ from ...core.appointment_modes import (
|
||||
appointment_type_description,
|
||||
appointment_type_value,
|
||||
)
|
||||
from ...core.esign import esign_status
|
||||
from .. import icons
|
||||
from ..appointment_drawer import AppointmentDrawer
|
||||
from ..design_system import PALETTE, clinical_stylesheet
|
||||
from ..dialogs import DiagnosisDialog, present_ai_consult, present_order_detail
|
||||
from ..dialogs.ai_consult import can_open_ai_consult
|
||||
from ..dialogs.prescription import PrescriptionOrderListDialog
|
||||
from ..dialogs.prescription_esign import (
|
||||
PrescriptionEsignDialog,
|
||||
can_continue_prescription_esign,
|
||||
can_review_uploaded_prescription,
|
||||
review_signature_time,
|
||||
review_submission_time,
|
||||
)
|
||||
from ..filter_disclosure import FilterDisclosure
|
||||
from ..infinite_list import InfiniteList
|
||||
from ..patient_orders_style import patient_orders_stylesheet
|
||||
@@ -2677,6 +2685,7 @@ class PatientOrdersWorkspace(QWidget):
|
||||
allowed("tcm.prescriptionOrder/auditPrescription")
|
||||
and rx_audit == 0
|
||||
and fulfillment not in {3, 4, 6}
|
||||
and can_review_uploaded_prescription(row, {})
|
||||
):
|
||||
actions.append(("audit_prescription", "处方审核", False))
|
||||
if (
|
||||
@@ -3185,6 +3194,7 @@ class PatientsPage(QWidget):
|
||||
self._detail_generation = 0
|
||||
self._edit_generation = 0
|
||||
self._assistant_generation = 0
|
||||
self._order_review_generation = 0
|
||||
|
||||
root = QVBoxLayout(self)
|
||||
root.setContentsMargins(28, 8, 26, 8)
|
||||
@@ -3647,6 +3657,69 @@ class PatientsPage(QWidget):
|
||||
if generation == self._edit_generation:
|
||||
self.order_workspace.banner.show_message(friendly_error(error), "danger")
|
||||
|
||||
def _submit_order_audit(self, order_id: int, *, prescription: bool, action: str) -> None:
|
||||
label = "处方审核" if prescription else "支付单审核"
|
||||
remark, accepted = QInputDialog.getText(self, label, "审核备注:")
|
||||
if not accepted:
|
||||
return
|
||||
if action == "reject" and not remark.strip():
|
||||
show_toast(self, "驳回时必须填写审核意见。", "danger")
|
||||
return
|
||||
method = "audit_patient_order_prescription" if prescription else "audit_patient_order_payment"
|
||||
self._run_action(
|
||||
"正在处理订单…",
|
||||
lambda: _invoke_first(
|
||||
self.repository, (method,), order_id=order_id, action=action, remark=remark.strip()
|
||||
),
|
||||
success=f"{label}已提交。",
|
||||
)
|
||||
|
||||
def _check_order_signature_before_approval(self, row: Any, order_id: int) -> None:
|
||||
status_method = getattr(self.repository, "get_prescription_esign_status", None)
|
||||
if not callable(status_method):
|
||||
self._submit_order_audit(order_id, prescription=True, action="approve")
|
||||
return
|
||||
prescription_id = _as_int(first_value(row, "prescription_id"))
|
||||
if prescription_id <= 0:
|
||||
self.order_workspace.banner.show_message("找不到此订单的处方,请刷新订单后重试。", "warning")
|
||||
return
|
||||
self._order_review_generation += 1
|
||||
generation = self._order_review_generation
|
||||
self.order_workspace.banner.show_message("正在核对关联处方的签署状态…", "info")
|
||||
|
||||
def failed(error: Exception) -> None:
|
||||
if self._order_review_generation == generation:
|
||||
self.order_workspace.banner.show_message(f"未能核对签署状态。{friendly_error(error)}", "warning")
|
||||
|
||||
def checked(state: dict[str, Any]) -> None:
|
||||
if self._order_review_generation != generation:
|
||||
return
|
||||
if review_submission_time(row, state) == 0:
|
||||
self.order_workspace.banner.show_message("请开方医生上传处方后再审核。", "warning")
|
||||
return
|
||||
verified = state["required"] and state["status"] == "signed" and state["can_download"]
|
||||
historical = not state["required"] and state["status"] == "legacy" and not state["can_download"]
|
||||
if verified and state.get("review_required") is True and not review_signature_time(state):
|
||||
self.order_workspace.banner.show_message("请先在管理后台完成药师审核签署,再提交审核通过。", "warning")
|
||||
return
|
||||
if verified or historical:
|
||||
self.order_workspace.banner.clear()
|
||||
self._submit_order_audit(order_id, prescription=True, action="approve")
|
||||
return
|
||||
if can_continue_prescription_esign(state, self.permissions, row):
|
||||
dialog = PrescriptionEsignDialog(self.repository, {"id": prescription_id, "esign": state}, parent=self)
|
||||
dialog.exec()
|
||||
self.order_workspace.banner.show_message("请在签署验签通过后,再点击处方审核。", "info")
|
||||
self.order_workspace.refresh(silent=True)
|
||||
else:
|
||||
message = state.get("message") or (
|
||||
"签署原件暂不可用,请联系管理员核验。" if state["status"] == "signed"
|
||||
else "请开方医生完成处方签署并通过验签,再审核通过。"
|
||||
)
|
||||
self.order_workspace.banner.show_message(str(message), "warning")
|
||||
|
||||
run_async(lambda: esign_status(status_method(prescription_id)), on_success=checked, on_error=failed)
|
||||
|
||||
def _handle_order_action(self, key: str, row: Any) -> None:
|
||||
allowed_keys = {item[0] for item in self.order_workspace._available_actions(row)}
|
||||
if key not in allowed_keys:
|
||||
@@ -3662,35 +3735,20 @@ class PatientsPage(QWidget):
|
||||
call: Any
|
||||
success = "订单已更新。"
|
||||
if key in {"audit_prescription", "audit_payment"}:
|
||||
label = "处方审核" if key == "audit_prescription" else "支付单审核"
|
||||
self._order_review_generation += 1
|
||||
prescription = key == "audit_prescription"
|
||||
label = "处方审核" if prescription else "支付单审核"
|
||||
action_label, accepted = QInputDialog.getItem(
|
||||
self, label, "审核结果:", ["通过", "驳回"], 0, False
|
||||
)
|
||||
if not accepted:
|
||||
return
|
||||
remark, accepted = QInputDialog.getText(self, label, "审核备注:")
|
||||
if not accepted:
|
||||
return
|
||||
method = (
|
||||
"audit_patient_order_prescription"
|
||||
if key == "audit_prescription"
|
||||
else "audit_patient_order_payment"
|
||||
)
|
||||
action = "approve" if action_label == "通过" else "reject"
|
||||
if action == "reject" and not remark.strip():
|
||||
show_toast(self, "驳回时必须填写审核意见。", "danger")
|
||||
return
|
||||
|
||||
def call() -> Any:
|
||||
return _invoke_first(
|
||||
self.repository,
|
||||
(method,),
|
||||
order_id=order_id,
|
||||
action=action,
|
||||
remark=remark.strip(),
|
||||
)
|
||||
|
||||
success = f"{label}已提交。"
|
||||
if prescription and action == "approve":
|
||||
self._check_order_signature_before_approval(row, order_id)
|
||||
else:
|
||||
self._submit_order_audit(order_id, prescription=prescription, action=action)
|
||||
return
|
||||
elif key in {"revoke_rx_audit", "revoke_pay_audit", "withdraw", "upload_pharmacy"}:
|
||||
labels = {
|
||||
"revoke_rx_audit": "撤回处方审核",
|
||||
@@ -3833,6 +3891,7 @@ class PatientsPage(QWidget):
|
||||
self.refresh()
|
||||
|
||||
def hideEvent(self, event: Any) -> None:
|
||||
self._order_review_generation += 1
|
||||
self.progress_workspace.set_active(False)
|
||||
super().hideEvent(event)
|
||||
|
||||
|
||||
@@ -62,6 +62,7 @@ from PySide6.QtWidgets import (
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from ...core.esign import esign_status
|
||||
from .. import icons, motion
|
||||
from ..design_system import PALETTE, clinical_stylesheet
|
||||
from ..dialogs.issued_prescription_ai import (
|
||||
@@ -75,6 +76,7 @@ from ..dialogs.issued_prescription_ai import (
|
||||
status_tooltip,
|
||||
)
|
||||
from ..dialogs.prescription import (
|
||||
PRESCRIBE_PERMISSIONS,
|
||||
AuditPrescriptionDialog,
|
||||
DiagnosisDetailDialog,
|
||||
PatchPatientDialog,
|
||||
@@ -82,7 +84,24 @@ from ..dialogs.prescription import (
|
||||
PrescriptionEditorDialog,
|
||||
PrescriptionOrderDialog,
|
||||
PrescriptionOrderListDialog,
|
||||
can_reissue_prescription,
|
||||
can_void_issued_prescription,
|
||||
confirm_prescription_void,
|
||||
prescription_edit_is_locked,
|
||||
reissue_prescription_seed,
|
||||
)
|
||||
from ..dialogs.prescription_esign import (
|
||||
PrescriptionEsignDialog,
|
||||
awaiting_prescription_upload,
|
||||
can_continue_prescription_esign,
|
||||
can_review_uploaded_prescription,
|
||||
can_upload_prescription,
|
||||
resume_saved_prescription,
|
||||
review_signature_time,
|
||||
review_submission_time,
|
||||
saved_prescription_message,
|
||||
signature_state,
|
||||
)
|
||||
from ..filter_disclosure import FilterDisclosure
|
||||
from ..infinite_list import InfiniteList
|
||||
from ..prescriptions_style import prescriptions_stylesheet
|
||||
@@ -343,7 +362,7 @@ class _RowDecorationDelegate(QStyledItemDelegate):
|
||||
|
||||
|
||||
def _row_action_button(
|
||||
kind: str,
|
||||
kind: str | None,
|
||||
tooltip: str,
|
||||
callback: Callable[[], None],
|
||||
parent: QWidget,
|
||||
@@ -363,9 +382,11 @@ def _row_action_button(
|
||||
button.setAccessibleName(tooltip)
|
||||
button.setToolTip(tooltip)
|
||||
button.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||
button.setFixedSize(64 if label else 28, 28)
|
||||
button.setIcon(_painted_icon(kind, "danger" if danger else "accent", 15))
|
||||
button.setIconSize(QSize(15, 15))
|
||||
width = max(64, button.fontMetrics().horizontalAdvance(label) + 26) if label else 28
|
||||
button.setFixedSize(width, 28)
|
||||
if kind:
|
||||
button.setIcon(_painted_icon(kind, "danger" if danger else "accent", 15))
|
||||
button.setIconSize(QSize(15, 15))
|
||||
button.setEnabled(enabled)
|
||||
button.clicked.connect(callback)
|
||||
return button
|
||||
@@ -423,6 +444,15 @@ def prescription_status(row: Any) -> tuple[str, str]:
|
||||
return "已驳回", "danger"
|
||||
if status == 1:
|
||||
return "已通过", "success"
|
||||
signature = signature_state(row)
|
||||
if awaiting_prescription_upload(row, signature) and not _voided(row):
|
||||
return "待上传处方", "warning"
|
||||
if signature.get("required") is True and signature.get("status") not in {"signed", "voided"}:
|
||||
if signature.get("status") == "signing":
|
||||
return "签名处理中", "warning"
|
||||
if signature.get("status") == "uncertain":
|
||||
return ("待验签" if signature.get("can_retry_verify") is True else "签署结果待确认", "warning")
|
||||
return "待签名", "warning"
|
||||
return "待审核", "warning"
|
||||
|
||||
|
||||
@@ -443,7 +473,7 @@ def can_create_order(row: Any) -> bool:
|
||||
)
|
||||
|
||||
|
||||
def can_audit(row: Any) -> bool:
|
||||
def _is_pending_audit(row: Any) -> bool:
|
||||
return (
|
||||
row is not None
|
||||
and _int(first_value(row, "audit_status", "status"), 0) == 0
|
||||
@@ -451,10 +481,22 @@ def can_audit(row: Any) -> bool:
|
||||
)
|
||||
|
||||
|
||||
def can_audit(row: Any) -> bool:
|
||||
return _is_pending_audit(row) and can_review_uploaded_prescription(row, signature_state(row))
|
||||
|
||||
|
||||
def can_edit_or_delete(row: Any) -> bool:
|
||||
return row is not None and not is_approved_active(row)
|
||||
|
||||
|
||||
def _voided(row: Any) -> bool:
|
||||
return _int(first_value(row, "void_status", "is_void"), 0) == 1
|
||||
|
||||
|
||||
def _can_change_issued_prescription(row: Any) -> bool:
|
||||
return can_edit_or_delete(row) and not prescription_edit_is_locked(row)
|
||||
|
||||
|
||||
def _formula(value: Any) -> str:
|
||||
text = str(value or "").strip().lower()
|
||||
return "辅方" if text in {"2", "aux", "auxiliary", "辅方"} else "主方"
|
||||
@@ -592,7 +634,7 @@ def _audit_cell(_value: Any, row: Any) -> str:
|
||||
|
||||
|
||||
def _void_cell(_value: Any, row: Any) -> str:
|
||||
return "作废" if _int(first_value(row, "void_status", "is_void"), 0) == 1 else "—"
|
||||
return "作废" if _voided(row) else "—"
|
||||
|
||||
|
||||
def _doctor_cell(_value: Any, row: Any) -> str:
|
||||
@@ -1197,6 +1239,7 @@ class PrescriptionsPage(QWidget):
|
||||
self._diagnosis_detail_generation = 0
|
||||
self._diagnosis_detail_target = 0
|
||||
self._mutation_pending = False
|
||||
self._audit_check_pending = False
|
||||
self._ai_statuses: dict[int, dict[str, Any]] = {}
|
||||
self._ai_enabled = False
|
||||
self._agreement_visible = False
|
||||
@@ -1406,10 +1449,16 @@ class PrescriptionsPage(QWidget):
|
||||
toolbar.addWidget(self.create_order_button)
|
||||
self.edit_button = self._action_button("编辑", "cf.prescription/edit", self._edit_selected)
|
||||
toolbar.addWidget(self.edit_button)
|
||||
self.upload_button = self._action_button("上传处方", None, self._upload_selected)
|
||||
toolbar.addWidget(self.upload_button)
|
||||
self.audit_button = self._action_button(
|
||||
"审核", "cf.prescription/audit", self._audit_selected
|
||||
)
|
||||
toolbar.addWidget(self.audit_button)
|
||||
self.void_button = self._action_button("作废", None, self._void_selected, danger=True)
|
||||
toolbar.addWidget(self.void_button)
|
||||
self.reissue_button = self._action_button("重新开方", None, self._reissue_selected)
|
||||
toolbar.addWidget(self.reissue_button)
|
||||
self.delete_button = self._action_button(
|
||||
"删除", "cf.prescription/del", self._delete_selected, danger=True
|
||||
)
|
||||
@@ -1548,7 +1597,7 @@ class PrescriptionsPage(QWidget):
|
||||
def _action_button(
|
||||
self,
|
||||
text: str,
|
||||
permission: str,
|
||||
permission: str | None,
|
||||
handler: Callable[[], None],
|
||||
*,
|
||||
danger: bool = False,
|
||||
@@ -1561,6 +1610,8 @@ class PrescriptionsPage(QWidget):
|
||||
"查看": "eye",
|
||||
"编辑": "pencil",
|
||||
"删除": "trash",
|
||||
"重新开方": "plus",
|
||||
"上传处方": "send",
|
||||
}.get(text)
|
||||
if icon_kind:
|
||||
button.setIcon(
|
||||
@@ -1569,7 +1620,7 @@ class PrescriptionsPage(QWidget):
|
||||
button.setIconSize(QSize(15, 15))
|
||||
if danger:
|
||||
button.setProperty("variant", "danger")
|
||||
button.setVisible(has_permission(self.permissions, permission))
|
||||
button.setVisible(permission is not None and has_permission(self.permissions, permission))
|
||||
button.setEnabled(False)
|
||||
button.clicked.connect(handler)
|
||||
return button
|
||||
@@ -1707,6 +1758,7 @@ class PrescriptionsPage(QWidget):
|
||||
self.table.setUpdatesEnabled(True)
|
||||
|
||||
def _decorate_rows_locked(self) -> None:
|
||||
action_width = max(self.table.columnWidth(2), 178 if self._ai_enabled else 144)
|
||||
for row_index in range(self.table.rowCount()):
|
||||
selector = self.table.item(row_index, 0)
|
||||
if selector is None:
|
||||
@@ -1785,7 +1837,18 @@ class PrescriptionsPage(QWidget):
|
||||
actions_host, label="AI",
|
||||
)
|
||||
)
|
||||
if has_permission(self.permissions, "cf.prescription/edit"):
|
||||
if self._can_upload(row):
|
||||
actions.addWidget(
|
||||
_row_action_button(
|
||||
None, "上传处方",
|
||||
lambda _checked=False, target=row: self._run_row_action(target, self._upload_selected),
|
||||
actions_host, label="上传处方", mutation=True,
|
||||
)
|
||||
)
|
||||
can_reissue = self._can_reissue(row)
|
||||
can_change = _can_change_issued_prescription(row)
|
||||
show_changes = can_change or not _voided(row)
|
||||
if show_changes and has_permission(self.permissions, "cf.prescription/edit"):
|
||||
actions.addWidget(
|
||||
_row_action_button(
|
||||
"pencil",
|
||||
@@ -1794,12 +1857,28 @@ class PrescriptionsPage(QWidget):
|
||||
target, self._edit_selected
|
||||
),
|
||||
actions_host,
|
||||
enabled=can_edit_or_delete(row),
|
||||
enabled=can_change,
|
||||
label="编辑",
|
||||
mutation=True,
|
||||
)
|
||||
)
|
||||
if has_permission(self.permissions, "cf.prescription/del"):
|
||||
if self._can_void(row):
|
||||
actions.addWidget(
|
||||
_row_action_button(
|
||||
"close", "作废处方",
|
||||
lambda _checked=False, target=row: self._run_row_action(target, self._void_selected),
|
||||
actions_host, danger=True, label="作废", mutation=True,
|
||||
)
|
||||
)
|
||||
if can_reissue:
|
||||
actions.addWidget(
|
||||
_row_action_button(
|
||||
"plus", "重新开方",
|
||||
lambda _checked=False, target=row: self._run_row_action(target, self._reissue_selected),
|
||||
actions_host, label="重新开方", mutation=True,
|
||||
)
|
||||
)
|
||||
if show_changes and has_permission(self.permissions, "cf.prescription/del"):
|
||||
actions.addWidget(
|
||||
_row_action_button(
|
||||
"trash",
|
||||
@@ -1809,12 +1888,14 @@ class PrescriptionsPage(QWidget):
|
||||
),
|
||||
actions_host,
|
||||
danger=True,
|
||||
enabled=can_edit_or_delete(row),
|
||||
enabled=can_change,
|
||||
mutation=True,
|
||||
)
|
||||
)
|
||||
actions.addStretch(1)
|
||||
action_width = max(action_width, actions.sizeHint().width() + 4)
|
||||
self.table.setCellWidget(row_index, 2, actions_host)
|
||||
self.table.setColumnWidth(2, action_width)
|
||||
self._sync_row_mutation_actions()
|
||||
self.table.resizeRowsToContents()
|
||||
|
||||
@@ -1893,7 +1974,6 @@ class PrescriptionsPage(QWidget):
|
||||
header.moveSection(header.visualIndex(12), header.visualIndex(11) + 1)
|
||||
self.table.setColumnWidth(11, 144)
|
||||
self.table.setColumnWidth(12, 130)
|
||||
self.table.setColumnWidth(2, 178)
|
||||
if changed:
|
||||
self._decorate_rows()
|
||||
|
||||
@@ -2090,9 +2170,39 @@ class PrescriptionsPage(QWidget):
|
||||
self.ai_report_button.setEnabled(ai_available)
|
||||
self.patch_button.setEnabled(active and can_patch_patient(row))
|
||||
self.create_order_button.setEnabled(active and can_create_order(row))
|
||||
self.edit_button.setEnabled(active and can_edit_or_delete(row))
|
||||
self.audit_button.setEnabled(active and can_audit(row))
|
||||
self.delete_button.setEnabled(active and can_edit_or_delete(row))
|
||||
can_change = _can_change_issued_prescription(row)
|
||||
self.edit_button.setEnabled(active and can_change)
|
||||
pending_audit = _is_pending_audit(row)
|
||||
state = signature_state(row)
|
||||
can_sign = pending_audit and can_continue_prescription_esign(state, self.permissions, row)
|
||||
can_review = has_permission(self.permissions, "cf.prescription/audit") and can_audit(row)
|
||||
can_upload = self._can_upload(row)
|
||||
self.upload_button.setVisible(can_upload)
|
||||
self.upload_button.setEnabled(active and can_upload)
|
||||
self.audit_button.setText("继续签署" if can_sign else "审核")
|
||||
self.audit_button.setVisible(can_sign or can_review)
|
||||
self.audit_button.setEnabled(
|
||||
active and not self._audit_check_pending and (can_sign or can_review)
|
||||
)
|
||||
can_void = self._can_void(row)
|
||||
self.void_button.setVisible(can_void)
|
||||
self.void_button.setEnabled(active and can_void)
|
||||
can_reissue = self._can_reissue(row)
|
||||
self.reissue_button.setVisible(can_reissue)
|
||||
self.reissue_button.setEnabled(active and can_reissue)
|
||||
self.delete_button.setEnabled(active and can_change)
|
||||
|
||||
def _can_void(self, row: Any) -> bool:
|
||||
return can_void_issued_prescription(row)
|
||||
|
||||
def _can_reissue(self, row: Any) -> bool:
|
||||
return can_reissue_prescription(row, self.current_user, self.permissions)
|
||||
|
||||
def _can_upload(self, row: Any) -> bool:
|
||||
return (
|
||||
_is_pending_audit(row)
|
||||
and can_upload_prescription(self.repository, row, signature_state(row))
|
||||
)
|
||||
|
||||
def _set_mutation_pending(self, pending: bool) -> None:
|
||||
self._mutation_pending = pending
|
||||
@@ -2163,9 +2273,10 @@ class PrescriptionsPage(QWidget):
|
||||
row = self._selected()
|
||||
if row is None or not has_permission(self.permissions, "cf.prescription/read"):
|
||||
return
|
||||
self._load_detail(row, self._show_detail)
|
||||
was_signed = signature_state(row).get("status") == "signed"
|
||||
self._load_detail(row, lambda detail: self._show_detail(detail, was_signed=was_signed))
|
||||
|
||||
def _show_detail(self, detail: Any) -> None:
|
||||
def _show_detail(self, detail: Any, *, was_signed: bool = False) -> None:
|
||||
if not has_permission(self.permissions, "cf.prescription/read"):
|
||||
return
|
||||
dialog = PrescriptionDetailDialog(
|
||||
@@ -2176,7 +2287,12 @@ class PrescriptionsPage(QWidget):
|
||||
)
|
||||
dialog.diagnosis_requested.connect(self._open_diagnosis)
|
||||
dialog.orders_requested.connect(lambda prescription_id: self._open_orders(prescription_id))
|
||||
submitted_at = review_submission_time(detail, dialog.esign)
|
||||
dialog.exec()
|
||||
if review_submission_time(detail, dialog.esign) != submitted_at or (
|
||||
not was_signed and dialog.esign.get("status") == "signed"
|
||||
):
|
||||
self.refresh()
|
||||
|
||||
def _open_diagnosis(self, diagnosis_id: int) -> None:
|
||||
if not has_permission(self.permissions, "tcm.diagnosis/readonlyDetail"):
|
||||
@@ -2230,17 +2346,60 @@ class PrescriptionsPage(QWidget):
|
||||
self.banner.show_message(friendly_error(error), "danger")
|
||||
|
||||
def _add_prescription(self) -> None:
|
||||
if not has_permission(self.permissions, "cf.prescription/add"):
|
||||
if has_permission(self.permissions, "cf.prescription/add"):
|
||||
self._open_new_prescription()
|
||||
|
||||
def _open_new_prescription(self, seed: dict[str, Any] | None = None) -> None:
|
||||
if self._mutation_pending or not has_permission(self.permissions, PRESCRIBE_PERMISSIONS):
|
||||
return
|
||||
dialog = PrescriptionEditorDialog(
|
||||
self.repository,
|
||||
seed,
|
||||
mode="add",
|
||||
current_user=self.current_user,
|
||||
save_draft=lambda payload: self.repository.create_prescription(payload),
|
||||
parent=self,
|
||||
)
|
||||
dialog.diagnosis_requested.connect(self._open_diagnosis)
|
||||
if dialog.exec() == QDialog.DialogCode.Accepted:
|
||||
self._save_prescription(dialog.payload(), None)
|
||||
saved = getattr(dialog, "saved_draft", None)
|
||||
if saved is not None:
|
||||
self._prescription_saved(saved, "处方已新增并提交审核。")
|
||||
else:
|
||||
self._save_prescription(dialog.payload(), None)
|
||||
|
||||
def _void_selected(self) -> None:
|
||||
row = self._selected()
|
||||
if self._mutation_pending or not self._can_void(row):
|
||||
return
|
||||
prescription_id = _int(first_value(row, "id", "prescription_id"))
|
||||
if prescription_id <= 0:
|
||||
self.banner.show_message("处方 ID 无效,请刷新列表后重试。", "warning")
|
||||
return
|
||||
if not confirm_prescription_void(self, row):
|
||||
return
|
||||
self._set_mutation_pending(True)
|
||||
run_async(
|
||||
lambda: self.repository.void_prescription(prescription_id),
|
||||
on_success=lambda _result: self._mutation_success("处方已作废。"),
|
||||
on_error=self._mutation_error,
|
||||
on_finished=lambda: self._set_mutation_pending(False),
|
||||
)
|
||||
|
||||
def _reissue_selected(self) -> None:
|
||||
row = self._selected()
|
||||
if self._mutation_pending or not self._can_reissue(row):
|
||||
return
|
||||
self._load_detail(
|
||||
row, lambda detail: self._open_reissue(merge_prescription_detail(row, detail)),
|
||||
message="正在准备重新开方…",
|
||||
)
|
||||
|
||||
def _open_reissue(self, detail: dict[str, Any]) -> None:
|
||||
if not self._can_reissue(detail):
|
||||
self.banner.show_message("该处方当前不可重新开方,请刷新列表后重试。", "warning")
|
||||
return
|
||||
self._open_new_prescription(reissue_prescription_seed(detail))
|
||||
|
||||
def _edit_selected(self) -> None:
|
||||
row = self._selected()
|
||||
@@ -2248,7 +2407,7 @@ class PrescriptionsPage(QWidget):
|
||||
row is None
|
||||
or self._mutation_pending
|
||||
or not has_permission(self.permissions, "cf.prescription/edit")
|
||||
or not can_edit_or_delete(row)
|
||||
or not _can_change_issued_prescription(row)
|
||||
):
|
||||
return
|
||||
self._load_detail(
|
||||
@@ -2258,29 +2417,32 @@ class PrescriptionsPage(QWidget):
|
||||
)
|
||||
|
||||
def _open_editor(self, detail: Any) -> None:
|
||||
if not can_edit_or_delete(detail):
|
||||
if not _can_change_issued_prescription(detail):
|
||||
self.banner.show_message("该处方状态已变化,当前不能编辑。", "warning")
|
||||
return
|
||||
prescription_id = _int(first_value(detail, "id", "prescription_id"), 0)
|
||||
dialog = PrescriptionEditorDialog(
|
||||
self.repository,
|
||||
detail,
|
||||
mode="edit",
|
||||
current_user=self.current_user,
|
||||
save_draft=lambda payload: self.repository.update_prescription(prescription_id, changes=payload),
|
||||
parent=self,
|
||||
)
|
||||
dialog.diagnosis_requested.connect(self._open_diagnosis)
|
||||
if dialog.exec() == QDialog.DialogCode.Accepted:
|
||||
self._save_prescription(
|
||||
dialog.payload(),
|
||||
_int(first_value(detail, "id", "prescription_id"), 0),
|
||||
)
|
||||
saved = getattr(dialog, "saved_draft", None)
|
||||
if saved is not None:
|
||||
self._prescription_saved(saved, "处方已保存并重新进入待审核。")
|
||||
else:
|
||||
self._save_prescription(dialog.payload(), prescription_id)
|
||||
|
||||
def _save_prescription(
|
||||
self,
|
||||
payload: dict[str, Any],
|
||||
prescription_id: int | None,
|
||||
) -> None:
|
||||
permission = "cf.prescription/edit" if prescription_id else "cf.prescription/add"
|
||||
permission = "cf.prescription/edit" if prescription_id else PRESCRIBE_PERMISSIONS
|
||||
if not has_permission(self.permissions, permission):
|
||||
return
|
||||
self._set_mutation_pending(True)
|
||||
@@ -2301,10 +2463,19 @@ class PrescriptionsPage(QWidget):
|
||||
message = "处方已新增并提交审核。"
|
||||
run_async(
|
||||
operation,
|
||||
on_success=lambda _result: self._mutation_success(message),
|
||||
on_success=lambda result: self._prescription_saved(result, message),
|
||||
on_error=self._mutation_error,
|
||||
on_finished=lambda: self._set_mutation_pending(False),
|
||||
)
|
||||
|
||||
def _prescription_saved(self, prescription: Any, fallback: str) -> None:
|
||||
message, kind = saved_prescription_message(prescription, fallback)
|
||||
self.banner.show_message(message, kind)
|
||||
show_toast(self, message, kind, 3600)
|
||||
if resume_saved_prescription(self.repository, prescription, self):
|
||||
self._mutation_success("医生签署已完成,等待药师审核。")
|
||||
else:
|
||||
self.refresh()
|
||||
|
||||
def _delete_selected(self) -> None:
|
||||
row = self._selected()
|
||||
@@ -2312,7 +2483,7 @@ class PrescriptionsPage(QWidget):
|
||||
row is None
|
||||
or self._mutation_pending
|
||||
or not has_permission(self.permissions, "cf.prescription/del")
|
||||
or not can_edit_or_delete(row)
|
||||
or not _can_change_issued_prescription(row)
|
||||
):
|
||||
return
|
||||
answer = QMessageBox.warning(
|
||||
@@ -2361,15 +2532,106 @@ class PrescriptionsPage(QWidget):
|
||||
on_finished=lambda: self._set_mutation_pending(False),
|
||||
)
|
||||
|
||||
def _upload_selected(self) -> None:
|
||||
row = self._selected()
|
||||
if self._mutation_pending or not self._can_upload(row):
|
||||
return
|
||||
prescription_id = _int(first_value(row, "id", "prescription_id"), 0)
|
||||
if prescription_id <= 0:
|
||||
self.banner.show_message("处方 ID 无效,请刷新列表后重试。", "warning")
|
||||
return
|
||||
state = signature_state(row)
|
||||
message = (
|
||||
"处方已上传,请点击「继续签署」。"
|
||||
if state.get("required") is True and state.get("status") != "signed"
|
||||
else "处方已上传,等待药师审核。"
|
||||
)
|
||||
self._set_mutation_pending(True)
|
||||
run_async(
|
||||
lambda: self.repository.submit_prescription_for_review(prescription_id),
|
||||
on_success=lambda _result: self._mutation_success(message),
|
||||
on_error=self._mutation_error,
|
||||
on_finished=lambda: self._set_mutation_pending(False),
|
||||
)
|
||||
|
||||
def _audit_selected(self) -> None:
|
||||
row = self._selected()
|
||||
if (
|
||||
row is None
|
||||
or not has_permission(self.permissions, "cf.prescription/audit")
|
||||
or not can_audit(row)
|
||||
):
|
||||
if self._mutation_pending or self._audit_check_pending or not _is_pending_audit(row):
|
||||
return
|
||||
can_review = has_permission(self.permissions, "cf.prescription/audit")
|
||||
local_state = signature_state(row)
|
||||
signing_action = can_continue_prescription_esign(local_state, self.permissions, row)
|
||||
if not (signing_action or (can_review and can_audit(row))):
|
||||
return
|
||||
dialog = AuditPrescriptionDialog(row, self)
|
||||
prescription_id = _int(first_value(row, "id", "prescription_id"), 0)
|
||||
if prescription_id <= 0:
|
||||
self.banner.show_message("处方 ID 无效,请刷新列表后重试。", "warning")
|
||||
return
|
||||
status_method = getattr(self.repository, "get_prescription_esign_status", None)
|
||||
if not callable(status_method):
|
||||
self.banner.show_message("无法查询处方签署状态,请联系管理员。", "warning")
|
||||
return
|
||||
|
||||
def checked(state: dict[str, Any]) -> None:
|
||||
selected = self._selected()
|
||||
if (
|
||||
self._mutation_pending
|
||||
or not _is_pending_audit(selected)
|
||||
or _int(first_value(selected, "id", "prescription_id"), 0) != prescription_id
|
||||
):
|
||||
return
|
||||
if can_continue_prescription_esign(state, self.permissions, selected):
|
||||
draft = {**_row_mapping(selected), "id": prescription_id, "esign": state}
|
||||
dialog = PrescriptionEsignDialog(self.repository, draft, parent=self)
|
||||
dialog.exec()
|
||||
if dialog.state.get("status") == "signed":
|
||||
self._mutation_success("医生签署已完成,等待药师审核。")
|
||||
return
|
||||
status = state["status"]
|
||||
eligible_status = (state["required"] and status == "signed") or (not state["required"] and status == "legacy")
|
||||
if eligible_status and can_review_uploaded_prescription(selected, state):
|
||||
if signing_action:
|
||||
if status == "signed":
|
||||
self._mutation_success("医生签署已完成,等待药师审核。")
|
||||
else:
|
||||
self.refresh()
|
||||
elif can_review:
|
||||
self._open_audit_dialog(selected, state)
|
||||
return
|
||||
if status == "voided":
|
||||
message = "处方已作废,请刷新列表。"
|
||||
elif awaiting_prescription_upload(selected, state) or review_submission_time(selected, state) == 0:
|
||||
message = "请开方医生上传处方后再审核。"
|
||||
elif _truthy(first_value(selected, "is_system_auto")):
|
||||
message = "请开方医生编辑并补全系统占号处方,再完成电子签署。"
|
||||
elif not state["enabled"]:
|
||||
message = "审核前须完成电子签署。请联系管理员启用签署服务。"
|
||||
elif status == "signing":
|
||||
message = "处方正在电子签署,请稍后再审核。"
|
||||
elif status == "uncertain":
|
||||
message = "请开方医生核对处方签署结果,确认完成后再审核。"
|
||||
elif status == "signed":
|
||||
message = "医生签署尚未通过验签,请核对签署状态后再审核。"
|
||||
else:
|
||||
message = "请开方医生完成电子签署后再审核。"
|
||||
self.banner.show_message(message, "warning")
|
||||
|
||||
def finished() -> None:
|
||||
self._audit_check_pending = False
|
||||
self._selection_changed()
|
||||
|
||||
self._audit_check_pending = True
|
||||
self._selection_changed()
|
||||
run_async(
|
||||
lambda: esign_status(status_method(prescription_id)),
|
||||
on_success=checked,
|
||||
on_error=self._mutation_error,
|
||||
on_finished=finished,
|
||||
)
|
||||
|
||||
def _open_audit_dialog(self, row: Any, state: Mapping[str, Any]) -> None:
|
||||
allow_approval = state.get("review_required") is not True or bool(review_signature_time(state))
|
||||
dialog = AuditPrescriptionDialog(row, self, allow_approval=allow_approval)
|
||||
if dialog.exec() != QDialog.DialogCode.Accepted:
|
||||
return
|
||||
payload = dialog.payload()
|
||||
|
||||
@@ -116,8 +116,8 @@ STATUS_TEXT = {1: "待接诊", 2: "已取消", 3: "已完成", 4: "已过号"}
|
||||
RECEPTION_STATUSES = {1, 4}
|
||||
NOTE_LIMIT = 500
|
||||
MAX_NOTE_MEDIA = 99
|
||||
AI_ANALYSIS_MODELS = ("qwen", "openai")
|
||||
AI_ANALYSIS_MODEL_LABELS = {"qwen": "千问", "openai": "OpenAI"}
|
||||
AI_ANALYSIS_MODELS = ("qwen", "openai", "doubao")
|
||||
AI_ANALYSIS_MODEL_LABELS = {"qwen": "千问", "openai": "OpenAI", "doubao": "豆包"}
|
||||
_ASYNC_REQUEST_CANCELLED = object()
|
||||
_ASYNC_REQUEST_DEFERRED = object()
|
||||
_AI_AUTOMATIC_GENERATION_SETTLE_SECONDS = 0.25
|
||||
@@ -2098,7 +2098,7 @@ def _analysis_value(payload: Mapping[str, Any], key: str) -> Any:
|
||||
|
||||
|
||||
def _patient_report_model(payload: Mapping[str, Any]) -> str:
|
||||
"""Return the only two model identifiers accepted by the desktop."""
|
||||
"""Return one of the model identifiers accepted by the desktop."""
|
||||
|
||||
raw = str(
|
||||
payload.get("model_key")
|
||||
@@ -2110,9 +2110,21 @@ def _patient_report_model(payload: Mapping[str, Any]) -> str:
|
||||
return "qwen"
|
||||
if raw in {"openai", "gpt"} or raw.startswith("gpt"):
|
||||
return "openai"
|
||||
if raw in {"doubao", "ark", "volcengine"} or "doubao" in raw:
|
||||
return "doubao"
|
||||
return ""
|
||||
|
||||
|
||||
def _next_ai_analysis_model(model: str) -> str | None:
|
||||
"""千问之后按顺序补齐其余模型;返回 None 表示本轮已到最后一个模型。"""
|
||||
|
||||
try:
|
||||
index = AI_ANALYSIS_MODELS.index(model)
|
||||
except ValueError:
|
||||
return None
|
||||
return AI_ANALYSIS_MODELS[index + 1] if index + 1 < len(AI_ANALYSIS_MODELS) else None
|
||||
|
||||
|
||||
def _normalize_patient_report(payload: Mapping[str, Any]) -> dict[str, Any] | None:
|
||||
"""Flatten a saved server snapshot into the existing structured card contract."""
|
||||
|
||||
@@ -2525,18 +2537,18 @@ class _ClinicalInfoPanel(QWidget):
|
||||
"""Let the clinical history use the full reading column."""
|
||||
|
||||
|
||||
class _ClinicalPageStack(QStackedWidget):
|
||||
"""Size the clinical card from its current page, including after a resize."""
|
||||
|
||||
def sizeHint(self) -> QSize: # noqa: N802 - Qt virtual
|
||||
page = self.currentWidget()
|
||||
return page.sizeHint() if page is not None else super().sizeHint()
|
||||
|
||||
def minimumSizeHint(self) -> QSize: # noqa: N802 - Qt virtual
|
||||
page = self.currentWidget()
|
||||
return page.minimumSizeHint() if page is not None else super().minimumSizeHint()
|
||||
|
||||
|
||||
class _ClinicalPageStack(QStackedWidget):
|
||||
"""Size the clinical card from its current page, including after a resize."""
|
||||
|
||||
def sizeHint(self) -> QSize: # noqa: N802 - Qt virtual
|
||||
page = self.currentWidget()
|
||||
return page.sizeHint() if page is not None else super().sizeHint()
|
||||
|
||||
def minimumSizeHint(self) -> QSize: # noqa: N802 - Qt virtual
|
||||
page = self.currentWidget()
|
||||
return page.minimumSizeHint() if page is not None else super().minimumSizeHint()
|
||||
|
||||
|
||||
class _ReceptionAiPanels(QWidget):
|
||||
"""Give both AI cards reading space before switching to a vertical layout."""
|
||||
|
||||
@@ -2554,16 +2566,16 @@ class _ReceptionAiPanels(QWidget):
|
||||
if needed > 0 and (self.minimumHeight() != needed or self.maximumHeight() != needed):
|
||||
self.setFixedHeight(needed)
|
||||
self.updateGeometry()
|
||||
|
||||
def resizeEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual
|
||||
super().resizeEvent(event)
|
||||
layout = self.layout()
|
||||
if not isinstance(layout, QBoxLayout):
|
||||
return
|
||||
stacked = self.width() < 800
|
||||
direction = QBoxLayout.Direction.TopToBottom if stacked else QBoxLayout.Direction.LeftToRight
|
||||
if layout.direction() != direction:
|
||||
layout.setDirection(direction)
|
||||
|
||||
def resizeEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual
|
||||
super().resizeEvent(event)
|
||||
layout = self.layout()
|
||||
if not isinstance(layout, QBoxLayout):
|
||||
return
|
||||
stacked = self.width() < 800
|
||||
direction = QBoxLayout.Direction.TopToBottom if stacked else QBoxLayout.Direction.LeftToRight
|
||||
if layout.direction() != direction:
|
||||
layout.setDirection(direction)
|
||||
layout.setStretch(0, 0 if stacked else 17)
|
||||
layout.setStretch(1, 0 if stacked else 23)
|
||||
self.updateGeometry()
|
||||
@@ -3193,7 +3205,7 @@ class _ReceptionAiAnalysisDialog(QDialog):
|
||||
title = QLabel("患者级 AI 诊断报告", header)
|
||||
title.setObjectName("ReceptionAiAnalysisDialogTitle")
|
||||
title.setProperty("dialogRole", "title")
|
||||
subtitle = QLabel("查看千问与 OpenAI 的历次患者报告快照", header)
|
||||
subtitle = QLabel("查看千问、OpenAI 与豆包的历次患者报告快照", header)
|
||||
subtitle.setObjectName("ReceptionAiAnalysisDialogSubtitle")
|
||||
subtitle.setProperty("dialogRole", "subtitle")
|
||||
heading.addWidget(title)
|
||||
@@ -3954,8 +3966,8 @@ class ReceptionDailyRecordsPanel(DailyRecordPanel):
|
||||
self.matrix.setAccessibleName("患者日常记录矩阵")
|
||||
self.matrix.setMinimumHeight(330)
|
||||
self.matrix.setMaximumHeight(460)
|
||||
self.matrix.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
|
||||
self._sizing_daily_columns = False
|
||||
self.matrix.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
|
||||
self._sizing_daily_columns = False
|
||||
self.matrix.viewport().installEventFilter(self)
|
||||
|
||||
for object_name in ("DiagnosisTrendCard", "DiagnosisTodoCard"):
|
||||
@@ -3964,37 +3976,37 @@ class ReceptionDailyRecordsPanel(DailyRecordPanel):
|
||||
child.hide()
|
||||
self.clear_with_message("选择患者后加载最近 7 天日常记录。")
|
||||
|
||||
def eventFilter(self, watched: Any, event: Any) -> bool: # noqa: N802 - Qt virtual
|
||||
if (
|
||||
watched is self.matrix.viewport()
|
||||
and event.type() == QEvent.Type.Resize
|
||||
and event.size().width() != event.oldSize().width()
|
||||
):
|
||||
self._fit_daily_columns()
|
||||
return super().eventFilter(watched, event)
|
||||
|
||||
def _fit_daily_columns(self) -> None:
|
||||
count = self.matrix.columnCount() - 1
|
||||
if count < 1 or self._sizing_daily_columns:
|
||||
return
|
||||
self._sizing_daily_columns = True
|
||||
try:
|
||||
header = self.matrix.horizontalHeader()
|
||||
header.setSectionResizeMode(QHeaderView.ResizeMode.Interactive)
|
||||
header.setMinimumSectionSize(96)
|
||||
available = max(0, self.matrix.viewport().width() - 132)
|
||||
width, remainder = divmod(available, count)
|
||||
widths = [max(96, width + (index < remainder)) for index in range(count)]
|
||||
changed = False
|
||||
for column, target in enumerate([132, *widths]):
|
||||
if self.matrix.columnWidth(column) != target:
|
||||
self.matrix.setColumnWidth(column, target)
|
||||
changed = True
|
||||
if changed:
|
||||
self.matrix.resizeRowsToContents()
|
||||
finally:
|
||||
self._sizing_daily_columns = False
|
||||
|
||||
def eventFilter(self, watched: Any, event: Any) -> bool: # noqa: N802 - Qt virtual
|
||||
if (
|
||||
watched is self.matrix.viewport()
|
||||
and event.type() == QEvent.Type.Resize
|
||||
and event.size().width() != event.oldSize().width()
|
||||
):
|
||||
self._fit_daily_columns()
|
||||
return super().eventFilter(watched, event)
|
||||
|
||||
def _fit_daily_columns(self) -> None:
|
||||
count = self.matrix.columnCount() - 1
|
||||
if count < 1 or self._sizing_daily_columns:
|
||||
return
|
||||
self._sizing_daily_columns = True
|
||||
try:
|
||||
header = self.matrix.horizontalHeader()
|
||||
header.setSectionResizeMode(QHeaderView.ResizeMode.Interactive)
|
||||
header.setMinimumSectionSize(96)
|
||||
available = max(0, self.matrix.viewport().width() - 132)
|
||||
width, remainder = divmod(available, count)
|
||||
widths = [max(96, width + (index < remainder)) for index in range(count)]
|
||||
changed = False
|
||||
for column, target in enumerate([132, *widths]):
|
||||
if self.matrix.columnWidth(column) != target:
|
||||
self.matrix.setColumnWidth(column, target)
|
||||
changed = True
|
||||
if changed:
|
||||
self.matrix.resizeRowsToContents()
|
||||
finally:
|
||||
self._sizing_daily_columns = False
|
||||
|
||||
def set_patient_age(self, age: Any) -> None:
|
||||
parsed = _as_int(age, None)
|
||||
self._patient_age = parsed if parsed is not None and parsed >= 0 else None
|
||||
@@ -5135,7 +5147,7 @@ class ReceptionPage(QWidget):
|
||||
self.ai_analysis_model_selector = _ReceptionAiModelCombo(analysis_card)
|
||||
self.ai_analysis_model_selector.setObjectName("ReceptionAiAnalysisModelSelector")
|
||||
self.ai_analysis_model_selector.setAccessibleName("选择卡片分析模型")
|
||||
self.ai_analysis_model_selector.setToolTip("切换千问与 OpenAI 分析")
|
||||
self.ai_analysis_model_selector.setToolTip("切换千问、OpenAI 与豆包分析")
|
||||
for model_key in AI_ANALYSIS_MODELS:
|
||||
self.ai_analysis_model_selector.addItem(
|
||||
AI_ANALYSIS_MODEL_LABELS[model_key],
|
||||
@@ -5326,13 +5338,13 @@ class ReceptionPage(QWidget):
|
||||
self.ai_analysis_history_button = QPushButton("历史报告", analysis_card)
|
||||
self.ai_analysis_history_button.setObjectName("ReceptionAiHistoryButton")
|
||||
self.ai_analysis_history_button.setAccessibleName("查看历次 AI 报告快照")
|
||||
self.ai_analysis_history_button.setToolTip("查看并切换千问与 OpenAI 历史报告")
|
||||
self.ai_analysis_history_button.setToolTip("查看并切换千问、OpenAI 与豆包历史报告")
|
||||
self.ai_analysis_history_button.clicked.connect(self._open_ai_analysis_dialog)
|
||||
report_footer.addWidget(self.ai_analysis_history_button)
|
||||
self.ai_analysis_regenerate_button = QPushButton("重新分析", analysis_card)
|
||||
self.ai_analysis_regenerate_button.setObjectName("ReceptionAiRegenerateButton")
|
||||
self.ai_analysis_regenerate_button.setAccessibleName("重新生成患者级 AI 报告")
|
||||
self.ai_analysis_regenerate_button.setToolTip("依次生成新的千问和 OpenAI 快照")
|
||||
self.ai_analysis_regenerate_button.setToolTip("依次生成新的千问、OpenAI 和豆包快照")
|
||||
self.ai_analysis_regenerate_button.clicked.connect(
|
||||
self._regenerate_patient_ai_reports
|
||||
)
|
||||
@@ -5528,10 +5540,11 @@ class ReceptionPage(QWidget):
|
||||
self._ai_analysis_active_model = "qwen"
|
||||
self._ai_analysis_model_states["qwen"] = state
|
||||
self._ai_analysis_model_messages["qwen"] = message
|
||||
self._ai_analysis_model_states["openai"] = (
|
||||
state if state in {"empty", "permission"} else "waiting"
|
||||
)
|
||||
self._ai_analysis_model_messages["openai"] = ""
|
||||
for secondary in AI_ANALYSIS_MODELS[1:]:
|
||||
self._ai_analysis_model_states[secondary] = (
|
||||
state if state in {"empty", "permission"} else "waiting"
|
||||
)
|
||||
self._ai_analysis_model_messages[secondary] = ""
|
||||
selector_index = self.ai_analysis_model_selector.findData("qwen")
|
||||
if selector_index >= 0:
|
||||
self.ai_analysis_model_selector.blockSignals(True)
|
||||
@@ -5626,15 +5639,41 @@ class ReceptionPage(QWidget):
|
||||
)
|
||||
|
||||
qwen_ready = "qwen" in self._ai_analysis_payloads
|
||||
openai_state = self._ai_analysis_model_states["openai"]
|
||||
openai_message = self._ai_analysis_model_messages["openai"]
|
||||
if qwen_ready and openai_state == "loading":
|
||||
secondary_message = "千问结果已显示,OpenAI 正在生成…"
|
||||
elif qwen_ready and openai_state == "error":
|
||||
secondary_message = f"千问结果已保留;{openai_message}"
|
||||
elif qwen_ready and openai_state == "success":
|
||||
secondary_message = "千问与 OpenAI 均已完成,可切换对照。"
|
||||
elif qwen_ready and openai_state == "unsupported":
|
||||
secondary_models = AI_ANALYSIS_MODELS[1:]
|
||||
secondary_states = [self._ai_analysis_model_states[key] for key in secondary_models]
|
||||
loading_labels = [
|
||||
AI_ANALYSIS_MODEL_LABELS[key]
|
||||
for key in secondary_models
|
||||
if self._ai_analysis_model_states[key] == "loading"
|
||||
]
|
||||
failed_messages = [
|
||||
self._ai_analysis_model_messages[key]
|
||||
for key in secondary_models
|
||||
if self._ai_analysis_model_states[key] == "error"
|
||||
]
|
||||
# 失败优先于进行中:已失败的模型不会因后续模型仍在生成而被隐藏。
|
||||
if "error" in secondary_states:
|
||||
secondary_state = "error"
|
||||
elif "loading" in secondary_states:
|
||||
secondary_state = "loading"
|
||||
elif all(item == "success" for item in secondary_states):
|
||||
secondary_state = "success"
|
||||
elif all(item == "unsupported" for item in secondary_states):
|
||||
secondary_state = "unsupported"
|
||||
else:
|
||||
secondary_state = secondary_states[0]
|
||||
if qwen_ready and secondary_state == "loading":
|
||||
secondary_message = f"千问结果已显示,{'、'.join(loading_labels)} 正在生成…"
|
||||
elif qwen_ready and secondary_state == "error":
|
||||
secondary_message = "千问结果已保留;" + ";".join(
|
||||
message for message in failed_messages if message
|
||||
) + (f";{'、'.join(loading_labels)} 正在生成…" if loading_labels else "")
|
||||
elif qwen_ready and secondary_state == "success":
|
||||
secondary_message = (
|
||||
f"{'、'.join(AI_ANALYSIS_MODEL_LABELS[key] for key in AI_ANALYSIS_MODELS)}"
|
||||
" 均已完成,可切换对照。"
|
||||
)
|
||||
elif qwen_ready and secondary_state == "unsupported":
|
||||
secondary_message = "千问结果已显示;当前数据源仅支持千问分析。"
|
||||
else:
|
||||
secondary_message = ""
|
||||
@@ -5646,7 +5685,7 @@ class ReceptionPage(QWidget):
|
||||
if success and payload is not None
|
||||
else ""
|
||||
)
|
||||
if current_snapshot_time and (openai_state == "success" or not secondary_message):
|
||||
if current_snapshot_time and (secondary_state == "success" or not secondary_message):
|
||||
secondary_message = f"快照时间:{current_snapshot_time[:16]}"
|
||||
if self._ai_analysis_regenerating:
|
||||
active_label = AI_ANALYSIS_MODEL_LABELS.get(
|
||||
@@ -5654,11 +5693,11 @@ class ReceptionPage(QWidget):
|
||||
self._ai_analysis_regeneration_model or "千问",
|
||||
)
|
||||
secondary_message = f"正在生成新的{active_label}快照,历史版本会保留。"
|
||||
openai_state = "loading"
|
||||
secondary_state = "loading"
|
||||
elif self._ai_analysis_operation_error:
|
||||
secondary_message = self._ai_analysis_operation_error
|
||||
openai_state = "error"
|
||||
self._set_ai_analysis_secondary_status(openai_state, secondary_message)
|
||||
secondary_state = "error"
|
||||
self._set_ai_analysis_secondary_status(secondary_state, secondary_message)
|
||||
|
||||
self.ai_analysis_card.setProperty("analysisState", state)
|
||||
self.ai_analysis_card.style().unpolish(self.ai_analysis_card)
|
||||
@@ -5980,12 +6019,14 @@ class ReceptionPage(QWidget):
|
||||
self._ai_analysis_payloads[model] = grouped[model][0]
|
||||
self._ai_analysis_model_states[model] = "success"
|
||||
self._ai_analysis_model_messages[model] = ""
|
||||
else:
|
||||
elif replace or self._ai_analysis_model_states.get(model) not in {"error", "loading"}:
|
||||
# 追加单个新快照时,保留其他模型尚未结束或已失败的状态与原因。
|
||||
self._ai_analysis_model_states[model] = "missing"
|
||||
self._ai_analysis_model_messages[model] = ""
|
||||
if self._ai_analysis_active_model not in self._ai_analysis_payloads:
|
||||
self._ai_analysis_active_model = (
|
||||
"qwen" if "qwen" in self._ai_analysis_payloads else "openai"
|
||||
self._ai_analysis_active_model = next(
|
||||
(key for key in AI_ANALYSIS_MODELS if key in self._ai_analysis_payloads),
|
||||
"qwen",
|
||||
)
|
||||
selector_index = self.ai_analysis_model_selector.findData(
|
||||
self._ai_analysis_active_model
|
||||
@@ -6436,9 +6477,10 @@ class ReceptionPage(QWidget):
|
||||
self._ai_analysis_model_states[model] = "success"
|
||||
self._ai_analysis_model_messages[model] = ""
|
||||
self._sync_ai_analysis_view()
|
||||
if model == "qwen":
|
||||
next_model = _next_ai_analysis_model(model)
|
||||
if next_model is not None:
|
||||
self._request_patient_ai_generation(
|
||||
"openai",
|
||||
next_model,
|
||||
effective_generation,
|
||||
effective_appointment_id,
|
||||
patient_id,
|
||||
@@ -6475,9 +6517,21 @@ class ReceptionPage(QWidget):
|
||||
else:
|
||||
self._ai_analysis_model_states[model] = "error"
|
||||
self._ai_analysis_model_messages[model] = message
|
||||
prefix = "千问新快照已保留;" if model == "openai" and "qwen" in self._ai_analysis_payloads else ""
|
||||
prefix = "千问新快照已保留;" if model != "qwen" and "qwen" in self._ai_analysis_payloads else ""
|
||||
self._ai_analysis_operation_error = f"{prefix}{message}"
|
||||
self._sync_ai_analysis_view()
|
||||
# 千问之后的某个模型失败,不阻断其余模型继续补齐;失败原因保留在该模型状态里。
|
||||
next_model = _next_ai_analysis_model(model) if model != "qwen" else None
|
||||
context = self._current_patient_ai_context(patient_id)
|
||||
if next_model is not None and context is not None:
|
||||
effective_generation, effective_appointment_id, _patient_id = context
|
||||
self._request_patient_ai_generation(
|
||||
next_model,
|
||||
effective_generation,
|
||||
effective_appointment_id,
|
||||
patient_id,
|
||||
settle_before_request=True,
|
||||
)
|
||||
|
||||
def _patient_ai_generation_finished(
|
||||
self,
|
||||
@@ -6617,7 +6671,7 @@ class ReceptionPage(QWidget):
|
||||
diagnosis_id,
|
||||
):
|
||||
return
|
||||
if model == "openai" and not self._ai_analysis_supports_models:
|
||||
if model != "qwen" and not self._ai_analysis_supports_models:
|
||||
self._ai_analysis_model_states[model] = "unsupported"
|
||||
self._ai_analysis_model_messages[model] = ""
|
||||
self._sync_ai_analysis_view()
|
||||
@@ -6764,11 +6818,12 @@ class ReceptionPage(QWidget):
|
||||
self._ai_analysis_model_messages[model] = ""
|
||||
self._sync_ai_analysis_view()
|
||||
|
||||
if model == "qwen":
|
||||
next_model = _next_ai_analysis_model(model)
|
||||
if next_model is not None:
|
||||
method = getattr(self.repository, "get_diagnosis_ai_analysis", None)
|
||||
if callable(method):
|
||||
self._request_ai_analysis_model(
|
||||
"openai",
|
||||
next_model,
|
||||
method,
|
||||
request_generation,
|
||||
appointment_id,
|
||||
@@ -6803,6 +6858,18 @@ class ReceptionPage(QWidget):
|
||||
f"{label}分析加载失败:{friendly_error(error)}"
|
||||
)
|
||||
self._sync_ai_analysis_view()
|
||||
# 与患者快照一致:千问之后的模型失败不阻断其余模型。
|
||||
next_model = _next_ai_analysis_model(model) if model != "qwen" else None
|
||||
method = getattr(self.repository, "get_diagnosis_ai_analysis", None)
|
||||
if next_model is not None and callable(method):
|
||||
self._request_ai_analysis_model(
|
||||
next_model,
|
||||
method,
|
||||
request_generation,
|
||||
appointment_id,
|
||||
diagnosis_id,
|
||||
settle_before_request=True,
|
||||
)
|
||||
|
||||
def _ai_analysis_finished(
|
||||
self,
|
||||
@@ -6869,7 +6936,7 @@ class ReceptionPage(QWidget):
|
||||
self._set_ai_analysis_state("error", "当前患者缺少诊单编号,无法重试。")
|
||||
return
|
||||
model = self._ai_analysis_active_model
|
||||
if model == "openai" and self._ai_analysis_model_states[model] == "error":
|
||||
if model != "qwen" and self._ai_analysis_model_states[model] == "error":
|
||||
method = getattr(self.repository, "get_diagnosis_ai_analysis", None)
|
||||
if callable(method):
|
||||
self._request_ai_analysis_model(
|
||||
|
||||
@@ -63,7 +63,9 @@ from .design_system import PALETTE, clinical_stylesheet
|
||||
from .dialogs.ai_consult import can_open_ai_consult
|
||||
from .dialogs.ai_consult_picker import select_and_present_ai_consult
|
||||
from .dialogs.diagnosis import DiagnosisDialog
|
||||
from .dialogs.esign_doctor import EsignDoctorDialog
|
||||
from .dialogs.local_audio_queue import LocalAudioQueueDialog
|
||||
from .dialogs.prescription_esign import can_open_esign_doctor
|
||||
from .pages import (
|
||||
AppointmentsPage,
|
||||
ConsultationsPage,
|
||||
@@ -873,6 +875,7 @@ class ShellWindow(QMainWindow):
|
||||
"""
|
||||
|
||||
logout_requested = Signal()
|
||||
close_requested = Signal()
|
||||
video_requested = Signal(dict)
|
||||
page_changed = Signal(str)
|
||||
update_check_requested = Signal()
|
||||
@@ -1421,6 +1424,8 @@ class ShellWindow(QMainWindow):
|
||||
self.menu_ai_action = user_menu.addAction("AI 助手")
|
||||
self.menu_ai_action.triggered.connect(self._open_ai_assistant)
|
||||
self.menu_ai_action.setVisible(False)
|
||||
if "1" in self._role_ids() and can_open_esign_doctor(self.repository, self.permissions):
|
||||
user_menu.addAction("医生电子签署身份", self._open_esign_doctor)
|
||||
update_action = user_menu.addAction("检查更新")
|
||||
update_action.triggered.connect(self.update_check_requested.emit)
|
||||
user_menu.addSeparator()
|
||||
@@ -1531,12 +1536,7 @@ class ShellWindow(QMainWindow):
|
||||
department = first_value(
|
||||
self.current_user, "department_name", "department.name", default=""
|
||||
)
|
||||
role_ids = (
|
||||
first_value(self.current_user, "role_ids", "role_id", default=[]) or []
|
||||
)
|
||||
if not isinstance(role_ids, (list, tuple, set, frozenset)):
|
||||
role_ids = [role_ids]
|
||||
role_values = {str(value) for value in role_ids}
|
||||
role_values = self._role_ids()
|
||||
role = (
|
||||
"医生"
|
||||
if "1" in role_values
|
||||
@@ -1546,6 +1546,12 @@ class ShellWindow(QMainWindow):
|
||||
)
|
||||
return f"{department} · {role}" if department else role
|
||||
|
||||
def _role_ids(self) -> set[str]:
|
||||
role_ids = first_value(self.current_user, "role_ids", "role_id", default=[]) or []
|
||||
if not isinstance(role_ids, (list, tuple, set, frozenset)):
|
||||
role_ids = [role_ids]
|
||||
return {str(value) for value in role_ids}
|
||||
|
||||
def toggle_sidebar(self) -> None:
|
||||
"""Toggle the admin-style compact menu while preserving the page state."""
|
||||
|
||||
@@ -1860,6 +1866,11 @@ class ShellWindow(QMainWindow):
|
||||
initial_query=self.global_search.text().strip(),
|
||||
)
|
||||
|
||||
def _open_esign_doctor(self) -> None:
|
||||
dialog = EsignDoctorDialog(self.repository, parent=self)
|
||||
dialog.exec()
|
||||
dialog.deleteLater()
|
||||
|
||||
def _open_local_audio_settings(self) -> None:
|
||||
current = self._local_audio_settings_dialog
|
||||
if current is not None and current.isVisible():
|
||||
@@ -2227,6 +2238,8 @@ class ShellWindow(QMainWindow):
|
||||
def closeEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual
|
||||
self.chat_notifications.stop()
|
||||
super().closeEvent(event)
|
||||
if event.isAccepted():
|
||||
self.close_requested.emit()
|
||||
|
||||
def _open_chat_notification(self, notification: ChatNotification) -> None:
|
||||
"""Take the doctor where the notification's work actually lives."""
|
||||
|
||||
@@ -381,9 +381,21 @@ def run_async(
|
||||
|
||||
worker = Worker(function, *args, **kwargs)
|
||||
_RUNNING_WORKERS.add(worker)
|
||||
session_handler = _AUTHENTICATION_EXPIRED_HANDLER
|
||||
|
||||
def dispatch_error(error: Exception, _traceback: str) -> None:
|
||||
# An earlier session's in-flight failure cannot dismiss a newly
|
||||
# authenticated shell or open an error dialog over its login window.
|
||||
if (
|
||||
isinstance(error, AuthenticationExpiredError)
|
||||
and session_handler is not _AUTHENTICATION_EXPIRED_HANDLER
|
||||
):
|
||||
return
|
||||
_dispatch_async_error(error, on_error)
|
||||
|
||||
if on_success is not None:
|
||||
worker.signals.result.connect(on_success)
|
||||
worker.signals.error.connect(lambda exc, _tb: _dispatch_async_error(exc, on_error))
|
||||
worker.signals.error.connect(dispatch_error)
|
||||
if on_finished is not None:
|
||||
worker.signals.finished.connect(on_finished)
|
||||
worker.signals.finished.connect(lambda: _RUNNING_WORKERS.discard(worker))
|
||||
|
||||
@@ -21,6 +21,8 @@ SYNC_TIMEOUT_SECONDS = 45.0
|
||||
_WORKER_SLOTS = BoundedSemaphore(4)
|
||||
_CANCEL_SLOTS = BoundedSemaphore(4)
|
||||
_ACTIONS = frozenset({"summary", "followup", "reply"})
|
||||
# 千问是服务端各任务的默认模型;医生在面板中切换后才显式携带。
|
||||
_MODELS = frozenset({"qwen", "openai", "doubao"})
|
||||
|
||||
|
||||
def _integer(value: Any, *, minimum: int) -> int | None:
|
||||
@@ -104,6 +106,7 @@ class _RequestError(Exception):
|
||||
class _Job:
|
||||
identity: dict[str, Any]
|
||||
action: str
|
||||
model: str | None = None
|
||||
cancelled: Event = field(default_factory=Event)
|
||||
completed: bool = False
|
||||
succeeded: bool = False
|
||||
@@ -193,8 +196,11 @@ class ImAiController:
|
||||
return True
|
||||
if event != "im-ai-request" or message["requestId"] in self._seen:
|
||||
return False
|
||||
model = message.get("model")
|
||||
if model is not None and (not isinstance(model, str) or model not in _MODELS):
|
||||
return False
|
||||
self._seen.append(message["requestId"])
|
||||
job = _Job(identity, message["action"])
|
||||
job = _Job(identity, message["action"], model)
|
||||
if self._running is not None:
|
||||
self._cancel(self._running)
|
||||
self._current = job
|
||||
@@ -269,6 +275,7 @@ class ImAiController:
|
||||
events = self.repository.stream_diagnosis_ai(
|
||||
self.diagnosis_id, prompt, task=task,
|
||||
request_id=job.identity["requestId"], cancelled=job.cancelled.is_set,
|
||||
**({"model": job.model} if job.model not in (None, "qwen") else {}),
|
||||
)
|
||||
try:
|
||||
for event in events:
|
||||
|
||||
@@ -20,7 +20,7 @@ from ..core.transcript_text import simplified_transcript
|
||||
|
||||
MAX_IMAGE_BYTES = 10 * 1024 * 1024
|
||||
_SLOTS = BoundedSemaphore(4)
|
||||
_MODELS = {"qwen", "openai"}
|
||||
_MODELS = {"qwen", "openai", "doubao"}
|
||||
_BUSINESS_MESSAGES = {
|
||||
"GPT 模型接口配置异常,请管理员检查 Dify 中的模型 API 地址。": "GPT 模型接口配置异常,请管理员检查 Dify 中的模型 API 地址。",
|
||||
"千问 模型接口配置异常,请管理员检查 Dify 中的模型 API 地址。": "千问 模型接口配置异常,请管理员检查 Dify 中的模型 API 地址。",
|
||||
|
||||
@@ -255,7 +255,7 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
def analyzeTongueScreenshotModel(self, request_id: str, data_url: str, model: str) -> None: # noqa: N802
|
||||
if (not isinstance(request_id, str) or len(request_id) != 36
|
||||
or not isinstance(data_url, str) or len(data_url) > 14 * 1024 * 1024
|
||||
or not isinstance(model, str) or model not in {"qwen", "openai"}):
|
||||
or not isinstance(model, str) or model not in {"qwen", "openai", "doubao"}):
|
||||
return
|
||||
self._callback({"source": "doctor-call", "event": "tongue-screenshot-analyze",
|
||||
"requestId": request_id, "dataUrl": data_url, "model": model})
|
||||
@@ -347,7 +347,7 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
call_error = Signal(str) # type: ignore[misc]
|
||||
_start_completed = Signal(bool) # type: ignore[misc]
|
||||
_policy_completed = Signal(str, object) # type: ignore[misc]
|
||||
_room_completed = Signal(str, bool, str) # type: ignore[misc]
|
||||
_room_completed = Signal(object, str, bool, str) # type: ignore[misc]
|
||||
_screenshot_completed = Signal(bool, str) # type: ignore[misc]
|
||||
_transcription_completed = Signal(str, str, str, bool, str, str) # type: ignore[misc]
|
||||
_local_transcription_event = Signal(object) # type: ignore[misc]
|
||||
@@ -723,12 +723,14 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
)
|
||||
return
|
||||
room_id = message.get("roomId", message.get("room_id"))
|
||||
if room_id not in (None, ""):
|
||||
if (room_id not in (None, "") and self._start_requested
|
||||
and not self._call_cycle_closed and not self._shutdown_requested):
|
||||
clean_room_id = str(room_id).strip()
|
||||
future = self.lifecycle.bind_room(clean_room_id)
|
||||
lifecycle = self.lifecycle
|
||||
future = lifecycle.bind_room(clean_room_id)
|
||||
future.add_done_callback(
|
||||
lambda completed, current_room_id=clean_room_id: (
|
||||
self._notify_room_completed(current_room_id, completed)
|
||||
lambda completed, current_lifecycle=lifecycle, current_room_id=clean_room_id: (
|
||||
self._notify_room_completed(current_lifecycle, current_room_id, completed)
|
||||
)
|
||||
)
|
||||
if event == "room":
|
||||
@@ -911,7 +913,12 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
extra={"video_call": self.request.safe_log_context()},
|
||||
)
|
||||
|
||||
def _notify_room_completed(self, room_id: str, future: Future[bool]) -> None:
|
||||
def _notify_room_completed(
|
||||
self,
|
||||
lifecycle: OrderedCallLifecycle,
|
||||
room_id: str,
|
||||
future: Future[bool],
|
||||
) -> None:
|
||||
try:
|
||||
succeeded = bool(future.result())
|
||||
except Exception as error:
|
||||
@@ -924,15 +931,20 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
else "通话房间尚未绑定,云端视频和本机录音无法关联通话记录。"
|
||||
)
|
||||
with suppress(RuntimeError):
|
||||
self._room_completed.emit(room_id, succeeded, message)
|
||||
self._room_completed.emit(lifecycle, room_id, succeeded, message)
|
||||
|
||||
def _on_room_completed(
|
||||
self,
|
||||
lifecycle: OrderedCallLifecycle,
|
||||
room_id: str,
|
||||
succeeded: bool,
|
||||
message: str,
|
||||
) -> None:
|
||||
if self._closing:
|
||||
# A worker may finish before redial, but its queued Qt signal can
|
||||
# arrive afterwards. Compare call identity on the UI thread.
|
||||
if (self._closing or self._released or self._shutdown_requested
|
||||
or lifecycle is not self.lifecycle or not self._start_requested
|
||||
or self._call_cycle_closed):
|
||||
return
|
||||
room_payload = json.dumps(str(room_id)[:160], ensure_ascii=True)
|
||||
payload = json.dumps(str(message)[:200], ensure_ascii=True)
|
||||
|
||||
@@ -367,14 +367,31 @@ def test_prescription_action_with_write_permission_but_without_ai_grant_is_block
|
||||
dialog.close()
|
||||
|
||||
|
||||
def test_prescription_action_opens_editor_and_forces_current_diagnosis_ownership(
|
||||
@pytest.mark.parametrize("esign_enabled", [False, True])
|
||||
def test_prescription_action_opens_upload_once_with_current_diagnosis_ownership(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
esign_enabled: bool,
|
||||
) -> None:
|
||||
created: list[dict[str, Any]] = []
|
||||
editor_seeds: list[dict[str, Any]] = []
|
||||
upload_receipts: list[dict[str, Any]] = []
|
||||
current_user = {"id": 12, "name": "甄医生"}
|
||||
receipt = {
|
||||
"id": 9001,
|
||||
"esign": {
|
||||
"enabled": esign_enabled,
|
||||
"required": esign_enabled,
|
||||
"environment": "sandbox",
|
||||
"status": "pending" if esign_enabled else "legacy",
|
||||
"can_sign": False,
|
||||
"can_download": False,
|
||||
"review_submitted_at": 0,
|
||||
"awaiting_upload": True,
|
||||
"can_submit_for_review": True,
|
||||
},
|
||||
}
|
||||
|
||||
class Repository:
|
||||
def get_diagnosis_detail(
|
||||
@@ -419,7 +436,10 @@ def test_prescription_action_opens_editor_and_forces_current_diagnosis_ownership
|
||||
|
||||
def create_prescription(self, prescription: dict[str, Any]) -> dict[str, Any]:
|
||||
created.append(prescription)
|
||||
return {"id": 9001, **prescription}
|
||||
return receipt
|
||||
|
||||
def submit_prescription_for_review(self, prescription_id: int) -> None:
|
||||
raise AssertionError(f"uploading {prescription_id} requires a separate click")
|
||||
|
||||
def list_prescriptions_by_diagnosis(
|
||||
self,
|
||||
@@ -427,10 +447,6 @@ def test_prescription_action_opens_editor_and_forces_current_diagnosis_ownership
|
||||
) -> list[dict[str, Any]]:
|
||||
return [{"id": 9001, "diagnosis_id": diagnosis_id, "sn": "RX-9001"}]
|
||||
|
||||
class FakeSignal:
|
||||
def connect(self, _slot: Any) -> None:
|
||||
return None
|
||||
|
||||
class FakeEditor:
|
||||
def __init__(
|
||||
self,
|
||||
@@ -441,9 +457,12 @@ def test_prescription_action_opens_editor_and_forces_current_diagnosis_ownership
|
||||
editor_seeds.append(seed)
|
||||
assert kwargs["mode"] == "add"
|
||||
assert kwargs["current_user"] == current_user
|
||||
self.diagnosis_requested = FakeSignal()
|
||||
self.save_draft = kwargs["save_draft"]
|
||||
self.saved_draft = None
|
||||
|
||||
def exec(self) -> Any:
|
||||
if esign_enabled:
|
||||
self.saved_draft = self.save_draft(self.payload())
|
||||
return ai_consult_module.QDialog.DialogCode.Accepted
|
||||
|
||||
@staticmethod
|
||||
@@ -452,17 +471,32 @@ def test_prescription_action_opens_editor_and_forces_current_diagnosis_ownership
|
||||
"diagnosis_id": 999,
|
||||
"appointment_id": 998,
|
||||
"case_record": {"forged": True},
|
||||
"patient_id": 997,
|
||||
"phone": "13900000000",
|
||||
"doctor_name": "甄医生",
|
||||
"herbs": [{"name": "茯苓", "dosage": 10, "unit": "g"}],
|
||||
}
|
||||
|
||||
from doctor_workstation.ui.dialogs import prescription as prescription_module
|
||||
class FakeUploadDialog:
|
||||
def __init__(self, _repository: Any, prescription: dict[str, Any], **_kwargs: Any) -> None:
|
||||
assert prescription is receipt
|
||||
self.state = prescription["esign"]
|
||||
upload_receipts.append(prescription)
|
||||
|
||||
def exec(self) -> None:
|
||||
return None
|
||||
|
||||
from doctor_workstation.ui.dialogs import (
|
||||
prescription as prescription_module,
|
||||
prescription_esign as prescription_esign_module,
|
||||
)
|
||||
|
||||
monkeypatch.setattr(
|
||||
prescription_module,
|
||||
"PrescriptionEditorDialog",
|
||||
FakeEditor,
|
||||
)
|
||||
monkeypatch.setattr(prescription_esign_module, "PrescriptionEsignDialog", FakeUploadDialog)
|
||||
host = QWidget()
|
||||
host.current_user = current_user # type: ignore[attr-defined]
|
||||
dialog = AiConsultDialog(
|
||||
@@ -484,7 +518,9 @@ def test_prescription_action_opens_editor_and_forces_current_diagnosis_ownership
|
||||
assert editor_seeds[0]["diagnosis_id"] == 501
|
||||
assert editor_seeds[0]["appointment_id"] == 801
|
||||
assert editor_seeds[0]["herbs"][0]["name"] == "茯苓"
|
||||
assert created and created[0]["diagnosis_id"] == 501
|
||||
assert len(created) == 1
|
||||
assert upload_receipts == [receipt]
|
||||
assert created[0]["diagnosis_id"] == 501
|
||||
assert created[0]["appointment_id"] == 801
|
||||
assert created[0]["case_record"] == {"chief_complaint": "性功能下降"}
|
||||
assert created[0]["patient_id"] == 301
|
||||
@@ -495,7 +531,7 @@ def test_prescription_action_opens_editor_and_forces_current_diagnosis_ownership
|
||||
browser.toPlainText()
|
||||
for browser in dialog.findChildren(QTextBrowser, "AiConsultBubbleText")
|
||||
]
|
||||
assert any("处方已开具并提交审核" in body for body in bodies)
|
||||
assert any("处方草稿已保存" in body and "上传处方" in body for body in bodies)
|
||||
dialog.close()
|
||||
host.close()
|
||||
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
"""Exercise persisted cloud captions across redials using the real lifecycle worker."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from itertools import count
|
||||
from queue import Queue
|
||||
from threading import Event
|
||||
from types import MethodType
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
from test_cloud_transcription_bridge import (
|
||||
SIMPLIFIED,
|
||||
TIMESTAMP,
|
||||
host,
|
||||
segment_message,
|
||||
transcription_result,
|
||||
)
|
||||
|
||||
from doctor_workstation.video import window
|
||||
from doctor_workstation.video.launcher import VideoCallRequest
|
||||
from doctor_workstation.video.lifecycle import OrderedCallLifecycle
|
||||
|
||||
pytestmark = pytest.mark.skipif(not window.WEBENGINE_AVAILABLE, reason="optional QtWebEngine")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cycle_host():
|
||||
record_ids = count(701)
|
||||
repository = Mock()
|
||||
repository.start_call.side_effect = lambda **_payload: {"call_record_id": next(record_ids)}
|
||||
repository.start_call_transcription.return_value = True
|
||||
repository.upsert_call_transcript_segments.return_value = True
|
||||
repository.finish_call_transcription.return_value = True
|
||||
request = VideoCallRequest(
|
||||
sdk_app_id=1400123456, user_id="doctor_test", user_sig="test-ticket",
|
||||
target_user_id="patient_test", diagnosis_id=123, patient_id=8,
|
||||
)
|
||||
item = host(
|
||||
request=request, repository=repository, _start_requested=False,
|
||||
open_im=True, call_ended=Mock(), _start_completed=Mock(),
|
||||
start_acks=Queue(), transcription_acks=Queue(), release_storage=Event(),
|
||||
)
|
||||
item._lifecycle_factory = lambda: OrderedCallLifecycle(
|
||||
request, repository, logging.getLogger(__name__),
|
||||
)
|
||||
item.lifecycle = item._lifecycle_factory()
|
||||
item._lifecycles = [item.lifecycle]
|
||||
for name in (
|
||||
"_prepare_call_cycle", "_start_call_cycle", "_notify_start_completed",
|
||||
"_on_lifecycle_started",
|
||||
):
|
||||
setattr(item, name, MethodType(getattr(window._EmbeddedVideoWindow, name), item))
|
||||
# A worker may complete while its Qt signal remains queued for the UI thread.
|
||||
item._start_completed.emit.side_effect = lambda *args: item.start_acks.put(args)
|
||||
item._transcription_completed.emit.side_effect = lambda *args: item.transcription_acks.put(args)
|
||||
try:
|
||||
yield item
|
||||
finally:
|
||||
item.release_storage.set()
|
||||
for lifecycle in item._lifecycles:
|
||||
lifecycle.end("test-cleanup").result(timeout=2)
|
||||
assert lifecycle.wait(2)
|
||||
|
||||
|
||||
def start_cycle(item, session_id):
|
||||
item._handle_bridge_message({"event": "call-start-request"})
|
||||
acknowledgement = item.start_acks.get(timeout=2)
|
||||
assert acknowledgement == (True,)
|
||||
item._on_lifecycle_started(*acknowledgement)
|
||||
item._handle_bridge_message({
|
||||
"event": "transcription-start-request", "sessionId": session_id,
|
||||
})
|
||||
acknowledgement = item.transcription_acks.get(timeout=2)
|
||||
assert acknowledgement[:4] == ("start", session_id, "", True)
|
||||
item._on_transcription_completed(*acknowledgement)
|
||||
item._live_ai.bind.assert_called_with(item.lifecycle.call_record_id, session_id)
|
||||
item._page.runJavaScript.reset_mock()
|
||||
item._live_ai.reset_mock()
|
||||
return item.lifecycle
|
||||
|
||||
|
||||
def assert_caption_ack(item, session_id, acknowledgement):
|
||||
assert acknowledgement[:4] == ("segment", session_id, "cloud-segment-1", True)
|
||||
item._on_transcription_completed(*acknowledgement)
|
||||
assert transcription_result(item) == [
|
||||
"segment", session_id, "cloud-segment-1", True, "",
|
||||
{"segmentId": "cloud-segment-1", "speakerUserId": "patient_test",
|
||||
"sourceText": SIMPLIFIED, "timestamp": TIMESTAMP, "isCompleted": True},
|
||||
]
|
||||
item._live_ai.changed.assert_called_once_with(session_id)
|
||||
|
||||
|
||||
def test_three_calls_save_reused_segment_id_and_ack_simplified_captions(cycle_host):
|
||||
item = cycle_host
|
||||
for record_id, session_id in ((701, "tr-first"), (702, "tr-second"), (703, "tr-third")):
|
||||
lifecycle = start_cycle(item, session_id)
|
||||
assert lifecycle.call_record_id == record_id
|
||||
item._handle_bridge_message(segment_message(sessionId=session_id))
|
||||
acknowledgement = item.transcription_acks.get(timeout=2)
|
||||
# Saving on the worker must finish before normalized text reaches the page.
|
||||
item._page.runJavaScript.assert_not_called()
|
||||
item._live_ai.changed.assert_not_called()
|
||||
saved = item.repository.upsert_call_transcript_segments.call_args.kwargs
|
||||
assert (saved["call_record_id"], saved["transcription_session_id"]) == (record_id, session_id)
|
||||
assert saved["segments"][0]["text"] == SIMPLIFIED
|
||||
assert saved["segments"][0]["segment_id"] == "cloud-segment-1"
|
||||
assert_caption_ack(item, session_id, acknowledgement)
|
||||
|
||||
item._handle_bridge_message({"event": "transcription-stop", "sessionId": session_id})
|
||||
acknowledgement = item.transcription_acks.get(timeout=2)
|
||||
assert acknowledgement[:4] == ("stop", session_id, "", True)
|
||||
item._on_transcription_completed(*acknowledgement)
|
||||
item._handle_bridge_message({"event": "hangup"})
|
||||
assert lifecycle.wait(2)
|
||||
|
||||
assert len({id(lifecycle) for lifecycle in item._lifecycles}) == 3
|
||||
assert item.repository.upsert_call_transcript_segments.call_count == 3
|
||||
assert [call.kwargs["call_record_id"] for call in item.repository.end_call.call_args_list] == [701, 702, 703]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("worker_finishes_before_redial", [False, True])
|
||||
@pytest.mark.parametrize("storage_succeeds", [False, True])
|
||||
def test_old_segment_ack_keeps_old_session_and_cannot_dirty_redial(
|
||||
cycle_host, worker_finishes_before_redial, storage_succeeds,
|
||||
):
|
||||
item = cycle_host
|
||||
entered = Event()
|
||||
|
||||
def save_segment(**payload):
|
||||
if payload["call_record_id"] == 701:
|
||||
entered.set()
|
||||
if not worker_finishes_before_redial:
|
||||
assert item.release_storage.wait(5), "test did not release the old write"
|
||||
if not storage_succeeds:
|
||||
raise RuntimeError("old call storage failure")
|
||||
return True
|
||||
|
||||
item.repository.upsert_call_transcript_segments.side_effect = save_segment
|
||||
previous = start_cycle(item, "tr-old")
|
||||
item._handle_bridge_message(segment_message(sessionId="tr-old"))
|
||||
assert entered.wait(2)
|
||||
if worker_finishes_before_redial:
|
||||
old_ack = item.transcription_acks.get(timeout=2)
|
||||
|
||||
item._handle_bridge_message({"event": "hangup"})
|
||||
current = start_cycle(item, "tr-current")
|
||||
assert current is not previous
|
||||
if not worker_finishes_before_redial:
|
||||
item.release_storage.set()
|
||||
old_ack = item.transcription_acks.get(timeout=2)
|
||||
assert old_ack[:4] == ("segment", "tr-old", "cloud-segment-1", storage_succeeds)
|
||||
|
||||
item._on_transcription_completed(*old_ack)
|
||||
# The companion filters ACKs by this session; the host must never retag them.
|
||||
assert transcription_result(item)[:4] == ["segment", "tr-old", "cloud-segment-1", storage_succeeds]
|
||||
assert item.lifecycle is current
|
||||
assert current.transcription_session_id == "tr-current"
|
||||
assert not item._asr_partial
|
||||
assert item._live_ai.mock_calls == []
|
||||
|
||||
item._handle_bridge_message(segment_message(sessionId="tr-current"))
|
||||
assert_caption_ack(item, "tr-current", item.transcription_acks.get(timeout=2))
|
||||
saved = item.repository.upsert_call_transcript_segments.call_args.kwargs
|
||||
assert (saved["call_record_id"], saved["transcription_session_id"]) == (702, "tr-current")
|
||||
@@ -183,7 +183,7 @@ def test_nested_appointments_confirmation_and_prescription_labels() -> None:
|
||||
)
|
||||
assert (
|
||||
prescription_action_label({"prescription_audit_status": 1, "prescription_void_status": 1})
|
||||
== "编辑处方"
|
||||
== "重新开方"
|
||||
)
|
||||
assert (
|
||||
prescription_action_label(
|
||||
@@ -672,6 +672,119 @@ def test_existing_pending_prescription_is_edited_in_place_not_duplicated(
|
||||
application.processEvents()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("other_appointment", [False, True])
|
||||
def test_stale_consultation_actions_use_verified_current_prescription(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
other_appointment: bool,
|
||||
) -> None:
|
||||
listed = _row(current_has_prescription=1, current_prescription_id=701, prescription_audit_status=0)
|
||||
current = {
|
||||
"id": 702, "sn": "RX-702", "appointment_id": 102 if other_appointment else 101,
|
||||
"diagnosis_id": 501, "audit_status": 0, "void_status": 0, "can_void": True,
|
||||
}
|
||||
updated: list[int] = []
|
||||
prompted: list[tuple[int, bool]] = []
|
||||
operations: list[int] = []
|
||||
|
||||
def confirm(_parent: QWidget, prescription: dict[str, Any], *, current_changed: bool) -> bool:
|
||||
prompted.append((prescription["id"], current_changed))
|
||||
return False
|
||||
|
||||
repository = SimpleNamespace(
|
||||
get_prescription_by_appointment=lambda appointment_id: current,
|
||||
void_prescription=lambda prescription_id: operations.append(prescription_id),
|
||||
)
|
||||
page = ConsultationsPage(repository, permissions=PermissionSet(["*"]))
|
||||
page.table_host.set_rows([listed])
|
||||
monkeypatch.setattr(page, "refresh", lambda **_kwargs: None)
|
||||
monkeypatch.setattr(page, "_open_existing_prescription_editor", lambda prescription: updated.append(prescription["id"]))
|
||||
monkeypatch.setattr(consultations_module, "confirm_prescription_void", confirm)
|
||||
|
||||
page._row_action("prescription", listed)
|
||||
page._row_action("void_prescription", listed)
|
||||
|
||||
assert not operations
|
||||
if other_appointment:
|
||||
assert not updated and not prompted
|
||||
assert "与当前挂号不一致" in page.banner.label.text()
|
||||
else:
|
||||
assert updated == [702]
|
||||
assert prompted == [(702, True)]
|
||||
page.close()
|
||||
|
||||
|
||||
def test_more_menu_voids_current_prescription_then_reissues_and_resumes_signing(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
original = {
|
||||
"id": 901, "sn": "RX-901", "creator_id": 7, "diagnosis_id": 501,
|
||||
"appointment_id": 202, "audit_status": 0, "void_status": 0, "can_void": True,
|
||||
"patient_name": "虚构测试", "doctor_signature": "archived",
|
||||
"herbs": [{"name": "黄芪", "dosage": 15}],
|
||||
}
|
||||
created: list[dict[str, Any]] = []
|
||||
resumed: list[int] = []
|
||||
voided: list[int] = []
|
||||
|
||||
def current_row() -> dict[str, Any]:
|
||||
return _row(appointment_id=202, current_has_prescription=1,
|
||||
current_prescription_id=901, prescription_audit_status=0,
|
||||
prescription_void_status=original["void_status"])
|
||||
|
||||
class Repository:
|
||||
def get_prescription_by_appointment(self, appointment_id: int) -> dict[str, Any]:
|
||||
assert appointment_id == 202
|
||||
return dict(original)
|
||||
|
||||
def void_prescription(self, prescription_id: int) -> dict[str, Any]:
|
||||
voided.append(prescription_id)
|
||||
original.update(void_status=1, can_void=False, can_restore_rejected=False)
|
||||
return {"id": prescription_id}
|
||||
|
||||
def list_consultations(self, **_kwargs: Any) -> dict[str, Any]:
|
||||
return {"lists": [current_row()], "count": 1}
|
||||
|
||||
def create_prescription(self, prescription: dict[str, Any]) -> dict[str, Any]:
|
||||
created.append(dict(prescription))
|
||||
return {"id": 902}
|
||||
|
||||
class ReissueEditor:
|
||||
def __init__(self, _repository: Any, seed: Any, **kwargs: Any) -> None:
|
||||
assert kwargs["mode"] == "add"
|
||||
assert not {"id", "sn", "doctor_signature", "void_status", "esign"} & seed.keys()
|
||||
self.saved_draft = kwargs["save_draft"](seed)
|
||||
|
||||
def exec(self) -> QDialog.DialogCode:
|
||||
return QDialog.DialogCode.Accepted
|
||||
|
||||
monkeypatch.setattr(consultations_module, "confirm_prescription_void", lambda *_args, **_kwargs: True)
|
||||
monkeypatch.setattr(consultations_module, "PrescriptionEditorDialog", ReissueEditor)
|
||||
monkeypatch.setattr(consultations_module, "resume_saved_prescription",
|
||||
lambda _repository, saved, _parent: resumed.append(saved["id"]))
|
||||
page = ConsultationsPage(Repository(), permissions=PermissionSet(["*"]),
|
||||
current_user=SimpleNamespace(id=7, name="测试医生"))
|
||||
page.table_host.set_rows([current_row()])
|
||||
|
||||
def more_actions() -> dict[str, Any]:
|
||||
widget = page.table_host._action_widget(current_row(), 0)
|
||||
more = widget.findChild(QToolButton, "DiagnosisRowMore")
|
||||
return {action.text(): action for action in more.menu().actions()}
|
||||
|
||||
more_actions()["作废处方"].trigger()
|
||||
assert voided == [901] and original["doctor_signature"] == "archived"
|
||||
actions = more_actions()
|
||||
assert "作废处方" not in actions and "重新开方" in actions
|
||||
actions["重新开方"].trigger()
|
||||
assert len(created) == 1 and created[0]["appointment_id"] == 202
|
||||
assert created[0]["herbs"] == original["herbs"]
|
||||
assert resumed == [902]
|
||||
page.close()
|
||||
|
||||
|
||||
def test_switching_rows_invalidates_prescription_worker_and_clears_busy(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
|
||||
@@ -143,3 +143,24 @@ def test_ai_report_columns_keep_headings_at_the_same_text_baseline(
|
||||
assert abs(centers[0] - centers[1]) <= 1
|
||||
finally:
|
||||
dialog.close()
|
||||
|
||||
|
||||
def test_prescription_form_edits_phone_and_id_card(application: QApplication) -> None:
|
||||
editor = PrescriptionEditorDialog(
|
||||
SimpleNamespace(list_medicines=lambda **kwargs: {"lists": [], "count": 0}),
|
||||
{"id": 77, "diagnosis_id": 501, "patient_name": "林晓岚", "phone": "13800000000",
|
||||
"patient_id_card": "11010119800101123X", "prescription_type": "浓缩水丸"},
|
||||
)
|
||||
try:
|
||||
# 已开处方编辑时手机号、身份证号可见可改(姓名仍只读),保存时随处方提交。
|
||||
assert editor.phone.text() == "13800000000" and editor.id_card.text() == "11010119800101123X"
|
||||
assert not editor.phone.isReadOnly() and not editor.id_card.isReadOnly()
|
||||
editor.phone.setText(" 13900000001 ")
|
||||
editor.id_card.setText("110101200001011234")
|
||||
payload = editor.payload()
|
||||
assert payload["phone"] == "13900000001" and payload["id_card"] == "110101200001011234"
|
||||
editor.id_card.setText("12345")
|
||||
assert editor.payload()["id_card"] == "12345"
|
||||
finally:
|
||||
editor.close()
|
||||
editor.deleteLater()
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
"""Opt-in Windows native WebEngine lifecycle regression; never load provider pages.
|
||||
|
||||
Run outside a process-restricted sandbox with ESIGN_NATIVE_QT_TEST=1 and
|
||||
QT_QPA_PLATFORM=windows. Ordinary headless test runs skip this module.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from PySide6.QtCore import QElapsedTimer
|
||||
from PySide6.QtTest import QTest
|
||||
from PySide6.QtWidgets import QApplication
|
||||
|
||||
from doctor_workstation.ui.dialogs import prescription_esign as module
|
||||
from doctor_workstation.ui.dialogs.esign_webview import EmbeddedIdentityView
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
sys.platform != "win32" or os.getenv("ESIGN_NATIVE_QT_TEST") != "1",
|
||||
reason="opt-in native Windows Qt process test",
|
||||
)
|
||||
|
||||
|
||||
def status(value: str = "pending") -> dict[str, Any]:
|
||||
return dict(enabled=True, required=True, environment="sandbox", status=value,
|
||||
can_sign=True, can_download=False, auth_url="https://smlt.esign.cn/no-request")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("hide_before_ready", [False, True])
|
||||
def test_real_webengine_initialization_and_user_hide(
|
||||
monkeypatch: pytest.MonkeyPatch, hide_before_ready: bool
|
||||
) -> None:
|
||||
app = QApplication.instance() or QApplication([])
|
||||
calls: list[str] = []
|
||||
loaded_urls: list[str] = []
|
||||
queued: list[dict[str, Any]] = []
|
||||
|
||||
class Repository:
|
||||
def get_prescription_esign_status(self, prescription_id: int) -> dict[str, Any]:
|
||||
calls.append("status")
|
||||
return status()
|
||||
|
||||
def dispatch(function: Any, **callbacks: Any) -> None:
|
||||
if not calls:
|
||||
callbacks["on_success"](function())
|
||||
callbacks["on_finished"]()
|
||||
else:
|
||||
queued.append(callbacks)
|
||||
|
||||
monkeypatch.setattr(module, "run_async", dispatch)
|
||||
monkeypatch.setattr(EmbeddedIdentityView, "load_authentication", lambda self, url: loaded_urls.append(url))
|
||||
dialog = module.PrescriptionEsignDialog(Repository(), {"id": 7})
|
||||
dialog.show()
|
||||
QTest.qWait(100)
|
||||
original_id = int(dialog.winId())
|
||||
generation = dialog._generation
|
||||
dialog.start_button.click()
|
||||
assert len(queued) == 1 and dialog.identity_view is None
|
||||
queued[0]["on_success"](status("authenticating"))
|
||||
queued[0]["on_finished"]()
|
||||
assert len(queued) == 2 and dialog.identity_view is None
|
||||
queued[1]["on_success"]({**status("authenticating"), "identity_status": "ING", "can_complete": False})
|
||||
if hide_before_ready:
|
||||
dialog.hide()
|
||||
queued[1]["on_finished"]()
|
||||
timer = QElapsedTimer()
|
||||
timer.start()
|
||||
while timer.elapsed() < 8000:
|
||||
QTest.qWait(20)
|
||||
if hide_before_ready:
|
||||
if not dialog._native_hide_pending:
|
||||
break
|
||||
elif int(dialog.winId()) != original_id and not dialog._native_hide_pending:
|
||||
break
|
||||
assert len(queued) == 2
|
||||
QTest.qWait(100)
|
||||
if hide_before_ready:
|
||||
assert not dialog.isVisible()
|
||||
assert dialog.identity_view is None
|
||||
assert not dialog.poll_timer.isActive()
|
||||
else:
|
||||
assert int(dialog.winId()) != original_id, "native recreation must actually be exercised"
|
||||
assert dialog._generation == generation
|
||||
assert dialog.isVisible() and dialog.state["status"] == "authenticating"
|
||||
assert loaded_urls == ["https://smlt.esign.cn/no-request"]
|
||||
assert dialog.identity_view is not None and dialog.poll_timer.isActive()
|
||||
dialog.poll_timer.timeout.emit()
|
||||
assert len(queued) == 3
|
||||
queued[2]["on_success"]({**status("authenticating"), "identity_status": "SUCCESS", "can_complete": True})
|
||||
queued[2]["on_finished"]()
|
||||
assert len(queued) == 3 and dialog.sign_button.isVisible()
|
||||
assert dialog.identity_view is None and not dialog.poll_timer.isActive()
|
||||
dialog.setVisible(False)
|
||||
assert not dialog._intent and not dialog.sign_button.isEnabled() and not dialog.poll_timer.isActive()
|
||||
assert calls == ["status"]
|
||||
dialog.close()
|
||||
app.processEvents()
|
||||
@@ -0,0 +1,90 @@
|
||||
"""Exercise navigation policy and page security without any provider request."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from PySide6.QtCore import QUrl
|
||||
|
||||
from doctor_workstation.core.esign import authentication_navigation_allowed
|
||||
from doctor_workstation.ui.dialogs import esign_webview
|
||||
|
||||
|
||||
@pytest.mark.parametrize("url", [
|
||||
"https://idverify.esign.cn/identity?flow=test",
|
||||
"https://smlfront.esign.cn:8890/identity/login",
|
||||
"https://static2.tsign.cn/a.css",
|
||||
"https://nested.official.tsign.cn/identity",
|
||||
])
|
||||
def test_official_https_redirects_remain_inside_system(url: str) -> None:
|
||||
assert authentication_navigation_allowed(url)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("url", [
|
||||
"http://idverify.esign.cn/identity", "javascript:alert(1)", "file:///C:/secret",
|
||||
"weixin://identity", "alipays://identity", "data:text/html,test", "about:blank",
|
||||
"https://esign.cn.evil.test/identity", "https://evil-esign.cn/identity",
|
||||
"https://evil.test/identity", "https://user@idverify.esign.cn/identity",
|
||||
"https://idverify.esign.cn:444/identity", "https://idverify.esign.cn:8890/identity",
|
||||
"https://idverify.esign.cn\\@evil.test/identity", "https://a%40b.esign.cn/identity",
|
||||
])
|
||||
def test_offsite_and_app_switch_navigation_is_rejected(url: str) -> None:
|
||||
assert not authentication_navigation_allowed(url)
|
||||
|
||||
|
||||
def test_encoded_space_on_official_host_is_not_mistaken_for_control_character() -> None:
|
||||
url = QUrl("https://asset.esign.cn/img/icon%20_world_.svg?t=1%202")
|
||||
assert not authentication_navigation_allowed(url.toString())
|
||||
assert authentication_navigation_allowed(esign_webview._policy_url(url))
|
||||
assert not authentication_navigation_allowed(esign_webview._policy_url(QUrl("https://evil.test/a%20b")))
|
||||
|
||||
|
||||
@pytest.mark.skipif(not esign_webview.WEBENGINE_AVAILABLE, reason="QtWebEngine unavailable")
|
||||
def test_page_blocks_popups_frames_custom_schemes_and_uploads() -> None:
|
||||
blocked: list[str] = []
|
||||
page = SimpleNamespace(shutting_down=False, blocked=SimpleNamespace(emit=blocked.append))
|
||||
for main_frame in (True, False):
|
||||
assert esign_webview.IdentityPage.acceptNavigationRequest(
|
||||
page, QUrl("https://idverify.esign.cn/test"), None, main_frame
|
||||
)
|
||||
assert not esign_webview.IdentityPage.acceptNavigationRequest(
|
||||
page, QUrl("weixin://open"), None, main_frame
|
||||
)
|
||||
assert not esign_webview.IdentityPage.acceptNavigationRequest(
|
||||
page, QUrl("https://offsite.test/"), None, main_frame
|
||||
)
|
||||
assert esign_webview.IdentityPage.createWindow(page, None) is None
|
||||
assert esign_webview.IdentityPage.chooseFiles(page, None, [], []) == []
|
||||
assert len(blocked) == 5
|
||||
page.shutting_down = True
|
||||
assert esign_webview.IdentityPage.acceptNavigationRequest(page, QUrl("about:blank"), None, True)
|
||||
assert not esign_webview.IdentityPage.acceptNavigationRequest(page, QUrl("https://idverify.esign.cn/"), None, True)
|
||||
|
||||
|
||||
def test_loading_is_not_identity_success_and_tls_download_permission_are_denied() -> None:
|
||||
errors: list[str] = []
|
||||
calls: list[str] = []
|
||||
view = SimpleNamespace(_failure=errors.append, _stopped=False, initialized=SimpleNamespace(emit=lambda: None))
|
||||
esign_webview.EmbeddedIdentityView._loaded(view, True)
|
||||
assert errors == []
|
||||
esign_webview.EmbeddedIdentityView._loaded(view, False)
|
||||
esign_webview.EmbeddedIdentityView._deny_certificate(
|
||||
view, SimpleNamespace(rejectCertificate=lambda: calls.append("reject certificate"))
|
||||
)
|
||||
esign_webview.EmbeddedIdentityView._deny_download(
|
||||
view, SimpleNamespace(cancel=lambda: calls.append("cancel download"))
|
||||
)
|
||||
esign_webview.EmbeddedIdentityView._deny_permission(
|
||||
view, SimpleNamespace(deny=lambda: calls.append("deny permission"))
|
||||
)
|
||||
assert calls == ["reject certificate", "cancel download", "deny permission"]
|
||||
assert len(errors) == 4
|
||||
|
||||
|
||||
def test_manual_recheck_preserves_entered_sms_form() -> None:
|
||||
loaded: list[str] = []
|
||||
view = SimpleNamespace(_auth_url=None, view=SimpleNamespace(setUrl=lambda url: loaded.append(url.toString())))
|
||||
esign_webview.EmbeddedIdentityView.load_authentication(view, "https://smlt.esign.cn/abc")
|
||||
esign_webview.EmbeddedIdentityView.load_authentication(view, "https://smlt.esign.cn/abc")
|
||||
assert loaded == ["https://smlt.esign.cn/abc"]
|
||||
@@ -98,6 +98,26 @@ def test_invalid_identity_or_action_cannot_read_patient_context(changes):
|
||||
assert not repository.sync_calls and not repository.stream_calls
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model,forwarded", [(None, None), ("qwen", None), ("openai", "openai"), ("doubao", "doubao")])
|
||||
def test_selected_model_is_forwarded_only_when_not_the_task_default(model, forwarded):
|
||||
repository = Repository()
|
||||
service = controller(repository)
|
||||
assert service.handle(request(service, **({} if model is None else {"model": model})))
|
||||
assert service.wait()
|
||||
assert service.take_result()["status"] == "success"
|
||||
_diagnosis_id, _prompt, options = repository.stream_calls[0]
|
||||
assert options.get("model") == forwarded
|
||||
assert ("model" in options) is (forwarded is not None)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model", ["deepseek", "", "Doubao", 1, ["doubao"]])
|
||||
def test_unknown_model_cannot_start_a_request(model):
|
||||
repository = Repository()
|
||||
service = controller(repository)
|
||||
assert not service.handle(request(service, model=model))
|
||||
assert not repository.sync_calls and not repository.stream_calls
|
||||
|
||||
|
||||
def test_permission_default_denied_and_each_host_has_unique_session():
|
||||
repository = Repository()
|
||||
disabled = im_ai.ImAiController(
|
||||
|
||||
@@ -2,8 +2,11 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
from time import time
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
@@ -11,6 +14,7 @@ import pytest
|
||||
from doctor_workstation.core.errors import (
|
||||
ApiBusinessError,
|
||||
ApiProtocolError,
|
||||
ApiTransportError,
|
||||
AuthenticationExpiredError,
|
||||
RepositoryNotFoundError,
|
||||
)
|
||||
@@ -152,6 +156,61 @@ def test_demo_prescription_lookup_is_appointment_authoritative(
|
||||
assert first.case_record["appointment_id"] == 101
|
||||
|
||||
|
||||
def test_demo_void_and_reissue_preserves_the_original_prescription(
|
||||
repository: DemoDoctorRepository,
|
||||
) -> None:
|
||||
original = repository.create_prescription(
|
||||
appointment_id=103,
|
||||
diagnosis_id=503,
|
||||
doctor_signature="/demo/signature.png",
|
||||
)
|
||||
repository.audit_prescription(original.id, action="approve")
|
||||
assert repository.get_reception(103)["appointment"]["has_prescription"] == 1
|
||||
assert repository.get_prescription(original.id).raw["can_void"] is True
|
||||
|
||||
repository.void_prescription(original.id)
|
||||
|
||||
voided = repository.get_prescription(original.id)
|
||||
assert voided.void_status == 1
|
||||
assert voided.raw["can_void"] is False
|
||||
assert voided.void_time
|
||||
assert voided.audit_status == 1
|
||||
assert voided.doctor_signature == original.doctor_signature
|
||||
assert repository.get_reception(103)["appointment"]["has_prescription"] == 0
|
||||
assert repository.get_prescription_by_appointment(103) == voided
|
||||
with pytest.raises(ApiBusinessError, match="该处方已作废"):
|
||||
repository.void_prescription(original.id)
|
||||
|
||||
replacement = repository.create_prescription(appointment_id=103, diagnosis_id=503)
|
||||
|
||||
assert replacement.id != original.id
|
||||
assert replacement.audit_status == 0
|
||||
assert replacement.void_status == 0
|
||||
assert not replacement.doctor_signature
|
||||
assert repository.get_prescription_by_appointment(103) == replacement
|
||||
assert repository.get_reception(103)["appointment"]["has_prescription"] == 1
|
||||
assert repository.get_prescription(original.id) == voided
|
||||
|
||||
|
||||
def test_demo_void_and_order_creation_preserve_the_existing_order(
|
||||
repository: DemoDoctorRepository,
|
||||
) -> None:
|
||||
ordered = repository.get_prescription(801)
|
||||
orders = repository.list_prescription_orders().items
|
||||
assert repository.list_prescriptions(sn=ordered.sn).items[0].raw["can_void"] is False
|
||||
|
||||
with pytest.raises(ApiBusinessError, match="已有业务订单"):
|
||||
repository.void_prescription(ordered.id)
|
||||
|
||||
assert repository.get_prescription(ordered.id) == ordered
|
||||
|
||||
repository.void_prescription(802)
|
||||
with pytest.raises(ApiBusinessError, match="已作废处方不可创建业务订单"):
|
||||
repository.create_prescription_order(prescription_id=802)
|
||||
|
||||
assert repository.list_prescription_orders().items == orders
|
||||
|
||||
|
||||
def test_demo_consultation_filters_and_dictionaries_cover_exposed_ui(
|
||||
repository: DemoDoctorRepository,
|
||||
) -> None:
|
||||
@@ -360,6 +419,8 @@ class _StubApiClient:
|
||||
self.token = ""
|
||||
self.get_calls: list[tuple[str, dict[str, Any]]] = []
|
||||
self.post_calls: list[tuple[str, dict[str, Any]]] = []
|
||||
self.deadline = int(time()) + 3600
|
||||
self.post_tokens: list[str] = []
|
||||
|
||||
def set_token(self, token: str) -> None:
|
||||
"""Retain the synthetic login token."""
|
||||
@@ -390,13 +451,17 @@ class _StubApiClient:
|
||||
return {"appointment": {"id": params["id"]}, "doctor_notes": []}
|
||||
return {"lists": [], "count": 0, "extend": {}}
|
||||
|
||||
def post(self, endpoint: str, payload: dict[str, Any] | None = None) -> Any:
|
||||
def post(self, endpoint: str, payload: dict[str, Any] | None = None, *,
|
||||
headers: dict[str, str] | None = None, timeout: float | None = None) -> Any:
|
||||
"""Return synthetic mutation data and record the exact JSON payload."""
|
||||
|
||||
body = dict(payload or {})
|
||||
self.post_calls.append((endpoint, body))
|
||||
self.post_tokens.append((headers or {}).get("token", self.token))
|
||||
if endpoint == "login/account":
|
||||
return {"token": "remote-token", "is_paw": 1}
|
||||
return {"token": "remote-token", "is_paw": 1, "desktop_expires_at": self.deadline}
|
||||
if endpoint == "login/desktopHeartbeat":
|
||||
return {"desktop_expires_at": self.deadline}
|
||||
if endpoint == "tcm.prescriptionLibrary/add":
|
||||
return {"id": 9}
|
||||
if endpoint == "tcm.diagnosis/getCallSignature":
|
||||
@@ -418,6 +483,8 @@ def test_remote_repository_uses_all_confirmed_endpoints_without_network() -> Non
|
||||
repository = RemoteDoctorRepository(client) # type: ignore[arg-type]
|
||||
|
||||
session = repository.login(" doctor ", "secret")
|
||||
assert client.post_calls == [("login/account", {"account": "doctor", "password": "secret", "terminal": 21})]
|
||||
assert session.desktop_expires_at == client.deadline
|
||||
assert session.token == "remote-token"
|
||||
assert repository.get_current_user().name == "远程医生"
|
||||
assert [path for path, _ in client.get_calls].count("auth.admin/mySelf") == 1
|
||||
@@ -533,6 +600,8 @@ def test_remote_login_persists_only_after_session_validation(
|
||||
)
|
||||
|
||||
assert saved == []
|
||||
assert client.post_calls[-1] == ("login/logout", {})
|
||||
assert client.post_tokens[-1] == "remote-token"
|
||||
assert client.token == ""
|
||||
assert store.load_token() is None
|
||||
|
||||
@@ -549,6 +618,10 @@ def test_remote_login_applies_remember_account_to_token_store(tmp_path: Path) ->
|
||||
assert store.load_token(scope=client.base_url) == "remote-token"
|
||||
|
||||
repository.logout()
|
||||
assert client.post_calls[-1] == ("login/logout", {})
|
||||
assert client.post_tokens[-1] == "remote-token"
|
||||
assert store.load_token() is None
|
||||
assert store.load_account() == "doctor"
|
||||
repository.login("doctor", "secret", remember_account=False)
|
||||
assert store.load_account() is None
|
||||
assert store.load_token(scope=client.base_url) == "remote-token"
|
||||
@@ -559,7 +632,8 @@ def test_expired_persisted_token_is_removed_during_restore(tmp_path: Path) -> No
|
||||
|
||||
client = _FailingProfileClient(AuthenticationExpiredError("expired", code=-1))
|
||||
store = TokenStore(tmp_path / "credentials.json", keyring_backend=None)
|
||||
store.save_token("expired-token", account="doctor", scope=client.base_url)
|
||||
store.save_token("expired-token", account="doctor", scope=client.base_url,
|
||||
desktop_expires_at=client.deadline)
|
||||
repository = RemoteDoctorRepository(client, store) # type: ignore[arg-type]
|
||||
|
||||
with pytest.raises(AuthenticationExpiredError):
|
||||
@@ -570,6 +644,101 @@ def test_expired_persisted_token_is_removed_during_restore(tmp_path: Path) -> No
|
||||
assert store.load_account() == "doctor"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("deadline", [0, 1])
|
||||
def test_old_web_or_past_cutoff_token_is_discarded_without_network(tmp_path: Path, deadline: int) -> None:
|
||||
client = _StubApiClient()
|
||||
store = TokenStore(tmp_path / "credentials.json", keyring_backend=None)
|
||||
store.save_token("saved-token", account="doctor", scope=client.base_url, desktop_expires_at=deadline)
|
||||
repository = RemoteDoctorRepository(client, store) # type: ignore[arg-type]
|
||||
|
||||
with pytest.raises(AuthenticationExpiredError):
|
||||
repository.restore_session()
|
||||
repository.logout()
|
||||
assert client.post_calls == client.get_calls == []
|
||||
assert store.load_account() == "doctor"
|
||||
assert store.load_token() is None
|
||||
|
||||
|
||||
def test_restore_requires_live_heartbeat_and_keeps_earlier_cutoff(tmp_path: Path) -> None:
|
||||
client = _StubApiClient()
|
||||
store = TokenStore(tmp_path / "credentials.json", keyring_backend=None)
|
||||
store.save_token("desktop-token", scope=client.base_url, desktop_expires_at=client.deadline - 10)
|
||||
repository = RemoteDoctorRepository(client, store) # type: ignore[arg-type]
|
||||
|
||||
session = repository.restore_session()
|
||||
assert session and session.desktop_expires_at == client.deadline - 10
|
||||
assert client.post_calls == [("login/desktopHeartbeat", {})]
|
||||
assert client.post_tokens == ["desktop-token"]
|
||||
assert client.get_calls == [("auth.admin/mySelf", {})]
|
||||
|
||||
|
||||
def test_network_loss_during_restore_preserves_token_for_retry(tmp_path: Path, monkeypatch: Any) -> None:
|
||||
client = _StubApiClient()
|
||||
store = TokenStore(tmp_path / "credentials.json", keyring_backend=None)
|
||||
store.save_token("desktop-token", scope=client.base_url, desktop_expires_at=client.deadline)
|
||||
repository = RemoteDoctorRepository(client, store) # type: ignore[arg-type]
|
||||
|
||||
def offline(*_args: Any, **_kwargs: Any) -> Any:
|
||||
raise ApiTransportError("offline")
|
||||
|
||||
monkeypatch.setattr(client, "post", offline)
|
||||
with pytest.raises(ApiTransportError):
|
||||
repository.restore_session()
|
||||
assert client.token == ""
|
||||
assert client.get_calls == []
|
||||
assert store.load_token() == "desktop-token"
|
||||
|
||||
|
||||
def test_logout_after_network_loss_clears_credentials_and_never_retries(tmp_path: Path, monkeypatch: Any) -> None:
|
||||
client = _StubApiClient()
|
||||
store = TokenStore(tmp_path / "credentials.json", keyring_backend=None)
|
||||
repository = RemoteDoctorRepository(client, store) # type: ignore[arg-type]
|
||||
repository.login("doctor", "secret", remember_account=True)
|
||||
attempts = []
|
||||
|
||||
def offline(endpoint: str, _payload: dict, **kwargs: Any) -> Any:
|
||||
attempts.append((endpoint, kwargs["headers"]["token"]))
|
||||
raise ApiTransportError("offline")
|
||||
|
||||
monkeypatch.setattr(client, "post", offline)
|
||||
repository.logout()
|
||||
repository.logout()
|
||||
assert attempts == [("login/logout", "remote-token")]
|
||||
assert client.token == ""
|
||||
assert store.load_token() is None
|
||||
assert store.load_account() == "doctor"
|
||||
|
||||
|
||||
def test_app_close_during_login_retires_issued_token_before_transport_close(tmp_path: Path, monkeypatch: Any) -> None:
|
||||
client = _StubApiClient()
|
||||
store = TokenStore(tmp_path / "credentials.json", keyring_backend=None)
|
||||
repository = RemoteDoctorRepository(client, store) # type: ignore[arg-type]
|
||||
profile_started = Event()
|
||||
finish_profile = Event()
|
||||
get_profile = client.get
|
||||
closes = []
|
||||
|
||||
def pending_profile(endpoint: str) -> Any:
|
||||
profile_started.set()
|
||||
assert finish_profile.wait(3)
|
||||
return get_profile(endpoint)
|
||||
|
||||
monkeypatch.setattr(client, "get", pending_profile)
|
||||
monkeypatch.setattr(client, "close", lambda: closes.append(client.token), raising=False)
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||
login = pool.submit(repository.login, "doctor", "secret", remember_account=True)
|
||||
assert profile_started.wait(3)
|
||||
shutdown = pool.submit(repository.close)
|
||||
finish_profile.set()
|
||||
assert login.result(timeout=3).token == "remote-token"
|
||||
shutdown.result(timeout=3)
|
||||
assert store.load_account() == "doctor"
|
||||
assert store.load_token() is None
|
||||
assert closes == [""]
|
||||
assert client.post_calls[-1] == ("login/logout", {})
|
||||
assert client.post_tokens[-1] == "remote-token"
|
||||
|
||||
|
||||
def test_restore_never_sends_token_to_a_different_api_scope(tmp_path: Path) -> None:
|
||||
"""Changing the configured server invalidates automatic token reuse."""
|
||||
|
||||
|
||||
@@ -81,13 +81,13 @@ def _detail(appointment_id: int, patient_id: int, diagnosis_id: int) -> dict[str
|
||||
|
||||
|
||||
def _snapshot(model: str, version: int, stamp: str) -> dict[str, Any]:
|
||||
label = "OpenAI" if model == "openai" else "千问"
|
||||
label = {"openai": "OpenAI", "doubao": "豆包"}.get(model, "千问")
|
||||
return {
|
||||
"id": version * 10 + (2 if model == "openai" else 1),
|
||||
"id": version * 10 + {"openai": 2, "doubao": 3}.get(model, 1),
|
||||
"patient_id": 301,
|
||||
"model_key": model,
|
||||
"model_label": label,
|
||||
"model_name": "gpt-demo" if model == "openai" else "qwen-demo",
|
||||
"model_name": {"openai": "gpt-demo", "doubao": "doubao-demo"}.get(model, "qwen-demo"),
|
||||
"version": version,
|
||||
"generated_at": stamp,
|
||||
"report": {
|
||||
@@ -211,7 +211,7 @@ def test_saved_history_is_rendered_without_automatic_generation(
|
||||
page.close()
|
||||
|
||||
|
||||
def test_empty_database_and_manual_refresh_append_qwen_then_openai(
|
||||
def test_empty_database_and_manual_refresh_append_every_model_in_order(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
) -> None:
|
||||
@@ -254,18 +254,20 @@ def test_empty_database_and_manual_refresh_append_qwen_then_openai(
|
||||
page._select_record(detail["appointment"])
|
||||
application.processEvents()
|
||||
|
||||
assert repository.calls == [("list", 302), ("generate", "qwen"), ("generate", "openai")]
|
||||
assert [len(page._ai_analysis_histories[key]) for key in ("qwen", "openai")] == [1, 1]
|
||||
assert repository.calls == [
|
||||
("list", 302), ("generate", "qwen"), ("generate", "openai"), ("generate", "doubao"),
|
||||
]
|
||||
assert [len(page._ai_analysis_histories[key]) for key in ("qwen", "openai", "doubao")] == [1, 1, 1]
|
||||
|
||||
page.ai_analysis_regenerate_button.click()
|
||||
application.processEvents()
|
||||
|
||||
assert repository.calls[-2:] == [("generate", "qwen"), ("generate", "openai")]
|
||||
assert [len(page._ai_analysis_histories[key]) for key in ("qwen", "openai")] == [2, 2]
|
||||
assert repository.calls[-3:] == [("generate", "qwen"), ("generate", "openai"), ("generate", "doubao")]
|
||||
assert [len(page._ai_analysis_histories[key]) for key in ("qwen", "openai", "doubao")] == [2, 2, 2]
|
||||
page.close()
|
||||
|
||||
|
||||
def test_openai_failure_keeps_new_qwen_snapshot(
|
||||
def test_openai_failure_keeps_new_qwen_snapshot_and_still_generates_doubao(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
) -> None:
|
||||
@@ -281,7 +283,7 @@ def test_openai_failure_keeps_new_qwen_snapshot(
|
||||
def generate_patient_ai_report(self, patient_id: int, *, model: str) -> dict[str, Any]:
|
||||
if model == "openai":
|
||||
raise RuntimeError("OpenAI 暂时不可用")
|
||||
row = _snapshot("qwen", 1, "2026-08-14 10:30:00")
|
||||
row = _snapshot(model, 1, "2026-08-14 10:30:00")
|
||||
row["patient_id"] = patient_id
|
||||
return {
|
||||
"patient_id": patient_id,
|
||||
@@ -305,7 +307,11 @@ def test_openai_failure_keeps_new_qwen_snapshot(
|
||||
assert page.ai_summary_label.text() == "千问第 1 版诊断建议"
|
||||
assert len(page._ai_analysis_histories["qwen"]) == 1
|
||||
assert page._ai_analysis_model_states["openai"] == "error"
|
||||
assert "千问新快照已保留" in page.ai_analysis_secondary_status.text()
|
||||
# 第二个模型失败不阻断第三个模型补齐。
|
||||
assert page._ai_analysis_model_states["doubao"] == "success"
|
||||
assert len(page._ai_analysis_histories["doubao"]) == 1
|
||||
assert "千问结果已保留" in page.ai_analysis_secondary_status.text()
|
||||
assert "OpenAI新快照生成失败" in page.ai_analysis_secondary_status.text()
|
||||
page.close()
|
||||
|
||||
|
||||
|
||||
@@ -528,6 +528,10 @@ def test_order_action_matrix_requires_exact_permissions_and_states(
|
||||
"ddcode",
|
||||
"withdraw",
|
||||
]
|
||||
for submission_time, review_ready in ((0, False), (1_760_000_000, False), (1_760_000_000, True)):
|
||||
current = {**pending, "review_submitted_at": submission_time, "can_review_prescription": review_ready}
|
||||
available = {key for key, _label, _danger in workspace._available_actions(current)}
|
||||
assert ("audit_prescription" in available) is review_ready
|
||||
assert [key for key, _label, _danger in workspace._available_actions(shipped)] == [
|
||||
"revoke_pay_audit",
|
||||
"ddcode",
|
||||
@@ -580,6 +584,75 @@ def test_order_audit_action_uses_repository_contract_values(
|
||||
application.processEvents()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("can_sign,opens_signing", [(True, True), (False, False)])
|
||||
def test_order_approval_routes_unsigned_prescription_before_audit(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
can_sign: bool,
|
||||
opens_signing: bool,
|
||||
) -> None:
|
||||
requested = []
|
||||
opened = []
|
||||
state = {"enabled": True, "required": True, "environment": "sandbox", "status": "pending",
|
||||
"can_sign": can_sign, "can_download": False}
|
||||
|
||||
def get_status(prescription_id: int) -> dict[str, Any]:
|
||||
requested.append(prescription_id)
|
||||
return state
|
||||
|
||||
repository = SimpleNamespace(get_prescription_esign_status=get_status)
|
||||
permissions = PermissionSet(["tcm.prescriptionOrder/auditPrescription", "cf.prescription/edit"])
|
||||
page = PatientsPage(repository, permissions)
|
||||
monkeypatch.setattr(page.order_workspace, "refresh", lambda **_kwargs: None)
|
||||
monkeypatch.setattr(page, "_submit_order_audit", lambda *_args, **_kwargs: pytest.fail("unsigned approval"))
|
||||
monkeypatch.setattr(QInputDialog, "getItem", staticmethod(lambda *_args, **_kwargs: ("通过", True)))
|
||||
monkeypatch.setattr(
|
||||
patients_module, "PrescriptionEsignDialog",
|
||||
lambda _repo, prescription, **_kwargs: SimpleNamespace(exec=lambda: opened.append(prescription["id"])),
|
||||
)
|
||||
|
||||
page._handle_order_action("audit_prescription", {"id": 70, "prescription_id": 52,
|
||||
"prescription_audit_status": 0, "fulfillment_status": 1})
|
||||
|
||||
assert requested == [52]
|
||||
assert opened == ([52] if opens_signing else [])
|
||||
assert "签署" in page.order_workspace.banner.label.text()
|
||||
page.close()
|
||||
application.processEvents()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("review_signed", [False, True])
|
||||
def test_order_approval_requires_pharmacist_signature_when_enabled(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
review_signed: bool,
|
||||
) -> None:
|
||||
signed_at = 1_760_000_000
|
||||
status = {
|
||||
"enabled": True, "required": True, "environment": "sandbox", "status": "signed",
|
||||
"can_sign": False, "can_download": True, "review_submitted_at": signed_at - 10,
|
||||
"review_required": True, "review_signature_time": signed_at if review_signed else 0,
|
||||
"can_review_prescription": False,
|
||||
}
|
||||
row = {
|
||||
"id": 70, "prescription_id": 52, "prescription_audit_status": 0, "fulfillment_status": 1,
|
||||
"review_submitted_at": signed_at - 10, "can_review_prescription": True,
|
||||
}
|
||||
approved = []
|
||||
repository = SimpleNamespace(get_prescription_esign_status=lambda _id: status)
|
||||
page = PatientsPage(repository, PermissionSet(["tcm.prescriptionOrder/auditPrescription"]))
|
||||
monkeypatch.setattr(page, "_submit_order_audit", lambda order_id, **_kwargs: approved.append(order_id))
|
||||
monkeypatch.setattr(QInputDialog, "getItem", staticmethod(lambda *_args, **_kwargs: ("通过", True)))
|
||||
page._handle_order_action("audit_prescription", row)
|
||||
assert approved == ([70] if review_signed else [])
|
||||
if not review_signed:
|
||||
assert "管理后台" in page.order_workspace.banner.label.text()
|
||||
page.close()
|
||||
application.processEvents()
|
||||
|
||||
|
||||
def test_shell_uses_demo_session_menu_and_fits_minimum_window(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -7,8 +7,8 @@ from typing import Any
|
||||
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
||||
|
||||
import pytest
|
||||
from PySide6.QtCore import QPoint, Qt
|
||||
from PySide6.QtWidgets import QApplication, QDialog, QPushButton
|
||||
from PySide6.QtCore import QPoint, Qt
|
||||
from PySide6.QtWidgets import QApplication, QDialog, QPushButton
|
||||
|
||||
from doctor_workstation.core import PermissionSet
|
||||
from doctor_workstation.ui import widgets
|
||||
@@ -412,114 +412,118 @@ def _finish_queued(callback: dict[str, Any], result: Any) -> None:
|
||||
callback["on_finished"]()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("owner_width", [1024, 1440])
|
||||
def test_embedded_prescription_history_opens_full_detail_without_changing_draft(
|
||||
application: QApplication, monkeypatch: pytest.MonkeyPatch, owner_width: int,
|
||||
) -> None:
|
||||
listed: list[int] = []
|
||||
fetched: list[int] = []
|
||||
shown: list[int] = []
|
||||
|
||||
class Repository(_DiagnosisRepository):
|
||||
def get_doctor_notes(self, _diagnosis_id: int) -> list[Any]:
|
||||
return []
|
||||
|
||||
def list_prescriptions_by_diagnosis(self, diagnosis_id: int) -> list[dict[str, Any]]:
|
||||
listed.append(diagnosis_id)
|
||||
return [
|
||||
{"id": 92, "diagnosis_id": diagnosis_id, "prescription_date": "2026-11-03",
|
||||
"doctor_name": "陈医生", "clinical_diagnosis": "气阴两虚", "audit_status": 1},
|
||||
{"id": 81, "diagnosis_id": diagnosis_id, "prescription_date": "2026-10-20",
|
||||
"doctor_name": "李医生", "clinical_diagnosis": "脾虚", "void_status": 1},
|
||||
]
|
||||
|
||||
def get_prescription(self, prescription_id: int) -> dict[str, Any]:
|
||||
fetched.append(prescription_id)
|
||||
return {"id": prescription_id, "diagnosis_id": 745, "patient_name": "测试患者",
|
||||
"herbs": [{"name": "黄芪", "dosage": 15}], "usage_instruction": "水煎服"}
|
||||
|
||||
def inspect_detail(dialog: dialog_module.PrescriptionDetailDialog) -> int:
|
||||
shown.append(dialog.prescription["id"])
|
||||
assert "黄芪" in dialog.document.toPlainText()
|
||||
assert "水煎服" in dialog.document.toPlainText()
|
||||
assert dialog.diagnosis_button.isHidden()
|
||||
assert dialog.orders_button.isHidden()
|
||||
return QDialog.DialogCode.Rejected
|
||||
|
||||
monkeypatch.setattr(diagnosis_module, "run_async", _immediate_async)
|
||||
monkeypatch.setattr(dialog_module.PrescriptionDetailDialog, "exec", inspect_detail)
|
||||
owner = QDialog()
|
||||
owner.resize(owner_width, 800)
|
||||
owner.show()
|
||||
editor = PrescriptionEditorDialog(
|
||||
Repository(), {"diagnosis_id": 745, "patient_name": "测试患者"}, mode="edit",
|
||||
permissions=PermissionSet(["tcm.diagnosis/readonlyDetail", "tcm.diagnosis/chufang"]),
|
||||
parent=owner,
|
||||
)
|
||||
editor.show()
|
||||
application.processEvents()
|
||||
editor.clinical_diagnosis.setPlainText("尚未保存的新诊断")
|
||||
draft = editor.payload()
|
||||
editor.diagnosis_button.click()
|
||||
for _ in range(6):
|
||||
application.processEvents()
|
||||
detail = editor._diagnosis_view
|
||||
assert detail is not None
|
||||
table = detail.readonly_prescriptions_table
|
||||
assert listed == [745]
|
||||
assert table.rowCount() == 2
|
||||
assert table.item(0, 5).text() == "审核通过"
|
||||
assert table.item(1, 5).text() == "已作废"
|
||||
assert table.horizontalScrollBar().maximum() == 0
|
||||
assert table.mapToGlobal(QPoint(table.width(), 0)).x() <= detail.readonly_scroll.viewport().mapToGlobal(
|
||||
QPoint(detail.readonly_scroll.viewport().width(), 0)
|
||||
).x()
|
||||
assert detail._readonly_sections["prescription"].y() < detail.case_grid.y()
|
||||
actions = table.cellWidget(1, 6).findChildren(QPushButton)
|
||||
assert [button.text() for button in actions] == ["查看"]
|
||||
actions[0].click()
|
||||
assert fetched == [81] and shown == [81]
|
||||
assert editor.payload() == draft
|
||||
assert editor.diagnosis_host.isVisibleTo(editor)
|
||||
detail.readonly_close_button.click()
|
||||
editor.diagnosis_button.click()
|
||||
assert listed == [745, 745]
|
||||
assert editor.payload() == draft
|
||||
editor.reject()
|
||||
owner.close()
|
||||
application.processEvents()
|
||||
|
||||
|
||||
def test_readonly_history_respects_permission_and_shows_empty_and_failure(
|
||||
application: QApplication, monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
calls: list[int] = []
|
||||
|
||||
class Repository(_DiagnosisRepository):
|
||||
def get_doctor_notes(self, _diagnosis_id: int) -> list[Any]:
|
||||
return []
|
||||
|
||||
def list_prescriptions_by_diagnosis(self, diagnosis_id: int) -> list[Any]:
|
||||
calls.append(diagnosis_id)
|
||||
if len(calls) > 1:
|
||||
raise RuntimeError("测试加载失败")
|
||||
return []
|
||||
|
||||
monkeypatch.setattr(diagnosis_module, "run_async", _immediate_async)
|
||||
dialog = DiagnosisDialog(Repository(), permissions=PermissionSet(["tcm.diagnosis/readonlyDetail"]))
|
||||
dialog.open_for(745, editable=False)
|
||||
assert dialog._readonly_sections["prescription"].isHidden()
|
||||
assert calls == []
|
||||
dialog.refresh_permissions(PermissionSet(["tcm.diagnosis/readonlyDetail", "tcm.diagnosis/chufang"]))
|
||||
dialog.open_for(745, editable=False)
|
||||
assert "暂无历史处方" in dialog.readonly_prescriptions_table.empty_label.text()
|
||||
dialog.open_for(745, editable=False)
|
||||
assert "加载失败" in dialog.readonly_prescriptions_table.empty_label.text()
|
||||
assert dialog.readonly_prescriptions_table.rowCount() == 0
|
||||
dialog.close()
|
||||
application.processEvents()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("owner_width", [1024, 1440])
|
||||
def test_embedded_prescription_history_opens_full_detail_without_changing_draft(
|
||||
application: QApplication, monkeypatch: pytest.MonkeyPatch, owner_width: int,
|
||||
) -> None:
|
||||
listed: list[int] = []
|
||||
fetched: list[int] = []
|
||||
shown: list[int] = []
|
||||
|
||||
class Repository(_DiagnosisRepository):
|
||||
def get_doctor_notes(self, _diagnosis_id: int) -> list[Any]:
|
||||
return []
|
||||
|
||||
def list_prescriptions_by_diagnosis(self, diagnosis_id: int) -> list[dict[str, Any]]:
|
||||
listed.append(diagnosis_id)
|
||||
return [
|
||||
{"id": 92, "diagnosis_id": diagnosis_id, "prescription_date": "2026-11-03",
|
||||
"doctor_name": "陈医生", "clinical_diagnosis": "气阴两虚", "audit_status": 1},
|
||||
{"id": 81, "diagnosis_id": diagnosis_id, "prescription_date": "2026-10-20",
|
||||
"doctor_name": "李医生", "clinical_diagnosis": "脾虚", "void_status": 1},
|
||||
]
|
||||
|
||||
def get_prescription(self, prescription_id: int) -> dict[str, Any]:
|
||||
fetched.append(prescription_id)
|
||||
return {"id": prescription_id, "diagnosis_id": 745, "patient_name": "测试患者",
|
||||
"herbs": [{"name": "黄芪", "dosage": 15}], "usage_instruction": "水煎服"}
|
||||
|
||||
def inspect_detail(dialog: dialog_module.PrescriptionDetailDialog) -> int:
|
||||
shown.append(dialog.prescription["id"])
|
||||
assert "黄芪" in dialog.document.toPlainText()
|
||||
assert "水煎服" in dialog.document.toPlainText()
|
||||
assert dialog.diagnosis_button.isHidden()
|
||||
assert dialog.orders_button.isHidden()
|
||||
return QDialog.DialogCode.Rejected
|
||||
|
||||
monkeypatch.setattr(diagnosis_module, "run_async", _immediate_async)
|
||||
monkeypatch.setattr(dialog_module.PrescriptionDetailDialog, "exec", inspect_detail)
|
||||
owner = QDialog()
|
||||
owner.resize(owner_width, 800)
|
||||
owner.show()
|
||||
editor = PrescriptionEditorDialog(
|
||||
Repository(), {"diagnosis_id": 745, "patient_name": "测试患者"}, mode="edit",
|
||||
permissions=PermissionSet(["tcm.diagnosis/readonlyDetail", "tcm.diagnosis/chufang"]),
|
||||
parent=owner,
|
||||
)
|
||||
editor.show()
|
||||
application.processEvents()
|
||||
editor.clinical_diagnosis.setPlainText("尚未保存的新诊断")
|
||||
draft = editor.payload()
|
||||
editor.diagnosis_button.click()
|
||||
for _ in range(6):
|
||||
application.processEvents()
|
||||
detail = editor._diagnosis_view
|
||||
assert detail is not None
|
||||
table = detail.readonly_prescriptions_table
|
||||
assert listed == [745]
|
||||
assert table.rowCount() == 2
|
||||
assert table.item(0, 5).text() == "审核通过"
|
||||
assert table.item(1, 5).text() == "已作废"
|
||||
assert table.horizontalScrollBar().maximum() == 0
|
||||
assert table.mapToGlobal(QPoint(table.width(), 0)).x() <= detail.readonly_scroll.viewport().mapToGlobal(
|
||||
QPoint(detail.readonly_scroll.viewport().width(), 0)
|
||||
).x()
|
||||
assert detail._readonly_sections["prescription"].y() < detail.case_grid.y()
|
||||
# 历史处方下方默认嵌入最新一张处方的三联预览。
|
||||
embedded = detail.readonly_prescription_preview
|
||||
assert fetched == [92] and embedded is not None and embedded.prescription_id == 92
|
||||
assert embedded.edit_button.isHidden() and "黄芪" in embedded.paper.toPlainText()
|
||||
actions = table.cellWidget(1, 6).findChildren(QPushButton)
|
||||
assert [button.text() for button in actions] == ["查看"]
|
||||
actions[0].click()
|
||||
assert fetched == [92, 81] and shown == [81]
|
||||
assert editor.payload() == draft
|
||||
assert editor.diagnosis_host.isVisibleTo(editor)
|
||||
detail.readonly_close_button.click()
|
||||
editor.diagnosis_button.click()
|
||||
assert listed == [745, 745]
|
||||
assert editor.payload() == draft
|
||||
editor.reject()
|
||||
owner.close()
|
||||
application.processEvents()
|
||||
|
||||
|
||||
def test_readonly_history_respects_permission_and_shows_empty_and_failure(
|
||||
application: QApplication, monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
calls: list[int] = []
|
||||
|
||||
class Repository(_DiagnosisRepository):
|
||||
def get_doctor_notes(self, _diagnosis_id: int) -> list[Any]:
|
||||
return []
|
||||
|
||||
def list_prescriptions_by_diagnosis(self, diagnosis_id: int) -> list[Any]:
|
||||
calls.append(diagnosis_id)
|
||||
if len(calls) > 1:
|
||||
raise RuntimeError("测试加载失败")
|
||||
return []
|
||||
|
||||
monkeypatch.setattr(diagnosis_module, "run_async", _immediate_async)
|
||||
dialog = DiagnosisDialog(Repository(), permissions=PermissionSet(["tcm.diagnosis/readonlyDetail"]))
|
||||
dialog.open_for(745, editable=False)
|
||||
assert dialog._readonly_sections["prescription"].isHidden()
|
||||
assert calls == []
|
||||
dialog.refresh_permissions(PermissionSet(["tcm.diagnosis/readonlyDetail", "tcm.diagnosis/chufang"]))
|
||||
dialog.open_for(745, editable=False)
|
||||
assert "暂无历史处方" in dialog.readonly_prescriptions_table.empty_label.text()
|
||||
dialog.open_for(745, editable=False)
|
||||
assert "加载失败" in dialog.readonly_prescriptions_table.empty_label.text()
|
||||
assert dialog.readonly_prescriptions_table.rowCount() == 0
|
||||
dialog.close()
|
||||
application.processEvents()
|
||||
|
||||
|
||||
def test_prescription_lists_snapshot_queries_and_supersede_stale_refresh(
|
||||
application: QApplication,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
|
||||
@@ -7,10 +7,11 @@ from typing import Any
|
||||
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
||||
|
||||
import pytest
|
||||
from PySide6.QtCore import QDate, QEvent, QObject, QSize, Qt
|
||||
from PySide6.QtGui import QColor, QImage, QPainter
|
||||
from PySide6.QtCore import QBuffer, QDate, QEvent, QIODevice, QObject, QSize, Qt
|
||||
from PySide6.QtGui import QColor, QImage, QPainter, QTextDocument
|
||||
from PySide6.QtPdf import QPdfDocument
|
||||
from PySide6.QtWidgets import QApplication, QComboBox, QDialog, QPushButton, QWidget
|
||||
from PySide6.QtTest import QTest
|
||||
from PySide6.QtWidgets import QApplication, QComboBox, QDialog, QMessageBox, QPushButton, QWidget
|
||||
|
||||
from doctor_workstation import app as app_module
|
||||
from doctor_workstation.core import PermissionSet, Prescription
|
||||
@@ -21,6 +22,7 @@ from doctor_workstation.ui.dialogs.prescription import (
|
||||
PrescriptionDetailDialog,
|
||||
PrescriptionEditorDialog,
|
||||
PrescriptionOrderDialog,
|
||||
PrescriptionSigningPreview,
|
||||
PrescriptionTemplateDialog,
|
||||
RemoteMedicineComboBox,
|
||||
build_prescription_clinical_diagnosis,
|
||||
@@ -479,6 +481,487 @@ def test_editor_builds_complete_add_payload(
|
||||
application.processEvents()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("saved_dietary_taboo", [["辛辣食物", "浓茶"], "辛辣食物, 浓茶"])
|
||||
def test_editor_dietary_taboo_popup_supports_consecutive_selections(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
saved_dietary_taboo: list[str] | str,
|
||||
) -> None:
|
||||
editor = PrescriptionEditorDialog(
|
||||
SimpleNamespace(), prescription={"dietary_taboo": saved_dietary_taboo}, mode="edit"
|
||||
)
|
||||
editor.show()
|
||||
editor.body_scroll.ensureWidgetVisible(editor.dietary_taboo)
|
||||
application.processEvents()
|
||||
|
||||
selector = editor.dietary_taboo
|
||||
field = selector.lineEdit()
|
||||
assert field.text() == "辛辣食物、浓茶"
|
||||
QTest.mouseClick(field, Qt.MouseButton.LeftButton)
|
||||
view = selector.view()
|
||||
assert view.isVisible()
|
||||
|
||||
for row, expected in (
|
||||
(1, "辛辣食物、生冷食物、浓茶"),
|
||||
(2, "辛辣食物、生冷食物、油腻食物、浓茶"),
|
||||
(0, "生冷食物、油腻食物、浓茶"),
|
||||
):
|
||||
point = view.visualRect(selector.model().index(row, 0)).center()
|
||||
QTest.mouseClick(view.viewport(), Qt.MouseButton.LeftButton, pos=point)
|
||||
assert view.isVisible()
|
||||
assert field.text() == expected
|
||||
|
||||
QTest.keyClick(view, Qt.Key.Key_Down)
|
||||
QTest.keyClick(view, Qt.Key.Key_Space)
|
||||
assert view.isVisible()
|
||||
QTest.keyClick(view, Qt.Key.Key_Escape)
|
||||
assert not view.isVisible()
|
||||
assert field.text() == "油腻食物、浓茶"
|
||||
assert editor.payload()["dietary_taboo"] == ["油腻食物", "浓茶"]
|
||||
editor.close()
|
||||
application.processEvents()
|
||||
|
||||
|
||||
def test_esign_draft_save_retries_without_discarding_form(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
) -> None:
|
||||
calls: list[dict[str, Any]] = []
|
||||
|
||||
def save(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
calls.append(payload)
|
||||
if len(calls) == 1:
|
||||
raise TimeoutError("request timed out")
|
||||
return {"id": 71}
|
||||
|
||||
repository = SimpleNamespace(
|
||||
get_prescription_esign_config=lambda: {"enabled": True, "environment": "sandbox"},
|
||||
list_medicines=lambda **_kwargs: {"lists": [], "count": 0},
|
||||
)
|
||||
editor = PrescriptionEditorDialog(repository, current_user={"id": 7, "name": "测试医生"}, save_draft=save)
|
||||
editor.show()
|
||||
editor.patient_name.setText("虚构患者")
|
||||
editor.clinical_diagnosis.setPlainText("测试草稿")
|
||||
editor.herbs.add_row(formula_type="主方")
|
||||
editor.herbs.rows[0].medicine.set_value(31, "测试药材")
|
||||
editor.herbs.rows[0].dosage.setValue(15)
|
||||
|
||||
editor.save_button.click()
|
||||
assert editor.isVisible()
|
||||
assert editor.save_button.text() == "重试保存草稿"
|
||||
assert editor.patient_name.text() == "虚构患者"
|
||||
assert len(calls) == 1
|
||||
|
||||
editor.save_button.click()
|
||||
assert editor.result() == QDialog.DialogCode.Accepted
|
||||
assert editor.saved_draft == {"id": 71}
|
||||
assert calls[0] == calls[1]
|
||||
assert calls[1]["request_key"]
|
||||
application.processEvents()
|
||||
|
||||
|
||||
def test_issued_page_voids_and_reissues_as_a_new_prescription(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
original = {
|
||||
"id": 71,
|
||||
"sn": "RX-71",
|
||||
"creator_id": 7,
|
||||
"doctor_name": "周医生",
|
||||
"diagnosis_id": 8,
|
||||
"appointment_id": 9,
|
||||
"patient_name": "沙箱测试",
|
||||
"visit_no": "VISIT-8",
|
||||
"prescription_date": "2026-03-10",
|
||||
"herbs": [{"name": "黄芪", "dosage": 15}],
|
||||
"audit_status": 1,
|
||||
"audit_time": "2026-03-10 09:10:00",
|
||||
"order_no": "ARCHIVED-ORDER",
|
||||
"doctor_signature": "old-signature",
|
||||
"esign": {"required": True, "status": "signed"},
|
||||
"void_status": 0,
|
||||
"can_void": True,
|
||||
}
|
||||
blocked = {**original, "id": 72, "creator_id": 8, "can_void": False}
|
||||
void_calls = []
|
||||
opened = []
|
||||
|
||||
class Repository:
|
||||
def list_prescriptions(self, **_filters: Any) -> dict[str, Any]:
|
||||
return {"lists": [original, blocked], "count": 2}
|
||||
|
||||
def get_prescription(self, prescription_id: int) -> dict[str, Any]:
|
||||
assert prescription_id == original["id"]
|
||||
return dict(original)
|
||||
|
||||
def void_prescription(self, prescription_id: int) -> None:
|
||||
void_calls.append(prescription_id)
|
||||
if len(void_calls) == 1:
|
||||
raise RuntimeError("作废失败,请稍后重试")
|
||||
original.update(void_status=1, can_void=False)
|
||||
|
||||
def capture_new_prescription(dialog: PrescriptionEditorDialog) -> int:
|
||||
assert dialog.mode == "add"
|
||||
opened.append(dialog.payload())
|
||||
return QDialog.DialogCode.Rejected
|
||||
|
||||
confirm_void = False
|
||||
|
||||
def selected_confirmation(box: QMessageBox) -> QPushButton:
|
||||
label = "确认作废" if confirm_void else "取消"
|
||||
return next(button for button in box.buttons() if button.text() == label)
|
||||
|
||||
monkeypatch.setattr(PrescriptionEditorDialog, "exec", capture_new_prescription)
|
||||
monkeypatch.setattr(QMessageBox, "exec", lambda _box: 0)
|
||||
monkeypatch.setattr(QMessageBox, "clickedButton", selected_confirmation)
|
||||
page = PrescriptionsPage(
|
||||
Repository(), {"cf.prescription/read", "cf.prescription/edit", "tcm.diagnosis/kaifang"},
|
||||
SimpleNamespace(id=7, name="周医生"),
|
||||
)
|
||||
page.refresh()
|
||||
page._run_row_action(blocked, page._void_selected)
|
||||
assert page.void_button.isHidden()
|
||||
assert not void_calls
|
||||
|
||||
page._run_row_action(original, page._void_selected)
|
||||
assert page.void_button.isEnabled()
|
||||
assert not void_calls
|
||||
confirm_void = True
|
||||
page.void_button.click()
|
||||
assert void_calls == [71]
|
||||
assert page.void_button.isEnabled() and original["void_status"] == 0
|
||||
assert "请稍后重试" in page.banner.label.text()
|
||||
page.void_button.click()
|
||||
assert void_calls == [71, 71]
|
||||
assert page.void_button.isHidden()
|
||||
assert page.reissue_button.isEnabled()
|
||||
assert not page.edit_button.isEnabled()
|
||||
|
||||
page.reissue_button.click()
|
||||
assert len(opened) == 1
|
||||
draft = opened[0]
|
||||
assert draft["diagnosis_id"] == 8 and draft["appointment_id"] == 9
|
||||
assert draft["patient_name"] == "沙箱测试" and draft["visit_no"] == "VISIT-8"
|
||||
assert draft["creator_id"] == 7
|
||||
assert draft["herbs"][0]["name"] == "黄芪"
|
||||
assert draft["prescription_date"] == QDate.currentDate().toString("yyyy-MM-dd")
|
||||
assert draft["audit_status"] == 0 and draft["doctor_signature"] == ""
|
||||
assert not draft.keys() & {"id", "sn", "order_no", "audit_time", "esign", "void_status"}
|
||||
assert original["void_status"] == 1
|
||||
assert original["esign"]["status"] == "signed" and original["audit_status"] == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("read_only", [False, True])
|
||||
def test_prescription_window_footer_preserves_draft_on_void_failure(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
read_only: bool,
|
||||
) -> None:
|
||||
calls: list[int] = []
|
||||
record = {"id": 71, "sn": "RX-71", "patient_name": "虚构测试", "can_void": True}
|
||||
|
||||
def void_prescription(prescription_id: int) -> dict[str, Any]:
|
||||
calls.append(prescription_id)
|
||||
if len(calls) == 1:
|
||||
raise RuntimeError("网络错误,请稍后重试")
|
||||
return {"id": prescription_id}
|
||||
|
||||
repository = SimpleNamespace(void_prescription=void_prescription)
|
||||
dialog = (
|
||||
PrescriptionDetailDialog(record, repository=repository, allow_void=True)
|
||||
if read_only else PrescriptionEditorDialog(repository, record, mode="edit", allow_void=True)
|
||||
)
|
||||
confirm = False
|
||||
monkeypatch.setattr(dialog_module, "confirm_prescription_void", lambda *_args: confirm)
|
||||
assert dialog.void_button.text() == "作废处方"
|
||||
dialog.void_button.click()
|
||||
assert not calls
|
||||
confirm = True
|
||||
dialog.void_button.click()
|
||||
assert calls == [71] and dialog.void_button.text() == "重试作废"
|
||||
assert "请稍后重试" in dialog.void_button.banner.label.text()
|
||||
dialog.void_button.click()
|
||||
assert calls == [71, 71] and dialog.result() == dialog_module.PRESCRIPTION_VOIDED_RESULT
|
||||
|
||||
|
||||
@pytest.mark.parametrize("variant", ["internal", "user"])
|
||||
@pytest.mark.parametrize("print_layout", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
("image_size", "expected_size"),
|
||||
[((300, 150), (40, 20)), ((384, 60), (64, 10)), ((20, 10), (20, 10))],
|
||||
)
|
||||
def test_prescription_slip_scales_both_signatures_proportionately(
|
||||
application: QApplication,
|
||||
variant: str,
|
||||
print_layout: bool,
|
||||
image_size: tuple[int, int],
|
||||
expected_size: tuple[int, int],
|
||||
) -> None:
|
||||
signatures = []
|
||||
for color in ("black", "red"):
|
||||
image = QImage(*image_size, QImage.Format.Format_ARGB32)
|
||||
image.fill(QColor(color))
|
||||
buffer = QBuffer()
|
||||
assert buffer.open(QIODevice.OpenModeFlag.WriteOnly)
|
||||
assert image.save(buffer, "PNG")
|
||||
signatures.append("data:image/png;base64," + bytes(buffer.data().toBase64()).decode("ascii"))
|
||||
|
||||
doctor_signature, review_signature = signatures
|
||||
rendered = render_prescription_html({
|
||||
"doctor_signature": doctor_signature,
|
||||
"esign": {
|
||||
"status": "signed",
|
||||
"review_signer_name": "张药师",
|
||||
"review_signature_time": 1795000017,
|
||||
"review_signature": review_signature,
|
||||
},
|
||||
}, variant=variant, print_layout=print_layout)
|
||||
width, height = expected_size
|
||||
for signature in signatures:
|
||||
assert f'src="{signature}" width="{width}" height="{height}"' in rendered
|
||||
|
||||
document = QTextDocument()
|
||||
document.setHtml(rendered)
|
||||
signature_sizes = {}
|
||||
block = document.begin()
|
||||
while block.isValid():
|
||||
fragments = block.begin()
|
||||
while not fragments.atEnd():
|
||||
image_format = fragments.fragment().charFormat().toImageFormat()
|
||||
if image_format.name() in signatures:
|
||||
signature_sizes[image_format.name()] = (image_format.width(), image_format.height())
|
||||
fragments += 1
|
||||
block = block.next()
|
||||
assert signature_sizes == dict.fromkeys(signatures, expected_size)
|
||||
|
||||
|
||||
def test_signing_preview_uses_full_seed_and_updates_visible_signatures(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
) -> None:
|
||||
def unexpected_detail(prescription_id: int) -> None:
|
||||
pytest.fail(f"Complete prescription {prescription_id} should not be reloaded")
|
||||
|
||||
prescription = Prescription.from_dict({
|
||||
"id": 71,
|
||||
"patient_name": "虚构患者",
|
||||
"clinical_diagnosis": "测试诊断",
|
||||
"prescription_type": "饮片",
|
||||
"dosage_amount": 20,
|
||||
"dosage_unit": "ml",
|
||||
"dose_count": 3,
|
||||
"herbs": [{"name": "白术", "dosage": 6}],
|
||||
"esign": {"status": "pending"},
|
||||
})
|
||||
preview = PrescriptionSigningPreview(SimpleNamespace(get_prescription=unexpected_detail), prescription)
|
||||
assert preview.paper is not None and preview.paper.isReadOnly()
|
||||
assert preview.paper._watermark_text == "处方联"
|
||||
document = preview.paper.document()
|
||||
for text in ("虚构患者", "测试诊断", "白术", "6克", "天数"):
|
||||
assert text in document.toPlainText()
|
||||
assert "药房联" not in document.toPlainText() and "18克" not in document.toPlainText()
|
||||
|
||||
def days_text(**fields: Any) -> str:
|
||||
data = {"id": 72, "patient_name": "虚构患者", "prescription_type": "浓缩水丸",
|
||||
"herbs": [{"name": "白术", "dosage": 6}], "esign": {"status": "pending"}, **fields}
|
||||
slip = PrescriptionSigningPreview(SimpleNamespace(get_prescription=unexpected_detail), Prescription.from_dict(data))
|
||||
text = slip.paper.document().toPlainText()
|
||||
return text[text.index("天数"):text.index("天数") + 12]
|
||||
|
||||
# RX202611279682:剂数为默认 1、服用天数 14,笺面天数应为 14 天,剂数不能当天数。
|
||||
assert "14 天" in days_text(usage_days=14, dose_count=1)
|
||||
assert "30 天" in days_text(medication_days=30, usage_days=14, dose_count=1)
|
||||
assert "—" in days_text(dose_count=1) and "1 天" not in days_text(dose_count=1)
|
||||
|
||||
revision = document.revision()
|
||||
preview.set_esign_state({"status": "pending", "message": "等待核验"})
|
||||
assert document.revision() == revision
|
||||
signed = {
|
||||
"status": "signed",
|
||||
"doctor_signer_name": "签名医生",
|
||||
"review_signer_name": "审核药师姓名",
|
||||
"review_signature_time": 1795000017,
|
||||
}
|
||||
preview.set_esign_state(signed)
|
||||
for text in ("签名医生", "审核药师姓名", "白术"):
|
||||
assert text in document.toPlainText()
|
||||
revision = document.revision()
|
||||
preview.set_esign_state(signed | {"review_signature_time": 1795000020})
|
||||
assert document.revision() == revision
|
||||
|
||||
|
||||
def test_signing_preview_adds_pharmacy_copy_and_case_record_tabs(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
) -> None:
|
||||
base = {
|
||||
"id": 72,
|
||||
"patient_name": "虚构患者",
|
||||
"clinical_diagnosis": "测试诊断",
|
||||
"herbs": [{"name": "白术", "dosage": 6}],
|
||||
"esign": {"status": "pending"},
|
||||
}
|
||||
with_case = base | {"case_record": {"patient_name": "虚构患者", "diagnosis_type": "follow_up",
|
||||
"symptoms": "口渴乏力"}}
|
||||
preview = PrescriptionSigningPreview(SimpleNamespace(), with_case)
|
||||
tabs = preview.tabs
|
||||
assert [tabs.tabText(index) for index in range(tabs.count())] == ["处方联", "药房联", "详细病历"]
|
||||
assert tabs.currentWidget() is preview.paper and preview.paper._watermark_text == "处方联"
|
||||
assert preview.pharmacy_paper is not None and preview.pharmacy_paper._watermark_text == "药房联"
|
||||
assert "白术" in preview.pharmacy_paper.toPlainText()
|
||||
assert preview.case_paper is not None and preview.case_paper.isReadOnly()
|
||||
case_text = preview.case_paper.toPlainText()
|
||||
assert "详细病历" in case_text and "口渴乏力" in case_text and "复诊" in case_text
|
||||
|
||||
signed = {"status": "signed", "doctor_signer_name": "签名医生"}
|
||||
preview.set_esign_state(signed)
|
||||
assert "签名医生" in preview.paper.toPlainText() and "签名医生" in preview.pharmacy_paper.toPlainText()
|
||||
|
||||
plain = PrescriptionSigningPreview(SimpleNamespace(), base)
|
||||
assert [plain.tabs.tabText(index) for index in range(plain.tabs.count())] == ["处方联", "药房联"]
|
||||
assert plain.case_paper is None
|
||||
|
||||
|
||||
def test_embedded_preview_loads_full_detail_and_rejects_other_diagnosis(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
) -> None:
|
||||
calls: list[int] = []
|
||||
|
||||
def detail(prescription_id: int) -> dict[str, Any]:
|
||||
calls.append(prescription_id)
|
||||
return {"id": prescription_id, "diagnosis_id": 9, "patient_name": "虚构患者",
|
||||
"herbs": [{"name": "白术", "dosage": 6}], "case_record": {"symptoms": "口渴乏力"},
|
||||
"esign": {"status": "pending"}}
|
||||
|
||||
repository = SimpleNamespace(get_prescription=detail, update_prescription=lambda *_args, **_kwargs: None)
|
||||
summary_row = {"id": 5, "diagnosis_id": 9, "herbs": [{"name": "白术", "dosage": 6}]}
|
||||
preview = PrescriptionSigningPreview(repository, summary_row, editable=False, load_detail=True, diagnosis_id=9)
|
||||
assert calls == [5] and preview.prescription_id == 5
|
||||
assert [preview.tabs.tabText(index) for index in range(preview.tabs.count())] == ["处方联", "药房联", "详细病历"]
|
||||
assert preview.edit_button.isHidden()
|
||||
|
||||
other = PrescriptionSigningPreview(repository, {"id": 6}, editable=False, load_detail=True, diagnosis_id=8)
|
||||
assert calls == [5, 6] and other.paper is None and other.tabs.isHidden()
|
||||
assert "不属于当前诊单" in other.status_label.text()
|
||||
|
||||
|
||||
def test_signing_preview_retries_wrong_detail_and_ignores_stale_response(
|
||||
application: QApplication,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
requests = []
|
||||
|
||||
def defer_detail(function: Any, prescription_id: int, *, on_success: Any, on_error: Any) -> None:
|
||||
requests.append((prescription_id, on_success))
|
||||
|
||||
monkeypatch.setattr(dialog_module, "run_async", defer_detail)
|
||||
seed = {"id": 72, "esign": {"status": "pending"}}
|
||||
repository = SimpleNamespace(get_prescription=lambda _prescription_id: None)
|
||||
preview = PrescriptionSigningPreview(repository, seed)
|
||||
assert "正在加载" in preview.status_label.text()
|
||||
assert requests[0][0] == 72
|
||||
preview.set_esign_state({"status": "signed", "doctor_signer_name": "签名医生"})
|
||||
|
||||
herbs = [{"name": "甘草", "dosage": 3}]
|
||||
requests[0][1]({"id": 73, "patient_name": "其他患者", "herbs": herbs})
|
||||
assert preview.paper is None
|
||||
assert "不匹配" in preview.status_label.text() and not preview.retry_button.isHidden()
|
||||
preview.retry_button.click()
|
||||
assert requests[1][0] == 72
|
||||
requests[0][1](seed | {"patient_name": "过时结果", "herbs": herbs})
|
||||
assert preview.paper is None
|
||||
requests[1][1](seed | {"patient_name": "当前患者", "herbs": herbs})
|
||||
assert preview.paper is not None
|
||||
text = preview.paper.toPlainText()
|
||||
assert "当前患者" in text and "甘草\n3克" in text and "签名医生" in text
|
||||
|
||||
|
||||
def test_signing_preview_edits_prescription_until_signing_starts(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
herbs = [{"name": "白术", "dosage": 6}]
|
||||
detail = {"id": 74, "patient_name": "原患者", "audit_status": 0, "herbs": herbs}
|
||||
updates: list[tuple[int, dict[str, Any]]] = []
|
||||
editors: list[dict[str, Any]] = []
|
||||
|
||||
def update(prescription_id: int, *, changes: dict[str, Any]) -> dict[str, Any]:
|
||||
updates.append((prescription_id, changes))
|
||||
detail["patient_name"] = changes["patient_name"]
|
||||
return {"id": prescription_id, **changes}
|
||||
|
||||
class FakeEditor:
|
||||
def __init__(self, _repository: Any, prescription: Any, *, mode: str, save_draft: Any, **_kwargs: Any) -> None:
|
||||
assert mode == "edit"
|
||||
editors.append(prescription)
|
||||
self.save_draft = save_draft
|
||||
self.saved_draft = None
|
||||
|
||||
def exec(self) -> QDialog.DialogCode:
|
||||
self.saved_draft = self.save_draft({"patient_name": "修改后患者"})
|
||||
return QDialog.DialogCode.Accepted
|
||||
|
||||
def payload(self) -> dict[str, Any]:
|
||||
return {}
|
||||
|
||||
def deleteLater(self) -> None: # noqa: N802 - Qt compatibility
|
||||
pass
|
||||
|
||||
monkeypatch.setattr(dialog_module, "PrescriptionEditorDialog", FakeEditor)
|
||||
repository = SimpleNamespace(get_prescription=lambda _id: dict(detail), update_prescription=update)
|
||||
preview = PrescriptionSigningPreview(repository, {"id": 74, "esign": {"required": True, "status": "pending"}})
|
||||
saved: list[Any] = []
|
||||
preview.prescription_saved.connect(saved.append)
|
||||
assert not preview.edit_button.isHidden() and not preview.edit_button.isEnabled()
|
||||
preview.set_edit_allowed(True)
|
||||
assert preview.edit_button.isEnabled()
|
||||
|
||||
preview.edit_button.click()
|
||||
assert updates == [(74, {"patient_name": "修改后患者"})]
|
||||
assert editors[0]["patient_name"] == "原患者" and editors[0]["esign"]["status"] == "pending"
|
||||
assert saved and "修改后患者" in preview.paper.toPlainText()
|
||||
|
||||
preview.set_esign_state({"required": True, "status": "authenticating"})
|
||||
assert preview.edit_button.isHidden()
|
||||
preview.set_esign_state({"required": True, "status": "pending"})
|
||||
preview.set_edit_allowed(False)
|
||||
assert not preview.edit_button.isHidden() and not preview.edit_button.isEnabled()
|
||||
|
||||
|
||||
def test_signing_preview_renders_an_intentionally_empty_saved_prescription(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
) -> None:
|
||||
prescription = Prescription.from_dict({
|
||||
"id": 73,
|
||||
"patient_name": "虚构患者",
|
||||
"clinical_diagnosis": "系统代开诊断",
|
||||
"is_system_auto": 1,
|
||||
"herbs": [],
|
||||
})
|
||||
preview = PrescriptionSigningPreview(
|
||||
SimpleNamespace(get_prescription=lambda _prescription_id: prescription),
|
||||
{"id": 73},
|
||||
)
|
||||
assert preview.paper is not None
|
||||
for text in ("虚构患者", "系统代开诊断", "暂无药材明细"):
|
||||
assert text in preview.paper.toPlainText()
|
||||
|
||||
|
||||
def test_unsigned_draft_shows_signing_state_before_audit() -> None:
|
||||
row = {"id": 71, "audit_status": 0, "esign": {"required": True, "status": "pending"}}
|
||||
assert prescription_status(row) == ("待签名", "warning")
|
||||
assert not can_audit(row)
|
||||
row["esign"]["status"] = "signed"
|
||||
assert prescription_status(row) == ("待审核", "warning")
|
||||
assert can_audit(row)
|
||||
|
||||
|
||||
def test_prescription_workflows_never_show_orphan_child_controls(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
@@ -602,7 +1085,8 @@ def test_editor_matches_admin_four_observation_fields_and_edit_context(
|
||||
assert editor.windowTitle() == "编辑处方"
|
||||
assert editor.patient_name.isReadOnly()
|
||||
assert editor.visit_no.isReadOnly()
|
||||
assert not hasattr(editor, "phone")
|
||||
# 已开处方编辑可修改手机号与身份证号(姓名、门诊号仍只读)。
|
||||
assert not editor.phone.isReadOnly() and not editor.id_card.isReadOnly()
|
||||
assert editor.gender_male.isChecked()
|
||||
assert editor.payload()["gender"] == 1
|
||||
assert editor.tongue.text() == "面象哨兵"
|
||||
@@ -898,7 +1382,7 @@ def test_order_payload_and_a4_print_document(
|
||||
assert "辅方" in rendered
|
||||
assert "105克" in rendered
|
||||
assert "84克" in rendered
|
||||
assert "剂量:</span> 27克" in rendered
|
||||
assert "剂量:</span> 27克" in rendered
|
||||
assert "每天2次, 一次2袋, 每袋5g, 温水送服, 饭后" in rendered
|
||||
assert "主服法:" in rendered
|
||||
assert "辅服法:" in rendered
|
||||
@@ -918,7 +1402,7 @@ def test_order_payload_and_a4_print_document(
|
||||
document_html = viewer.document.toHtml()
|
||||
assert "用药 (单剂)" in document_html
|
||||
assert viewer.preview.__class__.__name__ == "_PrescriptionPaperPreview"
|
||||
assert [viewer.tabs.tabText(index) for index in range(2)] == ["药房联", "处方联"]
|
||||
assert [viewer.tabs.tabText(index) for index in range(2)] == ["处方联", "药房联"]
|
||||
viewer.close()
|
||||
order.close()
|
||||
application.processEvents()
|
||||
@@ -929,6 +1413,7 @@ def test_prescription_pdf_export_writes_visible_content(
|
||||
tmp_path: Any,
|
||||
) -> None:
|
||||
prescription = {
|
||||
"esign": {"enabled": False, "required": False, "environment": "sandbox", "status": "legacy", "can_sign": False, "can_download": False},
|
||||
"id": 12,
|
||||
"sn": "CF-12",
|
||||
"patient_name": "林晓岚",
|
||||
@@ -1004,8 +1489,8 @@ def test_prescription_detail_can_open_immutable_case_record_tab(
|
||||
viewer = PrescriptionDetailDialog(prescription, initial_tab="case")
|
||||
|
||||
assert viewer.tabs.count() == 3
|
||||
assert viewer.tabs.tabText(0) == "药房联"
|
||||
assert viewer.tabs.tabText(1) == "处方联"
|
||||
assert viewer.tabs.tabText(0) == "处方联"
|
||||
assert viewer.tabs.tabText(1) == "药房联"
|
||||
assert viewer.tabs.tabText(viewer.tabs.currentIndex()) == "详细病历"
|
||||
assert viewer.case_document is not None
|
||||
case_html = viewer.case_document.toHtml()
|
||||
@@ -1022,6 +1507,28 @@ def test_prescription_detail_can_open_immutable_case_record_tab(
|
||||
application.processEvents()
|
||||
|
||||
|
||||
def test_prescription_detail_uses_signing_workspace_layout(application: QApplication) -> None:
|
||||
signed = {"enabled": True, "required": True, "environment": "sandbox", "status": "signed",
|
||||
"status_label": "已签署", "message": "", "can_sign": False, "can_download": True}
|
||||
viewer = PrescriptionDetailDialog({
|
||||
"id": 12, "patient_name": "林晓岚", "sn": "RX202611270001",
|
||||
"herbs": [{"name": "白术", "dosage": 6}], "esign": signed,
|
||||
})
|
||||
assert viewer.workspace_splitter.widget(1) is viewer.workflow_panel
|
||||
assert viewer.tabs.currentWidget() is viewer.user_preview
|
||||
assert not viewer.steps.isHidden()
|
||||
steps = {label.text(): label.accessibleDescription() for label in viewer.step_labels if not label.isHidden()}
|
||||
assert steps["保存草稿"] == "已完成" and steps["医生签署"] == "已完成"
|
||||
assert viewer.pdf_button.text() == "下载已签原件" and viewer.pdf_button.property("variant") == "primary"
|
||||
assert viewer.esign_button.property("variant") is None
|
||||
viewer.close()
|
||||
|
||||
unconfirmed = PrescriptionDetailDialog({"id": 13, "herbs": [{"name": "白术", "dosage": 6}]})
|
||||
assert unconfirmed.steps.isHidden()
|
||||
unconfirmed.close()
|
||||
application.processEvents()
|
||||
|
||||
|
||||
def test_case_record_translates_snapshot_dictionary_codes_to_chinese() -> None:
|
||||
# 处方快照存的是开方当时的原始 code,没有后端补的 *_text。
|
||||
prescription = {
|
||||
@@ -1134,3 +1641,20 @@ def test_demo_repository_pages_render_offscreen(
|
||||
library.close()
|
||||
issued.close()
|
||||
application.processEvents()
|
||||
|
||||
|
||||
def test_voided_prescriptions_can_be_reissued_by_any_prescriber() -> None:
|
||||
from doctor_workstation.ui.dialogs.prescription import can_reissue_prescription, prescription_phone_error
|
||||
|
||||
voided_by_admin = {"id": 14011, "creator_id": 117, "void_status": 1}
|
||||
prescriber = {"tcm.diagnosis/kaifang"}
|
||||
# 原方子作废后(含他人所开、他人作废)有开方权限即可重新开方;未作废或无开方权限不行。
|
||||
assert can_reissue_prescription(voided_by_admin, SimpleNamespace(id=1), prescriber)
|
||||
assert can_reissue_prescription(voided_by_admin, SimpleNamespace(id=117), prescriber)
|
||||
assert not can_reissue_prescription({**voided_by_admin, "void_status": 0}, SimpleNamespace(id=117), prescriber)
|
||||
assert not can_reissue_prescription(voided_by_admin, SimpleNamespace(id=1), {"cf.prescription/read"})
|
||||
|
||||
for valid in ("", "13800138000", "0571-88888888", "01088888888"):
|
||||
assert prescription_phone_error(valid) == ""
|
||||
for invalid in ("c", "1380013800", "23800138000", "138001380001", "0571-888"):
|
||||
assert "手机号格式不正确" in prescription_phone_error(invalid)
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user