igengx
This commit is contained in:
+3
-1
@@ -81,7 +81,9 @@ DOCTOR_VERIFY_SSL=true
|
||||
|
||||
程序会自动在地址末尾追加 `/adminapi`。它与现有管理端保持相同约定:
|
||||
|
||||
- 登录:`POST /login/account`,请求包含 `account`、`password`、`terminal=1`。
|
||||
- 工作站使用 `POST /login/account` 登录,请求包含 `account`、`password` 和独立的 `terminal=21`。升级前保存的登录凭据需要重新登录一次。
|
||||
- 工作站每 60 秒调用 `POST /login/desktopHeartbeat`。每次登录的有效期截至下一个北京时间 05:00,登录和心跳响应中的 `desktop_expires_at` 为 Unix 秒。退出账号或关闭应用时通过 `POST /login/logout` 结束会话。
|
||||
- Web 后台的「桌面登录记录」支持按日期、账号或姓名调阅。跨北京时间零点的会话按实际重叠时段计入各日。断线超过心跳宽限时,退出时间按服务器最后确认在线的时间记录。
|
||||
- 鉴权请求头:`token: <登录 token>`,`version: 1.9.4`。
|
||||
- 响应 envelope:`code=1` 成功、`0` 业务失败、`-1` 登录失效、`10` 需绑定企业微信。
|
||||
- 权限与数据范围:完全以后端 `/auth.admin/mySelf` 返回为准。
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
@@ -10,7 +11,7 @@ from collections.abc import Mapping, Sequence
|
||||
from contextlib import suppress
|
||||
from typing import Any
|
||||
|
||||
from PySide6.QtCore import QLibraryInfo, QLocale, QObject, Qt, QTimer, QTranslator
|
||||
from PySide6.QtCore import QLibraryInfo, QLocale, QObject, Qt, QThreadPool, QTimer, QTranslator
|
||||
from PySide6.QtGui import QGuiApplication, QIcon
|
||||
from PySide6.QtWidgets import (
|
||||
QApplication,
|
||||
@@ -423,9 +424,18 @@ class ApplicationController(QObject):
|
||||
self._restore_worker: Any = None
|
||||
self._shutting_down = False
|
||||
self._authentication_expiry_in_progress = False
|
||||
self._desktop_session: Session | None = None
|
||||
self._heartbeat_pending = False
|
||||
self._next_heartbeat_at = 0.0
|
||||
self._session_workers = QThreadPool(self)
|
||||
self._session_workers.setMaxThreadCount(2)
|
||||
self._desktop_timer = QTimer(self)
|
||||
self._desktop_timer.setSingleShot(True)
|
||||
self._desktop_timer.setTimerType(Qt.TimerType.PreciseTimer)
|
||||
self._desktop_timer.timeout.connect(self._check_desktop_session)
|
||||
application.applicationStateChanged.connect(self._check_desktop_session)
|
||||
self._rebuild_remote_repository()
|
||||
self.app_updater = AppUpdateSession(self)
|
||||
set_authentication_expired_handler(self._on_authentication_expired)
|
||||
application.aboutToQuit.connect(self.shutdown)
|
||||
|
||||
def start(self) -> None:
|
||||
@@ -529,7 +539,7 @@ class ApplicationController(QObject):
|
||||
self.remote_repository = repository
|
||||
if old is not None and old is not self.current_repository:
|
||||
with suppress(Exception):
|
||||
old.client.close()
|
||||
old.close()
|
||||
|
||||
def _begin_session_restore(self) -> None:
|
||||
"""Validate a scoped persisted token without racing manual login."""
|
||||
@@ -655,6 +665,8 @@ class ApplicationController(QObject):
|
||||
self.login_window.set_session_restore_pending(False)
|
||||
|
||||
def _on_login_succeeded(self, payload: dict[str, Any]) -> None:
|
||||
if self._shutting_down:
|
||||
return
|
||||
self._cancel_session_restore()
|
||||
session = payload.get("session")
|
||||
repository = payload.get("repository")
|
||||
@@ -683,13 +695,22 @@ class ApplicationController(QObject):
|
||||
self.current_repository = repository
|
||||
self._authentication_expiry_in_progress = False
|
||||
self.current_demo_mode = demo_mode
|
||||
set_authentication_expired_handler(self._on_authentication_expired)
|
||||
self.shell_window = ShellWindow(repository, payload, session.permissions)
|
||||
self.shell_window.logout_requested.connect(self._logout)
|
||||
self.shell_window.close_requested.connect(self.request_quit)
|
||||
self.shell_window.video_requested.connect(self._request_video)
|
||||
self.shell_window.update_check_requested.connect(
|
||||
lambda: self.app_updater.check(interactive=True)
|
||||
)
|
||||
self._apply_window_icon(self.shell_window)
|
||||
if isinstance(repository, RemoteDoctorRepository):
|
||||
self._desktop_session = session
|
||||
self._heartbeat_pending = False
|
||||
self._next_heartbeat_at = time.time() + 60
|
||||
self._check_desktop_session()
|
||||
if self.shell_window is None:
|
||||
return
|
||||
if self.login_window is not None:
|
||||
self.login_window.hide()
|
||||
self.shell_window.show()
|
||||
@@ -697,6 +718,45 @@ class ApplicationController(QObject):
|
||||
self.shell_window.activateWindow()
|
||||
self.app_updater.schedule(delay_ms=400)
|
||||
|
||||
def _check_desktop_session(self, *_args: Any) -> None:
|
||||
"""Check wall time even when idle, minimized or returning from sleep."""
|
||||
|
||||
session = self._desktop_session
|
||||
repository = self.current_repository
|
||||
if session is None or repository is None or self._shutting_down:
|
||||
return
|
||||
now = time.time()
|
||||
remaining = session.desktop_expires_at - now
|
||||
if remaining <= 0:
|
||||
self._logout(message="已到北京时间 05:00,请重新登录医生工作站。")
|
||||
return
|
||||
# A repeating wall-clock check also catches clock changes and resume on
|
||||
# platforms where a long monotonic timer pauses during system sleep.
|
||||
self._desktop_timer.start(max(1, min(1000, math.ceil(remaining * 1000))))
|
||||
if self._heartbeat_pending or now < self._next_heartbeat_at:
|
||||
return
|
||||
self._heartbeat_pending = True
|
||||
self._next_heartbeat_at = now + 60
|
||||
|
||||
def received(deadline: int) -> None:
|
||||
if self._desktop_session is session:
|
||||
self._heartbeat_pending = False
|
||||
session.desktop_expires_at = min(session.desktop_expires_at, deadline)
|
||||
self._check_desktop_session()
|
||||
|
||||
def failed(_error: Exception) -> None:
|
||||
if self._desktop_session is session:
|
||||
self._heartbeat_pending = False
|
||||
self._next_heartbeat_at = time.time() + 15
|
||||
|
||||
run_async(
|
||||
repository.desktop_heartbeat,
|
||||
session.token,
|
||||
on_success=received,
|
||||
on_error=failed,
|
||||
pool=self._session_workers,
|
||||
)
|
||||
|
||||
def _login_guard_error(self, message: str) -> None:
|
||||
if self.login_window is not None:
|
||||
self.login_window.error_banner.show_message(message, "warning")
|
||||
@@ -720,6 +780,9 @@ class ApplicationController(QObject):
|
||||
def _logout(self, *, message: str = "") -> None:
|
||||
"""Clear authenticated resources and return to the login window."""
|
||||
|
||||
self._desktop_session = None
|
||||
self._desktop_timer.stop()
|
||||
set_authentication_expired_handler(None)
|
||||
self._restore_video_preview(activate=False)
|
||||
calls = tuple(self.video_calls.values())
|
||||
for call in calls:
|
||||
@@ -729,18 +792,27 @@ class ApplicationController(QObject):
|
||||
self.video_calls.clear()
|
||||
self.video_pending.clear()
|
||||
self._pending_im_request = None
|
||||
for dialog in self.demo_video_dialogs.values():
|
||||
for dialog in tuple(self.demo_video_dialogs.values()):
|
||||
dialog.close()
|
||||
self.demo_video_dialogs.clear()
|
||||
if self.current_repository is not None:
|
||||
repository = self.current_repository
|
||||
if isinstance(repository, RemoteDoctorRepository):
|
||||
# Stale queued requests retain their old client. Detach locally
|
||||
# before enabling login and release the remote session off-thread.
|
||||
token = repository.detach_session()
|
||||
self.remote_repository = None
|
||||
self._rebuild_remote_repository()
|
||||
run_async(repository.close, token, pool=self._session_workers)
|
||||
elif repository is not None:
|
||||
with suppress(Exception):
|
||||
self.current_repository.logout()
|
||||
repository.logout()
|
||||
self.current_repository = None
|
||||
self._show_login()
|
||||
if self.shell_window is not None:
|
||||
self.shell_window.close_requested.disconnect(self.request_quit)
|
||||
self.shell_window.close()
|
||||
self.shell_window.deleteLater()
|
||||
self.shell_window = None
|
||||
self._show_login()
|
||||
if message and self.login_window is not None:
|
||||
self.login_window.error_banner.show_message(message, "warning")
|
||||
|
||||
@@ -1130,6 +1202,8 @@ class ApplicationController(QObject):
|
||||
if self._shutting_down:
|
||||
return
|
||||
self._shutting_down = True
|
||||
self._desktop_session = None
|
||||
self._desktop_timer.stop()
|
||||
self._cancel_session_restore()
|
||||
self.app_updater.shutdown()
|
||||
set_authentication_expired_handler(None)
|
||||
@@ -1141,7 +1215,7 @@ class ApplicationController(QObject):
|
||||
self._wait_for_video_lifecycle(calls, timeout=1.25)
|
||||
if self.remote_repository is not None:
|
||||
with suppress(Exception):
|
||||
self.remote_repository.client.close()
|
||||
self.remote_repository.close()
|
||||
|
||||
|
||||
def _prefer_native_tls_backend() -> None:
|
||||
|
||||
@@ -48,7 +48,10 @@ def esign_status(value: Any) -> dict[str, Any]:
|
||||
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",
|
||||
"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)
|
||||
|
||||
@@ -624,6 +624,8 @@ class Prescription:
|
||||
audit_time: str = ""
|
||||
audit_by_name: str = ""
|
||||
audit_remark: str = ""
|
||||
review_submitted_at: int | None = None
|
||||
can_submit_for_review: bool = False
|
||||
business_prescription_audit_status: int | None = None
|
||||
business_prescription_audit_rejected: bool = False
|
||||
business_prescription_audit_remark: str = ""
|
||||
@@ -698,6 +700,8 @@ class Prescription:
|
||||
audit_time=_text(source.get("audit_time")),
|
||||
audit_by_name=_text(source.get("audit_by_name")),
|
||||
audit_remark=_text(source.get("audit_remark")),
|
||||
review_submitted_at=_integer(source.get("review_submitted_at"), None),
|
||||
can_submit_for_review=source.get("can_submit_for_review") is True,
|
||||
business_prescription_audit_status=_integer(
|
||||
source.get("business_prescription_audit_status"), None
|
||||
),
|
||||
|
||||
@@ -20,6 +20,7 @@ class Session:
|
||||
is_paw: int = 1
|
||||
need_bind_work_wechat: bool = False
|
||||
metadata: dict[str, Any] = field(default_factory=dict, repr=False)
|
||||
desktop_expires_at: int = 0
|
||||
|
||||
@property
|
||||
def authenticated(self) -> bool:
|
||||
|
||||
@@ -241,15 +241,18 @@ class ApiClient:
|
||||
payload: Mapping[str, Any],
|
||||
*,
|
||||
timeout: float = 10.0,
|
||||
headers: Mapping[str, str] | None = None,
|
||||
) -> Any:
|
||||
"""Send a short control request without waiting for the ordinary pool."""
|
||||
|
||||
if not self._owns_client:
|
||||
return self.post(endpoint, payload, timeout=timeout, headers=headers)
|
||||
try:
|
||||
with httpx.Client(transport=self._stream_transport, verify=self._verify) as client:
|
||||
response = client.post(
|
||||
self._endpoint_url(endpoint),
|
||||
json=dict(payload),
|
||||
headers=self._headers(None),
|
||||
headers=self._headers(headers),
|
||||
timeout=timeout,
|
||||
)
|
||||
return self._unwrap(response)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -103,6 +103,7 @@ class TokenStore:
|
||||
*,
|
||||
account: str | None = None,
|
||||
scope: str | None = None,
|
||||
desktop_expires_at: int = 0,
|
||||
) -> None:
|
||||
"""Persist a token plus optional account and API-scope metadata.
|
||||
|
||||
@@ -117,6 +118,12 @@ class TokenStore:
|
||||
self.save_account(account)
|
||||
return
|
||||
data = self._read_file()
|
||||
data.pop("desktop_session", None)
|
||||
if desktop_expires_at > 0:
|
||||
data["desktop_session"] = {
|
||||
"token_sha256": hashlib.sha256(cleaned.encode()).hexdigest(),
|
||||
"expires_at": desktop_expires_at,
|
||||
}
|
||||
if account is not None:
|
||||
account_value = account.strip()
|
||||
previous_account = str(data.get("account") or "").strip()
|
||||
@@ -151,6 +158,18 @@ class TokenStore:
|
||||
data["token"] = cleaned
|
||||
self._write_file(data)
|
||||
|
||||
def desktop_expiry(self, token: str) -> int:
|
||||
"""Read the deadline only for the matching workstation-issued token."""
|
||||
|
||||
marker = self._read_file().get("desktop_session")
|
||||
if not isinstance(marker, dict):
|
||||
return 0
|
||||
fingerprint = hashlib.sha256(token.encode()).hexdigest()
|
||||
expiry = marker.get("expires_at")
|
||||
if marker.get("token_sha256") == fingerprint and type(expiry) is int and expiry > 0:
|
||||
return expiry
|
||||
return 0
|
||||
|
||||
def clear_token(self) -> None:
|
||||
"""Delete the token while retaining remembered login credentials."""
|
||||
|
||||
@@ -161,6 +180,7 @@ class TokenStore:
|
||||
self._uses_keyring = False
|
||||
data = self._read_file()
|
||||
data.pop("token", None)
|
||||
data.pop("desktop_session", None)
|
||||
if not data.get("account"):
|
||||
data.pop("scope", None)
|
||||
self._write_file(data)
|
||||
@@ -457,14 +477,14 @@ class TokenStore:
|
||||
# Explicit allow-list guarantees accidental password-like fields are ignored.
|
||||
return {
|
||||
key: value[key]
|
||||
for key in ("token", "account", "scope", "credential")
|
||||
for key in ("token", "account", "scope", "credential", "desktop_session")
|
||||
if key in value
|
||||
}
|
||||
|
||||
def _write_file(self, data: dict[str, Any]) -> None:
|
||||
safe = {
|
||||
key: data[key]
|
||||
for key in ("token", "account", "scope", "credential")
|
||||
for key in ("token", "account", "scope", "credential", "desktop_session")
|
||||
if data.get(key)
|
||||
}
|
||||
if not safe:
|
||||
|
||||
@@ -116,6 +116,7 @@ from .prescription_ai import (
|
||||
can_use_diagnosis_ai_assistant,
|
||||
diagnosis_ai_task,
|
||||
)
|
||||
from .prescription_esign import resume_saved_prescription, saved_prescription_message
|
||||
|
||||
AI_CONSULT_QSS = clinical_stylesheet("""
|
||||
QDialog#AiConsultDialog {
|
||||
@@ -1222,7 +1223,7 @@ def _unwrap_analysis(payload: Any) -> dict[str, Any]:
|
||||
current: Mapping[str, Any] = payload
|
||||
latest = current.get("latest_by_model")
|
||||
if isinstance(latest, Mapping):
|
||||
for key in ("qwen", "openai"):
|
||||
for key in ("qwen", "openai", "doubao"):
|
||||
row = latest.get(key)
|
||||
if isinstance(row, Mapping):
|
||||
current = row
|
||||
@@ -7085,7 +7086,7 @@ class AiConsultDialog(QDialog):
|
||||
):
|
||||
status.set_payload("AI处方草稿缺少诊断或药材,已停止开方。")
|
||||
return
|
||||
status.set_payload("AI 已生成处方草稿,请逐味复核、修改并完成医师签名。")
|
||||
status.set_payload("AI 已生成处方草稿,请逐味复核并保存。")
|
||||
self._open_prescription_editor_from_chat(
|
||||
generation,
|
||||
diagnosis_id,
|
||||
@@ -7177,45 +7178,46 @@ class AiConsultDialog(QDialog):
|
||||
}
|
||||
seed.update({key: deepcopy(value) for key, value in draft.items() if key in allowed})
|
||||
seed["ai_assisted"] = True
|
||||
linked_fields = {
|
||||
"diagnosis_id": diagnosis_id,
|
||||
"appointment_id": seed["appointment_id"],
|
||||
"case_record": deepcopy(seed["case_record"]),
|
||||
"patient_id": seed["patient_id"],
|
||||
"phone": seed["phone"],
|
||||
}
|
||||
|
||||
def save_prescription(payload: dict[str, Any]) -> Any:
|
||||
return invoke(
|
||||
self.repository, "create_prescription", prescription=deepcopy(payload | linked_fields)
|
||||
)
|
||||
|
||||
dialog = PrescriptionEditorDialog(
|
||||
self.repository,
|
||||
seed,
|
||||
mode="add",
|
||||
current_user=self._current_user(),
|
||||
permissions=self.permissions,
|
||||
save_draft=save_prescription,
|
||||
parent=self,
|
||||
)
|
||||
if dialog.exec() != QDialog.DialogCode.Accepted:
|
||||
status.set_payload("已取消开方,未保存或提交任何处方。")
|
||||
return
|
||||
saved = getattr(dialog, "saved_draft", None)
|
||||
if saved is not None:
|
||||
self._prescription_action_created(generation, diagnosis_id, status, saved)
|
||||
return
|
||||
|
||||
status.set_payload("正在保存处方。")
|
||||
payload = dialog.payload()
|
||||
payload.update(
|
||||
{
|
||||
"diagnosis_id": diagnosis_id,
|
||||
"appointment_id": seed["appointment_id"],
|
||||
"case_record": deepcopy(seed["case_record"]),
|
||||
"patient_id": seed["patient_id"],
|
||||
"phone": seed["phone"],
|
||||
}
|
||||
)
|
||||
status.set_payload("处方已填写,正在提交审核。")
|
||||
frozen_payload = deepcopy(payload)
|
||||
run_async(
|
||||
lambda: invoke(
|
||||
self.repository,
|
||||
"create_prescription",
|
||||
prescription=frozen_payload,
|
||||
),
|
||||
on_success=lambda _result: self._prescription_action_created(
|
||||
generation,
|
||||
diagnosis_id,
|
||||
status,
|
||||
),
|
||||
lambda: save_prescription(payload),
|
||||
on_success=lambda result: self._prescription_action_created(generation, diagnosis_id, status, result),
|
||||
on_error=lambda error: self._prescription_action_error(
|
||||
generation,
|
||||
status,
|
||||
error,
|
||||
prefix="处方提交失败",
|
||||
prefix="处方保存失败",
|
||||
),
|
||||
)
|
||||
|
||||
@@ -7224,11 +7226,14 @@ class AiConsultDialog(QDialog):
|
||||
generation: int,
|
||||
diagnosis_id: int,
|
||||
status: _ChatBubble,
|
||||
prescription: Any,
|
||||
) -> None:
|
||||
if generation != self._generation or diagnosis_id != self.diagnosis_id:
|
||||
return
|
||||
status.set_payload("处方已开具并提交审核。")
|
||||
message, _ = saved_prescription_message(prescription, "处方已保存。")
|
||||
status.set_payload(message)
|
||||
status.set_time_text(_join_meta("系统", datetime.now().strftime("%H:%M")))
|
||||
resume_saved_prescription(self.repository, prescription, self)
|
||||
self._reload_prescriptions(generation, diagnosis_id)
|
||||
|
||||
def _prescription_action_error(
|
||||
|
||||
@@ -3771,6 +3771,8 @@ class DiagnosisDialog(QDialog):
|
||||
if reload_key == "prescription":
|
||||
text, kind = saved_prescription_message(result, text)
|
||||
self._show_message(text, kind)
|
||||
if reload_key == "prescription":
|
||||
resume_saved_prescription(self.repository, result, self)
|
||||
self._loaded_tabs.discard(reload_key)
|
||||
if reload_key == "chat":
|
||||
QTimer.singleShot(
|
||||
@@ -3783,8 +3785,6 @@ class DiagnosisDialog(QDialog):
|
||||
)
|
||||
else:
|
||||
self._ensure_tab_loaded(reload_key, force=True)
|
||||
if reload_key == "prescription":
|
||||
resume_saved_prescription(self.repository, result, self)
|
||||
|
||||
def _order_offset_changed(self, value: int) -> None:
|
||||
self.order_offset_preview.setText(f"第 1 笔实单计为{_visit_slot_label(value)}")
|
||||
|
||||
@@ -96,6 +96,7 @@ from PySide6.QtWidgets import (
|
||||
QVBoxLayout,
|
||||
QWidget,
|
||||
)
|
||||
from shiboken6 import isValid
|
||||
|
||||
from ...core.esign import esign_config, esign_status
|
||||
from .. import icons
|
||||
@@ -118,8 +119,15 @@ from ..widgets import (
|
||||
)
|
||||
from .diagnosis import DiagnosisDialog as _StructuredDiagnosisDialog
|
||||
from .prescription_esign import (
|
||||
PRESCRIPTION_UPLOAD_BEFORE_SIGNING_PROMPT,
|
||||
PrescriptionEsignDialog,
|
||||
SigningLogDialog,
|
||||
awaiting_prescription_upload,
|
||||
can_upload_prescription,
|
||||
open_saved_original,
|
||||
review_signature_time,
|
||||
review_signing_status,
|
||||
review_submission_time,
|
||||
save_signed_original,
|
||||
signature_state,
|
||||
signature_time_text,
|
||||
@@ -1528,61 +1536,108 @@ class AdminDosageInput(SelectComboBox):
|
||||
return self._maximum
|
||||
|
||||
|
||||
class MultiSelectComboBox(QComboBox):
|
||||
"""Compact fixed-option multi-select matching Element Plus ``multiple`` selects."""
|
||||
class MultiSelectComboBox(SelectComboBox):
|
||||
"""A checklist popup with a read-only summary of its checked options."""
|
||||
|
||||
def __init__(self, options: Sequence[str], parent: QWidget | None = None) -> None:
|
||||
super().__init__(parent)
|
||||
self.setEditable(True)
|
||||
self.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||
if self.lineEdit() is not None:
|
||||
self.lineEdit().setReadOnly(True)
|
||||
self.lineEdit().setPlaceholderText("请选择忌口内容(可多选)")
|
||||
self.lineEdit().setCursor(Qt.CursorShape.PointingHandCursor)
|
||||
self.setCompleter(None)
|
||||
field = self.lineEdit()
|
||||
field.setReadOnly(True)
|
||||
field.setPlaceholderText("请选择忌口内容(可多选)")
|
||||
field.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||
self._options = QStandardItemModel(self)
|
||||
for option in options:
|
||||
self.addItem(option, option)
|
||||
self.setItemData(
|
||||
self.count() - 1, Qt.CheckState.Unchecked, Qt.ItemDataRole.CheckStateRole
|
||||
)
|
||||
self.view().pressed.connect(self._toggle_item)
|
||||
# QComboBox applies the clicked item's text after ``pressed``. Refresh
|
||||
# on the next event-loop tick so the field always shows every checked
|
||||
# value instead of only the last clicked one.
|
||||
self.currentIndexChanged.connect(lambda _index: QTimer.singleShot(0, self._refresh_text))
|
||||
item = QStandardItem(option)
|
||||
item.setCheckable(True)
|
||||
item.setEditable(False)
|
||||
self._options.appendRow(item)
|
||||
self.setModel(self._options)
|
||||
self._pressed_item = QModelIndex()
|
||||
self.view().installEventFilter(self)
|
||||
self.view().viewport().installEventFilter(self)
|
||||
field.installEventFilter(self)
|
||||
self.currentIndexChanged.connect(self._refresh_text)
|
||||
self._refresh_text()
|
||||
|
||||
def _toggle_item(self, index: Any) -> None:
|
||||
row = index.row()
|
||||
checked = self.itemData(row, Qt.ItemDataRole.CheckStateRole) == Qt.CheckState.Checked
|
||||
self.setItemData(
|
||||
row,
|
||||
Qt.CheckState.Unchecked if checked else Qt.CheckState.Checked,
|
||||
Qt.ItemDataRole.CheckStateRole,
|
||||
def eventFilter(self, watched: QObject, event: QEvent) -> bool: # noqa: N802 - Qt virtual
|
||||
view = self.view()
|
||||
event_type = event.type()
|
||||
if (
|
||||
watched is view.viewport()
|
||||
and isinstance(event, QMouseEvent)
|
||||
and event.button() == Qt.MouseButton.LeftButton
|
||||
):
|
||||
index = view.indexAt(event.position().toPoint())
|
||||
if event_type in (QEvent.Type.MouseButtonPress, QEvent.Type.MouseButtonDblClick):
|
||||
self._pressed_item = index
|
||||
view.setCurrentIndex(index)
|
||||
return True
|
||||
if event_type == QEvent.Type.MouseButtonRelease:
|
||||
# Consume the release before QComboBox can commit one row and close the popup.
|
||||
if index == self._pressed_item:
|
||||
self._toggle_item(index)
|
||||
self._pressed_item = QModelIndex()
|
||||
return True
|
||||
if (
|
||||
watched is view
|
||||
and event_type == QEvent.Type.KeyPress
|
||||
and event.key() in (Qt.Key.Key_Space, Qt.Key.Key_Return, Qt.Key.Key_Enter)
|
||||
):
|
||||
if not event.isAutoRepeat():
|
||||
self._toggle_item(view.currentIndex())
|
||||
return True
|
||||
if (
|
||||
watched is self.lineEdit()
|
||||
and event_type == QEvent.Type.MouseButtonPress
|
||||
and event.button() == Qt.MouseButton.LeftButton
|
||||
):
|
||||
self.setFocus(Qt.FocusReason.MouseFocusReason)
|
||||
self.showPopup()
|
||||
return True
|
||||
return super().eventFilter(watched, event)
|
||||
|
||||
def keyPressEvent(self, event: QKeyEvent) -> None: # noqa: N802 - Qt virtual
|
||||
if event.key() in (Qt.Key.Key_Space, Qt.Key.Key_Down, Qt.Key.Key_Up):
|
||||
self.showPopup()
|
||||
return
|
||||
super().keyPressEvent(event)
|
||||
|
||||
def wheelEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual
|
||||
event.ignore()
|
||||
|
||||
def _toggle_item(self, index: QModelIndex) -> None:
|
||||
item = self._options.itemFromIndex(index)
|
||||
if item is None:
|
||||
return
|
||||
item.setCheckState(
|
||||
Qt.CheckState.Unchecked
|
||||
if item.checkState() == Qt.CheckState.Checked
|
||||
else Qt.CheckState.Checked
|
||||
)
|
||||
self._refresh_text()
|
||||
|
||||
def set_values(self, values: Iterable[Any]) -> None:
|
||||
selected = {str(value).strip() for value in values if str(value).strip()}
|
||||
for row in range(self.count()):
|
||||
self.setItemData(
|
||||
row,
|
||||
for row in range(self._options.rowCount()):
|
||||
item = self._options.item(row)
|
||||
item.setCheckState(
|
||||
Qt.CheckState.Checked
|
||||
if str(self.itemData(row)).strip() in selected
|
||||
else Qt.CheckState.Unchecked,
|
||||
Qt.ItemDataRole.CheckStateRole,
|
||||
if item.text().strip() in selected
|
||||
else Qt.CheckState.Unchecked
|
||||
)
|
||||
self._refresh_text()
|
||||
|
||||
def values(self) -> list[str]:
|
||||
return [
|
||||
str(self.itemData(row))
|
||||
for row in range(self.count())
|
||||
if self.itemData(row, Qt.ItemDataRole.CheckStateRole) == Qt.CheckState.Checked
|
||||
item.text()
|
||||
for row in range(self._options.rowCount())
|
||||
if (item := self._options.item(row)).checkState() == Qt.CheckState.Checked
|
||||
]
|
||||
|
||||
def _refresh_text(self) -> None:
|
||||
if self.lineEdit() is not None:
|
||||
self.lineEdit().setText("、".join(self.values()))
|
||||
self.lineEdit().setText("、".join(self.values()))
|
||||
|
||||
|
||||
_MEDICINE_NAME_ROLE = Qt.ItemDataRole.UserRole + 1
|
||||
@@ -3888,8 +3943,13 @@ class PrescriptionEditorDialog(QDialog):
|
||||
banner.clear()
|
||||
messages: list[str] = []
|
||||
if self.mode == "edit":
|
||||
uses_upload = review_submission_time(self._source, signature_state(self._source)) is not None
|
||||
review_hint = (
|
||||
"保存修改后,请重新上传处方。须电子签署的处方在医生签署后进入药师审核。"
|
||||
if uses_upload else "保存修改后,该处方将重新进入「待审核」,需审核人员再次通过后方可生效。"
|
||||
)
|
||||
self.reaudit_banner.show_message(
|
||||
"保存修改后,该处方将重新进入「待审核」,需审核人员再次通过后方可生效。",
|
||||
review_hint,
|
||||
"info",
|
||||
)
|
||||
messages.append(self.reaudit_banner.label.text())
|
||||
@@ -3903,9 +3963,9 @@ class PrescriptionEditorDialog(QDialog):
|
||||
rejected = _int(self._source.get("audit_status"), -1) == 2
|
||||
if rejected:
|
||||
remark = str(self._source.get("audit_remark") or "").strip()
|
||||
text = "当前消费者处方为「已驳回」\n保存修改后将清除驳回并变为「待审核」。"
|
||||
text = "当前消费者处方为「已驳回」\n保存修改后将清除驳回。"
|
||||
if remark:
|
||||
text += f"上次意见:{remark}"
|
||||
text += f"\n上次意见:{remark}"
|
||||
self.consumer_reject_banner.show_message(text, "danger")
|
||||
messages.append(self.consumer_reject_banner.label.text())
|
||||
if _bool(self._source.get("business_prescription_audit_rejected")) and _int(
|
||||
@@ -3922,11 +3982,11 @@ class PrescriptionEditorDialog(QDialog):
|
||||
self.business_reject_banner.show_message(text, "warning")
|
||||
messages.append(self.business_reject_banner.label.text())
|
||||
if voided and rejected:
|
||||
revive = "当前处方已作废且已驳回。保存后将取消作废、清除驳回,并重新进入待审核。"
|
||||
revive = "当前处方已作废且已驳回。保存后将取消作废、清除驳回。"
|
||||
elif voided:
|
||||
revive = "当前为已作废处方。保存后将取消作废,并重新进入待审核。"
|
||||
revive = "当前为已作废处方。保存后将取消作废。"
|
||||
elif rejected:
|
||||
revive = "当前为已驳回处方。保存后将清除驳回,并重新进入待审核。"
|
||||
revive = "当前为已驳回处方。保存后将清除驳回。"
|
||||
else:
|
||||
revive = ""
|
||||
if revive:
|
||||
@@ -4475,10 +4535,11 @@ class PatchPatientDialog(QDialog):
|
||||
class AuditPrescriptionDialog(QDialog):
|
||||
"""Approve or reject a pending prescription with the canonical DTO."""
|
||||
|
||||
def __init__(self, prescription: Any, parent: QWidget | None = None) -> None:
|
||||
def __init__(self, prescription: Any, parent: QWidget | None = None, *, allow_approval: bool = True) -> None:
|
||||
super().__init__(parent)
|
||||
_apply_prescription_dialog_style(self)
|
||||
self.prescription_id = _int(first_value(prescription, "id", "prescription_id"))
|
||||
self._allow_approval = allow_approval
|
||||
self.action = ""
|
||||
self.setWindowTitle("处方审核")
|
||||
self.resize(500, 300)
|
||||
@@ -4490,10 +4551,13 @@ class AuditPrescriptionDialog(QDialog):
|
||||
root.addWidget(self.remark)
|
||||
self.banner = MessageBanner()
|
||||
root.addWidget(self.banner)
|
||||
if not allow_approval:
|
||||
self.banner.show_message("请先在管理后台完成药师审核签署,再提交审核通过。", "info")
|
||||
buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Cancel)
|
||||
buttons.rejected.connect(self.reject)
|
||||
approve = buttons.addButton("审核通过", QDialogButtonBox.ButtonRole.AcceptRole)
|
||||
approve.setProperty("variant", "primary")
|
||||
approve.setEnabled(allow_approval)
|
||||
approve.clicked.connect(lambda: self._choose("approve"))
|
||||
reject = buttons.addButton("驳回处方", QDialogButtonBox.ButtonRole.DestructiveRole)
|
||||
reject.setProperty("variant", "danger")
|
||||
@@ -4501,6 +4565,8 @@ class AuditPrescriptionDialog(QDialog):
|
||||
root.addWidget(buttons)
|
||||
|
||||
def _choose(self, action: str) -> None:
|
||||
if action == "approve" and not self._allow_approval:
|
||||
return
|
||||
if action == "reject" and not self.remark.toPlainText().strip():
|
||||
self.banner.show_message("驳回时请填写审核意见。", "warning")
|
||||
return
|
||||
@@ -4770,21 +4836,24 @@ h1 {{ text-align:center; font-size:20px; font-weight:600; margin:0;
|
||||
_SLIP_HOSPITAL_TITLE = "成都双流甄养堂互联网医院 处方笺"
|
||||
_SLIP_COMPANY_LINE = "成都双流甄养堂互联网医院有限公司 联系方式:4001667339"
|
||||
_SLIP_ADDRESS_LINE = "地址:四川省成都市双流区黄甲街道黄龙大道二段280号"
|
||||
_SLIP_SIGNATURE_BOUNDS = QSize(64, 20)
|
||||
|
||||
|
||||
def _prescription_signature_size(signature: str, *, is_internal: bool) -> str:
|
||||
bounds = QSize(78, 36) if is_internal else QSize(76, 24)
|
||||
def _prescription_signature_size(signature: str, *, require_png: bool = False) -> str:
|
||||
bounds = _SLIP_SIGNATURE_BOUNDS
|
||||
if require_png and not signature.startswith("data:image/png;base64,iVBORw0KGgo"):
|
||||
return ""
|
||||
if signature.startswith("data:image/") and "," in signature:
|
||||
try:
|
||||
image = QImage.fromData(base64.b64decode(signature.split(",", 1)[1], validate=True))
|
||||
except ValueError:
|
||||
return f'height="{bounds.height()}"'
|
||||
return "" if require_png else f'height="{bounds.height()}"'
|
||||
if not image.isNull():
|
||||
size = image.size()
|
||||
if size.width() > bounds.width() or size.height() > bounds.height():
|
||||
size = size.scaled(bounds, Qt.AspectRatioMode.KeepAspectRatio)
|
||||
return f'width="{max(1, size.width())}" height="{max(1, size.height())}"'
|
||||
return f'height="{bounds.height()}"'
|
||||
return "" if require_png else f'height="{bounds.height()}"'
|
||||
|
||||
|
||||
def render_prescription_html(
|
||||
@@ -5018,12 +5087,17 @@ def render_prescription_html(
|
||||
days_text = f"{source.get('dose_count')}剂"
|
||||
else:
|
||||
days_text = "—"
|
||||
signing = signature_state(prescription)
|
||||
doctor_name = source.get("doctor_name")
|
||||
signer = signing.get("doctor_signer_name")
|
||||
if signing.get("status") in ("signed", "voided") and isinstance(signer, str) and signer.strip():
|
||||
doctor_name = signer.strip()
|
||||
signature = str(source.get("doctor_signature") or "").strip()
|
||||
signature_html = (
|
||||
f'<img class="signature" src="{html.escape(signature, quote=True)}" '
|
||||
f'{_prescription_signature_size(signature, is_internal=is_internal)} alt="医师签名" />'
|
||||
f'{_prescription_signature_size(signature)} alt="医师签名" />'
|
||||
if signature
|
||||
else f'<span class="doctor-name">{esc(source.get("doctor_name"))}</span>'
|
||||
else f'<span class="doctor-name">{esc(doctor_name)}</span>'
|
||||
)
|
||||
|
||||
herb_html = herb_group(main, "主方", "main") + herb_group(aux, aux_title, "aux")
|
||||
@@ -5087,6 +5161,24 @@ def render_prescription_html(
|
||||
f'<td><span class="meta-key">天数:</span> {html.escape(days_text)}</td>'
|
||||
)
|
||||
hospital_colspan = 2
|
||||
review_row = ""
|
||||
reviewer = signing.get("review_signer_name")
|
||||
if review_signature_time(signing) and isinstance(reviewer, str) and reviewer.strip():
|
||||
seal = signing.get("review_signature")
|
||||
seal_size = (
|
||||
_prescription_signature_size(seal, require_png=True)
|
||||
if isinstance(seal, str) else ""
|
||||
)
|
||||
reviewer_html = esc(reviewer)
|
||||
if seal_size:
|
||||
reviewer_html = (
|
||||
f'<img class="signature" src="{html.escape(seal, quote=True)}" '
|
||||
f'{seal_size} alt="{esc(reviewer)}" />'
|
||||
)
|
||||
review_row = (
|
||||
f'<tr><td colspan="{hospital_colspan}">'
|
||||
f'<span class="doctor-title">审核药师</span> {reviewer_html}</td></tr>'
|
||||
)
|
||||
|
||||
family = html.escape(_ensure_slip_fonts())
|
||||
title_html = (
|
||||
@@ -5166,7 +5258,8 @@ body {{ margin:0; padding:{body_padding}; background:{body_background}; color:#1
|
||||
.pharmacy-key {{ color:#1f1f1f; }}
|
||||
.doctor-title {{ margin-right:8px; color:#6b7280; }}
|
||||
.doctor-name {{ font-size:13px; }}
|
||||
.signature {{ max-width:76px; max-height:24px; vertical-align:middle; }}
|
||||
.signature {{ max-width:{_SLIP_SIGNATURE_BOUNDS.width()}px; max-height:{_SLIP_SIGNATURE_BOUNDS.height()}px;
|
||||
vertical-align:middle; }}
|
||||
.meta-key {{ color:#6b7280; margin-right:6px; }}
|
||||
.hospital {{ height:auto; vertical-align:top; padding:10px 12px; font-size:12px;
|
||||
color:#6b7280; line-height:1.65; }}
|
||||
@@ -5201,6 +5294,7 @@ body {{ margin:0; padding:{body_padding}; background:{body_background}; color:#1
|
||||
<table class="bottom" width="100%" cellspacing="0" cellpadding="0"><tr class="{'pharmacy-signoff' if is_internal else ''}">
|
||||
{bottom_row}
|
||||
</tr>
|
||||
{review_row}
|
||||
<tr><td class="hospital" colspan="{hospital_colspan}">
|
||||
{_SLIP_COMPANY_LINE}<br/>{_SLIP_ADDRESS_LINE}
|
||||
</td></tr></table>
|
||||
@@ -5494,6 +5588,155 @@ class _PrescriptionPaperPreview(QTextBrowser):
|
||||
painter.end()
|
||||
|
||||
|
||||
class PrescriptionSigningPreview(QWidget):
|
||||
"""Read-only clinical prescription available alongside the signing workflow."""
|
||||
|
||||
def __init__(self, repository: Any, prescription: Any, *, parent: QWidget | None = None) -> None:
|
||||
super().__init__(parent)
|
||||
self.setObjectName("PrescriptionSigningPreview")
|
||||
self.setAccessibleName("处方预览")
|
||||
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)
|
||||
)
|
||||
self._prescription = _mapping(prescription) if has_full_seed else None
|
||||
self._get_detail = getattr(repository, "get_prescription", None)
|
||||
self._load_generation = 0
|
||||
self._esign = signature_state(prescription)
|
||||
self._has_live_esign_state = False
|
||||
self.paper: _PrescriptionPaperPreview | None = None
|
||||
|
||||
self._layout = QVBoxLayout(self)
|
||||
self._layout.setContentsMargins(0, 0, 0, 0)
|
||||
self._layout.setSpacing(10)
|
||||
heading = QLabel("处方预览", self)
|
||||
heading.setObjectName("PrescriptionSigningHeading")
|
||||
self._layout.addWidget(heading)
|
||||
self._notice = QWidget(self)
|
||||
notice_layout = QVBoxLayout(self._notice)
|
||||
notice_layout.setContentsMargins(4, 4, 4, 4)
|
||||
self.status_label = QLabel(self._notice)
|
||||
self.status_label.setTextFormat(Qt.TextFormat.PlainText)
|
||||
self.status_label.setWordWrap(True)
|
||||
notice_layout.addWidget(self.status_label)
|
||||
self.retry_button = QPushButton("重新加载处方", self._notice)
|
||||
self.retry_button.setAutoDefault(False)
|
||||
self.retry_button.clicked.connect(self._load_or_render)
|
||||
notice_layout.addWidget(self.retry_button, 0, Qt.AlignmentFlag.AlignLeft)
|
||||
notice_layout.addStretch(1)
|
||||
self._layout.addWidget(self._notice, 1)
|
||||
self._load_or_render()
|
||||
|
||||
@staticmethod
|
||||
def _has_clinical_content(prescription: Any) -> bool:
|
||||
herbs = _herb_rows(prescription)
|
||||
return bool(herbs) and all(
|
||||
str(row.get("name") or "").strip() and row.get("dosage") not in (None, "")
|
||||
for row in herbs
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _has_empty_slip(prescription: Any) -> bool:
|
||||
herbs = get_value(prescription, "herbs")
|
||||
return (
|
||||
isinstance(herbs, (list, tuple)) and not herbs
|
||||
and bool(first_value(prescription, "patient_name", "clinical_diagnosis"))
|
||||
)
|
||||
|
||||
def _show_notice(self, message: str, *, retry: bool = False) -> None:
|
||||
if self.paper is not None:
|
||||
self.paper.hide()
|
||||
self.status_label.setText(message)
|
||||
self.retry_button.setVisible(retry)
|
||||
self._notice.show()
|
||||
|
||||
def _load_or_render(self) -> None:
|
||||
if self._prescription is not None:
|
||||
self._render()
|
||||
return
|
||||
prescription_id = self._prescription_id
|
||||
if prescription_id <= 0 or not callable(self._get_detail):
|
||||
self._show_notice("处方明细暂不可用。")
|
||||
return
|
||||
self._load_generation += 1
|
||||
generation = self._load_generation
|
||||
self._show_notice("正在加载处方明细…")
|
||||
run_async(
|
||||
self._get_detail,
|
||||
prescription_id,
|
||||
on_success=lambda result: self._detail_loaded(result, generation),
|
||||
on_error=lambda _error: self._detail_failed(generation),
|
||||
)
|
||||
|
||||
def _detail_loaded(self, result: Any, generation: int) -> None:
|
||||
if not isValid(self) or generation != self._load_generation:
|
||||
return
|
||||
detail_id = _int(str(first_value(result, "id", "prescription_id")))
|
||||
if detail_id != self._prescription_id:
|
||||
self._show_notice("返回的处方与当前处方不匹配,请重试。", retry=True)
|
||||
return
|
||||
if not (self._has_clinical_content(result) or self._has_empty_slip(result)):
|
||||
self._show_notice("未获取到用药明细,请重试。", retry=True)
|
||||
return
|
||||
self._prescription = _mapping(result)
|
||||
if not self._has_live_esign_state:
|
||||
self._esign = signature_state(result) or self._esign
|
||||
self._render()
|
||||
|
||||
def _detail_failed(self, generation: int) -> None:
|
||||
if isValid(self) and generation == self._load_generation:
|
||||
self._show_notice("无法加载处方明细,请重试。", retry=True)
|
||||
|
||||
def _signature_appearance(self, state: Mapping[str, Any]) -> tuple[str, str, str]:
|
||||
prescription = self._prescription or {}
|
||||
doctor = str(prescription.get("doctor_name") or "")
|
||||
if state.get("status") not in ("signed", "voided"):
|
||||
return doctor, "", ""
|
||||
signer = state.get("doctor_signer_name")
|
||||
if isinstance(signer, str) and signer.strip() and not str(prescription.get("doctor_signature") or "").strip():
|
||||
doctor = signer.strip()
|
||||
reviewer = state.get("review_signer_name")
|
||||
reviewer = reviewer.strip() if isinstance(reviewer, str) and review_signature_time(state) else ""
|
||||
seal = state.get("review_signature")
|
||||
return doctor, reviewer, seal if reviewer and isinstance(seal, str) else ""
|
||||
|
||||
def set_esign_state(self, state: Mapping[str, Any]) -> None:
|
||||
previous = self._esign
|
||||
self._esign = dict(state)
|
||||
self._has_live_esign_state = True
|
||||
if (
|
||||
self._prescription is not None
|
||||
and self._signature_appearance(previous) != self._signature_appearance(self._esign)
|
||||
):
|
||||
self._render()
|
||||
|
||||
def _render(self) -> None:
|
||||
if self._prescription is None:
|
||||
return
|
||||
try:
|
||||
content = render_prescription_html(self._prescription | {"esign": self._esign}, variant="internal")
|
||||
if self.paper is None:
|
||||
self.paper = _PrescriptionPaperPreview(self._prescription, self, variant="internal")
|
||||
self.paper.setObjectName("PrescriptionSigningPaper")
|
||||
self.paper.setOpenLinks(False)
|
||||
self.paper.setOpenExternalLinks(False)
|
||||
self.paper.document().setDocumentMargin(0)
|
||||
self.paper.setStyleSheet(
|
||||
"QTextBrowser#PrescriptionSigningPaper { background-color: #F7F7F7; "
|
||||
"border: 1px solid #E4E4E5; padding: 0; }"
|
||||
)
|
||||
self._layout.addWidget(self.paper, 1)
|
||||
vertical_scroll = self.paper.verticalScrollBar()
|
||||
scroll_position = vertical_scroll.value()
|
||||
self.paper.setHtml(content)
|
||||
vertical_scroll.setValue(scroll_position)
|
||||
except Exception:
|
||||
self._show_notice("无法显示处方预览,请重试。", retry=True)
|
||||
return
|
||||
self._notice.hide()
|
||||
self.paper.show()
|
||||
|
||||
|
||||
class PrescriptionDetailDialog(QDialog):
|
||||
diagnosis_requested = Signal(int)
|
||||
orders_requested = Signal(int)
|
||||
@@ -5524,10 +5767,9 @@ class PrescriptionDetailDialog(QDialog):
|
||||
self._saved_original: Path | None = None
|
||||
self.document = QTextDocument(self)
|
||||
self.document.setDocumentMargin(0)
|
||||
self.document.setHtml(render_prescription_html(prescription, variant="internal"))
|
||||
self.user_document = QTextDocument(self)
|
||||
self.user_document.setDocumentMargin(0)
|
||||
self.user_document.setHtml(render_prescription_html(prescription, variant="user"))
|
||||
self._render_slip_previews()
|
||||
self.setWindowTitle("查看处方")
|
||||
self.resize(920, 780)
|
||||
root = QVBoxLayout(self)
|
||||
@@ -5546,6 +5788,10 @@ class PrescriptionDetailDialog(QDialog):
|
||||
self.esign_button.setVisible(self.repository is not None and callable(getattr(self.repository, "get_prescription_esign_status", None)))
|
||||
self.esign_button.clicked.connect(self.open_esign)
|
||||
actions.addWidget(self.esign_button)
|
||||
self.signing_log_button = QPushButton("签署日志", self)
|
||||
self.signing_log_button.setAutoDefault(False)
|
||||
self.signing_log_button.clicked.connect(lambda: SigningLogDialog(self.esign, self).exec())
|
||||
actions.addWidget(self.signing_log_button)
|
||||
actions.addStretch(1)
|
||||
print_button = QPushButton("打印")
|
||||
print_button.clicked.connect(self.print_slip)
|
||||
@@ -5561,31 +5807,7 @@ class PrescriptionDetailDialog(QDialog):
|
||||
root.addLayout(actions)
|
||||
self.status_banner = MessageBanner(parent=self)
|
||||
self.status_banner.setObjectName("PrescriptionDetailStatusBanner")
|
||||
status_lines: list[str] = []
|
||||
if _bool(first_value(prescription, "void_status", "is_void", default=False)):
|
||||
void_by = display_text(first_value(prescription, "void_by_name", default=""), "—")
|
||||
void_time = display_text(first_value(prescription, "void_time", default=""), "—")
|
||||
status_lines.append(f"已作废 作废人:{void_by} {void_time}")
|
||||
audit_status = _int(first_value(prescription, "audit_status", default=-1), -1)
|
||||
audit_label = {0: "待审核", 1: "已通过", 2: "已驳回"}.get(audit_status, "未知")
|
||||
if not status_lines or audit_status == 2:
|
||||
status_lines.append(f"消费者处方审核:{audit_label}")
|
||||
if _bool(first_value(prescription, "business_prescription_audit_rejected", default=False)):
|
||||
status_lines.append("业务订单处方审核:已驳回")
|
||||
banner_kind = (
|
||||
"danger"
|
||||
if _bool(first_value(prescription, "void_status", default=False))
|
||||
or audit_status == 2
|
||||
or _bool(
|
||||
first_value(prescription, "business_prescription_audit_rejected", default=False)
|
||||
)
|
||||
else "success"
|
||||
if audit_status == 1
|
||||
else "warning"
|
||||
if audit_status == 0
|
||||
else "info"
|
||||
)
|
||||
self.status_banner.show_message(" ".join(status_lines), banner_kind)
|
||||
self._render_review_status()
|
||||
root.addWidget(self.status_banner)
|
||||
self.esign_banner = MessageBanner(parent=self)
|
||||
self.esign_banner.label.setTextFormat(Qt.TextFormat.PlainText)
|
||||
@@ -5661,23 +5883,75 @@ class PrescriptionDetailDialog(QDialog):
|
||||
|
||||
def _esign_loaded(self, result: Any) -> None:
|
||||
try:
|
||||
self.esign = esign_status(result)
|
||||
current = esign_status(result)
|
||||
except Exception as error:
|
||||
self._esign_failed(error)
|
||||
return
|
||||
previous = self.esign
|
||||
if review_signature_time(previous) != review_signature_time(current):
|
||||
self._saved_original = None
|
||||
self.esign = current
|
||||
self._esign_unconfirmed = False
|
||||
if any(previous.get(key) != current.get(key) for key in (
|
||||
"status", "doctor_signer_name", "review_signature", "review_signer_name", "review_signature_time",
|
||||
)):
|
||||
self._render_slip_previews()
|
||||
self._render_review_status()
|
||||
self._render_esign_status()
|
||||
self._sync_esign_export()
|
||||
|
||||
def _slip_prescription(self) -> dict[str, Any]:
|
||||
return _mapping(self.prescription) | {"esign": self.esign}
|
||||
|
||||
def _render_slip_previews(self) -> None:
|
||||
prescription = self._slip_prescription()
|
||||
self.document.setHtml(render_prescription_html(prescription, variant="internal"))
|
||||
self.user_document.setHtml(render_prescription_html(prescription, variant="user"))
|
||||
|
||||
def _render_review_status(self) -> None:
|
||||
prescription = self.prescription
|
||||
lines: list[str] = []
|
||||
voided = _bool(first_value(prescription, "void_status", "is_void", default=False))
|
||||
if voided:
|
||||
void_by = display_text(first_value(prescription, "void_by_name", default=""), "—")
|
||||
void_time = display_text(first_value(prescription, "void_time", default=""), "—")
|
||||
lines.append(f"已作废 作废人:{void_by} {void_time}")
|
||||
audit_status = _int(first_value(prescription, "audit_status", default=-1), -1)
|
||||
label, kind = {
|
||||
0: ("待审核", "warning"),
|
||||
1: ("已通过", "success"),
|
||||
2: ("已驳回", "danger"),
|
||||
}.get(audit_status, ("未知", "info"))
|
||||
if audit_status == 0:
|
||||
if awaiting_prescription_upload(prescription, self.esign):
|
||||
label = "待上传处方"
|
||||
elif self.esign.get("required") is True and self.esign.get("status") != "signed":
|
||||
label = "待签名"
|
||||
if not voided or audit_status == 2:
|
||||
lines.append(f"消费者处方审核:{label}")
|
||||
business_rejected = _bool(first_value(prescription, "business_prescription_audit_rejected", default=False))
|
||||
if business_rejected:
|
||||
lines.append("业务订单处方审核:已驳回")
|
||||
self.status_banner.show_message(" ".join(lines), "danger" if voided or business_rejected else kind)
|
||||
|
||||
def _render_esign_status(self) -> None:
|
||||
time_text = signature_time_text(self.esign)
|
||||
if not (self.esign["enabled"] or self.esign["required"] or time_text):
|
||||
self.esign_banner.clear()
|
||||
return
|
||||
status = self.esign["status"]
|
||||
label = str(self.esign.get("status_label") or status)
|
||||
awaiting_upload = awaiting_prescription_upload(self.prescription, self.esign)
|
||||
label = review_signing_status(self.esign, awaiting_upload=awaiting_upload) or str(self.esign.get("status_label") or status)
|
||||
environment = " · 沙箱测试" if self.esign["environment"] == "sandbox" and status != "legacy" else ""
|
||||
status_message = str(self.esign.get("message") or "")
|
||||
if awaiting_upload:
|
||||
if can_upload_prescription(self.repository, self.prescription, self.esign):
|
||||
status_message = (
|
||||
PRESCRIPTION_UPLOAD_BEFORE_SIGNING_PROMPT
|
||||
if self.esign["required"] and status != "signed" else "请点击「上传处方」,提交药师审核。"
|
||||
)
|
||||
else:
|
||||
status_message = status_message or "请开方医生上传处方。"
|
||||
heading = f"电子签署:{label}{environment}"
|
||||
if status_message:
|
||||
heading += f" {status_message}"
|
||||
@@ -5705,11 +5979,15 @@ class PrescriptionDetailDialog(QDialog):
|
||||
original_available = not case_record and allowed and electronic and self._saved_original is not None
|
||||
self.open_original_button.setVisible(original_available)
|
||||
self.open_original_button.setEnabled(original_available and not self._esign_busy)
|
||||
if not self._esign_unconfirmed and self.esign.get("can_sign") is True:
|
||||
if not self._esign_unconfirmed and can_upload_prescription(self.repository, self.prescription, self.esign):
|
||||
self.esign_button.setText("去上传处方")
|
||||
elif (not self._esign_unconfirmed and self.esign.get("can_sign") is True
|
||||
and not awaiting_prescription_upload(self.prescription, self.esign)):
|
||||
self.esign_button.setText("继续开方签名")
|
||||
else:
|
||||
self.esign_button.setText("查看签署状态")
|
||||
self.esign_button.setEnabled(not self._esign_busy)
|
||||
self.signing_log_button.setEnabled(not self._esign_busy and not self._esign_unconfirmed)
|
||||
self.tabs.setEnabled(not self._esign_busy)
|
||||
|
||||
def open_esign(self) -> None:
|
||||
@@ -5729,7 +6007,7 @@ class PrescriptionDetailDialog(QDialog):
|
||||
if self._is_case_record_selected():
|
||||
return render_case_record_image(self.prescription)
|
||||
return render_prescription_slip_image(
|
||||
self.prescription,
|
||||
self._slip_prescription(),
|
||||
variant=self._current_variant(),
|
||||
)
|
||||
|
||||
@@ -6421,6 +6699,7 @@ __all__ = [
|
||||
"PrescriptionEditorDialog",
|
||||
"PrescriptionOrderDialog",
|
||||
"PrescriptionOrderListDialog",
|
||||
"PrescriptionSigningPreview",
|
||||
"PrescriptionTemplateDialog",
|
||||
"RemoteMedicineComboBox",
|
||||
"SignaturePad",
|
||||
|
||||
@@ -46,6 +46,7 @@ from ..widgets import (
|
||||
AI_MODELS: tuple[tuple[str, str, str], ...] = (
|
||||
("qwen", "千问", "qwen3.6-35b"),
|
||||
("openai", "OpenAI", "gpt-5.6-sol"),
|
||||
("doubao", "豆包", "doubao-seed-2.1-pro"),
|
||||
)
|
||||
AI_MODEL_KEYS = frozenset(profile for profile, _label, _name in AI_MODELS)
|
||||
AI_REPORT_EDIT_PERMISSIONS = (
|
||||
|
||||
@@ -4,6 +4,7 @@ from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable, Mapping
|
||||
from hashlib import sha256
|
||||
from html import escape
|
||||
from pathlib import Path
|
||||
from time import monotonic
|
||||
from typing import Any
|
||||
@@ -23,10 +24,14 @@ from PySide6.QtGui import QDesktopServices
|
||||
from PySide6.QtWidgets import (
|
||||
QDialog,
|
||||
QDialogButtonBox,
|
||||
QFrame,
|
||||
QHBoxLayout,
|
||||
QLabel,
|
||||
QLineEdit,
|
||||
QPushButton,
|
||||
QScrollArea,
|
||||
QSplitter,
|
||||
QTextBrowser,
|
||||
QVBoxLayout,
|
||||
QWidget,
|
||||
)
|
||||
@@ -58,6 +63,10 @@ _ESIGN_WRITE_PERMISSIONS = (
|
||||
_SIGNABLE_STATES = ("pending", "authenticating", "failed")
|
||||
_BEIJING_TIME = QTimeZone(b"Asia/Shanghai")
|
||||
_SIGNATURE_TIME_SOURCES = {"tsa": "可信时间戳", "local": "签名记录时间"}
|
||||
_SIGNING_LOG_SOURCES = {**_SIGNATURE_TIME_SOURCES, "system": "系统记录时间"}
|
||||
PRESCRIPTION_UPLOAD_PROMPT = "请在「已开处方」点击「上传处方」,提交药师审核。"
|
||||
PRESCRIPTION_UPLOAD_BEFORE_SIGNING_PROMPT = "请先点击「上传处方」,随后完成医生签署。"
|
||||
_REVIEW_PENDING_MESSAGE = "请有审核权限的药师在管理后台完成电子签署,随后刷新签署状态。"
|
||||
_QUICK_AUTHORIZATION_STATUS = {
|
||||
"missing": "尚未授权快捷签",
|
||||
"expired": "快捷签授权已过期",
|
||||
@@ -100,12 +109,62 @@ def signature_state(prescription: Any) -> dict[str, Any]:
|
||||
return dict(value) if isinstance(value, Mapping) else {}
|
||||
|
||||
|
||||
def review_submission_time(prescription: Any, state: Mapping[str, Any] | None = None) -> int | None:
|
||||
value = first_value(state, "review_submitted_at", default=first_value(prescription, "review_submitted_at"))
|
||||
return value if type(value) is int and value >= 0 else None
|
||||
|
||||
|
||||
def can_upload_prescription(repository: Any, prescription: Any, state: Mapping[str, Any]) -> bool:
|
||||
return (
|
||||
review_submission_time(prescription, state) == 0
|
||||
and first_value(state, "can_submit_for_review", default=first_value(prescription, "can_submit_for_review")) is True
|
||||
and callable(getattr(repository, "submit_prescription_for_review", None))
|
||||
)
|
||||
|
||||
|
||||
def awaiting_prescription_upload(prescription: Any, state: Mapping[str, Any]) -> bool:
|
||||
flag = first_value(state, "awaiting_upload", default=first_value(prescription, "awaiting_upload"))
|
||||
if isinstance(flag, bool):
|
||||
return flag
|
||||
return review_submission_time(prescription, state) == 0 and (
|
||||
state.get("status") in ("signed", "legacy")
|
||||
or first_value(state, "can_submit_for_review", default=first_value(prescription, "can_submit_for_review")) is True
|
||||
)
|
||||
|
||||
|
||||
def can_review_uploaded_prescription(prescription: Any, state: Mapping[str, Any]) -> bool:
|
||||
if review_submission_time(prescription, state) == 0 or awaiting_prescription_upload(prescription, state):
|
||||
return False
|
||||
flag = first_value(state, "can_review_prescription", default=first_value(prescription, "can_review_prescription"))
|
||||
if isinstance(flag, bool):
|
||||
return flag
|
||||
return state.get("required") is not True or state.get("status") == "signed"
|
||||
|
||||
|
||||
def _format_esign_time(value: Any) -> str:
|
||||
if type(value) is not int or not 0 < value <= 253402300799:
|
||||
return ""
|
||||
return QDateTime.fromSecsSinceEpoch(value, _BEIJING_TIME).toString("yyyy-MM-dd HH:mm:ss")
|
||||
|
||||
|
||||
def review_signature_time(state: Mapping[str, Any]) -> str:
|
||||
if state.get("status") not in ("signed", "voided"):
|
||||
return ""
|
||||
return _format_esign_time(state.get("review_signature_time"))
|
||||
|
||||
|
||||
def review_signing_status(state: Mapping[str, Any], *, awaiting_upload: bool = False) -> str:
|
||||
if awaiting_upload and state.get("status") in ("pending", "authenticating", "failed", "uncertain"):
|
||||
return "待上传处方"
|
||||
if state.get("status") != "signed":
|
||||
return ""
|
||||
if review_signature_time(state):
|
||||
return "医生与药师已签署"
|
||||
if awaiting_upload:
|
||||
return "医生已签署,待上传处方"
|
||||
return "医生已签署,待药师签署" if state.get("review_required") is True else ""
|
||||
|
||||
|
||||
def signature_time_text(state: Mapping[str, Any]) -> str:
|
||||
"""Display the archived prescription's issue and signing events separately."""
|
||||
status = state.get("status")
|
||||
@@ -121,22 +180,70 @@ def signature_time_text(state: Mapping[str, Any]) -> str:
|
||||
if QDate.fromString(original_date, date_format).toString(date_format) == original_date:
|
||||
lines.append(f"原件记载日期:{original_date}(未记录开具时分秒)")
|
||||
|
||||
review_time = review_signature_time(state)
|
||||
doctor = "医生" if state.get("review_required") is True or review_time else ""
|
||||
source = _SIGNATURE_TIME_SOURCES.get(str(state.get("signature_time_source")))
|
||||
signature_time = _format_esign_time(state.get("signature_time")) if source else ""
|
||||
if signature_time:
|
||||
lines.append(f"签署时间:{signature_time}(北京时间 · {source})")
|
||||
lines.append(f"{doctor}签署时间:{signature_time}(北京时间 · {source})")
|
||||
else:
|
||||
completed = _format_esign_time(state.get("signed_at"))
|
||||
if completed or status == "signed" or state.get("can_download") is True:
|
||||
lines.append("签署时间待核实")
|
||||
lines.append(f"{doctor}签署时间待核实")
|
||||
if completed:
|
||||
lines.append(f"系统验签完成时间:{completed}(北京时间)")
|
||||
if review_time:
|
||||
name = state.get("review_signer_name")
|
||||
if isinstance(name, str) and name.strip():
|
||||
lines.append(f"签署药师:{name.strip()}")
|
||||
lines.append(f"药师签署时间:{review_time}(北京时间 · 可信时间戳)")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def can_continue_prescription_esign(state: Mapping[str, Any], permissions: Any) -> bool:
|
||||
class SigningLogDialog(QDialog):
|
||||
"""Read-only signing events from the prescription status response."""
|
||||
|
||||
def __init__(self, state: Mapping[str, Any], parent: QWidget) -> None:
|
||||
super().__init__(parent)
|
||||
self.setWindowTitle("签署日志")
|
||||
self.resize(640, 440)
|
||||
self.setStyleSheet(clinical_stylesheet("QDialog { background:#FFFFFF; }"))
|
||||
layout = QVBoxLayout(self)
|
||||
self.entries = QTextBrowser(self)
|
||||
self.entries.setOpenLinks(False)
|
||||
layout.addWidget(self.entries, 1)
|
||||
|
||||
events = state.get("signing_log")
|
||||
rows = []
|
||||
for event in events if isinstance(events, list) else []:
|
||||
if not isinstance(event, Mapping):
|
||||
continue
|
||||
timestamp = _format_esign_time(event.get("time"))
|
||||
label, source = event.get("label"), event.get("source")
|
||||
if not timestamp or not isinstance(label, str) or not isinstance(source, str):
|
||||
continue
|
||||
source_label = _SIGNING_LOG_SOURCES.get(source)
|
||||
if not label.strip() or source_label is None:
|
||||
continue
|
||||
actor = event.get("actor_name")
|
||||
actor = f" · {escape(actor.strip())}" if isinstance(actor, str) and actor.strip() else ""
|
||||
message = event.get("message")
|
||||
message = f"<br/>{escape(message.strip())}" if isinstance(message, str) and message.strip() else ""
|
||||
rows.append(
|
||||
f'<p style="margin:8px 4px 14px;"><b>{escape(label.strip())}</b>{actor}<br/>'
|
||||
f'<span style="color:#526275;">{timestamp}(北京时间 · {source_label})</span>{message}</p>'
|
||||
)
|
||||
self.entries.setHtml("".join(rows) if rows else "<p>暂无签署日志。</p>")
|
||||
close = QDialogButtonBox(QDialogButtonBox.StandardButton.Close, self)
|
||||
close.button(QDialogButtonBox.StandardButton.Close).setText("关闭")
|
||||
close.rejected.connect(self.reject)
|
||||
layout.addWidget(close)
|
||||
|
||||
|
||||
def can_continue_prescription_esign(state: Mapping[str, Any], permissions: Any, prescription: Any = None) -> bool:
|
||||
return (
|
||||
state.get("enabled") is True
|
||||
not awaiting_prescription_upload(prescription, state)
|
||||
and state.get("enabled") is True
|
||||
and state.get("required") is True
|
||||
and (
|
||||
(state.get("status") in _SIGNABLE_STATES and state.get("can_sign") is True)
|
||||
@@ -157,11 +264,19 @@ def saved_prescription_message(prescription: Any, fallback: str) -> tuple[str, s
|
||||
state = esign_status(signature_state(prescription))
|
||||
except Exception:
|
||||
return "处方已保存,电子签署状态尚未确认,请在处方详情查询。", "warning"
|
||||
if awaiting_prescription_upload(prescription, state):
|
||||
if state.get("status") == "signed":
|
||||
return "处方已保存,医生已签署。" + PRESCRIPTION_UPLOAD_PROMPT, "success"
|
||||
if state.get("required") is True:
|
||||
return "处方草稿已保存。" + PRESCRIPTION_UPLOAD_BEFORE_SIGNING_PROMPT, "success"
|
||||
return "处方草稿已保存。" + PRESCRIPTION_UPLOAD_PROMPT, "success"
|
||||
if state.get("required") is True and state.get("status") != "signed":
|
||||
if state.get("verification_method") == "quick":
|
||||
return "处方草稿已保存,尚待完成电子签署。可在处方详情继续签署。", "warning"
|
||||
return "处方草稿已保存,尚待完成电子签署。可在处方详情继续验证身份或签名。", "warning"
|
||||
if state.get("status") == "signed":
|
||||
if state.get("review_required") is True and not review_signature_time(state):
|
||||
return "处方已保存,医生已签署,等待药师签署。", "success"
|
||||
return "处方已保存并完成电子签署,等待审核。", "success"
|
||||
return fallback, "success"
|
||||
|
||||
@@ -171,7 +286,12 @@ def resume_saved_prescription(repository: Any, prescription: Any, parent: QWidge
|
||||
state = esign_status(signature_state(prescription))
|
||||
except Exception:
|
||||
state = {}
|
||||
if state.get("required") is True and state.get("status") != "signed":
|
||||
has_next_step = (
|
||||
can_upload_prescription(repository, prescription, state)
|
||||
if awaiting_prescription_upload(prescription, state)
|
||||
else state.get("required") is True and state.get("status") != "signed"
|
||||
)
|
||||
if has_next_step:
|
||||
dialog = PrescriptionEsignDialog(repository, prescription, parent=parent)
|
||||
dialog.exec()
|
||||
return dialog.state.get("status") == "signed"
|
||||
@@ -190,6 +310,11 @@ class PrescriptionEsignDialog(QDialog):
|
||||
self.repository = repository
|
||||
self.prescription_id = int(first_value(prescription, "id", "prescription_id", default=0) or 0)
|
||||
self._system_placeholder = first_value(prescription, "is_system_auto") in (True, 1, "1")
|
||||
initial_state = signature_state(prescription)
|
||||
self._submission = {
|
||||
key: first_value(initial_state, key, default=first_value(prescription, key))
|
||||
for key in ("review_submitted_at", "awaiting_upload", "can_submit_for_review")
|
||||
}
|
||||
self.state: dict[str, Any] = {}
|
||||
self._saved_original: Path | None = None
|
||||
self._busy = False
|
||||
@@ -213,43 +338,96 @@ class PrescriptionEsignDialog(QDialog):
|
||||
self.poll_timer.timeout.connect(self._poll_identity)
|
||||
self.setWindowTitle("处方电子签署")
|
||||
self.setMinimumSize(900, 700)
|
||||
self.resize(1040, 800)
|
||||
self.setStyleSheet(clinical_stylesheet("QDialog { background:#FFFFFF; }"))
|
||||
layout = QVBoxLayout(self)
|
||||
layout.setContentsMargins(24, 24, 24, 24)
|
||||
layout.setSpacing(12)
|
||||
self.steps = QWidget(self)
|
||||
steps = QHBoxLayout(self.steps)
|
||||
self.resize(1240, 800)
|
||||
self.setStyleSheet(clinical_stylesheet(
|
||||
"QDialog { background: #FFFFFF; }"
|
||||
"QFrame#PrescriptionSigningWorkflow { background: #FFFFFF; border: 1px solid #DFE6EF; border-radius: 10px; }"
|
||||
"QLabel#PrescriptionSigningHeading { font-size: 16px; font-weight: 600; color: #20354E; }"
|
||||
"QScrollArea#PrescriptionSigningDetails { border: 0; background: #FFFFFF; }"
|
||||
"QWidget#PrescriptionSigningStatus { background: #FFFFFF; }"
|
||||
))
|
||||
self._build_workspace(prescription)
|
||||
self.refresh()
|
||||
|
||||
def _build_workspace(self, prescription: Any) -> None:
|
||||
# Prescription details share the same paper renderer as this preview.
|
||||
from .prescription import PrescriptionSigningPreview
|
||||
|
||||
root = QVBoxLayout(self)
|
||||
root.setContentsMargins(20, 20, 20, 20)
|
||||
self.workspace_splitter = QSplitter(Qt.Orientation.Horizontal, self)
|
||||
self.workspace_splitter.setChildrenCollapsible(False)
|
||||
self.workspace_splitter.setHandleWidth(12)
|
||||
root.addWidget(self.workspace_splitter)
|
||||
|
||||
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.workspace_splitter.addWidget(self.prescription_preview)
|
||||
|
||||
self.workflow_panel = QFrame(self.workspace_splitter)
|
||||
self.workflow_panel.setObjectName("PrescriptionSigningWorkflow")
|
||||
self.workflow_panel.setAccessibleName("签署流程")
|
||||
self.workflow_panel.setMinimumWidth(410)
|
||||
self.workspace_splitter.addWidget(self.workflow_panel)
|
||||
self.workspace_splitter.setStretchFactor(0, 3)
|
||||
self.workspace_splitter.setStretchFactor(1, 2)
|
||||
self.workspace_splitter.setSizes([650, 538])
|
||||
|
||||
workflow = QVBoxLayout(self.workflow_panel)
|
||||
workflow.setContentsMargins(16, 14, 16, 14)
|
||||
workflow.setSpacing(10)
|
||||
heading = QLabel("签署流程", self.workflow_panel)
|
||||
heading.setObjectName("PrescriptionSigningHeading")
|
||||
workflow.addWidget(heading)
|
||||
|
||||
# Keep the native identity browser outside the scrollable status area.
|
||||
self.workflow_scroll = QScrollArea(self.workflow_panel)
|
||||
self.workflow_scroll.setObjectName("PrescriptionSigningDetails")
|
||||
self.workflow_scroll.setWidgetResizable(True)
|
||||
self.workflow_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
|
||||
self.workflow_scroll.setMinimumHeight(118)
|
||||
workflow.addWidget(self.workflow_scroll, 1)
|
||||
details = QWidget(self.workflow_scroll)
|
||||
details.setObjectName("PrescriptionSigningStatus")
|
||||
self.workflow_scroll.setWidget(details)
|
||||
info = QVBoxLayout(details)
|
||||
info.setContentsMargins(0, 0, 0, 0)
|
||||
info.setSpacing(8)
|
||||
|
||||
self.steps = QWidget(details)
|
||||
steps = QVBoxLayout(self.steps)
|
||||
steps.setContentsMargins(0, 0, 0, 0)
|
||||
steps.setSpacing(8)
|
||||
steps.setSpacing(5)
|
||||
self.step_labels = []
|
||||
for title in ("处方草稿已保存", "验证医生身份", "签名并完成"):
|
||||
if self.step_labels:
|
||||
steps.addWidget(QLabel("→", self))
|
||||
label = QLabel(title, self)
|
||||
label.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
steps.addWidget(label, 1)
|
||||
for title in ("保存草稿", "上传处方", "验证医生身份", "医生签署", "药师审核"):
|
||||
label = QLabel(title, self.steps)
|
||||
label.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
|
||||
label.setWordWrap(True)
|
||||
steps.addWidget(label)
|
||||
self.step_labels.append(label)
|
||||
layout.addWidget(self.steps)
|
||||
self.review_step_label = self.step_labels[-1]
|
||||
info.addWidget(self.steps)
|
||||
patient = str(first_value(prescription, "patient_name", default="") or "").strip()
|
||||
reference = str(first_value(prescription, "sn", "prescription_no", default="") or "").strip()
|
||||
if patient or reference:
|
||||
summary = QLabel(" · ".join(text for text in (patient, reference) if text), self)
|
||||
summary = QLabel(" · ".join(text for text in (patient, reference) if text), details)
|
||||
summary.setTextFormat(Qt.TextFormat.PlainText)
|
||||
summary.setWordWrap(True)
|
||||
layout.addWidget(summary)
|
||||
self.status_label = QLabel("正在确认签署状态…")
|
||||
info.addWidget(summary)
|
||||
self.status_label = QLabel("正在确认签署状态…", details)
|
||||
self.status_label.setTextFormat(Qt.TextFormat.PlainText)
|
||||
layout.addWidget(self.status_label)
|
||||
self.signature_time_label = QLabel(self)
|
||||
self.status_label.setWordWrap(True)
|
||||
info.addWidget(self.status_label)
|
||||
self.signature_time_label = QLabel(details)
|
||||
self.signature_time_label.setTextFormat(Qt.TextFormat.PlainText)
|
||||
self.signature_time_label.setWordWrap(True)
|
||||
self.signature_time_label.hide()
|
||||
layout.addWidget(self.signature_time_label)
|
||||
self.banner = MessageBanner(parent=self)
|
||||
info.addWidget(self.signature_time_label)
|
||||
self.banner = MessageBanner(parent=details)
|
||||
self.banner.label.setTextFormat(Qt.TextFormat.PlainText)
|
||||
layout.addWidget(self.banner)
|
||||
self.identity_details_container = QWidget(self)
|
||||
info.addWidget(self.banner)
|
||||
self.identity_details_container = QWidget(details)
|
||||
details_layout = QVBoxLayout(self.identity_details_container)
|
||||
details_layout.setContentsMargins(0, 0, 0, 0)
|
||||
details_hint = QLabel(
|
||||
@@ -265,8 +443,8 @@ class PrescriptionEsignDialog(QDialog):
|
||||
self.identity_number_input.setInputMethodHints(Qt.InputMethodHint.ImhSensitiveData | Qt.InputMethodHint.ImhNoPredictiveText)
|
||||
details_layout.addWidget(self.identity_number_input)
|
||||
self.identity_details_container.hide()
|
||||
layout.addWidget(self.identity_details_container)
|
||||
self.sms_container = QWidget(self)
|
||||
info.addWidget(self.identity_details_container)
|
||||
self.sms_container = QWidget(details)
|
||||
sms_layout = QVBoxLayout(self.sms_container)
|
||||
sms_layout.setContentsMargins(0, 0, 0, 0)
|
||||
sms_label = QLabel("本张处方的短信验证码", self.sms_container)
|
||||
@@ -282,12 +460,20 @@ class PrescriptionEsignDialog(QDialog):
|
||||
sms_layout.addWidget(sms_label)
|
||||
sms_layout.addWidget(self.sms_code_input)
|
||||
self.sms_container.hide()
|
||||
layout.addWidget(self.sms_container)
|
||||
self.identity_container = QWidget(self)
|
||||
info.addWidget(self.sms_container)
|
||||
info.addStretch(1)
|
||||
|
||||
self.identity_container = QWidget(self.workflow_panel)
|
||||
self.identity_container.setMinimumHeight(240)
|
||||
self.identity_layout = QVBoxLayout(self.identity_container)
|
||||
self.identity_layout.setContentsMargins(0, 0, 0, 0)
|
||||
layout.addWidget(self.identity_container, 1)
|
||||
footer = QHBoxLayout()
|
||||
self.identity_container.hide()
|
||||
workflow.addWidget(self.identity_container, 2)
|
||||
|
||||
actions = QVBoxLayout()
|
||||
actions.setSpacing(6)
|
||||
self.upload_button = QPushButton("上传处方")
|
||||
self.upload_button.clicked.connect(self.upload)
|
||||
self.start_button = QPushButton("开始验证")
|
||||
self.start_button.clicked.connect(self.start)
|
||||
self.complete_button = QPushButton("继续验证")
|
||||
@@ -306,36 +492,49 @@ class PrescriptionEsignDialog(QDialog):
|
||||
self.open_original_button = QPushButton("打开已保存原件")
|
||||
self.open_original_button.clicked.connect(self._open_saved_original)
|
||||
self._action_buttons = (
|
||||
self.start_button, self.complete_button, self.sign_button, self.doctor_identity_button,
|
||||
self.upload_button, self.start_button, self.complete_button, self.sign_button, self.doctor_identity_button,
|
||||
self.refresh_button, self.verify_button, self.download_button, self.open_original_button,
|
||||
)
|
||||
for button in self._action_buttons:
|
||||
button.setAutoDefault(False)
|
||||
footer.addWidget(button)
|
||||
actions.addWidget(button)
|
||||
workflow.addLayout(actions)
|
||||
footer = QHBoxLayout()
|
||||
footer.addStretch(1)
|
||||
self.signing_log_button = QPushButton("签署日志", self.workflow_panel)
|
||||
self.signing_log_button.setAutoDefault(False)
|
||||
self.signing_log_button.clicked.connect(lambda: SigningLogDialog(self.state, self).exec())
|
||||
footer.addWidget(self.signing_log_button)
|
||||
self.close_buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Close)
|
||||
self.close_buttons.button(QDialogButtonBox.StandardButton.Close).setText("关闭")
|
||||
self.close_buttons.button(QDialogButtonBox.StandardButton.Close).setAutoDefault(False)
|
||||
self.close_buttons.rejected.connect(self.reject)
|
||||
footer.addWidget(self.close_buttons)
|
||||
layout.addLayout(footer)
|
||||
self.refresh()
|
||||
workflow.addLayout(footer)
|
||||
|
||||
def _sync_actions(self) -> None:
|
||||
available = not self._busy and not self._closed and not self._native_hide_pending
|
||||
status = self.state.get("status")
|
||||
requires_review = self.state.get("review_required") is True
|
||||
review_done = bool(review_signature_time(self.state))
|
||||
review_pending = status == "signed" and requires_review and not review_done
|
||||
legacy = self._confirmed and status == "legacy" and self.state.get("required") is False
|
||||
incomplete = self._confirmed and self._needs_prescription_content()
|
||||
awaiting_upload = self._awaiting_upload()
|
||||
signer = self._confirmed and self._can_sign() and not self._completion_sent
|
||||
restart = self.state.get("identity_status") in {"FAIL", "EXPIRED"}
|
||||
main = None if legacy or incomplete else self.refresh_button
|
||||
secondary = None
|
||||
sms_input = False
|
||||
if self._confirmed and status in {"signed", "voided"} and self.state.get("can_download") is True:
|
||||
if self._confirmed and self._can_upload():
|
||||
main = self.upload_button
|
||||
if status == "signed" and self.state.get("can_download") is True:
|
||||
secondary = self.download_button
|
||||
elif self._confirmed and status in {"signed", "voided"} and self.state.get("can_download") is True:
|
||||
main = self.download_button
|
||||
if self._saved_original is not None:
|
||||
secondary = self.open_original_button
|
||||
elif (self._confirmed and status == "uncertain"
|
||||
elif (self._confirmed and not awaiting_upload and status == "uncertain"
|
||||
and all(self.state.get(key) is True for key in ("enabled", "required", "can_retry_verify"))):
|
||||
main, secondary = self.verify_button, self.refresh_button
|
||||
elif signer:
|
||||
@@ -379,7 +578,9 @@ class PrescriptionEsignDialog(QDialog):
|
||||
else:
|
||||
self.refresh_button.setText("查询签署结果" if self._completion_sent or status in {"signing", "signed", "uncertain"} else "重试查询状态")
|
||||
for button in self._action_buttons:
|
||||
active = button in (main, secondary) or (sms_input and button is self.refresh_button)
|
||||
active = button in (main, secondary) or (
|
||||
(sms_input or review_pending) and button is self.refresh_button
|
||||
)
|
||||
button.setVisible(active)
|
||||
button.setEnabled(active and available)
|
||||
variant = "primary" if button is main else None
|
||||
@@ -392,29 +593,45 @@ class PrescriptionEsignDialog(QDialog):
|
||||
self.sms_code_input.setText("")
|
||||
self.sms_container.setVisible(sms_input)
|
||||
self.sms_code_input.setEnabled(available and sms_input)
|
||||
self.steps.setVisible(self._confirmed and not legacy and not incomplete)
|
||||
self.steps.setVisible(self._confirmed and (not legacy or awaiting_upload) and not incomplete)
|
||||
self.signing_log_button.setEnabled(self._confirmed and available)
|
||||
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))
|
||||
|
||||
finished = status == "signed"
|
||||
signing = self._identity_ready or self._completion_sent or status in {"signing", "uncertain", "signed"}
|
||||
self.step_labels[1].setText("核对快捷签授权" if self._uses_quick() else
|
||||
doctor_done = status == "signed" or (
|
||||
status == "voided" and (self.state.get("can_download") is True or review_done)
|
||||
)
|
||||
signing = self._identity_ready or self._completion_sent or status in {"signing", "uncertain"}
|
||||
self.step_labels[2].setText("核对快捷签授权" if self._uses_quick() else
|
||||
"短信确认签署意愿" if self._uses_sms() else "验证医生身份")
|
||||
for index, label in enumerate(self.step_labels):
|
||||
complete = index == 0 or finished or (index == 1 and signing)
|
||||
current = not complete and index == (2 if signing else 1)
|
||||
self.review_step_label.setText("药师审核签署" if requires_review or review_done else "药师审核")
|
||||
uses_upload = review_submission_time(self._submission, self.state) is not None
|
||||
visible_steps = (True, uses_upload, not legacy, not legacy, uses_upload or requires_review or review_done)
|
||||
completed_steps = (True, not awaiting_upload, signing or doctor_done, doctor_done, review_done)
|
||||
current_seen = status == "voided"
|
||||
for label, visible, complete in zip(self.step_labels, visible_steps, completed_steps, strict=True):
|
||||
label.setVisible(visible)
|
||||
current = visible and not complete and not current_seen
|
||||
current_seen = current_seen or current
|
||||
color, background = (("#146452", "#E6F4EF") if complete else
|
||||
("#174B79", "#E9F2FC") if current else ("#526275", "#F2F5F8"))
|
||||
label.setStyleSheet(f"padding: 10px 8px; border-radius: 6px; color: {color}; background: {background};")
|
||||
label.setStyleSheet(f"padding: 6px 10px; border-radius: 6px; color: {color}; background: {background};")
|
||||
label.setAccessibleDescription("已完成" if complete else "当前步骤" if current else "待完成")
|
||||
|
||||
def _awaiting_upload(self) -> bool:
|
||||
return awaiting_prescription_upload(self._submission, self.state)
|
||||
|
||||
def _can_upload(self) -> bool:
|
||||
return can_upload_prescription(self.repository, self._submission, self.state)
|
||||
|
||||
def _can_sign(self) -> bool:
|
||||
return (self.state.get("status") in _SIGNABLE_STATES
|
||||
return (not self._awaiting_upload() and self.state.get("status") in _SIGNABLE_STATES
|
||||
and all(self.state.get(key) is True for key in ("enabled", "required", "can_sign")))
|
||||
|
||||
def _needs_prescription_content(self) -> bool:
|
||||
return self._system_placeholder and self.state.get("status") in {"legacy", "pending"} and not self._can_sign()
|
||||
return (self._system_placeholder and self.state.get("status") in {"legacy", "pending"}
|
||||
and not self._can_upload() and not self._can_sign())
|
||||
|
||||
def _uses_sms(self) -> bool:
|
||||
return self.state.get("verification_method") == "sms"
|
||||
@@ -445,6 +662,7 @@ class PrescriptionEsignDialog(QDialog):
|
||||
view.stop()
|
||||
self.identity_layout.removeWidget(view)
|
||||
view.deleteLater()
|
||||
self.identity_container.hide()
|
||||
|
||||
def _stop_flow(self) -> None:
|
||||
self.poll_timer.stop()
|
||||
@@ -522,7 +740,11 @@ class PrescriptionEsignDialog(QDialog):
|
||||
self._identity_native_window_id = None
|
||||
|
||||
def _apply_state(self, result: Any, *, after_sign: bool = False) -> None:
|
||||
self.state = esign_status(result)
|
||||
state = esign_status(result)
|
||||
if review_signature_time(self.state) != review_signature_time(state):
|
||||
self._saved_original = None
|
||||
self.state = state
|
||||
self._submission.update({key: state[key] for key in self._submission if key in state})
|
||||
self._confirmed = True
|
||||
status = self.state["status"]
|
||||
self._retry_identity = False
|
||||
@@ -543,12 +765,32 @@ class PrescriptionEsignDialog(QDialog):
|
||||
label, message = "签署结果待确认", "请查询签署结果。"
|
||||
if status == "legacy" and not self.state["required"]:
|
||||
label = "沿用原有处方流程" if self.state["enabled"] else "电子签署功能已关闭"
|
||||
if self._awaiting_upload():
|
||||
label = "待上传处方"
|
||||
self.status_label.setText(label)
|
||||
message = "此处方沿用原有处方流程。您可关闭此窗口,返回处方详情或列表。"
|
||||
if self.state.get("can_review_prescription") is True:
|
||||
message = "处方已上传,等待药师审核。"
|
||||
else:
|
||||
self._show_status("签名已完成" if status == "signed" else label)
|
||||
review_status = review_signing_status(self.state, awaiting_upload=self._awaiting_upload())
|
||||
self._show_status(review_status or ("签名已完成" if status == "signed" else label))
|
||||
if review_status:
|
||||
if review_signature_time(self.state):
|
||||
message = "医生和药师的签名均已验签。"
|
||||
elif not self._awaiting_upload():
|
||||
server_message = self.state.get("message")
|
||||
message = f"{server_message}\n{_REVIEW_PENDING_MESSAGE}" if server_message else _REVIEW_PENDING_MESSAGE
|
||||
if self._needs_prescription_content():
|
||||
message = "此处方由系统占号生成。请开方医生先返回列表,编辑并补全处方内容。"
|
||||
elif self._awaiting_upload():
|
||||
if self._can_upload():
|
||||
message = (
|
||||
PRESCRIPTION_UPLOAD_BEFORE_SIGNING_PROMPT
|
||||
if self.state["required"] and status != "signed"
|
||||
else "请点击「上传处方」,提交药师审核。"
|
||||
)
|
||||
else:
|
||||
message = str(self.state.get("message") or "请开方医生上传处方。")
|
||||
elif self._can_sign() and self._needs_quick_account_setup():
|
||||
if self.state.get("doctor_identity_required") is True:
|
||||
if "signing_authorization_required" in self.state:
|
||||
@@ -597,6 +839,8 @@ class PrescriptionEsignDialog(QDialog):
|
||||
self._retry_identity = True
|
||||
self._show_status("身份验证状态待确认")
|
||||
self.banner.show_message(f"{friendly_error(error)} 请重试验证状态。", "warning")
|
||||
elif method == "submit_prescription_for_review":
|
||||
self.banner.show_message(f"{friendly_error(error)} 可重试上传处方。", "warning")
|
||||
else:
|
||||
self._confirmed = False
|
||||
self.status_label.setText("签署结果尚未确认" if self._completion_sent else "处方签署状态尚未确认")
|
||||
@@ -622,6 +866,7 @@ class PrescriptionEsignDialog(QDialog):
|
||||
self._busy = True
|
||||
generation = self._generation
|
||||
proof_supplied = bool(identity_number)
|
||||
upload_confirmed = False
|
||||
self._sync_actions()
|
||||
repository, prescription_id = self.repository, self.prescription_id
|
||||
|
||||
@@ -629,12 +874,23 @@ class PrescriptionEsignDialog(QDialog):
|
||||
return isValid(self) and not self._closed and self._generation == generation
|
||||
|
||||
def loaded(result: Any) -> None:
|
||||
nonlocal upload_confirmed
|
||||
if not current():
|
||||
return
|
||||
if self._native_hide_pending:
|
||||
QTimer.singleShot(0, lambda: loaded(result))
|
||||
return
|
||||
try:
|
||||
if method == "submit_prescription_for_review":
|
||||
submitted_at = review_submission_time(result)
|
||||
if not submitted_at or first_value(result, "can_submit_for_review") is not False:
|
||||
raise ValueError("处方上传结果格式不正确")
|
||||
self._apply_state({
|
||||
**self.state, "review_submitted_at": submitted_at, "awaiting_upload": False,
|
||||
"can_submit_for_review": False, "can_sign": False, "can_retry_verify": False,
|
||||
})
|
||||
upload_confirmed = True
|
||||
return
|
||||
readiness_query = method in {"get_prescription_esign_identity_status", "verify_prescription_esign_willingness"}
|
||||
if readiness_query:
|
||||
result = esign_identity_status(result)
|
||||
@@ -678,7 +934,9 @@ class PrescriptionEsignDialog(QDialog):
|
||||
self._sync_actions()
|
||||
if not current():
|
||||
return
|
||||
if method == "get_prescription_esign_status":
|
||||
if upload_confirmed:
|
||||
self.refresh()
|
||||
elif method == "get_prescription_esign_status":
|
||||
self._check_retained_identity()
|
||||
elif (method == "get_prescription_esign_identity_status" and check_only and self._uses_quick()
|
||||
and self.state.get("identity_status") in {"FAIL", "EXPIRED"}):
|
||||
@@ -713,6 +971,10 @@ class PrescriptionEsignDialog(QDialog):
|
||||
self._stop_flow()
|
||||
self._request("get_prescription_esign_status")
|
||||
|
||||
def upload(self) -> None:
|
||||
if self.upload_button.isEnabled() and self.isVisible():
|
||||
self._request("submit_prescription_for_review")
|
||||
|
||||
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):
|
||||
@@ -752,6 +1014,7 @@ class PrescriptionEsignDialog(QDialog):
|
||||
view.failed.connect(lambda message, source=view: self._web_failed(source, message))
|
||||
view.initialized.connect(lambda source=view: self._identity_native_ready(source))
|
||||
self.identity_layout.addWidget(self.identity_view)
|
||||
self.identity_container.show()
|
||||
except Exception as error:
|
||||
self._stop_flow()
|
||||
self.banner.show_message(friendly_error(error), "warning")
|
||||
@@ -971,8 +1234,8 @@ class PrescriptionEsignDialog(QDialog):
|
||||
def saved(result: tuple[dict[str, Any], Path | None]) -> None:
|
||||
if current():
|
||||
state, output = result
|
||||
self._apply_state(state)
|
||||
if output is None:
|
||||
self._apply_state(state)
|
||||
return
|
||||
if path is None:
|
||||
self._saved_original = output
|
||||
|
||||
@@ -2039,8 +2039,8 @@ class AppointmentsPage(QWidget):
|
||||
return
|
||||
message, kind = saved_prescription_message(prescription, "处方已保存并重新进入待审核。")
|
||||
self.banner.show_message(message, kind)
|
||||
self.refresh(silent=True)
|
||||
resume_saved_prescription(self.repository, prescription, self)
|
||||
self.refresh(silent=True)
|
||||
|
||||
def _after_prescription_void(self) -> None:
|
||||
show_toast(self, "处方已作废。需要再次开具时,请选择「重新开方」。", "success")
|
||||
@@ -2167,8 +2167,8 @@ class AppointmentsPage(QWidget):
|
||||
return
|
||||
message, kind = saved_prescription_message(prescription, "处方已开具并提交审核。")
|
||||
self.banner.show_message(message, kind)
|
||||
self.refresh(silent=True)
|
||||
resume_saved_prescription(self.repository, prescription, self)
|
||||
self.refresh(silent=True)
|
||||
|
||||
def _prescription_error(self, error: Exception, generation: int) -> None:
|
||||
if generation == self._prescription_generation:
|
||||
|
||||
@@ -3464,8 +3464,8 @@ class ConsultationsPage(QWidget):
|
||||
def _prescription_saved(self, prescription: Any, fallback: str) -> None:
|
||||
message, kind = saved_prescription_message(prescription, fallback)
|
||||
show_toast(self, message, kind)
|
||||
self.refresh(silent=True)
|
||||
resume_saved_prescription(self.repository, prescription, self)
|
||||
self.refresh(silent=True)
|
||||
|
||||
def _after_prescription_void(self) -> None:
|
||||
show_toast(self, "处方已作废。需要再次开具时,请选择「重新开方」。", "success")
|
||||
|
||||
@@ -55,7 +55,13 @@ from ..design_system import PALETTE, clinical_stylesheet
|
||||
from ..dialogs import DiagnosisDialog, present_ai_consult, present_order_detail
|
||||
from ..dialogs.ai_consult import can_open_ai_consult
|
||||
from ..dialogs.prescription import PrescriptionOrderListDialog
|
||||
from ..dialogs.prescription_esign import PrescriptionEsignDialog, can_continue_prescription_esign
|
||||
from ..dialogs.prescription_esign import (
|
||||
PrescriptionEsignDialog,
|
||||
can_continue_prescription_esign,
|
||||
can_review_uploaded_prescription,
|
||||
review_signature_time,
|
||||
review_submission_time,
|
||||
)
|
||||
from ..filter_disclosure import FilterDisclosure
|
||||
from ..infinite_list import InfiniteList
|
||||
from ..patient_orders_style import patient_orders_stylesheet
|
||||
@@ -2679,6 +2685,7 @@ class PatientOrdersWorkspace(QWidget):
|
||||
allowed("tcm.prescriptionOrder/auditPrescription")
|
||||
and rx_audit == 0
|
||||
and fulfillment not in {3, 4, 6}
|
||||
and can_review_uploaded_prescription(row, {})
|
||||
):
|
||||
actions.append(("audit_prescription", "处方审核", False))
|
||||
if (
|
||||
@@ -3687,13 +3694,19 @@ class PatientsPage(QWidget):
|
||||
def checked(state: dict[str, Any]) -> None:
|
||||
if self._order_review_generation != generation:
|
||||
return
|
||||
if review_submission_time(row, state) == 0:
|
||||
self.order_workspace.banner.show_message("请开方医生上传处方后再审核。", "warning")
|
||||
return
|
||||
verified = state["required"] and state["status"] == "signed" and state["can_download"]
|
||||
historical = not state["required"] and state["status"] == "legacy" and not state["can_download"]
|
||||
if verified and state.get("review_required") is True and not review_signature_time(state):
|
||||
self.order_workspace.banner.show_message("请先在管理后台完成药师审核签署,再提交审核通过。", "warning")
|
||||
return
|
||||
if verified or historical:
|
||||
self.order_workspace.banner.clear()
|
||||
self._submit_order_audit(order_id, prescription=True, action="approve")
|
||||
return
|
||||
if can_continue_prescription_esign(state, self.permissions):
|
||||
if can_continue_prescription_esign(state, self.permissions, row):
|
||||
dialog = PrescriptionEsignDialog(self.repository, {"id": prescription_id, "esign": state}, parent=self)
|
||||
dialog.exec()
|
||||
self.order_workspace.banner.show_message("请在签署验签通过后,再点击处方审核。", "info")
|
||||
|
||||
@@ -92,8 +92,13 @@ from ..dialogs.prescription import (
|
||||
)
|
||||
from ..dialogs.prescription_esign import (
|
||||
PrescriptionEsignDialog,
|
||||
awaiting_prescription_upload,
|
||||
can_continue_prescription_esign,
|
||||
can_review_uploaded_prescription,
|
||||
can_upload_prescription,
|
||||
resume_saved_prescription,
|
||||
review_signature_time,
|
||||
review_submission_time,
|
||||
saved_prescription_message,
|
||||
signature_state,
|
||||
)
|
||||
@@ -357,7 +362,7 @@ class _RowDecorationDelegate(QStyledItemDelegate):
|
||||
|
||||
|
||||
def _row_action_button(
|
||||
kind: str,
|
||||
kind: str | None,
|
||||
tooltip: str,
|
||||
callback: Callable[[], None],
|
||||
parent: QWidget,
|
||||
@@ -379,8 +384,9 @@ def _row_action_button(
|
||||
button.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||
width = max(64, button.fontMetrics().horizontalAdvance(label) + 26) if label else 28
|
||||
button.setFixedSize(width, 28)
|
||||
button.setIcon(_painted_icon(kind, "danger" if danger else "accent", 15))
|
||||
button.setIconSize(QSize(15, 15))
|
||||
if kind:
|
||||
button.setIcon(_painted_icon(kind, "danger" if danger else "accent", 15))
|
||||
button.setIconSize(QSize(15, 15))
|
||||
button.setEnabled(enabled)
|
||||
button.clicked.connect(callback)
|
||||
return button
|
||||
@@ -439,6 +445,8 @@ def prescription_status(row: Any) -> tuple[str, str]:
|
||||
if status == 1:
|
||||
return "已通过", "success"
|
||||
signature = signature_state(row)
|
||||
if awaiting_prescription_upload(row, signature) and not _voided(row):
|
||||
return "待上传处方", "warning"
|
||||
if signature.get("required") is True and signature.get("status") not in {"signed", "voided"}:
|
||||
if signature.get("status") == "signing":
|
||||
return "签名处理中", "warning"
|
||||
@@ -474,8 +482,7 @@ def _is_pending_audit(row: Any) -> bool:
|
||||
|
||||
|
||||
def can_audit(row: Any) -> bool:
|
||||
signature = signature_state(row)
|
||||
return _is_pending_audit(row) and (signature.get("required") is not True or signature.get("status") == "signed")
|
||||
return _is_pending_audit(row) and can_review_uploaded_prescription(row, signature_state(row))
|
||||
|
||||
|
||||
def can_edit_or_delete(row: Any) -> bool:
|
||||
@@ -1442,6 +1449,8 @@ class PrescriptionsPage(QWidget):
|
||||
toolbar.addWidget(self.create_order_button)
|
||||
self.edit_button = self._action_button("编辑", "cf.prescription/edit", self._edit_selected)
|
||||
toolbar.addWidget(self.edit_button)
|
||||
self.upload_button = self._action_button("上传处方", None, self._upload_selected)
|
||||
toolbar.addWidget(self.upload_button)
|
||||
self.audit_button = self._action_button(
|
||||
"审核", "cf.prescription/audit", self._audit_selected
|
||||
)
|
||||
@@ -1602,6 +1611,7 @@ class PrescriptionsPage(QWidget):
|
||||
"编辑": "pencil",
|
||||
"删除": "trash",
|
||||
"重新开方": "plus",
|
||||
"上传处方": "send",
|
||||
}.get(text)
|
||||
if icon_kind:
|
||||
button.setIcon(
|
||||
@@ -1827,6 +1837,14 @@ class PrescriptionsPage(QWidget):
|
||||
actions_host, label="AI",
|
||||
)
|
||||
)
|
||||
if self._can_upload(row):
|
||||
actions.addWidget(
|
||||
_row_action_button(
|
||||
None, "上传处方",
|
||||
lambda _checked=False, target=row: self._run_row_action(target, self._upload_selected),
|
||||
actions_host, label="上传处方", mutation=True,
|
||||
)
|
||||
)
|
||||
can_reissue = self._can_reissue(row)
|
||||
can_change = _can_change_issued_prescription(row)
|
||||
show_changes = can_change or not _voided(row)
|
||||
@@ -2155,11 +2173,17 @@ class PrescriptionsPage(QWidget):
|
||||
can_change = _can_change_issued_prescription(row)
|
||||
self.edit_button.setEnabled(active and can_change)
|
||||
pending_audit = _is_pending_audit(row)
|
||||
can_review = has_permission(self.permissions, "cf.prescription/audit")
|
||||
can_sign = pending_audit and can_continue_prescription_esign(signature_state(row), self.permissions)
|
||||
state = signature_state(row)
|
||||
can_sign = pending_audit and can_continue_prescription_esign(state, self.permissions, row)
|
||||
can_review = has_permission(self.permissions, "cf.prescription/audit") and can_audit(row)
|
||||
can_upload = self._can_upload(row)
|
||||
self.upload_button.setVisible(can_upload)
|
||||
self.upload_button.setEnabled(active and can_upload)
|
||||
self.audit_button.setText("继续签署" if can_sign else "审核")
|
||||
self.audit_button.setVisible(can_review or can_sign)
|
||||
self.audit_button.setEnabled(active and not self._audit_check_pending and pending_audit and (can_review or can_sign))
|
||||
self.audit_button.setVisible(can_sign or can_review)
|
||||
self.audit_button.setEnabled(
|
||||
active and not self._audit_check_pending and (can_sign or can_review)
|
||||
)
|
||||
can_void = self._can_void(row)
|
||||
self.void_button.setVisible(can_void)
|
||||
self.void_button.setEnabled(active and can_void)
|
||||
@@ -2174,6 +2198,12 @@ class PrescriptionsPage(QWidget):
|
||||
def _can_reissue(self, row: Any) -> bool:
|
||||
return can_reissue_prescription(row, self.current_user, self.permissions)
|
||||
|
||||
def _can_upload(self, row: Any) -> bool:
|
||||
return (
|
||||
_is_pending_audit(row)
|
||||
and can_upload_prescription(self.repository, row, signature_state(row))
|
||||
)
|
||||
|
||||
def _set_mutation_pending(self, pending: bool) -> None:
|
||||
self._mutation_pending = pending
|
||||
self.add_button.setEnabled(not pending)
|
||||
@@ -2257,8 +2287,11 @@ class PrescriptionsPage(QWidget):
|
||||
)
|
||||
dialog.diagnosis_requested.connect(self._open_diagnosis)
|
||||
dialog.orders_requested.connect(lambda prescription_id: self._open_orders(prescription_id))
|
||||
submitted_at = review_submission_time(detail, dialog.esign)
|
||||
dialog.exec()
|
||||
if not was_signed and dialog.esign.get("status") == "signed":
|
||||
if review_submission_time(detail, dialog.esign) != submitted_at or (
|
||||
not was_signed and dialog.esign.get("status") == "signed"
|
||||
):
|
||||
self.refresh()
|
||||
|
||||
def _open_diagnosis(self, diagnosis_id: int) -> None:
|
||||
@@ -2439,9 +2472,10 @@ class PrescriptionsPage(QWidget):
|
||||
message, kind = saved_prescription_message(prescription, fallback)
|
||||
self.banner.show_message(message, kind)
|
||||
show_toast(self, message, kind, 3600)
|
||||
self.refresh()
|
||||
if resume_saved_prescription(self.repository, prescription, self):
|
||||
self._mutation_success("电子签署已完成,处方等待审核。")
|
||||
self._mutation_success("医生签署已完成,等待药师审核。")
|
||||
else:
|
||||
self.refresh()
|
||||
|
||||
def _delete_selected(self) -> None:
|
||||
row = self._selected()
|
||||
@@ -2498,14 +2532,37 @@ class PrescriptionsPage(QWidget):
|
||||
on_finished=lambda: self._set_mutation_pending(False),
|
||||
)
|
||||
|
||||
def _upload_selected(self) -> None:
|
||||
row = self._selected()
|
||||
if self._mutation_pending or not self._can_upload(row):
|
||||
return
|
||||
prescription_id = _int(first_value(row, "id", "prescription_id"), 0)
|
||||
if prescription_id <= 0:
|
||||
self.banner.show_message("处方 ID 无效,请刷新列表后重试。", "warning")
|
||||
return
|
||||
state = signature_state(row)
|
||||
message = (
|
||||
"处方已上传,请点击「继续签署」。"
|
||||
if state.get("required") is True and state.get("status") != "signed"
|
||||
else "处方已上传,等待药师审核。"
|
||||
)
|
||||
self._set_mutation_pending(True)
|
||||
run_async(
|
||||
lambda: self.repository.submit_prescription_for_review(prescription_id),
|
||||
on_success=lambda _result: self._mutation_success(message),
|
||||
on_error=self._mutation_error,
|
||||
on_finished=lambda: self._set_mutation_pending(False),
|
||||
)
|
||||
|
||||
def _audit_selected(self) -> None:
|
||||
row = self._selected()
|
||||
if self._mutation_pending or self._audit_check_pending or not _is_pending_audit(row):
|
||||
return
|
||||
can_review = has_permission(self.permissions, "cf.prescription/audit")
|
||||
signing_action = can_continue_prescription_esign(signature_state(row), self.permissions)
|
||||
if not (can_review or signing_action):
|
||||
return
|
||||
local_state = signature_state(row)
|
||||
signing_action = can_continue_prescription_esign(local_state, self.permissions, row)
|
||||
if not (signing_action or (can_review and can_audit(row))):
|
||||
return
|
||||
prescription_id = _int(first_value(row, "id", "prescription_id"), 0)
|
||||
if prescription_id <= 0:
|
||||
self.banner.show_message("处方 ID 无效,请刷新列表后重试。", "warning")
|
||||
@@ -2523,25 +2580,28 @@ class PrescriptionsPage(QWidget):
|
||||
or _int(first_value(selected, "id", "prescription_id"), 0) != prescription_id
|
||||
):
|
||||
return
|
||||
if can_continue_prescription_esign(state, self.permissions):
|
||||
if can_continue_prescription_esign(state, self.permissions, selected):
|
||||
draft = {**_row_mapping(selected), "id": prescription_id, "esign": state}
|
||||
dialog = PrescriptionEsignDialog(self.repository, draft, parent=self)
|
||||
dialog.exec()
|
||||
if dialog.state.get("status") == "signed":
|
||||
self._mutation_success("电子签署已完成,处方等待审核。")
|
||||
self._mutation_success("医生签署已完成,等待药师审核。")
|
||||
return
|
||||
status = state["status"]
|
||||
if (state["required"] and status == "signed") or (not state["required"] and status == "legacy"):
|
||||
eligible_status = (state["required"] and status == "signed") or (not state["required"] and status == "legacy")
|
||||
if eligible_status and can_review_uploaded_prescription(selected, state):
|
||||
if signing_action:
|
||||
if status == "signed":
|
||||
self._mutation_success("电子签署已完成,处方等待审核。")
|
||||
self._mutation_success("医生签署已完成,等待药师审核。")
|
||||
else:
|
||||
self.refresh()
|
||||
elif can_review:
|
||||
self._open_audit_dialog(selected)
|
||||
self._open_audit_dialog(selected, state)
|
||||
return
|
||||
if status == "voided":
|
||||
message = "处方已作废,请刷新列表。"
|
||||
elif awaiting_prescription_upload(selected, state) or review_submission_time(selected, state) == 0:
|
||||
message = "请开方医生上传处方后再审核。"
|
||||
elif _truthy(first_value(selected, "is_system_auto")):
|
||||
message = "请开方医生编辑并补全系统占号处方,再完成电子签署。"
|
||||
elif not state["enabled"]:
|
||||
@@ -2550,6 +2610,8 @@ class PrescriptionsPage(QWidget):
|
||||
message = "处方正在电子签署,请稍后再审核。"
|
||||
elif status == "uncertain":
|
||||
message = "请开方医生核对处方签署结果,确认完成后再审核。"
|
||||
elif status == "signed":
|
||||
message = "医生签署尚未通过验签,请核对签署状态后再审核。"
|
||||
else:
|
||||
message = "请开方医生完成电子签署后再审核。"
|
||||
self.banner.show_message(message, "warning")
|
||||
@@ -2567,8 +2629,9 @@ class PrescriptionsPage(QWidget):
|
||||
on_finished=finished,
|
||||
)
|
||||
|
||||
def _open_audit_dialog(self, row: Any) -> None:
|
||||
dialog = AuditPrescriptionDialog(row, self)
|
||||
def _open_audit_dialog(self, row: Any, state: Mapping[str, Any]) -> None:
|
||||
allow_approval = state.get("review_required") is not True or bool(review_signature_time(state))
|
||||
dialog = AuditPrescriptionDialog(row, self, allow_approval=allow_approval)
|
||||
if dialog.exec() != QDialog.DialogCode.Accepted:
|
||||
return
|
||||
payload = dialog.payload()
|
||||
|
||||
@@ -116,8 +116,8 @@ STATUS_TEXT = {1: "待接诊", 2: "已取消", 3: "已完成", 4: "已过号"}
|
||||
RECEPTION_STATUSES = {1, 4}
|
||||
NOTE_LIMIT = 500
|
||||
MAX_NOTE_MEDIA = 99
|
||||
AI_ANALYSIS_MODELS = ("qwen", "openai")
|
||||
AI_ANALYSIS_MODEL_LABELS = {"qwen": "千问", "openai": "OpenAI"}
|
||||
AI_ANALYSIS_MODELS = ("qwen", "openai", "doubao")
|
||||
AI_ANALYSIS_MODEL_LABELS = {"qwen": "千问", "openai": "OpenAI", "doubao": "豆包"}
|
||||
_ASYNC_REQUEST_CANCELLED = object()
|
||||
_ASYNC_REQUEST_DEFERRED = object()
|
||||
_AI_AUTOMATIC_GENERATION_SETTLE_SECONDS = 0.25
|
||||
@@ -2098,7 +2098,7 @@ def _analysis_value(payload: Mapping[str, Any], key: str) -> Any:
|
||||
|
||||
|
||||
def _patient_report_model(payload: Mapping[str, Any]) -> str:
|
||||
"""Return the only two model identifiers accepted by the desktop."""
|
||||
"""Return one of the model identifiers accepted by the desktop."""
|
||||
|
||||
raw = str(
|
||||
payload.get("model_key")
|
||||
@@ -2110,9 +2110,21 @@ def _patient_report_model(payload: Mapping[str, Any]) -> str:
|
||||
return "qwen"
|
||||
if raw in {"openai", "gpt"} or raw.startswith("gpt"):
|
||||
return "openai"
|
||||
if raw in {"doubao", "ark", "volcengine"} or "doubao" in raw:
|
||||
return "doubao"
|
||||
return ""
|
||||
|
||||
|
||||
def _next_ai_analysis_model(model: str) -> str | None:
|
||||
"""千问之后按顺序补齐其余模型;返回 None 表示本轮已到最后一个模型。"""
|
||||
|
||||
try:
|
||||
index = AI_ANALYSIS_MODELS.index(model)
|
||||
except ValueError:
|
||||
return None
|
||||
return AI_ANALYSIS_MODELS[index + 1] if index + 1 < len(AI_ANALYSIS_MODELS) else None
|
||||
|
||||
|
||||
def _normalize_patient_report(payload: Mapping[str, Any]) -> dict[str, Any] | None:
|
||||
"""Flatten a saved server snapshot into the existing structured card contract."""
|
||||
|
||||
@@ -2525,18 +2537,18 @@ class _ClinicalInfoPanel(QWidget):
|
||||
"""Let the clinical history use the full reading column."""
|
||||
|
||||
|
||||
class _ClinicalPageStack(QStackedWidget):
|
||||
"""Size the clinical card from its current page, including after a resize."""
|
||||
|
||||
def sizeHint(self) -> QSize: # noqa: N802 - Qt virtual
|
||||
page = self.currentWidget()
|
||||
return page.sizeHint() if page is not None else super().sizeHint()
|
||||
|
||||
def minimumSizeHint(self) -> QSize: # noqa: N802 - Qt virtual
|
||||
page = self.currentWidget()
|
||||
return page.minimumSizeHint() if page is not None else super().minimumSizeHint()
|
||||
|
||||
|
||||
class _ClinicalPageStack(QStackedWidget):
|
||||
"""Size the clinical card from its current page, including after a resize."""
|
||||
|
||||
def sizeHint(self) -> QSize: # noqa: N802 - Qt virtual
|
||||
page = self.currentWidget()
|
||||
return page.sizeHint() if page is not None else super().sizeHint()
|
||||
|
||||
def minimumSizeHint(self) -> QSize: # noqa: N802 - Qt virtual
|
||||
page = self.currentWidget()
|
||||
return page.minimumSizeHint() if page is not None else super().minimumSizeHint()
|
||||
|
||||
|
||||
class _ReceptionAiPanels(QWidget):
|
||||
"""Give both AI cards reading space before switching to a vertical layout."""
|
||||
|
||||
@@ -2554,16 +2566,16 @@ class _ReceptionAiPanels(QWidget):
|
||||
if needed > 0 and (self.minimumHeight() != needed or self.maximumHeight() != needed):
|
||||
self.setFixedHeight(needed)
|
||||
self.updateGeometry()
|
||||
|
||||
def resizeEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual
|
||||
super().resizeEvent(event)
|
||||
layout = self.layout()
|
||||
if not isinstance(layout, QBoxLayout):
|
||||
return
|
||||
stacked = self.width() < 800
|
||||
direction = QBoxLayout.Direction.TopToBottom if stacked else QBoxLayout.Direction.LeftToRight
|
||||
if layout.direction() != direction:
|
||||
layout.setDirection(direction)
|
||||
|
||||
def resizeEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual
|
||||
super().resizeEvent(event)
|
||||
layout = self.layout()
|
||||
if not isinstance(layout, QBoxLayout):
|
||||
return
|
||||
stacked = self.width() < 800
|
||||
direction = QBoxLayout.Direction.TopToBottom if stacked else QBoxLayout.Direction.LeftToRight
|
||||
if layout.direction() != direction:
|
||||
layout.setDirection(direction)
|
||||
layout.setStretch(0, 0 if stacked else 17)
|
||||
layout.setStretch(1, 0 if stacked else 23)
|
||||
self.updateGeometry()
|
||||
@@ -3193,7 +3205,7 @@ class _ReceptionAiAnalysisDialog(QDialog):
|
||||
title = QLabel("患者级 AI 诊断报告", header)
|
||||
title.setObjectName("ReceptionAiAnalysisDialogTitle")
|
||||
title.setProperty("dialogRole", "title")
|
||||
subtitle = QLabel("查看千问与 OpenAI 的历次患者报告快照", header)
|
||||
subtitle = QLabel("查看千问、OpenAI 与豆包的历次患者报告快照", header)
|
||||
subtitle.setObjectName("ReceptionAiAnalysisDialogSubtitle")
|
||||
subtitle.setProperty("dialogRole", "subtitle")
|
||||
heading.addWidget(title)
|
||||
@@ -3954,8 +3966,8 @@ class ReceptionDailyRecordsPanel(DailyRecordPanel):
|
||||
self.matrix.setAccessibleName("患者日常记录矩阵")
|
||||
self.matrix.setMinimumHeight(330)
|
||||
self.matrix.setMaximumHeight(460)
|
||||
self.matrix.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
|
||||
self._sizing_daily_columns = False
|
||||
self.matrix.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
|
||||
self._sizing_daily_columns = False
|
||||
self.matrix.viewport().installEventFilter(self)
|
||||
|
||||
for object_name in ("DiagnosisTrendCard", "DiagnosisTodoCard"):
|
||||
@@ -3964,37 +3976,37 @@ class ReceptionDailyRecordsPanel(DailyRecordPanel):
|
||||
child.hide()
|
||||
self.clear_with_message("选择患者后加载最近 7 天日常记录。")
|
||||
|
||||
def eventFilter(self, watched: Any, event: Any) -> bool: # noqa: N802 - Qt virtual
|
||||
if (
|
||||
watched is self.matrix.viewport()
|
||||
and event.type() == QEvent.Type.Resize
|
||||
and event.size().width() != event.oldSize().width()
|
||||
):
|
||||
self._fit_daily_columns()
|
||||
return super().eventFilter(watched, event)
|
||||
|
||||
def _fit_daily_columns(self) -> None:
|
||||
count = self.matrix.columnCount() - 1
|
||||
if count < 1 or self._sizing_daily_columns:
|
||||
return
|
||||
self._sizing_daily_columns = True
|
||||
try:
|
||||
header = self.matrix.horizontalHeader()
|
||||
header.setSectionResizeMode(QHeaderView.ResizeMode.Interactive)
|
||||
header.setMinimumSectionSize(96)
|
||||
available = max(0, self.matrix.viewport().width() - 132)
|
||||
width, remainder = divmod(available, count)
|
||||
widths = [max(96, width + (index < remainder)) for index in range(count)]
|
||||
changed = False
|
||||
for column, target in enumerate([132, *widths]):
|
||||
if self.matrix.columnWidth(column) != target:
|
||||
self.matrix.setColumnWidth(column, target)
|
||||
changed = True
|
||||
if changed:
|
||||
self.matrix.resizeRowsToContents()
|
||||
finally:
|
||||
self._sizing_daily_columns = False
|
||||
|
||||
def eventFilter(self, watched: Any, event: Any) -> bool: # noqa: N802 - Qt virtual
|
||||
if (
|
||||
watched is self.matrix.viewport()
|
||||
and event.type() == QEvent.Type.Resize
|
||||
and event.size().width() != event.oldSize().width()
|
||||
):
|
||||
self._fit_daily_columns()
|
||||
return super().eventFilter(watched, event)
|
||||
|
||||
def _fit_daily_columns(self) -> None:
|
||||
count = self.matrix.columnCount() - 1
|
||||
if count < 1 or self._sizing_daily_columns:
|
||||
return
|
||||
self._sizing_daily_columns = True
|
||||
try:
|
||||
header = self.matrix.horizontalHeader()
|
||||
header.setSectionResizeMode(QHeaderView.ResizeMode.Interactive)
|
||||
header.setMinimumSectionSize(96)
|
||||
available = max(0, self.matrix.viewport().width() - 132)
|
||||
width, remainder = divmod(available, count)
|
||||
widths = [max(96, width + (index < remainder)) for index in range(count)]
|
||||
changed = False
|
||||
for column, target in enumerate([132, *widths]):
|
||||
if self.matrix.columnWidth(column) != target:
|
||||
self.matrix.setColumnWidth(column, target)
|
||||
changed = True
|
||||
if changed:
|
||||
self.matrix.resizeRowsToContents()
|
||||
finally:
|
||||
self._sizing_daily_columns = False
|
||||
|
||||
def set_patient_age(self, age: Any) -> None:
|
||||
parsed = _as_int(age, None)
|
||||
self._patient_age = parsed if parsed is not None and parsed >= 0 else None
|
||||
@@ -5135,7 +5147,7 @@ class ReceptionPage(QWidget):
|
||||
self.ai_analysis_model_selector = _ReceptionAiModelCombo(analysis_card)
|
||||
self.ai_analysis_model_selector.setObjectName("ReceptionAiAnalysisModelSelector")
|
||||
self.ai_analysis_model_selector.setAccessibleName("选择卡片分析模型")
|
||||
self.ai_analysis_model_selector.setToolTip("切换千问与 OpenAI 分析")
|
||||
self.ai_analysis_model_selector.setToolTip("切换千问、OpenAI 与豆包分析")
|
||||
for model_key in AI_ANALYSIS_MODELS:
|
||||
self.ai_analysis_model_selector.addItem(
|
||||
AI_ANALYSIS_MODEL_LABELS[model_key],
|
||||
@@ -5326,13 +5338,13 @@ class ReceptionPage(QWidget):
|
||||
self.ai_analysis_history_button = QPushButton("历史报告", analysis_card)
|
||||
self.ai_analysis_history_button.setObjectName("ReceptionAiHistoryButton")
|
||||
self.ai_analysis_history_button.setAccessibleName("查看历次 AI 报告快照")
|
||||
self.ai_analysis_history_button.setToolTip("查看并切换千问与 OpenAI 历史报告")
|
||||
self.ai_analysis_history_button.setToolTip("查看并切换千问、OpenAI 与豆包历史报告")
|
||||
self.ai_analysis_history_button.clicked.connect(self._open_ai_analysis_dialog)
|
||||
report_footer.addWidget(self.ai_analysis_history_button)
|
||||
self.ai_analysis_regenerate_button = QPushButton("重新分析", analysis_card)
|
||||
self.ai_analysis_regenerate_button.setObjectName("ReceptionAiRegenerateButton")
|
||||
self.ai_analysis_regenerate_button.setAccessibleName("重新生成患者级 AI 报告")
|
||||
self.ai_analysis_regenerate_button.setToolTip("依次生成新的千问和 OpenAI 快照")
|
||||
self.ai_analysis_regenerate_button.setToolTip("依次生成新的千问、OpenAI 和豆包快照")
|
||||
self.ai_analysis_regenerate_button.clicked.connect(
|
||||
self._regenerate_patient_ai_reports
|
||||
)
|
||||
@@ -5528,10 +5540,11 @@ class ReceptionPage(QWidget):
|
||||
self._ai_analysis_active_model = "qwen"
|
||||
self._ai_analysis_model_states["qwen"] = state
|
||||
self._ai_analysis_model_messages["qwen"] = message
|
||||
self._ai_analysis_model_states["openai"] = (
|
||||
state if state in {"empty", "permission"} else "waiting"
|
||||
)
|
||||
self._ai_analysis_model_messages["openai"] = ""
|
||||
for secondary in AI_ANALYSIS_MODELS[1:]:
|
||||
self._ai_analysis_model_states[secondary] = (
|
||||
state if state in {"empty", "permission"} else "waiting"
|
||||
)
|
||||
self._ai_analysis_model_messages[secondary] = ""
|
||||
selector_index = self.ai_analysis_model_selector.findData("qwen")
|
||||
if selector_index >= 0:
|
||||
self.ai_analysis_model_selector.blockSignals(True)
|
||||
@@ -5626,15 +5639,41 @@ class ReceptionPage(QWidget):
|
||||
)
|
||||
|
||||
qwen_ready = "qwen" in self._ai_analysis_payloads
|
||||
openai_state = self._ai_analysis_model_states["openai"]
|
||||
openai_message = self._ai_analysis_model_messages["openai"]
|
||||
if qwen_ready and openai_state == "loading":
|
||||
secondary_message = "千问结果已显示,OpenAI 正在生成…"
|
||||
elif qwen_ready and openai_state == "error":
|
||||
secondary_message = f"千问结果已保留;{openai_message}"
|
||||
elif qwen_ready and openai_state == "success":
|
||||
secondary_message = "千问与 OpenAI 均已完成,可切换对照。"
|
||||
elif qwen_ready and openai_state == "unsupported":
|
||||
secondary_models = AI_ANALYSIS_MODELS[1:]
|
||||
secondary_states = [self._ai_analysis_model_states[key] for key in secondary_models]
|
||||
loading_labels = [
|
||||
AI_ANALYSIS_MODEL_LABELS[key]
|
||||
for key in secondary_models
|
||||
if self._ai_analysis_model_states[key] == "loading"
|
||||
]
|
||||
failed_messages = [
|
||||
self._ai_analysis_model_messages[key]
|
||||
for key in secondary_models
|
||||
if self._ai_analysis_model_states[key] == "error"
|
||||
]
|
||||
# 失败优先于进行中:已失败的模型不会因后续模型仍在生成而被隐藏。
|
||||
if "error" in secondary_states:
|
||||
secondary_state = "error"
|
||||
elif "loading" in secondary_states:
|
||||
secondary_state = "loading"
|
||||
elif all(item == "success" for item in secondary_states):
|
||||
secondary_state = "success"
|
||||
elif all(item == "unsupported" for item in secondary_states):
|
||||
secondary_state = "unsupported"
|
||||
else:
|
||||
secondary_state = secondary_states[0]
|
||||
if qwen_ready and secondary_state == "loading":
|
||||
secondary_message = f"千问结果已显示,{'、'.join(loading_labels)} 正在生成…"
|
||||
elif qwen_ready and secondary_state == "error":
|
||||
secondary_message = "千问结果已保留;" + ";".join(
|
||||
message for message in failed_messages if message
|
||||
) + (f";{'、'.join(loading_labels)} 正在生成…" if loading_labels else "")
|
||||
elif qwen_ready and secondary_state == "success":
|
||||
secondary_message = (
|
||||
f"{'、'.join(AI_ANALYSIS_MODEL_LABELS[key] for key in AI_ANALYSIS_MODELS)}"
|
||||
" 均已完成,可切换对照。"
|
||||
)
|
||||
elif qwen_ready and secondary_state == "unsupported":
|
||||
secondary_message = "千问结果已显示;当前数据源仅支持千问分析。"
|
||||
else:
|
||||
secondary_message = ""
|
||||
@@ -5646,7 +5685,7 @@ class ReceptionPage(QWidget):
|
||||
if success and payload is not None
|
||||
else ""
|
||||
)
|
||||
if current_snapshot_time and (openai_state == "success" or not secondary_message):
|
||||
if current_snapshot_time and (secondary_state == "success" or not secondary_message):
|
||||
secondary_message = f"快照时间:{current_snapshot_time[:16]}"
|
||||
if self._ai_analysis_regenerating:
|
||||
active_label = AI_ANALYSIS_MODEL_LABELS.get(
|
||||
@@ -5654,11 +5693,11 @@ class ReceptionPage(QWidget):
|
||||
self._ai_analysis_regeneration_model or "千问",
|
||||
)
|
||||
secondary_message = f"正在生成新的{active_label}快照,历史版本会保留。"
|
||||
openai_state = "loading"
|
||||
secondary_state = "loading"
|
||||
elif self._ai_analysis_operation_error:
|
||||
secondary_message = self._ai_analysis_operation_error
|
||||
openai_state = "error"
|
||||
self._set_ai_analysis_secondary_status(openai_state, secondary_message)
|
||||
secondary_state = "error"
|
||||
self._set_ai_analysis_secondary_status(secondary_state, secondary_message)
|
||||
|
||||
self.ai_analysis_card.setProperty("analysisState", state)
|
||||
self.ai_analysis_card.style().unpolish(self.ai_analysis_card)
|
||||
@@ -5980,12 +6019,14 @@ class ReceptionPage(QWidget):
|
||||
self._ai_analysis_payloads[model] = grouped[model][0]
|
||||
self._ai_analysis_model_states[model] = "success"
|
||||
self._ai_analysis_model_messages[model] = ""
|
||||
else:
|
||||
elif replace or self._ai_analysis_model_states.get(model) not in {"error", "loading"}:
|
||||
# 追加单个新快照时,保留其他模型尚未结束或已失败的状态与原因。
|
||||
self._ai_analysis_model_states[model] = "missing"
|
||||
self._ai_analysis_model_messages[model] = ""
|
||||
if self._ai_analysis_active_model not in self._ai_analysis_payloads:
|
||||
self._ai_analysis_active_model = (
|
||||
"qwen" if "qwen" in self._ai_analysis_payloads else "openai"
|
||||
self._ai_analysis_active_model = next(
|
||||
(key for key in AI_ANALYSIS_MODELS if key in self._ai_analysis_payloads),
|
||||
"qwen",
|
||||
)
|
||||
selector_index = self.ai_analysis_model_selector.findData(
|
||||
self._ai_analysis_active_model
|
||||
@@ -6436,9 +6477,10 @@ class ReceptionPage(QWidget):
|
||||
self._ai_analysis_model_states[model] = "success"
|
||||
self._ai_analysis_model_messages[model] = ""
|
||||
self._sync_ai_analysis_view()
|
||||
if model == "qwen":
|
||||
next_model = _next_ai_analysis_model(model)
|
||||
if next_model is not None:
|
||||
self._request_patient_ai_generation(
|
||||
"openai",
|
||||
next_model,
|
||||
effective_generation,
|
||||
effective_appointment_id,
|
||||
patient_id,
|
||||
@@ -6475,9 +6517,21 @@ class ReceptionPage(QWidget):
|
||||
else:
|
||||
self._ai_analysis_model_states[model] = "error"
|
||||
self._ai_analysis_model_messages[model] = message
|
||||
prefix = "千问新快照已保留;" if model == "openai" and "qwen" in self._ai_analysis_payloads else ""
|
||||
prefix = "千问新快照已保留;" if model != "qwen" and "qwen" in self._ai_analysis_payloads else ""
|
||||
self._ai_analysis_operation_error = f"{prefix}{message}"
|
||||
self._sync_ai_analysis_view()
|
||||
# 千问之后的某个模型失败,不阻断其余模型继续补齐;失败原因保留在该模型状态里。
|
||||
next_model = _next_ai_analysis_model(model) if model != "qwen" else None
|
||||
context = self._current_patient_ai_context(patient_id)
|
||||
if next_model is not None and context is not None:
|
||||
effective_generation, effective_appointment_id, _patient_id = context
|
||||
self._request_patient_ai_generation(
|
||||
next_model,
|
||||
effective_generation,
|
||||
effective_appointment_id,
|
||||
patient_id,
|
||||
settle_before_request=True,
|
||||
)
|
||||
|
||||
def _patient_ai_generation_finished(
|
||||
self,
|
||||
@@ -6617,7 +6671,7 @@ class ReceptionPage(QWidget):
|
||||
diagnosis_id,
|
||||
):
|
||||
return
|
||||
if model == "openai" and not self._ai_analysis_supports_models:
|
||||
if model != "qwen" and not self._ai_analysis_supports_models:
|
||||
self._ai_analysis_model_states[model] = "unsupported"
|
||||
self._ai_analysis_model_messages[model] = ""
|
||||
self._sync_ai_analysis_view()
|
||||
@@ -6764,11 +6818,12 @@ class ReceptionPage(QWidget):
|
||||
self._ai_analysis_model_messages[model] = ""
|
||||
self._sync_ai_analysis_view()
|
||||
|
||||
if model == "qwen":
|
||||
next_model = _next_ai_analysis_model(model)
|
||||
if next_model is not None:
|
||||
method = getattr(self.repository, "get_diagnosis_ai_analysis", None)
|
||||
if callable(method):
|
||||
self._request_ai_analysis_model(
|
||||
"openai",
|
||||
next_model,
|
||||
method,
|
||||
request_generation,
|
||||
appointment_id,
|
||||
@@ -6803,6 +6858,18 @@ class ReceptionPage(QWidget):
|
||||
f"{label}分析加载失败:{friendly_error(error)}"
|
||||
)
|
||||
self._sync_ai_analysis_view()
|
||||
# 与患者快照一致:千问之后的模型失败不阻断其余模型。
|
||||
next_model = _next_ai_analysis_model(model) if model != "qwen" else None
|
||||
method = getattr(self.repository, "get_diagnosis_ai_analysis", None)
|
||||
if next_model is not None and callable(method):
|
||||
self._request_ai_analysis_model(
|
||||
next_model,
|
||||
method,
|
||||
request_generation,
|
||||
appointment_id,
|
||||
diagnosis_id,
|
||||
settle_before_request=True,
|
||||
)
|
||||
|
||||
def _ai_analysis_finished(
|
||||
self,
|
||||
@@ -6869,7 +6936,7 @@ class ReceptionPage(QWidget):
|
||||
self._set_ai_analysis_state("error", "当前患者缺少诊单编号,无法重试。")
|
||||
return
|
||||
model = self._ai_analysis_active_model
|
||||
if model == "openai" and self._ai_analysis_model_states[model] == "error":
|
||||
if model != "qwen" and self._ai_analysis_model_states[model] == "error":
|
||||
method = getattr(self.repository, "get_diagnosis_ai_analysis", None)
|
||||
if callable(method):
|
||||
self._request_ai_analysis_model(
|
||||
|
||||
@@ -875,6 +875,7 @@ class ShellWindow(QMainWindow):
|
||||
"""
|
||||
|
||||
logout_requested = Signal()
|
||||
close_requested = Signal()
|
||||
video_requested = Signal(dict)
|
||||
page_changed = Signal(str)
|
||||
update_check_requested = Signal()
|
||||
@@ -2237,6 +2238,8 @@ class ShellWindow(QMainWindow):
|
||||
def closeEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual
|
||||
self.chat_notifications.stop()
|
||||
super().closeEvent(event)
|
||||
if event.isAccepted():
|
||||
self.close_requested.emit()
|
||||
|
||||
def _open_chat_notification(self, notification: ChatNotification) -> None:
|
||||
"""Take the doctor where the notification's work actually lives."""
|
||||
|
||||
@@ -381,9 +381,21 @@ def run_async(
|
||||
|
||||
worker = Worker(function, *args, **kwargs)
|
||||
_RUNNING_WORKERS.add(worker)
|
||||
session_handler = _AUTHENTICATION_EXPIRED_HANDLER
|
||||
|
||||
def dispatch_error(error: Exception, _traceback: str) -> None:
|
||||
# An earlier session's in-flight failure cannot dismiss a newly
|
||||
# authenticated shell or open an error dialog over its login window.
|
||||
if (
|
||||
isinstance(error, AuthenticationExpiredError)
|
||||
and session_handler is not _AUTHENTICATION_EXPIRED_HANDLER
|
||||
):
|
||||
return
|
||||
_dispatch_async_error(error, on_error)
|
||||
|
||||
if on_success is not None:
|
||||
worker.signals.result.connect(on_success)
|
||||
worker.signals.error.connect(lambda exc, _tb: _dispatch_async_error(exc, on_error))
|
||||
worker.signals.error.connect(dispatch_error)
|
||||
if on_finished is not None:
|
||||
worker.signals.finished.connect(on_finished)
|
||||
worker.signals.finished.connect(lambda: _RUNNING_WORKERS.discard(worker))
|
||||
|
||||
@@ -21,6 +21,8 @@ SYNC_TIMEOUT_SECONDS = 45.0
|
||||
_WORKER_SLOTS = BoundedSemaphore(4)
|
||||
_CANCEL_SLOTS = BoundedSemaphore(4)
|
||||
_ACTIONS = frozenset({"summary", "followup", "reply"})
|
||||
# 千问是服务端各任务的默认模型;医生在面板中切换后才显式携带。
|
||||
_MODELS = frozenset({"qwen", "openai", "doubao"})
|
||||
|
||||
|
||||
def _integer(value: Any, *, minimum: int) -> int | None:
|
||||
@@ -104,6 +106,7 @@ class _RequestError(Exception):
|
||||
class _Job:
|
||||
identity: dict[str, Any]
|
||||
action: str
|
||||
model: str | None = None
|
||||
cancelled: Event = field(default_factory=Event)
|
||||
completed: bool = False
|
||||
succeeded: bool = False
|
||||
@@ -193,8 +196,11 @@ class ImAiController:
|
||||
return True
|
||||
if event != "im-ai-request" or message["requestId"] in self._seen:
|
||||
return False
|
||||
model = message.get("model")
|
||||
if model is not None and (not isinstance(model, str) or model not in _MODELS):
|
||||
return False
|
||||
self._seen.append(message["requestId"])
|
||||
job = _Job(identity, message["action"])
|
||||
job = _Job(identity, message["action"], model)
|
||||
if self._running is not None:
|
||||
self._cancel(self._running)
|
||||
self._current = job
|
||||
@@ -269,6 +275,7 @@ class ImAiController:
|
||||
events = self.repository.stream_diagnosis_ai(
|
||||
self.diagnosis_id, prompt, task=task,
|
||||
request_id=job.identity["requestId"], cancelled=job.cancelled.is_set,
|
||||
**({"model": job.model} if job.model not in (None, "qwen") else {}),
|
||||
)
|
||||
try:
|
||||
for event in events:
|
||||
|
||||
@@ -20,7 +20,7 @@ from ..core.transcript_text import simplified_transcript
|
||||
|
||||
MAX_IMAGE_BYTES = 10 * 1024 * 1024
|
||||
_SLOTS = BoundedSemaphore(4)
|
||||
_MODELS = {"qwen", "openai"}
|
||||
_MODELS = {"qwen", "openai", "doubao"}
|
||||
_BUSINESS_MESSAGES = {
|
||||
"GPT 模型接口配置异常,请管理员检查 Dify 中的模型 API 地址。": "GPT 模型接口配置异常,请管理员检查 Dify 中的模型 API 地址。",
|
||||
"千问 模型接口配置异常,请管理员检查 Dify 中的模型 API 地址。": "千问 模型接口配置异常,请管理员检查 Dify 中的模型 API 地址。",
|
||||
|
||||
@@ -255,7 +255,7 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration
|
||||
def analyzeTongueScreenshotModel(self, request_id: str, data_url: str, model: str) -> None: # noqa: N802
|
||||
if (not isinstance(request_id, str) or len(request_id) != 36
|
||||
or not isinstance(data_url, str) or len(data_url) > 14 * 1024 * 1024
|
||||
or not isinstance(model, str) or model not in {"qwen", "openai"}):
|
||||
or not isinstance(model, str) or model not in {"qwen", "openai", "doubao"}):
|
||||
return
|
||||
self._callback({"source": "doctor-call", "event": "tongue-screenshot-analyze",
|
||||
"requestId": request_id, "dataUrl": data_url, "model": model})
|
||||
|
||||
@@ -367,14 +367,31 @@ def test_prescription_action_with_write_permission_but_without_ai_grant_is_block
|
||||
dialog.close()
|
||||
|
||||
|
||||
def test_prescription_action_opens_editor_and_forces_current_diagnosis_ownership(
|
||||
@pytest.mark.parametrize("esign_enabled", [False, True])
|
||||
def test_prescription_action_opens_upload_once_with_current_diagnosis_ownership(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
esign_enabled: bool,
|
||||
) -> None:
|
||||
created: list[dict[str, Any]] = []
|
||||
editor_seeds: list[dict[str, Any]] = []
|
||||
upload_receipts: list[dict[str, Any]] = []
|
||||
current_user = {"id": 12, "name": "甄医生"}
|
||||
receipt = {
|
||||
"id": 9001,
|
||||
"esign": {
|
||||
"enabled": esign_enabled,
|
||||
"required": esign_enabled,
|
||||
"environment": "sandbox",
|
||||
"status": "pending" if esign_enabled else "legacy",
|
||||
"can_sign": False,
|
||||
"can_download": False,
|
||||
"review_submitted_at": 0,
|
||||
"awaiting_upload": True,
|
||||
"can_submit_for_review": True,
|
||||
},
|
||||
}
|
||||
|
||||
class Repository:
|
||||
def get_diagnosis_detail(
|
||||
@@ -419,7 +436,10 @@ def test_prescription_action_opens_editor_and_forces_current_diagnosis_ownership
|
||||
|
||||
def create_prescription(self, prescription: dict[str, Any]) -> dict[str, Any]:
|
||||
created.append(prescription)
|
||||
return {"id": 9001, **prescription}
|
||||
return receipt
|
||||
|
||||
def submit_prescription_for_review(self, prescription_id: int) -> None:
|
||||
raise AssertionError(f"uploading {prescription_id} requires a separate click")
|
||||
|
||||
def list_prescriptions_by_diagnosis(
|
||||
self,
|
||||
@@ -427,10 +447,6 @@ def test_prescription_action_opens_editor_and_forces_current_diagnosis_ownership
|
||||
) -> list[dict[str, Any]]:
|
||||
return [{"id": 9001, "diagnosis_id": diagnosis_id, "sn": "RX-9001"}]
|
||||
|
||||
class FakeSignal:
|
||||
def connect(self, _slot: Any) -> None:
|
||||
return None
|
||||
|
||||
class FakeEditor:
|
||||
def __init__(
|
||||
self,
|
||||
@@ -441,9 +457,12 @@ def test_prescription_action_opens_editor_and_forces_current_diagnosis_ownership
|
||||
editor_seeds.append(seed)
|
||||
assert kwargs["mode"] == "add"
|
||||
assert kwargs["current_user"] == current_user
|
||||
self.diagnosis_requested = FakeSignal()
|
||||
self.save_draft = kwargs["save_draft"]
|
||||
self.saved_draft = None
|
||||
|
||||
def exec(self) -> Any:
|
||||
if esign_enabled:
|
||||
self.saved_draft = self.save_draft(self.payload())
|
||||
return ai_consult_module.QDialog.DialogCode.Accepted
|
||||
|
||||
@staticmethod
|
||||
@@ -452,17 +471,32 @@ def test_prescription_action_opens_editor_and_forces_current_diagnosis_ownership
|
||||
"diagnosis_id": 999,
|
||||
"appointment_id": 998,
|
||||
"case_record": {"forged": True},
|
||||
"patient_id": 997,
|
||||
"phone": "13900000000",
|
||||
"doctor_name": "甄医生",
|
||||
"herbs": [{"name": "茯苓", "dosage": 10, "unit": "g"}],
|
||||
}
|
||||
|
||||
from doctor_workstation.ui.dialogs import prescription as prescription_module
|
||||
class FakeUploadDialog:
|
||||
def __init__(self, _repository: Any, prescription: dict[str, Any], **_kwargs: Any) -> None:
|
||||
assert prescription is receipt
|
||||
self.state = prescription["esign"]
|
||||
upload_receipts.append(prescription)
|
||||
|
||||
def exec(self) -> None:
|
||||
return None
|
||||
|
||||
from doctor_workstation.ui.dialogs import (
|
||||
prescription as prescription_module,
|
||||
prescription_esign as prescription_esign_module,
|
||||
)
|
||||
|
||||
monkeypatch.setattr(
|
||||
prescription_module,
|
||||
"PrescriptionEditorDialog",
|
||||
FakeEditor,
|
||||
)
|
||||
monkeypatch.setattr(prescription_esign_module, "PrescriptionEsignDialog", FakeUploadDialog)
|
||||
host = QWidget()
|
||||
host.current_user = current_user # type: ignore[attr-defined]
|
||||
dialog = AiConsultDialog(
|
||||
@@ -484,7 +518,9 @@ def test_prescription_action_opens_editor_and_forces_current_diagnosis_ownership
|
||||
assert editor_seeds[0]["diagnosis_id"] == 501
|
||||
assert editor_seeds[0]["appointment_id"] == 801
|
||||
assert editor_seeds[0]["herbs"][0]["name"] == "茯苓"
|
||||
assert created and created[0]["diagnosis_id"] == 501
|
||||
assert len(created) == 1
|
||||
assert upload_receipts == [receipt]
|
||||
assert created[0]["diagnosis_id"] == 501
|
||||
assert created[0]["appointment_id"] == 801
|
||||
assert created[0]["case_record"] == {"chief_complaint": "性功能下降"}
|
||||
assert created[0]["patient_id"] == 301
|
||||
@@ -495,7 +531,7 @@ def test_prescription_action_opens_editor_and_forces_current_diagnosis_ownership
|
||||
browser.toPlainText()
|
||||
for browser in dialog.findChildren(QTextBrowser, "AiConsultBubbleText")
|
||||
]
|
||||
assert any("处方已开具并提交审核" in body for body in bodies)
|
||||
assert any("处方草稿已保存" in body and "上传处方" in body for body in bodies)
|
||||
dialog.close()
|
||||
host.close()
|
||||
|
||||
|
||||
@@ -98,6 +98,26 @@ def test_invalid_identity_or_action_cannot_read_patient_context(changes):
|
||||
assert not repository.sync_calls and not repository.stream_calls
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model,forwarded", [(None, None), ("qwen", None), ("openai", "openai"), ("doubao", "doubao")])
|
||||
def test_selected_model_is_forwarded_only_when_not_the_task_default(model, forwarded):
|
||||
repository = Repository()
|
||||
service = controller(repository)
|
||||
assert service.handle(request(service, **({} if model is None else {"model": model})))
|
||||
assert service.wait()
|
||||
assert service.take_result()["status"] == "success"
|
||||
_diagnosis_id, _prompt, options = repository.stream_calls[0]
|
||||
assert options.get("model") == forwarded
|
||||
assert ("model" in options) is (forwarded is not None)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model", ["deepseek", "", "Doubao", 1, ["doubao"]])
|
||||
def test_unknown_model_cannot_start_a_request(model):
|
||||
repository = Repository()
|
||||
service = controller(repository)
|
||||
assert not service.handle(request(service, model=model))
|
||||
assert not repository.sync_calls and not repository.stream_calls
|
||||
|
||||
|
||||
def test_permission_default_denied_and_each_host_has_unique_session():
|
||||
repository = Repository()
|
||||
disabled = im_ai.ImAiController(
|
||||
|
||||
@@ -2,8 +2,11 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
from time import time
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
@@ -11,6 +14,7 @@ import pytest
|
||||
from doctor_workstation.core.errors import (
|
||||
ApiBusinessError,
|
||||
ApiProtocolError,
|
||||
ApiTransportError,
|
||||
AuthenticationExpiredError,
|
||||
RepositoryNotFoundError,
|
||||
)
|
||||
@@ -415,6 +419,8 @@ class _StubApiClient:
|
||||
self.token = ""
|
||||
self.get_calls: list[tuple[str, dict[str, Any]]] = []
|
||||
self.post_calls: list[tuple[str, dict[str, Any]]] = []
|
||||
self.deadline = int(time()) + 3600
|
||||
self.post_tokens: list[str] = []
|
||||
|
||||
def set_token(self, token: str) -> None:
|
||||
"""Retain the synthetic login token."""
|
||||
@@ -445,13 +451,17 @@ class _StubApiClient:
|
||||
return {"appointment": {"id": params["id"]}, "doctor_notes": []}
|
||||
return {"lists": [], "count": 0, "extend": {}}
|
||||
|
||||
def post(self, endpoint: str, payload: dict[str, Any] | None = None) -> Any:
|
||||
def post(self, endpoint: str, payload: dict[str, Any] | None = None, *,
|
||||
headers: dict[str, str] | None = None, timeout: float | None = None) -> Any:
|
||||
"""Return synthetic mutation data and record the exact JSON payload."""
|
||||
|
||||
body = dict(payload or {})
|
||||
self.post_calls.append((endpoint, body))
|
||||
self.post_tokens.append((headers or {}).get("token", self.token))
|
||||
if endpoint == "login/account":
|
||||
return {"token": "remote-token", "is_paw": 1}
|
||||
return {"token": "remote-token", "is_paw": 1, "desktop_expires_at": self.deadline}
|
||||
if endpoint == "login/desktopHeartbeat":
|
||||
return {"desktop_expires_at": self.deadline}
|
||||
if endpoint == "tcm.prescriptionLibrary/add":
|
||||
return {"id": 9}
|
||||
if endpoint == "tcm.diagnosis/getCallSignature":
|
||||
@@ -473,6 +483,8 @@ def test_remote_repository_uses_all_confirmed_endpoints_without_network() -> Non
|
||||
repository = RemoteDoctorRepository(client) # type: ignore[arg-type]
|
||||
|
||||
session = repository.login(" doctor ", "secret")
|
||||
assert client.post_calls == [("login/account", {"account": "doctor", "password": "secret", "terminal": 21})]
|
||||
assert session.desktop_expires_at == client.deadline
|
||||
assert session.token == "remote-token"
|
||||
assert repository.get_current_user().name == "远程医生"
|
||||
assert [path for path, _ in client.get_calls].count("auth.admin/mySelf") == 1
|
||||
@@ -588,6 +600,8 @@ def test_remote_login_persists_only_after_session_validation(
|
||||
)
|
||||
|
||||
assert saved == []
|
||||
assert client.post_calls[-1] == ("login/logout", {})
|
||||
assert client.post_tokens[-1] == "remote-token"
|
||||
assert client.token == ""
|
||||
assert store.load_token() is None
|
||||
|
||||
@@ -604,6 +618,10 @@ def test_remote_login_applies_remember_account_to_token_store(tmp_path: Path) ->
|
||||
assert store.load_token(scope=client.base_url) == "remote-token"
|
||||
|
||||
repository.logout()
|
||||
assert client.post_calls[-1] == ("login/logout", {})
|
||||
assert client.post_tokens[-1] == "remote-token"
|
||||
assert store.load_token() is None
|
||||
assert store.load_account() == "doctor"
|
||||
repository.login("doctor", "secret", remember_account=False)
|
||||
assert store.load_account() is None
|
||||
assert store.load_token(scope=client.base_url) == "remote-token"
|
||||
@@ -614,7 +632,8 @@ def test_expired_persisted_token_is_removed_during_restore(tmp_path: Path) -> No
|
||||
|
||||
client = _FailingProfileClient(AuthenticationExpiredError("expired", code=-1))
|
||||
store = TokenStore(tmp_path / "credentials.json", keyring_backend=None)
|
||||
store.save_token("expired-token", account="doctor", scope=client.base_url)
|
||||
store.save_token("expired-token", account="doctor", scope=client.base_url,
|
||||
desktop_expires_at=client.deadline)
|
||||
repository = RemoteDoctorRepository(client, store) # type: ignore[arg-type]
|
||||
|
||||
with pytest.raises(AuthenticationExpiredError):
|
||||
@@ -625,6 +644,101 @@ def test_expired_persisted_token_is_removed_during_restore(tmp_path: Path) -> No
|
||||
assert store.load_account() == "doctor"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("deadline", [0, 1])
|
||||
def test_old_web_or_past_cutoff_token_is_discarded_without_network(tmp_path: Path, deadline: int) -> None:
|
||||
client = _StubApiClient()
|
||||
store = TokenStore(tmp_path / "credentials.json", keyring_backend=None)
|
||||
store.save_token("saved-token", account="doctor", scope=client.base_url, desktop_expires_at=deadline)
|
||||
repository = RemoteDoctorRepository(client, store) # type: ignore[arg-type]
|
||||
|
||||
with pytest.raises(AuthenticationExpiredError):
|
||||
repository.restore_session()
|
||||
repository.logout()
|
||||
assert client.post_calls == client.get_calls == []
|
||||
assert store.load_account() == "doctor"
|
||||
assert store.load_token() is None
|
||||
|
||||
|
||||
def test_restore_requires_live_heartbeat_and_keeps_earlier_cutoff(tmp_path: Path) -> None:
|
||||
client = _StubApiClient()
|
||||
store = TokenStore(tmp_path / "credentials.json", keyring_backend=None)
|
||||
store.save_token("desktop-token", scope=client.base_url, desktop_expires_at=client.deadline - 10)
|
||||
repository = RemoteDoctorRepository(client, store) # type: ignore[arg-type]
|
||||
|
||||
session = repository.restore_session()
|
||||
assert session and session.desktop_expires_at == client.deadline - 10
|
||||
assert client.post_calls == [("login/desktopHeartbeat", {})]
|
||||
assert client.post_tokens == ["desktop-token"]
|
||||
assert client.get_calls == [("auth.admin/mySelf", {})]
|
||||
|
||||
|
||||
def test_network_loss_during_restore_preserves_token_for_retry(tmp_path: Path, monkeypatch: Any) -> None:
|
||||
client = _StubApiClient()
|
||||
store = TokenStore(tmp_path / "credentials.json", keyring_backend=None)
|
||||
store.save_token("desktop-token", scope=client.base_url, desktop_expires_at=client.deadline)
|
||||
repository = RemoteDoctorRepository(client, store) # type: ignore[arg-type]
|
||||
|
||||
def offline(*_args: Any, **_kwargs: Any) -> Any:
|
||||
raise ApiTransportError("offline")
|
||||
|
||||
monkeypatch.setattr(client, "post", offline)
|
||||
with pytest.raises(ApiTransportError):
|
||||
repository.restore_session()
|
||||
assert client.token == ""
|
||||
assert client.get_calls == []
|
||||
assert store.load_token() == "desktop-token"
|
||||
|
||||
|
||||
def test_logout_after_network_loss_clears_credentials_and_never_retries(tmp_path: Path, monkeypatch: Any) -> None:
|
||||
client = _StubApiClient()
|
||||
store = TokenStore(tmp_path / "credentials.json", keyring_backend=None)
|
||||
repository = RemoteDoctorRepository(client, store) # type: ignore[arg-type]
|
||||
repository.login("doctor", "secret", remember_account=True)
|
||||
attempts = []
|
||||
|
||||
def offline(endpoint: str, _payload: dict, **kwargs: Any) -> Any:
|
||||
attempts.append((endpoint, kwargs["headers"]["token"]))
|
||||
raise ApiTransportError("offline")
|
||||
|
||||
monkeypatch.setattr(client, "post", offline)
|
||||
repository.logout()
|
||||
repository.logout()
|
||||
assert attempts == [("login/logout", "remote-token")]
|
||||
assert client.token == ""
|
||||
assert store.load_token() is None
|
||||
assert store.load_account() == "doctor"
|
||||
|
||||
|
||||
def test_app_close_during_login_retires_issued_token_before_transport_close(tmp_path: Path, monkeypatch: Any) -> None:
|
||||
client = _StubApiClient()
|
||||
store = TokenStore(tmp_path / "credentials.json", keyring_backend=None)
|
||||
repository = RemoteDoctorRepository(client, store) # type: ignore[arg-type]
|
||||
profile_started = Event()
|
||||
finish_profile = Event()
|
||||
get_profile = client.get
|
||||
closes = []
|
||||
|
||||
def pending_profile(endpoint: str) -> Any:
|
||||
profile_started.set()
|
||||
assert finish_profile.wait(3)
|
||||
return get_profile(endpoint)
|
||||
|
||||
monkeypatch.setattr(client, "get", pending_profile)
|
||||
monkeypatch.setattr(client, "close", lambda: closes.append(client.token), raising=False)
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||
login = pool.submit(repository.login, "doctor", "secret", remember_account=True)
|
||||
assert profile_started.wait(3)
|
||||
shutdown = pool.submit(repository.close)
|
||||
finish_profile.set()
|
||||
assert login.result(timeout=3).token == "remote-token"
|
||||
shutdown.result(timeout=3)
|
||||
assert store.load_account() == "doctor"
|
||||
assert store.load_token() is None
|
||||
assert closes == [""]
|
||||
assert client.post_calls[-1] == ("login/logout", {})
|
||||
assert client.post_tokens[-1] == "remote-token"
|
||||
|
||||
|
||||
def test_restore_never_sends_token_to_a_different_api_scope(tmp_path: Path) -> None:
|
||||
"""Changing the configured server invalidates automatic token reuse."""
|
||||
|
||||
|
||||
@@ -81,13 +81,13 @@ def _detail(appointment_id: int, patient_id: int, diagnosis_id: int) -> dict[str
|
||||
|
||||
|
||||
def _snapshot(model: str, version: int, stamp: str) -> dict[str, Any]:
|
||||
label = "OpenAI" if model == "openai" else "千问"
|
||||
label = {"openai": "OpenAI", "doubao": "豆包"}.get(model, "千问")
|
||||
return {
|
||||
"id": version * 10 + (2 if model == "openai" else 1),
|
||||
"id": version * 10 + {"openai": 2, "doubao": 3}.get(model, 1),
|
||||
"patient_id": 301,
|
||||
"model_key": model,
|
||||
"model_label": label,
|
||||
"model_name": "gpt-demo" if model == "openai" else "qwen-demo",
|
||||
"model_name": {"openai": "gpt-demo", "doubao": "doubao-demo"}.get(model, "qwen-demo"),
|
||||
"version": version,
|
||||
"generated_at": stamp,
|
||||
"report": {
|
||||
@@ -211,7 +211,7 @@ def test_saved_history_is_rendered_without_automatic_generation(
|
||||
page.close()
|
||||
|
||||
|
||||
def test_empty_database_and_manual_refresh_append_qwen_then_openai(
|
||||
def test_empty_database_and_manual_refresh_append_every_model_in_order(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
) -> None:
|
||||
@@ -254,18 +254,20 @@ def test_empty_database_and_manual_refresh_append_qwen_then_openai(
|
||||
page._select_record(detail["appointment"])
|
||||
application.processEvents()
|
||||
|
||||
assert repository.calls == [("list", 302), ("generate", "qwen"), ("generate", "openai")]
|
||||
assert [len(page._ai_analysis_histories[key]) for key in ("qwen", "openai")] == [1, 1]
|
||||
assert repository.calls == [
|
||||
("list", 302), ("generate", "qwen"), ("generate", "openai"), ("generate", "doubao"),
|
||||
]
|
||||
assert [len(page._ai_analysis_histories[key]) for key in ("qwen", "openai", "doubao")] == [1, 1, 1]
|
||||
|
||||
page.ai_analysis_regenerate_button.click()
|
||||
application.processEvents()
|
||||
|
||||
assert repository.calls[-2:] == [("generate", "qwen"), ("generate", "openai")]
|
||||
assert [len(page._ai_analysis_histories[key]) for key in ("qwen", "openai")] == [2, 2]
|
||||
assert repository.calls[-3:] == [("generate", "qwen"), ("generate", "openai"), ("generate", "doubao")]
|
||||
assert [len(page._ai_analysis_histories[key]) for key in ("qwen", "openai", "doubao")] == [2, 2, 2]
|
||||
page.close()
|
||||
|
||||
|
||||
def test_openai_failure_keeps_new_qwen_snapshot(
|
||||
def test_openai_failure_keeps_new_qwen_snapshot_and_still_generates_doubao(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
) -> None:
|
||||
@@ -281,7 +283,7 @@ def test_openai_failure_keeps_new_qwen_snapshot(
|
||||
def generate_patient_ai_report(self, patient_id: int, *, model: str) -> dict[str, Any]:
|
||||
if model == "openai":
|
||||
raise RuntimeError("OpenAI 暂时不可用")
|
||||
row = _snapshot("qwen", 1, "2026-08-14 10:30:00")
|
||||
row = _snapshot(model, 1, "2026-08-14 10:30:00")
|
||||
row["patient_id"] = patient_id
|
||||
return {
|
||||
"patient_id": patient_id,
|
||||
@@ -305,7 +307,11 @@ def test_openai_failure_keeps_new_qwen_snapshot(
|
||||
assert page.ai_summary_label.text() == "千问第 1 版诊断建议"
|
||||
assert len(page._ai_analysis_histories["qwen"]) == 1
|
||||
assert page._ai_analysis_model_states["openai"] == "error"
|
||||
assert "千问新快照已保留" in page.ai_analysis_secondary_status.text()
|
||||
# 第二个模型失败不阻断第三个模型补齐。
|
||||
assert page._ai_analysis_model_states["doubao"] == "success"
|
||||
assert len(page._ai_analysis_histories["doubao"]) == 1
|
||||
assert "千问结果已保留" in page.ai_analysis_secondary_status.text()
|
||||
assert "OpenAI新快照生成失败" in page.ai_analysis_secondary_status.text()
|
||||
page.close()
|
||||
|
||||
|
||||
|
||||
@@ -528,6 +528,10 @@ def test_order_action_matrix_requires_exact_permissions_and_states(
|
||||
"ddcode",
|
||||
"withdraw",
|
||||
]
|
||||
for submission_time, review_ready in ((0, False), (1_760_000_000, False), (1_760_000_000, True)):
|
||||
current = {**pending, "review_submitted_at": submission_time, "can_review_prescription": review_ready}
|
||||
available = {key for key, _label, _danger in workspace._available_actions(current)}
|
||||
assert ("audit_prescription" in available) is review_ready
|
||||
assert [key for key, _label, _danger in workspace._available_actions(shipped)] == [
|
||||
"revoke_pay_audit",
|
||||
"ddcode",
|
||||
@@ -618,6 +622,37 @@ def test_order_approval_routes_unsigned_prescription_before_audit(
|
||||
application.processEvents()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("review_signed", [False, True])
|
||||
def test_order_approval_requires_pharmacist_signature_when_enabled(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
review_signed: bool,
|
||||
) -> None:
|
||||
signed_at = 1_760_000_000
|
||||
status = {
|
||||
"enabled": True, "required": True, "environment": "sandbox", "status": "signed",
|
||||
"can_sign": False, "can_download": True, "review_submitted_at": signed_at - 10,
|
||||
"review_required": True, "review_signature_time": signed_at if review_signed else 0,
|
||||
"can_review_prescription": False,
|
||||
}
|
||||
row = {
|
||||
"id": 70, "prescription_id": 52, "prescription_audit_status": 0, "fulfillment_status": 1,
|
||||
"review_submitted_at": signed_at - 10, "can_review_prescription": True,
|
||||
}
|
||||
approved = []
|
||||
repository = SimpleNamespace(get_prescription_esign_status=lambda _id: status)
|
||||
page = PatientsPage(repository, PermissionSet(["tcm.prescriptionOrder/auditPrescription"]))
|
||||
monkeypatch.setattr(page, "_submit_order_audit", lambda order_id, **_kwargs: approved.append(order_id))
|
||||
monkeypatch.setattr(QInputDialog, "getItem", staticmethod(lambda *_args, **_kwargs: ("通过", True)))
|
||||
page._handle_order_action("audit_prescription", row)
|
||||
assert approved == ([70] if review_signed else [])
|
||||
if not review_signed:
|
||||
assert "管理后台" in page.order_workspace.banner.label.text()
|
||||
page.close()
|
||||
application.processEvents()
|
||||
|
||||
|
||||
def test_shell_uses_demo_session_menu_and_fits_minimum_window(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
|
||||
@@ -13,8 +13,8 @@ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from PySide6.QtCore import Qt, Signal
|
||||
from PySide6.QtGui import QDesktopServices
|
||||
from PySide6.QtCore import QBuffer, QIODevice, Qt, Signal
|
||||
from PySide6.QtGui import QColor, QDesktopServices, QImage
|
||||
from PySide6.QtTest import QTest
|
||||
from PySide6.QtWidgets import QApplication, QDialog, QFileDialog, QLineEdit, QWidget
|
||||
|
||||
@@ -714,7 +714,9 @@ def test_authentication_stays_embedded_and_only_server_readiness_can_sign(
|
||||
)
|
||||
dialog = esign_module.PrescriptionEsignDialog(repository, {"id": 7, "esign": state()})
|
||||
dialog.show()
|
||||
assert [label.text() for label in dialog.step_labels] == ["处方草稿已保存", "验证医生身份", "签名并完成"]
|
||||
assert [label.text() for label in dialog.step_labels if not label.isHidden()] == [
|
||||
"保存草稿", "验证医生身份", "医生签署",
|
||||
]
|
||||
assert dialog.start_button.isEnabled()
|
||||
assert not dialog.sign_button.isVisible()
|
||||
dialog.start_button.click()
|
||||
@@ -896,6 +898,75 @@ def test_signing_and_detail_display_archived_issue_and_signature_times(
|
||||
detail.close()
|
||||
|
||||
|
||||
def test_verified_pharmacist_updates_both_copies_signing_steps_and_log(
|
||||
immediate: None, tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
repository = Repository()
|
||||
repository.status = state(
|
||||
"signed", review_required=True, signature_time=1795000007, signature_time_source="tsa",
|
||||
)
|
||||
detail = prescription_module.PrescriptionDetailDialog({"id": 7}, repository=repository)
|
||||
signing = esign_module.PrescriptionEsignDialog(repository, {"id": 7})
|
||||
assert "待药师签署" in detail.esign_banner.label.text()
|
||||
assert "待药师签署" in signing.status_label.text()
|
||||
assert signing.review_step_label.accessibleDescription() == "当前步骤"
|
||||
assert not signing.review_step_label.isHidden() and signing.refresh_button.isEnabled()
|
||||
assert "管理后台" in signing.banner.label.text()
|
||||
assert "审核药师" not in detail.user_document.toPlainText()
|
||||
detail._saved_original = signing._saved_original = tmp_path / "doctor-only.pdf"
|
||||
|
||||
image = QImage(160, 60, QImage.Format.Format_ARGB32)
|
||||
image.fill(QColor("red"))
|
||||
buffer = QBuffer()
|
||||
assert buffer.open(QIODevice.OpenModeFlag.WriteOnly) and image.save(buffer, "PNG")
|
||||
signature = "data:image/png;base64," + bytes(buffer.data().toBase64()).decode("ascii")
|
||||
repository.status.update(
|
||||
doctor_signer_name="签名医生",
|
||||
review_signer_name="张药师",
|
||||
review_signature_time=1795000017,
|
||||
review_signature=signature,
|
||||
signing_log=[
|
||||
{"event": "doctor_signed", "time": 1795000007, "source": "tsa",
|
||||
"label": "医生已签署", "actor_name": "签名医生"},
|
||||
{"event": "pharmacist_signed", "time": 1795000017, "source": "tsa",
|
||||
"label": "药师已签署", "actor_name": "张药师", "message": "<b>签章验签成功</b>"},
|
||||
{"event": "invalid", "time": -1, "source": "system", "label": "无效记录"},
|
||||
],
|
||||
)
|
||||
detail.refresh_esign()
|
||||
signing.refresh()
|
||||
assert signing.review_step_label.accessibleDescription() == "已完成"
|
||||
assert "药师签署时间:2026-11-18 19:06:57(北京时间 · 可信时间戳)" in signing.signature_time_label.text()
|
||||
assert "医生与药师已签署" in detail.esign_banner.label.text()
|
||||
assert detail._saved_original is None and signing._saved_original is None
|
||||
assert detail.tabs.tabText(1) == "处方联"
|
||||
for document in (detail.document, detail.user_document):
|
||||
assert "审核药师" in document.toPlainText()
|
||||
assert "签名医生" in document.toPlainText()
|
||||
assert f'src="{signature}"' in document.toHtml()
|
||||
|
||||
log_views = []
|
||||
monkeypatch.setattr(
|
||||
esign_module.SigningLogDialog, "exec", lambda dialog: log_views.append(dialog.entries.toPlainText()),
|
||||
)
|
||||
detail.signing_log_button.click()
|
||||
signing.signing_log_button.click()
|
||||
assert len(log_views) == 2 and log_views[0] == log_views[1]
|
||||
assert "医生已签署 · 签名医生" in log_views[0]
|
||||
assert "药师已签署 · 张药师" in log_views[0]
|
||||
assert "2026-11-18 19:06:57(北京时间 · 可信时间戳)" in log_views[0]
|
||||
assert "<b>签章验签成功</b>" in log_views[0]
|
||||
assert "无效记录" not in log_views[0]
|
||||
|
||||
repository.status["review_signature"] = "https://example.test/forged.png"
|
||||
detail.refresh_esign()
|
||||
for document in (detail.document, detail.user_document):
|
||||
assert "张药师" in document.toPlainText()
|
||||
assert "forged.png" not in document.toHtml()
|
||||
detail.close()
|
||||
signing.close()
|
||||
|
||||
|
||||
def test_download_validates_original_and_hash_before_writing(
|
||||
immediate: None, tmp_path: Path
|
||||
) -> None:
|
||||
@@ -1124,6 +1195,187 @@ def test_reviewer_without_signing_authority_gets_doctor_instruction(
|
||||
page.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("previously_signed", [False, True])
|
||||
def test_issued_prescription_requires_upload_and_verified_doctor_signature_for_audit(
|
||||
immediate: None, monkeypatch: pytest.MonkeyPatch, previously_signed: bool,
|
||||
) -> None:
|
||||
signed = state("signed", review_required=False)
|
||||
pending = state("pending", review_required=False, can_sign=True)
|
||||
upload_attempts = []
|
||||
audit_calls = []
|
||||
row = {
|
||||
"id": 7, "audit_status": 0, "esign": signed if previously_signed else pending,
|
||||
"review_submitted_at": 0, "can_review_prescription": False,
|
||||
}
|
||||
|
||||
def upload(prescription_id: int) -> dict[str, Any]:
|
||||
upload_attempts.append(prescription_id)
|
||||
if len(upload_attempts) == 1:
|
||||
raise ApiBusinessError("上传失败,请重试")
|
||||
receipt = {"review_submitted_at": 1_760_000_000, "can_submit_for_review": False}
|
||||
row.update(receipt)
|
||||
row["can_review_prescription"] = previously_signed
|
||||
return receipt
|
||||
|
||||
def repository(owner: bool) -> Any:
|
||||
def status() -> dict[str, Any]:
|
||||
awaiting_upload = row["review_submitted_at"] == 0
|
||||
return {
|
||||
**row["esign"], "review_submitted_at": row["review_submitted_at"],
|
||||
"awaiting_upload": awaiting_upload, "can_submit_for_review": owner and awaiting_upload,
|
||||
"can_review_prescription": row["can_review_prescription"],
|
||||
}
|
||||
|
||||
return SimpleNamespace(
|
||||
list_prescriptions=lambda **_filters: {"lists": [Prescription.from_dict({**row, "esign": status()})], "count": 1},
|
||||
get_prescription_esign_status=lambda _id: status(),
|
||||
submit_prescription_for_review=upload,
|
||||
audit_prescription=lambda prescription_id, **audit: audit_calls.append((prescription_id, audit)),
|
||||
)
|
||||
|
||||
def approve(dialog: Any) -> int:
|
||||
dialog._choose("approve")
|
||||
return dialog.result()
|
||||
|
||||
monkeypatch.setattr(page_module, "show_toast", lambda *_args: None)
|
||||
monkeypatch.setattr(page_module.AuditPrescriptionDialog, "exec", approve)
|
||||
doctor = page_module.PrescriptionsPage(repository(True), PermissionSet("cf.prescription/edit"))
|
||||
reviewer = page_module.PrescriptionsPage(repository(False), PermissionSet("cf.prescription/audit"))
|
||||
doctor.refresh()
|
||||
reviewer.refresh()
|
||||
assert page_module.prescription_status(doctor.table.current_data()) == ("待上传处方", "warning")
|
||||
assert doctor.audit_button.isHidden()
|
||||
assert reviewer.audit_button.isHidden()
|
||||
assert not reviewer.audit_button.isEnabled()
|
||||
assert reviewer.upload_button.isHidden()
|
||||
reviewer._audit_selected()
|
||||
assert not audit_calls
|
||||
|
||||
upload_button = doctor.upload_button
|
||||
assert upload_button.isEnabled() and not upload_button.isHidden()
|
||||
upload_button.click()
|
||||
assert "上传失败" in doctor.banner.label.text()
|
||||
assert upload_button.isEnabled()
|
||||
row_action = doctor.table.cellWidget(0, 2)
|
||||
row_upload = next(button for button in row_action.findChildren(type(upload_button)) if button.text() == "上传处方")
|
||||
row_upload.click()
|
||||
assert upload_attempts == [7, 7]
|
||||
assert upload_button.isHidden()
|
||||
if not previously_signed:
|
||||
assert page_module.prescription_status(doctor.table.current_data()) == ("待签名", "warning")
|
||||
assert doctor.audit_button.text() == "继续签署" and doctor.audit_button.isEnabled()
|
||||
reviewer.refresh()
|
||||
assert reviewer.audit_button.isHidden()
|
||||
row.update(esign=signed)
|
||||
reviewer.refresh()
|
||||
assert reviewer.audit_button.isHidden()
|
||||
row["can_review_prescription"] = True
|
||||
doctor.refresh()
|
||||
assert page_module.prescription_status(doctor.table.current_data()) == ("待审核", "warning")
|
||||
assert page_module.can_audit(doctor.table.current_data())
|
||||
|
||||
reviewer.refresh()
|
||||
assert not reviewer.audit_button.isHidden()
|
||||
assert reviewer.audit_button.isEnabled()
|
||||
reviewer.audit_button.click()
|
||||
assert audit_calls == [(7, {"action": "approve", "remark": ""})]
|
||||
doctor.close()
|
||||
reviewer.close()
|
||||
|
||||
|
||||
def test_saved_draft_offers_explicit_upload_before_doctor_signing(
|
||||
immediate: None, monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
repository = Repository()
|
||||
repository.status = state(
|
||||
"pending", review_submitted_at=0, awaiting_upload=True, can_submit_for_review=True,
|
||||
can_review_prescription=False, review_required=True,
|
||||
)
|
||||
record = {
|
||||
"id": 7, "audit_status": 0, "esign": repository.status,
|
||||
"patient_name": "测试患者", "herbs": [{"name": "样例药材甲", "dosage": 1}],
|
||||
}
|
||||
|
||||
def upload(prescription_id: int) -> dict[str, Any]:
|
||||
assert prescription_id == 7
|
||||
repository.calls.append("upload")
|
||||
receipt = {"review_submitted_at": 1_760_000_000, "can_submit_for_review": False}
|
||||
if repository.calls.count("upload") == 1:
|
||||
raise ApiBusinessError("上传失败,请重试")
|
||||
repository.status = {**repository.status, **receipt, "awaiting_upload": False}
|
||||
return receipt
|
||||
|
||||
def finish(dialog: esign_module.PrescriptionEsignDialog) -> None:
|
||||
dialog.resize(dialog.minimumSize())
|
||||
dialog.show()
|
||||
preview = dialog.prescription_preview
|
||||
assert dialog.workspace_splitter.widget(0) is preview
|
||||
assert dialog.workspace_splitter.widget(1) is dialog.workflow_panel
|
||||
assert preview.geometry().right() < dialog.workflow_panel.geometry().left()
|
||||
assert "样例药材甲" in preview.paper.toPlainText()
|
||||
assert dialog.workflow_panel.isAncestorOf(dialog.upload_button)
|
||||
assert [label.text() for label in dialog.step_labels if not label.isHidden()] == [
|
||||
"保存草稿", "上传处方", "验证医生身份", "医生签署", "药师审核签署",
|
||||
]
|
||||
assert dialog.step_labels[1].accessibleDescription() == "当前步骤"
|
||||
assert dialog.upload_button.isVisible() and not dialog.start_button.isEnabled()
|
||||
assert repository.calls == ["status"]
|
||||
dialog.start()
|
||||
assert repository.calls == ["status"]
|
||||
dialog.upload_button.click()
|
||||
assert "上传失败" in dialog.banner.label.text()
|
||||
assert dialog.upload_button.isEnabled() and not dialog.start_button.isEnabled()
|
||||
dialog.upload_button.click()
|
||||
assert repository.calls == ["status", "upload", "upload", "status"]
|
||||
assert dialog.step_labels[1].accessibleDescription() == "已完成"
|
||||
assert dialog.step_labels[2].accessibleDescription() == "当前步骤"
|
||||
assert dialog.upload_button.isHidden() and dialog.start_button.isEnabled()
|
||||
dialog.close()
|
||||
|
||||
monkeypatch.setattr(repository, "submit_prescription_for_review", upload, raising=False)
|
||||
monkeypatch.setattr(esign_module.PrescriptionEsignDialog, "exec", finish)
|
||||
assert esign_module.saved_prescription_message(record, "已提交审核") == (
|
||||
"处方草稿已保存。" + esign_module.PRESCRIPTION_UPLOAD_BEFORE_SIGNING_PROMPT, "success",
|
||||
)
|
||||
assert not esign_module.resume_saved_prescription(repository, record, None)
|
||||
|
||||
|
||||
def test_review_submission_repository_uses_prescription_id_and_validates_receipt() -> None:
|
||||
calls = []
|
||||
response = {"review_submitted_at": 1_760_000_000, "can_submit_for_review": False}
|
||||
|
||||
def post(endpoint: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
calls.append((endpoint, payload))
|
||||
return response.copy()
|
||||
|
||||
repository = RemoteDoctorRepository(SimpleNamespace(post=post))
|
||||
assert repository.submit_prescription_for_review(7) == response
|
||||
assert calls == [("tcm.prescription/submitForReview", {"id": 7})]
|
||||
response["review_submitted_at"] = 0
|
||||
with pytest.raises(ApiProtocolError, match="处方上传结果格式不正确"):
|
||||
repository.submit_prescription_for_review(7)
|
||||
|
||||
|
||||
def test_signed_prescription_details_show_upload_before_pharmacist_signing(immediate: None) -> None:
|
||||
signature = Repository()
|
||||
signature.status = state("signed", review_required=True, review_submitted_at=0)
|
||||
record = {"id": 7, "audit_status": 0, "esign": signature.status, "review_submitted_at": 0}
|
||||
assert esign_module.saved_prescription_message(record, "已提交审核") == (
|
||||
"处方已保存,医生已签署。" + esign_module.PRESCRIPTION_UPLOAD_PROMPT, "success",
|
||||
)
|
||||
signing = esign_module.PrescriptionEsignDialog(signature, record)
|
||||
detail = prescription_module.PrescriptionDetailDialog(record, repository=signature)
|
||||
assert "待上传处方" in signing.status_label.text()
|
||||
assert "待上传处方" in detail.status_banner.label.text()
|
||||
signature.status = {**signature.status, "review_submitted_at": 1_760_000_000}
|
||||
signing.refresh()
|
||||
detail.refresh_esign()
|
||||
assert "待药师签署" in signing.status_label.text()
|
||||
assert "待审核" in detail.status_banner.label.text()
|
||||
signing.close()
|
||||
detail.close()
|
||||
|
||||
|
||||
def test_saved_response_without_state_warns_without_claiming_completion(
|
||||
immediate: None, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
|
||||
@@ -10,6 +10,7 @@ import pytest
|
||||
from PySide6.QtCore import QBuffer, QDate, QEvent, QIODevice, QObject, QSize, Qt
|
||||
from PySide6.QtGui import QColor, QImage, QPainter, QTextDocument
|
||||
from PySide6.QtPdf import QPdfDocument
|
||||
from PySide6.QtTest import QTest
|
||||
from PySide6.QtWidgets import QApplication, QComboBox, QDialog, QMessageBox, QPushButton, QWidget
|
||||
|
||||
from doctor_workstation import app as app_module
|
||||
@@ -21,6 +22,7 @@ from doctor_workstation.ui.dialogs.prescription import (
|
||||
PrescriptionDetailDialog,
|
||||
PrescriptionEditorDialog,
|
||||
PrescriptionOrderDialog,
|
||||
PrescriptionSigningPreview,
|
||||
PrescriptionTemplateDialog,
|
||||
RemoteMedicineComboBox,
|
||||
build_prescription_clinical_diagnosis,
|
||||
@@ -479,6 +481,47 @@ def test_editor_builds_complete_add_payload(
|
||||
application.processEvents()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("saved_dietary_taboo", [["辛辣食物", "浓茶"], "辛辣食物, 浓茶"])
|
||||
def test_editor_dietary_taboo_popup_supports_consecutive_selections(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
saved_dietary_taboo: list[str] | str,
|
||||
) -> None:
|
||||
editor = PrescriptionEditorDialog(
|
||||
SimpleNamespace(), prescription={"dietary_taboo": saved_dietary_taboo}, mode="edit"
|
||||
)
|
||||
editor.show()
|
||||
editor.body_scroll.ensureWidgetVisible(editor.dietary_taboo)
|
||||
application.processEvents()
|
||||
|
||||
selector = editor.dietary_taboo
|
||||
field = selector.lineEdit()
|
||||
assert field.text() == "辛辣食物、浓茶"
|
||||
QTest.mouseClick(field, Qt.MouseButton.LeftButton)
|
||||
view = selector.view()
|
||||
assert view.isVisible()
|
||||
|
||||
for row, expected in (
|
||||
(1, "辛辣食物、生冷食物、浓茶"),
|
||||
(2, "辛辣食物、生冷食物、油腻食物、浓茶"),
|
||||
(0, "生冷食物、油腻食物、浓茶"),
|
||||
):
|
||||
point = view.visualRect(selector.model().index(row, 0)).center()
|
||||
QTest.mouseClick(view.viewport(), Qt.MouseButton.LeftButton, pos=point)
|
||||
assert view.isVisible()
|
||||
assert field.text() == expected
|
||||
|
||||
QTest.keyClick(view, Qt.Key.Key_Down)
|
||||
QTest.keyClick(view, Qt.Key.Key_Space)
|
||||
assert view.isVisible()
|
||||
QTest.keyClick(view, Qt.Key.Key_Escape)
|
||||
assert not view.isVisible()
|
||||
assert field.text() == "油腻食物、浓茶"
|
||||
assert editor.payload()["dietary_taboo"] == ["油腻食物", "浓茶"]
|
||||
editor.close()
|
||||
application.processEvents()
|
||||
|
||||
|
||||
def test_esign_draft_save_retries_without_discarding_form(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
@@ -645,29 +688,146 @@ def test_prescription_window_footer_preserves_draft_on_void_failure(
|
||||
|
||||
|
||||
@pytest.mark.parametrize("variant", ["internal", "user"])
|
||||
def test_prescription_preview_scales_signature_proportionately(
|
||||
application: QApplication, variant: str,
|
||||
@pytest.mark.parametrize("print_layout", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
("image_size", "expected_size"),
|
||||
[((300, 150), (40, 20)), ((384, 60), (64, 10)), ((20, 10), (20, 10))],
|
||||
)
|
||||
def test_prescription_slip_scales_both_signatures_proportionately(
|
||||
application: QApplication,
|
||||
variant: str,
|
||||
print_layout: bool,
|
||||
image_size: tuple[int, int],
|
||||
expected_size: tuple[int, int],
|
||||
) -> None:
|
||||
image = QImage(300, 150, QImage.Format.Format_ARGB32)
|
||||
image.fill(QColor("black"))
|
||||
buffer = QBuffer()
|
||||
assert buffer.open(QIODevice.OpenModeFlag.WriteOnly)
|
||||
assert image.save(buffer, "PNG")
|
||||
signature = "data:image/png;base64," + bytes(buffer.data().toBase64()).decode("ascii")
|
||||
signatures = []
|
||||
for color in ("black", "red"):
|
||||
image = QImage(*image_size, QImage.Format.Format_ARGB32)
|
||||
image.fill(QColor(color))
|
||||
buffer = QBuffer()
|
||||
assert buffer.open(QIODevice.OpenModeFlag.WriteOnly)
|
||||
assert image.save(buffer, "PNG")
|
||||
signatures.append("data:image/png;base64," + bytes(buffer.data().toBase64()).decode("ascii"))
|
||||
|
||||
doctor_signature, review_signature = signatures
|
||||
rendered = render_prescription_html({
|
||||
"doctor_signature": doctor_signature,
|
||||
"esign": {
|
||||
"status": "signed",
|
||||
"review_signer_name": "张药师",
|
||||
"review_signature_time": 1795000017,
|
||||
"review_signature": review_signature,
|
||||
},
|
||||
}, variant=variant, print_layout=print_layout)
|
||||
width, height = expected_size
|
||||
for signature in signatures:
|
||||
assert f'src="{signature}" width="{width}" height="{height}"' in rendered
|
||||
|
||||
document = QTextDocument()
|
||||
document.setHtml(render_prescription_html({"doctor_signature": signature}, variant=variant))
|
||||
signature_sizes = []
|
||||
document.setHtml(rendered)
|
||||
signature_sizes = {}
|
||||
block = document.begin()
|
||||
while block.isValid():
|
||||
fragments = block.begin()
|
||||
while not fragments.atEnd():
|
||||
image_format = fragments.fragment().charFormat().toImageFormat()
|
||||
if image_format.name() == signature:
|
||||
signature_sizes.append((image_format.width(), image_format.height()))
|
||||
if image_format.name() in signatures:
|
||||
signature_sizes[image_format.name()] = (image_format.width(), image_format.height())
|
||||
fragments += 1
|
||||
block = block.next()
|
||||
expected_size = (72, 36) if variant == "internal" else (48, 24)
|
||||
assert signature_sizes == [expected_size]
|
||||
assert signature_sizes == dict.fromkeys(signatures, expected_size)
|
||||
|
||||
|
||||
def test_signing_preview_uses_full_seed_and_updates_visible_signatures(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
) -> None:
|
||||
def unexpected_detail(prescription_id: int) -> None:
|
||||
pytest.fail(f"Complete prescription {prescription_id} should not be reloaded")
|
||||
|
||||
prescription = Prescription.from_dict({
|
||||
"id": 71,
|
||||
"patient_name": "虚构患者",
|
||||
"clinical_diagnosis": "测试诊断",
|
||||
"prescription_type": "饮片",
|
||||
"dosage_amount": 20,
|
||||
"dosage_unit": "ml",
|
||||
"dose_count": 3,
|
||||
"herbs": [{"name": "白术", "dosage": 6}],
|
||||
"esign": {"status": "pending"},
|
||||
})
|
||||
preview = PrescriptionSigningPreview(SimpleNamespace(get_prescription=unexpected_detail), prescription)
|
||||
assert preview.paper is not None and preview.paper.isReadOnly()
|
||||
document = preview.paper.document()
|
||||
for text in ("虚构患者", "测试诊断", "白术 (6克)", "18克", "一次20ml"):
|
||||
assert text in document.toPlainText()
|
||||
|
||||
revision = document.revision()
|
||||
preview.set_esign_state({"status": "pending", "message": "等待核验"})
|
||||
assert document.revision() == revision
|
||||
signed = {
|
||||
"status": "signed",
|
||||
"doctor_signer_name": "签名医生",
|
||||
"review_signer_name": "审核药师姓名",
|
||||
"review_signature_time": 1795000017,
|
||||
}
|
||||
preview.set_esign_state(signed)
|
||||
for text in ("签名医生", "审核药师姓名", "白术 (6克)"):
|
||||
assert text in document.toPlainText()
|
||||
revision = document.revision()
|
||||
preview.set_esign_state(signed | {"review_signature_time": 1795000020})
|
||||
assert document.revision() == revision
|
||||
|
||||
|
||||
def test_signing_preview_retries_wrong_detail_and_ignores_stale_response(
|
||||
application: QApplication,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
requests = []
|
||||
|
||||
def defer_detail(function: Any, prescription_id: int, *, on_success: Any, on_error: Any) -> None:
|
||||
requests.append((prescription_id, on_success))
|
||||
|
||||
monkeypatch.setattr(dialog_module, "run_async", defer_detail)
|
||||
seed = {"id": 72, "esign": {"status": "pending"}}
|
||||
repository = SimpleNamespace(get_prescription=lambda _prescription_id: None)
|
||||
preview = PrescriptionSigningPreview(repository, seed)
|
||||
assert "正在加载" in preview.status_label.text()
|
||||
assert requests[0][0] == 72
|
||||
preview.set_esign_state({"status": "signed", "doctor_signer_name": "签名医生"})
|
||||
|
||||
herbs = [{"name": "甘草", "dosage": 3}]
|
||||
requests[0][1]({"id": 73, "patient_name": "其他患者", "herbs": herbs})
|
||||
assert preview.paper is None
|
||||
assert "不匹配" in preview.status_label.text() and not preview.retry_button.isHidden()
|
||||
preview.retry_button.click()
|
||||
assert requests[1][0] == 72
|
||||
requests[0][1](seed | {"patient_name": "过时结果", "herbs": herbs})
|
||||
assert preview.paper is None
|
||||
requests[1][1](seed | {"patient_name": "当前患者", "herbs": herbs})
|
||||
assert preview.paper is not None
|
||||
text = preview.paper.toPlainText()
|
||||
assert "当前患者" in text and "甘草 (3克)" in text and "签名医生" in text
|
||||
|
||||
|
||||
def test_signing_preview_renders_an_intentionally_empty_saved_prescription(
|
||||
application: QApplication,
|
||||
immediate_async: None,
|
||||
) -> None:
|
||||
prescription = Prescription.from_dict({
|
||||
"id": 73,
|
||||
"patient_name": "虚构患者",
|
||||
"clinical_diagnosis": "系统代开诊断",
|
||||
"is_system_auto": 1,
|
||||
"herbs": [],
|
||||
})
|
||||
preview = PrescriptionSigningPreview(
|
||||
SimpleNamespace(get_prescription=lambda _prescription_id: prescription),
|
||||
{"id": 73},
|
||||
)
|
||||
assert preview.paper is not None
|
||||
for text in ("虚构患者", "系统代开诊断", "暂无药材明细"):
|
||||
assert text in preview.paper.toPlainText()
|
||||
|
||||
|
||||
def test_unsigned_draft_shows_signing_state_before_audit() -> None:
|
||||
|
||||
@@ -740,7 +740,7 @@ def test_silent_queue_polls_reuse_rows_and_do_not_restart_detail_or_ai(
|
||||
|
||||
assert repository.queue_calls == 4
|
||||
assert repository.detail_calls == 1
|
||||
assert repository.analysis_calls == [(210, "qwen"), (210, "openai")]
|
||||
assert repository.analysis_calls == [(210, "qwen"), (210, "openai"), (210, "doubao")]
|
||||
assert page.queue_list.item(0) is first_item
|
||||
assert page.queue_list.itemWidget(first_item) is first_row
|
||||
assert first_item.data(Qt.ItemDataRole.UserRole)["server_revision"] == 4
|
||||
@@ -748,7 +748,7 @@ def test_silent_queue_polls_reuse_rows_and_do_not_restart_detail_or_ai(
|
||||
|
||||
page.refresh()
|
||||
assert repository.detail_calls == 2
|
||||
assert repository.analysis_calls == [(210, "qwen"), (210, "openai")]
|
||||
assert repository.analysis_calls == [(210, "qwen"), (210, "openai"), (210, "doubao")]
|
||||
assert page.queue_list.item(0) is first_item
|
||||
|
||||
page.close()
|
||||
@@ -1683,14 +1683,14 @@ def test_reception_auto_loads_structured_ai_analysis_and_matches_reference_geome
|
||||
page._select_record(detail["appointment"])
|
||||
application.processEvents()
|
||||
|
||||
assert analysis_calls == [(233, "qwen"), (233, "openai")]
|
||||
assert analysis_calls == [(233, "qwen"), (233, "openai"), (233, "doubao")]
|
||||
assert [
|
||||
(
|
||||
page.ai_analysis_model_selector.itemText(index),
|
||||
page.ai_analysis_model_selector.itemData(index),
|
||||
)
|
||||
for index in range(page.ai_analysis_model_selector.count())
|
||||
] == [("千问", "qwen"), ("OpenAI", "openai")]
|
||||
] == [("千问", "qwen"), ("OpenAI", "openai"), ("豆包", "doubao")]
|
||||
assert page.ai_analysis_model_selector.currentData() == "qwen"
|
||||
assert page._ai_analysis_state == "success"
|
||||
assert page.ai_analysis_stack.currentWidget() is page.ai_analysis_content_page
|
||||
@@ -1798,7 +1798,7 @@ def test_reception_dual_ai_queues_openai_only_after_qwen_is_visible(
|
||||
assert len(queued_async) == 2
|
||||
assert calls == []
|
||||
assert page.ai_analysis_model_selector.currentData() == "qwen"
|
||||
assert page._ai_analysis_model_states == {"qwen": "loading", "openai": "waiting"}
|
||||
assert page._ai_analysis_model_states == {"qwen": "loading", "openai": "waiting", "doubao": "waiting"}
|
||||
|
||||
qwen_result = queued_async[1]["function"](*queued_async[1]["args"])
|
||||
assert calls == [(283, "qwen")]
|
||||
@@ -2009,6 +2009,7 @@ def test_reception_ai_analysis_permission_error_retry_states(
|
||||
(234, "qwen"),
|
||||
(234, "qwen"),
|
||||
(234, "openai"),
|
||||
(234, "doubao"),
|
||||
]
|
||||
assert page._ai_analysis_state == "success"
|
||||
assert page.ai_analysis_expand_button.isEnabled()
|
||||
@@ -2063,14 +2064,16 @@ def test_saved_diagnosis_forces_a_fresh_structured_ai_analysis(
|
||||
PermissionSet(["tcm.diagnosis/aiAnalysis"]),
|
||||
)
|
||||
page.refresh()
|
||||
assert repository.analysis_calls == [(238, "qwen"), (238, "openai")]
|
||||
assert repository.analysis_calls == [(238, "qwen"), (238, "openai"), (238, "doubao")]
|
||||
|
||||
page._diagnosis_saved()
|
||||
assert repository.analysis_calls == [
|
||||
(238, "qwen"),
|
||||
(238, "openai"),
|
||||
(238, "doubao"),
|
||||
(238, "qwen"),
|
||||
(238, "openai"),
|
||||
(238, "doubao"),
|
||||
]
|
||||
assert "第 2 次qwen分析" in page.ai_risk_label.text()
|
||||
|
||||
@@ -2172,7 +2175,7 @@ def test_ai_analysis_dialog_switches_complete_cached_payloads_without_requests(
|
||||
calls_before_dialog = list(repository.analysis_calls)
|
||||
page.ai_analysis_expand_button.click()
|
||||
|
||||
assert calls_before_dialog == [(239, "qwen"), (239, "openai")]
|
||||
assert calls_before_dialog == [(239, "qwen"), (239, "openai"), (239, "doubao")]
|
||||
assert repository.analysis_calls == calls_before_dialog
|
||||
assert len(dialogs) == 1
|
||||
dialog = dialogs[0]
|
||||
|
||||
@@ -782,6 +782,24 @@ def test_remote_diagnosis_ai_stream_normalises_chunks_in_order() -> None:
|
||||
assert client.post_calls == []
|
||||
|
||||
|
||||
def test_remote_diagnosis_ai_stream_sends_only_a_whitelisted_selected_model() -> None:
|
||||
payloads: list[dict[str, Any]] = []
|
||||
|
||||
class StreamingClient(RecordingClient):
|
||||
def post_event_stream(self, endpoint: str, payload: dict[str, Any], **kwargs: Any):
|
||||
payloads.append(dict(payload))
|
||||
yield {"event": "done", "data": {"model_label": "豆包", "answer": "完成"}}
|
||||
|
||||
repository = RemoteDoctorRepository(StreamingClient())
|
||||
list(repository.stream_diagnosis_ai(501, "请总结", task="summary", model="doubao"))
|
||||
list(repository.stream_diagnosis_ai(501, "请总结", task="summary"))
|
||||
assert payloads[0]["model"] == "doubao"
|
||||
assert "model" not in payloads[1]
|
||||
with pytest.raises(ValueError, match="qwen, openai or doubao"):
|
||||
list(repository.stream_diagnosis_ai(501, "请总结", model="deepseek"))
|
||||
assert len(payloads) == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize("status_code", [404, 405])
|
||||
def test_remote_diagnosis_ai_stream_falls_back_for_missing_route(status_code: int) -> None:
|
||||
class MissingStreamClient(RecordingClient):
|
||||
@@ -915,7 +933,7 @@ def test_remote_diagnosis_ai_analysis_uses_exact_post_contract() -> None:
|
||||
|
||||
calls_before_validation = list(client.post_calls)
|
||||
timeouts_before_validation = list(client.timeouts)
|
||||
with pytest.raises(ValueError, match="qwen or openai"):
|
||||
with pytest.raises(ValueError, match="qwen, openai or doubao"):
|
||||
repository.get_diagnosis_ai_analysis(501, model="invalid") # type: ignore[arg-type]
|
||||
with pytest.raises(ValueError, match="positive"):
|
||||
repository.get_diagnosis_ai_analysis(0)
|
||||
|
||||
@@ -167,6 +167,18 @@ def shell_window(
|
||||
application.processEvents()
|
||||
|
||||
|
||||
def test_minimize_preserves_session_and_close_requests_application_exit(
|
||||
shell_window: ShellWindow, application: QApplication
|
||||
) -> None:
|
||||
exits = []
|
||||
shell_window.close_requested.connect(lambda: exits.append(True))
|
||||
shell_window.showMinimized()
|
||||
application.processEvents()
|
||||
assert exits == []
|
||||
shell_window.close()
|
||||
assert exits == [True]
|
||||
|
||||
|
||||
def test_legacy_shell_matches_reference_geometry_at_both_acceptance_sizes(
|
||||
application: QApplication,
|
||||
shell_window: ShellWindow,
|
||||
|
||||
@@ -18,6 +18,7 @@ from PySide6.QtWidgets import (
|
||||
from doctor_workstation import app as app_module
|
||||
from doctor_workstation.app import ApplicationController
|
||||
from doctor_workstation.config import AppConfig
|
||||
from doctor_workstation.core import Session
|
||||
from doctor_workstation.core.errors import AuthenticationExpiredError
|
||||
from doctor_workstation.services import DemoDoctorRepository
|
||||
from doctor_workstation.ui import login as login_module
|
||||
@@ -186,6 +187,65 @@ def test_controller_session_expiry_returns_to_login_once() -> None:
|
||||
assert messages == ["登录状态已失效,请重新登录。"]
|
||||
|
||||
|
||||
def test_idle_heartbeat_is_single_flight_and_offline_wake_observes_cutoff(monkeypatch: Any) -> None:
|
||||
now = [100.0]
|
||||
queued = []
|
||||
messages = []
|
||||
timer_delays = []
|
||||
session = Session(token="first", desktop_expires_at=200)
|
||||
repository = SimpleNamespace(desktop_heartbeat=lambda _token: 200)
|
||||
controller = SimpleNamespace(
|
||||
current_repository=repository, _desktop_session=session, _shutting_down=False,
|
||||
_heartbeat_pending=False, _next_heartbeat_at=100, _session_workers=object(),
|
||||
_desktop_timer=SimpleNamespace(start=timer_delays.append),
|
||||
_logout=lambda *, message: messages.append(message),
|
||||
)
|
||||
controller._check_desktop_session = lambda: ApplicationController._check_desktop_session(controller)
|
||||
monkeypatch.setattr(app_module, "time", SimpleNamespace(time=lambda: now[0]))
|
||||
monkeypatch.setattr(app_module, "run_async", lambda fn, token, **opts: queued.append((fn, token, opts)))
|
||||
|
||||
controller._check_desktop_session()
|
||||
controller._check_desktop_session()
|
||||
assert len(queued) == 1 and queued[0][:2] == (repository.desktop_heartbeat, "first")
|
||||
queued[0][2]["on_error"](RuntimeError("offline"))
|
||||
now[0] = 114
|
||||
controller._check_desktop_session()
|
||||
assert len(queued) == 1
|
||||
now[0] = 115
|
||||
controller._check_desktop_session()
|
||||
assert len(queued) == 2
|
||||
queued[1][2]["on_success"](400)
|
||||
assert session.desktop_expires_at == 200
|
||||
now[0] = 199.75
|
||||
controller._check_desktop_session()
|
||||
assert timer_delays[-1] == 250
|
||||
assert not messages
|
||||
now[0] = 205 # Resume with a heartbeat still in flight.
|
||||
controller._check_desktop_session()
|
||||
assert len(queued) == 3
|
||||
assert messages == ["已到北京时间 05:00,请重新登录医生工作站。"]
|
||||
|
||||
|
||||
def test_old_worker_expiry_cannot_log_out_new_account() -> None:
|
||||
application = QApplication.instance() or QApplication([])
|
||||
errors: list[Exception] = []
|
||||
workers = []
|
||||
pool = SimpleNamespace(start=lambda worker, _priority: workers.append(worker))
|
||||
|
||||
def expired() -> None:
|
||||
raise AuthenticationExpiredError("first session expired", code=-1)
|
||||
|
||||
try:
|
||||
set_authentication_expired_handler(lambda error: errors.append(error) is None)
|
||||
widget_module.run_async(expired, on_error=errors.append, pool=pool)
|
||||
set_authentication_expired_handler(lambda error: errors.append(error) is None)
|
||||
workers[0].run()
|
||||
application.processEvents()
|
||||
assert not errors
|
||||
finally:
|
||||
set_authentication_expired_handler(None)
|
||||
|
||||
|
||||
def test_persisted_session_restore_blocks_manual_submit_before_worker_start(
|
||||
monkeypatch: Any,
|
||||
) -> None:
|
||||
|
||||
+113
-113
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
Vendored
+2
-2
@@ -6,8 +6,8 @@
|
||||
<meta name="color-scheme" content="light" />
|
||||
<link rel="icon" type="image/png" href="./favicon.png" />
|
||||
<title>视频面诊</title>
|
||||
<script type="module" crossorigin src="./assets/index-D15F7NRw.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="./assets/index-Do0GoLfO.css">
|
||||
<script type="module" crossorigin src="./assets/index-DnfCezBT.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="./assets/index-s1DhGM4I.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
|
||||
@@ -10,7 +10,7 @@ import { transcriptionStatus } from './transcription-status'
|
||||
import { emptyVideoAiState } from './video-ai-types'
|
||||
import type { VideoAiState } from './video-ai-types'
|
||||
import { appendAiDraft, shouldClearSubmittedDraft } from './im-ai'
|
||||
import type { ImAiAction, ImAiState } from './im-ai'
|
||||
import type { ImAiAction, ImAiModel, ImAiState } from './im-ai'
|
||||
import { aiPanelBounds, clampAiPanelWidth, resizeAiPanelByKey } from './im-ai-layout'
|
||||
|
||||
interface ChatMessage {
|
||||
@@ -83,6 +83,7 @@ const props = defineProps<{
|
||||
onRequestImAi: (action: ImAiAction) => void
|
||||
onRegenerateImAi: (action: ImAiAction) => void
|
||||
onCancelImAi: () => void
|
||||
onImAiModel?: (model: ImAiModel) => void
|
||||
onSendText: (text: string) => Promise<void>
|
||||
onSendAttachment: (file: File) => Promise<void>
|
||||
onLoadMore: () => Promise<void>
|
||||
@@ -792,6 +793,7 @@ watch(
|
||||
@request="onRequestImAi"
|
||||
@regenerate="onRegenerateImAi"
|
||||
@cancel="onCancelImAi"
|
||||
@model="onImAiModel?.($event)"
|
||||
@apply="applyAiDraft"
|
||||
@close="closeAi"
|
||||
@open-diagnosis="runAction(onOpenDiagnosis)"
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, ref, watch } from 'vue'
|
||||
import type { ImAiAction, ImAiState } from './im-ai'
|
||||
import { IM_AI_MODELS, IM_AI_MODEL_LABELS } from './im-ai'
|
||||
import type { ImAiAction, ImAiModel, ImAiState } from './im-ai'
|
||||
import { renderImAiMarkdown } from './im-ai-markdown'
|
||||
|
||||
const props = defineProps<{
|
||||
@@ -17,6 +18,7 @@ const emit = defineEmits<{
|
||||
apply: []
|
||||
close: []
|
||||
openDiagnosis: []
|
||||
model: [model: ImAiModel]
|
||||
}>()
|
||||
const panel = ref<HTMLElement | null>(null)
|
||||
const closeButton = ref<HTMLButtonElement | null>(null)
|
||||
@@ -27,6 +29,7 @@ const actions: { key: ImAiAction; label: string }[] = [
|
||||
{ key: 'followup', label: '建议追问' },
|
||||
{ key: 'reply', label: '起草回复' },
|
||||
]
|
||||
const model = ref<ImAiModel>('qwen')
|
||||
const busy = computed(() => ['loading', 'streaming'].includes(props.state.status))
|
||||
const pendingAction = computed(() => props.state.pendingAction || (busy.value ? props.state.action : null))
|
||||
const generating = computed(() => Boolean(pendingAction.value))
|
||||
@@ -52,6 +55,13 @@ watch([() => props.state.contextKey, () => props.state.action] as const, ([conte
|
||||
})
|
||||
}, { flush: 'pre' })
|
||||
|
||||
function selectModel(event: Event): void {
|
||||
const next = (event.target as HTMLSelectElement).value as ImAiModel
|
||||
if (!IM_AI_MODELS.includes(next)) return
|
||||
model.value = next
|
||||
emit('model', next)
|
||||
}
|
||||
|
||||
function regenerate(): void {
|
||||
if (!props.state.action || generating.value) return
|
||||
scrollPositions.delete(props.state.action)
|
||||
@@ -131,6 +141,12 @@ function onKeydown(event: KeyboardEvent): void {
|
||||
<span v-if="completedActions.includes(action.key)" class="im-ai-tool__saved" aria-label="已有内容">·</span>
|
||||
</button>
|
||||
</div>
|
||||
<label class="im-ai-model" title="之后的生成使用所选模型;已生成的内容保留原模型标注">
|
||||
<span>模型</span>
|
||||
<select :value="model" :disabled="!state.available || generating" @change="selectModel">
|
||||
<option v-for="key in IM_AI_MODELS" :key="key" :value="key">{{ IM_AI_MODEL_LABELS[key] }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<div ref="resultBody" class="im-ai-body" tabindex="0" aria-label="AI 结果">
|
||||
<div v-if="state.status === 'unavailable'" class="im-ai-empty">
|
||||
<strong>AI 助手暂不可用</strong>
|
||||
|
||||
@@ -12,10 +12,10 @@ const props = defineProps<{
|
||||
const emit = defineEmits<{ close: []; save: [] }>()
|
||||
const models = TONGUE_SCREENSHOT_MODELS
|
||||
const labels = TONGUE_SCREENSHOT_MODEL_LABELS
|
||||
const modelNames = models.map((model) => labels[model]).join(' + ')
|
||||
const activeModel = ref<TongueScreenshotModel>('qwen')
|
||||
const states = ref<Record<TongueScreenshotModel, TongueScreenshotPreviewState>>({
|
||||
qwen: emptyTongueScreenshotPreview(), openai: emptyTongueScreenshotPreview(),
|
||||
})
|
||||
const states = ref(Object.fromEntries(models.map((model) => [model, emptyTongueScreenshotPreview()])) as
|
||||
Record<TongueScreenshotModel, TongueScreenshotPreviewState>)
|
||||
const state = computed(() => states.value[activeModel.value])
|
||||
let userSelected = false
|
||||
let firstResultShown = false
|
||||
@@ -31,7 +31,8 @@ function controller(model: TongueScreenshotModel) {
|
||||
},
|
||||
})
|
||||
}
|
||||
const previews = { qwen: controller('qwen'), openai: controller('openai') }
|
||||
const previews = Object.fromEntries(models.map((model) => [model, controller(model)])) as
|
||||
Record<TongueScreenshotModel, ReturnType<typeof controller>>
|
||||
watch(() => props.image, (image) => {
|
||||
activeModel.value = 'qwen'; userSelected = false; firstResultShown = false
|
||||
for (const model of models) void previews[model].open(image)
|
||||
@@ -72,7 +73,7 @@ function retry(): void { void previews[activeModel.value].retry() }
|
||||
<section class="screenshot-dialog">
|
||||
<header>
|
||||
<div>
|
||||
<p class="eyebrow">患者视频截图 · 千问 + GPT</p>
|
||||
<p class="eyebrow">患者视频截图 · {{ modelNames }}</p>
|
||||
<h2 id="screenshot-preview-title">舌象分析与中医诊断参考</h2>
|
||||
</div>
|
||||
<button type="button" aria-label="关闭截图预览" :disabled="busy" @click="close">×</button>
|
||||
@@ -83,7 +84,7 @@ function retry(): void { void previews[activeModel.value].retry() }
|
||||
</div>
|
||||
<section class="tongue-analysis" aria-labelledby="tongue-analysis-title">
|
||||
<header><h3 id="tongue-analysis-title">AI 舌象分析</h3></header>
|
||||
<p class="tongue-analysis__intro">默认使用千问 + GPT 自动分析同一截图,结果分别保留。</p>
|
||||
<p class="tongue-analysis__intro">默认使用{{ modelNames }}自动分析同一截图,结果分别保留。</p>
|
||||
<div class="tongue-analysis__tabs" role="tablist" aria-label="舌象分析模型">
|
||||
<button v-for="model in models" :id="`tongue-tab-${model}`" :key="model" type="button" role="tab"
|
||||
:aria-selected="activeModel === model" aria-controls="tongue-model-panel" :tabindex="activeModel === model ? 0 : -1"
|
||||
@@ -96,7 +97,7 @@ function retry(): void { void previews[activeModel.value].retry() }
|
||||
<div v-if="state.phase === 'loading'" class="tongue-analysis__status" role="status" aria-live="polite">
|
||||
<span class="tongue-analysis__spinner" aria-hidden="true" />
|
||||
<strong>{{ labels[activeModel] }} 正在分析舌苔特征…</strong>
|
||||
<p>两个模型独立返回。可切换查看,也可直接确认保存截图。</p>
|
||||
<p>各模型独立返回。可切换查看,也可直接确认保存截图。</p>
|
||||
</div>
|
||||
<div v-else-if="state.phase === 'error' || state.phase === 'unavailable'" class="tongue-analysis__status tongue-analysis__status--error" role="alert">
|
||||
<strong>{{ state.phase === 'unavailable' ? '截图分析暂不可用' : `${labels[activeModel]} 本次分析未完成` }}</strong>
|
||||
@@ -144,7 +145,7 @@ function retry(): void { void previews[activeModel.value].retry() }
|
||||
<p class="tongue-analysis__note">仅供医生结合问诊、脉象等复核,不自动写入诊断或发送给患者。</p>
|
||||
</section>
|
||||
</div>
|
||||
<p class="screenshot-dialog__hint">截图会自动发送至千问和 GPT 进行 AI 分析;只有点击“确认并上传”才会保存到患者资料。</p>
|
||||
<p class="screenshot-dialog__hint">截图会自动发送至{{ models.map((model) => labels[model]).join('、') }}进行 AI 分析;只有点击“确认并上传”才会保存到患者资料。</p>
|
||||
<footer>
|
||||
<button class="screenshot-cancel" type="button" :disabled="busy" @click="close">取消</button>
|
||||
<button class="screenshot-confirm" type="button" :disabled="busy" @click="emit('save')">{{ busy ? '正在上传…' : '确认并上传' }}</button>
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { imAiMarkdownToPlainText } from './im-ai-markdown'
|
||||
|
||||
export type ImAiAction = 'summary' | 'followup' | 'reply'
|
||||
export type ImAiModel = 'qwen' | 'doubao' | 'openai'
|
||||
export const IM_AI_MODELS: readonly ImAiModel[] = ['qwen', 'doubao', 'openai']
|
||||
export const IM_AI_MODEL_LABELS: Record<ImAiModel, string> = { qwen: '千问', doubao: '豆包', openai: 'GPT' }
|
||||
export type ImAiStatus = 'unavailable' | 'idle' | 'loading' | 'streaming' | 'success' | 'error' | 'cancelled'
|
||||
|
||||
export interface ImAiCapabilities {
|
||||
@@ -31,6 +34,8 @@ export interface ImAiIdentity {
|
||||
export interface ImAiRequest extends ImAiIdentity {
|
||||
source: 'doctor-call'
|
||||
event: 'im-ai-request' | 'im-ai-cancel'
|
||||
/** 仅新请求携带;省略时由服务端按任务默认模型生成。 */
|
||||
model?: ImAiModel
|
||||
}
|
||||
|
||||
export interface ImAiResult extends ImAiIdentity {
|
||||
@@ -123,6 +128,7 @@ export function createImAiController(options: ControllerOptions) {
|
||||
let pending: ImAiIdentity | null = null
|
||||
let timer: number | null = null
|
||||
let selectedAction: ImAiAction | null = null
|
||||
let model: ImAiModel = 'qwen'
|
||||
let initialSummaryTimer: number | null = null
|
||||
let initialSummaryWaiting = false
|
||||
const results = new Map<ImAiAction, ImAiState>()
|
||||
@@ -240,7 +246,8 @@ export function createImAiController(options: ControllerOptions) {
|
||||
notifyCancel(identity)
|
||||
}, IM_AI_DEADLINE_MS)
|
||||
try {
|
||||
options.notify({ source: 'doctor-call', event: 'im-ai-request', ...identity })
|
||||
// 默认千问时不携带 model,保持旧请求原样;其余模型由服务端白名单再校验。
|
||||
options.notify({ source: 'doctor-call', event: 'im-ai-request', ...identity, ...(model !== 'qwen' ? { model } : {}) })
|
||||
} catch {
|
||||
if (pending !== identity) return
|
||||
release()
|
||||
@@ -283,7 +290,12 @@ export function createImAiController(options: ControllerOptions) {
|
||||
})
|
||||
}
|
||||
|
||||
return { request, regenerate, receive, cancel, reset, updateReadiness, dismissInitialSummary, getState: () => state }
|
||||
/** 只影响之后发起的生成;已生成的结果仍保留并标注原模型。 */
|
||||
function setModel(next: ImAiModel): void {
|
||||
if (IM_AI_MODELS.includes(next)) model = next
|
||||
}
|
||||
|
||||
return { request, regenerate, receive, cancel, reset, updateReadiness, dismissInitialSummary, setModel, getState: () => state }
|
||||
}
|
||||
|
||||
/** The only AI-to-composer operation; it cannot send or overwrite existing text. */
|
||||
|
||||
@@ -2388,6 +2388,7 @@ createApp(App, {
|
||||
onRequestImAi: imAi.request,
|
||||
onRegenerateImAi: imAi.regenerate,
|
||||
onCancelImAi: imAi.cancel,
|
||||
onImAiModel: imAi.setModel,
|
||||
onSendText: sendText,
|
||||
onSendAttachment: sendAttachment,
|
||||
onLoadMore: () => loadMessages(true),
|
||||
|
||||
@@ -339,6 +339,9 @@ button:disabled { cursor: not-allowed; opacity: .55; }
|
||||
.im-ai-close:hover { background: var(--accent-soft); color: var(--accent); }
|
||||
.im-ai-tools { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 5px; padding: 0 14px 14px; border-bottom: 1px solid var(--border); }
|
||||
.im-ai-tools button { min-height: 36px; padding: 7px 4px; border: 1px solid var(--border); border-radius: var(--radius-small); background: var(--surface); color: var(--muted); font-size: 12px; white-space: nowrap; }
|
||||
.im-ai-model { display: flex; align-items: center; gap: 8px; padding: 8px 14px; border-bottom: 1px solid var(--border); color: var(--muted); font-size: 12px; }
|
||||
.im-ai-model select { flex: 1; min-height: 30px; padding: 4px 8px; border: 1px solid var(--border); border-radius: var(--radius-small); background: var(--surface); color: var(--heading); font-size: 12px; }
|
||||
.im-ai-model select:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
.im-ai-tools button:enabled:hover,
|
||||
.im-ai-tools .im-ai-tool--selected { border-color: var(--border-strong); background: var(--accent-soft); color: var(--accent-hover); }
|
||||
.im-ai-tools .im-ai-tool--selected { font-weight: 600; }
|
||||
@@ -860,7 +863,7 @@ button:disabled { cursor: not-allowed; opacity: .55; }
|
||||
.tongue-analysis h3 { margin: 0; font-size: 16px; color: var(--heading); }
|
||||
.tongue-analysis__model { color: var(--muted); font-size: 11px; }
|
||||
.tongue-analysis__intro { margin: 6px 0 12px; color: var(--muted); font-size: 12px; }
|
||||
.tongue-analysis__tabs { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; margin-bottom: 14px; }
|
||||
.tongue-analysis__tabs { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; margin-bottom: 14px; }
|
||||
.tongue-analysis__tabs button { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 4px 8px; min-height: 44px; padding: 8px 10px; border: 1px solid var(--border); border-radius: var(--radius-control); color: var(--muted); background: var(--surface); cursor: pointer; }
|
||||
.tongue-analysis__tabs button[aria-selected="true"] { border-color: var(--accent); background: var(--accent-soft); color: var(--accent); }
|
||||
.tongue-analysis__tabs span { font-size: 11px; }
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
export type TongueScreenshotModel = 'qwen' | 'openai'
|
||||
export const TONGUE_SCREENSHOT_MODELS: readonly TongueScreenshotModel[] = ['qwen', 'openai']
|
||||
export const TONGUE_SCREENSHOT_MODEL_LABELS: Record<TongueScreenshotModel, string> = { qwen: '千问', openai: 'GPT' }
|
||||
export type TongueScreenshotModel = 'qwen' | 'openai' | 'doubao'
|
||||
export const TONGUE_SCREENSHOT_MODELS: readonly TongueScreenshotModel[] = ['qwen', 'openai', 'doubao']
|
||||
export const TONGUE_SCREENSHOT_MODEL_LABELS: Record<TongueScreenshotModel, string> = { qwen: '千问', openai: 'GPT', doubao: '豆包' }
|
||||
|
||||
export interface TongueScreenshotResult {
|
||||
model: TongueScreenshotModel
|
||||
@@ -85,7 +85,7 @@ export function createTongueScreenshotBridge(options: {
|
||||
cancel(model)
|
||||
const bridge = options.getBridge()
|
||||
if (!bridge?.analyzeTongueScreenshotModel) {
|
||||
return Promise.reject(new TongueScreenshotError('当前客户端不支持千问 + GPT 双模型截图分析,请更新桌面客户端。', 'unavailable'))
|
||||
return Promise.reject(new TongueScreenshotError('当前客户端不支持多模型截图分析,请更新桌面客户端。', 'unavailable'))
|
||||
}
|
||||
const context = options.getContext()
|
||||
if (!context?.key || !context.diagnosisId) {
|
||||
@@ -204,7 +204,7 @@ export function createTongueScreenshotPreview(options: {
|
||||
const current = generation
|
||||
if (!image) { update(emptyTongueScreenshotPreview()); return }
|
||||
if (!options.analyze) {
|
||||
update({ image, phase: 'unavailable', message: '当前客户端不支持千问 + GPT 双模型截图分析,请更新桌面客户端。', result: null })
|
||||
update({ image, phase: 'unavailable', message: '当前客户端不支持多模型截图分析,请更新桌面客户端。', result: null })
|
||||
return
|
||||
}
|
||||
update({ image, phase: 'loading', message: '', result: null })
|
||||
|
||||
@@ -66,6 +66,30 @@ for (const action of ['summary', 'followup', 'reply']) {
|
||||
})
|
||||
}
|
||||
|
||||
test('selected model rides only on new requests; qwen default keeps the original request shape', (t) => {
|
||||
const h = harness(t)
|
||||
h.request('summary')
|
||||
assert.equal('model' in h.messages[0], false)
|
||||
h.receive(h.result('success', '千问总结', { modelLabel: '千问' }))
|
||||
h.setModel('doubao')
|
||||
h.request('summary')
|
||||
assert.equal(h.messages.length, 1, 'switching model never regenerates or replaces a cached tab')
|
||||
h.regenerate('summary')
|
||||
assert.equal(h.messages.at(-1).event, 'im-ai-request')
|
||||
assert.equal(h.messages.at(-1).model, 'doubao')
|
||||
h.cancel()
|
||||
assert.equal(h.messages.at(-1).event, 'im-ai-cancel')
|
||||
assert.equal('model' in h.messages.at(-1), false, 'cancel matches identity only')
|
||||
h.setModel('unknown-provider')
|
||||
h.regenerate('followup')
|
||||
assert.equal(h.messages.at(-1).model, 'doubao', 'invalid model keys are ignored')
|
||||
h.receive(h.result('success', '豆包追问'))
|
||||
h.setModel('qwen')
|
||||
h.regenerate('reply')
|
||||
assert.equal('model' in h.messages.at(-1), false)
|
||||
h.receive(h.result('success', '回复'))
|
||||
})
|
||||
|
||||
test('capability defaults closed and requires actual true, version and session', () => {
|
||||
for (const value of [undefined, {}, { version: 1, enabled: true }, { version: 2, enabled: true, sessionId: 'x' }, { version: 1, enabled: 'true', sessionId: 'x' }]) {
|
||||
assert.equal(normalizeImAiCapabilities(value).enabled, false)
|
||||
|
||||
@@ -91,7 +91,7 @@ test('real App passes the same captured JPEG to preview, automatic AI and only e
|
||||
h.captures[0].resolve(JPEG)
|
||||
await pending; await flush()
|
||||
assert.equal(all(h.root).find(element => element.type === 'img' && element.props.src === JPEG).props.src, JPEG)
|
||||
assert.deepEqual(h.analyzed, [{ image: JPEG, model: 'qwen' }, { image: JPEG, model: 'openai' }])
|
||||
assert.deepEqual(h.analyzed, ['qwen', 'openai', 'doubao'].map(model => ({ image: JPEG, model })))
|
||||
assert.deepEqual(h.saved, [])
|
||||
await button(h.root, '确认并上传').props.onClick()
|
||||
await flush()
|
||||
@@ -133,6 +133,6 @@ test('real App clears open preview when a new call starts and cancels in-flight
|
||||
h.unmount()
|
||||
h.captures[1].resolve(JPEG)
|
||||
await next; await flush()
|
||||
assert.deepEqual(h.analyzed, [{ image: JPEG, model: 'qwen' }, { image: JPEG, model: 'openai' }])
|
||||
assert.deepEqual(h.analyzed, ['qwen', 'openai', 'doubao'].map(model => ({ image: JPEG, model })))
|
||||
assert.deepEqual(h.saved, [])
|
||||
})
|
||||
|
||||
@@ -249,10 +249,10 @@ function mount(t, analyze) {
|
||||
|
||||
test('captured preview immediately loads AI but confirm remains available and is the only save action', async (t) => {
|
||||
const h = mount(t)
|
||||
assert.equal(h.requests.length, 2)
|
||||
assert.equal(h.requests[0].image, JPEG)
|
||||
assert.deepEqual(h.requests.map(({ image, model }) => ({ image, model })),
|
||||
['qwen', 'openai', 'doubao'].map(model => ({ image: JPEG, model })))
|
||||
assert.match(textOf(h.root), /正在分析舌苔特征/)
|
||||
assert.match(textOf(h.root), /自动发送至千问和 GPT.*只有点击.*才会保存到患者资料/)
|
||||
assert.match(textOf(h.root), /自动发送至千问、GPT、豆包进行.*只有点击.*才会保存到患者资料/)
|
||||
assert.equal(h.events.includes('save'), false)
|
||||
const confirm = button(h.root, '确认并上传')
|
||||
assert.equal(confirm.props.disabled, false)
|
||||
@@ -282,10 +282,10 @@ test('service failure offers retry for the same image, without saving or sending
|
||||
assert.match(textOf(h.root), /本次分析未完成.*合成服务不可用/)
|
||||
button(h.root, '重试此模型').props.onClick()
|
||||
await flush()
|
||||
assert.equal(h.requests.length, 3)
|
||||
assert.equal(h.requests[2].image, JPEG)
|
||||
assert.equal(h.requests.length, 4)
|
||||
assert.equal(h.requests[3].image, JPEG)
|
||||
assert.equal(h.events.includes('save'), false)
|
||||
h.requests[2].resolve(result('request-2'))
|
||||
h.requests[3].resolve(result('request-2'))
|
||||
await flush()
|
||||
})
|
||||
|
||||
@@ -316,8 +316,8 @@ test('closing and unmounting the real modal cancel and suppress outstanding comp
|
||||
await flush()
|
||||
const before = h.events.length
|
||||
h.unmount()
|
||||
assert.equal(h.events.length, before + 2)
|
||||
h.requests[2].resolve(result('request-2'))
|
||||
assert.equal(h.events.length, before + 3)
|
||||
h.requests[3].resolve(result('request-2'))
|
||||
await flush()
|
||||
assert.equal(h.root.children.length, 0)
|
||||
})
|
||||
@@ -331,205 +331,206 @@ test('record-saving busy state, unlike AI loading, disables duplicate confirmati
|
||||
h.requests[0].resolve(result())
|
||||
await flush()
|
||||
})
|
||||
|
||||
test('both model requests use the identical JPEG and complete independently in either order', async (t) => {
|
||||
const h = bridgeHarness(t)
|
||||
const qwen = h.analyze(JPEG), gpt = h.analyze(JPEG, 'openai')
|
||||
assert.deepEqual(h.requests.map(({ image, model }) => ({ image, model })), [{ image: JPEG, model: 'qwen' }, { image: JPEG, model: 'openai' }])
|
||||
assert.equal(h.timers.size, 2)
|
||||
assert.deepEqual(h.notifications, [])
|
||||
h.receive({ requestId: 'request-2', ok: true, data: result('request-2', 21, 'usable', 'openai') })
|
||||
assert.equal((await gpt).model, 'openai')
|
||||
assert.equal(h.timers.size, 1)
|
||||
h.receive({ requestId: 'request-1', ok: true, data: result() })
|
||||
assert.equal((await qwen).model, 'qwen')
|
||||
})
|
||||
|
||||
test('one model timeout or explicit cancellation leaves the other request intact', async (t) => {
|
||||
const h = bridgeHarness(t)
|
||||
const qwen = h.analyze(JPEG), gpt = h.analyze(JPEG, 'openai')
|
||||
const rejected = assert.rejects(qwen, /分析超时/)
|
||||
;[...h.timers.values()][0].callback()
|
||||
await rejected
|
||||
assert.equal(h.timers.size, 1)
|
||||
const qwenRetry = h.analyze(JPEG)
|
||||
const cancelled = assert.rejects(qwenRetry, error => error.code === 'cancelled')
|
||||
h.cancel('qwen')
|
||||
await cancelled
|
||||
assert.equal(h.timers.size, 1)
|
||||
h.receive({ requestId: 'request-2', ok: true, data: result('request-2', 21, 'usable', 'openai') })
|
||||
assert.equal((await gpt).model, 'openai')
|
||||
})
|
||||
|
||||
test('context changes and default cancellation reject both models and ignore late completions', async (t) => {
|
||||
const h = bridgeHarness(t)
|
||||
for (const contextChange of [false, true]) {
|
||||
const qwen = h.analyze(JPEG), gpt = h.analyze(JPEG, 'openai')
|
||||
const rejected = Promise.all([qwen, gpt].map(pending => assert.rejects(pending, error => error.code === 'cancelled')))
|
||||
if (contextChange) {
|
||||
h.state.context.key = 'new-consultation'
|
||||
h.receive({ requestId: h.requests.at(-2).id, ok: true, data: result(h.requests.at(-2).id) })
|
||||
} else h.cancel()
|
||||
await rejected
|
||||
assert.equal(h.timers.size, 0)
|
||||
for (const request of h.requests) h.receive({ requestId: request.id, ok: true, data: result(request.id, 21, 'usable', request.model) })
|
||||
}
|
||||
})
|
||||
|
||||
test('legacy single-model slot cannot silently serve either dual-model tab', async (t) => {
|
||||
const h = bridgeHarness(t)
|
||||
h.state.bridge = { analyzeTongueScreenshot: () => assert.fail('must not call legacy slot') }
|
||||
for (const model of ['qwen', 'openai']) await assert.rejects(h.analyze(JPEG, model), error => error.code === 'unavailable')
|
||||
assert.equal(h.timers.size, 0)
|
||||
})
|
||||
|
||||
test('wrong-model response fails only its associated request', async (t) => {
|
||||
const h = bridgeHarness(t)
|
||||
const qwen = h.analyze(JPEG), gpt = h.analyze(JPEG, 'openai')
|
||||
h.receive({ requestId: 'request-1', ok: true, data: result('request-1', 21, 'usable', 'openai') })
|
||||
await assert.rejects(qwen, /不匹配/)
|
||||
assert.equal(h.timers.size, 1)
|
||||
h.receive({ requestId: 'request-2', ok: true, data: result('request-2', 21, 'usable', 'openai') })
|
||||
await gpt
|
||||
})
|
||||
|
||||
test('diagnosis contract rejects ungrounded, oversized and unusable-frame candidates', async (t) => {
|
||||
const h = bridgeHarness(t)
|
||||
const mutations = [
|
||||
value => { delete value.model },
|
||||
value => { value.image_sha256 = 'wrong-sha' },
|
||||
value => { delete value.analysis.tcm_diagnosis },
|
||||
value => { value.analysis.tcm_diagnosis.summary = '字'.repeat(241) },
|
||||
value => { value.analysis.tcm_diagnosis.candidates[0].name = '字'.repeat(41) },
|
||||
value => { value.analysis.tcm_diagnosis.candidates[0].basis = ['不存在的特征'] },
|
||||
value => { value.analysis.tcm_diagnosis.candidates[0].basis = Array(8).fill('苔色') },
|
||||
value => { value.analysis.tcm_diagnosis.candidates[0].verify = [] },
|
||||
value => { value.analysis.tcm_diagnosis.candidates[0].verify = Array(5).fill('待核实') },
|
||||
value => { value.analysis.tcm_diagnosis.candidates[0].verify = ['字'.repeat(161)] },
|
||||
value => { value.analysis.tcm_diagnosis.candidates = Array(4).fill(value.analysis.tcm_diagnosis.candidates[0]) },
|
||||
value => { value.analysis.tcm_diagnosis.missing_information = [] },
|
||||
value => { value.analysis.tcm_diagnosis.missing_information = Array(7).fill('缺少信息') },
|
||||
value => { value.analysis.tcm_diagnosis.status = 'insufficient' },
|
||||
value => { value.analysis.image_quality = 'unusable' },
|
||||
]
|
||||
for (const mutate of mutations) {
|
||||
const pending = h.analyze(JPEG)
|
||||
const id = h.requests.at(-1).id, value = result(id)
|
||||
mutate(value)
|
||||
h.receive({ requestId: id, ok: true, data: value })
|
||||
await assert.rejects(pending, /格式异常/)
|
||||
}
|
||||
const pending = h.analyze(JPEG)
|
||||
const id = h.requests.at(-1).id
|
||||
h.receive({ requestId: id, ok: true, data: result(id, 21, 'unusable') })
|
||||
assert.equal((await pending).analysis.tcm_diagnosis.status, 'insufficient')
|
||||
})
|
||||
|
||||
function tab(root, model) { return all(root).find(element => element.props.id === `tongue-tab-${model}`) }
|
||||
|
||||
test('real component shows first completed GPT immediately while qwen is loading and caches tab results', async (t) => {
|
||||
const h = mount(t)
|
||||
assert.equal(tab(h.root, 'qwen').props['aria-selected'], true)
|
||||
assert.equal(tab(h.root, 'qwen').props.tabindex, 0)
|
||||
assert.equal(tab(h.root, 'openai').props.tabindex, -1)
|
||||
h.requests[1].resolve({ ...result('gpt-ready', 21, 'usable', 'openai'), model_label: 'GPT synthetic ready' })
|
||||
await flush()
|
||||
assert.equal(tab(h.root, 'openai').props['aria-selected'], true)
|
||||
assert.equal(tab(h.root, 'qwen').props['data-phase'], 'loading')
|
||||
assert.match(textOf(h.root), /GPT synthetic ready/)
|
||||
tab(h.root, 'qwen').props.onClick()
|
||||
await flush()
|
||||
assert.match(textOf(h.root), /千问 正在分析/)
|
||||
tab(h.root, 'openai').props.onClick()
|
||||
await flush()
|
||||
assert.match(textOf(h.root), /GPT synthetic ready/)
|
||||
assert.equal(h.requests.length, 2, 'switching never regenerates a request')
|
||||
h.requests[0].resolve(result())
|
||||
await flush()
|
||||
assert.equal(tab(h.root, 'openai').props['aria-selected'], true, 'later completion never steals selected tab')
|
||||
})
|
||||
|
||||
test('manual tab selection is respected when the other model completes first', async (t) => {
|
||||
const h = mount(t)
|
||||
tab(h.root, 'qwen').props.onClick()
|
||||
h.requests[1].resolve(result('gpt-ready', 21, 'usable', 'openai'))
|
||||
await flush()
|
||||
assert.equal(tab(h.root, 'qwen').props['aria-selected'], true)
|
||||
assert.equal(tab(h.root, 'openai').props['data-phase'], 'ready')
|
||||
})
|
||||
|
||||
test('real component anchors candidate basis to visible observations and shows verification and missing information', async (t) => {
|
||||
const h = mount(t)
|
||||
h.requests[0].resolve(result())
|
||||
await flush()
|
||||
assert.match(textOf(h.root), /中医诊断参考.*初步辨证(待医生确认).*合成待核实证型.*可见依据.*苔色:合成浅白色描述.*需要核实.*单张图像不足.*还需补充的信息.*脉象与问诊/)
|
||||
const anchor = all(h.root).find(element => element.type === 'a' && element.props.href === '#tongue-feature-qwen-0')
|
||||
assert.ok(anchor)
|
||||
assert.ok(all(h.root).find(element => element.props.id === anchor.props.href.slice(1)))
|
||||
assert.match(textOf(h.root), /不自动写入诊断或发送给患者/)
|
||||
})
|
||||
|
||||
test('one model error and selected retry leave the completed peer cached', async (t) => {
|
||||
const h = mount(t)
|
||||
h.requests[0].resolve({ ...result(), model_label: 'Qwen retained' })
|
||||
h.requests[1].reject(new Error('GPT 独立失败'))
|
||||
await flush()
|
||||
assert.equal(tab(h.root, 'qwen').props['data-phase'], 'ready')
|
||||
assert.equal(tab(h.root, 'openai').props['data-phase'], 'error')
|
||||
tab(h.root, 'openai').props.onClick()
|
||||
await flush()
|
||||
assert.match(textOf(h.root), /GPT 独立失败/)
|
||||
button(h.root, '重试此模型').props.onClick()
|
||||
await flush()
|
||||
assert.equal(h.requests.length, 3)
|
||||
assert.equal(h.requests[2].model, 'openai')
|
||||
assert.equal(h.requests[2].image, JPEG)
|
||||
tab(h.root, 'qwen').props.onClick()
|
||||
await flush()
|
||||
assert.match(textOf(h.root), /Qwen retained/)
|
||||
assert.equal(tab(h.root, 'openai').props['data-phase'], 'loading')
|
||||
h.requests[2].resolve(result('gpt-retry', 21, 'usable', 'openai'))
|
||||
await flush()
|
||||
assert.equal(tab(h.root, 'qwen').props['aria-selected'], true)
|
||||
assert.equal(h.events.includes('save'), false)
|
||||
})
|
||||
|
||||
test('new image clears both caches and late earlier successes or failures cannot overwrite it', async (t) => {
|
||||
const h = mount(t)
|
||||
h.requests[0].resolve({ ...result(), model_label: 'Old cached qwen' })
|
||||
await flush()
|
||||
h.image.value = 'replacement-image'
|
||||
await flush()
|
||||
assert.deepEqual(h.requests.slice(2).map(({ image, model }) => ({ image, model })), [{ image: 'replacement-image', model: 'qwen' }, { image: 'replacement-image', model: 'openai' }])
|
||||
assert.doesNotMatch(textOf(h.root), /Old cached qwen/)
|
||||
assert.equal(tab(h.root, 'qwen').props['data-phase'], 'loading')
|
||||
assert.equal(tab(h.root, 'openai').props['data-phase'], 'loading')
|
||||
h.requests[1].reject(new Error('obsolete GPT failure'))
|
||||
await flush()
|
||||
assert.equal(tab(h.root, 'openai').props['data-phase'], 'loading')
|
||||
assert.doesNotMatch(textOf(h.root), /obsolete/)
|
||||
button(h.root, '取消').props.onClick()
|
||||
await flush()
|
||||
h.requests[2].resolve(result('late-qwen'))
|
||||
h.requests[3].resolve(result('late-gpt', 21, 'usable', 'openai'))
|
||||
await flush()
|
||||
assert.equal(tab(h.root, 'qwen').props['data-phase'], 'idle')
|
||||
assert.equal(tab(h.root, 'openai').props['data-phase'], 'idle')
|
||||
assert.doesNotMatch(textOf(h.root), /合成浅白色描述/)
|
||||
assert.ok(h.events.includes('cancel-qwen') && h.events.includes('cancel-openai'))
|
||||
})
|
||||
|
||||
test('model tabs support arrow keys, Home and End with roving keyboard focus', async (t) => {
|
||||
const h = mount(t)
|
||||
for (const [current, key, expected] of [['qwen', 'ArrowRight', 'openai'], ['openai', 'ArrowLeft', 'qwen'], ['qwen', 'End', 'openai'], ['openai', 'Home', 'qwen']]) {
|
||||
const tabs = ['qwen', 'openai'].map(model => tab(h.root, model))
|
||||
let prevented = false
|
||||
tab(h.root, current).props.onKeydown({ key, preventDefault: () => { prevented = true }, currentTarget: { parentElement: { querySelectorAll: () => tabs } } })
|
||||
await flush()
|
||||
assert.equal(prevented, true)
|
||||
assert.equal(tab(h.root, expected).props['aria-selected'], true)
|
||||
assert.equal(tab(h.root, expected).props.tabindex, 0)
|
||||
assert.equal(tab(h.root, expected).focused, true)
|
||||
}
|
||||
assert.equal(h.requests.length, 2)
|
||||
|
||||
test('both model requests use the identical JPEG and complete independently in either order', async (t) => {
|
||||
const h = bridgeHarness(t)
|
||||
const qwen = h.analyze(JPEG), gpt = h.analyze(JPEG, 'openai')
|
||||
assert.deepEqual(h.requests.map(({ image, model }) => ({ image, model })), [{ image: JPEG, model: 'qwen' }, { image: JPEG, model: 'openai' }])
|
||||
assert.equal(h.timers.size, 2)
|
||||
assert.deepEqual(h.notifications, [])
|
||||
h.receive({ requestId: 'request-2', ok: true, data: result('request-2', 21, 'usable', 'openai') })
|
||||
assert.equal((await gpt).model, 'openai')
|
||||
assert.equal(h.timers.size, 1)
|
||||
h.receive({ requestId: 'request-1', ok: true, data: result() })
|
||||
assert.equal((await qwen).model, 'qwen')
|
||||
})
|
||||
|
||||
test('one model timeout or explicit cancellation leaves the other request intact', async (t) => {
|
||||
const h = bridgeHarness(t)
|
||||
const qwen = h.analyze(JPEG), gpt = h.analyze(JPEG, 'openai')
|
||||
const rejected = assert.rejects(qwen, /分析超时/)
|
||||
;[...h.timers.values()][0].callback()
|
||||
await rejected
|
||||
assert.equal(h.timers.size, 1)
|
||||
const qwenRetry = h.analyze(JPEG)
|
||||
const cancelled = assert.rejects(qwenRetry, error => error.code === 'cancelled')
|
||||
h.cancel('qwen')
|
||||
await cancelled
|
||||
assert.equal(h.timers.size, 1)
|
||||
h.receive({ requestId: 'request-2', ok: true, data: result('request-2', 21, 'usable', 'openai') })
|
||||
assert.equal((await gpt).model, 'openai')
|
||||
})
|
||||
|
||||
test('context changes and default cancellation reject both models and ignore late completions', async (t) => {
|
||||
const h = bridgeHarness(t)
|
||||
for (const contextChange of [false, true]) {
|
||||
const qwen = h.analyze(JPEG), gpt = h.analyze(JPEG, 'openai')
|
||||
const rejected = Promise.all([qwen, gpt].map(pending => assert.rejects(pending, error => error.code === 'cancelled')))
|
||||
if (contextChange) {
|
||||
h.state.context.key = 'new-consultation'
|
||||
h.receive({ requestId: h.requests.at(-2).id, ok: true, data: result(h.requests.at(-2).id) })
|
||||
} else h.cancel()
|
||||
await rejected
|
||||
assert.equal(h.timers.size, 0)
|
||||
for (const request of h.requests) h.receive({ requestId: request.id, ok: true, data: result(request.id, 21, 'usable', request.model) })
|
||||
}
|
||||
})
|
||||
|
||||
test('legacy single-model slot cannot silently serve either dual-model tab', async (t) => {
|
||||
const h = bridgeHarness(t)
|
||||
h.state.bridge = { analyzeTongueScreenshot: () => assert.fail('must not call legacy slot') }
|
||||
for (const model of ['qwen', 'openai']) await assert.rejects(h.analyze(JPEG, model), error => error.code === 'unavailable')
|
||||
assert.equal(h.timers.size, 0)
|
||||
})
|
||||
|
||||
test('wrong-model response fails only its associated request', async (t) => {
|
||||
const h = bridgeHarness(t)
|
||||
const qwen = h.analyze(JPEG), gpt = h.analyze(JPEG, 'openai')
|
||||
h.receive({ requestId: 'request-1', ok: true, data: result('request-1', 21, 'usable', 'openai') })
|
||||
await assert.rejects(qwen, /不匹配/)
|
||||
assert.equal(h.timers.size, 1)
|
||||
h.receive({ requestId: 'request-2', ok: true, data: result('request-2', 21, 'usable', 'openai') })
|
||||
await gpt
|
||||
})
|
||||
|
||||
test('diagnosis contract rejects ungrounded, oversized and unusable-frame candidates', async (t) => {
|
||||
const h = bridgeHarness(t)
|
||||
const mutations = [
|
||||
value => { delete value.model },
|
||||
value => { value.image_sha256 = 'wrong-sha' },
|
||||
value => { delete value.analysis.tcm_diagnosis },
|
||||
value => { value.analysis.tcm_diagnosis.summary = '字'.repeat(241) },
|
||||
value => { value.analysis.tcm_diagnosis.candidates[0].name = '字'.repeat(41) },
|
||||
value => { value.analysis.tcm_diagnosis.candidates[0].basis = ['不存在的特征'] },
|
||||
value => { value.analysis.tcm_diagnosis.candidates[0].basis = Array(8).fill('苔色') },
|
||||
value => { value.analysis.tcm_diagnosis.candidates[0].verify = [] },
|
||||
value => { value.analysis.tcm_diagnosis.candidates[0].verify = Array(5).fill('待核实') },
|
||||
value => { value.analysis.tcm_diagnosis.candidates[0].verify = ['字'.repeat(161)] },
|
||||
value => { value.analysis.tcm_diagnosis.candidates = Array(4).fill(value.analysis.tcm_diagnosis.candidates[0]) },
|
||||
value => { value.analysis.tcm_diagnosis.missing_information = [] },
|
||||
value => { value.analysis.tcm_diagnosis.missing_information = Array(7).fill('缺少信息') },
|
||||
value => { value.analysis.tcm_diagnosis.status = 'insufficient' },
|
||||
value => { value.analysis.image_quality = 'unusable' },
|
||||
]
|
||||
for (const mutate of mutations) {
|
||||
const pending = h.analyze(JPEG)
|
||||
const id = h.requests.at(-1).id, value = result(id)
|
||||
mutate(value)
|
||||
h.receive({ requestId: id, ok: true, data: value })
|
||||
await assert.rejects(pending, /格式异常/)
|
||||
}
|
||||
const pending = h.analyze(JPEG)
|
||||
const id = h.requests.at(-1).id
|
||||
h.receive({ requestId: id, ok: true, data: result(id, 21, 'unusable') })
|
||||
assert.equal((await pending).analysis.tcm_diagnosis.status, 'insufficient')
|
||||
})
|
||||
|
||||
function tab(root, model) { return all(root).find(element => element.props.id === `tongue-tab-${model}`) }
|
||||
|
||||
test('real component shows first completed GPT immediately while qwen is loading and caches tab results', async (t) => {
|
||||
const h = mount(t)
|
||||
assert.equal(tab(h.root, 'qwen').props['aria-selected'], true)
|
||||
assert.equal(tab(h.root, 'qwen').props.tabindex, 0)
|
||||
assert.equal(tab(h.root, 'openai').props.tabindex, -1)
|
||||
h.requests[1].resolve({ ...result('gpt-ready', 21, 'usable', 'openai'), model_label: 'GPT synthetic ready' })
|
||||
await flush()
|
||||
assert.equal(tab(h.root, 'openai').props['aria-selected'], true)
|
||||
assert.equal(tab(h.root, 'qwen').props['data-phase'], 'loading')
|
||||
assert.match(textOf(h.root), /GPT synthetic ready/)
|
||||
tab(h.root, 'qwen').props.onClick()
|
||||
await flush()
|
||||
assert.match(textOf(h.root), /千问 正在分析/)
|
||||
tab(h.root, 'openai').props.onClick()
|
||||
await flush()
|
||||
assert.match(textOf(h.root), /GPT synthetic ready/)
|
||||
assert.equal(h.requests.length, 3, 'switching never regenerates a request')
|
||||
h.requests[0].resolve(result())
|
||||
await flush()
|
||||
assert.equal(tab(h.root, 'openai').props['aria-selected'], true, 'later completion never steals selected tab')
|
||||
})
|
||||
|
||||
test('manual tab selection is respected when the other model completes first', async (t) => {
|
||||
const h = mount(t)
|
||||
tab(h.root, 'qwen').props.onClick()
|
||||
h.requests[1].resolve(result('gpt-ready', 21, 'usable', 'openai'))
|
||||
await flush()
|
||||
assert.equal(tab(h.root, 'qwen').props['aria-selected'], true)
|
||||
assert.equal(tab(h.root, 'openai').props['data-phase'], 'ready')
|
||||
})
|
||||
|
||||
test('real component anchors candidate basis to visible observations and shows verification and missing information', async (t) => {
|
||||
const h = mount(t)
|
||||
h.requests[0].resolve(result())
|
||||
await flush()
|
||||
assert.match(textOf(h.root), /中医诊断参考.*初步辨证(待医生确认).*合成待核实证型.*可见依据.*苔色:合成浅白色描述.*需要核实.*单张图像不足.*还需补充的信息.*脉象与问诊/)
|
||||
const anchor = all(h.root).find(element => element.type === 'a' && element.props.href === '#tongue-feature-qwen-0')
|
||||
assert.ok(anchor)
|
||||
assert.ok(all(h.root).find(element => element.props.id === anchor.props.href.slice(1)))
|
||||
assert.match(textOf(h.root), /不自动写入诊断或发送给患者/)
|
||||
})
|
||||
|
||||
test('one model error and selected retry leave the completed peer cached', async (t) => {
|
||||
const h = mount(t)
|
||||
h.requests[0].resolve({ ...result(), model_label: 'Qwen retained' })
|
||||
h.requests[1].reject(new Error('GPT 独立失败'))
|
||||
await flush()
|
||||
assert.equal(tab(h.root, 'qwen').props['data-phase'], 'ready')
|
||||
assert.equal(tab(h.root, 'openai').props['data-phase'], 'error')
|
||||
tab(h.root, 'openai').props.onClick()
|
||||
await flush()
|
||||
assert.match(textOf(h.root), /GPT 独立失败/)
|
||||
button(h.root, '重试此模型').props.onClick()
|
||||
await flush()
|
||||
assert.equal(h.requests.length, 4)
|
||||
assert.equal(h.requests[3].model, 'openai')
|
||||
assert.equal(h.requests[3].image, JPEG)
|
||||
tab(h.root, 'qwen').props.onClick()
|
||||
await flush()
|
||||
assert.match(textOf(h.root), /Qwen retained/)
|
||||
assert.equal(tab(h.root, 'openai').props['data-phase'], 'loading')
|
||||
h.requests[3].resolve(result('gpt-retry', 21, 'usable', 'openai'))
|
||||
await flush()
|
||||
assert.equal(tab(h.root, 'qwen').props['aria-selected'], true)
|
||||
assert.equal(h.events.includes('save'), false)
|
||||
})
|
||||
|
||||
test('new image clears both caches and late earlier successes or failures cannot overwrite it', async (t) => {
|
||||
const h = mount(t)
|
||||
h.requests[0].resolve({ ...result(), model_label: 'Old cached qwen' })
|
||||
await flush()
|
||||
h.image.value = 'replacement-image'
|
||||
await flush()
|
||||
assert.deepEqual(h.requests.slice(3).map(({ image, model }) => ({ image, model })),
|
||||
['qwen', 'openai', 'doubao'].map(model => ({ image: 'replacement-image', model })))
|
||||
assert.doesNotMatch(textOf(h.root), /Old cached qwen/)
|
||||
assert.equal(tab(h.root, 'qwen').props['data-phase'], 'loading')
|
||||
assert.equal(tab(h.root, 'openai').props['data-phase'], 'loading')
|
||||
h.requests[1].reject(new Error('obsolete GPT failure'))
|
||||
await flush()
|
||||
assert.equal(tab(h.root, 'openai').props['data-phase'], 'loading')
|
||||
assert.doesNotMatch(textOf(h.root), /obsolete/)
|
||||
button(h.root, '取消').props.onClick()
|
||||
await flush()
|
||||
h.requests[3].resolve(result('late-qwen'))
|
||||
h.requests[4].resolve(result('late-gpt', 21, 'usable', 'openai'))
|
||||
h.requests[5].resolve(result('late-doubao', 21, 'usable', 'doubao'))
|
||||
await flush()
|
||||
for (const model of ['qwen', 'openai', 'doubao']) assert.equal(tab(h.root, model).props['data-phase'], 'idle')
|
||||
assert.doesNotMatch(textOf(h.root), /合成浅白色描述/)
|
||||
assert.ok(['qwen', 'openai', 'doubao'].every(model => h.events.includes(`cancel-${model}`)))
|
||||
})
|
||||
|
||||
test('model tabs support arrow keys, Home and End with roving keyboard focus', async (t) => {
|
||||
const h = mount(t)
|
||||
for (const [current, key, expected] of [['qwen', 'ArrowRight', 'openai'], ['openai', 'ArrowLeft', 'qwen'], ['qwen', 'End', 'doubao'], ['doubao', 'ArrowRight', 'qwen'], ['qwen', 'ArrowLeft', 'doubao'], ['doubao', 'Home', 'qwen']]) {
|
||||
const tabs = ['qwen', 'openai', 'doubao'].map(model => tab(h.root, model))
|
||||
let prevented = false
|
||||
tab(h.root, current).props.onKeydown({ key, preventDefault: () => { prevented = true }, currentTarget: { parentElement: { querySelectorAll: () => tabs } } })
|
||||
await flush()
|
||||
assert.equal(prevented, true)
|
||||
assert.equal(tab(h.root, expected).props['aria-selected'], true)
|
||||
assert.equal(tab(h.root, expected).props.tabindex, 0)
|
||||
assert.equal(tab(h.root, expected).focused, true)
|
||||
}
|
||||
assert.equal(h.requests.length, 3)
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user