From 301c04ca9056101862bfc64c0bc6dae33a7b4238 Mon Sep 17 00:00:00 2001 From: Your Name Date: Thu, 26 Nov 2026 17:17:43 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TUICallKit-Vue3/TUIKit/pages/chat/chat.vue | 146 +++++++++++--- .../doctor_workstation/services/repository.py | 13 +- .../ui/dialogs/esign_doctor.py | 20 +- .../ui/dialogs/prescription.py | 136 ++++++++++++- .../ui/dialogs/prescription_esign.py | 22 ++- app/tests/test_prescription_esign.py | 59 ++++++ app/tests/test_prescription_ui.py | 61 +++++- .../controller/tcm/PrescriptionController.php | 183 +++++++++--------- 8 files changed, 515 insertions(+), 125 deletions(-) diff --git a/TUICallKit-Vue3/TUIKit/pages/chat/chat.vue b/TUICallKit-Vue3/TUIKit/pages/chat/chat.vue index d9dfa003a..7b9074b11 100755 --- a/TUICallKit-Vue3/TUIKit/pages/chat/chat.vue +++ b/TUICallKit-Vue3/TUIKit/pages/chat/chat.vue @@ -272,10 +272,17 @@ const { proxy } = getCurrentInstance() let targetUserID = ''; let currentUserID = ''; // 当前登录用户ID let scrollTimer = null; // 滚动定时器 - /** 微信小程序:从系统后台回前台时刷新 IM/TUICall,避免无法接通视频 */ - let unsubscribeWxAppShow = null; + /** 微信小程序:从系统后台回前台时检查 IM/TUICall 链路,异常时才重建 */ + let wxAppShowHandler = null; let allowChatForegroundRelogin = false; let foregroundReloginTimer = null; + let pageUnloaded = false; + /** TUICallEngine 当前绑定的 IM 实例;与页面 chat 不一致说明引擎挂在已销毁的旧实例上 */ + let callKitBoundChat = null; + /** 串行化 TUICall 重绑 / IM 重登:并发执行时后一次 destroyed 会销毁前一次刚建好的引擎 */ + let callKitInitChain = Promise.resolve(); + let reloginTask = null; + const CALL_PAGE_ROUTE = 'TUICallKit/src/Components/TUICallKit'; /** 避免 onUnload 重复上报离开 */ let patientLeaveNotified = false; @@ -569,8 +576,44 @@ const { proxy } = getCurrentInstance() uni.setStorageSync('CallManager', userId) // TUICallKit 必须在 TIM chat 登录成功后再 init,且必须传入 tim,否则无法接收通话信令(聊天正常、视频接不到) } + function isCallIdle() { + try { + const status = TUIStore?.getData?.(StoreName.CALL, NAME.CALL_STATUS); + return status == null || status === CallStatus.IDLE; + } catch (_) { + return true; + } + } + /** + * 等 IM 进入 SDK_READY。TUICallEngine 登录时若 IM 未 ready 只等 2 秒,超时即登录失败; + * 而 TUICallKitAPI.init 不 await 登录,失败被吞掉、也不重试,之后的来电就全部收不到。 + */ + function waitForIMSdkReady(imChat, timeoutMs = 8000) { + if (!imChat) return Promise.resolve(false); + if (imChat.isReady?.()) return Promise.resolve(true); + return new Promise((resolve) => { + let timer = null; + const finish = () => { + clearTimeout(timer); + try { imChat.off(TencentCloudChat.EVENT.SDK_READY, finish); } catch (_) {} + resolve(!!imChat.isReady?.()); + }; + imChat.on(TencentCloudChat.EVENT.SDK_READY, finish); + timer = setTimeout(finish, timeoutMs); + }); + } /** 与当前页 IM 实例绑定后初始化音视频(TUICallEngine 依赖 tim 收发自定义信令) */ - async function initTUICallKitWithTim(imChat) { + function initTUICallKitWithTim(imChat, options) { + const task = callKitInitChain.catch(() => {}).then(() => doInitTUICallKitWithTim(imChat, options)); + callKitInitChain = task; + return task; + } + /** + * force:仅页面首次进入时为 true,允许清掉残留的非空闲通话状态。 + * 其它路径(回前台、发消息失败重登)遇到来电/通话中必须放弃重绑: + * 重绑第一步 handleExceptionExit 会把正在响铃的来电直接 reject 掉。 + */ + async function doInitTUICallKitWithTim(imChat, { force = false } = {}) { const app = getApp(); const sdkAppID = app.globalData.SDKAppID; const userSig = app.globalData.userSig; @@ -580,6 +623,17 @@ const { proxy } = getCurrentInstance() console.warn('initTUICallKitWithTim: 缺少 im / SDKAppID / userSig / userID'); return; } + if (!force && !isCallIdle()) { + console.warn('initTUICallKitWithTim: 通话未结束,跳过 TUICall 重绑'); + return; + } + if (!(await waitForIMSdkReady(imChat))) { + console.warn('initTUICallKitWithTim: IM 未就绪,TUICall 登录可能失败'); + } + if (!force && !isCallIdle()) { + console.warn('initTUICallKitWithTim: 等待 IM 期间来电,跳过 TUICall 重绑'); + return; + } // 非 IDLE 时 destroyed 会抛错,随后 _doInit 会因旧 engine 仍存在而直接 return,导致未绑定新 tim、接不到来电 try { await TUICallKitAPI.handleExceptionExit(); @@ -597,13 +651,20 @@ const { proxy } = getCurrentInstance() console.warn('CallManager.destroyed retry:', e2); } } + // 空闲状态下 destroyed 仍失败,说明是 destroyInstance 抛错:此时事件监听已移除,但旧引擎还挂在 + // TUICallKitAPI 上,init 看到旧引擎会直接 return —— 引擎在、监听没了,来电全部丢失。丢弃旧引擎重建。 + if (isCallIdle() && TUICallKitAPI.getTUICallEngineInstance()) { + console.warn('initTUICallKitWithTim: 旧引擎销毁失败,强制丢弃后重建'); + TUICallKitAPI._tuiCallEngine = null; + } await uni.CallManager.init({ sdkAppID: Number(sdkAppID), userID, userSig, - globalCallPagePath: 'TUICallKit/src/Components/TUICallKit', + globalCallPagePath: CALL_PAGE_ROUTE, tim: imChat }); + callKitBoundChat = imChat; } onLoad(async (options) => { try { @@ -717,8 +778,8 @@ const { proxy } = getCurrentInstance() chat.on(TencentCloudChat.EVENT.MESSAGE_RECEIVED, onMessageReceived); } - await initTUICallKitWithTim(chat); - + await initTUICallKitWithTim(chat, { force: true }); + await loadHistoryMessages(); // 打开会话时通知医生(IM自定义消息 + 后端全局事件) @@ -737,18 +798,20 @@ const { proxy } = getCurrentInstance() //uni.showToast({ title: '聊天已就绪', icon: 'success' }); // #ifdef MP-WEIXIN - // 系统级前后台切换时页面 onShow 不一定等价于「回前台」,用 wx.onAppShow 刷新音视频信令链路 + // 系统级前后台切换时页面 onShow 不一定等价于「回前台」,用 wx.onAppShow 检查音视频信令链路 + // 注意 wx.onAppShow 不返回取消函数,必须保存回调引用,卸载时用 wx.offAppShow 移除 if (typeof wx !== 'undefined' && wx.onAppShow) { - unsubscribeWxAppShow = wx.onAppShow(() => { + wxAppShowHandler = () => { if (!allowChatForegroundRelogin) return; const pages = getCurrentPages(); const top = pages[pages.length - 1]; if (!(top?.route || '').includes('pages/chat/chat')) return; reloginAfterMiniProgramForeground(); - }); + }; + wx.onAppShow(wxAppShowHandler); } setTimeout(() => { - allowChatForegroundRelogin = true; + if (!pageUnloaded) allowChatForegroundRelogin = true; }, 800); // #endif @@ -793,11 +856,12 @@ const { proxy } = getCurrentInstance() void notifyDoctorOnChatClose(); } allowChatForegroundRelogin = false; + pageUnloaded = true; // #ifdef MP-WEIXIN - if (typeof unsubscribeWxAppShow === 'function') { - unsubscribeWxAppShow(); - unsubscribeWxAppShow = null; + if (wxAppShowHandler && typeof wx !== 'undefined' && wx.offAppShow) { + wx.offAppShow(wxAppShowHandler); } + wxAppShowHandler = null; // #endif if (foregroundReloginTimer) { clearTimeout(foregroundReloginTimer); @@ -1071,8 +1135,16 @@ const { proxy } = getCurrentInstance() return m ? parseInt(m[1], 10) : null; } - /** 拉取最新 userSig 并重新登录 IM,必要时重建 chat 实例(与 onLoad 逻辑一致) */ - async function reloginIMChat() { + /** 拉取最新 userSig 并重新登录 IM,必要时重建 chat 实例(与 onLoad 逻辑一致);并发调用合并为一次 */ + function reloginIMChat() { + if (!reloginTask) { + reloginTask = doReloginIMChat().finally(() => { + reloginTask = null; + }); + } + return reloginTask; + } + async function doReloginIMChat() { const app = getApp(); await video(currentUserID); const userSig = app.globalData.userSig; @@ -1084,6 +1156,10 @@ const { proxy } = getCurrentInstance() if (!chat) { throw new Error('IM 未初始化'); } + // 拉 userSig 期间可能来电:此时登出 IM 会让来电信令中断,必须放弃 + if (!isCallIdle()) { + throw new Error('通话进行中,暂不重登 IM'); + } try { chat.off(TencentCloudChat.EVENT.MESSAGE_RECEIVED, onMessageReceived); } catch (_) {} @@ -1122,25 +1198,51 @@ const { proxy } = getCurrentInstance() await initTUICallKitWithTim(chat); } - /** 小程序切后台再回前台:拉取新 UserSig 并重登 IM、重绑 TUICallEngine(与发消息失败时的 relogin 一致) */ - async function reloginAfterMiniProgramForeground() { + /** + * 小程序切后台再回前台:IM SDK 会自行重连并补收后台期间的来电信令。 + * 以前这里无条件「登出 IM → 重登 → 销毁并重建 TUICallEngine」,重建窗口内(拉 userSig + IM 重登 + 引擎登录, + * 弱网下数秒)医生的呼叫会丢失,刚补收到的来电也会被重绑流程 reject;所以现在只在链路确实坏了时才重建。 + */ + function reloginAfterMiniProgramForeground() { if (!chat || !currentUserID) return; if (foregroundReloginTimer) clearTimeout(foregroundReloginTimer); foregroundReloginTimer = setTimeout(async () => { foregroundReloginTimer = null; - // reloginIMChat 会先 IM logout 再 initTUICallKit;若非 IDLE,destroyed 会失败且 IM 已断开,故仅 IDLE 时刷新 try { - const status = TUIStore?.getData?.(StoreName.CALL, NAME.CALL_STATUS); - if (status != null && status !== CallStatus.IDLE) { - console.warn('前台恢复: 通话未结束,跳过 IM/TUICall 重绑'); + if (!isCallIdle()) { + // 来电信令在后台到达时,跳转通话页的 navigateTo 可能失败,回前台后补跳,否则患者看不到来电 + ensureCallPageVisible(); return; } - await reloginIMChat(); + const imReady = await waitForIMSdkReady(chat, 5000); + if (pageUnloaded || !isCallIdle()) return; + const imOk = imReady && chat.getLoginUser?.() === currentUserID; + const callKitOk = !!TUICallKitAPI.getTUICallEngineInstance() && callKitBoundChat === chat; + if (imOk && callKitOk) return; + console.warn('前台恢复: IM/TUICall 链路异常,重建', { imOk, callKitOk }); + if (imOk) { + await initTUICallKitWithTim(chat); + } else { + await reloginIMChat(); + } } catch (e) { console.warn('前台恢复后 IM/TUICall 刷新失败:', e); } }, 400); } + + function ensureCallPageVisible() { + // 等 CallManager 自己的 navigateTo 走完再判断,避免叠出两个通话页(其中一个卸载时会把来电 reject 掉) + setTimeout(() => { + if (pageUnloaded || isCallIdle()) return; + const pages = getCurrentPages(); + if (pages.some((p) => (p?.route || '').includes(CALL_PAGE_ROUTE))) return; + uni.navigateTo({ + url: `/${CALL_PAGE_ROUTE}`, + fail: (e) => console.warn('补跳通话页失败:', e) + }); + }, 1000); + } async function sendTextMessage() { if (!inputText.value.trim()) return; diff --git a/app/src/doctor_workstation/services/repository.py b/app/src/doctor_workstation/services/repository.py index f9ddd9907..ca70a50c2 100755 --- a/app/src/doctor_workstation/services/repository.py +++ b/app/src/doctor_workstation/services/repository.py @@ -1861,7 +1861,7 @@ class RemoteDoctorRepository: payload = {"mobile": esign_doctor_mobile(mobile)} if mobile else {} return esign_doctor_status(self._post_esign_proof( - "esignDoctorStart", payload, "医生人脸认证启动状态待确认", + "esignDoctorStart", payload, "医生人脸认证启动状态待确认", forward_rejection=True, )) def complete_esign_doctor(self, identity_number: str = "") -> dict[str, Any]: @@ -1869,7 +1869,7 @@ class RemoteDoctorRepository: payload = {"identity_number": certificate_identity_number(identity_number)} if identity_number else {} return esign_doctor_status(self._post_esign_proof( - "esignDoctorComplete", payload, "医生签署证书绑定状态待确认", + "esignDoctorComplete", payload, "医生签署证书绑定状态待确认", forward_rejection=True, )) def start_prescription_esign(self, prescription_id: int, *, restart_identity: bool = False) -> dict[str, Any]: @@ -1890,11 +1890,18 @@ class RemoteDoctorRepository: raise ApiProtocolError("短信验证码校验结果格式不正确") return result - def _post_esign_proof(self, action: str, payload: dict[str, Any], failure: str) -> Any: + def _post_esign_proof( + self, action: str, payload: dict[str, Any], failure: str, *, forward_rejection: bool = False, + ) -> Any: try: return _client_request(self.client, "post", f"tcm.prescription/{action}", payload, timeout=60.0) except AuthenticationExpiredError: error: ApiError = AuthenticationExpiredError("登录状态已失效,请重新登录。") + except ApiBusinessError as rejected: + # 医师认证的拒绝原因由服务端白名单生成;仍拦截任何形似手机号或证件号的长数字。 + reason = str(rejected.message or "").strip()[:240] + usable = forward_rejection and reason and not re.search(r"[0-9]{11,}", reason) + error = ApiBusinessError(reason if usable else failure) except ApiError: error = ApiBusinessError(failure) finally: diff --git a/app/src/doctor_workstation/ui/dialogs/esign_doctor.py b/app/src/doctor_workstation/ui/dialogs/esign_doctor.py index c42eeca9f..b39898206 100644 --- a/app/src/doctor_workstation/ui/dialogs/esign_doctor.py +++ b/app/src/doctor_workstation/ui/dialogs/esign_doctor.py @@ -18,6 +18,7 @@ from PySide6.QtWidgets import ( ) from shiboken6 import isValid +from ...core.errors import ApiBusinessError, AuthenticationExpiredError from ...core.esign import certificate_identity_number, esign_doctor_mobile, esign_doctor_status from ..design_system import clinical_stylesheet from ..widgets import MessageBanner, run_async @@ -208,24 +209,33 @@ class EsignDoctorDialog(QDialog): 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 current(): - self._stop_view() + def failed(error: Exception) -> None: + if not current(): + return + self._stop_view() + if method == "get_esign_doctor_status": self.state = {} self.banner.show_message("医生签署身份状态待确认,请检查认证状态后继续。", "warning") - self._sync_actions() + 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): @@ -233,7 +243,7 @@ class EsignDoctorDialog(QDialog): if self._closed: return self._sync_actions() - if (current() and method == "start_esign_doctor" and self.isVisible() + if (succeeded and current() and method == "start_esign_doctor" and self.isVisible() and self.state.get("auth_url")): self._open_authentication() diff --git a/app/src/doctor_workstation/ui/dialogs/prescription.py b/app/src/doctor_workstation/ui/dialogs/prescription.py index bbfa9837a..25de07dc6 100755 --- a/app/src/doctor_workstation/ui/dialogs/prescription.py +++ b/app/src/doctor_workstation/ui/dialogs/prescription.py @@ -5555,6 +5555,9 @@ class _PrescriptionPaperPreview(QTextBrowser): ) -> None: super().__init__(parent) self._watermark_text = "处方联" if str(variant).strip().lower() == "user" else "药房联" + self.update_watermark(prescription) + + def update_watermark(self, prescription: Any) -> None: herbs = _herb_rows(prescription) main_count = sum(1 for row in herbs if _formula(row.get("formula_type")) == "主方") aux_count = len(herbs) - main_count @@ -5563,6 +5566,7 @@ class _PrescriptionPaperPreview(QTextBrowser): rp_height = 65 + medicine_rows * 30 + section_count * 22 # Title + stacked notice sit above Rp; keep the watermark in the herb block. self._watermark_document_y = 280 + rp_height // 2 + self.viewport().update() def paintEvent(self, event: Any) -> None: # noqa: N802 - Qt override super().paintEvent(event) @@ -5588,13 +5592,31 @@ class _PrescriptionPaperPreview(QTextBrowser): painter.end() +_PRESCRIPTION_EDIT_PERMISSIONS = ("cf.prescription/edit", "tcm.prescription/edit") + + +def _inherited_attribute(widget: QWidget | None, name: str) -> Any: + """Read page context (permissions / current user) from the nearest ancestor.""" + + while widget is not None: + value = getattr(widget, name, None) + if value is not None: + return value + widget = widget.parentWidget() + return None + + class PrescriptionSigningPreview(QWidget): - """Read-only clinical prescription available alongside the signing workflow.""" + """处方联 preview beside the signing workflow; editable until signing starts.""" + + prescription_saved = Signal(object) + edit_failed = Signal(str) def __init__(self, repository: Any, prescription: Any, *, parent: QWidget | None = None) -> None: super().__init__(parent) self.setObjectName("PrescriptionSigningPreview") self.setAccessibleName("处方预览") + self._repository = repository self._prescription_id = _int(str(first_value(prescription, "id", "prescription_id"))) has_full_seed = self._has_clinical_content(prescription) or ( _bool(first_value(prescription, "is_system_auto")) and self._has_empty_slip(prescription) @@ -5604,14 +5626,26 @@ class PrescriptionSigningPreview(QWidget): self._load_generation = 0 self._esign = signature_state(prescription) self._has_live_esign_state = False + self._edit_allowed = False + self._edit_saving = False self.paper: _PrescriptionPaperPreview | None = None self._layout = QVBoxLayout(self) self._layout.setContentsMargins(0, 0, 0, 0) self._layout.setSpacing(10) + header = QHBoxLayout() + header.setContentsMargins(0, 0, 0, 0) heading = QLabel("处方预览", self) heading.setObjectName("PrescriptionSigningHeading") - self._layout.addWidget(heading) + header.addWidget(heading) + header.addStretch(1) + self.edit_button = QPushButton("编辑处方", self) + self.edit_button.setAutoDefault(False) + self.edit_button.setToolTip("签署开始前可修改处方内容,保存后需重新上传处方") + self.edit_button.clicked.connect(self.edit_prescription) + self.edit_button.hide() + header.addWidget(self.edit_button) + self._layout.addLayout(header) self._notice = QWidget(self) notice_layout = QVBoxLayout(self._notice) notice_layout.setContentsMargins(4, 4, 4, 4) @@ -5649,6 +5683,7 @@ class PrescriptionSigningPreview(QWidget): self.status_label.setText(message) self.retry_button.setVisible(retry) self._notice.show() + self._sync_edit_button() def _load_or_render(self) -> None: if self._prescription is not None: @@ -5709,14 +5744,15 @@ class PrescriptionSigningPreview(QWidget): and self._signature_appearance(previous) != self._signature_appearance(self._esign) ): self._render() + self._sync_edit_button() def _render(self) -> None: if self._prescription is None: return try: - content = render_prescription_html(self._prescription | {"esign": self._esign}, variant="internal") + content = render_prescription_html(self._prescription | {"esign": self._esign}, variant="user") if self.paper is None: - self.paper = _PrescriptionPaperPreview(self._prescription, self, variant="internal") + self.paper = _PrescriptionPaperPreview(self._prescription, self, variant="user") self.paper.setObjectName("PrescriptionSigningPaper") self.paper.setOpenLinks(False) self.paper.setOpenExternalLinks(False) @@ -5726,6 +5762,8 @@ class PrescriptionSigningPreview(QWidget): "border: 1px solid #E4E4E5; padding: 0; }" ) self._layout.addWidget(self.paper, 1) + else: + self.paper.update_watermark(self._prescription) vertical_scroll = self.paper.verticalScrollBar() scroll_position = vertical_scroll.value() self.paper.setHtml(content) @@ -5735,6 +5773,90 @@ class PrescriptionSigningPreview(QWidget): return self._notice.hide() self.paper.show() + self._sync_edit_button() + + def prescription_data(self) -> dict[str, Any] | None: + return None if self._prescription is None else dict(self._prescription) + + def set_edit_allowed(self, allowed: bool) -> None: + """The signing dialog allows edits only while no request or identity flow is running.""" + + self._edit_allowed = bool(allowed) + self._sync_edit_button() + + def _content_editable(self) -> bool: + prescription = self._prescription + if prescription is None or self._prescription_id <= 0: + return False + approved = _int(first_value(prescription, "audit_status")) == 1 and not prescription_is_voided(prescription) + return ( + not approved + and callable(getattr(self._repository, "update_prescription", None)) + and has_permission(_inherited_attribute(self, "permissions"), _PRESCRIPTION_EDIT_PERMISSIONS) + and not prescription_edit_is_locked(prescription | {"esign": self._esign}) + ) + + def _sync_edit_button(self) -> None: + editable = self._content_editable() + self.edit_button.setVisible(editable) + self.edit_button.setEnabled(editable and self._edit_allowed and not self._edit_saving) + self.edit_button.setText("正在保存处方…" if self._edit_saving else "编辑处方") + + def edit_prescription(self) -> None: + if not self.edit_button.isEnabled() or self._prescription is None: + return + repository, prescription_id = self._repository, self._prescription_id + dialog = PrescriptionEditorDialog( + repository, + self._prescription | {"esign": self._esign}, + mode="edit", + current_user=_inherited_attribute(self, "current_user"), + permissions=_inherited_attribute(self, "permissions"), + save_draft=lambda payload: repository.update_prescription(prescription_id, changes=payload), + parent=self, + ) + accepted = dialog.exec() == QDialog.DialogCode.Accepted + saved, payload = dialog.saved_draft, dialog.payload() + dialog.deleteLater() + if not accepted or not isValid(self): + return + if saved is not None: + self._edit_saved(saved) + return + # Without e-sign the editor only validates; persist the payload here. + self._edit_saving = True + self._sync_edit_button() + + def succeeded(result: Any) -> None: + if isValid(self): + self._edit_saved(result) + + def failed(error: Exception) -> None: + if isValid(self): + self.edit_failed.emit(f"处方保存失败。{friendly_error(error)}") + + def finished() -> None: + if isValid(self): + self._edit_saving = False + self._sync_edit_button() + + run_async( + lambda: repository.update_prescription(prescription_id, changes=payload), + on_success=succeeded, + on_error=failed, + on_finished=finished, + ) + + def _edit_saved(self, result: Any) -> None: + merged = (self._prescription or {}) | _mapping(result) + if callable(self._get_detail): + # The edit response echoes the request; reload the authoritative slip. + self._prescription = None + self._load_or_render() + else: + self._prescription = merged + self._render() + self.prescription_saved.emit(merged) class PrescriptionDetailDialog(QDialog): @@ -5995,6 +6117,12 @@ class PrescriptionDetailDialog(QDialog): dialog = PrescriptionEsignDialog(self.repository, draft, parent=self) dialog.status_changed.connect(self._esign_loaded) dialog.exec() + edited = dialog.prescription_preview.prescription_data() if dialog.prescription_edited else None + if edited is not None: + self.prescription = _mapping(self.prescription) | edited + self.preview.update_watermark(self.prescription) + self.user_preview.update_watermark(self.prescription) + self._render_slip_previews() self.refresh_esign() def _current_variant(self) -> str: diff --git a/app/src/doctor_workstation/ui/dialogs/prescription_esign.py b/app/src/doctor_workstation/ui/dialogs/prescription_esign.py index c1df7770e..f9e72dcf0 100644 --- a/app/src/doctor_workstation/ui/dialogs/prescription_esign.py +++ b/app/src/doctor_workstation/ui/dialogs/prescription_esign.py @@ -48,7 +48,7 @@ from ...core.esign import ( signed_pdf_bytes, ) from ..design_system import clinical_stylesheet -from ..widgets import MessageBanner, first_value, friendly_error, has_permission, run_async +from ..widgets import MessageBanner, first_value, friendly_error, has_permission, run_async, show_toast from .esign_doctor import EsignDoctorDialog from .esign_webview import create_identity_view @@ -316,6 +316,7 @@ class PrescriptionEsignDialog(QDialog): for key in ("review_submitted_at", "awaiting_upload", "can_submit_for_review") } self.state: dict[str, Any] = {} + self.prescription_edited = False self._saved_original: Path | None = None self._busy = False self._confirmed = False @@ -363,6 +364,8 @@ class PrescriptionEsignDialog(QDialog): self.prescription_preview = PrescriptionSigningPreview(self.repository, prescription, parent=self.workspace_splitter) self.prescription_preview.setMinimumWidth(370) self.status_changed.connect(self.prescription_preview.set_esign_state) + self.prescription_preview.prescription_saved.connect(self._prescription_edited) + self.prescription_preview.edit_failed.connect(lambda message: self.banner.show_message(message, "danger")) self.workspace_splitter.addWidget(self.prescription_preview) self.workflow_panel = QFrame(self.workspace_splitter) @@ -595,6 +598,11 @@ class PrescriptionEsignDialog(QDialog): self.sms_code_input.setEnabled(available and sms_input) self.steps.setVisible(self._confirmed and (not legacy or awaiting_upload) and not incomplete) self.signing_log_button.setEnabled(self._confirmed and available) + # Content edits are only safe while no identity/signing request is in flight. + self.prescription_preview.set_edit_allowed( + available and self._confirmed and not self._intent + and not self._identity_ready and not self._completion_sent + ) time_text = signature_time_text(self.state) if self._confirmed else "" self.signature_time_label.setText(time_text) self.signature_time_label.setVisible(bool(time_text)) @@ -975,6 +983,18 @@ class PrescriptionEsignDialog(QDialog): if self.upload_button.isEnabled() and self.isVisible(): self._request("submit_prescription_for_review") + def _prescription_edited(self, result: Any) -> None: + if self._closed: + return + self.prescription_edited = True + # The server resets upload/review state on edit; read it back before any next step. + self._submission.update({ + key: value for key in self._submission if (value := first_value(result, key)) is not None + }) + show_toast(self, "处方已保存。", "success", 3600) + self.banner.show_message("处方已保存,正在刷新签署状态…", "success") + self.refresh() + def _check_retained_identity(self) -> None: if (not self._check_identity_on_open or self._busy or not self.isVisible() or self._closed or not self._confirmed): diff --git a/app/tests/test_prescription_esign.py b/app/tests/test_prescription_esign.py index 09bf4da9c..a5dc35cdb 100644 --- a/app/tests/test_prescription_esign.py +++ b/app/tests/test_prescription_esign.py @@ -318,6 +318,65 @@ def test_doctor_enrollment_binds_explicitly_after_provider_confirmation( dialog.close() +def test_doctor_enrollment_rejection_reason_is_forwarded_without_identifiers() -> None: + reasons = iter([ + "e签宝 startDoctorIdentity 失败(PROVIDER_30500121):开方医生姓名未通过核身校验", + "手机号 13800138000 未通过校验", + ]) + + def post(endpoint: str, payload: dict[str, Any], **_kwargs: Any) -> dict[str, Any]: + raise ApiBusinessError(next(reasons), data=payload) + + repository = RemoteDoctorRepository(SimpleNamespace(get=None, post=post)) + with pytest.raises(ApiBusinessError, match="开方医生姓名未通过核身校验") as raised: + repository.start_esign_doctor("13800138000") + assert raised.value.data is None and raised.value.__context__ is None + with pytest.raises(ApiBusinessError, match="^医生人脸认证启动状态待确认$"): + repository.start_esign_doctor("13800138000") + + +def test_doctor_enrollment_start_failure_keeps_mobile_form(immediate: None) -> None: + attempts: list[str] = [] + result: dict[str, Any] = {"enabled": True, "status": "unbound"} + + def start(mobile: str) -> dict[str, Any]: + attempts.append(mobile) + if len(attempts) == 1: + raise ApiBusinessError("开方医生姓名未通过核身校验") + return {**result, "status": "authenticating", "auth_url": "https://smlt.esign.cn/doctor"} + + repository = SimpleNamespace(get_esign_doctor_status=lambda: result, start_esign_doctor=start) + dialog = doctor_module.EsignDoctorDialog(repository) + dialog.show() + dialog.mobile_input.setText("13800138000") + dialog.start_button.click() + assert "开方医生姓名未通过核身校验" in dialog.banner.label.text() + assert dialog.identity_view is None and dialog.mobile_form.isVisible() + assert dialog.mobile_input.text() == "" and dialog.start_button.isEnabled() + dialog.mobile_input.setText("13800138000") + dialog.start_button.click() + assert attempts == ["13800138000", "13800138000"] + assert dialog.identity_view.urls == ["https://smlt.esign.cn/doctor"] + dialog.close() + + +def test_doctor_retry_mobile_failure_does_not_reopen_previous_flow(immediate: None) -> None: + result = {"enabled": True, "status": "authenticating", "auth_url": "https://smlt.esign.cn/old"} + + def start(_mobile: str) -> dict[str, Any]: + raise ApiBusinessError("医师认证暂不可用,请稍后重试") + + repository = SimpleNamespace(get_esign_doctor_status=lambda: result, start_esign_doctor=start) + dialog = doctor_module.EsignDoctorDialog(repository) + dialog.show() + dialog.change_mobile_button.click() + dialog.mobile_input.setText("13800138000") + dialog.start_button.click() + assert dialog.identity_view is None and dialog.mobile_form.isVisible() + assert "暂不可用" in dialog.banner.label.text() + dialog.close() + + def test_enrolled_doctor_authorizes_quicksign_without_reentering_identity(immediate: None) -> None: calls: list[str] = [] result = {"enabled": True, "status": "ready", "cert_expires_at": 2_000_000_000, diff --git a/app/tests/test_prescription_ui.py b/app/tests/test_prescription_ui.py index a034b1d07..67c2dbcb1 100755 --- a/app/tests/test_prescription_ui.py +++ b/app/tests/test_prescription_ui.py @@ -758,9 +758,11 @@ def test_signing_preview_uses_full_seed_and_updates_visible_signatures( }) preview = PrescriptionSigningPreview(SimpleNamespace(get_prescription=unexpected_detail), prescription) assert preview.paper is not None and preview.paper.isReadOnly() + assert preview.paper._watermark_text == "处方联" document = preview.paper.document() - for text in ("虚构患者", "测试诊断", "白术 (6克)", "18克", "一次20ml"): + for text in ("虚构患者", "测试诊断", "白术", "6克", "天数"): assert text in document.toPlainText() + assert "药房联" not in document.toPlainText() and "18克" not in document.toPlainText() revision = document.revision() preview.set_esign_state({"status": "pending", "message": "等待核验"}) @@ -772,7 +774,7 @@ def test_signing_preview_uses_full_seed_and_updates_visible_signatures( "review_signature_time": 1795000017, } preview.set_esign_state(signed) - for text in ("签名医生", "审核药师姓名", "白术 (6克)"): + for text in ("签名医生", "审核药师姓名", "白术"): assert text in document.toPlainText() revision = document.revision() preview.set_esign_state(signed | {"review_signature_time": 1795000020}) @@ -807,7 +809,60 @@ def test_signing_preview_retries_wrong_detail_and_ignores_stale_response( requests[1][1](seed | {"patient_name": "当前患者", "herbs": herbs}) assert preview.paper is not None text = preview.paper.toPlainText() - assert "当前患者" in text and "甘草 (3克)" in text and "签名医生" in text + assert "当前患者" in text and "甘草\n3克" in text and "签名医生" in text + + +def test_signing_preview_edits_prescription_until_signing_starts( + application: QApplication, + immediate_async: None, + monkeypatch: pytest.MonkeyPatch, +) -> None: + herbs = [{"name": "白术", "dosage": 6}] + detail = {"id": 74, "patient_name": "原患者", "audit_status": 0, "herbs": herbs} + updates: list[tuple[int, dict[str, Any]]] = [] + editors: list[dict[str, Any]] = [] + + def update(prescription_id: int, *, changes: dict[str, Any]) -> dict[str, Any]: + updates.append((prescription_id, changes)) + detail["patient_name"] = changes["patient_name"] + return {"id": prescription_id, **changes} + + class FakeEditor: + def __init__(self, _repository: Any, prescription: Any, *, mode: str, save_draft: Any, **_kwargs: Any) -> None: + assert mode == "edit" + editors.append(prescription) + self.save_draft = save_draft + self.saved_draft = None + + def exec(self) -> QDialog.DialogCode: + self.saved_draft = self.save_draft({"patient_name": "修改后患者"}) + return QDialog.DialogCode.Accepted + + def payload(self) -> dict[str, Any]: + return {} + + def deleteLater(self) -> None: # noqa: N802 - Qt compatibility + pass + + monkeypatch.setattr(dialog_module, "PrescriptionEditorDialog", FakeEditor) + repository = SimpleNamespace(get_prescription=lambda _id: dict(detail), update_prescription=update) + preview = PrescriptionSigningPreview(repository, {"id": 74, "esign": {"required": True, "status": "pending"}}) + saved: list[Any] = [] + preview.prescription_saved.connect(saved.append) + assert not preview.edit_button.isHidden() and not preview.edit_button.isEnabled() + preview.set_edit_allowed(True) + assert preview.edit_button.isEnabled() + + preview.edit_button.click() + assert updates == [(74, {"patient_name": "修改后患者"})] + assert editors[0]["patient_name"] == "原患者" and editors[0]["esign"]["status"] == "pending" + assert saved and "修改后患者" in preview.paper.toPlainText() + + preview.set_esign_state({"required": True, "status": "authenticating"}) + assert preview.edit_button.isHidden() + preview.set_esign_state({"required": True, "status": "pending"}) + preview.set_edit_allowed(False) + assert not preview.edit_button.isHidden() and not preview.edit_button.isEnabled() def test_signing_preview_renders_an_intentionally_empty_saved_prescription( diff --git a/server/app/adminapi/controller/tcm/PrescriptionController.php b/server/app/adminapi/controller/tcm/PrescriptionController.php index e46f619fd..49691dfc3 100755 --- a/server/app/adminapi/controller/tcm/PrescriptionController.php +++ b/server/app/adminapi/controller/tcm/PrescriptionController.php @@ -9,7 +9,7 @@ use app\adminapi\logic\tcm\PrescriptionLogic; use app\adminapi\validate\tcm\PrescriptionValidate; use app\common\service\esign\DoctorEsignIdentityService; use app\common\service\esign\PrescriptionCaSigningSettings; -use app\common\service\esign\PrescriptionEsignService; +use app\common\service\esign\PrescriptionEsignService; use app\common\service\esign\PrescriptionReviewEsignService; /** @@ -32,11 +32,11 @@ class PrescriptionController extends BaseAdminController { $params = (new PrescriptionValidate())->post()->goCheck('add'); $params['creator_id'] = $this->adminId; - $id = PrescriptionLogic::add($params, $this->adminId, $this->adminInfo); + $id = PrescriptionLogic::add($params, $this->adminId, $this->adminInfo); if ($id === null) { return $this->fail(PrescriptionLogic::getError()); } - return $this->success('保存成功', ['id' => $id, 'esign' => PrescriptionEsignService::status($id, (int) $this->adminId, $this->adminInfo)]); + return $this->success('保存成功', ['id' => $id, 'esign' => PrescriptionEsignService::status($id, (int) $this->adminId, $this->adminInfo)]); } /** @@ -49,7 +49,7 @@ class PrescriptionController extends BaseAdminController if (!$result) { return $this->fail(PrescriptionLogic::getError()); } - return $this->success('编辑成功', ['id' => (int) $params['id'], 'esign' => PrescriptionEsignService::status((int) $params['id'], (int) $this->adminId, $this->adminInfo)]); + return $this->success('编辑成功', ['id' => (int) $params['id'], 'esign' => PrescriptionEsignService::status((int) $params['id'], (int) $this->adminId, $this->adminInfo)]); } /** @@ -157,12 +157,12 @@ class PrescriptionController extends BaseAdminController $diagnosisId = (int)($this->request->get('diagnosis_id') ?? 0); if (!$diagnosisId) { return $this->fail('诊单ID不能为空'); - } - $list = PrescriptionLogic::listByDiagnosis($diagnosisId, (int) $this->adminId, $this->adminInfo); - if (PrescriptionLogic::getError() !== '') { - return $this->fail(PrescriptionLogic::getError()); - } - return $this->data($list); + } + $list = PrescriptionLogic::listByDiagnosis($diagnosisId, (int) $this->adminId, $this->adminInfo); + if (PrescriptionLogic::getError() !== '') { + return $this->fail(PrescriptionLogic::getError()); + } + return $this->data($list); } /** @@ -190,11 +190,11 @@ class PrescriptionController extends BaseAdminController */ public function void() { - if (!$this->request->isPost()) { - return $this->fail('请使用 POST 作废处方'); - } + if (!$this->request->isPost()) { + return $this->fail('请使用 POST 作废处方'); + } $id = (int)($this->request->post('id') ?? 0); - if ($id <= 0) { + if ($id <= 0) { return $this->fail('处方ID不能为空'); } $pendingOnly = $this->request->post('pending_only', false, null); @@ -207,11 +207,11 @@ class PrescriptionController extends BaseAdminController } return $this->success('作废成功'); } - - public function esignConfig() - { - return $this->data(PrescriptionEsignService::capability()); - } + + public function esignConfig() + { + return $this->data(PrescriptionEsignService::capability()); + } /** @notes 修改处方 CA 签名设置 */ public function esignSetConfig() @@ -235,37 +235,37 @@ class PrescriptionController extends BaseAdminController return $this->fail('CA 签名设置暂时无法保存,请稍后重试'); } } - - public function esignStatus() - { - return $this->esignOperation('status', false); - } - - public function esignIdentityStatus() - { - return $this->esignOperation('identityStatus', false); - } - - public function esignStart() - { - return $this->esignOperation('start', true); - } - - public function esignComplete() - { - return $this->esignOperation('complete', true); - } - + + public function esignStatus() + { + return $this->esignOperation('status', false); + } + + public function esignIdentityStatus() + { + return $this->esignOperation('identityStatus', false); + } + + public function esignStart() + { + return $this->esignOperation('start', true); + } + + public function esignComplete() + { + return $this->esignOperation('complete', true); + } + /** @notes 验证处方签署短信 */ public function esignVerifyWillingness() { return $this->esignOperation('verifyWillingness', true); } - public function esignDownload() - { - return $this->esignOperation('download', false); - } + public function esignDownload() + { + return $this->esignOperation('download', false); + } public function esignReviewStatus() { @@ -309,7 +309,7 @@ class PrescriptionController extends BaseAdminController ? $error->getMessage() : '审核签署暂不可用,请刷新状态后重试'); } } - + /** @notes 查询医师电子签署认证 */ public function esignDoctorStatus() { @@ -355,26 +355,35 @@ class PrescriptionController extends BaseAdminController } return $this->data($data)->header(['Cache-Control' => 'private, no-store']); } catch (\Throwable $error) { - return $this->fail($error instanceof \DomainException ? $error->getMessage() : '医师认证暂不可用,请稍后重试'); + // 只记录异常类型与位置,不记录手机号、证件号或 e签宝原始响应。 + \think\facade\Log::warning('Doctor esign ' . $operation . ' failed', [ + 'admin_id' => (int) $this->adminId, + 'exception' => get_class($error), + 'provider_code' => $error instanceof \app\common\service\esign\EsignProviderException + ? $error->operation . ':' . $error->providerCode . ':' . ($error->reason ?? '') : '', + 'at' => basename($error->getFile()) . ':' . $error->getLine(), + ]); + return $this->fail($error instanceof \DomainException || $error instanceof \app\common\service\esign\EsignProviderException + ? mb_substr($error->getMessage(), 0, 240) : '医师认证暂不可用,请稍后重试'); } } - private function esignOperation(string $operation, bool $post) - { - if ($post && !$this->request->isPost()) { - return $this->fail('请使用 POST 请求'); - } - $id = (int) ($post ? $this->request->post('id', 0) : $this->request->get('id', 0)); - if ($id <= 0) { - return $this->fail('处方ID无效'); - } - if ($operation === 'complete') { - // A browser disconnect must not interrupt archival after signing. - ignore_user_abort(true); - set_time_limit(300); - } - try { - $body = $post ? $this->request->post(false) : []; + private function esignOperation(string $operation, bool $post) + { + if ($post && !$this->request->isPost()) { + return $this->fail('请使用 POST 请求'); + } + $id = (int) ($post ? $this->request->post('id', 0) : $this->request->get('id', 0)); + if ($id <= 0) { + return $this->fail('处方ID无效'); + } + if ($operation === 'complete') { + // A browser disconnect must not interrupt archival after signing. + ignore_user_abort(true); + set_time_limit(300); + } + try { + $body = $post ? $this->request->post(false) : []; if ($operation === 'verifyWillingness') { $code = $this->request->post('auth_code', ''); if (!is_string($code)) { @@ -383,29 +392,29 @@ class PrescriptionController extends BaseAdminController return $this->data(PrescriptionEsignService::verifyWillingness($id, (int) $this->adminId, $this->adminInfo, $code)); } - if ($operation === 'start') { - $restartIdentity = array_key_exists('restart_identity', $body) ? $body['restart_identity'] : false; - if (!is_bool($restartIdentity)) { - return $this->fail('重新核身标记格式无效'); - } - return $this->data(PrescriptionEsignService::start($id, (int) $this->adminId, - $this->adminInfo, $restartIdentity)); - } - if ($operation === 'complete') { - $verifyOnly = array_key_exists('verify_only', $body) ? $body['verify_only'] : false; - if (!is_bool($verifyOnly)) { - return $this->fail('验签标记格式无效'); - } - $identityNumber = $this->request->post('identity_number', ''); - if (!is_string($identityNumber)) { - return $this->fail('身份证号码格式无效'); - } - return $this->data(PrescriptionEsignService::complete($id, (int) $this->adminId, - $this->adminInfo, $identityNumber, $verifyOnly)); - } - return $this->data(PrescriptionEsignService::{$operation}($id, (int) $this->adminId, $this->adminInfo)); - } catch (\Throwable $e) { - return $this->fail($e instanceof \DomainException ? $e->getMessage() : '电子签署暂不可用,请联系管理员'); - } - } + if ($operation === 'start') { + $restartIdentity = array_key_exists('restart_identity', $body) ? $body['restart_identity'] : false; + if (!is_bool($restartIdentity)) { + return $this->fail('重新核身标记格式无效'); + } + return $this->data(PrescriptionEsignService::start($id, (int) $this->adminId, + $this->adminInfo, $restartIdentity)); + } + if ($operation === 'complete') { + $verifyOnly = array_key_exists('verify_only', $body) ? $body['verify_only'] : false; + if (!is_bool($verifyOnly)) { + return $this->fail('验签标记格式无效'); + } + $identityNumber = $this->request->post('identity_number', ''); + if (!is_string($identityNumber)) { + return $this->fail('身份证号码格式无效'); + } + return $this->data(PrescriptionEsignService::complete($id, (int) $this->adminId, + $this->adminInfo, $identityNumber, $verifyOnly)); + } + return $this->data(PrescriptionEsignService::{$operation}($id, (int) $this->adminId, $this->adminInfo)); + } catch (\Throwable $e) { + return $this->fail($e instanceof \DomainException ? $e->getMessage() : '电子签署暂不可用,请联系管理员'); + } + } }