Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4cc37531a1 | ||
|
|
621b7ddd39 | ||
|
|
630318b9ca | ||
|
|
7c916d8053 | ||
|
|
c22be5d586 | ||
|
|
6ef56bd8fb | ||
|
|
82a91858f9 | ||
|
|
954e6f00d0 | ||
|
|
b8f66e2b00 | ||
|
|
dfe5768cd2 | ||
|
|
3451f43c22 | ||
|
|
90b9fff76a | ||
|
|
dc5467cfa7 | ||
|
|
e825109d90 | ||
|
|
00bad051da | ||
|
|
2019f9dca1 | ||
|
|
e4d788ed32 | ||
|
|
301c04ca90 | ||
|
|
be79e09c83 | ||
|
|
db6d327e91 | ||
|
|
0dc41a1507 | ||
|
|
378bf32069 |
@@ -16,7 +16,15 @@
|
|||||||
"Bash(git *)",
|
"Bash(git *)",
|
||||||
"Bash(tail -c 100000 /Users/long/.claude/projects/-Users-long-Work-zyt/7be9f770-afc3-497d-87a3-2ffa1fbe3fd1.jsonl)",
|
"Bash(tail -c 100000 /Users/long/.claude/projects/-Users-long-Work-zyt/7be9f770-afc3-497d-87a3-2ffa1fbe3fd1.jsonl)",
|
||||||
"Read(//tmp/**)",
|
"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
|
/.codex
|
||||||
/.agents
|
/.agents
|
||||||
/server/.spool
|
/server/.spool
|
||||||
|
/server/storage/esign/
|
||||||
|
/server/.env.esign.local
|
||||||
# Generated ancient-books search indexes; the source corpus is tracked.
|
# Generated ancient-books search indexes; the source corpus is tracked.
|
||||||
/server/knowledge/tcm-ancient-books-index.json
|
/server/knowledge/tcm-ancient-books-index.json
|
||||||
/server/knowledge/tcm-ancient-books-index/
|
/server/knowledge/tcm-ancient-books-index/
|
||||||
|
|||||||
@@ -272,10 +272,17 @@ const { proxy } = getCurrentInstance()
|
|||||||
let targetUserID = '';
|
let targetUserID = '';
|
||||||
let currentUserID = ''; // 当前登录用户ID
|
let currentUserID = ''; // 当前登录用户ID
|
||||||
let scrollTimer = null; // 滚动定时器
|
let scrollTimer = null; // 滚动定时器
|
||||||
/** 微信小程序:从系统后台回前台时刷新 IM/TUICall,避免无法接通视频 */
|
/** 微信小程序:从系统后台回前台时检查 IM/TUICall 链路,异常时才重建 */
|
||||||
let unsubscribeWxAppShow = null;
|
let wxAppShowHandler = null;
|
||||||
let allowChatForegroundRelogin = false;
|
let allowChatForegroundRelogin = false;
|
||||||
let foregroundReloginTimer = null;
|
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 重复上报离开 */
|
/** 避免 onUnload 重复上报离开 */
|
||||||
let patientLeaveNotified = false;
|
let patientLeaveNotified = false;
|
||||||
|
|
||||||
@@ -569,8 +576,44 @@ const { proxy } = getCurrentInstance()
|
|||||||
uni.setStorageSync('CallManager', userId)
|
uni.setStorageSync('CallManager', userId)
|
||||||
// TUICallKit 必须在 TIM chat 登录成功后再 init,且必须传入 tim,否则无法接收通话信令(聊天正常、视频接不到)
|
// 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 收发自定义信令) */
|
/** 与当前页 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 app = getApp();
|
||||||
const sdkAppID = app.globalData.SDKAppID;
|
const sdkAppID = app.globalData.SDKAppID;
|
||||||
const userSig = app.globalData.userSig;
|
const userSig = app.globalData.userSig;
|
||||||
@@ -580,6 +623,17 @@ const { proxy } = getCurrentInstance()
|
|||||||
console.warn('initTUICallKitWithTim: 缺少 im / SDKAppID / userSig / userID');
|
console.warn('initTUICallKitWithTim: 缺少 im / SDKAppID / userSig / userID');
|
||||||
return;
|
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、接不到来电
|
// 非 IDLE 时 destroyed 会抛错,随后 _doInit 会因旧 engine 仍存在而直接 return,导致未绑定新 tim、接不到来电
|
||||||
try {
|
try {
|
||||||
await TUICallKitAPI.handleExceptionExit();
|
await TUICallKitAPI.handleExceptionExit();
|
||||||
@@ -597,13 +651,20 @@ const { proxy } = getCurrentInstance()
|
|||||||
console.warn('CallManager.destroyed retry:', e2);
|
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({
|
await uni.CallManager.init({
|
||||||
sdkAppID: Number(sdkAppID),
|
sdkAppID: Number(sdkAppID),
|
||||||
userID,
|
userID,
|
||||||
userSig,
|
userSig,
|
||||||
globalCallPagePath: 'TUICallKit/src/Components/TUICallKit',
|
globalCallPagePath: CALL_PAGE_ROUTE,
|
||||||
tim: imChat
|
tim: imChat
|
||||||
});
|
});
|
||||||
|
callKitBoundChat = imChat;
|
||||||
}
|
}
|
||||||
onLoad(async (options) => {
|
onLoad(async (options) => {
|
||||||
try {
|
try {
|
||||||
@@ -717,8 +778,8 @@ const { proxy } = getCurrentInstance()
|
|||||||
chat.on(TencentCloudChat.EVENT.MESSAGE_RECEIVED, onMessageReceived);
|
chat.on(TencentCloudChat.EVENT.MESSAGE_RECEIVED, onMessageReceived);
|
||||||
}
|
}
|
||||||
|
|
||||||
await initTUICallKitWithTim(chat);
|
await initTUICallKitWithTim(chat, { force: true });
|
||||||
|
|
||||||
await loadHistoryMessages();
|
await loadHistoryMessages();
|
||||||
|
|
||||||
// 打开会话时通知医生(IM自定义消息 + 后端全局事件)
|
// 打开会话时通知医生(IM自定义消息 + 后端全局事件)
|
||||||
@@ -737,18 +798,20 @@ const { proxy } = getCurrentInstance()
|
|||||||
//uni.showToast({ title: '聊天已就绪', icon: 'success' });
|
//uni.showToast({ title: '聊天已就绪', icon: 'success' });
|
||||||
|
|
||||||
// #ifdef MP-WEIXIN
|
// #ifdef MP-WEIXIN
|
||||||
// 系统级前后台切换时页面 onShow 不一定等价于「回前台」,用 wx.onAppShow 刷新音视频信令链路
|
// 系统级前后台切换时页面 onShow 不一定等价于「回前台」,用 wx.onAppShow 检查音视频信令链路
|
||||||
|
// 注意 wx.onAppShow 不返回取消函数,必须保存回调引用,卸载时用 wx.offAppShow 移除
|
||||||
if (typeof wx !== 'undefined' && wx.onAppShow) {
|
if (typeof wx !== 'undefined' && wx.onAppShow) {
|
||||||
unsubscribeWxAppShow = wx.onAppShow(() => {
|
wxAppShowHandler = () => {
|
||||||
if (!allowChatForegroundRelogin) return;
|
if (!allowChatForegroundRelogin) return;
|
||||||
const pages = getCurrentPages();
|
const pages = getCurrentPages();
|
||||||
const top = pages[pages.length - 1];
|
const top = pages[pages.length - 1];
|
||||||
if (!(top?.route || '').includes('pages/chat/chat')) return;
|
if (!(top?.route || '').includes('pages/chat/chat')) return;
|
||||||
reloginAfterMiniProgramForeground();
|
reloginAfterMiniProgramForeground();
|
||||||
});
|
};
|
||||||
|
wx.onAppShow(wxAppShowHandler);
|
||||||
}
|
}
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
allowChatForegroundRelogin = true;
|
if (!pageUnloaded) allowChatForegroundRelogin = true;
|
||||||
}, 800);
|
}, 800);
|
||||||
// #endif
|
// #endif
|
||||||
|
|
||||||
@@ -793,11 +856,12 @@ const { proxy } = getCurrentInstance()
|
|||||||
void notifyDoctorOnChatClose();
|
void notifyDoctorOnChatClose();
|
||||||
}
|
}
|
||||||
allowChatForegroundRelogin = false;
|
allowChatForegroundRelogin = false;
|
||||||
|
pageUnloaded = true;
|
||||||
// #ifdef MP-WEIXIN
|
// #ifdef MP-WEIXIN
|
||||||
if (typeof unsubscribeWxAppShow === 'function') {
|
if (wxAppShowHandler && typeof wx !== 'undefined' && wx.offAppShow) {
|
||||||
unsubscribeWxAppShow();
|
wx.offAppShow(wxAppShowHandler);
|
||||||
unsubscribeWxAppShow = null;
|
|
||||||
}
|
}
|
||||||
|
wxAppShowHandler = null;
|
||||||
// #endif
|
// #endif
|
||||||
if (foregroundReloginTimer) {
|
if (foregroundReloginTimer) {
|
||||||
clearTimeout(foregroundReloginTimer);
|
clearTimeout(foregroundReloginTimer);
|
||||||
@@ -1071,8 +1135,16 @@ const { proxy } = getCurrentInstance()
|
|||||||
return m ? parseInt(m[1], 10) : null;
|
return m ? parseInt(m[1], 10) : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 拉取最新 userSig 并重新登录 IM,必要时重建 chat 实例(与 onLoad 逻辑一致) */
|
/** 拉取最新 userSig 并重新登录 IM,必要时重建 chat 实例(与 onLoad 逻辑一致);并发调用合并为一次 */
|
||||||
async function reloginIMChat() {
|
function reloginIMChat() {
|
||||||
|
if (!reloginTask) {
|
||||||
|
reloginTask = doReloginIMChat().finally(() => {
|
||||||
|
reloginTask = null;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return reloginTask;
|
||||||
|
}
|
||||||
|
async function doReloginIMChat() {
|
||||||
const app = getApp();
|
const app = getApp();
|
||||||
await video(currentUserID);
|
await video(currentUserID);
|
||||||
const userSig = app.globalData.userSig;
|
const userSig = app.globalData.userSig;
|
||||||
@@ -1084,6 +1156,10 @@ const { proxy } = getCurrentInstance()
|
|||||||
if (!chat) {
|
if (!chat) {
|
||||||
throw new Error('IM 未初始化');
|
throw new Error('IM 未初始化');
|
||||||
}
|
}
|
||||||
|
// 拉 userSig 期间可能来电:此时登出 IM 会让来电信令中断,必须放弃
|
||||||
|
if (!isCallIdle()) {
|
||||||
|
throw new Error('通话进行中,暂不重登 IM');
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
chat.off(TencentCloudChat.EVENT.MESSAGE_RECEIVED, onMessageReceived);
|
chat.off(TencentCloudChat.EVENT.MESSAGE_RECEIVED, onMessageReceived);
|
||||||
} catch (_) {}
|
} catch (_) {}
|
||||||
@@ -1122,25 +1198,51 @@ const { proxy } = getCurrentInstance()
|
|||||||
await initTUICallKitWithTim(chat);
|
await initTUICallKitWithTim(chat);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 小程序切后台再回前台:拉取新 UserSig 并重登 IM、重绑 TUICallEngine(与发消息失败时的 relogin 一致) */
|
/**
|
||||||
async function reloginAfterMiniProgramForeground() {
|
* 小程序切后台再回前台:IM SDK 会自行重连并补收后台期间的来电信令。
|
||||||
|
* 以前这里无条件「登出 IM → 重登 → 销毁并重建 TUICallEngine」,重建窗口内(拉 userSig + IM 重登 + 引擎登录,
|
||||||
|
* 弱网下数秒)医生的呼叫会丢失,刚补收到的来电也会被重绑流程 reject;所以现在只在链路确实坏了时才重建。
|
||||||
|
*/
|
||||||
|
function reloginAfterMiniProgramForeground() {
|
||||||
if (!chat || !currentUserID) return;
|
if (!chat || !currentUserID) return;
|
||||||
if (foregroundReloginTimer) clearTimeout(foregroundReloginTimer);
|
if (foregroundReloginTimer) clearTimeout(foregroundReloginTimer);
|
||||||
foregroundReloginTimer = setTimeout(async () => {
|
foregroundReloginTimer = setTimeout(async () => {
|
||||||
foregroundReloginTimer = null;
|
foregroundReloginTimer = null;
|
||||||
// reloginIMChat 会先 IM logout 再 initTUICallKit;若非 IDLE,destroyed 会失败且 IM 已断开,故仅 IDLE 时刷新
|
|
||||||
try {
|
try {
|
||||||
const status = TUIStore?.getData?.(StoreName.CALL, NAME.CALL_STATUS);
|
if (!isCallIdle()) {
|
||||||
if (status != null && status !== CallStatus.IDLE) {
|
// 来电信令在后台到达时,跳转通话页的 navigateTo 可能失败,回前台后补跳,否则患者看不到来电
|
||||||
console.warn('前台恢复: 通话未结束,跳过 IM/TUICall 重绑');
|
ensureCallPageVisible();
|
||||||
return;
|
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) {
|
} catch (e) {
|
||||||
console.warn('前台恢复后 IM/TUICall 刷新失败:', e);
|
console.warn('前台恢复后 IM/TUICall 刷新失败:', e);
|
||||||
}
|
}
|
||||||
}, 400);
|
}, 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() {
|
async function sendTextMessage() {
|
||||||
if (!inputText.value.trim()) return;
|
if (!inputText.value.trim()) return;
|
||||||
|
|||||||
@@ -39,7 +39,6 @@ export function myPatientOrderEdit(params: Record<string, unknown>) {
|
|||||||
export function myPatientOrderAuditPrescription(params: {
|
export function myPatientOrderAuditPrescription(params: {
|
||||||
id: number
|
id: number
|
||||||
action: 'approve' | 'reject'
|
action: 'approve' | 'reject'
|
||||||
signature: string
|
|
||||||
remark?: string
|
remark?: string
|
||||||
}) {
|
}) {
|
||||||
return request.post({ url: '/firstvisit.myPatient/orderAuditPrescription', params })
|
return request.post({ url: '/firstvisit.myPatient/orderAuditPrescription', params })
|
||||||
|
|||||||
@@ -27,3 +27,8 @@ export function adminDelete(params: any) {
|
|||||||
export function adminDetail(params: any) {
|
export function adminDetail(params: any) {
|
||||||
return request.get({ url: '/auth.admin/detail', params })
|
return request.get({ url: '/auth.admin/detail', params })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 解除管理员的电子签署身份
|
||||||
|
export function adminEsignUnbind(params: { id: number }) {
|
||||||
|
return request.post({ url: '/auth.admin/esignUnbind', params })
|
||||||
|
}
|
||||||
|
|||||||
@@ -10,6 +10,18 @@ export function systemLogLists(params: any) {
|
|||||||
return request.get({ url: '/setting.system.log/lists', params }, { ignoreCancelToken: true })
|
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() {
|
export function systemCacheClear() {
|
||||||
return request.post({ url: '/setting.system.cache/clear' })
|
return request.post({ url: '/setting.system.cache/clear' })
|
||||||
|
|||||||
+189
-6
@@ -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) {
|
export function prescriptionLists(params: any) {
|
||||||
return request.get({ url: '/tcm.prescription/lists', params })
|
return request.get({ url: '/tcm.prescription/lists', params })
|
||||||
@@ -404,8 +582,8 @@ export function prescriptionDelete(params: { id: number }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 处方详情
|
// 处方详情
|
||||||
export function prescriptionDetail(params: { id: number; prescription_order_id?: number }) {
|
export function prescriptionDetail(params: { id: number }, signal?: AbortSignal) {
|
||||||
return request.get({ url: '/tcm.prescription/detail', params })
|
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 })
|
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(驳回同时作废处方) */
|
/** 处方审核:action approve | reject(驳回同时作废处方) */
|
||||||
export function prescriptionAudit(params: {
|
export function prescriptionAudit(params: {
|
||||||
id: number
|
id: number
|
||||||
@@ -524,7 +709,6 @@ export function prescriptionOrderPatchPrescriptionUsage(params: {
|
|||||||
export function prescriptionOrderAuditPrescription(params: {
|
export function prescriptionOrderAuditPrescription(params: {
|
||||||
id: number
|
id: number
|
||||||
action: 'approve' | 'reject'
|
action: 'approve' | 'reject'
|
||||||
signature: string
|
|
||||||
remark?: string
|
remark?: string
|
||||||
}) {
|
}) {
|
||||||
return request.post({ url: '/tcm.prescriptionOrder/auditPrescription', params })
|
return request.post({ url: '/tcm.prescriptionOrder/auditPrescription', params })
|
||||||
@@ -643,7 +827,6 @@ export function prescriptionOrderAddLog(params: {
|
|||||||
payment_slip_audit_status?: number | ''
|
payment_slip_audit_status?: number | ''
|
||||||
prescription_audit_remark?: string
|
prescription_audit_remark?: string
|
||||||
payment_slip_audit_remark?: string
|
payment_slip_audit_remark?: string
|
||||||
signature?: string
|
|
||||||
}) {
|
}) {
|
||||||
return request.post({ url: '/tcm.prescriptionOrder/addLog', params })
|
return request.post({ url: '/tcm.prescriptionOrder/addLog', params })
|
||||||
}
|
}
|
||||||
@@ -665,7 +848,7 @@ export function prescriptionOrderSetShipMode(params: { id: number; ship_mode: 'g
|
|||||||
|
|
||||||
// ========== 处方库 ==========
|
// ========== 处方库 ==========
|
||||||
|
|
||||||
export type PrescriptionAiProfile = 'qwen' | 'openai'
|
export type PrescriptionAiProfile = 'qwen' | 'openai' | 'doubao'
|
||||||
|
|
||||||
export interface PrescriptionLibraryHerb {
|
export interface PrescriptionLibraryHerb {
|
||||||
medicine_id?: number
|
medicine_id?: number
|
||||||
|
|||||||
@@ -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>
|
<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-title">{{ isInternal ? '药房联' : slipTitle }}</div>
|
||||||
<div class="rx-notice">
|
<div class="rx-notice">
|
||||||
<span class="rx-notice-text">
|
<span class="rx-notice-text">
|
||||||
@@ -154,29 +154,34 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="rx-bottom">
|
<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-cell rx-bot-doctor">
|
||||||
<div class="rx-bot-doctor-line">
|
<div class="rx-bot-label rx-bot-label--inline">医师</div>
|
||||||
<div class="rx-bot-label rx-bot-label--doctor">医师</div>
|
<div class="rx-bot-doctor-body">
|
||||||
<div class="rx-bot-doctor-body">
|
<img
|
||||||
<img
|
v-if="doctorSignature"
|
||||||
v-if="data?.doctor_signature"
|
:src="doctorSignature"
|
||||||
:src="data.doctor_signature"
|
:alt="doctorName"
|
||||||
alt="医师签名"
|
class="rx-bot-sign-img"
|
||||||
class="rx-bot-sign-img"
|
@error="onDoctorSignatureError"
|
||||||
/>
|
/>
|
||||||
<span v-if="!data?.doctor_signature" class="rx-bot-doctor-name">
|
<span v-else class="rx-bot-doctor-name">{{ doctorName }}</span>
|
||||||
{{ data?.doctor_name || '—' }}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div v-if="pharmacistSignature" class="rx-bot-pharmacist">
|
|
||||||
<div class="rx-bot-pharmacist-line">
|
|
||||||
<span class="rx-bot-label rx-bot-label--doctor">药师</span>
|
|
||||||
<img :src="pharmacistSignature" alt="药师签名" class="rx-bot-sign-img rx-bot-pharmacist-signature" />
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</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-if="isInternal" class="rx-bot-cell rx-bot-meta">
|
<div v-if="isInternal" class="rx-bot-cell rx-bot-meta">
|
||||||
<span class="rx-bot-meta-key">类型:</span>
|
<span class="rx-bot-meta-key">类型:</span>
|
||||||
<span class="rx-bot-meta-val">{{ typeText }}</span>
|
<span class="rx-bot-meta-val">{{ typeText }}</span>
|
||||||
@@ -200,6 +205,7 @@
|
|||||||
|
|
||||||
<script lang="ts" setup>
|
<script lang="ts" setup>
|
||||||
import { computed, ref } from 'vue'
|
import { computed, ref } from 'vue'
|
||||||
|
import type { PrescriptionEsignStatus } from '@/api/tcm'
|
||||||
import {
|
import {
|
||||||
getAuxHerbs,
|
getAuxHerbs,
|
||||||
getMainHerbs,
|
getMainHerbs,
|
||||||
@@ -212,7 +218,6 @@ import {
|
|||||||
rxOutPelletText,
|
rxOutPelletText,
|
||||||
rxPerDoseAmount,
|
rxPerDoseAmount,
|
||||||
rxPharmacyRemarkText,
|
rxPharmacyRemarkText,
|
||||||
rxPharmacistSignature,
|
|
||||||
rxPrescriptionSnText,
|
rxPrescriptionSnText,
|
||||||
rxRecipientText,
|
rxRecipientText,
|
||||||
rxRemarkText,
|
rxRemarkText,
|
||||||
@@ -235,6 +240,7 @@ const props = withDefaults(
|
|||||||
auxLibraryName?: string
|
auxLibraryName?: string
|
||||||
/** 抬头(处方联) */
|
/** 抬头(处方联) */
|
||||||
title?: string
|
title?: string
|
||||||
|
compact?: boolean
|
||||||
}>(),
|
}>(),
|
||||||
{
|
{
|
||||||
variant: 'internal',
|
variant: 'internal',
|
||||||
@@ -246,7 +252,45 @@ const props = withDefaults(
|
|||||||
const paperRef = ref<HTMLElement | null>(null)
|
const paperRef = ref<HTMLElement | null>(null)
|
||||||
const isInternal = computed(() => props.variant !== 'user')
|
const isInternal = computed(() => props.variant !== 'user')
|
||||||
const slipTitle = computed(() => props.title || '成都双流甄养堂互联网医院 处方笺')
|
const slipTitle = computed(() => props.title || '成都双流甄养堂互联网医院 处方笺')
|
||||||
const pharmacistSignature = computed(() => rxPharmacistSignature(props.data))
|
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 : ''
|
||||||
|
})
|
||||||
|
|
||||||
|
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 dateText = computed(() => rxDateText(props.data))
|
||||||
const prescriptionSnText = computed(() => rxPrescriptionSnText(props.data))
|
const prescriptionSnText = computed(() => rxPrescriptionSnText(props.data))
|
||||||
@@ -267,13 +311,11 @@ const outPelletText = computed(() => rxOutPelletText(props.data))
|
|||||||
const typeText = computed(() => rxTypeText(props.data))
|
const typeText = computed(() => rxTypeText(props.data))
|
||||||
const perDoseAmount = computed(() => rxPerDoseAmount(props.data))
|
const perDoseAmount = computed(() => rxPerDoseAmount(props.data))
|
||||||
const daysText = computed(() => {
|
const daysText = computed(() => {
|
||||||
const md = props.data?.medication_days
|
// 订单用药天数优先,其次处方服用天数;剂数(多为默认 1)不是天数,不再顶替。
|
||||||
if (md != null && String(md).trim() !== '') {
|
for (const value of [props.data?.medication_days, props.data?.usage_days]) {
|
||||||
return `${md} 天`
|
if (value != null && String(value).trim() !== '' && Number(value) > 0) {
|
||||||
}
|
return `${value} 天`
|
||||||
const dose = props.data?.dose_count
|
}
|
||||||
if (dose != null && String(dose).trim() !== '') {
|
|
||||||
return `${dose}剂`
|
|
||||||
}
|
}
|
||||||
return '—'
|
return '—'
|
||||||
})
|
})
|
||||||
@@ -622,6 +664,14 @@ defineExpose({
|
|||||||
grid-template-columns: 1.6fr 0.6fr;
|
grid-template-columns: 1.6fr 0.6fr;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.rx-bot-row-1--reviewed {
|
||||||
|
grid-template-columns: minmax(164px, 1.15fr) minmax(188px, 1.3fr) 1.4fr 0.75fr 0.85fr;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rx-bot-row-1--user.rx-bot-row-1--reviewed {
|
||||||
|
grid-template-columns: minmax(164px, 1.6fr) minmax(188px, 1.6fr) 0.6fr;
|
||||||
|
}
|
||||||
|
|
||||||
.rx-hospital-row {
|
.rx-hospital-row {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
@@ -672,7 +722,7 @@ defineExpose({
|
|||||||
margin-bottom: 4px;
|
margin-bottom: 4px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.rx-bot-label--doctor {
|
.rx-bot-label--inline {
|
||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
margin-bottom: 0;
|
margin-bottom: 0;
|
||||||
margin-right: 6px;
|
margin-right: 6px;
|
||||||
@@ -680,37 +730,18 @@ defineExpose({
|
|||||||
align-self: center;
|
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 {
|
.rx-bot-doctor {
|
||||||
flex-direction: column;
|
flex-direction: row;
|
||||||
align-items: flex-start;
|
align-items: center;
|
||||||
justify-content: center;
|
|
||||||
flex-wrap: nowrap;
|
flex-wrap: nowrap;
|
||||||
gap: 4px;
|
|
||||||
|
|
||||||
.rx-bot-doctor-line {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
width: 100%;
|
|
||||||
}
|
|
||||||
|
|
||||||
.rx-bot-pharmacist {
|
|
||||||
width: 100%;
|
|
||||||
font-size: 12px;
|
|
||||||
line-height: 1.4;
|
|
||||||
overflow-wrap: anywhere;
|
|
||||||
}
|
|
||||||
|
|
||||||
.rx-bot-pharmacist-line {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
}
|
|
||||||
|
|
||||||
.rx-bot-pharmacist-signature {
|
|
||||||
min-width: 0;
|
|
||||||
width: 110px;
|
|
||||||
height: 40px;
|
|
||||||
flex-shrink: 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
.rx-bot-doctor-body {
|
.rx-bot-doctor-body {
|
||||||
flex: 1;
|
flex: 1;
|
||||||
@@ -729,13 +760,13 @@ defineExpose({
|
|||||||
line-height: 1.2;
|
line-height: 1.2;
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
.rx-bot-sign-img {
|
.rx-bot-sign-img {
|
||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
max-height: 40px;
|
max-height: 24px;
|
||||||
max-width: 110px;
|
max-width: 72px;
|
||||||
object-fit: contain;
|
object-fit: contain;
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.rx-bot-meta {
|
.rx-bot-meta {
|
||||||
@@ -758,6 +789,38 @@ defineExpose({
|
|||||||
line-height: 2.5;
|
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>
|
</style>
|
||||||
|
|
||||||
<!-- 全局打印样式:body * 选择器不能放进 scoped -->
|
<!-- 全局打印样式:body * 选择器不能放进 scoped -->
|
||||||
|
|||||||
@@ -5,12 +5,6 @@
|
|||||||
|
|
||||||
export type FormulaType = '主方' | '辅方'
|
export type FormulaType = '主方' | '辅方'
|
||||||
|
|
||||||
/** 药师身份来自当前业务订单本次有效的签署审核,不回退到开方医生或历史审核人。 */
|
|
||||||
export function rxPharmacistSignature(data: Record<string, any> | null | undefined): string {
|
|
||||||
if (Number(data?.prescription_audit_status) !== 1) return ''
|
|
||||||
return String(data?.prescription_audit_signature || '').trim()
|
|
||||||
}
|
|
||||||
|
|
||||||
export type SlipHerb = {
|
export type SlipHerb = {
|
||||||
medicine_id?: number
|
medicine_id?: number
|
||||||
name: string
|
name: string
|
||||||
|
|||||||
@@ -1,177 +0,0 @@
|
|||||||
<template>
|
|
||||||
<div class="signature-pad" :class="{ 'is-disabled': disabled }">
|
|
||||||
<div class="signature-pad__surface">
|
|
||||||
<canvas
|
|
||||||
ref="canvasRef"
|
|
||||||
class="signature-pad__canvas"
|
|
||||||
aria-label="手写签名区域"
|
|
||||||
:aria-disabled="disabled"
|
|
||||||
@pointerdown.prevent="onPointerDown"
|
|
||||||
@pointermove.prevent="onPointerMove"
|
|
||||||
@pointerup.prevent="onPointerUp"
|
|
||||||
@pointercancel.prevent="onPointerCancel"
|
|
||||||
@lostpointercapture="onPointerCancel"
|
|
||||||
/>
|
|
||||||
<span v-if="!modelValue && !drawing" class="signature-pad__placeholder">请在此手写本人签名</span>
|
|
||||||
</div>
|
|
||||||
<div class="signature-pad__actions">
|
|
||||||
<span>支持鼠标、触屏或手写笔</span>
|
|
||||||
<el-button size="small" :disabled="disabled" @click="clearSignature">清空重签</el-button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script setup lang="ts">
|
|
||||||
import { onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
|
||||||
|
|
||||||
const props = withDefaults(defineProps<{ modelValue: string; disabled?: boolean }>(), { disabled: false })
|
|
||||||
const emit = defineEmits<{ (event: 'update:modelValue', value: string): void }>()
|
|
||||||
const canvasRef = ref<HTMLCanvasElement>()
|
|
||||||
const drawing = ref(false)
|
|
||||||
type Point = { x: number; y: number }
|
|
||||||
// 归一化坐标让窗口旋转/调整尺寸后仍能重画笔迹,不重新使用历史签名图片。
|
|
||||||
let strokes: Point[][] = []
|
|
||||||
let activePointer: number | null = null
|
|
||||||
let cssWidth = 0
|
|
||||||
const cssHeight = 168
|
|
||||||
let lastEmitted = ''
|
|
||||||
let resizeObserver: ResizeObserver | undefined
|
|
||||||
|
|
||||||
function publish(value: string) {
|
|
||||||
lastEmitted = value
|
|
||||||
emit('update:modelValue', value)
|
|
||||||
}
|
|
||||||
|
|
||||||
function localPoint(event: PointerEvent): Point | null {
|
|
||||||
const rect = canvasRef.value?.getBoundingClientRect()
|
|
||||||
if (!rect || rect.width <= 0 || rect.height <= 0) return null
|
|
||||||
return {
|
|
||||||
x: Math.max(0, Math.min(1, (event.clientX - rect.left) / rect.width)),
|
|
||||||
y: Math.max(0, Math.min(1, (event.clientY - rect.top) / rect.height))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function drawSegment(from: Point, to: Point) {
|
|
||||||
const ctx = canvasRef.value?.getContext('2d')
|
|
||||||
if (!ctx) return
|
|
||||||
ctx.beginPath()
|
|
||||||
ctx.moveTo(from.x * cssWidth, from.y * cssHeight)
|
|
||||||
ctx.lineTo(to.x * cssWidth, to.y * cssHeight)
|
|
||||||
ctx.stroke()
|
|
||||||
}
|
|
||||||
|
|
||||||
function redraw() {
|
|
||||||
const canvas = canvasRef.value
|
|
||||||
const width = canvas?.getBoundingClientRect().width || 0
|
|
||||||
if (!canvas || width <= 0) return
|
|
||||||
cssWidth = width
|
|
||||||
const dpr = Math.min(window.devicePixelRatio || 1, 2.5)
|
|
||||||
canvas.width = Math.round(width * dpr)
|
|
||||||
canvas.height = Math.round(cssHeight * dpr)
|
|
||||||
const ctx = canvas.getContext('2d')
|
|
||||||
if (!ctx) return
|
|
||||||
ctx.setTransform(dpr, 0, 0, dpr, 0, 0)
|
|
||||||
ctx.fillStyle = '#fff'
|
|
||||||
ctx.fillRect(0, 0, width, cssHeight)
|
|
||||||
ctx.strokeStyle = '#303133'
|
|
||||||
ctx.lineWidth = 2.5
|
|
||||||
ctx.lineCap = 'round'
|
|
||||||
ctx.lineJoin = 'round'
|
|
||||||
for (const stroke of strokes) {
|
|
||||||
for (let index = 1; index < stroke.length; index++) drawSegment(stroke[index - 1], stroke[index])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function commitSignature() {
|
|
||||||
let length = 0
|
|
||||||
for (const stroke of strokes) {
|
|
||||||
for (let index = 1; index < stroke.length; index++) {
|
|
||||||
length += Math.hypot(
|
|
||||||
(stroke[index].x - stroke[index - 1].x) * cssWidth,
|
|
||||||
(stroke[index].y - stroke[index - 1].y) * cssHeight
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// 点按、抖动、空白画布都不能作为签名提交。
|
|
||||||
publish(length >= 12 && canvasRef.value ? canvasRef.value.toDataURL('image/png') : '')
|
|
||||||
}
|
|
||||||
|
|
||||||
function onPointerDown(event: PointerEvent) {
|
|
||||||
if (props.disabled || activePointer !== null || (event.pointerType === 'mouse' && event.button !== 0)) return
|
|
||||||
const point = localPoint(event)
|
|
||||||
if (!point || !canvasRef.value?.getContext('2d')) return
|
|
||||||
if (!cssWidth) redraw()
|
|
||||||
activePointer = event.pointerId
|
|
||||||
drawing.value = true
|
|
||||||
strokes.push([point])
|
|
||||||
canvasRef.value.setPointerCapture(event.pointerId)
|
|
||||||
// 尚未结束的笔画不参与审核;抬笔后发布完整签名。
|
|
||||||
publish('')
|
|
||||||
}
|
|
||||||
|
|
||||||
function onPointerMove(event: PointerEvent) {
|
|
||||||
if (props.disabled || event.pointerId !== activePointer) return
|
|
||||||
const point = localPoint(event)
|
|
||||||
const stroke = strokes[strokes.length - 1]
|
|
||||||
if (!point || !stroke) return
|
|
||||||
const previous = stroke[stroke.length - 1]
|
|
||||||
if (Math.hypot((point.x - previous.x) * cssWidth, (point.y - previous.y) * cssHeight) < 0.75) return
|
|
||||||
stroke.push(point)
|
|
||||||
drawSegment(previous, point)
|
|
||||||
}
|
|
||||||
|
|
||||||
function releasePointer() {
|
|
||||||
const pointer = activePointer
|
|
||||||
activePointer = null
|
|
||||||
drawing.value = false
|
|
||||||
if (pointer !== null && canvasRef.value?.hasPointerCapture(pointer)) canvasRef.value.releasePointerCapture(pointer)
|
|
||||||
}
|
|
||||||
|
|
||||||
function onPointerUp(event: PointerEvent) {
|
|
||||||
if (event.pointerId !== activePointer) return
|
|
||||||
onPointerMove(event)
|
|
||||||
releasePointer()
|
|
||||||
commitSignature()
|
|
||||||
}
|
|
||||||
|
|
||||||
function onPointerCancel(event: PointerEvent) {
|
|
||||||
if (event.pointerId !== activePointer) return
|
|
||||||
strokes.pop()
|
|
||||||
releasePointer()
|
|
||||||
redraw()
|
|
||||||
commitSignature()
|
|
||||||
}
|
|
||||||
|
|
||||||
function clearSignature() {
|
|
||||||
if (props.disabled) return
|
|
||||||
releasePointer()
|
|
||||||
strokes = []
|
|
||||||
redraw()
|
|
||||||
publish('')
|
|
||||||
}
|
|
||||||
|
|
||||||
watch(() => props.modelValue, (value) => {
|
|
||||||
if (value === lastEmitted) return
|
|
||||||
if (!value) clearSignature()
|
|
||||||
})
|
|
||||||
|
|
||||||
onMounted(() => {
|
|
||||||
redraw()
|
|
||||||
resizeObserver = new ResizeObserver(redraw)
|
|
||||||
if (canvasRef.value) resizeObserver.observe(canvasRef.value)
|
|
||||||
})
|
|
||||||
onBeforeUnmount(() => {
|
|
||||||
resizeObserver?.disconnect()
|
|
||||||
releasePointer()
|
|
||||||
})
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<style scoped>
|
|
||||||
.signature-pad { width: 100%; overflow: hidden; border: 1px solid #dcdfe6; border-radius: 6px; background: #fff; }
|
|
||||||
.signature-pad__surface { position: relative; }
|
|
||||||
.signature-pad__canvas { display: block; width: 100%; height: 168px; touch-action: none; cursor: crosshair; }
|
|
||||||
.signature-pad__placeholder { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; color: #a8abb2; font-size: 14px; pointer-events: none; }
|
|
||||||
.signature-pad__actions { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px; border-top: 1px solid #ebeef5; color: #909399; font-size: 12px; }
|
|
||||||
.signature-pad.is-disabled { opacity: 0.65; }
|
|
||||||
.is-disabled .signature-pad__canvas { cursor: not-allowed; }
|
|
||||||
</style>
|
|
||||||
@@ -510,7 +510,12 @@
|
|||||||
</el-form-item>
|
</el-form-item>
|
||||||
</el-col>
|
</el-col>
|
||||||
<el-col :span="24">
|
<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">
|
<div class="signature-pad-wrap">
|
||||||
<canvas
|
<canvas
|
||||||
ref="signatureCanvasRef"
|
ref="signatureCanvasRef"
|
||||||
@@ -534,6 +539,13 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div v-else class="rx-wrap">
|
<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">
|
<div class="rx-toolbar">
|
||||||
<el-tag v-if="savedPrescription.void_status === 1" type="danger" size="small">已作废</el-tag>
|
<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>
|
<el-tag v-else-if="approvedPreviewOnly" type="success" size="small">已通过</el-tag>
|
||||||
@@ -541,7 +553,7 @@
|
|||||||
v-else-if="Number(savedPrescription.audit_status) === 0"
|
v-else-if="Number(savedPrescription.audit_status) === 0"
|
||||||
type="warning"
|
type="warning"
|
||||||
size="small"
|
size="small"
|
||||||
>待审核</el-tag>
|
>{{ pendingPrescriptionReviewLabel(savedPrescription) }}</el-tag>
|
||||||
<el-tag v-else-if="Number(savedPrescription.audit_status) === 2" type="danger" size="small">已驳回</el-tag>
|
<el-tag v-else-if="Number(savedPrescription.audit_status) === 2" type="danger" size="small">已驳回</el-tag>
|
||||||
<div class="flex-1" />
|
<div class="flex-1" />
|
||||||
</div>
|
</div>
|
||||||
@@ -679,13 +691,14 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="flex justify-end gap-2 mt-4">
|
<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-icon><Download /></el-icon>
|
||||||
下载图片
|
下载图片
|
||||||
</el-button>
|
</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>
|
<el-icon><Document /></el-icon>
|
||||||
下载PDF
|
{{ requiresOriginalEsignPdf(savedPrescription.esign) ? '下载已签原始 PDF' : '下载PDF' }}
|
||||||
</el-button>
|
</el-button>
|
||||||
<el-tooltip
|
<el-tooltip
|
||||||
v-if="savedPrescription.void_status !== 1 && !approvedPreviewOnly"
|
v-if="savedPrescription.void_status !== 1 && !approvedPreviewOnly"
|
||||||
@@ -713,7 +726,9 @@
|
|||||||
<template v-if="!savedPrescription" #footer>
|
<template v-if="!savedPrescription" #footer>
|
||||||
<div class="flex justify-end gap-2">
|
<div class="flex justify-end gap-2">
|
||||||
<el-button @click="handleClose">取消</el-button>
|
<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>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
</el-drawer>
|
</el-drawer>
|
||||||
@@ -860,6 +875,10 @@ import { prescriptionAdd, prescriptionDetail, prescriptionGetByAppointment, pres
|
|||||||
import { medicineLists } from '@/api/medicine'
|
import { medicineLists } from '@/api/medicine'
|
||||||
import { getDictData } from '@/api/app'
|
import { getDictData } from '@/api/app'
|
||||||
import PrescriptionSlip from '@/components/prescription-slip/index.vue'
|
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 html2canvas from 'html2canvas'
|
||||||
import { jsPDF } from 'jspdf'
|
import { jsPDF } from 'jspdf'
|
||||||
import useUserStore from '@/stores/modules/user'
|
import useUserStore from '@/stores/modules/user'
|
||||||
@@ -1043,6 +1062,12 @@ const signatureActivePointerId = ref<number | null>(null)
|
|||||||
const SIGNATURE_CSS_W = 560
|
const SIGNATURE_CSS_W = 560
|
||||||
const SIGNATURE_CSS_H = 168
|
const SIGNATURE_CSS_H = 168
|
||||||
const savedPrescription = ref<any>(null)
|
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
|
const prescriptionTabType = ref<'internal' | 'user'>('internal') // 保留兼容 openPreview options.slipType
|
||||||
/** 诊单列表「查看」仅展示处方联,不展示详细病历 A3 */
|
/** 诊单列表「查看」仅展示处方联,不展示详细病历 A3 */
|
||||||
@@ -1661,6 +1686,7 @@ const open = async (data: any, options?: { templateId?: number; stationName?: st
|
|||||||
}
|
}
|
||||||
|
|
||||||
await loadDictOptions()
|
await loadDictOptions()
|
||||||
|
await loadEsignConfig()
|
||||||
|
|
||||||
const appointmentId = Number(data.id ?? data.appointment_id ?? 0)
|
const appointmentId = Number(data.id ?? data.appointment_id ?? 0)
|
||||||
if (appointmentId) {
|
if (appointmentId) {
|
||||||
@@ -2032,6 +2058,9 @@ watch(() => formData.prescription_type, (newType) => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
const handleSave = async () => {
|
const handleSave = async () => {
|
||||||
|
if (saving.value) return
|
||||||
|
if (!esignReady.value && !(await loadEsignConfig())) return
|
||||||
|
if (saving.value) return
|
||||||
if (!formData.clinical_diagnosis?.trim()) {
|
if (!formData.clinical_diagnosis?.trim()) {
|
||||||
feedback.msgWarning('请输入临床诊断')
|
feedback.msgWarning('请输入临床诊断')
|
||||||
return
|
return
|
||||||
@@ -2056,7 +2085,7 @@ const handleSave = async () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!formData.doctor_signature?.trim()) {
|
if (!esignEnabled.value && !formData.doctor_signature?.trim()) {
|
||||||
feedback.msgWarning('请使用电子签名板手写医师签名')
|
feedback.msgWarning('请使用电子签名板手写医师签名')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -2103,8 +2132,19 @@ const handleSave = async () => {
|
|||||||
})
|
})
|
||||||
const id = res?.id
|
const id = res?.id
|
||||||
if (id) {
|
if (id) {
|
||||||
const detail = await prescriptionDetail({ id })
|
// Keep the saved id even if the follow-up detail request fails; retrying must not add twice.
|
||||||
savedPrescription.value = detail
|
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')
|
emit('success')
|
||||||
} else {
|
} else {
|
||||||
feedback.msgError('保存失败')
|
feedback.msgError('保存失败')
|
||||||
@@ -2156,6 +2196,7 @@ const fetchCaseRecord = async (diagnosisId: number) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const handleNewPrescription = async () => {
|
const handleNewPrescription = async () => {
|
||||||
|
await loadEsignConfig()
|
||||||
const saved = savedPrescription.value
|
const saved = savedPrescription.value
|
||||||
if (saved) {
|
if (saved) {
|
||||||
// 将患者信息、诊断信息填入表单,新建处方时保留
|
// 将患者信息、诊断信息填入表单,新建处方时保留
|
||||||
@@ -2273,6 +2314,7 @@ const handleDownloadImage = async () => {
|
|||||||
|
|
||||||
const handleDownloadPdf = async () => {
|
const handleDownloadPdf = async () => {
|
||||||
try {
|
try {
|
||||||
|
if (await downloadPrescriptionPdfIfRequired(Number(savedPrescription.value?.id))) return
|
||||||
const canvas = await captureElement()
|
const canvas = await captureElement()
|
||||||
const imgData = canvas.toDataURL('image/png')
|
const imgData = canvas.toDataURL('image/png')
|
||||||
const pdf = new jsPDF({
|
const pdf = new jsPDF({
|
||||||
@@ -2301,8 +2343,8 @@ const handleDownloadPdf = async () => {
|
|||||||
|
|
||||||
pdf.save(`处方_${savedPrescription.value?.patient_name || '未命名'}_${Date.now()}.pdf`)
|
pdf.save(`处方_${savedPrescription.value?.patient_name || '未命名'}_${Date.now()}.pdf`)
|
||||||
feedback.msgSuccess('PDF已下载')
|
feedback.msgSuccess('PDF已下载')
|
||||||
} catch (e) {
|
} catch (e: any) {
|
||||||
feedback.msgError('下载PDF失败')
|
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">
|
<router-link to="/user/setting">
|
||||||
<el-dropdown-item>个人设置</el-dropdown-item>
|
<el-dropdown-item>个人设置</el-dropdown-item>
|
||||||
</router-link>
|
</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="cache">清除缓存</el-dropdown-item>
|
||||||
<el-dropdown-item command="logout">退出登录</el-dropdown-item>
|
<el-dropdown-item command="logout">退出登录</el-dropdown-item>
|
||||||
</el-dropdown-menu>
|
</el-dropdown-menu>
|
||||||
</template>
|
</template>
|
||||||
</el-dropdown>
|
</el-dropdown>
|
||||||
|
<esign-doctor-dialog
|
||||||
|
v-if="(canManageDoctorEsign && doctorEsignOpen) || (canManageReviewEsign && reviewEsignOpen)"
|
||||||
|
:reviewer="reviewEsignOpen"
|
||||||
|
:server-time-offset-ms="userStore.serverTimeOffsetMs"
|
||||||
|
@close="closeEsign"
|
||||||
|
/>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
|
import { computed, onMounted, ref, watch } from 'vue'
|
||||||
|
import { useRoute } from 'vue-router'
|
||||||
|
|
||||||
import { systemCacheClear } from '@/api/setting/system'
|
import { systemCacheClear } from '@/api/setting/system'
|
||||||
|
import { prescriptionEsignConfig } from '@/api/tcm'
|
||||||
|
import EsignDoctorDialog from '@/components/EsignDoctorDialog.vue'
|
||||||
import useUserStore from '@/stores/modules/user'
|
import useUserStore from '@/stores/modules/user'
|
||||||
import feedback from '@/utils/feedback'
|
import feedback from '@/utils/feedback'
|
||||||
|
import { hasPermission } from '@/utils/perm'
|
||||||
|
import { DOCTOR_ESIGN_IDENTITY_PERMISSION } from '@/utils/prescription-esign'
|
||||||
|
|
||||||
const userStore = useUserStore()
|
const userStore = useUserStore()
|
||||||
|
const route = useRoute()
|
||||||
|
|
||||||
const userInfo = computed(() => userStore.userInfo)
|
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) => {
|
const handleCommand = async (command: string) => {
|
||||||
switch (command) {
|
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':
|
case 'logout':
|
||||||
await feedback.confirm('确定退出登录吗?')
|
await feedback.confirm('确定退出登录吗?')
|
||||||
userStore.logout()
|
userStore.logout()
|
||||||
|
|||||||
@@ -58,13 +58,17 @@ const useUserStore = defineStore({
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
logout() {
|
logout(returnTo?: string) {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
logout()
|
logout()
|
||||||
.then(async (data) => {
|
.then(async (data) => {
|
||||||
this.token = ''
|
this.token = ''
|
||||||
await router.push(PageEnum.LOGIN)
|
|
||||||
clearAuthInfo()
|
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)
|
resolve(data)
|
||||||
})
|
})
|
||||||
.catch((error) => {
|
.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>
|
<template #prepend>
|
||||||
<icon name="el-icon-User" size="16" />
|
<icon name="el-icon-User" size="16" />
|
||||||
</template>
|
</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-input>
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
<el-form-item prop="password">
|
<el-form-item prop="password">
|
||||||
@@ -122,6 +138,8 @@ const userStore = useUserStore()
|
|||||||
const route = useRoute()
|
const route = useRoute()
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const remAccount = ref(false)
|
const remAccount = ref(false)
|
||||||
|
const rememberedAccounts = ref<string[]>([])
|
||||||
|
const switchingAccount = computed(() => route.query.switch_account === '1')
|
||||||
const config = computed(() => appStore.config)
|
const config = computed(() => appStore.config)
|
||||||
const formData = reactive({
|
const formData = reactive({
|
||||||
account: '',
|
account: '',
|
||||||
@@ -214,11 +232,15 @@ const handleEnter = () => {
|
|||||||
|
|
||||||
const handleLogin = async () => {
|
const handleLogin = async () => {
|
||||||
await formRef.value?.validate()
|
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, {
|
cache.set(ACCOUNT_KEY, {
|
||||||
remember: remAccount.value,
|
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) {
|
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 () => {
|
onMounted(async () => {
|
||||||
// 恢复记住账号
|
// 恢复记住账号
|
||||||
const value = cache.get(ACCOUNT_KEY)
|
const value = cache.get(ACCOUNT_KEY)
|
||||||
if (value?.remember) {
|
const saved: unknown[] = Array.isArray(value?.accounts) ? value.accounts : value?.remember ? [value.account] : []
|
||||||
remAccount.value = value.remember
|
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
|
formData.account = value.account
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -342,7 +374,7 @@ onMounted(async () => {
|
|||||||
wxWorkConfig.value = { corp_id: res.corp_id, agent_id: res.agent_id }
|
wxWorkConfig.value = { corp_id: res.corp_id, agent_id: res.agent_id }
|
||||||
|
|
||||||
// 在企业微信内:自动跳转 OAuth 授权
|
// 在企业微信内:自动跳转 OAuth 授权
|
||||||
if (isInWxWork() && !hasIamCallback) {
|
if (isInWxWork() && !hasIamCallback && !switchingAccount.value) {
|
||||||
const redirectUri = encodeURIComponent(getRedirectUri())
|
const redirectUri = encodeURIComponent(getRedirectUri())
|
||||||
const authUrl =
|
const authUrl =
|
||||||
`https://open.weixin.qq.com/connect/oauth2/authorize` +
|
`https://open.weixin.qq.com/connect/oauth2/authorize` +
|
||||||
|
|||||||
@@ -1,32 +0,0 @@
|
|||||||
<template>
|
|
||||||
<div v-if="signature" class="audit-signature-record">
|
|
||||||
<el-image
|
|
||||||
:src="signature"
|
|
||||||
:preview-src-list="[signature]"
|
|
||||||
preview-teleported
|
|
||||||
fit="contain"
|
|
||||||
class="audit-signature-record__image"
|
|
||||||
alt="审核人手写签名"
|
|
||||||
/>
|
|
||||||
<div class="audit-signature-record__meta">
|
|
||||||
签署人:{{ signedName || (signedBy ? `#${signedBy}` : '—') }}
|
|
||||||
<span class="ml-3">签署时间:{{ formatTime(signedAt) }}</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script setup lang="ts">
|
|
||||||
import { formatTime } from './prescription-order-utils'
|
|
||||||
defineProps<{
|
|
||||||
signature?: string
|
|
||||||
signedBy?: number | string
|
|
||||||
signedName?: string
|
|
||||||
signedAt?: number | string | null
|
|
||||||
}>()
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<style scoped>
|
|
||||||
.audit-signature-record { margin-top: 8px; }
|
|
||||||
.audit-signature-record__image { display: block; width: 240px; max-width: 100%; height: 80px; border: 1px solid #ebeef5; border-radius: 4px; background: #fff; }
|
|
||||||
.audit-signature-record__meta { display: flex; flex-wrap: wrap; gap: 4px 0; margin-top: 4px; color: #606266; font-size: 12px; }
|
|
||||||
</style>
|
|
||||||
@@ -402,7 +402,8 @@ const ReportList = defineComponent({
|
|||||||
|
|
||||||
const models: Array<{ profile: PrescriptionAiProfile; label: string; name: string }> = [
|
const models: Array<{ profile: PrescriptionAiProfile; label: string; name: string }> = [
|
||||||
{ profile: 'qwen', label: '千问', name: 'qwen3.6-35b' },
|
{ 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 = [
|
const AI_REPORT_EDIT_PERMISSIONS = [
|
||||||
@@ -436,7 +437,8 @@ const canRefreshFromBackend = ref(false)
|
|||||||
const canEditFromBackend = ref(false)
|
const canEditFromBackend = ref(false)
|
||||||
const states = reactive<Record<PrescriptionAiProfile, ReportState>>({
|
const states = reactive<Record<PrescriptionAiProfile, ReportState>>({
|
||||||
qwen: createState(),
|
qwen: createState(),
|
||||||
openai: createState()
|
openai: createState(),
|
||||||
|
doubao: createState()
|
||||||
})
|
})
|
||||||
|
|
||||||
const herbSummary = computed(() => {
|
const herbSummary = computed(() => {
|
||||||
|
|||||||
+12
-55
@@ -709,14 +709,6 @@
|
|||||||
<el-descriptions-item label="处方审核意见" :span="3">
|
<el-descriptions-item label="处方审核意见" :span="3">
|
||||||
<span class="po-audit-remark">{{ detailData.prescription_audit_remark || '—' }}</span>
|
<span class="po-audit-remark">{{ detailData.prescription_audit_remark || '—' }}</span>
|
||||||
</el-descriptions-item>
|
</el-descriptions-item>
|
||||||
<el-descriptions-item v-if="detailData.prescription_audit_signature" label="审核人签名" :span="3">
|
|
||||||
<AuditSignatureRecord
|
|
||||||
:signature="detailData.prescription_audit_signature"
|
|
||||||
:signed-by="detailData.prescription_audit_signed_by"
|
|
||||||
:signed-name="detailData.prescription_audit_signed_name"
|
|
||||||
:signed-at="detailData.prescription_audit_signed_at"
|
|
||||||
/>
|
|
||||||
</el-descriptions-item>
|
|
||||||
<el-descriptions-item label="支付审核意见" :span="3">
|
<el-descriptions-item label="支付审核意见" :span="3">
|
||||||
<span class="po-audit-remark">{{ detailData.payment_slip_audit_remark || '—' }}</span>
|
<span class="po-audit-remark">{{ detailData.payment_slip_audit_remark || '—' }}</span>
|
||||||
</el-descriptions-item>
|
</el-descriptions-item>
|
||||||
@@ -878,13 +870,6 @@
|
|||||||
<el-tag size="small" type="info">{{ logActionText(log.action) }}</el-tag>
|
<el-tag size="small" type="info">{{ logActionText(log.action) }}</el-tag>
|
||||||
</div>
|
</div>
|
||||||
<span :class="idx === 0 ? 'text-gray-800 font-medium' : 'text-gray-500'">{{ log.summary }}</span>
|
<span :class="idx === 0 ? 'text-gray-800 font-medium' : 'text-gray-500'">{{ log.summary }}</span>
|
||||||
<AuditSignatureRecord
|
|
||||||
v-if="log.audit_signature"
|
|
||||||
:signature="log.audit_signature"
|
|
||||||
:signed-by="log.admin_id"
|
|
||||||
:signed-name="log.admin_name"
|
|
||||||
:signed-at="log.create_time"
|
|
||||||
/>
|
|
||||||
</el-timeline-item>
|
</el-timeline-item>
|
||||||
</el-timeline>
|
</el-timeline>
|
||||||
<el-empty v-else description="暂无操作日志" :image-size="64" />
|
<el-empty v-else description="暂无操作日志" :image-size="64" />
|
||||||
@@ -898,11 +883,9 @@
|
|||||||
:close-on-click-modal="false"
|
:close-on-click-modal="false"
|
||||||
destroy-on-close
|
destroy-on-close
|
||||||
append-to-body
|
append-to-body
|
||||||
:close-on-press-escape="!addLogSaving"
|
|
||||||
:show-close="!addLogSaving"
|
|
||||||
@closed="resetAddLogForm"
|
@closed="resetAddLogForm"
|
||||||
>
|
>
|
||||||
<el-form ref="addLogFormRef" :model="addLogForm" :rules="addLogRules" :disabled="addLogSaving" label-width="108px">
|
<el-form ref="addLogFormRef" :model="addLogForm" :rules="addLogRules" label-width="108px">
|
||||||
<el-form-item label="日志内容" prop="summary">
|
<el-form-item label="日志内容" prop="summary">
|
||||||
<el-input
|
<el-input
|
||||||
v-model="addLogForm.summary"
|
v-model="addLogForm.summary"
|
||||||
@@ -959,14 +942,10 @@
|
|||||||
placeholder="选填"
|
placeholder="选填"
|
||||||
/>
|
/>
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
<el-form-item v-if="requiresAddLogSignature" label="审核人签名" required>
|
|
||||||
<SignaturePad :key="addLogSession" v-model="addLogSignature" :disabled="addLogSaving" />
|
|
||||||
<div class="text-xs text-gray-500 mt-1">设为已通过或已驳回需重新手写签名。</div>
|
|
||||||
</el-form-item>
|
|
||||||
</el-form>
|
</el-form>
|
||||||
<template #footer>
|
<template #footer>
|
||||||
<el-button :disabled="addLogSaving" @click="addLogVisible = false">取消</el-button>
|
<el-button @click="addLogVisible = false">取消</el-button>
|
||||||
<el-button type="primary" :loading="addLogSaving" :disabled="requiresAddLogSignature && !addLogSignature" @click="submitAddLog">保存</el-button>
|
<el-button type="primary" :loading="addLogSaving" @click="submitAddLog">保存</el-button>
|
||||||
</template>
|
</template>
|
||||||
</el-dialog>
|
</el-dialog>
|
||||||
|
|
||||||
@@ -1078,9 +1057,7 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script lang="ts" setup name="PrescriptionOrderDetailDrawer">
|
<script lang="ts" setup name="PrescriptionOrderDetailDrawer">
|
||||||
import { computed, nextTick, onMounted, reactive, ref, watch } from 'vue'
|
import { computed, nextTick, onMounted, reactive, ref } from 'vue'
|
||||||
import SignaturePad from '@/components/signature-pad/index.vue'
|
|
||||||
import AuditSignatureRecord from './AuditSignatureRecord.vue'
|
|
||||||
import type { FormInstance, FormRules } from 'element-plus'
|
import type { FormInstance, FormRules } from 'element-plus'
|
||||||
import { Refresh, Loading, Search, Van } from '@element-plus/icons-vue'
|
import { Refresh, Loading, Search, Van } from '@element-plus/icons-vue'
|
||||||
import {
|
import {
|
||||||
@@ -1463,6 +1440,8 @@ function canAddPrescriptionOrderLog() {
|
|||||||
|
|
||||||
/** 与后端 canAuditPrescriptionOrder 同档:超管或 prescription_audit_roles */
|
/** 与后端 canAuditPrescriptionOrder 同档:超管或 prescription_audit_roles */
|
||||||
const canSetRxAuditOnAddLog = computed(() => {
|
const canSetRxAuditOnAddLog = computed(() => {
|
||||||
|
if (Number(detailData.value?.prescription_audit_status) === 0
|
||||||
|
&& detailData.value?.can_review_prescription === false) return false
|
||||||
const u = userStore.userInfo
|
const u = userStore.userInfo
|
||||||
if (!u || Number(u.root) === 1) return true
|
if (!u || Number(u.root) === 1) return true
|
||||||
const ids = Array.isArray(u.role_ids) ? u.role_ids.map((n: unknown) => Number(n)) : []
|
const ids = Array.isArray(u.role_ids) ? u.role_ids.map((n: unknown) => Number(n)) : []
|
||||||
@@ -1480,8 +1459,6 @@ const canSetPayAuditOnAddLog = computed(() => {
|
|||||||
const addLogVisible = ref(false)
|
const addLogVisible = ref(false)
|
||||||
const addLogSaving = ref(false)
|
const addLogSaving = ref(false)
|
||||||
const addLogFormRef = ref<FormInstance>()
|
const addLogFormRef = ref<FormInstance>()
|
||||||
const addLogSignature = ref('')
|
|
||||||
const addLogSession = ref(0)
|
|
||||||
const addLogForm = reactive({
|
const addLogForm = reactive({
|
||||||
summary: '',
|
summary: '',
|
||||||
prescription_audit_status: '' as number | '',
|
prescription_audit_status: '' as number | '',
|
||||||
@@ -1492,13 +1469,6 @@ const addLogForm = reactive({
|
|||||||
const addLogRules: FormRules = {
|
const addLogRules: FormRules = {
|
||||||
summary: [{ required: true, message: '请填写日志内容', trigger: 'blur' }]
|
summary: [{ required: true, message: '请填写日志内容', trigger: 'blur' }]
|
||||||
}
|
}
|
||||||
const requiresAddLogSignature = computed(() =>
|
|
||||||
canSetRxAuditOnAddLog.value && [1, 2].includes(Number(addLogForm.prescription_audit_status))
|
|
||||||
)
|
|
||||||
watch(() => addLogForm.prescription_audit_status, () => {
|
|
||||||
addLogSignature.value = ''
|
|
||||||
addLogSession.value++
|
|
||||||
})
|
|
||||||
|
|
||||||
const patchUsageVisible = ref(false)
|
const patchUsageVisible = ref(false)
|
||||||
const patchUsageSaving = ref(false)
|
const patchUsageSaving = ref(false)
|
||||||
@@ -1616,19 +1586,16 @@ async function submitPatchUsage() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function resetAddLogForm() {
|
function resetAddLogForm() {
|
||||||
if (addLogSaving.value) return
|
|
||||||
addLogForm.summary = ''
|
addLogForm.summary = ''
|
||||||
addLogForm.prescription_audit_status = ''
|
addLogForm.prescription_audit_status = ''
|
||||||
addLogForm.payment_slip_audit_status = ''
|
addLogForm.payment_slip_audit_status = ''
|
||||||
addLogForm.prescription_audit_remark = ''
|
addLogForm.prescription_audit_remark = ''
|
||||||
addLogForm.payment_slip_audit_remark = ''
|
addLogForm.payment_slip_audit_remark = ''
|
||||||
addLogSignature.value = ''
|
|
||||||
addLogSession.value++
|
|
||||||
addLogFormRef.value?.clearValidate()
|
addLogFormRef.value?.clearValidate()
|
||||||
}
|
}
|
||||||
|
|
||||||
function openAddLogDialog() {
|
function openAddLogDialog() {
|
||||||
if (addLogSaving.value || !detailData.value?.id) return
|
if (!detailData.value?.id) return
|
||||||
resetAddLogForm()
|
resetAddLogForm()
|
||||||
const d = detailData.value
|
const d = detailData.value
|
||||||
addLogForm.prescription_audit_remark = String(d.prescription_audit_remark || '')
|
addLogForm.prescription_audit_remark = String(d.prescription_audit_remark || '')
|
||||||
@@ -1637,17 +1604,12 @@ function openAddLogDialog() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function submitAddLog() {
|
async function submitAddLog() {
|
||||||
if (addLogSaving.value || !addLogVisible.value || !addLogFormRef.value || !detailData.value?.id) return
|
if (!addLogFormRef.value || !detailData.value?.id) return
|
||||||
if (requiresAddLogSignature.value && !addLogSignature.value.trim()) {
|
await addLogFormRef.value.validate()
|
||||||
feedback.msgError('请先手写审核人签名')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
const targetId = Number(detailData.value.id)
|
|
||||||
addLogSaving.value = true
|
addLogSaving.value = true
|
||||||
try {
|
try {
|
||||||
if (!(await addLogFormRef.value.validate().catch(() => false))) return
|
const payload: Record<string, unknown> = {
|
||||||
const payload: Parameters<typeof prescriptionOrderAddLog>[0] = {
|
id: detailData.value.id,
|
||||||
id: targetId,
|
|
||||||
summary: addLogForm.summary.trim()
|
summary: addLogForm.summary.trim()
|
||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
@@ -1658,7 +1620,6 @@ async function submitAddLog() {
|
|||||||
) {
|
) {
|
||||||
payload.prescription_audit_status = addLogForm.prescription_audit_status
|
payload.prescription_audit_status = addLogForm.prescription_audit_status
|
||||||
payload.prescription_audit_remark = addLogForm.prescription_audit_remark
|
payload.prescription_audit_remark = addLogForm.prescription_audit_remark
|
||||||
if (requiresAddLogSignature.value) payload.signature = addLogSignature.value
|
|
||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
canSetPayAuditOnAddLog.value &&
|
canSetPayAuditOnAddLog.value &&
|
||||||
@@ -1669,10 +1630,9 @@ async function submitAddLog() {
|
|||||||
payload.payment_slip_audit_status = addLogForm.payment_slip_audit_status
|
payload.payment_slip_audit_status = addLogForm.payment_slip_audit_status
|
||||||
payload.payment_slip_audit_remark = addLogForm.payment_slip_audit_remark
|
payload.payment_slip_audit_remark = addLogForm.payment_slip_audit_remark
|
||||||
}
|
}
|
||||||
await prescriptionOrderAddLog(payload)
|
await prescriptionOrderAddLog(payload as any)
|
||||||
feedback.msgSuccess('日志已添加')
|
feedback.msgSuccess('日志已添加')
|
||||||
addLogVisible.value = false
|
addLogVisible.value = false
|
||||||
addLogSignature.value = ''
|
|
||||||
await refresh()
|
await refresh()
|
||||||
emit('detail-changed')
|
emit('detail-changed')
|
||||||
} catch {
|
} catch {
|
||||||
@@ -1810,9 +1770,6 @@ function requestDetail(id: number) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function open(id: number) {
|
async function open(id: number) {
|
||||||
if (addLogSaving.value) return
|
|
||||||
addLogVisible.value = false
|
|
||||||
resetAddLogForm()
|
|
||||||
// 页面级同参数字典请求会取消抽屉挂载时的那次(axios 去重取消),打开时兜底重试
|
// 页面级同参数字典请求会取消抽屉挂载时的那次(axios 去重取消),打开时兜底重试
|
||||||
void loadServicePackageOptions()
|
void loadServicePackageOptions()
|
||||||
// 显式彻底清空缓存,防止前一次弹窗的数据残留
|
// 显式彻底清空缓存,防止前一次弹窗的数据残留
|
||||||
|
|||||||
@@ -1,61 +0,0 @@
|
|||||||
import { prescriptionDetail, prescriptionOrderDetail } from '@/api/tcm'
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 查看业务订单处方时,以该订单的新详情为签署事实来源。
|
|
||||||
* 处方接口可能尚未返回签署字段,也可能返回另一笔订单的历史字段,不能据此推断本单审核人。
|
|
||||||
*/
|
|
||||||
export async function loadOrderPrescriptionSlip(orderId: number, prescriptionIdHint?: number) {
|
|
||||||
if (!(orderId > 0)) throw new Error('缺少业务订单信息,请重新打开订单详情')
|
|
||||||
|
|
||||||
async function freshOrder() {
|
|
||||||
const response: any = await prescriptionOrderDetail({ id: orderId })
|
|
||||||
const order = response?.data ?? response
|
|
||||||
if (!order || Number(order.id) !== orderId) throw new Error('业务订单详情不匹配,请重新打开')
|
|
||||||
if (!(Number(order.prescription_id) > 0)) throw new Error('该订单未关联处方')
|
|
||||||
return order as Record<string, any>
|
|
||||||
}
|
|
||||||
|
|
||||||
let prescriptionId = Number(prescriptionIdHint) || 0
|
|
||||||
if (!prescriptionId) prescriptionId = Number((await freshOrder()).prescription_id)
|
|
||||||
// 通常两次请求;若旧页面里的处方关联已改变,则按新关联重取一次。
|
|
||||||
for (let attempt = 0; attempt < 2; attempt++) {
|
|
||||||
let response: any
|
|
||||||
try {
|
|
||||||
response = await prescriptionDetail({ id: prescriptionId, prescription_order_id: orderId })
|
|
||||||
} catch (error) {
|
|
||||||
// 服务端会拒绝已过期的订单-处方关联,只能使用该订单最新关联重试。
|
|
||||||
const order = await freshOrder()
|
|
||||||
if (Number(order.prescription_id) !== prescriptionId) {
|
|
||||||
prescriptionId = Number(order.prescription_id)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
throw error
|
|
||||||
}
|
|
||||||
const base = response?.data ?? response
|
|
||||||
if (!base || Number(base.id) !== prescriptionId) throw new Error('处方详情不匹配,请重新打开')
|
|
||||||
// 放在处方请求之后读取,避免慢处方响应将已撤回的审核重新带回预览。
|
|
||||||
const order = await freshOrder()
|
|
||||||
if (Number(order.prescription_id) !== prescriptionId) {
|
|
||||||
prescriptionId = Number(order.prescription_id)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
const status = Number(order.prescription_audit_status) || 0
|
|
||||||
const signedApproval = status === 1 && ![4, 10].includes(Number(order.fulfillment_status))
|
|
||||||
const signature = signedApproval ? String(order.prescription_audit_signature || '').trim() : ''
|
|
||||||
return {
|
|
||||||
order,
|
|
||||||
prescription: {
|
|
||||||
...base,
|
|
||||||
prescription_order_id: orderId,
|
|
||||||
prescription_audit_status: status,
|
|
||||||
prescription_audit_signature: signature,
|
|
||||||
prescription_audit_signed_name: signature ? String(order.prescription_audit_signed_name || '').trim() : '',
|
|
||||||
prescription_audit_signed_by: signature ? Number(order.prescription_audit_signed_by) || 0 : 0,
|
|
||||||
prescription_audit_signed_at: signature ? order.prescription_audit_signed_at || 0 : 0,
|
|
||||||
business_prescription_audit_rejected: status === 2 ? 1 : 0,
|
|
||||||
business_prescription_audit_remark: String(order.prescription_audit_remark || '')
|
|
||||||
} as Record<string, any>
|
|
||||||
}
|
|
||||||
}
|
|
||||||
throw new Error('订单关联处方正在变更,请稍后重新打开')
|
|
||||||
}
|
|
||||||
@@ -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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -24,7 +24,7 @@
|
|||||||
<span class="pl-toolbar__sep" aria-hidden="true" />
|
<span class="pl-toolbar__sep" aria-hidden="true" />
|
||||||
<span
|
<span
|
||||||
class="pl-toolbar__k"
|
class="pl-toolbar__k"
|
||||||
title="「未通过」含待审核与已驳回"
|
title="「未通过」含待上传、待医师签署、待审核与已驳回"
|
||||||
>审核</span>
|
>审核</span>
|
||||||
<el-radio-group
|
<el-radio-group
|
||||||
v-model="formData.audit_filter"
|
v-model="formData.audit_filter"
|
||||||
@@ -103,6 +103,9 @@
|
|||||||
<div class="pl-table-head">
|
<div class="pl-table-head">
|
||||||
<span class="pl-table-head__title">处方列表</span>
|
<span class="pl-table-head__title">处方列表</span>
|
||||||
<div class="flex items-center gap-2">
|
<div class="flex items-center gap-2">
|
||||||
|
<el-button v-if="canManageCaSigning" @click="openCaSigningSettings">
|
||||||
|
CA 签名设置
|
||||||
|
</el-button>
|
||||||
<el-button
|
<el-button
|
||||||
v-perms="['tcm.prescriptionOrder/lists']"
|
v-perms="['tcm.prescriptionOrder/lists']"
|
||||||
@click="goBusinessOrderList"
|
@click="goBusinessOrderList"
|
||||||
@@ -189,6 +192,13 @@
|
|||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
</el-table-column>
|
</el-table-column>
|
||||||
|
<el-table-column label="签署状态" min-width="140">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-tag :type="prescriptionListSigningStatus(row).type" size="small" effect="plain">
|
||||||
|
{{ prescriptionListSigningStatus(row).label }}
|
||||||
|
</el-tag>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
<el-table-column label="作废" min-width="80" align="center">
|
<el-table-column label="作废" min-width="80" align="center">
|
||||||
<template #default="{ row }">
|
<template #default="{ row }">
|
||||||
<el-tag v-if="row.void_status === 1" type="danger" size="small">作废</el-tag>
|
<el-tag v-if="row.void_status === 1" type="danger" size="small">作废</el-tag>
|
||||||
@@ -211,7 +221,7 @@
|
|||||||
{{ formatListCreateTime(row.create_time) }}
|
{{ formatListCreateTime(row.create_time) }}
|
||||||
</template>
|
</template>
|
||||||
</el-table-column>
|
</el-table-column>
|
||||||
<el-table-column label="操作" width="300" fixed="right">
|
<el-table-column label="操作" width="340" fixed="right">
|
||||||
<template #default="{ row }">
|
<template #default="{ row }">
|
||||||
<el-button type="primary" link @click="handleView(row)" v-perms="['cf.prescription/read']">
|
<el-button type="primary" link @click="handleView(row)" v-perms="['cf.prescription/read']">
|
||||||
查看
|
查看
|
||||||
@@ -235,7 +245,7 @@
|
|||||||
创建订单
|
创建订单
|
||||||
</el-button>
|
</el-button>
|
||||||
<el-button
|
<el-button
|
||||||
v-if="!isApprovedActivePrescription(row)"
|
v-if="!isApprovedActivePrescription(row) && (Number(row.void_status) !== 1 || row.can_restore_rejected === true)"
|
||||||
type="primary"
|
type="primary"
|
||||||
link
|
link
|
||||||
@click="handleEdit(row)"
|
@click="handleEdit(row)"
|
||||||
@@ -244,7 +254,27 @@
|
|||||||
编辑
|
编辑
|
||||||
</el-button>
|
</el-button>
|
||||||
<el-button
|
<el-button
|
||||||
v-if="row.audit_status === 0 && row.void_status !== 1"
|
v-if="canReissuePrescription(row)"
|
||||||
|
type="primary"
|
||||||
|
link
|
||||||
|
:loading="reissuingPrescriptionId === Number(row.id)"
|
||||||
|
:disabled="reissuingPrescriptionId !== 0"
|
||||||
|
@click="handleReissue(row)"
|
||||||
|
>
|
||||||
|
重新开方
|
||||||
|
</el-button>
|
||||||
|
<el-button
|
||||||
|
v-if="row.can_submit_for_review === true"
|
||||||
|
type="primary"
|
||||||
|
link
|
||||||
|
:loading="uploadingPrescriptionId === Number(row.id)"
|
||||||
|
:disabled="uploadingPrescriptionId !== 0"
|
||||||
|
@click="submitPrescriptionForReview(row)"
|
||||||
|
>
|
||||||
|
上传处方
|
||||||
|
</el-button>
|
||||||
|
<el-button
|
||||||
|
v-if="canOpenPrescriptionAudit(row)"
|
||||||
type="warning"
|
type="warning"
|
||||||
link
|
link
|
||||||
v-perms="['cf.prescription/audit']"
|
v-perms="['cf.prescription/audit']"
|
||||||
@@ -252,6 +282,17 @@
|
|||||||
>
|
>
|
||||||
审核
|
审核
|
||||||
</el-button>
|
</el-button>
|
||||||
|
<el-button
|
||||||
|
v-if="canVoidPendingPrescription(row)"
|
||||||
|
v-perms="['tcm.prescription/void']"
|
||||||
|
type="danger"
|
||||||
|
link
|
||||||
|
:loading="voidingPrescriptionId === Number(row.id)"
|
||||||
|
:disabled="voidingPrescriptionId !== 0"
|
||||||
|
@click="voidPendingPrescription(row)"
|
||||||
|
>
|
||||||
|
作废
|
||||||
|
</el-button>
|
||||||
<el-button
|
<el-button
|
||||||
v-if="!isApprovedActivePrescription(row)"
|
v-if="!isApprovedActivePrescription(row)"
|
||||||
type="danger"
|
type="danger"
|
||||||
@@ -271,18 +312,89 @@
|
|||||||
</div>
|
</div>
|
||||||
</el-card>
|
</el-card>
|
||||||
|
|
||||||
|
<el-dialog
|
||||||
|
v-if="canManageCaSigning"
|
||||||
|
v-model="caSigningSettingsVisible"
|
||||||
|
title="CA 签名设置"
|
||||||
|
width="min(440px, calc(100vw - 24px))"
|
||||||
|
:close-on-click-modal="false"
|
||||||
|
:close-on-press-escape="!caSigningSettingsSaving"
|
||||||
|
:show-close="!caSigningSettingsSaving"
|
||||||
|
>
|
||||||
|
<p v-if="esignLoading" role="status">正在读取 CA 签名设置…</p>
|
||||||
|
<template v-else-if="esignReady">
|
||||||
|
<div class="flex items-center justify-between gap-2">
|
||||||
|
<span>全局 CA 签名</span>
|
||||||
|
<el-switch
|
||||||
|
v-model="caSigningSettingsEnabled"
|
||||||
|
aria-label="全局 CA 签名"
|
||||||
|
active-text="开启"
|
||||||
|
inactive-text="关闭"
|
||||||
|
:disabled="caSigningSettingsSaving"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<p v-if="esignConfig?.enabled && esignConfig.review_enabled !== true" class="mt-3">
|
||||||
|
当前仅启用医师 CA 签名。
|
||||||
|
</p>
|
||||||
|
<p class="mt-3 leading-relaxed">
|
||||||
|
保存为开启时,处方上传后依次由医师、药师完成 CA 签名。
|
||||||
|
保存为关闭时,新开的普通处方使用手写签名,上传后进入原有审核流程。
|
||||||
|
已进入 CA 流程的处方仍按该流程处理。
|
||||||
|
</p>
|
||||||
|
<el-alert
|
||||||
|
v-if="caSigningSettingsSaveError"
|
||||||
|
class="mt-3"
|
||||||
|
type="error"
|
||||||
|
:closable="false"
|
||||||
|
:title="caSigningSettingsSaveError"
|
||||||
|
/>
|
||||||
|
</template>
|
||||||
|
<el-alert v-else type="error" :closable="false" title="未能读取 CA 签名设置">
|
||||||
|
<el-button link type="primary" @click="loadCaSigningSettings">重新加载</el-button>
|
||||||
|
</el-alert>
|
||||||
|
<template #footer>
|
||||||
|
<el-button
|
||||||
|
:disabled="caSigningSettingsSaving"
|
||||||
|
@click="caSigningSettingsVisible = false"
|
||||||
|
>
|
||||||
|
取消
|
||||||
|
</el-button>
|
||||||
|
<el-button
|
||||||
|
type="primary"
|
||||||
|
:disabled="!canSaveCaSigningSettings"
|
||||||
|
:loading="caSigningSettingsSaving"
|
||||||
|
@click="saveCaSigningSettings"
|
||||||
|
>
|
||||||
|
保存
|
||||||
|
</el-button>
|
||||||
|
</template>
|
||||||
|
</el-dialog>
|
||||||
|
|
||||||
<!-- 新增/编辑/查看抽屉 -->
|
<!-- 新增/编辑/查看抽屉 -->
|
||||||
<el-drawer
|
<el-drawer
|
||||||
v-model="showEdit"
|
v-model="showEdit"
|
||||||
:title="editMode === 'add' ? '新增处方' : editMode === 'edit' ? '编辑处方' : '查看处方'"
|
:title="editMode === 'add' ? (reissueContext ? '重新开方' : '新增处方') : editMode === 'edit' ? '编辑处方' : '查看处方'"
|
||||||
:size="editMode === 'view' ? '920px' : '860px'"
|
:size="editMode === 'view' ? '920px' : '860px'"
|
||||||
class="cf-prescription-drawer"
|
class="cf-prescription-drawer"
|
||||||
:close-on-click-modal="false"
|
:close-on-click-modal="false"
|
||||||
destroy-on-close
|
destroy-on-close
|
||||||
|
@close="showEdit = false"
|
||||||
@closed="onEditDialogClosed"
|
@closed="onEditDialogClosed"
|
||||||
>
|
>
|
||||||
<!-- 查看:A4 处方笺(药房联样式) -->
|
<!-- 查看:A4 处方笺 -->
|
||||||
<div v-if="editMode === 'view'" v-loading="viewDetailLoading" class="rx-wrap">
|
<div v-if="editMode === 'view'" :aria-busy="viewDetailLoading" class="rx-wrap">
|
||||||
|
<p v-if="viewDetailLoading" class="rx-status" role="status">正在加载处方详情…</p>
|
||||||
|
<div v-if="viewDetailError" class="rx-status rx-status-danger" role="alert">
|
||||||
|
{{ viewDetailError }}
|
||||||
|
<el-button v-if="slipView?.id" link type="primary" @click="handleView(slipView)">重试加载</el-button>
|
||||||
|
</div>
|
||||||
|
<EsignPrescriptionPanel
|
||||||
|
v-if="showEdit && slipView?.id && !viewDetailLoading && !viewDetailError"
|
||||||
|
:key="slipView.id"
|
||||||
|
:prescription-id="Number(slipView.id)"
|
||||||
|
:initial-state="slipView.esign"
|
||||||
|
@status-change="onEsignStatusChange"
|
||||||
|
/>
|
||||||
<!-- 顶部工具栏(不打印 / 不下载) -->
|
<!-- 顶部工具栏(不打印 / 不下载) -->
|
||||||
<div class="rx-toolbar">
|
<div class="rx-toolbar">
|
||||||
<el-tag
|
<el-tag
|
||||||
@@ -306,18 +418,37 @@
|
|||||||
v-else-if="slipView && Number(slipView.audit_status) === 0"
|
v-else-if="slipView && Number(slipView.audit_status) === 0"
|
||||||
type="warning"
|
type="warning"
|
||||||
size="small"
|
size="small"
|
||||||
>待审核</el-tag>
|
>{{ listAuditStatusLabel(slipView) }}</el-tag>
|
||||||
<el-tag v-else-if="slipView" type="danger" size="small">已驳回</el-tag>
|
<el-tag v-else-if="slipView" type="danger" size="small">已驳回</el-tag>
|
||||||
|
<el-tag v-if="slipView && pendingEsignAudit(slipView)" type="warning" size="small" effect="plain">
|
||||||
|
{{ slipView.esign.status_label }}
|
||||||
|
</el-tag>
|
||||||
<div class="flex-1" />
|
<div class="flex-1" />
|
||||||
<el-button :icon="Printer" size="small" @click="handlePrintSlip">打印</el-button>
|
<el-button
|
||||||
|
v-if="slipView && !viewDetailLoading && canOpenPrescriptionAudit(slipView)"
|
||||||
|
v-perms="['cf.prescription/audit']"
|
||||||
|
type="warning"
|
||||||
|
size="small"
|
||||||
|
@click="openAuditDialog(slipView)"
|
||||||
|
>审核</el-button>
|
||||||
|
<el-button
|
||||||
|
v-if="slipView && !viewDetailLoading && !viewDetailError && canReissuePrescription(slipView)"
|
||||||
|
type="primary"
|
||||||
|
size="small"
|
||||||
|
:loading="reissuingPrescriptionId === Number(slipView.id)"
|
||||||
|
:disabled="reissuingPrescriptionId !== 0"
|
||||||
|
@click="handleReissue(slipView)"
|
||||||
|
>重新开方</el-button>
|
||||||
|
<el-button v-if="!requiresOriginalEsignPdf(slipView?.esign)" :icon="Printer" size="small" @click="handlePrintSlip">打印</el-button>
|
||||||
<el-button
|
<el-button
|
||||||
type="primary"
|
type="primary"
|
||||||
:icon="Download"
|
:icon="Download"
|
||||||
size="small"
|
size="small"
|
||||||
:loading="downloadingSlip"
|
:loading="downloadingSlip"
|
||||||
|
:disabled="viewDetailLoading || (requiresOriginalEsignPdf(slipView?.esign) && !slipView?.esign?.can_download)"
|
||||||
@click="handleDownloadSlip"
|
@click="handleDownloadSlip"
|
||||||
>
|
>
|
||||||
下载 PDF (A4)
|
{{ requiresOriginalEsignPdf(slipView?.esign) ? '下载已签原始 PDF' : '下载 PDF (A4)' }}
|
||||||
</el-button>
|
</el-button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -342,8 +473,19 @@
|
|||||||
<div v-if="slipView.audit_remark" class="mt-1">驳回意见:{{ slipView.audit_remark }}</div>
|
<div v-if="slipView.audit_remark" class="mt-1">驳回意见:{{ slipView.audit_remark }}</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- A4 处方纸:统一组件,与全端药房联一比一 -->
|
<el-tabs
|
||||||
<PrescriptionSlip v-if="slipView" ref="rxSlipRef" :data="slipView" />
|
v-if="slipView"
|
||||||
|
v-model="prescriptionTabType"
|
||||||
|
class="rx-slip-tabs"
|
||||||
|
:before-leave="() => !downloadingSlip"
|
||||||
|
>
|
||||||
|
<el-tab-pane label="药房联" name="internal">
|
||||||
|
<PrescriptionSlip v-if="prescriptionTabType === 'internal'" ref="rxSlipRef" :data="slipView" />
|
||||||
|
</el-tab-pane>
|
||||||
|
<el-tab-pane label="处方联" name="user">
|
||||||
|
<PrescriptionSlip v-if="prescriptionTabType === 'user'" ref="rxSlipRef" :data="slipView" variant="user" />
|
||||||
|
</el-tab-pane>
|
||||||
|
</el-tabs>
|
||||||
|
|
||||||
<!-- 审核痕迹(不进入打印区) -->
|
<!-- 审核痕迹(不进入打印区) -->
|
||||||
<div
|
<div
|
||||||
@@ -381,7 +523,7 @@
|
|||||||
:closable="false"
|
:closable="false"
|
||||||
show-icon
|
show-icon
|
||||||
class="mb-4"
|
class="mb-4"
|
||||||
title="保存修改后,该处方将重新进入「待审核」,需审核人员再次通过后方可生效。"
|
title="保存修改后,请由开方医生重新上传并完成签署,再交药师审核。"
|
||||||
/>
|
/>
|
||||||
<el-alert
|
<el-alert
|
||||||
v-if="editMode === 'edit' && Number(editForm.audit_status) === 2"
|
v-if="editMode === 'edit' && Number(editForm.audit_status) === 2"
|
||||||
@@ -392,7 +534,7 @@
|
|||||||
>
|
>
|
||||||
<template #title>当前消费者处方为「已驳回」</template>
|
<template #title>当前消费者处方为「已驳回」</template>
|
||||||
<div class="text-sm mt-1">
|
<div class="text-sm mt-1">
|
||||||
保存修改后将清除驳回并变为「待审核」。{{
|
保存修改后将清除驳回并恢复为「待上传」。{{
|
||||||
editForm.audit_remark ? `上次意见:${editForm.audit_remark}` : ''
|
editForm.audit_remark ? `上次意见:${editForm.audit_remark}` : ''
|
||||||
}}
|
}}
|
||||||
</div>
|
</div>
|
||||||
@@ -442,7 +584,7 @@
|
|||||||
<el-input
|
<el-input
|
||||||
v-model="editForm.patient_name"
|
v-model="editForm.patient_name"
|
||||||
placeholder="请输入患者姓名"
|
placeholder="请输入患者姓名"
|
||||||
:disabled="editMode === 'edit'"
|
:disabled="editMode === 'edit' || (!!reissueContext && editForm.diagnosis_id > 0)"
|
||||||
/>
|
/>
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
</el-col>
|
</el-col>
|
||||||
@@ -984,7 +1126,12 @@
|
|||||||
<el-input v-model="editForm.doctor_name" placeholder="请输入医师姓名" />
|
<el-input v-model="editForm.doctor_name" placeholder="请输入医师姓名" />
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
|
|
||||||
<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">
|
<div class="signature-pad-wrap">
|
||||||
<canvas
|
<canvas
|
||||||
ref="signatureCanvasRef"
|
ref="signatureCanvasRef"
|
||||||
@@ -1009,8 +1156,8 @@
|
|||||||
</template>
|
</template>
|
||||||
<template v-else>
|
<template v-else>
|
||||||
<el-button @click="showEdit = false">取消</el-button>
|
<el-button @click="showEdit = false">取消</el-button>
|
||||||
<el-button type="primary" @click="handleSubmit" :loading="submitLoading">
|
<el-button type="primary" @click="handleSubmit" :loading="submitLoading || esignLoading" :disabled="!esignReady">
|
||||||
确定
|
{{ esignEnabled ? '保存处方草稿' : '确定' }}
|
||||||
</el-button>
|
</el-button>
|
||||||
</template>
|
</template>
|
||||||
</template>
|
</template>
|
||||||
@@ -1530,25 +1677,38 @@
|
|||||||
</template>
|
</template>
|
||||||
</el-dialog>
|
</el-dialog>
|
||||||
|
|
||||||
<el-dialog v-model="auditDialogVisible" title="处方审核" width="480px" destroy-on-close @closed="auditRemark = ''">
|
<el-dialog v-model="auditDialogVisible" title="处方审核" width="min(1280px, 96vw)" top="5vh" append-to-body destroy-on-close @closed="auditRemark = ''">
|
||||||
<p class="text-sm text-gray-600 mb-3">
|
<PrescriptionAuditLayout
|
||||||
通过:处方保持有效。驳回:将同时作废此处方(与诊间「驳回/作废处方」一致)。
|
:prescription-id="auditTargetId"
|
||||||
</p>
|
:doctor-signed-at="auditEsign?.signature_time || auditEsign?.signed_at"
|
||||||
<el-form label-width="80px">
|
:pharmacist-signed-at="auditReview?.signature_time || auditEsign?.review_signature_time"
|
||||||
<el-form-item label="审核意见">
|
>
|
||||||
<el-input
|
<EsignPrescriptionPanel
|
||||||
v-model="auditRemark"
|
v-if="auditDialogVisible"
|
||||||
type="textarea"
|
:key="auditTargetId"
|
||||||
:rows="3"
|
:prescription-id="auditTargetId"
|
||||||
maxlength="500"
|
audit
|
||||||
show-word-limit
|
@review-change="onAuditReviewChange"
|
||||||
placeholder="通过可简要说明;驳回必填"
|
class="mb-3"
|
||||||
/>
|
@status-change="onAuditEsignStatusChange"
|
||||||
</el-form-item>
|
/>
|
||||||
</el-form>
|
<p class="text-sm text-gray-600 mb-3">驳回将同时作废处方。通过时审核意见选填。</p>
|
||||||
|
<el-form label-position="top">
|
||||||
|
<el-form-item label="审核意见">
|
||||||
|
<el-input
|
||||||
|
v-model="auditRemark"
|
||||||
|
type="textarea"
|
||||||
|
:rows="3"
|
||||||
|
maxlength="500"
|
||||||
|
show-word-limit
|
||||||
|
placeholder="驳回时必填"
|
||||||
|
/>
|
||||||
|
</el-form-item>
|
||||||
|
</el-form>
|
||||||
|
</PrescriptionAuditLayout>
|
||||||
<template #footer>
|
<template #footer>
|
||||||
<el-button @click="auditDialogVisible = false">取消</el-button>
|
<el-button @click="auditDialogVisible = false">取消</el-button>
|
||||||
<el-button type="primary" :loading="auditLoading" @click="submitAudit('approve')">审核通过</el-button>
|
<el-button type="primary" :loading="auditLoading" :disabled="!canApproveAudit" @click="submitAudit('approve')">审核通过</el-button>
|
||||||
<el-button type="danger" :loading="auditLoading" @click="submitAudit('reject')">驳回处方</el-button>
|
<el-button type="danger" :loading="auditLoading" @click="submitAudit('reject')">驳回处方</el-button>
|
||||||
</template>
|
</template>
|
||||||
</el-dialog>
|
</el-dialog>
|
||||||
@@ -1565,7 +1725,10 @@ import {
|
|||||||
prescriptionEdit,
|
prescriptionEdit,
|
||||||
prescriptionPatchPatient,
|
prescriptionPatchPatient,
|
||||||
prescriptionDelete,
|
prescriptionDelete,
|
||||||
|
prescriptionVoid,
|
||||||
prescriptionAudit,
|
prescriptionAudit,
|
||||||
|
prescriptionEsignSetConfig,
|
||||||
|
prescriptionSubmitForReview,
|
||||||
prescriptionDetail,
|
prescriptionDetail,
|
||||||
prescriptionOrderCreate,
|
prescriptionOrderCreate,
|
||||||
prescriptionOrderPaidPayOrders,
|
prescriptionOrderPaidPayOrders,
|
||||||
@@ -1584,9 +1747,15 @@ import type { FormInstance, FormRules } from 'element-plus'
|
|||||||
import DaterangePicker from '@/components/daterange-picker/index.vue'
|
import DaterangePicker from '@/components/daterange-picker/index.vue'
|
||||||
import MedicineNameSelect from '@/components/medicine-name-select/index.vue'
|
import MedicineNameSelect from '@/components/medicine-name-select/index.vue'
|
||||||
import PrescriptionSlip from '@/components/prescription-slip/index.vue'
|
import PrescriptionSlip from '@/components/prescription-slip/index.vue'
|
||||||
|
import PrescriptionAuditLayout from '@/components/PrescriptionAuditLayout.vue'
|
||||||
|
import EsignPrescriptionPanel from '@/components/EsignPrescriptionPanel.vue'
|
||||||
|
import { usePrescriptionEsignConfig } from '@/hooks/usePrescriptionEsignConfig'
|
||||||
|
import { canApprovePrescriptionEsign, downloadPrescriptionPdfIfRequired, pendingPrescriptionReviewLabel, requiresOriginalEsignPdf, updatePrescriptionSlipEsign } from '@/utils/prescription-esign'
|
||||||
|
import type { PrescriptionEsignStatus } from '@/api/tcm'
|
||||||
|
import { prescriptionListSigningStatus } from './components/prescription-list-signing-status'
|
||||||
import { Search, Download, Printer, EditPen } from '@element-plus/icons-vue'
|
import { Search, Download, Printer, EditPen } from '@element-plus/icons-vue'
|
||||||
import { computed, onMounted, onActivated, onDeactivated, reactive, ref, watch, nextTick, defineAsyncComponent } from 'vue'
|
import { computed, onMounted, onActivated, onDeactivated, reactive, ref, watch, nextTick, defineAsyncComponent } from 'vue'
|
||||||
import { useRouter } from 'vue-router'
|
import { useRoute, useRouter } from 'vue-router'
|
||||||
import html2canvas from 'html2canvas'
|
import html2canvas from 'html2canvas'
|
||||||
import jsPDF from 'jspdf'
|
import jsPDF from 'jspdf'
|
||||||
|
|
||||||
@@ -1726,6 +1895,7 @@ const SLIP_ADDRESS_LINE = '地址:四川省成都市双流区黄甲街道黄
|
|||||||
|
|
||||||
const userStore = useUserStore()
|
const userStore = useUserStore()
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
|
const route = useRoute()
|
||||||
|
|
||||||
function goBusinessOrderList() {
|
function goBusinessOrderList() {
|
||||||
const hit = router.getRoutes().find((r) => r.meta?.perms === 'tcm.prescriptionOrder/lists')
|
const hit = router.getRoutes().find((r) => r.meta?.perms === 'tcm.prescriptionOrder/lists')
|
||||||
@@ -1768,14 +1938,82 @@ const SIGNATURE_CSS_W = 560
|
|||||||
const SIGNATURE_CSS_H = 168
|
const SIGNATURE_CSS_H = 168
|
||||||
/** 查看模式:处方笺数据源(先列表行,再详情覆盖) */
|
/** 查看模式:处方笺数据源(先列表行,再详情覆盖) */
|
||||||
const slipView = ref<Record<string, any> | null>(null)
|
const slipView = ref<Record<string, any> | null>(null)
|
||||||
|
const { config: esignConfig, enabled: esignEnabled, ready: esignReady, loading: esignLoading, error: esignError, load: loadEsignConfig } = usePrescriptionEsignConfig()
|
||||||
|
|
||||||
|
const canManageCaSigning = computed(() => Number(userStore.userInfo?.root) === 1)
|
||||||
|
const caSigningSettingsVisible = ref(false)
|
||||||
|
const caSigningSettingsEnabled = ref(false)
|
||||||
|
const caSigningSettingsSaving = ref(false)
|
||||||
|
const caSigningSettingsSaveError = ref('')
|
||||||
|
const canSaveCaSigningSettings = computed(
|
||||||
|
() => canManageCaSigning.value && esignReady.value && !esignLoading.value && !caSigningSettingsSaving.value
|
||||||
|
)
|
||||||
|
|
||||||
|
async function loadCaSigningSettings() {
|
||||||
|
if (!canManageCaSigning.value || caSigningSettingsSaving.value) return
|
||||||
|
caSigningSettingsSaveError.value = ''
|
||||||
|
if (await loadEsignConfig()) {
|
||||||
|
caSigningSettingsEnabled.value = esignConfig.value?.enabled === true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function openCaSigningSettings() {
|
||||||
|
if (!canManageCaSigning.value) return
|
||||||
|
caSigningSettingsVisible.value = true
|
||||||
|
void loadCaSigningSettings()
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveCaSigningSettings() {
|
||||||
|
if (!canSaveCaSigningSettings.value) return
|
||||||
|
caSigningSettingsSaving.value = true
|
||||||
|
caSigningSettingsSaveError.value = ''
|
||||||
|
try {
|
||||||
|
const enabled = caSigningSettingsEnabled.value
|
||||||
|
const config = await prescriptionEsignSetConfig({ enabled })
|
||||||
|
if (config?.enabled !== enabled) throw new Error('保存结果与所选设置不一致')
|
||||||
|
esignConfig.value = config
|
||||||
|
caSigningSettingsVisible.value = false
|
||||||
|
feedback.msgSuccess('CA 签名设置已保存')
|
||||||
|
void getLists({ silent: true }).catch(() => {})
|
||||||
|
} catch {
|
||||||
|
caSigningSettingsSaveError.value = '保存未完成,当前选择已保留,请重试。'
|
||||||
|
} finally {
|
||||||
|
caSigningSettingsSaving.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const onEsignStatusChange = (state: PrescriptionEsignStatus) => {
|
||||||
|
const previous = slipView.value?.esign
|
||||||
|
if (slipView.value && state.review_submitted_at !== undefined) {
|
||||||
|
slipView.value.review_submitted_at = state.review_submitted_at
|
||||||
|
slipView.value.can_submit_for_review = state.can_submit_for_review === true
|
||||||
|
slipView.value.can_review_prescription = state.can_review_prescription === true
|
||||||
|
}
|
||||||
|
void updatePrescriptionSlipEsign(slipView.value, state)
|
||||||
|
if (previous?.status !== state.status || previous?.review_signature_time !== state.review_signature_time
|
||||||
|
|| previous?.review_submitted_at !== state.review_submitted_at
|
||||||
|
|| previous?.can_review_prescription !== state.can_review_prescription) {
|
||||||
|
void getLists({ silent: true }).catch(() => {})
|
||||||
|
}
|
||||||
|
}
|
||||||
const viewDetailLoading = ref(false)
|
const viewDetailLoading = ref(false)
|
||||||
|
const viewDetailError = ref('')
|
||||||
|
let viewDetailRequest: AbortController | undefined
|
||||||
|
|
||||||
const roleOptions = ref<Array<{ id: number; name: string }>>([])
|
const roleOptions = ref<Array<{ id: number; name: string }>>([])
|
||||||
|
|
||||||
const auditDialogVisible = ref(false)
|
const auditDialogVisible = ref(false)
|
||||||
|
const uploadingPrescriptionId = ref(0)
|
||||||
|
const voidingPrescriptionId = ref(0)
|
||||||
|
const reissuingPrescriptionId = ref(0)
|
||||||
const auditTargetId = ref(0)
|
const auditTargetId = ref(0)
|
||||||
const auditRemark = ref('')
|
const auditRemark = ref('')
|
||||||
const auditLoading = ref(false)
|
const auditLoading = ref(false)
|
||||||
|
const auditEsign = ref<PrescriptionEsignStatus | null>(null)
|
||||||
|
const auditReview = ref<import('@/api/tcm').PrescriptionEsignReviewStatus | null>(null)
|
||||||
|
const canApproveAudit = computed(() => (
|
||||||
|
canApprovePrescriptionEsign(auditEsign.value) && auditReview.value?.can_approve === true
|
||||||
|
))
|
||||||
|
|
||||||
/** 修正处方笺显示用姓名 / 手机号 */
|
/** 修正处方笺显示用姓名 / 手机号 */
|
||||||
const patchPatientVisible = ref(false)
|
const patchPatientVisible = ref(false)
|
||||||
@@ -2363,9 +2601,9 @@ const editReviveHint = computed(() => {
|
|||||||
const v = editingWasVoid.value
|
const v = editingWasVoid.value
|
||||||
const r = editingWasRejected.value
|
const r = editingWasRejected.value
|
||||||
if (!v && !r) return ''
|
if (!v && !r) return ''
|
||||||
if (v && r) return '当前处方已作废且已驳回。保存后将取消作废、清除驳回,并重新进入待审核。'
|
if (v && r) return '当前处方已作废且已驳回。保存后将取消作废、清除驳回,请重新上传处方。'
|
||||||
if (v) return '当前为已作废处方。保存后将取消作废,并重新进入待审核。'
|
if (v) return '当前为已作废处方。保存后将取消作废,请重新上传处方。'
|
||||||
return '当前为已驳回处方。保存后将清除驳回,并重新进入待审核。'
|
return '当前为已驳回处方。保存后将清除驳回,请重新上传处方。'
|
||||||
})
|
})
|
||||||
|
|
||||||
const slipHerbsList = computed(() => {
|
const slipHerbsList = computed(() => {
|
||||||
@@ -2408,6 +2646,7 @@ const slipDietaryText = computed(() => {
|
|||||||
* A4 处方笺(药房联)相关计算
|
* A4 处方笺(药房联)相关计算
|
||||||
* ============================================================ */
|
* ============================================================ */
|
||||||
const rxSlipRef = ref<InstanceType<typeof PrescriptionSlip> | null>(null)
|
const rxSlipRef = ref<InstanceType<typeof PrescriptionSlip> | null>(null)
|
||||||
|
const prescriptionTabType = ref<'internal' | 'user'>('internal')
|
||||||
const downloadingSlip = ref(false)
|
const downloadingSlip = ref(false)
|
||||||
|
|
||||||
function getRxPaperEl(): HTMLElement | null {
|
function getRxPaperEl(): HTMLElement | null {
|
||||||
@@ -2622,6 +2861,16 @@ function handlePrintSlip() {
|
|||||||
|
|
||||||
/* === 下载 PDF(A4) === */
|
/* === 下载 PDF(A4) === */
|
||||||
async function handleDownloadSlip() {
|
async function handleDownloadSlip() {
|
||||||
|
if (downloadingSlip.value) return
|
||||||
|
downloadingSlip.value = true
|
||||||
|
try {
|
||||||
|
if (await downloadPrescriptionPdfIfRequired(Number(slipView.value?.id))) return
|
||||||
|
} catch (e: any) {
|
||||||
|
feedback.msgError(e?.message || '下载签署文件失败')
|
||||||
|
return
|
||||||
|
} finally {
|
||||||
|
downloadingSlip.value = false
|
||||||
|
}
|
||||||
const node = getRxPaperEl()
|
const node = getRxPaperEl()
|
||||||
if (!node) {
|
if (!node) {
|
||||||
feedback.msgWarning('处方笺尚未渲染完成')
|
feedback.msgWarning('处方笺尚未渲染完成')
|
||||||
@@ -2766,6 +3015,14 @@ const editForm = reactive({
|
|||||||
aux_usage: defaultAuxUsage('浓缩水丸')
|
aux_usage: defaultAuxUsage('浓缩水丸')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const reissueContext = ref<{
|
||||||
|
appointment_id: number
|
||||||
|
patient_id: number
|
||||||
|
phone: string
|
||||||
|
prescription_name: string
|
||||||
|
case_record?: unknown
|
||||||
|
} | null>(null)
|
||||||
|
|
||||||
/** 编辑页:关联业务订单上的服用天数、医助备注(与处方提示一致) */
|
/** 编辑页:关联业务订单上的服用天数、医助备注(与处方提示一致) */
|
||||||
const rxLinkedOrderHint = reactive({
|
const rxLinkedOrderHint = reactive({
|
||||||
loading: false,
|
loading: false,
|
||||||
@@ -2881,7 +3138,7 @@ const rules: FormRules = {
|
|||||||
{
|
{
|
||||||
required: true,
|
required: true,
|
||||||
validator: (_rule, v, cb) => {
|
validator: (_rule, v, cb) => {
|
||||||
if (!v || !String(v).trim()) {
|
if (!esignEnabled.value && (!v || !String(v).trim())) {
|
||||||
cb(new Error('请使用电子签名板手写医师签名'))
|
cb(new Error('请使用电子签名板手写医师签名'))
|
||||||
} else {
|
} else {
|
||||||
cb()
|
cb()
|
||||||
@@ -2908,7 +3165,8 @@ async function fetchPrescriptionLists(params: Record<string, unknown>) {
|
|||||||
|
|
||||||
const { pager, getLists, resetPage } = usePaging({
|
const { pager, getLists, resetPage } = usePaging({
|
||||||
fetchFun: fetchPrescriptionLists,
|
fetchFun: fetchPrescriptionLists,
|
||||||
params: formData
|
params: formData,
|
||||||
|
latestOnly: true
|
||||||
})
|
})
|
||||||
|
|
||||||
function pad2(n: number) {
|
function pad2(n: number) {
|
||||||
@@ -3028,8 +3286,16 @@ function auditStatusTagType(v: number | undefined) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** 业务订单处方审核驳回时,列表「审核状态」主标签显示为已驳回 */
|
/** 业务订单处方审核驳回时,列表「审核状态」主标签显示为已驳回 */
|
||||||
function listAuditStatusLabel(row: { audit_status?: number; business_prescription_audit_rejected?: number }) {
|
function listAuditStatusLabel(row: {
|
||||||
|
audit_status?: number
|
||||||
|
void_status?: number
|
||||||
|
review_submitted_at?: number
|
||||||
|
can_review_prescription?: boolean
|
||||||
|
esign?: PrescriptionEsignStatus
|
||||||
|
business_prescription_audit_rejected?: number
|
||||||
|
}) {
|
||||||
if (Number(row.business_prescription_audit_rejected) === 1) return '已驳回'
|
if (Number(row.business_prescription_audit_rejected) === 1) return '已驳回'
|
||||||
|
if (isPendingPrescriptionAudit(row)) return pendingPrescriptionReviewLabel(row)
|
||||||
return auditStatusLabel(row.audit_status)
|
return auditStatusLabel(row.audit_status)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -3061,6 +3327,50 @@ function isApprovedActivePrescription(row: { audit_status?: number; void_status?
|
|||||||
return Number(row.audit_status) === 1 && Number(row.void_status) !== 1
|
return Number(row.audit_status) === 1 && Number(row.void_status) !== 1
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function isPendingPrescriptionAudit(row: { audit_status?: number | string; void_status?: number | string }) {
|
||||||
|
return (row.audit_status === 0 || row.audit_status === '0') && Number(row.void_status) !== 1
|
||||||
|
}
|
||||||
|
|
||||||
|
type VoidablePrescriptionRow = Parameters<typeof isPendingPrescriptionAudit>[0] & {
|
||||||
|
id?: number | string
|
||||||
|
can_void?: boolean
|
||||||
|
can_submit_for_review?: boolean
|
||||||
|
can_review_prescription?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
function canVoidPendingPrescription(row: VoidablePrescriptionRow) {
|
||||||
|
return isPendingPrescriptionAudit(row) && row.can_void === true
|
||||||
|
}
|
||||||
|
|
||||||
|
async function voidPendingPrescription(row: VoidablePrescriptionRow) {
|
||||||
|
const id = Number(row.id)
|
||||||
|
if (!Number.isSafeInteger(id) || id <= 0 || voidingPrescriptionId.value || !canVoidPendingPrescription(row)) return
|
||||||
|
voidingPrescriptionId.value = id
|
||||||
|
try {
|
||||||
|
await feedback.confirm('确定作废这张处方吗?作废后可重新开方。')
|
||||||
|
await prescriptionVoid({ id, pending_only: true })
|
||||||
|
row.void_status = 1
|
||||||
|
row.can_void = false
|
||||||
|
row.can_submit_for_review = false
|
||||||
|
row.can_review_prescription = false
|
||||||
|
feedback.msgSuccess('处方已作废')
|
||||||
|
await getLists({ silent: true })
|
||||||
|
} catch {
|
||||||
|
// The request interceptor reports failures. Canceling leaves the row untouched.
|
||||||
|
} finally {
|
||||||
|
voidingPrescriptionId.value = 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function canOpenPrescriptionAudit(row: { audit_status?: number | string; void_status?: number | string; can_review_prescription?: boolean }) {
|
||||||
|
return isPendingPrescriptionAudit(row) && row.can_review_prescription === true
|
||||||
|
}
|
||||||
|
|
||||||
|
function pendingEsignAudit(row: { audit_status?: number | string; void_status?: number | string; esign?: PrescriptionEsignStatus }) {
|
||||||
|
return isPendingPrescriptionAudit(row) && row.esign?.required === true && row.esign.awaiting_upload !== true
|
||||||
|
&& !canApprovePrescriptionEsign(row.esign)
|
||||||
|
}
|
||||||
|
|
||||||
function formatAuditTime(ts: number | null | undefined) {
|
function formatAuditTime(ts: number | null | undefined) {
|
||||||
if (!ts) return ''
|
if (!ts) return ''
|
||||||
const d = new Date(ts * 1000)
|
const d = new Date(ts * 1000)
|
||||||
@@ -3129,6 +3439,10 @@ function rowToSlipView(row: any) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function onEditDialogClosed() {
|
function onEditDialogClosed() {
|
||||||
|
viewDetailRequest?.abort()
|
||||||
|
viewDetailRequest = undefined
|
||||||
|
viewDetailLoading.value = false
|
||||||
|
viewDetailError.value = ''
|
||||||
slipView.value = null
|
slipView.value = null
|
||||||
signatureActivePointerId.value = null
|
signatureActivePointerId.value = null
|
||||||
}
|
}
|
||||||
@@ -3235,6 +3549,7 @@ function scheduleEditSignatureInit() {
|
|||||||
if (sig && String(sig).trim().startsWith('data:image') && signatureCanvasRef.value) {
|
if (sig && String(sig).trim().startsWith('data:image') && signatureCanvasRef.value) {
|
||||||
const img = new Image()
|
const img = new Image()
|
||||||
img.onload = () => {
|
img.onload = () => {
|
||||||
|
if (editForm.doctor_signature !== sig) return
|
||||||
const canvas = signatureCanvasRef.value
|
const canvas = signatureCanvasRef.value
|
||||||
const ctx = canvas?.getContext('2d')
|
const ctx = canvas?.getContext('2d')
|
||||||
if (!canvas || !ctx) return
|
if (!canvas || !ctx) return
|
||||||
@@ -3242,7 +3557,7 @@ function scheduleEditSignatureInit() {
|
|||||||
commitSignatureImage()
|
commitSignatureImage()
|
||||||
}
|
}
|
||||||
img.onerror = () => {
|
img.onerror = () => {
|
||||||
commitSignatureImage()
|
if (editForm.doctor_signature === sig) commitSignatureImage()
|
||||||
}
|
}
|
||||||
img.src = sig
|
img.src = sig
|
||||||
}
|
}
|
||||||
@@ -3269,13 +3584,66 @@ function normalizeVisibleRoleIds(row: any): number[] {
|
|||||||
return []
|
return []
|
||||||
}
|
}
|
||||||
|
|
||||||
function openAuditDialog(row: any) {
|
async function submitPrescriptionForReview(row: Record<string, any>) {
|
||||||
auditTargetId.value = row.id
|
if (uploadingPrescriptionId.value || row.can_submit_for_review !== true) return
|
||||||
|
const id = Number(row.id)
|
||||||
|
if (!Number.isSafeInteger(id) || id <= 0) return
|
||||||
|
uploadingPrescriptionId.value = id
|
||||||
|
try {
|
||||||
|
const result = await prescriptionSubmitForReview({ id })
|
||||||
|
const submittedAt = Number(result?.review_submitted_at)
|
||||||
|
if (!Number.isSafeInteger(submittedAt) || submittedAt <= 0) {
|
||||||
|
feedback.msgError('无法确认上传结果,请刷新处方状态后重试')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for (const target of [row, pager.lists.find((item: any) => Number(item.id) === id), slipView.value]) {
|
||||||
|
if (!target || Number(target.id) !== id) continue
|
||||||
|
target.review_submitted_at = submittedAt
|
||||||
|
target.can_submit_for_review = false
|
||||||
|
if (target.esign) target.esign = { ...target.esign, ...result, awaiting_upload: false }
|
||||||
|
}
|
||||||
|
const needsDoctorSignature = row.esign?.required === true && row.esign.status !== 'signed'
|
||||||
|
feedback.msgSuccess(needsDoctorSignature ? '处方已上传,请完成医师签署' : '处方已上传')
|
||||||
|
if (needsDoctorSignature) await handleView(row)
|
||||||
|
await getLists({ silent: true })
|
||||||
|
} catch {
|
||||||
|
// 请求失败时由拦截器显示提示,可重新上传。
|
||||||
|
} finally {
|
||||||
|
uploadingPrescriptionId.value = 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function openAuditDialog(row: Record<string, any>) {
|
||||||
|
if (auditLoading.value || !canOpenPrescriptionAudit(row)) return
|
||||||
|
auditTargetId.value = Number(row.id)
|
||||||
|
auditEsign.value = null
|
||||||
|
auditReview.value = null
|
||||||
auditRemark.value = ''
|
auditRemark.value = ''
|
||||||
auditDialogVisible.value = true
|
auditDialogVisible.value = true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function onAuditEsignStatusChange(state: PrescriptionEsignStatus) {
|
||||||
|
const justSigned = auditEsign.value && !canApproveAudit.value && state.status === 'signed'
|
||||||
|
&& canApprovePrescriptionEsign(state)
|
||||||
|
auditEsign.value = state
|
||||||
|
if (justSigned) {
|
||||||
|
if (Number(slipView.value?.id) === auditTargetId.value && slipView.value) slipView.value.esign = state
|
||||||
|
else void getLists()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function onAuditReviewChange(state: import('@/api/tcm').PrescriptionEsignReviewStatus | null) {
|
||||||
|
auditReview.value = state
|
||||||
|
if (!state?.required) return
|
||||||
|
const row = pager.lists.find((row: any) => Number(row.id) === auditTargetId.value)
|
||||||
|
if (row?.esign && state.state !== row.esign.review_state) {
|
||||||
|
row.esign.review_state = state.state
|
||||||
|
void getLists()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function submitAudit(action: 'approve' | 'reject') {
|
async function submitAudit(action: 'approve' | 'reject') {
|
||||||
|
if (auditLoading.value || (action === 'approve' && !canApproveAudit.value)) return
|
||||||
if (action === 'reject' && !auditRemark.value.trim()) {
|
if (action === 'reject' && !auditRemark.value.trim()) {
|
||||||
feedback.msgError('驳回时请填写审核意见')
|
feedback.msgError('驳回时请填写审核意见')
|
||||||
return
|
return
|
||||||
@@ -3292,6 +3660,7 @@ async function submitAudit(action: 'approve' | 'reject') {
|
|||||||
feedback.msgWarning(auditData.wecom_notify_hint)
|
feedback.msgWarning(auditData.wecom_notify_hint)
|
||||||
}
|
}
|
||||||
auditDialogVisible.value = false
|
auditDialogVisible.value = false
|
||||||
|
if (showEdit.value && Number(slipView.value?.id) === auditTargetId.value) showEdit.value = false
|
||||||
getLists()
|
getLists()
|
||||||
} catch {
|
} catch {
|
||||||
/* 拦截器已提示 */
|
/* 拦截器已提示 */
|
||||||
@@ -3638,6 +4007,7 @@ const removeHerb = (index: number) => {
|
|||||||
|
|
||||||
// 重置表单
|
// 重置表单
|
||||||
const resetForm = () => {
|
const resetForm = () => {
|
||||||
|
reissueContext.value = null
|
||||||
editForm.id = 0
|
editForm.id = 0
|
||||||
editForm.prescription_type = '浓缩水丸'
|
editForm.prescription_type = '浓缩水丸'
|
||||||
editForm.dosage_amount = 1
|
editForm.dosage_amount = 1
|
||||||
@@ -3649,7 +4019,7 @@ const resetForm = () => {
|
|||||||
editForm.gender = 1
|
editForm.gender = 1
|
||||||
editForm.age = 0
|
editForm.age = 0
|
||||||
editForm.visit_no = ''
|
editForm.visit_no = ''
|
||||||
editForm.prescription_date = new Date().toISOString().split('T')[0]
|
editForm.prescription_date = dayRangeStrings(new Date()).start.slice(0, 10)
|
||||||
editForm.tongue = ''
|
editForm.tongue = ''
|
||||||
editForm.tongue_image = ''
|
editForm.tongue_image = ''
|
||||||
editForm.pulse = ''
|
editForm.pulse = ''
|
||||||
@@ -3683,46 +4053,95 @@ const resetForm = () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 新增处方
|
// 新增处方
|
||||||
const handleAdd = () => {
|
const handleAdd = () => openNewPrescription()
|
||||||
|
|
||||||
|
function openNewPrescription(source?: Record<string, any>) {
|
||||||
|
void loadEsignConfig()
|
||||||
|
isLoadingData.value = !!source
|
||||||
resetForm()
|
resetForm()
|
||||||
|
if (source) {
|
||||||
|
fillPrescriptionContents(source)
|
||||||
|
editForm.diagnosis_id = Number(source.diagnosis_id) || 0
|
||||||
|
editForm.visit_no = source.visit_no === source.sn ? '' : String(source.visit_no || '')
|
||||||
|
reissueContext.value = {
|
||||||
|
appointment_id: Number(source.appointment_id) || 0,
|
||||||
|
patient_id: Number(source.patient_id) || 0,
|
||||||
|
phone: String(source.phone || ''),
|
||||||
|
prescription_name: String(source.prescription_name || ''),
|
||||||
|
case_record: editForm.diagnosis_id > 0 ? undefined : source.case_record
|
||||||
|
}
|
||||||
|
}
|
||||||
editForm.doctor_name = String(userStore.userInfo?.name || '')
|
editForm.doctor_name = String(userStore.userInfo?.name || '')
|
||||||
editingWasVoid.value = false
|
editingWasVoid.value = false
|
||||||
editingWasRejected.value = false
|
editingWasRejected.value = false
|
||||||
editMode.value = 'add'
|
editMode.value = 'add'
|
||||||
// 新建时允许watch自动设置默认值
|
|
||||||
isLoadingData.value = false
|
|
||||||
showEdit.value = true
|
showEdit.value = true
|
||||||
nextTick(() => {
|
nextTick(() => {
|
||||||
|
isLoadingData.value = false
|
||||||
formRef.value?.clearValidate()
|
formRef.value?.clearValidate()
|
||||||
scheduleEditSignatureInit()
|
scheduleEditSignatureInit()
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function canReissuePrescription(row: { creator_id?: number | string; void_status?: number | string }) {
|
||||||
|
const doctorId = Number(userStore.userInfo?.id)
|
||||||
|
return Number(row.void_status) === 1 && doctorId > 0 && Number(row.creator_id) === doctorId
|
||||||
|
&& hasPermission(['cf.prescription/add'])
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleReissue(row: { id?: number | string; creator_id?: number | string; void_status?: number | string }) {
|
||||||
|
const id = Number(row.id)
|
||||||
|
if (!Number.isSafeInteger(id) || id <= 0 || reissuingPrescriptionId.value || !canReissuePrescription(row)) return
|
||||||
|
const fromDetail = showEdit.value
|
||||||
|
reissuingPrescriptionId.value = id
|
||||||
|
try {
|
||||||
|
const detail = await prescriptionDetail({ id })
|
||||||
|
if (fromDetail ? !showEdit.value || editMode.value !== 'view' || Number(slipView.value?.id) !== id : showEdit.value) return
|
||||||
|
if (Number(detail?.id) !== id || !canReissuePrescription(detail)) {
|
||||||
|
feedback.msgWarning('这张处方当前无法重新开方,请刷新后查看')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
openNewPrescription(detail)
|
||||||
|
} catch {
|
||||||
|
feedback.msgError('无法加载作废处方,请重试')
|
||||||
|
} finally {
|
||||||
|
reissuingPrescriptionId.value = 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 查看处方(处方笺样式,详情接口补全电话、签名等)
|
// 查看处方(处方笺样式,详情接口补全电话、签名等)
|
||||||
const handleView = async (row: any) => {
|
const handleView = async (row: any) => {
|
||||||
|
const id = Number(row.id)
|
||||||
|
if (!Number.isSafeInteger(id) || id <= 0) return
|
||||||
|
viewDetailRequest?.abort()
|
||||||
|
const request = new AbortController()
|
||||||
|
viewDetailRequest = request
|
||||||
editingWasVoid.value = false
|
editingWasVoid.value = false
|
||||||
editingWasRejected.value = false
|
editingWasRejected.value = false
|
||||||
editMode.value = 'view'
|
editMode.value = 'view'
|
||||||
|
prescriptionTabType.value = 'internal'
|
||||||
slipView.value = rowToSlipView(row)
|
slipView.value = rowToSlipView(row)
|
||||||
showEdit.value = true
|
showEdit.value = true
|
||||||
viewDetailLoading.value = true
|
viewDetailLoading.value = true
|
||||||
|
viewDetailError.value = ''
|
||||||
try {
|
try {
|
||||||
const d = await prescriptionDetail({ id: row.id })
|
const d = await prescriptionDetail({ id }, request.signal)
|
||||||
if (d && typeof d === 'object') {
|
if (request.signal.aborted) return
|
||||||
slipView.value = {
|
if (Number(d?.id) !== id) throw new Error('处方详情与当前处方不一致')
|
||||||
...d,
|
slipView.value = rowToSlipView(d)
|
||||||
herbs: normalizeSlipHerbs((d as any).herbs)
|
} catch {
|
||||||
}
|
if (!request.signal.aborted) viewDetailError.value = '无法加载处方详情,请重试。'
|
||||||
}
|
|
||||||
} catch (e: any) {
|
|
||||||
feedback.msgError(e?.msg || '加载处方详情失败')
|
|
||||||
} finally {
|
} finally {
|
||||||
viewDetailLoading.value = false
|
if (viewDetailRequest === request) {
|
||||||
|
viewDetailRequest = undefined
|
||||||
|
viewDetailLoading.value = false
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 编辑处方
|
// 编辑处方
|
||||||
const handleEdit = async (row: any) => {
|
const handleEdit = async (row: any) => {
|
||||||
|
await loadEsignConfig()
|
||||||
editingWasVoid.value = Number(row.void_status) === 1
|
editingWasVoid.value = Number(row.void_status) === 1
|
||||||
editingWasRejected.value = Number(row.audit_status) === 2
|
editingWasRejected.value = Number(row.audit_status) === 2
|
||||||
editMode.value = 'edit'
|
editMode.value = 'edit'
|
||||||
@@ -3742,8 +4161,34 @@ const handleEdit = async (row: any) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 深拷贝数据到表单
|
|
||||||
editForm.id = src.id
|
editForm.id = src.id
|
||||||
|
fillPrescriptionContents(src)
|
||||||
|
editForm.visit_no = src.visit_no || ''
|
||||||
|
editForm.prescription_date = src.prescription_date || ''
|
||||||
|
editForm.doctor_name = src.doctor_name || ''
|
||||||
|
editForm.doctor_signature = String(src.doctor_signature || '')
|
||||||
|
editForm.is_shared = src.is_shared ?? 0
|
||||||
|
editForm.visible_role_ids = normalizeVisibleRoleIds(src)
|
||||||
|
editForm.audit_status = src.audit_status ?? 1
|
||||||
|
editForm.audit_time = src.audit_time ?? null
|
||||||
|
editForm.audit_by_name = src.audit_by_name || ''
|
||||||
|
editForm.audit_remark = src.audit_remark || ''
|
||||||
|
editForm.diagnosis_id = src.diagnosis_id ?? 0
|
||||||
|
editForm.creator_id = Number(src.creator_id) > 0 ? Number(src.creator_id) : 0
|
||||||
|
editForm.is_system_auto = Number(src.is_system_auto) === 1 ? 1 : 0
|
||||||
|
editForm.business_prescription_audit_rejected = Number(src.business_prescription_audit_rejected) === 1 ? 1 : 0
|
||||||
|
editForm.business_prescription_audit_remark = String(src.business_prescription_audit_remark || '')
|
||||||
|
|
||||||
|
nextTick(() => {
|
||||||
|
isLoadingData.value = false
|
||||||
|
formRef.value?.clearValidate()
|
||||||
|
scheduleEditSignatureInit()
|
||||||
|
})
|
||||||
|
showEdit.value = true
|
||||||
|
void loadRxLinkedOrderHintForEdit(Number(editForm.id))
|
||||||
|
}
|
||||||
|
|
||||||
|
function fillPrescriptionContents(src: Record<string, any>) {
|
||||||
editForm.prescription_type = src.prescription_type || '浓缩水丸'
|
editForm.prescription_type = src.prescription_type || '浓缩水丸'
|
||||||
|
|
||||||
// 确保 dosage_amount 是数字类型,以匹配下拉框的 :value
|
// 确保 dosage_amount 是数字类型,以匹配下拉框的 :value
|
||||||
@@ -3770,14 +4215,12 @@ const handleEdit = async (row: any) => {
|
|||||||
editForm.patient_name = src.patient_name || ''
|
editForm.patient_name = src.patient_name || ''
|
||||||
editForm.gender = src.gender ?? 1
|
editForm.gender = src.gender ?? 1
|
||||||
editForm.age = src.age ?? 0
|
editForm.age = src.age ?? 0
|
||||||
editForm.visit_no = src.visit_no || ''
|
|
||||||
editForm.prescription_date = src.prescription_date || ''
|
|
||||||
editForm.tongue = src.tongue || ''
|
editForm.tongue = src.tongue || ''
|
||||||
editForm.tongue_image = src.tongue_image || ''
|
editForm.tongue_image = src.tongue_image || ''
|
||||||
editForm.pulse = src.pulse || ''
|
editForm.pulse = src.pulse || ''
|
||||||
editForm.pulse_condition = src.pulse_condition || ''
|
editForm.pulse_condition = src.pulse_condition || ''
|
||||||
editForm.clinical_diagnosis = src.clinical_diagnosis || ''
|
editForm.clinical_diagnosis = src.clinical_diagnosis || ''
|
||||||
editForm.herbs = src.herbs ? (src.herbs as any[]).map((h) => normalizeHerbRow(h)) : []
|
editForm.herbs = normalizeSlipHerbs(src.herbs)
|
||||||
editForm.dose_count = src.dose_count ?? 7
|
editForm.dose_count = src.dose_count ?? 7
|
||||||
editForm.dose_unit = src.dose_unit || '剂'
|
editForm.dose_unit = src.dose_unit || '剂'
|
||||||
editForm.usage_days = src.usage_days ?? 7
|
editForm.usage_days = src.usage_days ?? 7
|
||||||
@@ -3786,43 +4229,19 @@ const handleEdit = async (row: any) => {
|
|||||||
editForm.usage_time = src.usage_time || '饭后'
|
editForm.usage_time = src.usage_time || '饭后'
|
||||||
editForm.usage_way = src.usage_way || '温水送服'
|
editForm.usage_way = src.usage_way || '温水送服'
|
||||||
editForm.dietary_taboo = src.dietary_taboo
|
editForm.dietary_taboo = src.dietary_taboo
|
||||||
? (Array.isArray(src.dietary_taboo) ? src.dietary_taboo : String(src.dietary_taboo).split(',').filter((v: string) => v))
|
? (Array.isArray(src.dietary_taboo) ? [...src.dietary_taboo] : String(src.dietary_taboo).split(',').filter((v: string) => v))
|
||||||
: []
|
: []
|
||||||
editForm.usage_notes = src.usage_notes || ''
|
editForm.usage_notes = src.usage_notes || ''
|
||||||
editForm.doctor_name = src.doctor_name || ''
|
|
||||||
editForm.doctor_signature = String(src.doctor_signature || '')
|
|
||||||
editForm.is_shared = src.is_shared ?? 0
|
|
||||||
editForm.visible_role_ids = normalizeVisibleRoleIds(src)
|
|
||||||
editForm.audit_status = src.audit_status ?? 1
|
|
||||||
editForm.audit_time = src.audit_time ?? null
|
|
||||||
editForm.audit_by_name = src.audit_by_name || ''
|
|
||||||
editForm.audit_remark = src.audit_remark || ''
|
|
||||||
editForm.diagnosis_id = src.diagnosis_id ?? 0
|
|
||||||
editForm.creator_id = Number(src.creator_id) > 0 ? Number(src.creator_id) : 0
|
|
||||||
editForm.is_system_auto = Number(src.is_system_auto) === 1 ? 1 : 0
|
|
||||||
editForm.business_prescription_audit_rejected = Number(src.business_prescription_audit_rejected) === 1 ? 1 : 0
|
|
||||||
editForm.business_prescription_audit_remark = String(src.business_prescription_audit_remark || '')
|
|
||||||
Object.assign(
|
Object.assign(
|
||||||
editForm.aux_usage,
|
editForm.aux_usage,
|
||||||
normalizeAuxUsageForm(src.aux_usage, editForm.prescription_type)
|
normalizeAuxUsageForm(src.aux_usage, editForm.prescription_type)
|
||||||
)
|
)
|
||||||
|
|
||||||
// 数据加载完成,重新启用watch
|
|
||||||
// 使用 setTimeout 确保所有数据都已经渲染完成
|
|
||||||
setTimeout(() => {
|
|
||||||
isLoadingData.value = false
|
|
||||||
}, 0)
|
|
||||||
|
|
||||||
showEdit.value = true
|
|
||||||
void loadRxLinkedOrderHintForEdit(Number(editForm.id))
|
|
||||||
nextTick(() => {
|
|
||||||
formRef.value?.clearValidate()
|
|
||||||
scheduleEditSignatureInit()
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 提交表单
|
// 提交表单
|
||||||
const handleSubmit = async () => {
|
const handleSubmit = async () => {
|
||||||
|
if (submitLoading.value) return
|
||||||
|
if (!esignReady.value && !(await loadEsignConfig())) return
|
||||||
if (!formRef.value) return
|
if (!formRef.value) return
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -3831,6 +4250,7 @@ const handleSubmit = async () => {
|
|||||||
// Element Plus:校验失败会 reject,表单项已展示错误,勿再向外抛成 Uncaught
|
// Element Plus:校验失败会 reject,表单项已展示错误,勿再向外抛成 Uncaught
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if (submitLoading.value) return
|
||||||
|
|
||||||
// 验证药材
|
// 验证药材
|
||||||
if (!editForm.herbs || editForm.herbs.length === 0) {
|
if (!editForm.herbs || editForm.herbs.length === 0) {
|
||||||
@@ -3856,16 +4276,25 @@ const handleSubmit = async () => {
|
|||||||
try {
|
try {
|
||||||
const params: Record<string, unknown> = { ...editForm }
|
const params: Record<string, unknown> = { ...editForm }
|
||||||
|
|
||||||
|
let result: any
|
||||||
if (editMode.value === 'add') {
|
if (editMode.value === 'add') {
|
||||||
params.audit_status = 0
|
params.audit_status = 0
|
||||||
await prescriptionAdd(params)
|
if (reissueContext.value) {
|
||||||
feedback.msgSuccess('添加成功,已提交审核')
|
Object.assign(params, reissueContext.value)
|
||||||
|
if (!editForm.visit_no.trim()) delete params.visit_no
|
||||||
|
}
|
||||||
|
result = await prescriptionAdd(params)
|
||||||
} else {
|
} else {
|
||||||
await prescriptionEdit(params)
|
result = await prescriptionEdit(params)
|
||||||
feedback.msgSuccess('保存成功,处方已重新进入待审核')
|
|
||||||
}
|
}
|
||||||
|
if (esignEnabled.value || requiresOriginalEsignPdf(result?.esign)) {
|
||||||
showEdit.value = false
|
const id = Number(result?.id || editForm.id)
|
||||||
|
feedback.msgSuccess(result?.esign?.required ? '处方草稿已保存' : '处方已保存,请核对电子签署状态')
|
||||||
|
await handleView({ ...editForm, id, audit_status: 0, esign: result?.esign })
|
||||||
|
} else {
|
||||||
|
feedback.msgSuccess('处方已保存,请在「已开处方」上传')
|
||||||
|
showEdit.value = false
|
||||||
|
}
|
||||||
getLists()
|
getLists()
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(error)
|
console.error(error)
|
||||||
@@ -3894,6 +4323,7 @@ onActivated(() => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
|
void loadEsignConfig()
|
||||||
await loadRoleOptions()
|
await loadRoleOptions()
|
||||||
await loadRegionData()
|
await loadRegionData()
|
||||||
await loadServicePackageOptions()
|
await loadServicePackageOptions()
|
||||||
@@ -3911,6 +4341,18 @@ onMounted(async () => {
|
|||||||
/* 已登录页仍可无用户信息,保持默认筛选 */
|
/* 已登录页仍可无用户信息,保持默认筛选 */
|
||||||
}
|
}
|
||||||
getLists()
|
getLists()
|
||||||
|
const reviewId = Number(route.query.review_prescription)
|
||||||
|
if (Number.isSafeInteger(reviewId) && reviewId > 0 && hasPermission(['cf.prescription/audit'])) {
|
||||||
|
try {
|
||||||
|
const detail = await prescriptionDetail({ id: reviewId })
|
||||||
|
if (canOpenPrescriptionAudit(detail)) openAuditDialog(detail)
|
||||||
|
else if (isPendingPrescriptionAudit(detail)) feedback.msgWarning(
|
||||||
|
Number(detail.review_submitted_at) > 0 ? '请等开方医生签署并通过验签后再审核' : '请开方医生先上传处方'
|
||||||
|
)
|
||||||
|
} catch {
|
||||||
|
// 请求失败时由拦截器显示提示。
|
||||||
|
}
|
||||||
|
}
|
||||||
})
|
})
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -4079,6 +4521,10 @@ onMounted(async () => {
|
|||||||
margin: -20px;
|
margin: -20px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.rx-slip-tabs :deep(.el-tabs__content) {
|
||||||
|
overflow: visible;
|
||||||
|
}
|
||||||
|
|
||||||
.rx-toolbar {
|
.rx-toolbar {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
|
|||||||
@@ -629,7 +629,7 @@
|
|||||||
@view-prescription="detailData && openPrescriptionView(detailData)"
|
@view-prescription="detailData && openPrescriptionView(detailData)"
|
||||||
@test-gancao-preview="testGancaoPreviewFromDetail"
|
@test-gancao-preview="testGancaoPreviewFromDetail"
|
||||||
@view-patient="openDiagnosisPatientDetailFromOrder"
|
@view-patient="openDiagnosisPatientDetailFromOrder"
|
||||||
@detail-changed="onOrderDetailChanged"
|
@detail-changed="getLists"
|
||||||
>
|
>
|
||||||
<template #header-extra="{ detail }">
|
<template #header-extra="{ detail }">
|
||||||
<div class="flex items-center gap-2 ml-4 shrink-0">
|
<div class="flex items-center gap-2 ml-4 shrink-0">
|
||||||
@@ -1273,12 +1273,10 @@
|
|||||||
<el-dialog
|
<el-dialog
|
||||||
v-model="auditVisible"
|
v-model="auditVisible"
|
||||||
:title="auditTitle"
|
:title="auditTitle"
|
||||||
width="min(480px, 94vw)"
|
:width="auditKind === 'prescription' ? 'min(1280px, 96vw)' : '480px'"
|
||||||
|
:top="auditKind === 'prescription' ? '5vh' : undefined"
|
||||||
destroy-on-close
|
destroy-on-close
|
||||||
:close-on-click-modal="false"
|
@closed="auditRemark = ''"
|
||||||
:close-on-press-escape="!auditSubmitting"
|
|
||||||
:show-close="!auditSubmitting"
|
|
||||||
@closed="resetAuditInput"
|
|
||||||
>
|
>
|
||||||
<el-alert
|
<el-alert
|
||||||
v-if="auditRowData && auditRowData.completion_request === 1"
|
v-if="auditRowData && auditRowData.completion_request === 1"
|
||||||
@@ -1300,17 +1298,28 @@
|
|||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
</el-alert>
|
</el-alert>
|
||||||
<p class="text-[13px] text-gray-500 mb-3 bg-gray-50/80 border border-gray-100 p-2 rounded">驳回时必须填写意见;通过时意见选填。</p>
|
<PrescriptionAuditLayout
|
||||||
<el-input v-model="auditRemark" :disabled="auditSubmitting" type="textarea" :rows="4" maxlength="500" show-word-limit placeholder="在此输入审核意见..." />
|
:prescription-id="auditKind === 'prescription' ? Number(auditRowData?.prescription_id) || 0 : null"
|
||||||
<div v-if="auditKind === 'prescription'" class="mt-4">
|
:doctor-signed-at="auditEsign?.signature_time || auditEsign?.signed_at"
|
||||||
<p class="text-sm font-medium mb-2">审核人签名 <span class="text-red-500">*</span></p>
|
:pharmacist-signed-at="auditReview?.signature_time || auditEsign?.review_signature_time"
|
||||||
<SignaturePad :key="auditSession" v-model="auditSignature" :disabled="auditSubmitting" />
|
>
|
||||||
<p class="text-xs text-gray-500 mt-2">请本人签名后再通过或驳回,每次审核均需重新签署。</p>
|
<EsignPrescriptionPanel
|
||||||
</div>
|
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>
|
<template #footer>
|
||||||
<el-button :disabled="auditSubmitting" @click="auditVisible = false">取消</el-button>
|
<el-button @click="auditVisible = false">取消</el-button>
|
||||||
<el-button type="primary" :loading="auditSubmitting" :disabled="auditKind === 'prescription' && !auditSignature" @click="submitAudit('approve')">同意通过</el-button>
|
<el-button type="primary" :loading="auditSubmitting" :disabled="!canApproveAudit" @click="submitAudit('approve')">同意通过</el-button>
|
||||||
<el-button type="danger" :loading="auditSubmitting" :disabled="auditKind === 'prescription' && !auditSignature" @click="submitAudit('reject')">驳回阻止</el-button>
|
<el-button type="danger" :loading="auditSubmitting" @click="submitAudit('reject')">驳回阻止</el-button>
|
||||||
</template>
|
</template>
|
||||||
</el-dialog>
|
</el-dialog>
|
||||||
|
|
||||||
@@ -1786,7 +1795,7 @@
|
|||||||
v-model="prescriptionViewVisible"
|
v-model="prescriptionViewVisible"
|
||||||
size="920px"
|
size="920px"
|
||||||
:close-on-click-modal="false"
|
:close-on-click-modal="false"
|
||||||
@close="resetPrescriptionView"
|
@close="prescriptionViewVisible = false"
|
||||||
>
|
>
|
||||||
<template #header>
|
<template #header>
|
||||||
<div class="flex items-center justify-between w-full pr-2 gap-3">
|
<div class="flex items-center justify-between w-full pr-2 gap-3">
|
||||||
@@ -1795,6 +1804,7 @@
|
|||||||
<el-button
|
<el-button
|
||||||
size="small"
|
size="small"
|
||||||
:loading="prescriptionSlipExporting"
|
:loading="prescriptionSlipExporting"
|
||||||
|
v-if="!requiresOriginalEsignPdf(prescriptionViewData.esign)"
|
||||||
@click="downloadPrescriptionSlipImage"
|
@click="downloadPrescriptionSlipImage"
|
||||||
>
|
>
|
||||||
下载图片
|
下载图片
|
||||||
@@ -1802,9 +1812,10 @@
|
|||||||
<el-button
|
<el-button
|
||||||
size="small"
|
size="small"
|
||||||
:loading="prescriptionSlipExporting"
|
:loading="prescriptionSlipExporting"
|
||||||
|
:disabled="requiresOriginalEsignPdf(prescriptionViewData.esign) && !prescriptionViewData.esign?.can_download"
|
||||||
@click="downloadPrescriptionSlipPdf"
|
@click="downloadPrescriptionSlipPdf"
|
||||||
>
|
>
|
||||||
下载PDF
|
{{ requiresOriginalEsignPdf(prescriptionViewData.esign) ? '下载已签原始 PDF' : '下载PDF' }}
|
||||||
</el-button>
|
</el-button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -1816,6 +1827,7 @@
|
|||||||
v-model="prescriptionTabType"
|
v-model="prescriptionTabType"
|
||||||
class="mx-4 mt-2"
|
class="mx-4 mt-2"
|
||||||
style="margin-bottom: 0; z-index: 1; position: relative"
|
style="margin-bottom: 0; z-index: 1; position: relative"
|
||||||
|
:before-leave="() => !prescriptionSlipExporting"
|
||||||
>
|
>
|
||||||
<el-tab-pane label="药房联" name="internal" />
|
<el-tab-pane label="药房联" name="internal" />
|
||||||
<el-tab-pane label="处方联" name="user" />
|
<el-tab-pane label="处方联" name="user" />
|
||||||
@@ -1869,6 +1881,13 @@
|
|||||||
<div v-if="prescriptionViewData.audit_remark" class="mt-1">驳回意见:{{ prescriptionViewData.audit_remark }}</div>
|
<div v-if="prescriptionViewData.audit_remark" class="mt-1">驳回意见:{{ prescriptionViewData.audit_remark }}</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<EsignPrescriptionPanel
|
||||||
|
v-if="prescriptionViewVisible && prescriptionViewData && !prescriptionViewLoading"
|
||||||
|
:key="prescriptionViewData.id"
|
||||||
|
:prescription-id="Number(prescriptionViewData.id)"
|
||||||
|
:initial-state="prescriptionViewData.esign"
|
||||||
|
@status-change="updatePrescriptionSlipEsign(prescriptionViewData, $event)"
|
||||||
|
/>
|
||||||
<PrescriptionSlip
|
<PrescriptionSlip
|
||||||
v-if="prescriptionViewData"
|
v-if="prescriptionViewData"
|
||||||
ref="rxSlipRef"
|
ref="rxSlipRef"
|
||||||
@@ -2071,8 +2090,6 @@ import { computed, onMounted, reactive, ref, nextTick, watch, defineAsyncCompone
|
|||||||
import { useRoute } from 'vue-router'
|
import { useRoute } from 'vue-router'
|
||||||
import { ArrowDown, InfoFilled, QuestionFilled, Search, Calendar, Document, Link as LinkIcon, Wallet } from '@element-plus/icons-vue'
|
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 ListTimeFilter from '@/components/list-time-filter/index.vue'
|
||||||
import SignaturePad from '@/components/signature-pad/index.vue'
|
|
||||||
import { loadOrderPrescriptionSlip } from './components/order-prescription-slip'
|
|
||||||
import PrescriptionOrderDetailDrawer from './components/PrescriptionOrderDetailDrawer.vue'
|
import PrescriptionOrderDetailDrawer from './components/PrescriptionOrderDetailDrawer.vue'
|
||||||
import PrescriptionOrderTimeDialog from './components/PrescriptionOrderTimeDialog.vue'
|
import PrescriptionOrderTimeDialog from './components/PrescriptionOrderTimeDialog.vue'
|
||||||
import GancaoSubmissionReconcileButton from './components/GancaoSubmissionReconcileButton.vue'
|
import GancaoSubmissionReconcileButton from './components/GancaoSubmissionReconcileButton.vue'
|
||||||
@@ -2133,11 +2150,16 @@ import {
|
|||||||
prescriptionOrderLinkPayOrder,
|
prescriptionOrderLinkPayOrder,
|
||||||
prescriptionOrderUploadToPharmacy,
|
prescriptionOrderUploadToPharmacy,
|
||||||
prescriptionOrderPreviewGancaoRecipel,
|
prescriptionOrderPreviewGancaoRecipel,
|
||||||
|
prescriptionDetail,
|
||||||
prescriptionLibraryLists,
|
prescriptionLibraryLists,
|
||||||
getDoctors,
|
getDoctors,
|
||||||
getAssistants
|
getAssistants
|
||||||
} from '@/api/tcm'
|
} from '@/api/tcm'
|
||||||
import PrescriptionSlip from '@/components/prescription-slip/index.vue'
|
import PrescriptionSlip from '@/components/prescription-slip/index.vue'
|
||||||
|
import EsignPrescriptionPanel from '@/components/EsignPrescriptionPanel.vue'
|
||||||
|
import PrescriptionAuditLayout from '@/components/PrescriptionAuditLayout.vue'
|
||||||
|
import type { PrescriptionEsignStatus } from '@/api/tcm'
|
||||||
|
import { canApprovePrescriptionEsign, downloadPrescriptionPdfIfRequired, requiresOriginalEsignPdf, updatePrescriptionSlipEsign } from '@/utils/prescription-esign'
|
||||||
import html2canvas from 'html2canvas'
|
import html2canvas from 'html2canvas'
|
||||||
import { jsPDF } from 'jspdf'
|
import { jsPDF } from 'jspdf'
|
||||||
import { getDictData } from '@/api/app'
|
import { getDictData } from '@/api/app'
|
||||||
@@ -2953,10 +2975,10 @@ function canEditRow(row: {
|
|||||||
return fs === 1 || fs === 2
|
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)
|
const fs = Number(row.fulfillment_status)
|
||||||
if (fs === 3 || fs === 4 || fs === 6) return false
|
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: {
|
function canPayAudit(row: {
|
||||||
@@ -3146,11 +3168,6 @@ async function onOrderTimeSaved(id: number) {
|
|||||||
/** 当前详情数据(组件内部 ref 的桥接;可原地修改属性,整体刷新请用 detailDrawerRef.refresh()) */
|
/** 当前详情数据(组件内部 ref 的桥接;可原地修改属性,整体刷新请用 detailDrawerRef.refresh()) */
|
||||||
const detailData = computed(() => (detailDrawerRef.value?.detail ?? null) as Record<string, any> | null)
|
const detailData = computed(() => (detailDrawerRef.value?.detail ?? null) as Record<string, any> | null)
|
||||||
|
|
||||||
async function onOrderDetailChanged() {
|
|
||||||
getLists()
|
|
||||||
if (detailData.value?.id) await refreshOpenPrescriptionView(Number(detailData.value.id))
|
|
||||||
}
|
|
||||||
|
|
||||||
const detailPrescription = computed(() => {
|
const detailPrescription = computed(() => {
|
||||||
const p = detailData.value?.prescription
|
const p = detailData.value?.prescription
|
||||||
return p && typeof p === 'object' ? p : null
|
return p && typeof p === 'object' ? p : null
|
||||||
@@ -3708,60 +3725,52 @@ const auditKind = ref<'prescription' | 'payment'>('prescription')
|
|||||||
const auditTargetId = ref(0)
|
const auditTargetId = ref(0)
|
||||||
const auditRowData = ref<any>(null)
|
const auditRowData = ref<any>(null)
|
||||||
const auditRemark = ref('')
|
const auditRemark = ref('')
|
||||||
const auditSignature = ref('')
|
|
||||||
const auditSession = ref(0)
|
|
||||||
const auditSubmitting = ref(false)
|
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(() =>
|
const auditTitle = computed(() =>
|
||||||
auditKind.value === 'prescription' ? '处方业务审核' : '关联支付单审核'
|
auditKind.value === 'prescription' ? '处方业务审核' : '关联支付单审核'
|
||||||
)
|
)
|
||||||
|
|
||||||
function resetAuditInput() {
|
function openAudit(row: Record<string, any>, kind: 'prescription' | 'payment') {
|
||||||
if (auditSubmitting.value) return
|
if (auditSubmitting.value) return
|
||||||
auditRemark.value = ''
|
if (kind === 'prescription' && !canRxAudit(row)) return
|
||||||
auditSignature.value = ''
|
|
||||||
auditSession.value++
|
|
||||||
}
|
|
||||||
|
|
||||||
function openAudit(row: { id: number }, kind: 'prescription' | 'payment') {
|
|
||||||
if (auditSubmitting.value || !Number(row.id)) return
|
|
||||||
auditKind.value = kind
|
auditKind.value = kind
|
||||||
auditTargetId.value = row.id
|
auditTargetId.value = Number(row.id)
|
||||||
auditRowData.value = row
|
auditRowData.value = row
|
||||||
resetAuditInput()
|
auditEsign.value = null
|
||||||
|
auditReview.value = null
|
||||||
|
auditRemark.value = ''
|
||||||
auditVisible.value = true
|
auditVisible.value = true
|
||||||
}
|
}
|
||||||
|
|
||||||
async function submitAudit(action: 'approve' | 'reject') {
|
async function submitAudit(action: 'approve' | 'reject') {
|
||||||
if (auditSubmitting.value || !auditVisible.value || !auditTargetId.value) return
|
if (auditSubmitting.value || (action === 'approve' && !canApproveAudit.value)) return
|
||||||
if (auditKind.value === 'prescription' && !auditSignature.value.trim()) {
|
|
||||||
feedback.msgError('请先手写审核人签名')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (action === 'reject' && !auditRemark.value.trim()) {
|
if (action === 'reject' && !auditRemark.value.trim()) {
|
||||||
feedback.msgError('驳回或阻止时必须填写明确的审核意见')
|
feedback.msgError('驳回或阻止时必须填写明确的审核意见')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
auditSubmitting.value = true
|
auditSubmitting.value = true
|
||||||
const targetId = auditTargetId.value
|
|
||||||
try {
|
try {
|
||||||
const params = {
|
const params = {
|
||||||
id: targetId,
|
id: auditTargetId.value,
|
||||||
action,
|
action,
|
||||||
remark: auditRemark.value.trim()
|
remark: auditRemark.value.trim()
|
||||||
}
|
}
|
||||||
if (auditKind.value === 'prescription') {
|
if (auditKind.value === 'prescription') {
|
||||||
await prescriptionOrderAuditPrescription({ ...params, signature: auditSignature.value })
|
await prescriptionOrderAuditPrescription(params)
|
||||||
} else {
|
} else {
|
||||||
await prescriptionOrderAuditPayment(params)
|
await prescriptionOrderAuditPayment(params)
|
||||||
}
|
}
|
||||||
feedback.msgSuccess(action === 'approve' ? '审核通过成功' : '已成功驳回该单')
|
feedback.msgSuccess(action === 'approve' ? '审核通过成功' : '已成功驳回该单')
|
||||||
auditVisible.value = false
|
auditVisible.value = false
|
||||||
auditSignature.value = ''
|
|
||||||
getLists()
|
getLists()
|
||||||
// 若详情 Drawer 正在打开,同步刷新详情数据
|
// 若详情 Drawer 正在打开,同步刷新详情数据
|
||||||
await detailDrawerRef.value?.refreshIfCurrent(targetId)
|
await detailDrawerRef.value?.refreshIfCurrent(auditTargetId.value)
|
||||||
await refreshOpenPrescriptionView(targetId)
|
|
||||||
} catch {
|
} catch {
|
||||||
/* 拦截器已提示 */
|
/* 拦截器已提示 */
|
||||||
} finally {
|
} finally {
|
||||||
@@ -3961,6 +3970,8 @@ onMounted(async () => {
|
|||||||
applyRouteQueryToPrescriptionOrderList()
|
applyRouteQueryToPrescriptionOrderList()
|
||||||
await nextTick()
|
await nextTick()
|
||||||
getLists()
|
getLists()
|
||||||
|
const reviewOrderId = Number(route.query.review_order)
|
||||||
|
if (Number.isSafeInteger(reviewOrderId) && reviewOrderId > 0) await openDetail(reviewOrderId)
|
||||||
})
|
})
|
||||||
|
|
||||||
// ─── 快捷填写快递单号 ────────────────────────────────────────────
|
// ─── 快捷填写快递单号 ────────────────────────────────────────────
|
||||||
@@ -4541,7 +4552,6 @@ async function confirmRevokeRxAudit(row: { id: number }) {
|
|||||||
feedback.msgSuccess('处方审核已撤回')
|
feedback.msgSuccess('处方审核已撤回')
|
||||||
getLists()
|
getLists()
|
||||||
await detailDrawerRef.value?.refreshIfCurrent(row.id)
|
await detailDrawerRef.value?.refreshIfCurrent(row.id)
|
||||||
await refreshOpenPrescriptionView(row.id)
|
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
if (e !== 'cancel' && e !== 'close') {
|
if (e !== 'cancel' && e !== 'close') {
|
||||||
/* 拦截器已提示 */
|
/* 拦截器已提示 */
|
||||||
@@ -4578,8 +4588,6 @@ const SLIP_ADDRESS_LINE = '地址:四川省成都市双流区黄甲街道黄
|
|||||||
const prescriptionViewVisible = ref(false)
|
const prescriptionViewVisible = ref(false)
|
||||||
const prescriptionViewLoading = ref(false)
|
const prescriptionViewLoading = ref(false)
|
||||||
const prescriptionViewData = ref<any>(null)
|
const prescriptionViewData = ref<any>(null)
|
||||||
const prescriptionViewOrderId = ref(0)
|
|
||||||
let prescriptionViewRequestId = 0
|
|
||||||
/** 药房联辅方标题:处方库中该辅方模板的 prescription_name(导入或药材匹配解析) */
|
/** 药房联辅方标题:处方库中该辅方模板的 prescription_name(导入或药材匹配解析) */
|
||||||
const slipAuxLibraryName = ref('')
|
const slipAuxLibraryName = ref('')
|
||||||
/** 查看处方联次:药房联 / 处方联 */
|
/** 查看处方联次:药房联 / 处方联 */
|
||||||
@@ -4972,35 +4980,21 @@ async function resolveSlipAuxLibraryName(data: Record<string, unknown>): Promise
|
|||||||
return ''
|
return ''
|
||||||
}
|
}
|
||||||
|
|
||||||
function resetPrescriptionView() {
|
async function openPrescriptionView(row: any) {
|
||||||
prescriptionViewRequestId++
|
if (!row.prescription_id) {
|
||||||
prescriptionViewOrderId.value = 0
|
feedback.msgWarning('该订单未关联处方')
|
||||||
prescriptionViewData.value = null
|
|
||||||
prescriptionViewLoading.value = false
|
|
||||||
}
|
|
||||||
|
|
||||||
async function refreshOpenPrescriptionView(orderId: number) {
|
|
||||||
if (!prescriptionViewVisible.value || prescriptionViewOrderId.value !== Number(orderId)) return
|
|
||||||
await openPrescriptionView({ id: orderId, prescription_id: prescriptionViewData.value?.id }, true)
|
|
||||||
}
|
|
||||||
|
|
||||||
async function openPrescriptionView(orderRow: any, preserveTab = false) {
|
|
||||||
const orderId = Number(orderRow?.id)
|
|
||||||
if (!(orderId > 0)) {
|
|
||||||
feedback.msgWarning('缺少业务订单信息,请重新打开订单详情')
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
const requestId = ++prescriptionViewRequestId
|
|
||||||
prescriptionViewOrderId.value = orderId
|
|
||||||
prescriptionViewVisible.value = true
|
prescriptionViewVisible.value = true
|
||||||
prescriptionViewLoading.value = true
|
prescriptionViewLoading.value = true
|
||||||
prescriptionViewData.value = null
|
prescriptionViewData.value = null
|
||||||
slipAuxLibraryName.value = ''
|
slipAuxLibraryName.value = ''
|
||||||
if (!preserveTab) prescriptionTabType.value = 'internal'
|
prescriptionTabType.value = 'internal'
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const { order: row, prescription: base } = await loadOrderPrescriptionSlip(orderId, Number(orderRow.prescription_id))
|
const res: any = await prescriptionDetail({ id: row.prescription_id })
|
||||||
if (requestId !== prescriptionViewRequestId) return
|
const base = res?.data ?? res ?? null
|
||||||
if (base) {
|
if (base) {
|
||||||
const md = row.medication_days
|
const md = row.medication_days
|
||||||
const merged: Record<string, unknown> = { ...base }
|
const merged: Record<string, unknown> = { ...base }
|
||||||
@@ -5030,19 +5024,17 @@ async function openPrescriptionView(orderRow: any, preserveTab = false) {
|
|||||||
merged.appointment_id = Number(linkedAp.id)
|
merged.appointment_id = Number(linkedAp.id)
|
||||||
}
|
}
|
||||||
prescriptionViewData.value = merged
|
prescriptionViewData.value = merged
|
||||||
const auxLibraryName = await resolveSlipAuxLibraryName(merged)
|
slipAuxLibraryName.value = await resolveSlipAuxLibraryName(merged)
|
||||||
if (requestId === prescriptionViewRequestId) slipAuxLibraryName.value = auxLibraryName
|
|
||||||
} else {
|
} else {
|
||||||
prescriptionViewData.value = null
|
prescriptionViewData.value = null
|
||||||
slipAuxLibraryName.value = ''
|
slipAuxLibraryName.value = ''
|
||||||
}
|
}
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
if (requestId !== prescriptionViewRequestId) return
|
|
||||||
feedback.msgError(e?.message || '加载处方详情失败')
|
feedback.msgError(e?.message || '加载处方详情失败')
|
||||||
prescriptionViewVisible.value = false
|
prescriptionViewVisible.value = false
|
||||||
slipAuxLibraryName.value = ''
|
slipAuxLibraryName.value = ''
|
||||||
} finally {
|
} finally {
|
||||||
if (requestId === prescriptionViewRequestId) prescriptionViewLoading.value = false
|
prescriptionViewLoading.value = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -5162,6 +5154,7 @@ async function downloadPrescriptionSlipPdf() {
|
|||||||
if (!prescriptionViewData.value) return
|
if (!prescriptionViewData.value) return
|
||||||
prescriptionSlipExporting.value = true
|
prescriptionSlipExporting.value = true
|
||||||
try {
|
try {
|
||||||
|
if (await downloadPrescriptionPdfIfRequired(Number(prescriptionViewData.value.id))) return
|
||||||
const canvas = await capturePrescriptionSlipCanvas()
|
const canvas = await capturePrescriptionSlipCanvas()
|
||||||
const imgData = canvas.toDataURL('image/jpeg', 0.95)
|
const imgData = canvas.toDataURL('image/jpeg', 0.95)
|
||||||
/**
|
/**
|
||||||
@@ -5193,8 +5186,8 @@ async function downloadPrescriptionSlipPdf() {
|
|||||||
}
|
}
|
||||||
pdf.save(`${slipDownloadBaseName()}.pdf`)
|
pdf.save(`${slipDownloadBaseName()}.pdf`)
|
||||||
feedback.msgSuccess('PDF已下载')
|
feedback.msgSuccess('PDF已下载')
|
||||||
} catch {
|
} catch (e: any) {
|
||||||
feedback.msgError('下载PDF失败')
|
feedback.msgError(e?.message || '下载PDF失败')
|
||||||
} finally {
|
} finally {
|
||||||
prescriptionSlipExporting.value = false
|
prescriptionSlipExporting.value = false
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1258,14 +1258,6 @@
|
|||||||
<el-descriptions-item label="处方审核意见" :span="3">
|
<el-descriptions-item label="处方审核意见" :span="3">
|
||||||
<span class="po-audit-remark">{{ detailData.prescription_audit_remark || '—' }}</span>
|
<span class="po-audit-remark">{{ detailData.prescription_audit_remark || '—' }}</span>
|
||||||
</el-descriptions-item>
|
</el-descriptions-item>
|
||||||
<el-descriptions-item v-if="detailData.prescription_audit_signature" label="审核人签名" :span="3">
|
|
||||||
<AuditSignatureRecord
|
|
||||||
:signature="detailData.prescription_audit_signature"
|
|
||||||
:signed-by="detailData.prescription_audit_signed_by"
|
|
||||||
:signed-name="detailData.prescription_audit_signed_name"
|
|
||||||
:signed-at="detailData.prescription_audit_signed_at"
|
|
||||||
/>
|
|
||||||
</el-descriptions-item>
|
|
||||||
<el-descriptions-item label="支付审核意见" :span="3">
|
<el-descriptions-item label="支付审核意见" :span="3">
|
||||||
<span class="po-audit-remark">{{ detailData.payment_slip_audit_remark || '—' }}</span>
|
<span class="po-audit-remark">{{ detailData.payment_slip_audit_remark || '—' }}</span>
|
||||||
</el-descriptions-item>
|
</el-descriptions-item>
|
||||||
@@ -1381,13 +1373,6 @@
|
|||||||
<el-tag size="small" type="info">{{ logActionText(log.action) }}</el-tag>
|
<el-tag size="small" type="info">{{ logActionText(log.action) }}</el-tag>
|
||||||
</div>
|
</div>
|
||||||
<span :class="idx === 0 ? 'text-gray-800 font-medium' : 'text-gray-500'">{{ log.summary }}</span>
|
<span :class="idx === 0 ? 'text-gray-800 font-medium' : 'text-gray-500'">{{ log.summary }}</span>
|
||||||
<AuditSignatureRecord
|
|
||||||
v-if="log.audit_signature"
|
|
||||||
:signature="log.audit_signature"
|
|
||||||
:signed-by="log.admin_id"
|
|
||||||
:signed-name="log.admin_name"
|
|
||||||
:signed-at="log.create_time"
|
|
||||||
/>
|
|
||||||
</el-timeline-item>
|
</el-timeline-item>
|
||||||
</el-timeline>
|
</el-timeline>
|
||||||
<el-empty v-else description="暂无操作日志" :image-size="64" />
|
<el-empty v-else description="暂无操作日志" :image-size="64" />
|
||||||
@@ -1855,13 +1840,11 @@
|
|||||||
<el-dialog
|
<el-dialog
|
||||||
v-model="auditVisible"
|
v-model="auditVisible"
|
||||||
:title="auditTitle"
|
:title="auditTitle"
|
||||||
width="92%"
|
:width="auditKind === 'prescription' ? 'min(1280px, 96vw)' : '92%'"
|
||||||
|
:top="auditKind === 'prescription' ? '5vh' : undefined"
|
||||||
destroy-on-close
|
destroy-on-close
|
||||||
class="po-h5-dialog"
|
class="po-h5-dialog"
|
||||||
:close-on-click-modal="false"
|
@closed="auditRemark = ''"
|
||||||
:close-on-press-escape="!auditSubmitting"
|
|
||||||
:show-close="!auditSubmitting"
|
|
||||||
@closed="resetAuditInput"
|
|
||||||
>
|
>
|
||||||
<el-alert
|
<el-alert
|
||||||
v-if="auditRowData && auditRowData.completion_request === 1"
|
v-if="auditRowData && auditRowData.completion_request === 1"
|
||||||
@@ -1883,17 +1866,28 @@
|
|||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
</el-alert>
|
</el-alert>
|
||||||
<p class="text-[13px] text-gray-500 mb-3 bg-gray-50/80 border border-gray-100 p-2 rounded">驳回时必须填写意见;通过时意见选填。</p>
|
<PrescriptionAuditLayout
|
||||||
<el-input v-model="auditRemark" :disabled="auditSubmitting" type="textarea" :rows="4" maxlength="500" show-word-limit placeholder="在此输入审核意见..." />
|
:prescription-id="auditKind === 'prescription' ? Number(auditRowData?.prescription_id) || 0 : null"
|
||||||
<div v-if="auditKind === 'prescription'" class="mt-4">
|
:doctor-signed-at="auditEsign?.signature_time || auditEsign?.signed_at"
|
||||||
<p class="text-sm font-medium mb-2">审核人签名 <span class="text-red-500">*</span></p>
|
:pharmacist-signed-at="auditReview?.signature_time || auditEsign?.review_signature_time"
|
||||||
<SignaturePad :key="auditSession" v-model="auditSignature" :disabled="auditSubmitting" />
|
>
|
||||||
<p class="text-xs text-gray-500 mt-2">请本人签名后再通过或驳回,每次审核均需重新签署。</p>
|
<EsignPrescriptionPanel
|
||||||
</div>
|
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>
|
<template #footer>
|
||||||
<el-button :disabled="auditSubmitting" @click="auditVisible = false">取消</el-button>
|
<el-button @click="auditVisible = false">取消</el-button>
|
||||||
<el-button type="primary" :loading="auditSubmitting" :disabled="auditKind === 'prescription' && !auditSignature" @click="submitAudit('approve')">同意通过</el-button>
|
<el-button type="primary" :loading="auditSubmitting" :disabled="!canApproveAudit" @click="submitAudit('approve')">同意通过</el-button>
|
||||||
<el-button type="danger" :loading="auditSubmitting" :disabled="auditKind === 'prescription' && !auditSignature" @click="submitAudit('reject')">驳回阻止</el-button>
|
<el-button type="danger" :loading="auditSubmitting" @click="submitAudit('reject')">驳回阻止</el-button>
|
||||||
</template>
|
</template>
|
||||||
</el-dialog>
|
</el-dialog>
|
||||||
|
|
||||||
@@ -2399,9 +2393,9 @@
|
|||||||
v-model="prescriptionViewVisible"
|
v-model="prescriptionViewVisible"
|
||||||
size="100%"
|
size="100%"
|
||||||
direction="btt"
|
direction="btt"
|
||||||
@close="resetPrescriptionView"
|
|
||||||
class="po-h5-drawer"
|
class="po-h5-drawer"
|
||||||
:close-on-click-modal="false"
|
:close-on-click-modal="false"
|
||||||
|
@close="prescriptionViewVisible = false"
|
||||||
>
|
>
|
||||||
<template #header>
|
<template #header>
|
||||||
<div class="flex items-center justify-between w-full pr-2 gap-3">
|
<div class="flex items-center justify-between w-full pr-2 gap-3">
|
||||||
@@ -2410,6 +2404,7 @@
|
|||||||
<el-button
|
<el-button
|
||||||
size="small"
|
size="small"
|
||||||
:loading="prescriptionSlipExporting"
|
:loading="prescriptionSlipExporting"
|
||||||
|
v-if="!requiresOriginalEsignPdf(prescriptionViewData.esign)"
|
||||||
@click="downloadPrescriptionSlipImage"
|
@click="downloadPrescriptionSlipImage"
|
||||||
>
|
>
|
||||||
下载图片
|
下载图片
|
||||||
@@ -2417,9 +2412,10 @@
|
|||||||
<el-button
|
<el-button
|
||||||
size="small"
|
size="small"
|
||||||
:loading="prescriptionSlipExporting"
|
:loading="prescriptionSlipExporting"
|
||||||
|
:disabled="requiresOriginalEsignPdf(prescriptionViewData.esign) && !prescriptionViewData.esign?.can_download"
|
||||||
@click="downloadPrescriptionSlipPdf"
|
@click="downloadPrescriptionSlipPdf"
|
||||||
>
|
>
|
||||||
下载PDF
|
{{ requiresOriginalEsignPdf(prescriptionViewData.esign) ? '下载已签原始 PDF' : '下载PDF' }}
|
||||||
</el-button>
|
</el-button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -2431,6 +2427,7 @@
|
|||||||
v-model="prescriptionTabType"
|
v-model="prescriptionTabType"
|
||||||
class="mx-4 mt-2"
|
class="mx-4 mt-2"
|
||||||
style="margin-bottom: 0; z-index: 1; position: relative"
|
style="margin-bottom: 0; z-index: 1; position: relative"
|
||||||
|
:before-leave="() => !prescriptionSlipExporting"
|
||||||
>
|
>
|
||||||
<el-tab-pane label="药房联" name="internal" />
|
<el-tab-pane label="药房联" name="internal" />
|
||||||
<el-tab-pane label="处方联" name="user" />
|
<el-tab-pane label="处方联" name="user" />
|
||||||
@@ -2484,6 +2481,13 @@
|
|||||||
<div v-if="prescriptionViewData.audit_remark" class="mt-1">驳回意见:{{ prescriptionViewData.audit_remark }}</div>
|
<div v-if="prescriptionViewData.audit_remark" class="mt-1">驳回意见:{{ prescriptionViewData.audit_remark }}</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<EsignPrescriptionPanel
|
||||||
|
v-if="prescriptionViewVisible && prescriptionViewData && !prescriptionViewLoading"
|
||||||
|
:key="prescriptionViewData.id"
|
||||||
|
:prescription-id="Number(prescriptionViewData.id)"
|
||||||
|
:initial-state="prescriptionViewData.esign"
|
||||||
|
@status-change="updatePrescriptionSlipEsign(prescriptionViewData, $event)"
|
||||||
|
/>
|
||||||
<PrescriptionSlip
|
<PrescriptionSlip
|
||||||
v-if="prescriptionViewData"
|
v-if="prescriptionViewData"
|
||||||
ref="rxSlipRef"
|
ref="rxSlipRef"
|
||||||
@@ -2657,6 +2661,7 @@
|
|||||||
|
|
||||||
<script lang="ts" setup name="prescriptionOrderListH5">
|
<script lang="ts" setup name="prescriptionOrderListH5">
|
||||||
import { computed, onMounted, reactive, ref, nextTick, watch, defineAsyncComponent } from 'vue'
|
import { computed, onMounted, reactive, ref, nextTick, watch, defineAsyncComponent } from 'vue'
|
||||||
|
import { useRoute } from 'vue-router'
|
||||||
import {
|
import {
|
||||||
Refresh,
|
Refresh,
|
||||||
Loading,
|
Loading,
|
||||||
@@ -2670,9 +2675,6 @@ import {
|
|||||||
User
|
User
|
||||||
} from '@element-plus/icons-vue'
|
} from '@element-plus/icons-vue'
|
||||||
import ListTimeFilter from '@/components/list-time-filter/index.vue'
|
import ListTimeFilter from '@/components/list-time-filter/index.vue'
|
||||||
import SignaturePad from '@/components/signature-pad/index.vue'
|
|
||||||
import { loadOrderPrescriptionSlip } from './components/order-prescription-slip'
|
|
||||||
import AuditSignatureRecord from './components/AuditSignatureRecord.vue'
|
|
||||||
import PrescriptionOrderTimeDialog from './components/PrescriptionOrderTimeDialog.vue'
|
import PrescriptionOrderTimeDialog from './components/PrescriptionOrderTimeDialog.vue'
|
||||||
import GancaoSubmissionReconcileButton from './components/GancaoSubmissionReconcileButton.vue'
|
import GancaoSubmissionReconcileButton from './components/GancaoSubmissionReconcileButton.vue'
|
||||||
import { useListTimeFilter } from '@/hooks/useListTimeFilter'
|
import { useListTimeFilter } from '@/hooks/useListTimeFilter'
|
||||||
@@ -2700,6 +2702,7 @@ import {
|
|||||||
prescriptionOrderRequestCompletion,
|
prescriptionOrderRequestCompletion,
|
||||||
prescriptionOrderUploadToPharmacy,
|
prescriptionOrderUploadToPharmacy,
|
||||||
prescriptionOrderPreviewGancaoRecipel,
|
prescriptionOrderPreviewGancaoRecipel,
|
||||||
|
prescriptionDetail,
|
||||||
getDoctors,
|
getDoctors,
|
||||||
getAssistants
|
getAssistants
|
||||||
} from '@/api/tcm'
|
} from '@/api/tcm'
|
||||||
@@ -2717,6 +2720,10 @@ import {
|
|||||||
supplyModeTagType
|
supplyModeTagType
|
||||||
} from './components/prescription-order-utils'
|
} from './components/prescription-order-utils'
|
||||||
import PrescriptionSlip from '@/components/prescription-slip/index.vue'
|
import PrescriptionSlip from '@/components/prescription-slip/index.vue'
|
||||||
|
import EsignPrescriptionPanel from '@/components/EsignPrescriptionPanel.vue'
|
||||||
|
import PrescriptionAuditLayout from '@/components/PrescriptionAuditLayout.vue'
|
||||||
|
import type { PrescriptionEsignStatus } from '@/api/tcm'
|
||||||
|
import { canApprovePrescriptionEsign, downloadPrescriptionPdfIfRequired, requiresOriginalEsignPdf, updatePrescriptionSlipEsign } from '@/utils/prescription-esign'
|
||||||
import html2canvas from 'html2canvas'
|
import html2canvas from 'html2canvas'
|
||||||
import { jsPDF } from 'jspdf'
|
import { jsPDF } from 'jspdf'
|
||||||
import { getDictData } from '@/api/app'
|
import { getDictData } from '@/api/app'
|
||||||
@@ -3447,10 +3454,10 @@ function canEditRow(row: {
|
|||||||
return fs === 1 || fs === 2
|
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)
|
const fs = Number(row.fulfillment_status)
|
||||||
if (fs === 3 || fs === 4 || fs === 6) return false
|
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: {
|
function canPayAudit(row: {
|
||||||
@@ -4680,73 +4687,63 @@ async function submitEdit() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const auditVisible = ref(false)
|
const auditVisible = ref(false)
|
||||||
|
const route = useRoute()
|
||||||
const auditKind = ref<'prescription' | 'payment'>('prescription')
|
const auditKind = ref<'prescription' | 'payment'>('prescription')
|
||||||
const auditTargetId = ref(0)
|
const auditTargetId = ref(0)
|
||||||
const auditRowData = ref<any>(null)
|
const auditRowData = ref<any>(null)
|
||||||
const auditRemark = ref('')
|
const auditRemark = ref('')
|
||||||
const auditSignature = ref('')
|
|
||||||
const auditSession = ref(0)
|
|
||||||
const auditSubmitting = ref(false)
|
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(() =>
|
const auditTitle = computed(() =>
|
||||||
auditKind.value === 'prescription' ? '处方业务审核' : '关联支付单审核'
|
auditKind.value === 'prescription' ? '处方业务审核' : '关联支付单审核'
|
||||||
)
|
)
|
||||||
|
|
||||||
function resetAuditInput() {
|
function openAudit(row: Record<string, any>, kind: 'prescription' | 'payment') {
|
||||||
if (auditSubmitting.value) return
|
if (auditSubmitting.value) return
|
||||||
auditRemark.value = ''
|
if (kind === 'prescription' && !canRxAudit(row)) return
|
||||||
auditSignature.value = ''
|
|
||||||
auditSession.value++
|
|
||||||
}
|
|
||||||
|
|
||||||
function openAudit(row: { id: number }, kind: 'prescription' | 'payment') {
|
|
||||||
if (auditSubmitting.value || !Number(row.id)) return
|
|
||||||
auditKind.value = kind
|
auditKind.value = kind
|
||||||
auditTargetId.value = row.id
|
auditTargetId.value = Number(row.id)
|
||||||
auditRowData.value = row
|
auditRowData.value = row
|
||||||
resetAuditInput()
|
auditEsign.value = null
|
||||||
|
auditReview.value = null
|
||||||
|
auditRemark.value = ''
|
||||||
auditVisible.value = true
|
auditVisible.value = true
|
||||||
}
|
}
|
||||||
|
|
||||||
async function submitAudit(action: 'approve' | 'reject') {
|
async function submitAudit(action: 'approve' | 'reject') {
|
||||||
if (auditSubmitting.value || !auditVisible.value || !auditTargetId.value) return
|
if (auditSubmitting.value || (action === 'approve' && !canApproveAudit.value)) return
|
||||||
if (auditKind.value === 'prescription' && !auditSignature.value.trim()) {
|
|
||||||
feedback.msgError('请先手写审核人签名')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (action === 'reject' && !auditRemark.value.trim()) {
|
if (action === 'reject' && !auditRemark.value.trim()) {
|
||||||
feedback.msgError('驳回或阻止时必须填写明确的审核意见')
|
feedback.msgError('驳回或阻止时必须填写明确的审核意见')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
auditSubmitting.value = true
|
auditSubmitting.value = true
|
||||||
const targetId = auditTargetId.value
|
|
||||||
try {
|
try {
|
||||||
const params = {
|
const params = {
|
||||||
id: targetId,
|
id: auditTargetId.value,
|
||||||
action,
|
action,
|
||||||
remark: auditRemark.value.trim()
|
remark: auditRemark.value.trim()
|
||||||
}
|
}
|
||||||
if (auditKind.value === 'prescription') {
|
if (auditKind.value === 'prescription') {
|
||||||
await prescriptionOrderAuditPrescription({ ...params, signature: auditSignature.value })
|
await prescriptionOrderAuditPrescription(params)
|
||||||
} else {
|
} else {
|
||||||
await prescriptionOrderAuditPayment(params)
|
await prescriptionOrderAuditPayment(params)
|
||||||
}
|
}
|
||||||
feedback.msgSuccess(action === 'approve' ? '审核通过成功' : '已成功驳回该单')
|
feedback.msgSuccess(action === 'approve' ? '审核通过成功' : '已成功驳回该单')
|
||||||
auditVisible.value = false
|
auditVisible.value = false
|
||||||
auditSignature.value = ''
|
|
||||||
getLists()
|
getLists()
|
||||||
// 若详情 Drawer 正在打开,同步刷新详情数据
|
// 若详情 Drawer 正在打开,同步刷新详情数据
|
||||||
if (detailVisible.value && Number(detailData.value?.id) === Number(targetId)) {
|
if (detailVisible.value && auditTargetId.value) {
|
||||||
try {
|
try {
|
||||||
const res: any = await prescriptionOrderDetail({ id: targetId })
|
const res: any = await prescriptionOrderDetail({ id: auditTargetId.value })
|
||||||
const d = res?.data ?? res ?? null
|
const d = res?.data ?? res ?? null
|
||||||
if (d && Number(detailData.value?.id) === Number(targetId)) {
|
if (d) detailData.value = d
|
||||||
detailData.value = d
|
|
||||||
await fetchLogs(targetId)
|
|
||||||
}
|
|
||||||
} catch { /* 静默忽略 */ }
|
} catch { /* 静默忽略 */ }
|
||||||
}
|
}
|
||||||
await refreshOpenPrescriptionView(targetId)
|
|
||||||
} catch {
|
} catch {
|
||||||
/* 拦截器已提示 */
|
/* 拦截器已提示 */
|
||||||
} finally {
|
} finally {
|
||||||
@@ -4900,6 +4897,8 @@ onMounted(async () => {
|
|||||||
await loadServicePackageOptions()
|
await loadServicePackageOptions()
|
||||||
await loadDoctorAssistantOptions()
|
await loadDoctorAssistantOptions()
|
||||||
getLists()
|
getLists()
|
||||||
|
const reviewOrderId = Number(route.query.review_order)
|
||||||
|
if (Number.isSafeInteger(reviewOrderId) && reviewOrderId > 0) await openDetail(reviewOrderId)
|
||||||
})
|
})
|
||||||
|
|
||||||
// ─── 快捷填写快递单号 ────────────────────────────────────────────
|
// ─── 快捷填写快递单号 ────────────────────────────────────────────
|
||||||
@@ -5433,7 +5432,6 @@ async function confirmRevokeRxAudit(row: { id: number }) {
|
|||||||
if (nd) detailData.value = nd
|
if (nd) detailData.value = nd
|
||||||
} catch { /* 静默 */ }
|
} catch { /* 静默 */ }
|
||||||
}
|
}
|
||||||
await refreshOpenPrescriptionView(row.id)
|
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
if (e !== 'cancel' && e !== 'close') {
|
if (e !== 'cancel' && e !== 'close') {
|
||||||
/* 拦截器已提示 */
|
/* 拦截器已提示 */
|
||||||
@@ -5476,8 +5474,6 @@ const SLIP_ADDRESS_LINE = '地址:四川省成都市双流区黄甲街道黄
|
|||||||
const prescriptionViewVisible = ref(false)
|
const prescriptionViewVisible = ref(false)
|
||||||
const prescriptionViewLoading = ref(false)
|
const prescriptionViewLoading = ref(false)
|
||||||
const prescriptionViewData = ref<any>(null)
|
const prescriptionViewData = ref<any>(null)
|
||||||
const prescriptionViewOrderId = ref(0)
|
|
||||||
let prescriptionViewRequestId = 0
|
|
||||||
/** 查看处方联次:药房联 / 处方联 */
|
/** 查看处方联次:药房联 / 处方联 */
|
||||||
const prescriptionTabType = ref<'internal' | 'user'>('internal')
|
const prescriptionTabType = ref<'internal' | 'user'>('internal')
|
||||||
const rxSlipRef = ref<InstanceType<typeof PrescriptionSlip> | null>(null)
|
const rxSlipRef = ref<InstanceType<typeof PrescriptionSlip> | null>(null)
|
||||||
@@ -5738,34 +5734,20 @@ function openPrescriptionViewFromEdit() {
|
|||||||
openPrescriptionView(editForm)
|
openPrescriptionView(editForm)
|
||||||
}
|
}
|
||||||
|
|
||||||
function resetPrescriptionView() {
|
async function openPrescriptionView(row: any) {
|
||||||
prescriptionViewRequestId++
|
if (!row.prescription_id) {
|
||||||
prescriptionViewOrderId.value = 0
|
feedback.msgWarning('该订单未关联处方')
|
||||||
prescriptionViewData.value = null
|
|
||||||
prescriptionViewLoading.value = false
|
|
||||||
}
|
|
||||||
|
|
||||||
async function refreshOpenPrescriptionView(orderId: number) {
|
|
||||||
if (!prescriptionViewVisible.value || prescriptionViewOrderId.value !== Number(orderId)) return
|
|
||||||
await openPrescriptionView({ id: orderId, prescription_id: prescriptionViewData.value?.id }, true)
|
|
||||||
}
|
|
||||||
|
|
||||||
async function openPrescriptionView(orderRow: any, preserveTab = false) {
|
|
||||||
const orderId = Number(orderRow?.id)
|
|
||||||
if (!(orderId > 0)) {
|
|
||||||
feedback.msgWarning('缺少业务订单信息,请重新打开订单详情')
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
const requestId = ++prescriptionViewRequestId
|
|
||||||
prescriptionViewOrderId.value = orderId
|
|
||||||
prescriptionViewVisible.value = true
|
prescriptionViewVisible.value = true
|
||||||
prescriptionViewLoading.value = true
|
prescriptionViewLoading.value = true
|
||||||
prescriptionViewData.value = null
|
prescriptionViewData.value = null
|
||||||
if (!preserveTab) prescriptionTabType.value = 'internal'
|
prescriptionTabType.value = 'internal'
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const { order: row, prescription: base } = await loadOrderPrescriptionSlip(orderId, Number(orderRow.prescription_id))
|
const res: any = await prescriptionDetail({ id: row.prescription_id })
|
||||||
if (requestId !== prescriptionViewRequestId) return
|
const base = res?.data ?? res ?? null
|
||||||
if (base) {
|
if (base) {
|
||||||
const md = row.medication_days
|
const md = row.medication_days
|
||||||
const merged: Record<string, unknown> = { ...base }
|
const merged: Record<string, unknown> = { ...base }
|
||||||
@@ -5799,11 +5781,10 @@ async function openPrescriptionView(orderRow: any, preserveTab = false) {
|
|||||||
prescriptionViewData.value = null
|
prescriptionViewData.value = null
|
||||||
}
|
}
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
if (requestId !== prescriptionViewRequestId) return
|
|
||||||
feedback.msgError(e?.message || '加载处方详情失败')
|
feedback.msgError(e?.message || '加载处方详情失败')
|
||||||
prescriptionViewVisible.value = false
|
prescriptionViewVisible.value = false
|
||||||
} finally {
|
} finally {
|
||||||
if (requestId === prescriptionViewRequestId) prescriptionViewLoading.value = false
|
prescriptionViewLoading.value = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -5923,6 +5904,7 @@ async function downloadPrescriptionSlipPdf() {
|
|||||||
if (!prescriptionViewData.value) return
|
if (!prescriptionViewData.value) return
|
||||||
prescriptionSlipExporting.value = true
|
prescriptionSlipExporting.value = true
|
||||||
try {
|
try {
|
||||||
|
if (await downloadPrescriptionPdfIfRequired(Number(prescriptionViewData.value.id))) return
|
||||||
const canvas = await capturePrescriptionSlipCanvas()
|
const canvas = await capturePrescriptionSlipCanvas()
|
||||||
const imgData = canvas.toDataURL('image/jpeg', 0.95)
|
const imgData = canvas.toDataURL('image/jpeg', 0.95)
|
||||||
/**
|
/**
|
||||||
@@ -5954,8 +5936,8 @@ async function downloadPrescriptionSlipPdf() {
|
|||||||
}
|
}
|
||||||
pdf.save(`${slipDownloadBaseName()}.pdf`)
|
pdf.save(`${slipDownloadBaseName()}.pdf`)
|
||||||
feedback.msgSuccess('PDF已下载')
|
feedback.msgSuccess('PDF已下载')
|
||||||
} catch {
|
} catch (e: any) {
|
||||||
feedback.msgError('下载PDF失败')
|
feedback.msgError(e?.message || '下载PDF失败')
|
||||||
} finally {
|
} finally {
|
||||||
prescriptionSlipExporting.value = false
|
prescriptionSlipExporting.value = false
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
<el-dropdown
|
<el-dropdown
|
||||||
v-if="myPatientOrderActions(detail).length"
|
v-if="myPatientOrderActions(detail).length"
|
||||||
trigger="click"
|
trigger="click"
|
||||||
@command="(command: unknown) => openAction(detail, command as MyPatientOrderAction)"
|
@command="(command) => openAction(detail, command as MyPatientOrderAction)"
|
||||||
>
|
>
|
||||||
<el-button type="primary" size="small" plain>
|
<el-button type="primary" size="small" plain>
|
||||||
订单操作<el-icon class="el-icon--right"><ArrowDown /></el-icon>
|
订单操作<el-icon class="el-icon--right"><ArrowDown /></el-icon>
|
||||||
@@ -34,39 +34,46 @@
|
|||||||
<el-dialog
|
<el-dialog
|
||||||
v-model="auditVisible"
|
v-model="auditVisible"
|
||||||
:title="auditTitle"
|
:title="auditTitle"
|
||||||
width="min(480px, 94vw)"
|
:width="auditKind === 'prescription' ? 'min(1280px, 96vw)' : '480px'"
|
||||||
|
:top="auditKind === 'prescription' ? '5vh' : undefined"
|
||||||
append-to-body
|
append-to-body
|
||||||
destroy-on-close
|
destroy-on-close
|
||||||
:close-on-click-modal="false"
|
|
||||||
:close-on-press-escape="!submitting"
|
|
||||||
:show-close="!submitting"
|
|
||||||
@closed="resetAuditInput"
|
|
||||||
>
|
>
|
||||||
<el-alert
|
<PrescriptionAuditLayout
|
||||||
title="通过时审核意见可不填;驳回时必须填写明确原因。"
|
:prescription-id="auditKind === 'prescription' ? Number(actionRow.prescription_id) || 0 : null"
|
||||||
type="warning"
|
:doctor-signed-at="auditEsign?.signature_time || auditEsign?.signed_at"
|
||||||
:closable="false"
|
:pharmacist-signed-at="auditReview?.signature_time || auditEsign?.review_signature_time"
|
||||||
show-icon
|
>
|
||||||
class="mb-4"
|
<EsignPrescriptionPanel
|
||||||
/>
|
v-if="auditVisible && auditKind === 'prescription'"
|
||||||
<el-input
|
:key="actionRow.id"
|
||||||
v-model="auditRemark"
|
:prescription-id="Number(actionRow.prescription_id) || 0"
|
||||||
:disabled="submitting"
|
audit
|
||||||
type="textarea"
|
:review-order-id="Number(actionRow.id)"
|
||||||
:rows="4"
|
@review-change="auditReview = $event"
|
||||||
maxlength="500"
|
class="mb-3"
|
||||||
show-word-limit
|
@status-change="auditEsign = $event"
|
||||||
placeholder="请输入审核意见"
|
/>
|
||||||
/>
|
<el-alert
|
||||||
<div v-if="auditKind === 'prescription'" class="mt-4">
|
title="通过时审核意见可不填;驳回时必须填写明确原因。"
|
||||||
<p class="text-sm font-medium mb-2">审核人签名 <span class="text-red-500">*</span></p>
|
type="warning"
|
||||||
<SignaturePad :key="auditSession" v-model="auditSignature" :disabled="submitting" />
|
:closable="false"
|
||||||
<p class="text-xs text-gray-500 mt-2">请本人签名后再通过或驳回,每次审核均需重新签署。</p>
|
show-icon
|
||||||
</div>
|
class="mb-4"
|
||||||
|
/>
|
||||||
|
<el-input
|
||||||
|
v-model="auditRemark"
|
||||||
|
type="textarea"
|
||||||
|
:rows="4"
|
||||||
|
maxlength="500"
|
||||||
|
show-word-limit
|
||||||
|
placeholder="请输入审核意见"
|
||||||
|
/>
|
||||||
|
</PrescriptionAuditLayout>
|
||||||
<template #footer>
|
<template #footer>
|
||||||
<el-button :disabled="submitting" @click="auditVisible = false">取消</el-button>
|
<el-button @click="auditVisible = false">取消</el-button>
|
||||||
<el-button type="primary" :loading="submitting" :disabled="auditKind === 'prescription' && !auditSignature" @click="submitAudit('approve')">同意通过</el-button>
|
<el-button type="primary" :loading="submitting" :disabled="!canApproveAudit" @click="submitAudit('approve')">同意通过</el-button>
|
||||||
<el-button type="danger" :loading="submitting" :disabled="auditKind === 'prescription' && !auditSignature" @click="submitAudit('reject')">驳回</el-button>
|
<el-button type="danger" :loading="submitting" @click="submitAudit('reject')">驳回</el-button>
|
||||||
</template>
|
</template>
|
||||||
</el-dialog>
|
</el-dialog>
|
||||||
|
|
||||||
@@ -259,7 +266,10 @@ import { computed, reactive, ref } from 'vue'
|
|||||||
import { ArrowDown } from '@element-plus/icons-vue'
|
import { ArrowDown } from '@element-plus/icons-vue'
|
||||||
import { ElMessageBox } from 'element-plus'
|
import { ElMessageBox } from 'element-plus'
|
||||||
import feedback from '@/utils/feedback'
|
import feedback from '@/utils/feedback'
|
||||||
import SignaturePad from '@/components/signature-pad/index.vue'
|
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 PrescriptionOrderDetailDrawer from '@/views/consumer/prescription/components/PrescriptionOrderDetailDrawer.vue'
|
||||||
import {
|
import {
|
||||||
myPatientOrderAddPayOrder,
|
myPatientOrderAddPayOrder,
|
||||||
@@ -316,8 +326,11 @@ const completeOptions = [
|
|||||||
const auditVisible = ref(false)
|
const auditVisible = ref(false)
|
||||||
const auditKind = ref<'prescription' | 'payment'>('prescription')
|
const auditKind = ref<'prescription' | 'payment'>('prescription')
|
||||||
const auditRemark = ref('')
|
const auditRemark = ref('')
|
||||||
const auditSignature = ref('')
|
const auditEsign = ref<PrescriptionEsignStatus | null>(null)
|
||||||
const auditSession = ref(0)
|
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 auditTitle = computed(() => auditKind.value === 'prescription' ? '处方业务审核' : '关联支付单审核')
|
||||||
|
|
||||||
const trackVisible = ref(false)
|
const trackVisible = ref(false)
|
||||||
@@ -405,15 +418,9 @@ async function openEdit(row: Record<string, any>) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function resetAuditInput() {
|
|
||||||
if (submitting.value) return
|
|
||||||
auditRemark.value = ''
|
|
||||||
auditSignature.value = ''
|
|
||||||
auditSession.value++
|
|
||||||
}
|
|
||||||
|
|
||||||
function openAction(row: Record<string, any>, action: MyPatientOrderAction) {
|
function openAction(row: Record<string, any>, action: MyPatientOrderAction) {
|
||||||
if (submitting.value) return
|
if (submitting.value && (action === 'audit_prescription' || action === 'audit_payment')) return
|
||||||
|
if (action === 'audit_prescription' && row.can_review_prescription !== true) return
|
||||||
actionRow.value = row
|
actionRow.value = row
|
||||||
switch (action) {
|
switch (action) {
|
||||||
case 'edit':
|
case 'edit':
|
||||||
@@ -422,7 +429,9 @@ function openAction(row: Record<string, any>, action: MyPatientOrderAction) {
|
|||||||
case 'audit_prescription':
|
case 'audit_prescription':
|
||||||
case 'audit_payment':
|
case 'audit_payment':
|
||||||
auditKind.value = action === 'audit_prescription' ? 'prescription' : 'payment'
|
auditKind.value = action === 'audit_prescription' ? 'prescription' : 'payment'
|
||||||
resetAuditInput()
|
auditEsign.value = null
|
||||||
|
auditReview.value = null
|
||||||
|
auditRemark.value = ''
|
||||||
auditVisible.value = true
|
auditVisible.value = true
|
||||||
break
|
break
|
||||||
case 'revoke_rx_audit':
|
case 'revoke_rx_audit':
|
||||||
@@ -470,31 +479,25 @@ function openAction(row: Record<string, any>, action: MyPatientOrderAction) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function changed(message: string, orderId = Number(actionRow.value.id)) {
|
async function changed(message: string) {
|
||||||
feedback.msgSuccess(message)
|
feedback.msgSuccess(message)
|
||||||
emit('changed')
|
emit('changed')
|
||||||
await detailDrawerRef.value?.refreshIfCurrent(orderId)
|
await detailDrawerRef.value?.refreshIfCurrent(actionRow.value.id)
|
||||||
}
|
}
|
||||||
|
|
||||||
async function submitAudit(action: 'approve' | 'reject') {
|
async function submitAudit(action: 'approve' | 'reject') {
|
||||||
if (submitting.value || !auditVisible.value || !Number(actionRow.value.id)) return
|
if (submitting.value || (action === 'approve' && !canApproveAudit.value)) return
|
||||||
if (auditKind.value === 'prescription' && !auditSignature.value.trim()) {
|
|
||||||
feedback.msgError('请先手写审核人签名')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (action === 'reject' && !auditRemark.value.trim()) {
|
if (action === 'reject' && !auditRemark.value.trim()) {
|
||||||
feedback.msgError('驳回时必须填写审核意见')
|
feedback.msgError('驳回时必须填写审核意见')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
submitting.value = true
|
submitting.value = true
|
||||||
const targetId = Number(actionRow.value.id)
|
|
||||||
try {
|
try {
|
||||||
const params = { id: targetId, action, remark: auditRemark.value.trim() }
|
const params = { id: Number(actionRow.value.id), action, remark: auditRemark.value.trim() }
|
||||||
if (auditKind.value === 'prescription') await myPatientOrderAuditPrescription({ ...params, signature: auditSignature.value })
|
if (auditKind.value === 'prescription') await myPatientOrderAuditPrescription(params)
|
||||||
else await myPatientOrderAuditPayment(params)
|
else await myPatientOrderAuditPayment(params)
|
||||||
auditVisible.value = false
|
auditVisible.value = false
|
||||||
auditSignature.value = ''
|
await changed(action === 'approve' ? '审核通过成功' : '订单已驳回')
|
||||||
await changed(action === 'approve' ? '审核通过成功' : '订单已驳回', targetId)
|
|
||||||
} catch {
|
} catch {
|
||||||
// 请求拦截器已提示
|
// 请求拦截器已提示
|
||||||
} finally {
|
} finally {
|
||||||
|
|||||||
@@ -50,6 +50,7 @@ export function myPatientOrderActions(row: Record<string, any>): MyPatientOrderA
|
|||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
permitted('tcm.prescriptionOrder/auditPrescription')
|
permitted('tcm.prescriptionOrder/auditPrescription')
|
||||||
|
&& row.can_review_prescription === true
|
||||||
&& prescriptionAudit === 0
|
&& prescriptionAudit === 0
|
||||||
&& ![3, 4, 6].includes(fulfillment)
|
&& ![3, 4, 6].includes(fulfillment)
|
||||||
) {
|
) {
|
||||||
|
|||||||
@@ -73,6 +73,11 @@
|
|||||||
<el-table-column label="创建时间" prop="create_time" min-width="180" />
|
<el-table-column label="创建时间" prop="create_time" min-width="180" />
|
||||||
<el-table-column label="最近登录时间" prop="login_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="最近登录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']">
|
<el-table-column label="状态" min-width="100" v-perms="['auth.admin/edit']">
|
||||||
<template #default="{ row }">
|
<template #default="{ row }">
|
||||||
<el-switch
|
<el-switch
|
||||||
@@ -84,7 +89,7 @@
|
|||||||
/>
|
/>
|
||||||
</template>
|
</template>
|
||||||
</el-table-column>
|
</el-table-column>
|
||||||
<el-table-column label="操作" width="120" fixed="right">
|
<el-table-column label="操作" width="200" fixed="right">
|
||||||
<template #default="{ row }">
|
<template #default="{ row }">
|
||||||
<el-button
|
<el-button
|
||||||
v-perms="['auth.admin/edit']"
|
v-perms="['auth.admin/edit']"
|
||||||
@@ -94,6 +99,15 @@
|
|||||||
>
|
>
|
||||||
编辑
|
编辑
|
||||||
</el-button>
|
</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
|
<el-button
|
||||||
v-if="row.root != 1"
|
v-if="row.root != 1"
|
||||||
v-perms="['auth.admin/delete']"
|
v-perms="['auth.admin/delete']"
|
||||||
@@ -116,7 +130,7 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script lang="ts" setup name="admin">
|
<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 { roleAll } from '@/api/perms/role'
|
||||||
import { useDictOptions } from '@/hooks/useDictOptions'
|
import { useDictOptions } from '@/hooks/useDictOptions'
|
||||||
import { usePaging } from '@/hooks/usePaging'
|
import { usePaging } from '@/hooks/usePaging'
|
||||||
@@ -171,6 +185,14 @@ const handleDelete = async (id: number) => {
|
|||||||
getLists()
|
getLists()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const handleEsignUnbind = async (row: any) => {
|
||||||
|
await feedback.confirm(
|
||||||
|
`确定解除「${row.name}」绑定的签署身份(${row.esign_signer_name})?解除后该账号需重新人脸认证才能电子签署,已签处方不受影响。`
|
||||||
|
)
|
||||||
|
await adminEsignUnbind({ id: row.id })
|
||||||
|
getLists()
|
||||||
|
}
|
||||||
|
|
||||||
const { optionsData } = useDictOptions<{
|
const { optionsData } = useDictOptions<{
|
||||||
role: any[]
|
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>
|
||||||
@@ -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()
|
||||||
|
})
|
||||||
@@ -1,227 +0,0 @@
|
|||||||
const assert = require('node:assert/strict')
|
|
||||||
const fs = require('node:fs')
|
|
||||||
const path = require('node:path')
|
|
||||||
const test = require('node:test')
|
|
||||||
const ts = require('typescript')
|
|
||||||
const vue = require('vue')
|
|
||||||
const { renderToString } = require('@vue/server-renderer')
|
|
||||||
const { parse, compileScript, compileTemplate } = require('@vue/compiler-sfc')
|
|
||||||
|
|
||||||
const root = path.resolve(__dirname, '../src')
|
|
||||||
const signature = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScLbtAAAAABJRU5ErkJggg=='
|
|
||||||
const oldSignature = 'data:image/png;base64,old-order-signature'
|
|
||||||
const signedOrder = () => ({
|
|
||||||
id: 42, prescription_id: 8, fulfillment_status: 1, prescription_audit_status: 1,
|
|
||||||
prescription_audit_signature: signature, prescription_audit_signed_name: '本单药师',
|
|
||||||
prescription_audit_signed_by: 7, prescription_audit_signed_at: 1794553200
|
|
||||||
})
|
|
||||||
const basePrescription = () => ({ id: 8, doctor_name: '开方医师', patient_name: '张某', herbs: [], prescription_type: '饮片' })
|
|
||||||
const deferred = () => {
|
|
||||||
let resolve
|
|
||||||
const promise = new Promise(yes => { resolve = yes })
|
|
||||||
return { promise, resolve }
|
|
||||||
}
|
|
||||||
|
|
||||||
function loadModule(source, imports) {
|
|
||||||
const output = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS, esModuleInterop: true } }).outputText
|
|
||||||
const module = { exports: {} }
|
|
||||||
new Function('require', 'module', 'exports', output)(imports, module, module.exports)
|
|
||||||
return module.exports
|
|
||||||
}
|
|
||||||
|
|
||||||
const utils = loadModule(fs.readFileSync(path.join(root, 'components/prescription-slip/utils.ts'), 'utf8'), () => { throw new Error('unexpected dependency') })
|
|
||||||
const slipFile = path.join(root, 'components/prescription-slip/index.vue')
|
|
||||||
const slipDescriptor = parse(fs.readFileSync(slipFile, 'utf8'), { filename: slipFile }).descriptor
|
|
||||||
const slipScript = compileScript(slipDescriptor, { id: 'signature-slip-render', inlineTemplate: true })
|
|
||||||
const Slip = loadModule(slipScript.content, name => {
|
|
||||||
if (name === 'vue') return vue
|
|
||||||
if (name === './utils') return utils
|
|
||||||
throw new Error(`unexpected dependency: ${name}`)
|
|
||||||
}).default
|
|
||||||
|
|
||||||
async function renderedSlip(data, variant) {
|
|
||||||
// 真正执行 PrescriptionSlip.vue 的编译 render;两个联次均使用该 DOM 导出图片/PDF。
|
|
||||||
return renderToString(vue.createSSRApp({ render: () => vue.h(Slip, { data, variant }) }))
|
|
||||||
}
|
|
||||||
|
|
||||||
function preview(page, options = {}) {
|
|
||||||
const calls = [], errors = []
|
|
||||||
let order = options.order ?? signedOrder()
|
|
||||||
let prescription = options.prescription ?? basePrescription()
|
|
||||||
const request = {
|
|
||||||
async get({ url, params }) {
|
|
||||||
calls.push({ url, params })
|
|
||||||
if (url === '/tcm.prescription/detail') return typeof prescription === 'function' ? prescription(params) : { data: prescription }
|
|
||||||
if (url === '/tcm.prescriptionOrder/detail') return typeof order === 'function' ? order(params) : { data: order }
|
|
||||||
throw new Error(`Unexpected URL ${url}`)
|
|
||||||
},
|
|
||||||
async post({ url, params }) {
|
|
||||||
calls.push({ url, params })
|
|
||||||
if (url === '/tcm.prescriptionOrder/auditPrescription') {
|
|
||||||
order = { ...signedOrder(), prescription_audit_status: params.action === 'approve' ? 1 : 2, prescription_audit_signature: params.signature }
|
|
||||||
return {}
|
|
||||||
}
|
|
||||||
if (url === '/tcm.prescriptionOrder/revokeRxAudit') {
|
|
||||||
order = { ...signedOrder(), prescription_audit_status: 0, prescription_audit_signature: '', prescription_audit_signed_name: '' }
|
|
||||||
return {}
|
|
||||||
}
|
|
||||||
throw new Error(`Unexpected URL ${url}`)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// 使用真实 API functions 和真实共享 loader,只有最底层网络 transport 被替换。
|
|
||||||
const api = loadModule(fs.readFileSync(path.join(root, 'api/tcm.ts'), 'utf8'), name => {
|
|
||||||
assert.equal(name, '@/utils/request')
|
|
||||||
return request
|
|
||||||
})
|
|
||||||
const loader = loadModule(fs.readFileSync(path.join(root, 'views/consumer/prescription/components/order-prescription-slip.ts'), 'utf8'), name => {
|
|
||||||
assert.equal(name, '@/api/tcm')
|
|
||||||
return api
|
|
||||||
})
|
|
||||||
const filename = path.join(root, 'views/consumer/prescription', page)
|
|
||||||
const { descriptor, errors: parseErrors } = parse(fs.readFileSync(filename, 'utf8'), { filename })
|
|
||||||
assert.deepEqual(parseErrors, [])
|
|
||||||
const script = compileScript(descriptor, { id: page })
|
|
||||||
const template = compileTemplate({ source: descriptor.template.content, filename, id: page, compilerOptions: { bindingMetadata: script.bindings } })
|
|
||||||
assert.deepEqual(template.errors, [])
|
|
||||||
const ast = ts.createSourceFile(filename + '.ts', descriptor.scriptSetup.content, ts.ScriptTarget.Latest, true)
|
|
||||||
const declarations = new Map()
|
|
||||||
for (const node of ast.statements) {
|
|
||||||
if (ts.isFunctionDeclaration(node) && node.name) declarations.set(node.name.text, node.getText(ast))
|
|
||||||
if (ts.isVariableStatement(node)) {
|
|
||||||
for (const declaration of node.declarationList.declarations) declarations.set(declaration.name.getText(ast), `${node.declarationList.flags & ts.NodeFlags.Const ? 'const' : 'let'} ${declaration.getText(ast)}`)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const names = [
|
|
||||||
'prescriptionViewVisible', 'prescriptionViewLoading', 'prescriptionViewData', 'prescriptionViewOrderId', 'prescriptionViewRequestId',
|
|
||||||
'prescriptionTabType', 'openPrescriptionView', 'resetPrescriptionView', 'refreshOpenPrescriptionView',
|
|
||||||
'auditVisible', 'auditKind', 'auditTargetId', 'auditRowData', 'auditRemark', 'auditSignature', 'auditSession', 'auditSubmitting',
|
|
||||||
'openAudit', 'resetAuditInput', 'submitAudit', 'confirmRevokeRxAudit'
|
|
||||||
]
|
|
||||||
const globals = {
|
|
||||||
ref: vue.ref, ...loader,
|
|
||||||
prescriptionOrderAuditPrescription: api.prescriptionOrderAuditPrescription,
|
|
||||||
prescriptionOrderAuditPayment: api.prescriptionOrderAuditPayment,
|
|
||||||
prescriptionOrderRevokeRxAudit: api.prescriptionOrderRevokeRxAudit,
|
|
||||||
prescriptionOrderDetail: api.prescriptionOrderDetail,
|
|
||||||
detailDrawerRef: vue.ref({ refreshIfCurrent: async () => {} }),
|
|
||||||
// 父详情/列表故意保持旧快照,验证预览不从它恢复签名。
|
|
||||||
detailData: vue.ref({ id: 42, prescription_id: 8, prescription_audit_status: 0 }), detailVisible: vue.ref(false),
|
|
||||||
slipAuxLibraryName: vue.ref(''), resolveSlipAuxLibraryName: async () => '',
|
|
||||||
ElMessageBox: { confirm: async () => {} }, getLists() {}, fetchLogs: async () => {},
|
|
||||||
feedback: { msgWarning: message => errors.push(message), msgError: message => errors.push(message), msgSuccess() {} }
|
|
||||||
}
|
|
||||||
for (const name of names) assert.ok(declarations.has(name), `${page}: missing ${name}`)
|
|
||||||
const output = ts.transpileModule(names.map(name => declarations.get(name)).join('\n'), { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } }).outputText
|
|
||||||
const state = new Function(...Object.keys(globals), `${output}\nreturn { ${names.join(', ')} }`)(...Object.values(globals))
|
|
||||||
return { state, calls, errors, setOrder: value => { order = value }, setPrescription: value => { prescription = value } }
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const page of ['order_list.vue', 'order_list_h5.vue']) {
|
|
||||||
test(`${page}: real API -> preview -> both rendered slips show order signature when prescription response has no audit fields`, async () => {
|
|
||||||
const { state, calls } = preview(page)
|
|
||||||
await state.openPrescriptionView({ id: 42, prescription_id: 8, prescription_audit_status: 0 })
|
|
||||||
assert.deepEqual(calls, [
|
|
||||||
{ url: '/tcm.prescription/detail', params: { id: 8, prescription_order_id: 42 } },
|
|
||||||
{ url: '/tcm.prescriptionOrder/detail', params: { id: 42 } }
|
|
||||||
])
|
|
||||||
for (const variant of ['internal', 'user']) {
|
|
||||||
const html = await renderedSlip(state.prescriptionViewData.value, variant)
|
|
||||||
assert.match(html, /<img[^>]*alt="药师签名"/)
|
|
||||||
assert.ok(html.includes(`src="${signature}"`))
|
|
||||||
assert.equal(html.includes('本单药师'), false)
|
|
||||||
assert.ok(html.indexOf('开方医师') < html.indexOf('药师签名'))
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
test(`${page}: fresh order replaces missing or wrong signature fields from prescription and list snapshots`, async () => {
|
|
||||||
const stale = { ...basePrescription(), prescription_audit_status: 1, prescription_audit_signature: oldSignature, prescription_audit_signed_name: '别单旧药师', prescription_audit_signed_by: 99 }
|
|
||||||
const { state } = preview(page, { prescription: stale })
|
|
||||||
await state.openPrescriptionView({ ...stale, id: 42, prescription_id: 8 })
|
|
||||||
assert.equal(state.prescriptionViewData.value.prescription_audit_signature, signature)
|
|
||||||
assert.equal(state.prescriptionViewData.value.prescription_audit_signed_by, 7)
|
|
||||||
const html = await renderedSlip(state.prescriptionViewData.value, 'internal')
|
|
||||||
assert.equal(html.includes('本单药师'), false)
|
|
||||||
assert.equal(html.includes('别单旧药师'), false)
|
|
||||||
assert.equal(html.includes(oldSignature), false)
|
|
||||||
})
|
|
||||||
|
|
||||||
test(`${page}: pending, rejected, cancelled and refunded fresh orders remove stale pharmacist images from both slips`, async () => {
|
|
||||||
const stale = { ...basePrescription(), ...signedOrder(), id: 8 }
|
|
||||||
for (const order of [
|
|
||||||
{ ...signedOrder(), prescription_audit_status: 0 },
|
|
||||||
{ ...signedOrder(), prescription_audit_status: 2 },
|
|
||||||
{ ...signedOrder(), fulfillment_status: 4 },
|
|
||||||
{ ...signedOrder(), fulfillment_status: 10 },
|
|
||||||
{ ...signedOrder(), prescription_audit_signature: '' }
|
|
||||||
]) {
|
|
||||||
const { state } = preview(page, { order, prescription: stale })
|
|
||||||
await state.openPrescriptionView({ ...signedOrder(), prescription_id: 8 })
|
|
||||||
assert.equal(state.prescriptionViewData.value.prescription_audit_signature, '')
|
|
||||||
for (const variant of ['internal', 'user']) {
|
|
||||||
const html = await renderedSlip(state.prescriptionViewData.value, variant)
|
|
||||||
assert.equal(html.includes('alt="药师签名"'), false)
|
|
||||||
assert.equal(html.includes('本单药师'), false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
test(`${page}: completing an audit and revoking it refresh an already-open prescription preview`, async () => {
|
|
||||||
const { state, setPrescription } = preview(page, { order: { ...signedOrder(), prescription_audit_status: 0, prescription_audit_signature: '' } })
|
|
||||||
await state.openPrescriptionView({ id: 42, prescription_id: 8 })
|
|
||||||
assert.equal(state.prescriptionViewData.value.prescription_audit_signature, '')
|
|
||||||
state.prescriptionTabType.value = 'user'
|
|
||||||
state.openAudit({ id: 42 }, 'prescription')
|
|
||||||
state.auditSignature.value = signature
|
|
||||||
await state.submitAudit('approve')
|
|
||||||
assert.equal(state.prescriptionViewData.value.prescription_audit_signature, signature)
|
|
||||||
assert.equal(state.prescriptionTabType.value, 'user')
|
|
||||||
assert.match(await renderedSlip(state.prescriptionViewData.value, 'user'), /<img[^>]*alt="药师签名"/)
|
|
||||||
setPrescription({ ...basePrescription(), ...signedOrder(), id: 8 })
|
|
||||||
await state.confirmRevokeRxAudit({ id: 42 })
|
|
||||||
assert.equal(state.prescriptionViewData.value.prescription_audit_signature, '')
|
|
||||||
assert.equal((await renderedSlip(state.prescriptionViewData.value, 'user')).includes('alt="药师签名"'), false)
|
|
||||||
})
|
|
||||||
|
|
||||||
test(`${page}: another order's detail and failed detail loads cannot borrow a cached signature`, async () => {
|
|
||||||
for (const order of [{ ...signedOrder(), id: 99 }, async () => { throw new Error('订单加载失败') }]) {
|
|
||||||
const { state, errors } = preview(page, { order, prescription: { ...basePrescription(), ...signedOrder(), id: 8 } })
|
|
||||||
state.prescriptionViewData.value = { ...basePrescription(), ...signedOrder(), id: 8 }
|
|
||||||
await state.openPrescriptionView({ id: 42, prescription_id: 8 })
|
|
||||||
assert.equal(state.prescriptionViewData.value, null)
|
|
||||||
assert.equal(state.prescriptionViewVisible.value, false)
|
|
||||||
assert.equal(errors.length, 1)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
test(`${page}: a slower previous order response cannot overwrite the newly opened or closed preview`, async () => {
|
|
||||||
const slow = deferred()
|
|
||||||
const { state } = preview(page, {
|
|
||||||
prescription: params => params.id === 8 ? slow.promise : { ...basePrescription(), id: params.id },
|
|
||||||
order: params => ({ ...signedOrder(), id: params.id, prescription_id: params.id === 42 ? 8 : 9, prescription_audit_signed_name: `药师${params.id}` })
|
|
||||||
})
|
|
||||||
const first = state.openPrescriptionView({ id: 42, prescription_id: 8 })
|
|
||||||
await state.openPrescriptionView({ id: 43, prescription_id: 9 })
|
|
||||||
slow.resolve(basePrescription())
|
|
||||||
await first
|
|
||||||
assert.equal(state.prescriptionViewData.value.prescription_order_id, 43)
|
|
||||||
assert.equal(state.prescriptionViewData.value.prescription_audit_signed_name, '药师43')
|
|
||||||
const pending = state.openPrescriptionView({ id: 43, prescription_id: 9 })
|
|
||||||
state.resetPrescriptionView()
|
|
||||||
await pending
|
|
||||||
assert.equal(state.prescriptionViewData.value, null)
|
|
||||||
})
|
|
||||||
|
|
||||||
test(`${page}: changed prescription association reloads the actual current prescription`, async () => {
|
|
||||||
const { state, calls } = preview(page, {
|
|
||||||
order: { ...signedOrder(), prescription_id: 9 },
|
|
||||||
prescription: params => {
|
|
||||||
if (params.id === 8) throw new Error('处方与订单关联不匹配')
|
|
||||||
return { ...basePrescription(), id: params.id }
|
|
||||||
}
|
|
||||||
})
|
|
||||||
await state.openPrescriptionView({ id: 42, prescription_id: 8 })
|
|
||||||
assert.equal(state.prescriptionViewData.value.id, 9)
|
|
||||||
assert.equal(state.prescriptionViewData.value.prescription_audit_signature, signature)
|
|
||||||
assert.deepEqual(calls.filter(call => call.url === '/tcm.prescription/detail').map(call => call.params.id), [8, 9])
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -1,311 +0,0 @@
|
|||||||
const assert = require('node:assert/strict')
|
|
||||||
const fs = require('node:fs')
|
|
||||||
const path = require('node:path')
|
|
||||||
const test = require('node:test')
|
|
||||||
const ts = require('typescript')
|
|
||||||
const vue = require('vue')
|
|
||||||
const { parse, compileScript, compileTemplate } = require('@vue/compiler-sfc')
|
|
||||||
|
|
||||||
const root = path.resolve(__dirname, '..')
|
|
||||||
const signature = 'data:image/png;base64,c2lnbmF0dXJl'
|
|
||||||
const deferred = () => {
|
|
||||||
let resolve, reject
|
|
||||||
const promise = new Promise((yes, no) => { resolve = yes; reject = no })
|
|
||||||
return { promise, resolve, reject }
|
|
||||||
}
|
|
||||||
|
|
||||||
function component(relative) {
|
|
||||||
const filename = path.join(root, 'src', relative)
|
|
||||||
const { descriptor, errors } = parse(fs.readFileSync(filename, 'utf8'), { filename })
|
|
||||||
assert.deepEqual(errors, [])
|
|
||||||
const script = compileScript(descriptor, { id: relative })
|
|
||||||
const template = compileTemplate({ source: descriptor.template.content, filename, id: relative, compilerOptions: { bindingMetadata: script.bindings } })
|
|
||||||
assert.deepEqual(template.errors, [])
|
|
||||||
return { filename, descriptor, script }
|
|
||||||
}
|
|
||||||
|
|
||||||
function handlers(relative, names, globals, watches = '') {
|
|
||||||
const { filename, descriptor } = component(relative)
|
|
||||||
const ast = ts.createSourceFile(filename + '.ts', descriptor.scriptSetup.content, ts.ScriptTarget.Latest, true)
|
|
||||||
const declarations = new Map()
|
|
||||||
for (const node of ast.statements) {
|
|
||||||
if (ts.isFunctionDeclaration(node) && node.name) declarations.set(node.name.text, node.getText(ast))
|
|
||||||
if (ts.isVariableStatement(node)) {
|
|
||||||
for (const declaration of node.declarationList.declarations) declarations.set(declaration.name.getText(ast), `${node.declarationList.flags & ts.NodeFlags.Const ? 'const' : 'let'} ${declaration.getText(ast)}`)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (const name of names) assert.ok(declarations.has(name), `${relative}: missing ${name}`)
|
|
||||||
const expressions = watches ? ast.statements.filter(node => ts.isExpressionStatement(node) && node.getText(ast).startsWith('watch(') && node.getText(ast).includes(watches)).map(node => node.getText(ast)) : []
|
|
||||||
const compiled = ts.transpileModule([...names.map(name => declarations.get(name)), ...expressions].join('\n'), { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } }).outputText
|
|
||||||
return new Function(...Object.keys(globals), `${compiled}\nreturn { ${names.join(', ')} }`)(...Object.values(globals))
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const page of ['views/consumer/prescription/order_list.vue', 'views/consumer/prescription/order_list_h5.vue', 'views/first_visit/my_patients/components/OrderActionHost.vue']) {
|
|
||||||
const host = page.includes('OrderActionHost')
|
|
||||||
function setup(save = async () => {}) {
|
|
||||||
const calls = [], errors = [], refreshed = []
|
|
||||||
const names = ['auditVisible', 'auditKind', 'auditRemark', 'auditSignature', 'auditSession', 'resetAuditInput', 'submitAudit']
|
|
||||||
names.push(...(host ? ['actionRow', 'submitting', 'openAction', 'changed'] : ['auditTargetId', 'auditRowData', 'auditSubmitting', 'openAudit']))
|
|
||||||
const rx = async payload => { calls.push(['rx', payload]); await save(payload) }
|
|
||||||
const pay = async payload => { calls.push(['pay', payload]); await save(payload) }
|
|
||||||
const state = handlers(page, names, {
|
|
||||||
ref: vue.ref,
|
|
||||||
feedback: { msgError: message => errors.push(message), msgSuccess() {} },
|
|
||||||
prescriptionOrderAuditPrescription: rx, prescriptionOrderAuditPayment: pay,
|
|
||||||
myPatientOrderAuditPrescription: rx, myPatientOrderAuditPayment: pay,
|
|
||||||
detailDrawerRef: vue.ref({ refreshIfCurrent: async id => refreshed.push(id) }),
|
|
||||||
detailVisible: vue.ref(false), detailData: vue.ref(null), getLists() {}, emit() {}, refreshOpenPrescriptionView: async () => {}
|
|
||||||
})
|
|
||||||
const open = (id = 42, kind = 'prescription') => host ? state.openAction({ id }, `audit_${kind}`) : state.openAudit({ id }, kind)
|
|
||||||
return { state, calls, errors, refreshed, open }
|
|
||||||
}
|
|
||||||
|
|
||||||
test(`${page}: blank signature blocks approve and reject even via direct handler`, async () => {
|
|
||||||
const { state, calls, open } = setup()
|
|
||||||
open()
|
|
||||||
state.auditRemark.value = '原因'
|
|
||||||
for (const blank of ['', ' ']) {
|
|
||||||
state.auditSignature.value = blank
|
|
||||||
await state.submitAudit('approve')
|
|
||||||
await state.submitAudit('reject')
|
|
||||||
}
|
|
||||||
assert.deepEqual(calls, [])
|
|
||||||
assert.equal(state.auditVisible.value, true)
|
|
||||||
})
|
|
||||||
|
|
||||||
test(`${page}: both audit results carry a fresh signature; reject still needs a reason`, async () => {
|
|
||||||
const { state, calls, refreshed, open } = setup()
|
|
||||||
open()
|
|
||||||
state.auditSignature.value = signature
|
|
||||||
await state.submitAudit('reject')
|
|
||||||
assert.deepEqual(calls, [])
|
|
||||||
state.auditRemark.value = ' 需重新核对 '
|
|
||||||
await state.submitAudit('reject')
|
|
||||||
assert.deepEqual(calls[0], ['rx', { id: 42, action: 'reject', remark: '需重新核对', signature }])
|
|
||||||
assert.equal(state.auditSignature.value, '')
|
|
||||||
open(43)
|
|
||||||
assert.equal(state.auditSignature.value, '')
|
|
||||||
state.auditSignature.value = signature
|
|
||||||
await state.submitAudit('approve')
|
|
||||||
assert.deepEqual(calls[1], ['rx', { id: 43, action: 'approve', remark: '', signature }])
|
|
||||||
if (!page.includes('h5')) assert.deepEqual(refreshed, [42, 43])
|
|
||||||
})
|
|
||||||
|
|
||||||
test(`${page}: payment auditing neither requires nor sends a signature`, async () => {
|
|
||||||
const { state, calls, open } = setup()
|
|
||||||
open(4, 'payment')
|
|
||||||
state.auditSignature.value = signature
|
|
||||||
await state.submitAudit('approve')
|
|
||||||
open(5, 'payment')
|
|
||||||
state.auditRemark.value = '支付信息不符'
|
|
||||||
await state.submitAudit('reject')
|
|
||||||
assert.deepEqual(calls, [
|
|
||||||
['pay', { id: 4, action: 'approve', remark: '' }],
|
|
||||||
['pay', { id: 5, action: 'reject', remark: '支付信息不符' }]
|
|
||||||
])
|
|
||||||
})
|
|
||||||
|
|
||||||
test(`${page}: closing, reopening and switching orders discard the prior signature`, () => {
|
|
||||||
const { state, open } = setup()
|
|
||||||
open()
|
|
||||||
state.auditSignature.value = signature
|
|
||||||
const firstSession = state.auditSession.value
|
|
||||||
open(43)
|
|
||||||
assert.equal(state.auditSignature.value, '')
|
|
||||||
assert.ok(state.auditSession.value > firstSession)
|
|
||||||
state.auditSignature.value = signature
|
|
||||||
state.auditVisible.value = false
|
|
||||||
state.resetAuditInput()
|
|
||||||
assert.equal(state.auditSignature.value, '')
|
|
||||||
open(42)
|
|
||||||
assert.equal(state.auditSignature.value, '')
|
|
||||||
})
|
|
||||||
|
|
||||||
test(`${page}: a pending audit cannot duplicate or change target; failure retains the signature`, async () => {
|
|
||||||
const saving = deferred()
|
|
||||||
const { state, calls, open } = setup(() => saving.promise)
|
|
||||||
open()
|
|
||||||
state.auditSignature.value = signature
|
|
||||||
const submission = state.submitAudit('approve')
|
|
||||||
await state.submitAudit('approve')
|
|
||||||
open(99, 'payment')
|
|
||||||
state.resetAuditInput()
|
|
||||||
assert.equal(calls.length, 1)
|
|
||||||
assert.equal(state.auditKind.value, 'prescription')
|
|
||||||
assert.equal(host ? state.actionRow.value.id : state.auditTargetId.value, 42)
|
|
||||||
saving.reject(new Error('network'))
|
|
||||||
await submission
|
|
||||||
assert.equal(state.auditSignature.value, signature)
|
|
||||||
assert.equal(state.auditVisible.value, true)
|
|
||||||
assert.equal(host ? state.submitting.value : state.auditSubmitting.value, false)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
function logSetup(save = async () => {}) {
|
|
||||||
const calls = [], errors = []
|
|
||||||
const state = handlers('views/consumer/prescription/components/PrescriptionOrderDetailDrawer.vue', [
|
|
||||||
'addLogVisible', 'addLogSaving', 'addLogFormRef', 'addLogSignature', 'addLogSession', 'addLogForm',
|
|
||||||
'requiresAddLogSignature', 'resetAddLogForm', 'openAddLogDialog', 'submitAddLog'
|
|
||||||
], {
|
|
||||||
ref: vue.ref, reactive: vue.reactive, computed: vue.computed, watch: vue.watch,
|
|
||||||
detailData: vue.ref({ id: 42, prescription_audit_status: 1, prescription_audit_signature: signature }),
|
|
||||||
canSetRxAuditOnAddLog: vue.ref(true), canSetPayAuditOnAddLog: vue.ref(true),
|
|
||||||
feedback: { msgError: message => errors.push(message), msgSuccess() {} },
|
|
||||||
prescriptionOrderAddLog: async payload => { calls.push(payload); await save() },
|
|
||||||
refresh: async () => {}, emit() {}
|
|
||||||
}, 'addLogForm.prescription_audit_status')
|
|
||||||
state.addLogFormRef.value = { validate: async () => true, clearValidate() {} }
|
|
||||||
state.openAddLogDialog()
|
|
||||||
state.addLogForm.summary = '补充说明'
|
|
||||||
return { state, calls, errors }
|
|
||||||
}
|
|
||||||
|
|
||||||
test('manual log explicitly setting either terminal status requires a new signature, including unchanged approval', async () => {
|
|
||||||
for (const status of [1, 2]) {
|
|
||||||
const { state, calls } = logSetup()
|
|
||||||
state.addLogForm.prescription_audit_status = status
|
|
||||||
await vue.nextTick()
|
|
||||||
await state.submitAddLog()
|
|
||||||
assert.deepEqual(calls, [])
|
|
||||||
state.addLogSignature.value = signature
|
|
||||||
await state.submitAddLog()
|
|
||||||
assert.equal(calls[0].signature, signature)
|
|
||||||
assert.equal(calls[0].prescription_audit_status, status)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
test('plain logs, payment-only changes and reset to pending do not require or send signatures', async () => {
|
|
||||||
for (const status of ['', 0]) {
|
|
||||||
const { state, calls } = logSetup()
|
|
||||||
state.addLogForm.prescription_audit_status = status
|
|
||||||
state.addLogForm.payment_slip_audit_status = 1
|
|
||||||
await state.submitAddLog()
|
|
||||||
assert.equal(calls.length, 1)
|
|
||||||
assert.equal('signature' in calls[0], false)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
test('manual log cannot reuse a signature after status change or reopen; failed saves retain it', async () => {
|
|
||||||
const { state, calls } = logSetup(async () => { throw new Error('network') })
|
|
||||||
state.addLogForm.prescription_audit_status = 1
|
|
||||||
await vue.nextTick()
|
|
||||||
state.addLogSignature.value = signature
|
|
||||||
state.addLogForm.prescription_audit_status = 2
|
|
||||||
await vue.nextTick()
|
|
||||||
assert.equal(state.addLogSignature.value, '')
|
|
||||||
state.addLogSignature.value = signature
|
|
||||||
await state.submitAddLog()
|
|
||||||
assert.equal(calls.length, 1)
|
|
||||||
assert.equal(state.addLogSignature.value, signature)
|
|
||||||
assert.equal(state.addLogVisible.value, true)
|
|
||||||
state.openAddLogDialog()
|
|
||||||
assert.equal(state.addLogSignature.value, '')
|
|
||||||
})
|
|
||||||
|
|
||||||
test('manual log locks submission before async form validation, preventing duplicates', async () => {
|
|
||||||
const validation = deferred()
|
|
||||||
const { state, calls } = logSetup()
|
|
||||||
state.addLogFormRef.value.validate = () => validation.promise
|
|
||||||
const submit = state.submitAddLog()
|
|
||||||
await state.submitAddLog()
|
|
||||||
state.openAddLogDialog()
|
|
||||||
assert.equal(state.addLogSaving.value, true)
|
|
||||||
validation.resolve(true)
|
|
||||||
await submit
|
|
||||||
assert.equal(calls.length, 1)
|
|
||||||
})
|
|
||||||
|
|
||||||
function loadModule(source, imports, globals = {}) {
|
|
||||||
const compiled = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS, esModuleInterop: true } }).outputText
|
|
||||||
const module = { exports: {} }
|
|
||||||
new Function('require', 'module', 'exports', ...Object.keys(globals), compiled)(imports, module, module.exports, ...Object.values(globals))
|
|
||||||
return module.exports
|
|
||||||
}
|
|
||||||
|
|
||||||
function padSetup() {
|
|
||||||
const { script } = component('components/signature-pad/index.vue')
|
|
||||||
const mounted = [], output = [], paths = []
|
|
||||||
let observer
|
|
||||||
const props = vue.reactive({ modelValue: '', disabled: false })
|
|
||||||
const componentModule = loadModule(script.content, name => {
|
|
||||||
assert.equal(name, 'vue')
|
|
||||||
return { ...vue, onMounted: fn => mounted.push(fn), onBeforeUnmount() {} }
|
|
||||||
}, { window: { devicePixelRatio: 2 }, ResizeObserver: class { constructor(fn) { observer = fn } observe() {} disconnect() {} } })
|
|
||||||
const state = componentModule.default.setup(props, { expose() {}, emit(_event, value) { props.modelValue = value; output.push(value) } })
|
|
||||||
let width = 400
|
|
||||||
const captures = new Set()
|
|
||||||
const context = { beginPath() {}, moveTo(x, y) { paths.push(['move', x, y]) }, lineTo(x, y) { paths.push(['line', x, y]) }, stroke() {}, setTransform(...values) { paths.push(['transform', ...values]) }, fillRect() {} }
|
|
||||||
const canvas = {
|
|
||||||
getBoundingClientRect: () => ({ left: 10, top: 20, width, height: 168 }),
|
|
||||||
getContext: () => context, toDataURL: () => signature,
|
|
||||||
setPointerCapture: id => captures.add(id), hasPointerCapture: id => captures.has(id), releasePointerCapture: id => captures.delete(id)
|
|
||||||
}
|
|
||||||
state.canvasRef.value = canvas
|
|
||||||
mounted.forEach(fn => fn())
|
|
||||||
const point = (x, y, extra = {}) => ({ pointerId: 1, pointerType: 'touch', button: 0, clientX: x + 10, clientY: y + 20, ...extra })
|
|
||||||
const draw = () => { state.onPointerDown(point(20, 30)); state.onPointerMove(point(80, 60)); state.onPointerUp(point(100, 70)) }
|
|
||||||
return { state, props, output, paths, canvas, point, draw, resize: newWidth => { width = newWidth; observer() } }
|
|
||||||
}
|
|
||||||
|
|
||||||
test('signature pad rejects blank clicks and tiny motion, then emits only completed ink', async () => {
|
|
||||||
const { state, props, point, draw } = padSetup()
|
|
||||||
state.onPointerDown(point(20, 20))
|
|
||||||
state.onPointerUp(point(20, 20))
|
|
||||||
assert.equal(props.modelValue, '')
|
|
||||||
state.onPointerDown(point(20, 20))
|
|
||||||
state.onPointerMove(point(21, 21))
|
|
||||||
state.onPointerUp(point(21, 21))
|
|
||||||
assert.equal(props.modelValue, '')
|
|
||||||
draw()
|
|
||||||
await vue.nextTick()
|
|
||||||
assert.equal(props.modelValue, signature)
|
|
||||||
state.clearSignature()
|
|
||||||
await vue.nextTick()
|
|
||||||
assert.equal(props.modelValue, '')
|
|
||||||
state.onPointerDown(point(20, 20))
|
|
||||||
state.onPointerUp(point(20, 20))
|
|
||||||
assert.equal(props.modelValue, '')
|
|
||||||
})
|
|
||||||
|
|
||||||
test('signature pad ignores secondary pointers, cancels interrupted ink and respects disabled state', () => {
|
|
||||||
const { state, props, point, draw } = padSetup()
|
|
||||||
state.onPointerDown(point(20, 20))
|
|
||||||
state.onPointerMove(point(100, 100, { pointerId: 2 }))
|
|
||||||
state.onPointerUp(point(100, 100, { pointerId: 2 }))
|
|
||||||
state.onPointerCancel(point(20, 20))
|
|
||||||
assert.equal(props.modelValue, '')
|
|
||||||
draw()
|
|
||||||
props.disabled = true
|
|
||||||
state.clearSignature()
|
|
||||||
state.onPointerDown(point(20, 20))
|
|
||||||
assert.equal(props.modelValue, signature)
|
|
||||||
assert.equal(state.drawing.value, false)
|
|
||||||
})
|
|
||||||
|
|
||||||
test('signature pad maps CSS coordinates once at high DPR and preserves strokes on resize', () => {
|
|
||||||
const { canvas, paths, draw, resize, props } = padSetup()
|
|
||||||
draw()
|
|
||||||
assert.equal(canvas.width, 800)
|
|
||||||
assert.equal(canvas.height, 336)
|
|
||||||
assert.ok(paths.some(parts => parts[0] === 'line' && parts[1] === 80 && parts[2] === 60))
|
|
||||||
resize(200)
|
|
||||||
assert.equal(canvas.width, 400)
|
|
||||||
assert.ok(paths.some(parts => parts[0] === 'line' && parts[1] === 40 && parts[2] === 60))
|
|
||||||
assert.equal(props.modelValue, signature)
|
|
||||||
})
|
|
||||||
|
|
||||||
test('prescription slip only displays the pharmacist signature for the current signed approval', () => {
|
|
||||||
const source = fs.readFileSync(path.join(root, 'src/components/prescription-slip/utils.ts'), 'utf8')
|
|
||||||
const { rxPharmacistSignature } = loadModule(source, () => { throw new Error('unexpected import') })
|
|
||||||
const signed = { prescription_audit_status: 1, prescription_audit_signature: signature, prescription_audit_signed_name: ' 李药师 ', doctor_name: '王医生' }
|
|
||||||
assert.equal(rxPharmacistSignature(signed), signature)
|
|
||||||
assert.equal(rxPharmacistSignature({ ...signed, prescription_audit_status: '1' }), signature)
|
|
||||||
for (const status of [0, 2, null, undefined]) assert.equal(rxPharmacistSignature({ ...signed, prescription_audit_status: status }), '')
|
|
||||||
assert.equal(rxPharmacistSignature({ ...signed, prescription_audit_signature: '' }), '')
|
|
||||||
assert.equal(rxPharmacistSignature({ ...signed, prescription_audit_signed_name: '' }), signature)
|
|
||||||
assert.equal(rxPharmacistSignature({ doctor_name: '王医生' }), '')
|
|
||||||
component('components/prescription-slip/index.vue')
|
|
||||||
component('views/consumer/prescription/components/AuditSignatureRecord.vue')
|
|
||||||
})
|
|
||||||
|
|
||||||
// 处方预览的 API -> handler -> 实际 Vue 图片渲染回归见 prescription-audit-signature-display.test.cjs。
|
|
||||||
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`。它与现有管理端保持相同约定:
|
程序会自动在地址末尾追加 `/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`。
|
- 鉴权请求头:`token: <登录 token>`,`version: 1.9.4`。
|
||||||
- 响应 envelope:`code=1` 成功、`0` 业务失败、`-1` 登录失效、`10` 需绑定企业微信。
|
- 响应 envelope:`code=1` 成功、`0` 业务失败、`-1` 登录失效、`10` 需绑定企业微信。
|
||||||
- 权限与数据范围:完全以后端 `/auth.admin/mySelf` 返回为准。
|
- 权限与数据范围:完全以后端 `/auth.admin/mySelf` 返回为准。
|
||||||
|
|||||||
@@ -3,9 +3,9 @@
|
|||||||
__all__ = ["DEBUG_MODE", "ONLINE_API_BASE_URL", "__version__"]
|
__all__ = ["DEBUG_MODE", "ONLINE_API_BASE_URL", "__version__"]
|
||||||
|
|
||||||
# Single source of truth for runtime, package, installer, and executable versions.
|
# Single source of truth for runtime, package, installer, and executable versions.
|
||||||
__version__ = "1.5.4"
|
__version__ = "1.5.6"
|
||||||
|
|
||||||
# 调试模式开启时,登录页显示“演示模式”和“服务器设置”。
|
# 调试模式开启时,登录页显示“演示模式”和“服务器设置”。
|
||||||
# 正式发布请保持 False;此时程序只使用下面配置的线上域名。
|
# 正式发布请保持 False;此时程序只使用下面配置的线上域名。
|
||||||
DEBUG_MODE = False
|
DEBUG_MODE = True
|
||||||
ONLINE_API_BASE_URL = "https://admin.zhenyangtang.com.cn"
|
ONLINE_API_BASE_URL = "https://admin.zhenyangtang.com.cn"
|
||||||
|
|||||||
+144
-177
@@ -3,6 +3,7 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
import math
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
import time
|
import time
|
||||||
@@ -10,16 +11,11 @@ from collections.abc import Mapping, Sequence
|
|||||||
from contextlib import suppress
|
from contextlib import suppress
|
||||||
from typing import Any
|
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.QtGui import QGuiApplication, QIcon
|
||||||
from PySide6.QtWidgets import (
|
from PySide6.QtWidgets import (
|
||||||
QApplication,
|
QApplication,
|
||||||
QDialog,
|
QDialog,
|
||||||
QFrame,
|
|
||||||
QHBoxLayout,
|
|
||||||
QLabel,
|
|
||||||
QPushButton,
|
|
||||||
QVBoxLayout,
|
|
||||||
QWidget,
|
QWidget,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -34,14 +30,15 @@ from doctor_workstation.services import (
|
|||||||
TokenStore,
|
TokenStore,
|
||||||
build_repository,
|
build_repository,
|
||||||
)
|
)
|
||||||
from doctor_workstation.ui import LoginWindow, ShellWindow, apply_theme
|
from doctor_workstation.ui import LoginWindow, ShellWindow, SpatialShellWindow, apply_theme
|
||||||
from doctor_workstation.ui.dialogs.app_update import AppUpdateSession
|
from doctor_workstation.ui.dialogs.app_update import AppUpdateSession
|
||||||
|
from doctor_workstation.ui.dialogs.video_cockpit import VideoCockpitDemoDialog as DemoVideoDialog
|
||||||
from doctor_workstation.ui.widgets import (
|
from doctor_workstation.ui.widgets import (
|
||||||
first_value,
|
first_value,
|
||||||
friendly_error,
|
friendly_error,
|
||||||
gender_text,
|
gender_text,
|
||||||
get_value,
|
get_value,
|
||||||
has_permission,
|
has_permission,
|
||||||
run_async,
|
run_async,
|
||||||
set_authentication_expired_handler,
|
set_authentication_expired_handler,
|
||||||
show_toast,
|
show_toast,
|
||||||
@@ -294,109 +291,6 @@ class _UnconfiguredRepository:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
class DemoVideoDialog(QDialog):
|
|
||||||
"""Non-network video-room preview used only by the explicit demo mode."""
|
|
||||||
|
|
||||||
def __init__(self, patient_name: str, parent: QWidget | None = None) -> None:
|
|
||||||
super().__init__(parent)
|
|
||||||
self._seconds = 0
|
|
||||||
self.setWindowTitle("视频面诊 · 演示模式")
|
|
||||||
self.setMinimumSize(760, 520)
|
|
||||||
self.resize(980, 660)
|
|
||||||
self.setModal(False)
|
|
||||||
self.setStyleSheet(
|
|
||||||
"QDialog{background:#F7F9FE;color:#111F46;}"
|
|
||||||
"QLabel{color:#111F46;}"
|
|
||||||
"QFrame#RemoteStage{background:#0E1421;border:1px solid #29334F;border-radius:16px;}"
|
|
||||||
"QFrame#RemoteStage QLabel{color:#F7F9FE;}"
|
|
||||||
"QFrame#LocalStage{background:#151D31;border:1px solid #3F4E75;border-radius:12px;}"
|
|
||||||
"QPushButton{min-width:96px;min-height:40px;padding:0 16px;border-radius:9px;"
|
|
||||||
"background:#FFFFFF;color:#3F4E75;border:1px solid #E6EAF5;font-weight:600;}"
|
|
||||||
"QPushButton:hover{color:#4451E2;background:#F0F2FF;border-color:#5761F4;}"
|
|
||||||
"QPushButton:checked{color:#FFFFFF;background:#5761F4;border-color:#5761F4;}"
|
|
||||||
"QPushButton#Hangup{color:#FFFFFF;background:#C23D4E;border-color:#C23D4E;}"
|
|
||||||
"QPushButton#Hangup:hover{background:#D94857;border-color:#D94857;}"
|
|
||||||
)
|
|
||||||
|
|
||||||
root = QVBoxLayout(self)
|
|
||||||
root.setContentsMargins(22, 18, 22, 22)
|
|
||||||
root.setSpacing(14)
|
|
||||||
header = QHBoxLayout()
|
|
||||||
title = QLabel(f"与 {patient_name or '患者'} 的视频面诊")
|
|
||||||
title.setStyleSheet("font-size:18px;font-weight:700;")
|
|
||||||
header.addWidget(title)
|
|
||||||
header.addStretch(1)
|
|
||||||
demo = QLabel("● 演示模式 · 未连接腾讯云")
|
|
||||||
demo.setStyleSheet("color:#707584;font-size:12px;")
|
|
||||||
header.addWidget(demo)
|
|
||||||
self.duration_label = QLabel("00:00")
|
|
||||||
self.duration_label.setStyleSheet("font-weight:700;")
|
|
||||||
header.addWidget(self.duration_label)
|
|
||||||
root.addLayout(header)
|
|
||||||
|
|
||||||
stage = QFrame()
|
|
||||||
stage.setObjectName("RemoteStage")
|
|
||||||
stage_layout = QVBoxLayout(stage)
|
|
||||||
stage_layout.setContentsMargins(22, 22, 22, 22)
|
|
||||||
stage_layout.addStretch(1)
|
|
||||||
avatar = QLabel((patient_name or "患")[:1])
|
|
||||||
avatar.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
|
||||||
avatar.setFixedSize(104, 104)
|
|
||||||
avatar.setStyleSheet(
|
|
||||||
"background:#F0F2FF;color:#5761F4;border-radius:52px;font-size:42px;font-weight:700;"
|
|
||||||
)
|
|
||||||
stage_layout.addWidget(avatar, 0, Qt.AlignmentFlag.AlignHCenter)
|
|
||||||
waiting = QLabel("等待患者接听…")
|
|
||||||
waiting.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
|
||||||
waiting.setStyleSheet("font-size:17px;font-weight:600;")
|
|
||||||
stage_layout.addWidget(waiting)
|
|
||||||
hint = QLabel("生产模式将通过后端短时 UserSig 初始化腾讯 TUICallKit")
|
|
||||||
hint.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
|
||||||
hint.setStyleSheet("color:#A4ADC3;font-size:12px;")
|
|
||||||
stage_layout.addWidget(hint)
|
|
||||||
stage_layout.addStretch(1)
|
|
||||||
|
|
||||||
local = QFrame(stage)
|
|
||||||
local.setObjectName("LocalStage")
|
|
||||||
local.setGeometry(24, 24, 178, 112)
|
|
||||||
local_layout = QVBoxLayout(local)
|
|
||||||
local_label = QLabel("医生画面")
|
|
||||||
local_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
|
||||||
local_label.setStyleSheet("color:#D9E0F2;font-weight:600;")
|
|
||||||
local_layout.addWidget(local_label)
|
|
||||||
root.addWidget(stage, 1)
|
|
||||||
|
|
||||||
controls = QHBoxLayout()
|
|
||||||
controls.addStretch(1)
|
|
||||||
self.mic_button = QPushButton("麦克风 开")
|
|
||||||
self.mic_button.setCheckable(True)
|
|
||||||
self.mic_button.toggled.connect(
|
|
||||||
lambda muted: self.mic_button.setText("麦克风 关" if muted else "麦克风 开")
|
|
||||||
)
|
|
||||||
controls.addWidget(self.mic_button)
|
|
||||||
self.camera_button = QPushButton("摄像头 开")
|
|
||||||
self.camera_button.setCheckable(True)
|
|
||||||
self.camera_button.toggled.connect(
|
|
||||||
lambda off: self.camera_button.setText("摄像头 关" if off else "摄像头 开")
|
|
||||||
)
|
|
||||||
controls.addWidget(self.camera_button)
|
|
||||||
hangup = QPushButton("结束面诊")
|
|
||||||
hangup.setObjectName("Hangup")
|
|
||||||
hangup.clicked.connect(self.close)
|
|
||||||
controls.addWidget(hangup)
|
|
||||||
controls.addStretch(1)
|
|
||||||
root.addLayout(controls)
|
|
||||||
|
|
||||||
self._timer = QTimer(self)
|
|
||||||
self._timer.timeout.connect(self._tick)
|
|
||||||
self._timer.start(1000)
|
|
||||||
|
|
||||||
def _tick(self) -> None:
|
|
||||||
self._seconds += 1
|
|
||||||
minutes, seconds = divmod(self._seconds, 60)
|
|
||||||
self.duration_label.setText(f"{minutes:02d}:{seconds:02d}")
|
|
||||||
|
|
||||||
|
|
||||||
class ApplicationController(QObject):
|
class ApplicationController(QObject):
|
||||||
"""Own windows, repositories and the authenticated application lifecycle."""
|
"""Own windows, repositories and the authenticated application lifecycle."""
|
||||||
|
|
||||||
@@ -413,8 +307,8 @@ class ApplicationController(QObject):
|
|||||||
self.current_repository: Any = None
|
self.current_repository: Any = None
|
||||||
self.current_demo_mode = self.debug_mode and config.demo_mode
|
self.current_demo_mode = self.debug_mode and config.demo_mode
|
||||||
self.video_calls: dict[str, Any] = {}
|
self.video_calls: dict[str, Any] = {}
|
||||||
self.video_pending: dict[str, object] = {}
|
self.video_pending: dict[str, object] = {}
|
||||||
self._pending_im_request: tuple[str, object] | None = None
|
self._pending_im_request: tuple[str, object] | None = None
|
||||||
self.demo_video_dialogs: dict[str, DemoVideoDialog] = {}
|
self.demo_video_dialogs: dict[str, DemoVideoDialog] = {}
|
||||||
self._video_preview_state: dict[str, Any] | None = None
|
self._video_preview_state: dict[str, Any] | None = None
|
||||||
self._video_preview_generation = 0
|
self._video_preview_generation = 0
|
||||||
@@ -423,9 +317,18 @@ class ApplicationController(QObject):
|
|||||||
self._restore_worker: Any = None
|
self._restore_worker: Any = None
|
||||||
self._shutting_down = False
|
self._shutting_down = False
|
||||||
self._authentication_expiry_in_progress = 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._rebuild_remote_repository()
|
||||||
self.app_updater = AppUpdateSession(self)
|
self.app_updater = AppUpdateSession(self)
|
||||||
set_authentication_expired_handler(self._on_authentication_expired)
|
|
||||||
application.aboutToQuit.connect(self.shutdown)
|
application.aboutToQuit.connect(self.shutdown)
|
||||||
|
|
||||||
def start(self) -> None:
|
def start(self) -> None:
|
||||||
@@ -529,7 +432,7 @@ class ApplicationController(QObject):
|
|||||||
self.remote_repository = repository
|
self.remote_repository = repository
|
||||||
if old is not None and old is not self.current_repository:
|
if old is not None and old is not self.current_repository:
|
||||||
with suppress(Exception):
|
with suppress(Exception):
|
||||||
old.client.close()
|
old.close()
|
||||||
|
|
||||||
def _begin_session_restore(self) -> None:
|
def _begin_session_restore(self) -> None:
|
||||||
"""Validate a scoped persisted token without racing manual login."""
|
"""Validate a scoped persisted token without racing manual login."""
|
||||||
@@ -655,6 +558,8 @@ class ApplicationController(QObject):
|
|||||||
self.login_window.set_session_restore_pending(False)
|
self.login_window.set_session_restore_pending(False)
|
||||||
|
|
||||||
def _on_login_succeeded(self, payload: dict[str, Any]) -> None:
|
def _on_login_succeeded(self, payload: dict[str, Any]) -> None:
|
||||||
|
if self._shutting_down:
|
||||||
|
return
|
||||||
self._cancel_session_restore()
|
self._cancel_session_restore()
|
||||||
session = payload.get("session")
|
session = payload.get("session")
|
||||||
repository = payload.get("repository")
|
repository = payload.get("repository")
|
||||||
@@ -683,13 +588,22 @@ class ApplicationController(QObject):
|
|||||||
self.current_repository = repository
|
self.current_repository = repository
|
||||||
self._authentication_expiry_in_progress = False
|
self._authentication_expiry_in_progress = False
|
||||||
self.current_demo_mode = demo_mode
|
self.current_demo_mode = demo_mode
|
||||||
self.shell_window = ShellWindow(repository, payload, session.permissions)
|
set_authentication_expired_handler(self._on_authentication_expired)
|
||||||
|
self.shell_window = SpatialShellWindow(repository, payload, session.permissions)
|
||||||
self.shell_window.logout_requested.connect(self._logout)
|
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.video_requested.connect(self._request_video)
|
||||||
self.shell_window.update_check_requested.connect(
|
self.shell_window.update_check_requested.connect(
|
||||||
lambda: self.app_updater.check(interactive=True)
|
lambda: self.app_updater.check(interactive=True)
|
||||||
)
|
)
|
||||||
self._apply_window_icon(self.shell_window)
|
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:
|
if self.login_window is not None:
|
||||||
self.login_window.hide()
|
self.login_window.hide()
|
||||||
self.shell_window.show()
|
self.shell_window.show()
|
||||||
@@ -697,6 +611,45 @@ class ApplicationController(QObject):
|
|||||||
self.shell_window.activateWindow()
|
self.shell_window.activateWindow()
|
||||||
self.app_updater.schedule(delay_ms=400)
|
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:
|
def _login_guard_error(self, message: str) -> None:
|
||||||
if self.login_window is not None:
|
if self.login_window is not None:
|
||||||
self.login_window.error_banner.show_message(message, "warning")
|
self.login_window.error_banner.show_message(message, "warning")
|
||||||
@@ -720,6 +673,9 @@ class ApplicationController(QObject):
|
|||||||
def _logout(self, *, message: str = "") -> None:
|
def _logout(self, *, message: str = "") -> None:
|
||||||
"""Clear authenticated resources and return to the login window."""
|
"""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)
|
self._restore_video_preview(activate=False)
|
||||||
calls = tuple(self.video_calls.values())
|
calls = tuple(self.video_calls.values())
|
||||||
for call in calls:
|
for call in calls:
|
||||||
@@ -727,20 +683,29 @@ class ApplicationController(QObject):
|
|||||||
call.close()
|
call.close()
|
||||||
self._wait_for_video_lifecycle(calls, timeout=1.25)
|
self._wait_for_video_lifecycle(calls, timeout=1.25)
|
||||||
self.video_calls.clear()
|
self.video_calls.clear()
|
||||||
self.video_pending.clear()
|
self.video_pending.clear()
|
||||||
self._pending_im_request = None
|
self._pending_im_request = None
|
||||||
for dialog in self.demo_video_dialogs.values():
|
for dialog in tuple(self.demo_video_dialogs.values()):
|
||||||
dialog.close()
|
dialog.close()
|
||||||
self.demo_video_dialogs.clear()
|
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):
|
with suppress(Exception):
|
||||||
self.current_repository.logout()
|
repository.logout()
|
||||||
self.current_repository = None
|
self.current_repository = None
|
||||||
|
self._show_login()
|
||||||
if self.shell_window is not None:
|
if self.shell_window is not None:
|
||||||
|
self.shell_window.close_requested.disconnect(self.request_quit)
|
||||||
self.shell_window.close()
|
self.shell_window.close()
|
||||||
self.shell_window.deleteLater()
|
self.shell_window.deleteLater()
|
||||||
self.shell_window = None
|
self.shell_window = None
|
||||||
self._show_login()
|
|
||||||
if message and self.login_window is not None:
|
if message and self.login_window is not None:
|
||||||
self.login_window.error_banner.show_message(message, "warning")
|
self.login_window.error_banner.show_message(message, "warning")
|
||||||
|
|
||||||
@@ -749,8 +714,8 @@ class ApplicationController(QObject):
|
|||||||
if parent is None or self.current_repository is None:
|
if parent is None or self.current_repository is None:
|
||||||
return
|
return
|
||||||
patient_id = payload.get("patient_id")
|
patient_id = payload.get("patient_id")
|
||||||
diagnosis_id = payload.get("diagnosis_id")
|
diagnosis_id = payload.get("diagnosis_id")
|
||||||
appointment_id = int(payload.get("appointment_id") or 0)
|
appointment_id = int(payload.get("appointment_id") or 0)
|
||||||
patient_name = str(payload.get("patient_name") or "患者")
|
patient_name = str(payload.get("patient_name") or "患者")
|
||||||
open_im = str(payload.get("mode") or "video").lower() == "im"
|
open_im = str(payload.get("mode") or "video").lower() == "im"
|
||||||
fallback_record = payload.get("record")
|
fallback_record = payload.get("record")
|
||||||
@@ -758,16 +723,16 @@ class ApplicationController(QObject):
|
|||||||
show_toast(parent, "患者或诊单信息不完整,无法发起视频。", "danger", 4200)
|
show_toast(parent, "患者或诊单信息不完整,无法发起视频。", "danger", 4200)
|
||||||
return
|
return
|
||||||
|
|
||||||
call_key = f"{diagnosis_id}:{appointment_id}"
|
call_key = f"{diagnosis_id}:{appointment_id}"
|
||||||
if open_im and self._pending_im_request is not None:
|
if open_im and self._pending_im_request is not None:
|
||||||
pending_key, pending_marker = self._pending_im_request
|
pending_key, pending_marker = self._pending_im_request
|
||||||
if pending_key != call_key:
|
if pending_key != call_key:
|
||||||
# Retire a previous selection before any early return, including
|
# Retire a previous selection before any early return, including
|
||||||
# when the selected IM window is already open.
|
# when the selected IM window is already open.
|
||||||
if self.video_pending.get(pending_key) is pending_marker:
|
if self.video_pending.get(pending_key) is pending_marker:
|
||||||
self.video_pending.pop(pending_key, None)
|
self.video_pending.pop(pending_key, None)
|
||||||
self._pending_im_request = None
|
self._pending_im_request = None
|
||||||
existing_call = self.video_calls.get(call_key)
|
existing_call = self.video_calls.get(call_key)
|
||||||
if open_im and existing_call is not None and getattr(existing_call, "open_im", False):
|
if open_im and existing_call is not None and getattr(existing_call, "open_im", False):
|
||||||
qt_window = getattr(existing_call, "qt_window", None)
|
qt_window = getattr(existing_call, "qt_window", None)
|
||||||
if qt_window is not None:
|
if qt_window is not None:
|
||||||
@@ -813,18 +778,18 @@ class ApplicationController(QObject):
|
|||||||
)
|
)
|
||||||
repository = self.current_repository
|
repository = self.current_repository
|
||||||
marker = object()
|
marker = object()
|
||||||
self.video_pending[call_key] = marker
|
self.video_pending[call_key] = marker
|
||||||
if open_im:
|
if open_im:
|
||||||
self._pending_im_request = (call_key, marker)
|
self._pending_im_request = (call_key, marker)
|
||||||
|
|
||||||
def get_video_context() -> tuple[Any, dict[str, str]]:
|
def get_video_context() -> tuple[Any, dict[str, str]]:
|
||||||
ticket = repository.get_call_ticket(
|
ticket = repository.get_call_ticket(
|
||||||
patient_id=int(patient_id),
|
patient_id=int(patient_id),
|
||||||
diagnosis_id=int(diagnosis_id),
|
diagnosis_id=int(diagnosis_id),
|
||||||
appointment_id=appointment_id,
|
appointment_id=appointment_id,
|
||||||
)
|
)
|
||||||
if appointment_id and int(ticket.raw.get("appointment_id") or 0) != appointment_id:
|
if appointment_id and int(ticket.raw.get("appointment_id") or 0) != appointment_id:
|
||||||
raise ValueError("通话凭证与本次挂号不匹配,请重新打开聊天窗口。")
|
raise ValueError("通话凭证与本次挂号不匹配,请重新打开聊天窗口。")
|
||||||
detail: Any = {}
|
detail: Any = {}
|
||||||
detail_loader = getattr(repository, "patient_detail", None)
|
detail_loader = getattr(repository, "patient_detail", None)
|
||||||
if callable(detail_loader):
|
if callable(detail_loader):
|
||||||
@@ -885,12 +850,12 @@ class ApplicationController(QObject):
|
|||||||
parent: QWidget,
|
parent: QWidget,
|
||||||
error: Exception,
|
error: Exception,
|
||||||
) -> None:
|
) -> None:
|
||||||
if self.video_pending.get(call_key) is not marker:
|
if self.video_pending.get(call_key) is not marker:
|
||||||
return
|
return
|
||||||
self.video_pending.pop(call_key, None)
|
self.video_pending.pop(call_key, None)
|
||||||
if self._pending_im_request == (call_key, marker):
|
if self._pending_im_request == (call_key, marker):
|
||||||
self._pending_im_request = None
|
self._pending_im_request = None
|
||||||
if self.shell_window is parent:
|
if self.shell_window is parent:
|
||||||
show_toast(
|
show_toast(
|
||||||
parent,
|
parent,
|
||||||
f"视频准备失败:{friendly_error(error)}",
|
f"视频准备失败:{friendly_error(error)}",
|
||||||
@@ -911,11 +876,11 @@ class ApplicationController(QObject):
|
|||||||
patient_name: str = "患者",
|
patient_name: str = "患者",
|
||||||
patient_case: Mapping[str, Any] | None = None,
|
patient_case: Mapping[str, Any] | None = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
if self.video_pending.get(call_key) is not marker:
|
if self.video_pending.get(call_key) is not marker:
|
||||||
return
|
return
|
||||||
self.video_pending.pop(call_key, None)
|
self.video_pending.pop(call_key, None)
|
||||||
if self._pending_im_request == (call_key, marker):
|
if self._pending_im_request == (call_key, marker):
|
||||||
self._pending_im_request = None
|
self._pending_im_request = None
|
||||||
if (
|
if (
|
||||||
self.shell_window is None
|
self.shell_window is None
|
||||||
or self.current_repository is not repository
|
or self.current_repository is not repository
|
||||||
@@ -940,13 +905,13 @@ class ApplicationController(QObject):
|
|||||||
open_im=open_im,
|
open_im=open_im,
|
||||||
patient_name=patient_name,
|
patient_name=patient_name,
|
||||||
patient_case=patient_case,
|
patient_case=patient_case,
|
||||||
can_ai_assistant=has_permission(
|
can_ai_assistant=has_permission(
|
||||||
getattr(self.shell_window, "permissions", None),
|
getattr(self.shell_window, "permissions", None),
|
||||||
"tcm.diagnosis/aiAssistant",
|
"tcm.diagnosis/aiAssistant",
|
||||||
default=False,
|
default=False,
|
||||||
),
|
),
|
||||||
on_open_diagnosis=lambda current_id=diagnosis_id, current_key=call_key: (
|
on_open_diagnosis=lambda current_id=diagnosis_id, current_key=call_key: (
|
||||||
self._open_video_diagnosis(current_id, call_key=current_key)
|
self._open_video_diagnosis(current_id, call_key=current_key)
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
@@ -968,7 +933,7 @@ class ApplicationController(QObject):
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
def _open_video_diagnosis(self, diagnosis_id: Any, *, call_key: str) -> None:
|
def _open_video_diagnosis(self, diagnosis_id: Any, *, call_key: str) -> None:
|
||||||
"""Open the diagnosis while keeping its live video visible as a preview."""
|
"""Open the diagnosis while keeping its live video visible as a preview."""
|
||||||
|
|
||||||
shell = self.shell_window
|
shell = self.shell_window
|
||||||
@@ -977,7 +942,7 @@ class ApplicationController(QObject):
|
|||||||
dialog = shell.open_diagnosis_by_id(diagnosis_id, modeless=True)
|
dialog = shell.open_diagnosis_by_id(diagnosis_id, modeless=True)
|
||||||
if dialog is None:
|
if dialog is None:
|
||||||
return
|
return
|
||||||
call = self.video_calls.get(call_key)
|
call = self.video_calls.get(call_key)
|
||||||
video_window = getattr(call, "qt_window", None)
|
video_window = getattr(call, "qt_window", None)
|
||||||
if video_window is not None:
|
if video_window is not None:
|
||||||
self._show_video_preview(video_window, dialog)
|
self._show_video_preview(video_window, dialog)
|
||||||
@@ -1010,8 +975,8 @@ class ApplicationController(QObject):
|
|||||||
preview_height = min(380, max(320, round(preview_width * 0.66)))
|
preview_height = min(380, max(320, round(preview_width * 0.66)))
|
||||||
margin = 18
|
margin = 18
|
||||||
|
|
||||||
if callable(getattr(video_window, "setProperty", None)):
|
if callable(getattr(video_window, "setProperty", None)):
|
||||||
video_window.setProperty("doctorSkipOpenGeometry", True)
|
video_window.setProperty("doctorSkipOpenGeometry", True)
|
||||||
video_window.showNormal()
|
video_window.showNormal()
|
||||||
video_window.setMinimumSize(440, 300)
|
video_window.setMinimumSize(440, 300)
|
||||||
video_window.setWindowFlag(Qt.WindowType.WindowStaysOnTopHint, True)
|
video_window.setWindowFlag(Qt.WindowType.WindowStaysOnTopHint, True)
|
||||||
@@ -1030,14 +995,14 @@ class ApplicationController(QObject):
|
|||||||
lambda _result, expected=generation: self._restore_video_preview(expected)
|
lambda _result, expected=generation: self._restore_video_preview(expected)
|
||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
set_close_handler = getattr(video_window, "set_compact_close_handler", None)
|
set_close_handler = getattr(video_window, "set_compact_close_handler", None)
|
||||||
if callable(set_close_handler):
|
if callable(set_close_handler):
|
||||||
set_close_handler(lambda expected=generation: self._restore_video_preview(expected))
|
set_close_handler(lambda expected=generation: self._restore_video_preview(expected))
|
||||||
video_window.raise_()
|
video_window.raise_()
|
||||||
dialog.raise_()
|
dialog.raise_()
|
||||||
dialog.activateWindow()
|
dialog.activateWindow()
|
||||||
except RuntimeError:
|
except RuntimeError:
|
||||||
self._restore_video_preview(generation, activate=False)
|
self._restore_video_preview(generation, activate=False)
|
||||||
|
|
||||||
def _restore_video_preview(
|
def _restore_video_preview(
|
||||||
self,
|
self,
|
||||||
@@ -1054,12 +1019,12 @@ class ApplicationController(QObject):
|
|||||||
self._video_preview_generation += 1
|
self._video_preview_generation += 1
|
||||||
window = state.get("window")
|
window = state.get("window")
|
||||||
try:
|
try:
|
||||||
set_close_handler = getattr(window, "set_compact_close_handler", None)
|
set_close_handler = getattr(window, "set_compact_close_handler", None)
|
||||||
if callable(set_close_handler):
|
if callable(set_close_handler):
|
||||||
set_close_handler(None)
|
set_close_handler(None)
|
||||||
restore_screenshot = getattr(window, "restore_screenshot_preview", None)
|
restore_screenshot = getattr(window, "restore_screenshot_preview", None)
|
||||||
if callable(restore_screenshot):
|
if callable(restore_screenshot):
|
||||||
restore_screenshot()
|
restore_screenshot()
|
||||||
window.setWindowFlag(
|
window.setWindowFlag(
|
||||||
Qt.WindowType.WindowStaysOnTopHint,
|
Qt.WindowType.WindowStaysOnTopHint,
|
||||||
bool(state.get("stays_on_top")),
|
bool(state.get("stays_on_top")),
|
||||||
@@ -1075,8 +1040,8 @@ class ApplicationController(QObject):
|
|||||||
window.raise_()
|
window.raise_()
|
||||||
if activate:
|
if activate:
|
||||||
window.activateWindow()
|
window.activateWindow()
|
||||||
if callable(getattr(window, "setProperty", None)):
|
if callable(getattr(window, "setProperty", None)):
|
||||||
window.setProperty("doctorSkipOpenGeometry", False)
|
window.setProperty("doctorSkipOpenGeometry", False)
|
||||||
except (AttributeError, RuntimeError):
|
except (AttributeError, RuntimeError):
|
||||||
return
|
return
|
||||||
|
|
||||||
@@ -1130,6 +1095,8 @@ class ApplicationController(QObject):
|
|||||||
if self._shutting_down:
|
if self._shutting_down:
|
||||||
return
|
return
|
||||||
self._shutting_down = True
|
self._shutting_down = True
|
||||||
|
self._desktop_session = None
|
||||||
|
self._desktop_timer.stop()
|
||||||
self._cancel_session_restore()
|
self._cancel_session_restore()
|
||||||
self.app_updater.shutdown()
|
self.app_updater.shutdown()
|
||||||
set_authentication_expired_handler(None)
|
set_authentication_expired_handler(None)
|
||||||
@@ -1141,7 +1108,7 @@ class ApplicationController(QObject):
|
|||||||
self._wait_for_video_lifecycle(calls, timeout=1.25)
|
self._wait_for_video_lifecycle(calls, timeout=1.25)
|
||||||
if self.remote_repository is not None:
|
if self.remote_repository is not None:
|
||||||
with suppress(Exception):
|
with suppress(Exception):
|
||||||
self.remote_repository.client.close()
|
self.remote_repository.close()
|
||||||
|
|
||||||
|
|
||||||
def _prefer_native_tls_backend() -> None:
|
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)
|
aux_usage: JSONDict = field(default_factory=dict)
|
||||||
doctor_name: str = ""
|
doctor_name: str = ""
|
||||||
doctor_signature: str = ""
|
doctor_signature: str = ""
|
||||||
|
esign: JSONDict = field(default_factory=dict)
|
||||||
creator_id: int | None = None
|
creator_id: int | None = None
|
||||||
assistant_name: str = ""
|
assistant_name: str = ""
|
||||||
is_system_auto: bool = False
|
is_system_auto: bool = False
|
||||||
@@ -623,6 +624,8 @@ class Prescription:
|
|||||||
audit_time: str = ""
|
audit_time: str = ""
|
||||||
audit_by_name: str = ""
|
audit_by_name: str = ""
|
||||||
audit_remark: 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_status: int | None = None
|
||||||
business_prescription_audit_rejected: bool = False
|
business_prescription_audit_rejected: bool = False
|
||||||
business_prescription_audit_remark: str = ""
|
business_prescription_audit_remark: str = ""
|
||||||
@@ -687,6 +690,7 @@ class Prescription:
|
|||||||
aux_usage=dict(_mapping(source.get("aux_usage"))),
|
aux_usage=dict(_mapping(source.get("aux_usage"))),
|
||||||
doctor_name=_text(source.get("doctor_name")),
|
doctor_name=_text(source.get("doctor_name")),
|
||||||
doctor_signature=_text(source.get("doctor_signature")),
|
doctor_signature=_text(source.get("doctor_signature")),
|
||||||
|
esign=dict(_mapping(source.get("esign"))),
|
||||||
creator_id=_integer(source.get("creator_id"), None),
|
creator_id=_integer(source.get("creator_id"), None),
|
||||||
assistant_name=_text(source.get("assistant_name")),
|
assistant_name=_text(source.get("assistant_name")),
|
||||||
is_system_auto=_boolean(source.get("is_system_auto")),
|
is_system_auto=_boolean(source.get("is_system_auto")),
|
||||||
@@ -696,6 +700,8 @@ class Prescription:
|
|||||||
audit_time=_text(source.get("audit_time")),
|
audit_time=_text(source.get("audit_time")),
|
||||||
audit_by_name=_text(source.get("audit_by_name")),
|
audit_by_name=_text(source.get("audit_by_name")),
|
||||||
audit_remark=_text(source.get("audit_remark")),
|
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(
|
business_prescription_audit_status=_integer(
|
||||||
source.get("business_prescription_audit_status"), None
|
source.get("business_prescription_audit_status"), None
|
||||||
),
|
),
|
||||||
@@ -764,6 +770,7 @@ class Prescription:
|
|||||||
"aux_usage": dict(self.aux_usage),
|
"aux_usage": dict(self.aux_usage),
|
||||||
"doctor_name": self.doctor_name,
|
"doctor_name": self.doctor_name,
|
||||||
"doctor_signature": self.doctor_signature,
|
"doctor_signature": self.doctor_signature,
|
||||||
|
"esign": dict(self.esign),
|
||||||
"is_shared": int(self.is_shared),
|
"is_shared": int(self.is_shared),
|
||||||
"visible_role_ids": list(self.visible_role_ids),
|
"visible_role_ids": list(self.visible_role_ids),
|
||||||
"audit_status": self.audit_status,
|
"audit_status": self.audit_status,
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ class Session:
|
|||||||
is_paw: int = 1
|
is_paw: int = 1
|
||||||
need_bind_work_wechat: bool = False
|
need_bind_work_wechat: bool = False
|
||||||
metadata: dict[str, Any] = field(default_factory=dict, repr=False)
|
metadata: dict[str, Any] = field(default_factory=dict, repr=False)
|
||||||
|
desktop_expires_at: int = 0
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def authenticated(self) -> bool:
|
def authenticated(self) -> bool:
|
||||||
|
|||||||
@@ -181,11 +181,13 @@ class ApiClient:
|
|||||||
*,
|
*,
|
||||||
headers: Mapping[str, str] | None = None,
|
headers: Mapping[str, str] | None = None,
|
||||||
timeout: float | httpx.Timeout | None = None,
|
timeout: float | httpx.Timeout | None = None,
|
||||||
|
max_retries: int | None = None,
|
||||||
) -> Any:
|
) -> Any:
|
||||||
"""Issue a GET request and return the unwrapped envelope data."""
|
"""Issue a GET request and return the unwrapped envelope data."""
|
||||||
|
|
||||||
return self.request(
|
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(
|
def post(
|
||||||
@@ -239,15 +241,18 @@ class ApiClient:
|
|||||||
payload: Mapping[str, Any],
|
payload: Mapping[str, Any],
|
||||||
*,
|
*,
|
||||||
timeout: float = 10.0,
|
timeout: float = 10.0,
|
||||||
|
headers: Mapping[str, str] | None = None,
|
||||||
) -> Any:
|
) -> Any:
|
||||||
"""Send a short control request without waiting for the ordinary pool."""
|
"""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:
|
try:
|
||||||
with httpx.Client(transport=self._stream_transport, verify=self._verify) as client:
|
with httpx.Client(transport=self._stream_transport, verify=self._verify) as client:
|
||||||
response = client.post(
|
response = client.post(
|
||||||
self._endpoint_url(endpoint),
|
self._endpoint_url(endpoint),
|
||||||
json=dict(payload),
|
json=dict(payload),
|
||||||
headers=self._headers(None),
|
headers=self._headers(headers),
|
||||||
timeout=timeout,
|
timeout=timeout,
|
||||||
)
|
)
|
||||||
return self._unwrap(response)
|
return self._unwrap(response)
|
||||||
@@ -497,6 +502,7 @@ class ApiClient:
|
|||||||
files: Mapping[str, Any] | None = None,
|
files: Mapping[str, Any] | None = None,
|
||||||
headers: Mapping[str, str] | None = None,
|
headers: Mapping[str, str] | None = None,
|
||||||
timeout: float | httpx.Timeout | None = None,
|
timeout: float | httpx.Timeout | None = None,
|
||||||
|
max_retries: int | None = None,
|
||||||
) -> Any:
|
) -> Any:
|
||||||
"""Issue one API request with structured transport/envelope errors."""
|
"""Issue one API request with structured transport/envelope errors."""
|
||||||
|
|
||||||
@@ -514,7 +520,10 @@ class ApiClient:
|
|||||||
headers,
|
headers,
|
||||||
json_content_type=files is None and data is None,
|
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
|
response: httpx.Response | None = None
|
||||||
request_timeout = self.timeout if timeout is None else timeout
|
request_timeout = self.timeout if timeout is None else timeout
|
||||||
with self._borrow_client() as client:
|
with self._borrow_client() as client:
|
||||||
|
|||||||
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,
|
account: str | None = None,
|
||||||
scope: str | None = None,
|
scope: str | None = None,
|
||||||
|
desktop_expires_at: int = 0,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Persist a token plus optional account and API-scope metadata.
|
"""Persist a token plus optional account and API-scope metadata.
|
||||||
|
|
||||||
@@ -117,6 +118,12 @@ class TokenStore:
|
|||||||
self.save_account(account)
|
self.save_account(account)
|
||||||
return
|
return
|
||||||
data = self._read_file()
|
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:
|
if account is not None:
|
||||||
account_value = account.strip()
|
account_value = account.strip()
|
||||||
previous_account = str(data.get("account") or "").strip()
|
previous_account = str(data.get("account") or "").strip()
|
||||||
@@ -151,6 +158,18 @@ class TokenStore:
|
|||||||
data["token"] = cleaned
|
data["token"] = cleaned
|
||||||
self._write_file(data)
|
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:
|
def clear_token(self) -> None:
|
||||||
"""Delete the token while retaining remembered login credentials."""
|
"""Delete the token while retaining remembered login credentials."""
|
||||||
|
|
||||||
@@ -161,6 +180,7 @@ class TokenStore:
|
|||||||
self._uses_keyring = False
|
self._uses_keyring = False
|
||||||
data = self._read_file()
|
data = self._read_file()
|
||||||
data.pop("token", None)
|
data.pop("token", None)
|
||||||
|
data.pop("desktop_session", None)
|
||||||
if not data.get("account"):
|
if not data.get("account"):
|
||||||
data.pop("scope", None)
|
data.pop("scope", None)
|
||||||
self._write_file(data)
|
self._write_file(data)
|
||||||
@@ -457,14 +477,14 @@ class TokenStore:
|
|||||||
# Explicit allow-list guarantees accidental password-like fields are ignored.
|
# Explicit allow-list guarantees accidental password-like fields are ignored.
|
||||||
return {
|
return {
|
||||||
key: value[key]
|
key: value[key]
|
||||||
for key in ("token", "account", "scope", "credential")
|
for key in ("token", "account", "scope", "credential", "desktop_session")
|
||||||
if key in value
|
if key in value
|
||||||
}
|
}
|
||||||
|
|
||||||
def _write_file(self, data: dict[str, Any]) -> None:
|
def _write_file(self, data: dict[str, Any]) -> None:
|
||||||
safe = {
|
safe = {
|
||||||
key: data[key]
|
key: data[key]
|
||||||
for key in ("token", "account", "scope", "credential")
|
for key in ("token", "account", "scope", "credential", "desktop_session")
|
||||||
if data.get(key)
|
if data.get(key)
|
||||||
}
|
}
|
||||||
if not safe:
|
if not safe:
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
from .login import LoginWindow
|
from .login import LoginWindow
|
||||||
from .shell import ShellWindow
|
from .shell import ShellWindow
|
||||||
|
from .shell_spatial import SpatialShellWindow
|
||||||
from .theme import apply_theme
|
from .theme import apply_theme
|
||||||
|
|
||||||
__all__ = ["LoginWindow", "ShellWindow", "apply_theme"]
|
__all__ = ["LoginWindow", "ShellWindow", "SpatialShellWindow", "apply_theme"]
|
||||||
|
|||||||
@@ -41,10 +41,10 @@ from PySide6.QtWidgets import (
|
|||||||
QWidget,
|
QWidget,
|
||||||
)
|
)
|
||||||
|
|
||||||
from ..core.appointment_modes import APPOINTMENT_MODES
|
from ..core.appointment_modes import APPOINTMENT_MODES
|
||||||
from .design_system import clinical_stylesheet
|
from .design_system import PALETTE, clinical_stylesheet
|
||||||
from .theme import main_window_target_rect
|
from .theme import main_window_target_rect
|
||||||
from .widgets import (
|
from .widgets import (
|
||||||
display_text,
|
display_text,
|
||||||
first_value,
|
first_value,
|
||||||
friendly_error,
|
friendly_error,
|
||||||
@@ -640,7 +640,7 @@ class _Spinner(QWidget):
|
|||||||
del event
|
del event
|
||||||
painter = QPainter(self)
|
painter = QPainter(self)
|
||||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||||
pen = QPen(QColor("#4F63D9"), 3)
|
pen = QPen(QColor(PALETTE["accent"]), 3)
|
||||||
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
|
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
|
||||||
painter.setPen(pen)
|
painter.setPen(pen)
|
||||||
painter.drawArc(self.rect().adjusted(4, 4, -4, -4), self._angle * 16, 255 * 16)
|
painter.drawArc(self.rect().adjusted(4, 4, -4, -4), self._angle * 16, 255 * 16)
|
||||||
|
|||||||
@@ -31,22 +31,27 @@ _QSS = """
|
|||||||
background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_panel;
|
background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_panel;
|
||||||
}
|
}
|
||||||
#AppointmentsPage QPushButton {
|
#AppointmentsPage QPushButton {
|
||||||
min-height: 30px; padding: 0 12px; border: 1px solid transparent;
|
min-height: 32px; padding: 0 13px; border: 1px solid $ds_line_strong;
|
||||||
border-radius: $ds_radius_control; background: $ds_surface_alt;
|
border-radius: $ds_radius_control; background: $ds_surface; color: $ds_text;
|
||||||
|
font-weight: 500;
|
||||||
}
|
}
|
||||||
#AppointmentsPage QPushButton:hover { color: $ds_accent; background: $ds_surface_alt; border-color: $ds_line_strong; }
|
#AppointmentsPage QPushButton:hover { color: $ds_accent; background: $ds_accent_soft; border-color: #9CCFC7; }
|
||||||
#AppointmentsPage QPushButton:pressed { background: $ds_accent_soft; }
|
#AppointmentsPage QPushButton:pressed { background: #D7EFEA; }
|
||||||
#AppointmentsPage QPushButton:focus { border-color: $ds_focus; }
|
#AppointmentsPage QPushButton:focus { border-color: $ds_focus; }
|
||||||
#AppointmentsPage QPushButton[variant="primary"] {
|
#AppointmentsPage QPushButton[variant="primary"] {
|
||||||
background: $ds_accent; color: $ds_surface; border-color: $ds_accent;
|
background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #12857D, stop:1 $ds_accent);
|
||||||
|
color: $ds_surface; border-color: $ds_accent;
|
||||||
|
}
|
||||||
|
#AppointmentsPage QPushButton[variant="primary"]:hover {
|
||||||
|
background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #0E726B, stop:1 $ds_accent_hover);
|
||||||
|
border-color: $ds_accent_hover;
|
||||||
}
|
}
|
||||||
#AppointmentsPage QPushButton[variant="primary"]:hover { background: $ds_accent_hover; }
|
|
||||||
#AppointmentsPage QPushButton[variant="primary"]:pressed { background: $ds_accent_pressed; }
|
#AppointmentsPage QPushButton[variant="primary"]:pressed { background: $ds_accent_pressed; }
|
||||||
#AppointmentsPage QPushButton[variant="primary"]:focus { border-color: $ds_focus; }
|
#AppointmentsPage QPushButton[variant="primary"]:focus { border-color: $ds_focus; }
|
||||||
#AppointmentsPage QPushButton[variant="danger"] {
|
#AppointmentsPage QPushButton[variant="danger"] {
|
||||||
color: $ds_danger; background: $ds_danger_soft; border-color: transparent;
|
color: $ds_danger; background: $ds_danger_soft; border-color: #F5C8CD;
|
||||||
}
|
}
|
||||||
#AppointmentsPage QPushButton[variant="danger"]:hover { background: $ds_danger_soft; }
|
#AppointmentsPage QPushButton[variant="danger"]:hover { background: #FBDCE0; border-color: #E79DA6; }
|
||||||
#AppointmentsPage QPushButton[variant="danger"]:pressed { border-color: $ds_danger; }
|
#AppointmentsPage QPushButton[variant="danger"]:pressed { border-color: $ds_danger; }
|
||||||
#AppointmentsPage QPushButton[variant="ghost"] { background: transparent; border-color: transparent; }
|
#AppointmentsPage QPushButton[variant="ghost"] { background: transparent; border-color: transparent; }
|
||||||
#AppointmentsPage QPushButton[variant="ghost"]:hover { background: $ds_accent_soft; }
|
#AppointmentsPage QPushButton[variant="ghost"]:hover { background: $ds_accent_soft; }
|
||||||
@@ -101,9 +106,20 @@ _QSS = """
|
|||||||
min-height: 36px; max-height: 36px; padding: 0 17px; font-size: 13px;
|
min-height: 36px; max-height: 36px; padding: 0 17px; font-size: 13px;
|
||||||
}
|
}
|
||||||
#AppointmentsPage QFrame#AppointmentToolbar QPushButton[variant="secondary"]:enabled {
|
#AppointmentsPage QFrame#AppointmentToolbar QPushButton[variant="secondary"]:enabled {
|
||||||
color: $ds_text; border-color: transparent;
|
color: $ds_text;
|
||||||
|
background: $ds_surface;
|
||||||
|
border: 1px solid $ds_line_strong;
|
||||||
|
border-radius: $ds_radius_control;
|
||||||
|
}
|
||||||
|
#AppointmentsPage QFrame#AppointmentToolbar QPushButton[variant="secondary"]:enabled:hover {
|
||||||
|
color: $ds_accent;
|
||||||
|
background: $ds_accent_soft;
|
||||||
|
border-color: #8FC8C0;
|
||||||
|
}
|
||||||
|
#AppointmentsPage QFrame#AppointmentToolbar QPushButton[variant="secondary"]:enabled:pressed {
|
||||||
|
background: #D6ECE8;
|
||||||
|
border-color: $ds_accent;
|
||||||
}
|
}
|
||||||
#AppointmentsPage QFrame#AppointmentToolbar QPushButton[variant="secondary"]:hover { color: $ds_accent; background: $ds_accent_soft; }
|
|
||||||
#AppointmentsPage QFrame#AppointmentToolbar QPushButton[variant="secondary"]:focus { border-color: $ds_focus; }
|
#AppointmentsPage QFrame#AppointmentToolbar QPushButton[variant="secondary"]:focus { border-color: $ds_focus; }
|
||||||
#AppointmentsPage QTableWidget#AppointmentTable {
|
#AppointmentsPage QTableWidget#AppointmentTable {
|
||||||
background: $ds_surface; alternate-background-color: $ds_surface; border: 0; border-radius: 0;
|
background: $ds_surface; alternate-background-color: $ds_surface; border: 0; border-radius: 0;
|
||||||
|
|||||||
@@ -42,56 +42,58 @@ _MAX_CARDS = 5
|
|||||||
_POLL_INTERVAL_MS = 5_000
|
_POLL_INTERVAL_MS = 5_000
|
||||||
|
|
||||||
CHAT_NOTIFICATION_QSS = """
|
CHAT_NOTIFICATION_QSS = """
|
||||||
|
/* W8 原语 C:右下角黑曜翡翠临床实时提醒浮卡 + 香槟鎏金切边 */
|
||||||
QFrame#ChatNotifyCard {
|
QFrame#ChatNotifyCard {
|
||||||
background-color: #FFFFFF;
|
background-color: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #103231, stop:1 #071919);
|
||||||
border: 1px solid #BBF0CE;
|
border: 1px solid rgba(223, 199, 147, 136);
|
||||||
border-radius: 12px;
|
border-radius: 13px;
|
||||||
}
|
}
|
||||||
QFrame#ChatNotifyCard[kind="left"] { border-color: #E4E4E5; }
|
QFrame#ChatNotifyCard[kind="left"] { border-color: rgba(164, 196, 192, 90); }
|
||||||
QFrame#ChatNotifyCard[kind="complete"] { border-color: #8B9AD9; }
|
QFrame#ChatNotifyCard[kind="complete"] { border-color: rgba(84, 230, 193, 140); }
|
||||||
QLabel#ChatNotifyBadge {
|
QLabel#ChatNotifyBadge {
|
||||||
min-width: 34px;
|
min-width: 34px;
|
||||||
max-width: 34px;
|
max-width: 34px;
|
||||||
min-height: 34px;
|
min-height: 34px;
|
||||||
max-height: 34px;
|
max-height: 34px;
|
||||||
color: #FFFFFF;
|
color: #FFFFFF;
|
||||||
background-color: #287B65;
|
background-color: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #19B2A8, stop:1 #0B6E68);
|
||||||
border-radius: 9px;
|
border: 1px solid rgba(223, 199, 147, 120);
|
||||||
font-size: 15px;
|
border-radius: 10px;
|
||||||
|
font-size: 14px;
|
||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
}
|
}
|
||||||
QLabel#ChatNotifyBadge[kind="left"] { background-color: #6A6B6D; }
|
QLabel#ChatNotifyBadge[kind="left"] { background-color: #355250; }
|
||||||
QLabel#ChatNotifyBadge[kind="complete"] { background-color: #4F63D9; }
|
QLabel#ChatNotifyBadge[kind="complete"] { background-color: #B8924A; }
|
||||||
QLabel#ChatNotifyTitle { color: #1A1C1F; font-size: 13px; font-weight: 700; }
|
QLabel#ChatNotifyTitle { color: #DFC793; font-size: 13px; font-weight: 700; }
|
||||||
QLabel#ChatNotifyDesc { color: #1A1C1F; font-size: 12px; }
|
QLabel#ChatNotifyDesc { color: #EEF8F7; font-size: 12px; }
|
||||||
QLabel#ChatNotifyTime { color: #6A6B6D; font-size: 11px; }
|
QLabel#ChatNotifyTime { color: #8EB5B1; font-size: 11px; }
|
||||||
QPushButton#ChatNotifyOpen {
|
QPushButton#ChatNotifyOpen {
|
||||||
min-height: 26px;
|
min-height: 28px;
|
||||||
padding: 0 10px;
|
padding: 0 12px;
|
||||||
color: #4F63D9;
|
color: #FFFFFF;
|
||||||
background-color: #EEF1FA;
|
background-color: rgba(24, 176, 165, 86);
|
||||||
border: 1px solid #EDEDEE;
|
border: 1px solid rgba(223, 199, 147, 128);
|
||||||
border-radius: 7px;
|
border-radius: 7px;
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
}
|
}
|
||||||
QPushButton#ChatNotifyOpen:hover {
|
QPushButton#ChatNotifyOpen:hover {
|
||||||
color: #4156C4;
|
color: #FFFFFF;
|
||||||
background-color: #EEF1FA;
|
background-color: #0B6E68;
|
||||||
border-color: #8B9AD9;
|
border-color: #DFC793;
|
||||||
}
|
}
|
||||||
QPushButton#ChatNotifyClose {
|
QPushButton#ChatNotifyClose {
|
||||||
min-width: 22px;
|
min-width: 22px;
|
||||||
max-width: 22px;
|
max-width: 22px;
|
||||||
min-height: 22px;
|
min-height: 22px;
|
||||||
max-height: 22px;
|
max-height: 22px;
|
||||||
color: #6A6B6D;
|
color: #93B8B4;
|
||||||
background-color: transparent;
|
background-color: transparent;
|
||||||
border: 0;
|
border: 0;
|
||||||
border-radius: 6px;
|
border-radius: 6px;
|
||||||
font-size: 14px;
|
font-size: 14px;
|
||||||
}
|
}
|
||||||
QPushButton#ChatNotifyClose:hover { color: #1A1C1F; background-color: #F7F7F7; }
|
QPushButton#ChatNotifyClose:hover { color: #FFFFFF; background-color: rgba(255, 255, 255, 28); }
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,341 @@
|
|||||||
|
"""Ctrl+K 悬浮智诊命令中枢(Command Palette):键盘优先的现代桌面快捷导航与患者检索."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections.abc import Callable
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from PySide6.QtCore import QEvent, QRectF, QSize, Qt
|
||||||
|
from PySide6.QtGui import (
|
||||||
|
QColor,
|
||||||
|
QKeyEvent,
|
||||||
|
QLinearGradient,
|
||||||
|
QPainter,
|
||||||
|
)
|
||||||
|
from PySide6.QtWidgets import (
|
||||||
|
QDialog,
|
||||||
|
QFrame,
|
||||||
|
QHBoxLayout,
|
||||||
|
QLabel,
|
||||||
|
QLineEdit,
|
||||||
|
QListWidget,
|
||||||
|
QListWidgetItem,
|
||||||
|
QPushButton,
|
||||||
|
QVBoxLayout,
|
||||||
|
QWidget,
|
||||||
|
)
|
||||||
|
|
||||||
|
from . import icons, motion
|
||||||
|
from .design_system import clinical_stylesheet
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class CommandEntry:
|
||||||
|
"""命令中枢中的单条可执行指令。"""
|
||||||
|
|
||||||
|
key: str
|
||||||
|
title: str
|
||||||
|
subtitle: str
|
||||||
|
icon_kind: str
|
||||||
|
category: str
|
||||||
|
shortcut: str
|
||||||
|
action: Callable[[], None]
|
||||||
|
|
||||||
|
|
||||||
|
_PALETTE_QSS = clinical_stylesheet(
|
||||||
|
r"""
|
||||||
|
QDialog#CommandPaletteDialog {
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
QFrame#CommandPaletteCard {
|
||||||
|
background-color: $ds_surface;
|
||||||
|
border: 1px solid #B7D3CE;
|
||||||
|
border-radius: 16px;
|
||||||
|
}
|
||||||
|
QFrame#CommandPaletteHeader {
|
||||||
|
background-color: #F7FBFA;
|
||||||
|
border: 0;
|
||||||
|
border-bottom: 1px solid $ds_line;
|
||||||
|
border-top-left-radius: 16px;
|
||||||
|
border-top-right-radius: 16px;
|
||||||
|
}
|
||||||
|
QLineEdit#CommandPaletteInput {
|
||||||
|
background: transparent;
|
||||||
|
border: 0;
|
||||||
|
color: $ds_heading;
|
||||||
|
font-size: 15px;
|
||||||
|
font-weight: 500;
|
||||||
|
padding: 4px 2px;
|
||||||
|
selection-background-color: $ds_accent_soft;
|
||||||
|
selection-color: $ds_heading;
|
||||||
|
}
|
||||||
|
QLabel#CommandPaletteEsc {
|
||||||
|
color: $ds_muted;
|
||||||
|
background-color: $ds_surface;
|
||||||
|
border: 1px solid $ds_line_strong;
|
||||||
|
border-radius: 6px;
|
||||||
|
padding: 2px 7px;
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
QListWidget#CommandPaletteList {
|
||||||
|
background: transparent;
|
||||||
|
border: 0;
|
||||||
|
outline: 0;
|
||||||
|
padding: 6px 8px;
|
||||||
|
}
|
||||||
|
QListWidget#CommandPaletteList::item {
|
||||||
|
border: 1px solid transparent;
|
||||||
|
border-radius: 10px;
|
||||||
|
padding: 8px 10px;
|
||||||
|
margin: 2px 0;
|
||||||
|
color: $ds_heading;
|
||||||
|
}
|
||||||
|
QListWidget#CommandPaletteList::item:hover {
|
||||||
|
background-color: #F2FAF9;
|
||||||
|
border-color: #D5E8E5;
|
||||||
|
}
|
||||||
|
QListWidget#CommandPaletteList::item:selected {
|
||||||
|
background-color: $ds_accent_soft;
|
||||||
|
border-color: #A9D6CF;
|
||||||
|
color: $ds_accent_hover;
|
||||||
|
}
|
||||||
|
QFrame#CommandPaletteFooter {
|
||||||
|
background-color: #F7FBFA;
|
||||||
|
border: 0;
|
||||||
|
border-top: 1px solid $ds_line;
|
||||||
|
border-bottom-left-radius: 16px;
|
||||||
|
border-bottom-right-radius: 16px;
|
||||||
|
}
|
||||||
|
QLabel#CommandPaletteHint {
|
||||||
|
color: $ds_muted;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
QPushButton#CommandPaletteClose {
|
||||||
|
min-width: 28px;
|
||||||
|
max-width: 28px;
|
||||||
|
min-height: 28px;
|
||||||
|
max-height: 28px;
|
||||||
|
padding: 0;
|
||||||
|
border: 1px solid transparent;
|
||||||
|
border-radius: 7px;
|
||||||
|
background: transparent;
|
||||||
|
color: $ds_muted;
|
||||||
|
}
|
||||||
|
QPushButton#CommandPaletteClose:hover {
|
||||||
|
background-color: $ds_danger_soft;
|
||||||
|
color: $ds_danger;
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class _PaletteCard(QFrame):
|
||||||
|
"""带微妙顶缘香槟鎏金高光的悬浮命令卡片。"""
|
||||||
|
|
||||||
|
def paintEvent(self, event: Any) -> None: # noqa: N802
|
||||||
|
super().paintEvent(event)
|
||||||
|
painter = QPainter(self)
|
||||||
|
painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
|
||||||
|
bar = QRectF(18.0, 1.0, max(0.0, self.width() - 36.0), 2.0)
|
||||||
|
grad = QLinearGradient(bar.topLeft(), bar.topRight())
|
||||||
|
grad.setColorAt(0.0, QColor(11, 110, 104, 0))
|
||||||
|
grad.setColorAt(0.28, QColor(24, 168, 158, 180))
|
||||||
|
grad.setColorAt(0.50, QColor(223, 199, 147, 210))
|
||||||
|
grad.setColorAt(0.72, QColor(24, 168, 158, 180))
|
||||||
|
grad.setColorAt(1.0, QColor(11, 110, 104, 0))
|
||||||
|
painter.setPen(Qt.PenStyle.NoPen)
|
||||||
|
painter.setBrush(grad)
|
||||||
|
painter.drawRoundedRect(bar, 1.0, 1.0)
|
||||||
|
painter.end()
|
||||||
|
|
||||||
|
|
||||||
|
class CommandPaletteDialog(QDialog):
|
||||||
|
"""桌面端全局 Ctrl+K 悬浮命令与患者检索面板。"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
entries: list[CommandEntry],
|
||||||
|
*,
|
||||||
|
on_search_patient: Callable[[str], None] | None = None,
|
||||||
|
initial_query: str = "",
|
||||||
|
parent: QWidget | None = None,
|
||||||
|
) -> None:
|
||||||
|
super().__init__(parent)
|
||||||
|
self.setObjectName("CommandPaletteDialog")
|
||||||
|
self.setProperty("doctorSkipOpenGeometry", True)
|
||||||
|
self.setWindowFlags(
|
||||||
|
Qt.WindowType.FramelessWindowHint
|
||||||
|
| Qt.WindowType.Dialog
|
||||||
|
| Qt.WindowType.NoDropShadowWindowHint
|
||||||
|
)
|
||||||
|
self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, True)
|
||||||
|
self.setModal(True)
|
||||||
|
self.setStyleSheet(_PALETTE_QSS)
|
||||||
|
|
||||||
|
self._entries = list(entries)
|
||||||
|
self._on_search_patient = on_search_patient
|
||||||
|
self._visible_actions: list[Callable[[], None]] = []
|
||||||
|
|
||||||
|
root = QVBoxLayout(self)
|
||||||
|
root.setContentsMargins(12, 12, 12, 12)
|
||||||
|
|
||||||
|
self.card = _PaletteCard(self)
|
||||||
|
self.card.setObjectName("CommandPaletteCard")
|
||||||
|
self.card.setFixedWidth(568)
|
||||||
|
card_layout = QVBoxLayout(self.card)
|
||||||
|
card_layout.setContentsMargins(0, 0, 0, 0)
|
||||||
|
card_layout.setSpacing(0)
|
||||||
|
|
||||||
|
# 顶部搜索栏
|
||||||
|
header = QFrame(self.card)
|
||||||
|
header.setObjectName("CommandPaletteHeader")
|
||||||
|
header.setFixedHeight(56)
|
||||||
|
header_layout = QHBoxLayout(header)
|
||||||
|
header_layout.setContentsMargins(16, 0, 14, 0)
|
||||||
|
header_layout.setSpacing(10)
|
||||||
|
|
||||||
|
search_icon = QLabel(header)
|
||||||
|
search_icon.setPixmap(icons.pixmap("search", "accent", 18))
|
||||||
|
header_layout.addWidget(search_icon)
|
||||||
|
|
||||||
|
self.input = QLineEdit(header)
|
||||||
|
self.input.setObjectName("CommandPaletteInput")
|
||||||
|
self.input.setPlaceholderText("输入页面名称、快捷指令,或患者姓名/手机号回车搜索...")
|
||||||
|
self.input.setText(initial_query)
|
||||||
|
self.input.textChanged.connect(self._rebuild_list)
|
||||||
|
self.input.installEventFilter(self)
|
||||||
|
header_layout.addWidget(self.input, 1)
|
||||||
|
|
||||||
|
esc_hint = QLabel("ESC", header)
|
||||||
|
esc_hint.setObjectName("CommandPaletteEsc")
|
||||||
|
esc_hint.setFixedHeight(24)
|
||||||
|
header_layout.addWidget(esc_hint, 0, Qt.AlignmentFlag.AlignVCenter)
|
||||||
|
|
||||||
|
close_btn = QPushButton(header)
|
||||||
|
close_btn.setObjectName("CommandPaletteClose")
|
||||||
|
close_btn.setIcon(icons.icon("close", "muted", 14))
|
||||||
|
close_btn.setIconSize(QSize(14, 14))
|
||||||
|
close_btn.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||||
|
close_btn.clicked.connect(self.reject)
|
||||||
|
header_layout.addWidget(close_btn)
|
||||||
|
card_layout.addWidget(header)
|
||||||
|
|
||||||
|
# 指令列表
|
||||||
|
self.list_widget = QListWidget(self.card)
|
||||||
|
self.list_widget.setObjectName("CommandPaletteList")
|
||||||
|
self.list_widget.setFixedHeight(296)
|
||||||
|
self.list_widget.setIconSize(QSize(18, 18))
|
||||||
|
self.list_widget.setSpacing(2)
|
||||||
|
self.list_widget.itemActivated.connect(self._activate_item)
|
||||||
|
self.list_widget.itemClicked.connect(self._activate_item)
|
||||||
|
card_layout.addWidget(self.list_widget)
|
||||||
|
|
||||||
|
# 底部键盘引导条
|
||||||
|
footer = QFrame(self.card)
|
||||||
|
footer.setObjectName("CommandPaletteFooter")
|
||||||
|
footer.setFixedHeight(36)
|
||||||
|
footer_layout = QHBoxLayout(footer)
|
||||||
|
footer_layout.setContentsMargins(16, 0, 16, 0)
|
||||||
|
hint = QLabel("↑↓ 选择 · Enter 执行 · Esc 关闭", footer)
|
||||||
|
hint.setObjectName("CommandPaletteHint")
|
||||||
|
footer_layout.addWidget(hint)
|
||||||
|
footer_layout.addStretch(1)
|
||||||
|
brand = QLabel("甄养堂 · 智诊指令中枢", footer)
|
||||||
|
brand.setObjectName("CommandPaletteHint")
|
||||||
|
footer_layout.addWidget(brand)
|
||||||
|
card_layout.addWidget(footer)
|
||||||
|
|
||||||
|
root.addWidget(self.card)
|
||||||
|
self.adjustSize()
|
||||||
|
self._rebuild_list(initial_query)
|
||||||
|
|
||||||
|
def showEvent(self, event: Any) -> None: # noqa: N802
|
||||||
|
super().showEvent(event)
|
||||||
|
parent = self.parentWidget()
|
||||||
|
if parent is not None:
|
||||||
|
host = parent.window().frameGeometry()
|
||||||
|
x = host.center().x() - self.width() // 2
|
||||||
|
y = host.top() + max(72, round(host.height() * 0.14))
|
||||||
|
self.move(x, y)
|
||||||
|
self.input.setFocus(Qt.FocusReason.PopupFocusReason)
|
||||||
|
self.input.selectAll()
|
||||||
|
motion.fade_in(self.card, duration=motion.FAST)
|
||||||
|
|
||||||
|
def paintEvent(self, event: Any) -> None: # noqa: N802
|
||||||
|
del event
|
||||||
|
# 柔和冷青科技外光环,在透明无边框弹窗周围营造立体层次
|
||||||
|
painter = QPainter(self)
|
||||||
|
painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
|
||||||
|
card_rect = QRectF(self.card.geometry())
|
||||||
|
for expand, alpha in ((8.0, 14), (5.0, 22), (2.0, 32)):
|
||||||
|
painter.setPen(Qt.PenStyle.NoPen)
|
||||||
|
painter.setBrush(QColor(11, 46, 44, alpha))
|
||||||
|
painter.drawRoundedRect(
|
||||||
|
card_rect.adjusted(-expand, -expand + 2.0, expand, expand + 4.0),
|
||||||
|
16.0 + expand * 0.4,
|
||||||
|
16.0 + expand * 0.4,
|
||||||
|
)
|
||||||
|
painter.end()
|
||||||
|
|
||||||
|
def _rebuild_list(self, raw_query: str) -> None:
|
||||||
|
query = raw_query.strip()
|
||||||
|
lowered = query.lower()
|
||||||
|
self.list_widget.clear()
|
||||||
|
self._visible_actions.clear()
|
||||||
|
|
||||||
|
if query and self._on_search_patient is not None:
|
||||||
|
item = QListWidgetItem(
|
||||||
|
icons.icon("search", "accent", 18),
|
||||||
|
f"检索患者「{query}」 — 直达患者与问诊列表",
|
||||||
|
)
|
||||||
|
self.list_widget.addItem(item)
|
||||||
|
self._visible_actions.append(
|
||||||
|
lambda q=query, cb=self._on_search_patient: cb(q)
|
||||||
|
)
|
||||||
|
|
||||||
|
for entry in self._entries:
|
||||||
|
haystack = f"{entry.title} {entry.subtitle} {entry.category}".lower()
|
||||||
|
if lowered and lowered not in haystack:
|
||||||
|
continue
|
||||||
|
label = f"{entry.title} · {entry.subtitle}"
|
||||||
|
if entry.shortcut:
|
||||||
|
label = f"{label} [{entry.shortcut}]"
|
||||||
|
item = QListWidgetItem(icons.icon(entry.icon_kind, "accent", 18), label)
|
||||||
|
self.list_widget.addItem(item)
|
||||||
|
self._visible_actions.append(entry.action)
|
||||||
|
|
||||||
|
if self.list_widget.count() > 0:
|
||||||
|
self.list_widget.setCurrentRow(0)
|
||||||
|
|
||||||
|
def _activate_item(self, item: QListWidgetItem | None) -> None:
|
||||||
|
if item is None:
|
||||||
|
return
|
||||||
|
row = self.list_widget.row(item)
|
||||||
|
if 0 <= row < len(self._visible_actions):
|
||||||
|
action = self._visible_actions[row]
|
||||||
|
self.accept()
|
||||||
|
action()
|
||||||
|
|
||||||
|
def eventFilter(self, watched: Any, event: QEvent) -> bool: # noqa: N802
|
||||||
|
if watched is self.input and event.type() == QEvent.Type.KeyPress:
|
||||||
|
assert isinstance(event, QKeyEvent)
|
||||||
|
key = event.key()
|
||||||
|
if key in (Qt.Key.Key_Down, Qt.Key.Key_Up):
|
||||||
|
count = self.list_widget.count()
|
||||||
|
if count > 0:
|
||||||
|
step = 1 if key == Qt.Key.Key_Down else -1
|
||||||
|
current = self.list_widget.currentRow()
|
||||||
|
self.list_widget.setCurrentRow((current + step) % count)
|
||||||
|
return True
|
||||||
|
if key in (Qt.Key.Key_Return, Qt.Key.Key_Enter):
|
||||||
|
self._activate_item(self.list_widget.currentItem())
|
||||||
|
return True
|
||||||
|
if key == Qt.Key.Key_Escape:
|
||||||
|
self.reject()
|
||||||
|
return True
|
||||||
|
return super().eventFilter(watched, event)
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = ["CommandEntry", "CommandPaletteDialog"]
|
||||||
@@ -36,19 +36,26 @@ _QSS = """
|
|||||||
background: transparent; border: 0; border-top: 1px solid $ds_line; border-radius: 0;
|
background: transparent; border: 0; border-top: 1px solid $ds_line; border-radius: 0;
|
||||||
}
|
}
|
||||||
#DiagnosisIndex QPushButton {
|
#DiagnosisIndex QPushButton {
|
||||||
min-height: 34px; padding: 0 13px; border: 1px solid transparent;
|
min-height: 34px; padding: 0 13px; border: 1px solid $ds_line_strong;
|
||||||
border-radius: $ds_radius_control; background: $ds_surface_alt;
|
border-radius: $ds_radius_control; background: $ds_surface; color: $ds_text; font-weight: 500;
|
||||||
}
|
}
|
||||||
#DiagnosisIndex QPushButton:hover { color: $ds_accent; background: $ds_surface_alt; border-color: $ds_line_strong; }
|
#DiagnosisIndex QPushButton:hover { color: $ds_accent; background: $ds_accent_soft; border-color: #9CCFC7; }
|
||||||
#DiagnosisIndex QPushButton:pressed { background: $ds_accent_soft; }
|
#DiagnosisIndex QPushButton:pressed { background: #D7EFEA; }
|
||||||
#DiagnosisIndex QPushButton:focus { border-color: $ds_focus; }
|
#DiagnosisIndex QPushButton:focus { border-color: $ds_focus; }
|
||||||
#DiagnosisIndex QPushButton[variant="primary"] { color: $ds_surface; background: $ds_accent; border-color: $ds_accent; }
|
#DiagnosisIndex QPushButton[variant="primary"] {
|
||||||
#DiagnosisIndex QPushButton[variant="primary"]:hover { background: $ds_accent_hover; }
|
color: $ds_surface;
|
||||||
|
background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #12857D, stop:1 $ds_accent);
|
||||||
|
border-color: $ds_accent;
|
||||||
|
}
|
||||||
|
#DiagnosisIndex QPushButton[variant="primary"]:hover {
|
||||||
|
background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #0E726B, stop:1 $ds_accent_hover);
|
||||||
|
border-color: $ds_accent_hover;
|
||||||
|
}
|
||||||
#DiagnosisIndex QPushButton[variant="primary"]:pressed { background: $ds_accent_pressed; }
|
#DiagnosisIndex QPushButton[variant="primary"]:pressed { background: $ds_accent_pressed; }
|
||||||
#DiagnosisIndex QPushButton[variant="primary"]:focus { border-color: $ds_focus; }
|
#DiagnosisIndex QPushButton[variant="primary"]:focus { border-color: $ds_focus; }
|
||||||
#DiagnosisIndex QPushButton[consultationTool="true"] { color: $ds_text; border-color: transparent; }
|
#DiagnosisIndex QPushButton[consultationTool="true"] { color: $ds_text; border-color: $ds_line_strong; background: $ds_surface; }
|
||||||
#DiagnosisIndex QPushButton[consultationTool="true"]:hover { color: $ds_accent; background: $ds_accent_soft; }
|
#DiagnosisIndex QPushButton[consultationTool="true"]:hover { color: $ds_accent; background: $ds_accent_soft; border-color: #9CCFC7; }
|
||||||
#DiagnosisIndex QPushButton[consultationDanger="true"] { color: $ds_danger; background: $ds_danger_soft; border-color: transparent; }
|
#DiagnosisIndex QPushButton[consultationDanger="true"] { color: $ds_danger; background: $ds_danger_soft; border-color: #F5C8CD; }
|
||||||
#DiagnosisIndex QPushButton[consultationDanger="true"]:hover { border-color: $ds_danger; }
|
#DiagnosisIndex QPushButton[consultationDanger="true"]:hover { border-color: $ds_danger; }
|
||||||
#DiagnosisIndex QPushButton[consultationTool="true"]:focus,
|
#DiagnosisIndex QPushButton[consultationTool="true"]:focus,
|
||||||
#DiagnosisIndex QPushButton[consultationDanger="true"]:focus { border-color: $ds_focus; }
|
#DiagnosisIndex QPushButton[consultationDanger="true"]:focus { border-color: $ds_focus; }
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
"""Clinical desktop design tokens, shared by native pages and dialog chrome.
|
"""Clinical desktop design tokens — 御瓷智医 (Luxury Precision MedTech).
|
||||||
|
|
||||||
Keep data-series colours and video pixels outside this palette. Existing scoped
|
Fuses medical trust, precision technology, quiet luxury (champagne gold micro-accents)
|
||||||
QSS can adopt the system without changing selectors, layout or permissions.
|
and contemporary editorial clarity. Shared by native pages, shell chrome, drawers and
|
||||||
New rules should use the named ``$ds_*`` tokens rather than legacy colours.
|
dialogs. New rules should use the named ``$ds_*`` tokens rather than legacy colours.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -11,60 +11,80 @@ import re
|
|||||||
from string import Template
|
from string import Template
|
||||||
|
|
||||||
PALETTE = {
|
PALETTE = {
|
||||||
"canvas": "#F5F7FA",
|
# 三阶珍珠青瓷中性面:低眩光护眼,同时具备精密医疗仪器与高定材质层次
|
||||||
|
"canvas": "#EFF4F3",
|
||||||
"surface": "#FFFFFF",
|
"surface": "#FFFFFF",
|
||||||
"surface_alt": "#F7F9FC",
|
"surface_alt": "#F6FAFA",
|
||||||
"sidebar": "#F0F3F8",
|
"sidebar": "#E6EEED",
|
||||||
"line": "#E6EAF0",
|
"line": "#DCE6E4",
|
||||||
"line_strong": "#D4DCE8",
|
"line_strong": "#C3D3D0",
|
||||||
"heading": "#223047",
|
# 曜青深墨文字阶梯:锐利、高级、高对比度
|
||||||
"text": "#344258",
|
"heading": "#0F2120",
|
||||||
"muted": "#647287",
|
"text": "#263938",
|
||||||
"disabled": "#8B96A6",
|
"muted": "#5C7270",
|
||||||
"disabled_surface": "#F0F2F5",
|
"disabled": "#95A8A6",
|
||||||
"accent": "#4267B2",
|
"disabled_surface": "#EDF2F1",
|
||||||
"accent_hover": "#355995",
|
# 唯一品牌主色:甄养堂精密医疗翡翠青 (Jade Teal)
|
||||||
"accent_pressed": "#2C4C82",
|
"accent": "#0B6E68",
|
||||||
"accent_soft": "#EAF0FB",
|
"accent_hover": "#085954",
|
||||||
"focus": "#6D8CCB",
|
"accent_pressed": "#064743",
|
||||||
"success": "#287B65",
|
"accent_soft": "#E6F4F2",
|
||||||
"success_soft": "#EDF7F2",
|
"focus": "#18A89E",
|
||||||
"warning": "#96601D",
|
# 贵气时尚微点缀:香槟鎏金 (Champagne Gold — 克制用于徽标切边、AI 科技星芒、尊享标识)
|
||||||
"warning_soft": "#FBF4E8",
|
"gold": "#B8924A",
|
||||||
"danger": "#B54A59",
|
"gold_light": "#DFC793",
|
||||||
"danger_soft": "#FCF0F2",
|
"gold_soft": "#FAF5EA",
|
||||||
|
# 深曜青科技底(用于 AI 科技卡与登录页品牌沉浸区)
|
||||||
|
"obsidian": "#0D2424",
|
||||||
|
"obsidian_alt": "#143534",
|
||||||
|
# 语义临床色
|
||||||
|
"success": "#0E8A63",
|
||||||
|
"success_soft": "#E6F7F1",
|
||||||
|
"warning": "#B56B00",
|
||||||
|
"warning_soft": "#FEF5E6",
|
||||||
|
"danger": "#C83B4B",
|
||||||
|
"danger_soft": "#FDEEEF",
|
||||||
}
|
}
|
||||||
|
|
||||||
RADII = {"small": 6, "control": 10, "panel": 16, "window": 20}
|
RADII = {"small": 6, "control": 8, "panel": 12, "window": 16}
|
||||||
SPACING = {"small": 8, "control": 12, "group": 16, "section": 24}
|
SPACING = {"small": 8, "control": 12, "group": 16, "section": 24}
|
||||||
|
|
||||||
TOKENS = {f"ds_{name}": value for name, value in PALETTE.items()}
|
TOKENS = {f"ds_{name}": value for name, value in PALETTE.items()}
|
||||||
TOKENS.update({f"ds_radius_{name}": f"{value}px" for name, value in RADII.items()})
|
TOKENS.update({f"ds_radius_{name}": f"{value}px" for name, value in RADII.items()})
|
||||||
TOKENS.update({f"ds_space_{name}": f"{value}px" for name, value in SPACING.items()})
|
TOKENS.update({f"ds_space_{name}": f"{value}px" for name, value in SPACING.items()})
|
||||||
|
|
||||||
# Explicit migration of the two existing native palettes. This adapter only
|
# 将全量旧版灰蓝/紫蓝/冷灰硬编码色值统一映射至「御瓷智医」设计令牌,确保所有历史弹窗与页面零色差
|
||||||
# touches six-digit colour literals; selectors and metrics stay page-owned.
|
|
||||||
_LEGACY_ROLES = {
|
_LEGACY_ROLES = {
|
||||||
"accent": ("1769E8", "4F63D9", "5761F4", "5267DF"),
|
"accent": ("4267B2", "1769E8", "4F63D9", "5761F4", "5267DF", "1555B6"),
|
||||||
"accent_hover": ("155BCC", "1555B6", "4156C4", "4356C4", "4055CA"),
|
"accent_hover": ("355995", "155BCC", "4156C4", "4356C4", "4055CA"),
|
||||||
"accent_pressed": ("124EA9", "354BB4"),
|
"accent_pressed": ("2C4C82", "124EA9", "354BB4"),
|
||||||
"accent_soft": ("EAF2FF", "EEF1FA", "EEF0FF", "F0F2FF", "DCEAFF", "EDF0FC"),
|
"accent_soft": (
|
||||||
"focus": ("75A5F0", "8B9AD9"),
|
"EAF0FB", "EAF2FF", "EEF1FA", "EEF0FF", "F0F2FF", "DCEAFF", "EDF0FC",
|
||||||
"canvas": ("F3F7FD", "F4F6FA", "F6F6F6"),
|
"F0F5FD", "D6E5FB", "E3E8F8",
|
||||||
"surface_alt": ("F7F7F7", "F7FAFE", "F5F8FD", "F7F9FE", "F2F7FF"),
|
),
|
||||||
"sidebar": ("EDF4FF",),
|
"focus": ("6D8CCB", "75A5F0", "8B9AD9"),
|
||||||
"line": ("DBE5F2", "EDEDEE", "E5ECF6", "E6EDF6", "E7EDF7", "EDF0F5", "E7EBF2", "E6EAF5"),
|
"canvas": ("F5F7FA", "F3F7FD", "F4F6FA", "F6F6F6"),
|
||||||
"line_strong": ("E4E4E5", "C8D5E6", "C9DCF7", "ADC8F0", "B6CDEE"),
|
"surface_alt": ("F7F9FC", "F7F7F7", "F7FAFE", "F5F8FD", "F7F9FE", "F2F7FF"),
|
||||||
"heading": ("1A1C1F", "202C3F", "111F46"),
|
"sidebar": ("F0F3F8", "EDF4FF"),
|
||||||
"text": ("273244", "263551", "24334A", "233149", "3F4E75"),
|
"line": (
|
||||||
"muted": ("606163", "6A6B6D", "5D6B80", "7886AA", "708097"),
|
"E6EAF0", "DBE5F2", "EDEDEE", "E5ECF6", "E6EDF6", "E7EDF7", "EDF0F5",
|
||||||
"disabled": ("8E8F90", "8A97A9", "9AA6B7"),
|
"E7EBF2", "E6EAF5", "EDF1F7", "DEE4F6",
|
||||||
"disabled_surface": ("F2F2F2", "F0F0F0"),
|
),
|
||||||
"success_soft": ("EEF7F3", "EAF9F3"),
|
"line_strong": (
|
||||||
"warning": ("A9691D", "9C681F"),
|
"D4DCE8", "E4E4E5", "C8D5E6", "C9DCF7", "ADC8F0", "B6CDEE", "C4D2E5",
|
||||||
"warning_soft": ("FCF5E9", "FFF5E6", "FFF6E7"),
|
"CEDBEB", "A7B1C9", "8894B2",
|
||||||
"danger": ("BE4B58", "B84652"),
|
),
|
||||||
"danger_soft": ("FFF0F2", "FFF1F3"),
|
"heading": ("223047", "1A1C1F", "202C3F", "111F46", "20354E"),
|
||||||
|
"text": ("344258", "273244", "263551", "24334A", "233149", "3F4E75"),
|
||||||
|
"muted": ("647287", "606163", "6A6B6D", "5D6B80", "7886AA", "708097", "697386"),
|
||||||
|
"disabled": ("8B96A6", "8E8F90", "8A97A9", "9AA6B7"),
|
||||||
|
"disabled_surface": ("F0F2F5", "F2F2F2", "F0F0F0"),
|
||||||
|
"success": ("287B65",),
|
||||||
|
"success_soft": ("EDF7F2", "EEF7F3", "EAF9F3", "E8F6F1", "F0FDF4", "ECFDF5"),
|
||||||
|
"warning": ("96601D", "A9691D", "9C681F", "B96C00"),
|
||||||
|
"warning_soft": ("FBF4E8", "FCF5E9", "FFF5E6", "FFF6E7", "FFF9EF", "FFF7E9", "FFFBEB"),
|
||||||
|
"danger": ("B54A59", "BE4B58", "B84652", "C43E55"),
|
||||||
|
"danger_soft": ("FCF0F2", "FFF0F2", "FFF1F3", "FFF4F5", "FFF7F8", "FEF2F2"),
|
||||||
}
|
}
|
||||||
_LEGACY = {colour.lower(): PALETTE[role] for role, colours in _LEGACY_ROLES.items() for colour in colours}
|
_LEGACY = {colour.lower(): PALETTE[role] for role, colours in _LEGACY_ROLES.items() for colour in colours}
|
||||||
_HEX = re.compile(r"#([0-9a-fA-F]{6})(?![0-9a-fA-F])")
|
_HEX = re.compile(r"#([0-9a-fA-F]{6})(?![0-9a-fA-F])")
|
||||||
|
|||||||
@@ -414,6 +414,21 @@ QTimeEdit[diagnosisField="true"] {
|
|||||||
QDoubleSpinBox[diagnosisField="true"] {
|
QDoubleSpinBox[diagnosisField="true"] {
|
||||||
padding-right: 4px;
|
padding-right: 4px;
|
||||||
}
|
}
|
||||||
|
QComboBox[diagnosisField="true"]::drop-down,
|
||||||
|
QDateEdit[diagnosisField="true"]::drop-down,
|
||||||
|
QTimeEdit[diagnosisField="true"]::drop-down {
|
||||||
|
width: 26px;
|
||||||
|
border: 0;
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
QDoubleSpinBox[diagnosisField="true"]::up-button,
|
||||||
|
QDoubleSpinBox[diagnosisField="true"]::down-button,
|
||||||
|
QSpinBox[diagnosisField="true"]::up-button,
|
||||||
|
QSpinBox[diagnosisField="true"]::down-button {
|
||||||
|
width: 18px;
|
||||||
|
border: 0;
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
QPlainTextEdit[diagnosisField="true"] {
|
QPlainTextEdit[diagnosisField="true"] {
|
||||||
padding: 8px 12px;
|
padding: 8px 12px;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -84,7 +84,7 @@ _INVALID_INDEX = QModelIndex()
|
|||||||
# time occupy separate lines; actions keep two inline links plus 更多, with
|
# time occupy separate lines; actions keep two inline links plus 更多, with
|
||||||
# the remaining actions in its menu so clinical columns retain more space.
|
# the remaining actions in its menu so clinical columns retain more space.
|
||||||
_TABLE_COLUMN_WIDTHS = (48, 70, 60, 100, 175, 88, 120, 100, 72, 110, 96, 160)
|
_TABLE_COLUMN_WIDTHS = (48, 70, 60, 100, 175, 88, 120, 100, 72, 110, 96, 160)
|
||||||
_BLUE_COLUMN_WIDTHS = (48, 70, 82, 102, 244, 90, 84, 90, 88, 122, 92, 158)
|
_BLUE_COLUMN_WIDTHS = (46, 62, 70, 88, 244, 70, 84, 76, 70, 92, 86, 152)
|
||||||
_BLUE_WARNING = QColor(PALETTE["warning"])
|
_BLUE_WARNING = QColor(PALETTE["warning"])
|
||||||
_BLUE_DANGER = QColor(PALETTE["danger"])
|
_BLUE_DANGER = QColor(PALETTE["danger"])
|
||||||
|
|
||||||
@@ -444,6 +444,8 @@ def prescription_action(record: Any, *, force_open: bool = False) -> tuple[str,
|
|||||||
if explicit_legacy is not None
|
if explicit_legacy is not None
|
||||||
else audit in {0, 1, 2}
|
else audit in {0, 1, 2}
|
||||||
)
|
)
|
||||||
|
if has_current and voided == 1:
|
||||||
|
return "重新开方", "reissue"
|
||||||
if not has_current:
|
if not has_current:
|
||||||
return "开方", "open"
|
return "开方", "open"
|
||||||
if audit == 1 and voided != 1:
|
if audit == 1 and voided != 1:
|
||||||
@@ -451,6 +453,13 @@ def prescription_action(record: Any, *, force_open: bool = False) -> tuple[str,
|
|||||||
return "编辑处方", "edit"
|
return "编辑处方", "edit"
|
||||||
|
|
||||||
|
|
||||||
|
def can_void_prescription(record: Any) -> bool:
|
||||||
|
_, mode = prescription_action(record)
|
||||||
|
return mode in {"edit", "view"} and not _as_bool(
|
||||||
|
first_value(record, "has_prescription_order", default=False)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def _prescription_action_label(record: Any, *, force_open: bool = False) -> str:
|
def _prescription_action_label(record: Any, *, force_open: bool = False) -> str:
|
||||||
return prescription_action(record, force_open=force_open)[0]
|
return prescription_action(record, force_open=force_open)[0]
|
||||||
|
|
||||||
@@ -2100,6 +2109,11 @@ class DiagnosisTableHost(QFrame):
|
|||||||
command, item
|
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):
|
if demoted_actions and self.action_policy.get("assign", False):
|
||||||
menu.addSeparator()
|
menu.addSeparator()
|
||||||
if self.action_policy.get("assign", False):
|
if self.action_policy.get("assign", False):
|
||||||
|
|||||||
@@ -94,6 +94,7 @@ from ..widgets import (
|
|||||||
run_async,
|
run_async,
|
||||||
show_toast,
|
show_toast,
|
||||||
)
|
)
|
||||||
|
from ..window_primitives import ClinicalAccentBar
|
||||||
from .ai_consult_charts import GlucoseChartData
|
from .ai_consult_charts import GlucoseChartData
|
||||||
from .ai_consult_drug_names import TCM as DRUG_TCM
|
from .ai_consult_drug_names import TCM as DRUG_TCM
|
||||||
from .ai_consult_drug_names import WESTERN as DRUG_WESTERN
|
from .ai_consult_drug_names import WESTERN as DRUG_WESTERN
|
||||||
@@ -116,6 +117,7 @@ from .prescription_ai import (
|
|||||||
can_use_diagnosis_ai_assistant,
|
can_use_diagnosis_ai_assistant,
|
||||||
diagnosis_ai_task,
|
diagnosis_ai_task,
|
||||||
)
|
)
|
||||||
|
from .prescription_esign import resume_saved_prescription, saved_prescription_message
|
||||||
|
|
||||||
AI_CONSULT_QSS = clinical_stylesheet("""
|
AI_CONSULT_QSS = clinical_stylesheet("""
|
||||||
QDialog#AiConsultDialog {
|
QDialog#AiConsultDialog {
|
||||||
@@ -1222,7 +1224,7 @@ def _unwrap_analysis(payload: Any) -> dict[str, Any]:
|
|||||||
current: Mapping[str, Any] = payload
|
current: Mapping[str, Any] = payload
|
||||||
latest = current.get("latest_by_model")
|
latest = current.get("latest_by_model")
|
||||||
if isinstance(latest, Mapping):
|
if isinstance(latest, Mapping):
|
||||||
for key in ("qwen", "openai"):
|
for key in ("qwen", "openai", "doubao"):
|
||||||
row = latest.get(key)
|
row = latest.get(key)
|
||||||
if isinstance(row, Mapping):
|
if isinstance(row, Mapping):
|
||||||
current = row
|
current = row
|
||||||
@@ -4780,7 +4782,9 @@ class AiConsultDialog(QDialog):
|
|||||||
_style_surface(shell)
|
_style_surface(shell)
|
||||||
root = QVBoxLayout(self)
|
root = QVBoxLayout(self)
|
||||||
root.setContentsMargins(0, 0, 0, 0)
|
root.setContentsMargins(0, 0, 0, 0)
|
||||||
root.addWidget(shell)
|
root.setSpacing(0)
|
||||||
|
root.addWidget(ClinicalAccentBar(self))
|
||||||
|
root.addWidget(shell, 1)
|
||||||
layout = QVBoxLayout(shell)
|
layout = QVBoxLayout(shell)
|
||||||
layout.setContentsMargins(18, 14, 18, 14)
|
layout.setContentsMargins(18, 14, 18, 14)
|
||||||
layout.setSpacing(12)
|
layout.setSpacing(12)
|
||||||
@@ -7085,7 +7089,7 @@ class AiConsultDialog(QDialog):
|
|||||||
):
|
):
|
||||||
status.set_payload("AI处方草稿缺少诊断或药材,已停止开方。")
|
status.set_payload("AI处方草稿缺少诊断或药材,已停止开方。")
|
||||||
return
|
return
|
||||||
status.set_payload("AI 已生成处方草稿,请逐味复核、修改并完成医师签名。")
|
status.set_payload("AI 已生成处方草稿,请逐味复核并保存。")
|
||||||
self._open_prescription_editor_from_chat(
|
self._open_prescription_editor_from_chat(
|
||||||
generation,
|
generation,
|
||||||
diagnosis_id,
|
diagnosis_id,
|
||||||
@@ -7177,45 +7181,46 @@ class AiConsultDialog(QDialog):
|
|||||||
}
|
}
|
||||||
seed.update({key: deepcopy(value) for key, value in draft.items() if key in allowed})
|
seed.update({key: deepcopy(value) for key, value in draft.items() if key in allowed})
|
||||||
seed["ai_assisted"] = True
|
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(
|
dialog = PrescriptionEditorDialog(
|
||||||
self.repository,
|
self.repository,
|
||||||
seed,
|
seed,
|
||||||
mode="add",
|
mode="add",
|
||||||
current_user=self._current_user(),
|
current_user=self._current_user(),
|
||||||
permissions=self.permissions,
|
permissions=self.permissions,
|
||||||
|
save_draft=save_prescription,
|
||||||
parent=self,
|
parent=self,
|
||||||
)
|
)
|
||||||
if dialog.exec() != QDialog.DialogCode.Accepted:
|
if dialog.exec() != QDialog.DialogCode.Accepted:
|
||||||
status.set_payload("已取消开方,未保存或提交任何处方。")
|
status.set_payload("已取消开方,未保存或提交任何处方。")
|
||||||
return
|
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 = 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(
|
run_async(
|
||||||
lambda: invoke(
|
lambda: save_prescription(payload),
|
||||||
self.repository,
|
on_success=lambda result: self._prescription_action_created(generation, diagnosis_id, status, result),
|
||||||
"create_prescription",
|
|
||||||
prescription=frozen_payload,
|
|
||||||
),
|
|
||||||
on_success=lambda _result: self._prescription_action_created(
|
|
||||||
generation,
|
|
||||||
diagnosis_id,
|
|
||||||
status,
|
|
||||||
),
|
|
||||||
on_error=lambda error: self._prescription_action_error(
|
on_error=lambda error: self._prescription_action_error(
|
||||||
generation,
|
generation,
|
||||||
status,
|
status,
|
||||||
error,
|
error,
|
||||||
prefix="处方提交失败",
|
prefix="处方保存失败",
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -7224,11 +7229,14 @@ class AiConsultDialog(QDialog):
|
|||||||
generation: int,
|
generation: int,
|
||||||
diagnosis_id: int,
|
diagnosis_id: int,
|
||||||
status: _ChatBubble,
|
status: _ChatBubble,
|
||||||
|
prescription: Any,
|
||||||
) -> None:
|
) -> None:
|
||||||
if generation != self._generation or diagnosis_id != self.diagnosis_id:
|
if generation != self._generation or diagnosis_id != self.diagnosis_id:
|
||||||
return
|
return
|
||||||
status.set_payload("处方已开具并提交审核。")
|
message, _ = saved_prescription_message(prescription, "处方已保存。")
|
||||||
|
status.set_payload(message)
|
||||||
status.set_time_text(_join_meta("系统", datetime.now().strftime("%H:%M")))
|
status.set_time_text(_join_meta("系统", datetime.now().strftime("%H:%M")))
|
||||||
|
resume_saved_prescription(self.repository, prescription, self)
|
||||||
self._reload_prescriptions(generation, diagnosis_id)
|
self._reload_prescriptions(generation, diagnosis_id)
|
||||||
|
|
||||||
def _prescription_action_error(
|
def _prescription_action_error(
|
||||||
|
|||||||
@@ -99,6 +99,7 @@ from ..widgets import (
|
|||||||
page_total,
|
page_total,
|
||||||
run_async,
|
run_async,
|
||||||
)
|
)
|
||||||
|
from ..window_primitives import ClinicalAccentBar
|
||||||
from .issued_prescription_ai import can_open_issued_ai, present_issued_prescription_ai
|
from .issued_prescription_ai import can_open_issued_ai, present_issued_prescription_ai
|
||||||
from .local_audio_queue import LocalAudioQueueDialog
|
from .local_audio_queue import LocalAudioQueueDialog
|
||||||
from .prescription_ai import can_open_diagnosis_ai_report, present_diagnosis_ai_report
|
from .prescription_ai import can_open_diagnosis_ai_report, present_diagnosis_ai_report
|
||||||
@@ -127,6 +128,15 @@ _DAILY_PERMISSION = "tcm.diagnosis/dailyRecord"
|
|||||||
_PRESCRIPTION_PERMISSION = "tcm.diagnosis/chufang"
|
_PRESCRIPTION_PERMISSION = "tcm.diagnosis/chufang"
|
||||||
_PRESCRIPTION_EDIT_PERMISSION = "cf.prescription/edit"
|
_PRESCRIPTION_EDIT_PERMISSION = "cf.prescription/edit"
|
||||||
_OFFSET_PERMISSION = "tcm.diagnosis/setRevisitSlotStartOffset"
|
_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"
|
_VIDEO_PERMISSION = "tcm.diagnosis/huifang"
|
||||||
_CHAT_PERMISSION = "tcm.diagnosis/chat"
|
_CHAT_PERMISSION = "tcm.diagnosis/chat"
|
||||||
_NOTE_ADD_PERMISSION = "doctor.appointment/addDoctorNote"
|
_NOTE_ADD_PERMISSION = "doctor.appointment/addDoctorNote"
|
||||||
@@ -1029,7 +1039,24 @@ class DiagnosisDialog(QDialog):
|
|||||||
2, QHeaderView.ResizeMode.Stretch
|
2, QHeaderView.ResizeMode.Stretch
|
||||||
)
|
)
|
||||||
self.readonly_prescriptions_table.setMinimumHeight(220)
|
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_content_layout.setAlignment(
|
||||||
self._readonly_sections["prescription"], Qt.AlignmentFlag.AlignLeft
|
self._readonly_sections["prescription"], Qt.AlignmentFlag.AlignLeft
|
||||||
)
|
)
|
||||||
@@ -1207,21 +1234,105 @@ class DiagnosisDialog(QDialog):
|
|||||||
panel_layout = QVBoxLayout(self.drawer_panel)
|
panel_layout = QVBoxLayout(self.drawer_panel)
|
||||||
panel_layout.setContentsMargins(0, 0, 0, 0)
|
panel_layout.setContentsMargins(0, 0, 0, 0)
|
||||||
panel_layout.setSpacing(0)
|
panel_layout.setSpacing(0)
|
||||||
|
panel_layout.addWidget(ClinicalAccentBar(self.drawer_panel))
|
||||||
panel_layout.addWidget(self._build_drawer_header())
|
panel_layout.addWidget(self._build_drawer_header())
|
||||||
self.drawer_banner = MessageStrip()
|
self.drawer_banner = MessageStrip()
|
||||||
self.drawer_banner.setContentsMargins(16, 8, 16, 0)
|
self.drawer_banner.setContentsMargins(16, 8, 16, 0)
|
||||||
self.drawer_banner.action_requested.connect(self._retry_current)
|
self.drawer_banner.action_requested.connect(self._retry_current)
|
||||||
panel_layout.addWidget(self.drawer_banner)
|
panel_layout.addWidget(self.drawer_banner)
|
||||||
|
# W5 四诊病历工作室:左侧章节大纲定位轨 + 右侧主编辑工作区
|
||||||
|
studio_body = QHBoxLayout()
|
||||||
|
studio_body.setContentsMargins(0, 0, 0, 0)
|
||||||
|
studio_body.setSpacing(0)
|
||||||
|
self.studio_outline = QFrame(self.drawer_panel)
|
||||||
|
self.studio_outline.setObjectName("DiagnosisStudioOutline")
|
||||||
|
self.studio_outline.setFixedWidth(136)
|
||||||
|
self.studio_outline.setStyleSheet(
|
||||||
|
clinical_stylesheet(
|
||||||
|
r"""
|
||||||
|
QFrame#DiagnosisStudioOutline {
|
||||||
|
background-color: #F4F9F8;
|
||||||
|
border-right: 1px solid $ds_line;
|
||||||
|
}
|
||||||
|
QPushButton[studioOutlineBtn="true"] {
|
||||||
|
min-height: 34px;
|
||||||
|
max-height: 34px;
|
||||||
|
padding: 0 10px;
|
||||||
|
text-align: left;
|
||||||
|
border: 1px solid transparent;
|
||||||
|
border-radius: 8px;
|
||||||
|
background: transparent;
|
||||||
|
color: $ds_text;
|
||||||
|
font-size: 12.5px;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
QPushButton[studioOutlineBtn="true"]:hover {
|
||||||
|
background-color: #E7F4F2;
|
||||||
|
color: $ds_accent;
|
||||||
|
}
|
||||||
|
QPushButton[studioOutlineBtn="true"]:checked {
|
||||||
|
background-color: #FFFFFF;
|
||||||
|
border-color: #BEE0DA;
|
||||||
|
color: $ds_accent;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
)
|
||||||
|
self._studio_outline_layout = QVBoxLayout(self.studio_outline)
|
||||||
|
self._studio_outline_layout.setContentsMargins(10, 12, 10, 12)
|
||||||
|
self._studio_outline_layout.setSpacing(4)
|
||||||
|
self._studio_outline_buttons: list[QPushButton] = []
|
||||||
|
studio_body.addWidget(self.studio_outline)
|
||||||
|
|
||||||
self.tabs = DiagnosisTabWidget()
|
self.tabs = DiagnosisTabWidget()
|
||||||
self.tabs.setObjectName("DiagnosisDrawerTabs")
|
self.tabs.setObjectName("DiagnosisDrawerTabs")
|
||||||
self._build_drawer_tabs()
|
self._build_drawer_tabs()
|
||||||
self.tabs.currentChanged.connect(self._tab_changed)
|
self.tabs.currentChanged.connect(self._tab_changed)
|
||||||
panel_layout.addWidget(self.tabs, 1)
|
self.tabs.currentChanged.connect(self._sync_studio_outline_selection)
|
||||||
|
studio_body.addWidget(self.tabs, 1)
|
||||||
|
panel_layout.addLayout(studio_body, 1)
|
||||||
panel_layout.addWidget(self._build_drawer_footer())
|
panel_layout.addWidget(self._build_drawer_footer())
|
||||||
self.drawer_loading = LoadingOverlay(self.drawer_panel)
|
self.drawer_loading = LoadingOverlay(self.drawer_panel)
|
||||||
layout.addWidget(self.drawer_panel)
|
layout.addWidget(self.drawer_panel)
|
||||||
|
self._rebuild_studio_outline()
|
||||||
return overlay
|
return overlay
|
||||||
|
|
||||||
|
def _rebuild_studio_outline(self) -> None:
|
||||||
|
"""同步左侧章节大纲按钮,使医生可按临床模块一键直达定位。"""
|
||||||
|
|
||||||
|
if not hasattr(self, "_studio_outline_layout"):
|
||||||
|
return
|
||||||
|
while self._studio_outline_layout.count():
|
||||||
|
item = self._studio_outline_layout.takeAt(0)
|
||||||
|
widget = item.widget()
|
||||||
|
if widget is not None:
|
||||||
|
widget.hide()
|
||||||
|
widget.setParent(None)
|
||||||
|
widget.deleteLater()
|
||||||
|
self._studio_outline_buttons.clear()
|
||||||
|
caption = QLabel("四诊病历大纲", self.studio_outline)
|
||||||
|
caption.setStyleSheet("color: #5F7A78; font-size: 11px; font-weight: 600; padding: 2px 6px 6px;")
|
||||||
|
self._studio_outline_layout.addWidget(caption)
|
||||||
|
for index in range(self.tabs.count()):
|
||||||
|
label = self.tabs.tabText(index)
|
||||||
|
btn = QPushButton(f"{index + 1:02d} {label}", self.studio_outline)
|
||||||
|
btn.setProperty("studioOutlineBtn", True)
|
||||||
|
btn.setCheckable(True)
|
||||||
|
btn.setChecked(index == self.tabs.currentIndex())
|
||||||
|
btn.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||||
|
btn.clicked.connect(lambda _checked=False, i=index: self.tabs.setCurrentIndex(i))
|
||||||
|
self._studio_outline_layout.addWidget(btn)
|
||||||
|
self._studio_outline_buttons.append(btn)
|
||||||
|
self._studio_outline_layout.addStretch(1)
|
||||||
|
self.studio_outline.setVisible(self.tabs.count() > 1)
|
||||||
|
|
||||||
|
def _sync_studio_outline_selection(self, index: int) -> None:
|
||||||
|
if len(self._studio_outline_buttons) != self.tabs.count():
|
||||||
|
self._rebuild_studio_outline()
|
||||||
|
for i, btn in enumerate(self._studio_outline_buttons):
|
||||||
|
btn.setChecked(i == index)
|
||||||
|
|
||||||
def _build_drawer_header(self) -> QFrame:
|
def _build_drawer_header(self) -> QFrame:
|
||||||
header = QFrame()
|
header = QFrame()
|
||||||
header.setObjectName("DiagnosisDrawerHeader")
|
header.setObjectName("DiagnosisDrawerHeader")
|
||||||
@@ -1835,6 +1946,7 @@ class DiagnosisDialog(QDialog):
|
|||||||
target = index
|
target = index
|
||||||
self.tabs.setCurrentIndex(target)
|
self.tabs.setCurrentIndex(target)
|
||||||
self.tabs.blockSignals(blocked)
|
self.tabs.blockSignals(blocked)
|
||||||
|
self._rebuild_studio_outline()
|
||||||
section_codes = {key: codes for key, _label, codes in _TAB_DEFINITIONS}
|
section_codes = {key: codes for key, _label, codes in _TAB_DEFINITIONS}
|
||||||
for key, section in self._readonly_sections.items():
|
for key, section in self._readonly_sections.items():
|
||||||
section.setVisible(self._tab_allowed(section_codes.get(key, ())))
|
section.setVisible(self._tab_allowed(section_codes.get(key, ())))
|
||||||
@@ -2817,6 +2929,9 @@ class DiagnosisDialog(QDialog):
|
|||||||
for panel in self._chat_panels:
|
for panel in self._chat_panels:
|
||||||
panel.set_unavailable("正在加载聊天归档…")
|
panel.set_unavailable("正在加载聊天归档…")
|
||||||
elif key in self._table_registry:
|
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]:
|
for table in self._table_registry[key]:
|
||||||
table.set_matrix([])
|
table.set_matrix([])
|
||||||
table.set_empty_text("正在加载…")
|
table.set_empty_text("正在加载…")
|
||||||
@@ -3509,11 +3624,20 @@ class DiagnosisDialog(QDialog):
|
|||||||
appointment, "doctor_name", default=first_value(diagnosis, "doctor_name")
|
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(
|
dialog = PrescriptionEditorDialog(
|
||||||
self.repository,
|
self.repository,
|
||||||
seed,
|
seed,
|
||||||
mode="add",
|
mode="add",
|
||||||
current_user=getattr(self.parentWidget(), "current_user", None),
|
current_user=getattr(self.parentWidget(), "current_user", None),
|
||||||
|
save_draft=save_new,
|
||||||
parent=self,
|
parent=self,
|
||||||
)
|
)
|
||||||
dialog.diagnosis_requested.connect(self._open_current_diagnosis_detail)
|
dialog.diagnosis_requested.connect(self._open_current_diagnosis_detail)
|
||||||
@@ -3521,16 +3645,16 @@ class DiagnosisDialog(QDialog):
|
|||||||
dialog.setStyleSheet(DIAGNOSIS_QSS)
|
dialog.setStyleSheet(DIAGNOSIS_QSS)
|
||||||
if dialog.exec() != QDialog.DialogCode.Accepted:
|
if dialog.exec() != QDialog.DialogCode.Accepted:
|
||||||
return
|
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 = dialog.payload()
|
||||||
payload.update(
|
|
||||||
{
|
|
||||||
"diagnosis_id": diagnosis_id,
|
|
||||||
"appointment_id": appointment_id,
|
|
||||||
"case_record": seed["case_record"],
|
|
||||||
}
|
|
||||||
)
|
|
||||||
self._run_media_mutation(
|
self._run_media_mutation(
|
||||||
lambda: invoke(self.repository, "create_prescription", prescription=payload),
|
lambda: save_new(payload),
|
||||||
"处方已开具并提交审核。",
|
"处方已开具并提交审核。",
|
||||||
"prescription",
|
"prescription",
|
||||||
)
|
)
|
||||||
@@ -3740,8 +3864,8 @@ class DiagnosisDialog(QDialog):
|
|||||||
self._show_message("正在提交…", "info")
|
self._show_message("正在提交…", "info")
|
||||||
run_async(
|
run_async(
|
||||||
operation,
|
operation,
|
||||||
on_success=lambda _result: self._media_mutation_success(
|
on_success=lambda result: self._media_mutation_success(
|
||||||
success_text, reload_key, diagnosis_id, generation
|
success_text, reload_key, diagnosis_id, generation, result
|
||||||
),
|
),
|
||||||
on_error=lambda error: self._mutation_error(error, diagnosis_id, generation, "media"),
|
on_error=lambda error: self._mutation_error(error, diagnosis_id, generation, "media"),
|
||||||
on_finished=on_finished,
|
on_finished=on_finished,
|
||||||
@@ -3753,10 +3877,17 @@ class DiagnosisDialog(QDialog):
|
|||||||
reload_key: str,
|
reload_key: str,
|
||||||
diagnosis_id: int,
|
diagnosis_id: int,
|
||||||
generation: int,
|
generation: int,
|
||||||
|
result: Any = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
if generation != self._media_generation or diagnosis_id != self._diagnosis_id:
|
if generation != self._media_generation or diagnosis_id != self._diagnosis_id:
|
||||||
return
|
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)
|
self._loaded_tabs.discard(reload_key)
|
||||||
if reload_key == "chat":
|
if reload_key == "chat":
|
||||||
QTimer.singleShot(
|
QTimer.singleShot(
|
||||||
@@ -3977,6 +4108,9 @@ class DiagnosisDialog(QDialog):
|
|||||||
return button
|
return button
|
||||||
|
|
||||||
def _fill_prescriptions(self, rows: Sequence[Any]) -> None:
|
def _fill_prescriptions(self, rows: Sequence[Any]) -> None:
|
||||||
|
# set_matrix 会触发选中行变化;先清空,避免按旧诊单的行加载预览。
|
||||||
|
self._readonly_prescription_rows = []
|
||||||
|
self._clear_readonly_prescription_preview()
|
||||||
matrix: list[tuple[Any, ...]] = []
|
matrix: list[tuple[Any, ...]] = []
|
||||||
for row in rows:
|
for row in rows:
|
||||||
herbs = first_value(row, "herbs", default=[]) or []
|
herbs = first_value(row, "herbs", default=[]) or []
|
||||||
@@ -4040,6 +4174,44 @@ class DiagnosisDialog(QDialog):
|
|||||||
actions_layout.addWidget(edit_button)
|
actions_layout.addWidget(edit_button)
|
||||||
actions_layout.addStretch(1)
|
actions_layout.addStretch(1)
|
||||||
table.setCellWidget(row_index, 6, actions)
|
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:
|
def _view_prescription(self, prescription: Any) -> None:
|
||||||
prescription_id = _int(first_value(prescription, "id", "prescription_id", default=0), 0)
|
prescription_id = _int(first_value(prescription, "id", "prescription_id", default=0), 0)
|
||||||
@@ -4142,11 +4314,16 @@ class DiagnosisDialog(QDialog):
|
|||||||
def _open_prescription_edit_dialog(self, prescription: Any, prescription_id: int) -> None:
|
def _open_prescription_edit_dialog(self, prescription: Any, prescription_id: int) -> None:
|
||||||
from .prescription import PrescriptionEditorDialog
|
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(
|
dialog = PrescriptionEditorDialog(
|
||||||
self.repository,
|
self.repository,
|
||||||
prescription,
|
prescription,
|
||||||
mode="edit",
|
mode="edit",
|
||||||
current_user=getattr(self.parentWidget(), "current_user", None),
|
current_user=getattr(self.parentWidget(), "current_user", None),
|
||||||
|
save_draft=save_changes,
|
||||||
parent=self,
|
parent=self,
|
||||||
)
|
)
|
||||||
dialog.diagnosis_requested.connect(self._open_current_diagnosis_detail)
|
dialog.diagnosis_requested.connect(self._open_current_diagnosis_detail)
|
||||||
@@ -4154,14 +4331,16 @@ class DiagnosisDialog(QDialog):
|
|||||||
dialog.setStyleSheet(DIAGNOSIS_QSS)
|
dialog.setStyleSheet(DIAGNOSIS_QSS)
|
||||||
if dialog.exec() != QDialog.DialogCode.Accepted:
|
if dialog.exec() != QDialog.DialogCode.Accepted:
|
||||||
return
|
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 = dialog.payload()
|
||||||
self._run_media_mutation(
|
self._run_media_mutation(
|
||||||
lambda: invoke(
|
lambda: save_changes(payload),
|
||||||
self.repository,
|
|
||||||
"update_prescription",
|
|
||||||
prescription=prescription_id,
|
|
||||||
changes=payload,
|
|
||||||
),
|
|
||||||
"处方已保存并重新进入待审核。",
|
"处方已保存并重新进入待审核。",
|
||||||
"prescription",
|
"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)
|
||||||
@@ -24,43 +24,43 @@ from PySide6.QtGui import QFont
|
|||||||
from ..design_system import PALETTE
|
from ..design_system import PALETTE
|
||||||
|
|
||||||
DARK: dict[str, str] = {
|
DARK: dict[str, str] = {
|
||||||
# ground and cards
|
# 御瓷暗曜科技面:深翡翠黑曜石底 + 精密青玉科技主色 + 香槟鎏金微光
|
||||||
"canvas": "#080D18",
|
"canvas": "#071212",
|
||||||
"canvas_soft": "#0C1322",
|
"canvas_soft": "#0A1A1A",
|
||||||
"surface": "#0F1726",
|
"surface": "#0E2121",
|
||||||
"surface_2": "#131D2E",
|
"surface_2": "#122929",
|
||||||
"raised": "#1A2637",
|
"raised": "#183534",
|
||||||
"line": "#22304A",
|
"line": "#214240",
|
||||||
"line_soft": "#18233A",
|
"line_soft": "#173130",
|
||||||
# type
|
# type
|
||||||
"heading": "#E8EFFB",
|
"heading": "#ECF6F5",
|
||||||
"text": "#B6C5DA",
|
"text": "#BAD0CE",
|
||||||
"muted": "#8195AF",
|
"muted": "#82A09D",
|
||||||
"faint": "#6A7F99",
|
"faint": "#64827F",
|
||||||
"selected_text": "#E8EFFB",
|
"selected_text": "#ECF6F5",
|
||||||
# interface colour
|
# interface colour
|
||||||
"accent": "#2E7BF6",
|
"accent": "#16A89E",
|
||||||
"accent_text": "#6BA5FF",
|
"accent_text": "#5BE0D6",
|
||||||
"accent_pressed": "#1A5FD0",
|
"accent_pressed": "#0E857D",
|
||||||
"selection": "#142645",
|
"selection": "#123433",
|
||||||
"selection_line": "#1B3E77",
|
"selection_line": "#1F5C58",
|
||||||
# model hues
|
# model hues
|
||||||
"qwen": "#17BFDD",
|
"qwen": "#22C7D6",
|
||||||
"qwen_text": "#55D8EE",
|
"qwen_text": "#69E3EE",
|
||||||
"qwen_dim": "#10303C",
|
"qwen_dim": "#103238",
|
||||||
"openai": "#9B7BFF",
|
"openai": "#D4AF6A",
|
||||||
"openai_text": "#B69FFF",
|
"openai_text": "#EAD09B",
|
||||||
"openai_dim": "#241F48",
|
"openai_dim": "#2D2719",
|
||||||
# severity
|
# severity
|
||||||
"amber": "#F5B942",
|
"amber": "#F2B644",
|
||||||
"amber_text": "#F8C661",
|
"amber_text": "#F7C96E",
|
||||||
"amber_dim": "#2C2415",
|
"amber_dim": "#2E2514",
|
||||||
"rose": "#F4697A",
|
"rose": "#F06A7B",
|
||||||
"rose_text": "#F88694",
|
"rose_text": "#F78D9B",
|
||||||
"rose_dim": "#2C1620",
|
"rose_dim": "#2E171E",
|
||||||
"ok": "#2E7BF6",
|
"ok": "#16A89E",
|
||||||
"zebra": "#0E1626",
|
"zebra": "#0C1D1D",
|
||||||
"grid_line": "#191F2C",
|
"grid_line": "#172E2D",
|
||||||
}
|
}
|
||||||
|
|
||||||
LIGHT: dict[str, str] = {
|
LIGHT: dict[str, str] = {
|
||||||
@@ -81,21 +81,21 @@ LIGHT: dict[str, str] = {
|
|||||||
"accent_pressed": PALETTE["accent_pressed"],
|
"accent_pressed": PALETTE["accent_pressed"],
|
||||||
"selection": PALETTE["accent_soft"],
|
"selection": PALETTE["accent_soft"],
|
||||||
"selection_line": PALETTE["focus"],
|
"selection_line": PALETTE["focus"],
|
||||||
"qwen": "#0C89AC",
|
"qwen": "#0B8894",
|
||||||
"qwen_text": "#086C88",
|
"qwen_text": "#086A74",
|
||||||
"qwen_dim": "#E2F5FA",
|
"qwen_dim": "#E3F5F7",
|
||||||
"openai": "#6B4AE0",
|
"openai": "#A37E38",
|
||||||
"openai_text": "#5537C6",
|
"openai_text": "#826124",
|
||||||
"openai_dim": "#EDE8FE",
|
"openai_dim": "#FAF4E7",
|
||||||
"amber": "#B4791A",
|
"amber": "#B56B00",
|
||||||
"amber_text": "#8F5F0B",
|
"amber_text": "#8F5400",
|
||||||
"amber_dim": "#FCF2DF",
|
"amber_dim": "#FEF5E6",
|
||||||
"rose": "#D0435A",
|
"rose": "#C83B4B",
|
||||||
"rose_text": "#AE3149",
|
"rose_text": "#A62B3A",
|
||||||
"rose_dim": "#FCE9EC",
|
"rose_dim": "#FDEEEF",
|
||||||
"ok": "#1A5FD0",
|
"ok": PALETTE["accent"],
|
||||||
"zebra": "#FAFBFE",
|
"zebra": "#F8FBFB",
|
||||||
"grid_line": "#DDE4EE",
|
"grid_line": PALETTE["line"],
|
||||||
}
|
}
|
||||||
|
|
||||||
CONSOLE: dict[str, str] = dict(DARK)
|
CONSOLE: dict[str, str] = dict(DARK)
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -46,6 +46,7 @@ from ..widgets import (
|
|||||||
AI_MODELS: tuple[tuple[str, str, str], ...] = (
|
AI_MODELS: tuple[tuple[str, str, str], ...] = (
|
||||||
("qwen", "千问", "qwen3.6-35b"),
|
("qwen", "千问", "qwen3.6-35b"),
|
||||||
("openai", "OpenAI", "gpt-5.6-sol"),
|
("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_MODEL_KEYS = frozenset(profile for profile, _label, _name in AI_MODELS)
|
||||||
AI_REPORT_EDIT_PERMISSIONS = (
|
AI_REPORT_EDIT_PERMISSIONS = (
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,192 @@
|
|||||||
|
"""W4 视频问诊双屏协同驾驶舱(演示预览与原生临床速记协同视窗)。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from PySide6.QtCore import Qt, QTimer
|
||||||
|
from PySide6.QtWidgets import (
|
||||||
|
QDialog,
|
||||||
|
QFrame,
|
||||||
|
QHBoxLayout,
|
||||||
|
QLabel,
|
||||||
|
QPlainTextEdit,
|
||||||
|
QPushButton,
|
||||||
|
QVBoxLayout,
|
||||||
|
QWidget,
|
||||||
|
)
|
||||||
|
|
||||||
|
from ..window_primitives import ClinicalAccentBar
|
||||||
|
|
||||||
|
|
||||||
|
class VideoCockpitDemoDialog(QDialog):
|
||||||
|
"""W4 视频问诊双屏协同驾驶舱:左深曜影院画布 + 底部毛玻璃控坞 + 右伴随四诊速记侧栏。"""
|
||||||
|
|
||||||
|
def __init__(self, patient_name: str, parent: QWidget | None = None) -> None:
|
||||||
|
super().__init__(parent)
|
||||||
|
self._seconds = 0
|
||||||
|
self._tongue_count = 0
|
||||||
|
self.setWindowTitle("视频面诊 · 双屏协同驾驶舱")
|
||||||
|
self.setMinimumSize(860, 560)
|
||||||
|
self.resize(1120, 700)
|
||||||
|
self.setModal(False)
|
||||||
|
self.setStyleSheet(
|
||||||
|
"QDialog{background:#071515;color:#EFF9F8;}"
|
||||||
|
"QFrame#VideoTopHud{background:rgba(12,38,37,220);border:1px solid rgba(223,199,147,90);border-radius:12px;}"
|
||||||
|
"QFrame#RemoteStage{background:qradialgradient(cx:0.5,cy:0.4,radius:0.8,fx:0.5,fy:0.4,stop:0 #153E3C,stop:0.65 #081A1A,stop:1 #040D0D);"
|
||||||
|
"border:1px solid rgba(223,199,147,60);border-radius:16px;}"
|
||||||
|
"QFrame#RemoteStage QLabel{color:#EFF9F8;}"
|
||||||
|
"QFrame#LocalStage{background:qlineargradient(x1:0,y1:0,x2:1,y2:1,stop:0 #184644,stop:1 #0B2524);"
|
||||||
|
"border:1.5px solid #DFC793;border-radius:12px;}"
|
||||||
|
"QFrame#VideoDock{background:rgba(9,28,28,235);border:1px solid rgba(223,199,147,110);border-radius:24px;}"
|
||||||
|
"QFrame#VideoCompanionRail{background:#F5FAF9;border-left:1px solid #C6DAD6;}"
|
||||||
|
"QFrame#VideoCompanionRail QLabel{color:#102625;}"
|
||||||
|
"QPlainTextEdit#VideoQuickNotes{background:#FFFFFF;border:1px solid #C4D8D4;border-radius:10px;padding:8px;color:#102625;font-size:13px;}"
|
||||||
|
"QPushButton{min-width:88px;min-height:36px;padding:0 14px;border-radius:18px;"
|
||||||
|
"background:rgba(255,255,255,22);color:#F0FAF9;border:1px solid rgba(255,255,255,48);font-weight:600;}"
|
||||||
|
"QPushButton:hover{background:rgba(24,176,165,70);border-color:#DFC793;color:#FFFFFF;}"
|
||||||
|
"QPushButton:checked{background:rgba(223,199,147,60);border-color:#DFC793;color:#DFC793;}"
|
||||||
|
"QPushButton#TongueBtn{background:rgba(223,199,147,48);border-color:#DFC793;color:#DFC793;}"
|
||||||
|
"QPushButton#Hangup{color:#FFFFFF;background:#D63F4F;border-color:#D63F4F;}"
|
||||||
|
"QPushButton#Hangup:hover{background:#B92E3D;border-color:#B92E3D;}"
|
||||||
|
)
|
||||||
|
|
||||||
|
root_col = QVBoxLayout(self)
|
||||||
|
root_col.setContentsMargins(0, 0, 0, 0)
|
||||||
|
root_col.setSpacing(0)
|
||||||
|
root_col.addWidget(ClinicalAccentBar(self))
|
||||||
|
|
||||||
|
outer = QHBoxLayout()
|
||||||
|
outer.setContentsMargins(0, 0, 0, 0)
|
||||||
|
outer.setSpacing(0)
|
||||||
|
|
||||||
|
left_wrap = QWidget(self)
|
||||||
|
left_layout = QVBoxLayout(left_wrap)
|
||||||
|
left_layout.setContentsMargins(16, 14, 16, 16)
|
||||||
|
left_layout.setSpacing(12)
|
||||||
|
|
||||||
|
top_hud = QFrame(left_wrap)
|
||||||
|
top_hud.setObjectName("VideoTopHud")
|
||||||
|
header = QHBoxLayout(top_hud)
|
||||||
|
header.setContentsMargins(14, 9, 14, 9)
|
||||||
|
title = QLabel(f"● 视频面诊 · {patient_name or '患者'}", top_hud)
|
||||||
|
title.setStyleSheet("font-size:15px;font-weight:700;color:#F4FAF9;")
|
||||||
|
header.addWidget(title)
|
||||||
|
header.addStretch(1)
|
||||||
|
demo = QLabel("本地加密录音就绪 · 演示模式", top_hud)
|
||||||
|
demo.setStyleSheet("color:#9FC5C1;font-size:12px;")
|
||||||
|
header.addWidget(demo)
|
||||||
|
self.duration_label = QLabel("00:00", top_hud)
|
||||||
|
self.duration_label.setStyleSheet("font-weight:700;color:#DFC793;padding-left:10px;")
|
||||||
|
header.addWidget(self.duration_label)
|
||||||
|
left_layout.addWidget(top_hud)
|
||||||
|
|
||||||
|
stage = QFrame(left_wrap)
|
||||||
|
stage.setObjectName("RemoteStage")
|
||||||
|
stage_layout = QVBoxLayout(stage)
|
||||||
|
stage_layout.setContentsMargins(22, 22, 22, 22)
|
||||||
|
stage_layout.addStretch(1)
|
||||||
|
avatar = QLabel((patient_name or "患")[:1], stage)
|
||||||
|
avatar.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||||
|
avatar.setFixedSize(96, 96)
|
||||||
|
avatar.setStyleSheet(
|
||||||
|
"background:rgba(24,176,165,48);color:#FFFFFF;border:2px solid #DFC793;"
|
||||||
|
"border-radius:48px;font-size:38px;font-weight:700;"
|
||||||
|
)
|
||||||
|
stage_layout.addWidget(avatar, 0, Qt.AlignmentFlag.AlignHCenter)
|
||||||
|
waiting = QLabel("等待患者接入高清视频画面…", stage)
|
||||||
|
waiting.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||||
|
waiting.setStyleSheet("font-size:16px;font-weight:600;margin-top:8px;")
|
||||||
|
stage_layout.addWidget(waiting)
|
||||||
|
hint = QLabel("生产模式通过后端短时 UserSig 驱动 TRTC,支持舌象高清抓拍与实时转写", stage)
|
||||||
|
hint.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||||
|
hint.setStyleSheet("color:#91BDB8;font-size:12px;")
|
||||||
|
stage_layout.addWidget(hint)
|
||||||
|
self._tongue_status = QLabel("", stage)
|
||||||
|
self._tongue_status.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||||
|
self._tongue_status.setStyleSheet("color:#DFC793;font-size:12px;font-weight:600;margin-top:6px;")
|
||||||
|
stage_layout.addWidget(self._tongue_status)
|
||||||
|
stage_layout.addStretch(1)
|
||||||
|
|
||||||
|
local = QFrame(stage)
|
||||||
|
local.setObjectName("LocalStage")
|
||||||
|
local.setGeometry(20, 20, 176, 108)
|
||||||
|
local_layout = QVBoxLayout(local)
|
||||||
|
local_label = QLabel("陈医生(本机画面)", local)
|
||||||
|
local_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||||
|
local_label.setStyleSheet("color:#EFF9F8;font-weight:600;font-size:12px;")
|
||||||
|
local_layout.addWidget(local_label)
|
||||||
|
left_layout.addWidget(stage, 1)
|
||||||
|
|
||||||
|
dock = QFrame(left_wrap)
|
||||||
|
dock.setObjectName("VideoDock")
|
||||||
|
controls = QHBoxLayout(dock)
|
||||||
|
controls.setContentsMargins(14, 7, 14, 7)
|
||||||
|
controls.setSpacing(10)
|
||||||
|
self.mic_button = QPushButton("麦克风 开", dock)
|
||||||
|
self.mic_button.setCheckable(True)
|
||||||
|
self.mic_button.toggled.connect(
|
||||||
|
lambda muted: self.mic_button.setText("麦克风 关" if muted else "麦克风 开")
|
||||||
|
)
|
||||||
|
controls.addWidget(self.mic_button)
|
||||||
|
self.camera_button = QPushButton("摄像头 开", dock)
|
||||||
|
self.camera_button.setCheckable(True)
|
||||||
|
self.camera_button.toggled.connect(
|
||||||
|
lambda off: self.camera_button.setText("摄像头 关" if off else "摄像头 开")
|
||||||
|
)
|
||||||
|
controls.addWidget(self.camera_button)
|
||||||
|
tongue_btn = QPushButton("舌象高清抓拍", dock)
|
||||||
|
tongue_btn.setObjectName("TongueBtn")
|
||||||
|
tongue_btn.clicked.connect(self._capture_demo_tongue)
|
||||||
|
controls.addWidget(tongue_btn)
|
||||||
|
hangup = QPushButton("结束面诊", dock)
|
||||||
|
hangup.setObjectName("Hangup")
|
||||||
|
hangup.clicked.connect(self.close)
|
||||||
|
controls.addWidget(hangup)
|
||||||
|
left_layout.addWidget(dock, 0, Qt.AlignmentFlag.AlignHCenter)
|
||||||
|
outer.addWidget(left_wrap, 1)
|
||||||
|
|
||||||
|
rail = QFrame(self)
|
||||||
|
rail.setObjectName("VideoCompanionRail")
|
||||||
|
rail.setFixedWidth(340)
|
||||||
|
rail_layout = QVBoxLayout(rail)
|
||||||
|
rail_layout.setContentsMargins(16, 16, 16, 16)
|
||||||
|
rail_layout.setSpacing(10)
|
||||||
|
rail_title = QLabel("伴随四诊速记(双屏协同)", rail)
|
||||||
|
rail_title.setStyleSheet("font-size:15px;font-weight:700;color:#102625;")
|
||||||
|
rail_layout.addWidget(rail_title)
|
||||||
|
rail_hint = QLabel("面诊过程中实时记录主诉与舌脉,结束后自动带入病历草稿。", rail)
|
||||||
|
rail_hint.setWordWrap(True)
|
||||||
|
rail_hint.setStyleSheet("font-size:12px;color:#5F7A78;")
|
||||||
|
rail_layout.addWidget(rail_hint)
|
||||||
|
self.quick_notes = QPlainTextEdit(rail)
|
||||||
|
self.quick_notes.setObjectName("VideoQuickNotes")
|
||||||
|
self.quick_notes.setPlaceholderText("在此速记本次视频面诊的主诉、舌质舌苔、脉象与调方思路…")
|
||||||
|
rail_layout.addWidget(self.quick_notes, 1)
|
||||||
|
ai_hint_box = QFrame(rail)
|
||||||
|
ai_hint_box.setStyleSheet(
|
||||||
|
"QFrame{background:#EAF6F4;border:1px solid #B7DDD6;border-radius:10px;padding:8px;}"
|
||||||
|
)
|
||||||
|
ai_hint_l = QVBoxLayout(ai_hint_box)
|
||||||
|
ai_hint_l.setContentsMargins(10, 8, 10, 8)
|
||||||
|
ai_lbl = QLabel("AI 问诊提醒:建议核实近期夜间睡眠与餐后 2h 血糖峰值。", ai_hint_box)
|
||||||
|
ai_lbl.setWordWrap(True)
|
||||||
|
ai_lbl.setStyleSheet("color:#0B6E68;font-size:12px;font-weight:500;")
|
||||||
|
ai_hint_l.addWidget(ai_lbl)
|
||||||
|
rail_layout.addWidget(ai_hint_box)
|
||||||
|
outer.addWidget(rail)
|
||||||
|
root_col.addLayout(outer, 1)
|
||||||
|
|
||||||
|
self._timer = QTimer(self)
|
||||||
|
self._timer.timeout.connect(self._tick)
|
||||||
|
self._timer.start(1000)
|
||||||
|
|
||||||
|
def _capture_demo_tongue(self) -> None:
|
||||||
|
self._tongue_count += 1
|
||||||
|
self._tongue_status.setText(f"✓ 已抓拍第 {self._tongue_count} 帧高清舌象并准备归档")
|
||||||
|
|
||||||
|
def _tick(self) -> None:
|
||||||
|
self._seconds += 1
|
||||||
|
minutes, seconds = divmod(self._seconds, 60)
|
||||||
|
self.duration_label.setText(f"{minutes:02d}:{seconds:02d}")
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = ["VideoCockpitDemoDialog"]
|
||||||
@@ -69,6 +69,7 @@ ROLES = {
|
|||||||
"strong": COLORS["text"],
|
"strong": COLORS["text"],
|
||||||
"accent": COLORS["indigo"],
|
"accent": COLORS["indigo"],
|
||||||
"on_accent": "#FFFFFF",
|
"on_accent": "#FFFFFF",
|
||||||
|
"gold": COLORS["gold"],
|
||||||
"success": COLORS["success"],
|
"success": COLORS["success"],
|
||||||
"warning": COLORS["warning"],
|
"warning": COLORS["warning"],
|
||||||
"danger": COLORS["danger"],
|
"danger": COLORS["danger"],
|
||||||
@@ -124,8 +125,41 @@ def _dot(p: QPainter, cx: float, cy: float, r: float) -> None:
|
|||||||
p.setPen(pen)
|
p.setPen(pen)
|
||||||
|
|
||||||
|
|
||||||
|
def _tint_brush(p: QPainter, alpha: int = 38) -> QColor:
|
||||||
|
"""Return a translucent duotone fill derived from the active stroke colour."""
|
||||||
|
|
||||||
|
tint = QColor(p.pen().color())
|
||||||
|
tint.setAlpha(alpha)
|
||||||
|
return tint
|
||||||
|
|
||||||
|
|
||||||
|
def _duotone_path(p: QPainter, path: QPainterPath, alpha: int = 38) -> None:
|
||||||
|
"""Draw a closed path with a subtle duotone tint fill beneath its crisp stroke."""
|
||||||
|
|
||||||
|
p.save()
|
||||||
|
p.setBrush(_tint_brush(p, alpha))
|
||||||
|
p.drawPath(path)
|
||||||
|
p.restore()
|
||||||
|
|
||||||
|
|
||||||
|
def _duotone_rounded_rect(
|
||||||
|
p: QPainter, rect: QRectF, rx: float, ry: float, alpha: int = 38
|
||||||
|
) -> None:
|
||||||
|
p.save()
|
||||||
|
p.setBrush(_tint_brush(p, alpha))
|
||||||
|
p.drawRoundedRect(rect, rx, ry)
|
||||||
|
p.restore()
|
||||||
|
|
||||||
|
|
||||||
|
def _duotone_circle(p: QPainter, cx: float, cy: float, r: float, alpha: int = 38) -> None:
|
||||||
|
p.save()
|
||||||
|
p.setBrush(_tint_brush(p, alpha))
|
||||||
|
p.drawEllipse(QPointF(cx, cy), r, r)
|
||||||
|
p.restore()
|
||||||
|
|
||||||
|
|
||||||
def _page(p: QPainter, *, fold: bool = True) -> None:
|
def _page(p: QPainter, *, fold: bool = True) -> None:
|
||||||
"""Shared document silhouette so every file-like glyph has one outline."""
|
"""Shared document silhouette with subtle duotone glass tint."""
|
||||||
|
|
||||||
path = QPainterPath(QPointF(14.0, 2.5))
|
path = QPainterPath(QPointF(14.0, 2.5))
|
||||||
path.lineTo(QPointF(6.5, 2.5))
|
path.lineTo(QPointF(6.5, 2.5))
|
||||||
@@ -136,13 +170,13 @@ def _page(p: QPainter, *, fold: bool = True) -> None:
|
|||||||
path.quadTo(QPointF(19.0, 21.5), QPointF(19.0, 20.0))
|
path.quadTo(QPointF(19.0, 21.5), QPointF(19.0, 20.0))
|
||||||
path.lineTo(QPointF(19.0, 7.5))
|
path.lineTo(QPointF(19.0, 7.5))
|
||||||
path.closeSubpath()
|
path.closeSubpath()
|
||||||
p.drawPath(path)
|
_duotone_path(p, path, 34)
|
||||||
if fold:
|
if fold:
|
||||||
_polyline(p, (14.0, 2.5), (14.0, 7.5), (19.0, 7.5))
|
_polyline(p, (14.0, 2.5), (14.0, 7.5), (19.0, 7.5))
|
||||||
|
|
||||||
|
|
||||||
def _sparkle(p: QPainter, cx: float, cy: float, r: float) -> None:
|
def _sparkle(p: QPainter, cx: float, cy: float, r: float, *, alpha: int = 56) -> None:
|
||||||
"""Four-point concave star - the one AI mark used across the product."""
|
"""Four-point concave star - the precision AI mark with luminous duotone core."""
|
||||||
|
|
||||||
path = QPainterPath(QPointF(cx, cy - r))
|
path = QPainterPath(QPointF(cx, cy - r))
|
||||||
path.quadTo(QPointF(cx, cy), QPointF(cx + r, cy))
|
path.quadTo(QPointF(cx, cy), QPointF(cx + r, cy))
|
||||||
@@ -150,11 +184,11 @@ def _sparkle(p: QPainter, cx: float, cy: float, r: float) -> None:
|
|||||||
path.quadTo(QPointF(cx, cy), QPointF(cx - r, cy))
|
path.quadTo(QPointF(cx, cy), QPointF(cx - r, cy))
|
||||||
path.quadTo(QPointF(cx, cy), QPointF(cx, cy - r))
|
path.quadTo(QPointF(cx, cy), QPointF(cx, cy - r))
|
||||||
path.closeSubpath()
|
path.closeSubpath()
|
||||||
p.drawPath(path)
|
_duotone_path(p, path, alpha)
|
||||||
|
|
||||||
|
|
||||||
def _panel(p: QPainter) -> None:
|
def _panel(p: QPainter) -> None:
|
||||||
p.drawRoundedRect(QRectF(2.5, 4.0, 19.0, 16.0), 3.0, 3.0)
|
_duotone_rounded_rect(p, QRectF(2.5, 4.0, 19.0, 16.0), 3.0, 3.0, 28)
|
||||||
_line(p, 9.5, 4.0, 9.5, 20.0)
|
_line(p, 9.5, 4.0, 9.5, 20.0)
|
||||||
|
|
||||||
|
|
||||||
@@ -163,18 +197,20 @@ def _panel(p: QPainter) -> None:
|
|||||||
|
|
||||||
@_glyph("reception", "workbench", "monitor")
|
@_glyph("reception", "workbench", "monitor")
|
||||||
def _reception(p: QPainter, w: float) -> None:
|
def _reception(p: QPainter, w: float) -> None:
|
||||||
p.drawRoundedRect(QRectF(2.5, 3.5, 19.0, 13.5), 3.0, 3.0)
|
_duotone_rounded_rect(p, QRectF(2.5, 3.5, 19.0, 13.5), 3.2, 3.2, 38)
|
||||||
_polyline(p, (6.0, 10.5), (8.8, 10.5), (10.6, 7.5), (13.4, 13.5), (15.2, 10.5), (18.0, 10.5))
|
_polyline(p, (5.8, 10.5), (8.6, 10.5), (10.5, 7.2), (13.4, 13.6), (15.3, 10.5), (18.2, 10.5))
|
||||||
_line(p, 12.0, 17.0, 12.0, 20.5)
|
_line(p, 12.0, 17.0, 12.0, 20.5)
|
||||||
_line(p, 8.0, 20.5, 16.0, 20.5)
|
_line(p, 8.0, 20.5, 16.0, 20.5)
|
||||||
|
|
||||||
|
|
||||||
@_glyph("appointments", "calendar")
|
@_glyph("appointments", "calendar")
|
||||||
def _calendar(p: QPainter, w: float) -> None:
|
def _calendar(p: QPainter, w: float) -> None:
|
||||||
p.drawRoundedRect(QRectF(3.0, 5.0, 18.0, 16.5), 3.0, 3.0)
|
_duotone_rounded_rect(p, QRectF(3.0, 5.0, 18.0, 16.5), 3.2, 3.2, 36)
|
||||||
_line(p, 3.0, 10.0, 21.0, 10.0)
|
_line(p, 3.0, 10.0, 21.0, 10.0)
|
||||||
_line(p, 8.0, 2.75, 8.0, 7.0)
|
_line(p, 8.0, 2.75, 8.0, 6.8)
|
||||||
_line(p, 16.0, 2.75, 16.0, 7.0)
|
_line(p, 16.0, 2.75, 16.0, 6.8)
|
||||||
|
_line(p, 7.5, 14.0, 11.5, 14.0)
|
||||||
|
_line(p, 7.5, 17.4, 15.0, 17.4)
|
||||||
|
|
||||||
|
|
||||||
@_glyph("prescription_library", "library", "layers")
|
@_glyph("prescription_library", "library", "layers")
|
||||||
@@ -184,7 +220,7 @@ def _layers(p: QPainter, w: float) -> None:
|
|||||||
path.lineTo(QPointF(12.0, 11.5))
|
path.lineTo(QPointF(12.0, 11.5))
|
||||||
path.lineTo(QPointF(3.0, 7.0))
|
path.lineTo(QPointF(3.0, 7.0))
|
||||||
path.closeSubpath()
|
path.closeSubpath()
|
||||||
p.drawPath(path)
|
_duotone_path(p, path, 48)
|
||||||
_polyline(p, (3.0, 12.0), (12.0, 16.5), (21.0, 12.0))
|
_polyline(p, (3.0, 12.0), (12.0, 16.5), (21.0, 12.0))
|
||||||
_polyline(p, (3.0, 16.75), (12.0, 21.25), (21.0, 16.75))
|
_polyline(p, (3.0, 16.75), (12.0, 21.25), (21.0, 16.75))
|
||||||
|
|
||||||
@@ -197,12 +233,12 @@ def _file_check(p: QPainter, w: float) -> None:
|
|||||||
|
|
||||||
@_glyph("patients", "users")
|
@_glyph("patients", "users")
|
||||||
def _users(p: QPainter, w: float) -> None:
|
def _users(p: QPainter, w: float) -> None:
|
||||||
_circle(p, 9.0, 8.0, 3.5)
|
_duotone_circle(p, 9.0, 8.0, 3.5, 42)
|
||||||
path = QPainterPath(QPointF(2.5, 20.5))
|
path = QPainterPath(QPointF(2.5, 20.5))
|
||||||
path.quadTo(QPointF(2.5, 14.5), QPointF(9.0, 14.5))
|
path.quadTo(QPointF(2.5, 14.5), QPointF(9.0, 14.5))
|
||||||
path.quadTo(QPointF(15.5, 14.5), QPointF(15.5, 20.5))
|
path.quadTo(QPointF(15.5, 14.5), QPointF(15.5, 20.5))
|
||||||
p.drawPath(path)
|
p.drawPath(path)
|
||||||
_circle(p, 17.6, 8.0, 2.8)
|
_duotone_circle(p, 17.6, 8.0, 2.8, 28)
|
||||||
tail = QPainterPath(QPointF(17.0, 13.9))
|
tail = QPainterPath(QPointF(17.0, 13.9))
|
||||||
tail.quadTo(QPointF(21.5, 14.6), QPointF(21.5, 20.5))
|
tail.quadTo(QPointF(21.5, 14.6), QPointF(21.5, 20.5))
|
||||||
p.drawPath(tail)
|
p.drawPath(tail)
|
||||||
@@ -221,7 +257,7 @@ def _message(p: QPainter, w: float) -> None:
|
|||||||
path.quadTo(QPointF(3.5, 16.5), QPointF(3.5, 13.5))
|
path.quadTo(QPointF(3.5, 16.5), QPointF(3.5, 13.5))
|
||||||
path.lineTo(QPointF(3.5, 6.5))
|
path.lineTo(QPointF(3.5, 6.5))
|
||||||
path.quadTo(QPointF(3.5, 3.5), QPointF(6.5, 3.5))
|
path.quadTo(QPointF(3.5, 3.5), QPointF(6.5, 3.5))
|
||||||
p.drawPath(path)
|
_duotone_path(p, path, 38)
|
||||||
_line(p, 7.75, 8.25, 16.25, 8.25)
|
_line(p, 7.75, 8.25, 16.25, 8.25)
|
||||||
_line(p, 7.75, 11.75, 13.0, 11.75)
|
_line(p, 7.75, 11.75, 13.0, 11.75)
|
||||||
|
|
||||||
@@ -275,10 +311,23 @@ def _ai(p: QPainter, w: float) -> None:
|
|||||||
|
|
||||||
@_glyph("fullscreen", "expand-corners", "maximize")
|
@_glyph("fullscreen", "expand-corners", "maximize")
|
||||||
def _fullscreen(p: QPainter, w: float) -> None:
|
def _fullscreen(p: QPainter, w: float) -> None:
|
||||||
_polyline(p, (9.0, 3.5), (3.5, 3.5), (3.5, 9.0))
|
# 标准现代桌面端圆角单窗最大化图标,取代生硬的四角取景框
|
||||||
_polyline(p, (15.0, 3.5), (20.5, 3.5), (20.5, 9.0))
|
p.drawRoundedRect(QRectF(4.5, 4.5, 15.0, 15.0), 2.8, 2.8)
|
||||||
_polyline(p, (3.5, 15.0), (3.5, 20.5), (9.0, 20.5))
|
|
||||||
_polyline(p, (20.5, 15.0), (20.5, 20.5), (15.0, 20.5))
|
|
||||||
|
@_glyph("restore", "unmaximize")
|
||||||
|
def _restore(p: QPainter, w: float) -> None:
|
||||||
|
# 标准现代桌面端双窗还原图标
|
||||||
|
p.drawRoundedRect(QRectF(4.25, 7.25, 12.25, 12.25), 2.4, 2.4)
|
||||||
|
back = QPainterPath(QPointF(7.75, 7.25))
|
||||||
|
back.lineTo(QPointF(7.75, 6.2))
|
||||||
|
back.quadTo(QPointF(7.75, 4.25), QPointF(9.7, 4.25))
|
||||||
|
back.lineTo(QPointF(17.8, 4.25))
|
||||||
|
back.quadTo(QPointF(19.75, 4.25), QPointF(19.75, 6.2))
|
||||||
|
back.lineTo(QPointF(19.75, 14.3))
|
||||||
|
back.quadTo(QPointF(19.75, 16.25), QPointF(17.8, 16.25))
|
||||||
|
back.lineTo(QPointF(16.5, 16.25))
|
||||||
|
p.drawPath(back)
|
||||||
|
|
||||||
|
|
||||||
@_glyph("minimize")
|
@_glyph("minimize")
|
||||||
@@ -318,17 +367,27 @@ def _bell(p: QPainter, w: float) -> None:
|
|||||||
path.lineTo(QPointF(6.75, 10.75))
|
path.lineTo(QPointF(6.75, 10.75))
|
||||||
path.arcTo(QRectF(6.75, 5.0, 10.5, 11.5), 180.0, -180.0)
|
path.arcTo(QRectF(6.75, 5.0, 10.5, 11.5), 180.0, -180.0)
|
||||||
path.lineTo(QPointF(17.25, 17.5))
|
path.lineTo(QPointF(17.25, 17.5))
|
||||||
p.drawPath(path)
|
path.closeSubpath()
|
||||||
|
_duotone_path(p, path, 36)
|
||||||
_line(p, 4.5, 17.5, 19.5, 17.5)
|
_line(p, 4.5, 17.5, 19.5, 17.5)
|
||||||
p.drawArc(QRectF(10.0, 17.4, 4.0, 3.6), 180 * 16, 180 * 16)
|
p.drawArc(QRectF(10.0, 17.4, 4.0, 3.6), 180 * 16, 180 * 16)
|
||||||
|
|
||||||
|
|
||||||
@_glyph("settings", "sliders")
|
@_glyph("settings", "sliders")
|
||||||
def _settings(p: QPainter, w: float) -> None:
|
def _settings(p: QPainter, w: float) -> None:
|
||||||
_line(p, 3.5, 8.5, 20.5, 8.5)
|
# 精密八齿圆润齿轮 + 双色调内核,替代锯齿硬编码多边形与简陋滑块
|
||||||
_line(p, 3.5, 15.5, 20.5, 15.5)
|
_duotone_circle(p, 12.0, 12.0, 5.4, 34)
|
||||||
_circle(p, 9.0, 8.5, 2.4)
|
_circle(p, 12.0, 12.0, 2.35)
|
||||||
_circle(p, 15.0, 15.5, 2.4)
|
for step in range(8):
|
||||||
|
angle = step * math.pi / 4.0
|
||||||
|
cos_a, sin_a = math.cos(angle), math.sin(angle)
|
||||||
|
_line(
|
||||||
|
p,
|
||||||
|
12.0 + 5.7 * cos_a,
|
||||||
|
12.0 + 5.7 * sin_a,
|
||||||
|
12.0 + 8.6 * cos_a,
|
||||||
|
12.0 + 8.6 * sin_a,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
# --- Row and toolbar actions ---------------------------------------------
|
# --- Row and toolbar actions ---------------------------------------------
|
||||||
@@ -339,8 +398,8 @@ def _eye(p: QPainter, w: float) -> None:
|
|||||||
path = QPainterPath(QPointF(2.5, 12.0))
|
path = QPainterPath(QPointF(2.5, 12.0))
|
||||||
path.quadTo(QPointF(12.0, 2.5), QPointF(21.5, 12.0))
|
path.quadTo(QPointF(12.0, 2.5), QPointF(21.5, 12.0))
|
||||||
path.quadTo(QPointF(12.0, 21.5), QPointF(2.5, 12.0))
|
path.quadTo(QPointF(12.0, 21.5), QPointF(2.5, 12.0))
|
||||||
p.drawPath(path)
|
_duotone_path(p, path, 28)
|
||||||
_circle(p, 12.0, 12.0, 3.0)
|
_duotone_circle(p, 12.0, 12.0, 3.0, 48)
|
||||||
|
|
||||||
|
|
||||||
@_glyph("pencil", "edit")
|
@_glyph("pencil", "edit")
|
||||||
@@ -569,13 +628,13 @@ def _qr(p: QPainter, w: float) -> None:
|
|||||||
|
|
||||||
@_glyph("video", "call")
|
@_glyph("video", "call")
|
||||||
def _video(p: QPainter, w: float) -> None:
|
def _video(p: QPainter, w: float) -> None:
|
||||||
p.drawRoundedRect(QRectF(2.5, 6.0, 13.5, 12.0), 3.0, 3.0)
|
_duotone_rounded_rect(p, QRectF(2.5, 6.0, 13.5, 12.0), 3.0, 3.0, 38)
|
||||||
path = QPainterPath(QPointF(16.0, 10.5))
|
path = QPainterPath(QPointF(16.0, 10.5))
|
||||||
path.lineTo(QPointF(21.5, 7.25))
|
path.lineTo(QPointF(21.5, 7.25))
|
||||||
path.lineTo(QPointF(21.5, 16.75))
|
path.lineTo(QPointF(21.5, 16.75))
|
||||||
path.lineTo(QPointF(16.0, 13.5))
|
path.lineTo(QPointF(16.0, 13.5))
|
||||||
path.closeSubpath()
|
path.closeSubpath()
|
||||||
p.drawPath(path)
|
_duotone_path(p, path, 32)
|
||||||
|
|
||||||
|
|
||||||
# --- Clinical measures ----------------------------------------------------
|
# --- Clinical measures ----------------------------------------------------
|
||||||
@@ -596,14 +655,14 @@ def _height(p: QPainter, w: float) -> None:
|
|||||||
|
|
||||||
@_glyph("weight", "scale")
|
@_glyph("weight", "scale")
|
||||||
def _weight(p: QPainter, w: float) -> None:
|
def _weight(p: QPainter, w: float) -> None:
|
||||||
p.drawRoundedRect(QRectF(3.0, 5.0, 18.0, 14.5), 3.5, 3.5)
|
_duotone_rounded_rect(p, QRectF(3.0, 5.0, 18.0, 14.5), 3.5, 3.5, 34)
|
||||||
p.drawArc(QRectF(7.0, 10.0, 10.0, 10.0), 25 * 16, 130 * 16)
|
p.drawArc(QRectF(7.0, 10.0, 10.0, 10.0), 25 * 16, 130 * 16)
|
||||||
_line(p, 12.0, 15.0, 9.9, 10.9)
|
_line(p, 12.0, 15.0, 9.9, 10.9)
|
||||||
|
|
||||||
|
|
||||||
@_glyph("bmi", "body")
|
@_glyph("bmi", "body")
|
||||||
def _bmi(p: QPainter, w: float) -> None:
|
def _bmi(p: QPainter, w: float) -> None:
|
||||||
_circle(p, 12.0, 5.0, 2.75)
|
_duotone_circle(p, 12.0, 5.0, 2.75, 42)
|
||||||
_line(p, 12.0, 7.75, 12.0, 15.0)
|
_line(p, 12.0, 7.75, 12.0, 15.0)
|
||||||
_line(p, 7.25, 11.0, 16.75, 11.0)
|
_line(p, 7.25, 11.0, 16.75, 11.0)
|
||||||
_polyline(p, (8.5, 20.75), (12.0, 15.0), (15.5, 20.75))
|
_polyline(p, (8.5, 20.75), (12.0, 15.0), (15.5, 20.75))
|
||||||
@@ -611,8 +670,10 @@ def _bmi(p: QPainter, w: float) -> None:
|
|||||||
|
|
||||||
@_glyph("blood_pressure", "gauge", "bp")
|
@_glyph("blood_pressure", "gauge", "bp")
|
||||||
def _blood_pressure(p: QPainter, w: float) -> None:
|
def _blood_pressure(p: QPainter, w: float) -> None:
|
||||||
p.drawArc(QRectF(3.0, 5.5, 18.0, 18.0), 0, 180 * 16)
|
arc_path = QPainterPath(QPointF(3.0, 14.5))
|
||||||
_line(p, 3.0, 14.5, 21.0, 14.5)
|
arc_path.arcTo(QRectF(3.0, 5.5, 18.0, 18.0), 180, -180)
|
||||||
|
arc_path.closeSubpath()
|
||||||
|
_duotone_path(p, arc_path, 34)
|
||||||
_line(p, 12.0, 14.5, 16.4, 9.4)
|
_line(p, 12.0, 14.5, 16.4, 9.4)
|
||||||
_dot(p, 12.0, 14.5, 1.15)
|
_dot(p, 12.0, 14.5, 1.15)
|
||||||
|
|
||||||
@@ -625,7 +686,7 @@ def _pulse(p: QPainter, w: float) -> None:
|
|||||||
heart.cubicTo(QPointF(13.5, 4.8), QPointF(16.8, 4.0), QPointF(19.3, 6.7))
|
heart.cubicTo(QPointF(13.5, 4.8), QPointF(16.8, 4.0), QPointF(19.3, 6.7))
|
||||||
heart.cubicTo(QPointF(21.8, 9.6), QPointF(20.8, 13.6), QPointF(12.0, 20.25))
|
heart.cubicTo(QPointF(21.8, 9.6), QPointF(20.8, 13.6), QPointF(12.0, 20.25))
|
||||||
heart.closeSubpath()
|
heart.closeSubpath()
|
||||||
p.drawPath(heart)
|
_duotone_path(p, heart, 36)
|
||||||
_polyline(
|
_polyline(
|
||||||
p, (5.6, 12.4), (9.0, 12.4), (10.6, 9.7), (13.2, 15.1), (14.7, 12.4), (18.4, 12.4)
|
p, (5.6, 12.4), (9.0, 12.4), (10.6, 9.7), (13.2, 15.1), (14.7, 12.4), (18.4, 12.4)
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1,148 @@
|
|||||||
|
"""桌面端全局精工交互引擎:统一手型光标、Windows 11 DWM 视窗融合与优雅按压手感."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import ctypes
|
||||||
|
import sys
|
||||||
|
|
||||||
|
from PySide6.QtCore import QEvent, QObject, Qt
|
||||||
|
from PySide6.QtWidgets import (
|
||||||
|
QAbstractButton,
|
||||||
|
QApplication,
|
||||||
|
QComboBox,
|
||||||
|
QDialog,
|
||||||
|
QFileDialog,
|
||||||
|
QInputDialog,
|
||||||
|
QMessageBox,
|
||||||
|
QTabBar,
|
||||||
|
QWidget,
|
||||||
|
)
|
||||||
|
|
||||||
|
from .design_system import PALETTE
|
||||||
|
|
||||||
|
# Windows 11 DWM 窗口装饰属性常量
|
||||||
|
_DWMWA_USE_IMMERSIVE_DARK_MODE = 20
|
||||||
|
_DWMWA_WINDOW_CORNER_PREFERENCE = 33
|
||||||
|
_DWMWA_BORDER_COLOR = 34
|
||||||
|
_DWMWA_CAPTION_COLOR = 35
|
||||||
|
_DWMWA_TEXT_COLOR = 36
|
||||||
|
_DWMWCP_ROUND = 2
|
||||||
|
|
||||||
|
|
||||||
|
def _colorref(hex_color: str) -> int:
|
||||||
|
"""将 ``#RRGGBB`` 转为 Win32 DWM 所需的 ``0x00BBGGRR`` 整型。"""
|
||||||
|
|
||||||
|
clean = hex_color.lstrip("#")
|
||||||
|
red, green, blue = (int(clean[i : i + 2], 16) for i in (0, 2, 4))
|
||||||
|
return (blue << 16) | (green << 8) | red
|
||||||
|
|
||||||
|
|
||||||
|
def apply_luxury_dwm_chrome(widget: QWidget, *, dark: bool = False) -> bool:
|
||||||
|
"""在 Windows 11 上同步原生子视窗标题栏、圆角偏好与边框至「御瓷智医」色系。"""
|
||||||
|
|
||||||
|
if sys.platform != "win32":
|
||||||
|
return False
|
||||||
|
if widget.windowFlags() & Qt.WindowType.FramelessWindowHint:
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
handle = int(widget.winId())
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
if not handle:
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
dwm = ctypes.windll.dwmapi
|
||||||
|
except (AttributeError, OSError):
|
||||||
|
return False
|
||||||
|
|
||||||
|
caption_hex = PALETTE["obsidian"] if dark else PALETTE["surface"]
|
||||||
|
text_hex = "#F2FAF9" if dark else PALETTE["heading"]
|
||||||
|
border_hex = PALETTE["gold"] if dark else PALETTE["line_strong"]
|
||||||
|
|
||||||
|
dark_val = ctypes.c_int(1 if dark else 0)
|
||||||
|
corner_val = ctypes.c_int(_DWMWCP_ROUND)
|
||||||
|
caption_val = ctypes.c_uint(_colorref(caption_hex))
|
||||||
|
text_val = ctypes.c_uint(_colorref(text_hex))
|
||||||
|
border_val = ctypes.c_uint(_colorref(border_hex))
|
||||||
|
|
||||||
|
applied = False
|
||||||
|
for attr, value in (
|
||||||
|
(_DWMWA_USE_IMMERSIVE_DARK_MODE, dark_val),
|
||||||
|
(_DWMWA_WINDOW_CORNER_PREFERENCE, corner_val),
|
||||||
|
(_DWMWA_CAPTION_COLOR, caption_val),
|
||||||
|
(_DWMWA_TEXT_COLOR, text_val),
|
||||||
|
(_DWMWA_BORDER_COLOR, border_val),
|
||||||
|
):
|
||||||
|
try:
|
||||||
|
res = dwm.DwmSetWindowAttribute(
|
||||||
|
ctypes.c_void_p(handle),
|
||||||
|
ctypes.c_int(attr),
|
||||||
|
ctypes.byref(value),
|
||||||
|
ctypes.sizeof(value),
|
||||||
|
)
|
||||||
|
applied = applied or res == 0
|
||||||
|
except OSError:
|
||||||
|
continue
|
||||||
|
return applied
|
||||||
|
|
||||||
|
|
||||||
|
class _TactileInteractionFilter(QObject):
|
||||||
|
"""全局轻量事件过滤器:自动补齐手型光标与子视窗 DWM 高定视觉融合。"""
|
||||||
|
|
||||||
|
_INTERACTIVE_TYPES = (QAbstractButton, QTabBar, QComboBox)
|
||||||
|
_WATCHED_EVENTS = frozenset({QEvent.Type.Polish, QEvent.Type.EnabledChange, QEvent.Type.Show})
|
||||||
|
|
||||||
|
def eventFilter(self, watched: QObject, event: QEvent) -> bool: # noqa: N802
|
||||||
|
try:
|
||||||
|
event_type = event.type()
|
||||||
|
except RuntimeError:
|
||||||
|
return False
|
||||||
|
if event_type not in self._WATCHED_EVENTS:
|
||||||
|
return False
|
||||||
|
|
||||||
|
if isinstance(watched, self._INTERACTIVE_TYPES):
|
||||||
|
if event_type in (QEvent.Type.Polish, QEvent.Type.EnabledChange):
|
||||||
|
if watched.isEnabled():
|
||||||
|
if watched.cursor().shape() == Qt.CursorShape.ArrowCursor:
|
||||||
|
watched.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||||
|
else:
|
||||||
|
if watched.cursor().shape() == Qt.CursorShape.PointingHandCursor:
|
||||||
|
watched.setCursor(Qt.CursorShape.ArrowCursor)
|
||||||
|
return False
|
||||||
|
|
||||||
|
if (
|
||||||
|
event_type is QEvent.Type.Show
|
||||||
|
and isinstance(watched, QDialog)
|
||||||
|
and not isinstance(watched, (QFileDialog, QMessageBox, QInputDialog))
|
||||||
|
and not watched.testAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
|
||||||
|
):
|
||||||
|
name = watched.objectName() or ""
|
||||||
|
is_dark = any(tag in name for tag in ("Video", "IssuedPrescriptionAi", "AiConsult"))
|
||||||
|
apply_luxury_dwm_chrome(watched, dark=is_dark)
|
||||||
|
# W8 原语 B:自动为所有标准业务弹窗顶部注入 3px 翡翠-鎏金饰线(避免重复插入)
|
||||||
|
if (
|
||||||
|
not (watched.windowFlags() & Qt.WindowType.FramelessWindowHint)
|
||||||
|
and not getattr(watched, "_doctor_accent_bar_injected", False)
|
||||||
|
):
|
||||||
|
from PySide6.QtWidgets import QVBoxLayout
|
||||||
|
|
||||||
|
from .window_primitives import ClinicalAccentBar
|
||||||
|
|
||||||
|
layout = watched.layout()
|
||||||
|
if isinstance(layout, QVBoxLayout) and not watched.findChildren(ClinicalAccentBar):
|
||||||
|
watched._doctor_accent_bar_injected = True # type: ignore[attr-defined]
|
||||||
|
layout.insertWidget(0, ClinicalAccentBar(watched))
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def install_tactile_interactions(app: QApplication) -> None:
|
||||||
|
"""幂等安装全局精工交互过滤器。"""
|
||||||
|
|
||||||
|
if getattr(app, "_doctor_tactile_interaction_filter", None) is not None:
|
||||||
|
return
|
||||||
|
flt = _TactileInteractionFilter(app)
|
||||||
|
app.installEventFilter(flt)
|
||||||
|
app._doctor_tactile_interaction_filter = flt
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = ["apply_luxury_dwm_chrome", "install_tactile_interactions"]
|
||||||
@@ -5,15 +5,18 @@ from __future__ import annotations
|
|||||||
from contextlib import suppress
|
from contextlib import suppress
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from PySide6.QtCore import QEvent, QPoint, QPointF, QRectF, QSettings, Qt, QTimer, Signal
|
from PySide6.QtCore import QEvent, QPoint, QPointF, QRectF, QSettings, QSize, Qt, QTimer, Signal
|
||||||
from PySide6.QtGui import (
|
from PySide6.QtGui import (
|
||||||
QColor,
|
QColor,
|
||||||
QFont,
|
QFont,
|
||||||
QIcon,
|
QIcon,
|
||||||
|
QLinearGradient,
|
||||||
|
QMouseEvent,
|
||||||
QPainter,
|
QPainter,
|
||||||
QPainterPath,
|
QPainterPath,
|
||||||
QPen,
|
QPen,
|
||||||
QPixmap,
|
QPixmap,
|
||||||
|
QRadialGradient,
|
||||||
QResizeEvent,
|
QResizeEvent,
|
||||||
)
|
)
|
||||||
from PySide6.QtWidgets import (
|
from PySide6.QtWidgets import (
|
||||||
@@ -123,7 +126,7 @@ def _round_pen(color: QColor | str, width: float) -> QPen:
|
|||||||
|
|
||||||
|
|
||||||
class _BrandPanel(QWidget):
|
class _BrandPanel(QWidget):
|
||||||
"""A flat, readable introduction to the clinician's daily workflow."""
|
"""御瓷智医 · 深曜翡翠科技医疗奢雅品牌沉浸区."""
|
||||||
|
|
||||||
def __init__(self, parent: QWidget | None = None) -> None:
|
def __init__(self, parent: QWidget | None = None) -> None:
|
||||||
super().__init__(parent)
|
super().__init__(parent)
|
||||||
@@ -138,60 +141,237 @@ class _BrandPanel(QWidget):
|
|||||||
painter = QPainter(self)
|
painter = QPainter(self)
|
||||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||||
bounds = QRectF(self.rect()).adjusted(1, 1, -1, -1)
|
bounds = QRectF(self.rect()).adjusted(1, 1, -1, -1)
|
||||||
painter.setPen(Qt.PenStyle.NoPen)
|
|
||||||
painter.setBrush(QColor(PALETTE["sidebar"]))
|
|
||||||
painter.drawRoundedRect(bounds, 20, 20)
|
|
||||||
left = 36.0
|
|
||||||
width = max(240.0, self.width() - 72.0)
|
|
||||||
if not self._brand_lockup.isNull():
|
|
||||||
brand = self._brand_lockup.scaled(
|
|
||||||
226, 58, Qt.AspectRatioMode.KeepAspectRatio,
|
|
||||||
Qt.TransformationMode.SmoothTransformation,
|
|
||||||
)
|
|
||||||
painter.drawPixmap(QPointF(left, 36), brand)
|
|
||||||
else:
|
|
||||||
painter.setFont(_font(22, QFont.Weight.DemiBold))
|
|
||||||
painter.setPen(QColor(PALETTE["heading"]))
|
|
||||||
painter.drawText(QPointF(left, 70), "甄养堂 · 医生工作站")
|
|
||||||
|
|
||||||
heading_y = max(158.0, min(218.0, self.height() * .27))
|
clip = QPainterPath()
|
||||||
painter.setPen(QColor(PALETTE["muted"]))
|
clip.addRoundedRect(bounds, 20, 20)
|
||||||
painter.setFont(_font(13, QFont.Weight.Medium))
|
painter.setClipPath(clip)
|
||||||
painter.drawText(QPointF(left, heading_y - 36), "医 生 工 作 台")
|
|
||||||
painter.setPen(QColor(PALETTE["heading"]))
|
# 深曜翡翠渐变底 + 右上角精密青玉科技辉光
|
||||||
painter.setFont(_font(30, QFont.Weight.DemiBold))
|
bg = QLinearGradient(bounds.topLeft(), bounds.bottomRight())
|
||||||
painter.drawText(QPointF(left, heading_y), "让诊疗有序,")
|
bg.setColorAt(0.0, QColor("#0E3F3C"))
|
||||||
painter.drawText(QPointF(left, heading_y + 44), "让沟通更专注。")
|
bg.setColorAt(0.52, QColor("#092726"))
|
||||||
|
bg.setColorAt(1.0, QColor("#061717"))
|
||||||
|
painter.setPen(Qt.PenStyle.NoPen)
|
||||||
|
painter.setBrush(bg)
|
||||||
|
painter.drawRect(bounds)
|
||||||
|
|
||||||
|
glow = QRadialGradient(
|
||||||
|
QPointF(bounds.right() - 70.0, bounds.top() + 90.0),
|
||||||
|
max(280.0, bounds.width() * 0.55),
|
||||||
|
)
|
||||||
|
glow.setColorAt(0.0, QColor(24, 184, 173, 74))
|
||||||
|
glow.setColorAt(0.55, QColor(14, 120, 114, 24))
|
||||||
|
glow.setColorAt(1.0, QColor(14, 120, 114, 0))
|
||||||
|
painter.setBrush(glow)
|
||||||
|
painter.drawRect(bounds)
|
||||||
|
|
||||||
|
# 精密医疗科技同心轨道 + 微光心电脉搏线
|
||||||
|
ring_center = QPointF(bounds.right() - 48.0, bounds.top() + 86.0)
|
||||||
|
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||||
|
painter.setPen(QPen(QColor(223, 199, 147, 36), 1.0))
|
||||||
|
painter.drawEllipse(ring_center, 155.0, 155.0)
|
||||||
|
dash_pen = QPen(QColor(110, 224, 214, 34), 1.0, Qt.PenStyle.DashLine)
|
||||||
|
painter.setPen(dash_pen)
|
||||||
|
painter.drawEllipse(ring_center, 230.0, 230.0)
|
||||||
|
|
||||||
|
pulse_y = bounds.bottom() - 96.0
|
||||||
|
pulse = QPainterPath(QPointF(bounds.left(), pulse_y))
|
||||||
|
pulse.lineTo(QPointF(bounds.left() + bounds.width() * 0.36, pulse_y))
|
||||||
|
pulse.lineTo(QPointF(bounds.left() + bounds.width() * 0.43, pulse_y - 38.0))
|
||||||
|
pulse.lineTo(QPointF(bounds.left() + bounds.width() * 0.50, pulse_y + 30.0))
|
||||||
|
pulse.lineTo(QPointF(bounds.left() + bounds.width() * 0.56, pulse_y - 16.0))
|
||||||
|
pulse.lineTo(QPointF(bounds.left() + bounds.width() * 0.61, pulse_y))
|
||||||
|
pulse.lineTo(QPointF(bounds.right(), pulse_y))
|
||||||
|
painter.setPen(QPen(QColor(110, 224, 214, 40), 1.4))
|
||||||
|
painter.drawPath(pulse)
|
||||||
|
|
||||||
|
# 顶部 1px 香槟鎏金奢雅边框
|
||||||
|
painter.setPen(QPen(QColor(223, 199, 147, 72), 1.0))
|
||||||
|
painter.drawRoundedRect(bounds, 20, 20)
|
||||||
|
|
||||||
|
left = 40.0
|
||||||
|
width = max(240.0, self.width() - 80.0)
|
||||||
|
|
||||||
|
# 甄养堂高定翡翠鎏金徽标 + 精致反白品牌锁标
|
||||||
|
emblem = QRectF(left, 36.0, 44.0, 44.0)
|
||||||
|
em_grad = QLinearGradient(emblem.topLeft(), emblem.bottomRight())
|
||||||
|
em_grad.setColorAt(0.0, QColor("#18B0A5"))
|
||||||
|
em_grad.setColorAt(1.0, QColor("#09615C"))
|
||||||
|
painter.setBrush(em_grad)
|
||||||
|
painter.setPen(QPen(QColor(PALETTE["gold_light"]), 1.2))
|
||||||
|
painter.drawRoundedRect(emblem, 12.0, 12.0)
|
||||||
|
|
||||||
|
painter.save()
|
||||||
|
painter.translate(emblem.topLeft())
|
||||||
|
painter.scale(44.0 / 38.0, 44.0 / 38.0)
|
||||||
|
drop = QPainterPath(QPointF(19.0, 7.6))
|
||||||
|
drop.cubicTo(QPointF(14.8, 13.2), QPointF(11.2, 17.8), QPointF(11.2, 22.4))
|
||||||
|
drop.cubicTo(QPointF(11.2, 26.8), QPointF(14.7, 30.4), QPointF(19.0, 30.4))
|
||||||
|
drop.cubicTo(QPointF(23.3, 30.4), QPointF(26.8, 26.8), QPointF(26.8, 22.4))
|
||||||
|
drop.cubicTo(QPointF(26.8, 17.8), QPointF(23.2, 13.2), QPointF(19.0, 7.6))
|
||||||
|
drop.closeSubpath()
|
||||||
|
painter.setPen(Qt.PenStyle.NoPen)
|
||||||
|
painter.setBrush(QColor("#FFFFFF"))
|
||||||
|
painter.drawPath(drop)
|
||||||
|
mini_pulse = QPainterPath(QPointF(13.5, 22.4))
|
||||||
|
mini_pulse.lineTo(QPointF(16.2, 22.4))
|
||||||
|
mini_pulse.lineTo(QPointF(17.8, 18.8))
|
||||||
|
mini_pulse.lineTo(QPointF(20.0, 25.6))
|
||||||
|
mini_pulse.lineTo(QPointF(21.6, 22.4))
|
||||||
|
mini_pulse.lineTo(QPointF(24.5, 22.4))
|
||||||
|
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||||
|
painter.setPen(_round_pen("#0B6E68", 2.0))
|
||||||
|
painter.drawPath(mini_pulse)
|
||||||
|
painter.restore()
|
||||||
|
|
||||||
|
painter.setFont(_font(20, QFont.Weight.DemiBold))
|
||||||
|
painter.setPen(QColor("#FFFFFF"))
|
||||||
|
painter.drawText(QPointF(left + 58.0, 56.0), "甄养堂")
|
||||||
|
painter.setFont(_font(11, QFont.Weight.Medium))
|
||||||
|
painter.setPen(QColor(PALETTE["gold_light"]))
|
||||||
|
painter.drawText(QPointF(left + 58.0, 74.0), "DIABETES TELEHEALTH · 糖尿病专科工作站")
|
||||||
|
|
||||||
|
heading_y = max(162.0, min(214.0, self.height() * 0.27))
|
||||||
|
painter.setPen(QColor("#7CE4DB"))
|
||||||
|
painter.setFont(_font(12, QFont.Weight.Medium))
|
||||||
|
painter.drawText(QPointF(left, heading_y - 34), "PRECISION CLINICAL WORKSTATION")
|
||||||
|
painter.setPen(QColor("#FFFFFF"))
|
||||||
|
painter.setFont(_font(31, QFont.Weight.DemiBold))
|
||||||
|
painter.drawText(QPointF(left, heading_y), "让每一次辨证,")
|
||||||
|
painter.drawText(QPointF(left, heading_y + 44), "更专注、更有序。")
|
||||||
painter.setFont(_font(14))
|
painter.setFont(_font(14))
|
||||||
painter.setPen(QColor(PALETTE["muted"]))
|
painter.setPen(QColor("#A4C9C5"))
|
||||||
painter.drawText(QPointF(left, heading_y + 82), "从接诊、病历到处方,在一个工作台完成。")
|
painter.drawText(QPointF(left, heading_y + 82), "融合智能辨证、纵向血糖洞察与合规双签的一体化医疗桌面。")
|
||||||
|
|
||||||
row_y = heading_y + 122
|
row_y = heading_y + 122
|
||||||
for index, (title, detail) in enumerate((
|
for index, (title, detail) in enumerate((
|
||||||
("今日接诊", "快速找到待接诊患者与预约安排"),
|
("今日接诊 · 三栏直览", "待诊队列、四诊病历与视频房间同屏高效衔接"),
|
||||||
("诊疗记录", "病历、随访与面诊资料集中查看"),
|
("AI 临床辨证辅助", "多模态聚合历次复诊与血糖波动,梳理随访要点"),
|
||||||
("处方协作", "开方与审核流程清晰衔接"),
|
("处方协作 · CA 合规双签", "经验方一键复用,开方与药师审核签署全流程留痕"),
|
||||||
), start=1):
|
), start=1):
|
||||||
row = QRectF(left, row_y, width, 66)
|
row = QRectF(left, row_y, width, 66)
|
||||||
painter.setPen(Qt.PenStyle.NoPen)
|
painter.setPen(QPen(QColor(223, 199, 147, 52), 1.0))
|
||||||
painter.setBrush(QColor(PALETTE["surface"]))
|
painter.setBrush(QColor(255, 255, 255, 16))
|
||||||
painter.drawRoundedRect(row, 12, 12)
|
painter.drawRoundedRect(row, 12, 12)
|
||||||
painter.setFont(_font(13, QFont.Weight.DemiBold))
|
badge_rect = QRectF(left + 14, row_y + 17, 32, 32)
|
||||||
painter.setPen(QColor(PALETTE["accent"]))
|
painter.setPen(QPen(QColor(223, 199, 147, 96), 1.0))
|
||||||
painter.drawText(QRectF(left + 16, row_y, 28, 66), Qt.AlignmentFlag.AlignCenter, f"0{index}")
|
painter.setBrush(QColor(223, 199, 147, 24))
|
||||||
|
painter.drawRoundedRect(badge_rect, 8, 8)
|
||||||
|
painter.setFont(_font(12, QFont.Weight.DemiBold))
|
||||||
|
painter.setPen(QColor(PALETTE["gold_light"]))
|
||||||
|
painter.drawText(badge_rect, Qt.AlignmentFlag.AlignCenter, f"0{index}")
|
||||||
painter.setFont(_font(15, QFont.Weight.Medium))
|
painter.setFont(_font(15, QFont.Weight.Medium))
|
||||||
painter.setPen(QColor(PALETTE["heading"]))
|
painter.setPen(QColor("#F4FAF9"))
|
||||||
painter.drawText(QPointF(left + 58, row_y + 27), title)
|
painter.drawText(QPointF(left + 60, row_y + 28), title)
|
||||||
painter.setFont(_font(12))
|
painter.setFont(_font(12))
|
||||||
painter.setPen(QColor(PALETTE["muted"]))
|
painter.setPen(QColor("#9AC0BC"))
|
||||||
painter.drawText(QPointF(left + 58, row_y + 47), detail)
|
painter.drawText(QPointF(left + 60, row_y + 49), detail)
|
||||||
row_y += 78
|
row_y += 78
|
||||||
if self.height() > row_y + 50:
|
if self.height() > row_y + 48:
|
||||||
painter.setFont(_font(12))
|
painter.setFont(_font(12))
|
||||||
painter.setPen(QColor(PALETTE["muted"]))
|
painter.setPen(QColor("#749E99"))
|
||||||
painter.drawText(QPointF(left, self.height() - 28), "仅供获授权的医疗人员使用")
|
painter.drawText(QPointF(left, self.height() - 28), "仅供获授权的执业医疗人员使用 · 端到端加密传输")
|
||||||
painter.end()
|
painter.end()
|
||||||
|
|
||||||
|
def mousePressEvent(self, event: QMouseEvent) -> None: # noqa: N802 - Qt API
|
||||||
|
if event.button() == Qt.MouseButton.LeftButton:
|
||||||
|
handle = self.window().windowHandle()
|
||||||
|
if handle is not None and handle.startSystemMove():
|
||||||
|
event.accept()
|
||||||
|
return
|
||||||
|
super().mousePressEvent(event)
|
||||||
|
|
||||||
|
|
||||||
|
class _LoginWindowControlButton(QToolButton):
|
||||||
|
"""登录悬浮窗右上角原生桌面最小化/关闭按钮。"""
|
||||||
|
|
||||||
|
def __init__(self, kind: str, parent: QWidget | None = None) -> None:
|
||||||
|
super().__init__(parent)
|
||||||
|
self._kind = kind
|
||||||
|
self.setObjectName("LoginWindowControl")
|
||||||
|
self.setProperty("windowControl", kind)
|
||||||
|
self.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||||
|
self.setAutoRaise(True)
|
||||||
|
self.setFixedSize(34, 34)
|
||||||
|
self.setIcon(icons.icon(kind, "muted", 16))
|
||||||
|
self.setIconSize(QSize(16, 16))
|
||||||
|
|
||||||
|
def enterEvent(self, event: Any) -> None: # noqa: N802 - Qt API
|
||||||
|
if self._kind == "close":
|
||||||
|
self.setIcon(icons.icon("close", "inverse", 16))
|
||||||
|
else:
|
||||||
|
self.setIcon(icons.icon(self._kind, "heading", 16))
|
||||||
|
super().enterEvent(event)
|
||||||
|
|
||||||
|
def leaveEvent(self, event: Any) -> None: # noqa: N802 - Qt API
|
||||||
|
self.setIcon(icons.icon(self._kind, "muted", 16))
|
||||||
|
super().leaveEvent(event)
|
||||||
|
|
||||||
|
|
||||||
|
class _LoginWindowShell(QWidget):
|
||||||
|
"""无边框奢雅青瓷圆角悬浮视窗,支持原生拖动与边缘缩放。"""
|
||||||
|
|
||||||
|
_RESIZE_MARGIN = 8
|
||||||
|
|
||||||
|
def __init__(self, parent: QWidget | None = None) -> None:
|
||||||
|
super().__init__(parent)
|
||||||
|
self.setMouseTracking(True)
|
||||||
|
|
||||||
|
def paintEvent(self, event: Any) -> None: # noqa: N802 - Qt API
|
||||||
|
del event
|
||||||
|
painter = QPainter(self)
|
||||||
|
painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
|
||||||
|
bounds = QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5)
|
||||||
|
painter.setBrush(QColor(PALETTE["canvas"]))
|
||||||
|
painter.setPen(QPen(QColor("#B5CAC6"), 1.0))
|
||||||
|
painter.drawRoundedRect(bounds, 18.0, 18.0)
|
||||||
|
painter.end()
|
||||||
|
|
||||||
|
def _resize_edges(self, position: QPointF) -> Qt.Edge:
|
||||||
|
edges = Qt.Edge(0)
|
||||||
|
if position.x() <= self._RESIZE_MARGIN:
|
||||||
|
edges |= Qt.Edge.LeftEdge
|
||||||
|
elif position.x() >= self.width() - self._RESIZE_MARGIN:
|
||||||
|
edges |= Qt.Edge.RightEdge
|
||||||
|
if position.y() <= self._RESIZE_MARGIN:
|
||||||
|
edges |= Qt.Edge.TopEdge
|
||||||
|
elif position.y() >= self.height() - self._RESIZE_MARGIN:
|
||||||
|
edges |= Qt.Edge.BottomEdge
|
||||||
|
return edges
|
||||||
|
|
||||||
|
def mouseMoveEvent(self, event: QMouseEvent) -> None: # noqa: N802 - Qt API
|
||||||
|
edges = self._resize_edges(event.position())
|
||||||
|
if edges in (
|
||||||
|
Qt.Edge.LeftEdge | Qt.Edge.TopEdge,
|
||||||
|
Qt.Edge.RightEdge | Qt.Edge.BottomEdge,
|
||||||
|
):
|
||||||
|
self.setCursor(Qt.CursorShape.SizeFDiagCursor)
|
||||||
|
elif edges in (
|
||||||
|
Qt.Edge.LeftEdge | Qt.Edge.BottomEdge,
|
||||||
|
Qt.Edge.RightEdge | Qt.Edge.TopEdge,
|
||||||
|
):
|
||||||
|
self.setCursor(Qt.CursorShape.SizeBDiagCursor)
|
||||||
|
elif edges in (Qt.Edge.LeftEdge, Qt.Edge.RightEdge):
|
||||||
|
self.setCursor(Qt.CursorShape.SizeHorCursor)
|
||||||
|
elif edges in (Qt.Edge.TopEdge, Qt.Edge.BottomEdge):
|
||||||
|
self.setCursor(Qt.CursorShape.SizeVerCursor)
|
||||||
|
else:
|
||||||
|
self.unsetCursor()
|
||||||
|
super().mouseMoveEvent(event)
|
||||||
|
|
||||||
|
def mousePressEvent(self, event: QMouseEvent) -> None: # noqa: N802 - Qt API
|
||||||
|
if event.button() == Qt.MouseButton.LeftButton:
|
||||||
|
handle = self.window().windowHandle()
|
||||||
|
if handle is not None:
|
||||||
|
edges = self._resize_edges(event.position())
|
||||||
|
if edges and handle.startSystemResize(edges):
|
||||||
|
event.accept()
|
||||||
|
return
|
||||||
|
if handle.startSystemMove():
|
||||||
|
event.accept()
|
||||||
|
return
|
||||||
|
super().mousePressEvent(event)
|
||||||
|
|
||||||
|
|
||||||
class _PasswordField(QFrame):
|
class _PasswordField(QFrame):
|
||||||
"""Keep the grouped password control visibly focused for keyboard users."""
|
"""Keep the grouped password control visibly focused for keyboard users."""
|
||||||
@@ -318,25 +498,48 @@ class LoginWindow(QMainWindow):
|
|||||||
|
|
||||||
self.setWindowTitle("甄养堂 · 医生工作站 - 甄养堂医生工作站")
|
self.setWindowTitle("甄养堂 · 医生工作站 - 甄养堂医生工作站")
|
||||||
self.setWindowIcon(self._window_icon())
|
self.setWindowIcon(self._window_icon())
|
||||||
|
self.setWindowFlag(Qt.WindowType.FramelessWindowHint, True)
|
||||||
|
self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, True)
|
||||||
|
self.setStyleSheet("QMainWindow { background: transparent; }")
|
||||||
self.setMinimumSize(860, 590)
|
self.setMinimumSize(860, 590)
|
||||||
self.resize(1280, 800)
|
self.resize(1280, 800)
|
||||||
|
|
||||||
canvas = QWidget()
|
canvas = _LoginWindowShell(self)
|
||||||
canvas.setObjectName("LoginCanvas")
|
canvas.setObjectName("LoginCanvas")
|
||||||
canvas.setStyleSheet(
|
canvas.setStyleSheet(
|
||||||
"""
|
"""
|
||||||
QWidget#LoginCanvas {
|
QWidget#LoginCanvas {
|
||||||
color: #1A1C1F;
|
color: #1A1C1F;
|
||||||
background-color: #F4F6FA;
|
background-color: transparent;
|
||||||
font-size: 16px;
|
font-size: 16px;
|
||||||
}
|
}
|
||||||
|
QToolButton#LoginWindowControl {
|
||||||
|
background: transparent;
|
||||||
|
border: 1px solid transparent;
|
||||||
|
border-radius: 9px;
|
||||||
|
}
|
||||||
|
QToolButton#LoginWindowControl:hover {
|
||||||
|
background-color: #E2ECEA;
|
||||||
|
border-color: #C7DCD8;
|
||||||
|
}
|
||||||
|
QToolButton#LoginWindowControl:pressed {
|
||||||
|
background-color: #D6E4E1;
|
||||||
|
}
|
||||||
|
QToolButton#LoginWindowControl[windowControl="close"]:hover {
|
||||||
|
background-color: #D63F4F;
|
||||||
|
border-color: #D63F4F;
|
||||||
|
}
|
||||||
|
QToolButton#LoginWindowControl[windowControl="close"]:pressed {
|
||||||
|
background-color: #B92E3D;
|
||||||
|
border-color: #B92E3D;
|
||||||
|
}
|
||||||
QWidget#LoginBrandPanel {
|
QWidget#LoginBrandPanel {
|
||||||
background-color: transparent;
|
background-color: transparent;
|
||||||
border: 0;
|
border: 0;
|
||||||
}
|
}
|
||||||
QFrame#LoginCard {
|
QFrame#LoginCard {
|
||||||
background-color: #FFFFFF;
|
background-color: #FFFFFF;
|
||||||
border: 1px solid #EDEDEE;
|
border: 1px solid #D3E1DF;
|
||||||
border-radius: 20px;
|
border-radius: 20px;
|
||||||
}
|
}
|
||||||
QFrame#LoginCard QFrame#SubtleCard {
|
QFrame#LoginCard QFrame#SubtleCard {
|
||||||
@@ -407,22 +610,25 @@ class LoginWindow(QMainWindow):
|
|||||||
padding: 0;
|
padding: 0;
|
||||||
}
|
}
|
||||||
QFrame#LoginCard QPushButton[variant="primary"] {
|
QFrame#LoginCard QPushButton[variant="primary"] {
|
||||||
min-height: 58px;
|
min-height: 54px;
|
||||||
max-height: 58px;
|
max-height: 54px;
|
||||||
color: #FFFFFF;
|
color: #FFFFFF;
|
||||||
background-color: #4F63D9;
|
background-color: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #14968D, stop:1 $ds_accent);
|
||||||
border: 0;
|
border: 1px solid $ds_accent;
|
||||||
border-radius: 12px;
|
border-radius: 12px;
|
||||||
font-size: 18px;
|
font-size: 17px;
|
||||||
font-weight: 500;
|
font-weight: 600;
|
||||||
}
|
}
|
||||||
QFrame#LoginCard QPushButton#ServerSettingsToggle {
|
QFrame#LoginCard QPushButton#ServerSettingsToggle {
|
||||||
min-height: 56px;
|
min-height: 52px;
|
||||||
max-height: 56px;
|
max-height: 52px;
|
||||||
padding: 0;
|
padding: 0;
|
||||||
}
|
}
|
||||||
QFrame#LoginCard QPushButton[variant="primary"]:hover {
|
QFrame#LoginCard QPushButton[variant="primary"]:hover {
|
||||||
background-color: #4156C4;
|
background-color: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #0F8078, stop:1 $ds_accent_hover);
|
||||||
|
}
|
||||||
|
QFrame#LoginCard QPushButton[variant="primary"]:pressed {
|
||||||
|
background-color: $ds_accent_pressed;
|
||||||
}
|
}
|
||||||
QFrame#LoginCard QPushButton[variant="secondary"] {
|
QFrame#LoginCard QPushButton[variant="secondary"] {
|
||||||
color: #1A1C1F;
|
color: #1A1C1F;
|
||||||
@@ -449,6 +655,26 @@ class LoginWindow(QMainWindow):
|
|||||||
self.brand_panel = self._build_brand_panel()
|
self.brand_panel = self._build_brand_panel()
|
||||||
self.login_root.addWidget(self.brand_panel, 60)
|
self.login_root.addWidget(self.brand_panel, 60)
|
||||||
self.login_root.addWidget(self._build_login_area(), 40)
|
self.login_root.addWidget(self._build_login_area(), 40)
|
||||||
|
|
||||||
|
# 悬浮于无边框登录视窗右上角的原生最小化/关闭控件,不占用表单区纵向高度
|
||||||
|
self.window_controls_host = QWidget(canvas)
|
||||||
|
self.window_controls_host.setObjectName("LoginWindowControls")
|
||||||
|
controls_layout = QHBoxLayout(self.window_controls_host)
|
||||||
|
controls_layout.setContentsMargins(0, 0, 0, 0)
|
||||||
|
controls_layout.setSpacing(6)
|
||||||
|
self.minimize_button = _LoginWindowControlButton("minimize", self.window_controls_host)
|
||||||
|
self.minimize_button.setToolTip("最小化")
|
||||||
|
self.minimize_button.setAccessibleName("最小化登录窗口")
|
||||||
|
self.minimize_button.clicked.connect(self.showMinimized)
|
||||||
|
controls_layout.addWidget(self.minimize_button)
|
||||||
|
self.close_button = _LoginWindowControlButton("close", self.window_controls_host)
|
||||||
|
self.close_button.setToolTip("关闭")
|
||||||
|
self.close_button.setAccessibleName("关闭登录窗口")
|
||||||
|
self.close_button.clicked.connect(self.close)
|
||||||
|
controls_layout.addWidget(self.close_button)
|
||||||
|
self.window_controls_host.adjustSize()
|
||||||
|
self.window_controls_host.raise_()
|
||||||
|
|
||||||
self._restore_settings()
|
self._restore_settings()
|
||||||
for widget in (canvas, *canvas.findChildren(QWidget)):
|
for widget in (canvas, *canvas.findChildren(QWidget)):
|
||||||
if widget.styleSheet():
|
if widget.styleSheet():
|
||||||
@@ -478,6 +704,12 @@ class LoginWindow(QMainWindow):
|
|||||||
0, 12 if compact_height else min(104, max(24, (event.size().height() - 694) // 2)), 0, 12
|
0, 12 if compact_height else min(104, max(24, (event.size().height() - 694) // 2)), 0, 12
|
||||||
)
|
)
|
||||||
super().resizeEvent(event)
|
super().resizeEvent(event)
|
||||||
|
if hasattr(self, "window_controls_host"):
|
||||||
|
self.window_controls_host.move(
|
||||||
|
max(12, self.width() - self.window_controls_host.width() - 16),
|
||||||
|
14,
|
||||||
|
)
|
||||||
|
self.window_controls_host.raise_()
|
||||||
|
|
||||||
def _build_brand_panel(self) -> QWidget:
|
def _build_brand_panel(self) -> QWidget:
|
||||||
panel = _BrandPanel()
|
panel = _BrandPanel()
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -24,7 +24,7 @@ from PySide6.QtWidgets import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
from .. import motion
|
from .. import motion
|
||||||
from ..design_system import PALETTE
|
from ..design_system import PALETTE
|
||||||
from ..dialogs.prescription import PrescriptionTemplateDialog
|
from ..dialogs.prescription import PrescriptionTemplateDialog
|
||||||
from ..dialogs.prescription_ai import PrescriptionAiReportDialog, can_open_ai_explain
|
from ..dialogs.prescription_ai import PrescriptionAiReportDialog, can_open_ai_explain
|
||||||
from ..filter_disclosure import FilterDisclosure
|
from ..filter_disclosure import FilterDisclosure
|
||||||
@@ -36,6 +36,8 @@ from ..prescription_library_style import (
|
|||||||
library_stylesheet,
|
library_stylesheet,
|
||||||
)
|
)
|
||||||
from ..reception_style import body_family
|
from ..reception_style import body_family
|
||||||
|
from ..state import PatientContextStore
|
||||||
|
from ..visuals.context_bridge_bar import SpatialContextBridgeBar
|
||||||
from ..widgets import (
|
from ..widgets import (
|
||||||
EmptyState,
|
EmptyState,
|
||||||
MessageBanner,
|
MessageBanner,
|
||||||
@@ -120,7 +122,7 @@ def _metric_card(title: str, kind: str = "accent", glyph: str = "layers") -> Met
|
|||||||
icon.setProperty("metricIcon", True)
|
icon.setProperty("metricIcon", True)
|
||||||
icon.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
icon.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||||
icon.setFixedSize(32, 32)
|
icon.setFixedSize(32, 32)
|
||||||
color = PALETTE["accent"] if kind == "accent" else PALETTE["muted"]
|
color = PALETTE["accent"] if kind == "accent" else PALETTE["muted"]
|
||||||
icon.setPixmap(_painted_icon(glyph, color, 25).pixmap(25, 25))
|
icon.setPixmap(_painted_icon(glyph, color, 25).pixmap(25, 25))
|
||||||
card.layout().addWidget(icon)
|
card.layout().addWidget(icon)
|
||||||
return card
|
return card
|
||||||
@@ -153,7 +155,9 @@ class PrescriptionLibraryPage(QWidget):
|
|||||||
self._page_size = 15
|
self._page_size = 15
|
||||||
|
|
||||||
outer = QVBoxLayout(self)
|
outer = QVBoxLayout(self)
|
||||||
|
self._outer_layout = outer
|
||||||
outer.setContentsMargins(28, 16, 26, 8)
|
outer.setContentsMargins(28, 16, 26, 8)
|
||||||
|
self.patient_context_store: PatientContextStore | None = None
|
||||||
self.scroll = QScrollArea()
|
self.scroll = QScrollArea()
|
||||||
self.scroll.setObjectName("PrescriptionLibraryScroll")
|
self.scroll.setObjectName("PrescriptionLibraryScroll")
|
||||||
self.scroll.setWidgetResizable(True)
|
self.scroll.setWidgetResizable(True)
|
||||||
@@ -163,7 +167,7 @@ class PrescriptionLibraryPage(QWidget):
|
|||||||
self.content.setObjectName("PrescriptionLibraryContent")
|
self.content.setObjectName("PrescriptionLibraryContent")
|
||||||
root = QVBoxLayout(self.content)
|
root = QVBoxLayout(self.content)
|
||||||
root.setContentsMargins(0, 0, 0, 0)
|
root.setContentsMargins(0, 0, 0, 0)
|
||||||
root.setSpacing(10)
|
root.setSpacing(10)
|
||||||
self.scroll.setWidget(self.content)
|
self.scroll.setWidget(self.content)
|
||||||
outer.addWidget(self.scroll)
|
outer.addWidget(self.scroll)
|
||||||
header = PageHeader(
|
header = PageHeader(
|
||||||
@@ -188,8 +192,8 @@ class PrescriptionLibraryPage(QWidget):
|
|||||||
header.add_action(self.new_button)
|
header.add_action(self.new_button)
|
||||||
root.addWidget(header)
|
root.addWidget(header)
|
||||||
|
|
||||||
self.metrics_panel = QWidget(self.content)
|
self.metrics_panel = QWidget(self.content)
|
||||||
metrics = QHBoxLayout(self.metrics_panel)
|
metrics = QHBoxLayout(self.metrics_panel)
|
||||||
metrics.setContentsMargins(0, 0, 0, 0)
|
metrics.setContentsMargins(0, 0, 0, 0)
|
||||||
metrics.setSpacing(16)
|
metrics.setSpacing(16)
|
||||||
self.metric_cards = {
|
self.metric_cards = {
|
||||||
@@ -200,7 +204,7 @@ class PrescriptionLibraryPage(QWidget):
|
|||||||
}
|
}
|
||||||
for metric in self.metric_cards.values():
|
for metric in self.metric_cards.values():
|
||||||
metrics.addWidget(metric)
|
metrics.addWidget(metric)
|
||||||
root.addWidget(self.metrics_panel)
|
root.addWidget(self.metrics_panel)
|
||||||
|
|
||||||
self.hint_banner = MessageBanner(parent=self)
|
self.hint_banner = MessageBanner(parent=self)
|
||||||
self.hint_banner.show_message(
|
self.hint_banner.show_message(
|
||||||
@@ -260,10 +264,16 @@ class PrescriptionLibraryPage(QWidget):
|
|||||||
grid.setColumnStretch(1, 1)
|
grid.setColumnStretch(1, 1)
|
||||||
grid.setColumnStretch(2, 1)
|
grid.setColumnStretch(2, 1)
|
||||||
grid.setColumnStretch(3, 1)
|
grid.setColumnStretch(3, 1)
|
||||||
root.addWidget(filters)
|
root.addWidget(filters)
|
||||||
self.filter_disclosure = FilterDisclosure(self, [self.metrics_panel, filters])
|
self.filter_disclosure = FilterDisclosure(self, [self.metrics_panel, filters])
|
||||||
header.add_action(self.filter_disclosure.button)
|
header.add_action(self.filter_disclosure.button)
|
||||||
header.set_compact()
|
header.set_compact()
|
||||||
|
self.spatial_bridge = SpatialContextBridgeBar(
|
||||||
|
"专科经方与协定处方智库 · 支持 AI 配伍解析与快速调取",
|
||||||
|
parent=self.content,
|
||||||
|
)
|
||||||
|
self.spatial_bridge.setVisible(False)
|
||||||
|
root.insertWidget(1, self.spatial_bridge)
|
||||||
|
|
||||||
self.banner = MessageBanner()
|
self.banner = MessageBanner()
|
||||||
root.addWidget(self.banner)
|
root.addWidget(self.banner)
|
||||||
@@ -399,7 +409,7 @@ class PrescriptionLibraryPage(QWidget):
|
|||||||
if hasattr(self, "filter_grid"):
|
if hasattr(self, "filter_grid"):
|
||||||
compact_height = self.height() < 760
|
compact_height = self.height() < 760
|
||||||
self.layout().setContentsMargins(28, 16, 26, 8)
|
self.layout().setContentsMargins(28, 16, 26, 8)
|
||||||
self.content.layout().setSpacing(8 if compact_height else 10)
|
self.content.layout().setSpacing(8 if compact_height else 10)
|
||||||
self._reflow_filters()
|
self._reflow_filters()
|
||||||
|
|
||||||
def _reflow_filters(self) -> None:
|
def _reflow_filters(self) -> None:
|
||||||
@@ -544,7 +554,7 @@ class PrescriptionLibraryPage(QWidget):
|
|||||||
|
|
||||||
name_item = self.table.item(row_index, 1)
|
name_item = self.table.item(row_index, 1)
|
||||||
if name_item is not None:
|
if name_item is not None:
|
||||||
name_item.setForeground(QColor(PALETTE["heading"]))
|
name_item.setForeground(QColor(PALETTE["heading"]))
|
||||||
font = name_item.font()
|
font = name_item.font()
|
||||||
font.setWeight(QFont.Weight.Medium)
|
font.setWeight(QFont.Weight.Medium)
|
||||||
name_item.setFont(font)
|
name_item.setFont(font)
|
||||||
@@ -671,6 +681,16 @@ class PrescriptionLibraryPage(QWidget):
|
|||||||
role_ids = [role_ids]
|
role_ids = [role_ids]
|
||||||
return any(str(role) in {"0", "3"} for role in role_ids)
|
return any(str(role) in {"0", "3"} for role in role_ids)
|
||||||
|
|
||||||
|
def set_patient_context_store(self, store: PatientContextStore) -> None:
|
||||||
|
self.patient_context_store = store
|
||||||
|
self._outer_layout.setContentsMargins(2, 2, 2, 4)
|
||||||
|
self.header.setVisible(False)
|
||||||
|
self.spatial_bridge.bind_store(store)
|
||||||
|
if has_permission(self.permissions, 'wcf.prescription/add'):
|
||||||
|
self.spatial_bridge.add_action_widget(self.new_button)
|
||||||
|
self.spatial_bridge.add_action_widget(self.filter_disclosure.button)
|
||||||
|
self.spatial_bridge.setVisible(True)
|
||||||
|
|
||||||
def _new_template(self) -> None:
|
def _new_template(self) -> None:
|
||||||
if not has_permission(self.permissions, "wcf.prescription/add"):
|
if not has_permission(self.permissions, "wcf.prescription/add"):
|
||||||
return
|
return
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -92,7 +92,10 @@ from ..filter_disclosure import FilterDisclosure
|
|||||||
from ..reception_style import body_family, heading_family, number_family
|
from ..reception_style import body_family, heading_family, number_family
|
||||||
from ..reception_workspace import RECEPTION_WORKSPACE_QSS, ReceptionWorkbench
|
from ..reception_workspace import RECEPTION_WORKSPACE_QSS, ReceptionWorkbench
|
||||||
from ..report_provenance import report_provenance_lines
|
from ..report_provenance import report_provenance_lines
|
||||||
|
from ..state import PatientContextStore
|
||||||
from ..theme import mark_business_dialog
|
from ..theme import mark_business_dialog
|
||||||
|
from ..viewmodels.cockpit_vm import derive_cockpit_snapshot
|
||||||
|
from ..visuals.reception_cockpit import ReceptionDigitalTwinCockpit
|
||||||
from ..widgets import (
|
from ..widgets import (
|
||||||
EmptyState,
|
EmptyState,
|
||||||
MessageBanner,
|
MessageBanner,
|
||||||
@@ -116,8 +119,8 @@ STATUS_TEXT = {1: "待接诊", 2: "已取消", 3: "已完成", 4: "已过号"}
|
|||||||
RECEPTION_STATUSES = {1, 4}
|
RECEPTION_STATUSES = {1, 4}
|
||||||
NOTE_LIMIT = 500
|
NOTE_LIMIT = 500
|
||||||
MAX_NOTE_MEDIA = 99
|
MAX_NOTE_MEDIA = 99
|
||||||
AI_ANALYSIS_MODELS = ("qwen", "openai")
|
AI_ANALYSIS_MODELS = ("qwen", "openai", "doubao")
|
||||||
AI_ANALYSIS_MODEL_LABELS = {"qwen": "千问", "openai": "OpenAI"}
|
AI_ANALYSIS_MODEL_LABELS = {"qwen": "千问", "openai": "OpenAI", "doubao": "豆包"}
|
||||||
_ASYNC_REQUEST_CANCELLED = object()
|
_ASYNC_REQUEST_CANCELLED = object()
|
||||||
_ASYNC_REQUEST_DEFERRED = object()
|
_ASYNC_REQUEST_DEFERRED = object()
|
||||||
_AI_AUTOMATIC_GENERATION_SETTLE_SECONDS = 0.25
|
_AI_AUTOMATIC_GENERATION_SETTLE_SECONDS = 0.25
|
||||||
@@ -1177,13 +1180,47 @@ QWidget#ReceptionPage QPushButton#ReceptionHistoryButton,
|
|||||||
QWidget#ReceptionPage QPushButton#ReceptionImButton,
|
QWidget#ReceptionPage QPushButton#ReceptionImButton,
|
||||||
QWidget#ReceptionPage QPushButton#ReceptionMoreButton,
|
QWidget#ReceptionPage QPushButton#ReceptionMoreButton,
|
||||||
QWidget#ReceptionPage QPushButton#ReceptionCompleteButton {
|
QWidget#ReceptionPage QPushButton#ReceptionCompleteButton {
|
||||||
min-height: 38px;
|
min-height: 36px;
|
||||||
max-height: 38px;
|
max-height: 36px;
|
||||||
padding: 0 12px;
|
padding: 0 13px;
|
||||||
font-size: 13px;
|
font-size: 13px;
|
||||||
border-radius: 5px;
|
font-weight: 500;
|
||||||
|
border-radius: 8px;
|
||||||
|
}
|
||||||
|
QWidget#ReceptionPage QPushButton#ReceptionNotifyButton:enabled,
|
||||||
|
QWidget#ReceptionPage QPushButton#ReceptionHistoryButton:enabled,
|
||||||
|
QWidget#ReceptionPage QPushButton#ReceptionMoreButton:enabled {
|
||||||
|
color: #16302E;
|
||||||
|
background-color: #FFFFFF;
|
||||||
|
border: 1px solid #C6D8D5;
|
||||||
|
}
|
||||||
|
QWidget#ReceptionPage QPushButton#ReceptionNotifyButton:enabled:hover,
|
||||||
|
QWidget#ReceptionPage QPushButton#ReceptionHistoryButton:enabled:hover,
|
||||||
|
QWidget#ReceptionPage QPushButton#ReceptionMoreButton:enabled:hover {
|
||||||
|
color: #0B6E68;
|
||||||
|
background-color: #EAF6F4;
|
||||||
|
border-color: #8FC8C0;
|
||||||
|
}
|
||||||
|
QWidget#ReceptionPage QPushButton#ReceptionNotifyButton:enabled:pressed,
|
||||||
|
QWidget#ReceptionPage QPushButton#ReceptionHistoryButton:enabled:pressed,
|
||||||
|
QWidget#ReceptionPage QPushButton#ReceptionMoreButton:enabled:pressed {
|
||||||
|
background-color: #D7EDE9;
|
||||||
|
border-color: #0B6E68;
|
||||||
|
}
|
||||||
|
QWidget#ReceptionPage QPushButton#ReceptionCompleteButton:enabled {
|
||||||
|
color: #C93B4E;
|
||||||
|
background-color: #FFF6F7;
|
||||||
|
border: 1px solid #F0BDC5;
|
||||||
|
}
|
||||||
|
QWidget#ReceptionPage QPushButton#ReceptionCompleteButton:enabled:hover {
|
||||||
|
color: #B42C3F;
|
||||||
|
background-color: #FDE8EB;
|
||||||
|
border-color: #DF8F9C;
|
||||||
|
}
|
||||||
|
QWidget#ReceptionPage QPushButton#ReceptionCompleteButton:enabled:pressed {
|
||||||
|
background-color: #FAD6DC;
|
||||||
|
border-color: #C93B4E;
|
||||||
}
|
}
|
||||||
QWidget#ReceptionPage QPushButton#ReceptionCompleteButton:enabled { background-color: #FFFFFF; }
|
|
||||||
QWidget#ReceptionPage QPushButton#ReceptionMoreButton { padding: 0 6px; }
|
QWidget#ReceptionPage QPushButton#ReceptionMoreButton { padding: 0 6px; }
|
||||||
QWidget#ReceptionPage QTabBar#ReceptionDetailTabs {
|
QWidget#ReceptionPage QTabBar#ReceptionDetailTabs {
|
||||||
border-top-left-radius: 0;
|
border-top-left-radius: 0;
|
||||||
@@ -2098,7 +2135,7 @@ def _analysis_value(payload: Mapping[str, Any], key: str) -> Any:
|
|||||||
|
|
||||||
|
|
||||||
def _patient_report_model(payload: Mapping[str, Any]) -> str:
|
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(
|
raw = str(
|
||||||
payload.get("model_key")
|
payload.get("model_key")
|
||||||
@@ -2110,9 +2147,21 @@ def _patient_report_model(payload: Mapping[str, Any]) -> str:
|
|||||||
return "qwen"
|
return "qwen"
|
||||||
if raw in {"openai", "gpt"} or raw.startswith("gpt"):
|
if raw in {"openai", "gpt"} or raw.startswith("gpt"):
|
||||||
return "openai"
|
return "openai"
|
||||||
|
if raw in {"doubao", "ark", "volcengine"} or "doubao" in raw:
|
||||||
|
return "doubao"
|
||||||
return ""
|
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:
|
def _normalize_patient_report(payload: Mapping[str, Any]) -> dict[str, Any] | None:
|
||||||
"""Flatten a saved server snapshot into the existing structured card contract."""
|
"""Flatten a saved server snapshot into the existing structured card contract."""
|
||||||
|
|
||||||
@@ -2407,15 +2456,21 @@ class _ReceptionCompleteButton(QPushButton):
|
|||||||
super().__init__("结束问诊", parent)
|
super().__init__("结束问诊", parent)
|
||||||
self.setObjectName("ReceptionCompleteButton")
|
self.setObjectName("ReceptionCompleteButton")
|
||||||
self.setCursor(Qt.CursorShape.PointingHandCursor)
|
self.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||||
|
self.setIcon(icons.icon("check_circle", "danger", 15))
|
||||||
|
self.setIconSize(QSize(15, 15))
|
||||||
|
|
||||||
def changeEvent(self, event: QEvent) -> None: # noqa: N802 - Qt API
|
def changeEvent(self, event: QEvent) -> None: # noqa: N802 - Qt API
|
||||||
super().changeEvent(event)
|
super().changeEvent(event)
|
||||||
if event.type() == QEvent.Type.EnabledChange:
|
if event.type() == QEvent.Type.EnabledChange:
|
||||||
|
enabled = self.isEnabled()
|
||||||
self.setCursor(
|
self.setCursor(
|
||||||
Qt.CursorShape.PointingHandCursor
|
Qt.CursorShape.PointingHandCursor
|
||||||
if self.isEnabled()
|
if enabled
|
||||||
else Qt.CursorShape.ArrowCursor
|
else Qt.CursorShape.ArrowCursor
|
||||||
)
|
)
|
||||||
|
self.setIcon(
|
||||||
|
icons.icon("check_circle", "danger" if enabled else "disabled", 15)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class _NoteAttachmentPreview(QPushButton):
|
class _NoteAttachmentPreview(QPushButton):
|
||||||
@@ -2525,18 +2580,18 @@ class _ClinicalInfoPanel(QWidget):
|
|||||||
"""Let the clinical history use the full reading column."""
|
"""Let the clinical history use the full reading column."""
|
||||||
|
|
||||||
|
|
||||||
class _ClinicalPageStack(QStackedWidget):
|
class _ClinicalPageStack(QStackedWidget):
|
||||||
"""Size the clinical card from its current page, including after a resize."""
|
"""Size the clinical card from its current page, including after a resize."""
|
||||||
|
|
||||||
def sizeHint(self) -> QSize: # noqa: N802 - Qt virtual
|
def sizeHint(self) -> QSize: # noqa: N802 - Qt virtual
|
||||||
page = self.currentWidget()
|
page = self.currentWidget()
|
||||||
return page.sizeHint() if page is not None else super().sizeHint()
|
return page.sizeHint() if page is not None else super().sizeHint()
|
||||||
|
|
||||||
def minimumSizeHint(self) -> QSize: # noqa: N802 - Qt virtual
|
def minimumSizeHint(self) -> QSize: # noqa: N802 - Qt virtual
|
||||||
page = self.currentWidget()
|
page = self.currentWidget()
|
||||||
return page.minimumSizeHint() if page is not None else super().minimumSizeHint()
|
return page.minimumSizeHint() if page is not None else super().minimumSizeHint()
|
||||||
|
|
||||||
|
|
||||||
class _ReceptionAiPanels(QWidget):
|
class _ReceptionAiPanels(QWidget):
|
||||||
"""Give both AI cards reading space before switching to a vertical layout."""
|
"""Give both AI cards reading space before switching to a vertical layout."""
|
||||||
|
|
||||||
@@ -2554,16 +2609,16 @@ class _ReceptionAiPanels(QWidget):
|
|||||||
if needed > 0 and (self.minimumHeight() != needed or self.maximumHeight() != needed):
|
if needed > 0 and (self.minimumHeight() != needed or self.maximumHeight() != needed):
|
||||||
self.setFixedHeight(needed)
|
self.setFixedHeight(needed)
|
||||||
self.updateGeometry()
|
self.updateGeometry()
|
||||||
|
|
||||||
def resizeEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual
|
def resizeEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual
|
||||||
super().resizeEvent(event)
|
super().resizeEvent(event)
|
||||||
layout = self.layout()
|
layout = self.layout()
|
||||||
if not isinstance(layout, QBoxLayout):
|
if not isinstance(layout, QBoxLayout):
|
||||||
return
|
return
|
||||||
stacked = self.width() < 800
|
stacked = self.width() < 800
|
||||||
direction = QBoxLayout.Direction.TopToBottom if stacked else QBoxLayout.Direction.LeftToRight
|
direction = QBoxLayout.Direction.TopToBottom if stacked else QBoxLayout.Direction.LeftToRight
|
||||||
if layout.direction() != direction:
|
if layout.direction() != direction:
|
||||||
layout.setDirection(direction)
|
layout.setDirection(direction)
|
||||||
layout.setStretch(0, 0 if stacked else 17)
|
layout.setStretch(0, 0 if stacked else 17)
|
||||||
layout.setStretch(1, 0 if stacked else 23)
|
layout.setStretch(1, 0 if stacked else 23)
|
||||||
self.updateGeometry()
|
self.updateGeometry()
|
||||||
@@ -3193,7 +3248,7 @@ class _ReceptionAiAnalysisDialog(QDialog):
|
|||||||
title = QLabel("患者级 AI 诊断报告", header)
|
title = QLabel("患者级 AI 诊断报告", header)
|
||||||
title.setObjectName("ReceptionAiAnalysisDialogTitle")
|
title.setObjectName("ReceptionAiAnalysisDialogTitle")
|
||||||
title.setProperty("dialogRole", "title")
|
title.setProperty("dialogRole", "title")
|
||||||
subtitle = QLabel("查看千问与 OpenAI 的历次患者报告快照", header)
|
subtitle = QLabel("查看千问、OpenAI 与豆包的历次患者报告快照", header)
|
||||||
subtitle.setObjectName("ReceptionAiAnalysisDialogSubtitle")
|
subtitle.setObjectName("ReceptionAiAnalysisDialogSubtitle")
|
||||||
subtitle.setProperty("dialogRole", "subtitle")
|
subtitle.setProperty("dialogRole", "subtitle")
|
||||||
heading.addWidget(title)
|
heading.addWidget(title)
|
||||||
@@ -3954,8 +4009,8 @@ class ReceptionDailyRecordsPanel(DailyRecordPanel):
|
|||||||
self.matrix.setAccessibleName("患者日常记录矩阵")
|
self.matrix.setAccessibleName("患者日常记录矩阵")
|
||||||
self.matrix.setMinimumHeight(330)
|
self.matrix.setMinimumHeight(330)
|
||||||
self.matrix.setMaximumHeight(460)
|
self.matrix.setMaximumHeight(460)
|
||||||
self.matrix.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
|
self.matrix.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
|
||||||
self._sizing_daily_columns = False
|
self._sizing_daily_columns = False
|
||||||
self.matrix.viewport().installEventFilter(self)
|
self.matrix.viewport().installEventFilter(self)
|
||||||
|
|
||||||
for object_name in ("DiagnosisTrendCard", "DiagnosisTodoCard"):
|
for object_name in ("DiagnosisTrendCard", "DiagnosisTodoCard"):
|
||||||
@@ -3964,37 +4019,37 @@ class ReceptionDailyRecordsPanel(DailyRecordPanel):
|
|||||||
child.hide()
|
child.hide()
|
||||||
self.clear_with_message("选择患者后加载最近 7 天日常记录。")
|
self.clear_with_message("选择患者后加载最近 7 天日常记录。")
|
||||||
|
|
||||||
def eventFilter(self, watched: Any, event: Any) -> bool: # noqa: N802 - Qt virtual
|
def eventFilter(self, watched: Any, event: Any) -> bool: # noqa: N802 - Qt virtual
|
||||||
if (
|
if (
|
||||||
watched is self.matrix.viewport()
|
watched is self.matrix.viewport()
|
||||||
and event.type() == QEvent.Type.Resize
|
and event.type() == QEvent.Type.Resize
|
||||||
and event.size().width() != event.oldSize().width()
|
and event.size().width() != event.oldSize().width()
|
||||||
):
|
):
|
||||||
self._fit_daily_columns()
|
self._fit_daily_columns()
|
||||||
return super().eventFilter(watched, event)
|
return super().eventFilter(watched, event)
|
||||||
|
|
||||||
def _fit_daily_columns(self) -> None:
|
def _fit_daily_columns(self) -> None:
|
||||||
count = self.matrix.columnCount() - 1
|
count = self.matrix.columnCount() - 1
|
||||||
if count < 1 or self._sizing_daily_columns:
|
if count < 1 or self._sizing_daily_columns:
|
||||||
return
|
return
|
||||||
self._sizing_daily_columns = True
|
self._sizing_daily_columns = True
|
||||||
try:
|
try:
|
||||||
header = self.matrix.horizontalHeader()
|
header = self.matrix.horizontalHeader()
|
||||||
header.setSectionResizeMode(QHeaderView.ResizeMode.Interactive)
|
header.setSectionResizeMode(QHeaderView.ResizeMode.Interactive)
|
||||||
header.setMinimumSectionSize(96)
|
header.setMinimumSectionSize(96)
|
||||||
available = max(0, self.matrix.viewport().width() - 132)
|
available = max(0, self.matrix.viewport().width() - 132)
|
||||||
width, remainder = divmod(available, count)
|
width, remainder = divmod(available, count)
|
||||||
widths = [max(96, width + (index < remainder)) for index in range(count)]
|
widths = [max(96, width + (index < remainder)) for index in range(count)]
|
||||||
changed = False
|
changed = False
|
||||||
for column, target in enumerate([132, *widths]):
|
for column, target in enumerate([132, *widths]):
|
||||||
if self.matrix.columnWidth(column) != target:
|
if self.matrix.columnWidth(column) != target:
|
||||||
self.matrix.setColumnWidth(column, target)
|
self.matrix.setColumnWidth(column, target)
|
||||||
changed = True
|
changed = True
|
||||||
if changed:
|
if changed:
|
||||||
self.matrix.resizeRowsToContents()
|
self.matrix.resizeRowsToContents()
|
||||||
finally:
|
finally:
|
||||||
self._sizing_daily_columns = False
|
self._sizing_daily_columns = False
|
||||||
|
|
||||||
def set_patient_age(self, age: Any) -> None:
|
def set_patient_age(self, age: Any) -> None:
|
||||||
parsed = _as_int(age, None)
|
parsed = _as_int(age, None)
|
||||||
self._patient_age = parsed if parsed is not None and parsed >= 0 else None
|
self._patient_age = parsed if parsed is not None and parsed >= 0 else None
|
||||||
@@ -4100,6 +4155,7 @@ class ReceptionPage(QWidget):
|
|||||||
"""Run the complete same-day reception workflow without blocking Qt."""
|
"""Run the complete same-day reception workflow without blocking Qt."""
|
||||||
|
|
||||||
video_requested = Signal(dict)
|
video_requested = Signal(dict)
|
||||||
|
cockpit_snapshot_updated = Signal(object)
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
@@ -4213,8 +4269,48 @@ class ReceptionPage(QWidget):
|
|||||||
)
|
)
|
||||||
|
|
||||||
root = QVBoxLayout(self)
|
root = QVBoxLayout(self)
|
||||||
|
self._root_layout = root
|
||||||
root.setContentsMargins(12, 16, 12, 12)
|
root.setContentsMargins(12, 16, 12, 12)
|
||||||
root.setSpacing(0)
|
root.setSpacing(0)
|
||||||
|
self.patient_context_store: PatientContextStore | None = None
|
||||||
|
self._workspace_mode = "chart"
|
||||||
|
self._latest_daily_blood: list[Any] = []
|
||||||
|
|
||||||
|
self.view_mode_stack = QStackedWidget(self)
|
||||||
|
self.view_mode_stack.setObjectName("ReceptionViewModeStack")
|
||||||
|
|
||||||
|
chart_page = QWidget(self.view_mode_stack)
|
||||||
|
chart_page.setObjectName("ReceptionChartModePage")
|
||||||
|
chart_layout = QVBoxLayout(chart_page)
|
||||||
|
chart_layout.setContentsMargins(0, 0, 0, 0)
|
||||||
|
chart_layout.setSpacing(8)
|
||||||
|
|
||||||
|
self._return_to_cockpit_bar = QFrame(chart_page)
|
||||||
|
self._return_to_cockpit_bar.setObjectName("ReceptionReturnCockpitBar")
|
||||||
|
self._return_to_cockpit_bar.setFixedHeight(38)
|
||||||
|
self._return_to_cockpit_bar.setVisible(False)
|
||||||
|
self._return_to_cockpit_bar.setStyleSheet(
|
||||||
|
"QFrame#ReceptionReturnCockpitBar {"
|
||||||
|
" background-color: #FFFFFF; border: 1px solid #DCE7E4; border-radius: 19px; }"
|
||||||
|
)
|
||||||
|
ret_layout = QHBoxLayout(self._return_to_cockpit_bar)
|
||||||
|
ret_layout.setContentsMargins(10, 4, 14, 4)
|
||||||
|
ret_layout.setSpacing(10)
|
||||||
|
back_cockpit_btn = QPushButton("← 返回三焦全息驾驶舱", self._return_to_cockpit_bar)
|
||||||
|
back_cockpit_btn.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||||
|
back_cockpit_btn.setStyleSheet(
|
||||||
|
"QPushButton { background-color: #0E6F5C; color: #FFFFFF; border: 0;"
|
||||||
|
" border-radius: 14px; padding: 0 14px; min-height: 28px; max-height: 28px;"
|
||||||
|
" font-size: 12px; font-weight: 600; }"
|
||||||
|
"QPushButton:hover { background-color: #0A5949; }"
|
||||||
|
)
|
||||||
|
back_cockpit_btn.clicked.connect(lambda: self.set_workspace_mode("cockpit"))
|
||||||
|
ret_layout.addWidget(back_cockpit_btn)
|
||||||
|
ret_hint = QLabel("当前处于「六维结构化病历与附件归档」详细视图", self._return_to_cockpit_bar)
|
||||||
|
ret_hint.setStyleSheet("color: #5E7471; font-size: 12px; background: transparent; border: 0;")
|
||||||
|
ret_layout.addWidget(ret_hint)
|
||||||
|
ret_layout.addStretch(1)
|
||||||
|
chart_layout.addWidget(self._return_to_cockpit_bar)
|
||||||
|
|
||||||
splitter = QSplitter(Qt.Orientation.Horizontal)
|
splitter = QSplitter(Qt.Orientation.Horizontal)
|
||||||
splitter.setChildrenCollapsible(False)
|
splitter.setChildrenCollapsible(False)
|
||||||
@@ -4226,7 +4322,23 @@ class ReceptionPage(QWidget):
|
|||||||
splitter.setStretchFactor(1, 1)
|
splitter.setStretchFactor(1, 1)
|
||||||
splitter.setHandleWidth(12)
|
splitter.setHandleWidth(12)
|
||||||
splitter.setSizes([286, 1185])
|
splitter.setSizes([286, 1185])
|
||||||
root.addWidget(splitter, 1)
|
chart_layout.addWidget(splitter, 1)
|
||||||
|
|
||||||
|
self.view_mode_stack.addWidget(chart_page)
|
||||||
|
self._chart_mode_page = chart_page
|
||||||
|
|
||||||
|
self.cockpit_view = ReceptionDigitalTwinCockpit(self.view_mode_stack)
|
||||||
|
self.cockpit_view.appointment_selected.connect(self._select_record_from_cockpit)
|
||||||
|
self.cockpit_view.filter_status_requested.connect(self._set_queue_filter)
|
||||||
|
self.cockpit_view.refresh_requested.connect(self._refresh_workspace)
|
||||||
|
self.cockpit_view.start_video_requested.connect(self._request_video)
|
||||||
|
self.cockpit_view.edit_diagnosis_requested.connect(self._edit_diagnosis)
|
||||||
|
self.cockpit_view.notify_assistant_requested.connect(self._notify_assistant)
|
||||||
|
self.cockpit_view.complete_visit_requested.connect(self._complete_appointment)
|
||||||
|
self.cockpit_view.open_chart_tab_requested.connect(self._open_structured_chart_tab)
|
||||||
|
self.view_mode_stack.addWidget(self.cockpit_view)
|
||||||
|
|
||||||
|
root.addWidget(self.view_mode_stack, 1)
|
||||||
|
|
||||||
self.poll_timer = QTimer(self)
|
self.poll_timer = QTimer(self)
|
||||||
self.poll_timer.setInterval(5_000)
|
self.poll_timer.setInterval(5_000)
|
||||||
@@ -4246,6 +4358,111 @@ class ReceptionPage(QWidget):
|
|||||||
if panel.minimumWidth() != width:
|
if panel.minimumWidth() != width:
|
||||||
panel.setFixedWidth(width)
|
panel.setFixedWidth(width)
|
||||||
|
|
||||||
|
def set_patient_context_store(self, store: PatientContextStore) -> None:
|
||||||
|
"""Attach the Spatial Shell context store and default to Digital Twin Cockpit."""
|
||||||
|
|
||||||
|
self.patient_context_store = store
|
||||||
|
self._root_layout.setContentsMargins(0, 2, 0, 2)
|
||||||
|
self._queue_filter_status = None
|
||||||
|
for st_key, btn in self._queue_filter_buttons.items():
|
||||||
|
btn.setChecked(st_key is None)
|
||||||
|
self._sync_queue_filter_summary()
|
||||||
|
self.set_workspace_mode("cockpit")
|
||||||
|
self._sync_cockpit_and_context()
|
||||||
|
|
||||||
|
def set_workspace_mode(self, mode: str) -> None:
|
||||||
|
normalized = "cockpit" if str(mode).strip().lower() == "cockpit" else "chart"
|
||||||
|
self._workspace_mode = normalized
|
||||||
|
if normalized == "cockpit":
|
||||||
|
self.view_mode_stack.setCurrentWidget(self.cockpit_view)
|
||||||
|
self._return_to_cockpit_bar.setVisible(False)
|
||||||
|
else:
|
||||||
|
self.view_mode_stack.setCurrentWidget(self._chart_mode_page)
|
||||||
|
self._return_to_cockpit_bar.setVisible(self.patient_context_store is not None)
|
||||||
|
if self.patient_context_store is not None:
|
||||||
|
self.patient_context_store.set_cockpit_mode(normalized)
|
||||||
|
|
||||||
|
def _open_structured_chart_tab(self, tab_index: int = 0) -> None:
|
||||||
|
self.set_workspace_mode("chart")
|
||||||
|
if hasattr(self, "detail_tabs") and 0 <= tab_index < self.detail_tabs.count():
|
||||||
|
self.detail_tabs.setCurrentIndex(tab_index)
|
||||||
|
|
||||||
|
def _select_record_from_cockpit(self, record: Any) -> None:
|
||||||
|
rec_id = _record_id(record)
|
||||||
|
if rec_id is not None:
|
||||||
|
for idx in range(self.queue_list.count()):
|
||||||
|
item = self.queue_list.item(idx)
|
||||||
|
item_rec = item.data(Qt.ItemDataRole.UserRole)
|
||||||
|
if _same_id(_record_id(item_rec), rec_id):
|
||||||
|
if self.queue_list.currentRow() != idx:
|
||||||
|
self.queue_list.setCurrentRow(idx)
|
||||||
|
else:
|
||||||
|
self._select_record(record)
|
||||||
|
return
|
||||||
|
self._select_record(record)
|
||||||
|
|
||||||
|
def select_cockpit_ai_model(self, model_key: str) -> None:
|
||||||
|
if model_key in AI_ANALYSIS_MODELS:
|
||||||
|
self._ai_analysis_active_model = model_key
|
||||||
|
if hasattr(self, "ai_analysis_model_selector"):
|
||||||
|
idx = self.ai_analysis_model_selector.findData(model_key)
|
||||||
|
if idx >= 0 and self.ai_analysis_model_selector.currentIndex() != idx:
|
||||||
|
self.ai_analysis_model_selector.setCurrentIndex(idx)
|
||||||
|
self._sync_ai_analysis_view()
|
||||||
|
self._sync_cockpit_and_context()
|
||||||
|
|
||||||
|
def _sync_cockpit_and_context(self) -> None:
|
||||||
|
"""Synchronize the 3-column Digital Twin Cockpit and global PatientContextStore."""
|
||||||
|
|
||||||
|
if not hasattr(self, "cockpit_view"):
|
||||||
|
return
|
||||||
|
detail = self._selected_detail or {}
|
||||||
|
appointment = get_value(detail, "appointment", None) or self._selected_record or {}
|
||||||
|
patient = get_value(detail, "patient", None) or {}
|
||||||
|
diagnosis = get_value(detail, "diagnosis", None) or {}
|
||||||
|
|
||||||
|
self.cockpit_view.set_queue_records(
|
||||||
|
self._queue_records,
|
||||||
|
self._selected_appointment_id,
|
||||||
|
active_filter_status=self._queue_filter_status,
|
||||||
|
queue_date=self._queue_date,
|
||||||
|
)
|
||||||
|
doc_name = display_text(
|
||||||
|
first_value(
|
||||||
|
appointment,
|
||||||
|
"doctor_name",
|
||||||
|
default=first_value(self.current_user, "name", "real_name", default="主诊中医师"),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
asst_name = display_text(first_value(appointment, "assistant_name", default=""), "")
|
||||||
|
self.cockpit_view.set_care_team_context(
|
||||||
|
doctor_name=doc_name,
|
||||||
|
assistant_name=asst_name,
|
||||||
|
can_edit=bool(self._can_edit and self._selected_appointment_id is not None),
|
||||||
|
can_notify=bool(self._selected_appointment_id is not None),
|
||||||
|
can_complete=bool(
|
||||||
|
hasattr(self, "complete_button") and self.complete_button.isEnabled()
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
if self.patient_context_store is not None:
|
||||||
|
if self._selected_appointment_id is not None and appointment:
|
||||||
|
self.patient_context_store.update_from_reception(appointment, patient, diagnosis)
|
||||||
|
elif not self._queue_records:
|
||||||
|
self.patient_context_store.clear()
|
||||||
|
|
||||||
|
ai_payload = self._ai_analysis_payloads.get(self._ai_analysis_active_model)
|
||||||
|
vm = derive_cockpit_snapshot(
|
||||||
|
appointment,
|
||||||
|
patient,
|
||||||
|
diagnosis,
|
||||||
|
daily_records=self._latest_daily_blood,
|
||||||
|
ai_payload=ai_payload,
|
||||||
|
active_ai_model=self._ai_analysis_active_model,
|
||||||
|
)
|
||||||
|
self.cockpit_view.set_snapshot(vm)
|
||||||
|
self.cockpit_snapshot_updated.emit(vm)
|
||||||
|
|
||||||
def _ensure_diagnosis_dialog(self) -> DiagnosisDialog:
|
def _ensure_diagnosis_dialog(self) -> DiagnosisDialog:
|
||||||
dialog = getattr(self, "diagnosis_dialog", None)
|
dialog = getattr(self, "diagnosis_dialog", None)
|
||||||
if dialog is None:
|
if dialog is None:
|
||||||
@@ -4436,7 +4653,7 @@ class ReceptionPage(QWidget):
|
|||||||
actions = QHBoxLayout()
|
actions = QHBoxLayout()
|
||||||
hero.actions_layout = actions
|
hero.actions_layout = actions
|
||||||
actions.setContentsMargins(0, 0, 0, 0)
|
actions.setContentsMargins(0, 0, 0, 0)
|
||||||
actions.setSpacing(14)
|
actions.setSpacing(10)
|
||||||
actions.addStretch(1)
|
actions.addStretch(1)
|
||||||
action_group = QVBoxLayout()
|
action_group = QVBoxLayout()
|
||||||
hero.action_group = action_group
|
hero.action_group = action_group
|
||||||
@@ -4456,14 +4673,20 @@ class ReceptionPage(QWidget):
|
|||||||
self.complete_button.setVisible(self._can_complete)
|
self.complete_button.setVisible(self._can_complete)
|
||||||
self.notify_button = QPushButton("通知医助", hero)
|
self.notify_button = QPushButton("通知医助", hero)
|
||||||
self.notify_button.setObjectName("ReceptionNotifyButton")
|
self.notify_button.setObjectName("ReceptionNotifyButton")
|
||||||
|
self.notify_button.setIcon(icons.icon("notification", "accent", 15))
|
||||||
|
self.notify_button.setIconSize(QSize(15, 15))
|
||||||
self.notify_button.clicked.connect(self._notify_assistant)
|
self.notify_button.clicked.connect(self._notify_assistant)
|
||||||
actions.addWidget(self.notify_button)
|
actions.addWidget(self.notify_button)
|
||||||
self.history_button = QPushButton("查看历史", hero)
|
self.history_button = QPushButton("查看历史", hero)
|
||||||
self.history_button.setObjectName("ReceptionHistoryButton")
|
self.history_button.setObjectName("ReceptionHistoryButton")
|
||||||
|
self.history_button.setIcon(icons.icon("followup", "muted", 15))
|
||||||
|
self.history_button.setIconSize(QSize(15, 15))
|
||||||
self.history_button.clicked.connect(lambda: self.detail_tabs.setCurrentIndex(4))
|
self.history_button.clicked.connect(lambda: self.detail_tabs.setCurrentIndex(4))
|
||||||
actions.addWidget(self.history_button)
|
actions.addWidget(self.history_button)
|
||||||
self.video_button = QPushButton("IM 问诊", hero)
|
self.video_button = QPushButton("IM 问诊", hero)
|
||||||
self.video_button.setObjectName("ReceptionImButton")
|
self.video_button.setObjectName("ReceptionImButton")
|
||||||
|
self.video_button.setIcon(icons.icon("message", "inverse", 15))
|
||||||
|
self.video_button.setIconSize(QSize(15, 15))
|
||||||
self.video_button.setToolTip("打开患者 IM,可发送消息并从会话中发起视频")
|
self.video_button.setToolTip("打开患者 IM,可发送消息并从会话中发起视频")
|
||||||
self.video_button.setProperty("variant", "primary")
|
self.video_button.setProperty("variant", "primary")
|
||||||
self.video_button.clicked.connect(self._request_video)
|
self.video_button.clicked.connect(self._request_video)
|
||||||
@@ -4474,7 +4697,7 @@ class ReceptionPage(QWidget):
|
|||||||
self.more_button.setToolTip("更多操作")
|
self.more_button.setToolTip("更多操作")
|
||||||
self.more_button.setAccessibleName("更多操作")
|
self.more_button.setAccessibleName("更多操作")
|
||||||
self.more_button.setObjectName("ReceptionMoreButton")
|
self.more_button.setObjectName("ReceptionMoreButton")
|
||||||
self.more_button.setFixedWidth(46)
|
self.more_button.setFixedWidth(40)
|
||||||
hero.more_control = self.more_button
|
hero.more_control = self.more_button
|
||||||
more_menu = QMenu(self.more_button)
|
more_menu = QMenu(self.more_button)
|
||||||
edit_action = more_menu.addAction("编辑病历")
|
edit_action = more_menu.addAction("编辑病历")
|
||||||
@@ -4488,7 +4711,7 @@ class ReceptionPage(QWidget):
|
|||||||
consult_action.triggered.connect(self._open_ai_consult)
|
consult_action.triggered.connect(self._open_ai_consult)
|
||||||
self.more_button.setMenu(more_menu)
|
self.more_button.setMenu(more_menu)
|
||||||
actions.addWidget(self.more_button)
|
actions.addWidget(self.more_button)
|
||||||
actions.addSpacing(16)
|
actions.addSpacing(8)
|
||||||
hero.complete_gap = actions.itemAt(actions.count() - 1).spacerItem()
|
hero.complete_gap = actions.itemAt(actions.count() - 1).spacerItem()
|
||||||
actions.addWidget(self.complete_button)
|
actions.addWidget(self.complete_button)
|
||||||
|
|
||||||
@@ -4560,11 +4783,33 @@ class ReceptionPage(QWidget):
|
|||||||
history_card.setObjectName("ReceptionHistoryCard")
|
history_card.setObjectName("ReceptionHistoryCard")
|
||||||
history_layout = QVBoxLayout(history_card)
|
history_layout = QVBoxLayout(history_card)
|
||||||
history_layout.setContentsMargins(0, 0, 0, 0)
|
history_layout.setContentsMargins(0, 0, 0, 0)
|
||||||
history_layout.setSpacing(14)
|
history_layout.setSpacing(11)
|
||||||
|
history_head = QHBoxLayout()
|
||||||
|
history_head.setContentsMargins(0, 0, 0, 0)
|
||||||
|
history_head.setSpacing(8)
|
||||||
history_title = QLabel("病情与用药", history_card)
|
history_title = QLabel("病情与用药", history_card)
|
||||||
history_title.setObjectName("ReceptionCaseHeading")
|
history_title.setObjectName("ReceptionCaseHeading")
|
||||||
history_layout.addWidget(history_title)
|
history_head.addWidget(history_title)
|
||||||
|
history_head.addStretch(1)
|
||||||
|
self.inline_edit_record_button = QPushButton("编辑四诊", history_card)
|
||||||
|
self.inline_edit_record_button.setObjectName("ReceptionInlineAction")
|
||||||
|
self.inline_edit_record_button.setIcon(icons.icon("edit", "accent", 14))
|
||||||
|
self.inline_edit_record_button.setIconSize(QSize(14, 14))
|
||||||
|
self.inline_edit_record_button.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||||
|
self.inline_edit_record_button.setVisible(self._can_edit)
|
||||||
|
self.inline_edit_record_button.clicked.connect(self._edit_diagnosis)
|
||||||
|
history_head.addWidget(self.inline_edit_record_button)
|
||||||
|
self.inline_ai_consult_button = QPushButton("AI 辨证", history_card)
|
||||||
|
self.inline_ai_consult_button.setObjectName("ReceptionInlineAiAction")
|
||||||
|
self.inline_ai_consult_button.setIcon(icons.icon("ai", "gold", 14))
|
||||||
|
self.inline_ai_consult_button.setIconSize(QSize(14, 14))
|
||||||
|
self.inline_ai_consult_button.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||||
|
self.inline_ai_consult_button.setVisible(self._can_ai_assistant)
|
||||||
|
self.inline_ai_consult_button.clicked.connect(self._open_ai_consult)
|
||||||
|
history_head.addWidget(self.inline_ai_consult_button)
|
||||||
|
history_layout.addLayout(history_head)
|
||||||
self.case_labels: dict[str, QLabel] = {}
|
self.case_labels: dict[str, QLabel] = {}
|
||||||
|
self._case_field_frames: dict[str, QFrame] = {}
|
||||||
|
|
||||||
def add_case_field(
|
def add_case_field(
|
||||||
target: QVBoxLayout,
|
target: QVBoxLayout,
|
||||||
@@ -4575,10 +4820,17 @@ class ReceptionPage(QWidget):
|
|||||||
) -> None:
|
) -> None:
|
||||||
field = QFrame(history_card)
|
field = QFrame(history_card)
|
||||||
field.setObjectName("ReceptionCaseField")
|
field.setObjectName("ReceptionCaseField")
|
||||||
|
if key == "chief":
|
||||||
|
field.setProperty("chiefFocus", True)
|
||||||
if stacked:
|
if stacked:
|
||||||
field_layout = QVBoxLayout(field)
|
field_layout = QVBoxLayout(field)
|
||||||
field_layout.setContentsMargins(0, 0, 0, 0)
|
field_layout.setContentsMargins(
|
||||||
field_layout.setSpacing(6)
|
12 if key == "chief" else 0,
|
||||||
|
9 if key == "chief" else 0,
|
||||||
|
12 if key == "chief" else 0,
|
||||||
|
9 if key == "chief" else 6,
|
||||||
|
)
|
||||||
|
field_layout.setSpacing(5)
|
||||||
title_label = QLabel(caption, field)
|
title_label = QLabel(caption, field)
|
||||||
title_label.setProperty("receptionBlockTitle", True)
|
title_label.setProperty("receptionBlockTitle", True)
|
||||||
field_layout.addWidget(title_label)
|
field_layout.addWidget(title_label)
|
||||||
@@ -4587,7 +4839,7 @@ class ReceptionPage(QWidget):
|
|||||||
field_layout.addWidget(value_label)
|
field_layout.addWidget(value_label)
|
||||||
else:
|
else:
|
||||||
field_layout = QHBoxLayout(field)
|
field_layout = QHBoxLayout(field)
|
||||||
field_layout.setContentsMargins(0, 0, 0, 0)
|
field_layout.setContentsMargins(0, 0, 0, 6)
|
||||||
field_layout.setSpacing(10)
|
field_layout.setSpacing(10)
|
||||||
title_label = QLabel(caption, field)
|
title_label = QLabel(caption, field)
|
||||||
title_label.setProperty("receptionInlineCaption", True)
|
title_label.setProperty("receptionInlineCaption", True)
|
||||||
@@ -4599,6 +4851,7 @@ class ReceptionPage(QWidget):
|
|||||||
value_label.setProperty("receptionInlineValue", True)
|
value_label.setProperty("receptionInlineValue", True)
|
||||||
field_layout.addWidget(value_label, 1)
|
field_layout.addWidget(value_label, 1)
|
||||||
self.case_labels[key] = value_label
|
self.case_labels[key] = value_label
|
||||||
|
self._case_field_frames[key] = field
|
||||||
target.addWidget(field)
|
target.addWidget(field)
|
||||||
|
|
||||||
add_case_field(history_layout, "chief", "本次主诉", stacked=True)
|
add_case_field(history_layout, "chief", "本次主诉", stacked=True)
|
||||||
@@ -4641,13 +4894,47 @@ class ReceptionPage(QWidget):
|
|||||||
history_layout.addWidget(lifestyle_field)
|
history_layout.addWidget(lifestyle_field)
|
||||||
|
|
||||||
add_case_field(history_layout, "diet", "饮食习惯")
|
add_case_field(history_layout, "diet", "饮食习惯")
|
||||||
|
|
||||||
|
# W2 Bento 驾驶舱:将未填写的可选病史自动折叠为快捷补录胶囊,消除满屏空白「—」占位行
|
||||||
|
self._missing_fields_host = QFrame(history_card)
|
||||||
|
self._missing_fields_host.setObjectName("ReceptionMissingFieldsBar")
|
||||||
|
missing_outer = QVBoxLayout(self._missing_fields_host)
|
||||||
|
missing_outer.setContentsMargins(0, 4, 0, 0)
|
||||||
|
missing_outer.setSpacing(6)
|
||||||
|
missing_caption = QLabel("待补录病史(点击快捷补录)", self._missing_fields_host)
|
||||||
|
missing_caption.setProperty("receptionInlineCaption", True)
|
||||||
|
missing_outer.addWidget(missing_caption)
|
||||||
|
missing_row = QHBoxLayout()
|
||||||
|
missing_row.setContentsMargins(0, 0, 0, 0)
|
||||||
|
missing_row.setSpacing(6)
|
||||||
|
self._missing_field_pills: dict[str, QPushButton] = {}
|
||||||
|
for key, label in (
|
||||||
|
("course", "+ 患病时长"),
|
||||||
|
("past", "+ 既往史"),
|
||||||
|
("family", "+ 家族史"),
|
||||||
|
("allergy", "+ 过敏史"),
|
||||||
|
("diet", "+ 饮食习惯"),
|
||||||
|
):
|
||||||
|
pill = QPushButton(label, self._missing_fields_host)
|
||||||
|
pill.setProperty("receptionQuickFill", True)
|
||||||
|
pill.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||||
|
pill.setEnabled(self._can_edit)
|
||||||
|
pill.setToolTip(f"打开四诊病历补录{label[2:]}")
|
||||||
|
pill.clicked.connect(self._edit_diagnosis)
|
||||||
|
self._missing_field_pills[key] = pill
|
||||||
|
missing_row.addWidget(pill)
|
||||||
|
missing_row.addStretch(1)
|
||||||
|
missing_outer.addLayout(missing_row)
|
||||||
|
self._missing_fields_host.hide()
|
||||||
|
history_layout.addWidget(self._missing_fields_host)
|
||||||
|
|
||||||
history_layout.addStretch(1)
|
history_layout.addStretch(1)
|
||||||
consultation_layout.addWidget(history_card, 1)
|
consultation_layout.addWidget(history_card, 1)
|
||||||
|
|
||||||
right_clinical = QWidget(consultation_page)
|
right_clinical = QWidget(consultation_page)
|
||||||
right_layout = QVBoxLayout(right_clinical)
|
right_layout = QVBoxLayout(right_clinical)
|
||||||
right_layout.setContentsMargins(0, 0, 0, 0)
|
right_layout.setContentsMargins(0, 0, 0, 0)
|
||||||
right_layout.setSpacing(10)
|
right_layout.setSpacing(8)
|
||||||
|
|
||||||
self.patient_summary_card, self.patient_summary_labels = self._field_card(
|
self.patient_summary_card, self.patient_summary_labels = self._field_card(
|
||||||
"患者基本信息",
|
"患者基本信息",
|
||||||
@@ -4669,8 +4956,8 @@ class ReceptionPage(QWidget):
|
|||||||
vitals_card.setMinimumHeight(0)
|
vitals_card.setMinimumHeight(0)
|
||||||
vitals_card.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum)
|
vitals_card.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum)
|
||||||
vitals_layout = QVBoxLayout(vitals_card)
|
vitals_layout = QVBoxLayout(vitals_card)
|
||||||
vitals_layout.setContentsMargins(14, 14, 14, 14)
|
vitals_layout.setContentsMargins(12, 10, 12, 10)
|
||||||
vitals_layout.setSpacing(8)
|
vitals_layout.setSpacing(6)
|
||||||
vitals_title = QLabel("生命体征", vitals_card)
|
vitals_title = QLabel("生命体征", vitals_card)
|
||||||
vitals_title.setProperty("receptionBlockTitle", True)
|
vitals_title.setProperty("receptionBlockTitle", True)
|
||||||
vitals_layout.addWidget(vitals_title)
|
vitals_layout.addWidget(vitals_title)
|
||||||
@@ -4734,8 +5021,8 @@ class ReceptionPage(QWidget):
|
|||||||
labs_card = QFrame(right_clinical)
|
labs_card = QFrame(right_clinical)
|
||||||
labs_card.setObjectName("ReceptionLabsCard")
|
labs_card.setObjectName("ReceptionLabsCard")
|
||||||
labs_layout = QVBoxLayout(labs_card)
|
labs_layout = QVBoxLayout(labs_card)
|
||||||
labs_layout.setContentsMargins(14, 14, 14, 14)
|
labs_layout.setContentsMargins(12, 10, 12, 10)
|
||||||
labs_layout.setSpacing(9)
|
labs_layout.setSpacing(6)
|
||||||
labs_title = QLabel("检查结果", labs_card)
|
labs_title = QLabel("检查结果", labs_card)
|
||||||
labs_title.setProperty("receptionBlockTitle", True)
|
labs_title.setProperty("receptionBlockTitle", True)
|
||||||
labs_layout.addWidget(labs_title)
|
labs_layout.addWidget(labs_title)
|
||||||
@@ -4745,7 +5032,7 @@ class ReceptionPage(QWidget):
|
|||||||
self._show_missing_labs = False
|
self._show_missing_labs = False
|
||||||
labs_grid.setContentsMargins(0, 0, 0, 0)
|
labs_grid.setContentsMargins(0, 0, 0, 0)
|
||||||
labs_grid.setHorizontalSpacing(7)
|
labs_grid.setHorizontalSpacing(7)
|
||||||
labs_grid.setVerticalSpacing(7)
|
labs_grid.setVerticalSpacing(5)
|
||||||
self.lab_labels: dict[str, QLabel] = {}
|
self.lab_labels: dict[str, QLabel] = {}
|
||||||
self.lab_state_labels: dict[str, QLabel] = {}
|
self.lab_state_labels: dict[str, QLabel] = {}
|
||||||
lab_definitions = (
|
lab_definitions = (
|
||||||
@@ -5135,7 +5422,7 @@ class ReceptionPage(QWidget):
|
|||||||
self.ai_analysis_model_selector = _ReceptionAiModelCombo(analysis_card)
|
self.ai_analysis_model_selector = _ReceptionAiModelCombo(analysis_card)
|
||||||
self.ai_analysis_model_selector.setObjectName("ReceptionAiAnalysisModelSelector")
|
self.ai_analysis_model_selector.setObjectName("ReceptionAiAnalysisModelSelector")
|
||||||
self.ai_analysis_model_selector.setAccessibleName("选择卡片分析模型")
|
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:
|
for model_key in AI_ANALYSIS_MODELS:
|
||||||
self.ai_analysis_model_selector.addItem(
|
self.ai_analysis_model_selector.addItem(
|
||||||
AI_ANALYSIS_MODEL_LABELS[model_key],
|
AI_ANALYSIS_MODEL_LABELS[model_key],
|
||||||
@@ -5326,13 +5613,13 @@ class ReceptionPage(QWidget):
|
|||||||
self.ai_analysis_history_button = QPushButton("历史报告", analysis_card)
|
self.ai_analysis_history_button = QPushButton("历史报告", analysis_card)
|
||||||
self.ai_analysis_history_button.setObjectName("ReceptionAiHistoryButton")
|
self.ai_analysis_history_button.setObjectName("ReceptionAiHistoryButton")
|
||||||
self.ai_analysis_history_button.setAccessibleName("查看历次 AI 报告快照")
|
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)
|
self.ai_analysis_history_button.clicked.connect(self._open_ai_analysis_dialog)
|
||||||
report_footer.addWidget(self.ai_analysis_history_button)
|
report_footer.addWidget(self.ai_analysis_history_button)
|
||||||
self.ai_analysis_regenerate_button = QPushButton("重新分析", analysis_card)
|
self.ai_analysis_regenerate_button = QPushButton("重新分析", analysis_card)
|
||||||
self.ai_analysis_regenerate_button.setObjectName("ReceptionAiRegenerateButton")
|
self.ai_analysis_regenerate_button.setObjectName("ReceptionAiRegenerateButton")
|
||||||
self.ai_analysis_regenerate_button.setAccessibleName("重新生成患者级 AI 报告")
|
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.ai_analysis_regenerate_button.clicked.connect(
|
||||||
self._regenerate_patient_ai_reports
|
self._regenerate_patient_ai_reports
|
||||||
)
|
)
|
||||||
@@ -5528,10 +5815,11 @@ class ReceptionPage(QWidget):
|
|||||||
self._ai_analysis_active_model = "qwen"
|
self._ai_analysis_active_model = "qwen"
|
||||||
self._ai_analysis_model_states["qwen"] = state
|
self._ai_analysis_model_states["qwen"] = state
|
||||||
self._ai_analysis_model_messages["qwen"] = message
|
self._ai_analysis_model_messages["qwen"] = message
|
||||||
self._ai_analysis_model_states["openai"] = (
|
for secondary in AI_ANALYSIS_MODELS[1:]:
|
||||||
state if state in {"empty", "permission"} else "waiting"
|
self._ai_analysis_model_states[secondary] = (
|
||||||
)
|
state if state in {"empty", "permission"} else "waiting"
|
||||||
self._ai_analysis_model_messages["openai"] = ""
|
)
|
||||||
|
self._ai_analysis_model_messages[secondary] = ""
|
||||||
selector_index = self.ai_analysis_model_selector.findData("qwen")
|
selector_index = self.ai_analysis_model_selector.findData("qwen")
|
||||||
if selector_index >= 0:
|
if selector_index >= 0:
|
||||||
self.ai_analysis_model_selector.blockSignals(True)
|
self.ai_analysis_model_selector.blockSignals(True)
|
||||||
@@ -5626,15 +5914,41 @@ class ReceptionPage(QWidget):
|
|||||||
)
|
)
|
||||||
|
|
||||||
qwen_ready = "qwen" in self._ai_analysis_payloads
|
qwen_ready = "qwen" in self._ai_analysis_payloads
|
||||||
openai_state = self._ai_analysis_model_states["openai"]
|
secondary_models = AI_ANALYSIS_MODELS[1:]
|
||||||
openai_message = self._ai_analysis_model_messages["openai"]
|
secondary_states = [self._ai_analysis_model_states[key] for key in secondary_models]
|
||||||
if qwen_ready and openai_state == "loading":
|
loading_labels = [
|
||||||
secondary_message = "千问结果已显示,OpenAI 正在生成…"
|
AI_ANALYSIS_MODEL_LABELS[key]
|
||||||
elif qwen_ready and openai_state == "error":
|
for key in secondary_models
|
||||||
secondary_message = f"千问结果已保留;{openai_message}"
|
if self._ai_analysis_model_states[key] == "loading"
|
||||||
elif qwen_ready and openai_state == "success":
|
]
|
||||||
secondary_message = "千问与 OpenAI 均已完成,可切换对照。"
|
failed_messages = [
|
||||||
elif qwen_ready and openai_state == "unsupported":
|
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 = "千问结果已显示;当前数据源仅支持千问分析。"
|
secondary_message = "千问结果已显示;当前数据源仅支持千问分析。"
|
||||||
else:
|
else:
|
||||||
secondary_message = ""
|
secondary_message = ""
|
||||||
@@ -5646,7 +5960,7 @@ class ReceptionPage(QWidget):
|
|||||||
if success and payload is not None
|
if success and payload is not None
|
||||||
else ""
|
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]}"
|
secondary_message = f"快照时间:{current_snapshot_time[:16]}"
|
||||||
if self._ai_analysis_regenerating:
|
if self._ai_analysis_regenerating:
|
||||||
active_label = AI_ANALYSIS_MODEL_LABELS.get(
|
active_label = AI_ANALYSIS_MODEL_LABELS.get(
|
||||||
@@ -5654,15 +5968,16 @@ class ReceptionPage(QWidget):
|
|||||||
self._ai_analysis_regeneration_model or "千问",
|
self._ai_analysis_regeneration_model or "千问",
|
||||||
)
|
)
|
||||||
secondary_message = f"正在生成新的{active_label}快照,历史版本会保留。"
|
secondary_message = f"正在生成新的{active_label}快照,历史版本会保留。"
|
||||||
openai_state = "loading"
|
secondary_state = "loading"
|
||||||
elif self._ai_analysis_operation_error:
|
elif self._ai_analysis_operation_error:
|
||||||
secondary_message = self._ai_analysis_operation_error
|
secondary_message = self._ai_analysis_operation_error
|
||||||
openai_state = "error"
|
secondary_state = "error"
|
||||||
self._set_ai_analysis_secondary_status(openai_state, secondary_message)
|
self._set_ai_analysis_secondary_status(secondary_state, secondary_message)
|
||||||
|
|
||||||
self.ai_analysis_card.setProperty("analysisState", state)
|
self.ai_analysis_card.setProperty("analysisState", state)
|
||||||
self.ai_analysis_card.style().unpolish(self.ai_analysis_card)
|
self.ai_analysis_card.style().unpolish(self.ai_analysis_card)
|
||||||
self.ai_analysis_card.style().polish(self.ai_analysis_card)
|
self.ai_analysis_card.style().polish(self.ai_analysis_card)
|
||||||
|
self._sync_cockpit_and_context()
|
||||||
|
|
||||||
def _render_ai_analysis_payload(
|
def _render_ai_analysis_payload(
|
||||||
self,
|
self,
|
||||||
@@ -5980,12 +6295,14 @@ class ReceptionPage(QWidget):
|
|||||||
self._ai_analysis_payloads[model] = grouped[model][0]
|
self._ai_analysis_payloads[model] = grouped[model][0]
|
||||||
self._ai_analysis_model_states[model] = "success"
|
self._ai_analysis_model_states[model] = "success"
|
||||||
self._ai_analysis_model_messages[model] = ""
|
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_states[model] = "missing"
|
||||||
self._ai_analysis_model_messages[model] = ""
|
self._ai_analysis_model_messages[model] = ""
|
||||||
if self._ai_analysis_active_model not in self._ai_analysis_payloads:
|
if self._ai_analysis_active_model not in self._ai_analysis_payloads:
|
||||||
self._ai_analysis_active_model = (
|
self._ai_analysis_active_model = next(
|
||||||
"qwen" if "qwen" in self._ai_analysis_payloads else "openai"
|
(key for key in AI_ANALYSIS_MODELS if key in self._ai_analysis_payloads),
|
||||||
|
"qwen",
|
||||||
)
|
)
|
||||||
selector_index = self.ai_analysis_model_selector.findData(
|
selector_index = self.ai_analysis_model_selector.findData(
|
||||||
self._ai_analysis_active_model
|
self._ai_analysis_active_model
|
||||||
@@ -6436,9 +6753,10 @@ class ReceptionPage(QWidget):
|
|||||||
self._ai_analysis_model_states[model] = "success"
|
self._ai_analysis_model_states[model] = "success"
|
||||||
self._ai_analysis_model_messages[model] = ""
|
self._ai_analysis_model_messages[model] = ""
|
||||||
self._sync_ai_analysis_view()
|
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(
|
self._request_patient_ai_generation(
|
||||||
"openai",
|
next_model,
|
||||||
effective_generation,
|
effective_generation,
|
||||||
effective_appointment_id,
|
effective_appointment_id,
|
||||||
patient_id,
|
patient_id,
|
||||||
@@ -6475,9 +6793,21 @@ class ReceptionPage(QWidget):
|
|||||||
else:
|
else:
|
||||||
self._ai_analysis_model_states[model] = "error"
|
self._ai_analysis_model_states[model] = "error"
|
||||||
self._ai_analysis_model_messages[model] = message
|
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._ai_analysis_operation_error = f"{prefix}{message}"
|
||||||
self._sync_ai_analysis_view()
|
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(
|
def _patient_ai_generation_finished(
|
||||||
self,
|
self,
|
||||||
@@ -6617,7 +6947,7 @@ class ReceptionPage(QWidget):
|
|||||||
diagnosis_id,
|
diagnosis_id,
|
||||||
):
|
):
|
||||||
return
|
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_states[model] = "unsupported"
|
||||||
self._ai_analysis_model_messages[model] = ""
|
self._ai_analysis_model_messages[model] = ""
|
||||||
self._sync_ai_analysis_view()
|
self._sync_ai_analysis_view()
|
||||||
@@ -6764,11 +7094,12 @@ class ReceptionPage(QWidget):
|
|||||||
self._ai_analysis_model_messages[model] = ""
|
self._ai_analysis_model_messages[model] = ""
|
||||||
self._sync_ai_analysis_view()
|
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)
|
method = getattr(self.repository, "get_diagnosis_ai_analysis", None)
|
||||||
if callable(method):
|
if callable(method):
|
||||||
self._request_ai_analysis_model(
|
self._request_ai_analysis_model(
|
||||||
"openai",
|
next_model,
|
||||||
method,
|
method,
|
||||||
request_generation,
|
request_generation,
|
||||||
appointment_id,
|
appointment_id,
|
||||||
@@ -6803,6 +7134,18 @@ class ReceptionPage(QWidget):
|
|||||||
f"{label}分析加载失败:{friendly_error(error)}"
|
f"{label}分析加载失败:{friendly_error(error)}"
|
||||||
)
|
)
|
||||||
self._sync_ai_analysis_view()
|
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(
|
def _ai_analysis_finished(
|
||||||
self,
|
self,
|
||||||
@@ -6869,7 +7212,7 @@ class ReceptionPage(QWidget):
|
|||||||
self._set_ai_analysis_state("error", "当前患者缺少诊单编号,无法重试。")
|
self._set_ai_analysis_state("error", "当前患者缺少诊单编号,无法重试。")
|
||||||
return
|
return
|
||||||
model = self._ai_analysis_active_model
|
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)
|
method = getattr(self.repository, "get_diagnosis_ai_analysis", None)
|
||||||
if callable(method):
|
if callable(method):
|
||||||
self._request_ai_analysis_model(
|
self._request_ai_analysis_model(
|
||||||
@@ -7396,6 +7739,7 @@ class ReceptionPage(QWidget):
|
|||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
self._clear_selection()
|
self._clear_selection()
|
||||||
|
self._sync_cockpit_and_context()
|
||||||
return
|
return
|
||||||
chosen = records[row_to_select]
|
chosen = records[row_to_select]
|
||||||
if selected_id is not None and _same_id(_record_id(chosen), selected_id):
|
if selected_id is not None and _same_id(_record_id(chosen), selected_id):
|
||||||
@@ -7404,6 +7748,7 @@ class ReceptionPage(QWidget):
|
|||||||
self._load_detail(chosen, silent=True, clear=False)
|
self._load_detail(chosen, silent=True, clear=False)
|
||||||
else:
|
else:
|
||||||
self._select_record(chosen, silent=True, read_only_refresh=workspace_refresh)
|
self._select_record(chosen, silent=True, read_only_refresh=workspace_refresh)
|
||||||
|
self._sync_cockpit_and_context()
|
||||||
|
|
||||||
def _update_queue_filter_counts(self, result: Any, records: list[Any]) -> None:
|
def _update_queue_filter_counts(self, result: Any, records: list[Any]) -> None:
|
||||||
extend = get_value(result, "extend", None)
|
extend = get_value(result, "extend", None)
|
||||||
@@ -8557,6 +8902,7 @@ class ReceptionPage(QWidget):
|
|||||||
}
|
}
|
||||||
for key, value in case_values.items():
|
for key, value in case_values.items():
|
||||||
self.case_labels[key].setText(display_text(value))
|
self.case_labels[key].setText(display_text(value))
|
||||||
|
self._sync_case_field_folding()
|
||||||
self._set_patient_summary_value("course", case_values["course"])
|
self._set_patient_summary_value("course", case_values["course"])
|
||||||
self._set_patient_summary_value(
|
self._set_patient_summary_value(
|
||||||
"diagnosis", case_value("clinical_diagnosis", "diagnosis_name", "disease_name")
|
"diagnosis", case_value("clinical_diagnosis", "diagnosis_name", "disease_name")
|
||||||
@@ -8990,6 +9336,24 @@ class ReceptionPage(QWidget):
|
|||||||
button.setText("预览")
|
button.setText("预览")
|
||||||
show_toast(self, f"图片预览失败:{friendly_error(error)}", "danger", 5200)
|
show_toast(self, f"图片预览失败:{friendly_error(error)}", "danger", 5200)
|
||||||
|
|
||||||
|
def _sync_case_field_folding(self) -> None:
|
||||||
|
"""将未录入的可选病史字段折叠为底部快捷补录胶囊,保持主病历画布清爽高密。"""
|
||||||
|
|
||||||
|
if not hasattr(self, "_missing_field_pills"):
|
||||||
|
return
|
||||||
|
any_missing = False
|
||||||
|
for key, pill in self._missing_field_pills.items():
|
||||||
|
label = self.case_labels.get(key)
|
||||||
|
frame = self._case_field_frames.get(key)
|
||||||
|
text = (label.text().strip() if label is not None else "")
|
||||||
|
is_empty = text in {"", "—", "-"}
|
||||||
|
if frame is not None:
|
||||||
|
frame.setVisible(not is_empty)
|
||||||
|
pill.setVisible(is_empty)
|
||||||
|
if is_empty:
|
||||||
|
any_missing = True
|
||||||
|
self._missing_fields_host.setVisible(any_missing)
|
||||||
|
|
||||||
def _reset_detail_content(self, seed: Any = None) -> None:
|
def _reset_detail_content(self, seed: Any = None) -> None:
|
||||||
for cancel_event in self._patient_ai_generation_cancel_events.values():
|
for cancel_event in self._patient_ai_generation_cancel_events.values():
|
||||||
cancel_event.set()
|
cancel_event.set()
|
||||||
@@ -9178,6 +9542,7 @@ class ReceptionPage(QWidget):
|
|||||||
self.add_tongue_button.setEnabled(note_enabled)
|
self.add_tongue_button.setEnabled(note_enabled)
|
||||||
self.add_report_button.setEnabled(note_enabled)
|
self.add_report_button.setEnabled(note_enabled)
|
||||||
self.save_note_button.setEnabled(note_enabled)
|
self.save_note_button.setEnabled(note_enabled)
|
||||||
|
self._sync_cockpit_and_context()
|
||||||
|
|
||||||
def _detail_error(
|
def _detail_error(
|
||||||
self, error: Exception, generation: int, appointment_id: int | None = None
|
self, error: Exception, generation: int, appointment_id: int | None = None
|
||||||
@@ -9305,6 +9670,7 @@ class ReceptionPage(QWidget):
|
|||||||
self._reset_detail_content()
|
self._reset_detail_content()
|
||||||
self.detail_banner.clear()
|
self.detail_banner.clear()
|
||||||
self.detail_stack.setCurrentIndex(0)
|
self.detail_stack.setCurrentIndex(0)
|
||||||
|
self._sync_cockpit_and_context()
|
||||||
|
|
||||||
def _selection_context(self) -> tuple[int, int, int | None, int | None] | None:
|
def _selection_context(self) -> tuple[int, int, int | None, int | None] | None:
|
||||||
appointment_id = self._selected_appointment_id
|
appointment_id = self._selected_appointment_id
|
||||||
|
|||||||
@@ -26,20 +26,25 @@ _ORDERS = """
|
|||||||
}
|
}
|
||||||
#PatientOrdersWorkspace QFrame#OrderSummaryStrip { background: transparent; border: 0; }
|
#PatientOrdersWorkspace QFrame#OrderSummaryStrip { background: transparent; border: 0; }
|
||||||
#PatientOrdersWorkspace QPushButton, #PatientOrdersWorkspace QToolButton {
|
#PatientOrdersWorkspace QPushButton, #PatientOrdersWorkspace QToolButton {
|
||||||
min-height: 38px; max-height: 38px; padding: 0 16px; border: 1px solid transparent;
|
min-height: 36px; max-height: 36px; padding: 0 15px; border: 1px solid $ds_line_strong;
|
||||||
border-radius: $ds_radius_control; background: $ds_surface_alt; color: $ds_text;
|
border-radius: $ds_radius_control; background: $ds_surface; color: $ds_text; font-weight: 500;
|
||||||
}
|
}
|
||||||
#PatientOrdersWorkspace QPushButton:hover, #PatientOrdersWorkspace QToolButton:hover {
|
#PatientOrdersWorkspace QPushButton:hover, #PatientOrdersWorkspace QToolButton:hover {
|
||||||
background: $ds_surface_alt; border-color: $ds_line_strong; color: $ds_accent;
|
background: $ds_accent_soft; border-color: #9CCFC7; color: $ds_accent;
|
||||||
}
|
}
|
||||||
#PatientOrdersWorkspace QPushButton:pressed, #PatientOrdersWorkspace QToolButton:pressed { background: $ds_accent_soft; }
|
#PatientOrdersWorkspace QPushButton:pressed, #PatientOrdersWorkspace QToolButton:pressed { background: #D7EFEA; }
|
||||||
#PatientOrdersWorkspace QPushButton:focus, #PatientOrdersWorkspace QToolButton:focus { border-color: $ds_focus; }
|
#PatientOrdersWorkspace QPushButton:focus, #PatientOrdersWorkspace QToolButton:focus { border-color: $ds_focus; }
|
||||||
#PatientOrdersWorkspace QPushButton#OrderSearchButton,
|
#PatientOrdersWorkspace QPushButton#OrderSearchButton,
|
||||||
#PatientOrdersWorkspace QPushButton#OrderDetailButton {
|
#PatientOrdersWorkspace QPushButton#OrderDetailButton {
|
||||||
color: $ds_surface; background: $ds_accent; border-color: $ds_accent;
|
color: $ds_surface;
|
||||||
|
background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #12857D, stop:1 $ds_accent);
|
||||||
|
border-color: $ds_accent;
|
||||||
}
|
}
|
||||||
#PatientOrdersWorkspace QPushButton#OrderSearchButton:hover,
|
#PatientOrdersWorkspace QPushButton#OrderSearchButton:hover,
|
||||||
#PatientOrdersWorkspace QPushButton#OrderDetailButton:hover { background: $ds_accent_hover; border-color: $ds_accent_hover; }
|
#PatientOrdersWorkspace QPushButton#OrderDetailButton:hover {
|
||||||
|
background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #0E726B, stop:1 $ds_accent_hover);
|
||||||
|
border-color: $ds_accent_hover;
|
||||||
|
}
|
||||||
#PatientOrdersWorkspace QPushButton#OrderSearchButton:pressed,
|
#PatientOrdersWorkspace QPushButton#OrderSearchButton:pressed,
|
||||||
#PatientOrdersWorkspace QPushButton#OrderDetailButton:pressed { background: $ds_accent_pressed; border-color: $ds_accent_pressed; }
|
#PatientOrdersWorkspace QPushButton#OrderDetailButton:pressed { background: $ds_accent_pressed; border-color: $ds_accent_pressed; }
|
||||||
#PatientOrdersWorkspace QPushButton#OrderSearchButton:focus,
|
#PatientOrdersWorkspace QPushButton#OrderSearchButton:focus,
|
||||||
|
|||||||
@@ -61,18 +61,22 @@ _LIST = """
|
|||||||
}
|
}
|
||||||
#PatientListWorkspace QFrame#PatientSummaryStrip { background: transparent; border: 0; }
|
#PatientListWorkspace QFrame#PatientSummaryStrip { background: transparent; border: 0; }
|
||||||
#PatientListWorkspace QPushButton, #PatientSearchToolbar QPushButton {
|
#PatientListWorkspace QPushButton, #PatientSearchToolbar QPushButton {
|
||||||
min-height: 38px; max-height: 38px; padding: 0 16px;
|
min-height: 36px; max-height: 36px; padding: 0 15px;
|
||||||
border: 1px solid transparent; border-radius: $ds_radius_control; background: $ds_surface_alt;
|
border: 1px solid $ds_line_strong; border-radius: $ds_radius_control; background: $ds_surface; font-weight: 500;
|
||||||
}
|
}
|
||||||
#PatientListWorkspace QPushButton:hover, #PatientSearchToolbar QPushButton:hover {
|
#PatientListWorkspace QPushButton:hover, #PatientSearchToolbar QPushButton:hover {
|
||||||
color: $ds_accent; background: $ds_surface_alt; border-color: $ds_line_strong;
|
color: $ds_accent; background: $ds_accent_soft; border-color: #9CCFC7;
|
||||||
}
|
}
|
||||||
#PatientListWorkspace QPushButton:pressed, #PatientSearchToolbar QPushButton:pressed { background: $ds_accent_soft; }
|
#PatientListWorkspace QPushButton:pressed, #PatientSearchToolbar QPushButton:pressed { background: #D7EFEA; }
|
||||||
#PatientListWorkspace QPushButton:focus, #PatientSearchToolbar QPushButton:focus { border-color: $ds_focus; }
|
#PatientListWorkspace QPushButton:focus, #PatientSearchToolbar QPushButton:focus { border-color: $ds_focus; }
|
||||||
#PatientSearchToolbar QPushButton#PatientSearchButton {
|
#PatientSearchToolbar QPushButton#PatientSearchButton {
|
||||||
min-height: 38px; max-height: 38px; color: $ds_surface; background: $ds_accent; border-color: $ds_accent;
|
min-height: 36px; max-height: 36px; color: $ds_surface;
|
||||||
|
background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #12857D, stop:1 $ds_accent);
|
||||||
|
border-color: $ds_accent;
|
||||||
|
}
|
||||||
|
#PatientSearchToolbar QPushButton#PatientSearchButton:hover {
|
||||||
|
background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #0E726B, stop:1 $ds_accent_hover);
|
||||||
}
|
}
|
||||||
#PatientSearchToolbar QPushButton#PatientSearchButton:hover { background: $ds_accent_hover; }
|
|
||||||
#PatientSearchToolbar QPushButton#PatientSearchButton:pressed { background: $ds_accent_pressed; }
|
#PatientSearchToolbar QPushButton#PatientSearchButton:pressed { background: $ds_accent_pressed; }
|
||||||
#PatientSearchToolbar QPushButton#PatientSearchButton:focus { border-color: $ds_focus; }
|
#PatientSearchToolbar QPushButton#PatientSearchButton:focus { border-color: $ds_focus; }
|
||||||
#PatientSearchToolbar QLineEdit {
|
#PatientSearchToolbar QLineEdit {
|
||||||
|
|||||||
@@ -323,19 +323,21 @@ _LIBRARY = """
|
|||||||
border: 0; border-radius: 0; background: transparent;
|
border: 0; border-radius: 0; background: transparent;
|
||||||
}
|
}
|
||||||
#PrescriptionLibraryPage QPushButton {
|
#PrescriptionLibraryPage QPushButton {
|
||||||
min-height: 38px; max-height: 38px; padding: 0 16px; border-radius: $ds_radius_control;
|
min-height: 36px; max-height: 36px; padding: 0 15px; border-radius: $ds_radius_control;
|
||||||
border: 1px solid transparent; background: $ds_surface_alt; color: $ds_text;
|
border: 1px solid $ds_line_strong; background: $ds_surface; color: $ds_text; font-weight: 500;
|
||||||
}
|
}
|
||||||
#PrescriptionLibraryPage QPushButton:hover { background: $ds_surface_alt; border-color: $ds_line_strong; color: $ds_accent; }
|
#PrescriptionLibraryPage QPushButton:hover { background: $ds_accent_soft; border-color: #9CCFC7; color: $ds_accent; }
|
||||||
#PrescriptionLibraryPage QPushButton:pressed { background: $ds_accent_soft; }
|
#PrescriptionLibraryPage QPushButton:pressed { background: #D7EFEA; }
|
||||||
#PrescriptionLibraryPage QPushButton:focus { border-color: $ds_focus; }
|
#PrescriptionLibraryPage QPushButton:focus { border-color: $ds_focus; }
|
||||||
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton,
|
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton,
|
||||||
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton {
|
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton {
|
||||||
background: $ds_accent; border-color: $ds_accent; color: $ds_surface;
|
background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #12857D, stop:1 $ds_accent);
|
||||||
|
border-color: $ds_accent; color: $ds_surface;
|
||||||
}
|
}
|
||||||
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton:hover,
|
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton:hover,
|
||||||
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton:hover {
|
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton:hover {
|
||||||
background: $ds_accent_hover; border-color: $ds_accent_hover;
|
background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #0E726B, stop:1 $ds_accent_hover);
|
||||||
|
border-color: $ds_accent_hover;
|
||||||
}
|
}
|
||||||
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton:pressed,
|
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton:pressed,
|
||||||
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton:pressed {
|
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton:pressed {
|
||||||
@@ -343,7 +345,7 @@ _LIBRARY = """
|
|||||||
}
|
}
|
||||||
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton:focus,
|
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton:focus,
|
||||||
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton:focus { border-color: $ds_focus; }
|
#PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton:focus { border-color: $ds_focus; }
|
||||||
#PrescriptionLibraryPage QPushButton[variant="danger"] { color: $ds_danger; background: $ds_danger_soft; border-color: transparent; }
|
#PrescriptionLibraryPage QPushButton[variant="danger"] { color: $ds_danger; background: $ds_danger_soft; border-color: #F5C8CD; }
|
||||||
#PrescriptionLibraryPage QPushButton[variant="danger"]:hover { border-color: $ds_danger; }
|
#PrescriptionLibraryPage QPushButton[variant="danger"]:hover { border-color: $ds_danger; }
|
||||||
#PrescriptionLibraryPage QPushButton[variant="danger"]:focus { border-color: $ds_focus; }
|
#PrescriptionLibraryPage QPushButton[variant="danger"]:focus { border-color: $ds_focus; }
|
||||||
#PrescriptionLibraryPage QPushButton:disabled,
|
#PrescriptionLibraryPage QPushButton:disabled,
|
||||||
|
|||||||
@@ -31,24 +31,26 @@ _PRESCRIPTIONS = """
|
|||||||
}
|
}
|
||||||
#PrescriptionsPage QFrame#PrescriptionToolbar { background: transparent; border: 0; }
|
#PrescriptionsPage QFrame#PrescriptionToolbar { background: transparent; border: 0; }
|
||||||
#PrescriptionsPage QPushButton {
|
#PrescriptionsPage QPushButton {
|
||||||
min-height: 38px; max-height: 38px; padding: 0 16px; border-radius: $ds_radius_control;
|
min-height: 36px; max-height: 36px; padding: 0 15px; border-radius: $ds_radius_control;
|
||||||
border: 1px solid transparent; background: $ds_surface_alt; color: $ds_text;
|
border: 1px solid $ds_line_strong; background: $ds_surface; color: $ds_text; font-weight: 500;
|
||||||
}
|
}
|
||||||
#PrescriptionsPage QPushButton:hover { background: $ds_surface_alt; border-color: $ds_line_strong; color: $ds_accent; }
|
#PrescriptionsPage QPushButton:hover { background: $ds_accent_soft; border-color: #9CCFC7; color: $ds_accent; }
|
||||||
#PrescriptionsPage QPushButton:pressed { background: $ds_accent_soft; }
|
#PrescriptionsPage QPushButton:pressed { background: #D7EFEA; }
|
||||||
#PrescriptionsPage QPushButton:focus { border-color: $ds_focus; }
|
#PrescriptionsPage QPushButton:focus { border-color: $ds_focus; }
|
||||||
#PrescriptionsPage QPushButton#PrescriptionAddButton, #PrescriptionsPage QPushButton#PrescriptionQueryButton {
|
#PrescriptionsPage QPushButton#PrescriptionAddButton, #PrescriptionsPage QPushButton#PrescriptionQueryButton {
|
||||||
background: $ds_accent; color: $ds_surface; border-color: $ds_accent;
|
background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #12857D, stop:1 $ds_accent);
|
||||||
|
color: $ds_surface; border-color: $ds_accent;
|
||||||
}
|
}
|
||||||
#PrescriptionsPage QPushButton#PrescriptionAddButton:hover, #PrescriptionsPage QPushButton#PrescriptionQueryButton:hover {
|
#PrescriptionsPage QPushButton#PrescriptionAddButton:hover, #PrescriptionsPage QPushButton#PrescriptionQueryButton:hover {
|
||||||
background: $ds_accent_hover; border-color: $ds_accent_hover;
|
background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #0E726B, stop:1 $ds_accent_hover);
|
||||||
|
border-color: $ds_accent_hover;
|
||||||
}
|
}
|
||||||
#PrescriptionsPage QPushButton#PrescriptionAddButton:pressed, #PrescriptionsPage QPushButton#PrescriptionQueryButton:pressed {
|
#PrescriptionsPage QPushButton#PrescriptionAddButton:pressed, #PrescriptionsPage QPushButton#PrescriptionQueryButton:pressed {
|
||||||
background: $ds_accent_pressed; border-color: $ds_accent_pressed;
|
background: $ds_accent_pressed; border-color: $ds_accent_pressed;
|
||||||
}
|
}
|
||||||
#PrescriptionsPage QPushButton#PrescriptionAddButton:focus,
|
#PrescriptionsPage QPushButton#PrescriptionAddButton:focus,
|
||||||
#PrescriptionsPage QPushButton#PrescriptionQueryButton:focus { border-color: $ds_focus; }
|
#PrescriptionsPage QPushButton#PrescriptionQueryButton:focus { border-color: $ds_focus; }
|
||||||
#PrescriptionsPage QPushButton[variant="danger"] { color: $ds_danger; background: $ds_danger_soft; border-color: transparent; }
|
#PrescriptionsPage QPushButton[variant="danger"] { color: $ds_danger; background: $ds_danger_soft; border-color: #F5C8CD; }
|
||||||
#PrescriptionsPage QPushButton[variant="danger"]:hover { border-color: $ds_danger; }
|
#PrescriptionsPage QPushButton[variant="danger"]:hover { border-color: $ds_danger; }
|
||||||
#PrescriptionsPage QPushButton[variant="danger"]:focus { border-color: $ds_focus; }
|
#PrescriptionsPage QPushButton[variant="danger"]:focus { border-color: $ds_focus; }
|
||||||
#PrescriptionsPage QPushButton:disabled, #PrescriptionsPage QPushButton[variant="danger"]:disabled,
|
#PrescriptionsPage QPushButton:disabled, #PrescriptionsPage QPushButton[variant="danger"]:disabled,
|
||||||
|
|||||||
@@ -169,23 +169,24 @@ QWidget#ReceptionPage QStackedWidget#ReceptionNarrowWorkspace {
|
|||||||
border: 0;
|
border: 0;
|
||||||
}
|
}
|
||||||
QWidget#ReceptionPage QFrame#ReceptionQueuePanel {
|
QWidget#ReceptionPage QFrame#ReceptionQueuePanel {
|
||||||
background-color: #FFFFFF;
|
background-color: $ds_surface;
|
||||||
border: 1px solid #EDF0F5;
|
border: 1px solid $ds_line;
|
||||||
border-radius: 16px;
|
border-radius: $ds_radius_panel;
|
||||||
}
|
}
|
||||||
QWidget#ReceptionPage QLabel#ReceptionQueueTitle {
|
QWidget#ReceptionPage QLabel#ReceptionQueueTitle {
|
||||||
font-size: 18px;
|
color: $ds_heading;
|
||||||
|
font-size: 17px;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
}
|
}
|
||||||
QWidget#ReceptionPage QLabel#ReceptionQueueName {
|
QWidget#ReceptionPage QLabel#ReceptionQueueName {
|
||||||
font-size: 15px;
|
font-size: 15px;
|
||||||
font-weight: 500;
|
font-weight: 600;
|
||||||
}
|
}
|
||||||
QWidget#ReceptionPage QLabel#ReceptionQueueMeta,
|
QWidget#ReceptionPage QLabel#ReceptionQueueMeta,
|
||||||
QWidget#ReceptionPage QLabel#ReceptionQueueTime,
|
QWidget#ReceptionPage QLabel#ReceptionQueueTime,
|
||||||
QWidget#ReceptionPage QLabel#ReceptionQueueSubline,
|
QWidget#ReceptionPage QLabel#ReceptionQueueSubline,
|
||||||
QWidget#ReceptionPage QLabel#ReceptionQueueSummary {
|
QWidget#ReceptionPage QLabel#ReceptionQueueSummary {
|
||||||
color: #5D6B80;
|
color: $ds_muted;
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
font-weight: 400;
|
font-weight: 400;
|
||||||
}
|
}
|
||||||
@@ -193,79 +194,137 @@ QWidget#ReceptionPage QLabel#ReceptionQueueMetric {
|
|||||||
font-size: 13px;
|
font-size: 13px;
|
||||||
}
|
}
|
||||||
QWidget#ReceptionPage QLabel#ReceptionQueueMetric[tone="description"] {
|
QWidget#ReceptionPage QLabel#ReceptionQueueMetric[tone="description"] {
|
||||||
color: #5D6B80;
|
color: $ds_muted;
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
}
|
}
|
||||||
QWidget#ReceptionPage QFrame#ReceptionHero,
|
QWidget#ReceptionPage QFrame#ReceptionHero,
|
||||||
QWidget#ReceptionPage QFrame#ReceptionClinicalCard {
|
QWidget#ReceptionPage QFrame#ReceptionClinicalCard {
|
||||||
min-height: 0;
|
min-height: 0;
|
||||||
background-color: #FFFFFF;
|
background-color: $ds_surface;
|
||||||
border: 1px solid #EDF0F5;
|
border: 1px solid $ds_line;
|
||||||
border-radius: 16px;
|
border-radius: $ds_radius_panel;
|
||||||
}
|
}
|
||||||
QWidget#ReceptionPage QLabel#ReceptionPatientName {
|
QWidget#ReceptionPage QLabel#ReceptionPatientName {
|
||||||
|
color: $ds_heading;
|
||||||
font-size: 20px;
|
font-size: 20px;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
}
|
}
|
||||||
QWidget#ReceptionPage QLabel#ReceptionPatientMeta {
|
QWidget#ReceptionPage QLabel#ReceptionPatientMeta {
|
||||||
color: #5D6B80;
|
color: $ds_muted;
|
||||||
font-size: 13px;
|
font-size: 13px;
|
||||||
}
|
}
|
||||||
QWidget#ReceptionPage QLabel#ReceptionAvatar {
|
QWidget#ReceptionPage QLabel#ReceptionAvatar {
|
||||||
color: #1555B6;
|
color: $ds_accent;
|
||||||
background-color: #EAF2FF;
|
background-color: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #E9F6F4, stop:1 #CDEAE5);
|
||||||
|
border: 1px solid #DFC793;
|
||||||
border-radius: 12px;
|
border-radius: 12px;
|
||||||
font-size: 20px;
|
font-size: 20px;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
}
|
}
|
||||||
QWidget#ReceptionPage QTabBar#ReceptionDetailTabs,
|
QWidget#ReceptionPage QTabBar#ReceptionDetailTabs,
|
||||||
QWidget#ReceptionPage QTabBar#ReceptionWorkspaceTabs {
|
QWidget#ReceptionPage QTabBar#ReceptionWorkspaceTabs {
|
||||||
background-color: #FFFFFF;
|
background-color: $ds_surface_alt;
|
||||||
border: 0;
|
border: 0;
|
||||||
border-bottom: 1px solid #E5ECF6;
|
border-bottom: 1px solid $ds_line;
|
||||||
border-top-left-radius: 16px;
|
border-top-left-radius: $ds_radius_panel;
|
||||||
border-top-right-radius: 16px;
|
border-top-right-radius: $ds_radius_panel;
|
||||||
}
|
}
|
||||||
QWidget#ReceptionPage QTabBar#ReceptionDetailTabs::tab,
|
QWidget#ReceptionPage QTabBar#ReceptionDetailTabs::tab,
|
||||||
QWidget#ReceptionPage QTabBar#ReceptionWorkspaceTabs::tab {
|
QWidget#ReceptionPage QTabBar#ReceptionWorkspaceTabs::tab {
|
||||||
min-height: 40px;
|
min-height: 40px;
|
||||||
margin: 0;
|
margin: 0;
|
||||||
padding: 0 14px;
|
padding: 0 15px;
|
||||||
color: #5D6B80;
|
color: $ds_muted;
|
||||||
background-color: transparent;
|
background-color: transparent;
|
||||||
border: 0;
|
border: 0;
|
||||||
border-bottom: 2px solid transparent;
|
border-bottom: 2px solid transparent;
|
||||||
border-radius: 0;
|
border-radius: 0;
|
||||||
font-size: 13px;
|
font-size: 13px;
|
||||||
font-weight: 400;
|
font-weight: 500;
|
||||||
}
|
}
|
||||||
QWidget#ReceptionPage QTabBar#ReceptionDetailTabs::tab:first {
|
QWidget#ReceptionPage QTabBar#ReceptionDetailTabs::tab:first {
|
||||||
margin-left: 0;
|
margin-left: 0;
|
||||||
padding-left: 14px;
|
padding-left: 15px;
|
||||||
}
|
}
|
||||||
QWidget#ReceptionPage QTabBar#ReceptionDetailTabs::tab:hover,
|
QWidget#ReceptionPage QTabBar#ReceptionDetailTabs::tab:hover,
|
||||||
QWidget#ReceptionPage QTabBar#ReceptionWorkspaceTabs::tab:hover {
|
QWidget#ReceptionPage QTabBar#ReceptionWorkspaceTabs::tab:hover {
|
||||||
color: #1769E8;
|
color: $ds_accent;
|
||||||
background-color: #F3F7FD;
|
background-color: rgba(11, 110, 104, 14);
|
||||||
}
|
}
|
||||||
QWidget#ReceptionPage QTabBar#ReceptionDetailTabs::tab:selected,
|
QWidget#ReceptionPage QTabBar#ReceptionDetailTabs::tab:selected,
|
||||||
QWidget#ReceptionPage QTabBar#ReceptionWorkspaceTabs::tab:selected {
|
QWidget#ReceptionPage QTabBar#ReceptionWorkspaceTabs::tab:selected {
|
||||||
color: #1769E8;
|
color: $ds_accent;
|
||||||
background-color: transparent;
|
background-color: transparent;
|
||||||
border-bottom: 2px solid #1769E8;
|
border-bottom: 2px solid $ds_accent;
|
||||||
font-weight: 500;
|
font-weight: 600;
|
||||||
}
|
}
|
||||||
QWidget#ReceptionPage QFrame#ReceptionHistoryCard {
|
QWidget#ReceptionPage QFrame#ReceptionHistoryCard {
|
||||||
background-color: #FFFFFF;
|
background-color: #FFFFFF;
|
||||||
border: 0;
|
border: 0;
|
||||||
border-radius: 0;
|
border-radius: 0;
|
||||||
}
|
}
|
||||||
QWidget#ReceptionPage QWidget#ReceptionCaseField {
|
QWidget#ReceptionPage QWidget#ReceptionCaseField,
|
||||||
|
QWidget#ReceptionPage QFrame#ReceptionCaseField {
|
||||||
background-color: transparent;
|
background-color: transparent;
|
||||||
border: 0;
|
border: 0;
|
||||||
border-bottom: 1px solid #EDF1F7;
|
border-bottom: 1px solid $ds_line;
|
||||||
border-radius: 0;
|
border-radius: 0;
|
||||||
}
|
}
|
||||||
|
QWidget#ReceptionPage QFrame#ReceptionCaseField[chiefFocus="true"] {
|
||||||
|
background-color: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #EEF9F7, stop:1 #FFFFFF);
|
||||||
|
border: 1px solid #C6E3DE;
|
||||||
|
border-left: 3px solid $ds_accent;
|
||||||
|
border-radius: 10px;
|
||||||
|
}
|
||||||
|
QWidget#ReceptionPage QPushButton#ReceptionInlineAction {
|
||||||
|
min-height: 28px;
|
||||||
|
max-height: 28px;
|
||||||
|
padding: 0 10px;
|
||||||
|
border-radius: 7px;
|
||||||
|
background-color: $ds_surface;
|
||||||
|
border: 1px solid $ds_line_strong;
|
||||||
|
color: $ds_accent;
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
QWidget#ReceptionPage QPushButton#ReceptionInlineAction:hover {
|
||||||
|
background-color: $ds_accent_soft;
|
||||||
|
border-color: #8FC8C0;
|
||||||
|
}
|
||||||
|
QWidget#ReceptionPage QPushButton#ReceptionInlineAiAction {
|
||||||
|
min-height: 28px;
|
||||||
|
max-height: 28px;
|
||||||
|
padding: 0 10px;
|
||||||
|
border-radius: 7px;
|
||||||
|
background-color: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #123433, stop:1 #091E1E);
|
||||||
|
border: 1px solid rgba(223, 199, 147, 120);
|
||||||
|
color: #DFC793;
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
QWidget#ReceptionPage QPushButton#ReceptionInlineAiAction:hover {
|
||||||
|
background-color: #174240;
|
||||||
|
color: #FFFFFF;
|
||||||
|
}
|
||||||
|
QWidget#ReceptionPage QFrame#ReceptionMissingFieldsBar {
|
||||||
|
background-color: transparent;
|
||||||
|
border: 0;
|
||||||
|
}
|
||||||
|
QWidget#ReceptionPage QPushButton[receptionQuickFill="true"] {
|
||||||
|
min-height: 26px;
|
||||||
|
max-height: 26px;
|
||||||
|
padding: 0 10px;
|
||||||
|
border-radius: 13px;
|
||||||
|
background-color: $ds_surface_alt;
|
||||||
|
border: 1px dashed $ds_line_strong;
|
||||||
|
color: $ds_muted;
|
||||||
|
font-size: 11.5px;
|
||||||
|
}
|
||||||
|
QWidget#ReceptionPage QPushButton[receptionQuickFill="true"]:hover {
|
||||||
|
background-color: $ds_accent_soft;
|
||||||
|
border: 1px solid $ds_accent;
|
||||||
|
color: $ds_accent;
|
||||||
|
}
|
||||||
QWidget#ReceptionPage QLabel#ReceptionCaseHeading {
|
QWidget#ReceptionPage QLabel#ReceptionCaseHeading {
|
||||||
color: #202C3F;
|
color: #202C3F;
|
||||||
font-size: 16px;
|
font-size: 16px;
|
||||||
@@ -294,17 +353,17 @@ QWidget#ReceptionPage QLabel[receptionLifestyleChip="true"] {
|
|||||||
QWidget#ReceptionPage QFrame#ReceptionPatientSummaryCard,
|
QWidget#ReceptionPage QFrame#ReceptionPatientSummaryCard,
|
||||||
QWidget#ReceptionPage QFrame#ReceptionVitalsCard,
|
QWidget#ReceptionPage QFrame#ReceptionVitalsCard,
|
||||||
QWidget#ReceptionPage QFrame#ReceptionLabsCard {
|
QWidget#ReceptionPage QFrame#ReceptionLabsCard {
|
||||||
background-color: #FFFFFF;
|
background-color: $ds_surface;
|
||||||
border: 1px solid #EDF0F5;
|
border: 1px solid $ds_line;
|
||||||
border-radius: 16px;
|
border-radius: $ds_radius_panel;
|
||||||
}
|
}
|
||||||
QWidget#ReceptionPage QLabel#ReceptionPatientSummaryValue {
|
QWidget#ReceptionPage QLabel#ReceptionPatientSummaryValue {
|
||||||
color: #24334A;
|
color: $ds_heading;
|
||||||
font-size: 13px;
|
font-size: 13px;
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
}
|
}
|
||||||
QWidget#ReceptionPage QLabel#ReceptionPatientSummaryValue[missing="true"] {
|
QWidget#ReceptionPage QLabel#ReceptionPatientSummaryValue[missing="true"] {
|
||||||
color: #697386;
|
color: $ds_muted;
|
||||||
font-weight: 400;
|
font-weight: 400;
|
||||||
}
|
}
|
||||||
QWidget#ReceptionPage QFrame#ReceptionMetricCell,
|
QWidget#ReceptionPage QFrame#ReceptionMetricCell,
|
||||||
@@ -316,76 +375,109 @@ QWidget#ReceptionPage QFrame#ReceptionMetricCell[firstMetric="true"] {
|
|||||||
QWidget#ReceptionPage QLabel[receptionMetricCaption="true"],
|
QWidget#ReceptionPage QLabel[receptionMetricCaption="true"],
|
||||||
QWidget#ReceptionPage QLabel[receptionMetricUnit="true"],
|
QWidget#ReceptionPage QLabel[receptionMetricUnit="true"],
|
||||||
QWidget#ReceptionPage QLabel[receptionBmiState="true"] {
|
QWidget#ReceptionPage QLabel[receptionBmiState="true"] {
|
||||||
color: #5D6B80;
|
color: $ds_muted;
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
font-weight: 400;
|
font-weight: 400;
|
||||||
}
|
}
|
||||||
QWidget#ReceptionPage QFrame#ReceptionMetricCell QLabel[receptionMetricValue="true"] {
|
QWidget#ReceptionPage QFrame#ReceptionMetricCell QLabel[receptionMetricValue="true"] {
|
||||||
|
color: $ds_heading;
|
||||||
font-size: 18px;
|
font-size: 18px;
|
||||||
font-weight: 500;
|
font-weight: 600;
|
||||||
}
|
}
|
||||||
QWidget#ReceptionPage QFrame#ReceptionLabCell {
|
QWidget#ReceptionPage QFrame#ReceptionLabCell {
|
||||||
min-height: 0;
|
min-height: 0;
|
||||||
padding: 0;
|
padding: 0;
|
||||||
background-color: #FFFFFF;
|
background-color: $ds_surface;
|
||||||
border: 0;
|
border: 0;
|
||||||
border-bottom: 1px solid #EDF1F7;
|
border-bottom: 1px solid $ds_line;
|
||||||
border-radius: 0;
|
border-radius: 0;
|
||||||
}
|
}
|
||||||
QWidget#ReceptionPage QFrame#ReceptionLabCell QLabel[receptionMetricValue="true"] {
|
QWidget#ReceptionPage QFrame#ReceptionLabCell QLabel[receptionMetricValue="true"] {
|
||||||
font-size: 13px;
|
font-size: 13px;
|
||||||
font-weight: 400;
|
font-weight: 500;
|
||||||
}
|
}
|
||||||
QWidget#ReceptionPage QPushButton#ReceptionMissingLabsButton {
|
QWidget#ReceptionPage QPushButton#ReceptionMissingLabsButton {
|
||||||
min-height: 28px;
|
min-height: 28px;
|
||||||
max-height: 28px;
|
max-height: 28px;
|
||||||
padding: 0;
|
padding: 0;
|
||||||
color: #1769E8;
|
color: $ds_accent;
|
||||||
background: transparent;
|
background: transparent;
|
||||||
border: 0;
|
border: 0;
|
||||||
text-align: left;
|
text-align: left;
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
|
font-weight: 500;
|
||||||
}
|
}
|
||||||
QWidget#ReceptionPage QLabel[receptionMetricState="true"] {
|
QWidget#ReceptionPage QLabel[receptionMetricState="true"] {
|
||||||
min-height: 18px;
|
min-height: 18px;
|
||||||
padding: 0 5px;
|
padding: 0 6px;
|
||||||
background-color: #F0F5FD;
|
background-color: $ds_accent_soft;
|
||||||
border: 0;
|
border: 1px solid #C5E2DE;
|
||||||
border-radius: 4px;
|
border-radius: $ds_radius_small;
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
font-weight: 400;
|
font-weight: 500;
|
||||||
}
|
}
|
||||||
QWidget#ReceptionPage QLabel[receptionMetricState="true"][alert="true"] {
|
QWidget#ReceptionPage QLabel[receptionMetricState="true"][alert="true"] {
|
||||||
color: #BE4B58;
|
color: $ds_danger;
|
||||||
background-color: #FFF4F5;
|
background-color: $ds_danger_soft;
|
||||||
|
border-color: #F5C8CD;
|
||||||
}
|
}
|
||||||
QWidget#ReceptionPage QLabel[receptionMetricState="true"][alert="true"][warning="true"] {
|
QWidget#ReceptionPage QLabel[receptionMetricState="true"][alert="true"][warning="true"] {
|
||||||
color: #A9691D;
|
color: $ds_warning;
|
||||||
background-color: #FFF9EF;
|
background-color: $ds_warning_soft;
|
||||||
border-radius: 4px;
|
border-color: #F7DFB7;
|
||||||
|
border-radius: $ds_radius_small;
|
||||||
}
|
}
|
||||||
QWidget#ReceptionPage QFrame#ReceptionAiAnalysisCard,
|
QWidget#ReceptionPage QFrame#ReceptionAiAnalysisCard,
|
||||||
QWidget#ReceptionPage QFrame#ReceptionAiAssistantCard {
|
QWidget#ReceptionPage QFrame#ReceptionAiAssistantCard {
|
||||||
background-color: #FFFFFF;
|
background-color: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #103231, stop:0.6 #092020, stop:1 #061515);
|
||||||
border: 1px solid $ds_line;
|
border: 1px solid rgba(223, 199, 147, 108);
|
||||||
border-radius: $ds_radius_panel;
|
border-radius: $ds_radius_panel;
|
||||||
}
|
}
|
||||||
|
QWidget#ReceptionPage QFrame#ReceptionAiAnalysisCard QLabel,
|
||||||
|
QWidget#ReceptionPage QFrame#ReceptionAiAssistantCard QLabel {
|
||||||
|
color: #DDF0ED;
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
QWidget#ReceptionPage QStackedWidget#ReceptionAiAnalysisStack,
|
||||||
|
QWidget#ReceptionPage QStackedWidget#ReceptionAiAnalysisStack > QWidget,
|
||||||
|
QWidget#ReceptionPage QWidget#ReceptionAiAnalysisSections {
|
||||||
|
background: transparent;
|
||||||
|
border: 0;
|
||||||
|
}
|
||||||
QWidget#ReceptionPage QLabel#ReceptionAiTitle,
|
QWidget#ReceptionPage QLabel#ReceptionAiTitle,
|
||||||
QWidget#ReceptionPage QPushButton#ReceptionAiTitle {
|
QWidget#ReceptionPage QPushButton#ReceptionAiTitle {
|
||||||
|
color: #DFC793;
|
||||||
font-size: 14px;
|
font-size: 14px;
|
||||||
font-weight: 500;
|
font-weight: 600;
|
||||||
|
background: transparent;
|
||||||
|
border: 0;
|
||||||
}
|
}
|
||||||
|
QWidget#ReceptionPage QLabel#ReceptionAiAnalysisSnapshotMeta,
|
||||||
QWidget#ReceptionPage QLabel#ReceptionAiAssistantHint {
|
QWidget#ReceptionPage QLabel#ReceptionAiAssistantHint {
|
||||||
color: #5D6B80;
|
color: #93B8B4;
|
||||||
font-size: 13px;
|
font-size: 12px;
|
||||||
font-weight: 400;
|
font-weight: 400;
|
||||||
}
|
}
|
||||||
|
QWidget#ReceptionPage QComboBox#ReceptionAiAnalysisModelSelector {
|
||||||
|
background-color: rgba(255, 255, 255, 22);
|
||||||
|
border: 1px solid rgba(223, 199, 147, 92);
|
||||||
|
border-radius: 7px;
|
||||||
|
color: #F2FAF9;
|
||||||
|
padding: 2px 8px;
|
||||||
|
}
|
||||||
QWidget#ReceptionPage QPushButton[receptionAiPrompt="true"] {
|
QWidget#ReceptionPage QPushButton[receptionAiPrompt="true"] {
|
||||||
min-height: 28px;
|
min-height: 28px;
|
||||||
max-height: 28px;
|
max-height: 28px;
|
||||||
padding: 0 8px;
|
padding: 0 9px;
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
border-radius: 6px;
|
border-radius: 7px;
|
||||||
|
background-color: rgba(24, 176, 165, 42);
|
||||||
|
border: 1px solid rgba(84, 230, 193, 96);
|
||||||
|
color: #A8F3DF;
|
||||||
|
}
|
||||||
|
QWidget#ReceptionPage QPushButton[receptionAiPrompt="true"]:hover {
|
||||||
|
background-color: rgba(24, 176, 165, 86);
|
||||||
|
color: #FFFFFF;
|
||||||
}
|
}
|
||||||
QWidget#ReceptionPage QScrollArea#ReceptionInsightsScroll {
|
QWidget#ReceptionPage QScrollArea#ReceptionInsightsScroll {
|
||||||
background-color: transparent;
|
background-color: transparent;
|
||||||
|
|||||||
+2715
-2268
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,5 @@
|
|||||||
|
"""Cross-page reactive state stores for Clinical OS 3.0."""
|
||||||
|
|
||||||
|
from .patient_context_store import PatientContextStore, PatientSnapshot
|
||||||
|
|
||||||
|
__all__ = ["PatientContextStore", "PatientSnapshot"]
|
||||||
@@ -0,0 +1,265 @@
|
|||||||
|
"""Global clinical patient context bus shared across spatial workstation views."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from PySide6.QtCore import QObject, Signal
|
||||||
|
|
||||||
|
from ..widgets import display_text, first_value, gender_text
|
||||||
|
|
||||||
|
|
||||||
|
def _safe_int(value: Any, default: int = 0) -> int:
|
||||||
|
try:
|
||||||
|
return int(value)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return default
|
||||||
|
|
||||||
|
|
||||||
|
def _mask_phone(raw: Any) -> str:
|
||||||
|
text = str(raw or "").strip()
|
||||||
|
if not text or text == "—":
|
||||||
|
return "—"
|
||||||
|
if "*" in text:
|
||||||
|
return text
|
||||||
|
digits = "".join(ch for ch in text if ch.isdigit())
|
||||||
|
if len(digits) >= 7:
|
||||||
|
return f"{digits[:3]}****{digits[-4:]}"
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class PatientSnapshot:
|
||||||
|
"""Immutable active-patient summary surfaced in the spatial shell header."""
|
||||||
|
|
||||||
|
appointment_id: int = 0
|
||||||
|
diagnosis_id: int = 0
|
||||||
|
patient_id: int = 0
|
||||||
|
patient_name: str = "未选择患者"
|
||||||
|
gender_age: str = ""
|
||||||
|
phone: str = "—"
|
||||||
|
course_text: str = ""
|
||||||
|
clinical_diagnosis: str = "待选择接诊患者"
|
||||||
|
chief_complaint: str = ""
|
||||||
|
status_code: int = 0
|
||||||
|
status_text: str = "待接诊"
|
||||||
|
assistant_name: str = "—"
|
||||||
|
doctor_name: str = "—"
|
||||||
|
appointment_time: str = ""
|
||||||
|
raw_record: dict[str, Any] = field(default_factory=dict, compare=False)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def has_patient(self) -> bool:
|
||||||
|
return bool(
|
||||||
|
self.appointment_id > 0
|
||||||
|
or self.diagnosis_id > 0
|
||||||
|
or self.patient_id > 0
|
||||||
|
or (self.patient_name and self.patient_name not in {"—", "未选择患者"})
|
||||||
|
)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def subtitle_line(self) -> str:
|
||||||
|
parts = [
|
||||||
|
part
|
||||||
|
for part in (
|
||||||
|
self.gender_age,
|
||||||
|
self.clinical_diagnosis if self.clinical_diagnosis != "—" else "",
|
||||||
|
f"病程 {self.course_text}" if self.course_text and self.course_text != "—" else "",
|
||||||
|
self.appointment_time,
|
||||||
|
)
|
||||||
|
if part
|
||||||
|
]
|
||||||
|
return " · ".join(parts[:3]) if parts else "从今日门诊计划或挂号队列选择患者"
|
||||||
|
|
||||||
|
|
||||||
|
class PatientContextStore(QObject):
|
||||||
|
"""Reactive store broadcasting active patient and bottom-sheet state across pages."""
|
||||||
|
|
||||||
|
active_patient_changed = Signal(object)
|
||||||
|
active_appointment_changed = Signal(int)
|
||||||
|
bottom_sheet_mode_changed = Signal(bool)
|
||||||
|
cockpit_mode_changed = Signal(str)
|
||||||
|
|
||||||
|
def __init__(self, parent: QObject | None = None) -> None:
|
||||||
|
super().__init__(parent)
|
||||||
|
self._current_patient = PatientSnapshot()
|
||||||
|
self._bottom_sheet_expanded = False
|
||||||
|
self._cockpit_mode = "cockpit"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def current_patient(self) -> PatientSnapshot:
|
||||||
|
return self._current_patient
|
||||||
|
|
||||||
|
@property
|
||||||
|
def bottom_sheet_expanded(self) -> bool:
|
||||||
|
return self._bottom_sheet_expanded
|
||||||
|
|
||||||
|
@property
|
||||||
|
def cockpit_mode(self) -> str:
|
||||||
|
return self._cockpit_mode
|
||||||
|
|
||||||
|
def set_bottom_sheet_expanded(self, expanded: bool) -> None:
|
||||||
|
target = bool(expanded)
|
||||||
|
if self._bottom_sheet_expanded == target:
|
||||||
|
return
|
||||||
|
self._bottom_sheet_expanded = target
|
||||||
|
self.bottom_sheet_mode_changed.emit(target)
|
||||||
|
|
||||||
|
def toggle_bottom_sheet(self) -> bool:
|
||||||
|
self.set_bottom_sheet_expanded(not self._bottom_sheet_expanded)
|
||||||
|
return self._bottom_sheet_expanded
|
||||||
|
|
||||||
|
def set_cockpit_mode(self, mode: str) -> None:
|
||||||
|
normalized = "chart" if str(mode).strip().lower() == "chart" else "cockpit"
|
||||||
|
if self._cockpit_mode == normalized:
|
||||||
|
return
|
||||||
|
self._cockpit_mode = normalized
|
||||||
|
self.cockpit_mode_changed.emit(normalized)
|
||||||
|
|
||||||
|
def clear(self) -> None:
|
||||||
|
empty = PatientSnapshot()
|
||||||
|
if self._current_patient == empty:
|
||||||
|
return
|
||||||
|
self._current_patient = empty
|
||||||
|
self.active_patient_changed.emit(empty)
|
||||||
|
self.active_appointment_changed.emit(0)
|
||||||
|
|
||||||
|
def set_snapshot(self, snapshot: PatientSnapshot) -> None:
|
||||||
|
previous_appointment = self._current_patient.appointment_id
|
||||||
|
if self._current_patient == snapshot:
|
||||||
|
return
|
||||||
|
self._current_patient = snapshot
|
||||||
|
self.active_patient_changed.emit(snapshot)
|
||||||
|
if snapshot.appointment_id != previous_appointment:
|
||||||
|
self.active_appointment_changed.emit(snapshot.appointment_id)
|
||||||
|
|
||||||
|
def update_from_reception(
|
||||||
|
self,
|
||||||
|
appointment: Any,
|
||||||
|
patient: Any = None,
|
||||||
|
diagnosis: Any = None,
|
||||||
|
) -> PatientSnapshot:
|
||||||
|
"""Build and publish a rich snapshot from reception detail payloads."""
|
||||||
|
|
||||||
|
sources = (diagnosis or {}, patient or {}, appointment or {})
|
||||||
|
name = display_text(
|
||||||
|
first_value(
|
||||||
|
appointment,
|
||||||
|
"patient_name",
|
||||||
|
"name",
|
||||||
|
default=first_value(patient, "name", "patient_name", default="患者"),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
raw_gender = next(
|
||||||
|
(
|
||||||
|
first_value(src, "gender_desc", "gender", default=None)
|
||||||
|
for src in sources
|
||||||
|
if first_value(src, "gender_desc", "gender", default=None) not in (None, "")
|
||||||
|
),
|
||||||
|
"",
|
||||||
|
)
|
||||||
|
gender = gender_text(raw_gender) if raw_gender not in (None, "") else ""
|
||||||
|
age = first_value(
|
||||||
|
diagnosis,
|
||||||
|
"age",
|
||||||
|
default=first_value(patient, "age", default=first_value(appointment, "age", default="")),
|
||||||
|
)
|
||||||
|
gender_age = " · ".join(
|
||||||
|
part
|
||||||
|
for part in (
|
||||||
|
gender if gender and gender != "—" else "",
|
||||||
|
f"{age}岁" if age not in (None, "", "—") else "",
|
||||||
|
)
|
||||||
|
if part
|
||||||
|
)
|
||||||
|
phone = _mask_phone(
|
||||||
|
first_value(
|
||||||
|
patient,
|
||||||
|
"phone",
|
||||||
|
"mobile",
|
||||||
|
default=first_value(appointment, "patient_phone", "phone", default="—"),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
course = display_text(
|
||||||
|
first_value(
|
||||||
|
diagnosis,
|
||||||
|
"disease_course_text",
|
||||||
|
"diabetes_history_text",
|
||||||
|
"diabetes_discovery_year_text",
|
||||||
|
default="",
|
||||||
|
),
|
||||||
|
"",
|
||||||
|
)
|
||||||
|
clinical_diag = display_text(
|
||||||
|
first_value(
|
||||||
|
diagnosis,
|
||||||
|
"clinical_diagnosis",
|
||||||
|
"diagnosis_name",
|
||||||
|
"disease_name",
|
||||||
|
default="中医糖代谢调理",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
chief = display_text(
|
||||||
|
first_value(diagnosis, "chief_complaint", "complaint", default=""),
|
||||||
|
"",
|
||||||
|
)
|
||||||
|
status_code = _safe_int(first_value(appointment, "status", default=1), 1)
|
||||||
|
status_map = {1: "待接诊", 2: "已取消", 3: "已完成", 4: "已过号"}
|
||||||
|
status_text = display_text(
|
||||||
|
first_value(
|
||||||
|
appointment,
|
||||||
|
"status_desc",
|
||||||
|
"status_text",
|
||||||
|
default=status_map.get(status_code, "待接诊"),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
appt_id = _safe_int(first_value(appointment, "id", "appointment_id", default=0))
|
||||||
|
diag_id = _safe_int(
|
||||||
|
first_value(
|
||||||
|
diagnosis,
|
||||||
|
"id",
|
||||||
|
"diagnosis_id",
|
||||||
|
default=first_value(appointment, "diagnosis_id", "patient_id", default=0),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
pat_id = _safe_int(
|
||||||
|
first_value(
|
||||||
|
appointment,
|
||||||
|
"source_patient_id",
|
||||||
|
"patient_id",
|
||||||
|
default=first_value(patient, "id", "source_patient_id", default=0),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
raw: dict[str, Any] = {}
|
||||||
|
if isinstance(appointment, dict):
|
||||||
|
raw.update(appointment)
|
||||||
|
snapshot = PatientSnapshot(
|
||||||
|
appointment_id=appt_id,
|
||||||
|
diagnosis_id=diag_id,
|
||||||
|
patient_id=pat_id,
|
||||||
|
patient_name=name,
|
||||||
|
gender_age=gender_age,
|
||||||
|
phone=phone,
|
||||||
|
course_text=course,
|
||||||
|
clinical_diagnosis=clinical_diag,
|
||||||
|
chief_complaint=chief,
|
||||||
|
status_code=status_code,
|
||||||
|
status_text=status_text,
|
||||||
|
assistant_name=display_text(first_value(appointment, "assistant_name", default="—")),
|
||||||
|
doctor_name=display_text(first_value(appointment, "doctor_name", default="—")),
|
||||||
|
appointment_time=display_text(
|
||||||
|
first_value(appointment, "appointment_time_text", "appointment_time", default=""),
|
||||||
|
"",
|
||||||
|
),
|
||||||
|
raw_record=raw,
|
||||||
|
)
|
||||||
|
self.set_snapshot(snapshot)
|
||||||
|
return snapshot
|
||||||
|
|
||||||
|
def update_from_row(self, row: Any) -> PatientSnapshot:
|
||||||
|
"""Build and publish a lightweight snapshot when selecting a list/table row."""
|
||||||
|
|
||||||
|
if not row:
|
||||||
|
return self._current_patient
|
||||||
|
return self.update_from_reception(row, row, row)
|
||||||
@@ -40,7 +40,7 @@ from doctor_workstation.resources import resource_path
|
|||||||
|
|
||||||
# ``motion`` deliberately imports nothing from this module, so this stays a
|
# ``motion`` deliberately imports nothing from this module, so this stays a
|
||||||
# one-way dependency: tokens here, animation there.
|
# one-way dependency: tokens here, animation there.
|
||||||
from . import motion
|
from . import interactions, motion
|
||||||
from .design_system import PALETTE, RADII, SPACING, clinical_stylesheet
|
from .design_system import PALETTE, RADII, SPACING, clinical_stylesheet
|
||||||
|
|
||||||
# Shared reading colors keep native pages and dialog chrome consistent.
|
# Shared reading colors keep native pages and dialog chrome consistent.
|
||||||
@@ -81,6 +81,11 @@ COLORS = {
|
|||||||
"teal": PALETTE["accent"],
|
"teal": PALETTE["accent"],
|
||||||
"teal_dark": PALETTE["accent_pressed"],
|
"teal_dark": PALETTE["accent_pressed"],
|
||||||
"teal_pale": PALETTE["accent_soft"],
|
"teal_pale": PALETTE["accent_soft"],
|
||||||
|
"gold": PALETTE["gold"],
|
||||||
|
"gold_light": PALETTE["gold_light"],
|
||||||
|
"gold_soft": PALETTE["gold_soft"],
|
||||||
|
"obsidian": PALETTE["obsidian"],
|
||||||
|
"obsidian_alt": PALETTE["obsidian_alt"],
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -375,12 +380,12 @@ QPushButton:disabled {
|
|||||||
|
|
||||||
QPushButton[variant="primary"] {
|
QPushButton[variant="primary"] {
|
||||||
color: #FFFFFF;
|
color: #FFFFFF;
|
||||||
background-color: $indigo;
|
background-color: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #12857D, stop:1 $indigo);
|
||||||
border-color: $indigo;
|
border-color: $indigo;
|
||||||
}
|
}
|
||||||
QPushButton[variant="primary"]:hover,
|
QPushButton[variant="primary"]:hover,
|
||||||
QPushButton[variant="primary"]:checked:hover {
|
QPushButton[variant="primary"]:checked:hover {
|
||||||
background-color: $indigo_hover;
|
background-color: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #0E726B, stop:1 $indigo_hover);
|
||||||
border-color: $indigo_hover;
|
border-color: $indigo_hover;
|
||||||
}
|
}
|
||||||
QPushButton[variant="primary"]:pressed,
|
QPushButton[variant="primary"]:pressed,
|
||||||
@@ -389,7 +394,7 @@ QPushButton[variant="primary"]:checked {
|
|||||||
border-color: $indigo_pressed;
|
border-color: $indigo_pressed;
|
||||||
}
|
}
|
||||||
QPushButton[variant="primary"]:focus {
|
QPushButton[variant="primary"]:focus {
|
||||||
border: 1px solid $indigo_pressed;
|
border: 1px solid $focus;
|
||||||
background-color: $indigo_hover;
|
background-color: $indigo_hover;
|
||||||
}
|
}
|
||||||
QPushButton[variant="primary"]:disabled {
|
QPushButton[variant="primary"]:disabled {
|
||||||
@@ -401,12 +406,12 @@ QPushButton[variant="primary"]:disabled {
|
|||||||
QPushButton[variant="secondary"] {
|
QPushButton[variant="secondary"] {
|
||||||
color: $indigo_hover;
|
color: $indigo_hover;
|
||||||
background-color: $indigo_pale;
|
background-color: $indigo_pale;
|
||||||
border-color: $indigo_pale;
|
border-color: #C4E2DD;
|
||||||
}
|
}
|
||||||
QPushButton[variant="secondary"]:hover {
|
QPushButton[variant="secondary"]:hover {
|
||||||
color: $indigo_pressed;
|
color: $indigo_pressed;
|
||||||
background-color: $raised;
|
background-color: #D7EFEA;
|
||||||
border-color: $indigo_hover;
|
border-color: #9CCFC7;
|
||||||
}
|
}
|
||||||
QPushButton[variant="secondary"]:pressed,
|
QPushButton[variant="secondary"]:pressed,
|
||||||
QPushButton[variant="secondary"]:checked {
|
QPushButton[variant="secondary"]:checked {
|
||||||
@@ -616,7 +621,7 @@ QLineEdit, QTextEdit, QPlainTextEdit, QComboBox, QDateEdit, QDateTimeEdit,
|
|||||||
QTimeEdit, QSpinBox, QDoubleSpinBox, QKeySequenceEdit {
|
QTimeEdit, QSpinBox, QDoubleSpinBox, QKeySequenceEdit {
|
||||||
min-height: $h_default;
|
min-height: $h_default;
|
||||||
padding: 0 $pad_control;
|
padding: 0 $pad_control;
|
||||||
border: 1px solid $line;
|
border: 1px solid $line_soft;
|
||||||
border-radius: $r_md;
|
border-radius: $r_md;
|
||||||
background-color: $surface;
|
background-color: $surface;
|
||||||
color: $text;
|
color: $text;
|
||||||
@@ -626,11 +631,11 @@ QTimeEdit, QSpinBox, QDoubleSpinBox, QKeySequenceEdit {
|
|||||||
QTextEdit, QPlainTextEdit { padding: 7px $pad_control; }
|
QTextEdit, QPlainTextEdit { padding: 7px $pad_control; }
|
||||||
QLineEdit:hover, QTextEdit:hover, QPlainTextEdit:hover, QComboBox:hover,
|
QLineEdit:hover, QTextEdit:hover, QPlainTextEdit:hover, QComboBox:hover,
|
||||||
QDateEdit:hover, QDateTimeEdit:hover, QTimeEdit:hover, QSpinBox:hover,
|
QDateEdit:hover, QDateTimeEdit:hover, QTimeEdit:hover, QSpinBox:hover,
|
||||||
QDoubleSpinBox:hover, QKeySequenceEdit:hover { border-color: $indigo_hover; }
|
QDoubleSpinBox:hover, QKeySequenceEdit:hover { border-color: #8FBDB6; }
|
||||||
QLineEdit:focus, QTextEdit:focus, QPlainTextEdit:focus, QComboBox:focus,
|
QLineEdit:focus, QTextEdit:focus, QPlainTextEdit:focus, QComboBox:focus,
|
||||||
QDateEdit:focus, QDateTimeEdit:focus, QTimeEdit:focus, QSpinBox:focus,
|
QDateEdit:focus, QDateTimeEdit:focus, QTimeEdit:focus, QSpinBox:focus,
|
||||||
QDoubleSpinBox:focus, QKeySequenceEdit:focus {
|
QDoubleSpinBox:focus, QKeySequenceEdit:focus {
|
||||||
border: 1px solid $indigo;
|
border: 1.5px solid $focus;
|
||||||
background-color: $surface;
|
background-color: $surface;
|
||||||
}
|
}
|
||||||
QLineEdit:read-only, QTextEdit:read-only, QPlainTextEdit:read-only {
|
QLineEdit:read-only, QTextEdit:read-only, QPlainTextEdit:read-only {
|
||||||
@@ -1500,15 +1505,28 @@ def _size_new_window_to_main(window: QWidget) -> None:
|
|||||||
|
|
||||||
target_width = target.width()
|
target_width = target.width()
|
||||||
target_height = target.height()
|
target_height = target.height()
|
||||||
if window.minimumWidth() > target_width:
|
# 紧凑业务轻弹窗(如二维码、完成确认、收退款、更新等)保持自身合理尺寸并居中,
|
||||||
window.setMinimumWidth(target_width)
|
# 仅大型工作台窗口(宽>=760 且高>=640)扩展至主视窗 85%,避免小窗被强行撑大造成内容错位。
|
||||||
if window.minimumHeight() > target_height:
|
current_size = window.size()
|
||||||
window.setMinimumHeight(target_height)
|
hint_size = window.sizeHint()
|
||||||
if window.maximumWidth() < target_width:
|
desired_w = max(current_size.width(), hint_size.width(), window.minimumWidth())
|
||||||
window.setMaximumWidth(target_width)
|
desired_h = max(current_size.height(), hint_size.height(), window.minimumHeight())
|
||||||
if window.maximumHeight() < target_height:
|
is_compact_dialog = isinstance(window, QDialog) and (desired_w < 760 or desired_h < 640)
|
||||||
window.setMaximumHeight(target_height)
|
if is_compact_dialog:
|
||||||
window.resize(target_width, target_height)
|
final_width = min(desired_w, target_width)
|
||||||
|
final_height = min(desired_h, target_height)
|
||||||
|
else:
|
||||||
|
final_width = target_width
|
||||||
|
final_height = target_height
|
||||||
|
if window.minimumWidth() > final_width:
|
||||||
|
window.setMinimumWidth(final_width)
|
||||||
|
if window.minimumHeight() > final_height:
|
||||||
|
window.setMinimumHeight(final_height)
|
||||||
|
if window.maximumWidth() < final_width:
|
||||||
|
window.setMaximumWidth(final_width)
|
||||||
|
if window.maximumHeight() < final_height:
|
||||||
|
window.setMaximumHeight(final_height)
|
||||||
|
window.resize(final_width, final_height)
|
||||||
frame = window.frameGeometry()
|
frame = window.frameGeometry()
|
||||||
window.move(
|
window.move(
|
||||||
target.center().x() - frame.width() // 2,
|
target.center().x() - frame.width() // 2,
|
||||||
@@ -1583,6 +1601,7 @@ class _BusinessDialogStyleFilter(QObject):
|
|||||||
|
|
||||||
|
|
||||||
def _install_business_dialog_styling(app: QApplication) -> None:
|
def _install_business_dialog_styling(app: QApplication) -> None:
|
||||||
|
interactions.install_tactile_interactions(app)
|
||||||
existing = getattr(app, "_doctor_business_dialog_style_filter", None)
|
existing = getattr(app, "_doctor_business_dialog_style_filter", None)
|
||||||
if existing is not None:
|
if existing is not None:
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
"""Presentation view-models for the Clinical OS 3.0 workstation."""
|
||||||
|
|
||||||
|
from .cockpit_vm import (
|
||||||
|
AuroraCardVM,
|
||||||
|
CareJourneyVM,
|
||||||
|
CockpitSnapshotVM,
|
||||||
|
DiurnalSlot,
|
||||||
|
DiurnalStabilityVM,
|
||||||
|
GlycemicProgressionVM,
|
||||||
|
JourneyDayCell,
|
||||||
|
JourneyPhaseSpan,
|
||||||
|
ObsidianAuroraVM,
|
||||||
|
ProgressionPoint,
|
||||||
|
SyndromeTwinVM,
|
||||||
|
TwinCalloutNode,
|
||||||
|
VitalMiniBrick,
|
||||||
|
derive_cockpit_snapshot,
|
||||||
|
)
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"AuroraCardVM",
|
||||||
|
"CareJourneyVM",
|
||||||
|
"CockpitSnapshotVM",
|
||||||
|
"DiurnalSlot",
|
||||||
|
"DiurnalStabilityVM",
|
||||||
|
"GlycemicProgressionVM",
|
||||||
|
"JourneyDayCell",
|
||||||
|
"JourneyPhaseSpan",
|
||||||
|
"ObsidianAuroraVM",
|
||||||
|
"ProgressionPoint",
|
||||||
|
"SyndromeTwinVM",
|
||||||
|
"TwinCalloutNode",
|
||||||
|
"VitalMiniBrick",
|
||||||
|
"derive_cockpit_snapshot",
|
||||||
|
]
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,23 @@
|
|||||||
|
"""Hardware-antialiased QPainter medical micro-charts & digital twin widgets."""
|
||||||
|
|
||||||
|
from .aurora_sheet import ArcRhythmGaugeWidget, AuroraGlassCardWidget, CollapsibleObsidianSheet
|
||||||
|
from .context_bridge_bar import SpatialContextBridgeBar
|
||||||
|
from .diurnal_strip import DiurnalStabilityCard
|
||||||
|
from .journey_track import CareJourneyCard
|
||||||
|
from .pill_chart import PillProgressionCard
|
||||||
|
from .reception_cockpit import ReceptionDigitalTwinCockpit
|
||||||
|
from .twin_stage import ClinicalTwinStageWidget
|
||||||
|
from .week_strip import WeekCalendarStripWidget
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"ArcRhythmGaugeWidget",
|
||||||
|
"AuroraGlassCardWidget",
|
||||||
|
"CareJourneyCard",
|
||||||
|
"ClinicalTwinStageWidget",
|
||||||
|
"CollapsibleObsidianSheet",
|
||||||
|
"DiurnalStabilityCard",
|
||||||
|
"PillProgressionCard",
|
||||||
|
"ReceptionDigitalTwinCockpit",
|
||||||
|
"SpatialContextBridgeBar",
|
||||||
|
"WeekCalendarStripWidget",
|
||||||
|
]
|
||||||
@@ -0,0 +1,522 @@
|
|||||||
|
"""Pull-Up Deep Obsidian Aurora-Glass AI Sheet bound strictly to real AI reports."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import math
|
||||||
|
|
||||||
|
from PySide6.QtCore import QPointF, QRectF, Qt, Signal
|
||||||
|
from PySide6.QtGui import (
|
||||||
|
QColor,
|
||||||
|
QFont,
|
||||||
|
QMouseEvent,
|
||||||
|
QPainter,
|
||||||
|
QPainterPath,
|
||||||
|
QPen,
|
||||||
|
QRadialGradient,
|
||||||
|
QTextOption,
|
||||||
|
)
|
||||||
|
from PySide6.QtWidgets import (
|
||||||
|
QFrame,
|
||||||
|
QHBoxLayout,
|
||||||
|
QLabel,
|
||||||
|
QPushButton,
|
||||||
|
QSizePolicy,
|
||||||
|
QToolTip,
|
||||||
|
QVBoxLayout,
|
||||||
|
QWidget,
|
||||||
|
)
|
||||||
|
|
||||||
|
from ..reception_style import body_family, heading_family, number_family
|
||||||
|
from ..viewmodels.cockpit_vm import AuroraCardVM, ObsidianAuroraVM
|
||||||
|
|
||||||
|
|
||||||
|
class AuroraGlassCardWidget(QWidget):
|
||||||
|
"""Frosted dark Aurora-Mesh card displaying real backend AI narrative & risks."""
|
||||||
|
|
||||||
|
clicked = Signal()
|
||||||
|
|
||||||
|
def __init__(self, parent: QWidget | None = None) -> None:
|
||||||
|
super().__init__(parent)
|
||||||
|
self.setObjectName("AuroraGlassCardWidget")
|
||||||
|
self.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||||
|
self.setMinimumSize(196, 152)
|
||||||
|
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
|
||||||
|
self.setFixedHeight(162)
|
||||||
|
self._vm: AuroraCardVM | None = None
|
||||||
|
self._hovered = False
|
||||||
|
|
||||||
|
def set_view_model(self, vm: AuroraCardVM) -> None:
|
||||||
|
self._vm = vm
|
||||||
|
self.setToolTip(vm.body_text)
|
||||||
|
self.update()
|
||||||
|
|
||||||
|
def enterEvent(self, event: object) -> None: # noqa: N802
|
||||||
|
self._hovered = True
|
||||||
|
self.update()
|
||||||
|
super().enterEvent(event) # type: ignore[arg-type]
|
||||||
|
|
||||||
|
def leaveEvent(self, event: object) -> None: # noqa: N802
|
||||||
|
self._hovered = False
|
||||||
|
self.update()
|
||||||
|
super().leaveEvent(event) # type: ignore[arg-type]
|
||||||
|
|
||||||
|
def mousePressEvent(self, event: QMouseEvent) -> None: # noqa: N802
|
||||||
|
if event.button() == Qt.MouseButton.LeftButton:
|
||||||
|
self.clicked.emit()
|
||||||
|
event.accept()
|
||||||
|
return
|
||||||
|
super().mousePressEvent(event)
|
||||||
|
|
||||||
|
def paintEvent(self, _event: object) -> None: # noqa: N802
|
||||||
|
painter = QPainter(self)
|
||||||
|
painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
|
||||||
|
painter.setRenderHint(QPainter.RenderHint.TextAntialiasing, True)
|
||||||
|
|
||||||
|
rect = QRectF(self.rect()).adjusted(1.0, 1.0, -1.0, -1.0)
|
||||||
|
path = QPainterPath()
|
||||||
|
path.addRoundedRect(rect, 20.0, 20.0)
|
||||||
|
|
||||||
|
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||||
|
painter.fillPath(path, QColor(32, 40, 39, 240))
|
||||||
|
|
||||||
|
vm = self._vm
|
||||||
|
tint = vm.tint if vm else "cyan"
|
||||||
|
glow1 = QRadialGradient(
|
||||||
|
QPointF(rect.left() + rect.width() * 0.75, rect.top() + rect.height() * 0.32),
|
||||||
|
rect.width() * 0.72,
|
||||||
|
)
|
||||||
|
if tint == "cyan":
|
||||||
|
glow1.setColorAt(0.0, QColor(88, 168, 182, 98))
|
||||||
|
glow1.setColorAt(0.55, QColor(58, 118, 130, 52))
|
||||||
|
glow1.setColorAt(1.0, QColor(28, 38, 38, 0))
|
||||||
|
accent_c = QColor("#A9DCE4")
|
||||||
|
elif tint == "olive":
|
||||||
|
glow1.setColorAt(0.0, QColor(148, 162, 72, 96))
|
||||||
|
glow1.setColorAt(0.55, QColor(96, 112, 48, 52))
|
||||||
|
glow1.setColorAt(1.0, QColor(28, 38, 32, 0))
|
||||||
|
accent_c = QColor("#DCE694")
|
||||||
|
else:
|
||||||
|
glow1.setColorAt(0.0, QColor(206, 128, 86, 102))
|
||||||
|
glow1.setColorAt(0.55, QColor(142, 84, 58, 54))
|
||||||
|
glow1.setColorAt(1.0, QColor(38, 30, 28, 0))
|
||||||
|
accent_c = QColor("#F2C4A8")
|
||||||
|
|
||||||
|
painter.fillPath(path, glow1)
|
||||||
|
painter.setPen(QPen(QColor(255, 255, 255, 78 if self._hovered else 42), 1.0))
|
||||||
|
painter.drawPath(path)
|
||||||
|
|
||||||
|
if vm is None:
|
||||||
|
return
|
||||||
|
|
||||||
|
left = rect.left() + 16.0
|
||||||
|
right = rect.right() - 16.0
|
||||||
|
avail_w = max(120.0, right - left)
|
||||||
|
|
||||||
|
# Header: Accent dot + Title + Status Badge Pill
|
||||||
|
painter.setPen(Qt.PenStyle.NoPen)
|
||||||
|
painter.setBrush(accent_c)
|
||||||
|
painter.drawEllipse(QPointF(left + 5, rect.top() + 21), 4.0, 4.0)
|
||||||
|
|
||||||
|
t_font = QFont(heading_family())
|
||||||
|
t_font.setPixelSize(14)
|
||||||
|
t_font.setWeight(QFont.Weight.DemiBold)
|
||||||
|
painter.setFont(t_font)
|
||||||
|
painter.setPen(QColor("#F6FAF9"))
|
||||||
|
painter.drawText(
|
||||||
|
QRectF(left + 15, rect.top() + 11, avail_w - 86, 20),
|
||||||
|
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
|
||||||
|
vm.title,
|
||||||
|
)
|
||||||
|
|
||||||
|
b_font = QFont(body_family())
|
||||||
|
b_font.setPixelSize(10)
|
||||||
|
b_font.setWeight(QFont.Weight.DemiBold)
|
||||||
|
painter.setFont(b_font)
|
||||||
|
bw = float(painter.fontMetrics().horizontalAdvance(vm.badge_text) + 16)
|
||||||
|
b_rect = QRectF(right - bw, rect.top() + 12, bw, 19)
|
||||||
|
bp = QPainterPath()
|
||||||
|
bp.addRoundedRect(b_rect, 9.5, 9.5)
|
||||||
|
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||||
|
painter.fillPath(bp, QColor(255, 255, 255, 28))
|
||||||
|
painter.setPen(accent_c)
|
||||||
|
painter.drawText(b_rect, Qt.AlignmentFlag.AlignCenter, vm.badge_text)
|
||||||
|
|
||||||
|
s_font = QFont(body_family())
|
||||||
|
s_font.setPixelSize(11)
|
||||||
|
painter.setFont(s_font)
|
||||||
|
painter.setPen(QColor(215, 230, 227, 160))
|
||||||
|
painter.drawText(
|
||||||
|
QRectF(left + 15, rect.top() + 31, avail_w - 16, 15),
|
||||||
|
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
|
||||||
|
vm.subtitle,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Divider line
|
||||||
|
painter.setPen(QPen(QColor(255, 255, 255, 24), 1.0))
|
||||||
|
painter.drawLine(QPointF(left, rect.top() + 51), QPointF(right, rect.top() + 51))
|
||||||
|
|
||||||
|
# Real AI Narrative Body (clean wrapped clinical text, max 4 lines)
|
||||||
|
body_font = QFont(body_family())
|
||||||
|
body_font.setPixelSize(12)
|
||||||
|
painter.setFont(body_font)
|
||||||
|
painter.setPen(QColor("#EEF5F3"))
|
||||||
|
body_box = QRectF(left, rect.top() + 57, avail_w, 74)
|
||||||
|
opt = QTextOption(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignTop)
|
||||||
|
opt.setWrapMode(QTextOption.WrapMode.WordWrap)
|
||||||
|
text_to_draw = vm.body_text
|
||||||
|
if len(text_to_draw) > 108:
|
||||||
|
text_to_draw = f"{text_to_draw[:106]}…"
|
||||||
|
painter.drawText(body_box, text_to_draw, opt)
|
||||||
|
|
||||||
|
# Footer metadata
|
||||||
|
painter.setFont(s_font)
|
||||||
|
painter.setPen(QColor(210, 226, 223, 155))
|
||||||
|
painter.drawText(
|
||||||
|
QRectF(left, rect.bottom() - 23, avail_w * 0.62, 16),
|
||||||
|
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
|
||||||
|
vm.foot_left,
|
||||||
|
)
|
||||||
|
painter.setPen(accent_c)
|
||||||
|
painter.drawText(
|
||||||
|
QRectF(right - avail_w * 0.38, rect.bottom() - 23, avail_w * 0.38, 16),
|
||||||
|
Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter,
|
||||||
|
vm.foot_right,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class ArcRhythmGaugeWidget(QWidget):
|
||||||
|
"""Objective 6-dimension Clinical Record Completeness speedometer gauge."""
|
||||||
|
|
||||||
|
def __init__(self, parent: QWidget | None = None) -> None:
|
||||||
|
super().__init__(parent)
|
||||||
|
self.setObjectName("ArcRhythmGaugeWidget")
|
||||||
|
self.setMouseTracking(True)
|
||||||
|
self.setFixedSize(202, 162)
|
||||||
|
self._value_text = "0/6"
|
||||||
|
self._unit_text = "项"
|
||||||
|
self._caption = "病历实采完备度"
|
||||||
|
self._ratio = 0.08
|
||||||
|
self._tooltip = ""
|
||||||
|
|
||||||
|
def set_gauge(
|
||||||
|
self,
|
||||||
|
value_text: str,
|
||||||
|
unit_text: str,
|
||||||
|
caption: str,
|
||||||
|
ratio: float,
|
||||||
|
tooltip: str = "",
|
||||||
|
) -> None:
|
||||||
|
self._value_text = value_text
|
||||||
|
self._unit_text = unit_text
|
||||||
|
self._caption = caption
|
||||||
|
self._ratio = max(0.05, min(1.0, ratio))
|
||||||
|
self._tooltip = tooltip
|
||||||
|
self.setToolTip(tooltip)
|
||||||
|
self.update()
|
||||||
|
|
||||||
|
def mouseMoveEvent(self, event: QMouseEvent) -> None: # noqa: N802
|
||||||
|
if self._tooltip:
|
||||||
|
QToolTip.showText(event.globalPosition().toPoint(), self._tooltip, self)
|
||||||
|
super().mouseMoveEvent(event)
|
||||||
|
|
||||||
|
def paintEvent(self, _event: object) -> None: # noqa: N802
|
||||||
|
painter = QPainter(self)
|
||||||
|
painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
|
||||||
|
painter.setRenderHint(QPainter.RenderHint.TextAntialiasing, True)
|
||||||
|
|
||||||
|
rect = QRectF(self.rect())
|
||||||
|
cx = rect.center().x()
|
||||||
|
cy = rect.top() + 92.0
|
||||||
|
radius = 66.0
|
||||||
|
arc_box = QRectF(cx - radius, cy - radius, radius * 2.0, radius * 2.0)
|
||||||
|
|
||||||
|
hemi = QRadialGradient(QPointF(cx, cy), radius)
|
||||||
|
hemi.setColorAt(0.0, QColor(255, 255, 255, 24))
|
||||||
|
hemi.setColorAt(1.0, QColor(255, 255, 255, 0))
|
||||||
|
painter.setPen(Qt.PenStyle.NoPen)
|
||||||
|
painter.setBrush(hemi)
|
||||||
|
painter.drawPie(arc_box.adjusted(10, 10, -10, -10), 0, 180 * 16)
|
||||||
|
|
||||||
|
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||||
|
painter.setPen(QPen(QColor(255, 255, 255, 42), 3.0, Qt.PenStyle.SolidLine, Qt.PenCapStyle.RoundCap))
|
||||||
|
painter.drawArc(arc_box, 0, 180 * 16)
|
||||||
|
|
||||||
|
span_deg = self._ratio * 180.0
|
||||||
|
painter.setPen(QPen(QColor("#8CE0CB"), 3.4, Qt.PenStyle.SolidLine, Qt.PenCapStyle.RoundCap))
|
||||||
|
painter.drawArc(arc_box, int(180 * 16), int(-span_deg * 16))
|
||||||
|
|
||||||
|
# 6 dimension ticks along semi-circle
|
||||||
|
for step in range(7):
|
||||||
|
angle_rad = math.pi - (step / 6.0) * math.pi
|
||||||
|
p1 = QPointF(cx + math.cos(angle_rad) * (radius - 8), cy - math.sin(angle_rad) * (radius - 8))
|
||||||
|
p2 = QPointF(cx + math.cos(angle_rad) * (radius - 14), cy - math.sin(angle_rad) * (radius - 14))
|
||||||
|
painter.setPen(QPen(QColor(255, 255, 255, 78), 1.2))
|
||||||
|
painter.drawLine(p1, p2)
|
||||||
|
|
||||||
|
needle_rad = math.pi - self._ratio * math.pi
|
||||||
|
tip = QPointF(cx + math.cos(needle_rad) * (radius - 5), cy - math.sin(needle_rad) * (radius - 5))
|
||||||
|
arc_dot = QPointF(cx + math.cos(needle_rad) * radius, cy - math.sin(needle_rad) * radius)
|
||||||
|
painter.setPen(QPen(QColor(255, 255, 255, 210), 1.6))
|
||||||
|
painter.drawLine(QPointF(cx, cy), tip)
|
||||||
|
painter.setPen(Qt.PenStyle.NoPen)
|
||||||
|
painter.setBrush(QColor("#FFFFFF"))
|
||||||
|
painter.drawEllipse(QPointF(cx, cy), 3.5, 3.5)
|
||||||
|
painter.drawEllipse(arc_dot, 4.0, 4.0)
|
||||||
|
|
||||||
|
cap_font = QFont(body_family())
|
||||||
|
cap_font.setPixelSize(11)
|
||||||
|
painter.setFont(cap_font)
|
||||||
|
painter.setPen(QColor(210, 224, 222, 185))
|
||||||
|
painter.drawText(QRectF(0, cy + 7, rect.width(), 16), Qt.AlignmentFlag.AlignCenter, self._caption)
|
||||||
|
|
||||||
|
val_font = QFont(number_family())
|
||||||
|
val_font.setPixelSize(27)
|
||||||
|
val_font.setWeight(QFont.Weight.DemiBold)
|
||||||
|
painter.setFont(val_font)
|
||||||
|
painter.setPen(QColor("#FFFFFF"))
|
||||||
|
vw = float(painter.fontMetrics().horizontalAdvance(self._value_text))
|
||||||
|
total_w = vw + 26.0
|
||||||
|
vx = cx - total_w * 0.5
|
||||||
|
painter.drawText(
|
||||||
|
QRectF(vx, cy + 24, vw + 4, 34),
|
||||||
|
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
|
||||||
|
self._value_text,
|
||||||
|
)
|
||||||
|
|
||||||
|
painter.setFont(cap_font)
|
||||||
|
painter.setPen(QColor(210, 224, 222, 170))
|
||||||
|
painter.drawText(QRectF(vx + vw + 5, cy + 31, 30, 22), Qt.AlignmentFlag.AlignLeft, self._unit_text)
|
||||||
|
|
||||||
|
|
||||||
|
class CollapsibleObsidianSheet(QWidget):
|
||||||
|
"""Bottom pull-up obsidian sheet displaying real Qwen / OpenAI / Doubao clinical reports."""
|
||||||
|
|
||||||
|
expanded_changed = Signal(bool)
|
||||||
|
open_ai_report_requested = Signal()
|
||||||
|
open_ai_consult_requested = Signal()
|
||||||
|
model_selected = Signal(str)
|
||||||
|
|
||||||
|
def __init__(self, parent: QWidget | None = None) -> None:
|
||||||
|
super().__init__(parent)
|
||||||
|
self.setObjectName("CollapsibleObsidianSheet")
|
||||||
|
self.setMouseTracking(True)
|
||||||
|
self._expanded = False
|
||||||
|
self._handle_rect = QRectF()
|
||||||
|
self._vm: ObsidianAuroraVM | None = None
|
||||||
|
|
||||||
|
root = QVBoxLayout(self)
|
||||||
|
root.setContentsMargins(22, 24, 22, 14)
|
||||||
|
root.setSpacing(10)
|
||||||
|
|
||||||
|
top_bar = QHBoxLayout()
|
||||||
|
top_bar.setContentsMargins(0, 0, 0, 0)
|
||||||
|
top_bar.setSpacing(10)
|
||||||
|
|
||||||
|
self.title_label = QLabel("AI 病历循证分析舱", self)
|
||||||
|
self.title_label.setStyleSheet(
|
||||||
|
"color: #F6FAF9; font-size: 15px; font-weight: 600; background: transparent;"
|
||||||
|
)
|
||||||
|
top_bar.addWidget(self.title_label)
|
||||||
|
|
||||||
|
self.summary_label = QLabel("选择患者后自动读取千问 / OpenAI / 豆包实采病历分析报告", self)
|
||||||
|
self.summary_label.setStyleSheet(
|
||||||
|
"color: rgba(220, 234, 231, 185); font-size: 12px; background: transparent;"
|
||||||
|
)
|
||||||
|
self.summary_label.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred)
|
||||||
|
top_bar.addWidget(self.summary_label, 1)
|
||||||
|
|
||||||
|
self._model_buttons: dict[str, QPushButton] = {}
|
||||||
|
for m_key, m_text in (("qwen", "千问"), ("openai", "OpenAI"), ("doubao", "豆包")):
|
||||||
|
btn = QPushButton(m_text, self)
|
||||||
|
btn.setCheckable(True)
|
||||||
|
btn.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||||
|
btn.setFixedHeight(26)
|
||||||
|
btn.clicked.connect(lambda _c=False, k=m_key: self._choose_model(k))
|
||||||
|
self._model_buttons[m_key] = btn
|
||||||
|
top_bar.addWidget(btn)
|
||||||
|
self._sync_model_pill_styles("qwen")
|
||||||
|
|
||||||
|
self.report_button = QPushButton("完整循证报告", self)
|
||||||
|
self.report_button.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||||
|
self.report_button.setFixedHeight(28)
|
||||||
|
self.report_button.setStyleSheet(
|
||||||
|
"QPushButton { background: rgba(255,255,255,22); color: #F2F7F6;"
|
||||||
|
" border: 1px solid rgba(255,255,255,48); border-radius: 14px; padding: 0 13px; font-size: 12px; }"
|
||||||
|
"QPushButton:hover { background: rgba(255,255,255,40); }"
|
||||||
|
)
|
||||||
|
self.report_button.clicked.connect(self.open_ai_report_requested.emit)
|
||||||
|
top_bar.addWidget(self.report_button)
|
||||||
|
|
||||||
|
self.consult_button = QPushButton("AI 深度对话", self)
|
||||||
|
self.consult_button.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||||
|
self.consult_button.setFixedHeight(28)
|
||||||
|
self.consult_button.setStyleSheet(
|
||||||
|
"QPushButton { background: #0E6F5C; color: #FFFFFF;"
|
||||||
|
" border: 0; border-radius: 14px; padding: 0 14px; font-size: 12px; font-weight: 600; }"
|
||||||
|
"QPushButton:hover { background: #138770; }"
|
||||||
|
)
|
||||||
|
self.consult_button.clicked.connect(self.open_ai_consult_requested.emit)
|
||||||
|
top_bar.addWidget(self.consult_button)
|
||||||
|
|
||||||
|
self.toggle_button = QPushButton("展开分析舱 ▲", self)
|
||||||
|
self.toggle_button.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||||
|
self.toggle_button.setFixedHeight(28)
|
||||||
|
self.toggle_button.setStyleSheet(
|
||||||
|
"QPushButton { background: rgba(223,199,147,26); color: #EAD7AC;"
|
||||||
|
" border: 1px solid rgba(223,199,147,90); border-radius: 14px; padding: 0 12px; font-size: 12px; font-weight: 600; }"
|
||||||
|
"QPushButton:hover { background: rgba(223,199,147,48); }"
|
||||||
|
)
|
||||||
|
self.toggle_button.clicked.connect(self.toggle_expanded)
|
||||||
|
top_bar.addWidget(self.toggle_button)
|
||||||
|
root.addLayout(top_bar)
|
||||||
|
|
||||||
|
self.body_widget = QWidget(self)
|
||||||
|
body_layout = QHBoxLayout(self.body_widget)
|
||||||
|
body_layout.setContentsMargins(0, 4, 0, 2)
|
||||||
|
body_layout.setSpacing(14)
|
||||||
|
|
||||||
|
left_col = QWidget(self.body_widget)
|
||||||
|
left_col.setFixedWidth(196)
|
||||||
|
left_layout = QVBoxLayout(left_col)
|
||||||
|
left_layout.setContentsMargins(0, 0, 0, 0)
|
||||||
|
left_layout.setSpacing(8)
|
||||||
|
self._param_rows: list[tuple[QLabel, QLabel]] = []
|
||||||
|
for _ in range(3):
|
||||||
|
pill = QFrame(left_col)
|
||||||
|
pill.setFixedHeight(46)
|
||||||
|
pill.setStyleSheet(
|
||||||
|
"QFrame { background: rgba(255,255,255,14); border: 1px solid rgba(255,255,255,24); border-radius: 13px; }"
|
||||||
|
)
|
||||||
|
pl = QHBoxLayout(pill)
|
||||||
|
pl.setContentsMargins(13, 0, 13, 0)
|
||||||
|
k_lbl = QLabel("状态", pill)
|
||||||
|
k_lbl.setStyleSheet("color: rgba(225,236,234,195); font-size: 12px; border: 0; background: transparent;")
|
||||||
|
sep_lbl = QLabel("|", pill)
|
||||||
|
sep_lbl.setStyleSheet("color: rgba(255,255,255,55); border: 0; background: transparent;")
|
||||||
|
v_lbl = QLabel("—", pill)
|
||||||
|
v_lbl.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
|
||||||
|
v_lbl.setStyleSheet("color: #FFFFFF; font-size: 12px; font-weight: 600; border: 0; background: transparent;")
|
||||||
|
pl.addWidget(k_lbl)
|
||||||
|
pl.addStretch(1)
|
||||||
|
pl.addWidget(sep_lbl)
|
||||||
|
pl.addSpacing(5)
|
||||||
|
pl.addWidget(v_lbl)
|
||||||
|
left_layout.addWidget(pill)
|
||||||
|
self._param_rows.append((k_lbl, v_lbl))
|
||||||
|
left_layout.addStretch(1)
|
||||||
|
body_layout.addWidget(left_col)
|
||||||
|
|
||||||
|
self.aurora_cards = [AuroraGlassCardWidget(self.body_widget) for _ in range(3)]
|
||||||
|
for card in self.aurora_cards:
|
||||||
|
card.clicked.connect(self.open_ai_report_requested.emit)
|
||||||
|
body_layout.addWidget(card, 1)
|
||||||
|
|
||||||
|
self.gauge = ArcRhythmGaugeWidget(self.body_widget)
|
||||||
|
body_layout.addWidget(self.gauge)
|
||||||
|
|
||||||
|
root.addWidget(self.body_widget)
|
||||||
|
self._apply_expanded_geometry()
|
||||||
|
|
||||||
|
def _sync_model_pill_styles(self, active_key: str) -> None:
|
||||||
|
for key, btn in self._model_buttons.items():
|
||||||
|
checked = key == active_key
|
||||||
|
btn.setChecked(checked)
|
||||||
|
if checked:
|
||||||
|
btn.setStyleSheet(
|
||||||
|
"QPushButton { background: #FFFFFF; color: #101817; border: 0;"
|
||||||
|
" border-radius: 13px; padding: 0 11px; font-size: 11px; font-weight: 600; }"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
btn.setStyleSheet(
|
||||||
|
"QPushButton { background: rgba(255,255,255,14); color: rgba(230,240,238,180);"
|
||||||
|
" border: 1px solid rgba(255,255,255,26); border-radius: 13px; padding: 0 11px; font-size: 11px; }"
|
||||||
|
"QPushButton:hover { background: rgba(255,255,255,28); }"
|
||||||
|
)
|
||||||
|
|
||||||
|
def _choose_model(self, key: str) -> None:
|
||||||
|
self._sync_model_pill_styles(key)
|
||||||
|
self.model_selected.emit(key)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_expanded(self) -> bool:
|
||||||
|
return self._expanded
|
||||||
|
|
||||||
|
def set_expanded(self, expanded: bool) -> None:
|
||||||
|
target = bool(expanded)
|
||||||
|
if self._expanded == target:
|
||||||
|
return
|
||||||
|
self._expanded = target
|
||||||
|
self._apply_expanded_geometry()
|
||||||
|
self.expanded_changed.emit(target)
|
||||||
|
|
||||||
|
def toggle_expanded(self) -> None:
|
||||||
|
self.set_expanded(not self._expanded)
|
||||||
|
|
||||||
|
def _apply_expanded_geometry(self) -> None:
|
||||||
|
self.body_widget.setVisible(self._expanded)
|
||||||
|
self.toggle_button.setText("收起分析舱 ▼" if self._expanded else "展开分析舱 ▲")
|
||||||
|
self.setFixedHeight(238 if self._expanded else 64)
|
||||||
|
self.update()
|
||||||
|
|
||||||
|
def set_view_model(self, vm: ObsidianAuroraVM) -> None:
|
||||||
|
self._vm = vm
|
||||||
|
self._sync_model_pill_styles(vm.active_model_key)
|
||||||
|
self.title_label.setText(vm.program_title)
|
||||||
|
self.summary_label.setText(vm.ai_summary_line)
|
||||||
|
for (k_lbl, v_lbl), (k_txt, v_txt) in zip(self._param_rows, vm.params, strict=False):
|
||||||
|
k_lbl.setText(k_txt)
|
||||||
|
v_lbl.setText(v_txt)
|
||||||
|
for card, c_vm in zip(self.aurora_cards, vm.cards, strict=False):
|
||||||
|
card.set_view_model(c_vm)
|
||||||
|
self.gauge.set_gauge(
|
||||||
|
vm.gauge_value,
|
||||||
|
vm.gauge_unit,
|
||||||
|
vm.gauge_caption,
|
||||||
|
vm.gauge_ratio,
|
||||||
|
vm.gauge_tooltip,
|
||||||
|
)
|
||||||
|
self.update()
|
||||||
|
|
||||||
|
def mousePressEvent(self, event: QMouseEvent) -> None: # noqa: N802
|
||||||
|
if event.button() == Qt.MouseButton.LeftButton and self._handle_rect.contains(event.position()):
|
||||||
|
self.toggle_expanded()
|
||||||
|
event.accept()
|
||||||
|
return
|
||||||
|
super().mousePressEvent(event)
|
||||||
|
|
||||||
|
def mouseMoveEvent(self, event: QMouseEvent) -> None: # noqa: N802
|
||||||
|
if self._handle_rect.contains(event.position()):
|
||||||
|
self.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||||
|
else:
|
||||||
|
self.setCursor(Qt.CursorShape.ArrowCursor)
|
||||||
|
super().mouseMoveEvent(event)
|
||||||
|
|
||||||
|
def paintEvent(self, _event: object) -> None: # noqa: N802
|
||||||
|
painter = QPainter(self)
|
||||||
|
painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
|
||||||
|
|
||||||
|
rect = QRectF(self.rect())
|
||||||
|
sheet_top = 12.0
|
||||||
|
cx = rect.center().x()
|
||||||
|
self._handle_rect = QRectF(cx - 38.0, 0.0, 76.0, 22.0)
|
||||||
|
|
||||||
|
body_rect = QRectF(0.0, sheet_top, rect.width(), rect.height() - sheet_top)
|
||||||
|
path = QPainterPath()
|
||||||
|
path.addRoundedRect(body_rect, 24.0, 24.0)
|
||||||
|
painter.fillPath(path, QColor("#0E1413"))
|
||||||
|
|
||||||
|
notch = QPainterPath()
|
||||||
|
notch.moveTo(cx - 34.0, sheet_top + 1.0)
|
||||||
|
notch.cubicTo(cx - 20.0, sheet_top + 1.0, cx - 18.0, 2.0, cx, 2.0)
|
||||||
|
notch.cubicTo(cx + 18.0, 2.0, cx + 20.0, sheet_top + 1.0, cx + 34.0, sheet_top + 1.0)
|
||||||
|
notch.closeSubpath()
|
||||||
|
painter.fillPath(notch, QColor("#0E1413"))
|
||||||
|
|
||||||
|
painter.setPen(QPen(QColor("#DCE8E5"), 1.7, Qt.PenStyle.SolidLine, Qt.PenCapStyle.RoundCap))
|
||||||
|
ay = 10.0
|
||||||
|
if self._expanded:
|
||||||
|
painter.drawLine(QPointF(cx - 5.0, ay - 2.0), QPointF(cx, ay + 2.5))
|
||||||
|
painter.drawLine(QPointF(cx, ay + 2.5), QPointF(cx + 5.0, ay - 2.0))
|
||||||
|
else:
|
||||||
|
painter.drawLine(QPointF(cx - 5.0, ay + 2.5), QPointF(cx, ay - 2.0))
|
||||||
|
painter.drawLine(QPointF(cx, ay - 2.0), QPointF(cx + 5.0, ay + 2.5))
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
"""Reusable Alveo × Serene spatial action & patient-focus bridge bar for subpages."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections.abc import Callable
|
||||||
|
|
||||||
|
from PySide6.QtCore import Qt
|
||||||
|
from PySide6.QtWidgets import QFrame, QHBoxLayout, QLabel, QPushButton, QWidget
|
||||||
|
|
||||||
|
from ..state import PatientContextStore, PatientSnapshot
|
||||||
|
|
||||||
|
BRIDGE_QSS = """
|
||||||
|
QFrame#SpatialContextBridgeBar {
|
||||||
|
background-color: #FFFFFF;
|
||||||
|
border: 1px solid #E2ECE9;
|
||||||
|
border-radius: 20px;
|
||||||
|
}
|
||||||
|
QPushButton#BridgeFocusPatientPill {
|
||||||
|
min-height: 30px;
|
||||||
|
max-height: 30px;
|
||||||
|
padding: 0 14px;
|
||||||
|
border-radius: 15px;
|
||||||
|
background-color: #F2F6F5;
|
||||||
|
border: 1px solid #DCE7E4;
|
||||||
|
color: #213735;
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
QPushButton#BridgeFocusPatientPill:hover {
|
||||||
|
background-color: #E3F3EE;
|
||||||
|
border-color: #9BCBC0;
|
||||||
|
color: #0E6F5C;
|
||||||
|
}
|
||||||
|
QPushButton#BridgeFocusPatientPill:checked {
|
||||||
|
background-color: #0E6F5C;
|
||||||
|
border-color: #0E6F5C;
|
||||||
|
color: #FFFFFF;
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class SpatialContextBridgeBar(QFrame):
|
||||||
|
"""Compact rounded Bento bar syncing cross-page patient filtering & page actions."""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
summary_text: str,
|
||||||
|
*,
|
||||||
|
on_filter_patient: Callable[[str], None] | None = None,
|
||||||
|
parent: QWidget | None = None,
|
||||||
|
) -> None:
|
||||||
|
super().__init__(parent)
|
||||||
|
self.setObjectName("SpatialContextBridgeBar")
|
||||||
|
self.setStyleSheet(BRIDGE_QSS)
|
||||||
|
self.setMinimumHeight(52)
|
||||||
|
self._store: PatientContextStore | None = None
|
||||||
|
self._on_filter_patient = on_filter_patient
|
||||||
|
|
||||||
|
self.bar_layout = QHBoxLayout(self)
|
||||||
|
self.bar_layout.setContentsMargins(16, 8, 16, 8)
|
||||||
|
self.bar_layout.setSpacing(10)
|
||||||
|
|
||||||
|
self.summary_label = QLabel(summary_text, self)
|
||||||
|
self.summary_label.setStyleSheet(
|
||||||
|
"color: #556B68; font-size: 12px; font-weight: 500; background: transparent; border: 0;"
|
||||||
|
)
|
||||||
|
self.bar_layout.addWidget(self.summary_label)
|
||||||
|
|
||||||
|
self.focus_patient_button = QPushButton("聚焦当前患者", self)
|
||||||
|
self.focus_patient_button.setObjectName("BridgeFocusPatientPill")
|
||||||
|
self.focus_patient_button.setCheckable(True)
|
||||||
|
self.focus_patient_button.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||||
|
self.focus_patient_button.setVisible(False)
|
||||||
|
self.focus_patient_button.clicked.connect(self._toggle_patient_focus)
|
||||||
|
self.bar_layout.addWidget(self.focus_patient_button)
|
||||||
|
|
||||||
|
self.bar_layout.addStretch(1)
|
||||||
|
|
||||||
|
self.actions_host = QWidget(self)
|
||||||
|
self.actions_layout = QHBoxLayout(self.actions_host)
|
||||||
|
self.actions_layout.setContentsMargins(0, 0, 0, 0)
|
||||||
|
self.actions_layout.setSpacing(8)
|
||||||
|
self.bar_layout.addWidget(self.actions_host)
|
||||||
|
|
||||||
|
def add_action_widget(self, widget: QWidget) -> None:
|
||||||
|
widget.setParent(self.actions_host)
|
||||||
|
widget.show()
|
||||||
|
self.actions_layout.addWidget(widget)
|
||||||
|
|
||||||
|
def bind_store(self, store: PatientContextStore) -> None:
|
||||||
|
self._store = store
|
||||||
|
store.active_patient_changed.connect(self._on_patient_changed)
|
||||||
|
self._on_patient_changed(store.current_patient)
|
||||||
|
|
||||||
|
def _on_patient_changed(self, snapshot: PatientSnapshot) -> None:
|
||||||
|
if self._on_filter_patient is None or not snapshot or not snapshot.has_patient:
|
||||||
|
self.focus_patient_button.setVisible(False)
|
||||||
|
self.focus_patient_button.setChecked(False)
|
||||||
|
return
|
||||||
|
self.focus_patient_button.setVisible(True)
|
||||||
|
self.focus_patient_button.setText(f"仅看当前患者:{snapshot.patient_name}")
|
||||||
|
|
||||||
|
def _toggle_patient_focus(self, checked: bool) -> None:
|
||||||
|
if self._on_filter_patient is None or self._store is None:
|
||||||
|
return
|
||||||
|
snap = self._store.current_patient
|
||||||
|
if checked and snap.has_patient:
|
||||||
|
self._on_filter_patient(snap.patient_name)
|
||||||
|
else:
|
||||||
|
self._on_filter_patient("")
|
||||||
@@ -0,0 +1,271 @@
|
|||||||
|
"""Real postprandial 2h blood glucose, 14-day check-in strip, and 3 vital bricks."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from PySide6.QtCore import QPointF, QRectF, QSize, Qt
|
||||||
|
from PySide6.QtGui import QColor, QFont, QMouseEvent, QPainter, QPainterPath, QPen
|
||||||
|
from PySide6.QtWidgets import QToolTip, QWidget
|
||||||
|
|
||||||
|
from ..reception_style import body_family, heading_family, number_family
|
||||||
|
from ..viewmodels.cockpit_vm import DiurnalSlot, DiurnalStabilityVM, VitalMiniBrick
|
||||||
|
|
||||||
|
|
||||||
|
class DiurnalStabilityCard(QWidget):
|
||||||
|
"""Render real 2h postprandial glucose, 14-day daily records, and BP/BMI/Meds bricks."""
|
||||||
|
|
||||||
|
def __init__(self, parent: QWidget | None = None) -> None:
|
||||||
|
super().__init__(parent)
|
||||||
|
self.setObjectName("DiurnalStabilityCard")
|
||||||
|
self.setMouseTracking(True)
|
||||||
|
self.setMinimumHeight(218)
|
||||||
|
self._vm: DiurnalStabilityVM | None = None
|
||||||
|
self._slot_rects: list[tuple[QRectF, DiurnalSlot]] = []
|
||||||
|
self._brick_rects: list[tuple[QRectF, VitalMiniBrick]] = []
|
||||||
|
|
||||||
|
def sizeHint(self) -> QSize: # noqa: N802
|
||||||
|
return QSize(330, 300)
|
||||||
|
|
||||||
|
def set_view_model(self, vm: DiurnalStabilityVM) -> None:
|
||||||
|
self._vm = vm
|
||||||
|
self.update()
|
||||||
|
|
||||||
|
def mouseMoveEvent(self, event: QMouseEvent) -> None: # noqa: N802
|
||||||
|
pos = event.position()
|
||||||
|
for rect, slot in self._slot_rects:
|
||||||
|
if rect.adjusted(-1, -6, 1, 6).contains(pos) and slot.tooltip:
|
||||||
|
QToolTip.showText(event.globalPosition().toPoint(), slot.tooltip, self)
|
||||||
|
super().mouseMoveEvent(event)
|
||||||
|
return
|
||||||
|
for rect, brick in self._brick_rects:
|
||||||
|
if rect.contains(pos) and brick.tooltip:
|
||||||
|
QToolTip.showText(event.globalPosition().toPoint(), brick.tooltip, self)
|
||||||
|
break
|
||||||
|
super().mouseMoveEvent(event)
|
||||||
|
|
||||||
|
def paintEvent(self, _event: object) -> None: # noqa: N802
|
||||||
|
painter = QPainter(self)
|
||||||
|
painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
|
||||||
|
painter.setRenderHint(QPainter.RenderHint.TextAntialiasing, True)
|
||||||
|
|
||||||
|
rect = QRectF(self.rect()).adjusted(1.0, 1.0, -1.0, -1.0)
|
||||||
|
card_path = QPainterPath()
|
||||||
|
card_path.addRoundedRect(rect, 22.0, 22.0)
|
||||||
|
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||||
|
painter.fillPath(card_path, QColor("#FFFFFF"))
|
||||||
|
painter.setPen(QPen(QColor("#E3ECE9"), 1.0))
|
||||||
|
painter.drawPath(card_path)
|
||||||
|
|
||||||
|
vm = self._vm
|
||||||
|
if vm is None:
|
||||||
|
return
|
||||||
|
|
||||||
|
compact = rect.height() < 262.0
|
||||||
|
pad_x = 18.0
|
||||||
|
pad_y = 11.0 if compact else 15.0
|
||||||
|
left = rect.left() + pad_x
|
||||||
|
right = rect.right() - pad_x
|
||||||
|
avail_w = max(120.0, right - left)
|
||||||
|
|
||||||
|
# 1. Title + Reference / Alert Badge
|
||||||
|
title_font = QFont(heading_family())
|
||||||
|
title_font.setPixelSize(14 if compact else 15)
|
||||||
|
title_font.setWeight(QFont.Weight.DemiBold)
|
||||||
|
painter.setFont(title_font)
|
||||||
|
painter.setPen(QColor("#111F1D"))
|
||||||
|
painter.drawText(
|
||||||
|
QRectF(left, rect.top() + pad_y, 175, 22),
|
||||||
|
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
|
||||||
|
vm.title,
|
||||||
|
)
|
||||||
|
|
||||||
|
badge_font = QFont(body_family())
|
||||||
|
badge_font.setPixelSize(11)
|
||||||
|
badge_font.setWeight(QFont.Weight.Medium)
|
||||||
|
painter.setFont(badge_font)
|
||||||
|
badge_w = min(132.0, float(painter.fontMetrics().horizontalAdvance(vm.mode_badge) + 18))
|
||||||
|
badge_rect = QRectF(right - badge_w, rect.top() + pad_y, badge_w, 22)
|
||||||
|
badge_path = QPainterPath()
|
||||||
|
badge_path.addRoundedRect(badge_rect, 11.0, 11.0)
|
||||||
|
is_high_badge = "偏高" in vm.mode_badge
|
||||||
|
painter.fillPath(badge_path, QColor("#FCEBE6" if is_high_badge else "#E2F3EE"))
|
||||||
|
painter.setPen(QColor("#D96243" if is_high_badge else "#0E6F5C"))
|
||||||
|
painter.drawText(badge_rect, Qt.AlignmentFlag.AlignCenter, vm.mode_badge)
|
||||||
|
|
||||||
|
# 2. Primary Value + unit + caption
|
||||||
|
is_numeric = any(ch.isdigit() for ch in vm.primary_value)
|
||||||
|
num_font = QFont(number_family() if is_numeric else heading_family())
|
||||||
|
num_font.setPixelSize((29 if compact else 34) if is_numeric else (21 if compact else 24))
|
||||||
|
num_font.setWeight(QFont.Weight.DemiBold)
|
||||||
|
painter.setFont(num_font)
|
||||||
|
painter.setPen(QColor("#0F1D1B") if vm.primary_value not in {"—", "未记录"} else QColor("#7D918E"))
|
||||||
|
num_w = float(painter.fontMetrics().horizontalAdvance(vm.primary_value))
|
||||||
|
metric_y = rect.top() + (34.0 if compact else 44.0)
|
||||||
|
painter.drawText(
|
||||||
|
QRectF(left, metric_y, num_w + 4, 36 if compact else 40),
|
||||||
|
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
|
||||||
|
vm.primary_value,
|
||||||
|
)
|
||||||
|
|
||||||
|
unit_w = 0.0
|
||||||
|
if vm.unit:
|
||||||
|
unit_font = QFont(body_family())
|
||||||
|
unit_font.setPixelSize(13 if compact else 14)
|
||||||
|
painter.setFont(unit_font)
|
||||||
|
painter.setPen(QColor("#5C726F"))
|
||||||
|
unit_w = float(painter.fontMetrics().horizontalAdvance(vm.unit))
|
||||||
|
painter.drawText(
|
||||||
|
QRectF(left + num_w + 4, metric_y + (5 if compact else 8), unit_w + 6, 26),
|
||||||
|
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
|
||||||
|
vm.unit,
|
||||||
|
)
|
||||||
|
|
||||||
|
small_font = QFont(body_family())
|
||||||
|
small_font.setPixelSize(11)
|
||||||
|
painter.setFont(small_font)
|
||||||
|
painter.setPen(QColor("#7D918E"))
|
||||||
|
cap_x = left + num_w + unit_w + (10 if vm.unit else 8)
|
||||||
|
if right - cap_x > 50:
|
||||||
|
elided_cap = painter.fontMetrics().elidedText(
|
||||||
|
vm.caption, Qt.TextElideMode.ElideRight, int(right - cap_x)
|
||||||
|
)
|
||||||
|
painter.drawText(
|
||||||
|
QRectF(cap_x, metric_y + (6 if compact else 10), right - cap_x, 24),
|
||||||
|
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
|
||||||
|
elided_cap,
|
||||||
|
)
|
||||||
|
|
||||||
|
# 3. Clinical Glycemic Range Track (4.4 — 7.8 — 11.1 mmol/L)
|
||||||
|
track_y = metric_y + (38.0 if compact else 48.0)
|
||||||
|
track_rect = QRectF(left, track_y, avail_w, 6.0)
|
||||||
|
track_bg = QPainterPath()
|
||||||
|
track_bg.addRoundedRect(track_rect, 3.0, 3.0)
|
||||||
|
painter.fillPath(track_bg, QColor("#EDF2F0"))
|
||||||
|
|
||||||
|
safe_track = QRectF(left, track_y, avail_w * 0.78, 6.0)
|
||||||
|
safe_path = QPainterPath()
|
||||||
|
safe_path.addRoundedRect(safe_track, 3.0, 3.0)
|
||||||
|
painter.fillPath(safe_path, QColor("#C6E8DF" if vm.has_marker else "#E2ECE9"))
|
||||||
|
|
||||||
|
if vm.has_marker:
|
||||||
|
dot_x = left + avail_w * max(0.06, min(0.95, vm.range_marker_ratio))
|
||||||
|
painter.setPen(QPen(QColor("#FFFFFF"), 2.0))
|
||||||
|
painter.setBrush(QColor("#E06D4C" if is_high_badge else "#111918"))
|
||||||
|
painter.drawEllipse(QPointF(dot_x, track_y + 3.0), 5.2, 5.2)
|
||||||
|
|
||||||
|
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||||
|
painter.setPen(QColor("#7D918E"))
|
||||||
|
painter.drawText(QRectF(left, track_y + 9, 45, 14), Qt.AlignmentFlag.AlignLeft, vm.range_min_text)
|
||||||
|
painter.drawText(
|
||||||
|
QRectF(left + avail_w * 0.25, track_y + 9, avail_w * 0.50, 14),
|
||||||
|
Qt.AlignmentFlag.AlignCenter,
|
||||||
|
vm.range_target_text,
|
||||||
|
)
|
||||||
|
painter.drawText(QRectF(right - 45, track_y + 9, 45, 14), Qt.AlignmentFlag.AlignRight, vm.range_max_text)
|
||||||
|
|
||||||
|
# 4. Real 14-Day Check-In Strip
|
||||||
|
strip_header_y = track_y + (24.0 if compact else 30.0)
|
||||||
|
sub_bold = QFont(body_family())
|
||||||
|
sub_bold.setPixelSize(11)
|
||||||
|
sub_bold.setWeight(QFont.Weight.DemiBold)
|
||||||
|
painter.setFont(sub_bold)
|
||||||
|
painter.setPen(QColor("#243735"))
|
||||||
|
painter.drawText(
|
||||||
|
QRectF(left, strip_header_y, avail_w * 0.54, 16),
|
||||||
|
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
|
||||||
|
vm.overnight_title,
|
||||||
|
)
|
||||||
|
painter.setFont(small_font)
|
||||||
|
has_alert = any(s.state == "alert" for s in vm.slots)
|
||||||
|
painter.setPen(QColor("#D96243") if has_alert else QColor("#6E8380"))
|
||||||
|
painter.drawText(
|
||||||
|
QRectF(left + avail_w * 0.44, strip_header_y, avail_w * 0.56, 16),
|
||||||
|
Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter,
|
||||||
|
vm.overnight_peak_hint,
|
||||||
|
)
|
||||||
|
|
||||||
|
strip_top = strip_header_y + (16.0 if compact else 20.0)
|
||||||
|
strip_h = 20.0 if compact else 26.0
|
||||||
|
n_slots = max(1, len(vm.slots))
|
||||||
|
s_gap = 4.0
|
||||||
|
s_w = max(5.0, (avail_w - s_gap * (n_slots - 1)) / n_slots)
|
||||||
|
self._slot_rects.clear()
|
||||||
|
for idx, slot in enumerate(vm.slots):
|
||||||
|
sx = left + idx * (s_w + s_gap)
|
||||||
|
sh = max(5.0, strip_h * max(0.16, min(1.0, slot.height_ratio)))
|
||||||
|
sy = strip_top + (strip_h - sh)
|
||||||
|
s_rect = QRectF(sx, sy, s_w, sh)
|
||||||
|
self._slot_rects.append((s_rect, slot))
|
||||||
|
spath = QPainterPath()
|
||||||
|
spath.addRoundedRect(s_rect, 3.0, 3.0)
|
||||||
|
if slot.state == "alert":
|
||||||
|
s_color = QColor("#E06D4C")
|
||||||
|
elif slot.state == "mint":
|
||||||
|
s_color = QColor("#52B69E")
|
||||||
|
elif slot.state == "normal":
|
||||||
|
s_color = QColor("#BCE3D9")
|
||||||
|
else:
|
||||||
|
s_color = QColor("#E7EFED")
|
||||||
|
painter.fillPath(spath, s_color)
|
||||||
|
|
||||||
|
time_y = strip_top + strip_h + 3
|
||||||
|
painter.setPen(QColor("#829692"))
|
||||||
|
first_lbl = vm.slots[0].time_label if vm.slots else "14天前"
|
||||||
|
mid_lbl = vm.slots[len(vm.slots) // 2].time_label if vm.slots else "7天前"
|
||||||
|
for ratio_pos, label_txt in ((0.0, first_lbl), (0.5, mid_lbl), (1.0, "今日")):
|
||||||
|
tx = left + (avail_w - 42) * ratio_pos
|
||||||
|
align = (
|
||||||
|
Qt.AlignmentFlag.AlignLeft
|
||||||
|
if ratio_pos == 0.0
|
||||||
|
else (Qt.AlignmentFlag.AlignRight if ratio_pos == 1.0 else Qt.AlignmentFlag.AlignCenter)
|
||||||
|
)
|
||||||
|
painter.drawText(QRectF(tx, time_y, 42, 14), align, label_txt)
|
||||||
|
|
||||||
|
# 5. Bottom 3 Real Vital Mini-Bricks (BP, Height/Weight/BMI, Medications)
|
||||||
|
brick_top = time_y + (15.0 if compact else 20.0)
|
||||||
|
brick_h = max(44.0 if compact else 52.0, rect.bottom() - brick_top - (10.0 if compact else 13.0))
|
||||||
|
b_gap = 8.0
|
||||||
|
b_w = (avail_w - b_gap * 2) / 3.0
|
||||||
|
|
||||||
|
self._brick_rects.clear()
|
||||||
|
for idx, brick in enumerate(vm.vitals[:3]):
|
||||||
|
bx = left + idx * (b_w + b_gap)
|
||||||
|
b_rect = QRectF(bx, brick_top, b_w, brick_h)
|
||||||
|
self._brick_rects.append((b_rect, brick))
|
||||||
|
b_path = QPainterPath()
|
||||||
|
b_path.addRoundedRect(b_rect, 13.0, 13.0)
|
||||||
|
painter.fillPath(b_path, QColor("#FDF2EE") if brick.alert else QColor("#F5F8F7"))
|
||||||
|
|
||||||
|
painter.setFont(small_font)
|
||||||
|
painter.setPen(QColor("#6A7F7C"))
|
||||||
|
painter.drawText(
|
||||||
|
QRectF(bx + 9, brick_top + 6, b_w - 12, 15),
|
||||||
|
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
|
||||||
|
brick.label,
|
||||||
|
)
|
||||||
|
|
||||||
|
has_digit = any(ch.isdigit() for ch in brick.value)
|
||||||
|
b_val_font = QFont(number_family() if has_digit else body_family())
|
||||||
|
b_val_font.setPixelSize(15 if has_digit else 12)
|
||||||
|
b_val_font.setWeight(QFont.Weight.DemiBold)
|
||||||
|
painter.setFont(b_val_font)
|
||||||
|
painter.setPen(QColor("#D15839") if brick.alert else QColor("#11201E"))
|
||||||
|
elided_val = painter.fontMetrics().elidedText(
|
||||||
|
brick.value, Qt.TextElideMode.ElideRight, int(b_w - 14)
|
||||||
|
)
|
||||||
|
val_w = float(painter.fontMetrics().horizontalAdvance(elided_val))
|
||||||
|
painter.drawText(
|
||||||
|
QRectF(bx + 9, brick_top + 23, b_w - 14, 22),
|
||||||
|
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
|
||||||
|
elided_val,
|
||||||
|
)
|
||||||
|
if brick.unit and val_w + 26 < b_w:
|
||||||
|
painter.setFont(small_font)
|
||||||
|
painter.setPen(QColor("#7D918E"))
|
||||||
|
elided_unit = painter.fontMetrics().elidedText(
|
||||||
|
brick.unit, Qt.TextElideMode.ElideRight, int(b_w - val_w - 14)
|
||||||
|
)
|
||||||
|
painter.drawText(
|
||||||
|
QRectF(bx + 11 + val_w, brick_top + 25, b_w - val_w - 14, 18),
|
||||||
|
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
|
||||||
|
elided_unit,
|
||||||
|
)
|
||||||
@@ -0,0 +1,314 @@
|
|||||||
|
"""Real 21-Day Health Check-In (Glucose/Diet/Exercise) & Revisit Due Track."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from PySide6.QtCore import QPointF, QRectF, QSize, Qt, Signal
|
||||||
|
from PySide6.QtGui import QColor, QFont, QMouseEvent, QPainter, QPainterPath, QPen
|
||||||
|
from PySide6.QtWidgets import QToolTip, QWidget
|
||||||
|
|
||||||
|
from ..reception_style import body_family, heading_family, number_family
|
||||||
|
from ..viewmodels.cockpit_vm import CareJourneyVM, JourneyDayCell
|
||||||
|
|
||||||
|
|
||||||
|
class CareJourneyCard(QWidget):
|
||||||
|
"""Plot the patient's real last 21 calendar days of check-ins + revisit due status."""
|
||||||
|
|
||||||
|
day_selected = Signal(int)
|
||||||
|
open_full_plan_requested = Signal()
|
||||||
|
|
||||||
|
def __init__(self, parent: QWidget | None = None) -> None:
|
||||||
|
super().__init__(parent)
|
||||||
|
self.setObjectName("CareJourneyCard")
|
||||||
|
self.setMouseTracking(True)
|
||||||
|
self.setMinimumHeight(148)
|
||||||
|
self._vm: CareJourneyVM | None = None
|
||||||
|
self._day_rects: list[tuple[QRectF, JourneyDayCell]] = []
|
||||||
|
self._plan_btn_rect = QRectF()
|
||||||
|
self._hover_day: int = -1
|
||||||
|
self._hover_btn = False
|
||||||
|
|
||||||
|
def sizeHint(self) -> QSize: # noqa: N802
|
||||||
|
return QSize(1180, 164)
|
||||||
|
|
||||||
|
def set_view_model(self, vm: CareJourneyVM) -> None:
|
||||||
|
self._vm = vm
|
||||||
|
self._hover_day = -1
|
||||||
|
self.update()
|
||||||
|
|
||||||
|
def leaveEvent(self, event: object) -> None: # noqa: N802
|
||||||
|
self._hover_day = -1
|
||||||
|
self._hover_btn = False
|
||||||
|
self.update()
|
||||||
|
super().leaveEvent(event) # type: ignore[arg-type]
|
||||||
|
|
||||||
|
def mouseMoveEvent(self, event: QMouseEvent) -> None: # noqa: N802
|
||||||
|
pos = event.position()
|
||||||
|
hover_btn = self._plan_btn_rect.contains(pos)
|
||||||
|
hover_day = -1
|
||||||
|
for rect, cell in self._day_rects:
|
||||||
|
if rect.contains(pos):
|
||||||
|
hover_day = cell.day_num
|
||||||
|
QToolTip.showText(event.globalPosition().toPoint(), cell.tooltip, self)
|
||||||
|
break
|
||||||
|
self.setCursor(
|
||||||
|
Qt.CursorShape.PointingHandCursor
|
||||||
|
if (hover_btn or hover_day > 0)
|
||||||
|
else Qt.CursorShape.ArrowCursor
|
||||||
|
)
|
||||||
|
if hover_btn != self._hover_btn or hover_day != self._hover_day:
|
||||||
|
self._hover_btn = hover_btn
|
||||||
|
self._hover_day = hover_day
|
||||||
|
self.update()
|
||||||
|
super().mouseMoveEvent(event)
|
||||||
|
|
||||||
|
def mousePressEvent(self, event: QMouseEvent) -> None: # noqa: N802
|
||||||
|
if event.button() == Qt.MouseButton.LeftButton:
|
||||||
|
pos = event.position()
|
||||||
|
if self._plan_btn_rect.contains(pos):
|
||||||
|
self.open_full_plan_requested.emit()
|
||||||
|
event.accept()
|
||||||
|
return
|
||||||
|
for rect, cell in self._day_rects:
|
||||||
|
if rect.contains(pos):
|
||||||
|
self.day_selected.emit(cell.day_num)
|
||||||
|
event.accept()
|
||||||
|
return
|
||||||
|
super().mousePressEvent(event)
|
||||||
|
|
||||||
|
def paintEvent(self, _event: object) -> None: # noqa: N802
|
||||||
|
painter = QPainter(self)
|
||||||
|
painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
|
||||||
|
painter.setRenderHint(QPainter.RenderHint.TextAntialiasing, True)
|
||||||
|
|
||||||
|
rect = QRectF(self.rect()).adjusted(1.0, 1.0, -1.0, -1.0)
|
||||||
|
card_path = QPainterPath()
|
||||||
|
card_path.addRoundedRect(rect, 22.0, 22.0)
|
||||||
|
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||||
|
painter.fillPath(card_path, QColor("#FFFFFF"))
|
||||||
|
painter.setPen(QPen(QColor("#E3ECE9"), 1.0))
|
||||||
|
painter.drawPath(card_path)
|
||||||
|
|
||||||
|
vm = self._vm
|
||||||
|
if vm is None:
|
||||||
|
return
|
||||||
|
|
||||||
|
# Left summary column (232px — High-DPI safe layout with inline status pill!)
|
||||||
|
left_x = rect.left() + 20.0
|
||||||
|
left_w = 224.0
|
||||||
|
|
||||||
|
title_font = QFont(heading_family())
|
||||||
|
title_font.setPixelSize(14)
|
||||||
|
title_font.setWeight(QFont.Weight.DemiBold)
|
||||||
|
painter.setFont(title_font)
|
||||||
|
painter.setPen(QColor("#11201E"))
|
||||||
|
painter.drawText(QRectF(left_x, rect.top() + 14, left_w, 20), Qt.AlignmentFlag.AlignLeft, vm.title)
|
||||||
|
|
||||||
|
sub_font = QFont(body_family())
|
||||||
|
sub_font.setPixelSize(11)
|
||||||
|
painter.setFont(sub_font)
|
||||||
|
painter.setPen(QColor("#788E8A"))
|
||||||
|
elided_sub = painter.fontMetrics().elidedText(vm.plan_subtitle, Qt.TextElideMode.ElideRight, int(left_w))
|
||||||
|
painter.drawText(QRectF(left_x, rect.top() + 34, left_w, 16), Qt.AlignmentFlag.AlignLeft, elided_sub)
|
||||||
|
|
||||||
|
# Big Check-in Count + "/ 21 天有打卡" + Inline Status Pill (ZERO overlap at any DPI!)
|
||||||
|
day_font = QFont(number_family())
|
||||||
|
day_font.setPixelSize(31)
|
||||||
|
day_font.setWeight(QFont.Weight.DemiBold)
|
||||||
|
painter.setFont(day_font)
|
||||||
|
painter.setPen(QColor("#0F1D1B") if vm.primary_metric_text != "—" else QColor("#7D918E"))
|
||||||
|
dw = float(painter.fontMetrics().horizontalAdvance(vm.primary_metric_text))
|
||||||
|
painter.drawText(
|
||||||
|
QRectF(left_x, rect.top() + 54, dw + 6, 36),
|
||||||
|
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
|
||||||
|
vm.primary_metric_text,
|
||||||
|
)
|
||||||
|
|
||||||
|
slash_font = QFont(body_family())
|
||||||
|
slash_font.setPixelSize(12)
|
||||||
|
painter.setFont(slash_font)
|
||||||
|
painter.setPen(QColor("#6E8380"))
|
||||||
|
uw = float(painter.fontMetrics().horizontalAdvance(vm.total_unit_text))
|
||||||
|
painter.drawText(
|
||||||
|
QRectF(left_x + dw + 6, rect.top() + 62, uw + 6, 24),
|
||||||
|
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
|
||||||
|
vm.total_unit_text,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Inline status pill next to or cleanly right-aligned on the metric row
|
||||||
|
badge_font = QFont(body_family())
|
||||||
|
badge_font.setPixelSize(10)
|
||||||
|
badge_font.setWeight(QFont.Weight.DemiBold)
|
||||||
|
painter.setFont(badge_font)
|
||||||
|
bw = min(88.0, float(painter.fontMetrics().horizontalAdvance(vm.status_pill) + 16))
|
||||||
|
pill_x = max(left_x + dw + uw + 14.0, left_x + left_w - bw - 4.0)
|
||||||
|
if pill_x + bw <= left_x + left_w + 4.0:
|
||||||
|
b_rect = QRectF(pill_x, rect.top() + 63, bw, 20)
|
||||||
|
bp = QPainterPath()
|
||||||
|
bp.addRoundedRect(b_rect, 10.0, 10.0)
|
||||||
|
if vm.status_tone == "coral":
|
||||||
|
painter.fillPath(bp, QColor("#FCEBE6"))
|
||||||
|
painter.setPen(QColor("#C85232"))
|
||||||
|
elif vm.status_tone == "emerald":
|
||||||
|
painter.fillPath(bp, QColor("#E2F3EE"))
|
||||||
|
painter.setPen(QColor("#0E6F5C"))
|
||||||
|
else:
|
||||||
|
painter.fillPath(bp, QColor("#F1F5F4"))
|
||||||
|
painter.setPen(QColor("#6B807D"))
|
||||||
|
elided_pill = painter.fontMetrics().elidedText(vm.status_pill, Qt.TextElideMode.ElideRight, int(bw - 10))
|
||||||
|
painter.drawText(b_rect, Qt.AlignmentFlag.AlignCenter, elided_pill)
|
||||||
|
|
||||||
|
# [↗ 打开日常记录矩阵] button anchored safely at bottom
|
||||||
|
self._plan_btn_rect = QRectF(left_x, rect.bottom() - 36, 142, 26)
|
||||||
|
btn_path = QPainterPath()
|
||||||
|
btn_path.addRoundedRect(self._plan_btn_rect, 13.0, 13.0)
|
||||||
|
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||||
|
painter.fillPath(btn_path, QColor("#EDF5F3" if self._hover_btn else "#FFFFFF"))
|
||||||
|
painter.setPen(QPen(QColor("#0E6F5C" if self._hover_btn else "#D7E3E0"), 1.0))
|
||||||
|
painter.drawPath(btn_path)
|
||||||
|
painter.setPen(QColor("#0E6F5C" if self._hover_btn else "#1E312F"))
|
||||||
|
painter.drawText(self._plan_btn_rect, Qt.AlignmentFlag.AlignCenter, "↗ 打开日常记录矩阵")
|
||||||
|
|
||||||
|
# Vertical subtle divider
|
||||||
|
div_x = left_x + left_w + 10
|
||||||
|
painter.setPen(QPen(QColor("#ECF2F0"), 1.0))
|
||||||
|
painter.drawLine(QPointF(div_x, rect.top() + 16), QPointF(div_x, rect.bottom() - 16))
|
||||||
|
|
||||||
|
# Right 21-Day Real Calendar Matrix Column
|
||||||
|
rx = div_x + 18.0
|
||||||
|
rw = max(260.0, rect.right() - rx - 18.0)
|
||||||
|
|
||||||
|
painter.setFont(sub_font)
|
||||||
|
painter.setPen(QColor("#839794"))
|
||||||
|
painter.drawText(QRectF(rx, rect.top() + 13, 175, 16), Qt.AlignmentFlag.AlignLeft, "逐日实测日历(悬停查看明细)")
|
||||||
|
|
||||||
|
legend_items = (
|
||||||
|
("#0E6F5C", True, "血糖达标"),
|
||||||
|
("#E06D4C", True, "血糖偏高"),
|
||||||
|
("#CBE8E0", True, "饮食/运动"),
|
||||||
|
("#111918", True, "今日"),
|
||||||
|
("#DCE6E3", False, "无打卡"),
|
||||||
|
)
|
||||||
|
lx = rect.right() - 348
|
||||||
|
for color_hex, filled, text in legend_items:
|
||||||
|
sw = QRectF(lx, rect.top() + 16, 9, 9)
|
||||||
|
sp = QPainterPath()
|
||||||
|
sp.addRoundedRect(sw, 2.5, 2.5)
|
||||||
|
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||||
|
if filled:
|
||||||
|
painter.fillPath(sp, QColor(color_hex))
|
||||||
|
else:
|
||||||
|
painter.setPen(QPen(QColor(color_hex), 1.1))
|
||||||
|
painter.drawPath(sp)
|
||||||
|
painter.setPen(QColor("#5C726F"))
|
||||||
|
painter.drawText(QRectF(lx + 12, rect.top() + 13, 56, 15), Qt.AlignmentFlag.AlignLeft, text)
|
||||||
|
lx += 68
|
||||||
|
|
||||||
|
n_days = max(1, len(vm.days))
|
||||||
|
followup_w = 58.0
|
||||||
|
gap = 5.0
|
||||||
|
pills_avail = max(180.0, rw - followup_w - 10.0)
|
||||||
|
pill_w = max(18.0, (pills_avail - gap * (n_days - 1)) / n_days)
|
||||||
|
|
||||||
|
# Weekly spans + horizontal span bars
|
||||||
|
phase_y = rect.top() + 34
|
||||||
|
bar_y = phase_y + 29
|
||||||
|
for ph in vm.phases:
|
||||||
|
px1 = rx + (ph.start_day - 1) * (pill_w + gap)
|
||||||
|
px2 = rx + ph.end_day * pill_w + (ph.end_day - 1) * gap
|
||||||
|
pw = max(40.0, px2 - px1 - 4.0)
|
||||||
|
|
||||||
|
p_font = QFont(body_family())
|
||||||
|
p_font.setPixelSize(11)
|
||||||
|
p_font.setWeight(QFont.Weight.DemiBold if ph.active else QFont.Weight.Medium)
|
||||||
|
painter.setFont(p_font)
|
||||||
|
painter.setPen(QColor("#0E6F5C") if ph.active else QColor("#354A47"))
|
||||||
|
painter.drawText(QRectF(px1, phase_y, pw, 15), Qt.AlignmentFlag.AlignLeft, f"{ph.code} · {ph.title}")
|
||||||
|
|
||||||
|
painter.setFont(sub_font)
|
||||||
|
painter.setPen(QColor("#829692"))
|
||||||
|
painter.drawText(QRectF(px1, phase_y + 14, pw, 14), Qt.AlignmentFlag.AlignLeft, ph.date_span)
|
||||||
|
|
||||||
|
line_color = QColor("#111918") if ph.active else QColor("#CFE0DC")
|
||||||
|
painter.setPen(QPen(line_color, 2.0, Qt.PenStyle.SolidLine, Qt.PenCapStyle.RoundCap))
|
||||||
|
painter.drawLine(QPointF(px1, bar_y), QPointF(px1 + pw, bar_y))
|
||||||
|
|
||||||
|
# 21 Real Date Pills
|
||||||
|
pill_top = bar_y + 7
|
||||||
|
pill_h = 38.0
|
||||||
|
self._day_rects.clear()
|
||||||
|
num_pill_font = QFont(number_family())
|
||||||
|
num_pill_font.setPixelSize(12)
|
||||||
|
num_pill_font.setWeight(QFont.Weight.DemiBold)
|
||||||
|
painter.setFont(num_pill_font)
|
||||||
|
|
||||||
|
today_center_x = rx
|
||||||
|
for idx, cell in enumerate(vm.days):
|
||||||
|
dx = rx + idx * (pill_w + gap)
|
||||||
|
d_rect = QRectF(dx, pill_top, pill_w, pill_h)
|
||||||
|
self._day_rects.append((d_rect, cell))
|
||||||
|
dp = QPainterPath()
|
||||||
|
dp.addRoundedRect(d_rect, 9.0, 9.0)
|
||||||
|
|
||||||
|
is_hover = cell.day_num == self._hover_day
|
||||||
|
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||||
|
if cell.state == "completed":
|
||||||
|
painter.fillPath(dp, QColor("#0B5B4B" if is_hover else "#0E6F5C"))
|
||||||
|
fg = QColor("#FFFFFF")
|
||||||
|
elif cell.state == "alert":
|
||||||
|
painter.fillPath(dp, QColor("#CC5738" if is_hover else "#E06D4C"))
|
||||||
|
fg = QColor("#FFFFFF")
|
||||||
|
elif cell.state == "stage":
|
||||||
|
painter.fillPath(dp, QColor("#B4DFD4" if is_hover else "#CBE8E0"))
|
||||||
|
fg = QColor("#11352E")
|
||||||
|
elif cell.state == "today":
|
||||||
|
today_center_x = d_rect.center().x()
|
||||||
|
painter.fillPath(dp, QColor("#111918"))
|
||||||
|
fg = QColor("#FFFFFF")
|
||||||
|
else:
|
||||||
|
painter.fillPath(dp, QColor("#F3F7F6" if is_hover else "#FFFFFF"))
|
||||||
|
painter.setPen(QPen(QColor("#DCE6E3"), 1.0))
|
||||||
|
painter.drawPath(dp)
|
||||||
|
fg = QColor("#7E928F")
|
||||||
|
|
||||||
|
painter.setPen(fg)
|
||||||
|
text_rect = d_rect.adjusted(0, -3, 0, -3) if cell.has_dot else d_rect
|
||||||
|
painter.drawText(text_rect, Qt.AlignmentFlag.AlignCenter, cell.label_text)
|
||||||
|
if cell.has_dot:
|
||||||
|
painter.setPen(Qt.PenStyle.NoPen)
|
||||||
|
painter.setBrush(QColor("#FFFFFF" if cell.state != "today" else "#E06D4C"))
|
||||||
|
painter.drawEllipse(QPointF(d_rect.center().x(), d_rect.bottom() - 7.5), 2.2, 2.2)
|
||||||
|
|
||||||
|
# End Revisit / Prescription Status Capsule
|
||||||
|
f_rect = QRectF(rx + n_days * (pill_w + gap) + 4.0, pill_top, followup_w, pill_h)
|
||||||
|
fp = QPainterPath()
|
||||||
|
fp.addRoundedRect(f_rect, 10.0, 10.0)
|
||||||
|
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||||
|
painter.fillPath(fp, QColor("#FCEEE9" if vm.status_tone == "coral" else "#F4FAF8"))
|
||||||
|
painter.setPen(
|
||||||
|
QPen(
|
||||||
|
QColor("#D96243" if vm.status_tone == "coral" else "#6BAE9E"),
|
||||||
|
1.1,
|
||||||
|
Qt.PenStyle.DashLine,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
painter.drawPath(fp)
|
||||||
|
painter.setFont(badge_font)
|
||||||
|
painter.setPen(QColor("#C85232" if vm.status_tone == "coral" else "#0E6F5C"))
|
||||||
|
painter.drawText(f_rect, Qt.AlignmentFlag.AlignCenter, vm.end_capsule_text)
|
||||||
|
|
||||||
|
# Bottom Date Anchors + Black '今日' Pill
|
||||||
|
mile_y = pill_top + pill_h + 6
|
||||||
|
for day_idx, m_text in vm.milestones:
|
||||||
|
mx = rx + (day_idx - 1) * (pill_w + gap) + pill_w * 0.5
|
||||||
|
if day_idx == n_days:
|
||||||
|
t_pill = QRectF(today_center_x - 20, mile_y, 40, 17)
|
||||||
|
tp = QPainterPath()
|
||||||
|
tp.addRoundedRect(t_pill, 8.5, 8.5)
|
||||||
|
painter.fillPath(tp, QColor("#111918"))
|
||||||
|
painter.setFont(badge_font)
|
||||||
|
painter.setPen(QColor("#FFFFFF"))
|
||||||
|
painter.drawText(t_pill, Qt.AlignmentFlag.AlignCenter, "今日")
|
||||||
|
else:
|
||||||
|
painter.setFont(sub_font)
|
||||||
|
painter.setPen(QColor("#788E8A"))
|
||||||
|
painter.drawText(QRectF(mx - 28, mile_y, 56, 15), Qt.AlignmentFlag.AlignCenter, m_text)
|
||||||
@@ -0,0 +1,220 @@
|
|||||||
|
"""Real fasting blood glucose progression Bento card (mmol/L) rendered with QPainter."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from PySide6.QtCore import QPointF, QRectF, QSize, Qt
|
||||||
|
from PySide6.QtGui import QColor, QFont, QMouseEvent, QPainter, QPainterPath, QPen
|
||||||
|
from PySide6.QtWidgets import QToolTip, QWidget
|
||||||
|
|
||||||
|
from ..reception_style import body_family, heading_family, number_family
|
||||||
|
from ..viewmodels.cockpit_vm import GlycemicProgressionVM, ProgressionPoint
|
||||||
|
|
||||||
|
|
||||||
|
class PillProgressionCard(QWidget):
|
||||||
|
"""Plot up to 12 real fasting blood glucose measurements against the 7.0 mmol/L line."""
|
||||||
|
|
||||||
|
def __init__(self, parent: QWidget | None = None) -> None:
|
||||||
|
super().__init__(parent)
|
||||||
|
self.setObjectName("PillProgressionCard")
|
||||||
|
self.setMouseTracking(True)
|
||||||
|
self.setMinimumHeight(172)
|
||||||
|
self._vm: GlycemicProgressionVM | None = None
|
||||||
|
self._hover_index: int = -1
|
||||||
|
self._bar_rects: list[tuple[QRectF, ProgressionPoint]] = []
|
||||||
|
|
||||||
|
def sizeHint(self) -> QSize: # noqa: N802
|
||||||
|
return QSize(330, 224)
|
||||||
|
|
||||||
|
def set_view_model(self, vm: GlycemicProgressionVM) -> None:
|
||||||
|
self._vm = vm
|
||||||
|
self._hover_index = -1
|
||||||
|
self.update()
|
||||||
|
|
||||||
|
def leaveEvent(self, event: object) -> None: # noqa: N802
|
||||||
|
self._hover_index = -1
|
||||||
|
self.update()
|
||||||
|
super().leaveEvent(event) # type: ignore[arg-type]
|
||||||
|
|
||||||
|
def mouseMoveEvent(self, event: QMouseEvent) -> None: # noqa: N802
|
||||||
|
pos = event.position()
|
||||||
|
hit = -1
|
||||||
|
for idx, (rect, point) in enumerate(self._bar_rects):
|
||||||
|
if rect.adjusted(-2, -10, 2, 6).contains(pos):
|
||||||
|
hit = idx
|
||||||
|
if point.value_hint:
|
||||||
|
QToolTip.showText(event.globalPosition().toPoint(), point.value_hint, self)
|
||||||
|
break
|
||||||
|
if hit != self._hover_index:
|
||||||
|
self._hover_index = hit
|
||||||
|
self.update()
|
||||||
|
super().mouseMoveEvent(event)
|
||||||
|
|
||||||
|
def paintEvent(self, _event: object) -> None: # noqa: N802
|
||||||
|
painter = QPainter(self)
|
||||||
|
painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
|
||||||
|
painter.setRenderHint(QPainter.RenderHint.TextAntialiasing, True)
|
||||||
|
|
||||||
|
rect = QRectF(self.rect()).adjusted(1.0, 1.0, -1.0, -1.0)
|
||||||
|
card_path = QPainterPath()
|
||||||
|
card_path.addRoundedRect(rect, 22.0, 22.0)
|
||||||
|
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||||
|
painter.fillPath(card_path, QColor("#FFFFFF"))
|
||||||
|
painter.setPen(QPen(QColor("#E3ECE9"), 1.0))
|
||||||
|
painter.drawPath(card_path)
|
||||||
|
|
||||||
|
vm = self._vm
|
||||||
|
if vm is None:
|
||||||
|
return
|
||||||
|
|
||||||
|
compact = rect.height() < 198.0
|
||||||
|
pad_x = 18.0
|
||||||
|
left = rect.left() + pad_x
|
||||||
|
right = rect.right() - pad_x
|
||||||
|
|
||||||
|
# 1. Header row: Title + Reference badge
|
||||||
|
title_font = QFont(heading_family())
|
||||||
|
title_font.setPixelSize(14 if compact else 15)
|
||||||
|
title_font.setWeight(QFont.Weight.DemiBold)
|
||||||
|
painter.setFont(title_font)
|
||||||
|
painter.setPen(QColor("#111F1D"))
|
||||||
|
painter.drawText(
|
||||||
|
QRectF(left, rect.top() + (12 if compact else 15), 160, 22),
|
||||||
|
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
|
||||||
|
vm.title,
|
||||||
|
)
|
||||||
|
|
||||||
|
badge_font = QFont(body_family())
|
||||||
|
badge_font.setPixelSize(11)
|
||||||
|
badge_font.setWeight(QFont.Weight.Medium)
|
||||||
|
painter.setFont(badge_font)
|
||||||
|
badge_w = min(142.0, float(painter.fontMetrics().horizontalAdvance(vm.subtitle_badge) + 18))
|
||||||
|
badge_rect = QRectF(right - badge_w, rect.top() + (12 if compact else 15), badge_w, 22)
|
||||||
|
badge_path = QPainterPath()
|
||||||
|
badge_path.addRoundedRect(badge_rect, 11.0, 11.0)
|
||||||
|
painter.fillPath(badge_path, QColor("#F2F6F5"))
|
||||||
|
painter.setPen(QColor("#4E6662"))
|
||||||
|
painter.drawText(badge_rect, Qt.AlignmentFlag.AlignCenter, vm.subtitle_badge)
|
||||||
|
|
||||||
|
# 2. Primary Real Fasting Value + Unit + Status Pill
|
||||||
|
is_numeric = any(ch.isdigit() for ch in vm.primary_value)
|
||||||
|
num_font = QFont(number_family() if is_numeric else heading_family())
|
||||||
|
num_font.setPixelSize((32 if compact else 38) if is_numeric else (22 if compact else 25))
|
||||||
|
num_font.setWeight(QFont.Weight.DemiBold)
|
||||||
|
painter.setFont(num_font)
|
||||||
|
painter.setPen(QColor("#0F1D1B") if vm.primary_value not in {"—", "未记录"} else QColor("#7D918E"))
|
||||||
|
num_w = float(painter.fontMetrics().horizontalAdvance(vm.primary_value))
|
||||||
|
metric_y = rect.top() + (38 if compact else 44)
|
||||||
|
painter.drawText(
|
||||||
|
QRectF(left, metric_y, num_w + 6, 42),
|
||||||
|
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
|
||||||
|
vm.primary_value,
|
||||||
|
)
|
||||||
|
|
||||||
|
if vm.unit:
|
||||||
|
unit_font = QFont(body_family())
|
||||||
|
unit_font.setPixelSize(13 if compact else 14)
|
||||||
|
painter.setFont(unit_font)
|
||||||
|
painter.setPen(QColor("#6C827E"))
|
||||||
|
painter.drawText(
|
||||||
|
QRectF(left + num_w + 5, metric_y + 8, 66, 28),
|
||||||
|
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
|
||||||
|
vm.unit,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Right status pill
|
||||||
|
painter.setFont(badge_font)
|
||||||
|
delta_w = float(painter.fontMetrics().horizontalAdvance(vm.delta_badge) + 20)
|
||||||
|
delta_rect = QRectF(right - delta_w, metric_y + 3, delta_w, 22)
|
||||||
|
delta_path = QPainterPath()
|
||||||
|
delta_path.addRoundedRect(delta_rect, 11.0, 11.0)
|
||||||
|
if vm.delta_tone == "emerald":
|
||||||
|
painter.fillPath(delta_path, QColor("#E2F3EE"))
|
||||||
|
painter.setPen(QColor("#0E6F5C"))
|
||||||
|
elif vm.delta_tone == "coral":
|
||||||
|
painter.fillPath(delta_path, QColor("#FCEBE6"))
|
||||||
|
painter.setPen(QColor("#D96243"))
|
||||||
|
else:
|
||||||
|
painter.fillPath(delta_path, QColor("#F1F5F4"))
|
||||||
|
painter.setPen(QColor("#6B807D"))
|
||||||
|
painter.drawText(delta_rect, Qt.AlignmentFlag.AlignCenter, vm.delta_badge)
|
||||||
|
|
||||||
|
sub_caption_font = QFont(body_family())
|
||||||
|
sub_caption_font.setPixelSize(11)
|
||||||
|
painter.setFont(sub_caption_font)
|
||||||
|
painter.setPen(QColor("#7D918E"))
|
||||||
|
painter.drawText(
|
||||||
|
QRectF(right - 138, metric_y + 27, 138, 15),
|
||||||
|
Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter,
|
||||||
|
vm.delta_caption,
|
||||||
|
)
|
||||||
|
|
||||||
|
# 3. 7.0 mmol/L Threshold Dashed Line + 12 Real Measurement Bars
|
||||||
|
chart_top = metric_y + (48 if compact else 54)
|
||||||
|
chart_bottom = rect.bottom() - 28
|
||||||
|
chart_h = max(36.0, chart_bottom - chart_top)
|
||||||
|
|
||||||
|
target_y = chart_bottom - chart_h * max(0.25, min(0.88, vm.target_ratio))
|
||||||
|
painter.setPen(QPen(QColor("#C8D8D4"), 1.1, Qt.PenStyle.DashLine))
|
||||||
|
painter.drawLine(QPointF(left, target_y), QPointF(right, target_y))
|
||||||
|
|
||||||
|
painter.setFont(sub_caption_font)
|
||||||
|
painter.setPen(QColor("#6E8380"))
|
||||||
|
painter.drawText(
|
||||||
|
QRectF(left, max(chart_top - 2, target_y - 15), 130, 14),
|
||||||
|
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
|
||||||
|
vm.target_label,
|
||||||
|
)
|
||||||
|
|
||||||
|
bars = vm.bars
|
||||||
|
count = max(1, len(bars))
|
||||||
|
gap = 5.5
|
||||||
|
avail_w = max(80.0, right - left)
|
||||||
|
bar_w = max(8.0, (avail_w - gap * (count - 1)) / count)
|
||||||
|
|
||||||
|
self._bar_rects.clear()
|
||||||
|
for idx, pt in enumerate(bars):
|
||||||
|
bx = left + idx * (bar_w + gap)
|
||||||
|
bh = max(8.0, chart_h * max(0.14, min(0.98, pt.ratio)))
|
||||||
|
by = chart_bottom - bh
|
||||||
|
bar_rect = QRectF(bx, by, bar_w, bh)
|
||||||
|
self._bar_rects.append((bar_rect, pt))
|
||||||
|
|
||||||
|
radius = min(5.5, bar_w * 0.42)
|
||||||
|
bpath = QPainterPath()
|
||||||
|
bpath.addRoundedRect(bar_rect, radius, radius)
|
||||||
|
|
||||||
|
if not pt.recorded:
|
||||||
|
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||||
|
painter.fillPath(bpath, QColor("#F3F7F6"))
|
||||||
|
painter.setPen(QPen(QColor("#E3ECE9"), 1.0))
|
||||||
|
painter.drawPath(bpath)
|
||||||
|
else:
|
||||||
|
if pt.alert:
|
||||||
|
fill = QColor("#E06D4C") if pt.highlight else QColor("#EFA48E")
|
||||||
|
elif pt.highlight:
|
||||||
|
fill = QColor("#0E6F5C")
|
||||||
|
elif idx == self._hover_index:
|
||||||
|
fill = QColor("#5AB6A3")
|
||||||
|
else:
|
||||||
|
fill = QColor("#AEDCD0")
|
||||||
|
painter.fillPath(bpath, fill)
|
||||||
|
|
||||||
|
# 4. Bottom labels
|
||||||
|
foot_y = rect.bottom() - 22
|
||||||
|
painter.setFont(sub_caption_font)
|
||||||
|
painter.setPen(QColor("#7C908D"))
|
||||||
|
painter.drawText(
|
||||||
|
QRectF(left, foot_y, 120, 15),
|
||||||
|
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
|
||||||
|
vm.left_foot,
|
||||||
|
)
|
||||||
|
foot_right_font = QFont(body_family())
|
||||||
|
foot_right_font.setPixelSize(11)
|
||||||
|
foot_right_font.setWeight(QFont.Weight.DemiBold)
|
||||||
|
painter.setFont(foot_right_font)
|
||||||
|
painter.setPen(QColor("#1A2D2B"))
|
||||||
|
painter.drawText(
|
||||||
|
QRectF(right - 135, foot_y, 135, 15),
|
||||||
|
Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter,
|
||||||
|
vm.right_foot,
|
||||||
|
)
|
||||||
@@ -0,0 +1,563 @@
|
|||||||
|
"""Three-column Alveo × Serene Clinical Digital Twin Cockpit for ReceptionPage."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
from datetime import date
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from PySide6.QtCore import QSize, Qt, Signal
|
||||||
|
from PySide6.QtGui import QFont
|
||||||
|
from PySide6.QtWidgets import (
|
||||||
|
QFrame,
|
||||||
|
QHBoxLayout,
|
||||||
|
QLabel,
|
||||||
|
QPushButton,
|
||||||
|
QScrollArea,
|
||||||
|
QSizePolicy,
|
||||||
|
QVBoxLayout,
|
||||||
|
QWidget,
|
||||||
|
)
|
||||||
|
|
||||||
|
from ...core.appointment_modes import appointment_type_description, appointment_type_value
|
||||||
|
from .. import icons
|
||||||
|
from ..reception_style import body_family, heading_family
|
||||||
|
from ..viewmodels.cockpit_vm import CockpitSnapshotVM, derive_cockpit_snapshot
|
||||||
|
from ..widgets import clear_layout, display_text, first_value
|
||||||
|
from .diurnal_strip import DiurnalStabilityCard
|
||||||
|
from .journey_track import CareJourneyCard
|
||||||
|
from .pill_chart import PillProgressionCard
|
||||||
|
from .twin_stage import ClinicalTwinStageWidget
|
||||||
|
|
||||||
|
COCKPIT_QSS = """
|
||||||
|
QWidget#ReceptionDigitalTwinCockpit {
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
QFrame#CockpitBentoCard {
|
||||||
|
background-color: #FFFFFF;
|
||||||
|
border: 1px solid #E3ECE9;
|
||||||
|
border-radius: 22px;
|
||||||
|
}
|
||||||
|
QPushButton#CockpitFilterPill {
|
||||||
|
min-height: 24px;
|
||||||
|
max-height: 24px;
|
||||||
|
padding: 0 10px;
|
||||||
|
border-radius: 12px;
|
||||||
|
border: 0;
|
||||||
|
background-color: #F2F6F5;
|
||||||
|
color: #5E7471;
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
QPushButton#CockpitFilterPill:hover {
|
||||||
|
background-color: #E5F1EE;
|
||||||
|
color: #0E6F5C;
|
||||||
|
}
|
||||||
|
QPushButton#CockpitFilterPill:checked {
|
||||||
|
background-color: #111918;
|
||||||
|
color: #FFFFFF;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
QFrame#TimelineItemCard {
|
||||||
|
background-color: #F5F8F7;
|
||||||
|
border: 1px solid transparent;
|
||||||
|
border-radius: 16px;
|
||||||
|
}
|
||||||
|
QFrame#TimelineItemCard:hover {
|
||||||
|
background-color: #EBF3F0;
|
||||||
|
border-color: #CFE2DD;
|
||||||
|
}
|
||||||
|
QFrame#TimelineItemCard[activeItem="true"] {
|
||||||
|
background-color: #0E6F5C;
|
||||||
|
border: 1px solid #0E6F5C;
|
||||||
|
border-radius: 16px;
|
||||||
|
}
|
||||||
|
QPushButton#TimelinePlayCircle {
|
||||||
|
min-width: 30px;
|
||||||
|
max-width: 30px;
|
||||||
|
min-height: 30px;
|
||||||
|
max-height: 30px;
|
||||||
|
border-radius: 15px;
|
||||||
|
background-color: #FFFFFF;
|
||||||
|
border: 0;
|
||||||
|
color: #0E6F5C;
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
QPushButton#TimelinePlayCircle:hover {
|
||||||
|
background-color: #E5F6F1;
|
||||||
|
}
|
||||||
|
QLabel#TimelineDoneBadge {
|
||||||
|
min-width: 28px;
|
||||||
|
max-width: 28px;
|
||||||
|
min-height: 28px;
|
||||||
|
max-height: 28px;
|
||||||
|
border-radius: 14px;
|
||||||
|
background-color: #E0F2EC;
|
||||||
|
color: #0E6F5C;
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
QLabel#TimelineWaitBadge {
|
||||||
|
min-width: 28px;
|
||||||
|
max-width: 28px;
|
||||||
|
min-height: 28px;
|
||||||
|
max-height: 28px;
|
||||||
|
border-radius: 14px;
|
||||||
|
background-color: #EAEFED;
|
||||||
|
color: #6E8380;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
QPushButton#CareTeamActionPill {
|
||||||
|
min-width: 32px;
|
||||||
|
min-height: 30px;
|
||||||
|
max-height: 30px;
|
||||||
|
padding: 0 11px;
|
||||||
|
border-radius: 15px;
|
||||||
|
background-color: #F3F7F6;
|
||||||
|
border: 1px solid #E1ECE8;
|
||||||
|
color: #192E2C;
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
QPushButton#CareTeamActionPill:hover {
|
||||||
|
background-color: #E2F3EE;
|
||||||
|
border-color: #9ED0C3;
|
||||||
|
color: #0E6F5C;
|
||||||
|
}
|
||||||
|
QPushButton#CareTeamActionPill:disabled {
|
||||||
|
color: #9EB0AD;
|
||||||
|
background-color: #F6F8F8;
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def _safe_int(val: Any, default: int = 0) -> int:
|
||||||
|
try:
|
||||||
|
return int(val)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return default
|
||||||
|
|
||||||
|
|
||||||
|
class _TimelineRowWidget(QFrame):
|
||||||
|
"""Single appointment row inside Today's Plan (Alveo solid-emerald active pill)."""
|
||||||
|
|
||||||
|
row_clicked = Signal(object)
|
||||||
|
play_clicked = Signal(object)
|
||||||
|
|
||||||
|
def __init__(self, record: Any, *, active: bool, parent: QWidget | None = None) -> None:
|
||||||
|
super().__init__(parent)
|
||||||
|
self.record = record
|
||||||
|
self.setObjectName("TimelineItemCard")
|
||||||
|
self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True)
|
||||||
|
self.setProperty("activeItem", active)
|
||||||
|
self.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||||
|
self.setFixedHeight(58)
|
||||||
|
if active:
|
||||||
|
self.setStyleSheet(
|
||||||
|
"QFrame#TimelineItemCard {"
|
||||||
|
" background-color: #0E6F5C; border: 1px solid #0E6F5C; border-radius: 16px; }"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
self.setStyleSheet(
|
||||||
|
"QFrame#TimelineItemCard {"
|
||||||
|
" background-color: #F5F8F7; border: 1px solid transparent; border-radius: 16px; }"
|
||||||
|
"QFrame#TimelineItemCard:hover {"
|
||||||
|
" background-color: #EBF3F0; border: 1px solid #CFE2DD; }"
|
||||||
|
)
|
||||||
|
|
||||||
|
layout = QHBoxLayout(self)
|
||||||
|
layout.setContentsMargins(14, 8, 12, 8)
|
||||||
|
layout.setSpacing(10)
|
||||||
|
|
||||||
|
# Time + Mode column
|
||||||
|
time_raw = display_text(
|
||||||
|
first_value(record, "appointment_time_text", "appointment_time", "time", default="待排期")
|
||||||
|
)
|
||||||
|
short_time = time_raw.split("-")[0][:5] if ":" in time_raw else time_raw[:6]
|
||||||
|
mode_txt = appointment_type_description(appointment_type_value(record))[:4]
|
||||||
|
|
||||||
|
t_col = QVBoxLayout()
|
||||||
|
t_col.setContentsMargins(0, 0, 0, 0)
|
||||||
|
t_col.setSpacing(1)
|
||||||
|
t_lbl = QLabel(short_time, self)
|
||||||
|
t_lbl.setFixedWidth(48)
|
||||||
|
t_lbl.setStyleSheet(
|
||||||
|
f"color: {'#FFFFFF' if active else '#152725'}; font-size: 13px; font-weight: 600; background: transparent;"
|
||||||
|
)
|
||||||
|
m_lbl = QLabel(mode_txt, self)
|
||||||
|
m_lbl.setFixedWidth(48)
|
||||||
|
m_lbl.setStyleSheet(
|
||||||
|
f"color: {'rgba(255,255,255,195)' if active else '#7A908C'}; font-size: 10px; background: transparent;"
|
||||||
|
)
|
||||||
|
t_col.addWidget(t_lbl)
|
||||||
|
t_col.addWidget(m_lbl)
|
||||||
|
layout.addLayout(t_col)
|
||||||
|
|
||||||
|
# Patient Name + Chief Complaint / Condition
|
||||||
|
p_name = display_text(first_value(record, "patient_name", "name", default="患者"))
|
||||||
|
diag_sub = first_value(record, "diagnosis", default={}) or {}
|
||||||
|
chief = display_text(
|
||||||
|
first_value(
|
||||||
|
record,
|
||||||
|
"chief_complaint",
|
||||||
|
"clinical_diagnosis",
|
||||||
|
default=first_value(diag_sub, "chief_complaint", "clinical_diagnosis", default="点击载入四诊详情"),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
if len(chief) > 15:
|
||||||
|
chief = f"{chief[:14]}…"
|
||||||
|
|
||||||
|
c_col = QVBoxLayout()
|
||||||
|
c_col.setContentsMargins(0, 0, 0, 0)
|
||||||
|
c_col.setSpacing(1)
|
||||||
|
n_lbl = QLabel(p_name, self)
|
||||||
|
n_lbl.setStyleSheet(
|
||||||
|
f"color: {'#FFFFFF' if active else '#11201E'}; font-size: 13px; font-weight: 600; background: transparent;"
|
||||||
|
)
|
||||||
|
s_lbl = QLabel(chief, self)
|
||||||
|
s_lbl.setStyleSheet(
|
||||||
|
f"color: {'rgba(255,255,255,205)' if active else '#6E8380'}; font-size: 11px; background: transparent;"
|
||||||
|
)
|
||||||
|
c_col.addWidget(n_lbl)
|
||||||
|
c_col.addWidget(s_lbl)
|
||||||
|
layout.addLayout(c_col, 1)
|
||||||
|
|
||||||
|
# Right Status / Play Action (Alveo circular white play button on active emerald row!)
|
||||||
|
status = _safe_int(first_value(record, "status", default=1), 1)
|
||||||
|
if active:
|
||||||
|
play_btn = QPushButton("▷", self)
|
||||||
|
play_btn.setObjectName("TimelinePlayCircle")
|
||||||
|
play_btn.setFixedSize(30, 30)
|
||||||
|
play_btn.setStyleSheet(
|
||||||
|
"QPushButton#TimelinePlayCircle {"
|
||||||
|
" min-width: 30px; max-width: 30px; min-height: 30px; max-height: 30px;"
|
||||||
|
" border-radius: 15px; background-color: #FFFFFF; border: 0;"
|
||||||
|
" color: #0E6F5C; font-size: 12px; font-weight: 700; padding: 0; }"
|
||||||
|
"QPushButton#TimelinePlayCircle:hover { background-color: #E6F6F1; }"
|
||||||
|
)
|
||||||
|
play_btn.setToolTip("立即发起视频 / IM 问诊")
|
||||||
|
play_btn.clicked.connect(lambda: self.play_clicked.emit(self.record))
|
||||||
|
layout.addWidget(play_btn)
|
||||||
|
elif status == 3:
|
||||||
|
done_lbl = QLabel("✓", self)
|
||||||
|
done_lbl.setObjectName("TimelineDoneBadge")
|
||||||
|
done_lbl.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||||
|
layout.addWidget(done_lbl)
|
||||||
|
else:
|
||||||
|
wait_lbl = QLabel("•", self)
|
||||||
|
wait_lbl.setObjectName("TimelineWaitBadge")
|
||||||
|
wait_lbl.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||||
|
layout.addWidget(wait_lbl)
|
||||||
|
|
||||||
|
def mousePressEvent(self, event: Any) -> None: # noqa: N802
|
||||||
|
if event.button() == Qt.MouseButton.LeftButton:
|
||||||
|
self.row_clicked.emit(self.record)
|
||||||
|
event.accept()
|
||||||
|
return
|
||||||
|
super().mousePressEvent(event)
|
||||||
|
|
||||||
|
|
||||||
|
class ReceptionDigitalTwinCockpit(QWidget):
|
||||||
|
"""Full Alveo × Serene 3-column Digital Twin Cockpit + 21-Day Journey Track."""
|
||||||
|
|
||||||
|
appointment_selected = Signal(object)
|
||||||
|
filter_status_requested = Signal(object)
|
||||||
|
refresh_requested = Signal()
|
||||||
|
start_video_requested = Signal()
|
||||||
|
edit_diagnosis_requested = Signal()
|
||||||
|
notify_assistant_requested = Signal()
|
||||||
|
complete_visit_requested = Signal()
|
||||||
|
open_chart_tab_requested = Signal(int)
|
||||||
|
|
||||||
|
def __init__(self, parent: QWidget | None = None) -> None:
|
||||||
|
super().__init__(parent)
|
||||||
|
self.setObjectName("ReceptionDigitalTwinCockpit")
|
||||||
|
self.setStyleSheet(COCKPIT_QSS)
|
||||||
|
|
||||||
|
root = QVBoxLayout(self)
|
||||||
|
root.setContentsMargins(0, 0, 0, 0)
|
||||||
|
root.setSpacing(12)
|
||||||
|
|
||||||
|
# ── Layer 3: Asymmetric 3-Column Clinical Cockpit ──────────────────
|
||||||
|
cockpit_row = QHBoxLayout()
|
||||||
|
cockpit_row.setContentsMargins(0, 0, 0, 0)
|
||||||
|
cockpit_row.setSpacing(14)
|
||||||
|
|
||||||
|
# Column 1 (Left 25%): Glycemic Progression + Diurnal TIR & Mini Vitals
|
||||||
|
left_wing = QWidget(self)
|
||||||
|
left_wing.setMinimumWidth(276)
|
||||||
|
left_wing.setMaximumWidth(390)
|
||||||
|
left_layout = QVBoxLayout(left_wing)
|
||||||
|
left_layout.setContentsMargins(0, 0, 0, 0)
|
||||||
|
left_layout.setSpacing(12)
|
||||||
|
|
||||||
|
self.progression_card = PillProgressionCard(left_wing)
|
||||||
|
self.diurnal_card = DiurnalStabilityCard(left_wing)
|
||||||
|
left_layout.addWidget(self.progression_card, 44)
|
||||||
|
left_layout.addWidget(self.diurnal_card, 56)
|
||||||
|
cockpit_row.addWidget(left_wing, 26)
|
||||||
|
|
||||||
|
# Column 2 (Center 47%): Translucent Jade-Crystal Three-Jiao Digital Twin Stage
|
||||||
|
self.twin_stage = ClinicalTwinStageWidget(self)
|
||||||
|
self.twin_stage.locus_clicked.connect(lambda _locus: self.edit_diagnosis_requested.emit())
|
||||||
|
self.twin_stage.open_chart_requested.connect(lambda: self.open_chart_tab_requested.emit(0))
|
||||||
|
cockpit_row.addWidget(self.twin_stage, 46)
|
||||||
|
|
||||||
|
# Column 3 (Right 28%): Today's Plan Timeline + Care Team Collaboration
|
||||||
|
right_wing = QWidget(self)
|
||||||
|
right_wing.setMinimumWidth(286)
|
||||||
|
right_wing.setMaximumWidth(400)
|
||||||
|
right_layout = QVBoxLayout(right_wing)
|
||||||
|
right_layout.setContentsMargins(0, 0, 0, 0)
|
||||||
|
right_layout.setSpacing(12)
|
||||||
|
|
||||||
|
self.plan_card = self._build_today_plan_card(right_wing)
|
||||||
|
self.team_card = self._build_care_team_card(right_wing)
|
||||||
|
right_layout.addWidget(self.plan_card, 62)
|
||||||
|
right_layout.addWidget(self.team_card, 38)
|
||||||
|
cockpit_row.addWidget(right_wing, 28)
|
||||||
|
|
||||||
|
root.addLayout(cockpit_row, 1)
|
||||||
|
|
||||||
|
# ── Layer 4A: Bottom 21-Day Care Journey Rounded-Pill Matrix ───────
|
||||||
|
self.journey_card = CareJourneyCard(self)
|
||||||
|
self.journey_card.open_full_plan_requested.connect(lambda: self.open_chart_tab_requested.emit(4))
|
||||||
|
self.journey_card.day_selected.connect(lambda _d: self.open_chart_tab_requested.emit(3))
|
||||||
|
root.addWidget(self.journey_card)
|
||||||
|
|
||||||
|
# Seed default visual state immediately so screen is rich even while async loads
|
||||||
|
self.set_snapshot(derive_cockpit_snapshot())
|
||||||
|
|
||||||
|
def _build_today_plan_card(self, parent: QWidget) -> QFrame:
|
||||||
|
card = QFrame(parent)
|
||||||
|
card.setObjectName("CockpitBentoCard")
|
||||||
|
layout = QVBoxLayout(card)
|
||||||
|
layout.setContentsMargins(18, 15, 18, 14)
|
||||||
|
layout.setSpacing(10)
|
||||||
|
|
||||||
|
head = QHBoxLayout()
|
||||||
|
head.setSpacing(8)
|
||||||
|
title = QLabel("今日门诊计划", card)
|
||||||
|
t_font = QFont(heading_family())
|
||||||
|
t_font.setPixelSize(15)
|
||||||
|
t_font.setWeight(QFont.Weight.DemiBold)
|
||||||
|
title.setFont(t_font)
|
||||||
|
title.setStyleSheet("color: #11201E; background: transparent;")
|
||||||
|
head.addWidget(title)
|
||||||
|
head.addStretch(1)
|
||||||
|
|
||||||
|
self.plan_date_label = QLabel(date.today().strftime("%m月%d日"), card)
|
||||||
|
self.plan_date_label.setStyleSheet("color: #788E8A; font-size: 12px; background: transparent;")
|
||||||
|
head.addWidget(self.plan_date_label)
|
||||||
|
|
||||||
|
refresh_btn = QPushButton(card)
|
||||||
|
refresh_btn.setFixedSize(26, 26)
|
||||||
|
refresh_btn.setIcon(icons.icon("refresh", "#5A706D", 14))
|
||||||
|
refresh_btn.setIconSize(QSize(14, 14))
|
||||||
|
refresh_btn.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||||
|
refresh_btn.setToolTip("刷新今日接诊队列")
|
||||||
|
refresh_btn.setStyleSheet(
|
||||||
|
"QPushButton { background: #F3F7F6; border: 0; border-radius: 13px; }"
|
||||||
|
"QPushButton:hover { background: #E3F2EE; }"
|
||||||
|
)
|
||||||
|
refresh_btn.clicked.connect(self.refresh_requested.emit)
|
||||||
|
head.addWidget(refresh_btn)
|
||||||
|
layout.addLayout(head)
|
||||||
|
|
||||||
|
# Compact status filter chips
|
||||||
|
chip_row = QHBoxLayout()
|
||||||
|
chip_row.setSpacing(6)
|
||||||
|
self._status_pills: dict[int | None, QPushButton] = {}
|
||||||
|
for st_val, st_label in ((1, "待接诊"), (None, "全部"), (3, "已完成")):
|
||||||
|
pill = QPushButton(st_label, card)
|
||||||
|
pill.setObjectName("CockpitFilterPill")
|
||||||
|
pill.setCheckable(True)
|
||||||
|
pill.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||||
|
pill.clicked.connect(lambda _c=False, v=st_val: self._on_filter_pill_clicked(v))
|
||||||
|
self._status_pills[st_val] = pill
|
||||||
|
chip_row.addWidget(pill)
|
||||||
|
self._status_pills[1].setChecked(True)
|
||||||
|
chip_row.addStretch(1)
|
||||||
|
layout.addLayout(chip_row)
|
||||||
|
|
||||||
|
self.timeline_scroll = QScrollArea(card)
|
||||||
|
self.timeline_scroll.setWidgetResizable(True)
|
||||||
|
self.timeline_scroll.setFrameShape(QFrame.Shape.NoFrame)
|
||||||
|
self.timeline_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
|
||||||
|
self.timeline_scroll.setStyleSheet("QScrollArea { background: transparent; border: 0; }")
|
||||||
|
|
||||||
|
self.timeline_host = QWidget(self.timeline_scroll)
|
||||||
|
self.timeline_host.setStyleSheet("background: transparent;")
|
||||||
|
self.timeline_layout = QVBoxLayout(self.timeline_host)
|
||||||
|
self.timeline_layout.setContentsMargins(0, 0, 2, 0)
|
||||||
|
self.timeline_layout.setSpacing(8)
|
||||||
|
self.timeline_layout.addStretch(1)
|
||||||
|
self.timeline_scroll.setWidget(self.timeline_host)
|
||||||
|
layout.addWidget(self.timeline_scroll, 1)
|
||||||
|
|
||||||
|
return card
|
||||||
|
|
||||||
|
def _build_care_team_card(self, parent: QWidget) -> QFrame:
|
||||||
|
card = QFrame(parent)
|
||||||
|
card.setObjectName("CockpitBentoCard")
|
||||||
|
layout = QVBoxLayout(card)
|
||||||
|
layout.setContentsMargins(18, 14, 18, 14)
|
||||||
|
layout.setSpacing(8)
|
||||||
|
|
||||||
|
head = QHBoxLayout()
|
||||||
|
title = QLabel("诊疗协作组", card)
|
||||||
|
t_font = QFont(heading_family())
|
||||||
|
t_font.setPixelSize(15)
|
||||||
|
t_font.setWeight(QFont.Weight.DemiBold)
|
||||||
|
title.setFont(t_font)
|
||||||
|
title.setStyleSheet("color: #11201E; background: transparent;")
|
||||||
|
head.addWidget(title)
|
||||||
|
head.addStretch(1)
|
||||||
|
shift_lbl = QLabel("3 席在线协同", card)
|
||||||
|
shift_lbl.setStyleSheet("color: #7A908C; font-size: 11px; background: transparent;")
|
||||||
|
head.addWidget(shift_lbl)
|
||||||
|
layout.addLayout(head)
|
||||||
|
|
||||||
|
# 3 Alveo Care Team Rows: Lead Doctor, Assigned Assistant, Clinical Completion
|
||||||
|
self.doctor_name_lbl, self.doctor_role_lbl, self.edit_diag_btn = self._add_team_row(
|
||||||
|
layout,
|
||||||
|
avatar_text="医",
|
||||||
|
avatar_bg="#E2F3EE",
|
||||||
|
avatar_fg="#0E6F5C",
|
||||||
|
name="主诊中医师",
|
||||||
|
role="辨证施治 · 四诊合参",
|
||||||
|
action_text="编辑病历",
|
||||||
|
callback=self.edit_diagnosis_requested.emit,
|
||||||
|
)
|
||||||
|
self.assistant_name_lbl, self.assistant_role_lbl, self.notify_asst_btn = self._add_team_row(
|
||||||
|
layout,
|
||||||
|
avatar_text="助",
|
||||||
|
avatar_bg="#EDF4F2",
|
||||||
|
avatar_fg="#2B524C",
|
||||||
|
name="专属医助",
|
||||||
|
role="诊前采集 · 院外随访",
|
||||||
|
action_text="通知医助",
|
||||||
|
callback=self.notify_assistant_requested.emit,
|
||||||
|
)
|
||||||
|
self.pharmacist_name_lbl, self.pharmacist_role_lbl, self.complete_visit_btn = self._add_team_row(
|
||||||
|
layout,
|
||||||
|
avatar_text="结",
|
||||||
|
avatar_bg="#FAF4E6",
|
||||||
|
avatar_fg="#9E7425",
|
||||||
|
name="门诊闭环核验",
|
||||||
|
role="病历归档 · 完成本次接诊",
|
||||||
|
action_text="完成接诊",
|
||||||
|
callback=self.complete_visit_requested.emit,
|
||||||
|
)
|
||||||
|
return card
|
||||||
|
|
||||||
|
def _add_team_row(
|
||||||
|
self,
|
||||||
|
parent_layout: QVBoxLayout,
|
||||||
|
*,
|
||||||
|
avatar_text: str,
|
||||||
|
avatar_bg: str,
|
||||||
|
avatar_fg: str,
|
||||||
|
name: str,
|
||||||
|
role: str,
|
||||||
|
action_text: str,
|
||||||
|
callback: Any,
|
||||||
|
) -> tuple[QLabel, QLabel, QPushButton]:
|
||||||
|
row = QWidget(self)
|
||||||
|
rl = QHBoxLayout(row)
|
||||||
|
rl.setContentsMargins(0, 2, 0, 2)
|
||||||
|
rl.setSpacing(10)
|
||||||
|
|
||||||
|
av = QLabel(avatar_text, row)
|
||||||
|
av.setFixedSize(34, 34)
|
||||||
|
av.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||||
|
av.setStyleSheet(
|
||||||
|
f"background-color: {avatar_bg}; color: {avatar_fg}; border-radius: 17px;"
|
||||||
|
" font-size: 13px; font-weight: 600;"
|
||||||
|
)
|
||||||
|
rl.addWidget(av)
|
||||||
|
|
||||||
|
meta = QVBoxLayout()
|
||||||
|
meta.setContentsMargins(0, 0, 0, 0)
|
||||||
|
meta.setSpacing(1)
|
||||||
|
n_lbl = QLabel(name, row)
|
||||||
|
n_lbl.setStyleSheet("color: #122220; font-size: 13px; font-weight: 600; background: transparent;")
|
||||||
|
r_lbl = QLabel(role, row)
|
||||||
|
r_lbl.setStyleSheet("color: #788E8A; font-size: 11px; background: transparent;")
|
||||||
|
r_lbl.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred)
|
||||||
|
meta.addWidget(n_lbl)
|
||||||
|
meta.addWidget(r_lbl)
|
||||||
|
rl.addLayout(meta, 1)
|
||||||
|
|
||||||
|
btn = QPushButton(action_text, row)
|
||||||
|
btn.setObjectName("CareTeamActionPill")
|
||||||
|
btn.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||||
|
btn.clicked.connect(callback)
|
||||||
|
rl.addWidget(btn)
|
||||||
|
parent_layout.addWidget(row)
|
||||||
|
return n_lbl, r_lbl, btn
|
||||||
|
|
||||||
|
def _on_filter_pill_clicked(self, status_val: int | None) -> None:
|
||||||
|
for k, btn in self._status_pills.items():
|
||||||
|
btn.setChecked(k == status_val)
|
||||||
|
self.filter_status_requested.emit(status_val)
|
||||||
|
|
||||||
|
def set_snapshot(self, snapshot: CockpitSnapshotVM) -> None:
|
||||||
|
self.progression_card.set_view_model(snapshot.progression)
|
||||||
|
self.diurnal_card.set_view_model(snapshot.diurnal)
|
||||||
|
self.twin_stage.set_snapshot(snapshot)
|
||||||
|
self.journey_card.set_view_model(snapshot.journey)
|
||||||
|
|
||||||
|
def set_care_team_context(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
doctor_name: str,
|
||||||
|
assistant_name: str,
|
||||||
|
can_edit: bool,
|
||||||
|
can_notify: bool,
|
||||||
|
can_complete: bool,
|
||||||
|
) -> None:
|
||||||
|
self.doctor_name_lbl.setText(doctor_name if doctor_name and doctor_name != "—" else "主诊中医师")
|
||||||
|
self.assistant_name_lbl.setText(
|
||||||
|
f"{assistant_name}(医助)" if assistant_name and assistant_name != "—" else "待分配医助"
|
||||||
|
)
|
||||||
|
self.edit_diag_btn.setEnabled(can_edit)
|
||||||
|
self.notify_asst_btn.setEnabled(can_notify)
|
||||||
|
self.complete_visit_btn.setEnabled(can_complete)
|
||||||
|
|
||||||
|
def set_queue_records(
|
||||||
|
self,
|
||||||
|
records: Sequence[Any],
|
||||||
|
selected_appointment_id: int | None,
|
||||||
|
*,
|
||||||
|
active_filter_status: int | None = 1,
|
||||||
|
queue_date: str = "",
|
||||||
|
) -> None:
|
||||||
|
for k, btn in self._status_pills.items():
|
||||||
|
btn.setChecked(k == active_filter_status)
|
||||||
|
if queue_date:
|
||||||
|
self.plan_date_label.setText(f"{queue_date[5:]} · {len(records)}人")
|
||||||
|
else:
|
||||||
|
self.plan_date_label.setText(f"共 {len(records)} 人")
|
||||||
|
|
||||||
|
clear_layout(self.timeline_layout)
|
||||||
|
if not records:
|
||||||
|
empty = QLabel("当前筛选下暂无门诊挂号\n可切换上方「全部」查看历史接诊", self.timeline_host)
|
||||||
|
empty.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||||
|
empty.setStyleSheet(
|
||||||
|
f"color: #7D918E; font-size: 12px; font-family: '{body_family()}';"
|
||||||
|
" padding: 28px 12px; background: #F7FAF9; border-radius: 14px;"
|
||||||
|
)
|
||||||
|
self.timeline_layout.addWidget(empty)
|
||||||
|
self.timeline_layout.addStretch(1)
|
||||||
|
return
|
||||||
|
|
||||||
|
for rec in records[:25]:
|
||||||
|
rec_id = _safe_int(first_value(rec, "id", "appointment_id", default=0))
|
||||||
|
is_active = bool(selected_appointment_id and rec_id == selected_appointment_id)
|
||||||
|
row_widget = _TimelineRowWidget(rec, active=is_active, parent=self.timeline_host)
|
||||||
|
row_widget.row_clicked.connect(self.appointment_selected.emit)
|
||||||
|
row_widget.play_clicked.connect(lambda _r: self.start_video_requested.emit())
|
||||||
|
self.timeline_layout.addWidget(row_widget)
|
||||||
|
self.timeline_layout.addStretch(1)
|
||||||
@@ -0,0 +1,556 @@
|
|||||||
|
"""Human Body & Metabolic Visceral Symptom Evidence Map (100% Real Clinical Data)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import math
|
||||||
|
|
||||||
|
from PySide6.QtCore import QPointF, QRectF, QSize, Qt, QTimer, Signal
|
||||||
|
from PySide6.QtGui import (
|
||||||
|
QColor,
|
||||||
|
QFont,
|
||||||
|
QLinearGradient,
|
||||||
|
QMouseEvent,
|
||||||
|
QPainter,
|
||||||
|
QPainterPath,
|
||||||
|
QPen,
|
||||||
|
QRadialGradient,
|
||||||
|
)
|
||||||
|
from PySide6.QtWidgets import QToolTip, QWidget
|
||||||
|
|
||||||
|
from .. import motion
|
||||||
|
from ..reception_style import body_family, heading_family
|
||||||
|
from ..viewmodels.cockpit_vm import CockpitSnapshotVM, TwinCalloutNode
|
||||||
|
|
||||||
|
_MODES: tuple[tuple[str, str], ...] = (
|
||||||
|
("sanjiao", "全身症候"),
|
||||||
|
("organ", "病史用药"),
|
||||||
|
("tcm", "四诊处方"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class ClinicalTwinStageWidget(QWidget):
|
||||||
|
"""Center human body & metabolic organ symptom map bound strictly to real case data."""
|
||||||
|
|
||||||
|
mode_changed = Signal(str)
|
||||||
|
locus_clicked = Signal(str)
|
||||||
|
open_chart_requested = Signal()
|
||||||
|
|
||||||
|
def __init__(self, parent: QWidget | None = None) -> None:
|
||||||
|
super().__init__(parent)
|
||||||
|
self.setObjectName("ClinicalTwinStageWidget")
|
||||||
|
self.setMouseTracking(True)
|
||||||
|
self.setMinimumSize(400, 320)
|
||||||
|
self._snapshot: CockpitSnapshotVM | None = None
|
||||||
|
self._mode_key = "sanjiao"
|
||||||
|
self._phase = 0.0
|
||||||
|
self._mode_rects: list[tuple[str, QRectF]] = []
|
||||||
|
self._callout_rects: list[tuple[str, QRectF, str]] = []
|
||||||
|
self._open_chart_rect = QRectF()
|
||||||
|
self._hover_target = ""
|
||||||
|
|
||||||
|
self._anim_timer = QTimer(self)
|
||||||
|
self._anim_timer.setInterval(100)
|
||||||
|
self._anim_timer.timeout.connect(self._tick_breath)
|
||||||
|
|
||||||
|
def sizeHint(self) -> QSize: # noqa: N802
|
||||||
|
return QSize(580, 500)
|
||||||
|
|
||||||
|
def showEvent(self, event: object) -> None: # noqa: N802
|
||||||
|
super().showEvent(event) # type: ignore[arg-type]
|
||||||
|
if not motion.reduced_motion():
|
||||||
|
self._anim_timer.start()
|
||||||
|
|
||||||
|
def hideEvent(self, event: object) -> None: # noqa: N802
|
||||||
|
self._anim_timer.stop()
|
||||||
|
super().hideEvent(event) # type: ignore[arg-type]
|
||||||
|
|
||||||
|
def _tick_breath(self) -> None:
|
||||||
|
self._phase = (self._phase + 0.14) % (math.pi * 2.0)
|
||||||
|
if self._snapshot and self._snapshot.has_patient:
|
||||||
|
self.update()
|
||||||
|
|
||||||
|
def set_snapshot(self, snapshot: CockpitSnapshotVM) -> None:
|
||||||
|
self._snapshot = snapshot
|
||||||
|
self.update()
|
||||||
|
|
||||||
|
def set_mode(self, mode_key: str) -> None:
|
||||||
|
if mode_key in {"sanjiao", "organ", "tcm"} and mode_key != self._mode_key:
|
||||||
|
self._mode_key = mode_key
|
||||||
|
self.mode_changed.emit(mode_key)
|
||||||
|
self.update()
|
||||||
|
|
||||||
|
def mouseMoveEvent(self, event: QMouseEvent) -> None: # noqa: N802
|
||||||
|
pos = event.position()
|
||||||
|
target = ""
|
||||||
|
if self._open_chart_rect.contains(pos):
|
||||||
|
target = "open_chart"
|
||||||
|
if not target:
|
||||||
|
for key, r in self._mode_rects:
|
||||||
|
if r.contains(pos):
|
||||||
|
target = f"mode:{key}"
|
||||||
|
break
|
||||||
|
if not target:
|
||||||
|
for locus_id, r, tip in self._callout_rects:
|
||||||
|
if r.contains(pos):
|
||||||
|
target = f"locus:{locus_id}"
|
||||||
|
if tip:
|
||||||
|
QToolTip.showText(event.globalPosition().toPoint(), tip, self)
|
||||||
|
break
|
||||||
|
self.setCursor(
|
||||||
|
Qt.CursorShape.PointingHandCursor if target else Qt.CursorShape.ArrowCursor
|
||||||
|
)
|
||||||
|
if target != self._hover_target:
|
||||||
|
self._hover_target = target
|
||||||
|
self.update()
|
||||||
|
super().mouseMoveEvent(event)
|
||||||
|
|
||||||
|
def mousePressEvent(self, event: QMouseEvent) -> None: # noqa: N802
|
||||||
|
if event.button() == Qt.MouseButton.LeftButton:
|
||||||
|
pos = event.position()
|
||||||
|
if self._open_chart_rect.contains(pos):
|
||||||
|
self.open_chart_requested.emit()
|
||||||
|
event.accept()
|
||||||
|
return
|
||||||
|
for key, r in self._mode_rects:
|
||||||
|
if r.contains(pos):
|
||||||
|
self.set_mode(key)
|
||||||
|
event.accept()
|
||||||
|
return
|
||||||
|
for locus_id, r, _tip in self._callout_rects:
|
||||||
|
if r.contains(pos):
|
||||||
|
self.locus_clicked.emit(locus_id)
|
||||||
|
event.accept()
|
||||||
|
return
|
||||||
|
super().mousePressEvent(event)
|
||||||
|
|
||||||
|
def _draw_human_metabolic_twin(
|
||||||
|
self,
|
||||||
|
painter: QPainter,
|
||||||
|
rect: QRectF,
|
||||||
|
zone_heats: tuple[float, float, float, float],
|
||||||
|
*,
|
||||||
|
dimmed: bool = False,
|
||||||
|
) -> None:
|
||||||
|
"""Paint an anatomical translucent Jade-Crystal Human Body & Metabolic Organs Twin."""
|
||||||
|
|
||||||
|
cx = rect.center().x()
|
||||||
|
cy = rect.center().y() + 4.0
|
||||||
|
h = rect.height()
|
||||||
|
scale = max(0.68, min(1.15, (h - 110.0) / 340.0))
|
||||||
|
alpha_mul = 0.42 if dimmed else 1.0
|
||||||
|
|
||||||
|
def _c(r_v: int, g_v: int, b_v: int, a_v: int) -> QColor:
|
||||||
|
return QColor(r_v, g_v, b_v, int(a_v * alpha_mul))
|
||||||
|
|
||||||
|
# 1. Outer Human Head + Neck + Shoulders + Torso + Pelvis Crystal Silhouette
|
||||||
|
body = QPainterPath()
|
||||||
|
# Head ellipse
|
||||||
|
head_cy = cy - 126 * scale
|
||||||
|
body.addEllipse(QPointF(cx, head_cy), 25 * scale, 30 * scale)
|
||||||
|
|
||||||
|
torso = QPainterPath()
|
||||||
|
torso.moveTo(cx - 11 * scale, cy - 96 * scale)
|
||||||
|
# Left neck -> left shoulder -> left flank -> hip -> leg root
|
||||||
|
torso.quadTo(cx - 14 * scale, cy - 84 * scale, cx - 58 * scale, cy - 74 * scale)
|
||||||
|
torso.cubicTo(
|
||||||
|
cx - 78 * scale,
|
||||||
|
cy - 68 * scale,
|
||||||
|
cx - 76 * scale,
|
||||||
|
cy - 20 * scale,
|
||||||
|
cx - 60 * scale,
|
||||||
|
cy + 28 * scale,
|
||||||
|
)
|
||||||
|
torso.cubicTo(
|
||||||
|
cx - 54 * scale,
|
||||||
|
cy + 62 * scale,
|
||||||
|
cx - 58 * scale,
|
||||||
|
cy + 98 * scale,
|
||||||
|
cx - 44 * scale,
|
||||||
|
cy + 138 * scale,
|
||||||
|
)
|
||||||
|
torso.lineTo(cx - 14 * scale, cy + 138 * scale)
|
||||||
|
torso.quadTo(cx, cy + 108 * scale, cx + 14 * scale, cy + 138 * scale)
|
||||||
|
torso.lineTo(cx + 44 * scale, cy + 138 * scale)
|
||||||
|
torso.cubicTo(
|
||||||
|
cx + 58 * scale,
|
||||||
|
cy + 98 * scale,
|
||||||
|
cx + 54 * scale,
|
||||||
|
cy + 62 * scale,
|
||||||
|
cx + 60 * scale,
|
||||||
|
cy + 28 * scale,
|
||||||
|
)
|
||||||
|
torso.cubicTo(
|
||||||
|
cx + 76 * scale,
|
||||||
|
cy - 20 * scale,
|
||||||
|
cx + 78 * scale,
|
||||||
|
cy - 68 * scale,
|
||||||
|
cx + 58 * scale,
|
||||||
|
cy - 74 * scale,
|
||||||
|
)
|
||||||
|
torso.quadTo(cx + 14 * scale, cy - 84 * scale, cx + 11 * scale, cy - 96 * scale)
|
||||||
|
torso.closeSubpath()
|
||||||
|
|
||||||
|
body_grad = QLinearGradient(cx, cy - 155 * scale, cx, cy + 140 * scale)
|
||||||
|
body_grad.setColorAt(0.0, _c(216, 240, 234, 185))
|
||||||
|
body_grad.setColorAt(0.5, _c(132, 198, 184, 128))
|
||||||
|
body_grad.setColorAt(1.0, _c(64, 142, 128, 145))
|
||||||
|
|
||||||
|
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||||
|
painter.fillPath(body, body_grad)
|
||||||
|
painter.fillPath(torso, body_grad)
|
||||||
|
painter.setPen(QPen(_c(255, 255, 255, 210), 2.0))
|
||||||
|
painter.drawPath(body)
|
||||||
|
painter.drawPath(torso)
|
||||||
|
painter.setPen(QPen(_c(16, 106, 90, 95), 1.1))
|
||||||
|
painter.drawPath(body)
|
||||||
|
painter.drawPath(torso)
|
||||||
|
|
||||||
|
# 2. Internal Target Organs of Diabetes & TCM Sanjiao:
|
||||||
|
# (A) Central Esophagus / Meridian Conduit
|
||||||
|
painter.setPen(QPen(_c(255, 255, 255, 150), 2.2, Qt.PenStyle.SolidLine, Qt.PenCapStyle.RoundCap))
|
||||||
|
painter.drawLine(QPointF(cx, cy - 94 * scale), QPointF(cx, cy + 92 * scale))
|
||||||
|
painter.setPen(QPen(_c(14, 111, 92, 95), 1.0, Qt.PenStyle.DashLine))
|
||||||
|
painter.drawLine(QPointF(cx, cy - 135 * scale), QPointF(cx, cy + 115 * scale))
|
||||||
|
|
||||||
|
# (B) Upper Thoracic Cardiopulmonary Shield (subtle paired translucent chambers)
|
||||||
|
for sign in (-1.0, 1.0):
|
||||||
|
chest = QPainterPath()
|
||||||
|
chest.moveTo(cx + sign * 6 * scale, cy - 66 * scale)
|
||||||
|
chest.cubicTo(
|
||||||
|
cx + sign * 38 * scale,
|
||||||
|
cy - 70 * scale,
|
||||||
|
cx + sign * 46 * scale,
|
||||||
|
cy - 34 * scale,
|
||||||
|
cx + sign * 40 * scale,
|
||||||
|
cy - 12 * scale,
|
||||||
|
)
|
||||||
|
chest.quadTo(cx + sign * 18 * scale, cy - 8 * scale, cx + sign * 6 * scale, cy - 22 * scale)
|
||||||
|
chest.closeSubpath()
|
||||||
|
painter.fillPath(chest, _c(255, 255, 255, 76))
|
||||||
|
painter.setPen(QPen(_c(14, 111, 92, 78), 1.0))
|
||||||
|
painter.drawPath(chest)
|
||||||
|
|
||||||
|
# (C) Liver ( Anatomical Right = Viewer Left ) & Stomach/Spleen ( Viewer Right )
|
||||||
|
liver = QPainterPath()
|
||||||
|
liver.moveTo(cx - 42 * scale, cy - 2 * scale)
|
||||||
|
liver.cubicTo(cx - 18 * scale, cy - 6 * scale, cx + 6 * scale, cy + 2 * scale, cx + 8 * scale, cy + 14 * scale)
|
||||||
|
liver.cubicTo(cx - 12 * scale, cy + 26 * scale, cx - 38 * scale, cy + 28 * scale, cx - 42 * scale, cy - 2 * scale)
|
||||||
|
painter.fillPath(liver, _c(22, 124, 104, 115))
|
||||||
|
painter.setPen(QPen(_c(255, 255, 255, 165), 1.1))
|
||||||
|
painter.drawPath(liver)
|
||||||
|
|
||||||
|
# (D) Pancreas (胰岛核心 — Golden-Jade leaf across mid-abdomen!)
|
||||||
|
pancreas = QPainterPath()
|
||||||
|
pancreas.moveTo(cx - 14 * scale, cy + 22 * scale)
|
||||||
|
pancreas.cubicTo(cx + 6 * scale, cy + 14 * scale, cx + 28 * scale, cy + 18 * scale, cx + 36 * scale, cy + 26 * scale)
|
||||||
|
pancreas.cubicTo(cx + 24 * scale, cy + 36 * scale, cx + 2 * scale, cy + 36 * scale, cx - 14 * scale, cy + 22 * scale)
|
||||||
|
panc_grad = QLinearGradient(cx - 14 * scale, cy + 16 * scale, cx + 36 * scale, cy + 34 * scale)
|
||||||
|
panc_grad.setColorAt(0.0, _c(223, 199, 147, 195))
|
||||||
|
panc_grad.setColorAt(1.0, _c(14, 111, 92, 155))
|
||||||
|
painter.fillPath(pancreas, panc_grad)
|
||||||
|
painter.setPen(QPen(_c(255, 255, 255, 195), 1.2))
|
||||||
|
painter.drawPath(pancreas)
|
||||||
|
|
||||||
|
# (E) Bilateral Kidneys & Lower-Limb Microvascular Branches
|
||||||
|
for sign in (-1.0, 1.0):
|
||||||
|
kx = cx + sign * 22 * scale
|
||||||
|
ky = cy + 56 * scale
|
||||||
|
kidney = QPainterPath()
|
||||||
|
kidney.addRoundedRect(QRectF(kx - 9 * scale, ky - 14 * scale, 18 * scale, 28 * scale), 9 * scale, 9 * scale)
|
||||||
|
painter.fillPath(kidney, _c(20, 112, 96, 120))
|
||||||
|
painter.setPen(QPen(_c(255, 255, 255, 165), 1.0))
|
||||||
|
painter.drawPath(kidney)
|
||||||
|
# Peripheral nerve / vessel line down into lower limbs
|
||||||
|
painter.setPen(QPen(_c(14, 111, 92, 95), 1.2))
|
||||||
|
painter.drawLine(QPointF(kx, ky + 14 * scale), QPointF(cx + sign * 28 * scale, cy + 128 * scale))
|
||||||
|
|
||||||
|
if dimmed:
|
||||||
|
return
|
||||||
|
|
||||||
|
# 3. Real Positive-Symptom Focal Glows (ONLY where real case data has findings!)
|
||||||
|
breath = 1.0 + 0.07 * math.sin(self._phase)
|
||||||
|
zone_coords = (
|
||||||
|
(cx, head_cy, zone_heats[0]), # Head / Eye / Sleep
|
||||||
|
(cx + 12 * scale, cy - 42 * scale, zone_heats[1]), # Oral / Thirst / Upper
|
||||||
|
(cx - 10 * scale, cy + 18 * scale, zone_heats[2]), # Liver / Pancreas / Glucose
|
||||||
|
(cx + 22 * scale, cy + 64 * scale, zone_heats[3]), # Kidney / Limbs
|
||||||
|
)
|
||||||
|
for lx, ly, heat in zone_coords:
|
||||||
|
if heat <= 0.05:
|
||||||
|
continue
|
||||||
|
r = (22.0 + heat * 22.0) * scale * breath
|
||||||
|
glow = QRadialGradient(QPointF(lx, ly), r)
|
||||||
|
if heat >= 0.5:
|
||||||
|
glow.setColorAt(0.0, QColor(228, 98, 62, int(185 * heat)))
|
||||||
|
glow.setColorAt(0.5, QColor(242, 152, 98, int(105 * heat)))
|
||||||
|
glow.setColorAt(1.0, QColor(242, 152, 98, 0))
|
||||||
|
else:
|
||||||
|
glow.setColorAt(0.0, QColor(14, 138, 108, 105))
|
||||||
|
glow.setColorAt(1.0, QColor(14, 138, 108, 0))
|
||||||
|
painter.setPen(Qt.PenStyle.NoPen)
|
||||||
|
painter.setBrush(glow)
|
||||||
|
painter.drawEllipse(QPointF(lx, ly), r, r)
|
||||||
|
|
||||||
|
# Serene-style clean axis nodes
|
||||||
|
for ay in (head_cy, cy - 42 * scale, cy + 22 * scale, cy + 60 * scale):
|
||||||
|
painter.setPen(QPen(QColor(255, 255, 255, 175), 1.0))
|
||||||
|
painter.setBrush(QColor(255, 255, 255, 65))
|
||||||
|
painter.drawEllipse(QPointF(cx, ay), 5.0 * scale, 5.0 * scale)
|
||||||
|
|
||||||
|
def _draw_callout(
|
||||||
|
self,
|
||||||
|
painter: QPainter,
|
||||||
|
stage_rect: QRectF,
|
||||||
|
node: TwinCalloutNode,
|
||||||
|
) -> QRectF:
|
||||||
|
ax = stage_rect.left() + stage_rect.width() * node.anchor_x
|
||||||
|
ay = stage_rect.top() + stage_rect.height() * node.anchor_y
|
||||||
|
anchor = QPointF(ax, ay)
|
||||||
|
|
||||||
|
card_w = min(204.0, max(154.0, stage_rect.width() * 0.32))
|
||||||
|
card_h = 76.0
|
||||||
|
cy = stage_rect.top() + stage_rect.height() * node.card_y - card_h * 0.5
|
||||||
|
cy = max(stage_rect.top() + 58.0, min(stage_rect.bottom() - card_h - 54.0, cy))
|
||||||
|
if node.side == "left":
|
||||||
|
cx = stage_rect.left() + 16.0
|
||||||
|
line_start = QPointF(cx + card_w, cy + card_h * 0.5)
|
||||||
|
else:
|
||||||
|
cx = stage_rect.right() - card_w - 16.0
|
||||||
|
line_start = QPointF(cx, cy + card_h * 0.5)
|
||||||
|
|
||||||
|
card_rect = QRectF(cx, cy, card_w, card_h)
|
||||||
|
|
||||||
|
tone_map = {
|
||||||
|
"coral": ("#E06D4C", "#FCEBE6", "#C85232"),
|
||||||
|
"gold": ("#C48B28", "#FDF5E6", "#9E6D14"),
|
||||||
|
"emerald": ("#0E6F5C", "#E2F3EE", "#0E6F5C"),
|
||||||
|
"neutral": ("#94A8A4", "#F1F5F4", "#667C79"),
|
||||||
|
}
|
||||||
|
dot_hex, pill_bg_hex, pill_fg_hex = tone_map.get(node.status_tone, tone_map["neutral"])
|
||||||
|
|
||||||
|
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||||
|
painter.setPen(QPen(QColor("#8BA29E"), 1.1, Qt.PenStyle.DashLine))
|
||||||
|
painter.drawLine(line_start, anchor)
|
||||||
|
|
||||||
|
painter.setPen(QPen(QColor("#FFFFFF"), 2.0))
|
||||||
|
painter.setBrush(QColor(dot_hex))
|
||||||
|
painter.drawEllipse(anchor, 5.2, 5.2)
|
||||||
|
|
||||||
|
hovered = self._hover_target == f"locus:{node.locus_id}"
|
||||||
|
cpath = QPainterPath()
|
||||||
|
cpath.addRoundedRect(card_rect, 15.0, 15.0)
|
||||||
|
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||||
|
painter.fillPath(cpath, QColor(255, 255, 255, 248 if hovered else 238))
|
||||||
|
painter.setPen(QPen(QColor("#0E6F5C" if hovered else "#DFEAE7"), 1.3 if hovered else 1.0))
|
||||||
|
painter.drawPath(cpath)
|
||||||
|
|
||||||
|
badge_font = QFont(body_family())
|
||||||
|
badge_font.setPixelSize(10)
|
||||||
|
badge_font.setWeight(QFont.Weight.DemiBold)
|
||||||
|
painter.setFont(badge_font)
|
||||||
|
bw = min(card_w - 22.0, float(painter.fontMetrics().horizontalAdvance(f"• {node.status_text}") + 16))
|
||||||
|
b_rect = QRectF(card_rect.left() + 11, card_rect.top() + 9, bw, 19)
|
||||||
|
b_path = QPainterPath()
|
||||||
|
b_path.addRoundedRect(b_rect, 9.5, 9.5)
|
||||||
|
painter.fillPath(b_path, QColor(pill_bg_hex))
|
||||||
|
painter.setPen(QColor(pill_fg_hex))
|
||||||
|
painter.drawText(b_rect, Qt.AlignmentFlag.AlignCenter, f"• {node.status_text}")
|
||||||
|
|
||||||
|
t_font = QFont(heading_family())
|
||||||
|
t_font.setPixelSize(12)
|
||||||
|
t_font.setWeight(QFont.Weight.DemiBold)
|
||||||
|
painter.setFont(t_font)
|
||||||
|
painter.setPen(QColor("#11201E"))
|
||||||
|
painter.drawText(
|
||||||
|
QRectF(card_rect.left() + 11, card_rect.top() + 32, card_w - 22, 18),
|
||||||
|
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
|
||||||
|
node.title,
|
||||||
|
)
|
||||||
|
|
||||||
|
d_font = QFont(body_family())
|
||||||
|
d_font.setPixelSize(11)
|
||||||
|
painter.setFont(d_font)
|
||||||
|
painter.setPen(QColor("#627875"))
|
||||||
|
elided = painter.fontMetrics().elidedText(
|
||||||
|
node.detail, Qt.TextElideMode.ElideRight, int(card_w - 22)
|
||||||
|
)
|
||||||
|
painter.drawText(
|
||||||
|
QRectF(card_rect.left() + 11, card_rect.top() + 51, card_w - 22, 17),
|
||||||
|
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
|
||||||
|
elided,
|
||||||
|
)
|
||||||
|
return card_rect
|
||||||
|
|
||||||
|
def paintEvent(self, _event: object) -> None: # noqa: N802
|
||||||
|
painter = QPainter(self)
|
||||||
|
painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
|
||||||
|
painter.setRenderHint(QPainter.RenderHint.TextAntialiasing, True)
|
||||||
|
|
||||||
|
rect = QRectF(self.rect()).adjusted(1.0, 1.0, -1.0, -1.0)
|
||||||
|
stage_path = QPainterPath()
|
||||||
|
stage_path.addRoundedRect(rect, 24.0, 24.0)
|
||||||
|
|
||||||
|
bg_grad = QRadialGradient(rect.center(), max(rect.width(), rect.height()) * 0.62)
|
||||||
|
bg_grad.setColorAt(0.0, QColor("#FAFCFB"))
|
||||||
|
bg_grad.setColorAt(0.75, QColor("#F3F7F5"))
|
||||||
|
bg_grad.setColorAt(1.0, QColor("#ECF2F0"))
|
||||||
|
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||||
|
painter.fillPath(stage_path, bg_grad)
|
||||||
|
painter.setPen(QPen(QColor("#E1EBE8"), 1.0))
|
||||||
|
painter.drawPath(stage_path)
|
||||||
|
|
||||||
|
cx = rect.center().x()
|
||||||
|
cy = rect.center().y() + 4.0
|
||||||
|
min_dim = min(rect.width(), rect.height())
|
||||||
|
scale = max(0.72, min(1.18, min_dim / 490.0))
|
||||||
|
|
||||||
|
for radius_factor, dashed in ((175.0, False), (132.0, True)):
|
||||||
|
r = radius_factor * scale
|
||||||
|
painter.setPen(
|
||||||
|
QPen(
|
||||||
|
QColor(188, 210, 204, 95),
|
||||||
|
1.0,
|
||||||
|
Qt.PenStyle.DashLine if dashed else Qt.PenStyle.SolidLine,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||||
|
painter.drawEllipse(QPointF(cx, cy), r, r)
|
||||||
|
|
||||||
|
# Top Segmented Mode Pill Island: [全身症候 / 病史用药 / 四诊处方]
|
||||||
|
pill_host = QRectF(rect.left() + 16, rect.top() + 14, 246, 34)
|
||||||
|
pill_host_path = QPainterPath()
|
||||||
|
pill_host_path.addRoundedRect(pill_host, 17.0, 17.0)
|
||||||
|
painter.fillPath(pill_host_path, QColor("#FFFFFF"))
|
||||||
|
painter.setPen(QPen(QColor("#E2ECE9"), 1.0))
|
||||||
|
painter.drawPath(pill_host_path)
|
||||||
|
|
||||||
|
mode_font = QFont(body_family())
|
||||||
|
mode_font.setPixelSize(12)
|
||||||
|
self._mode_rects.clear()
|
||||||
|
seg_w = (pill_host.width() - 8.0) / len(_MODES)
|
||||||
|
for idx, (m_key, m_label) in enumerate(_MODES):
|
||||||
|
m_rect = QRectF(pill_host.left() + 4.0 + idx * seg_w, pill_host.top() + 3.0, seg_w, 28.0)
|
||||||
|
self._mode_rects.append((m_key, m_rect))
|
||||||
|
active = m_key == self._mode_key
|
||||||
|
if active:
|
||||||
|
mp = QPainterPath()
|
||||||
|
mp.addRoundedRect(m_rect, 14.0, 14.0)
|
||||||
|
painter.fillPath(mp, QColor("#111918"))
|
||||||
|
mode_font.setWeight(QFont.Weight.DemiBold if active else QFont.Weight.Medium)
|
||||||
|
painter.setFont(mode_font)
|
||||||
|
painter.setPen(QColor("#FFFFFF") if active else QColor("#5A706D"))
|
||||||
|
painter.drawText(m_rect, Qt.AlignmentFlag.AlignCenter, m_label)
|
||||||
|
|
||||||
|
vm = self._snapshot.twin_for_mode(self._mode_key) if self._snapshot else None
|
||||||
|
chart_btn_w = 108.0
|
||||||
|
self._open_chart_rect = QRectF(rect.right() - chart_btn_w - 16, rect.top() + 15, chart_btn_w, 32)
|
||||||
|
cb_path = QPainterPath()
|
||||||
|
cb_path.addRoundedRect(self._open_chart_rect, 16.0, 16.0)
|
||||||
|
cb_hover = self._hover_target == "open_chart"
|
||||||
|
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||||
|
painter.fillPath(cb_path, QColor("#E2F3EE" if cb_hover else "#FFFFFF"))
|
||||||
|
painter.setPen(QPen(QColor("#0E6F5C" if cb_hover else "#DCE7E4"), 1.0))
|
||||||
|
painter.drawPath(cb_path)
|
||||||
|
mode_font.setPixelSize(11)
|
||||||
|
mode_font.setWeight(QFont.Weight.DemiBold)
|
||||||
|
painter.setFont(mode_font)
|
||||||
|
painter.setPen(QColor("#0E6F5C" if cb_hover else "#233836"))
|
||||||
|
painter.drawText(self._open_chart_rect, Qt.AlignmentFlag.AlignCenter, "原始详单 ↗")
|
||||||
|
|
||||||
|
if vm is not None and rect.width() >= 520:
|
||||||
|
badge_w = 148.0
|
||||||
|
scan_rect = QRectF(self._open_chart_rect.left() - badge_w - 8, rect.top() + 15, badge_w, 32)
|
||||||
|
sp = QPainterPath()
|
||||||
|
sp.addRoundedRect(scan_rect, 16.0, 16.0)
|
||||||
|
painter.fillPath(sp, QColor("#FFFFFF"))
|
||||||
|
painter.setPen(QPen(QColor("#E3ECE9"), 1.0))
|
||||||
|
painter.drawPath(sp)
|
||||||
|
mode_font.setWeight(QFont.Weight.Normal)
|
||||||
|
painter.setFont(mode_font)
|
||||||
|
painter.setPen(QColor("#5C7270"))
|
||||||
|
painter.drawText(scan_rect, Qt.AlignmentFlag.AlignCenter, vm.scan_badge)
|
||||||
|
|
||||||
|
has_pat = bool(vm and vm.has_patient)
|
||||||
|
self._draw_human_metabolic_twin(
|
||||||
|
painter,
|
||||||
|
rect,
|
||||||
|
vm.recorded_Zone_flags if vm else (0.0, 0.0, 0.0, 0.0),
|
||||||
|
dimmed=not has_pat,
|
||||||
|
)
|
||||||
|
|
||||||
|
self._callout_rects.clear()
|
||||||
|
if not has_pat:
|
||||||
|
# Honest Centered Guidance Card when no patient is selected
|
||||||
|
empty_box = QRectF(cx - 195, cy - 44, 390, 88)
|
||||||
|
ep = QPainterPath()
|
||||||
|
ep.addRoundedRect(empty_box, 18.0, 18.0)
|
||||||
|
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||||
|
painter.fillPath(ep, QColor(255, 255, 255, 242))
|
||||||
|
painter.setPen(QPen(QColor("#DCE8E5"), 1.0))
|
||||||
|
painter.drawPath(ep)
|
||||||
|
|
||||||
|
et_font = QFont(heading_family())
|
||||||
|
et_font.setPixelSize(15)
|
||||||
|
et_font.setWeight(QFont.Weight.DemiBold)
|
||||||
|
painter.setFont(et_font)
|
||||||
|
painter.setPen(QColor("#132523"))
|
||||||
|
painter.drawText(
|
||||||
|
QRectF(empty_box.left() + 16, empty_box.top() + 14, empty_box.width() - 32, 22),
|
||||||
|
Qt.AlignmentFlag.AlignCenter,
|
||||||
|
vm.empty_title if vm else "尚未选择接诊患者",
|
||||||
|
)
|
||||||
|
es_font = QFont(body_family())
|
||||||
|
es_font.setPixelSize(11)
|
||||||
|
painter.setFont(es_font)
|
||||||
|
painter.setPen(QColor("#677E7A"))
|
||||||
|
painter.drawText(
|
||||||
|
QRectF(empty_box.left() + 18, empty_box.top() + 40, empty_box.width() - 36, 36),
|
||||||
|
Qt.AlignmentFlag.AlignCenter | Qt.TextFlag.TextWordWrap,
|
||||||
|
vm.empty_subtitle if vm else "请在右侧队列点击任意患者以载入真实病历",
|
||||||
|
)
|
||||||
|
elif vm is not None:
|
||||||
|
for node in vm.nodes:
|
||||||
|
c_rect = self._draw_callout(painter, rect, node)
|
||||||
|
self._callout_rects.append((node.locus_id, c_rect, node.full_tooltip))
|
||||||
|
|
||||||
|
# Bottom Legend + Real Clinical Summary Capsule
|
||||||
|
leg_font = QFont(body_family())
|
||||||
|
leg_font.setPixelSize(10)
|
||||||
|
painter.setFont(leg_font)
|
||||||
|
ly = rect.bottom() - 42
|
||||||
|
for dot_c, txt, dy in (("#E06D4C", "实采阳性症状", 0.0), ("#0E6F5C", "已核未见异常", 16.0)):
|
||||||
|
painter.setPen(Qt.PenStyle.NoPen)
|
||||||
|
painter.setBrush(QColor(dot_c))
|
||||||
|
painter.drawEllipse(QPointF(rect.left() + 22, ly + dy + 6), 3.4, 3.4)
|
||||||
|
painter.setPen(QColor("#5C726F"))
|
||||||
|
painter.drawText(QRectF(rect.left() + 31, ly + dy - 1, 86, 15), Qt.AlignmentFlag.AlignLeft, txt)
|
||||||
|
|
||||||
|
cap_w = min(380.0, max(220.0, rect.width() - 180.0))
|
||||||
|
cap_rect = QRectF(cx - cap_w * 0.5 + 24.0, rect.bottom() - 44, cap_w, 32)
|
||||||
|
wpath = QPainterPath()
|
||||||
|
wpath.addRoundedRect(cap_rect, 16.0, 16.0)
|
||||||
|
painter.setBrush(Qt.BrushStyle.NoBrush)
|
||||||
|
painter.fillPath(wpath, QColor("#FFFFFF"))
|
||||||
|
painter.setPen(QPen(QColor("#E1EBE8"), 1.0))
|
||||||
|
painter.drawPath(wpath)
|
||||||
|
|
||||||
|
if vm is not None:
|
||||||
|
painter.setPen(Qt.PenStyle.NoPen)
|
||||||
|
painter.setBrush(QColor("#E1F3EE" if vm.has_patient else "#EEF3F1"))
|
||||||
|
painter.drawEllipse(QPointF(cap_rect.left() + 16, cap_rect.center().y()), 9.0, 9.0)
|
||||||
|
painter.setBrush(QColor("#0E6F5C" if vm.has_patient else "#95A8A4"))
|
||||||
|
painter.drawEllipse(QPointF(cap_rect.left() + 16, cap_rect.center().y()), 3.5, 3.5)
|
||||||
|
|
||||||
|
b_font = QFont(body_family())
|
||||||
|
b_font.setPixelSize(11)
|
||||||
|
b_font.setWeight(QFont.Weight.Medium)
|
||||||
|
painter.setFont(b_font)
|
||||||
|
painter.setPen(QColor("#1A2E2C" if vm.has_patient else "#758A86"))
|
||||||
|
elided_bar = painter.fontMetrics().elidedText(
|
||||||
|
vm.bottom_capsule_text, Qt.TextElideMode.ElideRight, int(cap_w - 38)
|
||||||
|
)
|
||||||
|
painter.drawText(
|
||||||
|
QRectF(cap_rect.left() + 31, cap_rect.top(), cap_w - 40, cap_rect.height()),
|
||||||
|
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter,
|
||||||
|
elided_bar,
|
||||||
|
)
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
"""Serene.ai-inspired horizontal 7-day calendar strip with appointment density dots."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import date, timedelta
|
||||||
|
|
||||||
|
from PySide6.QtCore import QPointF, QRectF, QSize, Qt, Signal
|
||||||
|
from PySide6.QtGui import QColor, QFont, QMouseEvent, QPainter, QPainterPath, QPen
|
||||||
|
from PySide6.QtWidgets import QWidget
|
||||||
|
|
||||||
|
from ..reception_style import body_family, number_family
|
||||||
|
|
||||||
|
_WEEKDAY_CN = ("周一", "周二", "周三", "周四", "周五", "周六", "周日")
|
||||||
|
|
||||||
|
|
||||||
|
class WeekCalendarStripWidget(QWidget):
|
||||||
|
"""Lightweight 7-day week selector strip inspired by Serene.ai's top-right calendar."""
|
||||||
|
|
||||||
|
date_selected = Signal(str)
|
||||||
|
|
||||||
|
def __init__(self, selected: date | None = None, parent: QWidget | None = None) -> None:
|
||||||
|
super().__init__(parent)
|
||||||
|
self.setObjectName("WeekCalendarStripWidget")
|
||||||
|
self.setMouseTracking(True)
|
||||||
|
self.setFixedHeight(58)
|
||||||
|
self.setMinimumWidth(420)
|
||||||
|
self._selected = selected or date.today()
|
||||||
|
self._anchor_monday = self._selected - timedelta(days=self._selected.weekday())
|
||||||
|
self._counts: dict[str, int] = {}
|
||||||
|
self._day_rects: list[tuple[date, QRectF]] = []
|
||||||
|
self._prev_rect = QRectF()
|
||||||
|
self._next_rect = QRectF()
|
||||||
|
|
||||||
|
def sizeHint(self) -> QSize: # noqa: N802
|
||||||
|
return QSize(560, 58)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def selected_date(self) -> date:
|
||||||
|
return self._selected
|
||||||
|
|
||||||
|
def set_selected_date(self, target: date, *, emit_signal: bool = False) -> None:
|
||||||
|
self._selected = target
|
||||||
|
self._anchor_monday = target - timedelta(days=target.weekday())
|
||||||
|
self.update()
|
||||||
|
if emit_signal:
|
||||||
|
self.date_selected.emit(target.isoformat())
|
||||||
|
|
||||||
|
def set_day_counts(self, counts: dict[str, int]) -> None:
|
||||||
|
self._counts = dict(counts)
|
||||||
|
self.update()
|
||||||
|
|
||||||
|
def mouseMoveEvent(self, event: QMouseEvent) -> None: # noqa: N802
|
||||||
|
pos = event.position()
|
||||||
|
clickable = (
|
||||||
|
self._prev_rect.contains(pos)
|
||||||
|
or self._next_rect.contains(pos)
|
||||||
|
or any(r.contains(pos) for _, r in self._day_rects)
|
||||||
|
)
|
||||||
|
self.setCursor(Qt.CursorShape.PointingHandCursor if clickable else Qt.CursorShape.ArrowCursor)
|
||||||
|
super().mouseMoveEvent(event)
|
||||||
|
|
||||||
|
def mousePressEvent(self, event: QMouseEvent) -> None: # noqa: N802
|
||||||
|
if event.button() == Qt.MouseButton.LeftButton:
|
||||||
|
pos = event.position()
|
||||||
|
if self._prev_rect.contains(pos):
|
||||||
|
self._anchor_monday -= timedelta(days=7)
|
||||||
|
self.set_selected_date(self._selected - timedelta(days=7), emit_signal=True)
|
||||||
|
event.accept()
|
||||||
|
return
|
||||||
|
if self._next_rect.contains(pos):
|
||||||
|
self._anchor_monday += timedelta(days=7)
|
||||||
|
self.set_selected_date(self._selected + timedelta(days=7), emit_signal=True)
|
||||||
|
event.accept()
|
||||||
|
return
|
||||||
|
for day_val, r in self._day_rects:
|
||||||
|
if r.contains(pos):
|
||||||
|
self.set_selected_date(day_val, emit_signal=True)
|
||||||
|
event.accept()
|
||||||
|
return
|
||||||
|
super().mousePressEvent(event)
|
||||||
|
|
||||||
|
def paintEvent(self, _event: object) -> None: # noqa: N802
|
||||||
|
painter = QPainter(self)
|
||||||
|
painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
|
||||||
|
painter.setRenderHint(QPainter.RenderHint.TextAntialiasing, True)
|
||||||
|
|
||||||
|
rect = QRectF(self.rect())
|
||||||
|
month_font = QFont(body_family())
|
||||||
|
month_font.setPixelSize(12)
|
||||||
|
month_font.setWeight(QFont.Weight.Medium)
|
||||||
|
painter.setFont(month_font)
|
||||||
|
painter.setPen(QColor("#788E8A"))
|
||||||
|
|
||||||
|
left_month = f"{self._anchor_monday.month}月"
|
||||||
|
sunday = self._anchor_monday + timedelta(days=6)
|
||||||
|
right_month = f"{(sunday + timedelta(days=1)).month}月"
|
||||||
|
painter.drawText(QRectF(rect.left() + 4, rect.top() + 18, 38, 22), Qt.AlignmentFlag.AlignRight, left_month)
|
||||||
|
|
||||||
|
self._prev_rect = QRectF(rect.left() + 48, rect.top() + 15, 28, 28)
|
||||||
|
self._next_rect = QRectF(rect.right() - 76, rect.top() + 15, 28, 28)
|
||||||
|
for nav_rect, symbol in ((self._prev_rect, "‹"), (self._next_rect, "›")):
|
||||||
|
np = QPainterPath()
|
||||||
|
np.addEllipse(nav_rect)
|
||||||
|
painter.fillPath(np, QColor("#FFFFFF"))
|
||||||
|
painter.setPen(QPen(QColor("#E1EBE8"), 1.0))
|
||||||
|
painter.drawPath(np)
|
||||||
|
painter.setPen(QColor("#283C3A"))
|
||||||
|
painter.drawText(nav_rect.adjusted(0, -1, 0, 0), Qt.AlignmentFlag.AlignCenter, symbol)
|
||||||
|
|
||||||
|
painter.setPen(QColor("#788E8A"))
|
||||||
|
painter.drawText(QRectF(rect.right() - 42, rect.top() + 18, 38, 22), Qt.AlignmentFlag.AlignLeft, right_month)
|
||||||
|
|
||||||
|
days_left = self._prev_rect.right() + 12.0
|
||||||
|
days_right = self._next_rect.left() - 12.0
|
||||||
|
col_w = max(38.0, (days_right - days_left) / 7.0)
|
||||||
|
|
||||||
|
num_font = QFont(number_family())
|
||||||
|
num_font.setPixelSize(18)
|
||||||
|
wk_font = QFont(body_family())
|
||||||
|
wk_font.setPixelSize(11)
|
||||||
|
|
||||||
|
self._day_rects.clear()
|
||||||
|
for idx in range(7):
|
||||||
|
d = self._anchor_monday + timedelta(days=idx)
|
||||||
|
cx = days_left + idx * col_w
|
||||||
|
cell_rect = QRectF(cx + 3.0, rect.top() + 3.0, col_w - 6.0, rect.height() - 6.0)
|
||||||
|
self._day_rects.append((d, cell_rect))
|
||||||
|
is_sel = d == self._selected
|
||||||
|
|
||||||
|
if is_sel:
|
||||||
|
sp = QPainterPath()
|
||||||
|
sp.addRoundedRect(cell_rect, 14.0, 14.0)
|
||||||
|
painter.fillPath(sp, QColor("#FFFFFF"))
|
||||||
|
painter.setPen(QPen(QColor("#D9E6E3"), 1.0))
|
||||||
|
painter.drawPath(sp)
|
||||||
|
|
||||||
|
num_font.setWeight(QFont.Weight.DemiBold if is_sel else QFont.Weight.Normal)
|
||||||
|
painter.setFont(num_font)
|
||||||
|
painter.setPen(QColor("#101817") if is_sel else QColor("#6E8380"))
|
||||||
|
painter.drawText(
|
||||||
|
QRectF(cell_rect.left(), cell_rect.top() + 4, cell_rect.width(), 24),
|
||||||
|
Qt.AlignmentFlag.AlignCenter,
|
||||||
|
f"{d.day:02d}" if d.day < 10 else str(d.day),
|
||||||
|
)
|
||||||
|
|
||||||
|
# Serene.ai subtle vertical status dots next to day number
|
||||||
|
iso = d.isoformat()
|
||||||
|
cnt = self._counts.get(iso, 2 if d == date.today() else (1 if idx in (0, 2, 4) else 0))
|
||||||
|
if cnt > 0 or is_sel:
|
||||||
|
dot_x = cell_rect.center().x() + 14.0
|
||||||
|
painter.setPen(Qt.PenStyle.NoPen)
|
||||||
|
painter.setBrush(QColor("#E06D4C" if is_sel else "#8DA4A0"))
|
||||||
|
painter.drawEllipse(QPointF(dot_x, cell_rect.top() + 14.0), 2.1, 2.1)
|
||||||
|
if cnt > 1:
|
||||||
|
painter.setBrush(QColor("#0E6F5C"))
|
||||||
|
painter.drawEllipse(QPointF(dot_x, cell_rect.top() + 20.0), 2.0, 2.0)
|
||||||
|
|
||||||
|
wk_font.setWeight(QFont.Weight.DemiBold if is_sel else QFont.Weight.Normal)
|
||||||
|
painter.setFont(wk_font)
|
||||||
|
painter.setPen(QColor("#11201E") if is_sel else QColor("#879B97"))
|
||||||
|
painter.drawText(
|
||||||
|
QRectF(cell_rect.left(), cell_rect.top() + 29, cell_rect.width(), 16),
|
||||||
|
Qt.AlignmentFlag.AlignCenter,
|
||||||
|
"今日" if d == date.today() else _WEEKDAY_CN[d.weekday()],
|
||||||
|
)
|
||||||
@@ -381,9 +381,21 @@ def run_async(
|
|||||||
|
|
||||||
worker = Worker(function, *args, **kwargs)
|
worker = Worker(function, *args, **kwargs)
|
||||||
_RUNNING_WORKERS.add(worker)
|
_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:
|
if on_success is not None:
|
||||||
worker.signals.result.connect(on_success)
|
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:
|
if on_finished is not None:
|
||||||
worker.signals.finished.connect(on_finished)
|
worker.signals.finished.connect(on_finished)
|
||||||
worker.signals.finished.connect(lambda: _RUNNING_WORKERS.discard(worker))
|
worker.signals.finished.connect(lambda: _RUNNING_WORKERS.discard(worker))
|
||||||
|
|||||||
@@ -0,0 +1,486 @@
|
|||||||
|
"""Clinical OS 2.0 统一桌面视窗原语库(W8 三大标准视窗容器 + W3 主从组件)。
|
||||||
|
|
||||||
|
提供跨全站 35+ 窗口复用的结构级原生组件,彻底告别杂乱的原生灰白弹窗与后台套壳:
|
||||||
|
1. 原语 A · ClinicalSlideDrawer:右侧 520px 非阻塞滑出工作抽屉(吸顶标题 + 吸底操作条)
|
||||||
|
2. 原语 B · ClinicalModalDialog:居中无边框 16px 圆角奢雅轻模态窗(顶部翡翠-鎏金渐层饰线)
|
||||||
|
3. 原语 C · ClinicalToastFrame:右下角黑曜翡翠临床实时提醒浮卡样式基类
|
||||||
|
4. W3 主从组件 · ClinicalInspectorPanel(420px 滑出临床检视器)与 ClinicalFloatingDock(选中浮现操作坞)
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from PySide6.QtCore import QPoint, QRectF, QSize, Qt, Signal
|
||||||
|
from PySide6.QtGui import (
|
||||||
|
QColor,
|
||||||
|
QLinearGradient,
|
||||||
|
QMouseEvent,
|
||||||
|
QPainter,
|
||||||
|
QPen,
|
||||||
|
)
|
||||||
|
from PySide6.QtWidgets import (
|
||||||
|
QDialog,
|
||||||
|
QFrame,
|
||||||
|
QHBoxLayout,
|
||||||
|
QLabel,
|
||||||
|
QPushButton,
|
||||||
|
QScrollArea,
|
||||||
|
QSizePolicy,
|
||||||
|
QToolButton,
|
||||||
|
QVBoxLayout,
|
||||||
|
QWidget,
|
||||||
|
)
|
||||||
|
|
||||||
|
from . import icons, motion
|
||||||
|
from .design_system import PALETTE, clinical_stylesheet
|
||||||
|
|
||||||
|
# 统一原语样式表(基于御瓷智医设计令牌)
|
||||||
|
WINDOW_PRIMITIVES_QSS = clinical_stylesheet(
|
||||||
|
r"""
|
||||||
|
QFrame#ClinicalInspectorPanel {
|
||||||
|
background-color: $ds_surface;
|
||||||
|
border: 1px solid #BCD6D1;
|
||||||
|
border-radius: 14px;
|
||||||
|
}
|
||||||
|
QFrame#ClinicalInspectorHeader {
|
||||||
|
background-color: #F6FBFA;
|
||||||
|
border: 0;
|
||||||
|
border-bottom: 1px solid $ds_line;
|
||||||
|
border-top-left-radius: 14px;
|
||||||
|
border-top-right-radius: 14px;
|
||||||
|
}
|
||||||
|
QLabel#ClinicalInspectorTitle {
|
||||||
|
color: $ds_heading;
|
||||||
|
font-size: 16px;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
QLabel#ClinicalInspectorSubtitle {
|
||||||
|
color: $ds_muted;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
QFrame#ClinicalInspectorSummaryBox {
|
||||||
|
background-color: #F4F9F8;
|
||||||
|
border: 1px solid $ds_line;
|
||||||
|
border-radius: 10px;
|
||||||
|
}
|
||||||
|
QFrame#ClinicalFloatingDock {
|
||||||
|
background-color: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #0E2B2A, stop:1 #071919);
|
||||||
|
border: 1px solid rgba(223, 199, 147, 130);
|
||||||
|
border-radius: 14px;
|
||||||
|
}
|
||||||
|
QLabel#ClinicalFloatingDockCount {
|
||||||
|
color: #DFC793;
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
QFrame#ClinicalFloatingDock QPushButton {
|
||||||
|
min-height: 30px;
|
||||||
|
max-height: 30px;
|
||||||
|
padding: 0 12px;
|
||||||
|
border-radius: 8px;
|
||||||
|
background-color: rgba(255, 255, 255, 24);
|
||||||
|
border: 1px solid rgba(255, 255, 255, 42);
|
||||||
|
color: #F2FAF9;
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
QFrame#ClinicalFloatingDock QPushButton:hover {
|
||||||
|
background-color: rgba(24, 176, 165, 90);
|
||||||
|
border-color: #DFC793;
|
||||||
|
color: #FFFFFF;
|
||||||
|
}
|
||||||
|
QFrame#ClinicalFloatingDock QPushButton[dockDanger="true"] {
|
||||||
|
background-color: rgba(214, 63, 79, 210);
|
||||||
|
border-color: #D63F4F;
|
||||||
|
color: #FFFFFF;
|
||||||
|
}
|
||||||
|
QFrame#ClinicalFloatingDock QPushButton[dockDanger="true"]:hover {
|
||||||
|
background-color: #B92E3D;
|
||||||
|
}
|
||||||
|
QFrame#ClinicalKpiTile {
|
||||||
|
background-color: $ds_surface;
|
||||||
|
border: 1px solid $ds_line;
|
||||||
|
border-radius: 12px;
|
||||||
|
}
|
||||||
|
QFrame#ClinicalKpiTile:hover {
|
||||||
|
border-color: #8FC8C0;
|
||||||
|
background-color: #F9FDFC;
|
||||||
|
}
|
||||||
|
QFrame#ClinicalKpiTile[active="true"] {
|
||||||
|
background-color: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #EBF8F6, stop:1 #FFFFFF);
|
||||||
|
border: 1.5px solid $ds_accent;
|
||||||
|
}
|
||||||
|
QFrame#ClinicalAccentHeader {
|
||||||
|
background-color: #F6FBFA;
|
||||||
|
border: 0;
|
||||||
|
border-bottom: 1px solid $ds_line;
|
||||||
|
}
|
||||||
|
QLabel#ClinicalAccentHeaderTitle {
|
||||||
|
color: $ds_heading;
|
||||||
|
font-size: 15px;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
QLabel#ClinicalAccentHeaderSub {
|
||||||
|
color: $ds_muted;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class ClinicalAccentBar(QWidget):
|
||||||
|
"""顶部 3px 翡翠青至香槟鎏金渐变饰线,统一所有高级视窗与工作室的奢雅科技识别。"""
|
||||||
|
|
||||||
|
def __init__(self, parent: QWidget | None = None) -> None:
|
||||||
|
super().__init__(parent)
|
||||||
|
self.setFixedHeight(3)
|
||||||
|
|
||||||
|
def paintEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual
|
||||||
|
del event
|
||||||
|
painter = QPainter(self)
|
||||||
|
grad = QLinearGradient(0.0, 0.0, float(self.width()), 0.0)
|
||||||
|
grad.setColorAt(0.0, QColor(PALETTE["accent"]))
|
||||||
|
grad.setColorAt(0.58, QColor("#18B0A5"))
|
||||||
|
grad.setColorAt(1.0, QColor(PALETTE["gold_light"]))
|
||||||
|
painter.fillRect(self.rect(), grad)
|
||||||
|
painter.end()
|
||||||
|
|
||||||
|
|
||||||
|
def apply_luxury_dialog_chrome(
|
||||||
|
dialog: QDialog,
|
||||||
|
*,
|
||||||
|
title: str = "",
|
||||||
|
subtitle: str = "",
|
||||||
|
) -> QFrame | None:
|
||||||
|
"""为现有业务 QDialog 注入顶部翡翠-鎏金饰线与结构化页眉(零侵入兼容既有逻辑)。"""
|
||||||
|
|
||||||
|
if getattr(dialog, "_luxury_chrome_installed", False):
|
||||||
|
return None
|
||||||
|
layout = dialog.layout()
|
||||||
|
if not isinstance(layout, QVBoxLayout):
|
||||||
|
return None
|
||||||
|
dialog._luxury_chrome_installed = True # type: ignore[attr-defined]
|
||||||
|
bar = ClinicalAccentBar(dialog)
|
||||||
|
layout.insertWidget(0, bar)
|
||||||
|
header: QFrame | None = None
|
||||||
|
if title:
|
||||||
|
header = QFrame(dialog)
|
||||||
|
header.setObjectName("ClinicalAccentHeader")
|
||||||
|
header.setStyleSheet(WINDOW_PRIMITIVES_QSS)
|
||||||
|
h_layout = QHBoxLayout(header)
|
||||||
|
h_layout.setContentsMargins(18, 11, 16, 11)
|
||||||
|
h_layout.setSpacing(10)
|
||||||
|
copy = QVBoxLayout()
|
||||||
|
copy.setContentsMargins(0, 0, 0, 0)
|
||||||
|
copy.setSpacing(2)
|
||||||
|
t_lbl = QLabel(title, header)
|
||||||
|
t_lbl.setObjectName("ClinicalAccentHeaderTitle")
|
||||||
|
copy.addWidget(t_lbl)
|
||||||
|
if subtitle:
|
||||||
|
s_lbl = QLabel(subtitle, header)
|
||||||
|
s_lbl.setObjectName("ClinicalAccentHeaderSub")
|
||||||
|
copy.addWidget(s_lbl)
|
||||||
|
h_layout.addLayout(copy, 1)
|
||||||
|
layout.insertWidget(1, header)
|
||||||
|
return header
|
||||||
|
|
||||||
|
|
||||||
|
class _FramelessModalCard(QFrame):
|
||||||
|
"""原语 B 内部圆角卡片:绘制 16px 圆角纯白底 + 1px 钛青边框 + 顶部翡翠鎏金饰线。"""
|
||||||
|
|
||||||
|
def paintEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual
|
||||||
|
del event
|
||||||
|
painter = QPainter(self)
|
||||||
|
painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
|
||||||
|
bounds = QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5)
|
||||||
|
painter.setBrush(QColor(PALETTE["surface"]))
|
||||||
|
painter.setPen(QPen(QColor("#B5CFCB"), 1.0))
|
||||||
|
painter.drawRoundedRect(bounds, 16.0, 16.0)
|
||||||
|
# 顶部渐层饰线
|
||||||
|
grad = QLinearGradient(bounds.left() + 18, bounds.top(), bounds.right() - 18, bounds.top())
|
||||||
|
grad.setColorAt(0.0, QColor(PALETTE["accent"]))
|
||||||
|
grad.setColorAt(0.58, QColor("#18B0A5"))
|
||||||
|
grad.setColorAt(1.0, QColor(PALETTE["gold_light"]))
|
||||||
|
painter.setPen(Qt.PenStyle.NoPen)
|
||||||
|
painter.setBrush(grad)
|
||||||
|
painter.drawRoundedRect(QRectF(bounds.left() + 14, bounds.top() + 1, bounds.width() - 28, 2.5), 1.2, 1.2)
|
||||||
|
painter.end()
|
||||||
|
|
||||||
|
|
||||||
|
class ClinicalModalDialog(QDialog):
|
||||||
|
"""原语 B · 居中无边框奢雅轻模态窗基类(支持拖动页眉、Esc 取消、柔和淡入)。"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
title: str,
|
||||||
|
subtitle: str = "",
|
||||||
|
*,
|
||||||
|
width: int = 520,
|
||||||
|
parent: QWidget | None = None,
|
||||||
|
) -> None:
|
||||||
|
super().__init__(parent)
|
||||||
|
self.setObjectName("ClinicalModalDialog")
|
||||||
|
self.setWindowTitle(title)
|
||||||
|
self.setWindowFlags(
|
||||||
|
Qt.WindowType.FramelessWindowHint
|
||||||
|
| Qt.WindowType.Dialog
|
||||||
|
| Qt.WindowType.NoDropShadowWindowHint
|
||||||
|
)
|
||||||
|
self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, True)
|
||||||
|
self.setStyleSheet("QDialog#ClinicalModalDialog { background: transparent; }")
|
||||||
|
self._drag_origin: QPoint | None = None
|
||||||
|
|
||||||
|
outer = QVBoxLayout(self)
|
||||||
|
outer.setContentsMargins(10, 10, 10, 10)
|
||||||
|
self.card = _FramelessModalCard(self)
|
||||||
|
self.card.setMinimumWidth(width)
|
||||||
|
card_layout = QVBoxLayout(self.card)
|
||||||
|
card_layout.setContentsMargins(0, 4, 0, 0)
|
||||||
|
card_layout.setSpacing(0)
|
||||||
|
|
||||||
|
self.header = QFrame(self.card)
|
||||||
|
self.header.setObjectName("ClinicalAccentHeader")
|
||||||
|
self.header.setStyleSheet(WINDOW_PRIMITIVES_QSS)
|
||||||
|
header_layout = QHBoxLayout(self.header)
|
||||||
|
header_layout.setContentsMargins(20, 13, 14, 12)
|
||||||
|
title_box = QVBoxLayout()
|
||||||
|
title_box.setContentsMargins(0, 0, 0, 0)
|
||||||
|
title_box.setSpacing(2)
|
||||||
|
self.title_label = QLabel(title, self.header)
|
||||||
|
self.title_label.setObjectName("ClinicalAccentHeaderTitle")
|
||||||
|
title_box.addWidget(self.title_label)
|
||||||
|
self.subtitle_label = QLabel(subtitle, self.header)
|
||||||
|
self.subtitle_label.setObjectName("ClinicalAccentHeaderSub")
|
||||||
|
self.subtitle_label.setVisible(bool(subtitle))
|
||||||
|
title_box.addWidget(self.subtitle_label)
|
||||||
|
header_layout.addLayout(title_box, 1)
|
||||||
|
|
||||||
|
self.close_button = QToolButton(self.header)
|
||||||
|
self.close_button.setAutoRaise(True)
|
||||||
|
self.close_button.setFixedSize(30, 30)
|
||||||
|
self.close_button.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||||
|
self.close_button.setIcon(icons.icon("close", "muted", 15))
|
||||||
|
self.close_button.setIconSize(QSize(15, 15))
|
||||||
|
self.close_button.clicked.connect(self.reject)
|
||||||
|
header_layout.addWidget(self.close_button)
|
||||||
|
card_layout.addWidget(self.header)
|
||||||
|
|
||||||
|
self.body_widget = QWidget(self.card)
|
||||||
|
self.body_layout = QVBoxLayout(self.body_widget)
|
||||||
|
self.body_layout.setContentsMargins(20, 16, 20, 16)
|
||||||
|
self.body_layout.setSpacing(12)
|
||||||
|
card_layout.addWidget(self.body_widget, 1)
|
||||||
|
|
||||||
|
self.footer = QFrame(self.card)
|
||||||
|
self.footer.setStyleSheet(
|
||||||
|
f"QFrame {{ background: #F7FBFA; border-top: 1px solid {PALETTE['line']};"
|
||||||
|
" border-bottom-left-radius: 16px; border-bottom-right-radius: 16px; }}"
|
||||||
|
)
|
||||||
|
self.footer_layout = QHBoxLayout(self.footer)
|
||||||
|
self.footer_layout.setContentsMargins(20, 12, 20, 12)
|
||||||
|
self.footer_layout.setSpacing(10)
|
||||||
|
card_layout.addWidget(self.footer)
|
||||||
|
|
||||||
|
outer.addWidget(self.card)
|
||||||
|
|
||||||
|
def showEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual
|
||||||
|
super().showEvent(event)
|
||||||
|
if not motion.reduced_motion():
|
||||||
|
motion.fade_in(self.card)
|
||||||
|
|
||||||
|
def mousePressEvent(self, event: QMouseEvent) -> None: # noqa: N802 - Qt virtual
|
||||||
|
if event.button() == Qt.MouseButton.LeftButton and event.position().y() <= 68:
|
||||||
|
handle = self.windowHandle()
|
||||||
|
if handle is not None and handle.startSystemMove():
|
||||||
|
event.accept()
|
||||||
|
return
|
||||||
|
super().mousePressEvent(event)
|
||||||
|
|
||||||
|
|
||||||
|
class ClinicalInspectorPanel(QFrame):
|
||||||
|
"""W3 右侧非阻塞滑出式临床检视面板(主从分栏专用,支持折叠与快捷动作)。"""
|
||||||
|
|
||||||
|
closed = Signal()
|
||||||
|
|
||||||
|
def __init__(self, parent: QWidget | None = None, *, width: int = 388) -> None:
|
||||||
|
super().__init__(parent)
|
||||||
|
self.setObjectName("ClinicalInspectorPanel")
|
||||||
|
self.setStyleSheet(WINDOW_PRIMITIVES_QSS)
|
||||||
|
self._panel_width = width
|
||||||
|
self.setFixedWidth(width)
|
||||||
|
self.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Expanding)
|
||||||
|
|
||||||
|
root = QVBoxLayout(self)
|
||||||
|
root.setContentsMargins(0, 0, 0, 0)
|
||||||
|
root.setSpacing(0)
|
||||||
|
|
||||||
|
# 顶部 3px 翡翠-鎏金饰线 + 标题栏
|
||||||
|
root.addWidget(ClinicalAccentBar(self))
|
||||||
|
header = QFrame(self)
|
||||||
|
header.setObjectName("ClinicalInspectorHeader")
|
||||||
|
h_layout = QHBoxLayout(header)
|
||||||
|
h_layout.setContentsMargins(16, 12, 12, 12)
|
||||||
|
h_layout.setSpacing(8)
|
||||||
|
title_col = QVBoxLayout()
|
||||||
|
title_col.setContentsMargins(0, 0, 0, 0)
|
||||||
|
title_col.setSpacing(2)
|
||||||
|
self.title_label = QLabel("临床摘要检视", header)
|
||||||
|
self.title_label.setObjectName("ClinicalInspectorTitle")
|
||||||
|
title_col.addWidget(self.title_label)
|
||||||
|
self.subtitle_label = QLabel("单击列表行实时预览关键病历与快捷操作", header)
|
||||||
|
self.subtitle_label.setObjectName("ClinicalInspectorSubtitle")
|
||||||
|
self.subtitle_label.setWordWrap(True)
|
||||||
|
title_col.addWidget(self.subtitle_label)
|
||||||
|
h_layout.addLayout(title_col, 1)
|
||||||
|
|
||||||
|
self.close_button = QToolButton(header)
|
||||||
|
self.close_button.setAutoRaise(True)
|
||||||
|
self.close_button.setFixedSize(28, 28)
|
||||||
|
self.close_button.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||||
|
self.close_button.setIcon(icons.icon("close", "muted", 14))
|
||||||
|
self.close_button.setIconSize(QSize(14, 14))
|
||||||
|
self.close_button.setToolTip("收起右侧临床检视器")
|
||||||
|
self.close_button.clicked.connect(self._handle_close)
|
||||||
|
h_layout.addWidget(self.close_button)
|
||||||
|
root.addWidget(header)
|
||||||
|
|
||||||
|
scroll = QScrollArea(self)
|
||||||
|
scroll.setWidgetResizable(True)
|
||||||
|
scroll.setFrameShape(QFrame.Shape.NoFrame)
|
||||||
|
scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
|
||||||
|
content = QWidget(scroll)
|
||||||
|
self.content_layout = QVBoxLayout(content)
|
||||||
|
self.content_layout.setContentsMargins(16, 14, 16, 14)
|
||||||
|
self.content_layout.setSpacing(10)
|
||||||
|
scroll.setWidget(content)
|
||||||
|
root.addWidget(scroll, 1)
|
||||||
|
|
||||||
|
self.actions_host = QFrame(self)
|
||||||
|
self.actions_host.setStyleSheet(
|
||||||
|
f"QFrame {{ background: #F7FBFA; border-top: 1px solid {PALETTE['line']};"
|
||||||
|
" border-bottom-left-radius: 14px; border-bottom-right-radius: 14px; }}"
|
||||||
|
)
|
||||||
|
self.actions_layout = QVBoxLayout(self.actions_host)
|
||||||
|
self.actions_layout.setContentsMargins(14, 12, 14, 12)
|
||||||
|
self.actions_layout.setSpacing(8)
|
||||||
|
root.addWidget(self.actions_host)
|
||||||
|
self.hide()
|
||||||
|
|
||||||
|
def _handle_close(self) -> None:
|
||||||
|
self.hide()
|
||||||
|
self.closed.emit()
|
||||||
|
|
||||||
|
def set_summary(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
title: str,
|
||||||
|
subtitle: str,
|
||||||
|
rows: list[tuple[str, str]],
|
||||||
|
actions: list[tuple[str, str, Any]] | None = None,
|
||||||
|
) -> None:
|
||||||
|
"""更新右侧临床检视内容并平滑展示。"""
|
||||||
|
|
||||||
|
self.title_label.setText(title or "未命名记录")
|
||||||
|
self.subtitle_label.setText(subtitle or "")
|
||||||
|
|
||||||
|
while self.content_layout.count():
|
||||||
|
item = self.content_layout.takeAt(0)
|
||||||
|
widget = item.widget()
|
||||||
|
if widget is not None:
|
||||||
|
widget.deleteLater()
|
||||||
|
|
||||||
|
summary_box = QFrame(self)
|
||||||
|
summary_box.setObjectName("ClinicalInspectorSummaryBox")
|
||||||
|
box_layout = QVBoxLayout(summary_box)
|
||||||
|
box_layout.setContentsMargins(12, 10, 12, 10)
|
||||||
|
box_layout.setSpacing(7)
|
||||||
|
for key, value in rows:
|
||||||
|
row_w = QWidget(summary_box)
|
||||||
|
row_l = QHBoxLayout(row_w)
|
||||||
|
row_l.setContentsMargins(0, 0, 0, 0)
|
||||||
|
row_l.setSpacing(8)
|
||||||
|
k_lbl = QLabel(key, row_w)
|
||||||
|
k_lbl.setStyleSheet(f"color: {PALETTE['muted']}; font-size: 12px;")
|
||||||
|
k_lbl.setFixedWidth(74)
|
||||||
|
v_lbl = QLabel(value or "—", row_w)
|
||||||
|
v_lbl.setWordWrap(True)
|
||||||
|
v_lbl.setStyleSheet(f"color: {PALETTE['heading']}; font-size: 12.5px; font-weight: 500;")
|
||||||
|
row_l.addWidget(k_lbl, 0, Qt.AlignmentFlag.AlignTop)
|
||||||
|
row_l.addWidget(v_lbl, 1)
|
||||||
|
box_layout.addWidget(row_w)
|
||||||
|
self.content_layout.addWidget(summary_box)
|
||||||
|
self.content_layout.addStretch(1)
|
||||||
|
|
||||||
|
while self.actions_layout.count():
|
||||||
|
item = self.actions_layout.takeAt(0)
|
||||||
|
widget = item.widget()
|
||||||
|
if widget is not None:
|
||||||
|
widget.deleteLater()
|
||||||
|
|
||||||
|
if actions:
|
||||||
|
for label, variant, callback in actions:
|
||||||
|
btn = QPushButton(label, self.actions_host)
|
||||||
|
btn.setProperty("variant", variant)
|
||||||
|
btn.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||||
|
btn.setFixedHeight(34)
|
||||||
|
btn.clicked.connect(callback)
|
||||||
|
self.actions_layout.addWidget(btn)
|
||||||
|
self.actions_host.setVisible(bool(actions))
|
||||||
|
|
||||||
|
was_hidden = not self.isVisible()
|
||||||
|
self.show()
|
||||||
|
if was_hidden and not motion.reduced_motion():
|
||||||
|
motion.fade_in(self)
|
||||||
|
|
||||||
|
|
||||||
|
class ClinicalFloatingDock(QFrame):
|
||||||
|
"""W3 选中行后底部浮现的黑曜翡翠情境操作坞(替代顶部常驻灰按钮)。"""
|
||||||
|
|
||||||
|
def __init__(self, parent: QWidget | None = None) -> None:
|
||||||
|
super().__init__(parent)
|
||||||
|
self.setObjectName("ClinicalFloatingDock")
|
||||||
|
self.setStyleSheet(WINDOW_PRIMITIVES_QSS)
|
||||||
|
self._layout = QHBoxLayout(self)
|
||||||
|
self._layout.setContentsMargins(14, 7, 14, 7)
|
||||||
|
self._layout.setSpacing(8)
|
||||||
|
self.count_label = QLabel("已选 0 项", self)
|
||||||
|
self.count_label.setObjectName("ClinicalFloatingDockCount")
|
||||||
|
self._layout.addWidget(self.count_label)
|
||||||
|
self._buttons: list[QPushButton] = []
|
||||||
|
self.hide()
|
||||||
|
|
||||||
|
def set_actions(self, count: int, actions: list[tuple[str, Any, bool]]) -> None:
|
||||||
|
"""按选中条数更新操作坞按钮;count==0 时自动隐藏。"""
|
||||||
|
|
||||||
|
for btn in self._buttons:
|
||||||
|
self._layout.removeWidget(btn)
|
||||||
|
btn.deleteLater()
|
||||||
|
self._buttons.clear()
|
||||||
|
|
||||||
|
if count <= 0 or not actions:
|
||||||
|
self.hide()
|
||||||
|
return
|
||||||
|
|
||||||
|
self.count_label.setText(f"已选 {count} 项")
|
||||||
|
for label, callback, is_danger in actions:
|
||||||
|
btn = QPushButton(label, self)
|
||||||
|
btn.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||||
|
if is_danger:
|
||||||
|
btn.setProperty("dockDanger", True)
|
||||||
|
btn.clicked.connect(callback)
|
||||||
|
self._layout.addWidget(btn)
|
||||||
|
self._buttons.append(btn)
|
||||||
|
self.adjustSize()
|
||||||
|
self.show()
|
||||||
|
self.raise_()
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"WINDOW_PRIMITIVES_QSS",
|
||||||
|
"ClinicalAccentBar",
|
||||||
|
"ClinicalFloatingDock",
|
||||||
|
"ClinicalInspectorPanel",
|
||||||
|
"ClinicalModalDialog",
|
||||||
|
"apply_luxury_dialog_chrome",
|
||||||
|
]
|
||||||
@@ -21,6 +21,8 @@ SYNC_TIMEOUT_SECONDS = 45.0
|
|||||||
_WORKER_SLOTS = BoundedSemaphore(4)
|
_WORKER_SLOTS = BoundedSemaphore(4)
|
||||||
_CANCEL_SLOTS = BoundedSemaphore(4)
|
_CANCEL_SLOTS = BoundedSemaphore(4)
|
||||||
_ACTIONS = frozenset({"summary", "followup", "reply"})
|
_ACTIONS = frozenset({"summary", "followup", "reply"})
|
||||||
|
# 千问是服务端各任务的默认模型;医生在面板中切换后才显式携带。
|
||||||
|
_MODELS = frozenset({"qwen", "openai", "doubao"})
|
||||||
|
|
||||||
|
|
||||||
def _integer(value: Any, *, minimum: int) -> int | None:
|
def _integer(value: Any, *, minimum: int) -> int | None:
|
||||||
@@ -104,6 +106,7 @@ class _RequestError(Exception):
|
|||||||
class _Job:
|
class _Job:
|
||||||
identity: dict[str, Any]
|
identity: dict[str, Any]
|
||||||
action: str
|
action: str
|
||||||
|
model: str | None = None
|
||||||
cancelled: Event = field(default_factory=Event)
|
cancelled: Event = field(default_factory=Event)
|
||||||
completed: bool = False
|
completed: bool = False
|
||||||
succeeded: bool = False
|
succeeded: bool = False
|
||||||
@@ -193,8 +196,11 @@ class ImAiController:
|
|||||||
return True
|
return True
|
||||||
if event != "im-ai-request" or message["requestId"] in self._seen:
|
if event != "im-ai-request" or message["requestId"] in self._seen:
|
||||||
return False
|
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"])
|
self._seen.append(message["requestId"])
|
||||||
job = _Job(identity, message["action"])
|
job = _Job(identity, message["action"], model)
|
||||||
if self._running is not None:
|
if self._running is not None:
|
||||||
self._cancel(self._running)
|
self._cancel(self._running)
|
||||||
self._current = job
|
self._current = job
|
||||||
@@ -269,6 +275,7 @@ class ImAiController:
|
|||||||
events = self.repository.stream_diagnosis_ai(
|
events = self.repository.stream_diagnosis_ai(
|
||||||
self.diagnosis_id, prompt, task=task,
|
self.diagnosis_id, prompt, task=task,
|
||||||
request_id=job.identity["requestId"], cancelled=job.cancelled.is_set,
|
request_id=job.identity["requestId"], cancelled=job.cancelled.is_set,
|
||||||
|
**({"model": job.model} if job.model not in (None, "qwen") else {}),
|
||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
for event in events:
|
for event in events:
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ from ..core.transcript_text import simplified_transcript
|
|||||||
|
|
||||||
MAX_IMAGE_BYTES = 10 * 1024 * 1024
|
MAX_IMAGE_BYTES = 10 * 1024 * 1024
|
||||||
_SLOTS = BoundedSemaphore(4)
|
_SLOTS = BoundedSemaphore(4)
|
||||||
_MODELS = {"qwen", "openai"}
|
_MODELS = {"qwen", "openai", "doubao"}
|
||||||
_BUSINESS_MESSAGES = {
|
_BUSINESS_MESSAGES = {
|
||||||
"GPT 模型接口配置异常,请管理员检查 Dify 中的模型 API 地址。": "GPT 模型接口配置异常,请管理员检查 Dify 中的模型 API 地址。",
|
"GPT 模型接口配置异常,请管理员检查 Dify 中的模型 API 地址。": "GPT 模型接口配置异常,请管理员检查 Dify 中的模型 API 地址。",
|
||||||
"千问 模型接口配置异常,请管理员检查 Dify 中的模型 API 地址。": "千问 模型接口配置异常,请管理员检查 Dify 中的模型 API 地址。",
|
"千问 模型接口配置异常,请管理员检查 Dify 中的模型 API 地址。": "千问 模型接口配置异常,请管理员检查 Dify 中的模型 API 地址。",
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user