This commit is contained in:
Your Name
2026-11-26 17:17:43 +08:00
parent be79e09c83
commit 301c04ca90
8 changed files with 515 additions and 125 deletions
@@ -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:
@@ -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()
@@ -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:
@@ -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):
+59
View File
@@ -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,
+58 -3
View File
@@ -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(